Skip to content

feat(keepalive): value rule for summary and sweep substitute calls - #1444

Merged
amiddavid merged 2 commits into
mainfrom
feat/substitute-value-rule
Nov 25, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/substitute-value-rule

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Behavior change (needs a human's yes before merge)

  • Who: every account where a summary or sweep substitute call replaces a keep-alive ping.
  • Old: the call was refused when its projected cost passed the flat $0.50 default (Policy.Ceiling()).
  • New: the call is allowed when its cost is below the miss it protects. An unset cap means no flat cap. An explicit cap still applies.
  • Off switch: set keepalive_max_usd_per_ping explicitly. A positive value caps each substitute call again.

Summary

What changed

  • Value used: the miss of the entry the replaced ping would renew (MissUSD, at the tier of the prompt size, 1-hour rate when the entry is 1-hour).
    • Summary: cost of one call (prefix read + 2000 output guess) against one miss. It renews the same entry, so it protects at least that miss.
    • Sweep: cost of n questions against one miss. The answer payoff (a cut) is not known from metadata at ping time, so it is not counted. The value is a floor. The refresh test (expectedRefreshSavingUSD) is unchanged.
  • New Policy.SubstituteVerdict(cost, miss): PingVerdict with one call. Cost >= miss is refused. An explicit cap refuses with the over-budget reason. Unpriced cost or unknown miss is allowed.
  • fireSummarySubstitute and affordableSweepBatches use it. The sweep lowers its batch count until the batches cost less than the miss.
  • A refusal returns false, so the ordinary ping goes out. The entry was admitted under the ping rule, so the ping passes it.
  • Policy.Ceiling() is no longer read by any keeper path. It stays for the pinned default that config mirrors (DefaultMaxUSDPerPing).

How it was tested

macOS, Go 1.27.4.

  • go build ./..., go vet ./...: clean.
  • go test on keepalive, campaign, proxy, dash: pass.
  • -race -run on the new tests: pass.
  • New tests (keepalive/substitute_value_test.go):
    • GPT-5.5 summary at 600K passes ($0.6+ cost, about $5.40 miss).
    • Integrated summary above $0.50 with no cap is sent.
    • Cost above miss is refused and the plain ping still goes (summary and sweep).
    • Explicit cap still refuses. Unpriced and unknown miss are allowed.
    • Sweep batches weigh against one miss.
  • Mutations: inverted comparison fails 10+ tests. A refusal that returns true (no ping fallback) fails the summary and sweep fallback tests.

Local tests: waived (owner rule)

Data dependence

Metadata only: price, prefix token count, flags. No stored customer data. Same at every storage level (off, metadata only, everything). No change to docs/data-dependence.md.

Decided

Owner decisions (David Amid, 2026-11-25):

  • Strict floor. A sweep's own payoff is not counted. The value is the miss alone.
  • Ceiling() stays for the config default (DefaultMaxUSDPerPing).
  • Merge: the owner gives the yes once the review passes.

Open questions

None.

Fixes #1439

A substitute call replaces a ping and renews the same entry. It now
passes when its projected cost is below the miss it protects
(SubstituteVerdict). An explicit MaxUSDPerPing still caps it. Unset
means no flat cap. A refusal falls back to the plain ping.

Fixes #1439

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid amiddavid added the openai OpenAI / Codex traffic and pricing label Nov 25, 2026

@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.332 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 ad0e9780c2a2 blocking

Verdict: blocking

Findings

  1. keepalive/substitute_value_test.go:121 — the new sweep test passes only on arm64; on gc/amd64 it fails

    • What fails: TestSweepBatchesAreWeighedAgainstOneMiss sets inf := 1e300 and expects 4, 1 and 2 batches. affordableSweepBatches computes int(ceiling/one) (substitute.go:406). With ceiling = 1e300 and one ≈ $0.0836, the quotient is about 1.2e301, outside int64. The conversion is implementation-defined. On gc/amd64 it yields MinInt64, so max(0, …) gives 0 and the function returns 0 batches. The test then wants 4 and gets 0.
    • Proof: the code's own comment at substitute.go:390-400 names this exact trap: "Dividing +Inf by a cost and converting it to int is implementation-defined (MinInt64 on gc)". That is why the math.IsInf guard exists. 1e300 is finite, so the guard does not catch it. The old tests (sweepsubstitute_test.go:919-930) use math.Inf(1) and stay on the guarded path. The variable is named inf, so math.Inf(1) is what was meant. The PR ran the tests on macOS arm64, where the conversion saturates to MaxInt64 and the test passes. Tier-1 CI does not run keepalive, so heavy CI on the Linux box is the first place this fails.
    • Fix: use math.Inf(1) instead of 1e300, as the older sweep tests do.
  2. config/config.go:175 and docs/how-to/cache-keepalive.md:87 — two operator-facing docs still state the removed $0.50 cap

    • What fails: an operator reads that summary and sweep calls keep a $0.50 default cap when keepalive_max_usd_per_ping is unset. After this PR, an unset cap means no flat cap for substitutes; only the value rule applies. The docs state the opposite of the shipped behavior. The PR's own off-switch ("set keepalive_max_usd_per_ping explicitly") depends on the operator knowing the default is gone.
    • Proof: config/config.go:173-176 says "Summary and sweep calls still use DefaultKeepAliveMaxUSDPerPing as their cap when this is 0." docs/how-to/cache-keepalive.md:87 says "Summary and sweep calls that replace a ping still use a $0.50 cap when you set none." Both describe Policy.Ceiling(), which this PR removes from every keeper path (the new types.go:289-293 comment says so).
    • Fix: update both lines to the new rule: unset means no flat cap; the value rule decides; an explicit cap still applies.

Non-blocking

  • The value rule weighs one substitute call alone. The other K-1 pings of the same idle span are not added, and the extra-slot call (j.extra) is spend on top of the chain. One span can therefore cost more than one miss while every guard passes alone. The PR body names the miss as a floor, so this is a design choice, not a defect. Worth a line in the doc when finding 2 is fixed.
  • summarySubstituteOverBudget and sweepOverBudget now also count value-rule refusals ("not worth"), not only cap refusals. The log lines still say "would exceed the per-ping cost cap". The counter names and the dash labels misdescribe the refusal reason. The verdict is in the log's verdict field, so this is wording only.
  • The long comment in affordableSweepBatches (substitute.go:390-400) explains the zero-and-NaN guard in terms of Policy.Ceiling(). The caller now passes PingCap(), which never returns 0 or a negative value. Half the comment describes a caller that no longer exists.

What I checked

  • The full diff (6 files) and the code around each change: fireSummarySubstitute, fireSweepSubstitute, affordableSweepBatches, verdict, capPolicy, PingVerdict, PingCap, Ceiling.
  • The verdict refactor is equivalent to the old code for both the manual-only and the normal case: same policy, same ping count, same miss.
  • Fail-open paths: every refusal returns false and the plain ping goes out. Unpriced cost and unknown miss are allowed. A refused sweep falls back to the ping, which the entry's own admission already passed.
  • Policy.Ceiling() has no remaining reader in any keeper path (grep over the repo; only comments and tests remain).
  • The behavior change is named at the top of the PR, with the old and new behavior and the off-switch. Issue #1439, authored by the owner, asks for exactly this change, so the human's yes is recorded.
  • Data dependence: metadata only (price, prefix tokens, flags). No change to the row files; correct to leave them alone.
  • Test helpers used by the new test file all exist, and the arithmetic in each fixture matches the prices it sets.
  • I did not run Go builds or tests; live tests were not approved. All proof above is static, from the diff and the repo's own comments.

@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.332 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 ad0e9780c2a2 blocking

Verdict: blocking

Findings

  1. keepalive/substitute_value_test.go:121 — the new test's "no cap" value 1e300 makes the batch count platform-dependent; the test fails on amd64

    • What fails: on gc/amd64 (the Linux CI runners and the eval box), the rows {0, 4} and {100, 4} at line 125 get 0 batches and want 4. On arm64 (the Mac the PR ran on) the same code returns 4, so the failure only shows on Linux.
    • Proof: one = 20000 x 3.8e-7 + 4000 x 19e-6 = about $0.0836, so ceiling/one = 1e300/0.0836 = about 1.2e301, far above int64's max (9.2e18). The Go spec makes an out-of-range float-to-int conversion implementation-dependent. The code's own comment at keepalive/substitute.go:390-393 documents the amd64 result for the same out-of-range division: "MinInt64 on gc". So on amd64 int(ceiling/one) is MinInt64, max(0, …) clamps it to 0 (substitute.go:406), and the function returns 0. The math.IsInf guard at substitute.go:402 does not catch 1e300 because it is finite. Tier 3 heavy CI runs make cover (go test -race ./..., Makefile:55) on ubuntu-latest, an amd64 runner, and it runs the keepalive package.
    • Fix: pass math.Inf(1) as the ceiling, as TestAnInfiniteCeilingAdmitsEveryPlannedBatch (sweepsubstitute_test.go:919) already does — the IsInf guard handles it on every platform. The unpriced case at line 136 also passes 1e300, but it returns before the conversion, so only line 121 needs the change.
  2. config/config.go:175 and docs/how-to/cache-keepalive.md:87 — docs still state the removed $0.50 default cap for substitutes

    • What fails: an operator reads "Summary and sweep calls still use DefaultKeepAliveMaxUSDPerPing as their cap when this is 0" and "Summary and sweep calls that replace a ping still use a $0.50 cap when you set none". Both are false after this PR: with no cap set, a substitute is refused only when it costs at least the miss it protects.
    • Proof: the new gate is keepalive/substitute.go:165 (capPol.SubstituteVerdict), and PingCap() returns +Inf when the operator set no cap (keepalive/value.go:51-56). The PR updated the comment in keepalive/types.go:136-139 but not these two places.
    • Fix: rewrite both lines to state the value rule and the opt-in cap.

Non-blocking

  • keepalive/value_test.go:70-73 — the comment "The cap the summary and sweep calls use is unchanged: zero still resolves to the default" is now false. The assertion below it still passes, because Ceiling() itself is unchanged. Update the comment.
  • The value rule weighs one substitute slot against the whole miss. The other K-1 pings of the same chain draw on the same miss and are checked on their own. A chain with a substitute that costs just under the miss can spend more than the miss in total. The PR body names the rule and asks about the floor under Open questions, so this is a visible choice, not an accident.
  • summarySubstituteOverBudget and sweepOverBudget now also count value-rule refusals, and both log texts still say "would exceed the per-ping cost cap". The logs carry the verdict reason, so the two cases are told apart in logs only, not in the counters.
  • docs/components/advanced-offload.md:569-579 and 793 still describe the sweep ceiling without the value rule.
  • The production clamp at substitute.go:406 has the same out-of-range conversion for an absurd finite operator cap (for example 1e300 typed in yaml). On amd64 it yields 0 batches, so the plain ping goes out — it fails toward the safe side. Not reachable through PingCap() in practice.

What I checked

  • The full diff 41152b6..ad0e978, and every changed file in full: keeper.go verdict(), substitute.go both fire paths and affordableSweepBatches, types.go, value.go, and both test files.
  • The verdict() refactor is behavior-identical: capPolicy() reproduces the old manual-only Policy{MaxUSDPerPing: e.ceiling} literal, and the PingVerdict arguments are unchanged.
  • Ceiling() callers: no keeper or host path reads it any more, only tests. The claim in types.go:289-291 holds.
  • Fail-open paths of the new rule: an unpriced cost (0) is allowed, an unknown miss (0) is allowed, and every refusal returns false, so the ordinary ping still goes out in both fire paths (verified in fire() and fireExtra()).
  • The behavior change is named at the top of the PR with who it affects, old and new behavior, and the off switch, as RELEASING.md asks. The human yes is still needed before merge.
  • Data dependence: metadata only (prices, prefix token counts, flags). No row change needed; the PR states this and it matches the code.
  • The new tests' arithmetic (projected costs, misses, chain admission at record time) recomputed by hand. All consistent except finding 1.
  • Go was not run; live tests are not approved for this review. Finding 1 rests on the Go spec, the code's own platform note at substitute.go:390-393, and the CI configuration, not on a local run.

Treat a huge finite cap as unlimited before the int conversion. Use
math.Inf in the test. Rewrite the operator docs that named the $0.50
default for substitutes. Name the verdict in the refusal logs.

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

Copy link
Copy Markdown
Collaborator Author

Replies to round 1 (both reviewers blocked)

Fixed in da58dbf5.

Both reviewers, finding 1: 1e300 overflows the int conversion on amd64. Fixed in the test and in the code.

  • The test now uses math.Inf(1), as the older sweep tests do.
  • affordableSweepBatches now treats a cap whose ceiling/one is at least the planned batch count as unlimited, before the int conversion. A very large finite operator cap is then safe on every platform.
  • A new case passes a finite 1e300 cap and expects all 4 batches. A mutation that removes the clamp makes it fail. On this Mac (arm64) the conversion saturates to MaxInt64, so the mutation shows a huge count, not 0. The amd64 overflow to MinInt64 was not reproduced here, but the clamp now runs before any conversion.

Both reviewers, finding 2: the operator docs still stated the $0.50 default. Fixed in config/config.go, docs/how-to/cache-keepalive.md and docs/components/advanced-offload.md.

  • Unset means no flat cap, and the value rule decides.
  • An explicit cap still applies.
  • The rule weighs each substitute call against the miss alone, so one idle span can cost more than one miss in total.

Non-blocking notes:

  • The stale comments are fixed: keepalive/value_test.go, affordableSweepBatches and PingCap().
  • The refusal logs now name the verdict reason.
  • The docs say the *_over_budget counters count both the cap and the value refusals. Their names stay, because dashboards read them.

Owner decisions (David Amid, 2026-11-25), now under "Decided" in the body:

  • Keep the strict floor: a sweep's own payoff is not counted.
  • Keep Ceiling() for the config default.
  • The owner said yes to merge once the review passes.

Tests (macOS, Go 1.27.4): build and vet are clean. Plain go test passes on keepalive, config, campaign, proxy and dash. -race -run on the new tests passes.

Local tests: waived (owner rule)

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

Verdict: approve

Findings

None. Both round-1 findings are fixed, and the fix commit adds no new defect.

Earlier findings

  1. Mine, finding 1 (also reviewer 1, finding 1): the 1e300 test value was platform-dependent. Fixed.
    • The test now passes math.Inf(1) (substitute_value_test.go:122), which the math.IsInf guard handles on every platform.
    • The code is also fixed, not only the test: affordableSweepBatches now compares q := ceiling/one against float64(planned) before any conversion (substitute.go:407-413). A huge finite cap takes the n = planned branch; only an in-range q reaches int(q). I checked the branch myself: when q < float64(planned) and planned is a real batch count, int(q) is inside int64 on both gc/amd64 and arm64.
    • The new test case (substitute_value_test.go:131-134) passes a finite 1e300 cap and wants 4 batches. It runs no out-of-range conversion, so it holds on both platforms. I also checked the author's mutation claim: with the clamp branch removed, max(0, int(q)) returns MaxInt64 on arm64 and 0 on amd64, so the case fails on both.
  2. Mine, finding 2 (also reviewer 1, finding 2): the operator docs still stated the $0.50 default. Fixed.
    • config/config.go:173-178, docs/how-to/cache-keepalive.md:87-90 and docs/components/advanced-offload.md:569-574 now state the new rule: unset means no flat cap, the value rule decides, an explicit cap still applies. The docs also carry the span-cost note from my non-blocking list: one idle span can cost more than one miss in total.

Non-blocking from round 1

  • The stale value_test.go comment is fixed (now names Ceiling() as the pinned default).
  • The affordableSweepBatches comment now speaks of Policy.PingCap(), the caller that exists.
  • The refusal logs name the verdict reason; the sweep log says "the cost cap or the value rule".
  • The counter names stay and the docs say they count both refusals. Accepted: dashboards read the names.

Non-blocking

  • keepalive/keeper.go:615-617: the summarySubstituteOverBudget comment now has a dangling last line, "because its projected cost exceeded the keep-alive per-ping $ cap". The parenthetical above it already covers both refusals, so the trailing clause describes only one of them. Wording only.

What I checked

  • Last review: round 1, ad0e978, 2026-11-25T20:43:26Z.
  • New commits read: 1 — da58dbf5 "fix(keepalive): safe sweep cap clamp, docs for the substitute value rule".
  • 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, and what I did about each:
    • Commit da58dbf5: read the full diff and the final state of each changed file (affordableSweepBatches, both fire paths' logs, the counter comments, all three docs, both test files). No new defect. The clamp branch is correct and platform-safe; the dropped min(planned, …) is safe because int(q) < planned whenever the else branch runs.
    • Author reply (2026-11-25T20:58:06Z): each claim checked against the code. All hold. The owner decisions it names are now in the PR body under "Decided", including the yes to merge once the review passes.
    • Reviewer 1's round-1 review (posted 20:45:43Z, after mine): findings 1 and 2 match mine, both fixed. Their extra non-blocking points — the value_test.go comment, advanced-offload.md, and the production clamp for an absurd finite operator cap — are all fixed by the same commit. I verified the clamp point myself; nothing to add.
  • Fail-open paths unchanged by the fix commit: refusals still return false and the plain ping goes out; unpriced and unknown-miss cases still pass.
  • The behavior change stays named at the top of the PR, with the off-switch, and the owner's yes is recorded in the body and the reply.
  • I did not run Go builds or tests; live tests were not approved. All proof is static.

@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.332 offload-review skill, @amiddavid's session resumed 1 of 2 2 of 2 da58dbf52d38 approve

Verdict: approve

Findings

None. Both round-1 findings are fixed, and the fix commit introduces no new defect.

Earlier findings

  1. Mine, finding 1 (1e300 overflows the int conversion on amd64) — fixed. The test now passes math.Inf(1) (substitute_value_test.go:122), which stays on the IsInf-guarded path, so no conversion runs at all for the main table. The code also got the stronger fix I did not ask for: affordableSweepBatches (substitute.go:409-413) now compares q := ceiling/one against float64(planned) and takes planned without any conversion when q is at or above it. Only a q strictly below float64(planned) reaches int(q), and the largest float64 below float64(planned) (at most 2^63) is 2^63 - 1024, inside int64, so the conversion is in range on every platform. A quotient that overflows to +Inf (a huge cap over a tiny one) also lands in the >= branch. For in-range quotients the answer matches the old formula. The new test case at substitute_value_test.go:131-133 passes a finite 1e300 cap and expects 4 batches, so the clamp is pinned on every platform, not just amd64.
  2. Mine, finding 2 (operator docs still stated the $0.50 default) — fixed. config/config.go:174-177, docs/how-to/cache-keepalive.md:87-89 and docs/components/advanced-offload.md:569-573 now state the value rule, the unset-means-no-flat-cap behavior, and the explicit cap. The how-to also names the floor's limit ("one idle span can cost more than one miss in total"), which answers my round-1 non-blocking note about the chain.
  3. My non-blocking notes — all addressed. The stale comment in value_test.go:70-72 is rewritten. The refusal logs now name the verdict (substitute.go:167-168, 489-490, 498-499). The counter comments in keeper.go and the docs (advanced-offload.md:797) say the *_over_budget counters count both refusal kinds; the names stay for dashboards, which is a reasonable trade. The affordableSweepBatches comment is rewritten in terms of PingCap(), as reviewer 2 asked.
  4. Reviewer 2's findings — same two as mine, both fixed as above. I checked each fix myself; I add no new proof beyond point 1.

What I checked

  • Last review: round 1, ad0e978, 2026-11-25T20:45:43Z.
  • New commits read: 1 (da58dbf "fix(keepalive): safe sweep cap clamp, docs for the substitute value rule").
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files; the inline list is empty).
  • New items since my last review: the fix commit da58dbf (full diff read, and each changed file around the change), and the author's reply comment at 2026-11-25T20:58:06Z (read in full). The reply records owner decisions of 2026-11-25 in the PR body under "Decided": the strict floor, Ceiling() staying, and the merge yes once review passes. That records the human's permission the behavior-change rule asks for.
  • The clamp's edge cases, by hand: q = +Inf, q huge finite, q NaN, q = 0, q just below and just at planned — all give the same answer as before on arm64 and a correct answer on amd64 (see finding 1 above).
  • The docs diff (config, how-to, advanced-offload) read against the new code paths; each statement matches the code.
  • The commit message carries the DCO sign-off and Assisted-By:, as the conventions ask.
  • Go was not run; live tests are not approved. The author reports build, vet and package tests clean on macOS, Go 1.27.4, and the interim waiver line is present.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Owner decision: merge yes (David Amid, 2026-11-25)

The owner said yes to merge this behavior change once the review passes. Round 2 approved at da58dbf5, and CI is green.

@amiddavid
amiddavid merged commit 3ef26ff into main Nov 25, 2026
12 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

openai OpenAI / Codex traffic and pricing

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

feat(keepalive): value rule for summary and sweep substitute calls

1 participant