Repository navigation
feat(kvcache): measure the idle keep-alive per ping — cache outcome, gaps and cost - #196
Conversation
…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]>
Review: audited the docstring against the Go, mutated the script, and probed it with synthetic data onlyReviewed at Data boundary: this script reads the production service database ( CI does not run this PR
Worth contrasting with #212, which faces the same problem and solves it: its Python is pinned by Go drift tests under Real run results
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 Docstring-claim audit — the script's correctness argument, checked against the GoThe docstring is written to be checkable, so it was checked. Every substantive claim holds; two citations do not.
Minor · docs · both citations were wrong when written, not drifted. I checked the two files at the PR's own merge-base ( Mutation testing — four defects introduced in the script, one at a time
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 ( FindingsMinor, and I'd fix it before merge · 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 — Minor · the Nits: dead Verified safe
No docs gapThe diff adds no page and no Not verifiable within the data boundaryTaken 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]>
|
Pushed Security fix (the one worth blocking on): Verified with a real invocation over a synthetic DB (no production data Stale docstring citations, checked against Go at this branch's Nits: dropped the dead Self-test output — 16/16 pass either way, pandas-less and with pandas: On the CI-coverage point: I didn't add a CI job or a
|
What this adds
Two files under
deploy/harbor/, alongside the existingkv_ttl_*analysis scripts:keepalive_ping_stats.py— produces one row per idle keep-alive ping over a window ofhistory, 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 syntheticrequeststable. Noproduction 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.gocarries a detailed account of what the mechanism is worth, sourced from areplay (
TestKeepAliveOnProductionSnapshot). What we did not have was a way to ask the samequestions 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_usdreports theservice'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 thedistinction is documented at the top of the script because it changes how a count is read:
KeepAlive: trueis set in exactly one non-test place in the service,proxy/keepalive.go(record1), and nothing everUPDATEs the column afterwards — thestrategy backfill writes
keepalive_strategy_idonly. No benchmark, simulation or campaignpath writes a ping row. Rows predating the mechanism read
0by theALTER TABLEdefault, andcorrectly 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).
failed in transport, or answered 4xx returns before
record1, so it never becomes a row. Thetable holds pings that were sent and answered non-4xx;
KeepAliveStatson/statsholds whatwas attempted.
The collector does not take the flag on trust. It also evaluates an independent structural
fingerprint of the row shape
record1produces —max_tokens=1,stream=0, and zero formessages,tokens_before,mode,cache_miss_reason,cg_latency_ms,ttfb_ms— in bothdirections, and prints any disagreement as a number. Over 1,038 production pings it reported
0flagged rows whose shape disagrees and0unflagged 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.
tsmeans different things on the two row types. A real request'stsis its start(
proxy/dashcapture.go,TS: c.start.UnixMilli()); a ping's is stamped inrecord1, after theround trip. Every gap here is therefore start-to-start, which is also the footing
CachePolicy.Idleand the provider's lifetime rule both use. It matters: corrected,gap_before_sclusters 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_reasonfrom
AttributeCache. On the first sample checked, taking the immediate next row reported 0 of 4following 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:
WHERE keepalive = 1has no supporting index, so an unbounded run is a full scan of the livefile. Pass
--since-ms <epoch ms>to bound it, which lets the query useidx_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.csvthatis
SELECT * FROM requests.Account ids are pseudonymised (
t01,t02, …) and session ids hashed unless--raw-idsispassed. No message content is read —
request_contentis never queried.Tests:
python3 deploy/harbor/test_keepalive_ping_stats.py # or run under pytestHow to read the results
collectprints three lines to stderr: how many pings it found, the identification audit in bothdirections, 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".
statsprints four blocks:ncolumn; it differs per row.gap_before_sis the configuredIdlerecovered from data.
gap_before_prev_real_sskips back past intervening pings, so on a secondping it measures the whole span rather than the inter-ping step.
gap_after_next_real_sis theone that answers "when did the human come back".
ping_cost_usdis heavily right-skewed, soread the median next to the mean.
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 nothingis the failurekeepalive.gocalls the mechanism being wrong rather than expensive.HITline is what happened; thecreditedline is theservice's own attribution, which a non-2xx row arriving first can consume. Expect them to
disagree. The
cache_miss_reasonbreakdown separates "came back too late" (ttl_expiry) from"the prefix moved" (
prefix_change) from "a different model" (cold_start, which with thesession already seen means
!seenModeland is not addressable by pinging).identification and the
tscorrection are both right: the share of gaps within ±12s of themedian is the band a 2s sweep firing one tick after
Idleproduces. It also names its twotails, 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/14tests pass. Run against the live ledger for 2026-08-23..09-02: 1,038 recorded pings across255 sessions and 15 accounts,
$150.87of ping spend, identification audit clean in bothdirections, and
91.8%of gaps inside the ±12s band. The same code over a session export bundlereproduces its rows identically.
CI does not currently run Python, so
test_keepalive_ping_stats.pyis a manual gate; it isstdlib-only apart from the two summariser tests, so it runs anywhere the collector does.