You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(budget): idempotency key on cost ingest, shared by route, adapter and scheduler (#21332) - #21971
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.
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.
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.
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: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
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
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
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.
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).
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.
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.
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.
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.
If the queue is draining normally, ignore this. Otherwise:
Check whether CI is dispatching at all — see the ci-dispatch-watchdog status on these PRs
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
Look for a loop opening near-identical PRs
Warn-only runaway detector — .github/workflows/pr-queue-gate.yml. It never blocks a merge.
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
mrveiss
removed
the
land-next
Landing set: CI capacity goes to these PRs first (owner direction 2026-09-18, #15397)
label
Nov 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refs #21332
Closes #21972
Thinking Path
The owner decided (2026-11-21) that
POST /budget/{agent_id}/ingesttakes an optionalIdempotency-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 inBudgetService.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 sharedAUTOBOT_IDEMPOTENCY_TTL_SECONDS(already registered inENV_VARS.mdandenv_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-Keyheader on the ingest route; an in-flight duplicate answers 409.llc/adapters/autobot_agent_adapter.py(_forward_cost) passesrun_id;llc/scheduler/heartbeat_scheduler.py/usage_billing.pypass the external run id.llc/tests/test_budget_ingest_idempotency_21332.py(new); repeated-GET test intest_budget_ingest_commit_before_response_21332.py;_exhaustasserts the ingest response body intest_e2e_04_budget_and_pause.py.Policies:
IngestInFlight, 409 on the route. Waiting would hold a worker; charging is the double charge.BudgetExhausted) is a stored result: the repeat re-raises it without charging again.Idempotency-Keymiddleware 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:
_exhaustasserts the ingest responsecost)fastapi>=0.162.2(constraints/shared.txt:48; no exact pin exists), read from the constraint, not runneeds-decision)Risks
The Redis claim is now only the fast path. The database is the authority (#21972):
company_os_cost_eventsgets a nullableidempotency_keycolumn 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.CancelledError). A retry after any of them finds the row.20261121_120(down_revision20261120_117). Open PRs claim20261121_118(fix(knowledge): dim-mismatch rebuild invalidates retrieval caches; credential and empty-collection cleanup proposals (#20992) #21835) and20261121_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.AUTOBOT_BUDGET_INGEST_RETRY_ATTEMPTS,AUTOBOT_BUDGET_INGEST_RETRY_DELAY_SECONDS, each sleep capped byAUTOBOT_BUDGET_INGEST_RETRY_MAX_DELAY_SECONDS) and logs an error with the run id if it is still in flight after the last attempt.llc/deps.py get_sessiondoes 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 staysRefs #21332.Verification
CI gates (no local test run, per owner rule).
ruff checkandblack --check --line-length=120clean on the changed files; pre-commit hooks passed. Grandfatheredheartbeat_scheduler.pyis 961 lines, equal toorigin/main;llc/api/budget.pyis 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