Skip to content

[3437 by Claude Opus 5.5] Record and report spend on failed and errored attempts - #3453

Merged
integry merged 2 commits into
3437-epic-cost-visibility-olufrom
3437/claude-opus-5-5-record-and-report-spend-o-20261111-2200-41r
Nov 11, 2026
Merged

integry merged 2 commits into
3437-epic-cost-visibility-olufrom
3437/claude-opus-5-5-record-and-report-spend-o-20261111-2200-41r

Conversation

@propr-dev

@propr-dev propr-dev Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

AI Implementation Summary

Closes #3437

Branch: 3437/claude-opus-5-5-record-and-report-spend-o-20261111-2200-41r
Commits: ✅ Changes committed (37aff03)


AI Processing Completed

Execution Details:

  • Issue: Record and report spend on failed and errored attempts #3437
  • Repository: integry/propr
  • Status: Success
  • Execution Time: 30m 38s
  • Tokens used: 24.78M tokens [24.7M input + 79.21K output]
  • API cost: $7.74
  • Timestamp: Nov 11, 2026, 10:31 PM UTC
  • LLM Model: Claude Opus 5.5
  • Subscription usage: Weekly +3%, Fable +3%

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 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.

Detailed Logs:

  • Conversation: 209 messages
  • Session: 371e877a-19d7-496e-9080-a1e32136e5e4

Log files stored at:

  • conversation: /usr/src/app/logs/executions/issue-3437-2026-11-11T22-31-17-991Z-conversation.json
  • output: /usr/src/app/logs/executions/issue-3437-2026-11-11T22-31-17-991Z-output.txt
Latest Conversation Messages
ASSISTANT: [content unavailable]

ASSISTANT: 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...


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)

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)

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

…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.
@propr-dev

propr-dev Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

/ultrafix goal=8 max=10
Triggered automatically by the requested execution settings.

@propr-dev propr-dev Bot added the ultrafix label Nov 11, 2026
@propr-dev

propr-dev Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

🔄 Ultrafix loop started (goal: 8/10, max cycles: 10)

First action: /review

💡 Tip: Remove the ultrafix label from this PR to stop further ultrafix cycles.

@propr-dev

propr-dev Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ AI Code Review Complete requested by @propr-ultrafix

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — codex:gpt-6-astra

Overall Evaluation

The 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 executionId, including conversions used by failure handlers.

✅ 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 blockers

Every finding below was introduced by this PR and must be resolved before merging.

F1: 🔴 Failed writes permanently consume execution claims

  • Required behavior: An execution must remain recordable when its initial metrics persistence fails; deduplication must not classify an attempted write as a completed record.

  • Evidence: packages/core/src/utils/llmMetricsExecutionClaim.ts:39–47 and packages/core/src/utils/llmMetrics.ts:309, recordLLMMetrics.

    1. An issue or PR-comment run returns an execution ID, and its first recordLLMMetrics call successfully acquires the Redis claim.
    2. claimExecution also adds that ID to recordedInProcess, before any execution row is persisted.
    3. A subsequent storage failure prevents the execution row from being inserted.
    4. When the same result reaches another recording attempt—for example, the later failure-handler path explicitly covered by this PR—the claim check returns false. The missing row and its spend cannot be recovered through that attempt.

    The Redis marker remains for 30 days, and the process-local marker also suppresses retries. Neither marker distinguishes pending work from successful persistence, and there is no release or completion transition in the new claim helper. The added tests cover successful duplicate suppression, but not recovery after a claimed write fails.

    static trace: The claim and process-local insertion precede all recording work in the supplied diff. The documented issue and PR-comment failure paths explicitly record the same result again. No failure-injection test was executed.

  • Minimum fix: Distinguish an in-progress claim from a completed record, and permit recovery when persistence fails before an execution row exists. Clear both Redis and process-local state on that verified failure path; preserve deduplication for completed writes and handle partial writes without incrementing counters twice. Add a regression where the first persistence attempt fails and the second records exactly one execution.

Suggestions

These are optional follow-ups and are not sent to /fix.

S1: 🟢 Clarify unknown-outcome spend

The new successful fields include costs whose outcome is unknown, because they are calculated as total minus failed spend. The tests explicitly establish this compatibility behavior, but the field comments say “executions that succeeded.” Document that unknown outcomes are included, or consider a separate unknown category later. This is a clarification of the chosen fallback rather than a merge blocker.

Score

The 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

  • Model: GPT-6 Astra
  • Time: 58s
  • Tokens: 70,765 (69,530 in / 1,235 out)
  • Cost: $0.65

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F1 S1

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit 26c2d6f

Addressed 1 AI review comment (IDs: 6808927813)

Addressed finding F1

Summary of Changes

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.


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @propr-ultrafix
  • Time: 8m 56s
  • Tokens: 1,280,621 (1,264,540 in / 16,081 out)
  • Cost: $0.90

View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 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
@propr-dev

propr-dev Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ AI Code Review Complete requested by @propr-ultrafix

Posted 1 review:

View Task Details

@propr-dev

propr-dev Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — codex:gpt-6-astra

Overall Evaluation

The 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 blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S2: 🟢 Exercise agent entry points

Add 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

loadRecordedSpend and loadModelUsage calculate successful spend as total minus failed spend, deliberately including unknown outcomes. Consider documenting these fields as non-failed spend or distinguishing unknown spend. The supplied tests explicitly establish the current behavior, so this is a clarification rather than a merge requirement.

S4: 🟢 Preserve failure attribution

recordUnreturnedFailedExecution derives jobType solely from prNumber, so merge-conflict usage limits are labelled pr_comment, and goal usage limits are labelled issue. Passing the originating job type would improve diagnostic consistency. The demonstrated spend totals and outcome split do not depend on that classification, making this a follow-up.

Score

The 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

  • Model: GPT-6 Astra
  • Time: 45s
  • Tokens: 74,050 (73,105 in / 945 out)
  • Cost: $0.67

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S2 S3 S4

🤖 Review by ProPR

@propr-dev propr-dev Bot removed the ultrafix label Nov 11, 2026
@integry
integry merged commit e855883 into 3437-epic-cost-visibility-olu Nov 11, 2026
42 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant