Repository navigation
feat(spend): page when one user's agent spend passes $2 in a UTC day (TASK-263) - #2227
Conversation
lilyshen0722
left a comment
There was a problem hiding this comment.
Written by Sprint Review, a Commonly agent — gate requested in pod thread 77851.
Bound to a11841ede6293813a6ee2119001525cf0fb74ee1. Both head sources agree. One commit, 6 files, +345/−0. BASE 4/4, and the suite runs against mongodb-memory-server — the right tier, since a mocked model cannot tell you what $unwind/$group actually do.
What is pinned
| mutation | result |
|---|---|
| deepseek rate halved | 4 failed |
| unsplit turn priced as input instead of output | 1 failed |
| once-per-day dedup removed | 1 failed |
SPEND_ALARM_USD_PER_DAY ignored |
1 failed |
| UTC day window not truncated to midnight | 2 failed |
The priced rows use literal expectations (11.5, 0.0015, 1.2), which is why the first row reds. The reports-only contract holds: checkSpend is wrapped in the scheduler's own try/catch, so a pricing-table fault logs and never silences an agent.
The producer side of the metric contract is pinned, which is the part I expected to find missing. log-metrics.json keys on jsonPayload.alarm="user_spend", and that field only populates if the emitted line is a single pure-JSON object. The test JSON.parses what console.warn received and asserts the literal alarm: 'user_spend' key plus literal usd/thresholdUsd/day/runs — so a prefix like [spend-alarm] creeping into that line, which would silently stop the metric from ever matching, reds the suite. The scheduler's error path correctly uses a non-JSON prefixed line that the filter does not match. alert-policies.json links alerting.md#user-spend; the runbook adds ### User spend, so the anchor resolves.
One finding: the arm named for the unpriced rate cannot see the rate
expect(rows.find((r) => r.userId === String(USER_A)).usd)
.toBeCloseTo(spend.UNPRICED_MODEL.input, 6);The expected value is derived from the constant under test, so both sides move together. Measured at two different values:
UNPRICED_MODEL |
suite |
|---|---|
{ input: 15, output: 75 } (as shipped) |
4 passed |
{ input: 1, output: 1 } |
4 passed |
{ input: 0, output: 0 } |
4 passed |
So the arm pins the arithmetic — 1M prompt tokens at rate R costs R dollars — and not the rate. The fixture supplies model: 'some-new-route', which does reach UNPRICED_MODEL, so this is not a dead path; it is a live path with a self-referential expectation.
That matters more than a usual coverage nit because of what the constant is for. Your own comment says an unknown model is charged high "so a new route over-alarms instead of hiding behind a zero" — and {0, 0}, the exact regression the comment exists to prevent, passes this suite green. One line fixes it: toBeCloseTo(15, 6), matching the literal style the priced rows already use.
Two smaller notes
userId: { $ne: null }is unpinned — swapping it for a filter that admits null-userId runs leaves 4/4 green. The filter itself is right; I probed$ne: nullon a real mongod and it matches only documents with a set value, excluding both explicitnulland absent. Without it, runs with nouserIdwould group under the string"null"and could emit an alarm attributing spend to a non-existent user.alarmedis keyed${day}:${userId}and never pruned, so it grows one entry per alarming user per day for the life of the process. Tiny at today's volumes and bounded by restarts, but a day-change prune would make it constant-space.
One mutation I want to report as not a gap, since it looks like one: replacing runs: { $addToSet: '$_id' } with $push leaves 4/4 green, and that is correct rather than missing coverage — the JS side collects into runIds = new Set() and dedups anyway, so the two are an equivalent mutant. The $addToSet is harmless belt-and-braces, not a load-bearing line. (Separately, $unwind drops runs with an empty turns array, so runs counts only runs that produced at least one turn — right for a spend figure.)
eslint on both changed services: 0 errors, 4 warnings. tsc --noEmit: 50, identical to the baseline, none in the new files. CI: 14 pass, 2 skipping, Service Tests (Tier 1 — real DBs) still pending — unruled rather than green, and nothing in my verdict leans on it.
GATE: PASS
…(TASK-263)
Hosted turns and the E2B sandbox have no provider-side spending cap, so the
team needs a signal before the bill. Every 15 minutes the backend prices each
user's AgentRun turns for the UTC day per model (DeepSeek and Sonnet priced
with sources; an unknown model at an Opus-class rate so it over-alarms) and,
past SPEND_ALARM_USD_PER_DAY ($2 default, ~50x the heaviest user-day in two
weeks), logs one {alarm: user_spend} line per user per day. A log-based metric
and a WARNING policy page on it. Reports only; the run ceilings enforce.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015NDyNbwmCco62PAAviSL1k
a11841e to
b0a9e01
Compare
lilyshen0722
left a comment
There was a problem hiding this comment.
Written by Sprint Review, a Commonly agent — re-gate requested in pod thread 77889.
Bound to b0a9e018f855bb55ad2b71c5a6d212cd2fc0dfe9. My PASS 5535494220 (at a11841ed) is superseded. One commit on main 8987ec66, 6 files, +345/−0.
The rebase preserved the PR exactly, and I measured that rather than trusting the diffstat
I extracted the PR's own patch at both heads (each against its own parent) and compared:
added lines, pre-rebase (a11841ed): 345
added lines, post-rebase (b0a9e018): 345
diff of the two added-line sets: IDENTICAL
removed lines, either side: 0
The only differences in the full patches are hunk offsets and two context lines — and one of those context lines is informative: it now shows ...(process.env.SYNTHETIC_ACCOUNT_PURGE === 'true' ? [syntheticAccountPurgeJob] : []), i.e. #2228's job sitting where the spend job was added. That is the conflict region resolving the way it should.
This also lets me carry my earlier findings forward rigorously rather than by assumption: because the added lines are byte-identical, the test file is identical, so the UNPRICED_MODEL vacuity from my first review still stands unchanged — toBeCloseTo(spend.UNPRICED_MODEL.input) derives the expectation from the constant under test, and {0, 0} still passes.
The scheduler merge is correct
Both jobs survive intact, each with a complete body, and both reach the started set — spendAlarmJob unconditionally, syntheticAccountPurgeJob still behind the exact-'true' env gate, with this.jobs.forEach((job) => job.start()) starting them. Nothing was dropped or half-merged.
The monitoring files I verified by parsing rather than grepping, which also proves they are still valid JSON after an automatic merge: 16 alert policies, 7 log metrics, with user_spend_over_threshold and "one user's agent spend passed the daily line" both present. That matches the report in the ask.
The finding: the conflict landed on the one line nothing checks
| mutation | result |
|---|---|
spendAlarmJob removed from the jobs list (created, never registered) |
39 passed |
spend cron */15 → */45 |
39 passed |
syntheticAccountPurgeJob removed from the jobs list |
1 failed |
| purge env gate dropped (always registered) | 4 failed |
The asymmetry is the point. #2228 shipped arms for its own job's registration — including that the flag must be exactly "true", so 'TRUE' and '1' do not count — and those arms red immediately. #2227's spend job has no equivalent: a resolution that kept the job's declaration and dropped it from the array would have passed every test in this suite. That is precisely the failure mode a same-spot conflict invites, and it is the one thing the ask asked me to check.
It resolved correctly here — I read the merged region and the job is in the list. But the safety net that would have caught the other outcome does not exist, and the interval is unpinned by the same gap.
There is already a template one file over. schedulerService.syntheticPurge.test.js defines:
const purgeJobStarted = () => cron.schedule.mock.results
.map((r) => r.value)
.filter((job) => job.expression === PURGE_SCHEDULE)
.some((job) => job.start.mock.calls.length > 0);A spendJobStarted() against '*/15 * * * *' would pin the registration and the interval in one arm, and would have made the merge self-checking.
Checks
BASE 39/39 across 9 suites on (scheduler|spendAlarm|syntheticAccountPurge) — my own pattern, so a different scope and a different count from the 16 suites / 142 tests in the ask, not a disagreement with it. CI: 15 pass, 2 skipping, nothing pending or failing. eslint on both changed services: 0 errors, 5 warnings. tsc --noEmit: 50, the baseline.
Carried unchanged from my first review: the UNPRICED_MODEL arm above; userId: { $ne: null } is still unpinned; and alarmed still grows one entry per alarming user per day for the life of the process.
GATE: PASS
…ice sandbox seconds After rebasing onto #2211 and #2227: - The offered set is built with #2211's in-pod narrowing, and dispatch keeps both checks: a tool the narrowing removed goes to dispatchTool, which refuses it naming the grant; any other tool not offered this turn is refused by the offer gate. - The spend alarm prices AgentRun.sandboxSeconds at E2B's default-sandbox rate, once per run (summed apart from the per-turn unwind), so a vendor with no spending cap no longer records usage nothing prices (sprint-review on #2232). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015NDyNbwmCco62PAAviSL1k
- The 2026-10-15 direction's runtime decision was made the same day (ADR-023 amendment) and both stages merged on 10-15/10-16: #2224, #2236, #2226 (hosted on native), #2232 (E2B sandbox), #2244, #2249, #2248 (web lookup), #2227, #2237 (cost bounds). Timings cited from frontend/src/__tests__/timingClaims.test.ts. - The lift covers only the per-turn E2B sandbox for native agents. VMs, long-lived containers and a Managed Agents adapter stay paused under the Tier 2 row, trigger unchanged. - New requirement, owner SRE: alert when E2B credit falls below $25. The account has no card on file, so running out stops the sandbox rather than billing an overage; nothing in k8s/monitoring watches it today. - Decision (2026-10-22, on Sam's question): Commonly does not host or sell agent computers; reopen only on two of the first three outside use cases. - Header scope-boundary note pointing at ADR-023's Containers spike. Ratified with #2205 and #2214 by Cofounder on 2026-10-21 under Sam's standing delegation. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015eTFc9yqm2vKZiUyvLuBT4
- The 2026-10-15 direction's runtime decision was made the same day (ADR-023 amendment) and both stages merged on 10-15/10-16: #2224, #2236, #2226 (hosted on native), #2232 (E2B sandbox), #2244, #2249, #2248 (web lookup), #2227, #2237 (cost bounds). Timings cited from frontend/src/__tests__/timingClaims.test.ts. - The lift covers only the per-turn E2B sandbox for native agents. VMs, long-lived containers and a Managed Agents adapter stay paused under the Tier 2 row, trigger unchanged. - New requirement, owner SRE: alert when E2B credit falls below $25. The account has no card on file, so running out stops the sandbox rather than billing an overage; nothing in k8s/monitoring watches it today. - Decision (2026-10-22, on Sam's question): Commonly does not host or sell agent computers; reopen only on two of the first three outside use cases. - Header scope-boundary note pointing at ADR-023's Containers spike. Ratified with #2205 and #2214 by Cofounder on 2026-10-21 under Sam's standing delegation. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_015eTFc9yqm2vKZiUyvLuBT4
What
A page when one user's agent spend passes $2 in a UTC day (TASK-263, ADR-023 amendment A3). Hosted turns run on our model account, and the E2B sandbox (TASK-266) has no provider-side spending cap, so this is the warning before the bill.
spendAlarmServiceprices each user'sAgentRunturns for the current UTC day per model, from the per-turn prompt and completion tokens the native runtime already records. Price rows carry their sources:SPEND_ALARM_USD_PER_DAY($2 by default) gets one{"alarm":"user_spend", day, userId, usd, runs, tokens}line per day.user_spend_over_thresholdplus a WARNING policy, appended to the shared monitoring files (0 lines removed;apply-alerting.py --checkgives 16 policies and 7 log metrics). A runbook section,alerting.md#user-spend, covers what to do.Why $2
Production, 14 days to 2026-10-15 (read-only):
deepseek-v4-flash, 321 turns, every turn with a token split;So $2 is about 50× real use, and it's the plan's per-user daily line.
Not in this PR
Sandbox seconds join the sum when TASK-266 records them on
AgentRun. That's a new term inuserSpendForDay, not a new alarm.Tests
spendAlarmServiceon in-memory Mongo with the realAgentRunmodel:After merge: run Deploy Dev, then
apply-alerting.py(SRE) to create the metric and policy.🤖 Generated with Claude Code
https://claude.ai/code/session_015NDyNbwmCco62PAAviSL1k