Repository navigation
refactor(keepalive): move keep-alive policy resolution out of the proxy (1/2) - #1328
Merged
Merged
Conversation
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
commented
Nov 24, 2026
amiddavid
left a comment
Collaborator
Author
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 | 2c22d2469614 |
approve |
Verdict: approve
Findings
None. I found no behavior change and no defect.
Non-blocking
proxy/keepalivestrategy.go:131—knownPredictorIDsis now the same map object askeepalive.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:90andproxy/keepalivestrategy.go:102—overrideFor,overrideForOpenAI,applyStrategyandapplyStrategyWindowshave 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—keepalivenow importsconfig, which pulls incomponentsandstore. The old code duplicated one constant to avoid this. The import is the point of this PR (FromConfig), and no cycle exists:config,components,storeandtenantimport nothing fromkeepalive. Note only that a future host that wantskeepalivewithout 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.Resolvevs the oldresolvePolicyWindowsbody, 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 oneNow. The old code took two strategy snapshots; the new code takes one. Both differences make one resolution more self-consistent. No user-visible change.EffectiveWaitPlanvs the oldDashWaitPolicybody: same ignore-windows flag (!campaignOn), same 300 s threshold, same zero-policy returns.WaitPlanOnlycopies exactly the seven fields the old inline literal built.keepalive.FromConfigvs the oldproxyapp.cachePolicy: identical field-by-field, including the parked early return andheadTTLMin.ValidOverride,Apply,ApplyOpenAIvs the old proxy code: identical, including the error texts, theMaxUSDPerPingnon-widening, theMaxPings1hminimum, and the OpenAI hold bound.pdec.campaignis never nil whenpdecOK(checkedpredictiveDecideInner), so the eagerly builtCampaignDecision.Tagis safe.ValidStrategyBoundsandvalidIdleBandvs 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:
keepaliveimportsconfigandtenant; neither importskeepaliveback, nor docomponentsorstore. No cycle.proxy.CachePolicyis a type alias ofkeepalive.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 intenantandconfig; the expectations match the code (I traced each case ofTestResolveOrder, 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
commented
Nov 24, 2026
amiddavid
left a comment
Collaborator
Author
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 | 2c22d2469614 |
approve |
Verdict: approve
Findings
None. I could not break the claim "Behaviour: None."
Non-blocking
keepalivenow importsconfig(keepalive/fromconfig.go:6,strategy.go:7,types.go:84). The oldtypes.gosaid "keepalive does not import config" and kept a copy ofheadTTLBytesPerTokenfor that reason. The PR states the change and removes the copy. Note the reach: every importer ofkeepalive(dash, the downstream sidecar plugin) now linksconfigand through itcomponents. No cycle exists today (configandtenantimport nothing fromkeepalive), and the design doc callskeepalivehost-agnostic, whichconfigdoes not break. Watch this edge in part 2 (#1338).proxy/keepaliveoverride.goandproxy/keepalivestrategy.gokeep 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:372tests>= 300*time.Secondwith a literal. The oldDashWaitPolicyhad the same literal. A named constant besideMaxOverrideIdlewould 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); thebestStrategywalk→BestStrategy; theDashWaitPolicybody→EffectiveWaitPlan+WaitPlanOnly. Every difference is a rename, theactiveOverridelookup moved to the caller (still done beforeResolve), or the idle-band check factored intovalidIdleBand— same condition and same error text. resolvePolicyWindows→Resolveorder: 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 andApplyOpenAI. The new code adds a nil check onCampaign.Apply; the proxy always suppliespdec.apply, so no change.- No import cycle:
configimports onlycomponents,modelinfo,store;tenantimports nothing from this repo. Onlydash,proxy,proxyapp,cmdimportkeepalive.keepalivedoes not importproxy— the library/proxy boundary holds, and the move strengthens it. - Type identity:
proxy.CachePolicy = keepalive.Policy(proxy/keepalive.go:26), soFromConfigintoproxyapp.cachePolicyand thesessionOverride↔Overrideconversions line up. All referenced symbols exist (modelinfoconstants,config.HeadTTLBytesPerToken/MaxHeadTTLMinBytes,tenant.Strategyfields and methods,predDecision.applymatchingCampaignDecision.Apply). - Remaining callers:
strategyTZFor,resolveHeadTTL, the ctl routes andcampaign.go's validator calls all reach the library through the kept shims.fmt/strings/timeimports 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-dependencerow 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]>
Collaborator
Author
|
Round 1 replies. Head is now f25929d. Tests: macOS, Go 1.27.4.
Checks: build, vet, |
amiddavid
commented
Nov 24, 2026
amiddavid
left a comment
Collaborator
Author
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 | 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
knownPredictorIDsmap): 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).ValidPredictorRefInchecks a caller-supplied set. The newTestKnownPredictorIDsReturnsACopypins 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 (
keepaliveimportsconfig): 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 inkeepalive/types_test.gois corrected. - Reviewer 2, note 3 (300 s literal): fixed.
OneHourIdleFloor = 300 * time.Second(keepalive/override.go) replaces the literal inEffectiveWaitPlan. 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 andvalidPredictorRefwrapper (semantics identical to the pre-PR proxy-owned map); the new copy test's assertions traced against the implementation; thetypes_test.gocomment 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,
gofmtand the targeted tests clean on macOS, Go 1.27.4.
amiddavid
commented
Nov 24, 2026
amiddavid
left a comment
Collaborator
Author
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 | 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.KnownPredictorIDsis now a function that returns a copy,ValidPredictorRefInchecks 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 newTestKnownPredictorIDsReturnsACopypins 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 againstValidatePredictor(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.Secondsits besideMaxOverrideIdlewith a comment that says what it means.EffectiveWaitPlanuses it. Same value, no behavior change. keepaliveimportsconfig(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 inkeepalive/types_test.gois 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 incampaign.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 itsvalidPredictorRefwrapper, the new copy test, and thetypes_test.gocomment. 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.goandproxy/keepalivestrategy.gouses the old map-styleKnownPredictorIDs; the grep is clean.campaign.go's calls tovalidPredictorRefwork through the new wrapper. Thekeeper.go:2479comment 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
OneHourIdleFloorholds. - 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]>
This was referenced Nov 24, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 inApplyStrategy.keepalive/override.go:Override, the bounds,ValidOverride,Apply,ApplyOpenAI. Strategies and overrides share one idle band check (validIdleBand).keepalive.FromConfigreplacesproxyapp.cachePolicyandheadTTLMin.keepalive.EffectiveWaitPlanreplaces the body ofDashWaitPolicy.keepalivereadsconfig.HeadTTLBytesPerToken. The host copy of the constant is gone.resolvePolicyWindowsnow builds aResolveInputand callsResolve.The campaign decision comes in as a value (
CampaignDecision). The proxy builds it frompredDecisionas is. #1302 files are not edited.New import edge
keepalivenow importsconfig(FromConfig,config.HeadTTLBytesPerToken).configdoes not importkeepalive, directly or through its dependencies (go list -deps ./configshowsinternal/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.goandproxy/keepalivestrategy.go, and asessionOverridestruct 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-dependencerow 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, exceptTestNoHooksKeepsTheBinaryDefaults(known failure onorigin/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 onorigin/main.keepalive/resolve_test.gocover the order, OpenAI, 1-hour never off, bounds, the shared band, wait plan, config mapping.applied == ""guard of the campaign step failsTestResolveOrder. Making a strategy overwriteOneHourOnWaitfailsTestApplyStrategyOnlyTurnsOneHourOn.