Skip to content

fix(sessions): age out idle thread session pointers - #224

Merged
insomnius merged 6 commits into
boonfrom
ariefrahman/session-index-evict-idle-threads
Sep 17, 2026
Merged

insomnius merged 6 commits into
boonfrom
ariefrahman/session-index-evict-idle-threads

Conversation

@insomnius

@insomnius insomnius commented Sep 16, 2026 •

Copy link
Copy Markdown

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 from session.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):

  • the cheapest prompt in the suite ("What can you help me with? Give me a one-sentence overview", zero tools, 90 s budget) went 25.5 s -> 62.2 s over ~14 h of uptime;
  • it dropped to 28.0 s at a gateway restart, then climbed monotonically over eleven consecutive runs to 90.3 s and began failing;
  • the reply was correct and simply late: 152.2 s on the last run, 62 s past the budget;
  • a manual break-glass on the same host removed 2,447 of 2,666 session-index entries and shrank the store from 68.5 MB to 3.7 MB, with the index regrowing afterwards.

Why This Change Was Made

isProtectedSessionMaintenanceEntry protected 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 is lastInteractionAt when present, falling back to updatedAt only when it is absent or non-finite — lastInteractionAt is the documented idle-lifetime clock and only a real user/channel turn advances it, whereas updatedAt also 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 in pruneStaleEntries.

Deliberate boundaries:

  • An active session is never made evictable. In-flight and recent work keeps a live timestamp; runtime-owned sessions still come through preserveKeys, and the active session key is still skipped by disk-budget cleanup.
  • Non-thread keys are untouched. Group and channel pointers, Telegram topic keys, and chatType group/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.
  • The retention window is a module constant in src/config/sessions/store-maintenance.ts, not a new session.maintenance key. 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:310 shouldPreserveMaintenanceEntry — the shared gate, used by pruneStaleEntries (:191) and capEntryCount (:422, :428).
  • src/config/sessions/store-maintenance.ts:329 getActiveSessionMaintenanceWarning — an idle thread can now produce a maintenance warning, which is the point.
  • src/config/sessions/store-maintenance.ts:375, :391 wouldCapActiveSession — idle threads stop inflating the protected count that shrinks the removable budget.
  • src/config/sessions/disk-budget.ts:732 — inherits the fix through shouldPreserveMaintenanceEntry; the active key is still skipped separately.
  • src/config/sessions/session-registry-maintenance.ts:63 — unaffected: it adds every non-cron key to preserveKeys before pruning, and preserveKeys wins.

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 window
  • isProtectedSessionMaintenanceEntry > keeps protecting a thread session with recent activity (covers the lastInteractionAt path)
  • isProtectedSessionMaintenanceEntry > keeps protecting a thread session whose entry carries no timestamps
  • isProtectedSessionMaintenanceEntry > keeps protecting idle non-thread group and channel sessions
  • capEntryCount > caps long-idle thread sessions while keeping live ones

Red, before any production change:

$ node scripts/run-vitest.mjs run src/config/sessions/store.pruning.test.ts --pool=forks --maxWorkers=1
FAIL isProtectedSessionMaintenanceEntry > stops protecting thread sessions that went idle past the retention window
  AssertionError: expected true to be false // Object.is equality
FAIL capEntryCount > caps long-idle thread sessions while keeping live ones
  AssertionError: expected { …(2) } to be undefined
FAIL pruneStaleEntries > preserves durable external conversation entries
  AssertionError: expected 1 to be 2
Tests  3 failed | 20 passed (23)

Green, after the predicate change:

$ node scripts/run-vitest.mjs run src/config/sessions/store.pruning.test.ts --pool=forks --maxWorkers=1
Tests  23 passed (23)

Surrounding suites, one file per run:

Command Result
node scripts/run-vitest.mjs run src/config/sessions/store.pruning.test.ts --pool=forks --maxWorkers=1 23 passed
node scripts/run-vitest.mjs run src/config/sessions/store.pruning.integration.test.ts --pool=forks --maxWorkers=1 29 passed
node scripts/run-vitest.mjs run src/config/sessions/disk-budget.test.ts --pool=forks --maxWorkers=1 17 passed
node scripts/run-vitest.mjs run src/config/sessions/session-accessor.test.ts --pool=forks --maxWorkers=1 58 passed
node scripts/run-vitest.mjs run src/config/sessions/cleanup-service.agent-purge.test.ts --pool=forks --maxWorkers=1 1 passed
node scripts/run-vitest.mjs run src/config/sessions/session-registry-maintenance.test.ts --pool=forks --maxWorkers=1 4 passed
node scripts/run-vitest.mjs run src/cron/session-reaper.test.ts --pool=forks --maxWorkers=1 17 passed
node scripts/run-vitest.mjs run src/config/sessions.test.ts --pool=forks --maxWorkers=1 50 passed
node scripts/run-vitest.mjs run src/config/config.pruning-defaults.test.ts --pool=forks --maxWorkers=1 7 passed
node scripts/run-tsgo.mjs -p tsconfig.core.json exit 0
node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.test.src.json exit 0
node scripts/run-oxlint.mjs <4 touched files> exit 0
node scripts/format-docs.mjs --check clean (673 files)

Three 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's updatedAt was 1 (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 --check is 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.

  • lastInteractionAt is the authoritative activity clock, with updatedAt as a fallback; unusable timestamps remain protected.
  • Group and channel pointers, including Telegram forum topics, keep their durable protection.
  • The 4-day window is a module constant, not a new configuration key; already oversized stores still need one-time cleanup.

Written for commit 9a56487. Summary will update on new commits.

Review in cubic


Updates since this description was first written

  • Window is 4 days, not 7. A live-gateway run at production scale showed 7 days protected more entries than session.maintenance.maxEntries, which zeroes capEntryCount's removal budget and leaves the store floored above the operator's cap. Break-even is maxEntries / threads-per-day.
  • Recency clock changed. lastInteractionAt is authoritative when present; updatedAt is 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.
  • Telegram forum topics are 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. Caught by the CI shard, reproduced locally, fixed with a regression test.
  • Both timestamps are finite-guarded; an entry with no usable stamp stays protected.

@insomnius
insomnius requested a review from a team September 16, 2026 13:33
@claude

claude Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@insomnius

Copy link
Copy Markdown
Author

End-to-end proof on a live gateway (and a defect it found in this PR)

Ran against a real openclaw gateway booted from this branch on a synthesized throwaway state dir (OPENCLAW_STATE_DIR + HOME in a scratch dir, port 19247 loopback, no provider credential, no channels, no network egress; find ~/.openclaw -newermt '-30 minutes' empty afterwards, so the developer's real state was never touched).

The mutating path is openclaw sessions cleanup --enforce, which requires a gateway (CLI → WS → server-methods/sessions.ts:945 → runSessionsCleanup → applyFileBackedSessionStoreMaintenance). The gateway's own startup sweep is dry-run by design.

Small mix — works as designed

Before 10 entries / 3,655 B → after 7 entries / 2,492 B.

key state outcome
thread, idle 45d past prune window evicted
thread, idle 12d past protection, inside prune evicted
whatsapp DM, idle 200d (control) unprotected evicted
thread, idle 2d live retained
thread, updatedAt 40d but lastInteractionAt 1d live by interaction retained
thread, no timestamps indeterminate retained
thread, idle 60d, passed as --active-key active retained
channel / telegram topic / msteams group, idle 200–400d non-thread retained

Pre-fix control on df250dd (parent commit): same store, same config → pruned: 1, capped: 0, both idle threads survive forever. Post-fix: 10 → 7. The change is what causes the eviction.

Production scale — this is where the 7-day window failed

Seeded 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.

7 days: beforeCount 2669 -> afterCount 759, pruned 0, capped 1910   (20.3 MB)
4 days: beforeCount 2669 -> afterCount 500, pruned 0, capped 2169   (13.3 MB)

pruneStaleEntries did nothing at either window — at this cadence nothing reaches 30 days, so 100% of the work runs through capEntryCount. And that is the defect: capEntryCount computes maxRemovableEntries = Math.max(0, maxEntries - preservedCount) (store-maintenance.ts:443). At 7 days a ~108-threads/day tenant protects 756 entries against DEFAULT_SESSION_MAX_ENTRIES = 500, so the budget is zero and the operator's session.maintenance.maxEntries silently stops binding — the store floors at 759 and 20.3 MB is parsed and cloned on every load.

Fixed in ac4d883: the window is now 4 days. Break-even is maxEntries / threads-per-day = 500 / 108 = 4.63 days; at 4 days the protected set is 432 < 500 and the cap governs again — measurably, the 4-day enforce trimmed inside the protection window (retained idle-age range 0.01d–4.59d), which is the signal that the operator knob is doing the work rather than being overridden. The constant's doc comment now states that invariant, since it is a protection window and not a size bound: raise threads-per-day and the window must come down (3 days holds the property up to ~166 threads/day).

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. store.pruning.test.ts 23 passed, store.pruning.integration.test.ts 29 passed, disk-budget.test.ts 17 passed, tsgo core exit 0, oxlint exit 0.

Not exercised

  • No real channel traffic — thread pointers were synthesized (key grammar checked against parseThreadSessionSuffix, and the live gateway parsed them identically).
  • The on-write path (commitReplySessionInitialization) needs live model turns; the two paths driven share the same decision code, only the trigger differs.
  • Disk-budget eviction never ran (maxDiskBytes unset by default) — untested branch.
  • Byte figures depend on the synthetic payload calibration; entry counts are exact. Ran from source via tsx, not a dist build, so the RSS numbers observed are not comparable to production.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

…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.
@insomnius

insomnius commented Sep 16, 2026 •

Copy link
Copy Markdown
Author

Second live-gateway proof, against the post-review rule (5114736)

The earlier proof ran at 2725fc7, before review changed the recency clock. Re-ran it end to end on a real gateway at the current head (throwaway HOME + OPENCLAW_STATE_DIR, loopback 127.0.0.1:19733, OPENCLAW_SKIP_CHANNELS=1, synthetic token; real ~/.openclaw verified untouched afterwards). Both cleanup calls were served by the gateway, not a local fallback — [ws] ⇄ res ✓ sessions.cleanup 148ms / 1957ms.

The case the old rule got wrong

Small mix of 14 entries, 14/14 expected-vs-actual exact. The decisive row:

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

  1. A literal NaN cannot reach the guard from disk — JSON.parse rejects 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.
  2. The finite guard is defense-in-depth, not the only line. normalizePersistedSessionEntryShape already coerces a non-finite updatedAt to 0 on load (which reads as protected), and the startup migration doctor can rewrite a corrupt updatedAt to Date.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.

@insomnius

Copy link
Copy Markdown
Author

Closing the gaps the earlier proofs left open

The 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 HOME + OPENCLAW_STATE_DIR, loopback ports, synthetic data, one short-lived gateway at a time; the real state dir was verified untouched afterwards. Nothing was committed.

1. Disk-budget eviction — closed, and it answers a question this PR raises

session.maintenance.maxDiskBytes is unset by default, so diskBudget was null in every earlier run. Seeded ~1 MB/entry stores and drove sessions cleanup --enforce through the gateway with pruneAfter/maxEntries slack so the disk budget was the only actor.

A. Budget reachable (maxDiskBytes: 9mb, 12 entries = 12,040,622 B):

diskBudget: removedEntries 5, totalBytesBefore 12042734, totalBytesAfter 7024929,
            maxBytes 9437184, highWaterBytes 7549747

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 (maxDiskBytes: 4mb):

[sessions/store] session disk budget still above high-water target after cleanup
removedEntries 6, totalBytesAfter 6021368, maxBytes 4194304

All 6 unprotected entries gone, all 6 protected live threads kept, store left 43.6% over the hard maxBytes.

C. Everything unconditionally protected (6 channel keys, 300d idle): zero evictions, budget permanently unenforceable.

Precedence: protection wins; maxDiskBytes is best-effort, not a cap. That matches the code — disk-budget.ts:732 consults shouldPreserveMaintenanceEntry and continues, and the only consequence of missing the target is the log.warn; there is no escalation tier.

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 threads/day × window. Two residual items look worth their own issue rather than scope creep here:

  1. The docs call it a hard budget (docs/gateway/config-agents.md:1281 "optional hard budget"; same framing in src/config/types.base.ts:270-273 and src/config/schema.help.ts:1703). Scenario C holds 6,020,798 B against a 4,194,304 B maxBytes with zero evictions and a warn line. Either the wording should change or an escalation tier should evict oldest protected entries once no unprotected ones remain.
  2. overBudget is a literal true on that return path (disk-budget.ts:849), not computed from the final total — scenario A reports overBudget: true despite ending under both thresholds. An operator cannot distinguish "reclaimed fine" from "gave up over budget" without diffing the numbers. A computed value or a separate reachedTarget flag would fix it.

2. The on-write path (commitReplySessionInitialization) — closed

Earlier proofs drove only the startup sweep and the cleanup RPC. Ran a real agent turn against a local mock provider (a ~50-line HTTP stub serving one canned completion, wired as a custom OpenAI-compatible provider; no real provider contacted, no real credential in the config). The stub's request log is the complete egress record: a models probe and two completion calls.

Seeded three entries and ran one turn. Maintenance fired during session init — [sessions/store] pruned stale session entries logged before the model call, i.e. the write path, not a sweep:

EVICTED  thread, updatedAt 30d / lastInteractionAt 30d
KEPT     thread, updatedAt 40d / lastInteractionAt  1d     <- the case this PR is about
EVICTED  dm, 40d, unprotected control

Re-running the cleanup RPC against an identical re-seeded store produced the same three verdicts (pruned: 2). Write-triggered and cleanup-triggered passes agree.

3. Transport-minted thread keys — unreachable here, not faked

Audited every channel plugin's declared env vars. The only fully-local, credential-free transport is qa-channel (synthetic Slack-class, thread:<room>/<thread> grammar, in-repo bus). The bus starts fine, but the channel will not register under either runtime:

[channels] failed to load bundled channel qa-channel: Cannot find module
  '.../plugin-sdk/root-alias.cjs/qa-channel-protocol' - extensions/qa-channel/src/inbound.ts

Root cause is independent of this branch (it touches package.json zero times): extensions/qa-channel/src/inbound.ts:10-13 value-imports from openclaw/plugin-sdk/qa-channel-protocol, but root package.json exports only ./plugin-sdk/qa-runner-runtime and ./plugin-sdk/qa-live-transport-scenarios, and files excludes dist/plugin-sdk/qa-channel-protocol.*, so the subpath resolves to nothing in dev or dist. The sanctioned path is the qa-lab staging harness, which is far outside this PR.

So every session key in every proof, including these, remains synthesized. Stating that plainly rather than papering over it. Separate pre-existing issue worth filing: bundled qa-channel cannot load at runtime in a source checkout or from dist — fix is either adding the SDK subpath to exports (and not excluding it from files) or re-pointing that import at an exported barrel.

4. dist vs tsx — closed

Full build, then the same 2,669-entry / 76,312,142 B fixture copied fresh for each run:

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.
@insomnius

Copy link
Copy Markdown
Author

The red CI shard was a real defect in this PR, now fixed in ef09ad8

checks-node-core-runtime-infra-process had been failing since this branch's first push, on two assertions in store.pruning.test.ts. Every local single-file run was green, so I reproduced CI's actual invocation instead of trusting that.

Reproduction

That shard runs three vitest configs; this file belongs to vitest.runtime-config.config.ts (project glob src/config/**/*.test.ts). Running the file alone under that same config passes 27/27 — so the config was never the difference. Running the whole project reproduced CI exactly:

FAIL runtime-config src/config/sessions/store.pruning.test.ts > pruneStaleEntries > preserves durable external conversation entries
AssertionError: expected 3 to be 2
FAIL runtime-config src/config/sessions/store.pruning.test.ts > isProtectedSessionMaintenanceEntry > keeps protecting idle non-thread group and channel sessions
AssertionError: expected false to be true
Tests  2 failed | 1986 passed (1988)

Instrumenting the failing assertion named the key:

DEBUG-PROT {"c999":true,"topic":false,"opaque":true}

It was the telegram forum topic, not the channel key.

Root cause

parseSessionThreadInfoFast delegates to resolveLoadedSessionThreadInfo (src/channels/plugins/session-thread-info-loaded.ts:51), which asks loaded channel plugins first and falls back to parseThreadSessionSuffix only when none are loaded:

return resolveLoadedSessionConversationThreadInfo(sessionKey) ?? parseThreadSessionSuffix(sessionKey);

So a key like …:telegram:group:-100123:topic:77 is not thread-keyed in a bare process, but is thread-keyed once the telegram plugin is loaded — the production case. Since the thread branch ran before isTelegramTopicSessionKey, a long-idle forum topic was handed to the new 4-day recency rule and lost durable protection, while isTelegramTopicSessionKey — which exists precisely to protect topics unconditionally — became unreachable in exactly the case it was written for.

That is a behaviour regression this PR would have shipped, not a test artifact. A bare-process unit test cannot see it, which is why every isolated run I did came back green.

Fix

The topic check now runs before the thread branch, with a comment naming the load-order dependency, plus a regression test pinning the ordering (asserting an idle topic stays protected both by updatedAt and by a stale lastInteractionAt).

Verification: full runtime-config project 1989 passed (1989), up from 2 failed | 1986 passed. tsgo core 0, tsgo test 0, oxlint 0.

Worth generalising

Any other unconditional durable class that sits after the thread branch has the same exposure whenever a plugin reports its keys as thread-keyed. Today isTelegramTopicSessionKey was the only one; isExternalGroupOrChannelSessionKey matches group/channel shapes that no loaded plugin currently reports as threads, so it is unaffected — but the ordering is now load-bearing and the comment says so.

@insomnius
insomnius enabled auto-merge (squash) September 17, 2026 04:52

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@insomnius

Copy link
Copy Markdown
Author

@augusteo RE your CHANGES_REQUESTED review — valid, fixed in 9a56487. The description was written before two rounds of review changes and never updated, so it documented semantics the code no longer has. That's exactly the mismatch an operator would have been misled by.

Corrected in the body:

  • Window: 7 days → 4 days, matching THREAD_SESSION_PROTECTION_MAX_IDLE_MS and the checked-in docs. The reason for the change is now stated too: at 7 days a bot-shaped tenant protects more entries than session.maintenance.maxEntries, which zeroes capEntryCount's removal budget (max(0, maxEntries - preservedCount)) and floors the store above the operator's cap. Break-even is maxEntries / threads-per-day.
  • Recency clock: "the newer of updatedAt and lastInteractionAt" → lastInteractionAt authoritative when present, updatedAt only as fallback. updatedAt advances on transcript-append and marker writes, which are not user turns, so the old reading let background writes renew protection indefinitely. The fallback is required rather than optional, because cron isolated runs delete the interaction stamp.
  • User-impact paragraph: "more than 7 days" → "more than 4 days, measured from the last real user/channel turn", and dropped the stale "week-idle" phrasing.

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 runtime-config project: 2 failed | 1986 passed before, 1989 passed after), and it ships with a regression test pinning the ordering.

@insomnius
insomnius requested a review from augusteo September 17, 2026 05:07

@augusteo augusteo left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@insomnius
insomnius merged commit add94f5 into boon Sep 17, 2026
145 of 146 checks passed
@insomnius
insomnius deleted the ariefrahman/session-index-evict-idle-threads branch September 17, 2026 06:10
orswn added a commit that referenced this pull request Sep 17, 2026
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.
orswn added a commit that referenced this pull request Sep 17, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants