Skip to content

fix(dash): four defects that cause a wrong action, not a wrong number - #168

Merged
OsherElhadad merged 15 commits into
mainfrom
fix/dash-acts-on-wrong-data-0901
Sep 1, 2026
Merged

OsherElhadad merged 15 commits into
mainfrom
fix/dash-acts-on-wrong-data-0901

Conversation

@OsherElhadad

@OsherElhadad OsherElhadad commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator

Four defects that make the dashboard act, not just report, on wrong data. Each fix has a test that fails without it.

1. The Inventory tab removed 15 skills while reporting 1

The per-skill "Off" switch, and the operator YAML filter behind it (components.toolfilter.remove: ["skill__<name>"]), removed 15 skills from the live prompt while reporting 1. The product recommended a change and then made a different, larger one.

internal/skills/skills.go required a ": " delimiter before treating a line as a skill name, so a skill listed with an empty description was not recognised as an entry at all — a bare - security-review, or - ui-ux-pro-max:brand where the colon is the plugin separator and the search for a second ": " fails. Unrecognised is not skipped: Parse runs an entry's span to the next line that parses as a name (deliberately, so a - bullet inside a description cannot truncate an entry), so an unread line is absorbed into the entry above it. One real entry swallowed 14 names. Aggregate token weight stayed correct; per-row identity did not, and per-row identity is what a removal acts on.

The switch renders disabled in single-tenant local mode and is armed in hosted mode — the deployment this dashboard exists for. The copyable "How to remove it" snippet was never affected: it writes the user's own skillOverrides and does not touch this parser.

The delimiter search collapses to one Index for ": ", which handles both the plugin form and the two-colon form the old branch existed for. Dropping the delimiter requirement makes ValidName the only lexical defence, and review measured that it is not enough: 17 of 20 adversarial bullets are accepted, 16 of them newly — - deprecated, - WARNING, - v1.2.3, - N/A, and a bare URL, which gets in because ValidName admits : and / for plugin:skill and apps/web:deploy.

No charset closes it. 47 of 245 real skill names in production have no separator at all — report, loop, gate, run, tools, simplify. So - report (a skill) and - deprecated (prose) are the same string, and any rule rejecting one rejects the other; tightening as far as it goes recovers 6 of 16 and still admits - deprecated, at a cost of 19% of real names.

Position separates them, and Parse has the neighbours EntryName does not. A name-only entry has an empty description by definition, so its successor is another entry, blank, or the region end — never its own indented continuation; a one-word bullet inside somebody else's description usually is followed by one. Six lines in Parse, no API change. The realistic case:

- alpha: does alpha things. See the docs:
- https://example.com/alpha/guide
  and then keep reading.

Before, that URL became an entry, truncated alpha's span, and removing alpha left the URL and its continuation orphaned in the prompt as prose with no heading — the outcome this package's doc comment names as its reason to exist, with the filter reporting a clean cut. Tested both ways: the prose case, and all four legal successors to a real name-only entry.

Residual, marked at the site with its ceiling: a one-word prose bullet with nothing after it. Unclosable by spelling, and measured at zero incidence — 0 of 95 installed SKILL.md files carry a space-free description bullet.

Before the fix, at the layer that acts on it:

removing "dataviz" left 1 entry lines, want 5     ← removed 5, reported n=1
removing "security-review" removed 0 entries, want 1
removing "ui-ux-pro-max:brand" removed 0 entries, want 1

The 15-of-39 figure is measured on live-captured bodies (two independent agents) and is unmeasurable on the stored corpus — the listing text is never stored, because that message is never rewritten (0 of 400,000 request_content.before_gz rows contain the header). What production can confirm: 283,753 of 856,486 skill declaration rows carry plugin:skill names, so plugin skills with descriptions always parsed. Only the name-only shape was lost. Real listings average 30 entries, max 78.

2. The skills listing and its own entries were both booked as waste

dash/toolapi.go added the skill_listing marker's tokens — the whole prose region — to declared weight, then added each parsed skill entry's tokens, a slice of that same region, on top.

This is broader than the finding as filed. The brief named one pair (the scope-wide UnusedReads/UnusedUSD adds with the KindSkill continue below them) and said explicitly to fix one, not both. But declTok/unusedTok in the declaration loop double-count the same way and feed totals.declared_tokens / totals.unused_tokens, which the same brief listed as affected. Fixing only the named pair would have left two figures wrong.

Corrected: totals.declared_tokens, unused_tokens, unused_reads, unused_usd, and the "Avoidable — projected" tile. Unaffected: declared_set_tokens (always summed the listing alone, and its own comment already documented why), aside_tokens, every per-row figure, servers[]. Skill rows keep their weight and waste in the skills table — this takes them out of the totals, not off the page.

Real corroboration, 133,064-row production corpus: skill_listing totals 71,098,662 tokens over 27,773 rows against skill's 69,671,352 over 856,486 — the same bytes twice, 2.0% apart, the difference being the header prose. On the repo fixture: declared and unused 6700 → 6400, unused reads 67,000 → 64,000, unused USD 0.0067 → 0.0064. Skills-only corpus: exactly 2.00×.

Every assertion is on absolute tokens, reads and dollars, never unused_pct — numerator and denominator inflate together, so a percentage assertion passes with the bug in place.

dash/ui/tools.js:1223-1229 already applied this correction client-side for its composition bar, which is why one viewport rendered 8,911 in the bar and 10,712 in the tile. That workaround is now redundant; impl-inventory removes it in its own PR.

3. Keep-alive credited savings it could not have earned

Event.keepaliveSavedUSD gates on four conditions, none of which is an upper bound on the idle gap. It requires the gap exceeded the provider's lifetime — the floor — then credits the row on the strength of keepalive_pings alone.

Corrected on read, in kaSaved(alias), at ten sites. Not in the arithmetic: the Event carries four keep-alive columns and nothing about the policy that sent the pings, and requests has the same four and no (X, K) — which is why the check is absent rather than wrong. A read-time test also repairs the history already on disk, with no migration, on a column documented as never backfilled.

Chosen over a join to the strategy's (X, K) and CoverageSeconds because it measures coverage instead of predicting it: a ping is a stored row with a ts and a session, so "was this prefix still inside a ping's five-minute window" is a fact rather than an assumption that every ping fired on schedule — and 8 credited rows carry no strategy id for a join to use. status = 200 is part of the test: two real ping rows are 502/503, and a ping the provider never answered refreshed nothing.

Two numbers, an order of magnitude apart, and both are right — the leak is not the same one.

corpus credited removed share
production, 133,064 rows, unpruned $167.2787 / 105 rows $11.8107 / 7 rows 7.06%
keep-alive corpus, pre-prune $76.46 / 179 rows $59.15 77.4%

The keep-alive corpus has idle gaps to 2,750 s, so its credits fail for the reason above: a gap longer than any ping could bridge. Production has no gap over 821.8 s against 860 s of coverage, so the missing upper bound is real code with no trigger there — what leaks instead is a keepalive_pings set on rows whose span held no ping at all, all 7 with zero pings in span, two with no ping within 16.7 hours. One test catches both. Production ping cost is untouched at $121.58, so the net verdict falls from +$45.70 to +$33.89 and stays positive.

Why those 7 rows exist, and the real justification for a read-time fix. KeepAlivePings does not hold what its own field contract promises. proxy/keepalive.go:829 increments it under the sweep's lock, before dispatch, and three paths then return without a request reaching the provider and without writing a ping row: the tenant limiter refusing spare headroom (on a gateway that returned 180 HTTP 429s in the measured window), an unusable body, and a transport error on send. All three leave the count already raised. So the column records dispatch intent, while only a stored row records an event — and the right fix is not "the gate was in the wrong layer" but the ping count cannot be trusted at all, so kaSaved re-derives the fact from stored ping rows rather than believing it.

Read from the code, not inferred. Two other explanations were proposed during review and both are wrong: it is not a process restart (keeper.arrive reads e.pings from a live map entry and returns 0 when the entry is gone, so a restart under-counts) and not an in-memory counter outliving its span (arrive deletes the entry on read). Tombstoned at the field where the promise is made; the counter itself is in proxy/, its three failure paths are not distinguishable from stored rows, and the figure it feeds is now protected.

Why this survived review: three separate fixtures encoded the impossible state. A campaign fixture and a ping-isolation invariant both asserted a credit with no ping row anywhere on its session, and a third required the credit to be identical with and without ping rows. That is not a state the write path can legitimately produce — the keeper only sets keepalive_pings after sending pings, and a ping is itself a stored row. Three independent tests asserting the impossible state is itself a finding about how the credit was reviewed. Each fixture was given the pings it always implied, and the ping-isolation invariant restated as the full decomposition (total_saved moves by credit minus ping spend) rather than the ping spend alone. It still fails without the fix.

Two things a reviewer must not undo:

  • kaSaved panics on an empty alias. Un-aliased, bare ts resolves to the subquery's row — kp.ts <= kp.ts — silently zeroing every credit with no error. A silent zero in a money path is the worst failure available, and TestStrategyLedgerGroupsPingsByTenantAndAttributesTheirCredit caught it during development.
  • The > 0 guard is FIRST inside the CASE on purpose. Guarded, a full-table SUM on the 2.1 GB corpus is 314 ms against a 141 ms baseline. With the EXISTS first it is 61.9 seconds for the identical answer — 197×, the same shape as the CompactionResets regression this repo already documents. The timings are in a comment at the CASE; impl-query has been told directly.

Overview and the ledger are now pinned to each other on both dollars and the misses-avoided count, so correcting one query and not the other fails rather than diverging quietly.

4. The proxy announced it was listening before it had bound

cmd/context-guru-proxy/main.go logged context-guru-proxy listening and called ListenAndServe forty lines later, so a bind failure announced a successful start and then exited. Every operator, CI job, container healthcheck and systemd readiness probe watching that line gets a green on the one failure it exists to catch.

Observed on this sweep, and worse than a dead process: the sibling that owned the port answered /healthz with 200 and served its corpus — 51 sessions, 64 tools the caller had never created — while the caller's own replay took 30 consecutive 401s.

net.Listen explicitly, log only on success, then srv.Serve(ln). Log fields and their order pass through unchanged; nothing in the repo greps the string; log.Fatalf matches the eight other fatal startup paths. Bind and announcement are one small function so a test can assert on what was not logged — in main() the ordering is only reachable by spawning subprocesses.

Doc comments, and one latent defect left standing

Four measurably false or misleading comments turned up, plus one incomplete one worth telling apart from them. In a codebase this thoroughly documented a reader trusts a comment like a test, so a false one costs more here than it would elsewhere.

  • kvcache/simulate.go insisted at length that no test pins PingsPerSpan against dash.PingsPerSpan. TestPingScheduleMatchesTheKeepAliveTab has pinned them all along, over a 12×4×5 grid of (gap, idle, K) straddling exactly the 279/280/281 and 559/560 boundaries where a float64-seconds and a time.Duration implementation could diverge. The irony is the instructive part: that comment was itself written to correct an earlier one for promising a guard that did not exist — "a comment that promises a guard is worse than no comment at all, because it tells the next reader to stop worrying" — and then became a comment denying a guard that does, doing the identical harm in the opposite direction. Instead of telling the reader to stop worrying, it sends them to duplicate a test already there. Six lines of prose deleted; the two functions stay separate (kvcache cannot import dash, the signatures differ deliberately, and neither is on the credit path).
  • providerCacheTTLMs read as though 5 minutes is the only ephemeral tier, which made SinceLastMs <= providerCacheTTLMs look complete. Tombstoned, not fixed — a named latent defect needing a scoped task with a corpus. A row that wrote at the one-hour tier keeps its entry an hour, so a nine-minute gap outlived nothing and the gate credits it anyway. Inert today: 0 of 105 credited rows have cache_write_1h > 0, and the gateway grants 1h on aws/claude-haiku-4-5 while refusing it on aws/claude-sonnet-5. Deliberately not fixed because the predicate does not exist yet: the 1h tier is recorded on the row that wrote the entry, not the row being credited, and the grant can change mid-session, so "is this a 1h entry" is a session walk rather than a column. Any predicate written before that walk exists encodes a guess about which row's tier counts, and a test on invented rows would certify the guess instead of checking it — strictly worse than a wrong but inert gate.
  • keepaliveSavedUSD's own docstring — "Four conditions, and each rules out a specific way of claiming money that is not ours" — is incomplete rather than false, and is left standing. Each condition does rule out what it claims; the set simply is not exhaustive, because the lifetime test is a floor with no ceiling. That is a different defect from an untrue assertion, and rewriting the write path's prose to describe a gate it does not have would have produced a genuinely false comment. Flagged from kaSaved instead, where the gate now lives. (Its first condition — that a ping happened during this span — is accurate against KeepAlivePings' contract; the defect is that the column does not honour that contract, which is tombstoned at the field.)
  • cachehistory.go:19-22 (min and max are the same number, false on 7 of 9 real models) is fixed in a sibling PR.

Landing order — dash/overview.go is co-edited

#167 also edits dash/overview.go, in a different region (the attempted-ratio aggregate), and it moved the two lines this PR patches from :539-540 to :555-556. This change was applied by content, not line number, so either merge order rebases cleanly.

The warning worth more than either diff: that SELECT list is positionally coupled to its Scan(...). Reshaping one without the other shifts every column silently — no compile error, and no test that names the cause.

Neither branch is rebased onto the other; whichever lands second rebases then.

A test this branch made fail, and the omission that let it through

TestCtlGetCampaignAggregatesPredictedAndRealPerTenant went red on CI. Two causes, one assertion message, separated by bisect:

  • Mine. The first cut of kaSaved required the covering ping row to have status = 200. The fixture's ping never sets Status, so a ping whose refresh was plainly visible (CacheRead: 40_000) was refused. Deterministic, 10 of 10 in isolation, cleared by the cache_read > 0 swap above.
  • Pre-existing. proxy/manager_test.go:96 waited for len(p.Requests) > 0 on the (tenant, session) it had just written — already true once a second row goes to the same session, so rows 2 and 3 returned with their writes still queued. Load-dependent: reproduced on dc29f22 in 1 of 3 full ./proxy/ runs with the identical message, invisible under -run narrowing. Now waits on Page.Total increasing.

Why it reached CI at all: ./proxy/ was not in this PR's verification list. A green suite is only green over the packages named, and that denominator went unstated — on a branch whose own thesis is that every number needs its denominator. The list below is now the whole repo.

A second gate was missing for the same reason. CI's next failure was Lint, not a test: one missing trailing newline in dash/query.go, from removing a temporary diagnostic. make lint runs test -z "$(gofmt -l .)", so one byte failed the build — and go build, go vet and go test all check formatting not at all. make lint is in the block below now.

Verification

CGO_ENABLED=1 go build ./...   OK
make lint                      OK   (go vet + gofmt -l; this is what CI runs)
go vet ./...                   OK
go test ./...                  all 27 packages ok, including ./config/ (doc-drift guard)
./proxy/  5 consecutive full runs   ok  (43.8s 44.7s 46.8s 45.6s 45.3s)
./dash/                             ok  (80.7s)

Rebased onto b193ff8 (#167 merged). The kaSaved calls in dash/overview.go moved to :555-556 with it; the Overview-vs-ledger pin still fails when either side alone is reverted, so no hunk was dropped. No assertion of this branch moved as a result of #167's money-figure changes.

On the reverted-failure captures above — which were file reverts and which were hand-edits. Three were file-level (git stash push <file>): internal/skills/skills.go for the parser and toolfilter captures, and dash/toolapi.go for the totals. Four were content-level hand-edits of this branch's own new code: kaSaved neutralised to return the raw column, Parse's lookahead replaced with _ = indented, overview.go's two expressions put back to the raw column, and listenAndAnnounce's two statements swapped.

For those four a file revert deletes the function the test calls and yields a compile error rather than a failure — the same trap review found in #167 — so the reproduction differs even though the guards are equally real. git stash push dash/keepalive.go is exactly where that showed: it fails with undefined: kaSaved at four call sites, not with the assertion.

Read-only against the production corpus throughout: opened mode=ro&_pragma=query_only(1), never written, never copied. No tenant id, session id or captured content appears in any commit, comment, test or fixture.

Osher-Elhadad added 12 commits September 1, 2026 14:53
EntryName required a ": " delimiter before it would treat a line as a name, so a
skill listed with no description was not recognised as an entry at all. Two real
shapes were affected: a bare `- security-review`, and `- ui-ux-pro-max:brand`,
where the colon is the plugin separator and the search for a second ": " fails.

Unrecognised is not the same as skipped. Parse runs an entry's span to the next
line that parses as a NAME — deliberately, so a "- " bullet inside a description
cannot truncate an entry — so an unread line is ABSORBED into the entry above it.
Aggregate token weight stays correct, but per-row identity does not, and per-row
identity is what a removal acts on: the Inventory tab's per-skill "Off" switch
posts to /api/toolfilter, which routes through this parser, and would remove
every line the surviving entry had swallowed while reporting one. The operator
YAML path (components.toolfilter.remove) shares it. The switch is disabled in
single-tenant local mode and armed in hosted mode.

The delimiter search collapses to one Index for ": ", which handles both the
plugin form and the two-colon form that motivated the old branch; a line with no
": " is a name on its own if ValidName accepts it. That charset is now the only
gate on such a line, which is what keeps a description's own prose bullet from
being read as an entry — everything observed has a space in it.

Tests: the name-only and plugin:skill shapes at the parser, and at the
toolfilter layer that removing one skill removes exactly one line. Without the
fix the latter removes five and reports one.

Signed-off-by: Osher-Elhadad <[email protected]>
toolapi.go added the skill_listing marker's tokens — the whole prose region — to
a session's declared weight, and then added each parsed skill entry's tokens, a
slice of that same region, on top. The scope-wide pair repeated it: every
non-aside row's UnusedReads/UnusedUSD went into the totals with the KindSkill
continue sitting after the add, and the listing's own figures were added again
below.

Affected: totals.declared_tokens, totals.unused_tokens, totals.unused_reads,
totals.unused_usd and the "Avoidable — projected" tile derived from the last.
Not affected: declared_set_tokens, which has always summed the listing alone and
whose comment already said adding the rows to it would count the same bytes
twice; nor aside_tokens, any per-row figure, or servers[].

Corroborated on the production corpus at /tmp/cg.db: skill_listing totals
71,098,662 tokens over 27,773 rows against skill's 69,671,352 over 856,486 — the
same tokens twice, 2.0% apart, the difference being the header prose. Inflation
of the reported figure is corpus-dependent because it scales with the skills'
share of declared weight; the bound is exactly 2.00x on a skills-only corpus,
which the new test pins.

The listing survives as the unit because it is the unit that can be acted on:
the prose is one indivisible block. Skill rows keep their own weight and waste
in the skills table — this takes them out of the totals, not off the page.

On the existing fixture: declared and unused per session 6700 -> 6400, unused
reads 67,000 -> 64,000, unused USD 0.0067 -> 0.0064. That fixture asserted the
inflated figures; its expectations move with the reason recorded beside them.
Both tests assert absolute tokens and dollars, never unused_pct — numerator and
denominator inflate together, so a percentage assertion passes with the bug in
place.

dash/ui/tools.js already applies this correction locally for its composition
bar, which is why one viewport rendered two different numbers. That workaround
is now redundant and is left for a UI change to remove.

Signed-off-by: Osher-Elhadad <[email protected]>
Event.keepaliveSavedUSD gates on four conditions and not one of them is an upper
bound on the idle gap. It requires that the gap EXCEEDED the provider's lifetime
— the floor — and then credits the row on the strength of keepalive_pings alone.
That column is the whole of the write path's evidence, and it is not sufficient:
on the production corpus at /tmp/cg.db, 7 of 105 credited rows carry
keepalive_pings >= 1 while no ping row exists anywhere in the idle span they
ended. Two have no ping within 16.7 hours. Whatever refreshed those prefixes —
another session sending byte-identical content — it was not us.

Corrected on READ, in a new kaSaved(alias), for two reasons. The Event cannot
answer the question: it carries KeepAlive, KeepAlivePings, KeepAliveRefreshed
and KeepAliveStrategyID and nothing about the policy that sent the pings, and
requests has the same four columns and no (X, K) either — which is why the check
is absent rather than wrong, and putting it there would be the wrong layer. And a
read-time test repairs the history already on disk, with no migration and no
backfill, on a column documented as never backfilled.

Chosen over a join to the strategy's (X, K) and CoverageSeconds because it
MEASURES coverage instead of predicting it: a ping is a stored row with a ts and
a session, so "was this row's prefix still inside a ping's five-minute window" is
a fact rather than an assumption that every ping fired on schedule — and 8 of the
credited rows carry no strategy id for a join to use. status = 200 is part of the
test: two real ping rows are 502/503, and a ping the provider never answered
refreshed nothing.

On /tmp/cg.db, over 133,064 rows: credited $167.2787 over 105 rows becomes
$155.4680 over 98, dropping $11.8107 (7.06%). Ping cost is untouched at
$121.5829, so the net verdict falls from +$45.70 to +$33.89 and stays positive.

Applied at every read site but one: the ledger's verdict and its misses-avoided
count, the per-tenant series, the three per-session sums, the Requests row and
session rollup, campaign savings and the strategy ledger. dash/overview.go:539
is held by another change on this sweep and has the patch; until it lands,
Overview reads the uncorrected sum.

Two things the reviewer should know. kaSaved panics on an empty alias: an
un-aliased caller resolves bare `ts` to the subquery's own row, turning
`kp.ts <= ts` into `kp.ts <= kp.ts` — every credit silently zeroed, no error. A
test caught exactly that, and the two un-aliased queries were given aliases. And
the `> 0` guard is FIRST inside the CASE on purpose: guarded, a full-table SUM on
that 2.1 GB database is 314 ms against a 141 ms baseline; with the EXISTS first
it is 61.9 seconds for the identical answer. Reordering it recreates the
correlated-subquery shape that once made Overview a 25-second page.

The correction is a ceiling and errs toward not claiming money: ts is the row's
recorded instant where the provider measures from the request start, and a
retention trim that removes ping rows before the real rows they protected will
withdraw a legitimate credit rather than invent one.

One campaign fixture seeded credited rows with no ping rows at all. That is not a
state the write path can legitimately produce, and it is the shape of the bug, so
it was given the pings it always implied.

Signed-off-by: Osher-Elhadad <[email protected]>
main logged "context-guru-proxy listening" and called ListenAndServe forty lines
later, so a bind failure — a port already owned by another instance being the
ordinary one — announced a successful start and then exited. Every operator, CI
job, container healthcheck and systemd readiness probe watching for that line
gets a green on the one failure it most needs to catch.

Observed on this sweep, and the failure mode is worse than a dead process: the
sibling that owned the port answered /healthz with 200 and served ITS corpus —
51 sessions, 64 tools the caller had never created — while the caller's own
replay took 30 consecutive 401s. Nothing was corrupted; every number from that
run belonged to another deployment.

net.Listen explicitly, log only once it succeeds, then srv.Serve(ln). The log's
fields and their order are passed through unchanged — only the moment it fires
has moved — and nothing in the repo greps the string. log.Fatalf matches the
eight other fatal startup paths in the file.

The bind and the announcement are one small function so a test can assert on
what was NOT logged; without it the ordering lives in main and is only reachable
by starting subprocesses. Inverting the two lines fails
TestListeningIsNotAnnouncedWhenTheBindFails.

Signed-off-by: Osher-Elhadad <[email protected]>
…op denying a guard

Two comment corrections, no behaviour change.

kaSaved's docstring now names the corpus each figure came from: $11.81 of
$167.28 (7 of 105 rows) on /tmp/cg.db, 133,064 real rows read-only and never
pruned, alongside $59.15 of $76.46 (77.4% of 179 credited rows) that the same
exact query removes on rev-keepalive's larger pre-prune corpus. The 77.4% is the
figure that matters commercially; the 7.1% is what this repository's own snapshot
can reproduce. Neither is "the" number without its denominator.

kvcache.PingsPerSpan's comment asserted at length that no test pins it against
dash.PingsPerSpan, calling that the easiest of three duplications to guard.
TestPingScheduleMatchesTheKeepAliveTab in package dash has pinned them all along,
over a 12x4x5 grid of (gap, idle, K) straddling exactly the boundaries where a
float64-seconds and a time.Duration implementation could diverge. A comment that
denies a guard sends the next reader to write a second one.

The two functions stay separate: kvcache cannot import dash, the signatures
differ deliberately, and neither is on the credit path this branch corrects.

Signed-off-by: Osher-Elhadad <[email protected]>
The last read site. Overview's own query summed the raw column, so its tile read
$167.28 while the Keep-alive tab read $155.47 for the same window — two answers
to one question, which is the shape this branch exists to remove. Two expressions
in the OverviewFor SELECT; the scan targets and the column order are untouched.

Pinned rather than merely fixed: TestLedgerRefusesCreditOnAGapNoPingCovered now
asserts Overview and the ledger agree on both the dollars and the
misses-avoided count. Reverting either side alone fails it.

TestPingRowsStayOutOfAgentAggregates needed its invariant restated. It compares a
fixture with ping rows against one without and required keepalive_saved_usd to be
identical in both. That is no longer coherent: a credit is booked only for a gap a
ping row demonstrably covered, so the fixture without pings holds a credited row
with no ping anywhere on its session — the impossible state that was being
credited — and correctly reads $0. Deleting the evidence has to delete the
credit. The two keep-alive fields join the may-move set, and the exactness
assertion is now the full decomposition (total_saved moves by credit minus ping
spend, +$0.34) rather than the ping spend alone. It still fails without the fix.

Also moved the ordering constraint into a comment at the CASE itself, where a
refactorer stands: guarded, a full-table SUM on the 2.1 GB corpus is 314 ms; with
the EXISTS first it is 61.9 seconds for the identical answer.

Signed-off-by: Osher-Elhadad <[email protected]>
kaSaved's docstring quoted two corpora without saying that they fail for two
different reasons, so a reader meeting 7.06% beside 77.4% assumes one is wrong.

rev-keepalive's pre-prune corpus has idle gaps to 2,750s, so its credits fail on
the missing upper bound — a gap longer than any ping could bridge. Production
(/tmp/cg.db, 133,064 rows) has no gap over 821.8s against 860s of coverage, so
that defect is real code with no trigger there; what leaks is a keepalive_pings
set on rows whose span held no ping at all, 7 rows and $11.81. One reachability
test catches both, which is the argument for measuring coverage rather than
gating on the gap.

Also the irony the previous commit understated, recorded here because it is the
most instructive thing on this branch and rewriting a pushed commit to hold it is
not worth the history churn. kvcache/simulate.go's comment was written to correct
an earlier comment for PROMISING a guard that did not exist — "a comment that
promises a guard is worse than no comment at all, because it tells the next
reader to stop worrying." It then became a comment DENYING a guard that does
exist, doing the identical harm in the opposite direction: instead of telling the
reader to stop worrying it sends them to duplicate a test already there. Two
generations of the same mistake in one comment block.

This is the second measurably false doc comment found on this sweep, after
cachehistory.go:19-22's claim that min and max are the same number. The comments
here are thorough enough that a reader trusts them like a test, which is exactly
what makes a false one expensive.

Signed-off-by: Osher-Elhadad <[email protected]>
providerCacheTTLMs's comment reads as though 5 minutes is the only ephemeral
lifetime, so keepaliveSavedUSD's `SinceLastMs <= providerCacheTTLMs` looks
complete. It is not: a row that wrote at the ONE-HOUR tier
(requests.cache_write_1h) keeps its entry for an hour, so a nine-minute gap
outlived nothing and the entry survived without a ping — and the gate credits it
anyway.

Inert on this deployment: 0 of 105 credited rows on the 133,064-row production
corpus have cache_write_1h > 0, and the gateway grants 1h on aws/claude-haiku-4-5
while refusing it on aws/claude-sonnet-5.

Deliberately not fixed. The 1h tier is recorded on the row that WROTE the entry,
not the row being credited, and the grant can change mid-session, so "is this a
1h entry" is a session walk rather than a column. Any predicate written before
that walk exists encodes a guess about which row's tier counts, and a test on
invented rows would certify the guess instead of checking it — strictly worse
than a wrong but inert gate. It also cannot be measured either way here, so there
is no before/after to report.

A comment asserting something untrue is half the defect, so the sign goes up
even though the floor stays missing. Third false doc comment on this sweep, after
kvcache/simulate.go denying a guard that exists and cachehistory.go:19-22 claiming
min and max are the same number.

Signed-off-by: Osher-Elhadad <[email protected]>
The field's own contract says "how many pings preceded it during the idle span it
just ended", and keepaliveSavedUSD's first condition restates that as "a ping
actually happened on this session during the idle span". Neither is what the
column holds.

proxy/keepalive.go:829 increments the counter under the sweep's lock, before
dispatch. Three paths then return without a request reaching the provider and
without writing a ping row: the tenant limiter refusing spare headroom
(AcquireSpare, on a gateway that returned 180 HTTP 429s in the measured window),
an unusable body, and a transport error on send. All three bump skipped/failed
and leave the count already raised. That accounts for all 7 rows on the
production corpus that carry KeepAlivePings >= 1 with no ping row anywhere in
their span, including the two with none within 16.7 hours.

Read from the code rather than inferred: two other explanations were proposed and
both are wrong. It is not a restart — keeper.arrive reads e.pings from a live map
entry and returns 0 when the entry is gone, so a restart under-counts, not over.
And it is not an in-memory counter outliving the span it describes — arrive
deletes the entry on read.

This is the better justification for correcting the credit at read time: not that
the write path lacks an upper bound on the gap, but that its ping count records
an intention while only a stored row (keepalive = 1, status = 200) records an
event. kaSaved re-derives the fact instead of trusting the column.

Not fixing the counter: it is in proxy/, three call paths would need to move the
increment past their own failure returns, the incidence of each path is not
recoverable from stored rows, and the figure it feeds is already protected. Sign
at the field where the promise is made, following the placement the 1h tombstone
established.

Signed-off-by: Osher-Elhadad <[email protected]>
kaSaved required the covering ping row to have status = 200. Reading the entry IS
the refresh, so cache_read > 0 is the direct observation and a status code is only
a proxy for it — and the proxy is weaker in both directions.

It credited the 18 ping rows in the production corpus that returned 200 while
reading nothing: a ping that arrived after the entry had already expired
re-CREATED it rather than refreshing it, which is why keepalive.go publishes
PingsThatReadNothing and PingsThatWrote beside the saving. The concept was
already here and the first cut reached past it.

And it refused a ping whose refresh was visible but whose status was not
recorded. Both of the 502/503 ping rows in that corpus read nothing, so the
direct test subsumes the status test on real data while being strictly stricter:
$155.47 credited under status = 200, $152.36 here, from $167.28 raw.

The test now covers both shapes — a transport failure, and a 200 that read
nothing — and says why each is real.

Signed-off-by: Osher-Elhadad <[email protected]>
f.record waited for len(p.Requests) > 0 on the (tenant, session) it had just
written — a condition already true the moment a caller records a SECOND event on
the same session. So every row after the first returned immediately with its
write still in the recorder's queue, and a test asserting on it read whatever had
landed.

TestCtlGetCampaignAggregatesPredictedAndRealPerTenant records three rows on one
session and then asserts on the second, so it fails whenever the writer is slow —
which under a full-package run it often is. Reproduced on origin/main at dc29f22,
1 of 3 full runs, with the identical message: this is pre-existing and was found
rather than introduced. In isolation it passes 10 of 10, which is why it reads as
branch-specific: the flake needs the CPU contention of the whole package.

Waits on Page.Total increasing instead. Four consecutive full-package runs green.

Signed-off-by: Osher-Elhadad <[email protected]>
The comment said the charset "has to stay narrow: it is what stops a
description's own bullet from being read as an entry". The reasoning was right and
the conclusion was not: a column-0 one-word bullet ("- charts", "- optional",
"- Note") does parse as a name here, and would split the entry it belongs to.

There is no lexical fix, and this is the measurement rather than an opinion: 47 of
245 real skill names in production are bare words with no separator — loop,
simplify, run, report, tools, gate, evaluate, finalize. So "- report" (a real
skill) and "- Note" (prose) are the same string shape, and any test that rejects
one rejects the other. Tightening the charset would drop 19% of real names to
avoid a class of line whose incidence cannot be measured at all, because the
listing text is never stored — 0 of 400,000 captured content rows carry the
header.

Marked with the ceiling and the upgrade path, which is a non-lexical
discriminator rather than a narrower charset. Against the alternative: keeping the
delimiter required drops 15 of 39 real entries and makes the removal switch cut 15
while reporting 1.

Refused either way, and tested: anything with whitespace in it, which is every
multi-word prose bullet, and anything indented, which is every continuation
bullet in the fixtures.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad force-pushed the fix/dash-acts-on-wrong-data-0901 branch from 041153a to 3d63551 Compare September 1, 2026 14:56
Osher-Elhadad added 3 commits September 1, 2026 14:58
Relaxing the delimiter requirement took EntryName's false-accept rate on
adversarial bullets from 1/20 to 17/20. Sixteen newly accepted lines are prose:
"- deprecated", "- WARNING", "- v1.2.3", "- e.g.", "- N/A", and the one that
matters most, a bare URL — ValidName admits ':' and '/' because `plugin:skill`
and `apps/web:deploy` need them, and a URL in a skill description is an ordinary
thing to write.

No charset closes it. 47 of 245 real skill names in production are bare words
with no separator — report, loop, gate, run, tools, simplify — so "- report" (a
skill) and "- Note" (prose) are the same string shape, and any rule rejecting one
rejects the other. Tightening as far as it goes (no "://", no leading '-' or '.',
no trailing '.', not all-punctuation) recovers 6 of 16 and still admits
"- deprecated", while risking the five real name-only shapes the parser fix
exists to rescue.

Position does separate them, and Parse has the neighbours where EntryName does
not: a name-only line has an empty description BY DEFINITION, so the next line is
another entry, blank, or the region end — never its own indented continuation. A
one-word bullet inside somebody else's description usually is followed by one.
Six lines in Parse, no API change, and the realistic case now parses correctly:

    - alpha: does alpha things. See the docs:
    - https://example.com/alpha/guide
      and then keep reading.

Before, that URL became an entry, truncated alpha's span, and removing alpha left
the URL and its continuation orphaned in the prompt as prose with no heading —
the exact outcome this package's doc comment names as its reason to exist, with
the filter reporting a clean cut. Tested in both directions: the prose case, and
every legal successor to a real name-only entry.

What is left is a one-word prose bullet with nothing after it, marked at the site.
Measured at zero incidence: 0 of 95 installed SKILL.md files carry a space-free
description bullet.

Found by review, not by me — the 20 cases and the positional insight are both
theirs.

Signed-off-by: Osher-Elhadad <[email protected]>
…e reads the gate

Review flagged the asymmetry in the three sumBySession calls: the filter is
`keepalive_saved_usd > 0` while the summed value is kaSaved. Deliberate, and now
it says so.

The filter is a superset of the value's condition, so no contributing row is lost;
a session whose credit is entirely unreachable reports $0.00, which is the honest
answer, and all three callers look up by session id rather than treating presence
in the map as "credited". Narrowing the filter would move the EXISTS from the
SELECT into the WHERE, where it runs once per row in scope rather than once per
credited row — the 61.9-second version of the same query.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad merged commit cee1f70 into main Sep 1, 2026
3 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Sep 1, 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.

1 participant