Repository navigation
[3437 by Claude Opus 5.5] Record and report spend on failed and errored attempts - #3453
Conversation
…on, and analytics reports it separately from successful spend. Typecheck passes for root, core, api and propr-ui, and eslint passes with `--max-warnings 0` on every changed file. In the related tests (28 root suites, the API analytics suites and the Analytics page tests) everything passes. The `processGoalJob` suite only failed when I ran suites four at a time, because they share a SQLite file; it passes 18/18 alone. `test/llmMetrics.test.ts` needs a real Redis, so I didn't run it; the new tests use a mocked Redis that behaves like the real one for these calls.
1. Failed attempts get one execution row
- Usage limits: `parseStreamJsonOutput` now attaches what it had parsed so far (turns, tokens, cost, session) to the `UsageLimitError`. When `ClaudeAgent` or `CodexAgent` catches one, it writes one `llm_logs` row and one `llm_executions` row with `success = false`, the error message and the observed tokens and cost (zero if none), then rethrows. Nothing downstream ever gets a result for this case, so the agent has to record it.
- Thrown errors: the agent returns a failed result as before, and the job records it as before. The difference is that it now also writes the missing `llm_logs` row. If the agent run had finished and a later step threw, the tokens and cost from that run are kept instead of being reset to zero.
- Cancellations: the issue and PR-comment jobs now record the run before checking whether the task was cancelled. A cancelled run's spend used to go unrecorded.
- The shared logic is in a new file, `agents/impl/utils/failedAgentExecution.ts`. Recording waits at most 10 seconds, so an unreachable store can't hold up a failing run.
2. `recordLLMMetrics` can't count an execution twice
- Each agent result now carries an `executionId`, assigned after the agent runs and passed through every result conversion in the issue, PR-comment, merge-conflict and goal jobs.
- The first record of an id claims it in Redis (`SET NX`, kept 30 days, with a small in-process backup set). Any later record with that id inserts no row and adds nothing to the `llm:metrics:*` counters. Results without an id are recorded as before. This is in a new file, `utils/llmMetricsExecutionClaim.ts`.
3. Analytics splits spend by outcome
- `loadRecordedSpend` now returns `{ total, successful, failed }` instead of a single number; `total` means the same as before. Its two callers in `statsRoutes.ts` are updated.
- `loadModelUsage` adds `successful_cost_usd`, `failed_cost_usd` and `failed_runs` to each model.
- `/stats/overview` adds `usage.successful_cost_usd` and `usage.failed_cost_usd`. `/stats/dashboard` adds `recordedSpendSuccessful` and `recordedSpendFailed`, including under `previous`. No existing field was renamed or removed.
- An execution with no recorded outcome is not counted as failed. A database without the `success` column reports zero failed spend.
- The Analytics page shows "$X on failed attempts" under Total spend for the selected window, and shows nothing when the server doesn't send the split. I shortened the wording from "spend on failed attempts" because it was cut off on a 390px phone.
Tests
- New `test/llmMetricsFailedExecutions.test.ts`: recording an id twice gives one row and one counter increment; an id claimed by another worker is skipped; usage limit with and without streamed tokens; thrown errors.
- New `test/llmMetricsFailureHandlerIdempotency.test.ts`: the issue and PR-comment failure handlers pass on the same id the run recorded. This test fails against the old code.
- The API tests cover the split, missing outcomes and the old schema. The Analytics page test covers the new line.
- I updated existing exact-match test expectations to include the new fields. The shared dashboard test database now has a nullable `success` column.
Two behaviour changes to check:
- The idempotency guard relies on Redis. If Redis is down, recording already fails as it did before.
- A thrown error before the agent did any work still writes a failed row with zero spend, as the issue asks. Those rows add to the run counts on the Analytics page.
I captured desktop and phone previews of the totals band using stubbed data.
|
/ultrafix goal=8 max=10 |
|
🔄 Ultrafix loop started (goal: 8/10, max cycles: 10) First action:
|
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR improves failed-attempt accounting and adds a compatible analytics split, but needs changes before merge because the deduplication claim can suppress recovery of an execution that was never recorded. ✅ Identity propagation — The issue and PR-comment result conversions preserve ✅ Compatible analytics fields — Existing total-spend fields remain intact, and the UI hides the new detail when an older server omits the split. ✅ Interrupted-stream preservation — Usage-limit errors retain parsed output so the new failure recorder can recover observed tokens and cost. The supplied current-head status has no failures; five checks remain pending. This review is a static analysis of the supplied code; no commands or tests were run. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F1: 🔴 Failed writes permanently consume execution claims
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Clarify unknown-outcome spendThe new ScoreThe implementation has useful coverage and preserves API compatibility, but the new claim lifecycle can make missing spend unrecoverable. Correct that persistence failure path before merging; the remaining checks are still pending. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit 26c2d6f
Summary of ChangesI fixed F1: a write that fails no longer uses up an execution's claim, so a later record of the same result can still write its row. A completed record is still never written twice. Typecheck passes for core and root, and eslint How the claim works now (
Tests
Separate from this fix (not changed)
There are no visual changes, so I made no previews. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…on's claim, so a later record of the same result can still write its row. A completed record is still never written twice. Typecheck passes for core and root, and eslint `--max-warnings 0` is clean on both changed source files. The new and existing metrics tests pass (25/25), and the other suites that record metrics through a mocked Redis pass (289/289). I fixed F1: a write that fails no longer uses up an execution's claim, so a later record of the same result can still write its row. A completed record is still never written twice. Typecheck passes for core and root, and eslint `--max-warnings 0` is clean on both changed source files. The new and existing metrics tests pass (25/25), and the other suites that record metrics through a mocked Redis pass (289/289). **How the claim works now** (`packages/core/src/utils/llmMetricsExecutionClaim.ts`) - Recording an execution now has two stages, each claimed separately with Redis `SET NX`: the `llm:metrics:*` counters (existing key `llm:metrics:recorded:<id>`) and the `llm_executions` row (new key `llm:metrics:persisted:<id>`). - Each claim stores a random token. A claim is released only if it still holds that token, so one worker can't remove another worker's claim. Releasing also clears the in-process backup entry. - A release happens only when the stage verifiably wrote nothing: - **Counters:** released if the attempt fails before any counter is incremented (a cost calculation or `setex` failure). Once incrementing has started the claim is kept, so a partial write is never counted again. - **Row:** `persistToDatabase` now returns whether the row was inserted, and the claim is released only if it wasn't. If the row went in but its detail rows failed, the claim stays, so nothing is inserted twice. - A record whose counters are already claimed now skips only the counters and still writes the row if that stage is unclaimed. That is how the failure handler's second record recovers a missing row. **Tests** - New `test/llmMetricsClaimRecovery.test.ts`, which injects failures. Each case records the same result again afterwards and checks the outcome: | First attempt fails at | Second attempt | |---|---| | Row insert | Exactly one row, counters not incremented again; a third record still writes nothing | | `setex` | Both claims were released; one row, one count | | A counter increment | One row; the counters keep the first attempt's value | | Detail rows | Still treated as recorded, no second row | A fifth case checks that a claim held by another worker is never released. The first three cases fail against the previous code. - In `test/llmMetricsFailedExecutions.test.ts`, the cross-worker test now marks both stages as claimed by the other worker. **Separate from this fix (not changed)** - One race can't be avoided: if the database inserts the row but the reply is lost, the claim is released and a retry could insert a second row. Redis being unreachable during a release leaves that stage claimed, so it's lost but not doubled. - As before, a Redis failure during the counters stage still skips the database write within that same attempt; the next record of the same result writes it. There are no visual changes, so I made no previews. PR: #3453 Comment by: @propr-ultrafix (ID: 0) Model: Claude Opus 5.5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds failed-execution recording, deduplication, and spend breakdowns across the API and UI. It appears merge-ready within the supplied review scope; no concrete merge blocker was established. ✅ Identity propagation — Issue and PR-comment result adapters preserve execution IDs through subsequent failure-handler recording. ✅ Recovery-aware deduplication — Separate counter and row claims allow a failed database insert to be retried without repeating completed counter updates. ✅ Compatible analytics changes — Existing total-spend fields remain intact, and the UI hides the new detail when older servers omit it. This was a static review of the supplied diff and context. No commands or tests were run. No current-head check runs were reported. Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S2: 🟢 Exercise agent entry pointsAdd integration tests that invoke ClaudeAgent and CodexAgent through usage-limit and thrown-error paths. The new tests validate the helpers and Claude parser directly, but do not establish that both agents supply observed usage to those helpers under their actual failure conditions. This would strengthen coverage rather than address a demonstrated defect. S3: 🟢 Clarify unknown-outcome terminology
S4: 🟢 Preserve failure attribution
ScoreThe implementation addresses the requested behavior with focused regression coverage and no verified blocker in the supplied code. Agent-level failure-path verification would increase confidence; current-head checks remain unreported. Score: 8/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
AI Implementation Summary
Closes #3437
Branch:
3437/claude-opus-5-5-record-and-report-spend-o-20261111-2200-41rCommits: ✅ Changes committed (37aff03)
AI Processing Completed
Execution Details:
Summary:
Spend on failed and errored attempts is now recorded once per execution, and analytics reports it separately from successful spend. Typecheck passes for root, core, api and propr-ui, and eslint passes with
--max-warnings 0on every changed file. In the related tests (28 root suites, the API analytics suites and the Analytics page tests) everything passes. TheprocessGoalJobsuite only failed when I ran suites four at a time, because they share a SQLite file; it passes 18/18 alone.test/llmMetrics.test.tsneeds a real Redis, so I didn't run it; the new tests use a mocked Redis that behaves like the real one for these calls.1. Failed attempts get one execution row
parseStreamJsonOutputnow attaches what it had parsed so far (turns, tokens, cost, session) to theUsageLimitError. WhenClaudeAgentorCodexAgentcatches one, it writes onellm_logsrow and onellm_executionsrow withsuccess = false, the error message and the observed tokens and cost (zero if none), then rethrows. Nothing downstream ever gets a result for this case, so the agent has to record it.llm_logsrow. If the agent run had finished and a later step threw, the tokens and cost from that run are kept instead of being reset to zero.agents/impl/utils/failedAgentExecution.ts. Recording waits at most 10 seconds, so an unreachable store can't hold up a failing run.2.
recordLLMMetricscan't count an execution twiceexecutionId, assigned after the agent runs and passed through every result conversion in the issue, PR-comment, merge-conflict and goal jobs.SET NX, kept 30 days, with a small in-process backup set). Any later record with that id inserts no row and adds nothing to thellm:metrics:*counters. Results without an id are recorded as before. This is in a new file,utils/llmMetricsExecutionClaim.ts.3. Analytics splits spend by outcome
loadRecordedSpendnow returns{ total, successful, failed }instead of a single number;totalmeans the same as before. Its two callers instatsRoutes.tsare updated.loadModelUsageaddssuccessful_cost_usd,failed_cost_usdandfailed_runsto each model./stats/overviewaddsusage.successful_cost_usdandusage.failed_cost_usd./stats/dashboardaddsrecordedSpendSuccessfulandrecordedSpendFailed, including underprevious. No existing field was renamed or removed.successcolumn reports zero failed spend.Tests
test/llmMetricsFailedExecutions.test.ts: recording an id twice gives one row and one counter increment; an id claimed by another worker is skipped; usage limit with and without streamed tokens; thrown errors.test/llmMetricsFailureHandlerIdempotency.test.ts: the issue and PR-comment failure handlers pass on the same id the run recorded. This test fails against the old code.successcolumn.Two behaviour changes to check:
I captured desktop and phone previews of the totals band using stubbed data.
Detailed Logs:
371e877a-19d7-496e-9080-a1e32136e5e4Log files stored at:
/usr/src/app/logs/executions/issue-3437-2026-11-11T22-31-17-991Z-conversation.json/usr/src/app/logs/executions/issue-3437-2026-11-11T22-31-17-991Z-output.txtLatest Conversation Messages
This PR was created automatically by ProPR after processing issue #3437.
💡 Need changes?
Comment on this PR to request refinements — the AI agent monitors comments and will update the implementation based on your feedback. Keep iterating until you're satisfied!
Visual preview
Analytics totals band (desktop)
Total spend for the selected 7-day window, with the new line showing what was spent on failed attempts (stubbed data, 1440px)
Connect sign-in required. Original retained until 2027-02-09T22:31:22.895Z.
View the full-resolution original in ProPR Connect
Analytics totals band (phone)
The same totals band at 390px: the failed-attempt spend fits under Total spend without truncation
Connect sign-in required. Original retained until 2027-02-09T22:31:24.134Z.
View the full-resolution original in ProPR Connect