Skip to content

refactor(accrec): move the savings tracker and the ping store out of proxy - #1370

Merged
amiddavid merged 4 commits into
mainfrom
feat/mv-1303-tracker
Nov 24, 2026
Merged

amiddavid merged 4 commits into
mainfrom
feat/mv-1303-tracker

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #1303, #1309. Does not close #1303 (see "Left in the proxy").

Summary

The savingsTracker moves out of proxy/ into accrec.Recorder. The ping store moves to accrec.PingStore. The proxy keeps the state file, the log lines, the metrics and the HTTP wiring.

What changed

  • accrec.Recorder: Begin, End, Compute, ComputeSafe (fail open), Drop, thinking counts, the rescue-facts-missing counter, and the per-thread stores (trackers, siblings, billed tiers).
  • accrec.Recorder.Price: the finish-time rules. It takes usage, status, rounds, the earlier no-result reason and the thread. It returns a result or a fallback reason (rejected_status, deferral_unplaced, compute_panicked). It also counts a request that followed pings and found no ping facts, and spends the ping facts it read.
  • accrec.Recorder.SnapshotState and RestoreState: the state format (StateFile, version 2) and the age rules. RestoreState returns what happened. The proxy logs it with the same lines as before.
  • accrec.ThreadOf: thread id and parent mapping.
  • accrec.PingStore: bounded map (4096), Put, Peek, Take, Drop, Priced.
  • proxy/accountant_savings.go: a thin host type. It embeds the Recorder and keeps the Usage conversion.
  • proxy/accountant_state.go: file I/O only (temp file, sync, rename, dedupe of unchanged writes, the periodic save).
  • proxy/dashcapture.go: only the accountant block of finish (it calls Price). Nothing else.

Left in the proxy

Behaviour

None. The figures are the same. The side-effect order in finish is the same: compute, event and metrics, rescue counter, ping-facts drop (Price has an AfterCompute hook for the second step).

Test edits (all mechanical, no assertion changed)

  • accountant_ping_test.go: put/take/drop/peek became Put/Take/Drop/Peek, and len(st.m) became st.Len(). The two tests of the store itself (TestPingStoreTakeDeletes..., TestPingStoreIsBounded) moved to accrec/pingstore_test.go.
  • accountant_wire_test.go: s.trackers = nil became s.Trackers = nil (2 lines). The field is now the Recorder's.

Data dependence

Same as before. The Recorder keeps hashes, sizes and token counts. It keeps no message text. No change at any storage level (off, metadata only, everything). docs/data-dependence.md needs no edit.

How it was tested

macOS, Go 1.27.4. Load average was about 380 during all runs.

  • go build ./..., go vet ./..., gofmt -l .: clean. Same with -tags cg_record.
  • go test ./accrec ./proxy: pass.
  • go test ./proxyapp ./cmd/cg-cache-campaign ./cmd/cg-selarm: pass, except TestNoHooksKeepsTheBinaryDefaults (known failure on origin/main).
  • go test -race ./accrec: pass.
  • Owed: go test -race ./proxy/.... I did not run it, because the load was above 50.
  • New: proxy/accountant_replay_test.go replays 6 requests on 2 threads, with a replayed change, a client edit and a save and restore between them. It compares a hash of each booked Result. I took the hashes on origin/main before the move. The test passes on the moved code with the same hashes.
  • New: accrec/recorder_test.go, accrec/pingstore_test.go.
  • Mutation 1: I removed the ping-facts drop in Price. TestPrice failed ("the ping facts the request read must be spent").
  • Order test: TestPrice checks that AfterCompute runs before the rescue counter and the ping-facts drop. Swapping the order fails it.
  • Mutation 2: I changed the age check to StateMaxAge-time.Minute. TestStateRoundTripAndRefusals failed.

Technical notes

  • Recorder.Trackers, Clients and OnEnd are exported so a host test can break or watch them.
  • The proxy type keeps thinking, billed1h and clients as views of the Recorder's pieces, so existing host code and tests read them unchanged.

…proxy

The savingsTracker becomes accrec.Recorder: begin, end, compute, the fail-open
compute, the finish-time pricing rules (Price) and the restart state format and
age rules. The ping store becomes accrec.PingStore. The proxy keeps the state
file I/O, the log lines, the Usage type and the HTTP wiring, and calls them.

No behaviour change. A replay test pins the booked figures of a fixed request
set, taken on origin/main before the move.

Refs #1303, #1309

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
Price gains an AfterCompute hook. The host books the event and the metrics
there, before the rescue counter and the ping-facts drop, as before the move.
A test pins the order.

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 0569091dd0cb approve

Verdict: approve

Findings

None. The move keeps behavior. I traced each path old against new (details under "What I checked").

Non-blocking

  • Test debt before merge. The PR body says go test -race ./proxy/... is owed. scripts/dev/local-tests.sh 1370 is also still needed at the final head (CLAUDE.md, "A PR is ready when"). Run both before the hand-off.
  • docs/design.md:20 — the accrec/ row does not name the new contents. The row lists the glue rules. The package now also holds the request recorder (Begin/End/Price) and the state-file format. One added clause would fix it.
  • accrec/state.go:685 — the error text says "proxy version". The message moved into the library, where any host reads it. Say "state file version" instead.
  • accrec/recorder_test.go:531 — the subtest name promises more than it checks. "Several rounds book nothing and keep the earlier reason" passes NoResult: "", so no earlier reason exists to keep. Pass a non-empty NoResult or rename it.
  • accrec/pingstore.go:79 — Take is Peek then Drop, not one atomic step. A ping stored between the two calls is dropped by the Drop(key, "") of the missed Peek. Pre-existing: the old proxy take had the same shape. No change in this PR.

What I checked

  • Read the full diff of all 13 files, and the code around each change in accrec/, proxy/ and thread/.
  • Side-effect order of finish (the PR's main claim). I compared the base proxy/dashcapture.go finish block against accrec.Recorder.Price line by line. Old order: ShouldCompute gate, accBilledTTL, computeSafe, event + metrics on success, ComputePanicked on panic, rescue counter, ping-facts drop — all only when compute runs. New order in Price: same gate (early return keeps the ping facts and skips the rescue counter, as before), BeforeCompute (= accBilledTTL), ComputeSafe, AfterCompute (= event + metrics) only on success, ComputePanicked on panic, rescue counter, ping-facts drop. c.accNoResult = out.NoResult lands the same values: why when gated, the earlier reason when priced, ComputePanicked on panic. The order test in TestPrice pins this.
  • Nil-safety and fail-open. c.savings.Price runs only when c.accReq != nil, and accReq is set only on a path that requires c.savings != nil (accBegin/accEnd/accRun), so the promoted-method call cannot meet a nil savings tracker. recordThinking, drop, RescueFactsMissing keep their nil checks. ComputeSafe keeps the recover-and-log of the old computeSafe. A nil *PingStore passed as the PingSink still works: its methods are nil-safe, as the old pingSink wrapper was.
  • State save and restore parity. save now calls SnapshotState, which marshals the same StateFile (version 2, snapshot, thinking). restore keeps the same log lines and the same decisions in the same order: read error, ThinkingMaxAge gate, thinking counts restored even when the snapshot is refused or too old, StateMaxAge gate, Trackers.Restore error. The proxy constants alias the accrec ones, so no value changed.
  • Ping store. The exported Put/Peek/Take/Drop/Priced are the old unexported methods, byte for byte in logic, bound still 4096 with the same eviction. proxy.PingSavings passes the store itself as the sink; the interface change is behavior-neutral (checked NotePriced and the manual-ping rule in accrec/ping.go).
  • ThreadOf in proxy/accountant_wire.go. Same mapping as the old inline code (thread.Result.InheritsFrom returns (string, bool); verified in thread/thread.go:103).
  • Compile-level checks by grep (live builds are not approved for this review): no leftover use of the removed put/peek/take/drop/notePriced/pingSink/pingStoreMax in non-test proxy code; s.clients, s.billed1h, s.thinking, s.onEnd view fields still have all their users; proxyapp uses proxy.NewPingStore, which still exists; the replay test's helpers (msg, body, rewriteOp, accFacts, mustMsg) all exist in proxy/accountant_savings_test.go; no import cycle (accrec imports only accountant, accwire, thinkcount, components).
  • Rules. Business logic (compute gate, pricing, state rules, ping facts) moved out of the host into accrec — the direction CLAUDE.md asks for. The PR names its data dependence (unchanged, metadata only) and claims no behavior change; my trace confirms both. New tests use no sleeps, so timingguard is safe.

@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 0569091dd0cb approve

Verdict: approve

Findings

None. The PR moves code, it does not change behavior. I checked each move against the base
commit line by line. Details under "What I checked".

Non-blocking

  • docs/design.md:20 — the accrec/ row does not name the three pieces this PR adds: the
    Recorder, the PingStore and the state-file format. The row still reads true ("the
    accountant's glue rules, shared by every host"), but a reader looking for where the restart
    state lives will not find it from the table.
  • accrec/state.go:31 — RestoreState's version-mismatch error says "state file has proxy
    version". The rule now lives in a library shared by every host, so "proxy" is the wrong word
    in a log an operator reads. The string also matches the old one, so changing it is cosmetic
    only.
  • accrec/pingstore.go:79 — Take is Peek then Drop under two lock holds. A Put between
    them is dropped by the empty window even though no request read it. The race existed before
    the move, and Take now has no production caller (the request path uses Peek at open and
    Drop with the read window at price). Test-only, so I leave it as a note.
  • accrec/recorder.go:361 — PriceIn.Pings is the concrete *PingStore, while PingSavings
    takes the PingSink interface. A host with its own sink cannot reuse Price. No host needs
    that today; worth an interface only when one does.

What I checked

  • Read the full diff (1d20435f..0569091d, 13 files) and docs/design.md.
  • The move is verbatim. I compared every moved function against the base commit
    (git show 1d20435f:proxy/...): begin/end/compute/computeSafe/drop/
    recordThinking/noteRescueFactsMissing (accountant_savings.go), all six PingStore
    methods and the 4096 bound (accountant_ping.go), and the save/restore logic
    (accountant_state.go). Only receiver and field names changed. The state-file JSON tags and
    StateVersion = 2 are unchanged, so old files still restore.
  • The finish order is kept. I diffed the old finish block (dashcapture.go) against
    Recorder.Price plus the BeforeCompute/AfterCompute hooks step by step: accBilledTTL
    before compute, event and metrics only when priced, rescue counter (kaPings > 0 && pingWindow == "") and ping-facts drop after them, accNoResult set the same way on each
    branch (rejected, deferral, rounds, panic). Commit 2 fixed the one order change commit 1 had
    introduced (event booked after the drop); the head is correct.
  • Fail-open paths survive. ComputeSafe keeps its recover; PingSavings keeps its recover;
    accRun keeps its recover and Drop. Nil-safe receivers are kept: a nil *PingStore passed
    as the PingSink interface is a typed nil, and NotePriced/Put stay no-ops — the same
    semantics the old pingSink wrapper had.
  • Keys match. Price drops with PingKey(Session, Thread); the capture passes
    c.accThread, which accEndNow sets from ThreadOf(th.ID,...).ID — the same mapped id
    entryFacts read with. ThreadOf is the old inline parent logic, unchanged.
  • External wiring still compiles by alias. proxyapp uses proxy.NewPingStore,
    proxy.PingSavings and Options.Pings; all three are now aliases or thin wrappers over
    accrec. promexport.go reads Priced() on the same store.
  • Tests cover the new code. TestPrice (six subtests, including the side-effect order and
    the panic path), TestPingStore*, TestStateRoundTripAndRefusals,
    TestReplayBooksTheSameFigures (pins the booked figures across the move),
    TestFinishSpendsThePingFactsOnlyWhenItPrices in the proxy. The moved tests were kept, not
    dropped.
  • Hard boundaries. accrec imports no host package; the proxy keeps only file I/O, log
    lines, the Usage type and wiring. This is the direction CLAUDE.md asks for (the Cortex
    test). No data-dependence change: the state file holds the same metadata, and the
    accountant-savings row stays true.
  • I did not run tests or builds; this review is from reading the code only.

…kept reason

Round 1 notes of #1370. The several-rounds subtest now passes a non-empty
NoResult and checks that Price keeps it.

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

Copy link
Copy Markdown
Collaborator Author

Round 1 notes, fixed in the new head.

  1. docs/design.md: the accrec/ row now names the Recorder (Begin/End/Price), the PingStore, and the state-file format. Fixed.
  2. The several-rounds subtest now passes NoResult: "earlier_reason" and checks that Price keeps it. Mutation: I made ShouldCompute return an empty reason for several rounds. The subtest failed (noResult=""). Fixed.

Kept as they are:

  • The "proxy version" error text in accrec/state.go: it matches the old string. A change to a message an operator reads is a separate decision.
  • PingStore.Take as Peek then Drop: this is the old code, moved as it was. It has no production caller.
  • PriceIn.Pings as the concrete type: no host needs another sink yet. A host that does can change it then.

Tests: build and vet are clean, with and without -tags cg_record. I did not run the unit tests. The load average is above 300.

@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 d901ba6b35e5 approve

Verdict: approve

Findings

None. The new commit changes one test and one doc line. No code path changes.

Earlier findings, this round's state

  • design.md accrec/ row (mine, and reviewer 1's) — fixed. The row now names the Recorder (Begin/End/Price), the PingStore and the state-file format (docs/design.md:20).
  • "Several rounds" subtest (mine) — fixed. It now passes NoResult: "earlier_reason" and asserts Price keeps it (accrec/recorder_test.go:127). I traced it: ShouldCompute(200, 2, "earlier_reason") returns (false, "earlier_reason"), so the assertion pins the kept reason. The author's mutation (empty reason from several rounds) failed the test, which confirms it checks something.
  • "proxy version" error text (mine, and reviewer 1's) — rejected by the author. Reason: the string matches the old one, and changing an operator-facing message is a separate decision. I accept the reason. The string is identical to the base commit's, so no behavior changed.
  • Take as Peek then Drop (mine, and reviewer 1's) — rejected by the author. Reason: old code moved as it was, no production caller. I checked: grep for .Take( over accrec, proxy, proxyapp, cmd, adapters, dash finds no non-test caller. I accept.
  • PriceIn.Pings concrete type (reviewer 1's) — rejected by the author. Reason: no host needs another sink yet. I checked PriceIn users: only proxy/dashcapture.go passes c.pings. I accept. Agree with reviewer 1, finding 4; nothing to add.
  • Owed test runs (mine) — still open. See Non-blocking.

Non-blocking

  • Test debt before merge. The author's comment says build and vet are clean, but the unit tests were not run at the new head, and go test -race ./proxy/... and scripts/dev/local-tests.sh 1370 are still owed. CLAUDE.md requires the heavy tests at the final head before the hand-off. The new head changed a test file, so the earlier runs (had they existed) would not cover it.

What I checked

  • Last review: round 1, 0569091, 2026-11-24T17:59:09Z.
  • New commits read: 1 (d901ba6b "docs(accrec): name the Recorder, PingStore and state format; pin the kept reason").
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files in my folder).
  • New items since my last review, and what I did about each:
    • Reviewer 1's round-1 review (18:00:15Z, approve, no findings): read in full. Their four non-blocking notes overlap my round-1 notes on three points; the fourth (PriceIn.Pings concrete type) I checked myself above.
    • Author's comment (18:02:16Z): read in full. Two fixes, three rejections with reasons — each checked above.
    • Commit d901ba6b: read the full diff. accrec/recorder_test.go — one subtest now passes and checks a non-empty NoResult; traced the assertion through ShouldCompute. docs/design.md — one row extended; the wording matches what the PR adds.
  • The rest of the PR is unchanged since my round-1 review of 0569091d, which traced the side-effect order of finish, the fail-open paths, the state save/restore parity and the ping-store move. I did not re-run tests or builds; this review is from reading the code 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 d901ba6b35e5 approve

Verdict: approve

Findings

None. The new commit changes one test and one docs row. Both are correct.

Non-blocking

  • Tests still owed before the hand-off. The author's comment says build and vet are clean,
    but the unit tests were not run (load average above 300). CLAUDE.md also asks for
    scripts/dev/local-tests.sh 1370 at the final head. Run both before the PR is handed to the
    integrator. Same point reviewer 2 raised in round 1; it still stands.

What I checked

  • Last review: round 1, 0569091dd0cb69761e3a0473cb16583f797ab32c, 2026-11-24T18:00:15Z.
  • New commits read: 1 (d901ba6b "docs(accrec): name the Recorder, PingStore and state
    format; pin the kept reason").
  • 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 2's round-1 review (approve, 5 non-blocking notes). Read in full. Our notes
      overlap on three points (design.md row, "proxy version" text, Take race); I checked each
      again myself below. No new finding to agree with or dispute.
    • The author's comment "Round 1 notes, fixed in the new head." Checked every claim in the
      commit (below).
    • Commit d901ba6b. Reviewed in full; see below.
  • Earlier findings, each resolved:
    • design.md accrec/ row (mine, and reviewer 2's): fixed. The row now names the
      Recorder (Begin/End/Price), the PingStore and the state-file format
      (SnapshotState/RestoreState). I checked the names against the code; they match.
    • Several-rounds subtest checked less than its name said (reviewer 2's): fixed. The
      subtest now passes NoResult: "earlier_reason" and asserts Price keeps it. I traced
      ShouldCompute(200, 2, "earlier_reason"): not rejected, not DeferralUnplaced, rounds 2,
      so it returns (false, noResult) — the earlier reason is kept and nothing is priced. The
      assertion matches the trace, and the author's mutation (empty reason for several rounds)
      fails it, as the comment says.
    • "proxy version" error text (mine, and reviewer 2's): rejected by the author, reason
      accepted.
      The string is byte-identical to the one before the move. Changing a message an
      operator reads is a visible change, and this PR claims none. A separate change can reword
      it.
    • PingStore.Take Peek-then-Drop race (mine, and reviewer 2's): rejected, reason
      accepted.
      The code is the old proxy code moved as it was, and Take has no production
      caller (the request path uses Peek then Drop with the read window).
    • PriceIn.Pings concrete type (mine): rejected, reason accepted. No host needs another
      sink today; an interface can come when one does.
    • Test debt before merge (reviewer 2's): not done yet, kept under Non-blocking above.
  • The new commit touches nothing else. git diff 0569091d..d901ba6b changes only
    accrec/recorder_test.go (2 lines) and docs/design.md (1 line). The rest of the PR is the
    code I verified line by line in round 1; my round-1 trace of the move and of the finish
    order still stands at this head.
  • I did not run tests or builds; this review is from reading the code only.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Output of scripts/release/approval-still-valid.sh 1370 d901ba6b35e5 at head c390400 (merge of origin/main, clean, no hand-resolved conflict):

approved: d901ba6b35e5 (base 1d20435fe193) patch-id 9a0e10210793
head:     c390400f88f5 (base 776492ceffdb) patch-id 1806d9880880
--- git range-diff
1:  e8e39c2e = 1:  e8e39c2e refactor(accrec): move the savings tracker and the ping store out of proxy
2:  0569091d = 2:  0569091d refactor(accrec): keep the side-effect order of finish
3:  d901ba6b = 3:  d901ba6b docs(accrec): name the Recorder, PingStore and state format; pin the kept reason
CHANGED: the head has new code or a conflict resolution. Each reviewer re-checks the delta.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Approval check by hand: the approvals of d901ba6b still hold at c390400f.

approval-still-valid.sh prints CHANGED, but the only new commit is a clean merge of main. It brings in #1357 and other merged PRs, and it has no hand resolution. The patch-id differs because main changed lines next to this PR's lines.

This PR's own changed lines did not change:

B=$(git merge-base origin/main d901ba6b35e5)
diff <(git diff $B d901ba6b35e5 | grep '^[-+]' | grep -v '^+++\|^---') \
     <(git diff origin/main...c390400f88f5 | grep '^[-+]' | grep -v '^+++\|^---')   # no output

The replay test TestReplayBooksTheSameFigures passes with the same hashes after the merge.

@amiddavid
amiddavid merged commit 2fd786d into main Nov 24, 2026
10 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 25, 2026
Add two bullets to RELEASING.md section 3, by owner decision ("add both"):
write issue numbers in a PR body as "Refs #N" only, and freeze every
merge for a PR stuck in a merge-of-main loop.

Refs #1303, #1370, #1331

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Nov 25, 2026
…eze) (#1405)

docs(release): tell the PR owner after every merge

Add a bullet to RELEASING.md section 3: after every merge, send the PR
owner one message in the same step. Owner decision (David Amid,
2026-11-25): "put the rule into the realsing.md file so other
integrators on other machines would know it".

Refs #1394, #1388

docs(release): add Refs-only and full-freeze merge rules

Add two bullets to RELEASING.md section 3, by owner decision ("add both"):
write issue numbers in a PR body as "Refs #N" only, and freeze every
merge for a PR stuck in a merge-of-main loop.

Refs #1303, #1370, #1331

Docs only. The owner approved the text and the merge with no review round, in
the integrator session, 2026-11-25: "1405 merge".

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(accountant): move the rest of the accountant glue out of the proxy

1 participant