Skip to content

refactor(campaign): move replay, scoring and fidelity math out of the proxy (1/3, #1302) - #1332

Merged
amiddavid merged 2 commits into
mainfrom
feat/mv-1302-campaign-replay
Nov 24, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/mv-1302-campaign-replay

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

First of 3 stacked PRs for #1302. Moves the campaign replay, scoring, fidelity and auto-build math from proxy/ into a new library package campaign. Part of #1309.

Why a new package, not predictive or kvcache: the replay needs keepalive (IsSubagentThread, Policy) and config. predictive and kvcache are small and do not import them. A new campaign package keeps both light.

Stack: this PR, then feat/mv-1302-campaign-arms (arm mapping), then feat/mv-1302-campaign (recommendation choice). Each PR is based on the one before.

What changed

  • One set of cf* constants in campaign/replay.go: Cliff 296.5, Late, PingDur, BenefitScale 0.948, PingScale 1.346. Values unchanged.
  • PlanOutcome, ScoreDecision, RowFacts (+ Outcome, Gain, DefaultK), Rows (was autoRowsX), SessionCI, ShipGate, GateLegs, Eval, BuildSpec.
  • Fidelity model (FitFidelity, Expected, FidMiss) moved as is. The fid* constants stay apart from the cf* ones: they belong to another model.
  • ScoreRows, CurrentPlan, RowFloor, ForcePolicy from adaptcache.go.
  • Choose and Apply from predictive.go. predDecision.apply is now a one-line call to campaign.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.
  • rowFloor keeps 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 (rowFacts to campaign.RowFacts, etc.). Tests of the moved logic moved to campaign/.

Differences kept as they are:

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.
  • Mutation: s >= gap to s > gap in PlanOutcome fails TestScoreDecisionFollowsTheClosedForm. PingScale 1.346 to 1.0 fails TestShadowConstantsMatchTheEngineCalibration. Dropping min(k1h, k) in Apply fails TestApplyWritesOnlyAnActiveDecision.
  • New library tests: ScoreDecision, Priced/Stake, Choose, Apply, CurrentPlan, ForcePolicy.
  • The shared tests of the head of the stack ran with -race (see the last PR).

Refs #1302, #1309.

…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 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 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 facts with a non-empty segBy panics.
    seg(&facts[i]) dereferences a nil slice. The doc on BuildSpec says facts "may be nil".
    The old autoEval/autoSpec had 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 dead if ... ; true wrapper.
    Carried over verbatim from autoRowsX. 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 in predictiveDecideInner),
    Apply/predDecision.apply, ScoreDecision (the old inline math in resolveStopLocked).
    The logic, the conditions and the arithmetic are the same in each. The one wording change
    (rowFacts → RowFacts and renamed fields) is a rename.
  • The mirrored constants. campaign.AutoX = config.DefaultKeepAliveIdle (240) replaces
    autoX = campaignKeepAlive5mIdle (240). RowFacts.DefaultK uses config.DefaultKeepAliveMinPrefix
    (80000), config.DefaultKeepAliveMaxPings (2) and keepalive.DefaultMaxUSDPerPing (0.50) where the
    old code used the proxy's local mirrors (80000, 2, 0.50). Apply uses config.DefaultKeepAliveIdle
    where the old code used campaignKeepAlive5mIdle. All values equal. CachePolicy is an alias of
    keepalive.Policy (proxy/keepalive.go:27), so the moved signatures keep their meaning.
  • The host rewiring. currentPlan in proxy/adaptcache.go still locks pc.mu to read spec, mode
    and id, and still passes clientSignalEnabled(). The Choose call sits where the old inline switch
    sat; spec.RuleFor is pure, so the move past the tracker block changes nothing.
    resolveStopLocked adds sc.PingUSD, sc.RescUSD and sc.NetUSD exactly 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
    unrelated autoRowsFor remain. campaign/ imports only config, keepalive, kvcache,
    predictive and internal/*; it never imports proxy or dash, 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 in proxy/campaignbuild_test.go
    (TestSessionEndCancelsPlannedPingsInTheCampaignScore). No new time.Sleep in tests.
    TestShadowConstantsMatchTheEngineCalibration reads ../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. The rowFloor wait-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 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 a0c73c59ec0e approve

Verdict: approve

Findings

None. The move is faithful. I found no behavior change.

Non-blocking

  • campaign/campaign_test.go:472 — TestAutoPlansNeverPingLaterThanTheConfiguredInterval keeps an inner loop over []float64{AutoX, 280, 300}. The loop variable idle no longer feeds anything: the old test varied predDecision.idleS, but Apply takes no scored-at idle. The loop runs the same call three times and only names idle in 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 new campaign/ package. It does not list predictive/ 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: campaignKeepAlive5mIdle 240 = config.DefaultKeepAliveIdle; campaignDefaultMinPrefixTokens 80000 = config.DefaultKeepAliveMinPrefix; campaignDefaultMaxPings 2 = config.DefaultKeepAliveMaxPings; proxy DefaultMaxUSDPerPing 0.50 = keepalive.DefaultMaxUSDPerPing; cfTC/cfLate/cfPingDur 296.5/1.0/2.0 = Cliff/Late/PingDur; cfScale/cfPingScale 0.948/1.346 = BenefitScale/PingScale; autoK 6 = AutoK. engine_calibration.json holds 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 (was autoRowsX), 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 known RowFloor wait-cause gap keeps its comment and the #1298 reference.
  • Choose and Apply. The old inline switch in predictiveDecideInner and predDecision.apply match campaign.Choose/campaign.Apply line for line. One order change — spec.RuleFor now runs after pc.tr.Ended instead of before — is safe: RuleFor reads only the spec and the facts.
  • resolveStopLocked. The new ScoreDecision produces the same PingUSD, RescUSD and NetUSD as the removed inline math.
  • Callers. adaptCacheApply and ctlBuildCacheCampaign validate segment_by through campaign.SegmentOf, which is the same map lookup as before. currentPlan builds the Active only when the mode is active, so the old active && pol.KeepAlive branch order is kept. forcePolicy guards and mutates exactly as the old inline code did.
  • Boundaries. campaign imports only config, keepalive, kvcache, predictive and internal/*. No library package imports proxy. No import cycle: none of those packages import campaign.
  • Leftovers. No proxy file still uses a moved identifier (familyOf, planOutcome, autoRows*, shipGate, cf*, autoX, rowFacts, ...). Removed imports (slices, waitcause, keepalive from adaptcache.go; kvcache, modelinfo from predictive.go) are unused. No identifier collides with the new campaign import.
  • Tests. The moved tests compare equal to their base versions. New tests cover ScoreDecision, Priced/Stake, Choose, Apply, CurrentPlan and ForcePolicy. keepalive.Policy holds only scalar fields, so the new got != pol struct 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]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Round-1 notes, fixed in beb1292 (macOS, Go 1.27.4; build, vet, gofmt clean; go test -race ./campaign pass):

  1. Eval/BuildSpec nil facts with a segBy: kept the behaviour. Both docs now say "facts may be nil only when segBy is empty". No guard.
  2. Dead if ss := ...; true wrapper in Rows: dropped.
  3. Idle loop in the Apply test: dropped. A comment says Apply takes no idle, so the property holds by the type.

@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 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 facts with a non-empty segBy panics — resolved by documentation, and I accept it. campaign/eval.go:78 and campaign/eval.go:131 now 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 old autoEval/autoSpec had the same gap, and no caller passes that combination (runAutoBuild, refreshAutoCampaigns and adaptReport all pass facts built by Rows; tests pass nil only with segBy empty). An exported function with a stated precondition is enough for a non-blocking note.
  • Reviewer 1, dead if ss := ...; true wrapper in Rows — fixed. campaign/replay.go:196-199 now reads ss := byThr[tk] and one plain if. I compared it with the base version: same sort.Search, same condition, same assignment. Behavior identical.
  • Reviewer 1 and me, docs/design.md has no campaign/ 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 Apply test — fixed. campaign/campaign_test.go:348-352 dropped 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 over conf (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:

  1. campaign/campaign_test.go — the test edit above. Same assertions, one less dead loop.
  2. campaign/eval.go — doc lines only, on Eval and BuildSpec. No code change.
  3. campaign/replay.go — the wrapper drop above. No code change beyond the removed if 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 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 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 facts with a segBy in Eval/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:78 and :131). I checked the reason: no caller passes that combination
    (all four call sites pass non-nil facts when they pass a segBy), 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 := ...; true wrapper in Rows (non-blocking): fixed.
    campaign/replay.go:196-199 now reads the slice and searches it directly. The logic is identical:
    same sort.Search, same bound check, same Span assignment.
  • Round 1, mine, missing campaign/ row in the docs/design.md package 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/ and predictive/. I keep this non-blocking. It is a docs gap, not a defect.
  • Round 1, reviewer 2, the dead idle loop in TestAutoPlansNeverPingLaterThanTheConfiguredInterval
    (non-blocking): fixed
    in campaign/campaign_test.go:345-353. I checked the fix myself. The loop ran
    the same Apply call three times and used idle only in the failure text; Apply takes no
    scored-at idle, so the property holds by the type. The comment now says so. The conf loop 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.md row (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 ./campaign pass"). 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 covers BuildSpec's second facts use
        (SegmentOf(segBy)(&facts[i]) in the segmented own policy). 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 over conf are intact.
  • 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.

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.

1 participant