Repository navigation
SCA-1750: add shared watch-only transcription reservations and settlement - #25155
Conversation
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a1cc782faa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| seconds = ( | ||
| max(0, int(accounting['seconds']) - int(accounting.get('charged', 0))) if accounting['updates'] else 0 | ||
| ) | ||
| observe_billed_batch(self.client, binding.owner_id, segment_ids, seconds, now) |
There was a problem hiding this comment.
Preserve billed seconds when replaying batch settlement
If billing commits but the first shadow settlement fails before writing receipts, replay records zero billed seconds. prepare_accounting() returns empty updates for an already-completed ledger (and for an unchanged partial completion), so this expression supplies zero to observe_billed_batch() despite the earlier successful charge. Settlement then creates immutable zero-second receipts and releases the holds, preventing subsequent retries from repairing the missing billed attribution. Recover the settlement amount from the durable billing history rather than whether this attempt needs new usage writes.
Useful? React with 👍 / 👎.
| @sync_attempt | ||
| @sync_snapshot_resolve_job | ||
| @with_batch_privacy_attempt | ||
| @allowance_operation('sync', live=False) |
There was a problem hiding this comment.
Settle sync reservations for terminal silence results
For a free sync upload whose provider calls complete with expected silence, the new scope acquires a reservation, but process_segment() returns false and leaves content_segment_count[0] at zero. The pipeline's usage block therefore never calls record_usage(), while this decorator only marks the scope closed; nothing settles the known zero-charge completion. Because expired holds remain chargeable indefinitely, ordinary completed silence uploads accumulate permanent holds and eventually make unrelated work appear over allowance in the watch data. Explicitly settle zero after a proven terminal silence result, without releasing uncertain failed work.
Useful? React with 👍 / 👎.
| async def _allowance_watch(self) -> None: | ||
| scope = getattr(self, 'allowance_operation', None) | ||
| if scope is not None: | ||
| await scope.monitor() |
There was a problem hiding this comment.
Stop the allowance monitor when the listen session shuts down
On a normal listen disconnect, _run() sets the session shutdown event and awaits drain_monitored(cancel=False) before entering teardown. This new monitored task ignores that event and state.active: Operation.monitor() exits only when scope.closed becomes true, which happens later in teardown's _flush_usage(final=True). Consequently, it forces the drain to exhaust its default 30-second timeout (or the remaining recovery deadline), delaying provider cleanup, final usage settlement, and conversation finalization on every such disconnect—even for paid users or with the watch switch disabled. Make the monitor interruptible by the session shutdown event before awaiting the monitored-task drain.
AGENTS.md reference: backend/AGENTS.md:L304-L304
Useful? React with 👍 / 👎.
| binding = started.get('projection_binding') or {} | ||
| return tx.get('intakes', binding.get('job_id', 'missing')) or {} | ||
|
|
||
| intake = self.protocol.store.run(read_intake) |
There was a problem hiding this comment.
Isolate shadow intake reads from provider dispatch
If this new intake transaction fails, _prepare() propagates the exception after protocol.start() has already committed the unit as running and minted its provider attempt, but before any provider call occurs. On redelivery, the running-state branch enters _reconcile() instead of dispatching: without a result artifact, it waits for abandonment and then consumes the attempt as ABANDONED, potentially terminating the unit as failed-held when failover is unavailable. Thus a shadow-accounting read can prevent transcription and exhaust provider attempts, even with the watch switch disabled. Resolve this metadata before minting the intent, or isolate observation failures so they cannot interrupt dispatch after the intent commits.
Useful? React with 👍 / 👎.
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fac8c24e81
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| data = _operation(user, lease.key).get(transaction=transaction).to_dict() | ||
| if data is None and registered_only: | ||
| continue | ||
| refused = refused or (data or {}).get('had_refusal') is True |
There was a problem hiding this comment.
Preserve per-operation decisions during batch settlement
When a batch projection includes both allowed and allowance-exhausted segments, observe_billed_batch() passes their references together with the aggregate billed duration. Combining had_refusal across those operations here makes prepare_settlement() mark every receipt would_refuse, while assigning the entire duration to the first receipt. For example, an allowed 90-second segment and a refused 10-second segment produce 100 seconds attributed to refusal instead of 10. This corrupts the durable excess-hours evidence used for the rollout reconciliation gate. Settle each operation with its own decision and attributable billed seconds rather than applying one decision to the whole group.
Useful? React with 👍 / 👎.
| reference = self.reference | ||
| if reference is None: | ||
| return |
There was a problem hiding this comment.
Mirror PTT charges when local VAD skips the provider
For a free user's silent REST PTT request, transcribe_voice_message() successfully consumes the audio duration through try_consume_budget() before transcription. However, transcribe_pcm_bytes() and transcribe_voice_message_segment() return immediately on local VAD silence, before any provider observer initializes self.reference. The route's subsequent scope.billed(..., daily_ptt=True) therefore exits here without recording the charged seconds. Unlike the sync silence hold leak, this leaves no hold at all: the shared balance and durable receipts permanently undercount an existing daily-budget charge. Give these billed PTT operations an entitlement-checked settlement identity even when no provider reservation was needed.
Useful? React with 👍 / 👎.
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 99e99d5563
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| prior_decision = previous.get('decision') | ||
| if prior_decision not in {'unobserved', 'would_allow', 'would_refuse'}: | ||
| raise ValueError('invalid batch aggregate decision') | ||
| verdict = 'would_refuse' if refused else prior_decision |
There was a problem hiding this comment.
Preserve observed allow decisions in batch aggregate receipts
For a batch whose units all successfully reserved allowance, the first aggregate receipt is nevertheless marked unobserved: prior_decision starts as unobserved, and this expression only changes it when a refusal occurred. Subsequent settlements preserve that value, so no normal batch can produce a would_allow aggregate. Because these aggregates own all billed seconds while unit receipts carry zero, fully observed, within-allowance batch billing becomes indistinguishable from missing instrumentation in the durable reconciliation evidence. Pass the operations' observed allow state into aggregate settlement while retaining unobserved for genuinely unavailable decisions.
Useful? React with 👍 / 👎.
Co-authored-by: multica-agent <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f1aef24cc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| except Exception: | ||
| # Billing already committed. Never retry billing because telemetry | ||
| # failed; retaining the old hold cannot manufacture free credit. | ||
| logger.warning('event=free_allowance_lease decision=settlement_unavailable') |
There was a problem hiding this comment.
Preserve pending billed seconds across live settlement failures
If a live usage write succeeds but its settlement transaction fails, this handler retains the reference without retaining the billed amount. The next _flush_usage() advances to a new billing window and calls _billed() with only that window's seconds, which then settles the original reference and clears it. For example, a failed settlement of 60 seconds followed by a successful 45-second flush produces an immutable 45-second receipt for 105 billed seconds; a final zero-second flush can instead settle it as zero. Preserve each pending billing window and its amount so subsequent flushes cannot overwrite its settlement evidence.
Useful? React with 👍 / 👎.
| scope = Operation( | ||
| uid, | ||
| 'sync', | ||
| operation=f'cap-hold:{snapshot.id}:{name}', | ||
| seconds=(plan.get(name) or receipts.get(name) or {}).get('seconds'), |
There was a problem hiding this comment.
Restore the allowance reference when replaying recovery receipts
If recovery saves a piece's transcribed receipt and then crashes or fails during billing, the next attempt creates this new scope with reference=None. The persisted receipt skips provider dispatch, so no observer initializes the reference. record_usage() can then successfully commit the charge, but scope.billed() returns without settling the original hold, and the piece is marked processed. This permanently counts both the billed usage and its outstanding hold in the watch balance. Restore the registered operation's settlement reference on receipt replay, including its recorded billing months, without requiring another provider call.
Useful? React with 👍 / 👎.
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: multica-agent <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed9e9a22e5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| free_allowance_executor.submit( | ||
| copy_context().run, self._locked_billed, seconds, daily_ptt=daily_ptt | ||
| ).result(timeout=2.5) |
There was a problem hiding this comment.
Move shadow settlement waits out of serving DB workers
When shadow Firestore operations are slow, this nested executor wait ties up serving DB workers for up to 2.5 seconds per settlement. In the listen path, ListenPersistence.call() runs record_usage() on db_executor, and record_usage() calls scope.billed() before returning; the new PTT routes likewise dispatch scope.billed() through db_executor. Thus the separate shadow pool does not isolate serving capacity: its queued work still occupies serving workers and delays usage flushes and teardown. Move settlement orchestration to the async boundary and await the shadow executor directly rather than waiting on another pool inside a billing worker, as required by the backend's leaf-worker rule.
AGENTS.md reference: backend/AGENTS.md:L286-L287
Useful? React with 👍 / 👎.
Co-authored-by: multica-agent <[email protected]>
…25318) ## Why SCA-1750 is meant to close free-tier allowance leaks. Its watch-only counter (#25155) is serving in production, but a 24h GMP read (ro-prod, aggregates only, to about 2026-11-15T01:40Z) showed it can't judge most free spend: | Path | 24h observations | Problem | |---|---|---| | `live_open` | 8,022 `would_allow`, **5,334 `usage_unavailable`** | about 40% of free live opens can't read usage | | `prerecorded` | **3,055 `would_refuse`**, all reason `identity_unavailable` | none of these are allowance refusals | | batch / upload / sync | **none** | counters are emitted, then dropped before GMP | No enforcement decision can be made until the counter sees these routes. David ruled on 2026-11-15 that the counter is validated by sampling free users, and this fix comes first. ## What changes 1. **Usage epoch on prod listen and pusher.** The Cloud Run billing gate rebuilds and trusts `monthly_usage_totals` docs under `c2fs_20261026_r1` (#24194, 0d18df1). Prod `backend-listen` and `pusher` read the same doc with `v1`, so the watch raised `ValueError('unverified monthly usage')` and reported `usage_unavailable`. - The epoch is now aligned in the prod overlay, the regenerated `runtime_env.yaml` and both prod chart values. - `FIRESTORE_READ_LEVERS` stays at `usage_month_*=0` on GKE, so no legacy reader starts trusting monthly totals. - Dev, jobs and desktop-backend are unchanged. - The served-defaults snapshot and the render test record the new pair. 2. **`unbound` decision.** `observe_unbound` used to emit `would_refuse` when the call had no uid: speaker-sample verification, recovery recognizers and the transcription shadow. It now emits `unbound`. Lease reason `identity_unavailable` is unchanged. - Calls that have a uid but no bound operation still emit `would_refuse` / `billing_scope_unavailable`. - Threading the uid into those callers is required before enforcement, and is left for a follow-up. 3. **Metrics reach GMP.** - `omi_free_allowance_.*` is added to the explicit keep rule in `cloud_run_gmp_sync.yaml` (backend-sync, backend-sync-backfill, backend-integration). - The batch worker's private `/metrics` registry now registers the four allowance collectors, so `batch_gpu` observations are exported. There is no change to serving admission, prices, plans or user-visible behaviour, and no data is deleted. ## Rollback Revert this PR, or delete the two overlay lines and restore `v1` in the two prod chart values, then regenerate. The observer kill switch, `STT_FREE_ALLOWANCE_WATCH_ENABLED=false`, is unchanged. ## Verification - From `backend/`: `pytest tests/unit/test_free_allowance_metrics_are_scraped.py test_free_allowance_session.py test_free_allowance_watch.py test_free_allowance_leases.py test_qualify_usage_month.py test_backend_runtime_env_validator.py test_render_backend_runtime_env.py test_verify_pusher_config_references.py test_batch_pipeline_runtime.py test_quiet_check_metrics_are_scraped.py test_attach_cloud_run_gmp_sidecar.py test_monthly_usage_totals.py test_fsr_s4_caches.py`: 876 passed. - `scripts/check_feature_flag_registry.py`: OK, after regenerating the registry doc. - After serving, readback is the same GMP query: `usage_unavailable` on `live_open` should fall sharply, `unbound` should replace the prerecorded `would_refuse`, and `batch_gpu`, `sync` and `batch_provider` series should appear. ## Product invariants affected - INV-MEM-4: not affected. This change touches no memory promotion path. The citation is only path-triggered (backend Python). ## Failure class (fixes) Failure-Class: FC-metric-dropped-by-scrape-allowlist 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25318?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/25318?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25318&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Concurrent transcription attempts previously observed independent monthly snapshots and could not reserve or reconcile one billing operation. This adds a shared watch-only ledger with stable operation identity, short renewable holds, strict baseline proof, and idempotent settlement after trusted billing commits.
Live (including desktop), upload/recovery, batch GPU/vendor, one-shot and PTT carry authenticated scope into actual spend points. Paid/trial and actual customer-provider-key exemptions precede usage lookup. Unreadable usage and unbound free work produce refusal evidence. Processing observes the same billed-plus-held balance. Existing served policy and client responses stay unchanged.
The batch writer records observer provenance beside its existing hourly billing update. One monotonic
batch_aggregatereceipt owns the committed integer billed total per content/generation; chunked unit receipts carry zero. Unknown pre-rollout provenance remains unavailable. Daily reconciliation must compare cumulative boundary differences against the billing source;settled_atis not an event billing timestamp. Entirely unregistered batches remain a coverage gap to quantify, never fabricated zero usage.Lifecycle integration owns live observer shutdown before task draining and creates no absent-scope lifetime task. Failed PTT providers close before optional shadow settlement can yield, while a finally-protected daily refund survives cancellation during cleanup. Batch settlement is CPU-only and does not expand the GPU import closure.
CI integration retains real operation/metric modules across legacy test package stubs and supplies explicit synthetic entitlements in provider-only fixtures. Idle-off tests check exact idle samples and registration sentinels. M8 excludes only the exact repository-owned
backend/.venvandbackend/.openapi-venvroots; a negative fixture still rejects first-party queues. The strict loopback stack labels REST/background admission origin, verifies every concurrent REST admission, and retains one global named task with identical opaque payload across retries. The branch merges targetmainat0cccb698b35090dbafb32fe355cacb60d88ec720, including default-off upload coalescing and its guards.Validation: 303 unique selected unit cases across 11 files passed through the canonical four-worker file-isolated runner, plus 44 M8 fixtures and the real generated-environment guard. The replay file passed 40 fresh-process runs (31 cases each) after a diagnostic assertion change; its original intermittent timeout was reproduced once and its underlying cause remains unproven. Exact PCM/order/rate/deadline assertions and the existing timeout remain. The full local backend suite is not claimed. That previous candidate had green hosted CI and complete stack evidence, recorded on the issue. The conflict-repair push starts fresh hosted CI; its result is left to the release gates.
Scope/rollout: owner authorization is watch-only reservation, settlement and coverage. No production activation, account reads, credentials, enforcement or old-route removal. No measured savings claimed. Release owner must apply the separate reviewed retention declaration and reconcile a full day of aggregate durable receipts against settled unit-cost excess hours, including unknown scope/duration and orphan holds. Offline/processing enforcement and live clean stopping with SCA-1752 require later authorization. Settlement follows billing in a separate transaction; lost replies retain conservative holds. Active held operations do not expire; receipts/settled operations retain 90 days. Tests do not establish production latency, cost or coverage.
Review order:
database/free_allowance_leases.py(transaction/erasure contract),utils/stt/allowance_session.py(ownership/executor), billing joins in analytics/batch projection/PTT, then provider scopes and change note. Kill switch stops new shadow observations/reservations; confirmed operations can settle.Product invariants affected: none (no served policy or wire change).
Batch pipeline tuning: no serving capacity changes. Shadow states are active/reserved/refused -> settled; expired protected holds await trusted settlement and require reconciliation before enforcement.
Line-Count-Exception: backend/routers/chat.py | 1828 -> 1869 | Attach authenticated PTT scope, mirror daily billing units, and complete failed provider cleanup before shadow settlement; shared ledger remains extracted.
Line-Count-Exception: backend/routers/listen/runtime.py | 1497 -> 1545 | Own live billing clock and observer lifetime beside billing boundaries; shared ledger is extracted.
Line-Count-Exception: backend/utils/stt/pre_recorded.py | 1648 -> 1659 | Pass measured provider durations at spend leaves; reservation ownership lives in the shared scope.
Line-Count-Exception: backend/utils/subscription.py | 1836 -> 1840 | Observe shared balance beside summary and memory policy without changing served results.
Line-Count-Exception: backend/utils/sync/pipeline.py | 4010 -> 4015 | Bind upload billing identity and estimate at the whole-job owner; reservation logic lives in dedicated modules.
Line-Count-Exception: backend/testing/listen_pusher_stack/run.py | 1935 -> 1941 | Verify all four REST admissions independently of background retries while preserving one global durable task; transport tagging remains extracted.
UI-Evidence: none -- Watch-only backend instrumentation preserves served admission and client behavior.
Conflict integration: merge current target
mainrather than rewriting the PR branch. Retain coalescing receipt mirror keys and allowance settlement after durable full completion; retain both independent flag entries (273 total) and both lifecycle writer inventories. Preserve main’s narrower M8 virtualenv-root exclusions, including look-alike first-party-directory coverage. No workflow changes or activation.Conflict repair validation: 2,035 selected backend cases across 10 files passed with the canonical four-worker file-isolated runner; 46 M8 fixtures passed; backend typecheck reports zero errors. Both real loopback Firestore integration suites passed (23 cases), including allowance contention/replay and coalescing receipt/auth/recovery. The auth fixture refreshes its synthetic drainer heartbeat after cold route imports, preserving the production five-second admission threshold. Preflight results are recorded in the issue handoff.