Skip to content

refactor(accwire): one wire adapter for the accountant integration - #1327

Merged
amiddavid merged 2 commits into
mainfrom
feat/mv-1164-accwire
Nov 24, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/mv-1164-accwire

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The accountant reads each wire in one place now: the new accwire package. It closes #1164. Part of #1309.

This is PR 1 of a stack of 2. PR 2 (#1303) is based on this branch.

What changed

  • New package accwire. A Wire value holds the four reads of a wire: Body/Parse, Breakpoints, EnvelopeOps/MessageOps, WireIndex.
  • accwire.For(raw) picks the wire once per body. The pick uses the old rule: no messages array and an input means Responses.
  • The code moved with git mv from proxy/accountant_savings_body.go and proxy/accountant_envelope.go. The proxy calls accwire directly.
  • apply uses WireIndex in wireGroups and responsesWire. slot and responseSlot are not merged. The write side is unchanged.
  • The old proxy names (accBodies, accParse, envelopeOps, messageOps and others) stay as one-line helpers in proxy/accountant_wire_view_test.go. This keeps all existing tests without an edit.
  • The accountant library is unchanged.

Two wire kinds, not three: Messages (Anthropic Messages and Chat Completions) and Responses. The two message wires read the same in all four places today. A body cannot tell them apart. A wire that reads differently gets its own kind.

Behaviour

None. No existing test changed.

Data dependence

Same as before. The move adds no feature and no component. No docs/data-dependence/ row changes.

How it was tested

macOS, Go 1.27.4.

  • go build ./... && go vet ./... && gofmt -l .: clean.
  • go test ./accwire ./apply ./proxy ./proxyapp ./cmd/...: pass. Two failures, both not from this change:
    • TestNoHooksKeepsTheBinaryDefaults: known failure on origin/main.
    • TestCGLLMCostIsChargedToTheRequestThatSpentIt: failed once in the full run. It passes alone (5 runs) on this branch and on origin/main. It is a timing flake.
  • CGO_ENABLED=1 go test -race -timeout 30m ./proxy/... ./accwire: no data race. TestMetricsCallLatency (a p99 timing test) failed once while the laptop was loaded. It passes alone with -race (3 runs).
  • CGO_ENABLED=1 go test -race ./apply ./accwire: pass.
  • New tests in accwire/wire_test.go: wire pick, WireIndex table, per-wire sections, envelope ops, message splice.
  • Mutation: Responses.WireIndex("input") returned 1 instead of 0. accwire and apply tests fail. The code was restored.
  • Benchmark (BenchmarkAccBodies, 600 KB body): 675 KB per call before and after, 51 allocs both. The wire pick reads the body in place with unsafe.String. gjson.GetBytes copies the value it finds: it measured 1288 KB per call and no faster, so it is not used. Time is within laptop noise (about 5 to 8 ms both).

Technical notes

  • For uses unsafe.String on the body bytes for a read-only type check. gjson.ParseBytes would copy the whole body and double the allocation.

  • parseCounted is now Wire.Parse(raw, count). count is the thinking-block price lookup.

  • Review round 1: pre-existing Responses gap in rootTTLOps is accountant: rootTTLOps anchors on messages.0 on the Responses wire #1340. Not fixed here.

Move the accountant's body parsing, cache-mark reading and envelope
diff out of proxy/ into the new accwire package. A Wire value, chosen
once per body by accwire.For, holds the four reads of a wire: Body and
Parse, Breakpoints, EnvelopeOps and MessageOps, and WireIndex.

apply uses WireIndex for wireGroups and responsesWire. The write-side
slot types stay as they are. No behaviour change.

Closes #1164
Refs #1309

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.331 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 d04aa181532f approve

Verdict: approve

Findings

None. I tried to break the equivalence claim ("Behaviour: None") and could not, on any
input the proxy can produce. The trace is under "What I checked", point 2.

Non-blocking

  • docs/design.md — the package map has no accwire/ row. Every other top-level package
    (thinkcount/, thread/, models/, ...) has one. The map is the layout doc CLAUDE.md
    points to. Add one row: "reads a request body for the accountant, one adapter per wire".
  • apply/responses.go:130 — responseInputIndex now duplicates the Responses branch of
    accwire.WireIndex, and apply/apply.go:2306 (splitSlotPath) duplicates the messages
    branch. The PR says the write side stays out on purpose, so this is scope, not a defect.
    But a later edit to one copy can silently diverge from the other. Worth a follow-up issue
    when PR 2 of the stack touches the write side.
  • accwire/wire.go:24 — the package doc says the Wire value is "chosen once per request".
    The proxy calls For on several bodies per request (client in begin, forwarded in end,
    client again in envelopeOpsFor, preDefer in proxy.go). Each call is correct — the pick
    is per body, as before — but the doc reads stronger than the code. The PR's benchmark says
    the extra scans cost nothing measurable.

What I checked

  1. Full diff read. All 11 files, every changed line, plus the code around each change
    (accwire/body.go, accwire/envelope.go, accwire/wire.go, the four proxy call sites,
    the two apply call sites, both new test files).
  2. Behavior equivalence, the core claim. Old accScan applied responsesSections to
    every body. New code gates it behind For(body) == responses. I checked that For
    returns responses exactly when responsesSections changes anything: both use
    "messages not an array AND input is an array or a string", both read the first key of a
    name (gjson parseObject returns on the first hit; scanTop keeps the first, and its
    early stop requires a messages ARRAY, so it never stops before input on a Responses
    body). So per body, old and new hash the same positions. The state version stays 2,
    correctly — the hash did not change.
  3. Cross-body call sites. envelopeOpsFor and the proxy.go MessageOps call now pick
    the wire from ONE body (client / preDefer) and scan both. Old code scanned each body on
    its own. These differ only if the proxy turns a messages-wire body into a Responses-shaped
    one mid-request. It does not: apply routes Responses bodies to the Responses adapter
    (apply/apply.go:395), rewrites happen in place, and billedBody only stubs tool
    definitions. Not reachable.
  4. WireIndex vs the functions it replaces. Messages branch is byte-for-byte
    splitSlotPath without the remainder, including the negative-index acceptance
    (messages.-1 → -1, true), so wireGroups (apply/apply.go:2350) is unchanged.
    Responses branch is responseInputIndex plus the old s.path == "input" special case of
    responsesWire, so apply/responses.go:106 is unchanged. wireGroups runs only on the
    messages path; responsesWire only on the Responses path.
  5. No dangling references. No non-test file in proxy/, proxyapp/, dash/, cmd/,
    components/, adapters/ uses the moved names (accBodies, accParse, envelopeOps,
    messageOps, withoutCacheMarks, ...). Only comments mention them. The one-line
    wrappers in proxy/accountant_wire_view_test.go cover every test use, with the old
    signatures.
  6. Import rules. accwire imports no host package (proxy, proxyapp, dash), only
    accountant, gjson, sjson, expand and internal/adjudicate. I checked
    expand and internal/adjudicate transitively import neither accwire nor apply,
    so apply → accwire → expand closes no cycle. The library/proxy boundary holds.
  7. unsafe.String in For. Guarded for empty input, nothing retains the string past
    the call, gjson reads in place. Same read-only pattern the code already used.
  8. Hard rules. Fail-open paths untouched (no component logic moved). No data-dependence
    change (pure move; the PR says so and the diff agrees). No behavior change needing a
    human's yes, per point 2. New seams (For, WireIndex, per-wire sections) have tests
    in accwire/wire_test.go, including the wire-pick table and the mutation the PR
    describes.
  9. Tests were not run. Live tests are not approved for this review. Code read only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None. The change moves the accountant's wire reading from proxy into the new library package accwire, behind one Wire interface. I could not find a case where behavior changes.

Non-blocking

  • docs/design.md — the package map has no row for accwire/. Every other top-level package has one. CLAUDE.md points readers there for the layout. Add one row.
  • accwire/wire.go:452 — Messages.WireIndex says ok for a negative index ("messages.-3" gives -3, true). Responses.WireIndex rejects negatives with i >= 0. The old splitSlotPath also accepted negatives, so nothing changes. But the two implementations of one exported interface now disagree. Give both the i >= 0 guard.
  • proxy/accountant_parse_equiv_test.go — the reference copy oldAccBodies predates the Responses wire (#899): it reads only messages, so the table has no Responses body. The one rule this PR moves (responsesSections now runs only on the responses wire) has no old-vs-new reference test. The new accwire/wire_test.go and proxy/accountant_responses_test.go cover it against hand-written values. A Responses case in a reference-style test would guard the wire gate itself.
  • Pre-existing, not from this PR: accwire/envelope.go:85 — rootTTLOps falls back to anchor on messages.0. On the Responses wire the positions come from input, so that fallback names no position and the op is dropped. The old code had the same fallback. Worth its own issue if a Responses body ever reaches it with no system and no tools.
  • accwire/wire.go:391 — For adds one gjson.Get pass per body before Parse on the hot path (begin/end). BenchmarkBeginEndUnchanged watches this. The pass is cheap and stops at the first messages key.

What I checked

  • Read the full diff (30a80767..HEAD, one commit) and the final state of every changed file.
  • Behavior parity of the wire gate. Old accScan applied responsesSections to every body. New code applies it only when For picked the responses wire. For returns responses exactly when responsesSections would act: messages is not an array and input is an array or a string (accwire/wire.go:391, accwire/body.go:92). So each body routed through For is read as before.
  • Duplicate keys. For uses gjson.Get; scanTop walks keys itself with first-key-wins. I read gjson v1.18.0 parseObject: it returns on the first key hit. The two agree, so For cannot pick a different wire than k.scan reads.
  • One wire for two bodies. EnvelopeOps and MessageOps now take the wire from the first body and scan both with it. The old code applied responsesSections to each body separately. These differ only if a pair of bodies changes wire shape (messages array becomes input). No pipeline path does that: apply splices inside messages or inside input, and the injections append to tools. Inside the responses wire, responsesSections still runs per body.
  • apply parity. accwire.Messages.WireIndex matches the old splitSlotPath (prefix messages., cut at first dot, Atoi). accwire.Responses.WireIndex matches the old responseInputIndex plus the input string case, including the i >= 0 guard. responsesWire and wireGroups results are unchanged.
  • No leftover callers. I grepped the repo for every moved name. No production file calls them. The old names live on only in proxy/accountant_wire_view_test.go, and every test file that uses them is package proxy. No duplicate declarations.
  • Boundaries. accwire imports no host package (proxy, proxyapp, dash); its deps are expand, internal/adjudicate, schema, store. No import cycle with apply, which now imports it. This improves the "library never imports proxy" rule (#1164).
  • State compatibility. The hash code moved byte for byte; accStateVersion stays. Correct: a state file from before this PR hashes the same.
  • Data dependence. Unchanged: the accountant-savings row describes behavior, not file paths. No doc names the moved files.
  • Fail open. No error path changed. For on invalid or empty JSON returns the messages wire, which gives an empty Body, as before.
  • Tests. New tests cover For, WireIndex, per-wire section reading, EnvelopeOps per wire, and a Responses MessageOps insertion. The existing proxy tests keep their wrappers.
  • I did not run builds or tests: live tests were not approved for this review.

- Say "once per body" in the package doc.
- Explain why For reads the body in place (GetBytes copies it).
- Name the negative-index difference between the two WireIndex forms.
- Test that only the Responses wire reads input.
- Add accwire to docs/design.md.

Refs #1164
Refs #1309

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

Copy link
Copy Markdown
Collaborator Author

Fixed in 862b178 (notes 1 to 5), or kept with a reason.

  1. Kept unsafe, with the reason in the code. I tried gjson.GetBytes. BenchmarkAccBodies (600 KB body): 1288 KB and 51 allocs per call, against 674 KB and 50 with unsafe.String (and 675 KB on origin/main). GetBytes copies the value it finds. Time was the same within noise (about 4.5 ms vs 5 ms).
  2. Fixed: "chosen once per body".
  3. Fixed: a comment on Messages.WireIndex names the negative-index difference. Both results are kept. No slot path is negative.
  4. Fixed: TestOnlyTheResponsesWireReadsInput. Mutation: make kind.scan call responsesSections for every kind. This test, TestWiresReadTheirOwnSections and TestEnvelopeOpsPerWire fail. Code restored.
  5. Fixed: docs/design.md has the accwire/ row. The accrec/ row is in refactor(accrec): move the accountant glue out of the proxy #1337.
  6. Opened accountant: rootTTLOps anchors on messages.0 on the Responses wire #1340. Not fixed here. It may not occur, because a Responses body carries no root cache_control. A fix would be a behaviour change for a human to decide.
  7. Kept. Refactor: one wire adapter for the accountant integration #1164 keeps the write side out. responseInputIndex is used by the summary-span code (apply/responses.go:150-317) and its "input" case differs from WireIndex (false vs 0). splitSlotPath returns the relative path that the write code uses. Neither is a pure read-side lookup, so neither calls accwire. wireGroups and responsesWire do.

Tests: build, vet, gofmt -l clean. go test ./accwire ./apply ./proxy (the touched parts) pass. go test -race ./accwire passes. macOS, Go 1.27.4.

@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.331 offload-review skill, @amiddavid's session resumed 2 of 2 2 of 2 862b17898a6e approve

Verdict: approve

Findings

None. The new commit changes comments, docs and tests only. No code path changed.

Status of the earlier findings

Mine (all non-blocking, round 1):

  1. docs/design.md missing accwire/ row — fixed. The row is added and reads right.
  2. responseInputIndex / splitSlotPath duplicate WireIndex — kept, reason accepted. The
    author's reason: #1164 keeps the write side out, and the two apply functions are not pure
    lookups — responseInputIndex returns false for "input" where WireIndex returns 0, and
    splitSlotPath also returns the relative path the write code uses. I checked both claims
    against the code in round 1; they are right. Divergence risk stays a follow-up for PR 2.
  3. "Chosen once per request" doc — fixed. Now "once per body".

Reviewer 1's (all non-blocking, round 1). I checked each myself before accepting the author's
answer:

  1. design.md row — fixed (same as mine).
  2. Messages.WireIndex accepts a negative index, Responses.WireIndex rejects it — kept,
    with a comment
    . The reason: each branch keeps the result of the code it replaced
    (splitSlotPath accepted negatives, responseInputIndex did not), and no slot path is
    negative. I verified both old behaviors in round 1. Making the two agree would be a
    behavior change, which this repo routes through a human. Reason is right.
  3. No reference-style test for the wire gate — fixed. TestOnlyTheResponsesWireReadsInput
    covers it. I hand-traced all four assertions: Messages gives 0 positions and 0 breakpoints
    on a messages:null body with input; Responses gives 2 positions and one breakpoint on
    the input item; a body with a messages array reads as messages on both wires. All correct.
    The reported mutation (gate removed → three tests fail) matches what the test asserts.
  4. Pre-existing: rootTTLOps anchors on messages.0, which names no position on the
    Responses wire — deferred to #1340, accepted. I read the issue. It states the case and
    the risk honestly. The reason a fix is not here is right: a top-level cache_control is an
    Anthropic feature, a Responses body carries none today, and booking a premium that was not
    booked is a behavior change that needs a human's yes.
  5. For adds a pass on the hot path — kept, with measurement. Accepted; the pass stops at
    the first messages key and the PR's benchmark shows no regression.

What I checked

  • Last review: round 1, d04aa18, 2026-11-24T09:39:05Z.
  • New commits read: 1 — 862b1789 "refactor(accwire): address review notes"
    (3 files: accwire/wire.go, accwire/wire_test.go, docs/design.md; 31 insertions,
    3 deletions).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files).
  • New items since my last review, and what I did about each:
    • Reviewer 1's round-1 review (posted after mine, so new to me). Read in full. Its five
      notes overlap mine on two points; the other three are addressed above.
    • The author's reply comment. Read in full. Checked every claim in it against the code or
      the gjson source.
    • Commit 862b1789. Full diff read, plus each changed file around the change:
      • The For comment says gjson.GetBytes copies the value it finds. I read gjson
        v1.18.0 getBytes: it converts the found value to a string (gjson.go:3310), which
        allocates a copy — about the size of the messages value on a 600 KB body. The
        comment's claim and the measured +610 KB are consistent. unsafe.String stays the
        right call.
      • The WireIndex negative-index comment matches what I verified in round 1.
      • The new test traced by hand, above.
      • The design.md row is accurate and sits with the other library packages.
  • Tests were not run. Live tests are not approved for this review. Code read only.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Verdict: approve

Findings

None. The new commit changes comments, adds one test, and adds one doc row. No code path changed.

Earlier findings, round 1

Mine (all non-blocking):

  1. docs/design.md missing accwire/ row — fixed. The row is there and reads right, including "Chosen once per body by accwire.For".
  2. WireIndex negative-index asymmetry — kept, with a reason I checked. The comment on accwire/wire.go:139 names the difference and why: each form keeps the result of the code it replaced (splitSlotPath accepted negatives, responseInputIndex did not). The reason is right. Adding the i >= 0 guard now would be a behavior change for an unreachable input, and this repo needs a human's yes for that. Accept.
  3. No old-vs-new reference test for the wire gate — fixed, better than asked. TestOnlyTheResponsesWireReadsInput (accwire/wire_test.go:104) pins the gate itself. I traced each assertion: Messages on a messages:null body gives 0 positions and no breakpoints; Responses gives 2 positions (instructions, one input item) and one breakpoint on {messages, 0}; a body with a messages array reads as messages on both wires. All correct. The author also ran the mutation (gate removed) and says this test, TestWiresReadTheirOwnSections and TestEnvelopeOpsPerWire fail. I did not run it; the trace says it would.
  4. Pre-existing rootTTLOps fallback on messages.0 — moved to #1340, kept here. Right call. The author adds that a Responses body carries no root cache_control, so headTTLRelabelled returns nil before the fallback is reached. I checked accwire/envelope.go:75: the fallback only runs after that check, so it is unreachable on the Responses wire today. A fix would be a behavior change for a human to decide.
  5. For adds one pass on the hot path — kept unsafe.String, reason in the code. The comment now says gjson.GetBytes copies the value it finds. I read gjson v1.18.0 getBytes (gjson.go:3295): it turns result.Raw into a string with string(*(*[]byte)(...)), a real copy, whenever the value has Raw data. The reason is accurate and measured. Accept.

Reviewer 2's notes: the design.md row (same as mine, fixed) and two keeps. On the kept duplicate responseInputIndex / splitSlotPath: I checked the author's reason myself. responseInputIndex("input") returns false (accwire's WireIndex returns 0, true), and responsesSummarySpanSafe relies on that false; splitSlotPath returns the relative path the write side splices by. Neither is a pure read-side lookup. The reason is right. Agree with the author, no finding.

Non-blocking

None new.

What I checked

  • Last review: round 1, d04aa181532f15a5cd34d9c79fba111f5efdaa11, 2026-11-24T09:39:46Z.
  • New commits read: 1 (862b1789 "refactor(accwire): address review notes": accwire/wire.go comments, accwire/wire_test.go new test, docs/design.md one row).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files; .review-in-inline.txt is empty).
  • New items since my last review: reviewer 2's round-1 review (09:39:05Z, read in full, verdict approve, no findings for me to re-check beyond the keeps above); the author's reply (09:48:03Z, all 7 points checked as above); commit 862b1789 (full diff and final file state read).
  • The new commit touches no code path: wire.go gets comment text only, plus the doc fix "once per body", which now matches what the code does (For runs per body in begin, end, envelopeOpsFor and the preDefer call).
  • TestOnlyTheResponsesWireReadsInput assertions traced by hand against scanTop, responsesSections, parse and breakpointsOf (see finding 3 above).
  • The gjson GetBytes copy claim verified in the gjson v1.18.0 source.
  • I did not run builds or tests: live tests are not approved for this review. The author reports them green (macOS, Go 1.27.4).

@amiddavid
amiddavid merged commit 807d217 into main Nov 24, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 24, 2026
amiddavid added a commit that referenced this pull request Nov 24, 2026
…xy (1/2) (#1328)

refactor(keepalive): move keep-alive policy resolution out of the proxy

The proxy chose the keep-alive policy. A host that called Keeper.Record
directly got different pings.

Move the rules into package keepalive:
- Resolve: account, manager strategy, ignore-windows retry, campaign,
  session override, and the OpenAI idle rule.
- Strategy pick and apply: BestStrategy, BetterStrategy, ApplyStrategy,
  ResolveHeadTTL, StrategyTZ, and the strategy bound checks.
- Override type, bounds, validation and apply, with one idle band check
  shared by strategies and overrides.
- FromConfig (was proxyapp cachePolicy) and EffectiveWaitPlan (was the
  body of DashWaitPolicy).
- keepalive now reads config.HeadTTLBytesPerToken instead of its own copy.

The proxy keeps the strategy list, the overrides map and its lock, the
control routes and the arm limits. Its old unexported names stay as thin
shims so the existing tests run unchanged.

No behaviour change. Refs #1301, #1309.

refactor(keepalive): fix review notes on the policy move

- The proxy keeps its own copy of the predictor id set; the library
  returns a copy (KnownPredictorIDs) and checks a given set
  (ValidPredictorRefIn).
- Name OneHourIdleFloor for the 300 s literal in EffectiveWaitPlan.
- Fix a test comment about the keepalive to config import.


No behavior change (a move into a library package). Integrator check on current main + #1327 + #1328: build, vet, accwire/keepalive/apply tests and the proxy accountant and keep-alive tests pass. Secret scan by hand: 0 findings.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
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 wire adapter for the accountant integration

1 participant