Repository navigation
refactor(campaign): move replay, scoring and fidelity math out of the proxy (1/3, #1302) - #1332
Conversation
…the proxy Add the library package `campaign`. It holds the calibrated constants, the closed-form replay, the fidelity model, the ship gate, the auto builder and the decision math that proxy/predictive.go, campaignauto.go, adaptreplay.go and adaptcache.go used to hold. The proxy reads history and files and calls it. No behaviour change. The rowFloor wait-cause gap stays as it is (#1298). Refs #1309 Closes #1302 (with the next PR in the stack) 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 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 | a0c73c59ec0e |
approve |
Verdict: approve
Findings
None. The move changes no behavior. Every defect I suspected did not survive a line-by-line
comparison with the old code.
Non-blocking
- campaign/eval.go:810 (Eval) and campaign/eval.go:863 (BuildSpec) — a nil
factswith a non-emptysegBypanics.
seg(&facts[i])dereferences a nil slice. The doc onBuildSpecsays facts "may be nil".
The oldautoEval/autoSpechad the same gap, and no caller passes that combination today.
The functions are exported now, so a future host can hit it. A guard, or a doc line that says
"nil facts needs segBy empty", would close it. - docs/design.md:11 — the package map has no
campaign/row.
The map lists most library packages.predictive/is missing too, so this follows practice.
A new top-level library package is what the map is for. One row would do. - campaign/replay.go:1397 (
if ss := byThr[tk]; true {) — a deadif ... ; truewrapper.
Carried over verbatim fromautoRowsX. It works, but it reads like a leftover. The block can
lose the wrapper.
What I checked
- Read the full diff, all 17 files, and the code around each change.
- Behavior identity, function by function. I compared each moved function with its old copy:
PlanOutcome/planOutcome,Rows/autoRowsX,Eval/autoEval,BuildSpec/autoSpec,
Expected/expected,FitFidelity/fitFidelity,SessionCI/sessionCI,ShipGate/shipGate,
ScoreRows/adaptScore,CurrentPlan/currentPlan,RowFloor/rowFloor,
ForcePolicy/forcePolicy,Choose(the old inline switch inpredictiveDecideInner),
Apply/predDecision.apply,ScoreDecision(the old inline math inresolveStopLocked).
The logic, the conditions and the arithmetic are the same in each. The one wording change
(rowFacts→RowFactsand renamed fields) is a rename. - The mirrored constants.
campaign.AutoX=config.DefaultKeepAliveIdle(240) replaces
autoX=campaignKeepAlive5mIdle(240).RowFacts.DefaultKusesconfig.DefaultKeepAliveMinPrefix
(80000),config.DefaultKeepAliveMaxPings(2) andkeepalive.DefaultMaxUSDPerPing(0.50) where the
old code used the proxy's local mirrors (80000, 2, 0.50).Applyusesconfig.DefaultKeepAliveIdle
where the old code usedcampaignKeepAlive5mIdle. All values equal.CachePolicyis an alias of
keepalive.Policy(proxy/keepalive.go:27), so the moved signatures keep their meaning. - The host rewiring.
currentPlaninproxy/adaptcache.gostill lockspc.muto read spec, mode
and id, and still passesclientSignalEnabled(). TheChoosecall sits where the old inline switch
sat;spec.RuleForis pure, so the move past the tracker block changes nothing.
resolveStopLockedaddssc.PingUSD,sc.RescUSDandsc.NetUSDexactly as the old inline code did. - Leftovers and cycles. No file outside
campaign/references a removed identifier
(cfTC,cfScale,planOutcome,autoSpec,rowFacts,segFeatures, ...) — only comments and the
unrelatedautoRowsForremain.campaign/imports onlyconfig,keepalive,kvcache,
predictiveandinternal/*; it never importsproxyordash, so the "library never imports a
host" rule holds. Every API it calls exists (Policy.WaitMinPrefix,PredictorFor,
Spec.RuleFor/PlanOf,AutoTune/AutoFit.PlanFor,kvcache.DefaultPingIdle,
modelinfo.AnthropicDefaultKeepAliveMaxPings1h). - Tests. The moved tests moved with the code and keep their assertions. The new exported
functions (ScoreDecision,Priced,Stake,Choose,Apply,CurrentPlan,ForcePolicy) each
got a test. The shadow scorer stays covered inproxy/campaignbuild_test.go
(TestSessionEndCancelsPlannedPingsInTheCampaignScore). No newtime.Sleepin tests.
TestShadowConstantsMatchTheEngineCalibrationreads../scripts/campaign/engine_calibration.json
from its new package dir; the path resolves and the file holds 0.948 / 1.346, the values in
campaign/replay.go. - Repo rules. Data dependence unchanged; the PR states this and no new component needs a row.
No behavior change without permission: none found, and the PR says so. TherowFloorwait-cause gap
is kept and points at #1298. The PR notes say where tests ran ("macOS, Go 1.27.4"). - I did not run builds or tests. Live tests are not approved for this review.
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 | a0c73c59ec0e |
approve |
Verdict: approve
Findings
None. The move is faithful. I found no behavior change.
Non-blocking
campaign/campaign_test.go:472—TestAutoPlansNeverPingLaterThanTheConfiguredIntervalkeeps an inner loop over[]float64{AutoX, 280, 300}. The loop variableidleno longer feeds anything: the old test variedpredDecision.idleS, butApplytakes no scored-at idle. The loop runs the same call three times and only namesidlein the failure text. Drop the loop, or say in the comment that the property now holds by the type.docs/design.md— the package table does not list the newcampaign/package. It does not listpredictive/either, so this matches current practice. A later PR in the stack can add both.
What I checked
- Read the full diff (17 files, +1430/-1131) and the code around each change.
- Constants. The old proxy mirrors equal the library values:
campaignKeepAlive5mIdle240 =config.DefaultKeepAliveIdle;campaignDefaultMinPrefixTokens80000 =config.DefaultKeepAliveMinPrefix;campaignDefaultMaxPings2 =config.DefaultKeepAliveMaxPings; proxyDefaultMaxUSDPerPing0.50 =keepalive.DefaultMaxUSDPerPing;cfTC/cfLate/cfPingDur296.5/1.0/2.0 =Cliff/Late/PingDur;cfScale/cfPingScale0.948/1.346 =BenefitScale/PingScale;autoK6 =AutoK.engine_calibration.jsonholds 0.948/1.346. Only one copy of each number remains in Go code. - Moved logic, function by function.
PlanOutcome,RowFacts.Outcome/Gain/DefaultK,Rows(wasautoRowsX),SessionCI,ShipGate/GateLegs,Eval,BuildSpec,FitFidelity,Expected,FidMiss,ScoreRows,CurrentPlan,RowFloor,ForcePolicy— each compares equal to its base version apart from the export renames. The knownRowFloorwait-cause gap keeps its comment and the #1298 reference. ChooseandApply. The old inline switch inpredictiveDecideInnerandpredDecision.applymatchcampaign.Choose/campaign.Applyline for line. One order change —spec.RuleFornow runs afterpc.tr.Endedinstead of before — is safe:RuleForreads only the spec and the facts.resolveStopLocked. The newScoreDecisionproduces the samePingUSD,RescUSDandNetUSDas the removed inline math.- Callers.
adaptCacheApplyandctlBuildCacheCampaignvalidatesegment_bythroughcampaign.SegmentOf, which is the same map lookup as before.currentPlanbuilds theActiveonly when the mode is active, so the oldactive && pol.KeepAlivebranch order is kept.forcePolicyguards and mutates exactly as the old inline code did. - Boundaries.
campaignimports onlyconfig,keepalive,kvcache,predictiveandinternal/*. No library package importsproxy. No import cycle: none of those packages importcampaign. - Leftovers. No proxy file still uses a moved identifier (
familyOf,planOutcome,autoRows*,shipGate,cf*,autoX,rowFacts, ...). Removed imports (slices,waitcause,keepalivefromadaptcache.go;kvcache,modelinfofrompredictive.go) are unused. No identifier collides with the newcampaignimport. - Tests. The moved tests compare equal to their base versions. New tests cover
ScoreDecision,Priced/Stake,Choose,Apply,CurrentPlanandForcePolicy.keepalive.Policyholds only scalar fields, so the newgot != polstruct comparison is valid. - Data dependence. No new component, no new reader of stored text. The PR says so and the code agrees.
- I did not build or run tests: live tests were not approved for this review. The compile-level claims above rest on reading the code.
- Document that Eval and BuildSpec need facts when segBy is set. - Drop the dead `if ss := ...; true` wrapper in Rows. - Drop the idle loop in the Apply test: Apply takes no idle. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
Round-1 notes, fixed in beb1292 (macOS, Go 1.27.4; build, vet, gofmt clean;
|
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 | beb1292d2c5d |
approve |
Verdict: approve
Findings
None. The new commit changes no behavior. It is a clean answer to the round-1 notes.
Earlier findings
- Reviewer 1, nil
factswith a non-emptysegBypanics — resolved by documentation, and I accept it.campaign/eval.go:78andcampaign/eval.go:131now say "facts may be nil only when segBy is empty: a segmentation reads each row's facts, and a nil slice panics". The author's reason holds: the oldautoEval/autoSpechad the same gap, and no caller passes that combination (runAutoBuild,refreshAutoCampaignsandadaptReportall pass facts built byRows; tests pass nil only withsegByempty). An exported function with a stated precondition is enough for a non-blocking note. - Reviewer 1, dead
if ss := ...; truewrapper inRows— fixed.campaign/replay.go:196-199now readsss := byThr[tk]and one plainif. I compared it with the base version: samesort.Search, same condition, same assignment. Behavior identical. - Reviewer 1 and me,
docs/design.mdhas nocampaign/row — not fixed, still non-blocking. The author's comment names only the three items above. Both round-1 reviews called this non-blocking, and I deferred it to a later PR in the stack. That stands. - Me, dead idle loop in the
Applytest — fixed.campaign/campaign_test.go:348-352dropped the loop over[]float64{AutoX, 280, 300}and added the comment "Apply takes no idle: the spacing the decision was scored at cannot change the result, by the type". The coverage overconf(0, 60 s, 240 s, 270 s) is unchanged, so the test still pins the interval rule.
The new commit
beb1292d touches three files, +9/-10:
campaign/campaign_test.go— the test edit above. Same assertions, one less dead loop.campaign/eval.go— doc lines only, onEvalandBuildSpec. No code change.campaign/replay.go— the wrapper drop above. No code change beyond the removedif true.
The commit message follows the repo rules: conventional title, DCO sign-off, Assisted-By: attribution.
What I checked
- Last review: round 1, a0c73c5, 2026-11-24T09:20:48Z.
- New commits read: 1 (beb1292, "refactor(campaign): address round-1 notes on the replay move").
- Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt). - New items since my last review, and what I did about each:
- Reviewer 1's round-1 review (approve, 3 non-blocking notes) — checked each note against the code and the fix commit; see "Earlier findings".
- Author's comment at 2026-11-24T09:30:36Z listing the three fixes — verified each claim against
beb1292d; all three match what the diff does. - Commit
beb1292d— read the full diff and the changed files around each change; see "The new commit".
- I did not run builds or tests: live tests are not approved for this review.
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 | beb1292d2c5d |
approve |
Verdict: approve
Findings
None. The new commit changes no behavior. It edits two doc comments, drops a dead code wrapper,
and drops a dead loop in a test.
Earlier findings, and their state
- Round 1, mine, nil
factswith asegByinEval/BuildSpec(non-blocking): answered with a doc.
The author kept the behavior and documented the contract: "facts may be nil only when segBy is
empty" (campaign/eval.go:78and:131). I checked the reason: no caller passes that combination
(all four call sites pass non-nil facts when they pass asegBy), and a doc-stated contract on an
internal invariant is a fair fix for a non-blocking note. Accepted. - Round 1, mine, dead
if ss := ...; truewrapper inRows(non-blocking): fixed.
campaign/replay.go:196-199now reads the slice and searches it directly. The logic is identical:
samesort.Search, same bound check, sameSpanassignment. - Round 1, mine, missing
campaign/row in thedocs/design.mdpackage map (non-blocking): not done.
The author's comment does not name it. Reviewer 2 suggested a later PR in the stack adds both
campaign/andpredictive/. I keep this non-blocking. It is a docs gap, not a defect. - Round 1, reviewer 2, the dead
idleloop inTestAutoPlansNeverPingLaterThanTheConfiguredInterval
(non-blocking): fixed incampaign/campaign_test.go:345-353. I checked the fix myself. The loop ran
the sameApplycall three times and usedidleonly in the failure text;Applytakes no
scored-at idle, so the property holds by the type. The comment now says so. Theconfloop and its
four cases stay, so the test still checks that a campaign never pings later than the tenant's
interval. - Round 1, reviewer 2, the
docs/design.mdrow (non-blocking): same item as mine above. Not done,
deferred to the stack.
What I checked
- Last review: round 1,
a0c73c59ec0e7fb3328127feda8cf3d521c67226, 2026-11-24T09:19:15Z. - New commits read: 1 —
beb1292d"refactor(campaign): address round-1 notes on the replay move". - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files in my folder).
- New items since my last review:
- Reviewer 2's round-1 review (09:20:48Z), verdict approve, two non-blocking notes. Both overlap
mine; I re-checked each myself above. - The author's comment (09:30:36Z): three fixes named for
beb1292d, with test notes
("macOS, Go 1.27.4; build, vet, gofmt clean;go test -race ./campaignpass"). I verified each
fix in the diff. - Commit
beb1292d: read the whole diff and the changed regions in the worktree.campaign/eval.go: two doc lines only. The new text is accurate —seg(&facts[i])on a nil
slice panics, and the same contract coversBuildSpec's second facts use
(SegmentOf(segBy)(&facts[i])in the segmentedownpolicy). No code change.campaign/replay.go: the wrapper drop keeps the semantics identical (read at:196-199).campaign/campaign_test.go: the loop drop removes only the repeated identical call; the
assertions overconfare intact.
- Reviewer 2's round-1 review (09:20:48Z), verdict approve, two non-blocking notes. Both overlap
- The rest of the PR is unchanged since my round-1 review, which verified the whole move
function by function. I did not repeat it and found no reason to: the new commit touches none of
the moved logic. - I did not run builds or tests. Live tests are not approved for this review.
Summary
First of 3 stacked PRs for #1302. Moves the campaign replay, scoring, fidelity and auto-build math from
proxy/into a new library packagecampaign. Part of #1309.Why a new package, not
predictiveorkvcache: the replay needskeepalive(IsSubagentThread,Policy) andconfig.predictiveandkvcacheare small and do not import them. A newcampaignpackage keeps both light.Stack: this PR, then
feat/mv-1302-campaign-arms(arm mapping), thenfeat/mv-1302-campaign(recommendation choice). Each PR is based on the one before.What changed
cf*constants incampaign/replay.go:Cliff296.5,Late,PingDur,BenefitScale0.948,PingScale1.346. Values unchanged.PlanOutcome,ScoreDecision,RowFacts(+Outcome,Gain,DefaultK),Rows(wasautoRowsX),SessionCI,ShipGate,GateLegs,Eval,BuildSpec.FitFidelity,Expected,FidMiss) moved as is. Thefid*constants stay apart from thecf*ones: they belong to another model.ScoreRows,CurrentPlan,RowFloor,ForcePolicyfromadaptcache.go.ChooseandApplyfrompredictive.go.predDecision.applyis now a one-line call tocampaign.Apply.NewFacts,Priced,Stake: one place each for what two copies did.proxy/keeps file I/O, the DB reads, the HTTP views and the shadow-stat counters.rowFloorkeeps its wait-cause gap. A comment points to decide: two proxy and library results that differ (server-held history, replay prefix floor) #1298.Behaviour
None. Existing proxy tests pass. Test edits are renames only (
rowFactstocampaign.RowFacts, etc.). Tests of the moved logic moved tocampaign/.Differences kept as they are:
rowFloorreads every tool stop as a tool wait. The keeper uses the stored wait cause. Held in decide: two proxy and library results that differ (server-held history, replay prefix floor) #1298.Data dependence
Same as before. The move changes no feature. The replay reads request metadata (tokens, timings, prices, stop reason). No new reader of stored text. No component added, so no
docs/data-dependence/row.How it was tested
macOS, Go 1.27.4.
go build ./... && go vet ./... && gofmt -l .: clean.go test ./campaign ./proxy ./cmd/cg-cache-campaign: pass.s >= gaptos > gapinPlanOutcomefailsTestScoreDecisionFollowsTheClosedForm.PingScale1.346 to 1.0 failsTestShadowConstantsMatchTheEngineCalibration. Droppingmin(k1h, k)inApplyfailsTestApplyWritesOnlyAnActiveDecision.ScoreDecision,Priced/Stake,Choose,Apply,CurrentPlan,ForcePolicy.-race(see the last PR).Refs #1302, #1309.