Skip to content

feat(kvcache): measure the idle keep-alive per ping — cache outcome, gaps and cost - #196

Merged
OsherElhadad merged 2 commits into
rossoctl:mainfrom
itay-nakash:feat/keepalive-ping-stats
Sep 6, 2026
Merged

OsherElhadad merged 2 commits into
rossoctl:mainfrom
itay-nakash:feat/keepalive-ping-stats

Conversation

@itay-nakash

Copy link
Copy Markdown
Collaborator

What this adds

Two files under deploy/harbor/, alongside the existing kv_ttl_* analysis scripts:

  • keepalive_ping_stats.py — produces one row per idle keep-alive ping over a window of
    history, answering four questions per ping: did the ping itself hit the provider cache, how
    many seconds after the previous request did it fire, did the request that followed it hit and
    how long after, and what did the ping cost. Plus a summariser over that table.
  • test_keepalive_ping_stats.py — 14 tests against a synthetic requests table. No
    production access, no network.

Nothing existing is modified. No Go code, no schema change, no runtime path is touched — this is
read-only analysis of rows the service already writes.

Why

proxy/keepalive.go carries a detailed account of what the mechanism is worth, sourced from a
replay (TestKeepAliveOnProductionSnapshot). What we did not have was a way to ask the same
questions of what actually shipped, per ping, against the live ledger — in particular whether a
given ping read the entry it was meant to refresh, and whether the request it was protecting then
hit. The dashboard reports pings in aggregate (count and cost); keepalive_saved_usd reports the
service's own attribution. Neither answers "did this ping work, and how close was it".

Identifying our own pings

requests.keepalive = 1. This is exact in one direction and a lower bound in the other, and the
distinction is documented at the top of the script because it changes how a count is read:

  • No false positives. KeepAlive: true is set in exactly one non-test place in the service,
    proxy/keepalive.go (record1), and nothing ever UPDATEs the column afterwards — the
    strategy backfill writes keepalive_strategy_id only. No benchmark, simulation or campaign
    path writes a ping row. Rows predating the mechanism read 0 by the ALTER TABLE default, and
    correctly so: the column and the emitter shipped in the same commit (feat(cache): keep an idle prompt cache alive, price the 1h write tier, and say what cachesplit did #86).
  • False negatives, all of them outside the table. A ping refused by the tenant rate limiter,
    failed in transport, or answered 4xx returns before record1, so it never becomes a row. The
    table holds pings that were sent and answered non-4xx; KeepAliveStats on /stats holds what
    was attempted.

The collector does not take the flag on trust. It also evaluates an independent structural
fingerprint of the row shape record1 produces — max_tokens=1, stream=0, and zero for
messages, tokens_before, mode, cache_miss_reason, cg_latency_ms, ttfb_ms — in both
directions, and prints any disagreement as a number. Over 1,038 production pings it reported
0 flagged rows whose shape disagrees and 0 unflagged rows shaped like a ping.

Two correctness traps this had to handle

Both were found by running against real rows, and both silently invert a headline number.

1. ts means different things on the two row types. A real request's ts is its start
(proxy/dashcapture.go, TS: c.start.UnixMilli()); a ping's is stamped in record1, after the
round trip. Every gap here is therefore start-to-start, which is also the footing
CachePolicy.Idle and the provider's lifetime rule both use. It matters: corrected, gap_before_s
clusters at 270–272s on a 270s-Idle account with a 1.6s spread; uncorrected it scatters over
273–288s, the noise being the ping's own round trip, which reaches 28s at p95.

2. A non-2xx row must not be taken as "the request after the ping". In production, a ping is
frequently followed within about a second by a status-400 row carrying a single message and no
tokens, with the actual resumption arriving next. Those rows still receive a cache_miss_reason
from AttributeCache. On the first sample checked, taking the immediate next row reported 0 of 4
following requests hitting; the truth was 2 of 4, both reading the ping's prefix back token for
token. The collector steps over non-2xx rows to find the neighbouring agent request, keeps the
immediate neighbour's id alongside it, and counts what it stepped over.

How to use it

The two subcommands split because the database is readable only by the account the service runs
as, and that account has no site-packages:

# 1. collect -- stdlib only, runs as the service account. One CSV row per ping.
sudo -u cg /usr/bin/python3 keepalive_ping_stats.py collect --out /var/tmp/pings.csv

# 2. stats -- loads that CSV into a DataFrame and prints the tables. Needs pandas.
python3 keepalive_ping_stats.py stats /var/tmp/pings.csv

WHERE keepalive = 1 has no supporting index, so an unbounded run is a full scan of the live
file. Pass --since-ms <epoch ms> to bound it, which lets the query use idx_requests_ts.

There is a second source that needs no privileged access, and it is how the script was developed
and validated: a session export bundle, one directory per session each holding a turns.csv that
is SELECT * FROM requests.

python3 keepalive_ping_stats.py collect --export <bundle.zip|dir> --out pings.csv

Account ids are pseudonymised (t01, t02, …) and session ids hashed unless --raw-ids is
passed. No message content is read — request_content is never queried.

Tests:

python3 deploy/harbor/test_keepalive_ping_stats.py     # or run under pytest

How to read the results

collect prints three lines to stderr: how many pings it found, the identification audit in both
directions, and the window the table covers versus the first recorded ping — so a count is read
against the history that could have contained pings rather than against "all time".

stats prints four blocks:

  • AVERAGES. Watch the n column; it differs per row. gap_before_s is the configured Idle
    recovered from data. gap_before_prev_real_s skips back past intervening pings, so on a second
    ping it measures the whole span rather than the inter-ping step. gap_after_next_real_s is the
    one that answers "when did the human come back". ping_cost_usd is heavily right-skewed, so
    read the median next to the mean.
  • WHAT THE PING DID — four disjoint outcomes with spend against each. A ping can read
    something and still write more than it read, so "wrote instead of read" is not a subset of
    "missed"; they are printed as separate buckets for that reason. wrote a new entry, read nothing is the failure keepalive.go calls the mechanism being wrong rather than expensive.
  • THE REQUEST AFTER THE PING. The HIT line is what happened; the credited line is the
    service's own attribution, which a non-2xx row arriving first can consume. Expect them to
    disagree. The cache_miss_reason breakdown separates "came back too late" (ttl_expiry) from
    "the prefix moved" (prefix_change) from "a different model" (cold_start, which with the
    session already seen means !seenModel and is not addressable by pinging).
  • BY PING POSITION, then a timing self-check. The self-check is the cheap evidence that
    identification and the ts correction are both right: the share of gaps within ±12s of the
    median is the band a 2s sweep firing one tick after Idle produces. It also names its two
    tails, because both have a known cause — a negative gap is a ping that was still in flight when
    a request arrived, and a gap near 2× the median is one whose preceding attempt advanced the
    timer without writing a row.

Evidence

14/14 tests pass. Run against the live ledger for 2026-08-23..09-02: 1,038 recorded pings across
255 sessions and 15 accounts, $150.87 of ping spend, identification audit clean in both
directions, and 91.8% of gaps inside the ±12s band. The same code over a session export bundle
reproduces its rows identically.

CI does not currently run Python, so test_keepalive_ping_stats.py is a manual gate; it is
stdlib-only apart from the two summariser tests, so it runs anywhere the collector does.

…gaps and cost

keepalive.go states what the mechanism is worth from a replay. This asks the same
questions of what actually shipped, one row per ping, against the live ledger: did
the ping read the entry it meant to refresh, how long after the previous request did
it fire, did the request it was protecting then hit and how much later, and what did
the ping cost.

Add deploy/harbor/keepalive_ping_stats.py, next to the kv_ttl_* scripts, with two
subcommands. The split is forced rather than stylistic: the dashboard database is
readable only by the account the service runs as, and that account has no
site-packages, so `collect` is stdlib-only and `stats` runs afterwards wherever
pandas is. `collect` also reads a session export bundle, which needs no privileged
access and is how this was developed.

Identify a ping by requests.keepalive = 1. That is exact one way and a lower bound
the other, and the script says so where a reader will see it: KeepAlive: true is set
in exactly one non-test place (record1), nothing UPDATEs the column afterwards, and
the column shipped with the emitter in rossoctl#86 so no ping predates the flag — but a ping
refused by the limiter, failed in transport or answered 4xx returns before record1
and never becomes a row. The collector cross-checks the flag against an independent
fingerprint of record1's row shape, in both directions, and prints disagreement as a
number rather than absorbing it.

Two traps found against real rows, each of which silently inverts a headline:

  ts is the request START on an agent row and the ping's COMPLETION on a ping row, so
  every gap here is start-to-start — the footing CachePolicy.Idle and the provider's
  lifetime rule both use. Corrected, gap_before_s holds a 1.6s spread; uncorrected it
  scatters over 15s, the noise being the ping's own round trip.

  A non-2xx row is not "the request after the ping". A ping is frequently followed
  within a second by a 400 carrying one message and no tokens, and AttributeCache
  still stamps it with a cache_miss_reason. Taking it reported 0 of 4 following
  requests hitting where 2 of 4 read the ping's prefix back token for token.

Read-only throughout: no Go code, no schema change, no runtime path. Account ids are
pseudonymized and session ids hashed unless --raw-ids; request_content is never
queried.

Evidence: 14/14 tests green; 1,038 recorded pings over 2026-08-23..09-02 across 255
sessions and 15 accounts, $150.87 of ping spend, identification audit clean both
ways, 91.8% of gaps inside the band a 2s sweep produces.

Assisted-By: Claude Opus 5 <[email protected]>
Signed-off-by: Itay Nakash <[email protected]>
@OsherElhadad

Copy link
Copy Markdown
Collaborator

Review: audited the docstring against the Go, mutated the script, and probed it with synthetic data only

Reviewed at 0a894ac8 in a dedicated worktree. Verdict: approve with nits — one security finding worth fixing before merge, two stale code citations, and a small pile of nits. The analysis logic is sound and the test suite genuinely catches the defects that would silently invert a headline number.

Data boundary: this script reads the production service database (DB = /var/lib/context-guru/cg.db). Nothing in this review touched it, /etc/context-guru/**, or any existing export. Everything below was checked either by reading Go source or against synthetic SQLite databases and zip bundles built for the purpose and deleted afterwards. The production figures in the body are listed at the end as not verifiable within that boundary — they are not disputed, just not re-derived.

CI does not run this PR

.github/workflows/ci.yaml has three jobs — build-test, purego, trivy — and none touches Python. The only setup-python anywhere is docs.yaml for the mkdocs build. This diff is 100% Python, so the five green checks are evidence about the Go build and say nothing about it. The body already says as much, which is the right call; recording it here so no one reads the green ticks as coverage.

Worth contrasting with #212, which faces the same problem and solves it: its Python is pinned by Go drift tests under deploy/harbor/, which make cover does run. If this script ever grows a claim worth defending in CI, that is the pattern available.

Real run results

Merge onto current main (87377e73) clean, zero conflicts — 20 commits behind, but mergeable: UNKNOWN was a caching artifact
python3 test_keepalive_ping_stats.py (no pandas, 3.9.25) Ran 14 tests — 11 pass, 3 ERROR with a clean ModuleNotFoundError
uv run --with pandas python3 test_keepalive_ping_stats.py -v Ran 14 tests … OK — 14/14
pandas genuinely importable verified at symbol level (from pandas import DataFrame), not just import pandas

Zero tests silently skipped — the pandas-dependent ones fail loudly rather than skipping, which is the honest failure mode. (Checked specifically because an unreadable root-owned site-packages can import as an empty namespace package, making import pandas succeed with __file__ = None; that hazard does not manifest here.)

Docstring-claim audit — the script's correctness argument, checked against the Go

The docstring is written to be checkable, so it was checked. Every substantive claim holds; two citations do not.

Claim Cited Status
KeepAlive: true set in exactly one non-test place proxy/keepalive.go:964 (record1) exact, at merge-base and main
Backfill writes keepalive_strategy_id only, never keepalive dash/keepalivestrategybackfill.go:151 exact; no other writer of the column repo-wide
Column and emitter shipped in one commit, so no pings predate the flag 50e3966 (#86) confirmed
A ping's ts is stamped after the round trip; a real request's is its start dashcapture.go TS: c.start.UnixMilli() confirmed
keepalive_saved_usd nonzero only when the row read more than it wrote — confirmed (dash/event.go:823-830)
AttributeCache not computed for a ping — confirmed, and structurally stronger than claimed — record1 builds its own dash.Event and never enters the path that calls it
4xx returns before record1, so a refused ping is invisible proxy/keepalive.go:906 stale — it is :908
keeper.arrive() consumes keepalive_pings before the next request's status is known proxy/proxy.go:1109 wrong — it is :1143

Minor · docs · both citations were wrong when written, not drifted. I checked the two files at the PR's own merge-base (51fcd916) as well as at main: neither was touched by the 20 intervening commits, and keeper.arrive( is at 1143 in both, with line 1109 in both landing inside an unrelated comment block about repair/tool-injection deferral. A reader following :1109 to check the attribution claim finds nothing related to it and may reasonably conclude the claim is unfounded — when it is in fact correct. Please re-grep the symbols and fix both numbers; the underlying claims stand.

Mutation testing — four defects introduced in the script, one at a time

Defect Caught by
start_ms() drops the ts correction (returns raw ts for a ping) 5 tests
Fingerprint check made one-directional (unflagged hardcoded to 0) 1 test
Trust the keepalive flag alone (fingerprint() always True) the same 1 test
Mis-attribute cost/outcome to the immediate next row, bypassing the non-2xx step-over 2 tests

Nothing went uncaught. But note the middle two: the "independent structural fingerprint, evaluated in both directions" safeguard — which the body calls out as a specific correctness guarantee — has exactly one test defending it (test_identification_audit_counts_both_directions). That test is well built (its 5-row fixture carries one flagged-but-not-shaped row and one shaped-but-not-flagged row, so it is not a cardinality-1 fixture restating totals). Still, delete that one test and both directions go dark at once.

Findings

Minor, and I'd fix it before merge · deploy/harbor/keepalive_ping_stats.py:322 — os.chmod(args.out, 0o644) runs unconditionally, including under --raw-ids, when the CSV carries real tenant_id plus per-row dollar figures (ping_cost_usd, next_real_cost_usd).

This repo has already decided this exact question, in the sibling script, with a comment saying why:

# kv_ttl_cost_model.py:1750-1756
# 0600, and created that way rather than chmod'd afterwards: the payload carries
# by_user keyed by TENANT ID with each account's request count and dollar total, so a
# world-readable default (0644 minus umask) hands per-customer spend to every local
# user. O_CREAT|O_TRUNC with the mode set at creation leaves no window where the file
# exists with wider permissions.
fd = os.open(args.json, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)

The sharp version: this is not a missing restriction, it is an active widening — open(args.out, "w") would inherit the umask, and the chmod then explicitly makes it world-readable. Failure scenario: an operator debugging one customer runs collect --export bundle.zip --raw-ids --out /var/tmp/pings.csv (a realistic use of --raw-ids, since debugging usually means you already know the tenant) and per-customer spend becomes readable by every local account. Fix: 0o600 when --raw-ids is set — or unconditionally, as the sibling does, since the pseudonymised default does not need 644 either. Adopting the sibling's atomic os.open idiom matters once the mode narrows, for the reason its own comment gives.

Minor · the agent column has no --raw-ids gate. tenant and session are pseudonymised by default; agent is exported verbatim. dash/event.go:agentFromUserAgent maps known clients to eight fixed tokens but otherwise falls back to up to 32 characters of the raw lower-cased User-Agent. Pre-existing Go behaviour, newly surfaced by this export. Low practical severity, but the docstring's "No message content is read" paragraph currently reads as a blanket privacy claim and this is the one column it does not fully cover — worth a sentence there.

Nits: dead io import (:52, zero references); no unittest.skipUnless(HAS_PANDAS, …) around the three pandas tests, so the body's "runs anywhere the collector does" claim is documented rather than self-enforcing; no test for a 5xx ping with all-zero usage although the docstring calls that case out explicitly (I built it synthetically — the logic is correct, landing in the "no usage at all (see status)" bucket with ping_cost_unpriced correctly staying 0, it is just untested); no test pinning the "session with real rows and zero pings contributes no output rows" filter (verified empirically, unasserted).

Verified safe

  • Zip-slip / absolute-path members: crafted both a ../../../../tmp/... member and an absolute-path member; neither escaped the mkdtemp'd root (stdlib extractall sanitises both). Note this protection is incidental to using zipfile.extractall — nothing in the script asserts it, so switching extraction libraries would silently reintroduce the class. No zip-bomb guard, which I'd accept for an operator-invoked forensics tool.
  • SQL injection: the only string-built SQL interpolates names from the hardcoded COLS list; --since-ms is bound with ? placeholders and argparse type=int rejects non-numeric input first.
  • Read-only on every path: collect() opens file:{db}?mode=ro uniformly; collect_export() never touches sqlite. No ATTACH, no write, no temp file beside the DB; the export tempdir is mode 0700.
  • No content or credentials on any error path. request_content is verifiably never selected — not in COLS, not in SQL, confirming the docstring's own claim.
  • The stdlib/pandas split is honoured in fact: no pandas at module scope; it is imported lazily inside cmd_stats/summarize only, so collect really can run as the service account.
  • Edge cases probed synthetically: n=0 and n=1 pings (gap fields come back None, not 0, matching the documented contract; the self-check block is skipped entirely at n≤1 rather than taking a median of nothing), all-identical gaps, median = 0 (1.75 * 0 makes the near-2× check g.gt(0) — well defined, no ZeroDivisionError), a negative gap and a ~1.8×-median gap together, and percentages from a zero denominator (guarded by pct()). Notably, a genuinely free no-usage row is distinguished from an unpriced had-usage row — the "$0.00 read as free" trap this repo has hit before is handled.

No docs gap

The diff adds no page and no mkdocs.yml entry, and that matches house convention: analyze.py, analyze_content.py, cachecost.py, cgenv.py and diffsum.py all ship without one. The scripts that do get pages are the ones backing a published investigation. So the docstring is the documentation here, which is why it was held to a doc's standard above.

Not verifiable within the data boundary

Taken on the author's word, not disputed: the 1,038 pings / 255 sessions / 15 accounts / $150.87 over 2026-08-23..09-02; the 91.8% inside the ±12s band and the 270-272s clustering vs the uncorrected 273-288s scatter; the "0 flagged rows disagree, 0 unflagged rows shaped like a ping" audit result; and the "every ping followed within ~1s by a 400" export observation. Each is author-reported production evidence whose mechanism is independently verifiable in the Go source, which is what the audit table above does.

os.chmod(args.out, 0o644) ran unconditionally after writing the file,
widening it past the creating umask even under --raw-ids, where the CSV
carries real tenant_id plus per-row dollar figures. Follow the sibling
kv_ttl_cost_model.py precedent: create the file 0600 via os.open with
O_CREAT|O_TRUNC so there is no window where it exists world-readable.

Also fix two stale line citations in the docstring against current Go
(proxy/keepalive.go:908, proxy/proxy.go:1143), note that the agent
column is exported verbatim regardless of --raw-ids, drop the now-dead
io import, and round out test_keepalive_ping_stats.py: skipUnless
guards on the three pandas-only tests so a pandas-less run reports
"skipped" rather than erroring, plus tests for a 5xx ping with no usage
and for a session with no pings contributing no rows.

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

Copy link
Copy Markdown
Collaborator

Pushed ab27bdf to address the review at #196.

Security fix (the one worth blocking on): cmd_collect() was doing
open(args.out, "w") then os.chmod(args.out, 0o644) unconditionally,
including under --raw-ids, on a CSV carrying tenant_id plus per-row
dollar figures. Switched to the same idiom kv_ttl_cost_model.py already
uses: os.open(args.out, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, 0o600), so the
file is created 0600 and never exists world-readable, even transiently.

Verified with a real invocation over a synthetic DB (no production data
touched):

before (open+chmod):  644
after  (os.open 0600): 600

Stale docstring citations, checked against Go at this branch's
checkout: proxy/keepalive.go:906 → :908 (the 4xx-early-return guard),
proxy/proxy.go:1109 → :1143 (keeper.arrive(). Both fixed.

Nits: dropped the dead io import; added a sentence noting agent is
exported verbatim regardless of --raw-ids; added unittest.skipUnless
guards on the three pandas-only tests in test_keepalive_ping_stats.py so
a pandas-less run reports "skipped" instead of erroring; added a test for
a 5xx ping with all-zero usage and one for a session with no pings
contributing no output rows.

Self-test output — 16/16 pass either way, pandas-less and with pandas:

$ python3 deploy/harbor/test_keepalive_ping_stats.py -v
Ran 16 tests in 0.080s
OK (skipped=3)

$ uv run --with pandas python3 deploy/harbor/test_keepalive_ping_stats.py -v
Ran 16 tests in 0.168s
OK

On the CI-coverage point: I didn't add a CI job or a --self-test
flag — this script already ships test_keepalive_ping_stats.py, which
your mutation testing already showed catches real defects. Wiring that
suite into CI (a Python job in ci.yaml, or pinning it via a Go drift
test the way #212 does) seems worth doing, but I'd rather leave that as a
proposal than bolt on a CI job unreviewed — happy to open it as a
follow-up if that's wanted.

git merge-tree origin/main HEAD is still clean (exit 0, no conflict
markers) after this push.

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