Skip to content

Fix: Give recordFor the keeper's identity and prefix-rewrite flag; refs #2154's open-task counts - #2170

Merged
boazdavid merged 1 commit into
mainfrom
fix/2154-2160-2163-keepalive-recordfor
Nov 29, 2026
Merged

boazdavid merged 1 commit into
mainfrom
fix/2154-2160-2163-keepalive-recordfor

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

All three touch the same function, so this is one PR.

What changed

  • Set Record.Identity from agent.Identify(pctx.Headers) in place of the removed Agent field.
  • Set Record.PrefixRewritten from the request's own thread.Result (AfterCompaction or InheritsFrom()), and from a new requestIsCompactionCall check. resolveOneHourProbe runs on the first Record of a probe's key and releases it unconditionally — that first Record is the compaction call itself, not the post-compaction request AfterCompaction marks. 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.go now keeps whether a request IS the client's own compaction call, next to the thread it resolved.
  • Call waitcause.ScanBody with the request's own body and waitcause.ForClient, and set Record.OpenTasks.Background from the result. ScanBody fails 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.
  • Remove the now-stale "is not exported" comment.

What this does not fix (#2154)

Setting OpenTasks.Background gives 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:

  • context-guru's keepalive.LongWait (keepalive/waitplan.go) treats background and teammate as long waits, same as human and unknown. That is a context-guru change, out of scope for a Cortex-only PR.
  • The teammate count this PR reads is never merged into WaitingFor — only the background count is, by that function's own design. Closing the teammate half needs Options.OpenTasks wired from a waitcause.Tracker, as proxy/keepalive.go does; 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 sets OpenTasks.Background; a plain body leaves OpenTasks nil.
  • core/plugins/contextguru/repro_2160_test.go: Identity is set from the request's User-Agent.
  • core/plugins/contextguru/repro_2163_test.go: PrefixRewritten is true on the compaction call itself and on the post-compaction request (TestPrefixRewrittenCoversTheCompactionCallItself drives 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 . and go test ./... are clean from core/ on this branch (two pre-existing, unrelated DST/tzdata test failures in core/cost/ledger and core/cost/usage reproduce identically on main).

Assisted-By: Claude (Anthropic AI) noreply@anthropic.com

@boazdavid
boazdavid requested a review from a team as a code owner November 29, 2026 07:32
@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

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

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 53d98d97-685e-4e01-9a57-73df6a573a94
Commits

Reviewing files that changed from the base of the PR and between 7e7fc6b and c7e5ff2.

Files selected for processing: 5

  • core/plugins/contextguru/keepalive.go
  • core/plugins/contextguru/repro_2154_test.go
  • core/plugins/contextguru/repro_2160_test.go
  • core/plugins/contextguru/repro_2163_test.go
  • core/plugins/contextguru/thread.go
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 PrefixRewritten mapping 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 leaves PrefixRewritten false on it.
  • #2154: with OpenTasks set, a background wait now reads background. But keepalive.LongWait is true for background and teammate too, 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:

  • Record is an in-process struct, so no JSON decoder is involved.
  • On the pinned v0.7.9, dropping Agent: leaves KeepAliveReport.Agent empty on ping reports. Neither logEmitter nor pingFromReport reads that field, so nothing changes in Cortex today.

return false
}
_, inherits := res.InheritsFrom()
return res.AfterCompaction || inherits

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. LongWait treats background and teammate as long waits. In v0.7.9 (and on context-guru main), keepalive.LongWait returns true for human, unknown, background and teammate (waitplan.go:69-79). I checked: LongWait("background", false) and LongWait("teammate", false) are both true. So moving the cause from human/unknown to background keeps the 1-hour-on-wait branch (keeper.go:1096). The new cause also lowers the floor from MinPrefixTokens to 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.
  2. The teammate count is never read. WaitingFor merges only open.Background. Its doc says the teammate count "is the tracker's alone", and TaskCounts says Teammate "never changes a plan". The tracker is keepalive.Options.OpenTasks, and the plugin does not set it (keepalive.New(keepalive.Options{Dispatcher: p.disp}), plugin.go:484). So a teammate wait still reads human (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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@boazdavid
boazdavid force-pushed the fix/2154-2160-2163-keepalive-recordfor branch from 0e416e6 to c7e5ff2 Compare November 29, 2026 08:12
@boazdavid boazdavid changed the title Fix: Give recordFor the keeper's open-task counts, identity and prefix-rewrite flag Fix: Give recordFor the keeper's identity and prefix-rewrite flag; refs #2154's open-task counts Nov 29, 2026

@clawgenti clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@boazdavid
boazdavid merged commit b86037f into main Nov 29, 2026
42 checks passed
@boazdavid
boazdavid deleted the fix/2154-2160-2163-keepalive-recordfor branch November 29, 2026 08:50
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

Status: Done

2 participants