Repository navigation
One derivation per published value: rollup completeness, one write budget, cycle provenance, and a seam registry - #688
Merged
Merged
Conversation
…onvention past_overspend_rollup() sums whatever proposal list it is handed. relearn's money only reached the rollup because a caller remembered to separately fetch relearn's clusters via inbox_contribution.relearn_contribution_rows() and concatenate them in. Two callers did (the CLI's `tj relearn cost-proposals` and the API's GET /relearn/cost-proposals); cmd_quickstart's first-run screen did not, despite a comment right above its rollup call asserting the two totals could never disagree because they went through "the same function" -- they disagreed by exactly relearn's contribution. Fix: inbox_contribution.gather_rollup_population() is now the one function that always gathers both feeds (cost proposals + relearn's open clusters, normalising either a cached dict or a live RelearnFinding dataclass) before reaching past_overspend_rollup(). All three call sites now go through it. A structural test walks the package and fails if past_overspend_rollup is called from anywhere outside inbox_contribution.py, so a future caller can no longer silently regress to a partial population. cmd_quickstart still deliberately excludes relearn from its own analyzer set (a measured runtime cost: 27.9s of a 35s analyzer pass on a real corpus, on a path whose own status line exists because ~14s of silence already reads as a hang) -- that reason survives, but the misleading "cannot disagree" comment does not. It is rewritten to state plainly that this screen is a declared lower bound on the Review inbox's total, never a guaranteed match, and the wiring is proven correct for when relearn's finding IS present by a test that fabricates that payload and checks the result against gather_rollup_population() called directly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The write budget was allocated TWICE. `analyzers/relearn` built a WriteBudget from RELEARN_WRITE_BUDGET_TOKENS / RELEARN_MAX_OFFERED_WRITES and spent it inside the analyzer; `cost_proposals` built a second one from COST_WRITE_BUDGET_TOKENS / COST_MAX_OFFERED_WRITES and spent it inside the adapter. Neither pass could see the other's candidates. Three consequences, all real: * The bound a user was actually subject to was the SUM of the two caps, so one window could grow the same agent file by both allowances. * Both passes sized their share against the SAME summarize-measured always-loaded footprint, each as though it were the only writer, so the growth share that caps what a file takes on per window was applied twice to one file. * Ranking was per-producer. A high-net cost write and a low-net relearn write never entered one ranked list, so the comparison that decides which deserves a permanent block never happened. Allocation is now removed from both producers and happens exactly once, in the new `core/optimize/write_allocation.py`, over the union of their candidates against one budget. Each producer keeps only the half it alone can do: relearn decides what a cluster IS and resolves the exposure a rule for it would be charged against (the per-repo session counts exist nowhere else), the cost adapter builds its cards and their placements. Neither may size or spend a budget. The allocation runs at the tail of `runner.build_report` — the choke point every surface funnels through, and the first moment both producers' candidates exist — and is memoized onto the report so the cost pass, which runs after the report has been stored and rehydrated, applies the same answer rather than deriving a second one. Preserved deliberately: MIN_NET_WRITE_USD still gates the OFFER only and still skips a candidate carrying no dollar figure; an advisory family still never enters the budget as a candidate at all, so no later pass can overwrite its upstream flag; relearn's detector stays unbounded and its past_overspend_* figures are untouched; each producer's rules stay priced against the sessions they were measured over rather than being re-based onto the other's horizon. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This product has fixed the same defect class roughly ten times by hand: a value that determines published output (a window, a rollup population, a write budget, a persona gate, a write-apply target) gets derived twice, and nothing fails when the two derivations disagree. Each fix landed with its own bespoke test, and nothing forced the NEXT shared value through the same discipline. core/optimize/single_derivation.py is one declarative registry naming every value that must have exactly one seam, by the symbol a second derivation would necessarily touch (a function call or an attribute read) and the one module allowed to touch it. tests/unit/test_single_derivation.py walks the shipped package once per registry entry — adding the next shared value is a line in the registry, never a new test file. Seeded with: rollup population (past_overspend_rollup, restricted to inbox_contribution.py), the write allocation point (build_write_budget, restricted to write_allocation.py), window length (scan_window_days, restricted to report_window.py + config.py), and rate profile (RateProfile, restricted to rate_profile.py). Three invariants that are real but not symbol-reachability shaped stay as their existing bespoke tests (persona classification's windowed-call requirement, the write-apply target's narrow scope.claude_home exception, and the scan-cycle anchor's data-flow property) — the registry names them as BESPOKE_SEAMS and a parametrized test now fails loudly if the test guarding one of them is ever deleted, rather than the coverage silently vanishing. The existing rollup single-caller test in test_cost_proposals.py now calls the shared walker instead of reimplementing it, so there's one AST-walking mechanism in the repo for this shape, not two. Also adds the aggregate-versus-parts invariant this defect class implies at one remove: when one finding fans out into several proposals, the total a surface publishes as the aggregate should equal the sum of what another surface publishes as the parts, or the gap should be disclosed at the point of summation. The `cache` family holds this by construction (pinned as a passing test); `downsize`'s per-agent path does not — a candidate on a model with no pricing data is correctly dropped from the per-agent breakdown, but the finding's own aggregate is unaffected, so the two surfaces can name arbitrarily different totals for one analyzer with no disclosure. Measured directly: an aggregate of $998.00 surfaced as roughly $0.11 across the cards the Review inbox actually renders. That gap is pinned as an xfail(strict=True), not fixed — closing it is a product decision (fall back to the window-wide card, disclose the shortfall per card, or reprice unpriced groups) beyond a mechanical guard's scope. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The unified write allocation ranked relearn's clusters and the cost lane's cards on the same net_tokens field, but relearn's figure is accumulated over its whole unbounded detector horizon while the cost lane's is scoped to the report window -- so relearn's number was structurally larger for identical real-world behaviour and tended to win shared slots regardless of merit. Add WriteCandidate.rank_gross_tokens / WriteDecision.rank_net_tokens as a ranking-only basis, separate from gross_tokens/net_tokens (which still decide whether a write is worth OFFERING at all -- net-negative verdict, value floor -- unchanged). relearn's write_candidates() now sets it from the cluster's own already-computed past_overspend_windows bucket matching the report's window label, never a new derived figure. A cluster with no matching bucket ranks at 0 rather than falling back to the unbounded gross, which would silently restore the bug. Co-Authored-By: Claude <[email protected]>
DOWNGRADE_CANDIDATES (model_downgrade.py) and pricing/models.toml are two independently hand-maintained lists. If either side of a downgrade pair has no pricing row, lookup_downgrade still returns the pair but build_agent_price_rows silently drops the whole group -- no log, no counter, no disclosure field. The DOWNGRADE_CANDIDATES comment already records this class biting once before via model_tiers.TIER_SUBSTRINGS; nothing previously guarded it in this direction. Registered as a BespokeSeam in single_derivation.py rather than a new SingleSeam: the defect is a missing row in a second table, not a second call site reaching a shared symbol, so a reachability walk can't express it. Co-Authored-By: Claude <[email protected]>
… writes Three defects that were one fact split into three ad-hoc conventions. The build was STAMPED BUT NEVER COMPARED. `tj_build()` was called independently at several sites — two write-time, two read-time — and nothing anywhere asked whether a stored stamp matched the running build. The analyzer stores are caches with no invalidation on upgrade, so after upgrading tokenjam every card on screen was produced by the PREVIOUS build and kept being served as an ordinary result until a pass completed. Analysis runs on `[optimize] scan_interval_hours` while ingestion runs on `[ingest] interval_minutes`, so the data under the cards refreshed on a minute scale while the cards were hours old. That is exactly the reading which makes an upgrade look like it did nothing. The window had TWO SPELLINGS. The report store wrote `since`/`until` and published `scan_since`/`scan_until`; the cost store wrote `cost_since`/`cost_until`. Raw dict keys, no shared type, nothing forcing them to describe the same span. The cycle had NO IDENTITY. One pass refreshes three stores sequentially on one thread, and each store's in-flight flag goes false as its leg lands, so a report-derived panel could serve cycle N figures beside inbox figures from cycle N-1 with no consumer able to tell. `core/optimize/cycle_provenance.py` is the one record: cycle id, anchor, resolved bounds, window length, persona and producing build, minted once per pass by `begin_cycle()` and threaded into all three stores. It absorbs `build_stamp.py`. The persona is SEALED from the report the pass built rather than re-derived — `build_report` is the choke point — and the cost recompute now reads it off the record instead of classifying the same window a second time. `provenance_block()` assembles the wire keys for every analyzer-fed payload, so the report envelope and the two hand-assembled relearn payloads can no longer spell a key differently. STALENESS IS DISCLOSED, NOT DISCARDED. `build_provenance()` resolves the stored build against the running one into `match`/`stale`/`unknown` — tri-state on purpose, since "we cannot tell" is not agreement — and every payload publishes the verdict. The figures are still served: dropping them would turn a populated surface into an empty one across an upgrade, and an empty state is the strongest claim a surface can make. The browser now renders the server's verdict rather than deriving its own, which is also what gives the CLI, `--json` and MCP the same answer. An artifact written before the record degrades: the legacy `tj_version` / `cost_tj_version` and window keys are read instead, `cycle_id` reports None, and nothing raises. The bounds are never invented from a bare day count. Registered as a SingleSeam so a second construction of the record fails the walk; the scan-cycle-anchor BespokeSeam now describes the record it threads. Also fixes a latent cross-file test leak: `scan_cycle`'s module-global ingestion watermark was never reset by the provenance tests that run the job body inline, so the cycle tests in another file failed only in a full run. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`cost_since`/`cost_until` and the provenance record's `since`/`until` are two spellings of one fact, and the store lets a caller supply them independently. They agree today only because the single production caller derives both from the same window. Pins the production artifact so bounds computed apart from the record fail here rather than silently restoring the two-spellings bug. Co-Authored-By: Claude <[email protected]>
Contributor
|
| Filename | Overview |
|---|---|
| tokenjam/core/optimize/write_allocation.py | Introduces the shared allocation choke point, namespaces both candidate lanes, persists decisions on the report, and safely reuses them downstream. |
| tokenjam/core/optimize/cycle_provenance.py | Defines the cycle identity and build/window provenance model, including tri-state staleness and legacy-artifact projection. |
| tokenjam/core/optimize/inbox_contribution.py | Centralizes complete rollup population gathering, exact-window relearn contributions, applied filtering, and exclusion disclosure. |
| tokenjam/core/optimize/scan_cycle.py | Mints and threads one provenance record through the sequential report, relearn, and cost-proposal writes. |
| tokenjam/core/optimize/relearn_store.py | Preserves independent relearn and cost provenance through shared-cache rewrites using prefix-based copy-forward behavior. |
| tokenjam/core/optimize/runner.py | Runs unified write allocation after all analyzers have populated the report. |
| tokenjam/api/routes/relearn.py | Uses shared provenance projection and complete rollup gathering for relearn and cost API payloads. |
| tokenjam/cli/cmd_quickstart.py | Adopts the shared rollup gatherer while clearly retaining relearn as a deliberate runtime-bounded exclusion. |
| tokenjam/ui/index.html | Updates the dashboard’s scan and provenance presentation to consume the expanded server payload. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
Scan[Scan cycle] --> Provenance[Mint cycle provenance]
Provenance --> Report[Build and store optimize report]
Report --> Candidates[Collect cost and relearn write candidates]
Candidates --> Allocate[Allocate one shared write budget]
Allocate --> ReportStore[Persist report decisions]
Report --> RelearnStore[Persist relearn artifact]
Report --> CostStore[Persist cost proposals]
Provenance --> ReportStore
Provenance --> RelearnStore
Provenance --> CostStore
CostStore --> Gather[Gather rollup population]
RelearnStore --> Gather
Gather --> API[API Review inbox]
Gather --> CLI[CLI cost proposals]
Gather --> Quickstart[Quickstart lower bound]
Reviews (1): Last reviewed commit: "test: pin the legacy cost-window keys to..." | Re-trigger Greptile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
One published value, one derivation — enforced structurally instead of checked by hand at each site.
The recurring defect in
core/optimize/is a value that determines published output being derivedin more than one place, with nothing failing when the derivations disagree. It has been fixed
repeatedly, each time by hand, each time with a bespoke test. This branch fixes the instances that
are still live and adds the guard that catches the next one.
Rollup completeness is a contract, not a caller convention
past_overspend_rollupaggregated whatever list it was handed.relearnemits noCostProposal,so its money reached the total only because a caller remembered to fetch
relearn_contribution_rowsand concatenate first. Two callers remembered;tj quickstartdid not,while the comment above that call asserted it could not disagree with the Review inbox.
inbox_contribution.gather_rollup_population()now gathers every producer itself and is the onlypermitted caller of the rollup, pinned by a structural test. A caller wanting a subset must declare
it, and the basis string records it. Quickstart still skips relearn deliberately — that analyzer's
unbounded history scan dominates the first-run pass — but it now says so as a declared lower bound
instead of claiming parity.
The permanent-write budget is allocated once
Two constant pairs and two
allocate_writespasses meant the real user-visible cap was the SUM ofboth, each lane sized its share against the whole measured footprint as though it were the only
writer, and ranking was per-lane, so a high-net write in one lane could never outrank a low-net
write in the other — the comparison never happened.
core/optimize/write_allocation.pyis now the single allocation point, at the tail ofbuild_report(the choke point every surface funnels through; the scan cycle is too late, since thereport is persisted before the cost pass runs). One budget, one ranked list, per-lane constants
deleted rather than orphaned.
This surfaced a live bug: when the cost lane had no writers, an early return skipped allocation
entirely, leaving relearn's clusters offered by a budget that never ran.
Unifying the lanes also exposed a basis mismatch — relearn's figures span its unbounded detector
horizon while every cost figure is window-bounded, so relearn won slots it had not earned. Ranking
now reads relearn's existing window-bounded bucket (the same one the inbox headline already
selects, by exact label match) via a separate rank field. The unbounded figure keeps its existing
job as the pre-net gross behind the worth decision and the value floor, which are unchanged.
One provenance record per cycle, compared on read
Build identity was stamped independently at several sites and never compared against the running
build, so after an upgrade every card was produced by the previous build and served as a result
until a pass completed. Windows were two ad-hoc conventions (
scan_since/scan_untilversuscost_since/cost_until). Nothing identified a cycle, so a report-derived panel could serve onepass's figures beside another's while the stores recomputed sequentially.
core/optimize/cycle_provenance.pymints one record per cycle — cycle id, build, anchor, span,window, persona, computed_at — carried by every artifact that cycle writes. The stored build is
compared against the running one and the verdict ships on the payload, so a surface can render
staleness instead of re-deriving it.
build_stamp.pyis absorbed and deleted. Caches writtenbefore the record degrade to their legacy keys rather than raising.
A registry instead of a test per incident
core/optimize/single_derivation.pynames the values that must have exactly one seam and drivesone test over them. Adding a shared value is a line in the registry. Invariants that cannot be
expressed as symbol reachability are registered as bespoke seams with a stated reason and a named
test, so they stay indexed rather than orphaned.
Seeded with the rollup population, the write allocation point, window length, rate profile, and a
new guard pinning every
DOWNGRADE_CANDIDATESentry — both sides of each pair — to a live pricerow. That map and the pricing table are hand-maintained and could drift silently, dropping priced
groups with no log, counter, or disclosure. It passes today; it cannot drift unnoticed now.
Known gap, deliberately left open
downsize's per-agent path drops groups it cannot price, and nothing subtracts them from thefinding's own total, so the Dashboard tile and the inbox rows can disagree without disclosure. The
reachable cause is narrow — the pricing guard above closes it — but the structural gap is real and
recorded as a strict xfail plus a registry entry, so it cannot silently worsen and will fail loudly
when someone closes it properly.
Verification
Full suite green against the merged tree, run independently of the branch author: 5018 passed
locally, 5180 via
make test, ruff and mypy clean across 271 source files.origin/mainmerged infirst and confirmed an ancestor; upstream symbol counts identical on both sides, so nothing upstream
was reverted. Upstream's new ingest-time session provenance and this branch's artifact-level cycle
provenance were checked for collision and are independent — different grain, different store, no
shared consumer.