Skip to content

feat(safety): a persisted spend meter that processRequest reserves against before any provider call - #167

Merged
jddunn merged 1 commit into
masterfrom
feat/spend-meter
Oct 8, 2026
Merged

jddunn merged 1 commit into
masterfrom
feat/spend-meter

Conversation

@jddunn

@jddunn jddunn commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

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; withBoundedRetry over the transient store errors.
  • SqlSpendMeter (src/safety/runtime/SqlSpendMeter.ts) on a @framers/sql-storage-adapter store, with SPEND_METER_DDL for products that run their own migrations. Every write is a conditional statement in one transaction: the reservation row, then the period's row, then reserved = 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.spendMeter and AgentOSInput.operationId. With a meter set, processRequest needs an operationId and 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_EXISTS for a replay of a live or counted operation, SYS_SPEND_METER_UNAVAILABLE (503).
  • The orchestrator heartbeats the lease on each tool iteration and settles in the turn's finally, so a caller that stopped reading still has its turn counted: consumed when the turn finished, asked for a tool, or streamed text before an error; released when it failed before any output. processRequest refunds a reply an output guardrail blocked (replaced) and releases a turn the orchestrator never started.
  • Docs: a "Spend meter" section in docs/safety/SAFETY_PRIMITIVES.md.

Without spendMeter nothing 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 after consumed, heartbeat and reconcile with resolveUnknown and 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 (on AGENTOS_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.ts on the real runtime with the OpenAI stub: a counted turn, then ALLOWANCE_EXHAUSTED with one provider call in all; a replay charged once; no operationId; 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:

  • Add a persisted, SQL-backed spend meter that reserves account allowance before provider calls and supports settlement, leases, reconciliation, snapshots, and allowance updates.
  • Integrate optional spend-meter enforcement into requests with durable operation IDs, fail-closed denial responses, duplicate protection, and configurable account and unit mapping.

Bug Fixes:

  • Ensure failed, abandoned, or guardrail-blocked turns correctly release or refund reservations while completed turns remain counted.

Enhancements:

  • Add bounded retries for transient storage failures and expose spend-meter runtime APIs and configuration.

Documentation:

  • Document spend-meter configuration, reservation outcomes, and usage.

Tests:

  • Add contract, SQLite, PostgreSQL concurrency, retry, and end-to-end runtime coverage for spend-meter behavior.

…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.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 8, 2026 18:52
@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 2 days and 10 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 13 billable files and costs up to $3.25.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

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.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: f87d9252-79e7-47b6-b92d-c021e0a5e061
📥 Commits

Reviewing files that changed from the base of the PR and between 14b86bf and 839445c.

📒 Files selected for processing (13)
  • docs/safety/SAFETY_PRIMITIVES.md
  • src/api/AgentOS.ts
  • src/api/__tests__/agentos-spend-meter.e2e.test.ts
  • src/api/runtime/AgentOSOrchestrator.ts
  • src/api/types/AgentOSInput.ts
  • src/api/types/OrchestratorConfig.ts
  • src/core/utils/errors.ts
  • src/safety/runtime/SpendMeter.ts
  • src/safety/runtime/SqlSpendMeter.ts
  • src/safety/runtime/__tests__/SpendMeter.contract.ts
  • src/safety/runtime/__tests__/SqlSpendMeter.postgres.test.ts
  • src/safety/runtime/__tests__/SqlSpendMeter.sqlite.test.ts
  • src/safety/runtime/index.ts
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewer's Guide

This 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 settlement

sequenceDiagram
    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
Loading

State diagram for spend reservation lifecycle

stateDiagram-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 --> [*]
Loading

File-Level Changes

Change Details Files
Add a persisted, transactional spend-meter contract and SQL-backed implementation with lease recovery and bounded retries.
  • Define reservation, settlement, heartbeat, reconciliation, snapshot, allowance-update, retry, and error APIs.
  • Persist per-account period counters and operation reservations with conditional transactional updates, idempotent state transitions, plan changes, and concurrent reservation protection.
  • Add schema DDL, shared-store capability validation, reconciler lifecycle, and SQLite/Postgres contract and concurrency coverage.
src/safety/runtime/SpendMeter.ts
src/safety/runtime/SqlSpendMeter.ts
src/safety/runtime/index.ts
src/safety/runtime/__tests__/SpendMeter.contract.ts
src/safety/runtime/__tests__/SqlSpendMeter.sqlite.test.ts
src/safety/runtime/__tests__/SqlSpendMeter.postgres.test.ts
Integrate metering into request admission and turn lifecycle so allowance is reserved before provider execution and settled according to observed output.
  • Add optional AgentOS spend-meter configuration, account/unit mapping, and durable operationId input.
  • Fail closed with validation, allowance, replay, or service-unavailable error chunks before any provider call.
  • Heartbeat active reservations during tool iterations and settle consumed, released, or guardrail-refunded turns in orchestrator and request cleanup paths.
src/api/AgentOS.ts
src/api/types/AgentOSInput.ts
src/api/types/OrchestratorConfig.ts
src/api/runtime/AgentOSOrchestrator.ts
src/core/utils/errors.ts
Document the spend-meter behavior and public configuration model, and verify end-to-end runtime semantics.
  • Document reservation timing, replay behavior, lease reconciliation, failure outcomes, configuration, and usage examples.
  • Test provider-call suppression, counted retries, unavailable meters, early failures, abandoned streams, and output-guardrail refunds against the real runtime.
docs/safety/SAFETY_PRIMITIVES.md
src/api/__tests__/agentos-spend-meter.e2e.test.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Reserve persisted spend allowance before provider calls

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add a shared, persisted allowance that reserves request units before provider calls.
• Settle completed turns, refund blocked replies, and reconcile reservations left by interrupted
 turns.
• Document configuration and test allowance limits, concurrency, retries, and runtime behavior.
Diagram

graph TD
  R["Request"] --> G["Input guardrails"] --> M["Spend meter"] --> O["Turn orchestrator"] --> P["Model provider"] --> C["Response stream"]
  M --> D[("SQL store")]
  M -->|refused| C
  O -->|heartbeat and settle| M
  M -->|reconcile expired| D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Renew leases throughout active turns
  • ➕ Protects reservations during a single long provider call or stream that exceeds the lease.
  • ➖ Requires a timer or other independently managed renewal lifecycle.
2. Use an atomic Redis-backed meter
  • ➕ Could offer lower-latency atomic reservations in deployments already using Redis.
  • ➖ Adds a separate durability and recovery strategy for billing state.

Recommendation: Keep the transactional SQL meter: it fits the requirement for durable, shared accounting and supports conditional, single-transition settlement. Consider independent lease renewal before relying on it for turns that may spend longer than one lease inside a provider call; heartbeats at tool iterations alone do not cover that interval.

Files changed (13) +1326 / -0

Enhancement (8) +709 / -0
AgentOS.tsGate processRequest on spend reservation +97/-0

Gate processRequest on spend reservation

• Adds optional meter configuration and requires an operation ID when enabled. Reserves after input guardrails, returns an error chunk on refusal or failure, and releases unstarted or output-blocked turns.

src/api/AgentOS.ts

AgentOSOrchestrator.tsHeartbeat and settle metered turns +23/-0

Heartbeat and settle metered turns

• Renews the reservation at tool iterations, tracks streamed text, and settles in the turn’s finally block according to completion, tool activity, or failure.

src/api/runtime/AgentOSOrchestrator.ts

AgentOSInput.tsAdd durable operation ID to requests +5/-0

Add durable operation ID to requests

• Introduces the optional operationId field used to identify reservations and recognize retries when metering is configured.

src/api/types/AgentOSInput.ts

OrchestratorConfig.tsPass the meter to the orchestrator +3/-0

Pass the meter to the orchestrator

• Adds an optional ISpendMeter dependency so turn execution can heartbeat and settle reservations.

src/api/types/OrchestratorConfig.ts

errors.tsDefine allowance and meter-unavailable errors +9/-0

Define allowance and meter-unavailable errors

• Adds error codes, HTTP statuses, and user-facing messages for exhausted allowance and an unavailable spend meter.

src/core/utils/errors.ts

SpendMeter.tsDefine the spend-meter contract and retry policy +176/-0

Define the spend-meter contract and retry policy

• Defines reservation, settlement, heartbeat, reconciliation, snapshot, and allowance APIs. Adds an unavailable error and bounded retries for transient storage failures.

src/safety/runtime/SpendMeter.ts

SqlSpendMeter.tsPersist conditional reservations and settlements in SQL +373/-0

Persist conditional reservations and settlements in SQL

• Adds the meter schema and transactional implementation for per-period counters and operation reservations. Supports replay limits, refunds, leases, reconciliation, snapshots, and allowance changes.

src/safety/runtime/SqlSpendMeter.ts

index.tsExport the spend-meter API +23/-0

Export the spend-meter API

• Exposes the meter interface, SQL implementation and DDL, result types, and retry utilities through the safety runtime barrel.

src/safety/runtime/index.ts

Tests (4) +548 / -0
agentos-spend-meter.e2e.test.tsTest metering through the request runtime +179/-0

Test metering through the request runtime

• Uses a provider stub and real runtime to check pre-provider refusals, replay handling, settlement after errors or abandoned streams, and output-guardrail refunds.

src/api/tests/agentos-spend-meter.e2e.test.ts

SpendMeter.contract.tsSpecify shared spend-meter behavior +151/-0

Specify shared spend-meter behavior

• Defines reusable tests for allowance enforcement, replay states, idempotent settlement, refunds, lease expiry, period rollover, plan changes, and account isolation.

src/safety/runtime/tests/SpendMeter.contract.ts

SqlSpendMeter.postgres.test.tsTest shared-store accounting under concurrency +105/-0

Test shared-store accounting under concurrency

• Runs the contract against Postgres when configured and checks simultaneous reservations and a settlement-versus-reconciliation race.

src/safety/runtime/tests/SqlSpendMeter.postgres.test.ts

SqlSpendMeter.sqlite.test.tsTest SQLite accounting, rollback, and retries +113/-0

Test SQLite accounting, rollback, and retries

• Runs the shared contract in memory and verifies transaction rollback, store capability checks, allowance lookup failures, and bounded transient-error retries.

src/safety/runtime/tests/SqlSpendMeter.sqlite.test.ts

Documentation (1) +69 / -0
SAFETY_PRIMITIVES.mdDocument spend-meter behavior and setup +69/-0

Document spend-meter behavior and setup

• Explains reservation outcomes, refusal codes, lease reconciliation, configuration, and an example using a Postgres adapter.

docs/safety/SAFETY_PRIMITIVES.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (5) 📘 Rule violations (2) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Spend contract types lack public docs 📘 Rule violation ⚙ Maintainability
Description
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.
Code

src/safety/runtime/SpendMeter.ts[R37-38]

+export interface SpendReserveRequest {
+  accountId: string;
Evidence
The checklist requires TSDoc for every exported symbol. These newly exported contract types have no
TSDoc before their declarations.

AGENTS.md: Document Exported Symbols and Nonobvious Code: AGENTS.md: Document Exported Symbols and Nonobvious Code
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]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


2. Meter options lack public documentation 📘 Rule violation ⚙ Maintainability
Description
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.
Code

src/safety/runtime/SqlSpendMeter.ts[R68-69]

+export interface SqlSpendMeterOptions {
+  db: StorageAdapter;
Evidence
The checklist requires TSDoc on exported symbols. Both new declarations are exported without a
preceding TSDoc comment.

AGENTS.md: Document Exported Symbols and Nonobvious Code: AGENTS.md: Document Exported Symbols and Nonobvious Code
src/safety/runtime/SqlSpendMeter.ts[65-69]
src/safety/runtime/SqlSpendMeter.ts[108-110]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


3. A heartbeat cannot save a selected turn 🐞 Bug ≡ Correctness
Description
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.
Code

src/safety/runtime/SqlSpendMeter.ts[300]

+      const settled = await this.settle({ operationId: r.operation_id, outcome, now });
Evidence
The due-row query and resolver run before settlement, while heartbeat can update the expiry
independently. Settlement tests the reservation state but not the renewed expiry.

src/safety/runtime/SqlSpendMeter.ts[279-300]
src/safety/runtime/SqlSpendMeter.ts[266-276]
src/safety/runtime/SqlSpendMeter.ts[227-240]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


View action required (2)
4. An old turn can charge its retry 🐞 Bug ≡ Correctness
Description
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.
Code

src/safety/runtime/SqlSpendMeter.ts[R185-189]

+              `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],
Evidence
Retry changes the existing row back to reserved and increments its attempt. Settlement reads and
updates by operation ID and state alone, so it cannot distinguish the old worker from the new
attempt.

src/safety/runtime/SqlSpendMeter.ts[184-196]
src/safety/runtime/SqlSpendMeter.ts[227-260]
src/safety/runtime/SpendMeter.ts[47-74]
src/api/runtime/AgentOSOrchestrator.ts[1128-1136]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


5. Long single-pass turns are reclaimed and go uncharged 🐞 Bug ≡ Correctness
Description
_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.
Code

src/api/runtime/AgentOSOrchestrator.ts[R728-732]

+        if (spendMeter && meteredOperationId) {
+          await spendMeter.heartbeat(meteredOperationId).catch((heartbeatError: unknown) => {
+            console.warn(`AgentOSOrchestrator: the spend meter's heartbeat failed for stream ${agentOSStreamId}.`, heartbeatError);
+          });
+        }
Evidence
Preparation occurs before the first heartbeat, and the heartbeat sits at the top of the outer loop.
The GMI stream is drained inside one withAgentOSSpan call, where the accompanying comment says
tool calls run inside the GMI; awaiting streamed chunks does not trigger another heartbeat.
SqlSpendMeter.reconcile selects reserved rows whose expires_at has passed and settles them as
released by default. A subsequent transition('released', 'consumed') returns null, while
reserve permits a released row to be reserved again if attempts < maxAttempts.

src/api/runtime/AgentOSOrchestrator.ts[726-812]
src/safety/runtime/SqlSpendMeter.ts[279-306]
src/safety/runtime/SqlSpendMeter.ts[183-197]
src/safety/runtime/SqlSpendMeter.ts[365-373]
src/api/runtime/AgentOSOrchestrator.ts[691-732]
src/api/runtime/AgentOSOrchestrator.ts[777-793]
src/safety/runtime/SqlSpendMeter.ts[279-305]
src/safety/runtime/SqlSpendMeter.ts[227-234]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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



Remediation recommended

6. One account can block another's turn 🐞 Bug ≡ Correctness
Description
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.
Code

src/safety/runtime/SqlSpendMeter.ts[R49-51]

+CREATE TABLE IF NOT EXISTS agentos_spend_reservations (
+  operation_id TEXT PRIMARY KEY,
+  account_id TEXT NOT NULL,
Evidence
The reservation primary key contains only operation ID. On conflict, reserve checks the existing
state to deny the operation rather than checking whether the existing reservation belongs to the
requesting account.

src/safety/runtime/SqlSpendMeter.ts[49-59]
src/safety/runtime/SqlSpendMeter.ts[176-194]
src/api/AgentOS.ts[1743-1755]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


7. A plan change is undone by the next turn 🐞 Bug ≡ Correctness
Description
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.
Code

src/safety/runtime/SqlSpendMeter.ts[R199-203]

+          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],
+          );
Evidence
The allowance lookup precedes the reservation transaction, and the reservation upsert and
setAllowance both write the same allowance column without an ordering check. The contract test
shows a reservation reporting remaining: 1 after setAllowance('a', 3), consistent with the
allowance returning to 5 (used 2 plus reserved 2), while the docs describe setAllowance as
applying the new allowance at once without a caveat.

src/safety/runtime/SqlSpendMeter.ts[199-203]
src/safety/runtime/tests/SpendMeter.contract.ts[131-136]
docs/safety/SAFETY_PRIMITIVES.md[345-346]
src/safety/runtime/SqlSpendMeter.ts[160-168]
src/safety/runtime/SqlSpendMeter.ts[198-209]
src/safety/runtime/SqlSpendMeter.ts[330-346]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## 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


Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment on lines +37 to +38
export interface SpendReserveRequest {
accountId: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

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

Comment on lines +68 to +69
export interface SqlSpendMeterOptions {
db: StorageAdapter;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

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 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

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

Comment on lines +185 to +189
`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],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

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

Comment on lines +49 to +51
CREATE TABLE IF NOT EXISTS agentos_spend_reservations (
operation_id TEXT PRIMARY KEY,
account_id TEXT NOT NULL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

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

Comment on lines +728 to +732
if (spendMeter && meteredOperationId) {
await spendMeter.heartbeat(meteredOperationId).catch((heartbeatError: unknown) => {
console.warn(`AgentOSOrchestrator: the spend meter's heartbeat failed for stream ${agentOSStreamId}.`, heartbeatError);
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

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

Comment on lines +199 to +203
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],
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

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

@jddunn
jddunn merged commit b9c2e91 into master Oct 8, 2026
6 checks passed
@jddunn
jddunn deleted the feat/spend-meter branch October 8, 2026 19:00
github-actions Bot pushed a commit that referenced this pull request Oct 8, 2026
## [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))
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