Repository navigation
Fix: Give recordFor the keeper's identity and prefix-rewrite flag; refs #2154's open-task counts - #2170
Conversation
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 14 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The Identity change is right, and go vet, gofmt and go test ./core/plugins/contextguru/... pass on this head. Two of the three fixes do not do what the PR says, though:
- #2163: the
PrefixRewrittenmapping is the same as in #2169. The blocker from my review of #2169 is still there: the request that resolves the 1-hour probe is the compaction call, and this change leavesPrefixRewrittenfalse on it. - #2154: with
OpenTasksset, a background wait now readsbackground. Butkeepalive.LongWaitis true forbackgroundandteammatetoo, and the scan's teammate count is never read. So 1-hour probes still start on these waits.
Details and probes are inline.
Author: boazdavid (CONTRIBUTOR association, admin repo permission — maintainer)
Areas reviewed: Go (contextguru plugin recordFor, and the context-guru v0.7.9 keepalive, waitcause, thread and agent code it calls), tests
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing. The annotations are only the usual cache, Node 20 and macOS-queue notices. I could not fetch the Go CI (core) job log from here (TLS timeout), so I ran the package tests locally.
Notes:
Recordis an in-process struct, so no JSON decoder is involved.- On the pinned v0.7.9, dropping
Agent:leavesKeepAliveReport.Agentempty on ping reports. NeitherlogEmitternorpingFromReportreads that field, so nothing changes in Cortex today.
| return false | ||
| } | ||
| _, inherits := res.InheritsFrom() | ||
| return res.AfterCompaction || inherits |
There was a problem hiding this comment.
must-fix: this does not cover the request that resolves the probe, so #2163's own check ("a client compaction right after a 1-hour probe gives 1-hour probe released") still fails. It is the same point I raised on #2169, and this PR carries that code over unchanged.
I ran a probe test on this head with the real tracker (configured(t, "{}") + invokeReq, then keeperKey and recordFor on each request). The sequence was turn 1, turn 2, the compaction call (a last user turn starting "Your task is to create a detailed summary of ..."), then the post-compaction request:
turn1 key.thread="" after=false PrefixRewritten=false
turn2 key.thread="" after=false PrefixRewritten=false
compaction call key.thread="" after=false PrefixRewritten=false
post-compaction key.thread="" after=true PrefixRewritten=true
The compaction call has the probe's key. resolveOneHourProbe runs on the first Record for that key and deletes the probe unconditionally (onehour.go:280-281). So the compaction call resolves the probe with PrefixRewritten=false. When the post-compaction request arrives with the flag set, there is no probe left. In the #2163 log, this is the 01:35:16 return and the WARN at 01:35:27; the 55k request at 01:35:28 is the post-compaction one.
The InheritsFrom half does not reach the probe either. Inherits is set only for a new thread id, so keeperKey puts that request on a key that holds no probe.
Suggested fix: keep the agentCompaction verdict that resolveThread already computes on reqThread (for example reqThread{res thread.Result; compactionCall bool}), and set PrefixRewritten on the compaction call too. Do not re-run IsClientCompaction on pctx.Body here: by finish time the engine may have rewritten the body, and stripOwnHeaders has removed x-context-guru-request-kind. At worst this releases a probe that would have proved the tier, which is the safe direction. It goes beyond the proxy's rule, so context-guru should make the same change, ideally through the shared library function from point 2 of the issue.
There was a problem hiding this comment.
Fixed in c7e5ff2. thread.go now keeps compactionCall on reqThread, set from the same agentall.IsClientCompaction check resolveThread already runs. prefixRewritten reads it first, so the compaction call itself gets PrefixRewritten=true, not only the post-compaction request.
Added TestPrefixRewrittenCoversTheCompactionCallItself (repro_2163_test.go), which drives the real tracker through your 4-step sequence (first turn, compaction call, post-compaction, next turn) and checks both steps. Mutation-checked: reverting the compaction-call check fails the test at the "compaction call" step with prefixRewritten = false, want true.
| UsageOK: parsercommon.Kind(inf.PresentKinds)&(parsercommon.KindCacheRead|parsercommon.KindCacheWrite) != 0, | ||
| ToolUseNames: toolUseNames, | ||
| ToolUseIncomplete: false, | ||
| OpenTasks: openTasks(provider, pctx.Body, identity), |
There was a problem hiding this comment.
must-fix: this does not stop the 1-hour probe on these waits, which is the main claim behind "Fixes #2154" (commit message: "it started the 1-hour probe on waits that return in seconds"). The issue's first check ("On an agent-team session, a wait on teammates no longer starts a 1-hour probe") still fails, for two reasons:
LongWaittreatsbackgroundandteammateas long waits. In v0.7.9 (and on context-gurumain),keepalive.LongWaitreturns true forhuman,unknown,backgroundandteammate(waitplan.go:69-79). I checked:LongWait("background", false)andLongWait("teammate", false)are bothtrue. So moving the cause fromhuman/unknowntobackgroundkeeps the 1-hour-on-wait branch (keeper.go:1096). The new cause also lowers the floor fromMinPrefixTokensto the tool-wait floor (WaitMinPrefix). Background waits with a prefix between the two floors then become eligible, so this could start more probes, not fewer.- The teammate count is never read.
WaitingFormerges onlyopen.Background. Its doc says the teammate count "is the tracker's alone", andTaskCountssays Teammate "never changes a plan". The tracker iskeepalive.Options.OpenTasks, and the plugin does not set it (keepalive.New(keepalive.Options{Dispatcher: p.disp}), plugin.go:484). So a teammate wait still readshuman(Claude Code) and gets the person plan.
What the change does deliver is the background half of the second symptom: a background wait gets the background ping count and floor.
To close #2154, wire Options.OpenTasks from a waitcause.Tracker, as proxy/keepalive.go does, so teammate waits classify. The probe rule (LongWait) also needs a context-guru change. Otherwise, change "Fixes #2154" to "Refs #2154" and narrow the commit message and the PR body to what ships.
There was a problem hiding this comment.
Confirmed both points. I checked keepalive.LongWait on v0.7.9: it returns true for background and teammate, same as human and unknown. That is a context-guru change; a Cortex-only PR cannot close it. The teammate count also needs Options.OpenTasks wired from a waitcause.Tracker, as proxy/keepalive.go does, which is a larger addition than this PR's scope.
I narrowed the PR: title, commit message and description now say "Refs #2154", not "Fixes #2154", and the description has a "What this does not fix" section naming both gaps. The code keeps the OpenTasks.Background scan, which gives a background wait the background ping count and floor — a real, partial improvement, not a close. #2154 stays open for the context-guru change and the tracker wiring.
| // panic. nil here means "no result from this body": the keeper falls back to its tracker's | ||
| // counts, as before this field existed. | ||
| func openTasks(provider bschemas.ModelProvider, body []byte, identity agent.Client) *keepalive.TaskCounts { | ||
| s := waitcause.ScanBody(nil, provider, body, waitcause.ForClient(identity)) |
There was a problem hiding this comment.
suggestion: this scans pctx.Body at OnFinish. By then it holds the bytes sent upstream: the engine's pctx.SetBody(out) (plugin.go:768) and tool deferral (tooldefer.go) have replaced it. The issue's sketch scans "the request as the client sent it, before the pipeline ran", and the proxy does the same in proxy/earlyscan.go. An engine rewrite that prunes or shortens old tool results can drop a start marker (under-count) or a completion marker (over-count, so a finished task reads as open).
Scanning in OnRequest, on the body resolveThread already gets (plugin.go:669), and keeping the result on pctx (like reqThread) avoids this. It is also where an off-path scan could start, which answers the latency question in the PR body.
There was a problem hiding this comment.
Not changed this round. The scan does run on the post-pipeline body (pctx.Body at OnFinish), so an engine rewrite could drop or add a marker, as you say. Moving it to OnRequest, on the body resolveThread reads, is correct but is a timing change beyond the open-task count itself. Left for a follow-up.
| if !ok { | ||
| t.Fatal("recordFor did not record a finished main-thread request") | ||
| } | ||
| if r.OpenTasks != nil { |
There was a problem hiding this comment.
suggestion: this test passes for the wrong reason. finishedPctx sends "messages":[], so ScanBody returns nil because the message list is empty, not because there are no markers. A real body with messages and no open-task marker gives a non-nil zero. On this head, openTasks("anthropic", threadBody(t, "fix the failing test", "now run the tests"), <claude-cli identity>) returns &{Background:0 Teammate:0}.
The comment, and the PR body ("not a zero-valued struct, which would override the tracker's own counts"), are also inaccurate: WaitingFor takes max(tracker, open.Background), so a zero does not override the tracker. Use a body with real turns and assert what actually ships, which is zero counts. Then fix the comment and the description.
There was a problem hiding this comment.
Not changed this round. Agreed the test passes for the wrong reason (messages:[] gives a nil scan, not a markerless zero), and the "not a zero-valued struct" line in the comment and PR body is inaccurate since WaitingFor takes max(tracker, open.Background). Left for a follow-up along with the other suggestions.
| pctx := finishedPctx(200, pipeline.AgentRoleMain) | ||
|
|
||
| // Simulate what resolveThread leaves on pctx right after a client compaction. | ||
| pipeline.SetState(pctx, reqThreadStateKey, &reqThread{res: thread.Result{ |
There was a problem hiding this comment.
suggestion: this test builds the thread.Result by hand, so it checks the field mapping but not the #2163 scenario. A test that drives the real tracker through invokeReq would catch the ordering problem above: a 1-hour probe, then the compaction call, then the post-compaction request, then assert that the probe was released and the route is still on. The InheritsFrom branch has no test. Result.inherits is unexported, so only the tracker can reach it.
There was a problem hiding this comment.
Not changed on this test directly, but TestPrefixRewrittenCoversTheCompactionCallItself (added for the must-fix above) now drives the real tracker through invokeReq the way you describe, and it does catch the ordering problem. The InheritsFrom branch still has no test of its own. Left for a follow-up.
#2154's open-task counts recordFor (core/plugins/contextguru/keepalive.go) mapped a finished request to keepalive.Record but left three fields at their old, zero, or incomplete values: - Agent carried the raw User-Agent string, a field context-guru v0.7.11 removes. Identity (agent.Identify) is the field the keeper reads now. Fixes #2160. - PrefixRewritten stayed false always. A cold return right after a client compaction or fork then counted as a 1-hour probe failure and could switch a proven route off for the life of the process. The first fix here missed that resolveOneHourProbe runs on the COMPACTION CALL itself, not only on the post-compaction request AfterCompaction marks: the compaction call resolves (and releases) the probe before the flag the post-compaction request carries is ever read. thread.go now also keeps whether THIS request is the client's own compaction call (requestIsCompactionCall), and prefixRewritten reads that too. Fixes #2163. - OpenTasks stayed nil. The comment said context-guru's waitcause classifier "is not exported" -- true before v0.7.9, false now. recordFor now calls waitcause.ScanBody and sets OpenTasks.Background from the request's own body, which gives a background wait the background ping count and floor. This is a partial fix, not a close, for #2154: context-guru's keepalive.LongWait (keepalive/waitplan.go) still starts the 1-hour probe on a background or teammate wait regardless, and the teammate count this change reads is never merged into WaitingFor (by design: only the background count is). Closing #2154 needs a context-guru change to LongWait, and wiring Options.OpenTasks from a waitcause.Tracker for the teammate half, as proxy/keepalive.go does -- out of scope for this PR. Refs #2154. #2154, #2160 and #2163 all touch the same function, so one PR covers them. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: DAVID BOAZ <DAVIDBO@il.ibm.com>
0e416e6 to
c7e5ff2
Compare
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The must-fix from my previous review is resolved. On c7e5ff2 the compaction call itself carries PrefixRewritten=true, so the call that resolves the 1-hour probe now goes down the release branch of resolveOneHourProbe (onehour.go:302-303) instead of the switch-off branch. I ran a probe through OnRequest and then recordFor with the real tracker: turn 1, turn 2, the compaction call, post-compaction, next turn. All five land on the same main-thread key ({Session:s1 Thread:}), and PrefixRewritten is false/false/true/true/false. That still holds when pctx.Body is replaced before finish, because the verdict is captured in OnRequest before stripOwnHeaders. I also mutation-checked the new test: disabling the requestIsCompactionCall branch fails it at the "compaction call" step.
The #2154 narrowing to "Refs" in the title, commit message and body matches what ships. Identity (#2160) is correct.
Remaining notes are non-blocking (inline): two comments still describe the larger #2154 claim, and the body scan runs on requests whose result the keeper discards. The suggestions you deferred from the last round (scan the pre-pipeline body in OnRequest, the messages:[] nil test, the InheritsFrom test) are still open as follow-ups. I am not repeating them here.
Author: boazdavid (CONTRIBUTOR association, admin repo permission — maintainer)
Areas reviewed: Go (contextguru plugin recordFor, resolveThread, and the context-guru v0.7.9 keepalive one-hour probe and wait-plan code and waitcause.ScanBody it calls), tests
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing. The annotations are only cache, Node 20, hadolint/yamllint warnings on unrelated files, and macOS-queue notices. The Go CI (core) job log would not download (TLS timeout), so I ran go vet, gofmt -l and go test -race on ./plugins/contextguru/ locally. All are clean.
No JSON decoder is involved: keepalive.Record is an in-process struct.
| // openTasks reads the open background-task and teammate-wait counts of the request's own body | ||
| // (Claude Code's own markers in the transcript), so a thread that is about to wait on a | ||
| // background task or a teammate is not classified as an unknown wait (WaitingFor's fallback), | ||
| // which the keeper then treats like a wait for a person: it starts the 1-hour probe on a wait |
There was a problem hiding this comment.
nit: this doc still describes the full #2154 claim ("…which the keeper then treats like a wait for a person: it starts the 1-hour probe on a wait that returns in seconds"). It reads as if openTasks prevents that, and the PR body now says it does not: LongWait is still true for background. It also says the function reads "teammate-wait counts" for classification, but WaitingFor never merges Teammate. Suggested wording: it gives a background wait the background cause, its ping count and its floor. Teammate waits and the 1-hour-on-wait rule are unchanged (#2154).
| // waitcause.ScanBody fails open (nil) on its own work bound, on server-held history or on a | ||
| // panic. nil here means "no result from this body": the keeper falls back to its tracker's | ||
| // counts, as before this field existed. | ||
| func openTasks(provider bschemas.ModelProvider, body []byte, identity agent.Client) *keepalive.TaskCounts { |
There was a problem hiding this comment.
suggestion: ScanBody runs on every recorded request, but the keeper reads r.OpenTasks only when planned is true: pol.WaitPlan && pol.On() && provider != OpenAI && !ttl1h && pol.Idle < OneHourIdleFloor (keeper.go:1059-1067). Everywhere else the result is dropped. That includes OpenAI routes, wait-plan off, and 1-hour tiers. The scan is not free: I measured about 63 ms per call for a 3.6 MB, 1200-message Anthropic body, synchronously inside OnFinish. A cheap gate before the scan would skip it in the common cases where it cannot matter, for example if !pol.WaitPlan || provider == bschemas.OpenAI { return nil }. The same gate applies if the scan moves to OnRequest in the follow-up.
| "github.com/rossoctl/cortex/core/pipeline" | ||
| ) | ||
|
|
||
| // Fixes cortex#2154: recordFor left keepalive.Record.OpenTasks nil, so a wait on a background |
There was a problem hiding this comment.
nit: this header still says "Fixes cortex#2154" and that the bug "started the 1-hour probe". The PR is now "Refs #2154" and does not change the probe. The same stale wording is in the nil-vs-zero comment at lines 34-36, which you already agreed to fix. Worth fixing both in the same touch, so a reader of the test does not take #2154 as closed.
Summary
recordFor(core/plugins/contextguru/keepalive.go) setRecord.Agent, a field context-guru v0.7.11 removes, instead ofRecord.Identity. Fixes contextguru plugin: set keepalive.Record.Identity; context-guru v0.7.11 removes Record.Agent #2160.recordFornever setRecord.PrefixRewritten, so a cold return right after a client compaction or fork counted as a 1-hour probe failure. Fixes contextguru plugin: set keepalive.Record.PrefixRewritten, so a client compaction does not switch the 1-hour route off #2163.recordForleftkeepalive.Record.OpenTasksnil and kept a stale comment. This PR gives it the request body's own background-task count. Refs contextguru plugin: give the keeper open-task counts, so a teammate or background wait does not start the 1-hour probe #2154 (does not close it — see What this does not fix below).All three touch the same function, so this is one PR.
What changed
Record.Identityfromagent.Identify(pctx.Headers)in place of the removedAgentfield.Record.PrefixRewrittenfrom the request's ownthread.Result(AfterCompactionorInheritsFrom()), and from a newrequestIsCompactionCallcheck.resolveOneHourProberuns on the firstRecordof a probe's key and releases it unconditionally — that firstRecordis the compaction call itself, not the post-compaction requestAfterCompactionmarks. Missing that releases the probe cold one request early, so the later return the flag was meant to excuse never sees a live probe.thread.gonow keeps whether a request IS the client's own compaction call, next to the thread it resolved.waitcause.ScanBodywith the request's own body andwaitcause.ForClient, and setRecord.OpenTasks.Backgroundfrom the result.ScanBodyfails open (nil) on its work bound or a panic, so a scan that cannot say anything keeps today's fallback to the tracker's counts.What this does not fix (#2154)
Setting
OpenTasks.Backgroundgives a background wait the background ping count and floor, which is real, but it does not stop a 1-hour probe from starting on a background or teammate wait:keepalive.LongWait(keepalive/waitplan.go) treatsbackgroundandteammateas long waits, same ashumanandunknown. That is a context-guru change, out of scope for a Cortex-only PR.WaitingFor— only the background count is, by that function's own design. Closing the teammate half needsOptions.OpenTaskswired from awaitcause.Tracker, asproxy/keepalive.godoes; that is a larger addition than this PR's scope.#2154 stays open for those two follow-ups.
How it was tested
core/plugins/contextguru/repro_2154_test.go: a body with an open background-task marker setsOpenTasks.Background; a plain body leavesOpenTasksnil.core/plugins/contextguru/repro_2160_test.go:Identityis set from the request'sUser-Agent.core/plugins/contextguru/repro_2163_test.go:PrefixRewrittenis true on the compaction call itself and on the post-compaction request (TestPrefixRewrittenCoversTheCompactionCallItselfdrives the real tracker through 4 turns and checks both); false otherwise. Mutation-checked: reverting the compaction-call check makes this test fail on the "compaction call" step.go vet ./...,gofmt -l .andgo test ./...are clean fromcore/on this branch (two pre-existing, unrelated DST/tzdata test failures incore/cost/ledgerandcore/cost/usagereproduce identically onmain).Assisted-By: Claude (Anthropic AI) noreply@anthropic.com