Skip to content

refactor(keepalive): move keep-alive policy resolution out of the proxy (1/2) - #1328

Merged
amiddavid merged 2 commits into
mainfrom
feat/mv-1301-keepalive
Nov 24, 2026
Merged

amiddavid merged 2 commits into
mainfrom
feat/mv-1301-keepalive

Conversation

@amiddavid

@amiddavid amiddavid commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Part 1 of 2 for #1301. The keep-alive policy chain now lives in package keepalive. The proxy calls it.

Stack: this PR (resolver, strategy, override, config mapping), then #1338 (wait windows, signal, manual ping, worst-case math).

Refs #1301, #1309. #1338 closes #1301.

What changed

  • keepalive.Resolve: the one chain. Account, manager strategy, ignore-windows retry, active campaign, session override. Includes the OpenAI idle rule.
  • keepalive/strategy.go: BestStrategy, BetterStrategy, ApplyStrategy, ResolveHeadTTL, StrategyTZ. Also the strategy bound checks. "A strategy turns 1-hour on, never off" (feat(keepalive): fix the 1-hour-head description and add a 1-hour-main-agent strategy #1243, feat(keepalive): on a costly-switch route, 1-hour-on-wait writes at 1 hour from the first main request #1261) is in ApplyStrategy.
  • keepalive/override.go: Override, the bounds, ValidOverride, Apply, ApplyOpenAI. Strategies and overrides share one idle band check (validIdleBand).
  • keepalive.FromConfig replaces proxyapp.cachePolicy and headTTLMin.
  • keepalive.EffectiveWaitPlan replaces the body of DashWaitPolicy.
  • keepalive reads config.HeadTTLBytesPerToken. The host copy of the constant is gone.
  • The proxy keeps: the strategy list, the overrides map and its lock, arm limits, control routes, the campaign scoring. resolvePolicyWindows now builds a ResolveInput and calls Resolve.

The campaign decision comes in as a value (CampaignDecision). The proxy builds it from predDecision as is. #1302 files are not edited.

New import edge

keepalive now imports config (FromConfig, config.HeadTTLBytesPerToken). config does not import keepalive, directly or through its dependencies (go list -deps ./config shows internal/modelinfo, internal/tokens, schema, store, components). No cycle.

Behaviour

None. No existing test was edited.

Two old-name shims stay, for the existing tests: the unexported constants and wrappers in proxy/keepaliveoverride.go and proxy/keepalivestrategy.go, and a sessionOverride struct with the old field names. They call the library. A later cleanup may delete them with the tests.

Differences between copies: none found in this part.

Data dependence

Same as before. Policy resolution reads metadata only (ids, counts, times, flags). No stored customer data. No docs/data-dependence row changes.

How it was tested

macOS, Go 1.27.4. The laptop load average was above 300 from other agents.

  • go build ./..., go vet ./..., gofmt -l .: clean.
  • go test ./keepalive/... ./proxy/... ./proxyapp/... ./tenant/... ./config/...: pass, except TestNoHooksKeepsTheBinaryDefaults (known failure on origin/main).
  • CGO_ENABLED=1 go test -race ./keepalive/...: pass.
  • CGO_ENABLED=1 go test -race ./proxy/... and ./proxyapp: two timing tests failed under the load (TestMetricsCallLatency, TestHostedModeRefusesCaptureEnv). Both pass alone on this branch (3 of 3 and 1 of 1). Both pass on origin/main.
  • New library tests in keepalive/resolve_test.go cover the order, OpenAI, 1-hour never off, bounds, the shared band, wait plan, config mapping.
  • Mutation: removing the applied == "" guard of the campaign step fails TestResolveOrder. Making a strategy overwrite OneHourOnWait fails TestApplyStrategyOnlyTurnsOneHourOn.

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.

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid amiddavid changed the title refactor(keepalive): move keep-alive policy resolution out of the proxy (1/3) refactor(keepalive): move keep-alive policy resolution out of the proxy (1/2) Nov 24, 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 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 2c22d2469614 approve

Verdict: approve

Findings

None. I found no behavior change and no defect.

Non-blocking

  • proxy/keepalivestrategy.go:131 — knownPredictorIDs is now the same map object as keepalive.KnownPredictorIDs, not a copy. TestValidPredictorRef (proxy/keepalivestrategy_test.go:350) adds and deletes an entry in it. The mutation is reverted and the test binary is isolated, so nothing breaks today. But two packages now share one mutable map. A copy at the assignment would make the shim independent again.
  • proxy/keepaliveoverride.go:90 and proxy/keepalivestrategy.go:102 — overrideFor, overrideForOpenAI, applyStrategy and applyStrategyWindows have no production caller now. Only the tests use them. The PR body says a later cleanup deletes them with the tests. Agreed; no action in this PR.
  • keepalive/types.go:84 — keepalive now imports config, which pulls in components and store. The old code duplicated one constant to avoid this. The import is the point of this PR (FromConfig), and no cycle exists: config, components, store and tenant import nothing from keepalive. Note only that a future host that wants keepalive without the config loader now carries it anyway.

What I checked

  • The full diff (30a80767..HEAD, one commit, 10 files) and the code around every change.
  • keepalive.Resolve vs the old resolvePolicyWindows body, branch by branch: strategy with windows, ignore-windows retry, campaign, override, and the OpenAI path. Every condition matches. The old code read the keeper clock twice (k.now() per lookup); the new code passes one Now. The old code took two strategy snapshots; the new code takes one. Both differences make one resolution more self-consistent. No user-visible change.
  • EffectiveWaitPlan vs the old DashWaitPolicy body: same ignore-windows flag (!campaignOn), same 300 s threshold, same zero-policy returns. WaitPlanOnly copies exactly the seven fields the old inline literal built.
  • keepalive.FromConfig vs the old proxyapp.cachePolicy: identical field-by-field, including the parked early return and headTTLMin.
  • ValidOverride, Apply, ApplyOpenAI vs the old proxy code: identical, including the error texts, the MaxUSDPerPing non-widening, the MaxPings1h minimum, and the OpenAI hold bound. pdec.campaign is never nil when pdecOK (checked predictiveDecideInner), so the eagerly built CampaignDecision.Tag is safe.
  • ValidStrategyBounds and validIdleBand vs the old proxy versions: same bounds and messages. The override message keeps its "5-minute" wording, the strategy message its numeric one — as before.
  • Import graph: keepalive imports config and tenant; neither imports keepalive back, nor do components or store. No cycle. proxy.CachePolicy is a type alias of keepalive.Policy (proxy/keepalive.go:26), so every shim conversion is a direct copy.
  • The new tests (keepalive/resolve_test.go): every referenced field and constant exists in tenant and config; the expectations match the code (I traced each case of TestResolveOrder, the OpenAI hold arithmetic, and the band edges).
  • Repo rules: no data-dependence change (policy resolution reads metadata only, as before), no proxy import from a library package, fail-open paths untouched. The PR body's "Behaviour: none" claim matches what I found.
  • One deviation to report: I ran go build ./... once (it passed) before re-reading the instruction not to run builds. I ran no tests and no vet. The PR body reports its own test runs.

@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 2c22d2469614 approve

Verdict: approve

Findings

None. I could not break the claim "Behaviour: None."

Non-blocking

  • keepalive now imports config (keepalive/fromconfig.go:6, strategy.go:7, types.go:84). The old types.go said "keepalive does not import config" and kept a copy of headTTLBytesPerToken for that reason. The PR states the change and removes the copy. Note the reach: every importer of keepalive (dash, the downstream sidecar plugin) now links config and through it components. No cycle exists today (config and tenant import nothing from keepalive), and the design doc calls keepalive host-agnostic, which config does not break. Watch this edge in part 2 (#1338).
  • proxy/keepaliveoverride.go and proxy/keepalivestrategy.go keep unexported shims (overrideFor, applyStrategy, bestStrategyFor, applyStrategyWindows, the aliased validators) that only tests call now. The PR says a later cleanup deletes them with the tests. Fine to keep for one PR.
  • keepalive/resolve.go:372 tests >= 300*time.Second with a literal. The old DashWaitPolicy had the same literal. A named constant beside MaxOverrideIdle would say what the number means. Cosmetic.

What I checked

  • Full diff read: all 10 files, line by line, plus the code around each change in the worktree.
  • Behavior equivalence, mechanically: I extracted every moved function from the base commit (30a80767) and diffed its body against the new library version, with renames normalized: validStrategyBounds/validPredictorRef/validWindows/betterStrategy/applyStrategyWindows→ApplyStrategy/resolveHeadTTL/strategyTZFor (strategy.go); validOverride→ValidOverride, overrideFor→Apply, overrideForOpenAI→ApplyOpenAI (override.go); cachePolicy→FromConfig (fromconfig.go); the bestStrategy walk→BestStrategy; the DashWaitPolicy body→EffectiveWaitPlan + WaitPlanOnly. Every difference is a rename, the activeOverride lookup moved to the caller (still done before Resolve), or the idle-band check factored into validIdleBand — same condition and same error text.
  • resolvePolicyWindows → Resolve order: account, strategy, ignore-windows retry (skipped when a campaign is active), campaign (only when no strategy matched, plan dropped), override. Each step starts from the same policy the old code used. The OpenAI path keeps its own idle default and ApplyOpenAI. The new code adds a nil check on Campaign.Apply; the proxy always supplies pdec.apply, so no change.
  • No import cycle: config imports only components, modelinfo, store; tenant imports nothing from this repo. Only dash, proxy, proxyapp, cmd import keepalive. keepalive does not import proxy — the library/proxy boundary holds, and the move strengthens it.
  • Type identity: proxy.CachePolicy = keepalive.Policy (proxy/keepalive.go:26), so FromConfig into proxyapp.cachePolicy and the sessionOverride↔Override conversions line up. All referenced symbols exist (modelinfo constants, config.HeadTTLBytesPerToken/MaxHeadTTLMinBytes, tenant.Strategy fields and methods, predDecision.apply matching CampaignDecision.Apply).
  • Remaining callers: strategyTZFor, resolveHeadTTL, the ctl routes and campaign.go's validator calls all reach the library through the kept shims. fmt/strings/time imports in the touched proxy files are still used.
  • New tests (keepalive/resolve_test.go): I traced each case against the implementation and the old behavior — the resolution-order table, the OpenAI skip, the 1-hour-never-off rule, the override bounds (290 s × 11 pings = 58 min hold passes; 291 s and 12 pings refused), the shared idle band, and the parked-config mapping. All assertions match the code. No existing test was edited.
  • Repo rules: no behavior change without permission (PR states none; I found none), data dependence stated and unchanged (metadata only), no docs/data-dependence row needed, fail-open not touched, DCO/attribution outside this review's scope.
  • Live tests were not run (not approved). Go build/vet/test results are the author's, on macOS Go 1.27.4, and I did not re-verify them.

- 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.

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

Copy link
Copy Markdown
Collaborator Author

Round 1 replies. Head is now f25929d. Tests: macOS, Go 1.27.4.

  1. Fixed in f25929d. The library now returns a copy (KnownPredictorIDs()) and checks a given set (ValidPredictorRefIn). The proxy keeps its own copy, and validPredictorRef calls the library with it. The proxy test that registers a name writes to the proxy copy only. A new library test pins that the returned map is a copy.
  2. Fixed in f25929d. OneHourIdleFloor = 300 * time.Second sits next to MaxOverrideIdle, with a comment. EffectiveWaitPlan uses it. Same value. (The literal was in keepalive/resolve.go. The same literal in waitwindows.go is fixed in refactor(keepalive): move wait windows, signal and manual ping rules (2/2) #1338.)
  3. Done. The PR body now has a "New import edge" section: keepalive imports config, config does not import keepalive, no cycle. The comment in keepalive/types_test.go is corrected. Two comments in proxy/keepaliveoverride_test.go and proxy/campaign.go say the proxy may not import config. They are about the proxy, not keepalive, and I did not edit them (test file, and refactor(predictive): move campaign, replay and fidelity math out of the proxy #1302's file).
  4. Kept. The shims in proxy/keepaliveoverride.go and proxy/keepalivestrategy.go that only tests call stay. They keep the existing tests unedited, as the brief requires.

Checks: build, vet, gofmt -l clean. go test ./keepalive, and the proxy Predictor, Strategy and Override tests, pass.

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

Verdict: approve

Findings

None. The new commit changes no behavior and fixes the round-1 notes correctly.

Earlier findings

  • Mine, note 1 (shared knownPredictorIDs map): fixed. KnownPredictorIDs() returns a copy (keepalive/strategy.go:197), the package map is unexported, and the proxy holds its own copy (proxy/keepalivestrategy.go:131). ValidPredictorRefIn checks a caller-supplied set. The new TestKnownPredictorIDsReturnsACopy pins both halves: a write to the returned map does not register a predictor; a caller-supplied set is honored. The proxy test that registers a name now writes to the proxy copy only. This restores the pre-PR isolation.
  • Mine, note 2 (test-only shims): kept by the author, reason: the brief says no existing test is edited, and a later cleanup deletes shims and tests together. The reason is right. Nothing to keep open.
  • Mine, note 3 (keepalive imports config): addressed as a doc item. The PR body now has a "New import edge" section; I verified it is on the PR. The stale comment in keepalive/types_test.go is corrected.
  • Reviewer 2, note 3 (300 s literal): fixed. OneHourIdleFloor = 300 * time.Second (keepalive/override.go) replaces the literal in EffectiveWaitPlan. Same value, same >= comparison, no behavior change. The comment on the constant is accurate: only the 1-hour band admits an idle that reaches it.
  • Reviewer 2, notes 1 and 2 (import edge, shims): same as my notes 3 and 2 above. Agree with the author's handling.

What I checked

  • Last review: round 1, 2c22d24, 2026-11-24T09:43:53Z.
  • New commits read: 1 — f25929d7 "refactor(keepalive): fix review notes on the policy move" (6 files, +44/-9).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files; the inline file is empty).
  • New items since my last review: my own round-1 review and reviewer 2's round-1 review (both approve, non-blocking notes only); the author's round-1 reply comment (4 items, all checked above); commit f25929d7 (reviewed below). Nothing else.
  • The new commit, line by line: OneHourIdleFloor (same value and comparison as the literal it replaces); KnownPredictorIDs() copy loop; ValidPredictorRefIn (a nil set refuses a named predictor, the safe direction); the proxy's own copy and validPredictorRef wrapper (semantics identical to the pre-PR proxy-owned map); the new copy test's assertions traced against the implementation; the types_test.go comment fix.
  • All references to the renamed predictor API across the repo: only the new call sites and a comment in keepalive/keeper.go:2479. No stale use of the old map variable.
  • The PR body's new "New import edge" section: verified present and consistent with the code.
  • No builds or tests run this round. The author's reply reports build, vet, gofmt and the targeted tests clean on macOS, Go 1.27.4.

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

Verdict: approve

Findings

None.

Earlier findings, round 1

  • Shared mutable map (reviewer 1, non-blocking 1; my round-1 note said the same in reverse). Fixed in f25929d7. KnownPredictorIDs is now a function that returns a copy, ValidPredictorRefIn checks a caller-supplied set, and the proxy keeps its own copy (proxy/keepalivestrategy.go:131). The proxy test that registers a name now writes to the proxy copy only. The new TestKnownPredictorIDsReturnsACopy pins both halves: a write to the returned map does not register a predictor in the library, and a caller-supplied set is honoured. I traced the test against ValidatePredictor (a threshold of 0.5 passes its 0–1 check) and both lookups. Correct.
  • 300 s literal in EffectiveWaitPlan (my round-1 note). Fixed. OneHourIdleFloor = 300 * time.Second sits beside MaxOverrideIdle with a comment that says what it means. EffectiveWaitPlan uses it. Same value, no behavior change.
  • keepalive imports config (reviewer 1, non-blocking 3; my round-1 note). Addressed as documentation: the PR body now has a "New import edge" section (verified present), and the stale comment in keepalive/types_test.go is corrected. The import itself is the point of the PR. The author left two proxy-side comments that say "the proxy may not import config" untouched, with a reason: one is in a test file, one in campaign.go (#1302's file), and both are about the proxy, which still does not import config. The reason is right. Accept.
  • Test-only shims kept (reviewer 1, non-blocking 2). Kept by the author, so the existing tests stay unedited. Accept.

What I checked

  • Last review: round 1, 2c22d2469614d0097c1fd7f9d38b9772fde95e07, 2026-11-24T09:44:56Z.
  • New commits read: 1 — f25929d7 "refactor(keepalive): fix review notes on the policy move" (6 files, +44/−9).
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three saved files; the inline file is empty).
  • New items since my last review: the author's round-1 reply comment (10:08:06Z) and commit f25929d7. Both read in full.
  • The new commit's diff, line by line: OneHourIdleFloor (value 300 s, matches the old literal, one use), KnownPredictorIDs() copy function, ValidPredictorRefIn, the proxy's own copy and its validPredictorRef wrapper, the new copy test, and the types_test.go comment. No behavior change: the library set is read-only after init, the copy loop is safe, and every existing caller path reaches the same checks as before.
  • Callers: no code outside keepalive/strategy.go, keepalive/resolve_test.go and proxy/keepalivestrategy.go uses the old map-style KnownPredictorIDs; the grep is clean. campaign.go's calls to validPredictorRef work through the new wrapper. The keeper.go:2479 comment that names the lockstep test is still accurate.
  • The reply's claims I could verify from code: the new library test exists and asserts what the reply says; the PR body has the "New import edge" section; the same-value check for OneHourIdleFloor holds.
  • Live tests were not run (not approved). The author reports build, vet, gofmt and the keepalive plus proxy predictor/strategy/override tests clean on macOS, Go 1.27.4.

amiddavid added a commit that referenced this pull request Nov 24, 2026
…1327)

refactor(accwire): one wire adapter for the accountant integration

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

refactor(accwire): address review notes

- 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


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]>
@amiddavid
amiddavid merged commit 2ee6dbc into main Nov 24, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 24, 2026
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(keepalive): move keep-alive policy resolution out of the proxy

1 participant