Repository navigation
feat(safety): a persisted spend meter that processRequest reserves against before any provider call - #167
Conversation
…ainst before any provider call ISpendMeter keeps an allowance per account and period. SqlSpendMeter stores it on a sql-storage-adapter store with conditional statements in one transaction, so two processes cannot both take the last unit and a reservation settles once. With AgentOSConfig.spendMeter set, processRequest needs an operationId and reserves before the turn: a refusal (BILLING_ALLOWANCE_EXHAUSTED, SYS_ALREADY_EXISTS on a replay) or a meter that cannot answer (SYS_SPEND_METER_UNAVAILABLE) ends the request with one error chunk and no model call. The orchestrator heartbeats the lease on each tool iteration and settles when the turn ends, even when the caller stopped reading: consumed when it finished, asked for a tool or streamed text before an error; released when it failed before any output. A reply an output guardrail blocks is refunded. reconcile() settles expired reservations through resolveUnknown.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
This review includes 13 billable files and costs up to $3.25.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Or wait 15 minutes for your next included review. View limit detailsLimit details: You’ve used all 4 included reviews currently available. Review configuration: ⚙️ Run configuration
📒 Files selected for processing (13)
Comment |
Reviewer's GuideThis PR introduces an optional persisted spend meter backed by transactional SQL, then wires it into processRequest and the orchestrator to reserve allowance before provider calls, safely settle or reconcile turns, prevent duplicate charging, and fail closed when allowance or storage is unavailable. Sequence diagram for metered request reservation and settlementsequenceDiagram
participant Client
participant AgentOS
participant SpendMeter
participant Orchestrator
participant Provider
Client->>AgentOS: processRequest(operationId)
AgentOS->>SpendMeter: reserve(accountId, operationId, units)
alt reservation denied or meter unavailable
SpendMeter-->>AgentOS: denied or SpendMeterUnavailableError
AgentOS-->>Client: error chunk
else reservation created
SpendMeter-->>AgentOS: reserved
AgentOS->>Orchestrator: process turn
Orchestrator->>Provider: provider call
Provider-->>Orchestrator: streamed output
Orchestrator->>SpendMeter: settle(operationId, consumed)
SpendMeter-->>Orchestrator: settled
Orchestrator-->>AgentOS: turn response
AgentOS-->>Client: response chunks
end
State diagram for spend reservation lifecyclestateDiagram-v2
[*] --> reserved: reserve
reserved --> reserved: heartbeat
reserved --> consumed: settle(consumed)
reserved --> released: settle(released)
consumed --> released: settle(replaced)
reserved --> consumed: reconcile resolves consumed
reserved --> released: reconcile resolves released or unknown
consumed --> consumed: duplicate settle
released --> released: duplicate settle
released --> reserved: retry operationId
consumed --> [*]
released --> [*]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by QodoReserve persisted spend allowance before provider calls
AI Description
Diagram
High-Level Assessment
Files changed (13)
|
Code Review by Qodo
1. Spend contract types lack public docs
|
| export interface SpendReserveRequest { | ||
| accountId: string; |
There was a problem hiding this comment.
1. Spend contract types lack public docs 📘 Rule violation ⚙ Maintainability
SpendReserveRequest, SpendReserveResult, SpendSettleRequest and several other exported contract types have no leading TSDoc. Consumers reading the reservation and settlement API must infer each type’s purpose from its fields or look elsewhere in the module.
Agent Prompt
## Issue description
Several exported spend-meter contract types have no TSDoc describing their purpose.
## Fix Focus Areas
- src/safety/runtime/SpendMeter.ts[37-38]
- src/safety/runtime/SpendMeter.ts[47-48]
- src/safety/runtime/SpendMeter.ts[69-96]
- src/safety/runtime/SpendMeter.ts[129-138]
## Recommended Fix
Add concise TSDoc immediately before each undocumented exported type, explaining what it represents and any nonobvious behavior.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| export interface SqlSpendMeterOptions { | ||
| db: StorageAdapter; |
There was a problem hiding this comment.
2. Meter options lack public documentation 📘 Rule violation ⚙ Maintainability
SqlSpendMeterOptions and SqlSpendMeter are exported without leading TSDoc, although some of their members are documented. A reader choosing or implementing a store must piece together the options’ overall purpose and the class’s role from individual members and the module overview.
Agent Prompt
## Issue description
The exported SQL meter options and class have no TSDoc on their declarations.
## Fix Focus Areas
- src/safety/runtime/SqlSpendMeter.ts[68-69]
- src/safety/runtime/SqlSpendMeter.ts[110-110]
## Recommended Fix
Add leading TSDoc to both exported declarations, describing their purpose and how the options configure the meter.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| } | ||
| const outcome: SpendOutcome = | ||
| resolution === 'consumed' ? 'consumed' : resolution === 'released' ? 'released' : this.opts.unknownAfterLease === 'consume' ? 'consumed' : 'released'; | ||
| const settled = await this.settle({ operationId: r.operation_id, outcome, now }); |
There was a problem hiding this comment.
3. A heartbeat cannot save a selected turn 🐞 Bug ≡ Correctness
reconcile() selects an expired reservation and later calls settle() without checking whether its lease changed. If the turn heartbeats while resolveUnknown() is pending, reconciliation can still release that now-live reservation and make its allowance available to another request.
Agent Prompt
## Issue description
Reconciliation can settle a reservation after a concurrent heartbeat has renewed it.
## Fix Focus Areas
- src/safety/runtime/SqlSpendMeter.ts[266-276]
- src/safety/runtime/SqlSpendMeter.ts[279-303]
- src/safety/runtime/SqlSpendMeter.ts[227-260]
## Recommended Fix
Make reconciliation's settlement conditional on the reservation still being expired with the lease version or expiry it selected. Add a test that pauses resolution, heartbeats the reservation, then resumes reconciliation.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| `UPDATE agentos_spend_reservations | ||
| SET state = 'reserved', attempts = attempts + 1, account_id = ?, period = ?, units = ?, reserved_at = ?, expires_at = ?, | ||
| outcome = NULL, settled_at = NULL, usage_json = NULL | ||
| WHERE operation_id = ? AND state = 'released' AND attempts < ?`, | ||
| [req.accountId, period, units, now, expiresAt, req.operationId, this.maxAttempts], |
There was a problem hiding this comment.
4. An old turn can charge its retry 🐞 Bug ≡ Correctness
reserve() reuses a released reservation row for another attempt, but settle() identifies the row only by operationId, not by attempt. If reconciliation releases a turn and a retry reserves the same ID before the old turn finishes, the old turn's settlement can consume the retry's reservation and prevent the retry from being counted on its own outcome.
Agent Prompt
## Issue description
A late settlement from an earlier attempt can settle a newer attempt using the same operation ID.
## Fix Focus Areas
- src/safety/runtime/SpendMeter.ts[47-74]
- src/safety/runtime/SqlSpendMeter.ts[184-196]
- src/safety/runtime/SqlSpendMeter.ts[227-260]
- src/api/runtime/AgentOSOrchestrator.ts[1128-1136]
## Recommended Fix
Return an attempt-specific reservation token and require it on heartbeat and settlement, rejecting changes to a newer attempt. Test release, retry, and late settlement in that order.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| CREATE TABLE IF NOT EXISTS agentos_spend_reservations ( | ||
| operation_id TEXT PRIMARY KEY, | ||
| account_id TEXT NOT NULL, |
There was a problem hiding this comment.
6. One account can block another's turn 🐞 Bug ≡ Correctness
agentos_spend_reservations makes operation_id globally unique, while reserve() treats a matching ID as a replay without checking its account. If two accounts generate the same request ID, the second receives an in-flight or already-consumed denial despite having its own available allowance.
Agent Prompt
## Issue description
A request ID used by one account blocks an unrelated account because reservation identity is global.
## Fix Focus Areas
- src/safety/runtime/SqlSpendMeter.ts[49-59]
- src/safety/runtime/SqlSpendMeter.ts[176-194]
- src/safety/runtime/SpendMeter.ts[37-74]
## Recommended Fix
Use account-scoped reservation identity throughout reserve, heartbeat, settle, and reconciliation, or explicitly validate and require globally unique operation IDs at the API boundary. Test identical operation IDs from two accounts.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| if (spendMeter && meteredOperationId) { | ||
| await spendMeter.heartbeat(meteredOperationId).catch((heartbeatError: unknown) => { | ||
| console.warn(`AgentOSOrchestrator: the spend meter's heartbeat failed for stream ${agentOSStreamId}.`, heartbeatError); | ||
| }); | ||
| } |
There was a problem hiding this comment.
5. Long single-pass turns are reclaimed and go uncharged 🐞 Bug ≡ Correctness
_processTurnInternal calls spendMeter.heartbeat only at the start of an outer loop iteration, leaving preparation and a single processTurnStream call—including tool calls, follow-up model calls, and provider streaming—without lease renewal. If that work lasts longer than leaseMs (45 seconds by default) and reconciliation runs, the reservation is released while the turn is active, its later consumed settlement changes nothing, and the same operationId can be reserved again up to maxAttemptsPerOperation without those runs being counted.
Agent Prompt
## Issue description
Active turns can outlive their spend-meter lease during preparation or a single long `processTurnStream` call. Reconciliation can then release the reservation while provider work is still running, so the turn's later settlement does not charge it.
## Fix Focus Areas
- src/api/runtime/AgentOSOrchestrator.ts[691-732]
- src/api/runtime/AgentOSOrchestrator.ts[777-793]
- src/api/runtime/AgentOSOrchestrator.ts[1127-1137]
- src/safety/runtime/SqlSpendMeter.ts[279-305]
## Recommended Fix
When `meteredOperationId` is set, start periodic lease renewal as soon as the reservation is active and keep it running through preparation and streaming. Call `spendMeter.heartbeat(meteredOperationId)` at a fraction of the lease, such as every 10–15 seconds, or use an interval exposed by the meter; log and swallow heartbeat errors. Clear the interval in `finally` before settling. Throttled heartbeats on streamed chunks can supplement this, but must not be the only renewal during waits. Test a turn that lasts longer than its lease while reconciliation runs.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| await trx.run( | ||
| `INSERT INTO agentos_spend_meter (account_id, period, allowance, used, reserved, updated_at) VALUES (?, ?, ?, 0, 0, ?) | ||
| ON CONFLICT (account_id, period) DO UPDATE SET allowance = excluded.allowance`, | ||
| [req.accountId, period, allowance, now], | ||
| ); |
There was a problem hiding this comment.
7. A plan change is undone by the next turn 🐞 Bug ≡ Correctness
reserve reads allowanceFor before its transaction and unconditionally writes that value into the period row, overwriting an allowance set by setAllowance. If allowanceFor still returns the old plan—or a reservation read it before a reduction committed—the next reservation restores the old allowance and may admit a turn after the reduction.
Agent Prompt
## Issue description
`reserve` overwrites the period allowance with an `allowanceFor` value even when `setAllowance` has written a newer value. This can undo a plan change on the next reservation, including when an in-flight reservation read the old plan before the change committed.
## Fix Focus Areas
- src/safety/runtime/SqlSpendMeter.ts[160-168]
- src/safety/runtime/SqlSpendMeter.ts[198-209]
- src/safety/runtime/SqlSpendMeter.ts[330-346]
- docs/safety/SAFETY_PRIMITIVES.md[345-346]
## Recommended Fix
Coordinate allowance reads and writes so a reservation cannot apply an older plan value after a newer allowance update. To address changes made only through `setAllowance`, either store an override flag or column that `setAllowance` sets and skip the reservation's allowance update while it is in force, or document that `allowanceFor` must already return the new plan and that `setAllowance` refreshes the snapshot only until the next reservation. Add a test that pauses a reservation after its allowance lookup, reduces the allowance, then resumes the reservation.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
## [0.13.0](v0.12.24...v0.13.0) (2026-10-08) ### ⚠ BREAKING CHANGE * **speech:** URL output (providerSpecificOptions.outputFormat 'url') downloads only from hosts listed in audioUrlHosts, or in MINIMAX_TTS_AUDIO_URL_HOSTS through SpeechRuntime; without one, synthesize() throws instead of fetching. MiniMaxAsyncSpeechResponse.task_id is number | string instead of string, and file_id is number | string instead of number. ### feat * **safety:** a persisted spend meter that processRequest reserves against before any provider call (#167) ([b9c2e91](b9c2e91)) ### fix * **api:** five defects from a cold read of the gmi() session runner (#165) ([5eec49c](5eec49c)) * **speech:** download MiniMax URL output only from allowed hosts, query async tasks with GET (#166) ([14b86bf](14b86bf))
A persisted allowance per account and period, reserved before a turn reaches any provider and settled when the turn ends. A product that sells a number of turns a month needs the count in a database several servers share, and needs a turn refused before the model is called, not counted after.
What it adds
ISpendMeter(src/safety/runtime/SpendMeter.ts): reserve, settle, heartbeat, reconcile, snapshot, setAllowance;SpendMeterUnavailableError;withBoundedRetryover the transient store errors.SqlSpendMeter(src/safety/runtime/SqlSpendMeter.ts) on a@framers/sql-storage-adapterstore, withSPEND_METER_DDLfor products that run their own migrations. Every write is a conditional statement in one transaction: the reservation row, then the period's row, thenreserved = reserved + n WHERE used + reserved + n <= allowance. A refused step rolls the reservation back. A settle moves the row only from the state it read, so a settle and a reconcile racing on one operation make one transition.AgentOSConfig.spendMeterandAgentOSInput.operationId. With a meter set,processRequestneeds anoperationIdand reserves after the input guardrails and before the orchestrator. A refusal or a meter that cannot answer yields one error chunk and no provider call:BILLING_ALLOWANCE_EXHAUSTED(402),SYS_ALREADY_EXISTSfor a replay of a live or counted operation,SYS_SPEND_METER_UNAVAILABLE(503).finally, so a caller that stopped reading still has its turn counted:consumedwhen the turn finished, asked for a tool, or streamed text before an error;releasedwhen it failed before any output.processRequestrefunds a reply an output guardrail blocked (replaced) and releases a turn the orchestrator never started.docs/safety/SAFETY_PRIMITIVES.md.Without
spendMeternothing changes: no reservation, no new field required.Tests
SpendMeter.contract.ts: the contract as a suite (reserve within and at the allowance, each replay state, the retry cap, settle idempotency, a refund afterconsumed, heartbeat and reconcile withresolveUnknownand the default, a period rollover, a plan change, accounts kept apart).SqlSpendMeter.sqlite.test.ts: the suite on in-memory SQLite; a failing step rolls the reservation back; the shared-store refusal; the bounded retry.SqlSpendMeter.postgres.test.ts(onAGENTOS_TEST_POSTGRES_URL): the suite; twenty concurrent reservations against an allowance of five give exactly five; a settle racing a reconcile makes one transition.agentos-spend-meter.e2e.test.tson the real runtime with the OpenAI stub: a counted turn, thenALLOWANCE_EXHAUSTEDwith one provider call in all; a replay charged once; nooperationId; a meter that cannot answer with zero provider calls; a provider error before output released; an abandoned stream still counted; an output guardrail's block refunded.Summary by Sourcery
Add optional persisted spend metering that prevents uncounted provider calls and safely accounts for each request across retries, failures, and process interruptions.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: