Repository navigation
refactor(accwire): one wire adapter for the accountant integration - #1327
Conversation
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
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.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 noaccwire/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—responseInputIndexnow duplicates the Responses branch of
accwire.WireIndex, andapply/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 theWirevalue is "chosen once per request".
The proxy callsForon several bodies per request (client inbegin, forwarded inend,
client again inenvelopeOpsFor,preDeferin 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
- 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). - Behavior equivalence, the core claim. Old
accScanappliedresponsesSectionsto
every body. New code gates it behindFor(body) == responses. I checked thatFor
returnsresponsesexactly whenresponsesSectionschanges anything: both use
"messages not an array AND input is an array or a string", both read the first key of a
name (gjsonparseObjectreturns on the first hit;scanTopkeeps the first, and its
early stop requires a messages ARRAY, so it never stops beforeinputon a Responses
body). So per body, old and new hash the same positions. The state version stays 2,
correctly — the hash did not change. - Cross-body call sites.
envelopeOpsForand the proxy.goMessageOpscall 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, andbilledBodyonly stubs tool
definitions. Not reachable. WireIndexvs the functions it replaces. Messages branch is byte-for-byte
splitSlotPathwithout the remainder, including the negative-index acceptance
(messages.-1→ -1, true), sowireGroups(apply/apply.go:2350) is unchanged.
Responses branch isresponseInputIndexplus the olds.path == "input"special case of
responsesWire, so apply/responses.go:106 is unchanged.wireGroupsruns only on the
messages path;responsesWireonly on the Responses path.- 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 inproxy/accountant_wire_view_test.gocover every test use, with the old
signatures. - Import rules.
accwireimports no host package (proxy, proxyapp, dash), only
accountant,gjson,sjson,expandandinternal/adjudicate. I checked
expandandinternal/adjudicatetransitively import neitheraccwirenorapply,
soapply→accwire→expandcloses no cycle. The library/proxy boundary holds. unsafe.StringinFor. Guarded for empty input, nothing retains the string past
the call, gjson reads in place. Same read-only pattern the code already used.- 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
inaccwire/wire_test.go, including the wire-pick table and the mutation the PR
describes. - Tests were not run. Live tests are not approved for this review. Code read only.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.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 foraccwire/. Every other top-level package has one. CLAUDE.md points readers there for the layout. Add one row.accwire/wire.go:452—Messages.WireIndexsays ok for a negative index ("messages.-3"gives-3, true).Responses.WireIndexrejects negatives withi >= 0. The oldsplitSlotPathalso accepted negatives, so nothing changes. But the two implementations of one exported interface now disagree. Give both thei >= 0guard.proxy/accountant_parse_equiv_test.go— the reference copyoldAccBodiespredates the Responses wire (#899): it reads onlymessages, so the table has no Responses body. The one rule this PR moves (responsesSectionsnow runs only on the responses wire) has no old-vs-new reference test. The newaccwire/wire_test.goandproxy/accountant_responses_test.gocover 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—rootTTLOpsfalls back to anchor onmessages.0. On the Responses wire the positions come frominput, 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—Foradds onegjson.Getpass per body beforeParseon the hot path (begin/end).BenchmarkBeginEndUnchangedwatches this. The pass is cheap and stops at the firstmessageskey.
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
accScanappliedresponsesSectionsto every body. New code applies it only whenForpicked the responses wire.Forreturnsresponsesexactly whenresponsesSectionswould act:messagesis not an array andinputis an array or a string (accwire/wire.go:391,accwire/body.go:92). So each body routed throughForis read as before. - Duplicate keys.
Forusesgjson.Get;scanTopwalks keys itself with first-key-wins. I read gjson v1.18.0parseObject: it returns on the first key hit. The two agree, soForcannot pick a different wire thank.scanreads. - One wire for two bodies.
EnvelopeOpsandMessageOpsnow take the wire from the first body and scan both with it. The old code appliedresponsesSectionsto each body separately. These differ only if a pair of bodies changes wire shape (messagesarray becomesinput). No pipeline path does that: apply splices insidemessagesor insideinput, and the injections append totools. Inside the responses wire,responsesSectionsstill runs per body. applyparity.accwire.Messages.WireIndexmatches the oldsplitSlotPath(prefixmessages., cut at first dot,Atoi).accwire.Responses.WireIndexmatches the oldresponseInputIndexplus theinputstring case, including thei >= 0guard.responsesWireandwireGroupsresults 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 ispackage proxy. No duplicate declarations. - Boundaries.
accwireimports no host package (proxy,proxyapp,dash); its deps areexpand,internal/adjudicate,schema,store. No import cycle withapply, which now imports it. This improves the "library never imports proxy" rule (#1164). - State compatibility. The hash code moved byte for byte;
accStateVersionstays. Correct: a state file from before this PR hashes the same. - Data dependence. Unchanged: the
accountant-savingsrow describes behavior, not file paths. No doc names the moved files. - Fail open. No error path changed.
Foron invalid or empty JSON returns the messages wire, which gives an emptyBody, as before. - Tests. New tests cover
For,WireIndex, per-wire section reading,EnvelopeOpsper wire, and a ResponsesMessageOpsinsertion. 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]>
|
Fixed in 862b178 (notes 1 to 5), or kept with a reason.
Tests: build, vet, |
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 2 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.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):
docs/design.mdmissingaccwire/row — fixed. The row is added and reads right.responseInputIndex/splitSlotPathduplicateWireIndex— kept, reason accepted. The
author's reason: #1164 keeps the write side out, and the two apply functions are not pure
lookups —responseInputIndexreturns false for"input"whereWireIndexreturns 0, and
splitSlotPathalso 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.- "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:
design.mdrow — fixed (same as mine).Messages.WireIndexaccepts a negative index,Responses.WireIndexrejects it — kept,
with a comment. The reason: each branch keeps the result of the code it replaced
(splitSlotPathaccepted negatives,responseInputIndexdid 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.- No reference-style test for the wire gate — fixed.
TestOnlyTheResponsesWireReadsInput
covers it. I hand-traced all four assertions:Messagesgives 0 positions and 0 breakpoints
on amessages:nullbody with input;Responsesgives 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. - Pre-existing:
rootTTLOpsanchors onmessages.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-levelcache_controlis 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. Foradds a pass on the hot path — kept, with measurement. Accepted; the pass stops at
the firstmessageskey 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
Forcomment saysgjson.GetBytescopies the value it finds. I read gjson
v1.18.0getBytes: it converts the found value to astring(gjson.go:3310), which
allocates a copy — about the size of themessagesvalue on a 600 KB body. The
comment's claim and the measured +610 KB are consistent.unsafe.Stringstays the
right call. - The
WireIndexnegative-index comment matches what I verified in round 1. - The new test traced by hand, above.
- The
design.mdrow is accurate and sits with the other library packages.
- The
- Reviewer 1's round-1 review (posted after mine, so new to me). Read in full. Its five
- Tests were not run. Live tests are not approved for this review. Code read only.
amiddavid
left a comment
There was a problem hiding this comment.
| Reviewer | Kind | Started by | Context | Review | Round | Head | Verdict |
|---|---|---|---|---|---|---|---|
| Reviewer 1 (glm, user of @amiddavid) | GLM rits/zai-org/glm-5-3 via Claude Code 2.1.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):
docs/design.mdmissingaccwire/row — fixed. The row is there and reads right, including "Chosen once per body byaccwire.For".WireIndexnegative-index asymmetry — kept, with a reason I checked. The comment onaccwire/wire.go:139names the difference and why: each form keeps the result of the code it replaced (splitSlotPathaccepted negatives,responseInputIndexdid not). The reason is right. Adding thei >= 0guard now would be a behavior change for an unreachable input, and this repo needs a human's yes for that. Accept.- 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:Messageson amessages:nullbody gives 0 positions and no breakpoints;Responsesgives 2 positions (instructions, one input item) and one breakpoint on{messages, 0}; a body with amessagesarray reads as messages on both wires. All correct. The author also ran the mutation (gate removed) and says this test,TestWiresReadTheirOwnSectionsandTestEnvelopeOpsPerWirefail. I did not run it; the trace says it would. - Pre-existing
rootTTLOpsfallback onmessages.0— moved to #1340, kept here. Right call. The author adds that a Responses body carries no rootcache_control, soheadTTLRelabelledreturns nil before the fallback is reached. I checkedaccwire/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. Foradds one pass on the hot path — keptunsafe.String, reason in the code. The comment now saysgjson.GetBytescopies the value it finds. I read gjson v1.18.0getBytes(gjson.go:3295): it turnsresult.Rawinto a string withstring(*(*[]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.gocomments,accwire/wire_test.gonew test,docs/design.mdone row). - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files;
.review-in-inline.txtis 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.gogets comment text only, plus the doc fix "once per body", which now matches what the code does (Forruns per body inbegin,end,envelopeOpsForand thepreDefercall). TestOnlyTheResponsesWireReadsInputassertions traced by hand againstscanTop,responsesSections,parseandbreakpointsOf(see finding 3 above).- The gjson
GetBytescopy 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).
…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]>
Summary
The accountant reads each wire in one place now: the new
accwirepackage. 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
accwire. AWirevalue 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: nomessagesarray and aninputmeans Responses.git mvfromproxy/accountant_savings_body.goandproxy/accountant_envelope.go. The proxy callsaccwiredirectly.applyusesWireIndexinwireGroupsandresponsesWire.slotandresponseSlotare not merged. The write side is unchanged.accBodies,accParse,envelopeOps,messageOpsand others) stay as one-line helpers inproxy/accountant_wire_view_test.go. This keeps all existing tests without an edit.Two wire kinds, not three:
Messages(Anthropic Messages and Chat Completions) andResponses. 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 onorigin/main.TestCGLLMCostIsChargedToTheRequestThatSpentIt: failed once in the full run. It passes alone (5 runs) on this branch and onorigin/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.accwire/wire_test.go: wire pick,WireIndextable, per-wire sections, envelope ops, message splice.Responses.WireIndex("input")returned 1 instead of 0.accwireandapplytests fail. The code was restored.BenchmarkAccBodies, 600 KB body): 675 KB per call before and after, 51 allocs both. The wire pick reads the body in place withunsafe.String.gjson.GetBytescopies 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
Forusesunsafe.Stringon the body bytes for a read-only type check.gjson.ParseByteswould copy the whole body and double the allocation.parseCountedis nowWire.Parse(raw, count).countis the thinking-block price lookup.Review round 1: pre-existing Responses gap in
rootTTLOpsis accountant: rootTTLOps anchors on messages.0 on the Responses wire #1340. Not fixed here.