Skip to content

fix(state): bound session ledgers and share SESSION_CAP (#224) - #287

Merged
abogartz merged 3 commits into
mainfrom
fix-issue-224-bounded-session-ledgers
Nov 4, 2026
Merged

abogartz merged 3 commits into
mainfrom
fix-issue-224-bounded-session-ledgers

Conversation

@ocsi-fixer

@ocsi-fixer ocsi-fixer Bot commented Nov 4, 2026

Copy link
Copy Markdown

Closes #224

What and why

Three in-process ledgers grew without bound on long-lived hosts, and src/identity/repokey.ts re-declared SESSION_CAP = 64 locally so its cap could silently drift from the shared one. The ticket's file paths predate the #168 domain restructure; each claim was located at its current home on main cb68647c and REPRODUCED there:

Ticket claim Current location at cb68647c Status
state.sessions: Map<string, SessionState> inserts and never removes src/core/state.ts:105 (session() at :107) reproduced
SessionState.calls appended, no cap src/capture/triggers.ts trackCall (s.calls.push(rec)) reproduced
frontierInjectedSessions: Set<string> no bound src/inject/digest.ts:21 (added at :80) reproduced
repokey.ts re-declares const SESSION_CAP = 64 src/identity/repokey.ts:188 reproduced

The fix

  • sessions Map (src/core/state.ts): behind the existing SessionLru at SESSION_CAP. An evicted session starts over — the same cost core/lru.ts already accepts for the epoch caches.
  • calls ledger (src/capture/triggers.ts): capped at CALLS_CAP = 4096, oldest dropped in trackCall. Two deliberate choices:
    • Cap, not clear-at-turn-end: a continuous cap also bounds a single pathological turn (the opencode serve case the finding is about); clearing at turn end does not.
    • 4096, above the 2,000-call scale pinned by test/write-evidence.test.ts (write_promoted re-serializes the whole session call ledger — evidence lines grow to 22 KB (O(n^2) per session) #163): that suite asserts the full ledger stays available at 2,000 calls (callsFor("long")).toHaveLength(2000)). A cap at or below 2,000 would require editing another ticket's contract test; the bound is the point, and no existing assertion was touched.
    • Lifetime facts (callsTotal, reDerives, firstCallTs, sawEngagement, sawGateCheck) are recorded on SessionState as calls arrive, so past the cap: write_promoted evidence_refs_count, t2_compaction captured_calls, session_convergence calls/re_derives, ms_to_tap's start, and the hasEngagement/hasGateCheck grounding signals all keep their full-session meaning. Attribution (callsFor) sees the retained tail — documented at the function.
  • frontierInjectedSessions (src/inject/digest.ts): behind the same SessionLru. An evicted session is shown the frontier block once more — one extra frontier_injected row, never unbounded growth.
  • shared constant (src/identity/repokey.ts): imports SESSION_CAP from core/lru.ts; the local declaration is gone. Eviction order there is unchanged (insertion-order, as before).

Acceptance criteria → evidence

New test/bounded-session-ledgers.test.ts (5 tests). Differential at merge-base cb68647c vs this head f76b0fc4:

  1. sessions Map bounded — red at base (again === first, no eviction), green here.
  2. calls capped, counts honest — red at base (ledger length 4146 ≠ 4096; counters undefined), green here (calls.length === 4096, callsTotal === 4146, reDerives === 4146, evidenceCallsCount === 4146).
  3. engagement/gate-check survive the cap — red at base (uncapped length assertion fails), green here (sticky flags).
  4. frontier set bounded — red at base (re-injection after eviction not recorded: count stays 1), green here (second frontier_injected row appears).
  5. repokey evicts at the shared SESSION_CAP — green at both (same value today); it pins future drift: if either cap moves without the other, this fails. The import itself is the diff.

Base run: 4 fail / 1 pass (each for the stated unbounded-ledger reason). Head run: 5 pass / 0 fail.

Commands run (measured)

  • bun run typecheck — exit 0
  • bun run lint — exit 0 (493 warnings / 130 infos, all in bench/ and e2e/ files this PR does not touch; biome lint on the six changed files reports 2 warnings + 1 info, all on pre-existing lines: the useTemplate in summarize() at triggers.ts:142 and two useImportType on digest.ts type imports that predate this change)
  • bun run test — 947 pass / 19 skip / 0 fail (966 tests, including the 5 new ones)
  • bun run test:e2e — 30 pass / 0 fail (src/ changed)
  • Pre-push merge gate ran the same suite on push: "merge gate: all green"

Deliberately not changed

  • test/write-evidence.test.ts — untouched; its 2,000-call full-ledger contract still passes (the reason CALLS_CAP = 4096).
  • SessionLru itself — no new methods; resetState() follows the existing authoredOrder precedent (the LRU order survives a reset; stale sids evict harmlessly).
  • repokey's insertion-order eviction — only the constant is shared, per the ticket.
  • No .github/workflows, no rulesets, no other labels.

Long-lived hosts grew three in-process ledgers without bound: the
sessions Map (one SessionState per session ever seen), each session's
calls array (no cap), and the frontier-injection once-per-process Set.
src/identity/repokey.ts also re-declared SESSION_CAP = 64 locally, so
its cap could silently drift from the shared one.

- Put the sessions Map behind the existing SessionLru (core/lru.ts):
  an evicted session starts over, the same cost the epoch caches accept.
- Cap the per-session calls ledger at CALLS_CAP = 4096 (oldest dropped).
  The cap sits above the 2,000-call scale pinned by write-evidence.test.ts
  (#163) so that contract keeps holding. Lifetime facts (callsTotal,
  reDerives, firstCallTs, sawEngagement, sawGateCheck) are recorded on
  SessionState as calls arrive, so promotion counts, t2_compaction and
  session_convergence telemetry, ms_to_tap, and the engagement /
  gate-check grounding signals keep their full-session meaning past the
  cap; attribution (callsFor) sees the retained tail.
- Bound the frontier-injection Set with the same SessionLru: an evicted
  session is shown the frontier block once more, one extra evidence row.
- Import the shared SESSION_CAP in repokey.ts; its session cache now
  cannot drift from the other ledgers.

Adds test/bounded-session-ledgers.test.ts (5 tests: 4 fail at the
merge-base for the stated unbounded-ledger reasons, all pass here; the
repokey test pins the shared cap against future drift).
@ocsi-triager ocsi-triager Bot added the review:requested Human-admitted for autonomous review by ocsi-reviewer label Nov 4, 2026

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed head f76b0fc45e6e78678ce186d61c777a80c310a71e against #224. The production ledger changes passed my focused checks; one test issue blocks this head.

F1 — New repokey-cap test exceeds Windows' default budget and leaks its fixtures (test/bounded-session-ledgers.test.ts:145). Windows job 126460650591 reports this exact new test failing at 5684.99 ms, with a 5000 ms timeout (936 pass, 29 skip, 1 fail). This is a PR-owned failure, not the unrelated capture-model evidence race.

The test creates 65 distinct directories and resolves each through rememberSessionDir → scopeForDir → resolveRepo, including real Git subprocesses. The cache under test is keyed by session ID, so those distinct directories are unnecessary. They are also outside root, and neither the test nor afterEach removes them.

Suggested fix: register SESSION_CAP + 1 distinct session IDs against the existing single fixture root, retaining the first-evicted/last-retained assertions. I independently exercised that shape at this head on Windows/Bun 1.4.4: both assertions hold, 65 sessions/one directory takes about 55 ms. That is a local observation, not a hosted-runner guarantee. Please keep fixture cleanup owned by the test. A larger timeout alone would leave the unnecessary subprocess work and leaked directories.

Verification: 24 focused tests passed (120 assertions) across bounded ledgers, write evidence, convergence, T4 evidence and sessions. With base production files restored, four new ledger tests fail behaviorally. An additional independent overflow probe verified emitted compaction/convergence counts of 4108 despite a 4096-entry tail, the original first-call timestamp, retained grounding signals, and hot-session retention under churn. I did not run the full local suite or a live host.

Requesting changes for F1; no production-code defect found in this pass. The fixture approach is a suggestion, and an equivalent scoped fix is fine.

ocsi-reviewer[bot]
ocsi-reviewer Bot previously requested changes Nov 4, 2026

@ocsi-reviewer ocsi-reviewer 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.

Reviewed head f76b0fc45e6e78678ce186d61c777a80c310a71e.

Verdict: CHANGES_REQUESTED — red required context decides

Final gate re-check at filing time (verbatim):

$ gh pr view 287 --json headRefOid -q .headRefOid
f76b0fc45e6e78678ce186d61c777a80c310a71e
$ gh pr checks 287 --json name,bucket
[{"bucket":"pass","name":"test"},{"bucket":"pass","name":"lint"},{"bucket":"fail","name":"test-windows"},{"bucket":"pass","name":"smoke"}]

Failing job: test-windows, run 41796156241, job 126460650591 — the PR's own new test:

test\bounded-session-ledgers.test.ts:
(fail) repokey session cache evicts at the shared SESSION_CAP (no drift) [5684.99ms]
  ^ this test timed out after 5000ms.
 936 pass
 1 fail

This is not the capture_lag race signature (capture.test.ts:978); it is the new test itself exceeding the 5 s default under Windows filesystem/AV timing. The repo already documents exactly this failure mode for the same family: test/repo-scope-session.test.ts:90-93 ("under Windows Defender timing on CI runners this leg measurably exceeds the 5s default … One wider timeout for the one heavy test") and grants test(…, 20_000) at :108.

P1 test/bounded-session-ledgers.test.ts:145 — the 65-iteration mkdtempSync + rememberSessionDir loop has no timeout override; it took 5684.99 ms on the Windows runner and timed out. Fix: pass an explicit timeout to that one test (the repo-scope-session.test.ts:108 precedent uses 20_000). No behaviour change requested.

Contract #224 (abogartz, trusted; spec anchor 9edded2507dac33d = frozen)

Fix direction quoted and evidenced against the tree at this head:

  1. "Put the sessions Map … behind the existing SessionLru" — src/core/state.ts:115-117 (sessionOrder = new SessionLru(SESSION_CAP, …)), touch at :120. Pinned by new test 1.
  2. "and the frontierInjectedSessions Set behind the existing SessionLru" — src/inject/digest.ts:24-26 + :88. Pinned by new test 4 (re-records frontier_injected after eviction).
  3. "cap or clear calls at turn end" — capped: CALLS_CAP = 4096 (src/capture/triggers.ts:53), oldest dropped in trackCall (:75). Cap is the ticket's allowed alternative; lifetime counters (callsTotal/reDerives/firstCallTs/sticky flags) keep telemetry and grounding truthful past the tail, pinned by tests 2-3.
  4. "import the shared constant in src/repokey.ts" — src/identity/repokey.ts:20 imports SESSION_CAP from core/lru.ts; local re-declaration removed. Pinned by new test 5.

Commands run at this head (macOS)

  • bun run typecheck — clean
  • bun run lint — 493 warnings / 130 infos (≤ baseline 494w/131i)
  • bun run test — 947 pass / 19 skip / 0 fail (new file included; passes locally — the Windows leg is the only failure)
  • bun run test:e2e — 30 pass / 0 fail (src/ changed)

Test integrity: only test change is the new additive file; no .skip, no weakened matcher, no raised tolerance in any touched test.

The code direction satisfies the contract; the block is the red required context from the new test's missing timeout. Green head → this verdict is dismissed as a fallen finding.

@ocsi-reviewer

ocsi-reviewer Bot commented Nov 4, 2026

Copy link
Copy Markdown

@WhollyMindless F1 verified against the tree at f76b0fc — your fix direction supersedes the timeout suggestion in my CR 5765689057, which I correct here.

Evidence per claim:

  • 65 distinct directories, each spawning git: test/bounded-session-ledgers.test.ts:147-148 loops i <= SESSION_CAP (64, src/core/lru.ts:9) → 65 mkdtempSync. Each rememberSessionDir (src/identity/repokey.ts:203-207) calls scopeForDir (:194-201); a distinct dir always misses byDir, so resolveRepo (:170-184) spawns git rev-parse --show-toplevel + git remote get-url origin — ~130 subprocesses for the test.
  • Leak: dirs are created under tmpdir() directly, outside root; afterEach (:53-56) removes only root. Confirmed.
  • Distinct dirs unnecessary: bySession is keyed by sid (:192, evict loop :208-209), and the assertions (:152-153) check sid-0 evicted / last sid retained. 65 distinct sids against one shared dir exercise exactly that: byDir resolves once, bySession still holds 65 entries. Your shape preserves both assertions; your measured ~55 ms on Windows/Bun 1.4.4 is consistent with removing 130 subprocess spawns.

Agreed fix: register SESSION_CAP + 1 session IDs against the existing fixture root, keep fixture cleanup owned by the test, keep the first-evicted/last-retained assertions. No timeout override needed once the subprocess work is gone. Verdict stays CHANGES_REQUESTED at this head (test-windows still fail); the block is unchanged.

…#287 F1)

The 65-mkdtemp loop resolved each dir through real git subprocesses
(5684.99ms on the Windows runner, 5s default) and leaked dirs outside
the afterEach root. The bySession cache is keyed by session ID, so
SESSION_CAP+1 ids against the single fixture dir pin the same
first-evicted/last-retained assertions in ~0.1s.
@ocsi-fixer

ocsi-fixer Bot commented Nov 4, 2026

Copy link
Copy Markdown
Author

Rework at head d77da89e7f7561674ef9306ec9c145e3526d22ba.

F1 (WhollyMindless) / P1 (ocsi-reviewer) — addressed. test/bounded-session-ledgers.test.ts:145 now registers SESSION_CAP + 1 distinct session IDs against the existing single fixture root instead of 65 mkdtempSync dirs. The bySession cache under test is keyed by session ID, so the first-evicted / last-retained assertions are unchanged; scopeForDir's byDir cache makes the git-subprocess work happen once instead of 65 times. Fixture cleanup stays owned by the test (afterEach removes root); no dirs leak outside it. No timeout was raised. The test runs in ~0.1 s locally; the 5684.99 ms Windows failure mode (per-iteration resolveRepo subprocesses) is removed at the root.

Measured at this head (macOS): bun run typecheck clean; bun run lint clean; bun run test 947 pass / 19 skip / 0 fail; pre-push merge gate green including bun run test:e2e 30 pass / 0 fail. Differential re-checked: with the merge-base (cb68647c) src/identity/repokey.ts restored, the reworked test still passes at the base for the same reason as before (both caps are 64 there — the test pins drift-prevention via the shared import, matching the reviewer's count of 4 behavioral failures, not 5).

Deliberately unchanged: all production files, all other tests, all assertions in this test.

@WhollyMindless WhollyMindless left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-verified d77da89e7f7561674ef9306ec9c145e3526d22ba: APPROVE, superseding my earlier changes request.

The only incremental change is the repokey-cap fixture: 65 distinct session IDs now use the existing root, and teardown owns that directory. Both eviction assertions remain, no timeout is increased, and production files are unchanged.

On Windows/Bun 1.4.4, all five bounded-ledger tests pass (18 assertions); the formerly failing test takes 56.51 ms locally. All four hosted checks also pass at this head. This closes F1; my prior independent production/overflow verification still applies.

@ocsi-reviewer
ocsi-reviewer Bot dismissed their stale review November 4, 2026 09:46

Resolved at d77da89: repokey cap test pinned to one fixture dir keyed by session ID — no mkdtemp leak (all temp under afterEach-removed root), 572ms local, test-windows green.

@ocsi-reviewer ocsi-reviewer 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.

Head reviewed: d77da89e7f7561674ef9306ec9c145e3526d22ba

Contract (#224, authored by abogartz, spec anchor 9edded2507dac33d — recomputed hash matches, frozen):

Put the sessions Map and the frontierInjectedSessions Set behind the existing SessionLru, cap or clear calls at turn end, and import the shared constant in src/repokey.ts.

Per-criterion evidence:

  1. sessions Map behind SessionLru — src/core/state.ts:119-124: sessionOrder = new SessionLru(SESSION_CAP, sid => sessions.delete(sid)), touched on every session() access. Pinned by test/bounded-session-ledgers.test.ts:58-65 (evicted session starts over).
  2. frontierInjectedSessions behind SessionLru — src/inject/digest.ts:26-28 + frontierOrder.touch(sid) at :88. Pinned by test/bounded-session-ledgers.test.ts:115-143 (evicted session re-records frontier_injected).
  3. calls capped — CALLS_CAP = 4096 (src/capture/triggers.ts:56), oldest dropped in trackCall. The issue's "cap or clear at turn end": capped (at insert, strictly stronger than at turn end). Lifetime facts recorded as they happen (callsTotal, reDerives, firstCallTs, sticky sawEngagement/sawGateCheck) so telemetry, grounding and ms_to_tap keep full-session meaning — pinned by test/bounded-session-ledgers.test.ts:67-87 and :89-113.
  4. Shared constant — src/identity/repokey.ts:20 imports SESSION_CAP from core/lru.ts; eviction loop uses it at :208. Drift test test/bounded-session-ledgers.test.ts:145-154 imports the literal from core/lru.ts, so a re-declared cap fails.

Commands run at this head (measured):

  • bun run typecheck — 0 errors
  • bun run lint — exit 0 (493 warnings, 130 infos)
  • bun run test — 947 pass / 19 skip / 0 fail
  • bun test ./test/bounded-session-ledgers.test.ts — 5 pass / 0 fail in 572ms
  • bun run test:e2e — 30 pass / 0 fail (src/ changed)
  • Differential at merge-base cb68647 with the new test file copied in: 4 fail / 1 pass — the four unbounded-ledger behaviors are red at base for the stated reasons; the repokey no-drift test passes at base by design (base cap is the same number; the test pins future drift). Fixed side clean, broken side fails for the stated reason.

Prior findings resolved at this head:

  • My CR 5765689057 (Windows timeout of the repokey cap test): fixed by d77da89 — single fixture dir keyed by session ID, 572ms local, test-windows green. Dismissed.
  • WhollyMindless CR 5765679319 (65 mkdtemp dirs leaked outside the afterEach root; ~130 git subprocesses): the same commit adopts that shape — the loop's only temp dir is root, removed by afterEach (test/bounded-session-ledgers.test.ts:52-56); mkdtemp now appears once per test, not per iteration. WM has posted their own APPROVED (5766383593) at this head.

Findings:

  • nit — resetState() (src/core/state.ts:164-169) clears sessions but not sessionOrder; test-only path, the bound still holds (order ≤ cap), worst case is a premature eviction right after a reset. Not blocking.

Final gate re-check (verbatim): headRefOid = d77da89e7f7561674ef9306ec9c145e3526d22ba; checks: lint=pass test=pass test-windows=pass smoke=pass.

APPROVE. Human merges.

@ocsi-reviewer ocsi-reviewer 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.

APPROVE — head d77da89e7f7561674ef9306ec9c145e3526d22ba, diff key 9e08386b… (gh pr diff | shasum -a 256).

Contract #224 (abogartz, trusted), spec anchor 9edded2507dac33d — recomputed hash equals the frozen anchor comment 6616783366. Fix direction quoted verbatim: "Put the sessions Map and the frontierInjectedSessions Set behind the existing SessionLru, cap or clear calls at turn end, and import the shared constant in src/repokey.ts."

Per-criterion evidence (paths at current homes per the PR's located table):

  1. sessions Map behind SessionLru — src/core/state.ts:115-117 sessionOrder = new SessionLru(SESSION_CAP, sid => sessions.delete(sid)), touched in session(). Pinned by test/bounded-session-ledgers.test.ts:58 (evicted session starts over): fails at merge-base cb68647, passes at head.
  2. frontierInjectedSessions behind SessionLru — src/inject/digest.ts:24-27 frontierOrder, touch at :88. Pinned by test :115 (second frontier_injected row after eviction): base measured Expected: 2 Received: 1, head green.
  3. cap or clear calls — cap chosen: CALLS_CAP = 4096, oldest dropped in trackCall (src/capture/triggers.ts:78). Ticket allows "cap or clear"; cap additionally bounds a single pathological turn. Lifetime facts (callsTotal, reDerives, firstCallTs, sawEngagement, sawGateCheck) recorded on arrival so telemetry keeps full-session meaning past the tail. Pinned by tests :67 and :89 (both red at base). write-evidence.test.ts:132 2,000-call contract preserved (4096 > 2000), untouched.
  4. repokey imports shared constant — src/identity/repokey.ts:20 imports SESSION_CAP from core/lru.ts; local re-declaration removed. Pinned by test :145 (evicts at the shared cap).

Commands run at head: bun run typecheck exit 0; bun run lint 130 infos = baseline; bun run test 947 pass / 19 skip / 0 fail; bun run test:e2e 30 pass / 0 fail. Differential: new test file at merge-base cb68647 → 4 fail / 1 pass (the pass is the repokey drift-guard, equal caps at base), at head 5/0.

Test integrity: single new file, purely additive; no .skip, no weakened assertions, no tolerance changes. web_search correctly non-engagement, so the sticky-flag test genuinely pushes the grounding records out of the retained tail.

Final gate re-check (verbatim): gh pr view 287 --json headRefOid → d77da89e7f7561674ef9306ec9c145e3526d22ba; gh pr checks → lint pass, test pass, test-windows pass, smoke pass.

WhollyMindless APPROVED 5766383593 at this head supersedes their earlier CHANGES_REQUESTED at f76b0fc; the only incremental change since is the repokey test pin to one fixture dir (measured git diff --stat f76b0fc..d77da89: 1 file, +8/−7), which resolves the Windows 5s timeout (5684.99ms git-subprocess loop) and the dir leak. Observation, not a finding: frontierOrder.touch runs only on first injection, so recency is first-injection order — documented at digest.ts:21-23, bounded either way.

Human merges.

@abogartz
abogartz merged commit 9bc22a9 into main Nov 4, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.15.28 🎉

The release is available on:

Your semantic-release bot 📦🚀

@abogartz
abogartz deleted the fix-issue-224-bounded-session-ledgers branch November 19, 2026 05:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released review:requested Human-admitted for autonomous review by ocsi-reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Follow-up to #75: state.sessions, per-session calls, and frontierInjectedSessions remain unbounded; repokey re-declares SESSION_CAP

2 participants