Repository navigation
[3439 by Claude Opus 5.5] Alert when a run's token use is far above the baseline for its repository and model - #3467
Conversation
… 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.
|
/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 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 blockersEvery finding below was introduced by this PR and must be resolved before merging. F1: 🔴 Commit alert state only after delivery
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Remove remaining retired-alert documentation
ScoreThe 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
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit 63579ae
Summary of ChangesI 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 Changes in
New tests in
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
There are no visual previews, because this change is backend-only. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 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
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe 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 blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S2: 🟢 Remove retired alert references
S3: 🟢 Test the notification integrationThe new tests inject ScoreThe 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
Copy and edit to choose records from this review: 🤖 Review by ProPR |
AI Implementation Summary
Closes #3439
Branch:
3439/claude-opus-5-5-alert-when-a-run-s-token--20261112-1031-e9dCommits: ✅ 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
warningInbox notification on its task. The new tests and the related suites pass.How the check works
issue,pr_comment, …).taskkind, 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×)."llm_execution_token_samples, added by migration20261112000000. 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_alertsset 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
token_outlier_multipliertoken_outlier_min_tokenstoken_outlier_baseline_runstoken_outlier_pause_alertstoken_outlier_pause_window_hoursSPECIALIZED_SETTING_NAMES, the settings API, the settings catalog, MCPupdate_execution_settings, and the CLI (propr setting update …).@propr/sharedso the CLI can use them.@propr/core. Several existing tests replace@propr/corewith 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, thellm:metrics:alerts:highcostlist,HighCostAlert, and therecentHighCostAlertssummary field in core and the API. Nothing in the UI, CLI or OpenAPI used that field.LLM_COST_THRESHOLD_USDno longer does anything, and the docs now describe the new alert instead:metrics.md,agents.md,execution-safety.md, plus a regeneratedsettings-locations.md.Tests
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.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.eslint --max-warnings 0.There are no visual previews: the alert uses the existing Inbox notification UI, and everything else is backend.
Detailed Logs:
6018439b-d2cd-427c-b2e8-d1e75ae01fedLog files stored at:
/usr/src/app/logs/executions/issue-3439-2026-11-12T10-54-58-961Z-conversation.json/usr/src/app/logs/executions/issue-3439-2026-11-12T10-54-58-961Z-output.txtLatest Conversation Messages
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!