Skip to content

fix(keepalive): a ping touches the cache clock the request reads - #904

Merged
amiddavid merged 5 commits into
mainfrom
fix/ping-touch-alias
Nov 4, 2026
Merged

amiddavid merged 5 commits into
mainfrom
fix/ping-touch-alias

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change

  • Who: ultrahigh users with keep-alive on.
  • Old: a ping did not count as a cache touch. The next real turn read "cold". The sweep cut a live prefix, right after system + tools (about 20k tokens), and the turn wrote the rest again.
  • New: the ping counts. The next turn within TTL reads warm.
  • Defaults and switch: no default changes. There is no switch, because this is a bug fix. It restores what a ping is meant to do.
  • xhigh and lower presets defer no tools, so their behavior does not change.

Summary

A ping wrote its touch under a key the request never read. Now both use one key.

What changed

  • The cold check reads cg:seen:<alias>. The alias came from the body before tool deferral.
  • The keeper derived the alias from the body after deferral. Deferral appends the names list to messages[1]. SessionHead hashes that message when it is the first system message. So the two aliases differ.
  • Option A chosen (carry the alias). apply already computes the alias once. It now puts it on Trace.TouchAlias. proxy passes it on keepalive.Record.TouchAlias. The ping, the substitute call and the manual ping touch that key through the new apply.RecordCacheTouchAlias.
  • Pattern: the same one graceAliasID uses (apply/apply.go, fix(restart): restart grace must use the thread's last request time, and a replay after a restart is priced as a write #766): one rule derives the key, so the keys the cold check asks for and the keys the recorder warms cannot drift apart.
  • SessionHead and tooldefer are not changed. SessionHead also feeds the session id, checkpoint and billed-input keys.
  • Why not option B (strip the names list in SessionHead): it must never touch the client's own text. It would also need schema to know about tooldefer. Option A has one source for the key and no text matching.
  • RecordCacheTouch stays. It is right for a host that sends the transcript unchanged. "" as the alias falls back to it.
  • Files: apply/apply.go, apply/responses.go, keepalive/keeper.go, keepalive/manual.go, keepalive/substitute.go, proxy/keepalive.go, proxy/proxy.go.

Other readers of an alias-keyed clock:

  • aliasSeen (cg:seen:): reads the arriving alias. Correct as is.
  • sessionTTL(st, alias, ...) (cg:ttl:): the request reads and writes it under the arriving alias. The keeper never touches it. Not affected.
  • graceAlias and the restart grace: derived from the body that apply receives, and the record side uses the same rule. Not affected.
  • Responses and Chat Completions routes: TouchAlias is set there too. Our own tool search (tooldefer.RewriteSearch) inserts the names list at the head: a system message at messages[0] on Chat Completions with no leading system message, and a developer message at input[0] on Responses with no instructions. That moves the alias, so before this PR a ping on those shapes touched a key the request never read. Now it touches the right key.

How it was tested

  • New test apply/touchalias_test.go, on two fixtures (messages[1] is system, so the list is appended; messages[1] is not system, so a system message is inserted). The client's own text stays fixed:
    • the aliases differ before and after deferral (the proof);
    • the old derivation reads cold 4 min after a ping;
    • the ping key equals the key the next cold check reads, and the next turn reads warm;
    • xhigh (no deferral) is unchanged.
  • New test keepalive/touchalias_test.go: the scheduled ping, the manual ping and the substitute booking each touch the alias the host passed in.
  • New test proxy/pingtouchalias_test.go: end to end through keeper.recordTouch, a sweep ping and a real request. Three cases: ultrahigh with the fix, ultrahigh with the old derivation (reads cold), xhigh. A second test covers OpenAI: Chat Completions with no leading system message, and Responses with no instructions, both rewritten by RewriteSearch. OpenAI's cache lifetime is a minimum, so ColdCache never fires there. The test checks IdleMs, which reads the same clock.
  • Mutation: remove the touchAlias branch in pingJob.touch. The keepalive test and the ultrahigh proxy test fail. Restored.
  • Hashing: with no explicit session id, TouchAlias reuses the session id, so the head is hashed once per request. record in proxy/keepalive.go is now a test shim. Production calls recordTouch.
  • On the eval box: go vet ./... and gofmt -l . clean. -race passes on apply, keepalive, tooldefer, schema, components, proxy and dash, after reruns on the shared box for apply and dash. Known timing flakes failed once each (TestBodyOptsLoadsSessionStateFromDisk in apply; two overview and inventory timing tests in dash). Each passes alone on this branch and on origin/main, and passed on rerun. No code in those packages changed. Last run is at the head after the merge of origin/main.

Data dependence

None changes. The alias is a hash of metadata. No stored customer data is read or written. The feature is the same at every storage level (off, metadata only, everything).

Open questions

  • None.

Closes #902

🤖 Generated with Claude Code

The request's cold check reads cg:seen:<alias> with the alias of the body
as it arrived. The keeper derived its touch alias from the body that goes
upstream. Tool deferral appends the names list to messages[1], which can
be the first system message SessionHead hashes. On ultrahigh the two
aliases differ, so a ping never counted and the sweep cut a live prefix.

apply now puts the arriving alias on Trace.TouchAlias. The proxy passes it
on keepalive.Record. The ping, substitute and manual ping touch that key
through RecordCacheTouchAlias. RecordCacheTouch stays for hosts that send
the transcript unchanged.

Closes #902

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

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.318 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 626576deb61e approve

Verdict: approve

Findings

None. The fix is correct. I traced every path that writes or reads the cg:seen: clock, and the
two sides now use one key.

Non-blocking

  1. PR description vs tests — the second fixture does not exist. The description says
    apply/touchalias_test.go runs "on two fixtures (messages[1] is system, so the list is
    appended; messages[1] is not system, so a system message is inserted)". The file has one
    fixture (deferredShape), where messages[1] is a system message. No test covers the insert
    shape (tooldefer/rewrite.go:169-181). The fix covers it by construction — TouchAlias comes
    from the arriving body in both shapes — but a reader of the PR cannot verify that from the
    tests. Fix the description, or add the second fixture. Note: gh pr edit no-ops on this repo;
    use the PATCH API.

  2. apply/apply.go:507-508 — a second hash of the same head on every request.
    sessionIDFrom (line 503) already runs schema.SessionHead(norm) and, when the request
    carries no explicit session id, computes the same Scoped(tenant, "", ...) hash. The hoisted
    alias repeats both. The cost is one walk plus one sha256 of the head text, and it now runs on
    bypassed requests too, where the old code computed it only on the cache-aware path. Small, but
    it is per request. Reusing sessionID when no explicit id applies would avoid it.

  3. apply/responses.go:521 — the alias is derived twice in one function. Line 494 sets
    res.TouchAlias = session.Scoped(o.Tenant, "", sys, first); line 521 computes the same value
    again into alias. The PR's own pattern ("one rule derives the key") argues for one variable.
    Cosmetic.

  4. proxy/keepalive.go:310 — record has no production caller left. Only tests call it. It
    is a reasonable shim to keep; saying so here so a later reader does not hunt for one.

  5. Test gap on two changed touch paths. keepalive/manual.go (PingNow) and
    keepalive/substitute.go (recordSubstitutePing) now call j.touch, but only the Sweep path
    (keepalive/keeper.go:1726) is pinned by a test that hands in a TouchAlias. Both take the
    same pingJob.touch branch, so the risk is low.

What I checked

  • Read CLAUDE.md, docs/design.md, the full diff, and the code around every change.
  • One key on both sides. The cold check reads cg:seen:<alias> with the alias derived at
    apply/apply.go:507-509 from the transcript as it arrived at apply (post envelope transform,
    pre pipeline and pre deferral). Trace.TouchAlias is that same variable, so the request's read
    key and the ping's write key cannot drift. This mirrors the graceAliasID one-rule pattern
    from #766.
  • The bug is real. tooldefer.Rewrite puts the names list at messages[1]
    (tooldefer/rewrite.go:135-181), appended to a system message there or as a new system message
    at index 1. schema.SessionHead (schema/schema.go:267) hashes the first system message, so
    the deferred body yields another alias. The old RecordCacheTouch call in record1 hashed the
    deferred body the keeper holds. Confirmed by the new apply test.
  • Every touch site switched. record1 (keeper.go:1726), PingNow (manual.go:167) and
    recordSubstitutePing (substitute.go:249) all go through pingJob.touch. All pingJob
    literals (Sweep extra, Sweep regular, manual) copy touchAlias off the entry. No other caller
    of apply.RecordCacheTouch exists in the repo.
  • The only keepalive.Record construction site is proxy/keepalive.go:404, which now takes
    touchAlias. The one serve caller passes tr.TouchAlias from applyMode. Other hosts are
    unaffected: "" falls back to the old body derivation, and no other host builds a Record.
  • Fallback is safe. When TouchAlias is "" (no messages, observe mode's zero Trace, a
    panic in BodyOpts), the touch derives from the body, exactly as before. On observe and
    bypassed requests the proxy forwards the body unchanged, so that derivation is right there.
  • Store and tenant agree. The request's cold check and the ping's touch both use the tenancy's
    store (tn.Store) and the same tenant-scoped alias (apply.Opts.Tenant = Record.Key.Tenant).
  • No fail-open regression. RecordCacheTouchAlias is a guarded two-field store write;
    pingJob.touch cannot panic on the new branch. The keeper still masks held bodies; the alias is
    a hash, so it carries no transcript text.
  • Behavior change is named at the top of the PR, with who it affects and why there is no
    switch. It matches the owner-approved bug fix in #902. Data dependence: none changes; the alias
    is a hash of metadata, and no docs/data-dependence.md row is affected (no component changed).
  • Test math. coldAfterPing: first request at t0, touch at t0+4m, second request at t0+8m.
    Anthropic TTL 5m + coldMargin 1m (apply/cachelifetime.go:25): 8m idle reads cold, 4m reads
    warm. The three proxy cases (fix, old derivation, no deferral) and the keepalive pass-through
    test all assert on the real cg:seen: key in the real store.
  • Could not run Go on this machine (per the review rules). Verified test helpers exist with
    matching signatures (aliasFor, coldSpy, trackedRecord, testKeeper, kaPolicy,
    fakeSender), and that apply's test-only tooldefer import creates no cycle (tooldefer
    imports no apply).

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

Verdict: blocking

One low-severity finding. The core fix is correct. I verified the key rule end to end: the
request's cold check, aliasSeen (apply/apply.go:1202), and the ping's new touch,
RecordCacheTouchAlias (apply/apply.go:1280), now write and read the same cg:seen:<alias> key,
and that key comes from one derivation, Trace.TouchAlias.

Note on the head: this review was started against 626576de. The PR head is now 807663db, two
commits later. Both commits (b8a29f09, 807663db) touch apply/touchalias_test.go only. I read
both in full. The production code is identical, so the review stands. The marker keeps the sha this
review was given.

Findings

  1. apply/responses.go:494 — the OpenAI half of the fix has no test, and the PR text says it does not exist
    • What fails: our own tool search rewrites OpenAI bodies after apply runs, and it can move the
      head the alias hashes. placeClientList (tooldefer/clientsearch.go:495) inserts the names
      list as a system message at messages[0] on Chat Completions when the first message is not
      system or developer, and as a developer message at input[0] on Responses. normalizeResponses
      maps a developer message to a system message (apply/responses.go:363). On a Responses body
      with no instructions string, that inserted message becomes the first system message
      SessionHead hashes. So on those shapes the old body-derived ping key missed the request's
      clock — the same defect as #902 — and this PR fixes them through Trace.TouchAlias. No test
      covers any OpenAI route: apply/touchalias_test.go and proxy/pingtouchalias_test.go use
      Anthropic shapes only.
    • Proof: applyClientSearch runs for provider == bschemas.OpenAI && tooldefer.ClientWire(wire)
      (proxy/tooldefer.go:396), and ClientWire accepts both OpenAI wires
      (tooldefer/clientsearch.go:70). Keep-alive pings OpenAI threads on their own idle schedule
      (proxy/keepalive.go:487-492). The PR text says "Responses route ... behaves as before", which
      is wrong for the no-instructions shape: before, a ping there touched a key the request never
      read; now it touches the right one.
    • Fix: add one OpenAI case to proxy/pingtouchalias_test.go — a Chat Completions body with no
      leading system message, deferred through tooldefer.RewriteSearch, pinged, then a second
      request asserting warm. Also correct the PR text's "behaves as before" claim. Low severity:
      the code path is right by reading, and it moves in the safe direction (warm).

Non-blocking

  • apply/apply.go:503-508 — the head is hashed twice per request. sessionIDFrom already runs
    schema.SessionHead + session.Scoped over the same norm. The new alias line repeats both,
    so every request pays one extra sha256 of the head. It also runs on turns that never computed it
    before (bypassed, non-cache-aware, no tracker). Small, but alias == sessionID whenever the
    request carries no explicit session id, so half of these calls are pure duplicates.
  • proxy/keepalive.go:310 — record is now test-only. Every production caller uses
    recordTouch. Keep it for the tests, or note it in the comment.

What I checked

  • The full diff dd3cfa6f..626576de, plus the two later test-only commits up to the real head
    807663db (b8a29f09, 807663db).
  • The key rule, end to end: BodyOpts and bodyResponsesOpts set Trace.TouchAlias from the same
    session.Scoped(tenant, "", sys, firstUser) expression their own cold check passes to
    aliasSeen; RecordCacheTouchAlias writes store.SeenPrefix + alias, the same key aliasSeen
    reads; the write stays monotone.
  • The moved alias computation in BodyOpts: same inputs (norm), same value, only hoisted. The
    cold decision's behavior is unchanged.
  • Every keepalive touch site migrated to pingJob.touch: record1, PingNow,
    recordSubstitutePing. The fallback (touchAlias == "") matches the old RecordCacheTouch
    call exactly, including the provider argument. j.raw is the unmasked copy in all three
    (the XOR mask toggles, keeper.go:1361-1364).
  • touchAlias is copied out under the keeper lock in Sweep (both job kinds) and PingNow, like
    every other entry field. Record builds a fresh entry per request, so the alias never goes
    stale across turns.
  • Host paths that leave TouchAlias empty and fall back: observe mode (applyMode returns the zero
    Trace, but the body is forwarded unchanged there, so the body-derived key is right), bypass
    (BodyOpts still sets the alias; body unchanged either way), and a panic before applyMode
    (zero Trace, body reverts to orig). All safe.
  • Post-apply body mutations that move the head: tooldefer.Rewrite/placeList (Anthropic,
    covered by tests), placeClientList (OpenAI, finding 1), expand.Inject and
    adjudicate.Inject (tools array only, head untouched).
  • Fail open: no new error path. RecordCacheTouchAlias returns on empty alias or nil store.
  • The new tests, for correctness and vacuity: the apply tests assert the alias moves, the old
    derivation reads cold, the fix reads warm, and the ping key equals the cold-check key; the
    keepalive test asserts the exact clock value under the handed-in alias; the proxy test runs all
    three cases end to end through recordTouch, a sweep and a real request. None is vacuous.
  • docs/data-dependence.md: no dependence change — the alias is a content hash. The PR states
    this. The behavior change is named at the top of the PR, as RELEASING.md requires.
  • Not verified: the PR's claim that go vet, gofmt and -race pass on the eval box. Live tests
    were not approved for this review.

…te touches (#902)

Round 1 review of #904.

- Add an OpenAI case: Chat Completions without a leading system message
  and Responses without instructions. tooldefer.RewriteSearch inserts the
  names list at the head, so the body-derived ping key missed the clock.
- Pin TouchAlias on the manual ping and the substitute booking.
- Hash the head once: TouchAlias reuses the session id when no explicit
  session id applies. One variable in the Responses path.
- Say on keeper.record that it is a test shim.

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

Copy link
Copy Markdown
Collaborator Author

Round 1 reply. New head: 766d6384. Both reviews saw 626576de. All findings are answered below.

R1-1 (blocking): OpenAI had no test

Fixed in 766d6384.

  • proxy/pingtouchalias_test.go has a new test, TestAPingOnASearchRewrittenOpenAIBodyKeepsTheNextRequestWarm.
  • OpenAI's cache lifetime is a minimum, so ColdCache never fires there. The test asserts Ctx.IdleMs, which reads the same cg:seen clock.
    • With the alias from the arriving request, idle runs from the ping (8 min - 281 s).
    • With the alias re-derived from the sent body (the bug), idle runs from the request (8 min).
  • The test touches through apply.RecordCacheTouchAlias and apply.RecordCacheTouch, not through Sweep. The keeper sends no scheduled ping on an OpenAI thread through this path. The hand-off from Record.TouchAlias to the touch is pinned in keepalive/touchalias_test.go.
  • Mutation: blank Trace.TouchAlias in apply/apply.go and apply/responses.go. Both OpenAI "alias from the arriving request" cases fail, and so does the ultrahigh Anthropic case. Restored.
  • PR text corrected. The "Responses route behaves as before" line was wrong. It now says that before this PR a ping on the no-instructions shape, and on Chat Completions with no leading system message, touched a key the request never read.

R2-1: description vs tests

Fixed. The insert shape was added in b8a29f09 and 807663db. The description now lists the fixtures, the OpenAI test and the keepalive touch tests. I read the body back from the server.

Hash the head once (both reviews)

Fixed in 766d6384. apply/apply.go: with no explicit session id, alias is sessionID, so the head is hashed once. With an explicit id, it is hashed once for the alias. TouchAlias is still set on every path that reaches that line, including bypassed and non-cache-aware requests.

R2-3: two derivations in responses.go

Fixed in 766d6384. One variable, alias, is used for TouchAlias and for the cold clock.

record shim (both reviews)

Fixed in 766d6384. The comment on keeper.record says it is a test shim and that production calls recordTouch.

R2-5: manual ping and substitute tests

Fixed in 766d6384. keepalive/touchalias_test.go now pins TouchAlias on PingNow and on recordSubstitutePing, next to the scheduled ping.

Test results at 766d6384

  • go vet ./... and gofmt -l .: clean.
  • -race: tooldefer, schema, components/..., keepalive and proxy pass.
  • -race ./apply/...: flaky. The first run failed on TestBodyOptsLoadsSessionStateFromDisk (a 10 s sqlite deadline). The test passes alone on this branch and on origin/main. After that, this branch passed 5 of 5 full runs, and origin/main passed 6 of 6. I did not find the cause.
  • -race ./dash/...: the first run at this head failed on two timing tests, TestOverviewSessionScopedStaysFastWithManyOtherSessions and TestInventoryTablePassEqualsPerSessionProbe. Both pass alone on this branch and on origin/main. A full rerun on this branch passed (626 s), and origin/main passed (612 s). No dash code changed.

@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.318 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 766d63848759 approve

Verdict: approve

Findings

None. The three new commits fix every round-1 finding. The only production change among them is
value-identical to the round-1 code; I proved that below. The rest is tests and comments.

Status of round-1 findings

  • Reviewer 1, finding 1 (OpenAI had no test; PR text said "behaves as before") — fixed.
    766d6384 adds TestAPingOnASearchRewrittenOpenAIBodyKeepsTheNextRequestWarm. I checked it
    myself: it covers Chat Completions with no leading system message and Responses with no
    instructions, through the real tooldefer.RewriteSearch. placeClientList
    (tooldefer/clientsearch.go:495-525) inserts a system message at messages[0] on Chat
    Completions and a developer message at input[0] on Responses; responseMessage
    (apply/responses.go:360-362) maps developer to system, so SessionHead sees the inserted
    list in both shapes. The test self-checks that the rewrite moves the alias
    (apply.SessionIDFor before vs. after), so it cannot pass vacuously. OpenAI's lifetime is a
    minimum, so it asserts Ctx.IdleMs — the same cg:seen clock — with the right numbers
    (199 s with the fix, 480 s with the bug). The PR text now states both OpenAI shapes were broken
    before the PR. I read the corrected body back from the server.
  • My non-blocking 1 (description named a second fixture that did not exist) — fixed.
    b8a29f09 adds insertedShape (messages[1] is an assistant message, so placeList inserts
    a system message at index 1), and every apply test now runs both shapes. The description lists
    the fixtures correctly.
  • My non-blocking 2 (the head was hashed twice per request) — fixed. apply/apply.go:506-511
    now reuses sessionID as the alias when explicitSession returns "". I verified the value
    is identical in every case: sessionIDFrom calls the same explicitSession(o.Session, body)
    that the new branch tests, and Scoped with an empty explicit id falls to the same content
    hash (safeExplicit("") is false, session/session.go:43). A whitespace-only or unsafe
    explicit id makes the branch re-derive the hash — the same value Scoped itself would
    produce. No behavior change, one hash instead of two in the common case.
  • My non-blocking 3 (two derivations in responses.go) — fixed. One alias variable now
    feeds both res.TouchAlias and the cold check at line 534. Same inputs, same value.
  • My non-blocking 4 (record had no production caller) — fixed. The comment on
    proxy/keepalive.go:310 says it is a test shim and that production calls recordTouch.
  • My non-blocking 5 (manual ping and substitute had no TouchAlias test) — fixed.
    keepalive/touchalias_test.go adds TestAManualPingTouchesTheAliasTheHostHandedIn (PingNow) and
    TestASubstituteCallTouchesTheAliasTheHostHandedIn (recordSubstitutePing). Both assert the
    exact clock value under the handed-in alias.

Non-blocking

  • PR body vs. reply on -race. The body says "-race passes on apply ... and dash".
    The reply discloses that the first run of each was flaky on the shared box (a 10 s sqlite
    deadline in apply; two timing tests in dash), then passed on repeated full runs of both this
    branch and origin/main. The reply is the honest record; the body states the end state. No
    code in this PR touches either flake. Nothing to change before merge; a one-word "after
    reruns" in the body would make it exact.
  • The manual test pokes entry internals. TestAManualPingTouchesTheAliasTheHostHandedIn
    sets e.st and e.touchAlias on the live entry under k.mu rather than going through
    Record. Acceptable for a unit test of PingNow's hand-off; noting it so nobody reads it as
    a supported entry API.

What I checked

  • Last review: round 1, 626576deb61ebe6b78ab1f204550893b2055c605, 2026-11-04T18:47:18Z.
  • New commits read: 3 — b8a29f09 test(apply): cover the inserted names-list shape;
    807663db test(apply): assert the ping key equals the cold-check key, both list shapes;
    766d6384 test(keepalive): cover the OpenAI search rewrite, manual and substitute touches.
  • 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, and what I did about each:
    • Reviewer 1's round-1 review (posted 11 s after mine, so unread in round 1): read in full.
      Its one finding overlapped nothing of mine — it named the OpenAI placeClientList path,
      which I had missed. I verified the claim independently (see above) and the fix.
    • The author's round-1 reply (2026-11-04T20:15:35Z): read in full. Every "fixed" claim
      checked against the code at 766d6384; every one holds.
    • The three new commits: full diff read, plus the code around each change.
  • The only production diff since round 1 (apply/apply.go, apply/responses.go,
    proxy/keepalive.go comment): verified value-identical for the alias in all
    explicitSession / safeExplicit / whitespace edge cases; verified sys/firstUser have
    no other reader in BodyOpts that the narrower scope could starve.
  • New test soundness. Fixtures exercise the real tooldefer.Rewrite / RewriteSearch /
    placeList / placeClientList code; the alias-move assertions are self-checking, so a
    fixture that stopped reproducing the #902 shape would fail the test, not pass vacuously.
    Idle math re-derived: touch at +281 s, second request at +480 s → 199 s (fix) vs 480 s (bug).
    Helpers exist with matching signatures (manualKeeper, sess1.id(), seenAt,
    recordSubstitutePing(j, model, u, ms, startedAt, answerUSD), apply.SessionIDFor,
    schema.WireOpenAI/WireResponses).
  • Round-1 conclusions that still stand at this head: one key on both sides of the cg:seen
    clock; every touch site (record1, PingNow, recordSubstitutePing) goes through
    pingJob.touch; the "" fallback matches the old behavior; no new fail-open path; data
    dependence unchanged.
  • Could not run Go on this machine (per the review rules). The author's eval-box runs
    (go vet, gofmt, -race) are disclosed in the reply, including the two flakes; I read
    that report but could not reproduce it.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.318 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 766d63848759 approve

Verdict: approve

No findings. My round-1 finding is fixed, and the fix itself is correct.

Round-1 finding: fixed

R1-1 (blocking): the OpenAI half of the fix had no test. Fixed in 766d6384.

  • TestAPingOnASearchRewrittenOpenAIBodyKeepsTheNextRequestWarm (proxy/pingtouchalias_test.go) covers
    both wires I named: Chat Completions with no leading system message, and Responses with no
    instructions. Both go through the real tooldefer.RewriteSearch.
  • The test guards its own fixture: it fails unless the rewrite moves the alias
    (apply.SessionIDFor on the sent body versus the arriving body). So it cannot pass vacuously.
  • Asserting Ctx.IdleMs instead of ColdCache is right: OpenAI's cache lifetime is a minimum, so
    the cold verdict never fires there (apply/responses.go:567-571, apply.go's lifetime-kind gate).
    IdleMs reads the same cg:seen clock through prevAt. The expected values check out:
    199 000 ms from the ping's start with the trace alias, 480 000 ms with the re-derived one.
  • The PR text is corrected on the server. I read the body back. It now states that before this PR
    a ping on those shapes touched a key the request never read.

Other reviewers' findings, checked myself

All of reviewer 2's round-1 non-blocking items are fixed in b8a29f09, 807663db or 766d6384:

  • The insert-shape fixture exists (insertedShape, apply/touchalias_test.go), and the fix test
    asserts the ping key equals the cold-check key on both shapes. Agree, verified.
  • The double head hash is gone; see the equivalence check below. Agree, verified.
  • responses.go derives the alias once. Agree, verified.
  • keeper.record is documented as a test shim. Agree, verified.
  • The manual ping and the substitute booking are pinned by tests. Agree, verified — both tests
    assert the exact clock value under the handed-in alias, and both paths really reach
    RecordCacheTouchAlias (PingNow through okPing's CacheRead, recordSubstitutePing through
    its u.CacheRead > 0 gate).

The hash-once change is exactly equivalent

I checked every case of the new alias := sessionID reuse in BodyOpts (apply/apply.go:506-511):

  • explicitSession returns only a safeExplicit-validated id or "" (session.Explicit →
    ExplicitID, session/session.go:103-110). So when it returns "", Scoped falls back to the
    content hash inside sessionIDFrom, and sessionID IS the bare-hash alias. Reuse is exact.
  • When it returns a non-empty id, the branch recomputes Scoped(tenant, "", sys, firstUser) —
    the same bare hash the round-1 code always computed. Same value the cold check reads.

The value of tr.TouchAlias and of the alias the cold check passes to aliasSeen is unchanged
on every path.

Non-blocking

  • apply/apply.go:510 — one extra full-body metadata scan per request on explicit-session
    traffic.
    The new explicitSession(o.Session, body) check runs the gjson metadata lookup a
    second time (sessionIDFrom at line 503 already ran it). On a request with an explicit session
    id — Claude Code's metadata.user_id — the hash-once fix keeps the hash AND adds this scan; on
    requests without one it saves the hash and adds nothing. Both costs are sub-millisecond, but the
    cleaner form is to resolve the explicit id once and share it with sessionIDFrom.

What I checked

  • Last review: round 1, 626576d, 2026-11-04T18:47:29Z
  • New commits read: 3 — b8a29f09 (insert-shape fixture), 807663db (ping-key-equals-cold-check
    assertion), 766d6384 (OpenAI test, manual and substitute tests, hash-once, responses variable,
    record shim comment). The first two were also read in full during round 1; the production code
    they touch is nil.
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files).
  • New items since my last review:
    • Reviewer 2's round-1 review (approve, 5 non-blocking items). Checked each against the fix
      commit; all fixed as stated above.
    • The author's round-1 reply (2026-11-04T20:15:35Z), which answers every finding from both
      reviews. Each claim in it that I could check from code held up: the new tests exist and assert
      what the reply says, and the corrected PR text is live on the server.
    • The flaky-test disclosure in the reply: one apply sqlite-deadline flake and two dash timing
      flakes on first runs, all passing alone and on reruns on both this branch and origin/main.
      No dash file is in the PR diff. I cannot re-run tests (not approved), so I take the
      disclosure as given; nothing in the changed code touches those areas.
  • The full diff dd3cfa6f..766d6384, file by file, plus the code around each change.
  • The new keepalive tests for reachability: manualKeeper records a pingable entry whose fake
    dispatcher answers with CacheRead, so PingNow's touch gate opens; recordSubstitutePing's
    gate opens on the Usage the test passes.
  • The new OpenAI test's route dispatch: API: "" reaches BodyOpts' chat path, API: "responses"
    reaches bodyResponsesOpts; CacheMode: "on" forces cache awareness on both, so the tracker
    branch and aliasSeen run.
  • Not verified: the reply's go vet, gofmt and -race results. Live tests were not approved
    for this review.

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

Copy link
Copy Markdown
Collaborator Author

Before round 3: what is new since round 2 (766d638).

The head is now ad769b20. It is a merge of origin/main (44f8318d), with no rebase and no force-push.

  • The merge had conflicts in 4 places, in keepalive/keeper.go (the kaEntry literal and two pingJob literals in Sweep) and in keepalive/manual.go (the pingJob literal in PingNow).
  • Cause: main reverted the gapStart field in revert: Price proxy savings with the accountant library (#768) #903.
  • Resolution: take main's side (no gapStart) and keep this PR's touchAlias in each literal. git show --remerge-diff ad769b20 shows only these 4 edits.
  • Tests at ad769b20:
    • CI is green: build-test, purego, record, DCO and trivy;
    • -race passes on keepalive, tooldefer, proxy and dash;
    • apply passed on a rerun, after the known TestBodyOptsLoadsSessionStateFromDisk deadline flake.
  • Please check only the merge resolution. Every other line is unchanged since your round-2 approval.

@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.318 offload-review skill, @amiddavid's session resumed 2 of 2 3 of 3 ad769b20dc98 approve

Verdict: approve

Findings

None. The only new commit is a merge of origin/main. I checked the merge resolution and the
interactions with both incoming main commits. The PR's fix is intact and still correct.

What the merge brought in

Main advanced by two commits: 38c00e13 (revert of #903, the accountant savings library) and
44f8318d (#900, client ToolSearch mode). The PR base moved from dd3cfa6f to 44f8318d.

Merge resolution — checked, correct

The author's note (2026-11-04T20:54:53Z) says 4 conflicts, resolved as main's side plus this
PR's touchAlias. I ran git show --remerge-diff ad769b20 myself. It shows exactly those 4
conflict hunks and nothing else:

  1. keepalive/keeper.go:934-935 — the kaEntry literal: main's fields (no gapStart) with
    touchAlias: r.TouchAlias kept. Correct.
  2. keepalive/keeper.go:1316-1317 — the Sweep extra pingJob: main's fields with
    touchAlias: e.touchAlias kept. Correct.
  3. keepalive/keeper.go:1362-1363 — the Sweep regular pingJob: same. Correct.
  4. keepalive/manual.go:113 — the PingNow pingJob: same, and gapStart's comment went with
    its field. Correct.

All four keep every touchAlias copy the PR needs (Record, both Sweep job kinds, PingNow),
and drop gapStart exactly as main's revert did. No third side was introduced anywhere.

Interactions with the incoming main commits — checked, safe

  • Revert #903. It removed Trace.Ops, the savings tracker and gapStart from files this PR
    touches (apply/apply.go, keepalive/*, proxy/proxy.go). None of the removals touch the
    TouchAlias plumbing; I grepped the merged head: Trace.TouchAlias (apply.go:507),
    res.TouchAlias (responses.go:498), touchAlias in all four literals, pingJob.touch
    (keeper.go:2218), recordTouch (proxy.go:1549) are all intact. The serve call still passes
    tr.TouchAlias.
  • #900 client ToolSearch. tooldefer.Rewrite now delegates to an internal rewrite with a
    client flag; with client=false (what the exported Rewrite and this PR's Anthropic tests
    use) the behavior is byte-identical: same search tool, same NamesList, same placeList. In
    client mode the list still goes through placeList at messages[1], so the head still moves
    and TouchAlias still covers it. RewriteSearch/placeClientList (tooldefer/clientsearch.go)
    are untouched by #900, so the OpenAI test's path is unchanged. #900's AugmentSearches rewrites
    the body inside applyToolDefer, which still runs after applyMode and before serve records
    — another post-apply body change that TouchAlias covers by construction.
  • Test helpers. The revert deleted tests from keepalive/manual_test.go, but manualKeeper,
    recordWithSink and recordBodyWithSink survived; the PR's three test files are byte-identical
    to round 2 (not in the merge diff at all).
  • Net PR diff. git diff 44f8318d..HEAD lists the same 10 files as round 2, same content.

Status of earlier findings

  • All round-1 and round-2 findings (both reviewers): fixed at 766d6384, unchanged by the merge.
    Verified again by grep at this head.
  • Reviewer 1's round-2 non-blocking note (one extra metadata scan per explicit-session
    request, apply/apply.go:510): still open, still non-blocking, unchanged by the merge. I agree
    with its assessment; nothing in this round asks for it.

Non-blocking

  • The merge commit message carries Signed-off-by: DAVID AMID twice. Cosmetic; the DCO check
    passed. Nothing to do before merge.

What I checked

  • Last review: round 2, 766d63848759af11693643fac6a2c9c32c871c6a, 2026-11-04T20:20:17Z.
  • New commits read: 1 — ad769b20 "Merge origin/main into fix/ping-touch-alias" (brings in
    main's 38c00e13 revert #903 and 44f8318d #900; both read through the merge diff).
  • Read in full: 4 reviews, 2 comments, 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, and what I did about each:
    • The merge commit ad769b20: full git diff 766d6384..HEAD read; git show --remerge-diff ad769b20 read to see every conflict resolution; PR plumbing grepped at the merged head.
    • The author's merge note (2026-11-04T20:54:53Z): read in full. Its claims (4 conflicts, the
      resolution rule, --remerge-diff showing only those 4 edits) all check out against my own run.
    • Reviewer 1's round-2 review (posted at the same second as mine, so unread then): read in
      full. Its verification of the OpenAI test and the hash-once equivalence matches mine; its
      one non-blocking note is noted above.
  • The base move dd3cfa6f → 44f8318d: confirmed the PR's net diff against the new base keeps
    the same 10-file shape and content as the round-2 approval.
  • Could not run Go on this machine (per the review rules). The author reports CI green at
    ad769b20 (build-test, purego, record, DCO, trivy) and -race passing on keepalive, tooldefer,
    proxy and dash, with apply passing after the known sqlite-deadline flake. I read that report;
    the flake is the same one disclosed in round 2, pre-existing on the shared box.

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

Verdict: approve

No findings. The one new commit is a merge of origin/main. I checked the merge resolution and
every interaction between main's two new commits and this PR's fix. The fix is intact.

The merge (ad769b20)

The author's note asked for exactly this check. I verified it independently, from the combined
diff (git show ad769b20), not from the note:

  • Conflicts in 4 places, as stated: the kaEntry literal in Record, the two pingJob
    literals in Sweep, and the pingJob literal in PingNow. Main's revert (#903) removed the
    gapStart field; this PR added touchAlias to the same lines.
  • Each resolution is right: it takes main's side (no gapStart) and keeps this PR's
    touchAlias. I confirmed touchAlias survives at every site — Record (keeper.go:936), both
    Sweep jobs (keeper.go:1316, 1362), PingNow (manual.go:113) — and that all three touch calls
    (record1, PingNow, recordSubstitutePing) still route through pingJob.touch.
  • No dangling gapStart: zero references left in keepalive or proxy, tests included.
  • This PR's own files are untouched by the merge: the diff 766d6384..ad769b20 is empty for
    apply/responses.go, apply/touchalias_test.go, keepalive/touchalias_test.go,
    proxy/pingtouchalias_test.go and proxy/keepalive.go.
  • apply/apply.go merged cleanly. Its only changes from the merge are the revert's removals
    of #768's accountant code (Trace.Ops, opsFromRun, wireSizes), all far from the alias
    block. The alias computation at apply/apply.go:497-507 is byte-identical to the state I
    approved in round 2. No reference to a removed symbol remains anywhere in proxy, apply,
    dash or components.
  • proxy/proxy.go merged cleanly: the revert removed the cp.accEnd(..., tr.Ops) call, and
    this PR's tr.TouchAlias argument on the serve call (proxy.go:1549) is kept.

Interaction with main's new commits

  • #903 (the revert) removes gapStart and the accountant savings path from the exact files
    this PR touches. The merge keeps both intents; see above. The KeepAliveReport.Window field
    and its gapStart source are gone together, which is main's reviewed change, not this PR's.
  • #900 (one search tool per request) changes tooldefer.Rewrite to a client mode: the
    list text differs and no server-side search tool is added, but placeList still puts the names
    list at messages[1] — the head-moving behavior this PR's fix exists for. RewriteSearch and
    placeClientList are unchanged, so the OpenAI test's path is intact.
    applyToolDefer still runs after apply and still returns the rewritten body, so the keeper
    still holds a head-changed body and TouchAlias is still the right key there.

Status of earlier findings

  • My round-1 finding (OpenAI test gap, PR text) — fixed in 766d6384, verified in round 2,
    unchanged by the merge.
  • My round-2 non-blocking note (the second explicitSession metadata scan) — not addressed, as
    expected; it was a suggestion, not a request. Still stands, still minor.
  • Reviewer 2's items — all fixed in 766d6384; reviewer 2 approved round 2. Nothing new.

What I checked

  • Last review: round 2, 766d638, 2026-11-04T20:20:17Z
  • New commits read: 1 on the branch — ad769b20 "Merge origin/main into fix/ping-touch-alias"
    (bringing main's 38c00e13 revert #903 and 44f8318d #900 into the ancestry; both read as
    diffs against the branch tree).
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files).
  • New items since my last review:
    • The author's round-3 note (2026-11-04T20:54:53Z): a request to check the merge resolution.
      Done as above; its claims (4 conflicts, main's side for gapStart, touchAlias kept,
      git show --remerge-diff shows only these edits) all match what I found.
    • Reviewer 2's round-2 review (approve, 20:20:17Z): read in full. Its verification of the
      hash-once equivalence matches mine; nothing new to add.
    • The merge commit and both main commits it brings: full diffs read, plus the code around each
      change in the merged tree.
  • Fix integrity at the new head: Trace.TouchAlias, RecordCacheTouchAlias, recordTouch,
    tr.TouchAlias on the serve call, all three touch sites, and all six PR tests present and
    unchanged.
  • Not verified: the author's CI report (build-test, purego, record, DCO, trivy green; -race
    passing after the known TestBodyOptsLoadsSessionStateFromDisk deadline flake, the same flake
    disclosed in round 2). Live tests were not approved for this review.

The PR is ready for merge from my side.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Behavior change: approved by the owner (@amiddavid), 2026-11-04, in the session that started this PR. The owner said, in words: "approve".

This PR is a bug fix. It restores what a keep-alive ping is meant to do.

  • Who it affects: users with keep-alive on, on the ultrahigh preset (tool deferral) and on OpenAI routes that use our own tool search.
  • Old behavior: a ping recorded its cache touch under a different key than the one the next request reads. The next turn read "cold" although the cache was warm, and the sweep cut a live prefix. The cache broke at about 20k tokens.
  • New behavior: the ping records its touch under the key the request reads, so the turn reads warm.
  • Defaults: none change. There is no switch, because this is a fix.

This comment records the approval on the PR so the integrator can read it. The release rule still asks the integrator to get the owner's yes in its own session.

@amiddavid
amiddavid merged commit 2a2c913 into main Nov 4, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 4, 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.

ultrahigh: a ping's cache touch misses the request's clock, so the sweep cuts a live prefix

1 participant