Skip to content

[3439 by Claude Opus 5.5] Alert when a run's token use is far above the baseline for its repository and model - #3467

Merged
integry merged 2 commits into
3437-epic-cost-visibility-olufrom
3439/claude-opus-5-5-alert-when-a-run-s-token--20261112-1031-e9d
Nov 12, 2026
Merged

integry merged 2 commits into
3437-epic-cost-visibility-olufrom
3439/claude-opus-5-5-alert-when-a-run-s-token--20261112-1031-e9d

Conversation

@propr-dev

@propr-dev propr-dev Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

AI Implementation Summary

Closes #3439

Branch: 3439/claude-opus-5-5-alert-when-a-run-s-token--20261112-1031-e9d
Commits: ✅ Changes committed (1795801)


AI Processing Completed

Execution Details:

Summary:
I've implemented #3439. After a run is recorded, its total tokens are compared with the usual tokens for the same repository, model and execution type. A run far above that usual level raises a warning Inbox notification on its task. The new tests and the related suites pass.

How the check works

  • Baseline: the median tokens of the last N successful runs (default 20) for the same repository, model and execution type. A run is never part of its own baseline. No alert fires until at least 8 such runs exist.
  • Execution type: older call sites don't pass one, so I fall back to the job type (issue, pr_comment, …).
  • Token total: input + output + cache writes + cache reads, the same total the cost estimate uses.
  • When it alerts: the run must be above the multiple (default 4×) and above an absolute floor (default 500,000 tokens), so small runs never alert.
  • Notification: reuses the existing task kind, links to the task, and states observed versus baseline. For example: "Used 6M tokens, 6× the baseline of 1M (median of the last 8 successful implementation runs of Claude Opus 5.5 in acme/widgets; alert above 4×)."
    • It goes to all instance members, the same way the spend-cap notification does.
    • It is skipped for repositories with notifications turned off.
    • Each task alerts at most once, so later runs of the same task stay quiet.
    • Runs with no task still count toward baselines but cannot alert, since there is nothing to link to.
  • Speed: one row per run goes into a new table, llm_execution_token_samples, added by migration 20261112000000. A composite index makes the baseline query a single indexed lookup. The check is loaded only when first used, and any error in it is logged without affecting the recording.

Automation pause (off by default)
With token_outlier_pause_alerts set to M, a repository with M alerts inside the window has its scheduled agent runs skipped, with a reason in the run history. This happens in the existing agent-run cost gate. Only scheduled runs are affected; manual, API, MCP and CLI triggers still run. The pause lifts by itself once the window passes, and if the check itself fails the run goes ahead.

Settings

Setting Default Range
token_outlier_multiplier 4 1.5–100
token_outlier_min_tokens 500,000 from 1,000
token_outlier_baseline_runs 20 8–200
token_outlier_pause_alerts 0 (off) 0–1,000
token_outlier_pause_window_hours 24 1–720
  • They follow the standard pattern: loader, validation, SPECIALIZED_SETTING_NAMES, the settings API, the settings catalog, MCP update_execution_settings, and the CLI (propr setting update …).
  • The definitions live in @propr/shared so the CLI can use them.
  • The API imports them from shared rather than from @propr/core. Several existing tests replace @propr/core with a fixed list of exports and broke when the API imported the new constants from core.

Old high-cost Redis list: removed. That covers checkCostThreshold, the llm:metrics:alerts:highcost list, HighCostAlert, and the recentHighCostAlerts summary field in core and the API. Nothing in the UI, CLI or OpenAPI used that field. LLM_COST_THRESHOLD_USD no longer does anything, and the docs now describe the new alert instead: metrics.md, agents.md, execution-safety.md, plus a regenerated settings-locations.md.

Tests

  • New: test/tokenOutlierAlert.test.ts, 18 tests on in-memory SQLite. They cover the baseline (median, last-N, failed runs excluded, other model/type/repository excluded, case-insensitive repository), the threshold and floor, the 8-run minimum, once-per-task deduplication, the pause and its window, the gate, and the settings (loader, API validation, CLI parsing). I broke the deduplication and the 8-run minimum on purpose to confirm the tests catch it.
  • Existing: I re-ran 30 related suites (settings, config routes, MCP, OpenAPI, cost export, and the existing metrics-recording suites). In test/configRoutes.followup.test.ts, the expected settings responses needed the new defaults added; it now passes 103/103.
  • test/llmMetrics.test.ts: I rewrote its old high-cost test to check that the list is gone. It needs a live Redis and timed out in the first run because this container has none. With a Redis 7.2 built locally it passes 5/5.
  • Typecheck and lint: clean for shared, core, API and CLI; the changed core and API files pass eslint --max-warnings 0.

There are no visual previews: the alert uses the existing Inbox notification UI, and everything else is backend.

Detailed Logs:

  • Conversation: 276 messages
  • Session: 6018439b-d2cd-427c-b2e8-d1e75ae01fed

Log files stored at:

  • conversation: /usr/src/app/logs/executions/issue-3439-2026-11-12T10-54-58-961Z-conversation.json
  • output: /usr/src/app/logs/executions/issue-3439-2026-11-12T10-54-58-961Z-output.txt
Latest Conversation Messages
ASSISTANT: [content unavailable]

ASSISTANT: I've implemented #3439. After a run is recorded, its total tokens are compared with the usual tokens for the same repository, model and execution type. A run far above that usual level raises a `warni...


This PR was created automatically by ProPR after processing issue #3439.


💡 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!

… compared with the usual tokens for the same repository, model and execution type. A run far above that usual level raises a `warning` Inbox notification on its task. The new tests and the related suites pass.

How the check works
- Baseline: the median tokens of the last N successful runs (default 20) for the same repository, model and execution type. A run is never part of its own baseline. No alert fires until at least 8 such runs exist.
- Execution type: older call sites don't pass one, so I fall back to the job type (`issue`, `pr_comment`, …).
- Token total: input + output + cache writes + cache reads, the same total the cost estimate uses.
- When it alerts: the run must be above the multiple (default 4×) and above an absolute floor (default 500,000 tokens), so small runs never alert.
- Notification: reuses the existing `task` kind, links to the task, and states observed versus baseline. For example: "Used 6M tokens, 6× the baseline of 1M (median of the last 8 successful implementation runs of Claude Opus 5.5 in acme/widgets; alert above 4×)."
  - It goes to all instance members, the same way the spend-cap notification does.
  - It is skipped for repositories with notifications turned off.
  - Each task alerts at most once, so later runs of the same task stay quiet.
  - Runs with no task still count toward baselines but cannot alert, since there is nothing to link to.
- Speed: one row per run goes into a new table, `llm_execution_token_samples`, added by migration `20261112000000`. A composite index makes the baseline query a single indexed lookup. The check is loaded only when first used, and any error in it is logged without affecting the recording.

Automation pause (off by default)
With `token_outlier_pause_alerts` set to M, a repository with M alerts inside the window has its scheduled agent runs skipped, with a reason in the run history. This happens in the existing agent-run cost gate. Only scheduled runs are affected; manual, API, MCP and CLI triggers still run. The pause lifts by itself once the window passes, and if the check itself fails the run goes ahead.

Settings
| Setting | Default | Range |
|---|---|---|
| `token_outlier_multiplier` | 4 | 1.5–100 |
| `token_outlier_min_tokens` | 500,000 | from 1,000 |
| `token_outlier_baseline_runs` | 20 | 8–200 |
| `token_outlier_pause_alerts` | 0 (off) | 0–1,000 |
| `token_outlier_pause_window_hours` | 24 | 1–720 |

- They follow the standard pattern: loader, validation, `SPECIALIZED_SETTING_NAMES`, the settings API, the settings catalog, MCP `update_execution_settings`, and the CLI (`propr setting update …`).
- The definitions live in `@propr/shared` so the CLI can use them.
- The API imports them from shared rather than from `@propr/core`. Several existing tests replace `@propr/core` with a fixed list of exports and broke when the API imported the new constants from core.

Old high-cost Redis list: removed. That covers `checkCostThreshold`, the `llm:metrics:alerts:highcost` list, `HighCostAlert`, and the `recentHighCostAlerts` summary field in core and the API. Nothing in the UI, CLI or OpenAPI used that field. `LLM_COST_THRESHOLD_USD` no longer does anything, and the docs now describe the new alert instead: `metrics.md`, `agents.md`, `execution-safety.md`, plus a regenerated `settings-locations.md`.

Tests
- New: `test/tokenOutlierAlert.test.ts`, 18 tests on in-memory SQLite. They cover the baseline (median, last-N, failed runs excluded, other model/type/repository excluded, case-insensitive repository), the threshold and floor, the 8-run minimum, once-per-task deduplication, the pause and its window, the gate, and the settings (loader, API validation, CLI parsing). I broke the deduplication and the 8-run minimum on purpose to confirm the tests catch it.
- Existing: I re-ran 30 related suites (settings, config routes, MCP, OpenAPI, cost export, and the existing metrics-recording suites). In `test/configRoutes.followup.test.ts`, the expected settings responses needed the new defaults added; it now passes 103/103.
- `test/llmMetrics.test.ts`: I rewrote its old high-cost test to check that the list is gone. It needs a live Redis and timed out in the first run because this container has none. With a Redis 7.2 built locally it passes 5/5.
- Typecheck and lint: clean for shared, core, API and CLI; the changed core and API files pass `eslint --max-warnings 0`.

There are no visual previews: the alert uses the existing Inbox notification UI, and everything else is backend.
@propr-dev

propr-dev Bot commented Nov 12, 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 12, 2026
@propr-dev

propr-dev Bot commented Nov 12, 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 12, 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 12, 2026

Copy link
Copy Markdown
Contributor Author

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

Overall Evaluation

The PR implements baseline-based token alerts and an optional scheduling pause with consistent settings across API, MCP, and CLI. It needs a localized correction before merge: executions are permanently marked as alerted before notification delivery succeeds—or even qualifies to run.

✅ Baseline isolation — Queries filter by repository, model, execution type, and success, and read history before inserting the current sample.

✅ Bounded configuration — Shared validation enforces threshold ranges, with tests covering minimum history, threshold boundaries, and scheduling behavior.

The supplied current-head status has no failures and two pending checks. This review is a static analysis of the supplied code; no commands were run.

Merge blockers

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

F1: 🔴 Commit alert state only after delivery

  • Required behavior: Alert deduplication and the automation pause must track alerts actually raised. Suppressed or failed notifications must not permanently consume a task’s alert or count as delivered alerts.

  • Evidence: packages/core/src/utils/tokenOutlierAlert.ts:148, recordTokenUsageSample; packages/core/src/utils/tokenOutlierAlert.ts:232, notifyTokenOutlier.

    1. Configure a repository with notifications disabled, eight successful baseline executions, and token_outlier_pause_alerts = 1.
    2. Record an outlier with a task. recordTokenUsageSample writes alerted_at before invoking the notification function and counts that row toward the pause.
    3. notifyTokenOutlier returns immediately because repository notifications are disabled. Nevertheless, the recorded row remains marked as alerted.
    4. The next scheduled automation reads that marker and is skipped despite no alert having been raised. Enabling notifications later does not restore this task’s opportunity to alert because taskAlreadyAlerted now returns true.
    5. With notifications enabled, a rejection during notification creation produces the same permanent marker: the caller logs the error, while subsequent outliers for the task are suppressed.

    static trace: The marker update precedes both the notification eligibility check and notification persistence. The notification service’s transaction covers its own event and recipients, not this earlier update. Its deduplication key prevents duplicate events but cannot recover an event that was never persisted. Existing tests replace notify with an always-successful callback, so they do not exercise either path.

  • Minimum fix: Distinguish suppressed, persisted, and failed notification outcomes. Only commit the alert marker and count it toward the pause after notification persistence is confirmed; leave failed delivery eligible for retry. Reuse the existing notification deduplication key to make retries safe, and add regression coverage for disabled notifications and notification-persistence failure.

Suggestions

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

S1: 🟢 Remove remaining retired-alert documentation

docs/docs/operations/metrics.md still advertises “The 10 most recent high-cost alerts” in the aggregated API section and references recent high-cost alerts in its weekly and operational guidance. Updating those references would align the documentation with the removed response field. This is documentation cleanup rather than another runtime blocker.

Score

The baseline logic and configuration coverage are solid, but premature alert bookkeeping can silently suppress notifications and incorrectly pause scheduled work. The required correction is localized.

Score: 6/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 51s
  • Tokens: 69,456 (68,400 in / 1,056 out)
  • Cost: $0.63

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 12, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit 63579ae

Addressed 1 AI review comment (IDs: 6822180100)

Addressed finding F1

Summary of Changes

I fixed F1: a task's alert is now marked, and counted toward the automation pause, only after its Inbox notification has actually been saved. All 21 tests in test/tokenOutlierAlert.test.ts pass, including three new ones.

Changes in packages/core/src/utils/tokenOutlierAlert.ts

  • Three outcomes: notifyTokenOutlier now reports delivered once the event is saved, or suppressed when nothing is raised (repository notifications off, no recipients, no task). A failed save throws as before. The new TokenOutlierNotificationOutcome type is also exported from packages/core/src/index.ts.
  • Marker after delivery: recordTokenUsageSample writes alerted_at only for delivered.
    • If the notification is suppressed, nothing is marked and the result is alerted: false.
    • If the save fails, the error reaches the caller's existing best-effort handler in llmMetrics.ts with nothing marked. The task's next outlier run tries again, and the existing token-outlier:<taskId> deduplication key stops a retry from creating a second Inbox event.
  • Pause count: since the current alert isn't in the table yet when the pause is worked out, the count adds 1 for it. The notification text still states the pause that this alert causes.
  • Two runs at once: two outlier runs of the same task could both pass the "already alerted" check while waiting on the notification, then both mark and count twice toward the pause. The marker update now skips the row if another run of the task has been marked in the meantime, so only one run reports alerted: true. The original code had the same gap, and it could only get wider once marking waits for delivery.

New tests in test/tokenOutlierAlert.test.ts

  • Notifications off: with the pause set to 1, a suppressed alert leaves no marker and no pause. Once delivery works again, the same task's next outlier alerts and starts the pause.
  • Save failure: the error propagates, there is no marker or pause, the next outlier run of the task alerts, and the one after that stays quiet.
  • Two runs at once: both runs get past the "already alerted" check before delivery finishes, and only one ends up marked.

All three new tests fail when run against the previous version of the file, and the other 18 still pass there. The core typecheck and eslint --max-warnings 0 on the changed core files are clean.

test/llmMetrics.test.ts was not run successfully: it needs Redis, which isn't in this container, so the attempt hung and I stopped it. The caller it would cover, checkTokenOutlier, is unchanged.

There are no visual previews, because this change is backend-only.


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @propr-ultrafix
  • Time: 6m 27s
  • Tokens: 802,471 (794,378 in / 8,093 out)
  • Cost: $0.60
  • Subscription usage: Fable +1%

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

…d the automation pause, only after its Inbox notification has actually been saved. All 21 tests in `test/tokenOutlierAlert.test.ts` pass, including three new ones.

I fixed F1: a task's alert is now marked, and counted toward the automation pause, only after its Inbox notification has actually been saved. All 21 tests in `test/tokenOutlierAlert.test.ts` pass, including three new ones.

**Changes in `packages/core/src/utils/tokenOutlierAlert.ts`**
- **Three outcomes:** `notifyTokenOutlier` now reports `delivered` once the event is saved, or `suppressed` when nothing is raised (repository notifications off, no recipients, no task). A failed save throws as before. The new `TokenOutlierNotificationOutcome` type is also exported from `packages/core/src/index.ts`.
- **Marker after delivery:** `recordTokenUsageSample` writes `alerted_at` only for `delivered`.
  - If the notification is suppressed, nothing is marked and the result is `alerted: false`.
  - If the save fails, the error reaches the caller's existing best-effort handler in `llmMetrics.ts` with nothing marked. The task's next outlier run tries again, and the existing `token-outlier:<taskId>` deduplication key stops a retry from creating a second Inbox event.
- **Pause count:** since the current alert isn't in the table yet when the pause is worked out, the count adds 1 for it. The notification text still states the pause that this alert causes.
- **Two runs at once:** two outlier runs of the same task could both pass the "already alerted" check while waiting on the notification, then both mark and count twice toward the pause. The marker update now skips the row if another run of the task has been marked in the meantime, so only one run reports `alerted: true`. The original code had the same gap, and it could only get wider once marking waits for delivery.

**New tests in `test/tokenOutlierAlert.test.ts`**
- **Notifications off:** with the pause set to 1, a suppressed alert leaves no marker and no pause. Once delivery works again, the same task's next outlier alerts and starts the pause.
- **Save failure:** the error propagates, there is no marker or pause, the next outlier run of the task alerts, and the one after that stays quiet.
- **Two runs at once:** both runs get past the "already alerted" check before delivery finishes, and only one ends up marked.

All three new tests fail when run against the previous version of the file, and the other 18 still pass there. The core typecheck and `eslint --max-warnings 0` on the changed core files are clean.

`test/llmMetrics.test.ts` was not run successfully: it needs Redis, which isn't in this container, so the attempt hung and I stopped it. The caller it would cover, `checkTokenOutlier`, is unchanged.

There are no visual previews, because this change is backend-only.

PR: #3467
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5
@propr-dev

propr-dev Bot commented Nov 12, 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 12, 2026

Copy link
Copy Markdown
Contributor Author

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

Overall Evaluation

The PR implements token-outlier detection, task Inbox alerts, and an optional scheduled-automation pause with consistent settings across API, MCP, and CLI. No merge-blocking defect was verified in the supplied diff and context. It is merge-ready within scope, conditional on the pending Validate Changes check passing.

✅ Bounded baseline — The query filters successful runs by repository, model, and execution type, limits history, and reads before inserting the current sample.

✅ Controlled alerting — Detection requires both thresholds and eight historical samples. Notification deduplication and conditional marking prevent concurrent alerts for one task from inflating the pause count.

✅ Failure isolation — Alert-check failures do not invalidate execution recording, and pause-check failures allow scheduled runs to proceed.

This was a static review; no commands or tests were run, as requested. The supplied current-head status reports 34 passed checks, no failures, and one pending check.

Merge blockers

No merge blockers.

Suggestions

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

S2: 🟢 Remove retired alert references

docs/docs/operations/metrics.md still promises “The 10 most recent high-cost alerts” under Aggregated metrics API and mentions recent high-cost alerts under weekly and operational signals. Update these references to the Inbox token-outlier notifications, since the PR removes recentHighCostAlerts. This is a documentation cleanup rather than a runtime blocker.

S3: 🟢 Test the notification integration

The new tests inject notify, so they exercise detection and marking without exercising notifyTokenOutlier itself. A focused integration test covering actual notification persistence, recipient selection, repository opt-out, and duplicate event reuse would strengthen coverage of the user-visible outcome. The supplied notification-service implementation supports the intended behavior, so this is additional assurance rather than a verified defect.

Score

The implementation is coherent and has substantial targeted coverage, with no verified blocker. Final merge readiness remains conditional on the pending validation check.

Score: 9/10


🤖 Review Details

  • Model: GPT-6 Astra
  • Time: 32s
  • Tokens: 69,595 (69,025 in / 570 out)
  • Cost: $0.61

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

🤖 Review by ProPR

@propr-dev propr-dev Bot removed the ultrafix label Nov 12, 2026
@integry
integry merged commit e3c18df into 3437-epic-cost-visibility-olu Nov 12, 2026
50 checks passed
@integry
integry deleted the 3439/claude-opus-5-5-alert-when-a-run-s-token--20261112-1031-e9d branch November 12, 2026 14:47
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