Skip to content

refactor(schema): one canonical form of a message for cross-request comparison (#783) - #787

Merged
amiddavid merged 2 commits into
mainfrom
feat/msg-canon
Nov 1, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/msg-canon

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (a human developer must confirm before merge)

  • Who it affects: expand anchors (fixed restore, Expanding an offloaded output re-writes the whole conversation cache; restore it at a fixed spot instead #407), summarizer checkpoints and the stale-prefix guard (summarize, cache_aware_summarizer), and held sweep answers (extract_llm_sweep).
  • Old behavior: a message that the client sent as a list of one text block on one request and as a plain string on the next read as a different message. The anchor was skipped (kept-verbatim fallback), the checkpoint read as a different span, the stale-prefix guard declined, and a held output read as "content changed".
  • New behavior: the two forms read as the same message. Nothing else changes: every other difference still counts.
  • Stored values: nothing stored is invalidated.
    • A message with no content of exactly one plain text block hashes byte for byte as before. Tests prove it.
    • A hash stored before the upgrade over a one-text-block message still matches. Each comparison with a stored value also accepts the old rule's hash. Tests prove it, and mutation tests show each fallback is needed.
  • Thread keys: no change. internal/thread already treats a string and a one-text-block list as equal. Its hash bytes are unchanged, so no thread id moves.
  • How to turn it off: none. It is a matching fix, with no setting.

Summary

  • One canonical form of a message for every comparison across requests (refactor: one canonical form of a message for every cross-request comparison #783).
  • schema.CanonicalMessage (bifrost schema) and schema.CanonicalWireMessage (wire JSON) define it: cache_control removed, and a list of one plain text block read as its string. The wire form also sorts keys and keeps numbers as their literal text.
  • One table test holds every caller to the same equality.

What we found

Place What it is for Stored? Strips cache_control String = one text block (before) After this PR
expand.Fingerprint (expand/anchor.go) Anchor for a fixed restore Yes, cg:rst: (pinned) Yes No Canonical form; stored anchors match through fingerprintMatches
components.SpanHash (components/component.go) Span identity: stale-prefix guard, CoversSpan, checkpoints Yes, cg:sum: CoveredHash Yes No (bifrost keeps ContentStr and ContentBlocks apart) Canonical form; stored hashes match through SpanHashMatches
offload.outputHash (extract_sweep_hold.go) Held sweep answer: did the output change Yes, cg:swh: Yes (via SpanHash) No Via SpanHash; recheck uses SpanHashMatches
offload.summaryCoveredHash (summarize.go) Summary checkpoint over a Responses stash payload Yes Yes (via SpanHash) No Via SpanHash; reuse uses summaryCoveredHashMatches
thread.canonAt (internal/thread/thread.go) Thread identity (prefix continuity) Ids key stored checkpoints Yes Yes already Unchanged; held to the shared table
apply.NormalizeMessages (apply/apply.go) Wire to bifrost schema No — Keeps both forms apart Unchanged (it is a converter, not a comparison)
offload.msgPrint (extract_sweep_apply.go) Cheap change point for a held answer Yes n/a (text only) Yes already (MessageText) Unchanged
components.reformatKeys (pipeline.go) Reformat counters No n/a (text only) Yes already (MessageText) Unchanged
  • proxy/prefixask.go (sentStash.CoversSpan, snapshotCovering) compares SpanHash values computed on the same turn. They are not stored across an upgrade, so plain == stays.

Why it happens

What changed

  1. schema/canon.go: the canonical form.
    • The representative of the pair is the string, not the block. This direction keeps every always-string message at its old hash, so nothing stored is invalidated.
    • Only a block whose fields are type: "text" and text collapses. A block with citations, an image or any other field stays a list.
    • The wire form also collapses a tool_result block's own content (one level down).
  2. components.SpanHash uses schema.CanonicalMessage. LegacySpanHash and SpanHashMatches keep stored hashes valid.
  3. expand.Fingerprint uses schema.CanonicalWireMessage. Anchor.Usable uses fingerprintMatches. It accepts the new hash, the old hash of the message, and the old hash of its block form.
  4. Every comparison with a stored hash goes through a ...Matches function: tryReuse (both summarizers), checkpointRefreshOpportunity, dispatchDeferred, recheckHeld.
  5. internal/thread is not changed. It hashes in one streaming pass for speed, and its ids are content-derived keys. Its key order is wire order on purpose, so the table test exempts it from the key-order pairs only.

How it was tested

  • schema/canon_callers_test.go: one table, 11 same-message pairs and 6 different-message pairs, run against 4 callers (CanonicalWireMessage, expand.Fingerprint, SpanHash over apply.NormalizeMessages, thread.Fingerprint).
    • Same: marker moved (block and message), string vs one block (with and without marker), escaped text, key order, integer above 2^53, nested marker in tool_result, tool_result string vs block.
    • Different: other text, two blocks vs the joined string, two blocks vs one joined block, other role, integers above 2^53 that differ by 1.
  • Stored values: TestTheFingerprintIsUnchangedWithoutAOneTextBlockContent, TestSpanHashIsUnchangedWithoutAOneTextBlockContent (byte-identical hashes), TestAnAnchorRecordedByTheOldRuleStillMatches, TestSpanHashMatchesAcceptsAHashStoredByTheOldRule, TestASummaryCheckpointStoredByTheOldRuleIsStillReused.
  • Mutations, each made a test fail: no collapse in CanonicalMessage; no collapse in CanonicalWireMessage; no tool_result collapse; no legacy fallback in fingerprintMatches, SpanHashMatches, summaryCoveredHashMatches.
  • go test -race on the eval box: ./components/... ./expand/... ./schema/... ./internal/... ./adapters/... ./config/... ./apply/... ./proxy/... ./proxyapp/... ./cmd/..., all pass. go vet clean.

Data dependence

None. It is a hash over a message already in the request. Nothing new is stored, at any storage level. docs/data-dependence.md needs no change: no component is added and none changes what it stores.

Open questions

  • Do we drop the legacy fallbacks in a later release, after the pinned cg:rst: / cg:sum: / cg:swh: values from before the upgrade have aged out?

Technical notes

  • Why the string is the representative: the other direction (string -> one block) gives the same equality. But every message that was always a string would then hash differently, and every stored hash over it would read as new once.
  • Why the legacy fallback is safe: two messages equal under the old rule are equal under the canonical rule (the canonical rule only adds one equivalence). So the fallback never accepts a message the new rule would reject.
  • fingerprintMatches also tries the old hash of the message with its string content written as a block. That matches an anchor recorded before the upgrade over the block form, when the client now sends the string: the exact toolfilter: defer unused tool declarations at session start, by history (was: remove at cold moments) #485 case.
  • #784 (sibling PR) touches expand/response.go and apply/metawrite.go. This PR changes only Fingerprint and its helpers in expand/anchor.go.

Closes #783.

🤖 Generated with Claude Code

…omparison (#783)

Add schema.CanonicalMessage (bifrost schema) and schema.CanonicalWireMessage
(wire JSON). Both remove cache_control and read a list of one plain text block
as its string. The wire form also sorts keys and keeps numbers as literal text.

- components.SpanHash and expand.Fingerprint use the canonical form.
- A stored hash is compared through SpanHashMatches / fingerprintMatches,
  which also accept the hash the old rule gives the same message. Nothing
  stored before the upgrade reads as new.
- A message with no one-text-block content hashes byte for byte as before.
- internal/thread keeps its own streaming hash (its ids key stored
  checkpoints); a shared table test holds every caller to one equality.

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

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: blocking

Both findings are the same class: the "stored before the upgrade" fallback does not try
every form the canonical rule now treats as one message. Fail-open holds in both. No wrong
content goes out. The cost is a lost reuse, once, per stored record that straddles the
upgrade. Severity is low, but both contradict the PR's own claim ("Nothing stored before
the upgrade reads as new"), and finding 1 hits the exact configuration (small
keep_last_turns) where this bug class was first found (#402).

Findings

  1. components/component.go:207 — the legacy fallback misses a pre-#783 checkpoint whose covered span held the then-newest message

    • What fails: a deployment runs keep_last_turns: 0 (allowed: Min: 0,
      components/offload/cache_aware_summarizer.go:431). Then end = len(msgs) - keepLast (components/offload/summarize_pairing.go:150), so the covered span
      includes the request's newest message. Claude Code sends that message as one text
      block with cache_control on that turn, and as a string on every later turn. A
      checkpoint written before the upgrade stores LegacySpanHash of the block form. On
      the next turn the span carries the string form. SpanHash(msgs) is the canonical
      (string) hash; LegacySpanHash(msgs) is the old rule over the string form. Neither
      equals the stored old-rule hash of the block form. So SpanHashMatches returns
      false, tryReuse declines (components/offload/summarize.go:819), and a fresh
      summary is commissioned. The fallback is dead code for this configuration: the first
      read after the write already sees the string form.
    • Proof: LegacySpanHash strips cache_control only (components/component.go:198,
      222-247); it does not collapse a one-text-block to its string, so old-rule(block) ≠
      old-rule(string). The anchor side solves exactly this transition by reconstructing
      the block form (asTextBlock, expand/anchor.go:126) before hashing under the old
      rule; SpanHashMatches has no such reconstruction. The new tests cover the legacy
      fallback only with the span in the same form it was stored in
      (components/spanhash_canon_test.go:288-309,
      components/offload/spanhash_upgrade_test.go:158-186). No test covers legacy-stored
      plus form transition.
    • Fix: in SpanHashMatches, also compare want with the legacy hash of the span
      rewritten so each plain-string content message becomes its one-text-block form (the
      inverse of schema.CanonicalMessage's collapse). Or state the limit in the
      SpanHashMatches doc and accept the one-time decline. Bounded either way: one extra
      summary commission per straddling checkpoint, then the new checkpoint is canonical
      and stable.
  2. expand/anchor.go:104 — the legacy fallback does not reconstruct a tool_result block's content

    • What fails: an anchor recorded before the upgrade over a user message whose
      tool_result content is [{"type":"text","text":"out","cache_control":…}]. After
      the upgrade the client sends that content as the string "out" — the transition
      CanonicalWireMessage itself unifies (schema/canon.go:88-93). Fingerprint(msg)
      collapses the tool_result content to the string, so it cannot equal the stored
      old-rule hash, which keeps the block form. legacyCanonical(msg.Raw) keeps the
      string. asTextBlock rewrites only a top-level string content
      (expand/anchor.go:126-135); here the top-level content is the tool_result array,
      so it returns "". No path matches, Usable returns false, and the anchor stays
      unusable forever — the expanded original is never restored for it.
    • Proof: the three values fingerprintMatches tries are Fingerprint(msg),
      legacyCanonical(msg.Raw) and legacyCanonical(asTextBlock(msg))
      (expand/anchor.go:93-108); none writes a tool_result block's string content back
      as one text block. The canonical rule says the two forms are one message
      (schema/canon_callers_test.go:701-703, pair "tool_result content, string vs one
      text block"), but TestAnAnchorRecordedByTheOldRuleStillMatches
      (expand/anchor_test.go:468-497) has no tool_result case. As with finding 1, this
      anchor was already lost before the upgrade, so it is a gap in the fix, not a
      regression.
    • Fix: in the fallback, also try the message with each tool_result block's string
      content written as one text block. Or name the limit in the
      fingerprintMatches comment.

Non-blocking

  • The two canonical forms disagree on one shape: a text block with a field bifrost does
    not model. The wire form requires exactly type + text
    (schema/canon.go:622-634, len(blk) != 2); the struct form drops unknown fields and
    collapses (schema/canon.go:45-47, plainText). No caller compares a struct hash with
    a wire hash, and the struct path cannot see the extra field anyway. Not reachable from
    a schema-valid client.
  • A message that carries both ContentStr and ContentBlocks makes bifrost's
    MarshalJSON error, so it adds empty bytes to both hashes
    (components/component.go:211-219, b, _ := json.Marshal). Two different such
    messages are legacy-equal but not canonical-equal, so the "fallback never accepts a
    span SpanHash would reject" claim (components/component.go:205-206) does not hold
    there. Invalid state, unreachable from the wire (see schema/schema.go:104-110).
  • dash/toolinventory.go:675-678 hashes the raw last tool-using message, cache_control
    included. That is the same false-mismatch class this PR removes elsewhere. The cost is
    only a recount of used tools. Suggest its own issue rather than a change here.
  • I could not run the tests (live tests not approved; Go is not on this laptop). CI
    purego passed; build-test was still pending when I posted.

What I checked

  • Full diff 1ce2d4c..d6c9995, and the code around every hunk: components/component.go,
    the four spanHashMatches call sites, state.go, summarize.go's
    summaryCoveredHashMatches, extract_sweep_recheck.go, expand/anchor.go, schema/canon.go.
  • Every store site and every compare site of a stored hash or fingerprint:
    sumCheckpoint.CoveredHash (4 readers, all through the new Matches), heldOutput.Hash
    (recheck), Anchor.Fp (Usable), the async and inline writers, the keepalive checkpoint
    writer, summarize.go:635's marker-full hash (it equals summaryCoveredHash, because
    spanJSON comes from summaryStashJSON, which is the same payload function).
  • The proxy's sentStash (proxy/prefixask.go): it recomputes both sides from in-memory
    bytes, so == there is safe across this change; nothing persisted compares a
    SpanHash with == outside the Matches wrappers.
  • The safety claims: canonical form is a function of the legacy form, so a legacy
    fallback match implies a canonical match — holds for both the struct and the wire path,
    except the degenerate both-fields case noted above.
  • Mutation safety: CanonicalMessage copies before it clears or collapses; confirmed by
    reading the code and by TestSpanHashDoesNotTouchTheMessage.
  • Import graph: schema imports only stdlib and bifrost, so components → schema and
    expand → schema add no cycle. Test-helper names collide with nothing in their
    packages.
  • internal/thread.Fingerprint already unifies string and one-text-block (its own canon),
    so the shared caller table's expectations hold for 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.316 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 d6c99955bf66 approve

Verdict: approve

Findings

None. Every defect candidate I chased survived neither a line-level proof nor a trace. Details of
what I proved are under "What I checked".

Non-blocking

  • components/offload/summarize.go:350 — on the Responses route, the covered hash stays
    representation-sensitive.
    summaryCoveredHash hashes the stash payload, which
    apply/responses.go:248 builds from raw wire bytes. The spanHash half is now flip-insensitive,
    but the payload half is not. So on Responses, a string-against-block flip still declines checkpoint
    reuse. The fail direction is safe (a fresh summary, never a wrong reuse), no known Responses client
    flips, and it is pre-existing. Worth a line in the PR if Responses flips are ever observed.
  • schema/canon.go:66 and schema/canon.go:623 — the struct form and the wire form can disagree
    on a block with an extra key.
    plainText works from the bifrost struct, which drops unknown wire
    fields, so [{type,text,unknown}] collapses under SpanHash. collapseTextContent needs exactly
    2 keys, so it does not collapse under Fingerprint. Each hash space is internally consistent, so
    this can only miss an equivalence, never invent one.
  • Responses input_text blocks do not collapse. Only type:"text" collapses, so a
    string-against-input_text flip on Responses is not recognized. Fail-safe direction (anchor
    skipped, checkpoint not reused).
  • expand/anchor.go:126 — the legacy fallback rewrites only the message's own content. A
    pre-upgrade anchor over a tool_result whose block content now arrives as a string is skipped:
    asTextBlock does not reach inside a tool_result. The old rule missed this case too, so it is
    not a regression, and the anchor's fallback is fail-open (kept-verbatim in place).
  • components/component.go:207 — the decline path pays two hash passes. When the primary hash
    does not match, SpanHashMatches also computes LegacySpanHash over the whole span. One extra
    marshal pass per declined checkpoint per turn. Acceptable; drop the legacy fallbacks when the
    pinned pre-upgrade values age out (the PR's own open question).

What I checked

  • Read the full diff (13 files) and the code around every hunk. One commit, d6c99955.
  • The legacy rule is byte-identical to the old one. I diffed legacyStripCacheControl against
    the pre-PR stripCacheControl (identical body), and legacyCanonical + fingerprintOf against
    the old Fingerprint (same decode, same stripCacheControl, same marshal, same truncation, same
    "" on unparseable input). So a pre-upgrade stored hash recomputes exactly.
  • The fallbacks cannot accept what the new rule rejects. Trace: if two forms are equal under the
    legacy rule, they are equal after the one extra equivalence the canonical rule adds (blocks to
    string), so they are equal under the canonical rule. The same holds for the asTextBlock branch:
    it only rebuilds the block form of the same text. Checked both SpanHashMatches and
    fingerprintMatches.
  • plainText covers every field ChatContentBlock carries. schema/schema.go:118 documents
    the full set (Type/Text/Refusal/ImageURLStruct/InputAudio/File plus CacheControl, Citations,
    CachePoint). plainText checks all of them except CacheControl, which is set aside on purpose.
    ChatMessageContent has only ContentStr and ContentBlocks, so the collapse drops nothing.
  • Every comparison against a stored hash goes through a ...Matches helper. I grepped the repo
    for stored-hash equality and read each site: tryReuse (both summarizers),
    checkpointRefreshOpportunity, dispatchDeferred, recheckHeld, Anchor.Usable. The two
    proxy/prefixask.go sites compare hashes computed live on the same turn (current request against
    the stash, both normalized by this binary), so plain == is right there. The dash, keepalive and
    modes packages hold no span hashes. thread.Fingerprint already collapsed string against block
    and is unchanged, so no thread id moves.
  • Write and read sides stay paired. The plain summarizer writes a payload-aware covered hash and
    reads with summaryCoveredHashMatches; the cache-aware writers write a bare spanHash and read
    with spanHashMatches. The legacy paths recompute the exact pre-PR formulas, including
    hashKey(payload + ":" + hash).
  • The collapse cannot merge two messages the model reads differently. A block collapses only
    when it is type: "text" plus text plus optional cache_control, which is what a provider
    renders as the bare string. Blocks with citations, cache_point, or any other field stay blocks.
  • CanonicalMessage copies, never mutates. The collapse and the strip both build new Content
    values; the caller's message keeps its breakpoint (the new test asserts this too).
  • The new tests are sound and should pass. I traced each pair in schema/canon_callers_test.go
    through all four callers (including thread.canonAt's synthetic block form for a string content,
    and attachToolUse keeping large integers exact in ToolCalls.Arguments), and each stored-value
    test's precondition, positive and negative cases. No test-helper name collisions in the
    components, schema_test, offload or expand packages; no import cycle from
    components/expand to schema.
  • Repo rules. The PR names the behavior change at the top, with old and new behavior and who it
    affects. Data dependence is stated (none: a hash over in-request data, nothing new stored), and no
    docs/data-dependence.md row changes. No proxy import from a library package. Live tests were
    not run (not approved); this is a code-only review.

…783)

Review round 1 of #787 found two stored values that still read as new:

- A summary checkpoint stored over the block form of the then-newest
  message (keep_last_turns: 0). SpanHashMatches now also tries the old
  hash with the last message, and with every message, written back as
  one text block (LegacySpanHashes). summaryCoveredHashMatches uses the
  same list.
- An expand anchor over a tool_result whose content was one text block.
  fingerprintMatches now also tries the old hash with the tool_result
  string content written back as one text block (the last one, and
  all of them).

Each extra form is the same message under the canonical rule, so the
fallback never accepts a pair the canonical rule rejects. Tests cover
both changes and the negative cases.

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

Copy link
Copy Markdown
Collaborator Author

Reply to reviewer 2, round 1, finding 1 (components/component.go: SpanHashMatches misses a checkpoint stored over the block form). Fixed in 954b64b.

  • SpanHashMatches now also checks the new LegacySpanHashes. That list is the old-rule hash of the span written 3 ways:
    1. the span as it is;
    2. the span with the last message's string content written as one text block (the keep_last_turns: 0 case you described);
    3. the span with every string content written as one text block.
  • summaryCoveredHashMatches uses the same list, with the stash-payload prefix added.
  • Each form is the same span under the canonical rule, so the fallback never accepts a span that SpanHash rejects.
  • Tests:
    • TestSpanHashMatchesAcceptsAnOldHashAcrossTheBlockToStringChange: block to string, string to block, and all blocks to all strings.
    • TestASummaryCheckpointOverTheBlockFormIsReusedOnTheStringForm: the same checks at the summarizer, with and without a stash payload.
    • Negative cases: other text, other role, two blocks, a shorter span.
  • Mutation: with the last-message form removed, both tests fail.
  • go test -race ./components/... ./schema/ ./expand/... ./internal/thread/ passes on the eval box, including components/offload (342 s).

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Reply to reviewer 2, round 1, finding 2 (expand/anchor.go: fingerprintMatches does not rebuild a tool_result block's content). Fixed in 954b64b.

  • fingerprintMatches now also tries the old-rule hash of the message with each tool_result block's string content written as one text block. It tries 2 forms: the last such block only (the one that held the moving cache_control), and all of them.
  • Each form is the same message under the canonical rule, so the fallback never accepts a message that Fingerprint rejects.
  • Test: TestAnOldAnchorOverAToolResultBlockMatchesItsStringForm.
    • An old-rule anchor over the block form is Usable on the string form. Two cases: only the last tool_result was a block, and every tool_result was a block.
    • Negative cases: other text, other tool_use_id, two text blocks.
  • Mutations:
    • With both tool_result forms removed, the test fails.
    • With only the last-only form removed, the test fails too.

@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.316 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 954b64be4b4a approve

Verdict: approve

Both round-1 findings are fixed, and I verified the fixes by hand. No new finding.

Round-1 findings

  1. SpanHashMatches missed a checkpoint stored over the block form — FIXED (954b64b,
    components/component.go:213).

    • LegacySpanHashes now tries three old-rule hashes: the span as it is, the span with
      the last message's string content as one text block (the keep_last_turns: 0 case),
      and the span with every string content as one text block.
    • I traced the case that failed: a checkpoint stored as LegacySpanHash([strings…, block "go"]), read on the next turn as [strings…, "go"]. Form 2 rewrites the last
      message back to a block and matches. The reverse direction (stored over strings, now
      a block) already matched through the primary SpanHash, because canonical(block) ==
      canonical(string) == legacy(string).
    • The dedup is right: form 3 is skipped when it would equal form 2 (one flip, at the
      last message) or form 1 (no flips). The msgs[len(msgs)-1] index is guarded by
      flipped == 1, so an empty span cannot panic.
    • The safety claim holds: every form differs from msgs only by a string written as
      one plain text block, and CanonicalMessage collapses that block back to the same
      string. So any form that matches a stored hash is a span the canonical rule accepts.
    • summaryCoveredHashMatches (components/offload/summarize.go:357) walks the same
      list and keeps the exact old payload formula, hashKey(payload + ":" + hash). The
      recheck, keepalive and cold-deferral readers get the new forms for free through
      SpanHashMatches.
    • Tests: TestSpanHashMatchesAcceptsAnOldHashAcrossTheBlockToStringChange and
      TestASummaryCheckpointOverTheBlockFormIsReusedOnTheStringForm. I traced every case,
      positive and negative (other text, other role, two blocks, shorter span, different
      span at the summarizer). Each fails without the fix and passes with it.
  2. fingerprintMatches did not rebuild a tool_result block's content — FIXED
    (954b64b, expand/anchor.go:143).

    • fingerprintMatches now also tries the old-rule hash of the message with each
      tool_result block's string content written as one text block: the last such block
      only, and all of them.
    • I traced the case that failed: an anchor stored over [t0:"first", t1:[text "out"]],
      read as [t0:"first", t1:"out"]. The last-only form matches (flipping both would
      break t0, which the stored hash keeps as a string — the test covers exactly this).
    • The rewrite is safe: CanonicalWireMessage collapses a tool_result block's
      one-plain-text-block content back to the string (schema/canon.go:88-93), so every
      tried form is the same message under the canonical rule. A tool_result whose stored
      block form had more than a plain text block cannot match the reconstruction, so no
      wrong accept.
    • gjson.Array() on a non-array returns the result itself, so a message with string
      content cannot be misread as a block list; the guard holds. The sjson path
      content.<i>.content indexes the same array gjson walked.
    • Test: TestAnOldAnchorOverAToolResultBlockMatchesItsStringForm, both recorded forms
      and three negatives (other text, other tool_use_id, two text blocks). I traced each;
      none matches.

Non-blocking

  • LegacySpanHashes tries three of the 2^k possible string/block mixes: none, the last
    message, all. A middle-only flip is not tried. No known client produces it (a block
    form exists only to carry cache_control on the newest message), the doc names the
    three forms and why, and a miss costs one declined reuse, fail-open. Fine as is.
  • On the mismatch path SpanHashMatches now computes up to four hash passes over the span
    (one canonical, three legacy). Bounded to the decline path, once per eligible turn.
    Acceptable; drop the legacy forms when pre-upgrade values age out.
  • The degenerate both-content-fields message from round 1 (bifrost MarshalJSON errors,
    unreachable from the wire) is unchanged. Still not reachable.

What I checked

  • Last review: round 1, d6c9995, 2026-11-01T09:28:11Z.
  • New commits read: 1 — 954b64b "fix(schema): old-rule fallbacks try every form of a
    changed message (#783)". Full diff read; each changed file read around the change
    (components/component.go, components/offload/summarize.go,
    components/offload/spanhash_upgrade_test.go, components/spanhash_canon_test.go,
    expand/anchor.go, expand/anchor_test.go).
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from the three saved files).
  • New items since my last review:
    • Reviewer 1's round-1 review (approve, no findings; non-blocking notes overlap my
      round-1 items — the tool_result fallback gap and the struct/wire divergence). I
      checked the two fixes above against the shared concern; nothing new to add.
    • Author's two replies to my findings (both "fixed in 954b64b"): verified each claim
      against the code — the three-form list, the payload-prefix formula, the two
      tool_result forms, the tests, and the mutation claims. The author reports
      go test -race green on the eval box; I could not run tests myself (not approved),
      but CI purego passes on 954b64b (build-test pending at posting).
  • No new commits beyond 954b64b; no inline comments exist.

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

Verdict: approve

Findings

None in the new commit. Both round-1 findings are fixed correctly, and the fix adds no defect
I could prove. Trace-level detail under "What I checked".

Earlier findings

  • Reviewer 2, finding 1 (SpanHashMatches misses a checkpoint stored over the block form):
    fixed.
    LegacySpanHashes (components/component.go:213) now also tries the span with the
    last message's string content written as one text block, and with every string content so
    written. I verified the gating (flipped > 1 || flipped == 1 && last is not the string)
    adds no duplicate and cannot index an empty span. summaryCoveredHashMatches
    (components/offload/summarize.go:357) applies the same list under the stash-payload prefix,
    and stays byte-identical to the round-1 behavior for the no-payload, no-flip case.
  • Reviewer 2, finding 2 (fingerprintMatches does not rebuild a tool_result's content):
    fixed.
    toolResultsAsTextBlocks (expand/anchor.go:143) rewrites each tool_result block's
    string content as one text block, in two forms: all of them, and the last one only. I traced
    both new test cases through fingerprintMatches by hand: the "last block" recording matches
    through the last-only form, the "every block" recording through the all form. The negative
    cases (other text, other tool_use_id, two text blocks) match no form.
  • Reviewer 2's non-blocking items: not addressed, and I agree they stay non-blocking. The
    both-fields Content state is unreachable from the wire (bifrost's MarshalJSON errors on
    it, so neither side of a stored comparison can be written from it). The
    dash/toolinventory.go raw-message hashing deserves its own issue, as reviewer 2 said.
  • My round-1 non-blocking notes: the tool_result fallback gap (my note 4) is now fixed by
    this commit. The others (Responses payload sensitivity, struct-against-wire disagreement on
    extra block keys, input_text not collapsing) are unchanged and still non-blocking.

Non-blocking

  • components/component.go:251 — the decline path now pays up to 4 marshal passes. A
    typical all-string span triggers every form: canonical, legacy as-is, last-flipped,
    all-flipped. That is one extra pass over the covered span per declined checkpoint per turn,
    on top of round 1's two. Correct, just cost. The PR's own open question (dropping the legacy
    fallbacks later) is the remedy.
  • components/offload/spanhash_upgrade_test.go:53 — the stash-payload test uses a constant
    payload.
    In production the payload is the raw wire bytes of the span
    (apply/responses.go:248), which differ across a string-against-block flip. So on the
    Responses route the new forms 2 and 3 are inert: an identical payload implies an identical
    normalized span, which form 1 already matched. Fail-safe, and no known Responses client
    flips. My round-1 note stands.
  • components/component.go:202 — the form list is 3 of the 2^n string/block assignments.
    It covers the known clients: only-the-newest-as-block (Claude Code) and all-blocks. A client
    flipping some other subset still reads as new, once, fail-safe. The doc comment enumerates
    the three forms honestly, so nothing overclaims.
  • Carried from reviewer 2, round 1: a message with both ContentStr and ContentBlocks
    breaks the "every form is the same span under the canonical rule" argument, because
    CanonicalMessage collapses to the block's text while asTextBlock uses ContentStr.
    Invalid state, unreachable from the wire, and the stored side cannot be written from it
    either. Agree: non-blocking.

What I checked

  • Last review: round 1, d6c9995, 2026-11-01T09:28:35Z.
  • New commits read: 1 — 954b64be fix(schema): old-rule fallbacks try every form of a changed
    message (#783).
  • Read in full: 2 reviews, 2 comments, 0 inline comments (from .review-in-reviews.txt,
    .review-in-comments.txt, .review-in-inline.txt).
  • New items since my last review: reviewer 2's round-1 review (same head as mine, posted 24
    seconds earlier — I read it in full now, as round 2 requires), the author's two replies
    (09:39:02Z, 09:39:03Z), and commit 954b64be. I checked each reply's claims against the
    code; both hold.
  • The safety invariant of the new forms. Each form rewrites a string content as exactly
    {type: "text", text: X} with every other field nil, which CanonicalMessage's plainText
    collapses back to the string X. So SpanHash(form) == SpanHash(msgs), and a legacy match on
    any form implies the stored span canonicalizes equal to msgs. The same holds on the wire
    side: toolResultsAsTextBlocks builds the exact two-key block that
    CanonicalWireMessage's tool_result collapse inverts. The one exception is the invalid
    both-fields state, noted above and already flagged by reviewer 2.
  • toolResultsAsTextBlocks edge cases. A non-array content (including gjson's
    single-element Array() on a string) is caught by the final IsArray guard after the loop,
    so the sjson rewrite on a degenerate object is discarded, not returned. A string content
    re-embeds as c.Raw, so escapes stay valid. Indices stay stable because only values are
    replaced.
  • LegacySpanHashes edge cases. Empty span: one hash, no index access. One string
    message: no duplicate of the last-flipped form. Mutation safety: asTextBlock builds a new
    Content on a copy of the message; the caller's span is untouched.
  • The new tests. I traced every positive and negative case by hand:
    TestSpanHashMatchesAcceptsAnOldHashAcrossTheBlockToStringChange (the string-against-block
    direction needs no new form — a legacy hash over an all-string span equals its canonical
    hash, so the primary check already matches; the block-against-string and all-blocks cases
    need forms 2 and 3), TestASummaryCheckpointOverTheBlockFormIsReusedOnTheStringForm (with
    and without payload), and TestAnOldAnchorOverAToolResultBlockMatchesItsStringForm
    (last-only form covers the "last block" recording, all-form covers "every block").
  • No caller drift. All stored-hash comparisons still go through SpanHashMatches /
    summaryCoveredHashMatches / fingerprintMatches; the new LegacySpanHashes has exactly
    one production caller besides SpanHashMatches (the summarizer). No name collisions for the
    new functions in their packages; strconv is the only new import.
  • Repo rules. No behavior change beyond what round 1 already named: the fix widens when a
    stored pre-upgrade value matches, which is the PR's stated intent. Data dependence unchanged
    (nothing new stored). Live tests were not run (not approved); I read the author's report
    that -race passes on the eval box, and my own traces agree with the test outcomes.

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.

refactor: one canonical form of a message for every cross-request comparison

1 participant