Skip to content

feat(dash): filter, hold out and honestly attribute strategy campaigns - #150

Merged
OsherElhadad merged 3 commits into
mainfrom
feat/campaign-filters-holdout-attribution
Sep 1, 2026
Merged

OsherElhadad merged 3 commits into
mainfrom
feat/campaign-filters-holdout-attribution

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Reviews the Campaigns tab that #126 added, fixes two numbers that could not be
trusted, and adds the filtering, per-user import and train/test measurement the
page was asked for.

Measurements against a copy of the live database informed this change and confirmed both
defects below. Those production figures are deliberately not reproduced in this
description; they are available internally to reviewers who need them. Everything
asserted here is provable from the code and the tests in this PR.

1. The duplication question: campaign-derived strategies vs. manual ones

The architecture stays as #126 built it, and that was the right call. "Enforcing" a
campaign already means literally creating real tenant.Strategy rows through
registry().CreateStrategy — so the ledger, savings attribution, active/paused state
and audit trail are the Strategies tab's existing machinery, and Campaigns is the
prediction/planning layer above it. There is no second enforcement path to build, and
building one (a parallel "campaign strategy" type) would have been the mistake: two
kinds of strategy competing in one resolution chain, with two savings queries to keep in
step.

What was NOT right was the accounting, in two independent ways.

1a. Real saved-$ was double-counted across campaigns (the load-bearing fix)

dash.CampaignRealSavings' credited half was:

SELECT ... SUM(CASE WHEN keepalive_saved_usd > 0 THEN keepalive_saved_usd ELSE 0 END)
  FROM requests WHERE keepalive = 0 AND tenant_id IN (?) AND ts >= ?

Keyed on tenant_id alone. So it summed an account's whole keep-alive credit into
whichever campaign named that account. Its own comment explained why that was supposedly
unavoidable: the credited row carries no strategy id, only the ping does, so the figure is
"a CEILING… not an exact per-strategy attribution".

That premise was already false when it shipped. A credited real row does carry
keepalive_strategy_id: keeper.arrive returns the strategy that resolved the idle entry,
capture threads it onto the credited row (see dash/schema.go's keepalive_strategy_id
comment), and dash/keepalivestrategybackfill.go exists for no other purpose than
recovering it on rows written before that tagging did. StrategyLedger was corrected to
filter on it in #131/#133 — this query was not, and the two have disagreed since.

The consequence follows from the query shape alone: any account served by more than one
strategy has its full credit reported under each campaign that names it.
A campaign
owning one of several strategies claims all of their savings; two campaigns over one
account each claim 100% of its credit, so the campaigns sum to more money than exists.
This is not an edge case — accounts accumulate strategies over time, and nine
manually-created strategies are active on this deployment right now, so the first
campaign created would have absorbed their credit. Verified against production, and pinned
by TestCampaignRealSavingsAttributesCreditToOneStrategyOnly.

The credited half is now scoped by keepalive_strategy_id IN (this campaign's own).
SavedUSD is exact and additive across campaigns — the same guarantee
renderStrategiesList already promises the reader for a single strategy.

Requests and ActiveDays deliberately stay account-wide. They are the denominators
for the $-per-1k-requests and $-per-active-day rates; narrowing them to the rescued rows
would divide a strategy's saving by its own successes, giving a rate that looks identical
however much traffic it missed. Both scopes now live in one conditional SUM inside one
scan, so the difference is visible in one place rather than split across queries.

The caveat string is rewritten rather than deleted — the remaining true caveat is that
these figures don't sum to the Overview/Keep-Alive totals, because a credit whose ping
matched no strategy (plain account config, or a session override) belongs to no campaign.

Traced end to end for the double-count you asked about: Overview and Grafana read
SUM(requests.keepalive_saved_usd) straight from the column, service-wide, once
(dash/overview.go:539, dash/keepalive.go). Campaigns only ever slice that column;
they never add to it. So there is no path by which a campaign-derived and a
manually-created strategy enter the same total twice — before or after this change. The
double-count was confined to the campaign views, and is now closed there.

1b. Two campaigns could enforce the same (account, hour)

campaign_cells' primary key stops one campaign naming an (account, hour) twice, but says
nothing across campaigns. Two campaigns built from overlapping suggest runs each got their
own live strategy for the same account in the same hour. Nothing crashed — the resolution
chain picks the highest-priority match and the loser never fires — but both campaigns then
reported that hour as theirs, one of them showing a prediction for a strategy that never
ran, with no way for a manager to tell which.

markCampaignOverlaps now marks any cell whose hour an active campaign already holds
as non-activatable, with a reason naming that campaign. Design notes:

  • A per-cell skip, not a rejected request. One already-covered hour must not block a
    batch of two hundred good cells, and it reuses the machinery every other unenforceable
    cell already flows through (recorded with a reason, grouped in the create result, never
    hidden).
  • Blind to the arm. A second campaign proposing a different arm for a held hour is
    still a conflict, not a refinement — only one strategy can win the resolution chain.
    Re-issuing an hour means archiving the campaign that holds it first. Pinned by a test,
    because "the arms differ, so let it through" is the plausible-looking relaxation that
    would restore the bug.
  • Archived campaigns don't hold hours. Archiving doesn't delete their strategies, but
    it is exactly how a manager says "stop managing this as a group"; treating it as a
    permanent claim would leave no way to release an hour short of deleting strategies by
    hand.
  • A failure to read the existing owners aborts the create rather than proceeding
    unchecked.

2. Train/test: what's real, and what I did not build

A true train/test split did not exist anywhere in kvcache or dash. Every
prediction on these pages is in-sample: KVCacheSuggest picks each cell's arm by
replaying every candidate over that cell's own rows and taking the argmax, then reports
that replay's saving as the cell's predicted saving. The arm is chosen to maximise the
very number then presented as its forecast, over exactly the rows it was chosen on. It is
a measure of fit, biased upward by construction, and more so as a cell thins — and
tenant.CampaignCell then freezes it as PredictedUSD and shows it beside a real, live
measurement, inviting exactly the comparison it is least able to support.

So I did not add a time control over that number. A control implying a train/test concept
that didn't exist would be the fake precision this codebase forbids. I built the split
itself.

dash/kvcacheholdout.go — KVCacheSuggestHoldout chooses each cell's arm on a train
window and scores that same arm on a disjoint test window, served at
GET /api/kvcache/suggest/holdout. Built from two calls to the existing suggester plus a
join on (user, hour, arm), because a suggest cell already carries every candidate's saving
and not just the winner's — so both halves come from the code path whose numbers a
campaign actually freezes, rather than a second simulator that could drift from it.

All four bounds are required and overlap is refused, unlike every other filter in
this package where 0 means unbounded: an unbounded train window would swallow the test
period, and an arm scored on rows it was chosen on is the single failure this view exists
to avoid — completely invisible in the output if allowed.

Run over two adjacent 7-day windows of this deployment's own traffic, a large majority of
the in-sample predicted saving did not survive
on rows the choice was not made on, and a
material number of cells went outright negative. (Figures withheld here per the note at
the top.) That is the number to have before committing to a large campaign, and it is now
one click from the tab that creates them. It is reported as a measurement, never applied
as a correction to a prediction.

Honesty details: a cell missing a test figure carries the reason (test_note) and is
excluded from the totals, never counted as $0.00 — "nothing was measured" and "this arm
saved nothing" are opposite findings. Cells thin on either side are excluded from the
totals (chosen from noise, or scored against noise) but still displayed. retention_pct
carries a retention_known flag, false where the ratio is undefined (no comparable cells,
or a train total of exactly zero — a ratio against nothing is undefined, not 0%). The
per-cell drawer shows every candidate arm's train-and-test pair, so a reader can see
whether the arm that won on train was anywhere near the best on test.

3. Filters, and per-user import

The preview gains a filter bar: users (native multi-select, matching the strategy
form's own account target), strategy, minimum predicted $, hour range, and
hide thin-data. Every dimension is one the payload can answer from a field it already
carries — nothing inferred.

The filters decide what gets created, not just what is displayed. campFilteredCells
is the single definition of "the cells this campaign is about": the table renders it, the
count reports it, and the create call submits it. That is the whole of "easy import of
campaigns per user" — the server already accepts an uploaded suggest payload verbatim, so
a narrowed payload is a narrowed campaign, with no per-account import route to build
and keep in step with the unfiltered one. A filter that narrowed the table but not the
create body would be the worst possible failure for a control whose only job is narrowing
a bulk action, so it is pinned by a test.

The cell/account count is rendered into the create button ("Create campaign — 2
cell(s), 1 account(s)"), because the filters are the only thing between a click and a live
strategy for every account in the payload. total_saving_usd is dropped from the narrowed
payload rather than carried over stale.

The campaign drawer gains a per-account filter (client-side over rows already fetched; the
totals above it deliberately keep covering the whole campaign) and surfaces the frozen
oracle-ceiling column that was already on the wire.

Verification

Build, vet, tests and -race on every touched package:

go build ./...                            BUILD_OK
go vet ./...                              VET_OK
gofmt -l dash proxy tenant                (clean)
go test ./dash/ ./proxy/ ./tenant/        ok dash 71.9s   ok proxy 39.3s    ok tenant 8.1s
go test -race ./dash/ ./proxy/ ./tenant/  ok dash 543.2s  ok proxy 258.6s   ok tenant 42.4s

One pre-existing test fails, and it is not from this change: TestSpendSurvivesRowEviction
(dash/spend_test.go:43, month-to-date = 1, want 10). spendEvents seeds the last 10
hours, so during the first ~10 hours of any calendar month most of its rows land in the
previous month and MonthToDateUSD correctly omits them. Confirmed by checking out
unmodified e88f5d8 into a clean worktree and running it there — identical failure. It
clears itself later the same day. Left alone as unrelated to this change; worth a one-line
fix in its own.

New tests, one per non-trivial behaviour: credit attributed to one strategy only (and the
denominators staying account-wide); the overlap gate, including its arm-blindness;
overlapping and under-specified holdout windows refused; the train-chosen arm scored on
test rows; a missing test cell reported rather than zeroed; thin cells excluded from the
totals; retention undefined against a zero train total; the route's 400-vs-500 split; the
create call submitting filtered cells; and the holdout copy naming the in-sample figure.

Two existing tests changed their expected numbers — both had encoded the double-count as
an expectation (a campaign owning no strategy still collecting an account's credit). The
properties they exist to protect are unchanged and still asserted.

Two static UI guards (duplicate top-level function, shadowed window method) now also
scan kvcache.js and campaigns.js, which shared one global scope with app.js while
sitting outside both loops — campaigns.js calls bare confirm() and alert().

Browser verification

Driven in headless Chromium through a real authenticated manager session against a
copy of the database on a separate port. The live context-guru.service was not
touched, restarted, or deployed to, and nothing was written to the live files.

Every filter exercised against a crafted 5-cell / 3-user synthetic payload, with zero
JS errors:

preview rows (all 5 cells) = 5
create label = Create campaign — 5 cell(s), 3 account(s)
after user=alice: rows = 2, create label = Create campaign — 2 cell(s), 1 account(s)
user=bob: rows = 2  →  + hide thin: rows = 1
arm=keepalive-5m: rows = 3
minSaving=2.00: rows = 2
hours 9-14: rows = 3
after reset: rows = 5

The holdout panel was then driven end to end over two disjoint windows and rendered
correctly: the table populated, the tiles showed the train figure labelled in-sample
beside the held-out one, the comparable-cell count read as a fraction of the total, cells
with no test traffic rendered "no data" rather than $0.00, and the per-cell drawer listed
every candidate arm with exactly one flagged as chosen.

That run also caught a real bug, now fixed: typing an out-of-range hour clamped the
filter's internal state to 23 while the input went on displaying 99 — a control
describing a narrowing it was not performing. Handlers now write the normalised value back
(99 → 23, -4 → 0, -9 → 0, each verified in the browser).

One environment note, not a defect: the holdout's first call on a cold process can return
no comparable cells, because the price list populates lazily and the earlier of its two
suggest calls sees it empty. It renders as "not enough data" with a stated reason — the
correct behaviour — and resolves on the next run. The existing /api/kvcache/suggest
behaves identically; this change neither introduces nor papers over it.

Not built, deliberately

  • No campaign editing or re-run. Archiving plus a fresh campaign already expresses it,
    and a mutable campaign would put the frozen predicted figures out of step with the
    strategies they describe.
  • No new per-account import endpoint. A filtered upload is that feature; a second route
    would be a parallel path to keep in step for no gain.
  • No retention/overfitting correction applied to any prediction. Measuring the gap is
    honest; adjusting a frozen number by it would invent one.
  • No campaigns.css. The filter bar is built from .field + .row-actions, already
    global in style.css, rather than borrowing .kv-controls across files or adding a
    stylesheet for one row.
  • Nothing removed. The tables that moved into their own functions render the same rows
    plus a column; archived campaigns still keep their strategies; archiving still leaves a
    campaign's strategies running.

The Campaigns tab shipped as a bulk create with no way to narrow what it
creates, and two numbers a reader could not trust. This fixes the numbers,
adds the filters, and builds the measurement that was missing.

Real saved-$ was double-counted across campaigns. CampaignRealSavings summed
a tenant's WHOLE keep-alive credit into whichever campaign named that tenant,
on the premise that a credited request carries no strategy id and so can only
be attributed to an account. That premise was already false when it shipped:
keeper.arrive returns the strategy that resolved the idle entry, capture
threads it onto the credited row, and keepalivestrategybackfill.go recovers it
on older rows. StrategyLedger was corrected to filter on it; this was not.
The cost was not theoretical — on this deployment every credited tenant is
credited under three to six DISTINCT strategies, so a campaign owning one of
them reported all six strategies' savings as its own, and two campaigns over
one tenant each reported 100% of that tenant's credit. The credited half is
now scoped by strategy id, so the figure is exact and additive, the same
guarantee the Strategies tab's own copy already promises. Requests and
ActiveDays stay tenant-wide on purpose: they are normalization denominators,
and dividing a strategy's saving by its own successes is a rate that looks the
same however much traffic it missed.

Two campaigns could also enforce the same (tenant, hour). Only one of the two
strategies can win the resolution chain, so the loser's campaign reported a
prediction for a policy that never ran. Cells whose hour an ACTIVE campaign
already holds are now recorded non-activatable with a reason naming that
campaign, reusing the same skip machinery every other unenforceable cell flows
through — a per-cell skip, so one taken hour cannot block a batch of two
hundred good ones.

Predicted saving is in-sample, and nothing said so. Each cell's arm is chosen
by replaying every candidate over that cell's own rows and keeping the best,
then that replay's saving is presented as the prediction — a measure of fit,
biased upward by construction. No train/test concept existed anywhere in
kvcache or dash, so rather than add a time control over a number that could
not support it, this adds the split itself: KVCacheSuggestHoldout chooses on a
train window and scores the SAME arm on a disjoint test window, built from two
calls to the existing suggester and a join on (user, hour, arm) so both halves
come from the code path whose numbers a campaign actually freezes. All four
bounds are required and overlap is refused; an arm scored on rows it was
chosen on is the one failure the view exists to avoid and is invisible in the
output. Measured over two adjacent 7-day windows of this deployment's own
traffic: $253.20 of in-sample saving became $90.97 out of sample, 35.9%
retained, with 20 cells going negative. Cells missing a test figure say why
and are excluded from the totals, never counted as $0.00.

The preview gains filters on user, strategy, minimum predicted $, hour range
and thin-data, and the create call submits exactly the filtered cells — which
is what makes "import this campaign for these two accounts" a filter rather
than a separate route, since the server already takes an uploaded suggest
payload verbatim. The count is on the button itself, because the filters are
the only thing between a click and a live strategy for every account in the
payload. The campaign drawer gains a per-tenant filter and its frozen oracle
ceiling column.

Nothing is removed: the tables that moved into their own functions render the
same rows plus a column, and archived campaigns still keep their strategies.

Also widens two static UI guards (duplicate top-level function, shadowed
window method) to scan kvcache.js and campaigns.js, which shared one global
scope with app.js while sitting outside both loops.

Signed-off-by: Osher-Elhadad <[email protected]>
Osher-Elhadad added 2 commits September 1, 2026 02:43
KVCacheDataset caps one analysis read at kvCacheMaxRows and keeps the window's
NEWEST rows, so a window bigger than the cap is silently reduced to its own
recent tail. The single-window page declares that: KVCacheSuggestions carries
Scanned/Total/Truncated and dash/ui/kvcache.js renders a warning banner saying
every figure covers only the rows that were read.

KVCacheSuggestHoldout copied Baseline, Weekdays, TimeZone and MinRequests off
its train run and dropped all three coverage fields, from both windows. A
holdout needs them more, not less. The two windows are read and capped
INDEPENDENTLY, so a capped train window means the arm was chosen on a slice of
the period the reader asked for, a capped test window means it was scored on
one, and retention_pct then divides two totals whose populations cover
different fractions of their own windows. Every per-cell request count reports
only the post-cap rows, so nothing in the payload revealed any of it — the one
silent data loss that leaves every other honesty flag in that file (TestKnown,
TestNote, RetentionKnown, the thin-cell exclusion) still reading as correct.

Both windows' scanned/total/truncated are now on the payload, a note states
the cap in words when either side hits it, and the holdout panel carries the
same banner the KV-cache page already shows, worded the same way.

Pinned in both directions: a capped pair reports 4-of-8 and 4-of-6 with a note,
and an uncapped one reports whole with no note, so the flag means something
when it is set.

Signed-off-by: Osher-Elhadad <[email protected]>
@OsherElhadad
OsherElhadad merged commit 79e0716 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
amiddavid added a commit that referenced this pull request Sep 1, 2026
The new job runs `go test` over five package trees, and `go test` starts up to GOMAXPROCS package
binaries in parallel. On a 2-core CI runner that added a second heavily-parallel run of the proxy
package per PR, and under that contention a timing-sensitive control-plane test from #150
(TestCtlGetCampaignAggregatesPredictedAndRealPerTenant) failed on two unrelated PRs — then passed on
a re-run of the same commit, and passes 3/3 whole-package on a 16-core box against both main and the
affected branch. Filed as #163.

Hunting that flake is not this job's business. Not provoking it is: `-p 1` costs about a minute and
removes the contention this job introduced, without dropping any coverage.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Sep 1, 2026
The new job runs `go test` over five package trees, and `go test` starts up to GOMAXPROCS package
binaries in parallel. On a 2-core CI runner that added a second heavily-parallel run of the proxy
package per PR, and under that contention a timing-sensitive control-plane test from #150
(TestCtlGetCampaignAggregatesPredictedAndRealPerTenant) failed on two unrelated PRs — then passed on
a re-run of the same commit, and passes 3/3 whole-package on a 16-core box against both main and the
affected branch. Filed as #163.

Hunting that flake is not this job's business. Not provoking it is: `-p 1` costs about a minute and
removes the contention this job introduced, without dropping any coverage.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
OsherElhadad pushed a commit that referenced this pull request Sep 1, 2026
…pand-tool gate, count_tokens, C-toolchain claim, preset facts) (#161)

* fix: defects that surfaced while building the distribution funnel

None of this is distribution work. Every item is a defect in code or docs that already shipped,
found while doing #141, and split out at review request so it can be judged on its own — and so it
can land whether or not the funnel does.

## 1. The expand tool was advertised where no marker can exist

`expand.Inject` under `auto` gated on "the request declares tools" and "the store persists".
Nothing asked whether the pipeline could produce a `<<cg:HASH>>` marker at all, so an
offloader-free pipeline declared `context_guru_expand` to the provider — and every call against it
must fail, because there is nothing in the Store to resolve. Measured on the real gateway route:

  tools SENT by client    : [Read Bash]
  tools FORWARDED upstream: [Read Bash context_guru_expand]

Affected `safe` and any cachesplit-only configuration, and — the one that matters most — **`off`,
the A/B control arm**. A control that carries an extra tool declaration is not a control, and every
measurement taken against it was comparing two arms that differed by more than the pipeline.

The cost when it fires is a wasted round trip and a step of the user's turn: on a transcript
containing marker-shaped text (this repo's own docs contain literal `<<cg:HASH>>`), a model calls
the tool and gets "[expand: original for id ... is no longer available]".

It was also a code-vs-comment contradiction, which is why nobody noticed: `Options.InjectExpand`
documented the gate as requiring "an expandable marker", while `expand/inject.go` says "No marker
condition, deliberately" three lines from the code. Both now describe what happens.

`components.Pipeline.HasOffload()` answers by TYPE ASSERTION, not a list of component names: a
name list is a second copy of "which components are lossy" and drifts the moment somebody adds
one. `components.Offload` cannot be implemented by accident — it requires returning cache keys
proving the original was stashed. Marker independence is preserved (the property that keeps the
tools array byte-stable across a session, and hence the prefix cached): a pipeline does not change
turn to turn.

**Ten existing tests changed fixture.** Every test of the expand loop hand-seeds the Store to
simulate an offload, but built its handler with `pipeline: []` — which cannot offload anything.
Harmless while injection ignored the pipeline; now they use `offloadCapablePipeline` (`[linecap]`,
which does not act on their short bodies). No assertion was weakened; each fixture now matches its
own premise.

## 2. `POST /v1/messages/count_tokens` was not served

Absent it, a client asking how big its context is gets a 404 and falls back to working it out with
**inference requests** — billed calls, caused by a proxy whose purpose is to reduce them. Cheap to
add, and it costs every routed user, not only the funnel.

Forwarded verbatim, with no pipeline. Returning the compacted count would be smaller and would be
wrong in the dangerous direction: the client budgets its own transcript from this number, and
because every component fails open, the next request could forward the full body and take a 400.
Over-reporting is recoverable; under-reporting is a failed turn. The cost of that choice is now
documented in `docs/reference/routes.md`, where the route was absent entirely — a routed session
self-compacts earlier than it needs to (115,933 reported vs 32,802 forwarded on a measured body).

The hosted branch has tests, because that branch is the only thing standing between the
multi-tenant service and an unmetered open forwarder that would send OUR credential upstream.

## 3. Our own docs said the binary needs a C toolchain

`docs/setup.md`, `docs/hosted.md` and `docs/get-started/quickstart-proxy.md` all told evaluators to
install one. It is needed for `go test -race` and for the optional `cg_skeleton` tag, not for the
binary. setup.md went further and named **bifrost's tokenizer** as a cgo dependency, which it never
was — o200k_base is embedded (`internal/tokens/tokens.go`).

Asserted rather than re-claimed: a new `purego` CI job builds with `CGO_ENABLED=0` and
`CC=/nonexistent-c-compiler`, checks the artifact is statically linked, starts it and probes
/healthz. It also runs the packages whose behaviour depends on which components compile in —
because `build-test` runs exclusively with `CGO_ENABLED=1` (the race detector needs it), so
`TestEveryPresetBuilds` had **never executed in the configuration a user would build**. That guard
exists for exactly the `preset: coding` / `unknown component "skeleton"` breakage.

## 4. Preset facts stated outside the guarded files (#143, #145)

- The binary defaults to **`house`**; five sites said `codesmart` (README x3,
  `docs/reference/config.md`, `docs/get-started/quickstart-proxy.md` — the last is step 2 of the
  first page anyone runs). Anyone running the binary bare while reading those measured a different
  configuration than the published SWE-bench numbers describe.
- README's `codesmart`/`codesafe` pipeline lists and
  `docs/get-started/connect-ibm-service.md`'s "Default pipeline" were stale — naming `toon`,
  retired after acting 0 of 5,752 production requests, and omitting components that do run.
  The IBM page's omission of `toolfilter` matters most: that page is what a prospective hosted
  tenant reads to decide what the service does to their traffic.

All regenerated from the `presets` map. The two tables inside #142's drift guard are untouched
here; these are the sites that guard cannot reach.

## Verification

Five mutations, each proven to have landed in the source before its result was allowed to count:

  expand injection ungated        -> TestExpandToolIsAdvertisedOnlyWhereMarkersCanExist FAIL
    on cachesplit-only, `safe`, and `off`
  HasOffload always false         -> same test FAIL on `mcp` and the offloader pipeline: "mints
    markers but no longer advertises the expand tool, so a model cannot recover what it offloaded"
  count_tokens route unregistered -> TestCountTokensIsServed FAIL (404)
  count_tokens rewrites the body  -> TestCountTokensIsServed FAIL
  hosted auth removed             -> TestCountTokensHostedRequiresAuth FAIL (502, want 401)

The second is the mirror-image check: it proves the gate did not trade one silent defect for
another, an offloader whose output nothing can expand.

Two things I got wrong on the way, recorded because both were caught by tests rather than by me:

- I first asserted `mcp` had no offloader. `smartcrush` implements `components.Offload`
  (`components/offload/smartcrush.go`), so that pipeline genuinely mints markers and genuinely
  needs the tool. The case now asserts the opposite, with the reason — and it is the argument for
  asking the interface rather than keeping a hand-written list.
- Copying `proxy/proxy.go` wholesale from the older distribution branch onto current main silently
  reverted #155's `effPreset`/`notePreset` work. `TestCompactRowNamesThePresetThatRan` — a test I
  had never read — failed with "the dashboard names a pipeline that did not run". The file was
  restored from main and the two edits re-applied on top; #155's change is intact.

`go build ./...`, `go vet ./...`, `gofmt -l` and the full `go test ./...` are clean.

One unrelated flake seen once and not reproduced: `TestConcurrentCallsDoNotRaceOnTheGateHistogram`
failed in a full-suite run with "no single-flight follower ran ... the race was never exercised",
then passed 8/8 in isolation and in two further full suites, and passes on clean main. Reported
separately rather than papered over.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

* ci(purego): run one package binary at a time

The new job runs `go test` over five package trees, and `go test` starts up to GOMAXPROCS package
binaries in parallel. On a 2-core CI runner that added a second heavily-parallel run of the proxy
package per PR, and under that contention a timing-sensitive control-plane test from #150
(TestCtlGetCampaignAggregatesPredictedAndRealPerTenant) failed on two unrelated PRs — then passed on
a re-run of the same commit, and passes 3/3 whole-package on a 16-core box against both main and the
affected branch. Filed as #163.

Hunting that flake is not this job's business. Not provoking it is: `-p 1` costs about a minute and
removes the contention this job introduced, without dropping any coverage.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

* fix: make this PR's own prose true, and unit-test HasOffload

Review of #161 found the same defect this PR is themed on — claims that are not true — in seven more
places, one of them in shipped code. All seven fixed, plus the `HasOffload` unit test the reviewer
raised without asking for.

Rebased onto current main first, so #142's preset-table guard and the preset pass below cannot
re-fix or re-break each other.

## Merge-blocking

**1. `proxy/proxy.go` named `mcp` as offloader-free.** It is not: `smartcrush` implements
components.Offload, which this PR's own test asserts (`wantAdd: true`) and its own mirror-image
mutation proves. I had corrected the test and left the comment wrong — the copy a future reader
actually trusts.

The fix deletes the list rather than correcting it. The comment now names the shapes affected
(`off`, `safe`, any cachesplit-only configuration) and then says why enumerating presets here is the
wrong move: a list in a comment is a second source of truth, and this one was wrong about `mcp` on
its first draft. That is the whole argument for gating on the interface.

**2. Five sites named the `cache` preset, which does not exist on this base.** It is #141's, and it
reached here in the wholesale copy of `proxy/proxy.go` this PR already admits to, then travelled
into the test files when they were split out of that branch. Reworded to name configurations that
exist here; the underlying defect they describe is unchanged and still reproduces on `off` and
`safe`.

**3. `proxy/counttokens_test.go` carried copy-paste artifacts vet and gofmt cannot see.** A
duplicated 3-line doc comment, and a 20-line orphan documenting a function that lives in
`expandgate_test.go` under a different name and citing a test that exists nowhere. Both from the
same cause: my splitter took each test's doc comment by scanning back to the previous blank line,
which swallowed the FOLLOWING test's comment as a trailing block. A third artifact the review did not
list is fixed too — `expandgate_test.go`'s doc comment still described "the preset's promise" and
cited `docs/how-to/install-plugin.md` and an install skill, both of which belong to #160.

## The rest

**4.** `docs/reference/config.md` and `docs/components.md` said `auto` injection has exactly two
conditions. It has three. Both now say so, and say what the third is for. The cache-stability
argument those passages make is unaffected — a pipeline does not change turn to turn either — so it
gained a member rather than needing a rewrite.

**5. `make build` now sets `CGO_ENABLED=0`.** The docs could claim "no C toolchain" all they liked
while step 1 of the quickstart was `make build`, which needed one because the Makefile exported
`CGO_ENABLED=1` for every target. Pointing readers at `build-static` would have fixed the sentence;
making the DEFAULT build pure Go makes the claim true of the command the docs tell people to run.
`CGO_ENABLED=1` stays for the test targets, where `-race` requires it, and the comment says exactly
that. Verified: `CC=/nonexistent make build` produces a statically linked binary.

README, CLAUDE.md and the quickstart no longer require a C toolchain. All five remaining
`codesmart`-is-the-default sites are corrected — including two in `config/config.go`, which is how
the claim spread to five documents: it sat three lines from the flag that disproves it.

**6.** `docs/setup.md` overstated its own evidence, which is the exact sin this PR is about. It
claimed CI removes the C compiler from `PATH` (with cgo off the toolchain never consults `CC`; that
variable is a tripwire, not the mechanism) and that cross-compilation to four targets is asserted,
when CI builds native linux/amd64 only. Now says what CI actually does, and states separately that
the other three targets were verified by hand and are asserted at release time. Same overstatement
fixed in the `ci.yaml` comment.

**7.** `ci.yaml` promised a linked issue and linked nothing, and named a different flake than the PR
body did. Both are real; the comment is about the campaign one, and now links #163.

## HasOffload unit tests

`./components`: nil-safe, empty pipeline (the A/B control arm), reformatters-only, and an offloader
in three positions. Revert-verified both ways — always-true fails the empty and reformatter cases,
always-false fails the offloader cases.

A registry-walking test was supposed to make it rot-proof, and **it skipped**: registrations happen
in `components/all`, so a test inside `components` can neither see them nor import the package that
does. A test that skips reads as coverage and is not, so it moved to `components/all`, where it
runs — 21 of 21 registered components, 13 implementing Offload. It fails if either count is zero,
because an all-false or all-true population would agree with a broken HasOffload.

Full `go test ./...`, `go vet ./...` and `gofmt -l` clean; doc link/anchor checker re-run over every
document touched.

Assisted-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>

---------

Signed-off-by: DAVID AMID <[email protected]>
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