Repository navigation
fix: keep the cached part safe after a proxy restart, and label partial cache reads as misses (#496) - #759
Conversation
Issue #496, Task A. Event.AttributeCache called every row with a cache read a hit. Claude Code keeps the system prompt and tools under a separate breakpoint, so a request that re-wrote the rest of the prompt still reads 35k-51k tokens. The TTL test and the cause check never ran on those rows: 101 rows since 10-15 read "hit" while they re-wrote most of the prompt. What changed: - PrefixFacts carries PromptTokens, the request's whole prompt (fresh input + cache read + cache write). A token count, so metadata only. - Recorder.ObservePrefix returns the previous same-model request's PromptTokens; the caller in proxy/dashcapture.go passes it on. - AttributeCache calls a row a hit only when the read is not a partial read: the previous prompt is known, the read is under half of it, and more was written than read. A partial read takes the existing chain (cold start, then ttl_expiry, then the measured cause). - Old rows keep their labels. Nothing is migrated. The keep-alive reports in dash/keepalive.go count only ttl_expiry, so the 83 rows that are really ttl_expiry now count there too. No code change was needed for that. Written by GLM (rits/zai-org/glm-5-3) through Claude Code. Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
Issue #496, Task B. modes.Tracker keeps the cached-prefix boundary in memory only. After a proxy restart, TurnFrom found no record for a live thread and returned 0, so apply set MaxCachedIdx = -1 and every component could change every message. Example: request 29967, 62 s after the previous request, compacted message 253 of 925. What changed: - Tracker carries a start time. NewTracker stamps it; SetStartedAt lets a test set it. - In TurnFrom, a key with no record, no drop and no usable parent reads as all-cached (prevLen = n, prevAtMs = 0) while the tracker started less than restartGraceMs ago. The grace lasts the longest cache lifetime, 1 hour: past it, no entry a restart forgot can still be alive, so an unknown key is a new thread again, as before. - The idle clock stays unknown, so nothing reads cold off a fabricated age. Cost: in the first hour after a restart, a brand-new thread cannot be changed on its first request. Its second request acts on the new tail as usual. Four existing tests model steady-state traffic with a fresh tracker, so they now run on a clock from before the tracker started (the state they model). One proxy end-to-end test ages its tracker the same way. Data dependence: metadata only (a timestamp). The "Cache tracker" row in docs/data-dependence.md says so. Written by GLM (rits/zai-org/glm-5-3) through Claude Code. Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 | offload-review skill, @amiddavid's session | fresh | 2 of 2 | 1 of 2 | 200adb5883bc |
approve |
Verdict: approve
Findings
None. I found no wrong behavior, no data loss, and no broken fail-open path.
Non-blocking
- modes/tracker.go:136 —
SetStartedAtwritesstartedAtMswithoutt.mu.
graceLockedreads the field under the lock. A call on a live tracker races with
in-flight requests. All callers in this repo set it before traffic starts, so nothing
breaks today. Suggest takingt.muin the setter, or a doc line that says "call before
serving only". - modes/tracker.go:91 — the grace freezes new threads too.
For one hour after each start, the first request of every unknown key reads all-cached.
This includes brand-new threads, where nothing is cached. The cost is one turn per
thread, and the code comment states the trade. Note for benchmark runs: a proxy started
fresh, then measured, holds every session's first request inside the grace. First
requests of new sessions are small, so I expect a small effect, but it is a real change
to what a fresh proxy measures. - dash/prefixcause.go:112 — a partial read after a dashboard restart reads
cold_start.
The recorder is in-memory. After it restarts,seenSessionis false, so a partial read
falls to the cold-start branch. Before this PR it readhit. The PR documents that old
rows are not migrated; it does not name the restart relabel. Minor, label only. - No test covers the second request after a restart. The apply test checks turn 1 only.
Turn 2 follows from the normal record path, which otherTurnFromtests cover. A
two-turn restart test would pin the full contract.
What I checked
- The full diff of both commits, and the code around every hunk:
modes/tracker.go,apply/apply.go(boundary wiring),apply/responses.go,
dash/event.go,dash/prefixcause.go,proxy/dashcapture.go. - The grace logic.
graceLockedonly raises a boundary, which is the safe direction for
the cache.prevAtMsstays 0, so no code can read cold off a fabricated idle time.
One hour covers the longest provider TTL. Keep-alive pings die with the process, so no
entry a restart forgot outlives the grace. - The clock rule. A caller clock behind the tracker start gets no grace. I checked every
existing test that uses aTracker: all pass fixed past timestamps, so none change
behavior. The replay tool (cmd/cg-transcript-replay) passes transcript timestamps, so
it also keeps the old behavior, which matches the steady state it models. - The partial-read rule. I traced each guard:
- A full hit reads about the previous prompt, so
read*2 < prevPromptcannot fire. - A trimmed history reads most of what it kept; the
write > readguard keeps it a hit. - A keep-alive ping writes nothing, so it stays a hit.
PromptTokens= fresh + read + write. I checkedproxy/usage.go: both dialects
define fresh as input minus cached, so the sum is the whole prompt.- The cachesplit dollar figure: a qualifying row needs
CacheWrite < SplitStableTokens <= CacheRead, soCacheWrite > CacheReadis impossible there. The updated
SessionFirstcomment holds; no qualifying row can be relabeled.
- A full hit reads about the previous prompt, so
- Usage is written onto the event (
proxy/dashcapture.go:517) beforeFactsOfreads it,
soPromptTokensis real, not zero. - All
AttributeCacheandObservePrefixcallers were updated to the new signatures. docs/data-dependence.mdhas the new timestamp in the cache-tracker row, with a plain
reason. Both changes stay metadata only.- Both commits carry
Signed-off-by. - I did not run builds or tests. Live tests were not approved for this review, and Go is
not installed on this machine. My check of the test suite is a read of the code, not a
run.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 | offload-review skill, @amiddavid's session | fresh | 1 of 2 | 1 of 2 | 200adb5883bc |
blocking |
Verdict: blocking
Findings
- cmd/context-guru-proxy/main.go:540 — every eval run now measures the restart grace, and no eval path can escape it
- What fails: an eval container or gateway starts fresh, so its tracker is young. For its first hour,
graceLocked(modes/tracker.go:229) reads every unknown thread key as all-cached. The first request of every session is forwarded unmodified, so measured savings on it are zero./compact— documented as the offline replay/eval endpoint (proxy/proxy.go:727-761) — passes noNow, so it runs on the real clock and sits inside the grace. Published benchmark numbers shift down, silently. - Proof:
NewTrackerstampstime.Now()(modes/tracker.go:130);proxy.Newbuilds the tracker this way (proxy/proxy.go:366); nothing incmd/orproxy/callsSetStartedAt. The PR's own tests had to escape the grace to keep their meaning (apply/compaction_test.go:76-78, apply/trigger_counterfactual_test.go:279-281, proxy/dash_test.go:145-147). The eval paths got no such escape.cg-transcript-replayis exempt only by accident of design: it feeds recorded past timestamps (cmd/cg-transcript-replay/main.go:172), whichgraceLockedreads as past the grace. - Fix: let the eval gateway stamp an old start (a flag or env var that calls
SetStartedAtwith a time past the grace), or state the one-hour effect in the benchmark procedure. The A/B arms stay fair and the direction is safe, so this may be acceptable — but then it must be a stated, measured choice, not a silent one.
- What fails: an eval container or gateway starts fresh, so its tracker is young. For its first hour,
Non-blocking
SetStartedAt(modes/tracker.go:136) writesstartedAtMswith no lock, whilegraceLockedreads it undert.mu. No production caller races it today (tests call it before traffic). Worth a lock or a "call before traffic only" note if it stays exported.- The cached-prefix section of docs/design.md (~lines 310-318) does not mention the restart grace. Its "boundary only ever grows" sentence is also stale from the earlier compaction-reset change. data-dependence.md was updated; design.md was not.
- The partial-read rule (dash/event.go:1189) needs
CacheWrite > CacheRead. A prompt that read a little, wrote a little and billed the rest fresh still reads "hit". Only the #496 shape is fixed. Fine as a first step; the guard is documented. restartGraceMsis 1 hour even for threads on the 5-minute tier. Safe direction; costs at most one turn of savings per such thread.
What I checked
- Full diff of both commits (200adb5 modes, 704d76e dash) and the code around each hunk.
- modes/tracker.go in full:
TurnFromcase order (record, dropped, parent, grace),graceLockededge values (nowMs <= 0, clock behind start,startedAtMs == 0), the recorded turnn/atafter a grace turn, andpruneLocked/wasDroppedinterplay. The grace turn is forwarded unmodified, so recordingnis the correct boundary for the next turn. - apply: the
TurnFromcall site andmaxCachedIdx--(apply/apply.go:547-548),cacheIsColdrefusingprevAt <= 0(no cold verdict off the grace), the idle/alias/TTL widening paths, and the no-trackerstoreBoundarycontrol used by the new test. - dash:
AttributeCachechain order withpartialRead,ObservePrefixreturningprev.PromptTokensonly from a committed same-model baseline (failed requests never become it),FactsOfreadingFreshInput + CacheRead + CacheWrite, and proxy/dashcapture.go setting those fields beforeFactsOfruns. All callers of the two changed signatures (production and test) were updated; grep found none left. - The new tests: the apply restart test's control arm rules out a vacuous pass; the modes grace tests cover young/old tracker with and without a parent; the dash partial-read test covers miss, TTL, unknown, full-cover read and first-request shapes.
- Existing tests that use
NewTrackerwith fake past clocks (coldcache, thread_cache, responses, sweep) keep the old behaviour because a clock behind the start reads as past the grace. The replay tool keeps the old behaviour for the same reason. - Fail-open: the grace only widens the protected region; it cannot let a component mutate a cached prefix. The dash change alters labels only, not pricing (
repeatRatereads the tiers directly). - Data dependence: the tracker row in docs/data-dependence.md was updated;
PromptTokensis a token count from the usage block, so metadata only. Direction unchanged. - I did not run builds or tests (not approved). I did not read the PR conversation.
Round 1 of the review on PR #759 found that an eval run could not turn the restart grace off: every fresh gateway sat inside it for an hour, so benchmark numbers shifted down with no escape. - The grace is now a tracker field, not a constant. NewTracker keeps the 1-hour default (modes.DefaultRestartGrace, the longest cache lifetime). SetRestartGrace turns it off with 0 or less. - The proxy exposes it as --restart-grace (env RESTART_GRACE), default 1 hour, and passes it through proxy.Options.RestartGrace to the tracker the handler builds. An explicit 0 turns it off, for an eval that sends whole transcripts to a fresh proxy. - SetStartedAt and SetRestartGrace take the tracker lock; both are startup settings, and the read side was already locked. - The apply restart test now runs a second turn on the same thread: the grace recorded turn 1, so turn 2's boundary is real and only the new tail is changeable. A modes test pins grace 0 as the old behaviour on a young tracker. - docs/design.md names the grace in the cached-prefix section and drops its stale "boundary only ever grows" sentence (a shrink has reset the boundary to 0 since the compaction-reset change). Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
|
Round 1: every finding answered. One commit, Reviewer 11. Blocking — an eval run cannot turn off the restart grace.
2. 3. docs/design.md. 4. 5. 1 hour of grace on 5-minute threads. Reviewer 21. 2. The grace freezes new threads too. 3. A partial read after a dashboard restart reads 4. No test covers the second request after a restart. |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 | offload-review skill, @amiddavid's session | resumed | 1 of 2 | 2 of 2 | b62b16e6753f |
approve |
Verdict: approve
Findings
None. The round-1 finding is fixed, and commit b62b16e6 adds no new defect.
Earlier findings
Mine, round 1
- An eval run cannot turn off the restart grace — fixed. The grace is now a tracker field (
modes/tracker.go), defaultmodes.DefaultRestartGrace(1 hour).SetRestartGrace(0)turns it off;graceLockedchecksrestartGraceMs <= 0first. The proxy passes--restart-grace(envRESTART_GRACE) throughproxy.Options.RestartGraceinto the trackerproxy.Newbuilds (proxy/proxy.go:371-375), so/compact, which shares that tracker, is covered too. I checked the wiring end to end: the flag always carries a value, an explicit0reaches the tracker, andparseEnvDuration("0")yields 0 with no error, soRESTART_GRACE=0also works. The PR body now states the cost and the escape under Benchmarks, with a measured figure. This is what I asked for. SetStartedAtwrites without the lock — fixed. BothSetStartedAtandSetRestartGracetaket.mu(modes/tracker.go:140-155).- design.md gap — fixed. The cached-prefix section names the grace, its default, and
--restart-grace 0, and replaces the stale "boundary only ever grows" sentence with the reset rule. CacheWrite > CacheReadguard scope — not changed, reason accepted. First step for the #496 shape; my round-1 note already allowed it.- 1-hour grace on 5-minute-tier threads — not changed, reason accepted. Safe direction, one turn of savings at most.
Reviewer 2, round 1 (I checked each myself)
- SetStartedAt lock — fixed, same change as mine.
- The grace freezes brand-new threads — accepted cost, now stated in the PR body with the measured 63-of-70 figure;
--restart-grace 0restores the old behaviour for a benchmark run. Agree: resolved. - A partial read after a dashboard restart reads
cold_start— label only, named under Known labels. Agree: acceptable. - No second-request test — fixed. The apply restart test now runs turn 2 on the same thread.
The new commit
b62b16e6 makes the grace a host setting. What I verified:
NewTrackerkeeps the 1-hour default, so library users and the replay tool are unchanged.graceLockedtreatsrestartGraceMs <= 0like the old no-grace behaviour, before any other test.proxy.Options.RestartGraceis*time.Duration; nil keeps the default, so every otherproxy.Newcaller (tests, adapters) is unchanged.- The new turn-2 assertions are right: the grace records turn 1's 925 messages, so
Boundary(925, 927)gives 925 andMaxCachedIdx924; the changed-index check demands a change in the tail and forbids one below it. - The grace-0 test pins the off switch on a young tracker, with and without a parent.
- A malformed
RESTART_GRACEis refused at startup by the existingcheckEnvDurationspath, like the other duration envs. - Commit message carries
Signed-off-byandAssisted-By, per repo rules.
Non-blocking
modes/tracker.gofield comment onstartedAtMsstill says "0 (a Tracker built without NewTracker) gets no grace" — true, and now also the stateSetRestartGrace(0)produces. No change needed.
What I checked
- Last review: round 1, 200adb5, 2026-10-27T18:06:16Z
- New commits read: 1 (
b62b16e6fix(modes): make the restart grace a host setting) - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files), plus the PR body fetched from the API
- New items since my last review: the author's comment at 2026-10-27T19:22:12Z (answers every round-1 finding; each answer checked against the code) and commit
b62b16e6(full diff plus the code around each hunk). Reviewer 2's round-1 review (18:04:37Z) I read now, as round 2 requires. - The flag path:
flag.Durationdefault,envDuration/parseEnvDurationon"0",checkEnvDurations,Options.RestartGracenil handling, and theSetRestartGracelock. - The new tests' arithmetic: 925 → 927 messages, boundary 925,
MaxCachedIdx924, changed indices at or above 925. - Fail-open and data dependence are unchanged by the new commit; the grace only widens the protected region, and the setting only narrows it back to the old behaviour.
- I did not run builds or tests (not approved). I read the author's test-result tables as claims, not as my own verification.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 2 of 2 | b62b16e6753f |
approve |
Verdict: approve
Findings
None. The fix commit is correct, and every round-1 finding is answered.
Findings from round 1
Mine:
SetStartedAtwrites without the lock — fixed. BothSetStartedAtand the new
SetRestartGracetaket.mu(modes/tracker.go:139-156). The read side was already
locked.- The grace freezes new threads too — accepted cost, now documented and escapable.
The PR body carries a Benchmarks section with a live figure (63 of 70 first requests
of a new session have 1 or 2 messages).--restart-grace 0gives a benchmark run the
old behavior exactly. I checked the flag end to end; see below. - A partial read after a dashboard restart reads
cold_start— accepted, named.
The PR body states it under Known labels. Label only, as I wrote in round 1. - No test covers the second request after a restart — fixed. The apply test now runs
turn 2 with 927 messages. I checked the math: turn 1 records 925 under the grace,
Boundary(925, 927)is 925, soMaxCachedIdxis 924. The test asserts every changed
index is at or above 925 and that at least one changes.
Reviewer 1 (I checked each myself, not from the reply alone):
- Blocking: an eval run cannot turn off the grace — fixed, and I verified the whole
path.modes.DefaultRestartGrace(1 hour) is the default fromNewTracker.
SetRestartGrace(0)turns it off;graceLockedreturns 0 whenrestartGraceMs <= 0.
The proxy reads--restart-grace(envRESTART_GRACE) and passes the flag pointer
throughproxy.Options.RestartGraceinto the trackerproxy.Newbuilds.
parseEnvDuration("0")parses to 0, so both--restart-grace 0andRESTART_GRACE=0
turn it off. A malformed env value falls back to the default and is refused at startup
bycheckEnvDurations.nilinOptionskeeps the default for library callers.
/compactshares the handler's tracker, so the same flag covers it. A new modes test
pins grace 0 as the old behavior on a young tracker. SetStartedAtwithout the lock — fixed, same as mine.- docs/design.md stale — fixed. The cached-prefix section now names the grace, its
default, and--restart-grace 0. The wrong "boundary only ever grows" sentence now
states the reset rule, which matchesmodes.Boundary. CacheWrite > CacheReadguard scope — rejected by the author, reason accepted.
First step for the #496 shape; the guard is documented inAttributeCache. I agreed in
round 1 that only the #496 shape is fixed.- 1 hour of grace on 5-minute threads — rejected by the author, reason accepted.
Safe direction; at most one turn of savings per such thread.
Non-blocking
- modes/tracker.go:148 —
SetRestartGraceis safe to call live, but the doc says
"must run before traffic". The lock makes it race-free, and a mid-flight change can
only move unknown keys between "frozen once" and "not frozen" — never a wrong boundary.
The doc is stricter than the code needs. No change required.
What I checked
- Last review: round 1,
200adb5883bccf80d14e99d29ea3c0a78f974e6f, 2026-10-27T18:04:37Z. - New commits read: 1 —
b62b16e6fix(modes): make the restart grace a host setting
(#496 review). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files), plus
the PR body. - New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (18:06:16Z, blocking): read in full, verified its fix
myself (see above). - The author's reply comment (19:22:12Z): read in full; every claim in it that I could
check from code held up — the lock fix, the flag plumbing, the turn-2 test, and the
two rejections with reasons. - Commit
b62b16e6: full diff read, and the code around each hunk
(modes/tracker.go,proxy/proxy.go,cmd/context-guru-proxy/main.go,
apply/tracker_restart_test.go,modes/modes_test.go, both docs). - PR body: fetched and read; it carries the Benchmarks and Known labels sections the
reply promises, plus the data-dependence statement (metadata only, both tasks —
matches the code).
- Reviewer 1's round-1 review (18:06:16Z, blocking): read in full, verified its fix
- The new flag path end to end:
flag.Durationdefault fromenvDuration, which parses
0to a real zero;proxy.NewappliesSetRestartGracebefore the handler is built;
onlycmd/context-guru-proxy/main.gocallsproxy.New, so there is one tracker and one
setting per process. - The turn-2 test arithmetic: 925 recorded under the grace, 927 sent, boundary 925,
MaxCachedIdx924, changed indices asserted at or above 925. - That no existing test changed meaning: the grace-0 test sets the field directly in
package; the young/old tracker tests keep the default grace; the round-1 clock rules
are untouched. - The commit carries
Signed-off-byandAssisted-By: GLM, per repo convention. - I did not run builds or tests. Live tests were not approved. The author reports green
runs on the eval box, including a mutation check that the grace-0 test fails when the
setting is ignored; I read that claim but did not reproduce it.
|
The owner's decision on this PR, as first written (head
The author is changing the PR to follow this rule. |
…e review skill Round 1 of the review, both reviewers: - RELEASING.md: the example now states the real cost of #759 as first written (a fixed 1-hour window, for every model, in which the first request of each new thread went out unchanged). The owner's rejection is now posted on #759, and the example links to it. The rule names the real change: the window lasts only for the thread's model cache lifetime. - RELEASING.md: the opening sentence covers every behavior change, as its bullets do. - CLAUDE.md: the rule covers the library as well as the proxy, and links to the RELEASING.md section. - offload-review skill: two approvals do not make a behavior-changing PR ready; it needs a human developer's yes. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ache lifetime (#496) The owner rejected the global 1-hour window: an eval could not escape it, and 5-minute threads were held for an hour. The grace now follows the owner's rule: once the thread's first request after the restart arrives, the record exists again; until then the thread is held as in cache for the default TTL of that request's provider and model. - The lifetime is the one apply already computes (apply.CacheLifetime): 1 hour on Anthropic's extended tier (a body asking ttl "1h"), 5 minutes on Anthropic otherwise, 30 minutes on OpenAI GPT-5.6+ (a minimum, used as the grace). An unknown lifetime gets 5 minutes, the shortest known one, so an unrecognized model never holds a thread long. No second copy of the lifetime table; keepalive keeps its own. - modes must not import apply, so apply computes the lifetime before the tracker call and passes it in: TurnFrom and TurnAt take a grace duration. modes.DefaultRestartGrace and the restartGraceMs field are gone. The tracker keeps only an on/off switch (graceOn, default on); SetRestartGrace(bool) sets it under the lock. - The proxy flag is now a bool: --restart-grace (default true, env RESTART_GRACE), through proxy.Options.RestartGrace (*bool, nil = on). --restart-grace=false gives a benchmark run the old behaviour exactly. - apply.go reads the lifetime once, before the boundary, so the restart grace and the cold decision use the same value; responses.go gets the same rule. - Tests: the modes table covers 5/30/60-minute lifetimes inside and past the window, the second request using the record, and the switch-off. The apply tests cover 2 minutes (protected), 7 minutes (a new thread), an extended-tier body 40 minutes after start (protected), and the two-turn shape. - docs/design.md and the data-dependence row state the per-thread rule. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
|
The owner did not accept the global 1-hour grace. Task A (commit 704d76e) is unchanged. Task B now follows the owner's rule, in one new commit, The owner's ruleOnce a new message comes in on the thread, the thread record changes. The thread is held as in cache until its first message after the restart, for the default TTL of that request's provider and model: 5 minutes, 1 hour (Anthropic subscription tier), or 30 minutes (OpenAI). What changed in 043f47f
Test resultsNew and changed tests, all on the eval box:
The modes table test cannot compile on b62b16e (the signature changed), so a probe with the same 6-minute case ran there; it failed, as required. The second-request and switch-off tests pin behaviour that is the same on b62b16e, so they fail nowhere old — they are guards, not new behaviour. Also on the box: |
Owner's follow-up on the per-thread grace. apply.CacheLifetime returns CacheLifetimeUnknown for OpenAI models before GPT-5.6, and the grace was mapping unknown to 5 minutes. An older OpenAI model's prefixes survive too, so for the restart grace only, every OpenAI request now gets OpenAIMinimumCacheTTL (30 minutes), whatever CacheLifetime says about the model. CacheLifetime itself is unchanged: the cold gate must not declare cold on an undocumented retention, so it keeps reading Unknown for those models. Only restartGrace (apply/cachelifetime.go) changed, plus the provider passed through its two callers (apply.go, responses.go). New test: TestAnOlderOpenAIRequestGetsTheThirtyMinuteGrace — a gpt-5.5 chat-completions body, 20 minutes after the tracker started, is protected (boundary 925); at 31 minutes it is a new thread, as before the PR. The test fails on the previous commit, where unknown mapped to 5 minutes. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]>
|
Owner's follow-up, one more commit: Every OpenAI request now gets a 30-minute restart grace, for any model. New test: a On the box: build, |
…rmission (#760) docs: a behavior change for an edge case needs a human developer's permission The owner set this rule for the release process and for all development: a PR does not change behavior because of an edge case without permission from a human developer. - CLAUDE.md: a new hard boundary. A fix that changes what the proxy does for users or other cases needs a human developer's yes before it merges, and the PR names the change at the top. - RELEASING.md step 2: the permission is a merge condition. The integrator reads the diff for behavior changes, also in a PR called "test-only" or "docs-only", and gets the yes in words. A peer agent's report is not enough. #759 is the example. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> docs: make the #759 example match the record, and name the rule in the review skill Round 1 of the review, both reviewers: - RELEASING.md: the example now states the real cost of #759 as first written (a fixed 1-hour window, for every model, in which the first request of each new thread went out unchanged). The owner's rejection is now posted on #759, and the example links to it. The rule names the real change: the window lasts only for the thread's model cache lifetime. - RELEASING.md: the opening sentence covers every behavior change, as its bullets do. - CLAUDE.md: the rule covers the library as well as the proxy, and links to the RELEASING.md section. - offload-review skill: two approvals do not make a behavior-changing PR ready; it needs a human developer's yes. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]> docs(review): check for a behavior change before "ready to merge" Round 2: step 4 of the offload-review skill said "Stop." before the new behavior-change check, so an agent that stops there never reached it. The check now comes first, then the message, then the stop. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 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 4 | 7d0737a9bff3 |
approve |
Verdict: approve
Findings
None. The two new commits follow the owner's rule, and I found no defect in them.
The owner's decision and what was built
The owner rejected the global 1-hour grace (comment 2026-10-27T21:43:46Z): a thread is held as in cache until its first message after the restart, for the default TTL of that model — 5 minutes, 1 hour on an Anthropic subscription, 30 minutes on OpenAI. Commits 043f47f5 and 7d0737a9 implement exactly that:
- The grace is per thread and per request:
applycomputes the request's cache lifetime once and passes it toTurnFrom/TurnAt(apply/apply.go:550-552).modeskeeps only an on/off switch, so it does not importapply. All three production call sites pass the new parameter; grep found no caller left on the old signature. - The window is measured from the tracker start to the request's arrival (
graceLocked, modes/tracker.go:239-247). The entry a restart forgot was last written before the restart, so its lifetime ends at or before start + TTL. The window therefore covers every live entry and can only over-protect. Safe direction. - The first request writes the record, so the grace covers exactly one request per thread; the second follows the normal
Boundaryrule. The new modes test pins both the growth and the shrink case. restartGrace(apply/cachelifetime.go:62-70): OpenAI always 30 minutes; an unknown non-OpenAI lifetime 5 minutes; otherwise the lifetime itself. For Anthropic-compatible providers (Bedrock,VertexviaexplicitBreakpointProvider) the tier comes from the body'sttl: "1h"ask — the subscription signal.CacheLifetimeitself is unchanged, so the cold gate still refuses to act on an unknown retention. The two facts are deliberately separate, and the comment says why.apply.goreads the lifetime once, before the boundary; the store-widening ofttlstill happens after, for the cold decision only. After a restart the store is empty, so the grace's un-widened value is the right one. No path uses a different value for the same fact.- The flag is now a bool:
--restart-grace(envRESTART_GRACE), default on,--restart-grace=falseoff, throughproxy.Options.RestartGrace(*bool, nil = on).envBoolparses0/off/noas false, soRESTART_GRACE=0works. The eval escape my round-1 finding asked for survives the redesign, and the distortion it fixes is now bounded to 5 minutes on a plain Anthropic body instead of an hour. - The bypass path passes grace 0 because it discards the boundary (apply/apply.go:656). Correct: a bypassed request changes nothing.
What I verified in the new tests
- The modes table: 1 min/5 min → 925; 6 min/5 min → 0; 6 min/1 h → 925; 20 min/30 min → 925; 31 min/30 min → 0. Each with and without an unknown parent. The arithmetic matches
graceLocked. - The apply tests: 2 minutes after start → protected (924,
cached_prefixgates, nothing changed); 7 minutes → new thread (-1, deep compaction asserted, so the test cannot pass vacuously); an extended-tier body (ttl: "1h"on the first user block, whichbodyAsksExtendedTTLreads) 40 minutes after start → protected; agpt-5.5OpenAI body 20 minutes after start → protected, 31 minutes → new thread. The OpenAI test is the one that fails on043f47f5, where unknown mapped to 5 minutes — the author reports that mutation check; I could not run it. - The two-turn test keeps its control arm and its second-turn assertions (boundary 925, changes only at or above index 925).
- No leftover references to
modes.DefaultRestartGraceor the old duration field; themodesimport was removed fromcmd/context-guru-proxy/main.go.
Earlier findings
- My round-1 blocking finding (eval cannot escape the grace) — the escape now exists and is shorter by design; resolved.
- My round-1 non-blocking notes — all resolved or accepted in round 2; the redesign does not reopen any of them.
- Reviewer 2 has not posted a round-3 review yet; nothing of theirs to check this round.
Non-blocking
- A thread on the 1-hour tier whose first post-restart request carries a plain body gets only the 5-minute grace, because the tier is read from that request. This follows the owner's rule as written ("the default ttl for that model"), and a thread that changes tier across a restart is rare. Edge only; no change requested.
docs/design.mdsays "30 minutes on OpenAI GPT-5.6+" in the cached-prefix section, while the code gives every OpenAI request 30 minutes. The next sentence names the per-request rule, so a reader can reconcile it, but the GPT-5.6 mention is now narrower than the behaviour. Small wording fix.
What I checked
- Last review: round 2, b62b16e, 2026-10-27T19:26:27Z
- New commits read: 2 (
043f47f5fix(modes): the restart grace is per thread and lasts the request's cache lifetime;7d0737a9fix(apply): every OpenAI request gets the 30-minute restart grace) - Read in full: 4 reviews, 3 comments, 0 inline comments (from the three files), plus the PR body fetched again from the API
- New items since my last review, and what I did about each:
- The owner's decision comment (21:43:46Z): read in full; treated as the spec for this round.
- The author's two comments (21:49:13Z, 21:57:59Z): read in full; every code claim in them checked against the diff.
- Commits
043f47f5and7d0737a9: full diff read, plus the code around each hunk —modes/tracker.go(signature change,graceLocked, the on/off switch, both locked setters),apply/apply.go(lifetime read once, ordering againstaliasSeenand the widening block),apply/cachelifetime.go(CacheLifetimekinds andrestartGracesubstitutions),apply/responses.go(same rule, early read, the!cacheAwarereset still after the tracker call),cmd/context-guru-proxy/main.go(flag.Bool,envBool),proxy/proxy.go(*booloption), both docs, and the four test files. - Reviewer 2's round-2 review (19:26:30Z) predates my last review by 3 seconds; I read it in full this round. Its one non-blocking note (the
SetRestartGracedoc stricter than the code) is moot: the setter is now a bool switch.
- Provider coverage:
explicitBreakpointProvidercovers Anthropic, Bedrock, BedrockMantle, Vertex — so those get the tier-based grace; every other non-OpenAI provider falls to the 5-minute unknown case. - Consistency of the one-fact rule: the grace, the cold decision and the Ctx's
ttlMsall derive from the singleCacheLifetimeread; the grace runs before the store widening, which is empty in every state the grace can fire in. - Docs: design.md and the data-dependence row state the per-thread rule; the PR body matches the code, including the OpenAI-any-model rule.
- I did not run builds or tests (not approved). The author's test tables, including the mutation checks, are claims I read but did not reproduce.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.312 | offload-review skill, @amiddavid's session | resumed | 2 of 2 | 3 of 4 | 7d0737a9bff3 |
approve |
Verdict: approve
Findings
None. The two new commits follow the owner's rule, and I found no wrong behavior in them.
The owner's rule, as implemented
The owner rejected the global 1-hour grace (comment at 21:43:46Z). The rule: a thread with no
record is held as in cache until its first request after the restart, for that request's
default cache TTL — 5 minutes on Anthropic, 1 hour on the extended tier, 30 minutes on OpenAI.
I verified each leg in the code:
restartGrace(apply/cachelifetime.go:62) maps the request'sCacheLifetimeto the grace:
OpenAI → 30 minutes for every model; an unknown non-OpenAI lifetime → 5 minutes; otherwise
the lifetime itself.CacheLifetimegives Anthropic 5 minutes exact, 1 hour exact when the body asks
ttl: "1h". I checkedbodyAsksExtendedTTL(apply/apply.go:1032): it scans
messages.#.content.#.cache_control.ttl, which is where the test's fixture puts the ask.- The grace window is measured from the tracker start and ends at the thread's first request,
which writes the record. That is sound: a restart cannot start before the thread's last
touch, so "tracker start + lifetime" always covers the longest an entry the restart forgot
can still be alive. The window can only be too long (one frozen turn), never too short. apply.goreads the lifetime once and uses it for both the grace and the cold decision,
inside the sameif o.Tracker != nilblock as before. The no-tracker path is unchanged:
ttlstays 0 there, as on main.responses.gois the same rule, and its
!cacheAwarereset still runs after the grace call, which only fires when cache-aware.- The bypass path passes grace 0 (
apply.go:656): the boundary it returns is discarded, so
there is nothing to protect. The legacyTurnpath passes 0 too and also hasnowMs = 0. - The proxy flag is now a bool:
--restart-grace(default true, envRESTART_GRACE);
envBoolusesparseBool, which acceptsfalse,0,off,no.nilin
proxy.Options.RestartGracekeeps the grace on for library callers.
Earlier findings
- Everything fixed in round 2 stays fixed: both setters take
t.mu, design.md and
data-dependence.md name the rule (now the per-thread one), the turn-2 test survives as the
two-turn restart test, and the benchmark escape is now--restart-grace=false, stated in
the PR body's Benchmarks section. - The accepted rejections stand unchanged (guard scope, label-only dash note).
- My round-2 approval covered the global-grace head
b62b16e6. The owner rejected that
design, not a defect I missed; the new head replaces it, and I reviewed the replacement as
a first review above.
Non-blocking
- apply/cachelifetime.go:62 — the grace uses the incoming request's tier, not the entry's.
A thread cached under the 1-hour tier whose first post-restart request carries nottl: "1h"ask gets the 5-minute grace. In practice a tier change on the wire also changes the
breakpoint bytes, which breaks the prefix anyway, and a side request that inherits a 1-hour
parent prefix gets only its own short grace past 5 minutes. Both are edges of the owner's
own rule, and both are no worse than main (which protects nothing). No change asked. - modes/tracker.go:171 —
TurnAtandTurnFromchanged signature for the second time in
this PR. All in-repo callers are updated (I grepped: apply, proxy, cmd and the tests; the
only othermodesimporter,components/offload/extract_llm.go, usesDefaultMaxKeys,
not these methods). The documented downstream API iscomponents,apply,schema,
config, so the sidecar plugin should not break. Worth one line in the release notes. - The modes tests write
tr.startedAtMsdirectly, without the lock. No concurrent traffic in
those tests, so it is safe.SetStartedAtexists for callers that need the lock.
What I checked
- Last review: round 2,
b62b16e6753fbe1aba05e113100820053fc43a85, 2026-10-27T19:26:30Z. - New commits read: 2 —
043f47f5fix(modes): the restart grace is per thread and lasts the
request's cache lifetime;7d0737a9fix(apply): every OpenAI request gets the 30-minute
restart grace. - Read in full: 4 reviews, 3 comments, 0 inline comments (from the three saved files), plus
the PR body fetched again after the new commits. - New items since my last review, and what I did about each:
- Reviewer 1's round-2 review (19:26:27Z, approve on the old head): read in full now; its
verification agrees with mine, and its one non-blocking note (a stale field comment) is
moot — the field it named no longer exists. - The owner's decision (21:43:46Z): read in full. The rule quoted there is the spec I
checked the implementation against, line by line, above. - The author's comments at 21:49:13Z and 21:57:59Z: read in full; each claim I could check
from code held up (the wiring, the unknown→5-minute mapping, the OpenAI override, and
which tests fail on which parent commit). - Commits
043f47f5and7d0737a9: full diff read, plus the code around every hunk
(modes/tracker.go,apply/apply.go,apply/cachelifetime.go,apply/responses.go,
cmd/context-guru-proxy/main.go,proxy/proxy.go, and all five touched test files). - The PR body: read again; it now states the per-thread rule, the OpenAI 30-minute rule,
the benchmark escape, and the test tables for the new rounds.
- Reviewer 1's round-2 review (19:26:27Z, approve on the old head): read in full now; its
- The test arithmetic: 2 minutes < 5 minutes (protected), 7 minutes > 5 (new thread),
40 minutes < 60 (extended tier protected), 20 < 30 (OpenAI protected), 31 > 30 (new
thread); the modes table covers 5/30/60-minute lifetimes inside and past the window; the
second-request test checks growth keeps the record and a shrink resets it. - Every caller of
TurnAt/TurnFromand every importer ofmodes, by grep, to confirm
none were left on the old signature. graceLockededge values again on the new code:graceOnfalse,startedAtMs0,
nowMs <= 0,grace <= 0, and a clock behind the start all read as no grace.- Fail-open and data dependence: the grace only raises a boundary; the dash task is
untouched by these two commits; the data-dependence row states the per-thread rule. - Both commits carry
Signed-off-byandAssisted-By: GLM. - I did not run builds or tests. Live tests were not approved. The author's test tables,
including the fails-on-parent-commit checks, are claims I read but did not reproduce.
docs(design): the restart grace is 30 minutes on any OpenAI model #759 gives every OpenAI request the 30-minute restart grace, for any model. docs/design.md still said "OpenAI GPT-5.6+". This fixes the wording to match the code (apply.restartGrace). Docs only. No behavior change. Refs #496 Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
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]>
…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]>
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]>
fix: the restart grace uses the thread's last request time (#766) Part 1 of issue #766. After a proxy restart, the grace from #759 decided "is this thread still cached?" by the time the proxy started. It now decides by the time of the thread's own last non-ping request. - modes: Tracker.SetLastSeen gives the tracker a "last seen" lookup. A key with no record, no drop and no usable parent is protected only when its last request is inside the request's cache lifetime. A key the lookup does not know is a really new thread: no grace. With no lookup set (no database, dashboard off), #759's start-time rule stays as the fallback. A panicking lookup reads as "no lookup", so it cannot fail a request. - dash: Recorder.ThreadLastSeen answers that lookup for a thread.Key (session, thread) shape, from the map SeedSessions reloads at startup. - proxy: New wires the tracker's lookup to the recorder when the dashboard is on. --restart-grace=false still turns the grace off in every case. Behavior change: for the first request of each thread after a restart, a thread is protected only if its own last request was within one cache lifetime; a thread with no history is not protected. Decided by the owner on 2026-10-28 in the integrator's session. Part 2 (the dashboard's pricing of a replay after a restart) stays open on the issue; this PR does not build it. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix: the restart grace counts pings and the alias session id (#766) Round 2 of PR #767, from the offload-review's three blocking findings: - Keep-alive pings count on the grace clock. A ping that READ the cache kept the provider's entry warm, so the grace must treat it as a refresh. The recorder now holds a SEPARATE grace map (SeedGraceSessions seeds it from the requests table, Record and ObserveThread keep it current), because the recency map SeedSessions loads must stay ping-free: attribution must not re-date a thread from a ping. A ping that read nothing still counts nowhere. - The grace asks for the thread's keys under BOTH session ids. A conversation that switches between header and headerless turns may be known to the lookup only under its alias id, so TurnFrom takes the alias keys and graceLocked takes the LATER timestamp of the two — the same widening the cold decision's alias clock already had. - Observe mode keeps #759's start-time fallback. Observe rows carry no session id, so the lookup would miss every thread and read each warm one as new. New wires the lookup only for an enforcing mode. Non-blocking from the same review: ThreadRefreshedAt's doc states the prune policy honestly (age-prune above 20,000 entries; the last resort empties the map, and design.md says what that means), and the proxy restart tests seed the grace clock with controlled timestamps. Tests: alias widening at modes and apply level; the ping clock at dash level (seed and live) and through a full proxy restart; observe mode's fallback; all with mutation checks (M7-M15) and the four -race suites. Written by GLM (rits/zai-org/glm-5-3) through Claude Code Assisted-By: GLM Signed-off-by: DAVID AMID <[email protected]> fix: the restart grace records the alias id and declines observe tenants (#766) Round 3 of the offload-review on PR #767. Both blocking findings fixed, plus the three non-blocking items. Finding 1 - the alias widening worked in one direction only. The ask-side wideness could not help a headerless turn, because a headerless request's own derived id IS the alias id: the tracker asks for one key, and the recorder held the header turns' warmth under the other one. Now the record side touches the grace clock under BOTH ids: - proxy/dashcapture.go derives the alias off the pristine body on the writer goroutine (the same lazy normalization WaitCause uses), so the derivation matches what apply computes; the touch and the row's new session_alias column are filled there, never on the handler's defer. - dash's write() invokes that closure before the insert, touches the grace clock under thread.Key(alias, thread), and stores the alias on the row. - SeedGraceSessions seeds both keys, reading the stored alias back. Known limits, documented in docs/design.md and covered by a test: rows written before the column existed have no alias to recover, and a keep-alive ping carries no body to derive one from, so a ping refreshes only the id it ran under. Finding 2 - observe mode is per tenant. The gate read the process mode, so a hosted proxy in sync mode wired the lookup for a tenant whose document sets mode: observe, whose rows carry no session id, and every one of its live threads read as new after a restart. The robust fix (give observe rows their real session id) changes what the observe projection stores and shows, so it was NOT built - that is a behavior change for the owner to allow. What is built instead: the lookup is wired unconditionally and declines the key (have=false) for a tenant whose pipeline runs observe, so #759's start-time fallback answers for exactly that tenant: - modes.Tracker's lookup now returns (atMs, known, have): a third answer, "cannot answer for this key", that falls to the start-time rule where a miss would have read every warm thread as new. - TenantSource.ObserveNamespaces walks the live tenancy cache; the wired lookup declines the keys of the tenants it names, and every key while the whole proxy runs observe. - New tests: a hosted proxy in sync mode with one tenant in observe protects that tenant's live thread after a restart; a sync tenant's unknown thread still reads as new. Non-blocking items: - SeedGraceSessions counts only rows the upstream accepted (2xx); a failed request wrote no cache entry. - Record's comment about a cache-blind ping now states the real rule: such a ping is not counted, as the keeper does not count it either. - The PR body names the compile breaks: TurnFrom gained 2 parameters (round 2) and SetLastSeen's lookup returns 3 values now (round 3). Verified on the eval box: vet and gofmt clean; the focused and full suites for modes, apply, dash, proxy and cmd pass; the new tests fail on origin/main (build: the APIs they use do not exist there); 7 new mutations (M16-M22) are each caught by a test; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> fix: the alias derivation goes through the pipeline transform (#766) Round 4 of the offload-review on PR #767. Both reviewers blocked on the same finding, and the owner decided the fix. The finding: dashcapture's AliasFn derived the alias from the PRISTINE body, but apply derives the id it asks for from the body AFTER transformEnvelope. When toolfilter's skills half rewrites the head message (a skill__ entry in the tenant's removal list), the two hashes differ, so the record-side touch and the session_alias column held an id no request ever asks for — the round-3 widening did nothing for that traffic. The repo names this trap itself: apply.EnforcedSessionIDFor exists for exactly it, and the proxy already uses it twice for that reason. What changed: - proxy/dashcapture.go: the capture holds the pipeline, wire dialect and bypass flag of the request (noteAliasSource, set beside noteWaitBody). finish()'s AliasFn derives the alias through apply.EnforcedSessionIDFor with an EMPTY explicit id, so it is the content-derived alias of the TRANSFORMED body — the exact id the pipeline's own turn asks under. It runs on the writer goroutine, which AliasFn already uses. A capture with no noted source (nil pipe) transforms nothing and keeps the raw-body derivation, the pre-round-4 behavior. - The "never disagree" comment is corrected: the two derivations agree because they read the same transformed body now, not because the hash function is shared. - /compact rows no longer store a constant tenant-wide hash as their alias: EnforcedSessionIDFor returns '' for a bodyless request, so the alias is simply absent (reviewer 2's non-blocking item). - docs/design.md states the transform-based derivation. - Test: TestTheRestartGraceProtectsAHeaderlessTurnWhenToolfilterRewritesTheHead — a tenant whose toolfilter removes a skill, a headered turn before the restart, a headerless turn after it within the lifetime: protected. It fails at fcbb99b (verified on a copy of that head with the new test overlaid). Mutation-checked: deriving from the raw body again (a nil pipe handed to noteAliasSource) fails the test. Verification: vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> fix: one alias rule on both sides of the restart grace (#766) Round 5 of the offload-review on PR #767, the last granted round. Reviewer 2 blocked; the fix follows their proposal and the owner's decisions (the session_alias column, the wider rule and the observe fallback all stay). The finding: after round 4 the two sides of the grace derived the alias by different rules. The record side resolved the metadata session id (EnforcedSessionIDFor resolves explicitSession first), so for a body with metadata.user_id (Claude Code) or metadata.taskId (Bob Shell) it warmed the metadata id. The ask side still asked the bare content hash (session.Scoped with an empty explicit id). A headerless turn runs under the metadata id, so for metadata-carrying traffic the header turn after a restart asked {header id, bare hash}, both missed, and the warm prefix was rewritten. Round 4 fixed the toolfilter case and regressed this one; #759 on main froze it. What changed: - apply/apply.go: new graceAliasID, the ONE rule for the restart grace's alias id: sessionIDFrom with an empty explicit id over the transformed body — the metadata session id when the body carries one, else the content hash of the head. The ask side's TurnFrom alias keys (chat and responses paths) now use it, as a value SEPARATE from the bare-hash alias that keys the cold decision's own clocks (aliasSeen, sessionTTL, RecordCacheTouch): this fix stays inside the restart grace. The record side reaches the same rule through EnforcedSessionIDFor's empty-explicit-id path, so the two cannot drift again. - The round-4 comment, docs/design.md and the PR body now say which id comes out: the metadata id when the body carries one, else the content hash of the transformed body. - Left as is, stated in the PR: the cold decision's own alias clocks key on the bare content hash and do not bridge to a metadata id — old code, no regression from this PR. Tests (proxy/restart_grace_test.go): - TestTheRestartGraceProtectsAHeaderTurnAfterUserMetadataHeaderlessOnes and ...AfterTaskMetadataHeaderlessOnes: a metadata body, headerless turns before the restart, a header turn after it within the lifetime: protected. Both fail at 74ca2a9. - TestAHeaderlessOnlyConversationIsUnchangedAcrossARestart: the no-metadata, no-header shape is unchanged — a control that passes at 74ca2a9 too, which is the point. - The round-3 and round-4 seesaw tests still pass. - Mutations: the ask side reverting to the bare hash fails the metadata tests; the record side reverting to the pristine body fails the toolfilter test. Verification: vet and gofmt clean; full suites for modes, apply, dash, proxy and cmd pass; the four -race suites pass. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]> Merge origin/main into fix/restart-grace-last-seen (#766) main moved under this branch: #770 (8cc5b84) added session-state persistence to apply, with loadSessionState calls beside the alias and TurnFrom code this branch changed. GitHub reported PR #767 as conflicting and CI did not run on c5443e7. Both sides stay: - #770's loadSessionState(st, res.Session) and loadSessionState(st, alias) calls: the alias session's state loads from disk under the bare-hash alias, the id the store's alias keys use. - This branch's graceAlias := graceAliasID(...) and the TurnFrom alias keys, which resolve the metadata id when the body carries one. No behavior changed on either side. The reviewed commits are untouched; this merge commit is the only addition. Refs #766 Written by GLM (rits/zai-org/glm-5-3) through Claude Code Signed-off-by: DAVID AMID <[email protected]>
Behavior change (needs a human developer's yes)
Who it affects: every proxy user, for a short time after each proxy restart. Dashboard readers.
hitcold_start,ttl_expiryor the measured cause. Old rows keep their labels.How to turn it off:
--restart-grace=false(orRESTART_GRACE=false) on the proxy. Use it for a benchmark that sends whole transcripts to a fresh proxy. The label change has no switch.Decided by: the owner set the per-thread rule on 2026-10-27, through integrator-053, after rejecting the earlier 1-hour version.
Summary
Fixes the two open causes from #496 (update of 2026-10-27). GLM wrote this PR (rits/zai-org/glm-5-3), through Claude Code.
hit. A request that re-wrote most of its prompt still read 35k-51k tokens, because Claude Code keeps the system prompt and tools under a separate breakpoint. 101 rows since 10-15 were labelledhitwhile they re-wrote the prompt.searchfoldis not touched. The older proposal in the issue body is replaced by the 2026-10-27 comment.What changed
Task A — label a large partial read as a miss (commit 1,
704d76ef)dash.PrefixFactscarriesPromptTokens: the request's whole prompt (fresh input + cache read + cache write).Recorder.ObservePrefixreturns the previous same-model request'sPromptTokens. The caller inproxy/dashcapture.gopasses it toAttributeCache.AttributeCachecalls a row ahitonly when the read is not partial. Partial: the previous prompt is known,cache_read < PromptTokens/2, andcache_write > cache_read. A partial read takes the existing chain: cold start, thenttl_expiry, then the measured cause.dash/keepalive.gocount onlyttl_expiry. The 83 rows that are reallyttl_expirynow count there. No code change was needed.Task B — keep the cached part safe after a restart (commits 2-5)
modes.Trackercarries a start time.NewTrackerstamps it;SetStartedAtlets a test set it.apply.CacheLifetimealready computes: 1 hour on Anthropic's extended tier (a body askingttl: "1h"), 5 minutes on Anthropic otherwise, 30 minutes on OpenAI — every OpenAI request, whateverCacheLifetimesays about the model (a pre-GPT-5.6 model reads Unknown; the grace uses the documented 30-minute minimum anyway, andCacheLifetimeitself is unchanged for the cold gate). A lifetime we do not know on another provider gets 5 minutes, the shortest known one — a model we cannot price in cache terms must not hold a thread long.TurnFrom, a key with no record, no drop and no usable parent reads as all-cached (prevLen = n,prevAtMs = 0) when its first request arrives less than that lifetime after the tracker started. The first request writes the thread record, and the normal rules apply from then on. A first request past the lifetime is a new thread, as before the PR.modesdoes not importapply: apply computes the lifetime before the tracker call and passes it toTurnFrom/TurnAt.apply.goreads it once, so the restart grace and the cold decision use the same value;responses.gogets the same rule.--restart-grace(envRESTART_GRACE), default true, throughproxy.Options.RestartGrace(*bool, nil = on).--restart-grace=falseturns the rule off.7d0737a9): every OpenAI request gets the 30-minute grace, for any model. New test: agpt-5.5body, 20 minutes after the start → protected; 31 minutes → a new thread.Benchmarks
A fresh proxy keeps the first request of each unknown thread unchanged until that thread's first request, for the request's own cache lifetime; set
--restart-grace=falsefor an eval that sends whole transcripts to a fresh proxy. Measured on live data: 63 of 70 first requests of a new session have 1 or 2 messages, so normal chat traffic barely changes.Known labels
A partial read that arrives after a dashboard restart reads
cold_start(the recorder is in-memory; old rows are not migrated). Label only.How it was tested
Every run on the shared eval box,
CGO_ENABLED=1,/usr/local/go/bin/go:gofmt -l dash modes apply proxygo vet ./dash/... ./modes/... ./apply/... ./proxy/...go test ./modes/...,./apply/...,./dash/...,./proxy/...(no race)go test ./components/... ./cmd/... ./adapters/... ./expand/... ./store/... ./config/... ./schema/... ./internal/... ./predictive/...origin/main(glm496-main)glm496-mut)glm496-mut)go test -race ./modes/... ./apply/... ./dash/... ./proxy/...(one package per run, detached)Round 1 (
b62b16e6, now superseded by the owner's rule):gofmt -l modes apply proxy cmd/context-guru-proxygo vet ./modes/... ./apply/... ./proxy/... ./cmd/...go test ./modes/...,./apply/...,./proxy/...,./cmd/...(no race)glm496-mut)go test -race ./modes/... ./apply/... ./proxy/...(one package per run, detached)Round 2 (
043f47f5, the owner's rule):go build ./...,gofmt -l modes apply proxy cmd/context-guru-proxy,go vet ./modes/... ./apply/... ./proxy/... ./cmd/...go test ./modes/...(2.2 s),./apply/...(5.5 s),./proxy/...(106.5 s),./cmd/...b62b16e6(the global 1-hour rule)b62b16e6origin/maingo test -race, one package per detached run:./modes/...(3.2 s),./apply/...(69.6 s),./proxy/...(462.5 s)Round 3 (
7d0737a9, the OpenAI grace):go build,gofmt -l apply,go vet ./apply/...go test ./apply/...043f47f5(unknown → 5 min)go test -race ./apply/...(detached)Data dependence
Metadata only, in both tasks.
PromptTokens) to the in-memory per-thread facts. The dashboard database row does not change.Closes #496
🤖 Generated with Claude Code