Repository navigation
feat(usage): add shadow unit ledger with zero additional writes - #21369
Conversation
# Conflicts: # backend/config/plan_catalog.py
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Codex Review SummaryThis 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. |
Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 87b1d86fd5
ℹ️ 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".
| if entitlements is None: | ||
| snap = user.get(['subscription']) | ||
| data = snap.to_dict() or {} | ||
| entitlements = resolve_subscription_entitlements(data.get('subscription') or {}) |
There was a problem hiding this comment.
Require period-matched entitlements for historical reads
When period selects a past month and the user has since upgraded, downgraded, or churned, this reads the user's current subscription and returns its budget and entitlement version alongside the historical month's usage. That makes historical utilization incorrect (and an inactive subscription can even be resolved against the current wall clock); either require callers to supply entitlements for non-current periods or load a subscription snapshot corresponding to the requested month.
Useful? React with 👍 / 👎.
Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72ca0376d9
ℹ️ 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".
| transcription_seconds=usage_seconds, | ||
| speech_seconds=usage_seconds, | ||
| idempotency_key=content_id, | ||
| usage_metadata={"funding": "omi", "provider": sync_provider, "source": "sync_v2"}, |
There was a problem hiding this comment.
Preserve BYOK funding for sync v2 transcription
When /v2/sync-local-files runs inline with a validated Deepgram BYOK key and Deepgram is the selected provider, _deepgram_client_for_request() sends the transcription through the user's key, but this unconditional funding: "omi" records the resulting shadow units as Omi-funded. This overstates used_units and the Omi funding total for BYOK sync traffic; carry the successful segment's actual funding provenance into this aggregate instead of hard-coding it.
Useful? React with 👍 / 👎.
| if raw.startswith(('conv_', 'memories', 'memory', 'external_structure')): | ||
| return 'conversation_extraction' |
There was a problem hiding this comment.
Map full conversation feature names to extraction
Gateway calls already use feature names such as conversation_processing, conversation_structure.extract.shadow, and conversation_action_items.extract.shadow, but none starts with conv_, so this classifier records their units under other_llm rather than conversation_extraction. This makes the new per-feature usage report systematically misattribute core conversation-processing spend; include the established conversation_ feature namespace in this branch.
Useful? React with 👍 / 👎.
What changed and why
Shadow usage ledger stacked on #21352 (base
lane/sub-w3-rate-card); merge #21351, then #21352, then this draft. Admission and released subscription payloads retain legacy authority. No enforcement switch or deployment.Project pinned rate-card micro-units into existing hourly usage and gateway day-rollup writes, preserving per-attempt identity, retry costs, funding/provider provenance, completeness, and coverage gaps.
get_usage_units(uid, timezone_aware_month)reads projected hourly records, at most 31 hashed UTC day rollups, and subscription metadata; annual subscriptions still reset monthly. It never scans attempts or user content, and performs zero writes.Repair Firestore
set(merge=True)plan attribution with the shared nested-field expansion primitive. Readers add disjoint historical literal dotted fields to nested counters, including mixed documents, without backfill or rewriting history. Root allowance and finops counters stay intact.Write-cost evidence
0 added writes per event, verified through real production writers against the serializer-aware Firestore fixture in
test_usage_units.py: ordinary hourly 1→1; sync content marker transaction 2→2; immutable gateway attempt + day rollup 2→2; duplicate sync/attempt identity adds no writes. Reader fixture asserts zero writes and 33 reads for a 31-day month. Tests retain root-meter counters and execute the real Firestore protobuf serializer for field paths. This is hermetic write-count evidence, not a live invoice measurement.Verification
BACKEND_UNIT_TEST_FILE_LIST=/tmp/w3-resume/ledger-tests.txt BACKEND_PYTEST_WORKERS=3 bash backend/test.sh: focused ledger, user usage, gateway accounting, nested-field, STT router tests pass. Repository preflight and normal push gate run before publication. No new public endpoint; internal writer/reader behavior exercised through tests. No prod write, provider call, backfill, deployment, or full backend shard.Risks
Product invariants affected
none
UI evidence
UI-Evidence: none -- internal ledger and reporting helpers
Failure class
Failure-Class: none
Restack and review corrections
Merged reviewed #21351 (
60d12adcdad) into #21352 (4245d38efdb), then merged #21352 into this branch, using merge commits throughout. Trialing retains paid legacy entitlements. Free's dormant budget now uses the most expensive Free-routable managed provider because fixed accepted-speech shares are unavailable:(0.0058 + 0.0020) × 60 × 5 × L / 0.001 + 30 × 0.302974 = 4852.703387, rounded up to 4853. Display equivalents use supplied routed provider shares or the conservative default. Gemini audio/tool and reasoning defaults follow the corrected lower card.Initial ledger CI identified two stale expectations: the sync import now binds
record_sync_v1_usage as record_usage, and custom-STT usage carries funding/provider/source metadata. Both assertions are updated; the live flush test still asserts custom-lane fair-use accounting exactly once and no extra write for zero speech delta. The read-aggregation test now expects the reviewed 4853 Free budget. Final focused tests include both full files alongside the ledger, real Firestore serializer, funding/dedup/write-count, pricing, golden and subscription suites.Final validation:
BACKEND_PYTEST_MARK_EXPR='not integration' BACKEND_UNIT_TEST_FILE_LIST=/tmp/w3-resume/final-tests.txt BACKEND_PYTEST_WORKERS=3 bash backend/test.sh;OMI_PR_BODY_FILE=/tmp/w3-resume/ledger-body.md make preflight; normal keepalive push gate. Exact-head GitHub CI status is reported separately, not inferred from local checks.Focused validation result: 344 tests across 13 files pass, with the corrected ledger budget assertion rerun through the same executor. Hermetic layers cover pricing/catalog golden, serializer/write-count/dedup behavior, and live-runtime custom-STT flush behavior. No cloud emulator or deployed product acceptance was run.
r4 review corrections
Lower r4 fixes are merged upward with merge commits. Accepted-speech float conversion and finite/nonnegative validation now run inside
_safe_price; malformed quantities cannot suppress the legacy hourly write even if a price implementation accepts them. Chat prefixes win over realtime/voice/screen substrings, including desktop_chat_realtime, public_shared_conversation_chat, and file_chat. Hourly pricing reuses the lower-card cloud Deepgram normalization.test_usage_units.pyadds malformed/nonfinite accepted-speech legacy-write regressions, feature mapping cases, canonical Deepgram attribution, and a gateway pricing exception regression proving the immutable attempt and existing day rollup both persist with missing shadow coverage and duplicate attempts do not add writes. The explicit catalog mix test fixture is migrated to carry its quantities.Declined: sync v1 funding correction at the aggregate wrapper. Successful per-segment provider/funding is absent; inferring from key presence can misclassify Omi-funded fallback work. The current Omi/unknown estimate can overstate Deepgram BYOK shadow units and is now explicitly documented; a segment-provenance change is needed. Retained: listen's elapsed-counter ×0.32 estimate, as specified; the available VAD counter is not claimed as provider-accepted speech.
Validation: focused ledger/pricing/catalog selection passes 125 tests via
BACKEND_UNIT_TEST_FILE_LIST=/tmp/w3-shadow-tests.txt bash backend/test.sh. The full 13-file stack selection passes 386 tests viaBACKEND_PYTEST_MARK_EXPR='not integration' BACKEND_UNIT_TEST_FILE_LIST=/tmp/w3-final-tests.txt BACKEND_PYTEST_WORKERS=3 bash backend/test.sh. No production data, Stripe writes, flag flips, admission/client changes or deployment in this review round.