Skip to content

Mechanize the aggregate-versus-parts check, and stop three surfaces asserting more than their data supports - #692

Merged
anshss merged 6 commits into
mainfrom
single-derivation
Aug 4, 2026
Merged

anshss merged 6 commits into
mainfrom
single-derivation

Conversation

@anshss

@anshss anshss commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Follow-on to the single-derivation work already merged. Same rule — one published value, one
derivation — applied to the cases the first pass left open, plus the guard that finds the next one
mechanically instead of by hand.

The aggregate-versus-parts check is now mechanical

The invariant: for any analyzer emitting more than one card from one finding, the figure a surface
publishes as the total must equal the sum of the cards another surface publishes, or the difference
must be disclosed at the point of summation.

It was previously checked by hand, one family at a time. It is now driven by a registry: the live
adapter dispatch table is parsed from source (there is no importable object — the table is built per
call from persona and config), every adapter must belong to a registered family, and a new adapter
that nobody registers fails the build. Conserving families are asserted to sum; single-card families
are asserted to emit at most one card and are given multi-row fixtures so the exemption is re-checked
every run rather than assumed.

It immediately found a violation in the family previously believed safe. The cache finding
charges every (provider, model) row the gap between its own efficacy and the ceiling, but cards
come only from flagged rows — and a row is flagged only when the provider supports caching, its
input clears a minimum, and its efficacy is below the flag threshold. Every row between the flag
threshold and the ceiling is money on the Dashboard tile with no card in the inbox to act on it.
The netting is keyed to flagged rows too, so the parts can also overshoot. The module docstring
claimed this family held "by construction"; it now says it holds "where its cards reach".

Not fixed here — closing it is a product decision (price the aggregate over flagged rows only,
disclose the remainder, or card the unflagged rows against the analyzer's own judgment). Pinned as a
strict xfail with a registry entry, so it cannot silently worsen and will fail loudly when someone
closes it.

A lone cost refresh no longer races a scan cycle

The scan cycle has three legs and only the last takes the cost lock. A manual refresh landing
between the report write and the cost leg took the lock uncontested, built its own report, minted its
own provenance record, and wrote the cost store — after which the cycle's own cost leg found the lock
held, returned empty, and dropped its work with nothing recorded. The result was a cost block
carrying an unrelated cycle id beside a report and relearn cache from the real cycle, which is the
exact split the provenance record exists to prevent.

A call carrying neither provenance nor a prebuilt report is by definition a competing standalone
pass, and now declines while a cycle is in flight. Provenance is the discriminator, so a leg of the
cycle is never blocked by its own flag. No pre-call check in the route: that would be a race
disguised as a guard.

A declined refresh no longer reports a completed one

recompute_cost_proposals returns an empty list for four different reasons — declined on the cycle,
declined on the lock, build failure, or genuinely nothing to propose — and the refresh route could
not tell them apart. It answered ready with zero proposals while the store held a full set, and its
own docstring claimed it returned the last-good result. It never re-read the store.

The return contract now distinguishes those outcomes. A decline reports its status, its reason, that
the result is not fresh, and the real size of the stored last-good set rather than a zero nobody
measured. The UI reads the new field and falls back cleanly against a server that does not send it.

The component split is priced the way the stored total was priced

/cost sums the stored per-span cost, priced once at ingest from each span's own timestamp and its
actual rate variant, with a guaranteed fallback when a model is absent from the pricing table.
/cost/components re-priced from raw tokens at the standard variant always, and silently contributed
nothing for any model the table did not know. Two totals for the same window, from two pricing paths,
diverging on any non-standard variant and on every unpriced model — with no test coverage at all.

The component path now prices the way the stored total does, and the two reconcile. Tests cover the
variant case and the unpriced-model case, which previously had none.

Verification

Full suite green against the merged tree, run independently of the branch authors. origin/main
merged in first and confirmed an ancestor.

The already-merged half of this work was also validated end to end against a real corpus rather than
fixtures: one daemon pass over 976 sessions produced report, relearn and cost artifacts sharing a
single cycle id, anchor, build and persona, while a standalone run correctly minted a different id.
Forcing a stored artifact to a foreign build flipped its published verdict from match to stale,
confirming the comparison runs rather than being assumed.

Known gaps, deliberately open

Two aggregate-versus-parts violations ship pinned rather than fixed, because closing either is a
product decision rather than a mechanical fix: the cache family described above, and downsize's
per-agent path, which drops groups it cannot price without subtracting them from the finding's own
total. Downsize's reachable cause is already closed by the guard pinning every downgrade pair to a
live price row; the structural gap is not. Both are strict xfails with registry entries.

anshss and others added 5 commits August 4, 2026 18:51
…apter

The aggregate-versus-parts invariant — the total a surface publishes for an
analyzer must equal the sum of the rows another surface publishes for it —
was enforced one assertion at a time: `cache` was pinned as holding,
`downsize` as a known gap, and every other many-from-one adapter was simply
unchecked. That is the shape the seam registry in this module exists to
retire, so the fan-out adapters now get the same treatment.

`AGGREGATE_FAMILIES` names every finding that fans out into proposals, which
adapters fan it, and whether its cards conserve the finding's own figure. A
single property test drives off it, and `cost_adapter_symbols()` reads
`_adapt_report`'s dispatch table straight out of the source, so an adapter
wired in without a registry entry fails at the coverage test rather than
shipping unchecked. Families claiming to be one-card are held to it too: each
of their fixtures carries several rows, so an adapter that starts fanning out
loses its exemption instead of keeping it by an assumption nobody re-checked.

That check found a second gap, in the family previously believed to hold by
construction. `CacheEfficacyFinding.past_overspend_usd` is priced over EVERY
(provider, model) row in the window, charging each the gap between its own
efficacy and the 80% ceiling — but the cards come from `flagged`, and a row is
flagged on a much narrower test (supported provider, enough input, efficacy
under 0.30). Every row between the flag threshold and the ceiling is therefore
real money on the Dashboard tile and no card at all in the Review inbox, with
neither surface naming the difference; the netting that keeps the per-agent
root-cause cards from double-claiming is keyed to `flagged` as well, so it
never fires for those rows either. Closing it is a product decision, so it is
pinned as a strict xfail beside the downsize one and recorded in KNOWN_GAPS.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`recompute_cost_proposals` was described as locked against a concurrent
recompute, and it is — but the lock only ever covered two COST recomputes.
A scan cycle is three legs (report store, then relearn, then cost proposals)
and only its LAST leg touches that lock, so between the cycle's report write
and its cost leg the lock sits free.

A manual "Rescan now" (POST /relearn/cost-proposals/refresh) or a `tj optimize`
landing in that gap took the lock uncontested, built its OWN report over a
corpus ingestion has moved on, resolved its own anchor and minted its own
CycleProvenance, and wrote the cost store under a cycle id nothing else
carried. The cycle's own cost leg then found the lock held, returned [], and
dropped its cost work with no error recorded anywhere. The user is left with a
report store from cycle N beside a cost store from a standalone pass at a
different anchor — exactly the torn artifact the cycle provenance record was
introduced to make impossible, and undetectable from either surface.

The guard that spans the gap is the cycle-in-flight flag, which is set before
the cycle dispatches and cleared only after its cost leg. A call carrying
neither `provenance` nor `report` is by definition a competing standalone
pass, so it now declines against that flag the same way it already declines
against a held lock: the caller gets [] and the last-good proposals stay up,
while the cycle's coherent write is the one that survives. A leg OF the cycle
carries the record, so it is never blocked by its own flag.

Both directions are pinned, and the exclusion is registered in the seam
registry beside the one-record-per-cycle seam it completes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`recompute_cost_proposals` returned a bare list, and `[]` meant four
different things: a scan cycle was in flight, `_COST_LOCK` was already
held, the build raised, or there was genuinely nothing to propose. The
refresh route could not tell them apart, so it answered
`{"status": "ready", "proposals": 0}` for a refresh that never ran —
while the proposal store still held a full, good set. Its own docstring
claimed it returned "the unchanged last-good proposals"; it never
re-read the store. That is the recurring defect in this product: a
surface asserting more than its data supports.

The call now returns a `CostRecomputeResult` carrying `status`
(ready / declined / failed), the caller's own `proposals`, and
`served_count`/`served_computed_at`/`fresh` describing what a reader of
the store would actually see right now. A decline reports the last-good
set's real size instead of a zero nobody measured, and is kept distinct
from a failure: one is routine, the other is not. The signal comes back
FROM the call, not from a pre-call `is_cycle_computing()` probe, which
would be racy in exactly the window it claims to cover.

A declined leg is deliberately not stamped into the cost block's
`excluded`: that channel names an analyzer whose money is missing from
an otherwise-fresh total, and a declined call produced no fresh total.
Recording a `cost_proposals_error` would be worse still — it would flag
the tab degraded over an expected outcome. The reasoning is in the
docstrings at both ends.

The route keeps `proposals` as an integer count, so an older client
reading only `status`/`proposals` degrades to a truthful status and the
store's real size rather than a fabricated zero.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/cost publishes SUM(spans.cost_usd) — priced once at ingest by
CostEngine.process_span, at each span's own start_time, at the variant
that actually billed it, with a guaranteed non-null fallback for a model
absent from the pricing table. /cost/components re-priced the same
window from raw tokens and agreed with none of that:

  * it called rates_at() with no variant argument, so every span
    resolved STANDARD_VARIANT. The pricing table carries a genuine
    `variant = "fast"` row for Anthropic speed-mode at double the
    standard rate, so a fast call was published at its real cost by one
    endpoint and at half that by the other;
  * it `continue`d past a None, contributing exactly $0 for any model
    missing from the table while the same traffic contributed real
    fallback dollars to the window total.

Both endpoints describe their figure as the cost of the window, so the
divergence is the recurring defect here: two published figures over
populations that do not match.

The fallback resolution is lifted out of calculate_cost into
core.cost.billing_rates, so the stored path and the component path share
ONE derivation rather than agreeing by convention, and the variant is
read back from the stored request_params column through
core.cost.SPAN_VARIANT_SQL — deliberately defined beside
rate_variant_for_span, since a second spelling of "which variant billed
this" living in an API module is how the split drifted in the first
place. The analyzers' None-on-unpriced contract is untouched: an
analyzer that cannot price a figure must not claim one, while a measured
spend total has the opposite duty, and the docstrings say so.

/cost/components now also ships the pricing_coverage block /cost already
had. That fallback money now exists on this payload, so a reader has to
be able to tell an estimated figure from a quoted one.

Tests: the endpoint had none. Five reconciliation tests cover the plain
case, a fast-variant case, an unpriced-model case, all three mixed in one
window (the case a per-bucket grouping bug would show up in), and
capture-off traffic where request_params is NULL. Three of the five fail
against the previous behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 14:26
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR mechanizes aggregate-versus-parts coverage and aligns cost-component pricing with stored span costs. It also introduces explicit recompute outcomes and guards standalone cost refreshes against overlapping scan cycles.

  • Adds registry-driven aggregate/card conservation tests and pins known product gaps.
  • Reconciles component pricing across variants and unknown-model fallback rates.
  • Distinguishes ready, declined, and failed recompute outcomes at the refresh API.
  • Prevents standalone proposal refreshes from racing an active scan cycle.

Confidence Score: 4/5

The PR should not merge until failed cost-proposal persistence is reported as failed or stale rather than as a successful fresh refresh.

The proposal build can succeed while persistence raises, after which the exception is swallowed and the API receives a ready, fresh result with the newly generated count even though the store still serves its previous contents.

Files Needing Attention: tokenjam/core/optimize/cost_proposals.py, tokenjam/api/routes/relearn.py

Important Files Changed

Filename Overview
tokenjam/core/optimize/cost_proposals.py Adds structured recompute outcomes and cycle-overlap protection, but the previously reported persistence-failure success response remains outstanding.
tokenjam/api/routes/relearn.py Publishes the structured recompute status, freshness, stored count, reason, and timestamp.
tokenjam/api/routes/cost.py Reprices component buckets using span variants and the same unknown-model fallback convention as stored costs.
tokenjam/core/optimize/single_derivation.py Adds the registry and source-based adapter coverage mechanism for aggregate-versus-parts checks.
tests/unit/test_single_derivation.py Adds comprehensive family fixtures, conservation assertions, single-card checks, and strict pins for acknowledged gaps.
tests/integration/test_cost_components_reconcile.py Covers reconciliation for standard, fast-variant, unknown-model, mixed, and capture-disabled traffic.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Refresh as Cost Refresh
  participant Cycle as Scan Cycle
  participant Store as Proposal Store
  Client->>Refresh: request recompute
  Refresh->>Cycle: check cycle in flight
  alt standalone refresh conflicts
    Refresh->>Store: read last-good metadata
    Refresh-->>Client: "declined, fresh=false"
  else refresh proceeds
    Refresh->>Refresh: build proposals
    Refresh->>Store: persist proposals
    Refresh-->>Client: recompute outcome
  end
Loading

Reviews (2): Last reviewed commit: "Merge branch 'main' into single-derivati..." | Re-trigger Greptile

@anshss
anshss merged commit 4f05165 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the single-derivation branch September 18, 2026 21:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant