Skip to content

fix: the restart grace uses the thread's last request time - #767

Merged
amiddavid merged 6 commits into
mainfrom
fix/restart-grace-last-seen
Oct 29, 2026
Merged

amiddavid merged 6 commits into
mainfrom
fix/restart-grace-last-seen

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human's yes per RELEASING.md — decided by the owner on 2026-10-28 in the integrator's session: "I accept part 1")

  • Who: every proxy user, for the first request of each thread after a restart.
  • Old: the thread was protected if it arrived within one cache lifetime of the proxy start — new or old thread alike.
  • New: the thread is protected only if its own last request or ping that refreshed the cache, under either session id the conversation uses, was within one cache lifetime. A thread with no history is not protected. A tenant running observe mode keeps the old start-time rule (its rows carry no session id, so the lookup declines its keys).
  • Off switch: --restart-grace=false, as today. With the dashboard off (no database), the old start-time rule stays as the fallback.

Summary

Part 1 of #766, written by GLM (rits/zai-org/glm-5-3) through Claude Code. After a proxy restart, the restart 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 cache refresh. Part 2 (the dashboard's pricing of a replayed removal after a restart) is not built here and stays open on the issue.

What changed

  • modes/tracker.go: TurnFrom asks the host's last-seen lookup for the thread's key and its alias key (the same conversation under a second session id), taking the later timestamp. SetLastSeen's lookup returns (atMs, known, have) — three answers: the timestamp; "looked, never seen" (a really new thread, no grace); and "cannot answer for this key" (no database, or a deployment running observe mode), which falls to fix: keep the cached part safe after a proxy restart, and label partial cache reads as misses (#496) #759's start-time rule where a miss would have read every warm thread as new. A panic in the lookup reads as "cannot answer" (fail open). A fork whose parent is unknown asks about the parent's last request.
  • apply (chat and responses paths): passes both keys to TurnFrom. The alias key comes from graceAliasID, the ONE rule both sides of the grace resolve — the metadata session id when the body carries one (metadata.user_id, metadata.taskId), else the content hash of the transformed head. It is a separate value from the bare-hash alias that keys the cold decision's own clocks (idle, TTL), which are unchanged.
  • dash/capture.go: a separate grace clock (graceSeen), distinct from the attribution recency map. SeedGraceSessions reloads it at startup — real requests and cache-reading pings, 2xx rows only, each row seeding both its own key and its stored alias key. ObserveThread (real requests), Record (cache-reading pings) and the writer goroutine's alias touch keep it current. ThreadRefreshedAt answers the tracker.
  • proxy/dashcapture.go: derives the alias through the pipeline's own envelope transform (apply.EnforcedSessionIDFor, empty explicit id) on the writer goroutine — the metadata session id when the body carries one, else the content hash of the transformed head (toolfilter's skills half rewrites the head message the session hash reads, so the transform must run) — touches the grace clock under the alias key, and stores the alias in the new session_alias column — so a headerless turn after the restart, whose own derived id IS the alias, finds the header turns' warmth.
  • proxy/proxy.go + proxy/tenancy.go: the lookup is wired whenever the dashboard is on, and declines the keys of tenants running observe (TenantSource.ObserveNamespaces walks the live tenancy cache), so those tenants keep the start-time fallback — including per tenant on a hosted proxy whose own mode is sync.
  • Docs: the restart-grace paragraph in docs/design.md, and the Cache tracker row in docs/data-dependence.md.

Compile breaks for a downstream importer of modes (the sidecar plugin depends on this repo): TurnFrom gained 2 parameters (round 2) and SetLastSeen's lookup returns 3 values (round 3). Loud, not silent.

Known limits (documented in docs/design.md, covered by tests): a row written before the session_alias column existed has no alias to recover, so a seesaw-id tenant's first headerless request after an upgrade can read as expired (one turn, once); a keep-alive ping carries no body to derive an alias from, so a ping refreshes only the id it ran under.

The library does not import dash: the host hands the lookup in, the same way apply passes the cache lifetime to TurnFrom.

Data dependence: metadata only — thread ids, session ids (including the content-derived alias id, a hash like the session id itself) and one timestamp per thread. One new column on the dashboard's requests table (session_alias), additive with a default. At storage level "off" (no database), the fallback is #759's start-time rule. The Cache tracker row in docs/data-dependence.md is updated to say this.

How it was tested

All runs on the eval box (~/cgssh2), Go 1.26, CGO_ENABLED=1.

Round 1 (see the reply comments for the round-by-round detail): the modes matrix, the proxy wiring test, mutations M1–M6, and the four -race suites.

Round 2: ping-counting and alias-ask tests at the dash, apply, modes and proxy levels, mutations M7–M15, four -race suites.

Round 3:

Run Copy Result
go vet ./modes/... ./apply/... ./dash/... ./proxy/... ./cmd/..., gofmt -l fix clean
Full suites: modes, apply, dash, proxy, cmd fix PASS
New tests on unmodified origin/main main + changed test files FAIL (build: the APIs they use do not exist there)
Mutation M16: writer goroutine never runs AliasFn mut caught by the dash alias test and the proxy seesaw test
Mutation M17: capture path sets no AliasFn mut caught by the proxy seesaw test
Mutation M18: seed ignores the stored alias mut caught by the dash seed test and the proxy seesaw test
Mutation M19: seed counts rejected rows mut caught by the dash seed test
Mutation M20: tenantObserves answers no for every key mut caught by the hosted observe test and the single-tenant observe test
Mutation M21: ObserveNamespaces reports no tenant mut caught by the hosted observe test
Mutation M22: a declined lookup reads as a miss mut caught by the modes declining test and the hosted observe test
go test -race -count=1 on modes, apply, dash, proxy fix PASS (all four)

New tests, round 3:

  1. Last pre-restart request with the session header, first request after the restart headerless, within the lifetime: protected (the record-side alias touch and the seeded alias key).
  2. A different conversation, also headerless, unknown: editable.
  3. A hosted proxy in sync mode with one tenant in observe: after a restart, that tenant's live thread is protected (start-time fallback); a sync tenant's unknown thread still reads as new.
  4. The dash seed covers the alias key and skips rejected rows; the live recorder touches the alias key and stores it on the row.
  5. A lookup that declines the key falls to the start-time rule (modes level).

Round 4 — the alias derivation goes through the pipeline's transform (apply.EnforcedSessionIDFor), so toolfilter's skills half cannot make the recorded alias differ from the id the pipeline's turn asks under:

Run Copy Result
go vet ./proxy/... ./dash/..., gofmt -l fix clean
Full suites: modes, apply, dash, proxy, cmd fix PASS
New test on unmodified fcbb99b3 fcbb99b + the changed test file FAIL (the transformed alias id's grace clock = (0, false))
Mutation M23: the alias derived from the raw body again (a nil pipeline handed to the transform) mut caught by the round-4 test
go test -race -count=1 on modes, apply, dash, proxy fix PASS (all four)

New test, round 4: a tenant whose toolfilter removes a skill (the head message changes), a headered turn before the restart, a headerless turn after it within the lifetime: protected. A different conversation stays editable.

Round 5 (this commit) — ONE alias rule on both sides (apply.graceAliasID on the ask side, EnforcedSessionIDFor's empty-explicit-id path on the record side): the metadata session id when the body carries one, else the content hash of the transformed head. Round 4 had regressed metadata-carrying traffic (the ask side still asked the bare hash, which no metadata turn runs under):

Run Copy Result
go vet ./apply/... ./proxy/..., gofmt -l fix clean
Full suites: modes, apply, dash, proxy, cmd fix PASS
New metadata tests on unmodified 74ca2a96 74ca2a9 + the changed test file FAIL (12 of 12 tokens attempted — the warm prefix rewritten)
The round-3, round-4 and no-metadata control tests on 74ca2a96 74ca2a9 + the changed test file PASS (the control passes at both heads, which is the point)
Mutation M24: the ask side reverts to the bare hash mut caught by both metadata tests
Mutation M25: the record side reverts to the pristine body mut caught by the round-4 toolfilter test
go test -race -count=1 on modes, apply, dash, proxy fix PASS (all four)

New tests, round 5: a metadata.user_id body (Claude Code's JSON-object shape) and a metadata.taskId body (Bob Shell's bare id), each with headerless turns before the restart and a header turn after it within the lifetime: protected. A no-metadata, no-header conversation across a restart: unchanged (protected under its own content-hash id, at both heads).

Known limit, unchanged old code: the cold decision's own alias clocks (idle, TTL) key on the bare content hash and do not bridge to a metadata id. Moving that rule is the owner's call, not this PR's.

Refs #766 (part 2 stays open)

🤖 Generated with Claude Code

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]>

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

Verdict: blocking

Findings

  1. modes/tracker.go:279 — the grace clock ignores keep-alive pings, so a restart during a ping-held idle gap edits a warm prefix

    • What fails: a thread goes idle at t=0 (Anthropic, 5-minute lifetime). The keeper pings every ~4 minutes, so the provider entry stays warm. The proxy restarts at t=2h; the keeper is memory-only ("never persisted", keepalive/keeper.go), so the pings stop. The thread's next request arrives at t=2h+1min. The entry is still warm (last ping just before the restart). The lookup answers t=0 — the last non-ping request — so 2h > 5min reads as expired, the boundary is 0, and the pipeline rewrites a prefix the provider still holds. Cost: a full cache-write at 1.25x, the exact cost this design exists to avoid.
    • Proof: graceLocked (modes/tracker.go:279-286) compares the lookup's timestamp against the lifetime. ThreadLastSeen (dash/capture.go:741-748) reads r.lastSeen, which observe writes from real requests only, and which SeedSessions seeds with keepalive = 0 in both halves of the query (dash/capture.go:686-689). But a ping refreshes the entry: dashcapture.go:582 says "A keep-alive ping that READ the cache moved the provider's clock", and ping rows with their own ts do exist in requests (keepalive = 1). The repo states the invariant this breaks in the same file the PR edits: modes/tracker.go:79-82 — "a keep-alive can hold a provider entry warm with no request at all, so an expired key is remembered as dropped and never read as 'nothing cached'". Before this PR the case was covered twice: #759 froze the request (restart 1 minute ago), and a live tracker protects the same thread (record until StaleAfter = 6h, then dropped → all-cached). One more aggravation: keep-alive runs only with the dashboard on (cmd/context-guru-proxy/main.go:384-388), so the start-time fallback never applies in exactly the deployments that use keep-alive. graceLocked's own comment claims the request lifetime is "the longest a restart-forgotten entry of this thread can still be alive" — false when a ping refreshed it later than the last request.
    • Fix: answer the grace from the last refresh, request or ping. Seed a grace-specific map from max(ts) over rows including keepalive = 1 (or make ThreadLastSeen consult them). Keep SeedSessions' recency map ping-free, as its comment requires — the attribution figures must not re-date a session from a ping.
  2. modes/tracker.go:279 — the lookup answers per derived session id, so an id-switched thread reads expired though its prefix is warm

    • What fails: a tenant sends the session header on some turns and not on others — apply.go:560-564 documents this for three of thirteen production tenants. Before the restart, the conversation's last request ran under id A (header present), 30 seconds ago. After the restart, the first request comes headerless and derives id B (session.Scoped hashes the head when no header is given, session/session.go:151-170). The tracker asks about B; the lookup answers B's last headerless turn, which can be older than the lifetime; the boundary is 0 and the pipeline edits the prefix. The provider entry is keyed on content, and A's request refreshed it 30 seconds before the restart.
    • Proof: turnKey is thread.Key(sessionID, tr.Thread.ID) with sessionID from sessionIDFrom (apply/apply.go:497, 521); ThreadLastSeen keys on that same string with no alias consult. The cold decision in the same function already widens across the alias (aliasSeen, apply.go:579-583) for exactly this reason; the grace does not. Before this PR: post-restart, #759 froze the request within the restart window; in a live process, B's own tracker record protected it. The PR body's approved wording — "protected only if its own last non-ping request was within one cache lifetime" — reads as the conversation's last request; the implementation answers the last request under the same derived id, which can be much older.
    • Fix: widen the grace the way the cold decision does. The host lookup (or the caller in apply, where the body is at hand) also asks for the alias key and takes the later of the two timestamps.

Non-blocking

  • ThreadLastSeen's comment (dash/capture.go:739) says a thread "has pruned after two silent hours". Pruning runs only when the map passes 20,000 entries (dash/capture.go:599), and the overflow fallback empties the map wholesale (dash/capture.go:654-656). On that fallback every thread reads as new at once, and the grace protects nothing — #759's start-time rule used to. Rare, but the doc states a prune that does not run on a timer.
  • The new proxy test relies on wall-clock freshness ("moments ago, well inside the 5-minute lifetime"). It passed, but a slow CI box could flake. Seeding lastSeen with a controlled timestamp would make it deterministic.

What I checked

  • The full diff, and the code around each change: modes/tracker.go (grace path, TurnFrom, pruneLocked, dropped), dash/capture.go (observe, SeedSessions, pruneSessionsLocked, the new ThreadLastSeen), proxy/proxy.go (New wiring), and both TurnFrom callers in apply (chat and responses paths).
  • Key-shape agreement: the tracker's turnKey and the recorder's map both use thread.Key(sessionID, threadID) with the same sessionIDFrom derivation, so the lookup answers for the key the tracker asks about.
  • Ordering: main.go runs SeedSessions before it builds the handler, so the wiring comment in proxy/proxy.go holds.
  • Lock order: the lookup runs under t.mu and takes r.mu; I found no path that holds r.mu and calls into the tracker, so no deadlock.
  • Fail-open: a panicking lookup is recovered and reads as "no lookup" (modes/tracker.go:299-310); a nil recorder returns not-known. Both verified.
  • The new tests: all six modes cases and the proxy restart test match the code's behavior; the helpers they use exist in proxy/dash_test.go.
  • The PR body: the behavior change is named at the top with the owner's decision, and the data-dependence row is updated. Process requirements from CLAUDE.md and RELEASING.md are met.
  • I did not run Go builds or tests (not approved for this review).

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

Verdict: blocking

Findings

  1. proxy/proxy.go:383 — in observe mode the last-seen lookup never matches, so the restart grace is silently off there
    • What fails: a proxy runs in observe mode with the dashboard on. It restarts. The first request of a live thread reads as a brand-new thread (boundary 0), not as all-cached. Before this PR, #759's start-time rule protected it.
    • Proof: the lookup keys and the tracker keys disagree in observe mode.
      • The tracker key is thread.Key(sessionID, threadID) with the derived session id (apply/apply.go:521).
      • The recorder's lastSeen key is thread.Key(e.SessionID, e.ThreadID) (dash/capture.go:574, set at dashcapture.go:561-562).
      • In observe mode the enforced path returns a zero trace (proxy/modes.go:43), so e.SessionID = tr.Session is "" (dash/event.go:661). The comment at proxy/proxy.go:1791 says the same: "there is no Trace, session above is ''".
      • So observe-mode rows key lastSeen under thread.Key("", ""), and SeedSessions seeds those same "" keys. The tracker asks for the real session id. Every lookup misses.
      • A miss takes the have && !known branch (modes/tracker.go:279-281) and returns 0. The start-time fallback is skipped. The off-path run then measures the whole cached prefix as compactable, which overstates the projection — the exact gap the shared Tracker exists to close (docs/design.md, Observe; modes.go:171-176 puts a similar gap at 9.5% projected vs 0.8% enforced).
    • Fix: give observe-mode rows their real session id, the way the response path already does for billed input (apply.EnforcedSessionIDFor, proxy/proxy.go:1804), so both sides key the same. Or wire SetLastSeen only for an enforcing mode, so observe keeps #759's fallback. Add an observe-mode restart test; the new proxy test covers sync mode only.

Non-blocking

  • dash/capture.go:654 — pruneSessionsLocked's last resort empties the whole lastSeen map when more than 20,000 threads are active inside two hours. The grace now depends on that map, so in that case every thread reads as "really new" and the start-time fallback is skipped too. Pre-existing map policy, rare; worth a sentence in the design doc.
  • modes/tracker.go:299-310 — lastSeenLocked recovers a panic and reads it as "no lookup". Good fail-open. Note the recovered branch returns have=false, so the fallback rule answers; the test covers this.

What I checked

  • Read CLAUDE.md, docs/design.md, the full diff, and the code around every change.
  • modes/tracker.go: SetLastSeen, graceLocked, lastSeenLocked semantics against every caller (Turn, TurnAt, TurnFrom, the fork/parent path, the bypass path with grace 0). Checked the panic-recovery branch, the nowMs <= 0 legacy path, and the --restart-grace=false gate.
  • Key agreement in sync mode: the tracker's turnKey and the recorder's lastSeen both derive from sessionIDFrom + thread.Result.ID, so ThreadLastSeen matches. Confirmed by the new proxy test's approach.
  • Lock order: the lookup runs under the tracker's lock and takes the recorder's mu. No dash path calls back into the tracker while holding mu, so no inversion.
  • Startup order in cmd/context-guru-proxy/main.go: SeedSessions (line 393) runs before proxy.New (line 550); the bound method reads the live map anyway.
  • Ping paths: automatic pings (dispatch + dashEmitter.KeepAlivePing) and manual pings (keeper path) never call ObserveThread, and SeedSessions filters keepalive = 0. "Last non-ping request" holds.
  • The new tests: read all four modes tests and the proxy restart test, including the helpers they reuse (dashHandler, waitForRows uses the recorder's own Written counter, so the shared database does not make the wait racy).
  • PR rules: the behavior change is named at the top of the PR with the owner's yes (2026-10-28), and docs/data-dependence.md's Cache tracker row is updated. Both match the repo's stated policy.
  • Live tests were not run (not approved); this review reads the code only.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 2 is pushed: d91efe93. All three blocking findings are fixed, plus both non-blocking items. Details per finding below.

Finding 1 (reviewer 1): pings must count on the grace clock

Fixed. The grace now answers from the thread's last cache refresh, not its last request.

  • dash.Recorder holds a separate grace map (graceSeen), seeded by the new SeedGraceSessions: per thread, max(ts) over rows that refreshed the entry — a real request (keepalive = 0), or a ping that read the cache (keepalive = 1 AND cache_read > 0). main.go runs it next to SeedSessions.
  • SeedSessions' recency map stays ping-free, as its comment requires. The dash test asserts this directly: the pinged thread's attributed gap is its real request's 2 hours, not the ping's 1 minute.
  • At runtime, ObserveThread (real requests) and Record (cache-reading pings) keep the map current. A timestamp only ever moves forward.
  • ThreadLastSeen is renamed ThreadRefreshedAt, since that is what it now answers.

Tests: dash-level (restart seed and live clock, including a ping that read nothing), and a full proxy restart — idle 2 h, ping 1 min before the restart reading the cache, back 1 min after: protected (whole request frozen). The same thread pinged with cache_read = 0 stays editable. Mutation checks M7–M10 and M15 (seed ignores pings; seed counts blind pings; live ping removed; live request removed; clock moves backwards) — all caught.

Finding 2 (reviewer 1): the alias session id must widen the grace

Fixed, the way the cold decision widens its clock.

  • TurnFrom now takes the thread's alias key and the parent's alias key. graceLocked asks the lookup for both keys and takes the later timestamp — monotone toward warm, like aliasSeen.
  • apply computes both alias keys on the chat and the responses paths, from the same session.Scoped alias the cold decision uses.

Tests: a modes matrix (only the alias knows the thread, recent and expired; both known, either later; fork of an alias-refreshed parent), and an apply-level test: the header-bearing turn after a restart is protected by the alias id's clock alone (MaxCachedIdx covers the request; without the alias key it is -1). Mutations M11 (graceLocked ignores the alias) and M13 (apply passes no alias key) — both caught.

Finding 3 (reviewer 2): observe mode read every thread as new

Fixed with the smaller of your two options: New wires SetLastSeen only for an enforcing mode. Observe keeps #759's start-time fallback, so a live thread inside one lifetime of the restart is protected instead of editable.

Test: TestObserveModeKeepsTheStartTimeFallbackForTheRestartGrace. One note on its shape: an observe row's figures are zeroed with the trace, so the dashboard cannot show the boundary — the test probes the handler's tracker directly, which is the same tracker the off-path run consults. It fails under mutation M12 (wiring the lookup in observe mode too).

Non-blocking items

  • ThreadRefreshedAt's comment now states the prune policy honestly: age-prune only above 20,000 entries, last resort empties the map. docs/design.md says what that means — every thread reads as new until its next request, a lost saving for one turn, never a wrong rewrite.
  • The proxy tests now seed the grace clock with controlled timestamps and assert the exact seeded value, so nothing depends on wall-clock freshness.

Verification

go vet and gofmt clean; full suites pass for modes, apply, dash, proxy, cmd; all new tests fail on unmodified origin/main; 8 mutation checks all caught; the four -race suites pass. One note: TestALateFirstByteOnTheRealTransportNeverReachesTheClient (upstreamsilence, untouched by this PR) failed once in the first proxy -race run under full-suite load on the shared box, then passed in isolation and in a full -race rerun — a 5 ms real-transport timing budget, not related to this change.

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

Verdict: blocking

Status of earlier findings

  • Reviewer 1, finding 1 (pings must count on the grace clock): fixed. graceSeen is a separate map; SeedGraceSessions counts real requests and cache-reading pings; Record and ObserveThread keep it current; SeedSessions' recency stays ping-free, and the dash test asserts the attributed gap directly. I verified the query, the guards (session != "", CacheRead > 0), the forward-only clock, and that ping rows reach Record through dashEmitter.KeepAlivePing with the derived session id — the same key shape the tracker asks for.
  • Reviewer 1, finding 2 (the alias session id must widen the grace): fixed in one direction only. The direction the finding describes — headerless first turn after a restart, warmth recorded under the header id — is unchanged. Finding 1 below.
  • Reviewer 2 (mine), finding 3 (observe mode read every thread as new): fixed for a single-tenant proxy. New wires the lookup only when opts.Mode != ModeObserve, and the test proves the fallback answers. The fix does not hold in hosted mode, where mode is per tenant. Finding 2 below.
  • Non-blocking items from round 1: both addressed (ThreadRefreshedAt's doc and design.md state the prune policy; the proxy tests seed controlled timestamps and assert the seeded value).

Findings

  1. modes/tracker.go:294 — the alias widening collapses for a headerless turn, so reviewer 1's finding-2 scenario is still open

    • What fails: a tenant sends the session header on some turns and not others. The conversation's last pre-restart request carried the header, 30 seconds before the restart. The first request after the restart is headerless. Its prefix is warm, but the boundary is 0, so the pipeline rewrites it — a full cache-write of the suffix, the expensive direction. On main (#759) this turn was frozen.
    • Proof: for a headerless request, the turn's own session id IS the alias id. sessionIDFrom with no header derives the content hash (session.Scoped, session/session.go:161-166), and apply computes alias := session.Scoped(o.Tenant, "", sys, firstUser) — the same string (apply/apply.go:553-556). So aliasKey == turnKey, and graceLocked's guard aliasKey != key (modes/tracker.go:294) skips the alias consult. The lookup is asked for the content-hash key only. But the dash map holds the header turns' warmth under the header id: ObserveThread keys graceSeen by e.SessionID (dash/capture.go:650-653), which is the id the request ran under. Miss → have && !known → 0, and the start-time fallback is skipped (modes/tracker.go:304-306).
    • The round-2 commit fixed the mirror case only: a header-bearing turn asks for (header id, content-hash id) and finds headerless warmth. The author's test (TestTheRestartGraceAsksTheAliasSessionIdToo, and the apply-level test) covers only that direction. The reply's claim "fixed the way the cold decision widens its clock" does not hold: the cold decision's alias clock is symmetric, because aliasSeen writes the store under the alias id on every turn (apply/apply.go:1124-1135); the dash map is keyed by each turn's own id, so it cannot answer the reverse question.
    • Fix: make the recorder learn the alias key too. dashcapture.go's finish already has the pristine body and the normalizer; compute the content-derived alias there (the same session.Scoped(tenant, "", sys, firstUser)) and touch graceSeen under both keys. Then a headerless turn's single ask finds the header turns' warmth. RecordCacheTouch (apply/apply.go:1137) is precedent for alias-keyed writes.
  2. proxy/proxy.go:390 — in hosted mode a per-tenant observe deployment still wires the lookup, so my round-1 finding returns through that door

    • What fails: a hosted proxy runs with the dashboard on and the operator's mode left at the default (sync). One tenant's config sets mode: observe. The proxy restarts. That tenant's live threads read as brand-new on their first request — the observe projection overstates savings, the exact defect of round 1.
    • Proof: the gate reads the handler-wide mode. New wires SetLastSeen when opts.Mode != components.ModeObserve (proxy/proxy.go:390), and opts.Mode is the operator's proxy-level mode (cmd/context-guru-proxy/main.go:602). In hosted mode the mode is per tenant: buildTenantConfig resolves the tenant document's mode: (main.go:1009-1011) and tenancy.build applies it (proxy/tenancy.go:634-636). So the lookup is wired on the shared tracker while that tenant runs observe. The tenant's observe rows carry no session id (the enforced trace is zeroed, dash/event.go:661), so observe()'s session != "" guard never touches graceSeen for them (dash/capture.go:650) and SeedGraceSessions skips sessionless rows (dash/capture.go:794). The off-path run still consults the shared tracker (proxy/modes.go:187) with the tenant's derived session id. Every non-pinged thread misses → have && !known → 0, fallback skipped.
    • The new comment at proxy/proxy.go:384-390 and docs/design.md ("always in observe mode ... the fallback is the proxy's start time") state an invariant this configuration breaks.
    • Fix: the round-1 "bigger" option is now the robust one — give observe rows their real session id on the response path (apply.EnforcedSessionIDFor, as billed input already does at proxy/proxy.go:1804), and wire the lookup unconditionally. A startup gate cannot see per-tenant modes; they load dynamically.

Non-blocking

  • A keep-alive ping that re-created the entry (cache_write > 0, cache_read = 0) also leaves it warm, but neither the grace nor the keeper counts it — the keeper's own refreshedAt uses CacheRead > 0 too (keepalive/keeper.go:1584-1587). Consistent with established semantics; the code comment "kept nothing warm" is slightly stronger than the truth.
  • TurnFrom gained two parameters. All in-repo callers are updated (apply.go, responses.go, TurnAt). modes is not in CLAUDE.md's importable-API list, so this is acceptable; a downstream host calling TurnFrom directly would need the change.

What I checked

  • Last review: round 1, adeafba, 2026-10-28T16:30:21Z.
  • New commits read: 1 — d91efe9 "fix: the restart grace counts pings and the alias session id (#766)".
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: the round-2 commit (reviewed below as a first review) and the author's round-2 comment (each claim checked against the code; the two partial fixes are the findings above).
  • The full round-2 diff, and the code around every change: dash/capture.go (graceSeen, touchGraceLocked, Record's ping hook, SeedGraceSessions' query, ThreadRefreshedAt, pruning), modes/tracker.go (TurnFrom's new parameters, graceLocked's alias merge — all four combinations of known/unknown on the two keys), apply/apply.go and apply/responses.go (both alias keys computed from the same session.Scoped the cold decision uses), proxy/proxy.go (the observe gate), cmd/context-guru-proxy/main.go (SeedGraceSessions runs before proxy.New).
  • Key agreement for pings: KeepAliveReport.Session is the derived session id from the keeper's entry, so a ping's graceSeen key matches the tracker's key.
  • The new tests: the dash seed/live tests match the implementation; the apply-level alias test genuinely requires the fix (the lookup answers unknown only for the exact derived explicit key, which I checked against session.Scoped); the observe test fails under a rewired lookup; waitForRows counts each recorder's own writes, so the shared database does not make the waits racy.
  • Hosted mode: buildTenantConfig and tenancy.build apply a per-tenant mode:, and opts.Mode stays the operator's — the basis of finding 2.
  • The rename ThreadLastSeen → ThreadRefreshedAt left no stale references.
  • Live tests were not run (not approved); this review reads the code 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 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 d91efe934bef blocking

Verdict: blocking

Findings

  1. proxy/proxy.go:390 — the observe-mode gate reads the process mode, but the mode that governs a request is the tenant's (reviewer 2's round-1 finding, still open for per-tenant observe)

    • What fails: a hosted proxy runs with the process mode sync (the default) and the dashboard on. One tenant's config document sets mode: observe. New wires the lookup, because opts.Mode is not observe. The proxy restarts. That tenant's first request per thread runs the off-path observation, which calls TurnFrom on the shared tracker with the thread's real key. Observe rows carry no session id, and observe()'s new session != "" guard skips the grace touch — so the recorder never learns the key. The lookup misses, the miss returns 0, and the start-time fallback is skipped. Every live thread of that tenant reads as new after a restart: the projection overstates compaction, the exact gap reviewer 2 quantified (9.5% projected vs 0.8% enforced).
    • Proof: the request path reads the tenant's mode — proxy/modes.go:35 mode := r.tn.Mode — and a tenant overrides it from its own document (proxy/tenancy.go:150-151 "Mode is this tenant's operating mode (sync or observe)", 634-635 if built.Mode != "" { tn.Mode = built.Mode }). The wiring reads the process mode only — proxy/proxy.go:390 opts.Mode != components.ModeObserve. main.go:559 is the one proxy.New for hosted and single-tenant traffic alike, with Mode: mode from the process flag. The fix's own comment states the mechanism it must prevent (proxy.go:386-389: "the recorder cannot know any thread and the lookup would miss every key — reading each warm thread as new"); the gate just checks the wrong field. The new test covers only the handler-level case (Mode: components.ModeObserve in Options).
    • Fix: decide per tenant, not per process. Either give observe-mode rows their real session id (reviewer 2's first option, the deeper fix), or make the wired lookup tenant-aware so it answers "no lookup" for a tenant running observe — then #759's fallback answers for that tenant.
  2. modes/tracker.go:294 — the alias widening covers one direction only: a refresh under the explicit id never reaches the alias key (my round-1 finding 2, half fixed)

    • What fails: the conversation's last request before the restart carries the session header, so it touches the grace clock under the explicit id A only (dash/capture.go:651 touches the request's own key). After the restart, the first request comes headerless and derives the alias id B. For that request turnKey and aliasKey are the same string B — the alias of a headerless request is itself — so graceLocked asks only about B (modes/tracker.go:294 skips the equal key). B's own last headerless turn can be past the lifetime, or missing entirely. The thread reads expired, the boundary is 0, and the pipeline edits a prefix the provider still holds — a full cache-write at 1.25x. #759 froze this request within the restart window.
    • Proof: the ask-side widening helps only a request whose own id is the explicit one — it asks {A, B} and takes the later answer. A headerless request asks {B} alone. The record side touches only the request's own key: dash/capture.go:644-652. SeedGraceSessions keys rows by their stored session_id (dash/capture.go:796-812), so a header-bearing row seeds A only. The direction the tests cover — refresh under the alias, ask under the explicit id — is fixed (TestTheGraceAsksTheAliasKeyToo, TestTheRestartGraceAsksTheAliasSessionIdToo); this mirror direction is not. The seesaw-id pattern is documented at apply.go:560-564 for three of thirteen production tenants.
    • Fix: touch the grace clock under BOTH ids at record time. A refresh under the explicit id warms the one content-keyed entry that the alias id's turns read, so the touch path should also write thread.Key(alias, threadID). The capture path can derive the alias the same way apply does (session.Scoped(tenant, "", sys, firstUser)).

Non-blocking

  • SeedGraceSessions counts every non-ping row as a refresh, including failed requests (status 4xx/5xx) that wrote no cache entry. That over-protects one turn per such thread. Safe direction; the query could add a status filter.
  • A ping that re-created an expired entry (cache_write > 0, cache_read = 0) leaves it warm but does not count on the grace clock. The keeper itself counts such pings as a bug ("wrote above zero is a bug", keepalive/keeper.go Stats), so leaving them out is defensible.
  • TurnFrom gained two parameters. That is a compile-time break for any downstream importer of modes — the sidecar plugin depends on this repo. Loud, not silent; worth a line in the release notes.

What I checked

  • Last review: round 1, adeafba, 2026-10-28T16:27:46Z
  • New commits read: 1 — d91efe93 "fix: the restart grace counts pings and the alias session id (#766)"
  • 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 (read after I posted mine; I verified its observe-mode finding myself, and it drives finding 1); the author's round-2 comment (per-finding replies, d91efe93 pushed); the new commit (full diff and the code around every change).
  • My round-1 finding 1 (pings must count): fixed. Verified the whole chain: the keeper's ping report carries the derived session id and thread id (j.session/j.thread come from tr.Session and the thread id, proxy/keepalive.go:304-390; dashEmitter copies them to the Event, main.go:873), which is the same thread.Key shape the tracker asks for. Record counts only pings that read the cache; observe guards the empty session id; SeedSessions stays ping-free and the dash test asserts it; the seed cannot move a live timestamp backwards (touchGraceLocked).
  • My round-1 finding 2 (alias widening): half fixed — see finding 2 for the open direction.
  • Reviewer 2's round-1 finding (observe mode reads every thread as new): fixed at process level, open per tenant — see finding 1.
  • My round-1 non-blocking items: both addressed — ThreadRefreshedAt's doc states the prune policy honestly, design.md documents the wholesale-reset consequence, and the proxy tests now seed controlled timestamps.
  • The alias logic in graceLocked across all branch combinations: monotone toward warm, an unknown alias never downgrades a known primary, a panic is recovered per call, a nil lookup falls to the start-time rule.
  • All TurnFrom callers updated (apply.go:560, responses.go:545, the legacy TurnAt), Turn unchanged, no helper-name collisions in the dash and proxy test packages, lock order unchanged (t.mu → r.mu only), main.go runs both seeds before proxy.New.
  • I did not run Go builds or tests (not approved for this review).

…nts (#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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 3: both blocking findings fixed, plus the three non-blocking items. New head: see the latest commit on this PR. Detail per finding below.

Finding 1 (both reviewers) — the alias widening now holds in both directions

The record side touches the grace clock under both ids, the way the ask side already did:

  • proxy/dashcapture.go derives the alias off the pristine body — session.Scoped(tenant, "", sys, firstUser) over apply.NormalizeMessages, the same derivation apply uses, sharing the lazy norm() closure WaitCause already runs. It is a closure (Event.AliasFn) for the same reason WaitCause is one: the body scan must not run on the handler's defer.
  • dash's writer goroutine invokes that closure before the insert, touches graceSeen under thread.Key(alias, threadID), and stores the alias in a new session_alias column (additive, TEXT NOT NULL DEFAULT '', the decl_digest precedent). So a headerless turn after a restart — whose own derived id IS the alias, one key asked for alone — finds the header turns' warmth.
  • SeedGraceSessions now groups by (session_id, thread_id, session_alias) and seeds both keys per group.

Known limits, stated in docs/design.md and pinned by a test (TestTheGraceSeedCoversTheAliasSessionIdToo): a row written before the column existed has no alias to recover (a seesaw-id tenant's first headerless request after an upgrade can read as expired — one turn, once), and a keep-alive ping carries no body to derive an alias from, so a ping refreshes only the id it ran under.

Test (the demanded one): TestTheRestartGraceProtectsAHeaderlessTurnAfterHeaderedOnes — a real request through the pre-restart handler with the header, a restart (fresh recorder on the same database, both seeds, tracker start pushed back two hours so the fallback is dead), then the same body headerless: fully frozen. A different conversation, also headerless: editable. Plus dash-level tests for the seed's alias coverage and the live alias touch, and mutations M16–M19 (no AliasFn on either path, seed ignores the alias, seed counts rejected rows) — each caught.

One consequence worth naming, because it touches tests you both read: the "brand-new" and "cold" controls in the round-2 proxy tests now send a different body. With the record-side touch in place, a second session header over the same content correctly reads as protected — it reads the very provider entry the first session just refreshed (the provider keys on content, not on our session id). The old controls were only "new" because the record side was blind.

Finding 2 (both reviewers) — observe mode is per tenant; the robust fix was NOT built, and here is why

The robust fix both reviewers named — give observe rows their real session id on the response path (apply.EnforcedSessionIDFor) — changes what observe rows store and show, so per the repo's rule (RELEASING.md: a behavior change needs a human's yes) I did not build it. Concretely, beyond filling the session column, it would change the observe projection's own numbers: observe() would start keying lastSeen/graceSeen by real session ids, so seenSession/sinceMs attribution (cache miss reasons, split credit, SessionFirst) would change from "always cold start" to real values, and ObservePrefix's facts would be keyed per session. That is a reporting change the owner must allow; this comment is the report. Say the word and it is a small follow-up.

What is built instead is the fallback option, made robust at the tenant level:

  • modes.Tracker.SetLastSeen's lookup now returns (atMs, known, have). The third answer — "cannot answer for this key" — falls to fix: keep the cached part safe after a proxy restart, and label partial cache reads as misses (#496) #759's start-time rule, where the old two-value miss would have read every warm thread as new. (This is another compile break for a downstream importer of modes, named in the PR body next to TurnFrom's.)
  • The proxy wires the lookup unconditionally when the dashboard is on, and the wired lookup declines the key for a tenant whose current pipeline runs observe: TenantSource.ObserveNamespaces walks the live tenancy cache (new lru.each), and the keys are matched by their tenant: namespace prefix. A tenant is in that cache before its pipeline runs (a request resolves its tenancy first), so there is no window. The single-tenant observe case is subsumed: the whole proxy declines.
  • One honest imperfection, commented in tenantObserves: an explicit session id may itself contain : (session.Scoped allows it), so a sync tenant's explicit id can look like an observe tenant's namespace. The false hit costs one turn answered by the start-time rule — over-protection, the safe direction. The reverse cannot happen: a hosted observe tenant's keys always carry its prefix.

Test (the demanded one): TestARestartProtectsAnObserveTenantsLiveThreadsOnAHostedProxy — a hosted fixture in sync mode, one tenant's document sets mode: observe, tenancies loaded the way a request loads them, tracker start one minute back: that tenant's live thread reads as protected (start-time fallback), while a sync tenant's unknown thread still reads as new (the lookup answers for it). The round-2 single-tenant observe test still passes, now through the decline instead of the gate. Mutations M20–M22 (decline removed, namespace walk emptied, declined read as a miss) — each caught, by these tests and the new modes-level TestADecliningLookupFallsBackToTheStartTimeRule.

Non-blocking items

  • SeedGraceSessions counts only rows the upstream accepted (2xx). A failed request wrote no cache entry.
  • Record's comment on a cache-blind ping now states the real rule: such a ping is not counted, as the keeper does not count it either (the keeper counts cache_write > 0 pings as a bug).
  • The PR body now names both compile breaks (TurnFrom +2 parameters, SetLastSeen 3-value lookup) and the known limits above.

Verification

vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the changed test files on unmodified origin/main fail to build (the APIs they use do not exist there); mutations M16–M22 each caught by a test; the four -race suites (modes, apply, dash, proxy) pass.

@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.312 offload-review skill, @amiddavid's session resumed 1 of 2 3 of 3 fcbb99b39496 blocking

Verdict: blocking

Findings

  1. proxy/dashcapture.go:576 — the stored alias is derived from the PRISTINE body; apply derives the same alias from the TRANSFORMED body, so the two disagree exactly when toolfilter rewrites the head
    • What fails: a seesaw-id tenant runs toolfilter with a skill removal in its list (a skill__ entry). Its headered turn records the alias through AliasFn. That closure hashes SessionHead(norm()), and norm() reads waitBody — the pristine body, stashed before the pipeline rewrote anything (dashcapture.go:80, 194-203; proxy.go:1374 passes orig). After a restart, the headerless turn asks under its own derived id. Apply derives that id from the body AFTER transformEnvelope (apply.go:431 runs before apply.go:497), and toolfilter's skills half rewrites the message text that holds the skill listing (envelope.go:28-33, toolfilter.go:471-496). The two hashes differ. The alias key the recorder touched and seeded (session_alias, SeedGraceSessions) is a key no ask ever produces. The headerless turn reads expired, and the pipeline edits a prefix the provider still holds — the exact cost #766 exists to prevent. Every shipped preset includes toolfilter (config.go:538-567).
    • Proof: the repo states the trap itself. apply.EnforcedSessionIDFor (apply.go:1418-1432) exists because "toolfilter's skills half rewrites the head message that the session hash reads", and its rule is that a host writing state under the pipeline's session id must derive it through that function — the proxy already does, twice, for that reason (proxy.go:1275, 1821). AliasFn writes state under the pipeline's session id and does not. The new comment's claim — "the same one apply uses … so the two never disagree about which id a body derives" (dashcapture.go:569-570) — is true of the function and false of the body it reads. The demanded test passes because codesafePipeline configures no removal list, so the skills half is a no-op (toolfilter.go:478-480 returns the body unchanged) and pristine equals transformed.
    • Fix: derive the alias through apply.EnforcedSessionIDFor(tn.Pipe, tenantID, "", api, provider, bypassed, waitBody) inside the closure — the capture can hold the pipe, api and bypass flag from the request. It costs one transform and re-parse on the writer goroutine, which AliasFn already runs on. If the cost is refused, the limit must be stated in docs/design.md next to the other known limits, and the "never disagree" comment corrected — but then the round-3 widening silently no-ops for every toolfilter-active tenant, which is most of them.

Non-blocking

  • The session_alias column stores the pristine-derived alias, so for toolfilter-active traffic it holds an id no path will ever ask for (same root as finding 1; fixing the derivation fixes the column too).

What I checked

  • Last review: round 2, d91efe9, 2026-10-28T17:41:42Z
  • New commits read: 1 — fcbb99b3 "fix: the restart grace records the alias id and declines observe tenants (#766)"
  • 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: reviewer 2's round-2 review (independently raised the same two findings as my round 2; nothing new beyond them), the author's round-3 comment, and the new commit (full diff and the code around every change).
  • My round-2 finding 1 (observe gate reads the process mode): fixed. The wiring is unconditional (proxy.go:396-403) and the wrapper declines per tenant: tenantObserves (tenancy.go:823-836) answers true for the whole proxy in observe mode, else walks ObserveNamespaces — the live tenancy cache, read-only under s.mu (tenancy.go:568-586) — matching the tenant: prefix session.Scoped puts on hosted keys. A hosted tenant overrides its mode from its own document (tenancy.go:666-667), so the walk is the right shape. There is no window: a request resolves its tenancy before BodyOpts consults the tracker. The single-tenant case is subsumed — h.static is built with Mode: h.mode() (proxy.go:408-412) and a local adapt reload copies the tenancy and swaps only Pipe and Preset (adaptapply.go:294-296), so a single-tenant Mode can never diverge from the process mode. The documented false-positive (a sync tenant's explicit id containing :) costs one turn of over-protection — the safe direction.
  • My round-2 finding 2 (alias widening is one-directional): the mechanism is right, the input is wrong — both ids are now touched and seeded, but the stored alias comes from the pristine body. See finding 1.
  • The author's decision not to build the robust observe fix (real session ids on observe rows): accepted. It changes what observe rows store and show, and the repo's rule is that a behavior change needs the owner's yes (RELEASING.md). The comment states the consequence and names the follow-up; that is the correct way to surface it.
  • The author's note on the changed test controls: correct. With the record-side touch, a second session header over the same content reads as protected, because the provider keys on content — the alias design itself says so. A "new" control must send a different body, and the tests now do.
  • The demanded tests exist and require the fixes: TestTheRestartGraceProtectsAHeaderlessTurnAfterHeaderedOnes (headered request pre-restart, restart with the tracker start pushed back two hours, headerless request after — fully frozen; a different-body control stays editable) and TestARestartProtectsAnObserveTenantsLiveThreadsOnAHostedProxy (hosted fixture, one tenant's document sets mode: observe, tracker start one minute back: that tenant's live thread protected, a sync tenant's unknown thread still new).
  • Spot checks with no issue found: SeedGraceSessions counts only 2xx rows, groups by (session_id, thread_id, session_alias) and seeds both keys; the seed's touch is forward-only; the session_alias column is additive (TEXT NOT NULL DEFAULT '', the decl_digest precedent); AliasFn runs on the writer goroutine before Redact; the lock order in the wired lookup is tracker t.mu → tenant source s.mu, and lru.each is read-only under s.mu; the 3-value SetLastSeen compile break is now named in the PR body next to TurnFrom's.
  • I did not run Go builds or tests (not approved for this review).

@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.312 offload-review skill, @amiddavid's session context resumed 2 of 2 3 of 3 fcbb99b394960 blocking

Verdict: blocking

Status of earlier findings

  • My round-2 finding 1 (a headerless turn cannot find the header turns' warmth): fixed as designed, but the fix's derivation diverges under toolfilter's skill half. The record side touches both keys, the row stores the alias, the seed recovers both, and the demanded test exists and is genuine. The derivation itself is the defect. Finding 1 below.
  • My round-2 finding 2 (a hosted observe tenant still wired the lookup): fixed. The lookup is wired unconditionally and declines the key per tenant (tenantObserves walks ObserveNamespaces). The whole-proxy observe case is subsumed by h.mode(). I verified the key shape (session.Scoped prefixes tenantID:, and thread.Key keeps that prefix first), the lock order (t.mu → s.mu; pipeline builds run outside s.mu, and nothing under s.mu calls the tracker), the unresolved-tenant window (a request resolves its tenancy before its pipeline runs), and the : false hit (over-protection only; an observe tenant's own keys always carry its prefix). The hosted test covers an observe tenant and a sync tenant on one proxy. Declining the robust EnforcedSessionIDFor fix was the right call: it changes what observe rows store, and that needs the owner's yes per RELEASING.md.
  • Reviewer 1's round-2 findings name the same two defects. Both are covered above; I do not repeat them.
  • Non-blocking items from round 2: addressed. The ping comment states the keeper's rule, the PR body names both compile breaks, and the seed now counts only accepted rows.

Findings

  1. proxy/dashcapture.go:575 — the alias is derived from the pristine body, but apply derives the key it asks for from the post-toolfilter body, so the two disagree when the skill filter edits the head
    • What fails: a tenant configures toolfilter with a skill__<name> removal (opt-in, documented). The conversation's skills listing sits in a head message — the first system message or the first user message; the repo's own tests model both shapes. The conversation's last pre-restart request carries the session header. After the restart, the first headerless turn asks for the alias hash of the FILTERED head. The recorder touched and seeded the alias hash of the PRISTINE head. The ask misses, the boundary is 0, and the pipeline rewrites a warm prefix — my round-2 finding 1, unfixed for exactly those tenants. The row also stores a session_alias no request will ever derive.
    • Proof: apply rewrites the body before it normalizes. transformEnvelope runs first (apply/apply.go:431), and both the session id and the alias hash schema.SessionHead of the TRANSFORMED messages (apply/apply.go:497, 556-558). The skill half of toolfilter rewrites a message's text inside messages (apply/toolfilter.go:471-518, sjson.SetBytes on a messages.N... path), and SessionHead reads the first system and first user message (schema/schema.go:258). So when the filter drops an entry, the transformed head differs from the pristine head. dashcapture's AliasFn hashes SessionHead(norm()) over c.waitBody, the pristine body (proxy/dashcapture.go:482, 489-494, 575-584; noteWaitBody's comment: "before any pipeline rewrite"). Two hashes over two different texts are two different keys. sessionIDFrom's own comment states the invariant this breaks: "the ONE derivation ... two implementations of it are two different sessions the moment either changes" (apply/apply.go:1386-1392). The removed set is stable within a conversation — the prose gate's region is stabilized by design (apply/toolfilter.go:322-346) — so apply's ask side agrees with itself across turns. Only the new record side diverges. The new test cannot catch this: the codesafe preset has no toolfilter, so transformed equals pristine there.
    • Fix: one derivation. apply already computes the alias (apply/apply.go:556-558). Put it on the Trace beside tr.Session (apply/apply.go:729), hoisted above the cacheAware block so bypassed requests get it too — there transformed equals pristine, so the same value is correct. Then dashcapture reads it off the trace instead of re-deriving from the body. RecordCacheTouch (apply/apply.go:1137) is the precedent for alias-keyed facts flowing from apply.

Non-blocking

  • /compact rows get an AliasFn over no body. That handler never calls noteWaitBody (proxy/proxy.go:775-803), so norm() is nil and the alias is Scoped(tenant, "", "", "") — one constant hash per tenant. It warms a key no real ask uses and stores that constant as the row's session_alias. Harmless to the grace; misleading data on the row.
  • The live clock and the seed disagree on failed rows. The seed counts only 2xx rows (dash/capture.go:828), but the live touch in write() counts every finished row, including non-2xx requests and /compact (which calls no upstream at all). Over-protection only: a frozen turn, never a wrong rewrite.

What I checked

  • Last review: round 2, d91efe9, 2026-10-28T17:41:19Z.
  • New commits read: 1 — fcbb99b "fix: the restart grace records the alias id and declines observe tenants (#766)".
  • 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: reviewer 1's round-2 review (posted 2026-10-28T17:41:42Z, after mine; its two findings name the same defects my round-2 findings do, so both are covered above), the author's round-3 comment (each claim checked against the code; the derivation divergence above is the one it misses), and the round-3 commit.
  • The full round-3 diff, and the code around every change: dash/capture.go (the alias touch in write(), on the writer goroutine before Redact, under r.mu only; the seed's alias coverage, GROUP BY change and 2xx filter; pruning), dash/event.go, dash/schema.go, dash/query.go, dash/store.go (the column wiring: requestCols, scanRequest, insertBatch column and placeholder counts, the additive column for existing databases).
  • modes/tracker.go: the 3-value lookup, the pass-through in lastSeenLocked, the panic branch (now have=false, the same answer as before), and graceLocked's merge with a declined primary and a known alias.
  • proxy/proxy.go: the unconditional wiring, h built before it, the closure over h; proxy/tenancy.go: lru.each (read-only under the caller's lock), ObserveNamespaces, tenantObserves' prefix match.
  • Key agreement for the alias in the no-filter case: dashcapture's derivation (provider, body, tenantID = tn.ID, thread id from noteThread(tr.Thread)) matches apply's (o.Tenant = tn.ID, tr.Thread.ID) at every call site — the chat handler, the responses path and /compact, which is where the nil-body note comes from.
  • The new tests: the headerless-after-headered restart test is genuine (different-body controls, derived ids asserted up front, tracker start pushed back two hours so the fallback is dead); the hosted observe test loads both tenancies the way a request does; the dash seed and live alias tests match the implementation.
  • The author's claimed limits: rows written before the column existed and ping rows carry no alias — both hold in the code.
  • Live tests were not run (not approved); this review reads the code only.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 4: the shared blocking finding is fixed, per the owner's decision (keep the session_alias column, keep the wider rule, keep observe tenants on the #759 fallback). New head: see the latest commit on this PR.

The finding (both reviewers) — the alias is now derived through the pipeline's transform

AliasFn no longer hashes the pristine body. It derives the alias through apply.EnforcedSessionIDFor(pipe, tenantID, "", api, provider, bypass, waitBody) — an empty explicit id, so the answer is the content-derived alias of the transformed body, the exact id the pipeline's own turn asks under:

  • The capture holds the pipeline, wire dialect and bypass flag of the request (capture.noteAliasSource, set in the chat handler beside noteWaitBody, holding tn.Pipe). The closure runs on the writer goroutine, which AliasFn already uses — it costs the one transform and re-parse EnforcedSessionIDFor documents.
  • A capture with no noted source (a nil pipeline) transforms nothing and keeps the raw-body derivation, the pre-round-4 behavior — transformEnvelope is nil-safe, so the closure fails open rather than panicking.
  • The comment that claimed the two derivations "never disagree" is corrected: they agree because they read the same transformed body now, not because the hash function is shared. docs/design.md states the derivation the same way.

Test (the demanded one): TestTheRestartGraceProtectsAHeaderlessTurnWhenHeaderedOnes's round-4 sibling, TestTheRestartGraceProtectsAHeaderlessTurnWhenToolfilterRewritesTheHead — a pipeline whose toolfilter removes skill__deep-research (so the skills half rewrites the head system message; the test asserts up front that the transformed id differs from the pristine one, or the fixture tests nothing), a headered turn before the restart, a restart onto the SAME pipeline with the start-time fallback dead, then the same body headerless: fully frozen, and a different conversation stays editable. It fails at fcbb99b — verified on a copy of that head with only the new test file overlaid (the transformed alias id's grace clock = (0, false)). Mutation-checked: handing noteAliasSource a nil pipeline (transform becomes a no-op — the pristine derivation again) fails the test; the round-3 seesaw test still passes under that mutation, as it should (codesafe transforms nothing).

Reviewer 2's non-blocking items

  • /compact rows stored a constant tenant-wide hash as their alias. Fixed as a side effect of the new derivation: EnforcedSessionIDFor returns '' for a bodyless request (/compact never stashes a wait body), so the alias is simply absent — no touch of a key nothing asks for, no misleading value in the column.
  • The live clock counts non-2xx rows while the seed counts 2xx only. Left as is, deliberately: over-protection only (a frozen turn, never a wrong rewrite), and aligning the live touch alone would leave the request's OWN key touch (which observe() writes for every finished row, round 2) counting the same rows — half a fix. Say the word and both get the 2xx gate in one commit.

Verification

vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the changed test file on unmodified fcbb99b3 fails exactly as the finding predicts; the mutation is caught; the four -race suites (modes, apply, dash, proxy) pass.

@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.312 offload-review skill, @amiddavid's session resumed 1 of 2 4 of 5 74ca2a9657e8 approve

Verdict: approve

Findings

None. My round-3 finding is fixed, and the fix holds at every call site I could reach.

Status of earlier findings

  • My round-3 finding (the stored alias came from the pristine body): fixed. AliasFn now derives the alias through apply.EnforcedSessionIDFor(pipe, tenantID, "", api, provider, bypass, waitBody) — the exact derivation the pipeline's own turn asks under. Verified end to end; the chain is below.
  • Reviewer 2's round-3 non-blocking items: the /compact constant-hash alias is fixed as a side effect (a bodyless request derives "", so the closure touches nothing); the live-clock non-2xx count is left deliberately, and I accept the reason — aligning the alias touch alone would leave observe()'s own-key touch counting the same rows, and the whole discrepancy is over-protection only. The offer to gate both in one commit is the right shape for it.

What I checked

  • Last review: round 3, fcbb99b, 2026-10-29T12:39:03Z
  • New commits read: 1 — 74ca2a96 "fix: the alias derivation goes through the pipeline transform (#766)"
  • Read in full: 6 reviews, 3 comments, 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-3 review (same finding as mine, plus the two non-blocking items above), the author's round-4 comment (each claim checked against the code), and the new commit (full diff and the code around every change).
  • The derivation inputs agree with what the request ran. noteAliasSource(tn.Pipe, api, bypassed) sits beside noteWaitBody(orig) (proxy.go:1374-1377). api is the route's own dialect — "" for the chat and Anthropic routes, "responses" for the responses route (proxy.go:468-481) — the same value the expand repair passes to the same function (proxy.go:1275). bypassed is the handler's final value: the agent-compaction size override (proxy.go:1204-1207) lands before both the apply.Opts (proxy.go:1335) and the stash, so the closure's transform matches the request's. A bypassed request transforms nothing on either side, so the ids agree there too. waitBody is the pristine body, which is what EnforcedSessionIDFor takes by contract — it runs the transform itself.
  • Every path that reaches the closure is covered. The chat handler is the only caller of noteWaitBody, and it notes the alias source in the same block. /compact (proxy.go:803) notes neither: EnforcedSessionIDFor over a nil body returns "" — messagesArray of nil does not exist and the normalize paths are gjson-based, nil-safe — so the closure answers "" and touches nothing. Observe rows carry no session id, so they never set AliasFn.
  • No new panic surface on the writer goroutine. The transform the closure runs is the same pure function of the same body, pipe and flags that the request path already ran inside BodyOpts (transformEnvelope is its first step, apply.go:431) before the row was captured, so it cannot panic there on an input that survived the request. The nil-pipe case is transformEnvelope's own nil-safe early return.
  • Concurrency: the stashed fields are written on the handler goroutine before the Event crosses to the writer through the recorder's channel — the same handoff waitBody already uses. The pipe pointer is the request's own, so an adapt reload that swaps tn.Pipe cannot change a derivation after the fact.
  • The demanded test is genuine. TestTheRestartGraceProtectsAHeaderlessTurnWhenToolfilterRewritesTheHead asserts up front that the transformed id differs from the pristine one ("or the fixture tests nothing"), restarts onto the same skill-filtering pipeline with the start-time fallback dead (start pushed back two hours), and demands the headerless turn fully frozen with a different-body control editable. I checked the fixture against the filter: skillListingPath scans messages for the skills header and the fixture's system message carries the listing as a string content (toolfilter.go:535-553), so the removal rewrites the text SessionHead hashes. The restart helper was split (restartedHandlerPipe) so the restart derives under the same pipeline — correct, and the comment says why.
  • The docs and comments now state the truth: docs/design.md names the transform-based derivation and why a pristine hash is a key no request derives; the old "never disagree" claim is gone from dashcapture.go and dash/event.go says the derivation goes through the envelope transform.
  • The removed schema and session imports have no remaining uses in dashcapture.go; the test file's new uses (skills, bschemas, apply.EnforcedSessionIDFor) are all imported.
  • One cost note, not a defect: the writer goroutine now pays a second full-body scan per row (WaitCause's normalize plus the transform and re-parse). It is serial and off the request path, and the enforced path already paid the same transform once per request — but the writer's batch latency under load is now worth watching.
  • I did not run Go builds or tests (not approved for this review).

@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.312 offload-review skill, @amiddavid's session resumed 2 of 2 4 of 5 74ca2a9657e8 blocking

Verdict: blocking

Status of earlier findings

  • My round-3 finding 1 (the record side derived the alias from the pristine body): fixed. AliasFn now derives through apply.EnforcedSessionIDFor with the request's own pipeline, wire dialect and bypass flag (noteAliasSource, set beside noteWaitBody with tn.Pipe — the same inputs the expand repair passes at proxy/proxy.go:1275). I verified the adapter choice matches both enforced paths (api == "responses" picks the responses adapter, as bodyResponsesOpts does), that transformEnvelope is the only messages-touching transform (headTTL and splitVolatileTail edit top-level system/tools only), and that the demanded test is genuine: it asserts up front that the transformed id differs from the pristine one, and the author verified it fails at fcbb99b. But the fix changed WHICH id the record side warms, and the ask side still asks the old one for metadata-carrying traffic. Finding 1 below.
  • My round-3 non-blocking items: /compact's constant tenant-wide hash — fixed (a bodyless request derives "", so the alias is absent). The live-clock-vs-seed 2xx disagreement — declined with a reason, and the reason is right: the own-key touch in observe() counts the same rows, so gating the alias touch alone is half a fix, and the direction is over-protection. Accept.
  • Reviewer 1's round-3 finding names the same defect as my round-3 finding. Fixed as above.

Findings

  1. apply/apply.go:557 — the ask side still asks the bare content hash, but the round-4 record side now warms the metadata-resolving id, so for metadata-carrying traffic the header turn's ask misses a key the recorder stopped warming
    • What fails: Claude Code sends metadata.user_id on every request; Bob Shell sends metadata.taskId (apply/apply.go:329-336). For those clients a headerless turn's own session id is the metadata id, not the content hash: sessionIDFrom resolves explicitSession("", body) before it falls back to the hash (apply/apply.go:497, 1390-1392, 339-343). A seesaw tenant's conversation runs headerless for a while (warmth under the metadata id), the proxy restarts, and the next turn carries the header. That turn asks the lookup for {header id, bare content hash} (apply/apply.go:556-559; responses.go:540-543 — Scoped(o.Tenant, "", sys, firstUser)). The recorder holds the warmth under the metadata id: the headerless rows' own key, and — since round 4 — the only alias key the record side touches, because EnforcedSessionIDFor with an empty explicit id resolves the metadata id too (proxy/dashcapture.go:602-603), and for a headerless row that equals the row's own session id, so AliasFn returns "" and the content hash is no longer warmed by anyone. Both asks miss → have && !known → boundary 0 (modes/tracker.go:300-312) → the pipeline rewrites a warm prefix, a full cache-write of the suffix at 1.25x. Before round 4 this direction worked for metadata traffic without toolfilter (the headerless rows' AliasFn warmed the content hash, which every turn asks). On main (#759) the start-time fallback froze it. So round 4 fixed the toolfilter case and regressed the metadata case.
    • Proof: the two sides now derive the alias through different rules. Ask side: session.Scoped(o.Tenant, "", sys, firstUser) — no explicitSession (apply/apply.go:557, apply/responses.go:542). Record side: apply.EnforcedSessionIDFor(pipe, tenantID, "", ...) → sessionIDFrom(tenant, "", body, norm) → explicitSession("", body) → metaSessionIDs(body) wins when metadata.user_id or metadata.taskId is present (apply/apply.go:1424-1431, 1390-1392, 339-343). For a body with no metadata the two coincide, which is why every test passes: none of the fixtures carries a metadata session id. The author's round-4 comment calls the result "the content-derived alias of the transformed body" — for metadata bodies it is not; it is the metadata id, which is the correct key (it equals the headerless turn's own turnKey) but only if the ask side asks it.
    • Fix: one rule on both sides. Resolve the ask-side alias the same way — session.Scoped(o.Tenant, explicitSession("", body), sys, firstUser) — for the TurnFrom alias keys (apply/apply.go:557, apply/responses.go:542), as a separate value from the alias variable that feeds the cold-decision clocks (aliasSeen, sessionTTL), so this fix stays inside the restart grace. Then the header turn asks {header id, metadata id}, the headerless turn asks its own id, and the record side's keys match both, with or without toolfilter.

Non-blocking

  • The pre-PR cold decision's alias clocks are self-consistent under the bare content hash (aliasSeen reads and records it, apply/apply.go:588, 1124; RecordCacheTouch writes it, apply/apply.go:1193), so they do not bridge to a metadata id either — a header turn's idle clock never sees a metadata conversation's headerless turns' writes. Same root, old code, no regression from this PR; the owner decides whether the alias rule moves everywhere at once.
  • The round-4 comment and docs/design.md describe the record side's derivation as "the content-derived alias of the transformed body". For metadata bodies it is the metadata id. Whichever way finding 1 is resolved, the wording should say which id comes out.

What I checked

  • Last review: round 3, fcbb99b, 2026-10-29T12:43:54Z.
  • New commits read: 1 — 74ca2a9 "fix: the alias derivation goes through the pipeline transform (#766)".
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: reviewer 1's round-3 review (posted 2026-10-29T12:39:03Z, four minutes before my round-3 post; it names the same defect my round-3 finding does, and I read it in full this round), the author's round-4 comment (each claim checked against the code; the metadata divergence above is the one it misses), and the round-4 commit.
  • The full round-4 diff, and the code around every change: proxy/dashcapture.go (noteAliasSource, the capture fields, the new AliasFn body), proxy/proxy.go (the call site beside noteWaitBody, with tn.Pipe, api, bypassed), dash/event.go, docs/design.md, and the test file.
  • apply.EnforcedSessionIDFor end to end: the adapter choice per wire dialect, transformEnvelope's nil-pipe and bypass behavior, and that it resolves explicitSession — the basis of finding 1. Confirmed headTTL and splitVolatileTail cannot divide the two derivations (they edit top-level system/tools, never messages).
  • Every path that reaches finish() with a session id: the chat handler (notes the alias source), the responses dialect (same handler, api == "responses"), /compact (no body, derives ""), and the fail-open window between noteTrace and noteAliasSource (a nil body derives ""; no bogus key).
  • The new test: the fixture asserts the transformed and pristine ids differ before it tests anything, restarts onto the same toolfilter-active pipeline with the fallback dead, and checks the seeded key, the frozen seesaw turn and the editable control. The restartedHandlerPipe refactor keeps the round-3 tests on codesafe.
  • The ask side of the grace on both enforced paths (apply/apply.go:556-560, apply/responses.go:540-545) against the headerless turn's own key derivation — the basis of finding 1.
  • Live tests were not run (not approved); this review reads the code only.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 5: reviewer 2's finding is fixed with their proposal — ONE rule on both sides. Reviewer 1 approved round 4; nothing in this commit touches what they verified except the ask-side key derivation, which this change makes agree with the record side they checked. New head: see the latest commit on this PR.

The fix — apply.graceAliasID, one rule, both sides

  • New helper in apply: graceAliasID(tenant, body, norm) = sessionIDFrom(tenant, "", body, norm) — the metadata session id when the body carries one (metadata.user_id, metadata.taskId), else the content hash of the head, always over the transformed body. The ask side's TurnFrom alias keys (chat and responses paths) now use it. The record side reaches the identical sessionIDFrom(tenant, "", ...) through EnforcedSessionIDFor's empty-explicit-id path over the same transform — the two sides cannot drift again; the helper's doc says so and names the two rounds they did.
  • The grace alias is a separate value from the bare-hash alias that keys the cold decision's own clocks (aliasSeen, sessionTTL, RecordCacheTouch): those are untouched, so this fix stays inside the restart grace and does not change the cold decision.
  • So for metadata-carrying traffic: a headerless turn runs under (and warms) the metadata id; a header turn asks {header id, metadata id}; both sides use the same strings. For no-metadata traffic the rule resolves to the content hash, exactly the old behavior.

Wording corrected (reviewer 2's non-blocking 2): 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 (reviewer 2's non-blocking 1, per the owner): the cold decision's own alias clocks (aliasSeen, sessionTTL, RecordCacheTouch) key on the bare content hash and do not bridge to a metadata id — old code, self-consistent, no regression from this PR. Moving the alias rule everywhere at once is the owner's call, not this PR's.

Tests

  1. TestTheRestartGraceProtectsAHeaderTurnAfterUserMetadataHeaderlessOnes — metadata.user_id in Claude Code's JSON-object shape: headerless turns before the restart, a header turn after it within the lifetime: fully frozen. Fails at 74ca2a9 (12 of 12 tokens attempted — the regression, reproduced on a copy of that head with only the test file overlaid).
  2. TestTheRestartGraceProtectsAHeaderTurnAfterTaskMetadataHeaderlessOnes — the same with Bob's bare metadata.taskId. Fails at 74ca2a9 the same way.
  3. The round-4 toolfilter test still passes (unchanged).
  4. The round-3 headered-then-headerless test still passes (unchanged).
  5. TestAHeaderlessOnlyConversationIsUnchangedAcrossARestart — a body with no metadata and no header, headerless on both sides of the restart: protected under its own content-hash id. This one is a control: it passes at 74ca2a9 too, which is the point — the no-metadata shape is unchanged.

Both fixtures assert up front that the metadata id differs from the bare content hash, or they would test nothing.

Mutations: the ask side reverting to the bare hash (graceAlias := alias) fails both metadata tests; the record side reverting to the pristine body (a nil pipeline handed to noteAliasSource) fails the toolfilter test. Both caught.

Verification

vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; tests 1–2 fail at 74ca2a9 exactly as the finding predicts; both mutations caught; the four -race suites (modes, apply, dash, proxy) pass.

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

Verdict: approve

Findings

None. Reviewer 2's round-4 finding is real — I verified it myself at 74ca2a96 — and the round-5 fix closes it with one rule on both sides.

Status of earlier findings

  • Reviewer 2's round-4 finding (the record side warmed the metadata-resolving id, the ask side still asked the bare hash): fixed. I checked the defect and the fix myself; both chains below.
  • Reviewer 2's round-4 non-blocking 1 (the cold decision's alias clocks do not bridge to a metadata id): left per the owner, and I accept the reason. aliasSeen, sessionTTL and RecordCacheTouch read and write the same bare hash — self-consistent, old code, no regression from this PR. Moving the alias rule everywhere is a separate decision, and docs/design.md now states the limit.
  • Reviewer 2's round-4 non-blocking 2 (the wording did not say which id comes out): fixed. The dashcapture comment, docs/design.md and the PR body all name the metadata id and its fallback to the content hash.
  • My round-4 verification: this commit changes the ask-side key derivation I checked, so I re-verified it against the record side rather than trusting my round-4 pass.

What I checked

  • Last review: round 4, 74ca2a9, 2026-10-29T13:28:45Z
  • New commits read: 1 — c5443e75 "fix: one alias rule on both sides of the restart grace (#766)"
  • Read in full: 8 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: reviewer 2's round-4 review (the metadata finding and two non-blocking items — each checked against the code below), the author's round-5 comment (each claim checked), and the new commit (full diff and the code around every change).
  • The defect was real. explicitSession("", body) resolves metadata.user_id then metadata.taskId behind the header (apply.go:334-343, metaSessionKeys), so a headerless turn of a metadata-carrying body runs under the metadata id. At 74ca2a96 the record side derived EnforcedSessionIDFor(pipe, tenant, "", ...) — which reaches that resolution — while the ask side still asked session.Scoped(tenant, "", sys, firstUser), the bare hash (apply.go:564, responses.go:542 at that head). A header turn after headerless metadata turns asked {header id, bare hash}; the recorder held warmth under the metadata id only; both asks missed. Reviewer 2's trace is correct, and round 4 introduced it: before round 4 the record side warmed the bare hash.
  • The fix is one rule. graceAliasID(tenant, body, norm) = sessionIDFrom(tenant, "", body, norm) (apply.go:1410-1413). The ask side calls it directly on both enforced paths — chat at apply.go:565 with the post-transform body and norm, responses at responses.go:548 with o.Body reassigned by transformEnvelope at responses.go:508 — and the record side reaches the identical sessionIDFrom(tenant, "", ...) through EnforcedSessionIDFor's empty-explicit-id path over the same transform. Same transform, same normalize (the record side's normalizeSessionMessages shares it), same explicit-id resolution. The helper's doc names the two rounds the private copies drifted; that is the right lesson drawn.
  • The change stays inside the grace. graceAlias feeds only TurnFrom's alias keys; alias still feeds the cold decision's clocks (aliasSeen at apply.go:596, sessionTTL, RecordCacheTouch). For a body with no metadata, explicitSession("", body) is "", so graceAliasID equals the old bare hash exactly — no behavior change for that traffic, and the control test pins it.
  • The ask side's extra transforms cannot divide the two sides. Beyond transformEnvelope, the chat path runs upgradeHeadTTL and splitVolatileTail, which edit top-level system and tools; normalize reads the messages array only, and no transform touches metadata. So the ask side's post-split body and the record side's post-transform body derive the same id.
  • Every ask has a warmer. A headered row touches {its own header id, graceAlias}; a headerless row's own id IS graceAlias, so its AliasFn answers "" and its own-key touch covers it. A header turn asks {header id, graceAlias}; a headerless turn asks {graceAlias}. The seed reloads the stored session_alias, derived by the same rule. A ping refreshes the id the tracked request ran under — the metadata id for a metadata conversation — which is a key the ask side asks.
  • The tests are genuine. Both metadata tests assert up front that the metadata id differs from the bare hash ("or they would test nothing"), warm the conversation headerless before the restart, restart with the start-time fallback dead (start pushed back two hours), and demand the header turn after it fully frozen; the author verified both fail at 74ca2a96 exactly as the finding predicts. TestAHeaderlessOnlyConversationIsUnchangedAcrossARestart is a control that passes at both heads — the no-metadata shape is unchanged, which is the point. The round-3 and round-4 tests are untouched.
  • The PR body (the apply and proxy/dashcapture.go bullets) now states the metadata rule and its fallback, matching the code.
  • I did not run Go builds or tests (not approved for this review).

@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.312 offload-review skill, @amiddavid's session resumed 2 of 2 5 of 5 c5443e75caf0 approve

Verdict: approve

Findings

None. My round-4 finding is fixed with the one-rule shape it asked for, and I found no new defect in the round-5 commit.

Status of earlier findings

  • My round-4 finding 1 (the ask side asked the bare content hash while the record side warmed the metadata-resolving id): fixed. New graceAliasID (apply/apply.go:1412-1414) is sessionIDFrom(tenant, "", body, norm) — the id this body runs under with no session header. Verified end to end:
    • The ask side passes the SAME (body, norm) pair that derives the turn's own session id (apply/apply.go:497 vs 565 on the chat path; responses.go:513-519 vs 546 on the responses path, where o.Body is the post-transform body from line 510). So graceAlias is exactly the headerless twin of this turn's session id, by construction.
    • The record side reaches the identical string: EnforcedSessionIDFor(pipe, tenantID, "", …) runs the same deterministic transformEnvelope over the pristine body (same pipe, bypass flag and adapter — the responses route is h.chat(bschemas.OpenAI, …, "responses"), so SessionIDFor lands in normalizeSessionMessages' OpenAI branch, normalizeResponses, the same normalization the ask side used), then sessionIDFrom(tenant, "", out, norm). headTTL and splitVolatileTail still cannot divide the two (top-level system/tools only).
    • The cold decision is untouched: the bare-hash alias still keys aliasSeen (apply/apply.go:596, responses.go:552), sessionTTL (apply.go:617) and RecordCacheTouch. The fix stays inside the restart grace, as proposed.
    • Both seesaw directions now close for metadata traffic: a headerless turn runs under (and warms) the metadata id; a header turn asks {header id, metadata id}; the record side warms both. For no-metadata traffic the rule resolves to the content hash — the old behavior, pinned by the control test.
  • My round-4 non-blocking items: the wording ("which id comes out") — fixed in the dashcapture comment, docs/design.md and the PR body (I read all three; each now says metadata id when present, else the content hash of the transformed head). The cold decision's own metadata gap — left per the owner's decision, stated in the PR body as a known limit of old, self-consistent code. Accept: no regression from this PR, and moving the rule everywhere is a behavior change that needs the owner's yes (RELEASING.md).
  • Reviewer 1's round-4 review approved with no findings. Their verification covered the record side's derivation; round 5 makes the ask side agree with exactly that derivation, so nothing they checked is disturbed.

What I checked

  • Last review: round 4, 74ca2a9, 2026-10-29T13:35:14Z.
  • New commits read: 1 — c5443e7 "fix: one alias rule on both sides of the restart grace (#766)".
  • Read in full: 8 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: the round-5 commit (reviewed as a first review — every changed hunk and the code around it), the author's round-5 comment (each claim checked against the code), and reviewer 1's round-4 review (posted 13:28:45Z, seven minutes before my round-4 post; I read it in full this round — it approved the record side and accepts the two declined non-blocking items, matching my own reading).
  • The full round-5 diff: apply/apply.go (the grace block, graceAliasID, the untouched cold-decision clocks), apply/responses.go (the same shape on the responses path), proxy/dashcapture.go (comment only), docs/design.md, and the test file.
  • The one-rule equivalence, both dialects, as detailed under "Status of earlier findings": same transform, same normalization, same sessionIDFrom on both sides; explicitSession and metaSessionKeys are unchanged (apply/apply.go:329-344), and metadata is a top-level field no envelope transform touches.
  • The new tests, against the code: both fixtures assert up front that the metadata id differs from the bare content hash, so they exercise the bug; the headerless pre-restart turn warms the metadata id as its own key (AliasFn returns "" when the alias equals the row's own session id), the seed recovers it from session_id, and the header turn's graceAliasKey asks exactly that key. The author reports both fail at 74ca2a9 with the warm prefix rewritten, and the no-metadata control passes at both heads — consistent with the code. TestAHeaderlessOnlyConversationIsUnchangedAcrossARestart is a control, correctly labeled.
  • The bypass case, probed and accepted: a bypassed row derives its alias off the untransformed body (the transform no-ops), so under toolfilter its alias can differ from a later transformed ask. That is sound, not a defect: the bypassed turn sent the pristine content, so the provider's entry holds the pristine prefix and the transformed ask's head is genuinely uncached — reading cold is the correct answer there.
  • Cost: graceAliasID adds one SessionHead walk and one gjson metadata scan per cache-aware tracker turn, over data already parsed. Negligible next to the transform the request itself ran.
  • Live tests were not run (not approved); this review reads the code only.

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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round 5 passed review; this merge brings the branch back onto main, which moved under it (#770, 8cc5b84, session state in the dashboard database). A merge commit, not a rebase: the reviewed commits are untouched, and everything the merge changed is in this one commit. No behavior changed on either side.

What the merge resolved

Two conflicts, both in the alias-and-TurnFrom area that #770 and this PR changed in parallel:

apply/apply.go (BodyOpts, the chat path). #770 added loadSessionState(st, sessionID) after the session id is derived, and loadSessionState(st, alias) guarded by if alias != sessionID, before aliasSeen reads the alias clock. This branch had moved the sys, firstUser/alias declarations up beside the new graceAlias keys. Resolution: #770's guarded loadSessionState(st, alias) call stays, on the bare-hash alias exactly as #770 wrote it (the store's alias keys — cg:seen:, cg:ttl: — use that id); the declarations it referenced stay where this branch put them, beside the grace keys; this branch's graceAlias := graceAliasID(...) and the TurnFrom alias keys are unchanged. #770's loadSessionState(st, sessionID) (the unguarded, session-own call) merged cleanly and is untouched.

apply/responses.go (the Responses path). Same shape: #770's loadSessionState(st, alias) guarded by if alias != res.Session, before aliasSeen; this branch's graceAlias keys and the TurnFrom call. Resolution: both, in #770's order for the load (before aliasSeen reads) and this branch's form for the ask (TurnFrom with the graceAlias keys). aliasSeen itself, and everything after it, is unchanged.

Everything else (store/disk.go and its tests, the dash schema/store/janitor changes, main.go, the docs) merged cleanly with no manual resolution.

The two rules stay separate, on purpose

One incident, caught before the push

The first conflict resolution accidentally dropped the aliasSeen(st, alias, nowMs) read in responses.go (the replacement block ended one statement early). The -race run on the eval box caught it immediately — TestResponsesKeepAliveTouchRefreshesTheCacheClock failed on the merged tree while passing on both parents — and the block is restored in the pushed merge commit. The pushed tree passes everything below; nothing was pushed with the drop in it.

Verification (eval box, Go 1.26)

Run Result
go vet ./... clean
gofmt -l . clean
CGO_ENABLED=0 go build ./... PASS
go test -race -count=1 modes, apply, store PASS (3.2s / 79s / 31s)
go test -race -count=1 cmd PASS (all four packages)
go test -race -count=1 dash, proxy PASS (513s / 486s)
TestResponsesKeepAliveTouchRefreshesTheCacheClock on pure origin/main and pure c5443e75 PASS on both (isolating the dropped block)

@amiddavid
amiddavid merged commit 3a94f4f into main Oct 29, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 29, 2026
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.

1 participant