Skip to content

feat(usage): add shadow unit ledger with zero additional writes - #21369

Merged
Git-on-my-level merged 26 commits into
mainfrom
lane/sub-w3-shadow-ledger
Oct 13, 2026
Merged

Git-on-my-level merged 26 commits into
mainfrom
lane/sub-w3-shadow-ledger

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

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

  • Historical projection gaps yield incomplete lower bounds. Existing best-effort attempt/rollup delivery can lose coverage.
  • Most speech counters use elapsed ×0.32; sync counters already apply initial VAD and may underestimate accepted speech. Accepted fractional hooks remain available.
  • Unlisted self-hosted Deepgram uses a labeled provisional proxy. Unsupported rates and unknown funding remain incomplete.
  • MCP/API cache-hit requests have no durable existing writer; zero extra writes leaves explicit coverage gaps. Web-tool infra is provisional and vendor search fees are absent.
  • Loaded rate factor and request placeholder overlap some infrastructure; Luna/Parakeet cards and request estimates are provisional.
  • Ledger annotations pin reviewed v1 SHA-256 782edb7e64afdd72be88e81d03cc7346b46df332881de836a5e7cd6fe8ae32a0. Future revisions require a new card identity; this draft has never written production annotations.

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.py adds 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 via BACKEND_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.

@Git-on-my-level
Git-on-my-level changed the base branch from lane/sub-w3-rate-card to main October 13, 2026 08:27
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 13, 2026 09:57
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T12:07:43.750765Z 72ca037 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +212 to +215
if entitlements is None:
snap = user.get(['subscription'])
data = snap.to_dict() or {}
entitlements = resolve_subscription_entitlements(data.get('subscription') or {})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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"},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +58 to +59
if raw.startswith(('conv_', 'memories', 'memory', 'external_structure')):
return 'conversation_extraction'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 479c8b9 into main Oct 13, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sub-w3-shadow-ledger branch October 13, 2026 12:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant