Repository navigation
feat(store): keep session state through a restart and a long pause (#769) - #770
Conversation
) The summary checkpoint (cg:sum:), the billed input (cg:bin:) and the other session state were lost on a restart and after 2.8 hours idle. The next turn then sent the full transcript. - store.Disk: a SQLite write-through copy of the state keys, behind store.Memory. Writes are batched once a second, never in the request. - store.Memory.LoadSession: reads one session's keys from disk, once per state lifetime, before the pipeline runs. No load at startup. - Options.StateTTLSeconds: memory lifetime of the state keys only. - Proxy flags --session-state-db (off by default), --session-state- metadata-only, --session-state-retention. With a path set and no explicit value, the proxy sets the state lifetime to 24 h. - The rewind stash is never written. Any disk error falls back to memory only. Library default and proxy default are both OFF: no behavior change until the owner turns it on. Fixes #769 Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | f5ff7a3388da |
blocking |
Verdict: blocking
Findings
-
apply/responses.go:543 — the Responses route reads the alias clock without loading the alias state from disk
- What fails: explicit session id + a restart (or a pause past the state lifetime) +
--session-state-dbon.aliasSeen(st, alias, nowMs)readscg:seen:<alias>from memory only. The key sits on disk, so the read returns 0 andidleMsstays -1 (unknown) instead of the true idle. The chat route handles the same case. - Proof: apply.go:582-584 loads the alias before
aliasSeenat apply.go:585, with the comment "so a session that comes back under its other id finds its clocks". responses.go:520 loads onlyres.Session. The two ids differ exactly whenexplicitSessionreturns a valid id (session.Scoped, session/session.go:151-170), which is the case apply.go guards withif alias != sessionID. - Fix: in
bodyResponsesOpts, after computingalias, callloadSessionState(st, alias)whenalias != res.Session, as apply.go does. Add a test likeTestBodyOptsLoadsSessionStateFromDisk, but with an explicit session id. No test covers the alias load on either route today.
- What fails: explicit session id + a restart (or a pause past the state lifetime) +
-
store/disk.go:405-412 — the
loadedAtmap has no hard cap, and every request scans it once past 4096 sessions- What fails: many distinct sessions inside one state lifetime (24 h with the disk on; eval-containers stamps one id per task).
loadedAtkeeps every session seen in 24 h. EachLoadSessioncall — one per request — then walks the whole map underm.mu. The cleanup deletes only ids older than the lifetime, so live churn never brings the count back under 4096. The map also grows without bound within one lifetime. - Proof: disk.go:405-412 adds the id, then
if len(m.loadedAt) > 4096runs a full-range delete of expired ids only. Nothing caps the count. The store's own precedent bounds its maps:noteLostis capped bym.max(store.go:1016-1020). Default deployments are safe:LoadSessionreturns before this code when no disk is attached (disk.go:390-394). - Fix: cap the map the way
noteLostdoes — drop the oldest id on insert. The per-request scan then goes away.
- What fails: many distinct sessions inside one state lifetime (24 h with the disk on; eval-containers stamps one id per task).
Non-blocking
- cmd/context-guru-proxy/main.go:567-582 —
--store=falseplus--session-state-dbset:pstoreisstore.Nop{}, the type assertion fails, and no warning is logged. The flag is silently ignored. The multi-tenant case gets a warning; this one should too. - store/disk.go:220-253 — a failed
Flushdrops its batch; the rows are not re-queued. A busy or locked file can lose up to 1 s of state writes. Counted inDisk.Errors, logged once. Fail-open by design; the docs could say a write can be lost this way, not only on a crash. - store/disk.go:405 —
loadedAtis written before the disk read. A failed read is not retried until the state lifetime passes (24 h default). Consider clearing the mark whenloadSessionreports an error. - store/disk.go:354-373 —
Memory.Getnow reads the disk on every miss of a global key (cg:xres:,cg:swx:), with no negative cache. Todaycg:xres:has no production reader andcg:swx:is read once per expand, so the cost is small. Watch this if a per-message reader appears. - docs/data-dependence.md — the new row lists confirmations as pending (Itay Nakash for the
summarizerows). CLAUDE.md wants that confirmation before merge.
What I checked
- The full diff (9 files) and the code around each change:
store/disk.go,store/store.go,apply/apply.go,apply/responses.go,cmd/context-guru-proxy/main.go. - Key shapes for every persisted namespace against
boundaryOK:cg:bint:and thread keys use\x00(internal/thread/thread.go:57), sweep drop records use\x01/\x02(extract_sweep_apply.go:101-102),cg:swk:andcg:res:use:. All allowed. - Lock order between
m.muandd.muinPut,Get,getGlobal,LoadSession,Flush. No cycle. The disk read inLoadSessionruns outsidem.mu. - The race between
LoadSessionand a concurrentPutof the same key: the "memory is newer" check (disk.go:420) closes it in both orders. evictOldestskips stash entries (store.go:1202-1206), so a restore cannot evict a rewind payload.PutStashnever reachesenqueue;enqueuerefuses keys outside the persisted namespaces. Tested inTestStashNeverWritten.- Config plumbing:
store.Options.state_ttl_seconds,Config.NewStore, and the 24 h default set only when the flag is on and the config is silent (main.go:280-282). - The metadata and content prefix lists in disk.go match both docs. The rewind stash is documented as never written, and the code agrees.
- Fail-open paths have tests: corrupt file, missing directory, closed database, read-only file.
- Test helpers used by the new apply test exist (
runTurn,compactBody,RecordBilledInput). - I did not run tests (not approved) and did not read the PR conversation (round 1).
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | f5ff7a3388da |
approve |
Verdict: approve
Findings
None. I found no wrong behavior, no data loss, and no broken fail-open path.
Non-blocking
-
store/disk.go:163 — the
maxPendingguard blocks updates to keys already pending.if len(d.pending) < maxPendingalso stops an update to a key already in the map when the map is at the cap. The flush then writes the older value, and a restart can restore it.- Reach: 50,000 distinct state keys inside one 1-second flush window. Not realistic today.
- Fix: allow the write when the key is already present:
if _, ok := d.pending[key]; ok || len(d.pending) < maxPending.
-
store/disk.go:196 — only the first disk error is ever logged.
logOnceis async.Onceon the wholeDisk. A disk that fails later (full, unreadable) is counted inErrors()but never logged again.Errors()is read by tests only, so an operator has no live signal.- The reference doc says "logged once", so code and doc agree. Consider logging per distinct op, or wiring
Errors()into/stats.
-
store/disk.go:399 — a failed load suppresses the retry for a full state lifetime.
LoadSessionrecordsloadedAt[session]before the disk read. A transient read error (3 s timeout, lock contention) then blocks the next load of that session for 24 h.- Fail-open holds: the request runs with memory only, which is the behavior before this PR. A retry on error would close the gap.
-
apply/responses.go:520 — the responses path loads only
res.Session, not the alias.BodyOptsloads the tenant-less alias too (apply/apply.go:582), becausecg:seen:andcg:ttl:are keyed by it.bodyResponsesOptsreads the same keys (apply/responses.go:543) without loading them.- Effect: after a restart or a long pause, a session with an explicit id that uses the Responses API reads its alias clocks as unknown.
cacheIsColdthen returns false (unknown is not cold), so thecold_cachesaving is forgone. No wrong cold reading, no corruption.
-
store/disk.go:403 —
loadedAtis a soft bound.- The prune loop runs only when the map exceeds 4096, and deletes only expired entries. With more than 4096 distinct sessions inside one state lifetime, the map keeps growing and the loop scans it on every request. Entries do expire, so the growth is bounded by distinct sessions per 24 h.
-
store/disk.go:380 — a state key untouched for the state lifetime is not re-read from disk while the session stays active.
- A fresh
loadedAtblocksLoadSession, so a key that expired in memory (for example a quiet thread'scg:swh:held answer) is not restored even though the disk holds it. Every key a turn reads slides its own TTL, so this hits only keys no turn reads. Loss is a wasted model answer, not a cache flip.
- A fresh
What I checked
- Read the full diff of all 9 files, and the code around each change (
store/store.go,store/disk.go,apply/apply.go,apply/responses.go,apply/restore.go,expand/anchor.go,internal/thread/thread.go,cmd/context-guru-proxy/main.go,proxy/proxy.go,proxy/tenancy.go). - Fail open. Every
Diskerror path counts, returns, and lets the request continue (fail,get,loadSession,Flush,sweep).OpenDiskfailure inmain.gologs and runs memory only.TestDiskFailsOpenandTestDiskReadOnlyFilecover this. - No stash on disk.
PutStashnever callsenqueue;enqueuerefuses keys outsideStatePrefixes; bare marker ids andcg:keep:/cg:own:failallowed.TestStashNeverWrittencovers this. - Key boundary. I traced every key format against
boundaryOK:thread.Key(session +\x00), sweep drop records (\x01,\x02),resultKey/frozenKey/keep records (:), plain session keys (end). All pass; a longer session id (abcdef) is excluded.TestLoadSessionBoundarycovers this. - Locking.
Putnestsm.mu→d.muonly.Flush,get,loadSession, andgetGlobalnever holdd.muwhile takingm.mu. No deadlock path. - Restore ordering.
loadSessionStateruns beforeplanRestore,aliasSeen,sessionTTL,prevBilledInput, and the pipeline in bothBodyOptsandbodyResponsesOpts. A concurrentPutduring the disk read wins over the loaded row (the live-entry check inLoadSession). - Off by default. Empty path means no file, no
Disk, noLoadSessiondisk read, andStateTTLSecondsstays 0.Get's new fallback returns false at once whendiskis nil.TestOffCreatesNoFileandTestMemoryOnlyDefaultsUnchangedcover this. - Hosted mode. With
--upstreams, the disk is skipped with a warning, and per-tenant stores are built from tenant documents (buildTenantConfig), so they never see the disk. The 24 hStateTTLSecondsbump lands on the base store, which serves no tenant traffic in hosted mode. - Data dependence. The new row in
docs/data-dependence.mdmatches the code:metadataPrefixesandcontentPrefixeslist the same keys the doc names, and the sweep drop record (sweepDropRec) holds keys and flags only. - Config surface.
state_ttl_secondszero keepsttl_seconds; the proxy sets 86400 only when the disk path is set and the config is silent.IdleExitFloorreadsEffectiveTTLonly, so the idle-exit check is unaffected.
- Responses route: load the alias session state too, as the chat route does, so a returning session finds its idle clocks. - Cap the loaded-session record at 4096 ids and drop the oldest on insert, with no scan per request. - A failed disk read clears the loaded mark, so the next request retries. - At the pending-write cap, keep an update to a key already waiting. - Log each distinct failing disk operation once. All are counted. - Warn when --session-state-db is set with --store=false. - Docs: a failed flush drops its batch. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Round 1 fixes are in
Left as known limits, now in the PR body: a disk read per miss of a global key, and a state key that no turn reads can expire in memory while the session stays active. Box runs: |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | befcc038a028 |
blocking |
Verdict: blocking
Earlier findings
- My finding 1 (responses alias load): fixed. responses.go:543-545 now loads the alias when
alias != res.Session, as the chat route does.TestBothRoutesLoadTheAliasSessioncovers both routes and fails if either load is removed (checked the spy path:loadSpy.LoadSessionoverrides the embedded method, so the type assertion inloadSessionStaterecords the call). Verified. - My finding 2 (loadedAt cap): fixed for
loadedAt, but the fix leaks on the failure path.markLoadedcaps the map at 4096 and drops the oldest id, with no scan (TestLoadedRecordIsCapped). The retry-on-failure fix interacts badly with it — see finding 1 below. - My non-blocking items:
--store=falsewarning — fixed (main.go:586-591, and the OpenDisk-failure case still gets its own warning). Flush-drops-batch doc — fixed (reference.md). Failed-read retry — fixed, with the leak below as a side effect. Global-key miss reads and the quiet-key expiry — left as known limits in the PR body; I accept both, they were non-blocking in round 1. The data-dependence confirmations (Itay Nakash's rows) are still not shown on the PR; CLAUDE.md wants them before merge. - Reviewer 1's items: I checked each fix myself. Pending cap keeps updates — fixed (disk.go:194-198,
TestPendingCapKeepsUpdates). Per-op logging — fixed (disk.go:181-186,TestEachOpLoggedOnce); every failure is still counted inDisk.Errors(). Their #4 (alias load) is my finding 1, fixed. Their #6 (quiet key not re-read) — left as a known limit; I agree with that call: the loss is a wasted model answer, not a cache flip.
Findings
- store/disk.go:412-417 — a failed disk read makes
loadedOrdergrow without bound- What fails: the state file breaks (corrupt, closed, unwritable) while the proxy keeps serving — the exact state the fail-open design runs through. Each request for an affected session:
markLoadedappends the id toloadedOrder(disk.go:441, the id is absent fromloadedAt), the read fails, and the failure path deletes onlyloadedAt[session](disk.go:415). TheloadedOrderentry stays. The next request appends the id again. The eviction loop (disk.go:436) runs only whenlen(loadedAt) >= maxLoaded, so it never trims these orphans whileloadedAtis below the cap. One string entry per request, forever. - Proof: trace —
markLoadedappends only when the id is missing fromloadedAt(disk.go:435); the only code that removes fromloadedAtwithout removing fromloadedOrderis the failure path at disk.go:414-416.TestFailedLoadAllowsRetrydoes two loads and so cannot see it;TestLoadedRecordIsCappeduses only successful loads. - Fix: on the failure path, remove the id from
loadedOrdertoo (linear scan, the same patternputLockeduses forlostOrder, store.go:960-964). Or record the insert position inloadedAtand delete by it.
- What fails: the state file breaks (corrupt, closed, unwritable) while the proxy keeps serving — the exact state the fail-open design runs through. Each request for an affected session:
Non-blocking
- store/disk.go:411 — with a disk that hangs rather than fails fast, the retry now pays the 3 s
loadTimeouton every request, not once per lifetime. Requests still succeed (fail open); they are just slow. Consider a short backoff on the retry (for example, one retry per minute) instead of every request. - The
-racebox runs the author reports are not verified here; live tests were not approved for this review.
What I checked
- Last review: round 1, f5ff7a3, 2026-10-29T11:00:03Z
- New commits read: 1 (
befcc038fix(store): address round 1 review of the session state file (#769)) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
- New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (approve, 6 non-blocking): checked each item against the fix commit; two overlaps with my findings, four author fixes verified in code.
- The author's comment listing the seven fixes and the two known limits: verified each claim in the diff; the
loadedAtcap claim holds for the map but not forloadedOrder(finding 1). - Commit
befcc038: read the full diff and the code around each change.
- The new test's fields and helpers exist (
Opts.Now,Opts.API,Opts.Tracker,modes.NewTracker,components.NewPipeline(nil, nil)). markLoaded's eviction loop terminates: every live id inloadedAthas at least one entry inloadedOrder, so the loop always reaches an entry that shrinks the map.- The
enqueuecap change keeps both the newest value and the newest timestamp for a key already waiting. - The
--store=falsewarning fires only when the store is not aMemory(Nop), and does not double-warn whenOpenDiskitself failed. failundersync.Mapis safe from concurrent callers;errNstays a count of every failure.- I did not run tests (not approved).
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | befcc038a028 |
blocking |
Verdict: blocking
Findings
- store/disk.go:415 — the failed-load retry path grows
loadedOrderwithout bound; a persistently failing disk adds one entry per request.- What fails:
--session-state-dbon, andloadSessionfails on every request (a query that times out at its 3 s limit behind a stuck writer, a file that corrupts after open, or the missing-table shapeTestFailedLoadAllowsRetrycreates). Each request then appends the session id toloadedOrderagain and again.loadedAtstays empty for that session, so the cap loop inmarkLoaded(disk.go:436) never runs, and nothing ever removes the entries. Memory grows at request rate for as long as the disk fails. - Proof:
markLoaded(disk.go:434-444) appends toloadedOrderonly when the id is absent fromloadedAt. The failure branch (disk.go:412-417) deletesloadedAt[session]but leaves theloadedOrderentry. Trace one request: mark appendss→ load fails →loadedAt["s"]deleted,loadedOrderkeepss. Next request:sabsent fromloadedAt→ mark appendssagain. Repeat per request. A single transient failure leaves the same stale entry: it is popped only when the map reaches the cap, and only from the front.TestLoadedRecordIsCappednever fails a load, so it does not catch this. - Fix: remove the id from
loadedOrderwhen the failure branch clears the mark — the same scan-and-removenoteLost's repair path uses (store.go:960-966). Or makemarkLoadeddrop an existing stale entry before it appends.
- What fails:
Non-blocking
- The data-dependence confirmations are still open.
docs/data-dependence.mdnames Itay Nakash for thesummarizerows. CLAUDE.md wants that confirmation before merge. A human gate, not a code defect.
Earlier findings, round 1
Mine (all non-blocking then):
- Pending-cap update drop — fixed (disk.go:194-197,
TestPendingCapKeepsUpdates). - Only the first disk error logged — fixed (per-op
loggedmap, disk.go:181 and 196-202,TestEachOpLoggedOnce). Not wired into/stats; the author said so, andDisk.Errors()stays test-only. Accepted. - Failed load blocks retry for a lifetime — fixed in intent (disk.go:411-417,
TestFailedLoadAllowsRetry), but the fix introduces finding 1 above. - Responses route loads no alias — fixed (responses.go:543-545,
TestBothRoutesLoadTheAliasSession). I checked the test: it overridesLoadSessionon an embedded*Memory, so it proves apply calls the loader with both ids on both routes. TheAPI,Now,Tracker, andCacheModefields it uses all exist (opts.go:22, 60). loadedAtsoft bound — fixed (hard cap, drop-oldest on insert, no scan). The leak is finding 1.- Unread state key expires while the session is active — left as a known limit, now written in the PR body (Known limits). Accepted: keys a turn reads slide their own TTL, so only unread keys are exposed, and the loss is a wasted model answer, not a cache flip.
Reviewer 2's:
- Responses alias load (blocking) — fixed, same change as my item 4. Verified myself.
loadedAtuncapped with a per-request scan (blocking) — fixed, with finding 1 as the new defect.
--store=falsesilently ignores the flag — fixed (main.go:586-591). I checked:cfg.NewStorereturnsNop{}only when the store is disabled, so the type test is exact.- Failed flush drops its batch, undocumented — fixed (reference.md now says a failed write drops that batch).
- Global-key miss costs a disk read — left as a known limit, now in the PR body. Accepted.
What I checked
- Last review: round 1,
f5ff7a3388da41abe777266378a82d0a780663e0, 2026-10-29T11:02:32Z. - New commits read: 1 (
befcc038"fix(store): address round 1 review of the session state file (#769)"). Full diff read:apply/responses.go,apply/sessionstate_disk_test.go,cmd/context-guru-proxy/main.go,docs/reference/reference.md,store/disk.go,store/disk_test.go,store/store.go. - Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review:
- Reviewer 2's round-1 review — both findings checked against the fix commit; both fixed.
- The author's comment "Round 1 fixes are in
befcc038" — each of its 7 claims verified in the code; claim 3 (failed-read retry) is the source of finding 1. - The PR body's "Known limits" section — confirmed it names the two deferred items.
- Verified the
loadSessionsignature change (([]diskRow, bool)) at both call sites: the empty-session early return givestrue(no failure),rows.Err()returns the partial rows withfalse(retry allowed, partial rows still applied, and the "memory is newer" check makes the retry idempotent). - Verified
markLoaded's normal path: a re-marked session keeps its queue position (oldest means first-loaded), which costs one extra disk read under cap pressure and then self-heals. Accepted. - Did not run tests (not approved).
- A failed session read now removes the id from the order list as well as the map. Before, each request added it again. - After a failed read, the session is not read again for 1 minute, so a hanging disk costs one timeout per session per minute. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Round 2 fix is in the new head.
Box runs, |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 3 of 3 | 960fd24e5626 |
approve |
Verdict: approve
Findings
None.
Earlier findings
-
My round-2 finding (the
loadedOrderleak on a failing disk): fixed.unmarkLoaded(disk.go:459-467) removes the id from both the map and the order list, so a failed load marks and unmarks with nothing left over. The backoff check (disk.go:409) runs beforemarkLoaded, so requests inside the backoff add nothing either. Trace: mark appends → read fails → unmark scans and removes → net zero entries. A stale entry can no longer exist: the only removal path fromloadedAtoutsideunmarkLoadedis the eviction loop, which pops from both.TestFailedLoadsDoNotGrowTheOrderListcovers 50 failed loads of one session and 200 failing sessions and expects 0 entries. -
Reviewer 2's round-2 finding (same leak): fixed, same change. I verified it myself; no extra proof to add.
-
Reviewer 2's round-2 non-blocking (a hanging disk pays the 3 s timeout on every request): fixed by the backoff. After a failed read, the session is skipped for
loadRetryAfter(1 minute), so a hanging disk costs one timeout per session per minute.TestFailedLoadBacksOffcovers both sides of the window. This also answers my round-1 note that a transient failure should not cost a full read cycle per request.
Non-blocking
- The data-dependence confirmations are still open.
docs/data-dependence.mdnames Itay Nakash for thesummarizerows. CLAUDE.md wants that confirmation before merge. A human gate, not a code defect. - The failure record (
loadFailedAt) is cleared wholesale at 4096 entries rather than per-entry. A cleared mark costs one early retry per session. Bounded and documented in the code comment. No action needed.
What I checked
- Last review: round 2,
befcc038a02858cb0e2349bbdb4e8ae93cd35818, 2026-10-29T11:19:25Z. - New commits read: 1 (
960fd24e"fix(store): do not grow the load order list on a failing disk (#769)"). Full diff read:store/disk.go,store/disk_test.go,store/store.go. No other file changed since my last review. - Read in full: 4 reviews, 2 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review, and what I did about each:
- Reviewer 2's round-2 review (blocking, the same
loadedOrderleak) — checked the fix against it; fixed. - Reviewer 2's round-2 non-blocking (per-request 3 s timeout on a hanging disk) — the new backoff addresses it.
- The author's comment "Round 2 fix is in the new head" — both claims verified in the code and its tests.
- Reviewer 2's round-2 review (blocking, the same
- The backoff logic: the check sits before
markLoadedand after the fresh-mark slide, uses the samenowas the lifetime check, and a successful load needs no cleanup (a staleloadFailedAtentry ages out of the window by itself). The map is initialized inNewMemoryand bounded byclearat 4096. unmarkLoadedis the only new remover; it scans the order list on the failure path only, matching thenoteLostrepair precedent. No new lock ordering: the failure branch takesm.muafter the disk read, as before.- The updated
TestFailedLoadAllowsRetryadvances the clock past the backoff, so it still tests the retry and not the window. - Did not run tests (not approved). The author reports
-raceruns green on store, apply, cmd, proxy; not verified here.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 3 of 3 | 960fd24e5626 |
approve |
Verdict: approve
Findings
None. The round-2 leak is closed, and the fix adds no new defect.
Earlier findings
- My round-2 finding (
loadedOrdergrows without bound on a failing disk): fixed.unmarkLoaded(disk.go:459-467) removes the id from bothloadedAtandloadedOrderon the failure path. The invariant holds again:markLoadedappends only when the id is absent fromloadedAt, and every removal now takes both. Trace one failing session: mark appends once → read fails → unmark removes both → the backoff blocks the next mark for 1 minute → the retry appends once again.loadedOrdernever holds orphans. - My round-2 non-blocking (a hanging disk pays 3 s per request): fixed too.
loadFailedAt(disk.go:409-412) backs the retry off for 1 minute, so a hanging disk costs one timeout per session per minute. The failure record is bounded at 4096 byclear(disk.go:423-425); a cleared mark only costs one early retry. - Reviewer 1's round-2 finding is the same leak as mine, now fixed. I verified the fix myself rather than taking the author's word.
- All round-1 findings (both reviewers) were fixed in
befcc038and verified in round 2. Nothing regressed in960fd24e: the diff touches onlyLoadSession,unmarkLoaded,loadFailedAt, and tests.
Non-blocking
- The data-dependence confirmations are still open:
docs/data-dependence.mdnames Itay Nakash for thesummarizerows, and CLAUDE.md wants that confirmation before merge. A human gate, not a code defect. Close it before merging. - The
-racebox runs the author reports (store,apply,cmd,proxy) are not verified here; live tests were not approved for this review.
What I checked
- Last review: round 2, befcc03, 2026-10-29T11:19:03Z
- New commits read: 1 (
960fd24efix(store): do not grow the load order list on a failing disk (#769)) - Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files; the two round-1 reviews and the first comment were read in full in round 2 and are unchanged)
- New items since my last review, and what I did about each:
- Reviewer 1's round-2 review (blocking, 1 finding): it is the same
loadedOrderleak I found; checked the new fix against their trace too. - The author's round-2 comment ("Round 2 fix is in the new head"): both claims verified in the diff —
unmarkLoadedwithTestFailedLoadsDoNotGrowTheOrderList, and the 1-minute backoff withTestFailedLoadBacksOff. - Commit
960fd24e: read the full diff and the finalLoadSessionin place (disk.go:388-438).
- Reviewer 1's round-2 review (blocking, 1 finding): it is the same
- The tests are mutation-sensitive: without
unmarkLoaded, the 50 failed loads of one session leave entries andTestFailedLoadsDoNotGrowTheOrderListfails; without the backoff check,TestFailedLoadBacksOffsees a second disk error inside the window. TestFailedLoadAllowsRetrywas updated for the backoff (clock advanced pastloadRetryAfter), so it still tests what its name says.- Race between two concurrent
LoadSessioncalls for one session: worst case one extra disk read or a stale backoff mark; the "memory is newer" check (disk.go:433) keeps the restored data correct in both orders. - A stale
loadFailedAtentry after a later success is harmless: the freshloadedAtmark wins at disk.go:403, and the record is bounded. loadFailedAtis initialized inNewMemory(store.go:652) and keyed only by non-empty session ids.- I did not run tests (not approved).
The owner chose one database, not a second file. The state now lives in its own table, session_state, in the dashboard database. - store.OpenDisk takes the host's *sql.DB. store does not import dash. - The proxy hands the store the recorder's handle. One pool serializes the dashboard writer and the one-second state flush. - On whenever --dashboard is on. --session-state=false turns it off. --session-state-db is removed. - State rows follow --session-state-retention, not the dashboard prune. A session's rows go when the dashboard archives or evicts it. - A schema bump carries the table across. - Off with --upstreams, with an in-memory dashboard database and with --store=false. A warning says why. - Uninstall skill text names the session state. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
The session state needs a dashboard database on disk. The check compared the path to an empty string only, so ":memory:" passed. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Design change by the owner: one database, no second file. New head
The PR body is rewritten to match. |
|
Data-dependence confirmations, recorded by the integrator (2026-10-29):
The design follows the owner's decision in the same session: the state goes in the dashboard database, in its own table, and it is on whenever the dashboard is on. |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 4 of 5 | 8401b4d8f82a |
approve |
Verdict: approve
Findings
None. The redesign (one database, the dashboard's) is wired correctly, and I found no new defect in it.
Earlier findings
- All findings from rounds 1-3 (both reviewers) were fixed and verified in earlier rounds. The two new commits do not touch
LoadSession,markLoaded,unmarkLoaded, the backoff, or any path reviewed before, except through the*sql.DBswap below, which I re-checked. - My standing non-blocking gate (data-dependence confirmations) is still open: Itay Nakash's confirmation for the
summarizerows. The author says so too. A human gate, not a code defect.
Non-blocking
- dash/janitor.go:378 — the janitor's
deleteSessionStatecall has no test (the author flagged this). Two of the three call sites are tested (DropOldestSessions,ArchiveSessionFull); the third is the same one-line call in the "could not archive, so delete" branch. Low risk, but it is the one new-behavior line without a test. - Alias-keyed rows survive archive and eviction.
cg:seen:andcg:ttl:are keyed by the content-hash alias, not the session id the dashboard knows (apply/apply.go:1125, 1197).DeleteSessionStateremoves only the request's session id, so those rows linger until the 30-day retention sweeps them. Two timestamps per alias, bounded. - dash/store.go:871-885 —
DropOldestSessionsraces itself.oldestSessionIDsruns first, then theDELETEre-derives the victim set with its own subquery. A request inserted between the two can change the ordering, so the state deleted may belong to a survivor. The mismatched rows linger until retention. Off-path, bounded, no data loss. - store/disk.go:189-204 —
DeleteSessionStateignoresrows.Err(). A scan that fails midway silently deletes less. Best-effort by contract, and the caller only logs. - docs/data-dependence.md — small slip. The row says "David Amid confirmed the data-dependence change for
extract_llm_sweep" and then listsextract_llm_sweepagain under "Rows to confirm". One of the two should go. - The default is now on for existing dashboard users. Anyone with
--dashboardon starts writing summary text and freeze decisions to the dashboard database, content keys included, without--dashboard-content. This is the owner's design change (recorded in the row's "Decided by", 2026-10-29), it is named in the docs, and--session-state=falseturns it off. Named here so the merge decision sees it.
What I checked
- Last review: round 3, 960fd24, 2026-10-29T12:32:43Z
- New commits read: 2 (
88005a31feat(store): keep the session state in the dashboard database (#769);8401b4d8fix(proxy): treat the :memory: dashboard database as in memory (#769)) - Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files; rounds 1-3 items were read in full in their rounds and are unchanged)
- New items since my last review, and what I did about it:
- Reviewer 1's round-3 review (approve, no findings): read; nothing to act on.
- The author's design-change comment (one database, no second file): checked every claim against the two commits.
- Commits
88005a31and8401b4d8: read both full diffs and the code around each change.
- The wiring in main.go: the
switchorder (explicit off, dashboard off, multi-tenant, in-memory database, default) is right;rec == nilis guarded;pstoreis created after theStateTTLSecondsbump, so the 24 h lifetime lands;--store=falsekeeps the bump off and logs the warning through the*store.Memorytype test. - Close order:
defer rec.Close()(main.go:395) runs beforedefer d.Close()(main.go:590) is registered, so LIFO flushes the state batch first;Recorder.Closethen closes the database (dash/capture.go:367).Disk.Closeno longer closes a database it does not own. - The schema story:
session_stateis inadditiveDDL, whichmigrateruns on every open (dash/schema.go:936), so an existing version-6 database gets the table with no version bump — the file's own rule for additive tables.nonDerivedTablescarries it across a future bump, andTestSchemaBumpCarriesSessionStatesimulates one. DeleteSessionState: boundary logic matchesloadSession(same prefix ranges, sameboundaryOK); over-deletion past a:is documented and tested (TestDeleteSessionStateKeepsPrefixSessionskeepsabcdefwhenabcgoes); a missing table is not an error.- One pool, two writers: the state flush and the dashboard writer share the dashboard's pool (WAL,
busy_timeout(5000));TestDashboardWriterAndStateFlushTogetherruns both at once and counts rows and errors.OpenDiskno longer touches the host pool's limits. - Fail open holds:
OpenDiskfailure logs and runs memory only (main.go:587-588); everyDiskerror path still counts and continues; the removedSetMaxOpenConns(2)only ever applied to the store's own file. - No leftover references: no
--session-state-db/SESSION_STATE_DB/sessionStateDBremains in code or docs (grep, exit 1). The uninstall skill text now names the session state. - Package boundary:
dashimportsstore;storeimports no dashboard code and no SQLite driver — the host brings both. No cycle. - The
8401b4d8fix itself:rec.DB().Path()returns""or":memory:"for an in-memory database, and both are now refused with the warning;TestDiskFileModewas removed with the file creation it tested (the dashboard owns the file now). - I did not run tests (not approved). The author reports
-racegreen on store, apply, dash, proxy, cmd, and aCGO_ENABLED=0build; not verified here.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 4 of 5 | 8401b4d8f82a |
approve |
Verdict: approve
Findings
None. The redesign is wired correctly. I found no wrong behavior, no data loss, and no broken fail-open path.
Earlier findings
- All findings from rounds 1-3 (both reviewers) were fixed and verified in those rounds. The two new commits do not touch
LoadSession,markLoaded,unmarkLoaded, or the backoff. The only change to those paths is the*sql.DBhandle swap, which I re-checked:get,loadSession,Flush, andsweeprun the same queries on the host's handle. - The data-dependence gate is now closed on the PR: the comment at 13:37:45Z records David Amid's confirmation for
extract_llm_sweepand Itay Nakash's forsummarizeandcache_aware_summarizer, relayed by David Amid. See non-blocking item 3 for the stale records.
Non-blocking
-
The
8401b4d8fix changes nothing:Path()can never return":memory:".dash.Open(":memory:")swaps the path for an in-memory DSN and passes""as the path (dash/store.go:92, 109-110);openDSNsetsd.pathfrom that argument (dash/store.go:288). So the pre-fix checkPath() == ""already refused an in-memory database and logged the warning. The commit message describes a bug that could not occur. The added|| ":memory:"is harmless defense. This also corrects round 4's statement from reviewer 2 thatPath()returns""or":memory:"— only""is reachable. -
Two more session-deletion paths in
dashdo not delete state rows.PurgeTenant(dash/purge.go:134) and the quota trim without cold storage,DropOldestSessionsOfTenant(dash/store.go:952). Both are unreachable while the sessions they delete hold state: they run only for a non-emptytenant_id(TenantRowCountsfilterstenant_id <> '', dash/store.go:913; the purge endpoint is hosted-only, proxy/control.go:136, 188), and hosted mode keeps the state off (main.go warns and skips). But nothing enforces that link. If the state ever turns on per tenant, a purge would keep the tenant's summary text for up to 30 days. Each path is a one-linedeleteSessionStatecall, like the three already wired. -
The confirmation records are stale. The PR body still says "Itay Nakash, confirmation pending", and the doc row in
docs/data-dependence.mdstill lists all three rows under "Rows to confirm". The PR comment at 13:37:45Z records all three as confirmed. Update both before merge, so the record a reader pulls from the repo matches the decision. The PR body also says the owner's final yes on the behavior change is pending — that human gate stays open until merge.
What I checked
- Last review: round 3,
960fd24e56265db76870d85334479082c0aef55d, 2026-10-29T12:32:39Z. - New commits read: 2 (
88005a31"feat(store): keep the session state in the dashboard database (#769)";8401b4d8"fix(proxy): treat the :memory: dashboard database as in memory (#769)"). Full diff read:apply/sessionstate_disk_test.go,cmd/context-guru-proxy/main.go,context-guru-plugin/skills/uninstall/SKILL.md,dash/archive.go,dash/janitor.go,dash/schema.go,dash/sessionstate_test.go,dash/store.go,docs/data-dependence.md,docs/reference/reference.md,store/disk.go,store/disk_test.go. - Read in full: 7 reviews, 4 comments, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review, and what I did about each:
- Reviewer 2's round-3 review (approve): read; nothing to act on.
- Reviewer 2's round-4 review (approve): read in full; checked each of its claims myself rather than repeating them. Its non-blocking items (the untested janitor call, the alias-keyed rows, the
DropOldestSessionsvictim race, the ignoredrows.Err(), the doc slip, the default-on note) are not repeated here. - The author's design-change comment (13:36:15Z): every claim checked against the two commits. All hold.
- The confirmation comment (13:37:45Z): read; closes the data-dependence gate (non-blocking item 3).
- The wiring in main.go: the
switchorder is right (explicit off, dashboard off, multi-tenant, in-memory database, default).recis built before the switch (main.go:390-395) and is never nil with the dashboard on. TheStateTTLSecondsbump lands beforecfg.NewStore(), so the 24 h memory lifetime applies.--store=falsekeeps the bump off (thecfg.Store.Enabledtest) and logs its warning through the*store.Memorytype test. - Close order:
defer rec.Close()(main.go:395) is registered beforedefer d.Close()(main.go:590), so LIFO flushes the state batch first, thenRecorder.Closecloses the database.Disk.Closeno longer closes a database it does not own (disk.go:298-310). - The schema story:
session_stateis inadditiveDDL(dash/schema.go:396-401), whichmigrateruns on every open, so an existing database gets the table with no version bump.nonDerivedTablescarries it across a bump (dash/store.go:180).TestOldDatabaseGetsSessionStateTableandTestSchemaBumpCarriesSessionStatecover both. - Deletion wiring:
ArchiveSessionFull(dash/archive.go:341), the janitor's eviction (dash/janitor.go:378), andDropOldestSessions(dash/store.go:896-899) each calldeleteSessionState. The victims are read before the requests delete inDropOldestSessions.DeleteSessionStateuses the same prefix ranges andboundaryOKasloadSession; over-deletion past a:is documented and tested (TestDeleteSessionStateKeepsPrefixSessions). A missing table is not an error. The dashboard's retention prune leaves the table alone (TestPruneKeepsSessionState), and the store's sweep leaves the dashboard tables alone (TestStateSweepLeavesDashboardTables). - Every other
DELETE FROM requestssite indash: the retention prune (store.go:695) and the byte-budget row drop (store.go:738) delete rows, not sessions; state follows its own retention there by design.purge.go:134andDropOldestSessionsOfTenantare non-blocking item 2. - One pool, two writers: the flush and the dashboard writer share the recorder's pool (WAL,
busy_timeout(5000)).OpenDiskno longer touches the pool's limits.TestDashboardWriterAndStateFlushTogetherruns both at once, counts rows and errors. - Session-id shapes match: in single-tenant mode the store keys and the dash
session_idare the same bare id (tenant""inTenancy.ID, proxy/tenancy.go:135-137); in hosted mode the state is off, so no mismatch can matter. The archive test seedssess-1and the candidate query returnssess-1(dash/archive.go:134-138). - Fail open holds:
OpenDiskfailure logs and runs memory only (main.go:587-588). EveryDiskerror path still counts and continues. The removedSetMaxOpenConns(2)and the file creation with mode 0600 applied only to the store's own file, which no longer exists. - No leftover references: no
--session-state-db/SESSION_STATE_DB/sessionStateDBremains in code or docs (grep, no matches). The test helpers the newdashtests use all exist (openTestDB,seedSessions,seedSessionWithContent,archiveRecorder,countRows,oldestLocalSessions). - The behavior change is named at the top of the PR: who (every
--dashboardinstall), old, new, the off switch, and the owner's decision of 2026-10-29. The uninstall skill text names the summary text in the dashboard database, and its parenthesis is balanced. - I did not run tests (not approved). The author reports
-racegreen on store, apply, dash, proxy, cmd and aCGO_ENABLED=0build; not verified here.
One conflict, in docs/data-dependence.md: #770 added the session state row next to the Keep-alive row. Both changes stay. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
main moved under this branch: #770 (8cc5b84) added session-state persistence to apply, with loadSessionState calls beside the alias and TurnFrom code this branch changed. GitHub reported PR #767 as conflicting and CI did not run on c5443e7. Both sides stay: - #770's loadSessionState(st, res.Session) and loadSessionState(st, alias) calls: the alias session's state loads from disk under the bare-hash alias, the id the store's alias keys use. - This branch's graceAlias := graceAliasID(...) and the TurnFrom alias keys, which resolve the metadata id when the body carries one. No behavior changed on either side. The reviewed commits are untouched; this merge commit is the only addition. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]>
fix: the restart grace uses the thread's last request time (#766) Part 1 of issue #766. After a proxy restart, the grace from #759 decided "is this thread still cached?" by the time the proxy started. It now decides by the time of the thread's own last non-ping request. - modes: Tracker.SetLastSeen gives the tracker a "last seen" lookup. A key with no record, no drop and no usable parent is protected only when its last request is inside the request's cache lifetime. A key the lookup does not know is a really new thread: no grace. With no lookup set (no database, dashboard off), #759's start-time rule stays as the fallback. A panicking lookup reads as "no lookup", so it cannot fail a request. - dash: Recorder.ThreadLastSeen answers that lookup for a thread.Key (session, thread) shape, from the map SeedSessions reloads at startup. - proxy: New wires the tracker's lookup to the recorder when the dashboard is on. --restart-grace=false still turns the grace off in every case. Behavior change: for the first request of each thread after a restart, a thread is protected only if its own last request was within one cache lifetime; a thread with no history is not protected. Decided by the owner on 2026-10-28 in the integrator's session. Part 2 (the dashboard's pricing of a replay after a restart) stays open on the issue; this PR does not build it. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix: the restart grace counts pings and the alias session id (#766) Round 2 of PR #767, from the offload-review's three blocking findings: - Keep-alive pings count on the grace clock. A ping that READ the cache kept the provider's entry warm, so the grace must treat it as a refresh. The recorder now holds a SEPARATE grace map (SeedGraceSessions seeds it from the requests table, Record and ObserveThread keep it current), because the recency map SeedSessions loads must stay ping-free: attribution must not re-date a thread from a ping. A ping that read nothing still counts nowhere. - The grace asks for the thread's keys under BOTH session ids. A conversation that switches between header and headerless turns may be known to the lookup only under its alias id, so TurnFrom takes the alias keys and graceLocked takes the LATER timestamp of the two — the same widening the cold decision's alias clock already had. - Observe mode keeps #759's start-time fallback. Observe rows carry no session id, so the lookup would miss every thread and read each warm one as new. New wires the lookup only for an enforcing mode. Non-blocking from the same review: ThreadRefreshedAt's doc states the prune policy honestly (age-prune above 20,000 entries; the last resort empties the map, and design.md says what that means), and the proxy restart tests seed the grace clock with controlled timestamps. Tests: alias widening at modes and apply level; the ping clock at dash level (seed and live) and through a full proxy restart; observe mode's fallback; all with mutation checks (M7-M15) and the four -race suites. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix: the restart grace records the alias id and declines observe tenants (#766) Round 3 of the offload-review on PR #767. Both blocking findings fixed, plus the three non-blocking items. Finding 1 - the alias widening worked in one direction only. The ask-side wideness could not help a headerless turn, because a headerless request's own derived id IS the alias id: the tracker asks for one key, and the recorder held the header turns' warmth under the other one. Now the record side touches the grace clock under BOTH ids: - proxy/dashcapture.go derives the alias off the pristine body on the writer goroutine (the same lazy normalization WaitCause uses), so the derivation matches what apply computes; the touch and the row's new session_alias column are filled there, never on the handler's defer. - dash's write() invokes that closure before the insert, touches the grace clock under thread.Key(alias, thread), and stores the alias on the row. - SeedGraceSessions seeds both keys, reading the stored alias back. Known limits, documented in docs/design.md and covered by a test: rows written before the column existed have no alias to recover, and a keep-alive ping carries no body to derive one from, so a ping refreshes only the id it ran under. Finding 2 - observe mode is per tenant. The gate read the process mode, so a hosted proxy in sync mode wired the lookup for a tenant whose document sets mode: observe, whose rows carry no session id, and every one of its live threads read as new after a restart. The robust fix (give observe rows their real session id) changes what the observe projection stores and shows, so it was NOT built - that is a behavior change for the owner to allow. What is built instead: the lookup is wired unconditionally and declines the key (have=false) for a tenant whose pipeline runs observe, so #759's start-time fallback answers for exactly that tenant: - modes.Tracker's lookup now returns (atMs, known, have): a third answer, "cannot answer for this key", that falls to the start-time rule where a miss would have read every warm thread as new. - TenantSource.ObserveNamespaces walks the live tenancy cache; the wired lookup declines the keys of the tenants it names, and every key while the whole proxy runs observe. - New tests: a hosted proxy in sync mode with one tenant in observe protects that tenant's live thread after a restart; a sync tenant's unknown thread still reads as new. Non-blocking items: - SeedGraceSessions counts only rows the upstream accepted (2xx); a failed request wrote no cache entry. - Record's comment about a cache-blind ping now states the real rule: such a ping is not counted, as the keeper does not count it either. - The PR body names the compile breaks: TurnFrom gained 2 parameters (round 2) and SetLastSeen's lookup returns 3 values now (round 3). Verified on the eval box: vet and gofmt clean; the focused and full suites for modes, apply, dash, proxy and cmd pass; the new tests fail on origin/main (build: the APIs they use do not exist there); 7 new mutations (M16-M22) are each caught by a test; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> fix: the alias derivation goes through the pipeline transform (#766) Round 4 of the offload-review on PR #767. Both reviewers blocked on the same finding, and the owner decided the fix. The finding: dashcapture's AliasFn derived the alias from the PRISTINE body, but apply derives the id it asks for from the body AFTER transformEnvelope. When toolfilter's skills half rewrites the head message (a skill__ entry in the tenant's removal list), the two hashes differ, so the record-side touch and the session_alias column held an id no request ever asks for — the round-3 widening did nothing for that traffic. The repo names this trap itself: apply.EnforcedSessionIDFor exists for exactly it, and the proxy already uses it twice for that reason. What changed: - proxy/dashcapture.go: the capture holds the pipeline, wire dialect and bypass flag of the request (noteAliasSource, set beside noteWaitBody). finish()'s AliasFn derives the alias through apply.EnforcedSessionIDFor with an EMPTY explicit id, so it is the content-derived alias of the TRANSFORMED body — the exact id the pipeline's own turn asks under. It runs on the writer goroutine, which AliasFn already uses. A capture with no noted source (nil pipe) transforms nothing and keeps the raw-body derivation, the pre-round-4 behavior. - The "never disagree" comment is corrected: the two derivations agree because they read the same transformed body now, not because the hash function is shared. - /compact rows no longer store a constant tenant-wide hash as their alias: EnforcedSessionIDFor returns '' for a bodyless request, so the alias is simply absent (reviewer 2's non-blocking item). - docs/design.md states the transform-based derivation. - Test: TestTheRestartGraceProtectsAHeaderlessTurnWhenToolfilterRewritesTheHead — a tenant whose toolfilter removes a skill, a headered turn before the restart, a headerless turn after it within the lifetime: protected. It fails at fcbb99b (verified on a copy of that head with the new test overlaid). Mutation-checked: deriving from the raw body again (a nil pipe handed to noteAliasSource) fails the test. Verification: vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> fix: one alias rule on both sides of the restart grace (#766) Round 5 of the offload-review on PR #767, the last granted round. Reviewer 2 blocked; the fix follows their proposal and the owner's decisions (the session_alias column, the wider rule and the observe fallback all stay). The finding: after round 4 the two sides of the grace derived the alias by different rules. The record side resolved the metadata session id (EnforcedSessionIDFor resolves explicitSession first), so for a body with metadata.user_id (Claude Code) or metadata.taskId (Bob Shell) it warmed the metadata id. The ask side still asked the bare content hash (session.Scoped with an empty explicit id). A headerless turn runs under the metadata id, so for metadata-carrying traffic the header turn after a restart asked {header id, bare hash}, both missed, and the warm prefix was rewritten. Round 4 fixed the toolfilter case and regressed this one; #759 on main froze it. What changed: - apply/apply.go: new graceAliasID, the ONE rule for the restart grace's alias id: sessionIDFrom with an empty explicit id over the transformed body — the metadata session id when the body carries one, else the content hash of the head. The ask side's TurnFrom alias keys (chat and responses paths) now use it, as a value SEPARATE from the bare-hash alias that keys the cold decision's own clocks (aliasSeen, sessionTTL, RecordCacheTouch): this fix stays inside the restart grace. The record side reaches the same rule through EnforcedSessionIDFor's empty-explicit-id path, so the two cannot drift again. - The round-4 comment, docs/design.md and the PR body now say which id comes out: the metadata id when the body carries one, else the content hash of the transformed body. - Left as is, stated in the PR: the cold decision's own alias clocks key on the bare content hash and do not bridge to a metadata id — old code, no regression from this PR. Tests (proxy/restart_grace_test.go): - TestTheRestartGraceProtectsAHeaderTurnAfterUserMetadataHeaderlessOnes and ...AfterTaskMetadataHeaderlessOnes: a metadata body, headerless turns before the restart, a header turn after it within the lifetime: protected. Both fail at 74ca2a9. - TestAHeaderlessOnlyConversationIsUnchangedAcrossARestart: the no-metadata, no-header shape is unchanged — a control that passes at 74ca2a9 too, which is the point. - The round-3 and round-4 seesaw tests still pass. - Mutations: the ask side reverting to the bare hash fails the metadata tests; the record side reverting to the pristine body fails the toolfilter test. Verification: vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> Merge origin/main into fix/restart-grace-last-seen (#766) main moved under this branch: #770 (8cc5b84) added session-state persistence to apply, with loadSessionState calls beside the alias and TurnFrom code this branch changed. GitHub reported PR #767 as conflicting and CI did not run on c5443e7. Both sides stay: - #770's loadSessionState(st, res.Session) and loadSessionState(st, alias) calls: the alias session's state loads from disk under the bare-hash alias, the id the store's alias keys use. - This branch's graceAlias := graceAliasID(...) and the TurnFrom alias keys, which resolve the metadata id when the body carries one. No behavior changed on either side. The reviewed commits are untouched; this merge commit is the only addition. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]>
…the cache expires (#773) feat(mod): hide the Ping button while an automatic ping fires before the cache expires (#771) The cachestate answer now carries next_ping_ms (metadata only). The band and the pane use one rule, showPing: hide the button when pings_left > 0 and the next ping fires before the cache expires. The band shows "next ping m:ss" in its place. An old proxy that sends no next_ping_ms keeps the old rule. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> feat(mod): remove /ping, and show the Ping button after a stopped thread (#771) - Remove the /ping slash command and its mentions. The Ping button and cg.py ping stay. - A thread the keeper stopped (a miss, a refused ping, a route failure) keeps its copy until the hold ends. A press now works on it, and the server reports it pingable. After the keeper lets go, the reason is still "stopped". Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> test(mod): pin the next-ping rule to the entry's own expiry, and the 59:59 hint width (#771) Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> Merge origin/main into feat/ping-button-when-needed One conflict, in docs/data-dependence.md: #770 added the session state row next to the Keep-alive row. Both changes stay. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> fix(keepalive): a press on a stopped thread checks the route and the credential first (#771) The scheduled ping checks the route breaker and the dead-credential mark right before it sends. A press on a stopped thread now runs the same two checks. If either holds, the press is refused and the thread is reported not pingable, reason "unavailable", so the button stays hidden. When the mark clears, the thread is pingable again while its copy is held. A thread stopped by a miss or a refused ping is not blocked. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> fix(mod): tick the pane's next-ping hint, say the reason in the 409, show "pinging" at 0:00 (#771) - The pane reads the band's tick, so its "next ping m:ss" counts each second. - A 409 "not held" now carries ping_reason (the keeper's own, read at the press). cg.py ping prefers it over the cache-state copy, which can be 15 s old. - When the planned ping time has passed and no new plan came, the hint reads "pinging…" instead of 0:00. The button stays hidden. Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> test(mod): pin the pane tick and the 409 reason test (#771) Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> chore(codex): copy cg.py to the Codex plugin (#771) Assisted-By: Claude Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
fix(dash): session-state follow-ups from #770 Five follow-ups from the session-state change (#770), none blocking: 1. The janitor's "could not archive, so delete" branch now has a test (TestEvictFallbackDeletesSessionAndAliasState), mutation-checked. 2. Deleting or archiving a session now removes the state rows under its content-derived alias too (cg:seen:, cg:ttl: are keyed by the alias), so they no longer outlive the session until the 30-day retention. An alias another live session still uses — by its session_alias column or by a headerless session whose own id IS the alias — is kept. 3. DropOldestSessions picks its victims once and removes exactly that set. The delete used to re-run the ordering subquery itself, so a request landing between the pick and the delete could change the order, and the state cleanup then acted on a set other than the one deleted. 4. DeleteSessionState checks rows.Err(): a scan that fails midway now returns the error instead of silently deleting less. 5. docs/data-dependence.md: extract_llm_sweep removed from "Rows to confirm"; both confirmations are recorded on #770. Data dependence: no change (this deletes more, it stores nothing new). Behavior change: none that a user sees, apart from fewer leftover rows. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix(dash): state cleanup on every session-delete path (#775 review) Both round-1 reviews on #775 were blocking; this answers them. 1. A victim's own id gets the same in-use guard as its aliases. A headerless session (its session_id IS an alias) evicted while the header session sharing that alias is live used to lose cg:seen: and cg:ttl: that the live session still reads. Now both halves are checked before any state key goes: rows carrying it as session_alias, or a live session whose own id IS it. 2. DropOldestSessionsOfTenant deletes state with the rows, through the same guard. The tenant row-quota trim was the one session-delete path that left state behind. 3. The in-use check is no longer one full-table scan per alias on the writer goroutine. idx_requests_session_alias is added on open (old databases get it too, like idx_requests_project), and one pass answers all its in-use checks with TWO queries over the whole key list, not one query per key. 4. Every IN (...) list is bound in batches of 500 ids: the disk rule can ask for a tenth of all sessions at once, past SQLite's 32,766-variable statement limit. 5. A failed victim pick or alias read now returns its error instead of reading as "nothing left to evict", and stateRowsFor-style checks match exact keys. docs/data-dependence.md says an eviction or an archive can end a state row before its 30 days. Data dependence: no change (this deletes more, it stores nothing new). Behavior change: none that a user sees, apart from fewer leftover rows. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> merge: origin/main into chore/session-state-followups Main moved ahead through #773 (the mod's Ping-button change), which conflicted with this branch in one place: docs/data-dependence.md, where #773 grew the keep-alive row next to the row this branch edits. The resolution keeps both: main's keep-alive row (the sentence about the cache-state answer carrying the next planned ping) and this branch's session-state row (an eviction or an archive can end a row before its 30 days). Nothing else was changed; every other file merged cleanly. No behavior change: the merge only combines docs text and already-merged main code. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix(dash): an unreadable in-use answer keeps all state (#775 round 2) Both round-2 reviews blocked on one finding: inUseIDs closed its rows without checking rows.Err(), and skipped a failed Scan silently. A scan that fails midway ends the loop early, so the keys it did not reach read as unused, and deleteSessionState then deleted state a live session still reads — the unsafe direction, and the one the function's own contract forbids. Both failure modes now take the same path as a query that fails to open: log once, mark every key in use, return. Two fake-driver tests cover them; each fails at 434b232 and catches its own mutation. Also: DropOldestSessions' comment no longer says "one statement, so one transaction" — the delete is chunked, and a failed chunk returns before the state cleanup, so earlier chunks' victims keep their state until retention (the safe direction). Left as is, said on the PR: the age-rule archiver runs on its own goroutine, so its delete can interleave with the janitor's in-use count. That window is old, self-healing within one turn, and state cleanup is best-effort by contract. Data dependence: no change (this deletes less on a failure, it stores nothing new). Behavior change: none that a user sees. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
…1101) dedup's "keep in full" marks (cg:keep:) now survive a tenant config rebuild and a restart, so a warm thread with an earlier expand keeps its outputs in full and its cache is read, not rewritten. On cg2 one such rewrite (749k tokens) cost $3.58 after a preset move. - Rebuild: carryKeepMarks (proxy/tenancy.go) copies the marks from the old Store to the new one when both pipelines have the same component names in the same order. It also runs when a second request published the rebuild first. store.CarryPrefix and Memory.EntriesWithPrefix do the copy; an error copies nothing. - Restart: store.KeptPrefix is a metadata session-state key, so the #770 session state saves and reloads the marks. - A different component set, and dedup on a fresh thread: no change. Behavior change: hosted tenants whose config changes, and local hosts after a restart, on a thread with an earlier expand. Old: dedup compacted those outputs again and the warm cache was rewritten. New: they stay in full and the cache is read. A hosted restart still loses the marks (no session-state table there). How to turn it off: no dedicated switch; store.enabled: false removes all marks, --session-state=false stops the restart half. Owner's yes, 2026-11-11, in the integrator session: "1101 behavior approved". Data dependence: metadata only. A mark key holds a session id and a content hash; the value is one byte. Row: docs/data-dependence/features/session-state-table.md. Fixes #1097. Reviews: 2 offload reviews (GLM), round 2, both approve at 23d8b5e, which is the PR head. Signed-off-by: DAVID AMID <[email protected]> Assisted-By: Claude Opus 5.5 <[email protected]>
Behavior change
--dashboard. Also every proxy started with--dashboard. No change without the dashboard.--session-state=false(SESSION_STATE=false). That is today's memory-only store with the 2.8 h lifetime.Data dependence
This changes data dependence. At "everything", content keys go to the dashboard database:
cg:sum:(summary text),cg:res:,cg:xres:,cg:frz:,cg:swh:. Today they live only in memory.--session-state=false)--session-state-metadata-only)cg:bin:,cg:bint:,cg:len:,cg:ttl:,cg:seen:,cg:swd:,cg:swk:,cg:swx:,cg:rst:,cg:use:.docs/data-dependence.mdhas a new row, and two cells are updated.extract_llm_sweep: David Amid confirmed the change.cache_aware_summarizer,summarize: Itay Nakash, confirmation pending.Summary
What changed
store/disk.go:Disk, a write-through copy of the state keys.store.OpenDisk(*sql.DB, opts)takes a handle the host owns.storedoes not importdash.Disk.Closeflushes and never closes the handle.session_state(key BLOB PRIMARY KEY, val BLOB, updated INTEGER), one row per store key. The DDL is indash/schema.go(so an old database gets the table on open) andstore.OpenDiskruns the sameCREATE TABLE IF NOT EXISTS. Choice: one row per key, with no session column. A session is found by a key range, since every key ends in the session id.rec.DB().SQL(), the recorder's own pool. The proxy opens nothing new.--session-state-dbis removed. New:--session-state(default true),--session-state-metadata-only,--session-state-retention(720 h).store.state_ttl_secondssets the memory lifetime of state keys only. Default 0 =ttl_seconds(2.8 h). The proxy sets 24 h when the table is on and the value is 0.store.Memory:Putqueues state keys.LoadSessionreads one session's rows.Getfalls back to the table for the two keys with no session id (cg:xres:,cg:swx:).apply: callsLoadSessiononce per request, before the pipeline, for the session id and the alias id, on the chat and the Responses route.--session-state-retention. The store's sweep (at open, then hourly) deletes only fromsession_state.store.DeleteSessionState, at a key boundary).nonDerivedTables).-race.--upstreams(a store per tenant), with an in-memory dashboard database, and with--store=false. A warning says why.docs/data-dependence.md,docs/reference/reference.md.Choices to confirm
session_state, one row per key, no session column.cg:use:: included, so a cost is never lost.How it was tested
All runs on the eval box,
CGO_ENABLED=1 go test -race -count=1, unless noted../store/..../apply/..../dash/..../proxy/..../cmd/..../components/...go vet ./...,gofmt -l .CGO_ENABLED=0 go build ./...New tests:
store: restart, idle past 24 h, no startup load, one read per lifetime, metadata only, stash never written, fail open (corrupt, bad handle, closed DB), no sync write, retention sweep, loaded-record cap, retry and backoff, order list does not grow.apply:BodyOptsrestores state on the first request. Both routes load the alias id.dash: an old database gets the table; the prune keeps state rows; the store sweep leaves dashboard tables; eviction and archive delete the session's rows; a prefix-sharing session is kept; a schema bump carries the table; the dashboard writer and the flush run together with no error and no lost row.Mutation checks (one break each in a box copy; the named test fails):
Putdoes not queueTestDiskCheckpointSurvivesRestartTestMetadataOnlyWritesNoContentKeyTestStashNeverWrittenTestLoadSessionReadsOncePerLifetimeTestNoLoadAtStartupTestBothRoutesLoadTheAliasSessionTestFailedLoadsDoNotGrowTheOrderList,TestFailedLoadBacksOffTestDiskCheckpointSurvivesRestartTestSchemaBumpCarriesSessionStateTestEvictionDeletesSessionState,TestArchiveDeletesSessionStateTestDeleteSessionStateKeepsPrefixSessionsTestStateSweepLeavesDashboardTablesI did not mutation-check the janitor's delete of a session's state (
dash/janitor.go). No test covers that path.My first prefix-sharing test checked a BLOB key with
LIKEand passed for nothing. It now casts the key to text.Known limits
--upstreams.cg:xres:,cg:swx:) costs one table read each time.modes.Tracker,thread.Tracker,keepalive.Keeper,sentStash, the registries.Fixes #769
🤖 Generated with Claude Code