Skip to content

fix(offload): scope kept-verbatim marks to the session that expanded (#175) - #756

Merged
amiddavid merged 3 commits into
mainfrom
fix/kept-session
Oct 27, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/kept-session

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

A kept-verbatim mark now belongs to the session that expanded the content. One session no longer exempts that content in every other session.

What changed

  • Key shape: cg:keep:<session>:<contentkey>. Before: cg:keep:<contentkey>.
  • MarkKeptVerbatim(st, session, original) and KeptVerbatim(st, session, original) take the session. isKeptVerbatim reads c.Session.
  • Empty session writes nothing. No fallback to a global key.
  • No migration read (changed in round 1). The Store is in memory only, so an old-shape mark cannot survive the restart that installs this change. Reading the old shape would only keep the cross-session leak alive. The window is therefore zero and there is nothing to retire.
  • Proxy: repairExpandErrors derives the session with new apply.EnforcedSessionIDFor. It runs the same envelope transform as BodyOpts first, then derives the id. It runs only when a repair restored something. The expand loop already had tr.Session.
  • Breaking change: the exported MarkKeptVerbatim and KeptVerbatim gain a session argument. Downstream importers (the sidecar plugin repo) fail to compile until they pass it.
  • Pin list: no change. cg:keep: stays unpinned, and the prefix is the same. store/stash_test.go still passes.
  • Tests: un-skipped TestKeptVerbatimDoesNotLeakAcrossSessions and TestMarkKeptVerbatimIgnoresAnEmptySession. Added TestEnforcedSessionIDForMatchesThePipelineWithTheSkillsHalfActive and TestObserveBilledInputKeyMatchesThePipelineWithTheSkillsHalfActive. Callers in tests now pass the session. (TestLegacyKeptMarkIsStillReadButNeverWritten was added in round 0 and removed with the legacy read in round 1.)
  • Docs: one line in docs/how-to/recover-context.md.

How it was tested

Run Where Result
New leak test (body from the PR) clean origin/main copy FAIL: "session-b inherited session-a's kept-verbatim exemption"
Three new/restored tests this branch PASS
Mutation: key without session mutated copy TestKeptVerbatimDoesNotLeakAcrossSessions FAIL
gofmt -l, go vet ./components/... ./proxy/... this branch clean
go test -race ./components/offload this branch PASS (358 s)
go test -race components/all, dsl, reformat, store, expand, apply this branch PASS
go test -race ./proxy/... this branch PASS (463 s after round 1)
Round 1: TestEnforcedSessionIDForMatchesThePipelineWithTheSkillsHalfActive fixture asserts raw id differs from the pipeline id (this is what the old code used) PASS; mutation (skip the transform) FAIL
Round 1: delete the c.Restored return in isKeptVerbatim mutated copy TestTheSpanGuardProtectsARestoredOriginalInEitherForm FAIL
Round 1: -race offload, apply, components/*, store, expand, proxy this branch PASS

The first run of ./components/offload failed in 3 tests that built old-shape keys with the wrong session. I fixed the tests. The code did not change.

Data dependence

  • Metadata only. The key holds a session id and a content hash. The value is the byte 1.
  • Off (store.enabled: false): no Store, no mark. Same as before.
  • Metadata only: works, as before.
  • Everything: works.
  • No row in docs/data-dependence.md changes. No feature gains or loses a dependence on stored content.

Open questions

  • KeptVerbatim (dashboard count-once) is now session-scoped too. Reason: the dashboard row is per session. A second session that gets the same bytes back is a second recovery and should be charged. A global flag would charge only the first session. Cost: the same bytes can be charged once per session. Alternative: a separate global "counted" key. The code does not need it. Do you want it?
  • Unknown session. If SessionIDFor returns "" (body has no usable messages), the repair writes no mark and charges the dashboard on every turn. That body has nothing to repair, so I expect it to be rare. Tell me if you want a fallback.

Closes #175

🤖 Generated with Claude Code

…175)

The key was cg:keep:<contentkey>, so one session's expand exempted that
content in every session sharing the store. The key is now
cg:keep:<session>:<contentkey>.

- MarkKeptVerbatim and KeptVerbatim take the session. isKeptVerbatim
  reads c.Session.
- A write with an empty session writes nothing.
- The read side still accepts the old key shape for a deprecation
  window. Only the new shape is written.
- The proxy repair passes the session id derived for the request.
- The two skipped tests are restored, plus one test for the old shape.

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.311 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 62c2b0d347d0 blocking

Verdict: blocking

Findings

  1. proxy/proxy.go:1233 — the repair writes its kept-verbatim mark under a session id the pipeline never reads

    • What fails: a request that needs the expand repair gets a dead mark. The pipeline then re-compacts the restored original on every later turn. The model expands it again. The client answers the expand call with an error again. That is the bounce loop cg:keep: exists to stop. The charge-once guard (KeptVerbatim, proxy.go:1590) also never latches, so noteExpand charges the same original on every turn.
    • Proof: the write side keys the mark on apply.SessionIDFor(tn.ID, header, provider, body) (proxy.go:1234, used at :1596). Go evaluates that argument before repairExpandErrors runs, so it hashes the body BEFORE the repair and BEFORE the envelope transforms. The read side, isKeptVerbatim (state.go:423), uses c.Session, which apply derives inside BodyOpts from the body AFTER transformEnvelope (apply/apply.go:430 transform, :443 messagesArray, :486 normalize, :496 sessionIDFrom). The skills half of toolfilter rewrites the first message in messages that carries the skills listing, with no role check (apply/toolfilter.go:471 and :535). When that message is the first system or first user message, schema.SessionHead hashes different text before and after the transform. The two session ids differ, keptMarked misses, and the mark is never read. The repair itself does not diverge the hash: it only rewrites tool_result content, which normalize moves into synthetic role:tool messages (apply/apply.go:1640-1658), and SessionHead reads only system and user roles. So the divergence is exactly the envelope transform. Reachability is narrow but real: toolfilter ships in every major preset (config/config.go:538-567), the skills removal needs a skill__… entry, the listing must sit in the head message (the measured shape puts it at messages[1] behind a first system message at messages[0], which does NOT diverge — a client that puts the listing in the head message does), and the session must be derived, not explicit. No test pins write-session == read-session: TestTheRepairPathSendsRecoveredContentUpstreamOnce runs without toolfilter, so the transform is a no-op there.
    • Fix: key the repair's mark on the same session apply will derive. Either resolve the session after transformEnvelope on the same bytes BodyOpts normalizes, or have apply expose the resolved session to the caller once, and pass that into repairExpandErrors. Add a test with toolfilter's skills half active and the listing in the head message.
  2. components/offload/expand_restore_test.go:136 — the fixed-restore override test lost its kept-verbatim half

    • What fails: TestTheSpanGuardProtectsARestoredOriginalInEitherForm no longer tests what its comment claims. It would pass with the c.Restored override in isKeptVerbatim deleted, so nothing pins the #407 property that a restored original must read as NOT kept-verbatim.
    • Proof: line 136 builds c := &components.Ctx{Store: …, Restored: …} with no Session. Line 138 marks under session "s". isKeptVerbatim (state.go:419-424) with c.Session == "" skips the session key and checks only the legacy key (keptMarked, state.go:375-383). Nothing wrote a legacy key. So the answer is false with or without the c.Restored early return, and the assertion at :139-141 passes for the wrong reason. Before this PR the mark was global, so the same test genuinely proved the override.
    • Fix: add Session: "s" to the Ctx at line 136. The mark at :138 is already under "s".

Non-blocking

  • state.go:359-361 — the keptKey comment says "the first ':' after the prefix always ends the session part". That is false for tenant-scoped sessions (tenant:base always contains a colon) and for explicit ids (safeExplicit allows ':'). Nothing parses the key today, so no behavior breaks. But the comment invites a future parser to split on the first colon. Say instead that nothing parses the key, or drop the claim.
  • state.go:375-383 — during the deprecation window every unmarked candidate pays a second Get (the legacy key) through skipReduce, on the hot path. Memory.Get also slides the TTL and reorders the LRU on legacy keys. Accepted cost of the window; worth remembering when the window ends.
  • The cross-session leak persists for legacy marks during the window. That is deliberate per issue #175 and documented at state.go:364-371. The PR title alone could read as if the leak is fully closed today.

What I checked

  • The full diff, and the code around each hunk (state.go, proxy.go chat/serve/repairExpandErrors, every touched test).
  • Key scheme soundness: contentKey is fixed-length 24-hex, so no two (session, ck) pairs can produce the same key, and the new shape (always one extra colon) can never collide with the legacy shape.
  • All callers of MarkKeptVerbatim / KeptVerbatim / keptKey across the repo: updated to the new signatures; no old-signature call remains; no other host (adapters, cmd, dash) calls them.
  • Session consistency of the other write path: serve's expand loop marks under tr.Session (proxy.go:2045), which is the same post-transform id the pipeline's Ctx.Session uses on later turns. Consistent.
  • The empty-session no-op: MarkKeptVerbatim writes nothing, keptMarked reads only the legacy shape, and Ctx.Session == "" only occurs when the pipeline derived no session, so write and read stay consistent there.
  • Test wiring in every touched test file: mark session matches reader session (coref, expand_gates, skeleton, summarize, all, cache_aware_span, extract_sweep_recheck, expand_restore), except finding 2.
  • Issue #175's spec against the implementation: session in the key, empty session as a no-op write, read-both-shapes window, both skipped tests restored. All present. The KeptVerbatim charge-once scoping choice (per session, not global) is a documented decision in the comment, which the issue asked to be made explicitly.
  • Store side: cg:keep: stays an unpinned, evictable namespace; the store's own comments about it still hold. Per-session keying multiplies entries only for content expanded in several sessions, which is the case the fix targets.
  • Data dependence: unchanged — the mark is still metadata (session id plus content hash); no docs/data-dependence.md update needed.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.311 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 62c2b0d347d0 blocking

Verdict: blocking

Findings

  1. proxy/proxy.go:1234 — the repair derives the session id from the pristine body, but the pipeline derives it from the envelope-transformed body, so the kept-verbatim mark can be written under an id no offloader reads.

    • What fails: a tenant configures toolfilter with skill__ removals, and the skills listing sits in the message SessionHead hashes (the system message on the OpenAI dialect, or the first user message). The client answers an expand call itself with an error. The next request repairs it. The repair marks the original under SessionIDFor(pristine body). The pipeline then derives tr.Session from the body after transformEnvelope removed skill entries from that head message. The two ids differ. isKeptVerbatim (components/offload/state.go:423) reads c.Session, finds no mark, and the offloader re-compacts the restored original. The model meets the marker again, calls expand again, and the session enters the bounce loop this mark exists to prevent. On such a tenant, every repair-path mark is orphaned, on every turn.
    • Proof: proxy/proxy.go:1234 passes the pre-transform body to SessionIDFor. BodyOpts runs transformEnvelope at apply/apply.go:430 before it derives the session at apply/apply.go:496 (sessionIDFrom(o.Tenant, o.Session, body, norm) — body is the transformed one). filterSkillListingWithAdapter rewrites the message text that holds the listing (apply/toolfilter.go:518, sjson.SetBytes(body, path, ...)), and skillListingPath scans every message with no exclusion for the head (apply/toolfilter.go:543-560; the responses adapter scans instructions and leading system items, apply/responses.go:94-122, and bodyResponsesOpts also transforms before deriving, apply/responses.go:510-519). SessionHead hashes exactly that text (schema/schema.go:258-272). The in-band expand loop does not have this defect: it marks under tr.Session (proxy/proxy.go:2045 via proxy/proxy.go:1432). Note the once-only charge still holds — the repair reads and writes the mark with the same (wrong) id — so the visible damage is the bounce guard only.
    • Fix: mark under the id the pipeline will derive. Either run the same envelope transform before SessionIDFor, or hand the restored originals to apply (an Opts field) and let BodyOpts mark them right after it computes sessionID at apply/apply.go:496, before the pipeline reads the transcript.
  2. proxy/proxy.go:1233 — the session id is derived eagerly on every enforced chat request, and the derivation re-normalizes the whole transcript.

    • What fails: Go evaluates the apply.SessionIDFor(...) argument before repairExpandErrors runs. This happens on every non-observe, non-bypassed chat request. SessionIDFor → normalizeSessionMessages → normalize unmarshals every message of the transcript (apply/apply.go:1395-1401, apply/apply.go:1600). BodyOpts then repeats the same normalize at apply/apply.go:486. So the request path pays the full messages parse and unmarshal twice, plus the []ChatMessage allocation twice. The value is used only inside the for _, orig := range restored loop (proxy/proxy.go:1587-1597), which runs only when a repair actually restored an original — a rare event. This repo prices the request path at about 0.35 s and 140 MiB of allocation per MiB (proxy/proxy.go:1156-1158), so a second full normalize is a real latency and GC cost on every large request.
    • Proof: the only consumers of session in repairExpandErrors are the KeptVerbatim and MarkKeptVerbatim calls inside the restored loop. RepairToolResults returns restored empty on almost every request (no expand tool_use in the transcript), so the derivation is wasted work in the common case.
    • Fix: compute the session lazily. Run RepairToolResults first, and call SessionIDFor only when len(restored) > 0. Combined with finding 1, derive it from the body the pipeline will see.

Non-blocking

  • components/offload/state.go:359-361 — the comment says "the first ':' after the prefix always ends the session part". A tenant-scoped session id is tenant:base (session/session.go:167-169), so the first ':' ends the tenant, not the session. Nothing parses the key today. Fix the comment before a future parser believes it, or say "the last ':'".
  • components/offload/state.go:364-372 — the legacy read re-opens the cross-session exemption for old-shape marks during the window. The shipped store is in-process (Memory), so an old-shape mark cannot survive an upgrade; the window only matters behind a custom persistent Store. Also nothing tracks the stated "two releases". Consider dropping the legacy read, or file the removal.
  • The exported signature change of MarkKeptVerbatim and KeptVerbatim breaks downstream importers (the sidecar plugin repo) at compile time. The break is loud, but that repo needs a coordinated update.
  • docs/components/coref.md:383 still describes kept-verbatim without the session scope. recover-context.md was updated; this page was not.
  • components/offload/expand_restore_test.go:138 — TestTheSpanGuardProtectsARestoredOriginalInEitherForm marks under session "s" while its Ctx carries no session, so the mark is never read. The test passes because c.Restored short-circuits isKeptVerbatim. The mark line suggests coverage it does not provide.

What I checked

  • The full diff and the code around each hunk: state.go key layout, both proxy call sites, all test updates.
  • Every offloader reaches the mark through isKeptVerbatim → c.Session (components/offload/state.go:419-424), so the scoping itself is complete. No caller of the old two-argument forms remains.
  • The in-band expand loop marks under tr.Session (proxy/proxy.go:1432, 2045), the id the pipeline itself derived. Consistent.
  • The repair itself cannot change the session head: RepairToolResults rewrites only expand tool_result content (expand/repair.go:59-117), and normalize maps tool_result blocks to synthetic role:tool messages, never to the system or first user message (apply/apply.go:1600-1687).
  • Key collisions: contentKey is 24 hex chars with no colon (internal/extract/extract.go:151), so scoped keys of different sessions cannot collide, and the empty session writes nothing.
  • Store behavior: cg:keep: is not in DefaultPinPrefixes, and both key shapes share the prefix, so eviction and pinning are unchanged (store/store.go:254-268).
  • The new and un-skipped tests: session values in each fixture match the Ctx the test builds (coref, gates, recheck, span, skeleton, summarize, all).
  • Live tests were not run (not approved). Findings rest on code reading only.

… legacy read (#175)

- The proxy repair derived the session from the raw body. The pipeline
  derives it after the envelope transform (toolfilter rewrites the head
  message), so the ids could differ and the mark was never read. New
  apply.EnforcedSessionIDFor runs the same transform first.
- The repair derives the session only when it restored something.
- Drop the read of the pre-#175 key shape. The Store is in memory only.
- Fix the keptKey comment, the span-guard test Ctx, and coref.md.

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 1 fixes are in e95ec831. Reviewer 1 is R1, reviewer 2 is R2.

Blocking

Non-blocking

  • keptKey comment (both): fixed. It now says nothing parses the key and the session may hold ":".
  • coref.md:383 (R1): fixed.
  • Signature break for downstream importers (R1): added to the PR body.
  • Legacy read (R1 question, R2 note): dropped. The Store is in memory and never on disk, so an old mark cannot survive the restart that installs this change. The read only kept the leak alive and cost a second Get on the hot path. The legacy test went with it. The PR body no longer has a deprecation window.

Run results are in the PR body table.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.311 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 e95ec831de08 approve

Verdict: approve

Findings

None. Both round-1 blocking findings are fixed and verified; the new commit introduces no new defect I can show.

Status of round-1 findings

  1. R1 #1 and R2 #1 (the repair marked under a session the pipeline never reads): fixed.

    • apply.EnforcedSessionIDFor (apply/apply.go:1403-1417) runs the same transformEnvelope BodyOpts runs, with the same pipeline and adapter, then derives the id through SessionIDFor. The proxy calls it through the sessionOf closure (proxy/proxy.go:1233-1236).
    • I checked the two transforms EnforcedSessionIDFor does not run: upgradeHeadTTL writes only tools.N.cache_control.ttl and top-level system (apply/headttl.go:60, 96-121), and splitVolatileTail writes only top-level system (apply/prefixsplit.go:167). Neither touches messages, so neither can change what SessionHead hashes. The derivation matches BodyOpts exactly, on both the chat and the responses path (apply/responses.go:510-519 transforms before deriving too).
    • The closure receives the repaired body (sessionOf(out), proxy/proxy.go:1594), which is what BodyOpts will see. The one rewrite between the two, adjudicate.AnswerStrayCalls (proxy/proxy.go:1256), touches only tool_result content of adjudicate calls (internal/adjudicate/tool.go:251-281), which normalize maps to role:tool — never the session head. So the ids agree.
    • The new test pins it: TestEnforcedSessionIDForMatchesThePipelineWithTheSkillsHalfActive (apply/session_enforced_test.go) puts the skills listing in a head system message, asserts the raw-body id differs from the pipeline id (so the fixture really exercises the bug), and that EnforcedSessionIDFor equals the pipeline id. I checked the test compiles against the existing pipe helper (apply/apply_test.go:24) and Config.Build (config/config.go:887).
  2. R1 #2 (eager session derivation on every request): fixed. repairExpandErrors returns early when nothing was restored (proxy/proxy.go:1587-1589) and derives the session only inside the rare path. The derivation is also heavier now (a transform plus a re-parse), which makes the laziness matter more, not less.

  3. R2 #2 (span-guard test passed for the wrong reason): fixed. The Ctx now carries Session: "s" (components/offload/expand_restore_test.go:136), matching the mark. With the c.Restored early return deleted from isKeptVerbatim, the mark would now make the test fail — so the override is genuinely pinned.

  4. Non-blocking notes: all addressed. The keptKey comment now says nothing parses the key and the session may hold ":" (components/offload/state.go:359-364). coref.md states the session scope. The signature break is in the PR body. The legacy read is dropped entirely.

    On dropping the legacy read, the author's reason is: the Store is in memory and never written to disk, so a pre-#175 mark cannot survive the restart that installs this change. I accept the reason. store.Memory is the only shipped Store; nothing in this repo persists it. The residual risk is a downstream host that plugs a persistent Store in behind the interface: an unread old-shape mark costs one bounce turn before the expand loop re-marks under the scoped key. Fail open holds, and the cost is one turn. Dropping the read also removes R2's hot-path note (the second Get on every unmarked candidate) and closes the window's leak for good.

Non-blocking

  • proxy/proxy.go:1770 — observe mode's RecordBilledInput still derives its id with plain SessionIDFor from the body the enforced path forwarded. The shadow pipeline derives its own id from the envelope-transformed copy, so on a tenant with skill__ removals and the listing in the head message, the write and the read key on different ids and PrevBilledInput stays 0 — the permanent zero SessionIDFor was created to fix, on the same divergence this PR just repaired. Pre-existing, not this PR's diff, and narrow (R2's round-1 note says the measured listing shape does not sit in the head message). Follow-up: use EnforcedSessionIDFor there too. It runs once per response, so the extra transform is cheap.

What I checked

  • Last review: round 1, 62c2b0d, 2026-10-27T16:46:23Z
  • New commits read: 1 — e95ec831 "fix(offload): derive the repair's session like the pipeline, drop the legacy read (#175)"
  • 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 2's round-1 review (16:45:29Z, before my posting time): read in full. Its finding 1 matches my finding 1; I verified the fix once, above. Its finding 2 (span-guard test) I re-derived myself: the missing Session made the mark unread, so only c.Restored decided the outcome — the fix restores the pin.
    • The author's comment (17:06:22Z): read in full. Each claim checked against the code — all hold. The mutation claim for the new test follows from the logic (skip the transform → the derived id equals the raw id → the assertion EnforcedSessionIDFor == res.Session fails against a fixture where the raw id differs).
    • Commit e95ec831: read the full diff and the code around each hunk.
  • EnforcedSessionIDFor vs BodyOpts, transform by transform: envelope (same call), headttl and prefixsplit (messages untouched, so no session effect), responses path (same adapter and order).
  • No reference to legacyKeptKey or keptMarked remains anywhere in the repo.
  • The lazy path: sessionOf is called only after len(restored) > 0, on the repaired body.
  • The reworked tests: TestMarkKeptVerbatimIgnoresAnEmptySession (inline legacy literal), the deleted legacy test, the span-guard Ctx fix.
  • Live tests were not run (not approved). Findings rest on code reading only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.311 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 e95ec831de08 blocking

Verdict: blocking

Status of earlier findings

  • My #1 (repair marks under a session the pipeline never reads): fixed. EnforcedSessionIDFor (apply/apply.go:1403) runs the same transformEnvelope adapter BodyOpts runs, then derives the id through the shared SessionIDFor/sessionIDFrom. I checked both paths against BodyOpts: the chat path normalizes the same post-transform messages; the responses path (always an OpenAI route, proxy.go:436) reaches the same normalizeResponses; headttl adds only cache_control (never message text) and splitVolatileTail reorders system after norm is built from the pre-split messages, so neither moves the hash; metadata is untouched by every transform, so explicitSession agrees. The derivation is lazy (len(restored) > 0) and keyed on the repaired body, which is what applyMode receives. The new test puts the listing in the head system message and asserts the raw id differs, so it fails on the old code.
  • My #2 (span-guard test lost its kept-verbatim half): fixed. Session: "s" is on the Ctx (expand_restore_test.go:136). The mark is now read, so the c.Restored override is load-bearing again.
  • Reviewer 1 #1 (same defect as my #1): fixed, agree. Verified myself above.
  • Reviewer 1 #2 (eager session derivation on every request): fixed. repairExpandErrors takes a sessionOf function and calls it only after a repair restored something (proxy.go:1590-1594).
  • Non-blocking round 1: the keptKey comment now says nothing parses the key and the session may hold ":" — fixed. coref.md:383 now states the session scope — fixed. The legacy read is dropped, not windowed: I checked the author's reason and accept it. The shipped Store is Memory (process-local) or Nop; no persistent Store exists in this repo, so no old-shape mark can survive the restart that installs the new shape, and the exported-signature break already forces a coordinated rebuild for any downstream persistent-store host. The signature break is now in the PR body.

Findings

  1. proxy/proxy.go:1778 — the observe-mode billed-input record still uses the raw-body session id, so the shadow pipeline never reads it
    • What fails: on an observe tenant with toolfilter's skills half active and the listing in the head message, RecordBilledInput(tn.Shadow, sid, …) writes cg:bin: under the pre-transform id (proxy.go:1778-1780). The shadow pipeline derives its Ctx.Session after transformEnvelope (proxy/modes.go:162, apply/apply.go:430→496) and reads prevBilledInput under that id. The two differ, the record is never found, PrevBilledInput stays 0, FracResolvable reads false, and every fraction gate declines in the projection. That is the exact failure the comment above the call site (proxy.go:1763-1773) says this write exists to prevent: the operator sees the mode save nothing, forever. This is the same divergence class this PR just fixed for the repair path, in SessionIDFor's other customer. It is PRE-EXISTING on the base (present at proxy.go:1769 in 245982d) and milder than my round-1 finding: observe mode only, measurement understated, no agent harm, same narrow config (a skill__… removal, listing in the head message, derived session).
    • Proof: the call passes body — in observe mode applyMode returns the input unchanged and expand.Inject is skipped, so it is the raw, pre-transform body. The shadow job in observe runs BodyOpts on a copy of that body with no Bypass, so transformEnvelope runs and the session is the post-transform id (apply/apply.go:430, 496). SessionIDFor's own doc comment names this observe path as the reason it exists.
    • Fix: one line — use the PR's own new function here: apply.EnforcedSessionIDFor(tn.Pipe, tn.ID, r.Header.Get("x-context-guru-session"), api, provider, false, body). If the author prefers to keep this PR scoped to #175, file it as its own issue; say so and I will not hold the merge for it.

Non-blocking

  • PR body drift after e95ec83: the Tests bullet still says "Added TestLegacyKeptMarkIsStillReadButNeverWritten" and the mutation table still names it, but that test was deleted with the legacy read. Update the body. Remember gh pr edit silently no-ops on this repo — use gh api -X PATCH repos/rossoctl/context-guru/pulls/756 --input.
  • On a repair turn the transcript is now parsed twice (once in EnforcedSessionIDFor, once in BodyOpts). Repair turns are rare, so this is fine; noted only so the cost is visible.

What I checked

  • Last review: round 1, 62c2b0d, 2026-10-27T16:45:29Z
  • New commits read: 1 — e95ec83 "fix(offload): derive the repair's session like the pipeline, drop the legacy read (#175)"
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files)
  • New items since my last review, and what I did about each:
    • Reviewer 1's round-1 review (posted 16:46:23Z, one minute after mine): read in full. Its two findings match my #1 and add the eager-derivation cost. Both fixed; I verified the fixes myself.
    • The author's comment (17:06:22Z) describing the fixes: each claim checked against the code. All hold, except the PR body still names the deleted legacy test (non-blocking above).
    • Commit e95ec83: full diff read, and the code around every hunk (EnforcedSessionIDFor against BodyOpts on both wire paths, the lazy sessionOf, the dropped keptMarked, both test edits, coref.md).
  • The new test's fixture: the listing sits in messages[0] role system, the only system message, so SessionHead hashes it; the skill__deep-research removal passes the prose gate because the listing is subtracted from the region; apply_test already blank-imports components/all, so the toolfilter registration runs.
  • No remaining references to legacyKeptKey / keptMarked anywhere; the empty-session test now builds the old shape inline.
  • EnforcedSessionIDFor with a nil pipeline: transformEnvelope no-ops, matching BodyOpts with a nil pipeline. Consistent even there.
  • Live tests were NOT run (not approved). The PASS and mutation results in the PR body are the author's; I did not reproduce them.

…sion (#175)

The observe path wrote cg:bin: under the id of the raw body. The shadow
pipeline reads it under the id derived after the envelope transform, so
with toolfilter's skills half and the listing in the head message the
record was never found. Use EnforcedSessionIDFor, as the repair does.

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 2 fix is in the new head (see the commit below). Reviewer 2's finding is fixed.

  • Finding (observe path wrote cg:bin: under the raw-body id): fixed. proxy/proxy.go now calls apply.EnforcedSessionIDFor(tn.Pipe, tn.ID, header, wire, provider, false, body). bypass is false, as in the observe job. wire is "responses" for the responses API.
  • Test: TestObserveBilledInputKeyMatchesThePipelineWithTheSkillsHalfActive. It uses an observe tenant with toolfilter (skill__deep-research), the listing in a head system message, and no explicit session header. It asserts the raw id differs from the pipeline id, then waits for the record under the pipeline id. With the old SessionIDFor call back, it fails: no cg:bin: record under the pipeline's id "8bf63f5edb37ffb5" (raw-body id is "45fbf6259aa1b27f").
  • gofmt, go vet ./proxy/ clean. -race ./proxy/... passes.

Every caller of SessionIDFor

  • proxy/proxy.go repair (was SessionIDFor, now EnforcedSessionIDFor, round 1): the id must match the pipeline's.
  • proxy/proxy.go observe billed-input record: changed now, same reason.
  • apply/apply.go: EnforcedSessionIDFor calls it after the transform. No change.
  • Tests only, unchanged: apply/responses_test.go:112, apply/restore_test.go:44, proxy/cgllm_test.go:552, proxy/dashexpand_test.go:253, proxy/expand_restore_test.go:261. Their bodies have no skills listing, so the transform is a no-op and both ids are equal.
  • No other host (adapters, cmd, dash) calls it.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.311 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 66320c44450e approve

Verdict: approve

Findings

None. The new commit fixes the one open finding correctly, and I found no new defect in it.

Status of earlier findings

  1. R2 round-2 #1 / my round-2 non-blocking note (observe billed-input record keyed on the raw-body id): fixed.

    • proxy/proxy.go:1777-1781 now calls apply.EnforcedSessionIDFor(tn.Pipe, tn.ID, header, wire, provider, false, body). I verified each argument against what the shadow job's BodyOpts derives:
      • Same pipe — tn.Pipe is what h.observe passes to the off-path BodyOpts (proxy/modes.go:162).
      • Same wire discriminator — serve's wire is "responses" exactly when up.path == "/v1/responses" (proxy/proxy.go:1633-1636), which is the one responses route (proxy/proxy.go:436). So the adapter choice matches BodyOpts's o.API branch.
      • Same bypass — the observe job's Opts.Bypass is the zero value, and observe runs only when the request is not bypassed (proxy/modes.go:41), so false is the value the shadow run uses.
      • Same body — in observe mode applyMode returns the input unchanged, the repair and expand.Inject are skipped, so body is the same pristine body the observe job copies.
    • Two edges checked and clean. A bypassed observe request writes a record no shadow job read that turn — but a later non-bypassed turn of the same session derives the same id, so the record is still found. A hallucinated expand call could reassign body to a continuation inside the loop, but a continuation appends messages at the tail and SessionHead hashes only the system and first user message, so the id is unchanged. That edge predates this PR.
    • The test pins it end to end: TestObserveBilledInputKeyMatchesThePipelineWithTheSkillsHalfActive (proxy/cgllm_test.go:576-630) posts through the real mux on an observe tenant with skill__deep-research removed, a head system message carrying the listing, and no session header. It asserts the raw id differs from the pipeline id first, so the fixture exercises the bug, then polls the shadow store for the record under the pipeline id. It reads h.shadow, the store New wires into the default tenancy (proxy/proxy.go:370-376) — the same one the sibling observe test documents as the request path's store.
    • Cost: one transformEnvelope per observe response, on top of the normalize SessionIDFor already did. Once per response, on the measurement path. Accepted.
  2. My round-1 #1 and #2, R2 round-1 #1 and #2: fixed in e95ec831, re-verified in round 2. Unchanged by the new commit; I re-read the touched regions and nothing regressed.

  3. R2 round-2 non-blocking (PR body names the deleted TestLegacyKeptMarkIsStillReadButNeverWritten): still open. I fetched the PR body: the Tests bullet and the mutation table still name the deleted test. Agree with R2, non-blocking, doc only. Remember gh pr edit silently no-ops on this repo — use gh api -X PATCH repos/rossoctl/context-guru/pulls/756 --input.

  4. R2 round-2 non-blocking (repair turn parses the transcript twice): accepted as-is. Repair turns are rare; noted, no change needed.

Non-blocking

  • The PR body drift above is the only open item I know of. It does not hold the merge.

What I checked

  • Last review: round 2, e95ec83, 2026-10-27T17:11:16Z
  • New commits read: 1 — 66320c44 "fix(proxy): key the observe billed-input record on the pipeline's session (#175)"
  • Read in full: 3 reviews, 2 comments, 0 inline comments (from the three saved files)
  • New items since my last review, and what I did about each:
    • R2's round-2 review (17:12:35Z): read in full. Its finding matches my round-2 non-blocking note, with the same proof line (shadow job derives post-transform, record wrote pre-transform). I verified the fix myself, argument by argument, above.
    • The author's comment (17:26:22Z): read in full. Each claim checked — the fix, the test's failure mode on the old code (follows from the same mechanism the apply-level test pins), and the SessionIDFor caller census (I re-ran it: repair and the observe record now use EnforcedSessionIDFor; the rest are tests whose bodies carry no skills listing, so both ids agree).
    • Commit 66320c44: full diff read, plus the code around both hunks (serve's wire derivation, the deferred block's variables, the observe job in modes.go, New's shadow wiring).
    • The PR body (fetched separately, to check R2's drift note): the deleted legacy test is still named in two places.
  • The observe record's edge cases: a bypassed observe request, and a hallucinated expand call reassigning body mid-loop. Both leave the derived id correct; both predate this PR.
  • Live tests were not run (not approved). The PASS and mutation results quoted on the PR are the author's; I did not reproduce them.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Field Value
Reviewer 2 of 2 (GLM)
Context Resumed
Head 66320c44450e
Review 3 of 3
Verdict Approve

Status of earlier findings

My round-2 finding (observe billed-input record keyed on the raw-body id): fixed in 66320c44.

  • proxy/proxy.go serve defer now calls apply.EnforcedSessionIDFor(tn.Pipe, tn.ID, header, wire, provider, false, body). This is the id the shadow pipeline derives.
  • I checked the arguments against the shadow job:
    • wire is string(provider), or "responses" only on /v1/responses (proxy.go:1633-1636). For EnforcedSessionIDFor this matches the api == "responses" branch on all three routes.
    • bypass is false, as in the observe job's BodyOpts.
    • tn.Pipe is the same pipeline the shadow job uses.
    • In observe mode, serve's body is the raw input, the same bytes the shadow job's BodyOpts transforms.
  • New test TestObserveBilledInputKeyMatchesThePipelineWithTheSkillsHalfActive covers it. The fixture is right: head system message with the skills listing, skill__deep-research removal, no explicit session header. It asserts the raw id differs from the pipeline id, then polls the shadow store under the pipeline id. The helpers it uses exist (fakeUpstream returns usage, so the defer writes the record; h.shadow exists in observe mode).
  • I did not run the test. Live test runs were not approved. I verified it by reading.

What I checked

  • Last review: round 2, e95ec831de08aa74afdd97ff317a1fb8713a7fe3, posted 2026-10-27T17:12:35Z.
  • New commits read: 1.
    • 66320c44 fix(proxy): key the observe billed-input record on the pipeline's session (#175) — proxy/proxy.go +6/-2, proxy/cgllm_test.go +56.
  • Read in full: 4 reviews, 2 comments, 0 inline comments.
  • New items since my last review, and what I did:
    1. Commit 66320c44 — read the full diff and the changed code around it (serve defer, wire construction, route registration). Verified as above.
    2. Author comment 2026-10-27T17:26:22Z — checked each claim. The caller enumeration of SessionIDFor matches my own grep of the tree: repair and observe now use EnforcedSessionIDFor; apply/apply.go internal; the rest are tests whose bodies carry no skills listing. No other host calls it.
    3. Reviewer 1 round-2 review (approve, with the observe-path issue as non-blocking) — no finding of mine to duplicate; the follow-up it asked for is done in this head.
  • I also re-fetched the PR body to check the round-2 non-blocking note.

New findings

None blocking. One non-blocking note:

  • PR body drift, still present. The Tests bullet says "Added TestLegacyKeptMarkIsStillReadButNeverWritten", and the mutation table names the same test. That test was deleted in e95ec831 with the legacy read. Fix the body with gh api -X PATCH repos/rossoctl/context-guru/pulls/756 --input — gh pr edit silently no-ops on this repo.

Notes

  • I did not run Go builds or tests. Test runs were not approved for this review.
  • All three of my blocking findings across rounds 1 and 2 are fixed and verified by reading. The core change — session-scoped cg:keep: marks, with both proxy writers deriving the session the same way as the pipeline — is sound.

@amiddavid
amiddavid merged commit 50af4d3 into main Oct 27, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 27, 2026
@amiddavid
amiddavid deleted the fix/kept-session branch October 27, 2026 17:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(offload): kept-verbatim marks are global, so one session's expand exempts that content for every session

1 participant