Skip to content

feat(spend): page when one user's agent spend passes $2 in a UTC day (TASK-263) - #2227

Merged
lilyshen0722 merged 1 commit into
mainfrom
lily/spend-alarm
Oct 15, 2026
Merged

lilyshen0722 merged 1 commit into
mainfrom
lily/spend-alarm

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

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.

  • spendAlarmService prices each user's AgentRun turns 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:
    • DeepSeek V4.1 Flash: $0.30 / $1.20 per M, cache-miss input;
    • Sonnet: $2 / $10;
    • any other model: an Opus-class $15 / $75, so a new route over-alarms instead of hiding behind a zero;
    • a turn with no token split is priced as all output.
  • Every 15 minutes (scheduler), a user past SPEND_ALARM_USD_PER_DAY ($2 by default) gets one {"alarm":"user_spend", day, userId, usd, runs, tokens} line per day.
  • Paging: log metric user_spend_over_threshold plus a WARNING policy, appended to the shared monitoring files (0 lines removed; apply-alerting.py --check gives 16 policies and 7 log metrics). A runbook section, alerting.md#user-spend, covers what to do.
  • It reports and never blocks. The per-user run ceiling and the per-install caps enforce.

Why $2

Production, 14 days to 2026-10-15 (read-only):

  • one model recorded, deepseek-v4-flash, 321 turns, every turn with a token split;
  • the heaviest user-day was about 105k tokens, roughly $0.04.

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 in userSpendForDay, not a new alarm.

Tests

  • spendAlarmService on in-memory Mongo with the real AgentRun model:
    • per-model pricing summed across runs for today only;
    • the unpriced-model rate and the unsplit-turn rate;
    • one line per user per day, nothing under the line;
    • the env threshold moves the line, and a bad value falls back to $2.
  • Mutations, each caught: no day filter; no once-a-day dedupe; an unpriced model at the cheapest rate.
  • Wider run: the 14 scheduler and spend suites pass, 129 tests. tsc and lint are 0 on the changed TypeScript.

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

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: null on a real mongod and it matches only documents with a set value, excluding both explicit null and absent. Without it, runs with no userId would group under the string "null" and could emit an alarm attributing spend to a non-existent user.
  • alarmed is 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

@lilyshen0722
lilyshen0722 added this pull request to the merge queue Oct 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 15, 2026
…(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

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@lilyshen0722
lilyshen0722 added this pull request to the merge queue Oct 15, 2026
Merged via the queue into main with commit ff909fb Oct 15, 2026
18 checks passed
samxu01 pushed a commit that referenced this pull request Oct 15, 2026
…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
samxu01 pushed a commit that referenced this pull request Oct 23, 2026
- 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
samxu01 pushed a commit that referenced this pull request Oct 25, 2026
- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant