Skip to content

fix(keepalive): book a timed-out ping at its projected cost (#754) - #1186

Merged
amiddavid merged 3 commits into
mainfrom
fix/754-timeout-ping-cost
Nov 17, 2026
Merged

amiddavid merged 3 commits into
mainfrom
fix/754-timeout-ping-cost

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #754.

Behavior change (approved by boazdavid, 2026-11-17)

Who it affects: every proxy that runs keep-alive, on a ping that runs to its 60 s timeout. On the owner's proxy, that was 92 of 95 failed pings (#719).

Old: a timed-out ping adds 1 to failed and books nothing: no row, no cost, no metric.

New: it books one row at the keeper's projected cost of one ping (e.pingUSD), marked stop_reason = timeout_estimated, with status 0 and no tokens. These figures change:

Figure Old New
/stats keepalive.spend_usd measured pings only + the projected cost of each timeout
/stats keepalive.timed_out (did not exist) count of timeouts (a part of failed)
Dashboard keep-alive ledger pings, ping_usd, net_usd timeouts left out timeouts included
Ledger pings_timed_out, ping_timed_out_usd (did not exist) count and projected USD of timeouts
Ledger pings_that_read_nothing (timeouts never had rows) timeouts are not counted here
Strategy and campaign ledgers (dash/keepalivestrategy.go, dash/campaignsavings.go), adaptReport, insights.py net_usd / losers timeouts left out timeouts included in ping cost
Month-to-date tenant_spend / control-plane spent_usd timeouts left out + the projected cost. Display only, not a cap (proxy/limits.go). It is a rollup, so rows booked now stay in it.
Central metric llm_keepalive_pings_total timeouts left out outcome="timeout", as docs/metrics/spec.md §5.3 defines
Central metric llm_keepalive_cost_usd_total timeouts left out + the projected cost
Central metric llm_keepalive_estimated_cost_usd_total (did not exist) the projected part of the line above, a sub-set (spec rule 6: estimates stay visible)
Central Grafana "Cache and keep-alive" board no estimate shown new "Estimated ping cost" stat; "Pings that paid" is half as tall

What does not change: a timed-out ping is not a refresh. No cache clock moves, it gets no rescue or saving credit, and it does not stop or restart pinging. Fast failures (EOF, reset, refused) still book nothing.

How to turn it off: there is no switch for this change alone. CONTEXT_GURU_KEEPALIVE=off turns off keep-alive as a whole.

Decision: boazdavid approved the change on 2026-11-17, including the central metrics and tenant_spend, and asked that the new metric be added to the metrics spec.

Data dependence

Metadata only: a projected cost (prompt size × a price), a counter and a stop-reason string. Nothing new is stored. The data dependence of keep-alive does not change, so docs/data-dependence/features/keep-alive-pings.md needs no edit.

Problem

A keep-alive ping that runs to its 60 s timeout is counted only as failed. It writes no row and books no cost. But it probably reached the provider and was billed (#532). So the dashboard and /stats undercount keep-alive spend and overstate its net saving.

Reproduced on main (f3f108cd) with a fake dispatcher: the same thread with the same price books $0.015015 on a successful ping and $0.000000 on a timed-out one. The keeper's own projection for that ping is $0.015015.

Change

  • Keeper (keepalive/keeper.go). If the error is context.DeadlineExceeded, or the ping's context ran out, recordTimedOut books one row at e.pingUSD and sets KeepAliveReport.TimedOut. It adds the cost to spend_usd and to the entry's spend. No cache clock moves, and Refreshed stays as it was.
  • /stats: new timed_out. failed still counts timeouts.
  • Dashboard. The row is stored with stop_reason = "timeout_estimated" (dash.StopTimeoutEstimated). A timed-out ping has no provider stop reason, so this column is free, and no schema change is needed. The refresh probes need cache_read > 0 or cache_write > 0, and PingSavings needs a 2xx, so the row gets no refresh or saving credit.
  • Central metrics (proxy/inferencemetrics.go): the row is pushed as outcome="timeout". Its cost goes to llm_keepalive_cost_usd_total and also to the new llm_keepalive_estimated_cost_usd_total.
  • Metrics spec (docs/metrics/spec.md): §5.3 adds the new counter, says what a timeout ping books and where, and notes that skipped is not emitted yet. §6.3 adds the "Estimated ping cost" panel.
  • Central dashboard (deploy/central/grafana/): the "Estimated ping cost" stat, and corrected "Ping outcomes" text. The JSON is regenerated, and gen_dashboards.py --check passes.
  • Docs: docs/how-to/cache-keepalive.md lists timed_out and says how a timeout is booked. docs/reference/reference.md says that a timed-out ping leaves a row.

Not in scope

  • The 60 s timeout, and retries (as the issue says).
  • The dashboard JS does not show pings_timed_out / ping_timed_out_usd yet. The API returns them.
  • A manual ping (the Ping button, keepalive/manual.go) that times out still books nothing. That is a follow-up.

Tests

  • TestATimedOutPingBooksItsProjectedCost: 1 row, cost e.pingUSD, TimedOut, timed_out 1, failed 1, Refreshed unchanged.
  • TestAFastFailedPingBooksNothing: EOF books no row and no cost.
  • TestDashEmitterBooksATimedOutPingAsEstimatedSpend: report → dash row → KeepAliveLedger, including ping_timed_out_usd.
  • TestPingBooksKeepAliveAndNoRequest: a timeout row is pushed as outcome="timeout", its cost is in the cost metric, and only its cost is in the estimated cost metric.
  • TestCentralNamesMatchTheSpec now expects llm_keepalive_estimated_cost_usd_total. It needs a live central stack, so it was not run here (it skips).
  • Mutation checks: removing the booking, the dash mark, the read-nothing exclusion, the timeout label, or the estimated cost booking each makes a test fail.
  • keepalive, dash, proxy, components and metrics pass. In proxyapp, TestPreflightResolvesToolsOnTheServicePATH and TestPreflightReadsKeyEnvFromConfigNotComments fail locally (bash 3.2 on macOS). They fail the same way on clean main.

Assisted-By: Claude (Anthropic AI) [email protected]

A keep-alive ping that ran to its 60 s timeout was counted only as
failed. It wrote no row and booked no cost, although it probably
reached the provider and was billed (#532). So the dashboard and
/stats undercounted keep-alive spend and overstated its net saving.

When a ping fails with context.DeadlineExceeded, the keeper now books
one row at e.pingUSD, its own projection of one ping on the prefix,
and marks the report TimedOut. The row counts as spend, not as a
refresh: no cache clock moves and Refreshed stays as it was. A fast
failure (EOF, reset, refused) still books nothing.

- /stats gets timed_out, the part of failed that timed out.
- The dashboard row is stored with stop_reason = timeout_estimated,
  so it needs no schema change. The keep-alive ledger counts it in
  pings and ping_usd and in the new pings_timed_out, and no longer in
  pings_that_read_nothing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session fresh 2 of 2 1 of 2 383e4e2e011e blocking

Verdict: blocking

The keeper change is correct. Booking, refresh, and fail-open logic are sound. Two findings remain. One is a wrong label in the central metrics. The other is a missing part of the PR description that CLAUDE.md requires.

Findings

  1. proxy/inferencemetrics.go:210 — a timed-out ping is pushed as outcome="failed", not outcome="timeout"

    • What fails: before this PR, a timed-out ping wrote no row, so it never reached the push metrics. Now dashEmitter.KeepAlivePing builds a row with Status: 0 and calls observeMetrics → sinks.inference.Observe(ev, 0) → observePing. observePing sets outcome = "failed" for any status outside 2xx. So every timeout now adds 1 to llm_keepalive_pings_total{outcome="failed"}.
    • Proof: docs/metrics/spec.md:326 defines the label values. failed means "the provider returned an error". timeout means "no answer in time". This PR creates the first timeout case, and the code labels it failed. Also, llm_keepalive_cost_usd_total now includes the projected cost of a timeout, with no estimate mark. The KeepAliveReport.TimedOut doc (components/component.go:1256) says a sink should mark it as an estimate. The PR text does not mention any change to the central metrics.
    • Fix: in observePing, set outcome = "timeout" when e.StopReason == dash.StopTimeoutEstimated. Add a test for it, for example in proxy/inferencemetrics_test.go. Name the central metric change in the PR text.
  2. PR description — no behavior-change statement and no data-dependence statement

    • What fails: CLAUDE.md asks for 2 things that the PR body does not have.
      • "Metadata first": every PR that changes a feature states its data dependence and what it does at each storage level. The PR body has no such section. Issue #754 says "Metadata only", but the PR does not.
      • "No behavior change for an edge case without a human developer's permission": name the change at the top of the PR (who it affects, the old and the new behavior, how to turn it off).
    • Proof: this PR changes what users see. /stats spend_usd, the dashboard ping_usd and net_usd, KeepAliveNetUSDByTenant, the strategy ledgers (dash/keepalivestrategy.go:45, dash/campaignsavings.go:120), and the central llm_keepalive_* metrics all go up by the projected cost of each timeout. A new ping row with status 0 also appears. Issue #754 (by @amiddavid) proposes the /stats and dashboard parts. It does not mention the central metrics.
    • Fix: add a short "Behavior change" section at the top. List the figures that change, old and new, and say there is no switch (or add one). Add a "Data dependence" section: metadata only (a projected cost and counts, no new content stored). If you think the keep-alive row should say that timed-out pings are booked, edit docs/data-dependence/features/keep-alive-pings.md and run go run ./cmd/gen-datadep. Ask @amiddavid to confirm the central-metric part.

Non-blocking

  • dash/event.go:370-376 is now stale. It says a transport error on send returns "without writing a ping row". A timed-out ping now writes one. Update the comment.
  • docs/how-to/cache-keepalive.md:244-246 lists the /stats keep-alive fields. Add timed_out there.
  • keepalive/manual.go:142-148: a manual ping (the Ping button) that times out still books nothing. Its own comment says "A deadline or cancel may have left a billed request behind". The same undercount remains for that path. A follow-up issue is enough.
  • keepalive/keeper.go:1535: giveBackFailedPing runs before the booking. On an OpenAI thread (30 min cache, ping at 28 min), a 60 s timeout returns at about 29 min, inside the lifetime, so the keeper retries it. Then the timed-out row and the retry row carry the same Pings number, and the billed timeout does not use up one of MaxPings. This is probably acceptable, but the commit text does not say it.
  • keepalive/timedout_ping_test.go covers only errors.Is(err, context.DeadlineExceeded). No test covers the ctxErr branch (the dispatcher returns a different error after the deadline). The fake uses k.now(), and context.WithTimeout uses the wall clock, so that branch is hard to test without a dispatcher that blocks on ctx.Done(). Note also that the old TestAFailureAfterTheCacheExpiredIsNotRetried (keepalive/failedping_test.go:59) returns errors.New("context deadline exceeded"), a plain string. So it does not book a row, and its name suggests a timeout that this PR would now book.

What I checked

  • I read the full diff (8 files, 1 commit 383e4e2e), the commit message, the PR body, and issue #754 with its comments.
  • keepalive/keeper.go: fire, giveBackFailedPing, record1, the new recordTimedOut, projectedPingUSD, and Stats. ctx.Err() is read before cancel(), which is correct. recordTimedOut reads the entry fields under k.mu. It does not move refreshedAt, does not call touch, and does not change e.refreshed. e.spent is report-only and is not a cap (keeper.go:163), so booking it changes no ping decision.
  • keepalive/manual.go: the manual ping path, which this PR leaves unchanged.
  • proxyapp/main_run.go dashEmitter.KeepAlivePing: the new StopReason override. ev.Price(..., false) sets token_accounting = missing, then CostUSD gets the projected cost. PingSavings returns no result for status 0, so the row gets no saving credit. dash/reprice.go:125 only reprices rows with cost_usd = 0, so it does not wipe the estimate.
  • proxy/inferencemetrics.go observePing and docs/metrics/spec.md §5.3 (finding 1).
  • dash/keepalive.go ledger SQL. stop_reason is NOT NULL DEFAULT '' (dash/schema.go:366), so != has no NULL problem. The refresh probe in kaSavedGate needs cache_read > 0 (or cache_write > 0), so a timed-out row cannot credit a rescue. dash/capture.go:966 uses the same gate for the cache clock.
  • Other readers of ping rows: dash/keepalivestrategy.go, dash/campaignsavings.go, dash/overview.go, dash/kvcache.go (ping rows only with WithKeepAlive), and context-guru-plugin/scripts/insights.py. None breaks. Only the totals change.
  • The golden file dash/testdata/golden/keepalive.json adds pings_timed_out: 0.
  • Data dependence: docs/data-dependence/features/keep-alive-pings.md. The PR edits no row file and does not touch the generated page.
  • I did not run any build or test. Live tests are not approved.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 383e4e2e011e blocking

Verdict: blocking

The code does what #754 asks, and I found no correctness defect in it. The one finding is the repo's behavior-change rule. The change reaches more figures than the issue names, and the PR does not name any of them at the top.

Findings

  1. PR body / proxyapp/main_run.go:1142 — the behavior change is not named at the top of the PR, and some side effects go past the scope of #754
    • What fails: CLAUDE.md ("No behavior change for an edge case without a human developer's permission") says a fix that changes what is shown must name the change at the top of the PR: who it affects, the old and new behavior, and how to turn it off. The PR starts with "Problem" and "Change". It has no behavior-change header and no off switch. #754 (by @amiddavid) asks for the booking in "the dashboard and /stats". But the new row also changes these figures, and neither the issue nor the PR names them:
      • Pushed central metrics. dashEmitter.KeepAlivePing → observeMetrics → InferenceMetrics.observePing (proxy/inferencemetrics.go:209-217). Each timed-out ping now adds 1 to llm.keepalive.pings{outcome="failed"} and adds the projected USD to llm.keepalive.cost.usd. Before this PR, a timed-out ping added nothing. The metric has no estimate label, so the central collector cannot tell the estimate apart from measured cost.
      • Month-to-date spend. dash/store.go:727 adds e.CostUSD of every row to tenant_spend. The control plane shows it as spent_usd (proxy/control.go:490). It now includes estimates, and it is monotonic, so a later fix cannot remove them.
      • Strategy and campaign ledgers. StrategyLedger (dash/keepalivestrategy.go:45) and CampaignRealSavings (dash/campaignsavings.go:120) sum cost_usd over keepalive = 1 rows. Their comments call this cost "EXACT" / "exact per row". adaptReport (proxy/adaptcache.go:370,568) and insights.py (net_usd, losers) read the same PingUSD. These outputs feed the advice to keep or change a keep-alive strategy.
      • pings_that_read_nothing. It changes meaning: timed-out rows are now left out of it (dash/keepalive.go:369). insights.py:1650 reads it.
    • Proof: the trace is keeper.fire (keepalive/keeper.go:1543-1546) → recordTimedOut (:1805-1826) → KeepAliveReport{TimedOut: true, CostUSD: e.pingUSD} → dashEmitter.KeepAlivePing (proxyapp/main_run.go:1106-1170). That function calls d.observeMetrics(ev, …) and d.rec.Record(ev) for every report, with no TimedOut check. The PR body's "Change" section names only the keeper, /stats and the dashboard ledger.
    • Fix: at the top of the PR, add a "Behavior change" section. List each affected figure above, with old → new. State that there is no off switch, or add one. Ask @amiddavid to confirm the side effects that #754 does not name, mainly the central metric and tenant_spend. If the central metric must stay measured-only, skip observeMetrics cost for r.TimedOut, or label it.

Non-blocking

  • Docs drift. docs/how-to/cache-keepalive.md:245-246 lists the /stats keepalive fields without timed_out. Line 190 says "A failed ping is logged and forgotten", which is no longer true for a timeout. Lines 195-196 say every ping row has "its own tokens, its own cost". A timed-out row has 0 tokens and a projected cost.
  • Data dependence is not stated in the PR. CLAUDE.md asks every PR that changes a feature to state its data dependence. #754 states it ("Metadata only"), but the PR body does not. The row docs/data-dependence/features/keep-alive-pings.md needs no edit: the new fields are a flag, a counter and a stop-reason string.
  • No test for the ctxErr branch. keepalive/keeper.go:1543 also books when ctx.Err() is DeadlineExceeded but err does not wrap it, for example a dispatcher that flattens its error with %v. Both new tests return an error that wraps context.DeadlineExceeded, so they never reach that branch. A fake dispatcher that blocks on ctx.Done() and then returns errors.New("upstream gone") would cover it. A short test timeout would need pingTimeout to be injectable.
  • A timeout is not always a sent request. A 60 s dial or TLS hang (for example, a black-holed SYN) or a wait inside the host dispatcher also ends in DeadlineExceeded. Neither one reached the provider. The comment "was sent" (keepalive/keeper.go:1539) is stronger than the facts. The report doc says "probably", which is the correct word. Consider using "probably" in the keeper comment too.
  • The ledger gives a count but no USD for estimates. KeepAliveLedger.PingsTimedOut is a count only. Because PingUSD mixes measured and projected cost, a reader cannot split them. A PingTimedOutUSD field (one more SUM(CASE …)) would help the dashboard show the estimate apart, as #754 point 3 asks.
  • recordTimedOut reads e.pingUSD when the ping ends, not when it starts. A real request during the 60 s wait can change e.prefix/e.pingUSD. The effect on an estimate is small.

What I checked

  • I read the full diff (8 files, +209/−4) and the commit message. I also read the PR body and #754. I did not read other reviews or comments.
  • keepalive/keeper.go: all of fire, noteOutcome, giveBackFailedPing, record1, addSpent, Stats. ctxErr is read before cancel(), which is correct. recordTimedOut takes k.mu for the e fields and does not touch refreshed, refreshedAt or startedAt, so no cache clock moves. A retry through giveBackFailedPing books a second row only when a second ping really goes out, which is correct.
  • I checked that e.spent / k.spentUSD / tenant_spend gate nothing. SpendChecker is "for display. Not a cap" (proxy/limits.go:275), and EntryView.Spent has no reader that makes a decision. So the extra spend cannot stop pings or refuse requests.
  • Dash consumers of the new row (status 0, all tokens 0, token_accounting = missing, cost > 0):
    • CacheStateFor needs 2xx and cache tokens, so the row does not change the cold countdown.
    • The kaSavedGate probes need cache_read > 0 / cache_write > 0, so the row gets no rescue credit.
    • capture.go:379 needs cache tokens.
    • PingSavings needs a 2xx.
    • noteUnpriced skips rows with 0 tokens, so the reprice pass never zeroes the estimate.
    • DropUnbilledSavings leaves status 0 alone.
    • The stop_reason column is NOT NULL DEFAULT '' (dash/schema.go:366), so != 'timeout_estimated' cannot drop old rows through NULL.
  • Tests: the helpers newFake, trackedRecord, reportSink, fixedPrice, proxyPricer and setPrices exist with the signatures the new tests use. In TestATimedOutPingBooksItsProjectedCost, the clock moves to 281 s + 60 s = 341 s, which is past refreshedAt + 300 s. So giveBackFailedPing refuses, and fd.n() == 1 holds. The golden file adds pings_timed_out: 0, and no other golden file has the ledger.
  • Data dependence: the row file needs no change, and docs/data-dependence.md is not touched.
  • I ran no Go build or test, as this review's instructions say.

…imated cost (#754)

Review round 1 on #1186.

- proxy/inferencemetrics.go: a row marked timeout_estimated is pushed
  as llm_keepalive_pings_total{outcome="timeout"}, as docs/metrics/spec.md
  defines it, not as "failed" (the provider returned an error).
- dash/keepalive.go: the keep-alive ledger adds ping_timed_out_usd, the
  part of ping_usd that is a projection, so a reader can split measured
  spend from estimated spend.
- Comments and docs: a timed-out ping now writes a row
  (dash/event.go, docs/how-to/cache-keepalive.md), /stats lists
  timed_out, and the keeper says "probably sent", because a dial or TLS
  hang also ends in a timeout.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1 (head 383e4e2e → abd9de30)

Reviewer 1

  1. Behavior change not named; side effects past keepalive: book a timed-out ping as an estimated cost #754. Fixed in the PR body. A "Behavior change" section is now at the top. It lists each figure that changes, old and new: /stats, the dashboard ledger, the strategy and campaign ledgers, tenant_spend, and the central metrics. It says there is no switch for this change alone. It asks a human developer to confirm the parts that keepalive: book a timed-out ping as an estimated cost #754 does not name (the central metrics and tenant_spend). I did not add a switch, because that decision belongs to a human.

Non-blocking:

  • Docs drift: fixed in abd9de30. docs/how-to/cache-keepalive.md lists timed_out and says that a timeout is booked at its projected cost with no tokens.
  • Data dependence not stated: fixed in the PR body ("Metadata only"). The row file needs no edit.
  • No test for the ctxErr branch: not fixed. pingTimeout is a 60 s constant and context.WithTimeout uses the wall clock. So a test needs a 60 s wait, or a change that makes pingTimeout injectable only for this test. The real dispatcher returns the net/http error unchanged, and *url.Error unwraps to context.DeadlineExceeded. So the errors.Is(err, …) branch is the one production takes, and the tests cover it.
  • "was sent" is too strong: fixed in abd9de30. The keeper comment now says "probably sent", and it names the dial or TLS hang case.
  • No USD for estimates: fixed in abd9de30. The ledger adds ping_timed_out_usd. The test checks it.
  • e.pingUSD read at the end of the ping: kept. The value is an estimate. A real request inside the 60 s wait can change the prefix only a little, and the new prefix is what the provider holds now.

Reviewer 2

  1. Timed-out ping pushed as outcome="failed". Fixed in abd9de30. observePing reports a StopTimeoutEstimated row as outcome="timeout", as docs/metrics/spec.md §5.3 defines it. TestPingBooksKeepAliveAndNoRequest now checks one ok, one failed and one timeout, and checks that the cost includes the projection. Mutation check: when I remove the timeout case, the test fails. The cost metric still includes the projection. The PR body names this, and asks a human to confirm it.
  2. No behavior-change or data-dependence statement. Fixed in the PR body. See Reviewer 1, finding 1.

Non-blocking:

  • dash/event.go comment is stale: fixed in abd9de30.
  • docs/how-to/cache-keepalive.md lacks timed_out: fixed in abd9de30.
  • A manual ping that times out still books nothing: correct. This PR does not cover it. The PR body names it as a follow-up under "Not in scope".
  • On an OpenAI thread, giveBackFailedPing can retry a timed-out ping inside the 30 min cache, so two rows carry the same Pings number. That is correct: two requests were sent and both are booked. A timeout that is given back does not use one of MaxPings, the same as before this PR. This PR changes only the booking, not the schedule.
  • No test for the ctxErr branch: see Reviewer 1 above.
  • TestAFailureAfterTheCacheExpiredIsNotRetried returns a plain string error, so it books no row. That test checks the retry schedule, not the booking, and the booking does not change its result. I left it unchanged.

Tests on abd9de30

go vet passes. keepalive, dash, proxy, components and metrics pass. In proxyapp, TestPreflightResolvesToolsOnTheServicePATH and TestPreflightReadsKeyEnvFromConfigNotComments fail locally. They fail the same way on clean main (f3f108cd).

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session resumed 2 of 2 2 of 2 abd9de30d272 approve

Verdict: approve

All round-1 findings of both reviewers are fixed or answered with a correct reason. The new commit abd9de30 adds no defect.

Merge gate, not a finding: the PR body asks a human developer to confirm the behavior change. This is mainly the central cost metric and tenant_spend, which #754 does not name. CLAUDE.md says that a reviewer agent cannot give this yes. Get @amiddavid's confirmation before merge.

Findings

None.

Earlier findings

  • Reviewer 2, finding 1 (outcome="failed" for a timeout): fixed. proxy/inferencemetrics.go observePing now checks e.StopReason == dash.StopTimeoutEstimated first and sets outcome = "timeout". Then it checks the status. This matches docs/metrics/spec.md §5.3. TestPingBooksKeepAliveAndNoRequest adds a status-0 timeout_estimated row. It expects one ok, one failed and one timeout, and a cost of 0.005, which includes the 0.002 projection. The cost metric still has no estimate label. The PR body names this and gives it to a human to decide. I accept that.
  • Reviewer 2, finding 2 (no behavior-change or data-dependence statement): fixed. The PR body now starts with "Behavior change". It names who the change affects, the old and new behavior in a table of 9 figures, and that no switch exists for this change alone (CONTEXT_GURU_KEEPALIVE=off turns off all of keep-alive). It names the open questions for a human. A "Data dependence" section says "Metadata only". I agree that docs/data-dependence/features/keep-alive-pings.md needs no edit.
  • Reviewer 1, finding 1 (behavior change not named, side effects past #754): fixed. I checked it as a part of my finding 2. The table names the central metrics, tenant_spend, the strategy and campaign ledgers, adaptReport and insights.py.
  • Non-blocking items:
    • dash/event.go stale comment: fixed.
    • /stats timed_out in docs/how-to/cache-keepalive.md: fixed, with a new sentence at line 191 on how a timeout is booked.
    • "was sent" changed to "probably sent": fixed (keepalive/keeper.go:1539-1543).
    • ping_timed_out_usd in the ledger: added. The SQL uses the same autoPing and stop_reason gate as pings_timed_out. The scan order matches the column order. The golden file adds the key in alphabetical position.
    • Manual-ping timeout: listed as a follow-up under "Not in scope". I accept that.
    • Retry gives the same Pings number twice: rejected with a reason. Two requests went out and both are booked, and the schedule is as before this PR. The reason is correct.
    • No test for the ctxErr branch: rejected with a reason. pingTimeout is a constant, and context.WithTimeout uses the wall clock. The real dispatcher returns the net/http error, and *url.Error unwraps to context.DeadlineExceeded. The reason is correct. The branch is a safety net.
    • Plain-string error in TestAFailureAfterTheCacheExpiredIsNotRetried: rejected. That test checks the retry schedule, not the booking. The reason is correct.
    • e.pingUSD is read at the end of the ping (reviewer 1): kept, because the value is an estimate. I accept that.

Non-blocking

  • docs/how-to/cache-keepalive.md:195-196 still says every ping row has "its own tokens, its own cost". A timed-out row has 0 tokens and a projected cost. Line 191 now says this, so a reader can find it.

What I checked

  • Last review: round 1, 383e4e2e011eae7622ba7a720bc2e1fdbc8b498a, 2026-11-17T05:55:44Z
  • New commits read: 1 (abd9de30 fix(keepalive): report a timed-out ping as timeout, and split its estimated cost (#754))
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 1 round-1 review (05:56:12Z). I read it. I checked its finding 1 as a part of my finding 2. I checked each of its non-blocking items against abd9de30 and the author's replies (listed above).
    • The author's reply comment (06:07:11Z). I checked each reply against the code and the PR body (listed above).
    • The updated PR body. I read it in full: the "Behavior change", "Data dependence", "Change", "Not in scope" and "Tests" sections.
  • Diff 383e4e2e..abd9de30: all 8 files. I read observePing and the code around it, the KeepAliveLedger SQL and its Scan, the doc text around lines 180-200 and 240-250 of docs/how-to/cache-keepalive.md, and the two test changes. proxy/inferencemetrics.go already imports dash, so the import cycle rule holds (proxy imports dash, not the reverse).
  • I ran no build or test. Live tests are not approved.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 abd9de30d272 approve

Verdict: approve

All round-1 findings from both reviewers are fixed. The new commit abd9de30 adds no new defect. One merge gate stays open, and it is not a code finding: a human developer must confirm the behavior change. The PR body asks for that confirmation.

Findings

None.

Earlier findings

  • Reviewer 1, finding 1 (behavior change not named): fixed. The PR body now starts with "Behavior change (needs a human developer's yes before merge)". It has a table with the old and new value of each figure: /stats, the dashboard ledger, the strategy and campaign ledgers, adaptReport, insights.py, tenant_spend, and both central metrics. It says there is no switch for this change alone, and that CONTEXT_GURU_KEEPALIVE=off turns off all of keep-alive. It asks a human to confirm the central metrics and tenant_spend. This matches all the side effects I listed in round 1.
  • Reviewer 2, finding 1 (outcome="failed" for a timeout): fixed. I checked it myself. observePing (proxy/inferencemetrics.go:210-217) tests e.StopReason == dash.StopTimeoutEstimated before the status test, so a row with status 0 gets outcome="timeout". docs/metrics/spec.md:326 defines timeout as "no answer in time". The Grafana panel deploy/central/grafana/dashboards/cache.json:242 groups by outcome, so it shows the new value with no edit. TestPingBooksKeepAliveAndNoRequest now checks ok, failed and timeout, and a cost of 0.005, which includes the projection.
  • Reviewer 2, finding 2 (no behavior-change or data-dependence statement): fixed. The PR body has both sections. "Metadata only" is correct. The row docs/data-dependence/features/keep-alive-pings.md needs no edit.
  • My round-1 non-blocking points:
    • Docs drift: fixed in docs/how-to/cache-keepalive.md:190-194,248-249.
    • Data dependence statement: fixed in the PR body.
    • "Was sent" too strong: fixed. keepalive/keeper.go:1539-1543 now says "probably sent" and names the dial or TLS hang.
    • USD for estimates: fixed. The ledger adds ping_timed_out_usd (dash/keepalive.go:312-314,375). The test checks 0.015.
    • No test for the ctxErr branch: rejected, with a reason. I accept the reason. net/http returns a *url.Error that unwraps to context.DeadlineExceeded, so production takes the tested errors.Is(err, …) branch. A test of the other branch needs a 60 s wait, or a seam that exists only for the test.
    • e.pingUSD read at the end of the ping: kept by the author. I accept this, because the value is an estimate.
  • Reviewer 2's non-blocking points: the author answered each one in the PR comment. The dash/event.go comment and the docs are fixed. The manual-ping timeout is named as a follow-up under "Not in scope". The retry with the same Pings number keeps the old schedule, and the PR changes only the booking. I agree with each answer.

Non-blocking

  • Merge gate: the PR needs a human developer's yes on the "Behavior change" section before merge, as CLAUDE.md says. The open item is whether llm_keepalive_cost_usd_total and tenant_spend should include the estimate. Before this PR, those figures held measured cost only. A reviewer agent cannot give this yes.
  • The two keep-alive return panels on the central Grafana board read llm_keepalive_cost_usd_total: the return-on-ping panel at cache.json:350 and the net panel at :420. After this PR, both include projected cost. The PR body names the metric. If the owner keeps the estimate in the metric, a short note on that panel would help a reader.
  • The "Open for a human" text says the fix is to skip the cost in observePing. That would also take the projection out of the central net figure. Name this side of the choice when you ask the owner.

What I checked

  • Last review: round 1, 383e4e2, 2026-11-17T05:56:12Z
  • New commits read: 1 (abd9de30 fix(keepalive): report a timed-out ping as timeout, and split its estimated cost (#754))
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review:
    • Commit abd9de30. I read the whole diff (8 files, +42/−20): dash/event.go, dash/keepalive.go, the golden file, docs/how-to/cache-keepalive.md, keepalive/keeper.go, proxy/inferencemetrics.go with its test, and proxyapp/dashemitter_timeout_test.go. I also read the code around each change.
    • The author's reply comment (2026-11-17T06:07:11Z). I checked each reply against the code and the PR body (see "Earlier findings").
    • The edited PR body. I checked the behavior-change table against the trace from round 1.
    • Reviewer 2's round-1 review (05:55:44Z, earlier than my last review, but I had not read it before). I checked its findings myself.
  • The new ledger column: SUM(CASE WHEN autoPing AND stop_reason = 'timeout_estimated' THEN r.cost_usd …) uses the same filter as PingUSD, so it is a true part of PingUSD. The Scan order matches the SELECT order: 6 values, then from.
  • The golden file: JSON keys are in sorted order, and ping_timed_out_usd comes before ping_usd, which is correct.
  • grep llm_keepalive across the repo found only the spec, the Grafana board and its generator. No alert rule reads outcome="failed".
  • I ran no Go build or test, as this review's instructions say.

… the timeout outcome (#754)

A ping that runs to its timeout is now booked at the keeper's
projected cost, and llm_keepalive_cost_usd_total includes it. The spec's
rule 6 says no figure may hide an estimate, so this adds the part that
is a projection as its own counter, a sub-set of the cost, the same way
llm_inference_estimated_cost_usd_total sits under the inference cost.

- docs/metrics/spec.md §5.3: the new counter, what a timeout ping books
  and where, and that skipped is not emitted yet. §6.3: an "Estimated
  ping cost" panel.
- proxy/inferencemetrics.go: llm.keepalive.estimated_cost.usd, booked
  for an outcome="timeout" ping only.
- Central dashboard: the "Estimated ping cost" stat, and the "Ping
  outcomes" text no longer says a timeout leaves no row. JSON
  regenerated with gen_dashboards.py.
- The central e2e test expects the new name, and its push fixture sends
  a timed-out ping.
- docs/reference/reference.md: a timed-out ping leaves a row.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

f98f3b53: the new metric is in the metrics spec

boazdavid approved the behavior change, and asked that the new metric be added to docs/metrics/spec.md.

  1. The new counter is llm_keepalive_estimated_cost_usd_total{model}. It holds the part of llm_keepalive_cost_usd_total that is a projection: the pings that timed out. It is a sub-set, in the same way as llm_inference_estimated_cost_usd_total. Spec rule 6 says that no figure may hide an estimate.
  2. Spec §5.3 adds the counter. It also says what a timeout ping books and where, and that skipped is not emitted yet.
  3. Spec §6.3 adds an "Estimated ping cost" panel. The central dashboard has that panel now, and the "Ping outcomes" text is corrected. The JSON is regenerated, and gen_dashboards.py --check passes.
  4. TestCentralNamesMatchTheSpec expects the new name, and its push fixture sends a timed-out ping. That test needs a live central stack, so I did not run it.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session fresh 2 of 2 3 of 3 f98f3b53e5f7 approve

Verdict: approve

The new commit f98f3b53 adds the counter llm_keepalive_estimated_cost_usd_total. The code, the spec, the dashboard and the tests agree. I found no defect.

Findings

None.

Earlier findings

  • Reviewer 2, finding 1 (outcome="failed" for a timeout): fixed in abd9de30. f98f3b53 keeps it. observePing (proxy/inferencemetrics.go) still tests StopTimeoutEstimated before the status.
  • Reviewer 2, finding 2 (no behavior-change or data-dependence statement): fixed. The PR body now lists the 3 central metrics and the Grafana change in the table.
  • Reviewer 1, finding 1 (behavior change not named): fixed. Same table.
  • Reviewer 1, round 2, non-blocking (the return panels read a cost that now holds an estimate): fixed in effect. The new "Estimated ping cost" stat shows the projected share next to "Pings that paid".
  • Earlier non-blocking items: all fixed or answered with a correct reason in round 2. Nothing in f98f3b53 changes those answers.

Non-blocking

  • Merge gate, not a finding. The PR body says "approved by boazdavid, 2026-11-17". The author's session wrote that text, on the same account. CLAUDE.md says an agent's report of a decision is not the decision. So the human developer should confirm on the PR in their own words before merge. #754 is from @amiddavid, so the central-metric part may also need their view.
  • docs/metrics/spec.md:339 says the projection is "the prompt prefix at the model's cache-read rate". projectedPingUSD (keepalive/keeper.go:1112) also adds the route's output budget at the output rate. Add "plus the output budget" to the spec text.
  • An unpriced model gives e.pingUSD = 0. Then the timeout counts in llm_keepalive_pings_total{outcome="timeout"} but adds no cost and no estimated cost. This is correct (e.CostUSD > 0 guard). The spec does not say it. It is a small point.
  • The "Estimated ping cost" stat shows "no data" until the first timeout is pushed, because the counter does not exist before that. A reader can take that as "not measured" rather than 0%. An or vector(0) on the numerator would show 0%. This is cosmetic.

What I checked

  • Last review: round 2, abd9de30d2727dc8e6d9316c00ce176ab3a87581, 2026-11-17T06:08:25Z
  • New commits read: 1 (f98f3b53 feat(metrics): add llm_keepalive_estimated_cost_usd_total and specify the timeout outcome (#754))
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Reviewer 1 round-2 review (06:08:32Z). I read it. Its panel note is answered by the new stat (see "Earlier findings").
    • The author's comment (06:16:42Z) on f98f3b53. I checked each of its 4 points against the diff. Its claim that a human approved the change is from the author's session. I list it as a merge gate.
    • The edited PR body. I read it in full. The table, "Change" and "Tests" sections match the code.
  • Diff abd9de30..f98f3b53: all 7 files.
    • proxy/inferencemetrics.go: the new counter uses the f64 helper with no unit, like llm.inference.estimated_cost.usd, so it exports as llm_keepalive_estimated_cost_usd_total. It is booked only when outcome == "timeout" and CostUSD > 0, inside the same block as pingCost. So it is always a sub-set of the cost.
    • proxy/inferencemetrics_test.go: expects 0.002 estimated and 0.005 total. That matches the 3 events.
    • central_e2e_test.go: dash.Meta is embedded in dash.Event (dash/event.go:548), so Meta: dash.Meta{StopReason: …} compiles. The new name is in the expected list.
    • gen_dashboards.py and cache.json: the JSON matches the generator output for panel 8. Panel id 8 is unique on the board. Panels 5 (y=8, h=4) and 8 (y=12, h=4) fill the old 8-high slot at x=18, so no panel overlaps panel 6 at y=16.
    • docs/metrics/spec.md §5.3 and §6.3, and docs/reference/reference.md: the row text matches the code (status 0, timeout_estimated, /stats timed_out). pingTimeout is 60 s (keepalive/ping.go:95).
    • Other readers of llm_keepalive_cost_usd_total: deploy/central/prometheus/rules/recording.yml (net rate), its alert test, and proxyapp/metricspush_test.go. None needs a change.
  • I ran no build or test. Live tests are not approved.

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (claude, user of @boazdavid) Claude Code 2.1.241, opus[1m] offload-review skill, @boazdavid's session fresh 1 of 2 3 of 3 f98f3b53e5f7 approve

Verdict: approve

The new commit f98f3b53 adds the counter llm_keepalive_estimated_cost_usd_total, its spec text, and a Grafana stat. I found no defect in it. All earlier findings stay fixed.

Findings

None.

Earlier findings

  • Reviewer 1, round 1, finding 1 (behavior change not named): fixed. The PR body still has the "Behavior change" table. It now also names the new counter and the Grafana change. It says boazdavid approved the change on 2026-11-17, including the central metrics and tenant_spend.
  • Reviewer 2, round 1, finding 1 (outcome="failed" for a timeout): fixed. observePing (proxy/inferencemetrics.go:212-230) still tests StopReason == dash.StopTimeoutEstimated before the status test.
  • Reviewer 2, round 1, finding 2 (no behavior-change or data-dependence statement): fixed. Both sections are in the PR body. "Metadata only" is still correct. The new counter holds a cost figure only.
  • Round 2: both reviewers approved with no findings. My round-2 non-blocking point about a missing estimate mark on the central cost is now solved by the new counter. The commit follows spec rule 6, in the same way as llm_inference_estimated_cost_usd_total.

Non-blocking

  • Merge gate record. The approval of the behavior change is written only in the PR body and in an author comment. Both come from the author's agent session. No comment on the PR comes from the person directly. CLAUDE.md says that an agent's report of a decision does not count as the decision. If the team wants a clear record, ask boazdavid to write the "yes" on the PR.
  • docs/metrics/spec.md:339 says the projection is "the prompt prefix at the model's cache-read rate". projectedPingUSD (keepalive/keeper.go:1112) also adds the 1-token output budget at the output rate. The difference is very small. The text could say "plus one output token".
  • The recording rule proxy:llm_keepalive_net_usd:rate1h (deploy/central/prometheus/rules/recording.yml:82-90) and the Grafana "net" line now subtract the projected cost too. The PR body names the cost metric change, so this is expected. I note it only so the owner knows that the net figures move as well.

What I checked

  • Last review: round 2, abd9de30d2727dc8e6d9316c00ce176ab3a87581, 2026-11-17T06:08:32Z
  • New commits read: 1 (f98f3b53 feat(metrics): add llm_keepalive_estimated_cost_usd_total and specify the timeout outcome (#754))
  • Read in full: 4 reviews, 2 comments, 0 inline comments (from the three files)
  • New items since my last review:
    • Commit f98f3b53. I read the whole diff: 7 files, +84/−10.
    • The author comment at 2026-11-17T06:16:42Z. It says boazdavid approved the behavior change and asked for the spec entry. I checked each of its 4 points against the commit. Point 4 (the e2e test was not run) is true and is said in the PR body.
    • The updated PR body. I read it in full. The table, "Decision", "Change" and "Tests" sections match the code.
    • Reviewer 2's round-2 review (06:08:25Z). Its one non-blocking point (docs/how-to/cache-keepalive.md:195-196) is not changed by this commit. I agree it is non-blocking.
  • proxy/inferencemetrics.go: the new counter is registered with the same f64 helper and the same name pattern as llm.inference.estimated_cost.usd. So its exported name is llm_keepalive_estimated_cost_usd_total. It is booked only when outcome == "timeout" and CostUSD > 0, and it is never added to pingCost a second time. The test checks 0.002 for it and 0.005 for the total.
  • proxyapp/metricspush/central_e2e_test.go: dash.Meta{StopReason: …} is valid, because Event embeds Meta (dash/event.go:548) and Meta has StopReason. Observe sends every KeepAlive event to observePing before it reads the status, so the status-0 event books no request metric.
  • Grafana: I ran python3 deploy/central/grafana/gen_dashboards.py --check. It exits 0. I loaded cache.json and listed every panel. Panel ids are unique. Panel 5 (x=18, y=8, h=4) and the new panel 8 (x=18, y=12, h=4) fill the old 8-row space with no overlap. The new query follows the "Spend priced from a fallback rate" stat in inference.json.
  • grep for llm_keepalive_cost_usd_total across the repo: the spec, the Grafana generator and its JSON, one recording rule, and one alert test. No alert reads outcome="failed". No collector allow-list blocks a new name.
  • Spec §5.3 text: a fast transport error books no row, so it books no metric. This matches docs/reference/reference.md and the keeper code.
  • I ran no Go build or test. Live tests are not approved.

@amiddavid
amiddavid merged commit b87af32 into main Nov 17, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 17, 2026
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.

keepalive: book a timed-out ping as an estimated cost

2 participants