Skip to content

feat(keepalive): client lifecycle signals retire a session's cache on exit and compaction - #520

Merged
amiddavid merged 2 commits into
mainfrom
port/lifecycle-signals
Oct 14, 2026
Merged

amiddavid merged 2 commits into
mainfrom
port/lifecycle-signals

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

What

The proxy cannot see from the request stream that a user quit Claude Code or that the conversation was compacted, so the keep-alive keeps pinging a cache no later request will read. With this change the Claude Code plugin tells the proxy, and the proxy retires the held entries.

Event (plugin hook) Proxy action
SessionEnd (any reason) Retire every entry held for the session; keep a per-tenant end mark (12 h, 2,000 per tenant) so a request still in flight at exit is not held afterwards. A resumed session's next request is held as usual.
SessionStart source=compact Retire only entries whose last request started at least 2 s before the event (the pre-compaction prefix). The session goes on.
other SessionStart sources, Notification Recorded only (debug log).
  • POST /signal: authenticated and metered like any request; body {"session","event","kind"} from a closed set, unknown fields refused, 1 KiB cap, 204 on accept.
  • Plugin: SessionEnd, SessionStart (compact|resume|clear) and Notification hooks run scripts/signal.sh. It reads only those three fields from the hook payload, sends the credential to curl on stdin, has a 2 s timeout, retries a not-yet-started proxy in the background, and exits 0 on every path.

How to turn it on

Off by default on both sides.

  1. Proxy: CONTEXT_GURU_CLIENT_SIGNALS=on (otherwise /signal is 404).
  2. Plugin: client_signals option on (/plugin configure), or CONTEXT_GURU_CLIENT_SIGNALS=on in the shell.

How it fails safe

A signal only removes spend: it retires a held entry and never extends a hold or arms a ping. A lost or late event leaves the no-signal behaviour; a forged one can only affect the sender's own sessions (the key is tenant-scoped); end marks are capped per tenant. If ANTHROPIC_BASE_URL is not a context-guru proxy, that host sees POST /signal with the token it already receives, so leave the option off there (documented).

Docs

docs/how-to/cache-keepalive.md (new section) and the plugin options table in docs/how-to/install-plugin.md.

Tests

  • gofmt -l clean, go vet ./proxy ./context-guru-plugin clean.
  • go test -race -run 'Signal|Lifecycle|Compact|Retire' ./proxy ./context-guru-plugin pass.
  • go test ./proxy ./context-guru-plugin ./session pass.
  • Covered: route off by default, auth and tenant scoping, closed-set validation, per-tenant mark caps, the compact 2 s cutoff, the in-flight request after SessionEnd, the hook script's payload filtering and retries (race-free).

… exit and compaction

The Claude Code plugin can tell the proxy that a session ended (SessionEnd) or was
compacted (SessionStart source=compact). The proxy retires the keep-alive entries that
hold the dead prefix, so it stops pinging a cache no later request will read.

- POST /signal: authenticated, metered, content-free body (session, event, kind from a
  closed set), 204 on accept. 404 unless CONTEXT_GURU_CLIENT_SIGNALS=on.
- SessionEnd retires the session and keeps a per-tenant end mark (12 h, 2,000 per tenant)
  so a request in flight at exit is not held afterwards.
- SessionStart compact retires only entries whose last request started 2 s before the
  event, so a late event cannot retire the post-compaction entry.
- Other SessionStart sources and Notification are recorded only.
- Plugin: SessionEnd, SessionStart compact|resume|clear and Notification hooks run
  scripts/signal.sh, gated by the client_signals option (default off). Never blocks;
  every exit is 0.
- Docs: cache-keepalive how-to section and the plugin option row.

Signed-off-by: Osher-Elhadad <[email protected]>

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

Review: APPROVE at ae84df7. (Posted as a comment: GitHub does not let the author account approve.)

  • The code matches what was reviewed and merged in the private mirror. The only difference is one comment in proxy/clientsignal.go, which now gives no figures.
  • go vet is clean on proxy and context-guru-plugin. The proxy Signal|Compact|InFlight|Lifecycle|SessionEnd tests and the plugin Signal tests pass.
  • The commit is by Osher-Elhadad, signed off, with no AI attribution. The PR text has no identifiers or results.

Approved.

@amiddavid amiddavid 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

One concern about how this interacts with #519 (thread identity across compaction). It is not a blocker for #520 alone. The two PRs merge with no conflict.

What we found

On SessionStart source=compact, keeper.signal calls retireSessionStartedBefore(tenant, session, now-2s). That loop matches base and every base+"\x00"<thread> key, so it retires the held entry of every thread in the session: the main thread, each subagent (a:<id>), and each side thread.

Only one thread was compacted: the one whose request carried the compaction prompt (the main agent, for /compact and auto-compact). A subagent or teammate that is idle with a live cache loses its keep-alive pings until its next request.

How #519 and #520 work together

We ran a live check of #519 (Claude Code 2.1.296, auto mode, /compact):

  • Released v0.5.0: the compaction call got a new thread id. The old main entry stayed held, and keep-alive pinged it 2 times after the compaction, for a prefix nothing reads again. #520 removes exactly that waste.
  • #519: the compaction call stays on the main thread, so its arrival already clears the old main entry. What is left for #520 is the compaction call's own entry (the old conversation plus the prompt). Retiring it is correct.

Proposal

  1. On compact, retire only the compacted thread, not the whole session. After #519, the thread tracker marks that thread (compacting, internal/thread). The keeper could read it, or retire only header-less (main-agent) keys.
  2. Optional, later: use this hook as the proxy's compaction signal for thread identity, in place of matching the prompt text. That would remove the false positive in #533. The hook arrives after the compaction call and before the next turn, so the timing works.

Open questions

  • Does SessionStart source=compact also fire when a subagent compacts its own context? If it does, the payload would need the agent id to pick the right thread.

Reviewed by an AI reviewer (Claude), for the release integrator.

@amiddavid

Copy link
Copy Markdown
Collaborator

Summary

The concern in my earlier comment is now a confirmed defect, so it needs a fix in this PR before release v0.5.1. #524 makes these signals the default, so the fix here reaches every user once #524 rebases.

What we found

The review of #524 tested it (#524 (review)). The main thread and an idle subagent a:sub1 both held an entry. After a SessionStart source=compact signal, both entries were gone, with default settings. Only the main agent compacted.

Proposal

  1. On the compact path only (cutoff set), skip entries whose thread is not the main thread (e.thread != ""). SessionEnd still retires the whole session. The reviewer tried this fix: it passed the new test and all existing Signal, Lifecycle, Compact, SessionEnd and Codex tests.
  2. Add the test to this PR: main and a subagent held, compact signal, the subagent's entry survives. The reviewer's test file was not saved, so it needs to be written again.
  3. After feat(keepalive): client lifecycle signals on by default whenever the keep-alive runs #524 rebases, check that its raw-payload and Codex session-id paths reach the same function, so they also keep the subagents' entries.

Posted by an AI assistant (Claude), for the release integrator.

…l takes JSON only

Only the main agent compacts, and its compaction call stays on the main thread, so SessionStart
compact retires that thread's entry and leaves an idle subagent's or teammate's held cache pinging.
SessionEnd still retires every thread. The route refuses a non-JSON body (415): a web page can POST
text/plain to a loopback proxy without a CORS preflight, and the local proxy takes no credential.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator Author

Thanks. Here is a point-by-point reply to the review. The fix is in d221800.

1. Compact retired every thread. Fixed. On the compact path (a non-zero cutoff), retireSessionStartedBefore now retires only main-thread entries (e.thread == ""). With #519 on main, the compaction call stays on the main thread. SessionEnd keeps the full-session retire.

  • Test: TestCompactRetiresOnlyTheMainThread. Main and a:sub1 are both held. After 30 s, a compact signal retires main and a:sub1 survives; a later SessionEnd retires a:sub1. Without the fix the test fails ("idle subagent held false").
  • Live check: one real Claude Code 2.1.296 session (main plus feat(keepalive): client lifecycle signals retire a session's cache on exit and compaction #520, Azure route via LiteLLM, keep-alive idle 60 s).
    • A background subagent did 5 requests and went idle at about 90 s. The main agent's last request was at about 104 s. Both were held (2 live entries).
    • /compact: the SessionStart compact signal at about 128 s retired 1 entry, the main one. The subagent's entry stayed held, and the keep-alive pinged it at 154 s and 213 s.
    • /exit: SessionEnd retired the subagent entry.
  • Your proposal 2 (using the hook as the thread-identity signal) is a good follow-up. It is not in this PR.

Open question: subagent compaction. The SessionStart payload carries no agent id. In every run we have seen, compact fired only for the main agent's /compact or auto-compact. If a subagent ever compacts itself, it keeps its entry under this rule, which is the safe direction: it costs at most the remaining pings.

Question 1 (loopback proxy needs no credential). Agreed that it is acceptable. I also closed the browser case: /signal now refuses any body that is not application/json (415). A cross-origin page can send text/plain without a preflight, but it cannot send JSON. All three clients already send Content-Type: application/json (the plugin hook, the Codex hook and the hosted snippet). Test: TestSignalTakesJSONOnly.

Question 2 (auto treats any loopback URL as context-guru). That is in #524. I am leaving it as it is: that host already receives the same token on every request, and the cost is one 404. A port or /healthz check would add a request to every session end.

Checks: go vet ./proxy ./dash ./internal/thread ./context-guru-plugin is clean, and go test ./proxy ./dash ./internal/thread and the plugin Signal tests pass.

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

Re-review: APPROVE at d221800. This covers the delta since ae84df7. (Posted as a comment: GitHub does not let the author account approve.)

  • Compact retires the main thread only. retireSessionStartedBefore with a non-zero cutoff now skips e.thread != "", and SessionEnd (zero cutoff) still retires every thread. The main agent is the primary thread "": newID gives the primary to the tool-declaring thread, and the post-compaction request inherits the compacting thread's id. That holds for Claude Code and Codex. Removing the thread skip makes TestCompactRetiresOnlyTheMainThread fail.
  • JSON only. mime.ParseMediaType accepts application/json with parameters and in any case, and refuses missing, text/plain and form types with 415. TestSignalTakesJSONOnly covers all five, and disabling the check fails it. The route is POST /signal only, and nothing in proxy or dash sets Access-Control-Allow-*, so a cross-origin JSON preflight is never granted. signal.sh sends Content-Type: application/json, and so do the Codex hook and the hosted snippet in #524.
  • gofmt and go vet are clean, and the proxy signal tests pass. CI is green. The commit is signed off with no AI attribution.

Non-blocking:

  • A p: side thread is kept on compact as well. Those are tool-less auxiliary requests, rarely large enough to be held, and their pings are bounded by MaxPings.
  • If the primary was evicted (restart or idle) before a compact, the main thread can come back under a p: id. A compact then retires nothing, which is the no-signal behaviour and fails safe.

Approved.

@amiddavid
amiddavid merged commit 6d34ce1 into main Oct 14, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 14, 2026
amiddavid added a commit to AIMikav/context-guru that referenced this pull request Nov 9, 2026
…gin to 0.2.1

Both plugins changed in v0.5.1: the Claude Code plugin gained the lifecycle
signal hooks (rossoctl#520, rossoctl#524) and the per-agent money status line (rossoctl#525); the
Codex plugin gained its SessionEnd and SessionStart hooks (rossoctl#524). A new
version number is what makes an installed plugin update.

Assisted-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
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.

2 participants