Skip to content

fix(backend): release the chat question when the turn fails after charging (#15287) - #15304

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
t3ratech:fix/chat-quota-release
Sep 21, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
t3ratech:fix/chat-quota-release

Conversation

@t3ratech

@t3ratech t3ratech commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes #15287 — the quota charge lands before the provider call (fail-closed, correct), but a terminal failure left it spent and message.id is minted per request, so a retry charged a second question.

  • llm_usage.release_chat_quota_question: marks the sha256-keyed event doc released and decrements quota_questions in one transaction, into the plan bucket recorded on the event (not the caller's current plan — a plan change between charge and release cannot leak the refund). Idempotent: unrecorded/already-released keys return False.
  • routers/chat.py: best-effort release on both terminal-failure shapes — the stream exception and the not answered error-fallback path. Cancellation keeps the charge (user aborted mid-delivery).

Regression: test_chat_quota_release.py reuses the fake-Firestore harness — release→zero, idempotent retry, ghost-key no-op, bucket attribution, no phantom call_count.

Verified: release exercised against stubbed Firestore (charge→release→0, idempotent, correct bucket); CI runs pytest.

Line-Count-Exception: backend/routers/chat.py | 2214 -> 2234 | +20 lines: one release helper and two call sites inside the existing stream generator; splitting the generator for a 20-line bug fix would obscure the failure-path contract this PR exists to repair.

/claim #15287 PayPal: $BUG_BOUNTY_PAYPAL_EMAIL

Failure-Class: none

…rging

record_chat_quota_question charges the monthly quota before the provider
call (fail-closed on Firestore — correct posture), but nothing gave the
question back when the turn then failed, and message.id is minted per
request so a client retry charged again (BasedHardware#15287).

- llm_usage.release_chat_quota_question: marks the same sha256-keyed event
  doc `released` and decrements quota_questions in one transaction, in the
  plan bucket recorded on the event (not the caller's current plan — a plan
  change between charge and release cannot leak the refund). Idempotent:
  unrecorded or already-released keys return False.
- routers/chat.py: _release_chat_quota_question_best_effort called on the
  two terminal-failure shapes — the stream exception path and the
  not-answered error-fallback path; a release failure never masks the
  original stream failure. Cancellation and partial-answer paths keep the
  charge (the turn was delivered or user-aborted mid-answer).

Test: test_chat_quota_release.py reuses the fake-Firestore harness from
test_realtime_quota_counter — release returns quota to zero, idempotent
retry, ghost-key no-op, decrement lands in the recorded plan bucket and
never mints a phantom call.

Verified: release path exercised against a stubbed Firestore surface
(charge→release→0, idempotent, bucket attribution); CI runs pytest.

Failure-Class: none
@t3ratech

t3ratech commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor Author

/claim #15287 PayPal: [email removed]

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified against #15287 - the charge in _record_chat_quota_question (fail-closed, pre-stream) had no compensating release, and this adds one. Ran the new suite plus the adjacent quota suites on a clean checkout of this head: all green (4 new + 42 quota-counter + 24 chat-quota-router tests).

Per-file notes:

  • backend/database/llm_usage.py - _release_chat_quota_question_transaction mirrors the record transaction's shape well: event read before mutation, released flag + decrement in one transaction, False for both never-recorded and already-released keys (no double-refund on a retried failure path). Reading the plan bucket from the stored event instead of re-resolving _plan_key(uid) is right - a plan change between charge and release refunds the bucket that was actually debited - and count_call=False avoids minting a phantom call_count, which the last test pins.
  • backend/routers/chat.py - hoisting quota_idempotency_key above the charge is the load-bearing change; both release sites (the not-answered fallback and the terminal except Exception inside generate_stream) close over it. CancelledError correctly keeps the charge (user aborted mid-delivery), and the best-effort wrapper means a release failure cannot mask the original stream error.
  • backend/tests/unit/test_chat_quota_release.py - reuses the fake-Firestore harness from test_realtime_quota_counter; release-to-zero, idempotent retry, ghost-key no-op, and plan-bucket attribution (with no phantom call_count) are exactly the regression set this bug calls for. The ENCRYPTION_SECRET literal matches the existing conftest fixture, so nothing new is exposed.

Two minor observations, neither blocking:

  1. Post-answer exception refund: if execute_chat_stream raises after the done frame was already yielded, the except Exception release fires even though an answer was delivered, so the user gets an answered turn refunded. It is refund-biased rather than exploitable (client disconnects raise CancelledError, which skips the release), but gating the release on not answered would tighten it.
  2. The release runs a synchronous Firestore transaction inside the async generator. This mirrors the existing _record_chat_quota_question_best_effort pattern on this path, so it is consistent - if this stream is ever migrated to run_blocking, take the release with it.

One maintainer call before merge: this changes what a failed turn costs. The embedded boundaries - cancelled keeps the charge, degraded-but-answered keeps it, post-answer exception refunds it - are product decisions on a billing surface, so they deserve a quick maintainer sign-off on the semantics even though the implementation checks out.

🤖 Automated review on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge labels Sep 21, 2026

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Verified on b08cd0219ef2.

A terminal failed chat turn now releases the question charged up front, idempotent on the same event doc, into the recorded plan bucket. Four unit tests cover release, retry, never-recorded, and plan bucket.

Not merging.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Releases the charged chat quota question when a turn fails terminally after charging, idempotent on retry, correct plan-bucket attribution. Scoped diff with regression tests, CI green. Confidence 5/5.

@kodjima33
kodjima33 merged commit e102ac1 into BasedHardware:main Sep 21, 2026
54 of 57 checks passed
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
…rging (BasedHardware#15304)

record_chat_quota_question charges the monthly quota before the provider
call (fail-closed on Firestore — correct posture), but nothing gave the
question back when the turn then failed, and message.id is minted per
request so a client retry charged again (BasedHardware#15287).

- llm_usage.release_chat_quota_question: marks the same sha256-keyed event
  doc `released` and decrements quota_questions in one transaction, in the
  plan bucket recorded on the event (not the caller's current plan — a plan
  change between charge and release cannot leak the refund). Idempotent:
  unrecorded or already-released keys return False.
- routers/chat.py: _release_chat_quota_question_best_effort called on the
  two terminal-failure shapes — the stream exception path and the
  not-answered error-fallback path; a release failure never masks the
  original stream failure. Cancellation and partial-answer paths keep the
  charge (the turn was delivered or user-aborted mid-answer).

Test: test_chat_quota_release.py reuses the fake-Firestore harness from
test_realtime_quota_counter — release returns quota to zero, idempotent
retry, ghost-key no-op, decrement lands in the recorded plan bucket and
never mints a phantom call.

Verified: release path exercised against a stubbed Firestore surface
(charge→release→0, idempotent, bucket attribution); CI runs pytest.

Failure-Class: none
Wizard815 pushed a commit to Wizard815/omi-local that referenced this pull request Nov 25, 2026
Brings the fork from the 2026-09-14 merge base (6075928) to upstream
8a1de0d (2026-10-21). 122 conflicts. Upstream's code is the baseline; the
fork's self-hosting changes are re-applied on top, ported into upstream's new
structure where it moved code. Fork commits that were cherry-picks of
upstream PRs (BasedHardware#15202, BasedHardware#15289, BasedHardware#15304, BasedHardware#15317, BasedHardware#15462, BasedHardware#15649) take upstream's
newer version.

Resolution decisions
- Chat: upstream moved the send-message turn into utils/chat_turn.py. That
  call now forwards model_shortcut, so the sticky /adult toggle still works.
  graph.execute_chat_stream keeps the shortcut-routing wrapper around
  upstream's body. upstream already has the async quota release.
- Local LLM: upstream routes every managed get_llm() through the Omi LLM
  gateway (OMI_LLM_GATEWAY_FEATURE_MODE no longer opts out). In local mode
  (is_local_mode()) clients.py now keeps generation on the direct client at
  OPENAI_BASE_URL. model_config keeps the fork's Redis/env model resolution,
  the per-turn shortcut override and local_base_chat_model.
- Conversation notes: upstream serves them only through the shaped notes
  agent and fails closed unless OMI_SHAPED_AGENT_MODE is on, so
  omi-host/entrypoint.sh now exports OMI_SHAPED_AGENT_MODE=on (default).
- Auth: upstream added POST /v1/auth/local-dev/custom-token, gated only on
  FIREBASE_AUTH_EMULATOR_HOST. omi-host always sets that (the emulator is its
  real auth store), so the route would mint a token for any uid.
  OMI_DISABLE_LOCAL_DEV_TOKEN_ROUTE (set by the entrypoint) switches it off.
  The fork's /v1/auth/local-login and remote-login sessions are kept.
- Time zone: upstream added the same PUT /v1/users/time-zone. Keep upstream's
  handler and database.notifications.set_user_time_zone, and drop the fork's
  duplicate setter (it shadowed upstream's) and SaveTimeZoneRequest. The
  app calls upstream's syncUserTimeZoneServer.
- Folders: upstream has no hierarchy, so the fork's folder tree is kept.
  folder_tabs.dart was deleted upstream (folder browsing moved into global
  search), so the subfolder bar, breadcrumb and tree entry were ported into
  global_search.dart and folder_options_sheet.dart.
- Static map: rebuilt on upstream's themed renderer. The no-key
  OpenStreetMap fallback dispatches to _render_osm_png.
- TTS: upstream's provider switch, plus the fork's local Piper path
  (TTS_LOCAL_BASE_URL).
- Subscription/billing: the PROVIDER_MODE=offline early return sits ahead of
  upstream's new funded-compute and budget gates.
- belief_model.py: deleted upstream (BasedHardware#22209) with nothing left importing it,
  so it stays deleted, as do its fork-only tests.
- Vector DB: the fork's LOCAL_VECTOR_DB=chroma path is kept on top of
  upstream's upsert_vector2 metrics and legal-hold gates.
- App:
  - The "/" popup, the sticky shortcut chip and modelShortcut are ported
    onto upstream's composer.
  - The day-review banner stays on Home.
  - The day-review list moves into the Daily Recaps app bar (its Home header
    button went away upstream).
  - LED dim on mute is re-applied after upstream's dispatch-based
    pause/resume.
- Session snapshots: AuthService snapshots recognize a valid remote-login
  session. Upstream's snapshots read it as signed out, which silently
  disabled data export, on-demand recaps and onboarding sync.
- SaaS removals stay removed: referral page and its Settings destination,
  Creator Payouts destination, Crashlytics, the FCM token, and the Google
  sign-in button.
- route_policy_manifest.yaml: upstream's entries plus the fork's 25 routes.
- Generated files:
  - regenerated from the merged sources: app-client OpenAPI spec and its
    Dart/Swift/TS types, flutter gen-l10n;
  - regenerated from requirements.txt by update-python-lock.sh: all
    pylocks, which also restores the e2e packages main's pylock had lost.

Verification (details in the PR):
- flutter analyze: 0 errors; app/scripts/analyze_ratchet.sh passes.
- Backend suites for every touched area pass, among them
  test_local_model_routing (including the new gateway-bypass tests),
  test_chat_model_shortcuts through upstream's run_chat_turn,
  test_nested_folders, test_local_scheduler, test_local_dev_auth plus the
  new self-host opt-out test, test_static_map, and the
  LLM/retrieval/vector suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0148HLrpWR8Mimn43rkNvGKg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A failed chat turn still spends the user's question, and retrying spends another

4 participants