Skip to content

feat(cli): waste injection harness — recall and quantity error per finding type (#80) - #131

Merged
axisrow merged 3 commits into
mainfrom
ao/claude-devtools-47/waste-injection
Oct 12, 2026
Merged

axisrow merged 3 commits into
mainfrom
ao/claude-devtools-47/waste-injection

Conversation

@axisrow

@axisrow axisrow commented Oct 12, 2026 •

Copy link
Copy Markdown
Owner

Waste injection harness (#80, часть #78)

Ground truth для recall без ML: мутатор вставляет в распарсенную сессию один известный паттерн с известной ценой, затем прогоняется настоящий детектор (buildLedger + computeFindings) и считаются recall (нашёл ли) и ошибка количества |tokensWasted − injected| / injected.

Closes #80

Что сделано

  • src/cli/injectWaste.ts — 9 мутаторов над ParsedMessage[]: duplicate_call, loop_streak, cycle_motif, probe_no_progress, cache_dead, wait_loop, stall_streak, oversized_output, failed_call + движок оценки (evaluateInjection, scoreOutcomes) и CLI-отчёт.
  • Правдоподобие ledger: вставленные раунды перечитывают накопленный контекст (cache_read = running ctx), каждый вставленный результат попадает в контекст следующего раунда, все базовые раунды после точки вставки подняты на ту же дельту — контекст монотонный, billed растёт не меньше вставленного waste, инварианты корпуса (Regression corpus of real sessions (local, via .env) with numeric snapshots #79) выполняются.
  • pnpm waste:recall — отчёт по сессиям CORPUS_DIR (корпус в репо не попадает, печатаются только агрегаты — то же правило, что у corpus:snapshot).
  • test/main/cli/injectWaste.test.ts — CI-гейт на мини-фикстурах Regression corpus of real sessions (local, via .env) with numeric snapshots #79 (4 фикстуры × 9 типов = 36 прогонов полного пайплайна): каждый тип должен быть найден с точной ценой, тест падает при recall < 100 %; плюс проверка инвариантов ledger после каждой вставки и unit-тесты агрегации.

Нюансы встраивания, которые вскрылись при прогоне:

  • wait_loop бронирует все тихие тики терна (не серию подряд) — паттерн вставляется отдельным новым терном в конце, чтобы не сливаться с тихими раундами базы; ramp-раунд ниже порога context_spike держит прыжок контекста ≤ 30k.
  • stall_streak окружается «стенками» (раунды с большим output, не stalled и не quiet) — базовые quasi-stall раунды (delta ≤ 300) не присоединяются к серии.
  • Атрибуция: у 7 типов маркер winject-<type> виден в summary находки; у cache_dead/wait_loop — точное совпадение суммы в терне вставки.

context_spike / thinking_heavy / long_turn не имеют call/result для вставки и не входят в набор мутаторов.

Отчёт pnpm waste:recall (acceptance #1)

Прогон на локальном фоне: 15 реальных сессий проекта claude-devtools из ~/.claude/projects (полный корпус #79 материализуется локально через CORPUS_DIR; в репо не попадает).

waste:recall — 15 corpus session(s), 9 injected pattern types
type                   recall  median|err|  recalled  attempts
duplicate_call         100.0%         0.0%         6         6
loop_streak            100.0%         0.0%         6         6
cycle_motif            100.0%         0.0%         6         6
probe_no_progress      100.0%         0.0%         6         6
cache_dead             100.0%         0.0%         6         6
wait_loop              100.0%         0.0%        13        13
stall_streak           100.0%         0.0%         6         6
oversized_output       100.0%         0.0%         6         6
failed_call            100.0%         0.0%         6         6

(74 skipped — кароткие сессии без пары раундов для точки вставки; у wait_loop попыток больше, т.к. append-стратегии достаточно одного раунда.)

Проверки

  • pnpm test — 1081/1081 зелёные (включая 39 новых)
  • pnpm typecheck — чисто
  • pnpm lint — 0 ошибок (6 предупреждений — pre-existing в других файлах)
  • инварианты Regression corpus of real sessions (local, via .env) with numeric snapshots #79 (checkInvariants) выполняются после каждой из 36 вставок на мини-фикстурах

Риски / заметки

  • wait_loop-инъекция в реальном корпусе измеряется на новом терне: recall/ошибка относятся к паттерну в изоляции; слияние с фоном терна — семантика детектора, не ошибка харнесса.
  • Детектор (analyzeSession.ts) не изменён — только чтение его публичных функций и WASTE_THRESHOLDS.

Обновление: merge main (#124) и семантика аллокации

Ветка обновлена до main (в неё успели #124, #125–#130). #124 вводит claims-аллокацию: перекрывающиеся находки делят одни токены, полностью перекрытая находка остаётся видимой с tokensWasted 0. Для харнесса это один случай: повторы probe_no_progress клеймят те же result:<toolUseId>, что и его парная duplicate_call, которая обслуживается первой — probe бронирует 0. Атрибуция переписана: booked = сумма всех находок паттерна с маркером (probe + duplicate), recall по-прежнему требует видимости probe-находки; CI-гейт остался на точной цене. Отчёт на 15 реальных сессиях после мержа — по-прежнему recall 100 %, медиана 0.0 % по всем 9 типам. CI зелёный (ubuntu, windows, validate).

🤖 Generated with Claude Code

axisrow and others added 3 commits October 12, 2026 21:59
…nding type (#80)

Ground truth for recall without ML: a mutator plants one known waste
pattern with a known cost into a parsed session (ParsedMessage[]), then
the real detector (buildLedger + computeFindings) runs and the harness
measures recall and |tokensWasted − injected| / injected per FindingType.

- 9 mutators: duplicate_call, loop_streak, cycle_motif, probe_no_progress,
  cache_dead, wait_loop, stall_streak, oversized_output, failed_call
- inserted rounds re-read the accumulated context; every injected result
  feeds the next round's context; base rounds after the gap are bumped by
  the same delta, so the ledger stays plausible and invariants hold
- `pnpm waste:recall` prints the report over CORPUS_DIR sessions (the
  corpus never enters the repo, same rule as corpus:snapshot)
- CI gate on the #79 mini fixtures: every type must be found with the
  exact injected cost on every fixture (fails below 100% recall)

context_spike / thinking_heavy / long_turn have no call/result to plant
and are left out of the injectable set.

Closes #80

Co-Authored-By: Claude Code <noreply@anthropic.com>
…/waste-injection

# Conflicts:
#	package.json
Merge of main brought #124: findings carry claims, allocation serves
overlapping claims in severity order, and a fully overlapped finding
stays visible with tokensWasted 0. probe_no_progress's repeats claim
the same result:<toolUseId> tokens as its co-firing duplicate_call,
which is served first — the probe finding books 0 and the exact-amount
attribution failed on all four mini fixtures (CI test job red).

The pattern's booked amount is now the sum over all marker-carrying
findings of the pattern (probe + duplicate). Recall still requires the
probe finding to be visible; the CI gate stays at exact cost.

Also merges origin/main (branch freshness validate job): conflict in
package.json scripts resolved by keeping both sides' entries.

Co-Authored-By: Claude Code <noreply@anthropic.com>

@axisrow axisrow left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ревью PR #131 — waste injection harness (#80)

Вердикт: changes requested — одна находка (нумерация терна вставки при неявном терне 1). Остальное проверено и сходится.

Что проверено

Диф vs main: src/cli/injectWaste.ts, test/main/cli/injectWaste.test.ts, script waste:recall в package.json. Бухгалтерию каждого мутатора сверил с детектором (buildLedger / computeFindings в analyzeSession.ts) и порогами loopPolicy:

  • точные суммы сходятся у всех 9 типов: duplicate_call 200 (reread = repeats only), loop_streak 3×100 (streak.tokens считает повторы 2..4), cycle_motif = сумма contextSize раундов 4..9 (expected копит b.ctx перед раундом — это в точности contextSize раунда), probe_no_progress (sig по последней непустой строке, books второй прогон), cache_dead (весь contextSize > 20k при cr=cw=0), wait_loop 5×ctx (ramp вставляется только при b.ctx < 20k, его cr = 25k < 50k — тихим тиком не станет; скачок 25k < 30k — context_spike не породит), stall_streak (стены out=1500 > 300 рвут серии, delta +1 за раунд ≤ 300, 4 раунда = LOOP_MIN_STREAK), oversized_output (est текста > 8k), failed_call (input + result, rejection-паттерны не срабатывают);
  • пост-бамп base-раундов после гэпа одной и той же дельтой сохраняет все последующие contextDelta неизменными — ложных context_spike не порождает; инварианты #79 после вставки держатся;
  • классификация вставленных сообщений корректна: носители результатов areMeta:true — не опернеры и не релеи, wait_loop-опернер — настоящий юзер-терн; deduplicateByRequestId вставленным сообщениям с requestId не грозит; retry-copy детекция инъекцию не ловит (у вставленных раундов есть requestId);
  • CI-гейт: 4 фикстуры × 9 типов с требованием found + relError 0 + инварианты + рост billed; skip-ветка для слишком мелких сессий покрыта юнит-тестом; scoreOutcomes покрыт.

Находка (требует правки)

  1. Off-by-one в нумерации терна вставки при неявном терне 1 — inline на src/cli/injectWaste.ts:135. buildLedger создаёт неявный терн 1, когда первый раунд с usage идёт раньше первого опенера (analyzeSession.ts:538, currentTurn ?? newTurn); тогда гэп после k опернеров лежит в терне k+1, а Math.max(openers, 1) в pickPoint и countOpeners(...)+1 в appendPoint (строка 159) дают k. У cache_dead и wait_loop маркера в summary нет — атрибуция держится только на f.turnIndex === inj.turnIndex, поэтому инъекция на такой сессии будет вставлена, но засчитана как missed → ложное занижение recall именно там, где харнесс обязан быть точным. Все 4 мини-фикстуры начинаются с юзер-опенера, так что CI-гейт этот случай не ловит никогда. Фикс мелкий: учесть неявный первый терн в parity (раунд с usage до первого опенера) или брать терн вставленного раунда из buildLedger собранной сессии вместо ручного счётчика — ручная синхронизация с нумерацией buildLedger и так уже дублирует логику.

Заметки (правки не требуют)

  • pickPoint может выбрать гэп между оригиналом и router-retry копией (#15): бамп ломает совпадение счётчиков, копия перестаёт распознаваться и учитывается как реальный раунд. На метрику вставленного паттерна не влияет (атрибуция по маркеру и точной сумме), plausibility лишь чуть шумит; при желании такие пары можно исключить из кандидатов.
  • resolveCorpusDir(process.env, process.cwd()) — sibling corpus.ts специально использует REPO_ROOT (независимость от cwd); при запуске tsx не из корня пакета .env не найдётся. Поведение pnpm waste:recall не задевает, но единообразие бы сохранило.
  • «missed injections» печатают путь относительно CORPUS_DIR — на строку больше, чем печатает corpus:snapshot; если осознанно, ок.

Comment thread src/cli/injectWaste.ts
prevContext: contextSizeOf(prev.m),
tPrev: prev.m.timestamp.getTime(),
tNext: next.m.timestamp.getTime(),
turnIndex: Math.max(openers, 1),

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нумерация терна вставки ломается при неявном терне 1 (сессия начинается с раундов до первого опенера): buildLedger кладет гэп после k опернеров в терн k+1, а Math.max(openers, 1) здесь и countOpeners(...)+1 в appendPoint (строка 159) дают k. У cache_dead/wait_loop маркера в summary нет — hit держится только на turnIndex, такие сессии станут ложными missed injection и занизят recall; все 4 фикстуры начинаются с опернера, CI-гейт это не ловит. Учесть неявный первый терн в parity или брать терн вставленного раунда из buildLedger собранной сессии.

@axisrow
axisrow merged commit c1feda4 into main Oct 12, 2026
3 checks passed
axisrow added a commit that referenced this pull request Oct 12, 2026
…ng estimate (#83) (#135)

* feat(cli): price waste in dollars with cache residency; billed-thinking estimate

Issue #82 — findings carry wastedUsd (shared price table) and
tokensWastedInputEq, priced with cache residency: a result of size S from
round k costs one cache write + one cache read per later round until
compaction (negative contextDelta) cuts it. cache_dead books only the
fresh-input premium over a cache read. Every finding is marked
basis: measured | estimated. tokensWasted keeps its raw once-per-result
semantics — the PR #124 claim allocation and the #131 harness expected
values stay untouched.

Issue #83 — thinking is the billed estimate (output_tokens minus visible
output: text blocks + tool_use inputs, chars/4, floor 0), not chars/4 of
the returned thinking text (a summary, often empty). Rounds with empty
thinking text and large output now contribute; totals.thinkingTokens and
the thinking_heavy finding measure the paid quantity.

Corpus snapshots (#79) gain wastedUsd per finding so corpus:diff shows
the pricing shift once a corpus is configured. The per-model corpus
report (#83 step 3) and a live corpus:diff run are pending — CORPUS_DIR
is not configured in the build environment.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(cli): review — keep failed_call's raw claim when unpriced; --no-cost hides dollar figures

The failed_call claim on result:<id> stays unconditional: dropping it when
the model is unpriced shifted the raw tokensWasted allocation of the
overlapped oversized/duplicate/streak claims (contract: tokensWasted
semantics unchanged). Unpriced now drops only the rates. --no-cost no
longer prints ~$ tags and strips wastedUsd/tokensWastedInputEq from the
--json findings output.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(cli): review — result residency bills write at round k+1, reads from k+2

A result produced by round k's calls lands in the gap AFTER round k: round
k+1's request first bills it as a cache WRITE (cache_creation) — it cannot
be read there. Charged cost was cacheWrite5m(k) + readAfter[k], which
counted round k+1 as a read too — one phantom read per result (~7%
overstatement). Now: write at round k+1's rate + readAfter[k+1] (rounds
k+2..compaction). Results never sent again (k+1 past session end) carry no
future cost. Test expectations updated per the corrected model.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: axisrow <axisrow@users.noreply.github.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
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.

Waste injection harness: measure recall and quantity error per finding type

1 participant