Repository navigation
refactor(keepalive): move wait windows, signal and manual ping rules (2/2) - #1338
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
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 | ee80f77770fa |
approve |
Verdict: approve
Findings
None. I checked every moved block against the code it replaced. Each one keeps its old behavior.
Non-blocking
proxy/clientsignal.go:61—compactRaceMarginis now an unused alias. Nothing inproxyreads it after the move. Go permits an unused constant, so it compiles. Drop it, or say in the comment that it is kept for compatibility.keepalive/waitwindows_test.go:398— test nameTestResolveWithWindowsAnOneHourIdleDropsTheReadingreads "An One Hour". Cosmetic only.
What I checked
I read the full diff (2c22d246..ee80f777, one commit, 11 files) and the code around each change.
ResolveWithWindowsvs the old inline block inrecordTouch(proxy/keepalive.go:391-407). I compared both branch by branch: theWaitPlan && trackedgate, the tracker-only cause, the merged-cause condition (open != nil && !OpenAI && !OneHourTier()), the resolution order (wide first, then today),planEligible(Idle < 300s),causeFor,holds,pingsOf, and all three switch outcomes, including which paths returnopenand which return nil. Identical. The callbacks keep the old laziness:OneHourTierandCauseOf(open)are read only where the old code read them.ApplyClientSignal+NormalizeSignalvs the oldkeeper.signalandclientSignalvalidation (proxy/clientsignal.go:149-181, keepalive/lifecycle.go:130-210). The closed sets match the oldlifecycleEvents/lifecycleKindsentry for entry. The "other" rewrite for a new SessionEnd reason matches. The retire-before-mark order holds:afterRetire(the campaign call) runs beforeMarkEnded, as before. For SessionEnd the campaign cutoff is the zero time, as before; for compact it isnow - CompactRaceMargin.signalAppliedcounts the same events. The debug log now fires once per event withappliedandretired; the PR names this and no metric or test reads it.OneHourFirstFor(keepalive/onehour.go:498-516) vs the old closure inproxy/keepalive.go. Same gates (threadID != "" || !toolsDeclared || session == ""), same lazy policy resolution, same mode check, same arguments intoOneHourFirst.CanKeepAlive(keepalive/resolve.go:126-135) vs the old tail ofcanPing. Same logic;toolSeenis read only whenWaitPlanis on.ManualPingBlock,ManualSavedUSD,ManualPingMinGap(keepalive/manual.go) vs proxy/manualping.go. Same gate order (1-hour live before cold), same TTL edge (!now.Before(lastTouch.Add(ttl))), same saved-USD clamps.WorstCasePings,PingUSD(keepalive/override.go) vs the oldworstCaseandarmedViewin proxy/keepalivectl.go.time.Until(o.until)equalsUntil.Sub(time.Now()); theIdle <= 0and minimum-1 clamps match.o.lib()is a field copy of the samesessionOverride, so no policy drift.- Arm-dialog defaults (proxy/keepalivectl.go:156-160).
config.DefaultKeepAliveIdleis 240 andconfig.DefaultKeepAliveMaxPingsis 2 (config/config.go:288-290). Same values as the literals they replace. - Nil safety.
ApplyClientSignalandOneHourFirstnil-check the receiver; the proxy wrapper checksh.keeper.Keeper != nilbefore building theOneHourFirstForclosure. The removed proxy wrappers (retireSession,markEnded,retireSessionStartedBefore) were pure forwarders. - Boundaries.
keepaliveimports onlytime,tenant,bschemasandwaitcause(test). No library package importsproxy. No data-dependence change: the moved code works on ids, counts and times only, and the PR says so. - Tests. The new
keepalive/waitwindows_test.gocovers every new exported function. I read each test against the code: the helper types (tenant.Strategy,tenant.Window,ResolveInput,ManualResult,Options) and the package test helpers (allDay,t0,newFake) all exist with matching signatures. - The PR states no behavior change. I found none beyond the named debug-log difference.
One process note: I ran go build ./keepalive/... ./proxy/... once before re-reading the "live tests are NOT approved" rule. It passed. It changed nothing. All other checking was by reading.
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 | ee80f77770fa |
approve |
Verdict: approve
Findings
None. The PR moves logic from proxy/ into the keepalive library. I compared each moved block against the base commit line by line. The behavior stays the same in every case I traced.
Non-blocking
proxy/clientsignal.go:61—compactRaceMarginis now dead. Nothing inproxyreads it after the move. Go compiles an unused constant, so it is harmless. Either delete it, or keep it only if a follow-up needs the alias.manualPingMinGap(proxy/manualping.go:45) stays used, so the two aliases now differ.keepalive/lifecycle.go:156— the doc says "SignalResult is what ApplyClientSignal did." The sentence names the wrong thing: it is the result type of the old proxysignalpath. One line of rewording would fix it.keepalive/waitwindows_test.go:398— the test nameTestResolveWithWindowsAnOneHourIdleDropsTheReadinghas a typo ("AnOneHour").
What I checked
- Every changed line in
keepalive/lifecycle.go,manual.go,onehour.go,override.go,resolve.go,waitwindows.go,waitwindows_test.go,proxy/clientsignal.go,proxy/keepalive.go,proxy/keepalivectl.go,proxy/manualping.go, against base2c22d246. - Signal route equivalence.
NormalizeSignal(keepalive/lifecycle.go:149) reproduces the oldlifecycleEvents/lifecycleKindscheck, including the "other" reading of a newSessionEndreason. I traced each event and kind pair: accept, refuse, and rewrite decisions match the oldclientSignalhandler. The check order moved beforescopedClientID; the 400 answers stay the same. ApplyClientSignalequivalence. ForSessionEnd: retire, then the campaign hook, then the end mark — the old order. ForSessionStart+compact: cutoffnow - 2 s, retire, campaign hook, no end mark — the old behavior. The campaign hook gets a zero cutoff forSessionEndand the margin cutoff for compact, as before. ThesignalAppliedcounter fires on the same events.ResolveWithWindowsequivalence. I comparedkeepalive/waitwindows.go:44against the removed block inproxy/keepalive.go. The gate (Account.WaitPlan && Tracked), the lazyOneHourTierread (short-circuited behindopen != nil && !OpenAI, as before),planEligible,causeFor,holds,pingsOf, and all three switch outcomes match. Theopen = nildrop in the 1-hour branch is preserved through the third return value.OneHourFirstFor,CanKeepAlive,WorstCasePings,PingUSD,ManualPingBlock,ManualSavedUSD. Each matches the removed proxy code.CanKeepAlivereadstoolSeenonly when the plan is on, because&&short-circuits — the old laziness holds.worstCasestill returns zero output for a zero idle, and clamps to at least 1 ping.- Compile-level checks by reading.
config.DefaultKeepAliveIdle/MaxPingsexist as untyped int constants (config/config.go:288-290).CachePolicyis an alias ofkeepalive.Policy(proxy/keepalive.go:26).sessionOverride.lib()returns akeepalive.OverridewithPolandUntil. Test helpers (allDay,t0,newFake) exist once each in the package;newTestKeeperis new and unique. - Repo rules. The
keepalivepackage imports no proxy package, so the library boundary holds. The PR changes no feature's data dependence, so nodocs/data-dependence/row is needed. I found no behavior change for any edge case, so the human-permission rule for behavior changes is not triggered. - Test coverage.
waitwindows_test.gocovers each new exported function: both window readings, the never-fewer-pings rule, the 1-hour drop, the 1-hour tier skip, the gates, the closed sets, and the cost math. The proxy route tests (clientsignal_test.go,manualping_test.go) still exercise the moved behavior end to end.
Live tests were not approved, so I read the code only and did not build or run anything.
- 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]>
Part 2 of 3 for #1301. Move more keep-alive decisions out of the proxy: - ResolveWithWindows: today's windows reading against the wide one (was the middle of recordTouch). - CanKeepAlive and Keeper.OneHourFirstFor: the record-time gate and the 1-hour apply hook decision (was canPing and oneHourFirstFor). - Keeper.ApplyClientSignal and NormalizeSignal: what SessionEnd and SessionStart(compact) retire, the closed event sets, and CompactRaceMargin (was keeper.signal). - ManualPingBlock, ManualSavedUSD, ManualPingMinGap: the cold gate, the 1-hour touch conflict and the saved-USD math of the Ping button. - Override.WorstCasePings and PingUSD: the worst-case spend math. - The arm dialog defaults now read config.DefaultKeepAliveIdle and config.DefaultKeepAliveMaxPings (same values, 240 and 2). The proxy keeps HTTP decode and encode, the credential, and the campaign call. No behaviour change. Refs #1301, #1309. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
- Restore the exact cg.client_signal debug lines (same fields per case). - Remove the unused compactRaceMargin alias. - Use OneHourIdleFloor in the window resolver. - Fix the SignalResult doc and a test name. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
ee80f77 to
ce99757
Compare
|
Round 1 replies. Head is now ce99757 (rebased on #1328 at f25929d). Tests: macOS, Go 1.27.4.
Checks: build, vet, |
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 | ce9975770a00 |
approve |
Verdict: approve
Findings
None. The fix commit ce997577 changes docs, names and debug lines only. I found no behavior change in it.
Non-blocking
keepalive/lifecycle.go:156— the type-level comment still reads "SignalResult is what ApplyClientSignal did." My round-1 note pointed at this line. The field docs below it are now fixed and accurate, so the substance is gone. Only this one sentence remains odd. Cosmetic; drop it or leave it.
Round-1 findings, status
- Reviewer 2,
compactRaceMargindead alias — fixed.ce997577deletes the constant fromproxy/clientsignal.go. Nothing inproxyorkeepalivereferences it now. - Reviewer 2,
SignalResultdoc — partly fixed. The field docs are rewritten and now match the code exactly (Appliedtrue even with nothing live,Cutoffzero for SessionEnd, main-thread-only retirement before the cutoff for compact). The type-level sentence remains; see Non-blocking. - Reviewer 2, test name typo — fixed. Renamed to
TestResolveWithWindowsAOneHourIdleDropsTheReading(keepalive/waitwindows_test.go:81). No stale reference to the old name. - Reviewer 1, unused alias and test name — the same two items; both fixed as above.
- Reviewer 1, the debug-log difference — fixed.
ce997577restores the pre-move lines: an acted event logsevent, kind, session, retired; any other logsevent, kind, session, applied=false. Same fields per case, same Debug level. I checked them against the base commit'ssignal. ThesignalAppliedcounter still fires on the same events. The PR's Behaviour section now says "None", which is correct.
What I checked
- Last review: round 1,
ee80f77770fa3575b218c619f92d57fbe4fb5c8b, 2026-11-24T09:43:37Z. - New commits read: 3 (
f25929d7fix review notes on the policy move — the new base from #1328;68c8d6aathe rebased PR commit;ce997577fix review notes on the signal and window move). - Read in full: 2 reviews, 1 comment, 0 inline comments (from
.review-in-reviews.txt,.review-in-comments.txt,.review-in-inline.txt), plus the PR description. - New items since my last review, and what I did:
- The rebase onto
f25929d7. I diffedee80f777..68c8d6aaagainst2c22d246..f25929d7. The content hunks are identical; only theindexheader lines differ. The rebase changed no code. f25929d7(base side). Read in full. It definesOneHourIdleFloor = 300 * time.Second(keepalive/override.go:37), makesKnownPredictorIDsa copy-returning function, and addsValidPredictorRefIn. Coherent on its own; it belongs to #1328.ce997577. Read the full diff and the files around each change:keepalive/waitwindows.go:44—planEligiblenow usesOneHourIdleFloorin place of300*time.Second. Same value, so no behavior change. Thetimeimport is dropped; notime.use remains in the file, so it compiles.proxy/clientsignal.go— the restored debug lines match the pre-move fields per case;keepaliveandtimeimports stay used.keepalive/lifecycle.go— field docs verified against the code, line by line.keepalive/waitwindows_test.go:81— rename only.
- The author's reply comment (2026-11-24T10:08:08Z). I checked each of its five claims against the code. Items 5 to 8 are the fixes above. Item 9 (
OneHourIdleFloor) is verified same-value. The reported test runs are the author's; I did not run them, because live tests are not approved.
- The rebase onto
- The full PR diff
f25929d7..HEAD(11 files) matches the round-1 content plus the fix commit. I read it again against the round-1 reading; nothing else moved.
Live tests were not approved, so I read the code only and did not build or run anything.
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 | ce9975770a00 |
approve |
Verdict: approve
Findings
None.
Earlier findings
- Mine,
compactRaceMarginunused alias — fixed in ce99757. The constant is gone fromproxy; a grep overproxy/andkeepalive/finds no reference. - Mine, test-name typo — fixed in ce99757. The test is now
TestResolveWithWindowsAOneHourIdleDropsTheReading. - Reviewer 2,
SignalResultdoc — fixed in ce99757. Each field now says what it means. I read the new doc against the code; every sentence matches (Appliedtrue for both acted events even with nothing live,Cutoffzero for SessionEnd,Retiredcan be 0). - Reviewer 2, the debug-log difference — fixed in ce99757. The two log lines now carry the same fields per case as the pre-move code: an acted event logs
event, kind, session, retired; any other logsevent, kind, session, applied=false. One residual ordering difference stays: for an acted event the line now fires after the end mark instead of between the campaign call and the mark. Log order only; nothing reads it.
Non-blocking
None new.
What I checked
- Last review: round 1, ee80f77, 2026-11-24T09:42:18Z.
- New commits read: 3 —
f25929d7"fix review notes on the policy move" (the new base, from #1328),68c8d6aa"move wait windows, signal and manual ping rules" (the rebased round-1 head),ce997577"fix review notes on the signal and window move". - Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files).
- New items since my last review, and what I did about each:
f25929d7(new base). I read its full diff (2c22d246..f25929d7). It addsOneHourIdleFloor, makesKnownPredictorIDsa copy-returning function, and points the proxy at its own copy. It is outside this PR's diff and belongs to #1328's review. I checked only its interaction with this PR:OneHourIdleFlooris 300 s, so the two places that switched to it (EffectiveWaitPlan,planEligible) keep their old values.68c8d6aa(rebase). I verified it changes nothing I reviewed:git diff ee80f777 68c8d6aadiffers fromgit diff 2c22d246 f25929d7in nothing, and the PR diff against its new base differs from my round-1 diff only in blob hashes and hunk offsets inoverride.goandresolve.go— the two filesf25929d7touched. No content change.ce997577(fix commit). Read in full, all four changes verified, listed under "Earlier findings" and below.- Author's comment at 10:08:08Z. Read. Each claim in it checks out against the commit.
ce997577details.planEligiblenow readsp.Idle < OneHourIdleFloor(keepalive/waitwindows.go:44). Same value as the old300*time.Secondliteral, and the constant's own doc inoverride.go:34-37states exactly this band. Thetimeimport was dropped with the literal; a grep finds notime.use left in the file, so the drop is correct.- The restored debug lines (proxy/clientsignal.go:173-180) match the pre-move field sets exactly.
signalAppliedstill counts the same two events. - The
SignalResultdoc rewrite and the test rename change no code paths.
- I did not build or run anything this round. All checks were by reading.
Comment only. Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
|
|
Assisted-By: Claude Opus 5.5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]> # Conflicts: # keepalive/override.go # keepalive/resolve.go # proxy/clientsignal.go
|
Merged The merge was not clean. 3 conflicts, resolved by hand:
This PR's own diff is unchanged. The changed lines of Checks at 4ffa09a (macOS, Go 1.27.4): build, vet and |
Summary
Part 2 of 2 for #1301. It stacks on #1328 (this PR targets that branch). It moves the wait-window reading, the record-time gates, the client signal rules and the manual ping rules into
keepalive.Closes #1301. Refs #1309.
What changed
keepalive.ResolveWithWindows: today's windows reading against the wide one. It was the middle ofrecordTouch. The host passes callbacks (tracker cause, 1-hour tier, policy chain), so each is read only where it was read before.keepalive.CanKeepAliveandKeeper.OneHourFirstFor: the decision part ofcanPingandoneHourFirstFor. The host keeps the kill switch, audit-sink, provider and session checks.Keeper.ApplyClientSignal,NormalizeSignal,CompactRaceMargin: what SessionEnd and SessionStart(compact) retire, and the closed event sets. A hook runs between the retire and the end mark, so the host can tell the campaign (refactor(predictive): move campaign, replay and fidelity math out of the proxy #1302 code is called, not edited).ManualPingBlock,ManualSavedUSD,ManualPingMinGap: the cold gate, the 1-hour touch conflict and the saved-USD math.Override.WorstCasePings,PingUSD: the worst-case spend math.recIdleSecondsDefault,recMaxPingsDefault) now readconfig.DefaultKeepAliveIdleandconfig.DefaultKeepAliveMaxPings. The values are the same (240 and 2).The proxy keeps: HTTP decode and encode, the credential, the price lookup (
dash.NextRequestUSD), the control routes and the campaign call.Behaviour
None. The
cg.client_signaldebug lines are unchanged (same events, fields and level).No existing test was edited.
Data dependence
Same as before. Metadata only (ids, counts, times, flags). No
docs/data-dependencerow changes.Not moved, and why
keeper.recordTouchstill builds thekeepalive.Recordand calls the campaign. That part is transport and refactor(predictive): move campaign, replay and fidelity math out of the proxy #1302 code.dash.PingStateanddash.OneHourTouchmapping stays in the host. It is a type copy, not a decision.proxy/campaign.gostill calls the shimsvalidStrategyBoundsand others. refactor(predictive): move campaign, replay and fidelity math out of the proxy #1302 owns that file. The shims call the library.How it was tested
macOS, Go 1.27.4. The laptop load average was 50 to 300 from other agents.
go build ./...,go vet ./...,gofmt -l .: clean.go test ./keepalive/... ./proxy/... ./proxyapp/... ./dash/...: pass, exceptTestNoHooksKeepsTheBinaryDefaults(known failure onorigin/main).CGO_ENABLED=1 go test -race ./keepalive/...: pass.CGO_ENABLED=1 go test -race ./proxy/: onlyTestMetricsCallLatencyfailed, a latency test under load. It passes alone (4 of 4 runs) and onorigin/main.keepalive/waitwindows_test.go. Mutations: flippingpingsOf(todayPol) > pingsOf(pol)failsTestResolveWithWindowsNeverPlansFewerPingsThanToday. DroppingMarkEndedfailsTestApplyClientSignal.