Skip to content

feat(budget): idempotency key on cost ingest, shared by route, adapter and scheduler (#21332) - #21971

Merged
mrveiss merged 18 commits into
mainfrom
issue-21332
Nov 22, 2026
Merged

mrveiss merged 18 commits into
mainfrom
issue-21332

Conversation

@mrveiss

@mrveiss mrveiss commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

Refs #21332
Closes #21972

Thinking Path

The owner decided (2026-11-21) that POST /budget/{agent_id}/ingest takes an optional Idempotency-Key, and that internal callers pass their run or cost-event id. The repo already has the canonical replay store (autobot_shared/idempotency.py: SET NX claim, fencing token, stored response, env-backed TTL, used by the HTTP middleware), so it is reused, not rewritten. The check lives in BudgetService.ingest_cost_event, because the native adapter and the scheduler call the service directly and never pass through HTTP; one implementation covers all three paths.

What Changed

  • llc/services/budget_idempotency.py (new): charge_once, a thin layer over the shared store. The key is namespaced by company and agent, so the same key on another agent charges. TTL is the shared AUTOBOT_IDEMPOTENCY_TTL_SECONDS (already registered in ENV_VARS.md and env_registry_backend.py; no new env var).
  • llc/services/budget.py: ingest_cost_event(..., idempotency_key=None); the previous body is now _charge_cost_event (unchanged). No key keeps the old behaviour exactly.
  • llc/api/budget.py: Idempotency-Key header on the ingest route; an in-flight duplicate answers 409.
  • llc/adapters/autobot_agent_adapter.py (_forward_cost) passes run_id; llc/scheduler/heartbeat_scheduler.py / usage_billing.py pass the external run id.
  • Tests: llc/tests/test_budget_ingest_idempotency_21332.py (new); repeated-GET test in test_budget_ingest_commit_before_response_21332.py; _exhaust asserts the ingest response body in test_e2e_04_budget_and_pause.py.

Policies:

  • Concurrent duplicate while the first is in flight: IngestInFlight, 409 on the route. Waiting would hold a worker; charging is the double charge.
  • Redis unavailable or erroring: fail OPEN. The charge runs without dedupe and a warning is logged; a budget is never silently skipped.
  • A hard stop (BudgetExhausted) is a stored result: the repeat re-raises it without charging again.
  • Any other failure releases the claim so the retry can run.
  • With a key, the charge is committed before the result is recorded, so a stored result never points at a rolled-back charge.
  • The existing HTTP Idempotency-Key middleware also sees this header (its own namespace, keyed by actor and path); the two layers do not share keys, and the service layer is the one that covers internal callers.

Remaining AC rows:

Row Status
Repeated GET after ingest sees the post-ingest value done (new test, 5 reads from fresh sessions)
Same key charges once done (route, adapter, scheduler via the service)
_exhaust asserts the ingest response done (response body must carry cost)
FastAPI version against claim (b) recorded in the test docstring: floor fastapi>=0.162.2 (constraints/shared.txt:48; no exact pin exists), read from the constraint, not run
Function-scoped session dependency for the other write routes NOT done; stays on the issue (needs-decision)

Risks

The Redis claim is now only the fast path. The database is the authority (#21972): company_os_cost_events gets a nullable idempotency_key column and a partial unique index over (company_id, agent_id, idempotency_key). The charge inserts the keyed row in its own transaction before it changes spend; only the transaction that inserts it may charge. A loser hits the constraint, its charge never starts, and it returns the winner's stored cost.

  • Closed, each with a test: a claim that expires mid-charge; (a) a crash or failed result store after commit; (b) an ambiguous commit (commit reaches the DB then raises, and the same with CancelledError). A retry after any of them finds the row.
  • Still true: a repeat answered from the database returns the first cost, not a repeated hard stop (only the Redis record keeps the 402); a retry inside window (a) still gets 409 until the claim lapses, but can no longer double-charge.
  • Migration 20261121_120 (down_revision 20261120_117). Open PRs claim 20261121_118 (fix(knowledge): dim-mismatch rebuild invalidates retrieval caches; credential and empty-collection cleanup proposals (#20992) #21835) and 20261121_119 (fix(plugins): plugin trust boundary - opt-in gate, host-side reversal, authenticated marketplace (#17421, #19302, #17266) #21935): re-parent onto whichever lands first. Downgrade drops the index and keeps the nullable column, so no recorded key is deleted.
  • The adapter retries an in-flight ingest with bounded backoff (AUTOBOT_BUDGET_INGEST_RETRY_ATTEMPTS, AUTOBOT_BUDGET_INGEST_RETRY_DELAY_SECONDS, each sleep capped by AUTOBOT_BUDGET_INGEST_RETRY_MAX_DELAY_SECONDS) and logs an error with the run id if it is still in flight after the last attempt.
  • Not done: "commit before answer everywhere" (the llc session dependency). llc/deps.py get_session does not commit at all and routes commit themselves; 44 llc files use a session dependency and there are about 191 write routes, so it fans out. Reported, not started; that is why this PR stays Refs #21332.

Verification

CI gates (no local test run, per owner rule). ruff check and black --check --line-length=120 clean on the changed files; pre-commit hooks passed. Grandfathered heartbeat_scheduler.py is 961 lines, equal to origin/main; llc/api/budget.py is 599 (limit 600).

Model Used

Claude Sonnet 5.5

Single-issue rationale: the owner decision and the remaining rows are all of #21332; nothing else shares these files.

Summary by CodeRabbit

  • New Features
    • Budget cost submissions can now include an idempotency key, so repeated submissions return the original cost instead of charging again.
    • Automated usage billing uses run identifiers to prevent duplicate charges and retries submissions that are still being processed.
  • Bug Fixes
    • Budget submissions now return clearer responses for in-progress duplicates, exhausted budgets and unpriced models.
  • Documentation
    • Added documentation for configuring budget-ingest retry attempts and delays.

@mrveiss mrveiss added the phase:M2.6 Budgets enforced and costs recorded label Nov 21, 2026
@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 16 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3d7ffa7 and 3001d37.

Files ignored due to path filters: 1

  • autobot-frontend/src/types/generated/api.ts is excluded by !**/generated/**
Files selected for processing: 16

  • autobot-backend/llc/adapters/autobot_agent_adapter.py
  • autobot-backend/llc/api/budget.py
  • autobot-backend/llc/exceptions.py
  • autobot-backend/llc/models/company_os_cost.py
  • autobot-backend/llc/scheduler/heartbeat_scheduler.py
  • autobot-backend/llc/scheduler/usage_billing.py
  • autobot-backend/llc/services/budget.py
  • autobot-backend/llc/services/budget_idempotency.py
  • autobot-backend/llc/tests/test_budget_ingest_commit_before_response_21332.py
  • autobot-backend/llc/tests/test_budget_ingest_idempotency_21332.py
  • autobot-backend/llc/tests/test_registry_adapter_rate_limit.py
  • autobot-backend/llc/tests/test_subscription_usage_20266.py
  • autobot-backend/migrations/versions/20261121_120_cost_event_idempotency_key.py
  • autobot-backend/tests/company_os_e2e/test_e2e_04_budget_and_pause.py
  • autobot_shared/env_registry_llc.py
  • docs/developer/ENV_VARS.md
Walkthrough

Cost-event ingestion now supports idempotency keys. The API accepts a key in a request header, while adapter and scheduler paths pass run identifiers as keys. The budget service uses Redis claims and a database unique index to handle keyed charges, replays and in-flight duplicates.

Changes: Budget cost-event idempotency

Layer / File(s) Summary
Keyed charge and replay handling
autobot-backend/llc/models/company_os_cost.py, autobot-backend/migrations/versions/20261121_120_cost_event_idempotency_key.py, autobot-backend/llc/exceptions.py, autobot-backend/llc/services/budget.py, autobot-backend/llc/services/budget_idempotency.py, autobot-backend/llc/tests/test_budget_ingest_idempotency_21332.py
The budget service routes keyed cost events through charge_once and stores the key on each event. A partial unique index covers company, agent and non-null key values. The Redis claim flow handles replays, in-flight requests, charge commits and result recording. Tests cover repeated keys, failures and Redis availability.
API cost-event ingestion
autobot-backend/llc/api/budget.py, autobot-backend/llc/tests/test_budget_ingest_commit_before_response_21332.py, autobot-backend/tests/company_os_e2e/test_e2e_04_budget_and_pause.py
The API accepts an Idempotency-Key header and passes it to the budget service. In-flight duplicates return HTTP 409. Tests check post-ingest budget reads and the exact-remainder response.
Run ID propagation and retries
autobot-backend/llc/adapters/autobot_agent_adapter.py, autobot-backend/llc/scheduler/heartbeat_scheduler.py, autobot-backend/llc/scheduler/usage_billing.py, autobot-backend/llc/services/budget_idempotency.py, autobot-backend/llc/tests/test_budget_ingest_idempotency_21332.py, autobot_shared/env_registry_llc.py, docs/developer/ENV_VARS.md
Adapter and scheduler paths pass run identifiers as idempotency keys. The adapter retries in-flight ingests using configurable attempt and delay limits. Tests verify propagation and retry behaviour. The environment registry and documentation list the retry settings.

Severity of issue fixed: Medium

Merge Risk: Moderate · previous review 3d7ff

Keyed cost ingestion is now deduplicated by the database. One new test expects a double charge when Redis is down, which contradicts that behavior and will fail. A retry after a lost Redis record can also return a pricing refusal instead of the first cost when the pricing cache is cold. Fix the test expectation and the replay lookup order before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: an idempotency key on budget cost ingest. The changeset adds an Idempotency-Key header to the ingest route, a service-level idempotency_key parameter, a Redis-backed c…
Linked Issues check Passed Linked issue #21972 is the only direct target. Its four acceptance criteria are addressed by the reviewed head.

1. Unique (company, agent, key) row in the charge transaction: _record_event passes `…
Out of Scope Changes check Passed All changed areas trace to budget-ingest idempotency for #21972 and its parent context #21332. Changes include: the service-level charge path (budget.py, budget_idempotency.py); the route header a…
Full details: Title check

Explanation

The title names the main change: an idempotency key on budget cost ingest. The changeset adds an Idempotency-Key header to the ingest route, a service-level idempotency_key parameter, a Redis-backed claim with database unique index, and retry logic in the adapter and scheduler. The title is specific and matches the primary change, although it omits the database uniqueness and retry aspects. The title also uses a PR number in parentheses, which is acceptable.

Full details: Linked Issues check

Explanation

Linked issue #21972 is the only direct target. Its four acceptance criteria are addressed by the reviewed head.

  1. Unique (company, agent, key) row in the charge transaction: _record_event passes idempotency_key into CompanyOsCostEvent, and _add_event flushes the row inside a savepoint before _charge_cost_event changes spend. The partial unique index is declared in llc/models/company_os_cost.py (per the summary).
  2. Crash between commit and Redis store: _run_claimed commits before _record. A retry finds the committed row, _charge_once_in_db catches CostEventAlreadyRecorded, and it returns the stored cost. A retry inside the claim TTL gets IngestInFlight (409) and does not charge. The PR states this limit.
  3. Ambiguous commit: the row is written in the charge transaction, so a commit that reaches the database and then raises is found by the retry. _run_claimed releases the claim only for BaseException paths, so a retry after the lapse can still run and finds the row.
  4. Migration 20261121_120 with downgrade: per the summary, downgrade() drops only the index and keeps the nullable column, so no data is deleted. I did not open the migration file directly; this rests on the summary.

Relevant code inspected: llc/services/budget.py diff and llc/services/budget_idempotency.py at the reviewed head.

Full details: Out of Scope Changes check

Explanation

All changed areas trace to budget-ingest idempotency for #21972 and its parent context #21332. Changes include: the service-level charge path (budget.py, budget_idempotency.py); the route header and 409 mapping (api/budget.py); caller forwarding of run IDs (adapter, scheduler, usage_billing.py); the model column, index, migration, and CostEventAlreadyRecorded exception; retry env settings with registry and ENV_VARS.md entries, which support the adapter retry; and tests for these paths, including the _exhaust assertion. The PR does not implement the deferred session-dependency work, so it adds no unrelated change. The retry env vars and the repeated-GET test are supporting changes for the stated objective.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

Copy link
Copy Markdown
Contributor

Notice: 29 open PRs — past the runaway threshold (25)

This is not a request to defer this PR. There is no cap on open PRs (#19397) -- nothing blocks opening or pushing a PR.

This notice only means the count is high enough to be worth a glance for a runaway — something opening PRs in a loop, or a merge pipeline that has stalled so nothing is draining.

Currently open:

If the queue is draining normally, ignore this. Otherwise:

  1. Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
  2. Approved PRs land through the merge train the coordinator sequences (merge commits, never squash) -- check the open chore(merge-train) PR is moving, not each PR on its own
  3. Look for a loop opening near-identical PRs

Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.

@github-actions

Copy link
Copy Markdown
Contributor

✅ SSOT Configuration Compliance: Passing

🎉 No new hardcoded values of either class — ssot and other both block.

Known backlog in pipeline-scripts/hardcoded_values_baseline.txt is suppressed and tracked in #14371.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a087eae and e8b0d8c.

Files selected for processing: 9

  • autobot-backend/llc/adapters/autobot_agent_adapter.py
  • autobot-backend/llc/api/budget.py
  • autobot-backend/llc/scheduler/heartbeat_scheduler.py
  • autobot-backend/llc/scheduler/usage_billing.py
  • autobot-backend/llc/services/budget.py
  • autobot-backend/llc/services/budget_idempotency.py
  • autobot-backend/llc/tests/test_budget_ingest_commit_before_response_21332.py
  • autobot-backend/llc/tests/test_budget_ingest_idempotency_21332.py
  • autobot-backend/tests/company_os_e2e/test_e2e_04_budget_and_pause.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between e8b0d8c and 3d7ffa7.

Files selected for processing: 12

  • autobot-backend/llc/adapters/autobot_agent_adapter.py
  • autobot-backend/llc/api/budget.py
  • autobot-backend/llc/exceptions.py
  • autobot-backend/llc/models/company_os_cost.py
  • autobot-backend/llc/scheduler/usage_billing.py
  • autobot-backend/llc/services/budget.py
  • autobot-backend/llc/services/budget_idempotency.py
  • autobot-backend/llc/tests/test_budget_ingest_commit_before_response_21332.py
  • autobot-backend/llc/tests/test_budget_ingest_idempotency_21332.py
  • autobot-backend/migrations/versions/20261121_120_cost_event_idempotency_key.py
  • autobot_shared/env_registry_llc.py
  • docs/developer/ENV_VARS.md

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Comment thread autobot-backend/llc/services/budget.py Resolved
@mrveiss mrveiss added the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
@mrveiss mrveiss removed the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
@mrveiss mrveiss added the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
@mrveiss mrveiss removed the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
@mrveiss mrveiss added the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
@mrveiss
mrveiss merged commit 51fc69c into main Nov 22, 2026
73 checks passed
@mrveiss
mrveiss deleted the issue-21332 branch November 22, 2026 15:32
@mrveiss mrveiss removed the land-next Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397) label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

phase:M2.6 Budgets enforced and costs recorded

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(company-os): budget ingest idempotency can double-charge across a crash or ambiguous commit

1 participant