Repository navigation
fix(sessions): age out idle thread session pointers - #224
Conversation
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
There was a problem hiding this comment.
All reported issues were addressed across 7 files
Reply with feedback, questions, or to request a fix.
Fix all with cubic | Re-trigger cubic
A live-gateway proof at production scale found the 7-day window silently disabled the operator's entry cap. capEntryCount computes its removal budget as max(0, maxEntries - preservedCount); a tenant minting ~108 threads/day protects 756 entries against a maxEntries default of 500, so the budget is zero and the store floors above the cap forever. Measured on a seeded 2,669-entry / 68.3MB store through a real gateway: 7 days -> 759 entries, 20.3MB, removal budget 0 (cap never binds) 4 days -> 500 entries, 13.3MB, cap governs and trims inside the window Break-even is maxEntries / threads-per-day = 500 / 108 = 4.63 days, so 4 days restores a non-zero budget with margin. The doc comment now states the real invariant: this is a protection window whose job is to keep the protected set under maxEntries, not a size bound. One existing fixture seeded its durable thread at 5 days idle, inside the old window and outside the new one; it now uses a live thread, which is what the test name claims. Docs updated to match the window.
End-to-end proof on a live gateway (and a defect it found in this PR)Ran against a real The mutating path is Small mix — works as designedBefore 10 entries / 3,655 B → after 7 entries / 2,492 B.
Pre-fix control on Production scale — this is where the 7-day window failedSeeded 2,669 entries at the observed cadence (9 threads per run, every 2h, 24/7) padded to the observed ~25.7 KB/entry: 68.3 MB, matching the 68.5 MB reported from the field.
Fixed in One pre-existing fixture seeded its "durable" thread at 5 days idle — inside the old window, outside the new one. It now uses a live thread, which is what the test name claims. Not exercised
|
There was a problem hiding this comment.
All reported issues were addressed across 5 files (changes from recent commits).
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
Fix all with cubic | Re-trigger cubic
…ndex-evict-idle-threads
…otection Review found the recency rule read the wrong clock. updatedAt advances on transcript-append touches (session-accessor.ts:2216) and marker writes (:2681), neither of which is a user turn, so taking the newer of updatedAt and lastInteractionAt kept a silent thread pinned forever - the exact leak this branch exists to close. lastInteractionAt is the documented idle-lifetime clock (types.ts) and only moves on touchInteraction, so it now wins when present. updatedAt remains the fallback because cron isolated runs delete the interaction stamp (cron/isolated-agent/run-session-state.ts:46). Both timestamps are now finite-checked: a non-numeric persisted value used to make Math.max return NaN, which read as infinitely idle and dropped the entry. Unusable stamps keep the entry protected, matching pruneStaleEntries. Tests pin the window absolutely, not relative to the constant - a relative assertion moves with the value and stayed green when the window was widened to 15 days. Verified red at 15 days, green at 4. Added the interaction-authoritative case and the non-finite case. Constant comment trimmed to the invariant; the sizing measurements live in the PR discussion, not the source.
Second live-gateway proof, against the post-review rule (
|
| session | updatedAt |
lastInteractionAt |
expected | actual |
|---|---|---|---|---|
…:thread:…100 |
fresh (0d) | 30d | evict | evict |
…:thread:…101 |
20d | 1d | retain | retain |
…:thread:…102 |
1d | absent (cron shape) | retain | retain |
…:thread:…103 |
10d | absent (cron shape) | evict | evict |
…:thread:…104/105/108 |
non-finite / null / missing |
non-finite | retain | retain |
…:thread:…106 / …107 |
3d / 5d | 3d / 5d | retain / evict | retain / evict |
| channel, group, telegram topic (20d idle) | — | — | retain | retain |
--active-key dm (20d idle) |
— | — | retain | retain |
pruned: 0 throughout — every eviction came from capEntryCount, i.e. from the protection decision itself, not the 30-day age prune.
Production scale, shipped defaults
2,669 thread pointers over 24.7 days at a bot-shaped tenant cadence, both stamps set as real entries carry them, padded to ~26.3 KB/entry. No session.maintenance block at all (so maxEntries=500, pruneAfter=30d):
before: 2,669 entries / 70,230,959 B (67.0 MiB)
after: 500 entries / 13,189,442 B (12.6 MiB) capped 2169, pruned 0
Retained = 432 protected + 68 unprotected survivors, which is exactly the maxEntries − preservedCount = 500 − 432 = 68 removal budget. Of a 319-entry subset seeded with a fresh updatedAt but a stale last turn (standing in for transcript-append and marker touches), 251 were evicted; under the old rule all 319 would have been pinned.
Counterfactual across the three commits
Real capEntryCount + isProtectedSessionMaintenanceEntry extracted per commit and run against the same population at maxEntries=500:
2725fc7 max(updatedAt, interaction) + 7d protected=1030 budget= 0 after=1030
ac4d883 max(updatedAt, interaction) + 4d protected= 752 budget= 0 after= 752
5114736 interaction-authoritative + 4d protected= 432 budget=68 after= 500
Worth being precise about what a zero budget means: it is not a no-op — capEntryCount still deletes every unprotected entry, so the store floors at exactly protectedCount. Narrowing the window alone only moved that floor from 1030 to 752, both above the cap. Only the clock change gets under it. (These protected counts are higher than the first proof's 759 because this population deliberately includes the fresh-updatedAt/stale-interaction subset, which is precisely what max() over-protects.)
Two honest corrections to my earlier claims
- A literal
NaNcannot reach the guard from disk —JSON.parserejects it, and the store would read as{}. The reviewable shapes are"not-a-number"strings,null, and a missing key; all three were exercised and retained. - The finite guard is defense-in-depth, not the only line.
normalizePersistedSessionEntryShapealready coerces a non-finiteupdatedAtto0on load (which reads as protected), and the startup migration doctor can rewrite a corruptupdatedAttoDate.now()while canonicalizing non-lowercase keys. The guard is still correct to keep — it makes the protection rule self-contained rather than dependent on two upstream normalizations — but it is not load-bearing on the shipped path.
Unit suite re-run at head: store.pruning.test.ts 27 passed. Nothing was committed by the proof; worktree verified clean.
Closing the gaps the earlier proofs left openThe previous two live-gateway proofs listed four things they did not exercise. Three are now closed, one is genuinely unreachable in this checkout. All runs used a throwaway 1. Disk-budget eviction — closed, and it answers a question this PR raises
A. Budget reachable ( Evicted the 5 oldest of 6 idle threads, stopped on crossing high-water, kept all 6 live threads. B. Budget NOT reachable without evicting protected threads ( All 6 unprotected entries gone, all 6 protected live threads kept, store left 43.6% over the hard C. Everything unconditionally protected (6 channel keys, 300d idle): zero evictions, budget permanently unenforceable. Precedence: protection wins; This PR strictly improves that situation: previously every thread key was protected forever, so a bot-shaped tenant could park unbounded protected bytes and the budget would never bind again. With the window, protected mass is bounded at roughly
2. The on-write path (
|
| tsx | dist | |
|---|---|---|
| entries | 2,669 → 500 (capped: 2169) |
2,669 → 500 (capped: 2169) |
| store bytes | → 14,821,210 | → 14,821,210 |
| gateway peak RSS | 2.01 GiB | 1.35 GiB |
| cleanup RPC | 1,725 ms | 1,565 ms |
| startup to ready | ~85 s | ~15 s |
Identical maintenance outcome. This is dist-vs-tsx on one synthetic fixture on one machine — still not comparable to production RSS (no channels, no real transcripts, no concurrent traffic).
One honest note: a first attempt ran cleanup before the gateway logged ready, and the CLI silently fell back to in-process maintenance — the capped session entry count line landed on CLI stderr instead of the gateway log. That run was discarded and re-done after ready; every number above came from a gateway-served run. Worth knowing, since it is an easy way to publish a "live gateway" figure that never touched the gateway.
CI's runtime-config shard has been red since this branch's first push, and it was reporting a real defect rather than a flaky test. parseSessionThreadInfoFast resolves through resolveLoadedSessionThreadInfo, which consults loaded channel plugins and only falls back to static parsing when none are loaded. A telegram forum-topic key is therefore NOT thread-keyed in a bare process, but IS thread-keyed once the telegram plugin is loaded - which is the production case. The thread branch ran before the topic check, so a long-idle topic was handed to the 4-day recency rule and lost its durable protection, and isTelegramTopicSessionKey became dead code in exactly the case it exists for. Topics are durable surfaces, not per-conversation threads, so the topic check now runs first, with a comment naming the load-order dependency. Added a regression test pinning the ordering. Verified by reproducing CI locally: the full runtime-config project failed 2/1988 before (same two assertions as CI) and passes 1989/1989 after. Single-file runs cannot surface this - no plugins are loaded there - which is why every local run reported green while CI stayed red.
The red CI shard was a real defect in this PR, now fixed in
|
augusteo
left a comment
There was a problem hiding this comment.
Found one blocking documentation mismatch in the PR description:
- The main “Why This Change Was Made” section says the protection window is 7 days and that recency is the newer of updatedAt and lastInteractionAt. The implementation and checked-in docs use a 4-day window, and the current implementation intentionally treats lastInteractionAt as authoritative, falling back to updatedAt only when absent.
- Please update the PR description so reviewers/operators are not left with the wrong retention and activity semantics.
The code diff otherwise looks consistent with the stated idle-thread behavior, and the reported CI checks are passing.
…ndex-evict-idle-threads
|
@augusteo RE your CHANGES_REQUESTED review — valid, fixed in Corrected in the body:
I also added an explicit "Updates since this description was first written" section so the delta is visible rather than silently rewritten, including one more change you'll want to know about: telegram forum topics are now checked before the thread branch. Once the telegram plugin is loaded, a topic key resolves as thread-keyed, so the original ordering would have subjected long-lived topics to the idle window and pruned them. CI caught it, I reproduced it locally (full |
augusteo
left a comment
There was a problem hiding this comment.
Rechecked at the current head 9a56487. The PR description now matches the implementation: 4-day protection window, lastInteractionAt authoritative with updatedAt fallback, and unusable timestamps protected. The implementation and tests look consistent, and current CI checks are passing. Approved.
Routine release chore for the next train. Root package.json to 2026.6.11-boon.44, plugin package.json files synced via scripts/sync-plugin-versions.ts, changed npm-shrinkwrap.json files regenerated via scripts/generate-npm-shrinkwrap.mjs --changed, and a CHANGELOG.md section for boon.44. Ships #225 (ENG-20103), #224, #228 (ENG-20090) and #227. No separately published plugin source changed since boon.43 (#227 moves diagnostics-otel into the gateway bundle), so a gateway roll delivers the whole release.
…226) Routine release chore for the next train. Root package.json to 2026.6.11-boon.44, plugin package.json files synced via scripts/sync-plugin-versions.ts, changed npm-shrinkwrap.json files regenerated via scripts/generate-npm-shrinkwrap.mjs --changed, and a CHANGELOG.md section for boon.44. Ships #225 (ENG-20103), #224, #228 (ENG-20090) and #227. No separately published plugin source changed since boon.43 (#227 moves diagnostics-otel into the gateway bundle), so a gateway roll delivers the whole release.
What Problem This Solves
Fixes an issue where operators running a bot-shaped tenant that opens a new chat thread per conversation would see agent turn latency climb monotonically with gateway uptime, until replies blew past their budget and automated suites started failing with
poll timed out.Every
:thread:-keyed session was treated as permanently protected fromsession.maintenance, so the session index only ever grew: nothing aged out, the index regrew after every prune or restart, and each turn paid to load a larger store.Measured on one regression host (off-box telemetry):
Why This Change Was Made
isProtectedSessionMaintenanceEntryprotected thread sessions by key shape alone. Key shape says nothing about whether a conversation is alive, so a tenant that mints threads continuously pinned one store entry per thread forever.Protection is now scoped by real activity instead: a thread session stays durable while it has recent activity, and a thread idle past
THREAD_SESSION_PROTECTION_MAX_IDLE_MS(4 days) rejoins the normal age / count / disk-budget candidate set. Recency islastInteractionAtwhen present, falling back toupdatedAtonly when it is absent or non-finite —lastInteractionAtis the documented idle-lifetime clock and only a real user/channel turn advances it, whereasupdatedAtalso moves on transcript-append and marker writes, which would otherwise let background writes renew protection forever. An entry with no usable timestamp stays protected, matching the existing "cannot determine staleness, so keep it" rule inpruneStaleEntries.Deliberate boundaries:
preserveKeys, and the active session key is still skipped by disk-budget cleanup.chatTypegroup/channel metadata are still protected regardless of age, and synthetic cron/hook/heartbeat/ACP/sub-agent keys are still disposable. Only the thread branch changed.src/config/sessions/store-maintenance.ts, not a newsession.maintenancekey. Nothing today needs to tune it per host, and the config surface bar is high.Caller audit — every caller of the predicate routes through the one edited branch, so no call site needed its own guard:
src/config/sessions/store-maintenance.ts:310shouldPreserveMaintenanceEntry— the shared gate, used bypruneStaleEntries(:191) andcapEntryCount(:422,:428).src/config/sessions/store-maintenance.ts:329getActiveSessionMaintenanceWarning— an idle thread can now produce a maintenance warning, which is the point.src/config/sessions/store-maintenance.ts:375,:391wouldCapActiveSession— idle threads stop inflating the protected count that shrinks the removable budget.src/config/sessions/disk-budget.ts:732— inherits the fix throughshouldPreserveMaintenanceEntry; the active key is still skipped separately.src/config/sessions/session-registry-maintenance.ts:63— unaffected: it adds every non-cron key topreserveKeysbefore pruning, andpreserveKeyswins.User Impact
On hosts that open many chat threads, the session index now stays flat instead of growing without bound, so turn latency no longer degrades with gateway uptime and long-running gateways stop drifting into timeouts.
What this change does not do: it does not prune an already-bloated index on a running host. Existing oversized stores still need their one-time manual cleanup; after that, this keeps them flat.
Thread pointers idle for more than 4 days — measured from the last real user/channel turn — are now ordinary maintenance candidates. Eviction is still oldest-first and only happens once a store is over its configured age, count, or disk budget, so an idle thread is only dropped when newer entries already fill the cap. A dropped pointer means the next message in that thread starts a fresh session rather than resuming the old one.
Evidence
TDD, red before green. Unit coverage added in
src/config/sessions/store.pruning.test.ts:isProtectedSessionMaintenanceEntry > stops protecting thread sessions that went idle past the retention windowisProtectedSessionMaintenanceEntry > keeps protecting a thread session with recent activity(covers thelastInteractionAtpath)isProtectedSessionMaintenanceEntry > keeps protecting a thread session whose entry carries no timestampsisProtectedSessionMaintenanceEntry > keeps protecting idle non-thread group and channel sessionscapEntryCount > caps long-idle thread sessions while keeping live onesRed, before any production change:
Green, after the predicate change:
Surrounding suites, one file per run:
node scripts/run-vitest.mjs run src/config/sessions/store.pruning.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions/store.pruning.integration.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions/disk-budget.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions/session-accessor.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions/cleanup-service.agent-purge.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions/session-registry-maintenance.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/cron/session-reaper.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/sessions.test.ts --pool=forks --maxWorkers=1node scripts/run-vitest.mjs run src/config/config.pruning-defaults.test.ts --pool=forks --maxWorkers=1node scripts/run-tsgo.mjs -p tsconfig.core.jsonnode scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.test.src.jsonnode scripts/run-oxlint.mjs <4 touched files>node scripts/format-docs.mjs --checkThree existing tests encoded the defect and were updated rather than worked around, each for the same reason — a long-idle thread pointer is no longer immortal:
pruneStaleEntries > preserves durable external conversation entries: the 31-day-idle thread key is now pruned; a live thread key was added and is still preserved.loadSessionStore maintenance preserves channel, live thread, and topic session pointers: the 100-day-idle thread key is now capped out; a live thread key was added and is still kept alongside the channel and topic pointers.enforceSessionDiskBudget > does not evict protected thread session entries under store pressure: the protected entry'supdatedAtwas1(epoch), which is not a live thread; it now carries a current timestamp so the test proves what its name claims.Not verified locally, left to CI: the broad changed-lane gate,
markdownlint(not installed in this checkout;format-docs --checkis clean), and any live/E2E proof on a real gateway.Summary by cubic
Thread session pointers were previously protected indefinitely; they now rejoin age, count, and disk-budget cleanup after 4 days of inactivity. This keeps bot-shaped session stores bounded, and an evicted thread starts a fresh session on its next message.
lastInteractionAtis the authoritative activity clock, withupdatedAtas a fallback; unusable timestamps remain protected.Written for commit 9a56487. Summary will update on new commits.
Updates since this description was first written
session.maintenance.maxEntries, which zeroescapEntryCount's removal budget and leaves the store floored above the operator's cap. Break-even ismaxEntries / threads-per-day.lastInteractionAtis authoritative when present;updatedAtis a fallback only, because it advances on transcript-append and marker writes that are not user turns. The fallback is required because cron isolated runs delete the interaction stamp.