Skip to content

feat(finops): Omi TV cost/revenue accuracy — measured Stripe fees, FinOps-book MRR, software cost per customer - #23289

Merged
Git-on-my-level merged 13 commits into
mainfrom
lane/omi-tv-fixes
Oct 22, 2026
Merged

Git-on-my-level merged 13 commits into
mainfrom
lane/omi-tv-fixes

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Round 6 (2026-10-23): Luna r3 final item — annual SaaS completeness, auto cadence, one-time backfill

Failure-Class: none (round 6 fixes code introduced by this PR; no shipped failure class).

UI-Evidence: none -- round 6 touches finops scripts, the wall lib layer, and tests only; no UI component or visual change.

Luna r3 (rev-23289-luna-r3) resolved everything except finding 4: the mercury_vendor_spend_daily ledger starts 2026-07-04 (~109 days), so it cannot rule out yearly bills, yet mercury_costs.py treated an empty manual annual set as complete. A read-only 13-month Mercury check confirmed real once-a-year charges outside the window (Modal Group, Inc. $12,000 on 2026-01-08; several vendors posting exactly once in 12 months).

  1. Completeness gate. annual_history_complete now requires a full preceding 365 covered days and no above-threshold uncategorized year-window spend — independent of any configured annual vendors (the empty-map loophole is gone). While false, the new annual_history_reason column names the blocking gate (history_under_12_months or uncategorized_above_threshold) in mercury_saas_daily, and the wall's SaaS line keeps the amortized measured value but appends the partial note (e.g. "measured SaaS (Mercury) $X/day (partial: SaaS ledger history under 12 months; one-off vendors amortized ÷12, estimated)"). The old behavior — dropping a short-history day back to the dated constant — is replaced by measured-but-labelled-partial.

  2. Automatic cadence detection (detect_annual_charges) replaces the hand-maintained annual: true list. A saas charge is an annual bill when it repeats about once per 12 months (304–426-day neighbour gap), when it is ≥5× that vendor's other-charge median (≥3 other charges), or — for a vendor seen exactly once — as an ambiguous one-off amortized ÷12 across its service year and reported as estimated in the new annual_estimated_usd column. The vendor map's annual: true remains a manual correction; annual: false means auto-detect. The detector is category-parameterized (CADENCE_CATEGORIES); the run-rate line amortizes only saas rows so STT/LLM cash never double-counts against its own lines.

  3. One-time backfill. FINOPS_MERCURY_BACKFILL_DAYS (91..400) widens a single job run's Mercury pull to N posted days (13 months ≈ 400) — the env route exists because the Cloud Run job invokes the pull with fixed arguments. The aggregate artifact is keyed (date, vendor, category) with duplicate keys rejected, and the loader's per-date delete/insert transaction replaces the window, so re-running the backfill re-derives identical rows — idempotent on (date, vendor). The exact one-time deploy step (gcloud job env update → execute once → remove var) is documented in backend/scripts/finops/README.md. Not run against prod by this round.

  4. Vendor categories from the 13-month check (company names only, no person names): modal group alias (the $12,000 compute wire lands infra_non_gcp — compute, not SaaS — instead of falling to uncategorized other_opex); www deepgram com alias (the $40,758.67 2025-09-08 STT cash wire → stt_vendor, previously unmapped and would have blocked completeness after backfill); named SaaS entries for once-a-year Software posters (vanta $3,500, mintlify $3,034.50) and monthly greptile so detection reads each vendor's own series instead of the blended mercury_category aggregate; Software Costs joins Software & Subscriptions as a saas category-data rule.

Schema note: mercury_saas_daily gains two columns (annual_estimated_usd NUMERIC, annual_history_reason STRING) via the loader's idempotent add-columns path; old rows load NULL and the wall query IFNULLs both.

Backfill step for the lead (one-time, after merge): update the deployed job's env with FINOPS_MERCURY_BACKFILL_DAYS=400 (full list in the README — --set-env-vars replaces the whole set), execute finops-unit-cost-job once, then remove the var (or redeploy from the workflow). After ~13 months of ledger, the SaaS line may flip to complete — subject to the uncategorized year-window gate.

Tests: backend test_finops_mercury.py 31 passed — yearly-repeat, monthly, one-off (estimated), outlier cadence, override, <365-day and gapped history completeness, backfill window validation + byte-identical idempotence, new aliases. web/admin npm run check green (lint/typecheck clean, 1087 tests passed).


Round 5 (2026-10-23): Luna r2 re-review fixes — 1×P1 + 4×P2

Failure-Class: none (all five items fix code introduced by this PR; no shipped failure class).

UI-Evidence: none -- round 5 touches wall lib code, finops scripts, tests, and one deploy workflow's secret-mount logic; no UI component or visual change.

P1 gap/reset days never book Soniox as $0 (web/admin/lib/wall-cost.ts). A covered day with no published spend row (snapshot gap) or a reset row previously took spend ?? 0, silently dropping Soniox spend from the all-in total and cost per customer. Both day kinds now take the labelled fallback — the FinOps usage line when it has the day, else the dated console constant — unmeasured and flagged (snapshot_gap / baseline_reset); an unknown day is never added as $0. The wall text now states the dated estimate covers the day. Tests: wall-cost.test.ts — the reset day carries the constant (the usage line wins when present), the snapshot-gap day carries the constant, and a new all-in test proves a gap day's and a reset day's totals equal a no-series day's total (the total does not drop) while a published row still measures; wall-metrics.test.ts reset-day value/text updated to the new contract.

P2 UGX/ISK backward-compatibility scaling (backend/scripts/finops/pull_stripe.py). Stripe's currencies "Special cases" table (https://docs.stripe.com/currencies#special-cases): "UGX transitioned to a zero-decimal currency, but backwards compatibility requires you to represent it as a two-decimal value, where the decimal amount is always 00. For example, to charge 5 UGX, provide an amount value of 500." — the same rule is documented for ISK; HUF's and TWD's special cases are payout divisibility only ("you can charge two-decimal amounts"), so charges keep the default two-decimal handling. ugx is removed from ZERO_DECIMAL_CURRENCIES; a new TWO_DECIMAL_COMPAT_CURRENCIES = {isk, ugx} set divides by 100 ahead of the zero-decimal set, so a UGX 500 price now reports native UGX 5 (previously UGX 500, 100×; it never entered mrr_usd). Test test_backward_compat_currencies_stay_two_decimal quotes the doc and pins UGX/ISK ÷100 and the HUF/TWD default.

P2 dev-deploy safety for STRIPE_READ_API_KEY. The two bindings this PR added:

  • gcp_finops_unit_cost_job.yml — the workflow's environment input is selectable (development is even the dispatch default), so the read-key mount applied to a non-prod target. It is now required only in prod; a development deploy mounts it only when the secret resource exists in the target project (the same existence-only gcloud secrets describe gate the optional vendor keys use; no payload read). An unprovisioned dev project can no longer fail the job deploy during secret resolution; the Stripe legs then skip as unavailable. New pin: test_deploy_workflow_stripe_mount_cannot_fail_a_dev_deploy.
  • config/public-build-contract.json (admin target) — no non-prod target exists to fail today, evidence: there is no omi-admin-dashboard service in based-hardware-dev (verified 2026-10-23); the repo has no development branch (git ls-remote — the admin workflow's development push trigger cannot fire), and every admin deploy in the workflow run history is prod from main. The only theoretical path is a manual workflow_dispatch with environment=development, which would already fail the deploy-public-build runtime preflight on the ~24 pre-existing WEB_ADMIN_* contract bindings if based-hardware-dev lacks them — this key adds no new class of failure to an unused path. Per the review's own bar ("scope the binding ... or establish the development secret/accessor contract before using those deploy paths"), first use of that path still requires provisioning the dev secret (round 4's deploy-time step 2 stands).

P2 annual SaaS: no annual vendor exists — ledger evidence re-checked. Re-ran the cadence analysis read-only (based-hardware.omi_finops.mercury_vendor_spend_daily, full window 2026-07-04..2026-10-20, vendor/day aggregate sums only, no transaction detail): every SaaS vendor is monthly (same-day-of-month repeats — shopify the 3rd, posthog ~the 7th, nevercode the 1st-2nd, pinecone the 2nd, figma the 18th, sentry the 14th, cognition the 23rd, github the 26th, google_workspace the 1st-2nd), usage-based within a single month (replicate 7 postings 10-06..10-14, klaviyo 5 postings 10-01..10-20), or a $10-scale one-off (vercel $11.25 + $9.99; perplexity $10, not SaaS). An annual bill would be a single large posting per year; none exists in the window. The vendor map therefore keeps zero annual: true entries (pinned by the committed-evidence test, whose docstring now carries the 2026-10-23 re-check), the annual_history_complete gate stays, and the test that a future annual vendor degrades to a labelled partial stays.

P2 refund fee sign follows the documented contract. fee_minor/aggregate_fees no longer claim refunds carry a negative fee (Stripe documents no such shape): fee is "Represented as a positive integer when assessed" (https://docs.stripe.com/api/balance_transactions/object), the funds direction lives in amount ("A positive value represents funds charged to another party, and a negative value represents funds sent to another party"), and the API's own documented example of a funds-out transaction carries fee: 0, fee_details: []. The fixture now uses that documented shape (refund row: negative amount, fee 0, empty details) and a new test pins the handling rule: a non-zero fee on any row is taken with its own sign — an explicitly represented fee return stays negative, a fee assessed on a refund stays positive; no refund-specific sign is invented. The fee_details-sums-to-fee cross-check is unchanged.

INV-DATA-1 (same file as rounds 2/4): round 5 edits .github/workflows/gcp_finops_unit_cost_job.yml again — the Stripe mount becomes prod-required / dev-existence-gated; no job, trigger, or input change, so no ci-budget bump (same precedent as round 4's edit).

Tests. Backend via backend/test.sh + BACKEND_UNIT_TEST_FILE_LIST over the nine finops unit files: 171 passed (3 new — UGX/ISK compat scaling, dev-deploy mount gate, refund-fee sign rule; the refund fixture reshaped to the documented shape). web/admin npm run check (lint + typecheck + vitest): 1086 passed | 13 skipped across 89 files.


Round 4 (2026-10-22): Stripe read vs write split — least privilege

Failure-Class: none (new client split on code introduced in this PR; no shipped failure class).

UI-Evidence: none -- round 4 touches server-side API routes, lib code, CI, and JSON config only; no UI component or visual change.

A restricted read-only Stripe live key (STRIPE_READ_API_KEY, Secret Manager, project based-hardware; accessors finops-writer@ and omi-admin-dashboard-runtime@) now backs every Stripe read in both consumers.

FinOps job. gcp_finops_unit_cost_job.yml mounts STRIPE_READ_API_KEY instead of the full STRIPE_API_KEY; cloudrun.py SECRET_FILES and pull_stripe.py's local .env read are renamed to match — the producer no longer names the full key anywhere (local runs need STRIPE_READ_API_KEY= in the omi-stripe skill .env). The job never needs the full key again. A backend contract test pins the mount name and fails if a full-key Stripe mount line returns.

Admin dashboard (omi-admin-dashboard / admin.omi.me). web/admin/lib/stripe.ts gains getStripeRead() / getOptionalStripeRead() on STRIPE_READ_API_KEY, with a one-time-warned fallback to the full key so a deploy that lands before the secret binding cannot take the wall down. Every read path moved to the read client: the wall's subscription book and live cross-check (lib/wall-metrics.ts), all stats/* Stripe routes (profitability, mrr-trends, subscription-trends, subscriptions, revenue, app-subscriptions), omi/subscriptions, omi/payouts, omi/all-payouts, the organizations routes' payment-intent lookups, and the affiliate-payouts account verification. config/public-build-contract.json binds STRIPE_READ_API_KEY=STRIPE_READ_API_KEY:latest for the admin service.

Write call sites that keep the full key (exhaustive audit of web/admin): exactly one — stripe.transfers.create in app/api/omi/affiliate-payouts/route.ts (POST action=transfer, the affiliate payout, idempotency-keyed). Every other Stripe SDK call in web/admin is a list/retrieve (subscriptions.list, accounts.retrieve, paymentIntents.retrieve, payouts.list); there are no direct api.stripe.com calls and no other .create/.update/.del/.cancel/refund/invoice Stripe calls. The read key's scope was verified live before the switch (read-only GETs): subscriptions, balance transactions, charges, customers, invoices, prices, products, coupons, transfers, subscription schedules, payouts, payment intents, and connected accounts all return 200.

Deploy-time steps for the rollout lead:

  1. On merge, the admin deploy (triggered by the config/public-build-*.json path filter) binds STRIPE_READ_API_KEY on omi-admin-dashboard; omi-admin-dashboard-runtime@based-hardware.iam.gserviceaccount.com already holds secretAccessor. Order cannot break the wall: until the binding lands, reads use the full key with exactly one warning line.
  2. Development env: create STRIPE_READ_API_KEY in based-hardware-dev (a dev-scoped read key) before the next development-branch admin deploy — --set-secrets fails if the resource is missing in the target project.
  3. Re-run the FinOps deploy workflow (workflow_dispatch, prod) from main after merge so the job's mount swaps; the next daily run reads Stripe with the restricted key.

Tests. web/admin +5 in stripe-client-split.test.ts (read client constructed from STRIPE_READ_API_KEY when set and cached separately from the full client; silent when set; full-key fallback warns exactly once; quiet null + getStripeRead error naming both envs when nothing is set; a source-scan pinning that only lib/stripe.ts and the affiliate-payouts write route reference the full-key accessors) — suite 611 passed | 13 skipped, lint + typecheck clean. Backend: mount-contract test added and secret-name pins renamed in test_finops_cloudrun.py; 24 passed across the finops cloudrun/stripe-book/stripe-fees files; check_ci_budget.py passes vs origin/main (no job/trigger/matrix change); line-count ratchet OK.

Round 3 (2026-10-22): Luna review fixes (rev-23289-luna) — all 4 P1 + 6 P2 + CI

P1 stale Soniox series can no longer read as $0 spend or a false reset. The balance series is now bounded by its last covered day (SonioxBalanceInputs.lastDay): a day beyond it falls back to the labelled, dated console constant — unmeasured and flagged — never USD 0 and never a baseline_reset (that label stays reserved for an actual lower cumulative balance, the producer's null-usd row). A covered day with no published row is flagged snapshot_gap. A live series that no longer covers the settled cutoff day marks the STT estimate stale immediately (not only once the 10-16 constant ages past 14 days) and the wall text names the break with the last covered day and as-of. Tests: wall-cost.test.ts (stale series → constant+flag, never $0/reset; snapshot_gap; series bounds; broken → estimate stale now) and wall-metrics.test.ts (wall-level text + no "balance reset" claim on uncovered days).

P1 STT aggregation keeps every vendor separate. The plan-cost BigQuery query now selects the stt_<vendor>_measured component instead of collapsing them into one stt sum; the wall keeps Record<date, Record<vendor, usd>>. Deepgram combines independently: its measured usage when the FinOps line has it, else its own Mercury cash — a Soniox measurement can never hide Deepgram dollars, and a Deepgram-only aggregate is never presented as Soniox. Validated live read-only: the new query runs against prod and returns per-component rows (stt_soniox_measured first row). Tests: wall-cost.test.ts (both-providers day counts both; Deepgram-only day keeps the Soniox constant), wall-finops parse tests.

P1 cost per paying customer uses a payer count over the SAME window as the cost. Denominator = the average of daily paying customers from the FinOps book inside the 30-day cost window (snapshot-day count stated in the metric reason); the window-end snapshot count and the pre-migration subscription-item sum are labelled fallbacks. The producer counts a customer once per plan and once book-wide, never per subscription item: stripe_plan_mrr.json gains paying_customers / non_usd_paying_subs (book-wide, repeated per plan row) and plan_revenue_daily gains them as two new nullable columns, added to the live table by one idempotent ALTER TABLE … ADD COLUMN IF NOT EXISTS in the loader (old artifacts load NULL; the wall query falls back to the legacy column set — verified read-only against prod, where the V2 query fails today and the fallback parses). The wall takes MAX per snapshot day, not the plan-row sum.

P1 zero-decimal currencies are never divided by 100. monthly_amount/coupon amount_off scale minor units by the price/coupon currency per Stripe's documented zero-decimal list (JPY, KRW, VND, …; three-decimal BHD/JOD/KWD/OMR ÷1000). mrr_usd is USD only: a non-USD price keeps its payer counted, reports its native monthly amount per currency (non_usd_mrr_native), and the wall labels MRR partial with the excluded payer count. Tests: test_finops_stripe_book.py (JPY/KRW/VND/KWD scaling, annual ÷12 in native, coupon scaling, non-USD exclusion+counting, JPY ¥1,200 ≠ $12).

P2s. Grafana "STT measured" now carries only measured dollars (Soniox balance/usage + measured Deepgram); modelled Modulate gets its own sand-colored series (sttModulateModelledUsd) and Mercury STT cash its own (sttCashUsd), so the stack still reconciles to the total. Foreign-currency Stripe fee rows surface as a partial label ("N foreign-currency fee rows in the 30d window counted, not converted") instead of silent omission — per the balance-transaction docs, a charge converted into the USD balance already arrives as a usd row with exchange_rate, so non-USD rows are foreign-balance fees with no conversion data of their own. Mercury SaaS days whose annual history is incomplete now keep the dated estimate with the gate named in the text (the wall query carries annual_history_complete; all prod days are currently true, read-only). The Modulate reconciliation sums Mercury cash over the whole window, including cash-only dates. The refund fee test follows the documented contract (fee "positive when assessed"; funds direction in amount; refunds hand fees back via negative fee_details summing to fee, cross-checked — disagreement is a shape error). The deploy workflow mounts the two optional org-key secrets only when the resource exists (gcloud secrets describe gate, existence only, no payload read), so a target project without them cannot block the deploy.

CI at ceed0ee. Backend unit shards 3/6+4/6 failed in the runner's apt-get update inside "Install native audio replay dependencies" (5-minute step timeout, cache already restored — infrastructure stall, unrelated to this PR). Shard 5/6 failed test_sync_silent_failure.py::test_app_keeps_wals_retryable_on_failed_reconcile because main's #23288 moved the pinned app code (case SyncJobFetchOutcome.notFound) from local_wal_sync.dart to wal_job_reconciliation.dart without updating the pin — main's own Backend Unit workflow is red on the same test (runs 39776810910/39777111780); the pin now reads the file where the behavior lives.

Round-3 schema note: plan_revenue_daily gains nullable paying_customers INT64 and non_usd_paying_subs INT64 (the first change to an existing FinOps table in this PR): added by an idempotent loader-side ALTER before the first load that carries them; old artifacts load NULL; the wall falls back to the legacy query until the columns exist (both paths validated read-only against prod).

Round 2 (2026-10-22): measured vendor STT lines on the daily FinOps job

Soniox — exact daily spend from prepaid-balance deltas. The Soniox organization key has no usage/invoice/billing API (all 404); the only readable endpoint is GET /v1/organization/balance. pull_vendor_balance.py (new) snapshots the parsed used_balance_usd / available_balance_usd / invoice_billing_enabled each daily run — artifact and logs carry parsed numbers only, never the key or raw response (pinned by test). The loader writes two new dark-able tables (Schema below) and derives the per-UTC-day rate from consecutive snapshots: a run gap spreads the delta over the missed days and flags them gap_spread; a lower cumulative value (recharge/reset) makes that day unmeasured (usd NULL, flag baseline_reset) and takes the new value as baseline. The whole trailing window is recomputed each run, so the rules can change without backfilling. The wall shows Soniox as measured with its as-of date once ≥2 snapshots exist; until then the labelled dated console constant stays (STALE after 14 days, round-1 rule); a dark table is an explicit unavailable line, never a guess. Optional by design: missing key / 401/403 / transport failure ⇒ status=skipped, job exits 0.

Modulate — modelled volume line + Mercury reconciliation (no API exists). Every Modulate GET path probed returns 404. The line is modelled by construction: pull_prometheus.py gains sum by (provider) (increase(omi_live_stt_audio_seconds_total[1d])) (VAD speech seconds flushed per backend provider), and pull_modulate_modelled.py (new) multiplies the modulate series by the committed, dated price from backend/config/rate_card_v2.json (committed 2026-10-18 @ f6a3589): $0.06/audio-hour — Modulate "Multilingual Transcription" streaming WebSocket list price, platform.modulate.ai (100 credits = $1 ⇒ 6 credits/h), SKU velma-2-stt-streaming, not Velma Triage. The rate card is SHA-pinned by tests; a re-price is a reviewed commit. The wall prints the trailing-30-day reconciliation of the modelled line against Mercury modulate cash (vendor map stt_vendor), variance shown on the STT line; when the modelled line is unavailable the labelled Mercury-cash fallback stays. The Modulate ORG key binding (FINOPS_MODULATE_ORG_KEY) is mounted for a future API only — no code calls a Modulate endpoint with it, pinned by test.

Secret wiring (deploy workflow). cloudrun.py SECRET_FILES gains soniox_org (FINOPS_SONIOX_ORG_KEY) and modulate_org (FINOPS_MODULATE_ORG_KEY); the deploy workflow's --set-secrets mounts both (they exist in based-hardware Secret Manager, readable by finops-writer@…). The producer image now also ships backend/config/rate_card_v2.json for the committed price. Round-1's dark-deploy rule is respected: both new pulls skip cleanly when a mount is missing, and the snapshot/Modulate tables stay dark until the first successful pull.

Schema changes (round 2)

Three new date-partitioned BigQuery tables in based-hardware.omi_finops; no existing table changes schema:

  • vendor_balance_snapshot — date, ts TIMESTAMP, vendor, used_usd NUMERIC, available_usd NUMERIC, invoice_billing_enabled BOOL, run_id, computed_at (one row per successful pull; idempotent per date+vendor).
  • vendor_balance_spend_daily — date, vendor, usd NUMERIC (NULL on a reset day), flag STRING ('' | gap_spread | baseline_reset), interval_start, interval_end, run_id, computed_at.
  • stt_modulate_modelled_daily — date, audio_seconds FLOAT64, usd NUMERIC, price_usd_per_hour NUMERIC, price_as_of DATE, method STRING='modelled', run_id, computed_at.

Deploy tolerance: all three are created only by a first successful pull; skipped artifacts mean no table creation/read/write and the daily job is unaffected. The wall reads them through dedicated readers that cannot fail the plan/STT/SaaS legs (same pattern as stripe_fee_daily). Deploy-time step for the rollout lead: re-deploy finops-unit-cost-job from this branch (the workflow adds the two secret mounts); no other orchestration — the first daily run starts the snapshot series, and the wall switches Soniox to measured on the second day.

Tests (round 2)

  • backend: +38 — test_finops_vendor_balance.py (new, 24: string parsing incl. numeric-lenient + rejects negative/NaN/bool/missing; absent-key skip; 401/403 and error skips; no-key-in-logs across stdout/stderr/artifact; delta math — consecutive days, missing-day spread+flag, reset→new baseline+flag, same-day snapshots, unsorted input, decimal strings; loader dark paths + tampered artifact) and test_finops_modulate_modelled.py (new, 14: committed price pin $0.06/h as-of 2026-10-18, non-card/invalid card rejection, provider filter + bucket→prior-day mapping, seconds×price math, ready/skip artifacts, never-reads-the-org-key). Existing finops family re-run green (119).
  • web/admin: +12 (591 passed total) — sttLineFor balance-delta/gap/reset/constant-below-2-snapshots/modelled-Modulate/Deepgram rules, modulateReconciliation math, parseVendorBalance, dedicated-query isolation, wall line text (measured as-of, reset day, 1/2-snapshots constant, both legs unavailable in missing).

Product invariants affected

  • INV-DATA-1: this PR edits .github/workflows/gcp_finops_unit_cost_job.yml (round 2 adds two Secret Manager mounts for the finops Cloud Run job: FINOPS_SONIOX_ORG_KEY, FINOPS_MODULATE_ORG_KEY; round 4 swaps the Stripe mount to the restricted STRIPE_READ_API_KEY). No mobile/desktop routing authority or retired-GKE ownership is touched; ci-budget.yaml was refreshed with check_ci_budget.py --refresh and validates against origin/main (no trigger or input widening).

What

Makes the Omi TV cost and revenue wall accurate and (for software cost per customer) fully automatic, per David's 2026-10-22 scoping: software cost per customer only — no marketing, hardware or COGS lines are added.

Read-only audit context: data/run-2026-10-12-subscription-overhaul/reports/omi-tv-reconcile-haiku.md (workspace). All BigQuery numbers below are read-only ro-prod queries over the settled window 2026-09-21..2026-10-20, book snapshot 2026-10-21.

The nine items

  1. Stripe fees — measured, scope-gated. pull_stripe.py --end now refreshes the trailing 90 posted UTC days of GET /v1/balance_transactions into raw/stripe_fee_daily.json: per day the signed fee sum across all transaction types (refunds carry a negative fee, so fees are net of refunds on the refund's own day), gross charge/payment volume, row count, and a non-USD count (counted, never summed — no implicit FX). Aggregates only; no identifiers. The loader writes a new FinOps table (see Schema below), dark while the fee source is unavailable. The wall adds the fee leg via a dedicated reader (fetchStripeFeeHistory) that is deliberately outside the plan-cost query, so a dark fee table can never fail the plan/STT/SaaS legs; the wall shows Stripe fees UNAVAILABLE (finops key lacks balance-transaction read scope) and lists it under missing. Never a guess.
    Exact scope needed on the finops Stripe restricted key: Read on the "Balance" category — the permission that authorizes GET /v1/balance_transactions. Today's restricted read key appears to lack it (403 → the skip path); granting it and letting one daily job run is all that is needed — no code change, no backfill (the first run loads 90 days of history). Estimated size when measured: ≈$3.2k/month (audit estimate; not used as data).
  2. Wall MRR = FinOps book. revenue.mrr now uses the latest complete-day plan_revenue_daily snapshot (≤ D-1): coupons applied, annual ÷ 12, trialing excluded, with the snapshot date shown (dataThrough, reason) and the producer computed_at as the freshness watermark. The live Stripe read stays only as a printed cross-check (it applies no coupons, so the delta is the coupon effect made visible); it becomes the value only if the FinOps read fails, with that labelled. arpmau follows automatically.
  3. Anthropic. The Anthropic admin-API leg is counted in per-customer cost only on days it reports non-zero spend (today: $0.00 across the window, confirmed read-only); a zero/off leg is no longer "missing". Mercury anthropic cash now maps to SaaS in mercury_vendor_map.json — it is Claude team seats (~$1.8k/mo), not per-customer cost.
  4. Modulate. Mercury modulate → stt_vendor (already mapped; verified). Round 2 supersedes the cash-as-rate treatment with the modelled volume line above; the cash stays as fallback and monthly reconciliation. Counted once: Soniox Mercury cash is never added (prepaid auto-recharge; near-daily $100–$700 top-ups, 48 payments in the window); Deepgram cash only counts on days with no measured line.
  5. SaaS run rate. The amortization machinery already existed (bill/12 over its 12 service months); the missing piece was the cadence map. Ledger evidence (2026-07-04..2026-10-19, read-only) shows the audit's four suspected "single annual payments" — Shopify, PostHog, Nevercode, Pinecone — are all monthly (same-day-of-month repeats), so the committed map correctly contains no annual vendor, pinned by a test that documents the evidence. inputs_complete now gates only the 30-posted-day cash window; annual-history seeding is its own annual_history_complete signal, so configuring a real annual vendor without the 400-day backfill degrades to a labelled partial instead of dropping the measured line to the $4.8k constant.
  6. STT automation. Round 1 kept the measured usage line and made the console constant a labelled, dated fallback that goes STALE after 14 days. Round 2 replaces both with the measured balance-delta day-rate (above) once ≥2 snapshots exist; the constant survives only for the pre-series transition, still labelled/dated/STALE-bounded.
  7. Staleness. Every cost line states its source and as-of: STT/SaaS constants carry their read dates with per-line staleness thresholds (STT 14d, SaaS 35d) surfaced on the cost frames, estimates frame and margin-status line; MRR carries its snapshot date; the fee line carries measured-through or the unavailable reason; measured SaaS rows keep the existing 3-day freshness gate; round 2 adds the Soniox balance as-of date and gap/reset flags.
  8. Headline metric. Wall stat cost.per_customer_month — software cost per paying customer: the same 30-day all-in software cost as cost/MAU ÷ paying customers from the same FinOps book (3,209 at snapshot 2026-10-21), with a per-plan variable cost per customer/month breakdown (FinOps variable_total ÷ cost-active user-days × 30.44, now pulled in the plan-cost query).
  9. MAU snapshot discrepancy — root cause: definition drift, not window/caching. The 10-15 "real snapshot" (7,163 for [09-13,10-13)) was generated at 09:27 UTC from a hand-built query with the six original wire events. The shipped qualified-v2-2026-10-15 allowlist (commit 474c1105, 12:19 UTC that day — ~3h later, and the file did not exist at the snapshot's pinned commit 95460feb) widened qualification with the macOS UI events and the mobile tab/list/search/action-item events; the same window under the shipped definition is 9,665 (+35%). WAU reproduced because its reference (4,197, 10-05..10-11) was produced under the shipped definition. Fix: a regression test pins the full v2 event inventory, requires every people-counting query to scan every allowlisted event, and the definition-version coupling is documented at DEFINITION_VERSION.

Schema change (producer)

Round 1: new date-partitioned table based-hardware.omi_finops.stripe_fee_daily: date, fee_usd NUMERIC, volume_usd NUMERIC, transaction_count INT64, foreign_transaction_count INT64, run_id, computed_at. Round 2: three further new tables (vendor_balance_snapshot, vendor_balance_spend_daily, stt_modulate_modelled_daily — see the Round 2 section). Round 3: one existing table changes schema — plan_revenue_daily gains two nullable columns (paying_customers, non_usd_paying_subs) via an idempotent loader-side ALTER TABLE … ADD COLUMN IF NOT EXISTS; old artifacts load NULL and the wall query falls back to the legacy column set until they exist. Deploy tolerance: every new table is created only by the first successful pull of its source; skipped sources mean no table creation/read/write and the daily job is unaffected. Loads are idempotent per date via the existing delete/insert transaction.

Before / after (read-only, window 09-21..10-20, book 10-21)

Metric Before (shipped formula) After (this PR)
30-day all-in software cost $82,094 (audit; GCP export net $53,682 + OpenAI $7,011 + Anthropic $0 + STT $6,092 + SaaS $15,309) $82,698 = before + Modulate cash $604.40 + Stripe fees $0 counted (unavailable, listed missing until the key scope lands; audit-estimated ≈$3.2k/mo). Round 2 recomposes the STT line (Soniox balance-delta + Modulate modelled) without changing the all-in total's sources.
MRR live Stripe read, no coupon handling (size unmeasured; FinOps book $75,610) round 2: $75,609.74 (book 2026-10-21). Round 3: latest snapshot $75,477.73 (2026-10-22, read-only) now USD-only — the two JPY subscriptions' yen/100 amounts leave mrr_usd (native sums reported per currency; exact figure printed by the first post-merge run; the contamination was ≈tens of $/mo but semantically yen-as-dollars). Wall marks MRR partial while non-USD payers exist.
Cost per qualified MAU $7.70 (÷ 10,666) $7.75
Cost per paying customer not shown; round 2 ÷ 3,209 item-count = $25.77 round 3: ÷ the same-window average of daily paying customers (item dedup applied) — measured on the first producer run post-merge; lower bound $28.25 (÷ 2,927, the 30-day item-average, 16 snapshot days) and higher per multi-item customer. Round-2 audited numerator $82,698 unchanged (no Deepgram cash in the window, all annual flags true).
ARPMAU live-read dependent $7.09 (book ÷ MAU, same-cutoff when the book day matches)

Tests

  • web/admin: npm test — 591 passed, 13 skipped (76 files) + npm run typecheck + npm run lint clean. Round 1: FinOps-book MRR with live cross-check and fallback, per-customer metric with per-plan variable breakdown, STT vendor-cash rules, fee unavailable naming, Anthropic gating, per-line staleness thresholds, MAU definition-drift pin. Round 2: the vendor STT line tests listed above.
  • backend: BACKEND_PYTEST_WORKERS=4 BACKEND_UNIT_TEST_FILE_LIST=... ./test.sh — round 1: 119 passed (test_finops_stripe_fees.py new, Mercury cadence/annual tests, unit-cost/stt-costs/cloudrun/auth-http green); round 2: +38 in the two new files listed above, with the whole finops family re-run green (157 total across the eight files).
  • The new plan-cost BigQuery query was validated read-only against prod (dry run + shape check: plans/variable rows, stt cash by vendor, saas).

Safety

No prod writes: no BigQuery writes/table changes outside code paths, the FinOps job was not run against prod, all checks were read-only ro-prod queries (aggregates only, no user identifiers). Fee/skip paths keep the daily job deploy-safe, and round 2 keeps the same contract for the balance and Modulate lines. Follow-ups for the orchestrator (no code needed): grant the finops Stripe key Balance read; deploy the job from this branch to mount the two new org-key secrets (the secrets and the SA accessor grants already exist).

View guided diff

Failure-Class: none

…nOps-book MRR, software cost per customer

Producer (backend/scripts/finops):
- pull_stripe.py: measured daily Stripe processing fees from balance
  transactions (fee field, net of refunds, no-implicit-FX), 90-day refresh,
  scope-gated — a restricted key without balance-transaction read skips with
  the exact grant needed and never guesses; the subscription book is unaffected
- load_bigquery.py: new date-partitioned omi_finops.stripe_fee_daily table,
  dark while the fee source is skipped; idempotent per-date loads
- mercury_vendor_map.json: anthropic → saas (Mercury cash is Claude team
  seats, David 2026-10-22); modulate stays stt_vendor
- mercury_costs.py: inputs_complete is the 30-day cash-window gate; annual
  seeding is its own annual_history_complete signal so an unseeded annual
  history cannot drop the measured SaaS line to a manual constant
- README: fee section, cadence evidence (shopify/posthog/nevercode/pinecone
  are monthly per the 2026-07-04..10-19 ledger), reader contract updates

Wall (web/admin):
- wall-finops.ts: paying_subs + refreshed watermark in the book history;
  variable_total plan rows; Mercury STT-vendor cash by vendor; a separate
  stripe-fee reader that cannot fail the plan/STT/SaaS legs
- wall-cost.ts: STT line = measured usage + Modulate/Deepgram Mercury cash,
  Soniox prepaid recharge never a rate; dated Soniox constant goes STALE
  after 14 days; Anthropic API leg counted only when non-zero; Stripe fees
  measured or explicitly unavailable
- wall-metrics.ts: revenue.mrr from the FinOps book snapshot (coupons,
  annual/12, trialing excluded) with the live read as a cross-check; new
  cost.per_customer_month (all-in software cost ÷ paying customers, same
  window) with per-plan variable cost breakdown
- qualified-activity.ts: pin note for the 2026-10-15 MAU definition-drift
  incident (7,163 six-event snapshot vs 9,665 shipped allowlist) + regression
  test pinning the event inventory to every people-counting query
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-22T20:04:00.492671Z f992382 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: f7af21f88b

ℹ️ 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".

"revenue.mrr",
"revenue.arpmau",
"cost.per_mau_month",
"cost.per_customer_month",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Expose the per-customer stat to the TV frames

Adding this ID to HEADLINE_IDS only affects retained-stat freshness; headlineFrames never creates a frame for it, and web/admin/grafana/dashboards/omi-tv-v2.json has no selector or panel for it. Consequently /series/headline, which the TV dashboard consumes, never exposes the newly computed software-cost-per-customer metric, so the headline feature is invisible in production.

Useful? React with 👍 / 👎.

Comment thread web/admin/lib/wall-metrics.ts Outdated
Comment on lines +645 to +649
const plans = finops.mrr[snap];
const usd = Object.values(plans).reduce((s, v) => s + v, 0);
m.value = usd;
m.numerator = usd;
m.denominator = finops.paying[snap] ?? null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the primary MRR calculation product-scoped

When an existing Omi product receives a new Stripe price, the FinOps producer maps subscriptions by price_id and load_bigquery.py drops plans prefixed with unmapped:, whereas the canonical stripe-subscriptions.ts path recognizes every price under an approved product. Making the FinOps totals authoritative here therefore silently undercounts both MRR and the paying-customer denominator until every new price is manually added to the catalog; keep this subscription metric product-scoped or make the producer share the canonical classification.

AGENTS.md reference: web/admin/AGENTS.md:L4-L4

Useful? React with 👍 / 👎.

: " Live Stripe cross-check unavailable."),
refreshed
);
m.dataThrough = `${snap}T00:00:00Z`;

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 the date-only data-through contract

For a normal D−1 FinOps snapshot this changes dataThrough from YYYY-MM-DD to a full timestamp, but the derived ARPMAU block still compares it directly with isoDay(...). That comparison is therefore always false on the new primary path, causing same-cutoff FinOps MRR/MAU to be labeled as a cutoff mismatch and setting materialGap even though both inputs cover the same day.

Useful? React with 👍 / 👎.

Comment on lines +301 to +302
# After the book: a fee-leg skip must never lose the subscription snapshot.
pull_fees(get, raw, a.end)

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 Clear fee artifacts before pulling subscriptions

On a retry using the same deterministic run directory, a subscription request can fail before this call is reached, leaving the previous stripe_fee_daily.json untouched. Because run_unit_cost.py treats the Stripe child as optional and the loader consumes any existing fee artifact afterward, the failed run can publish stale, apparently ready fees; unlink the fee artifact before any Stripe request, not only inside pull_fees after the subscription book succeeds.

Useful? React with 👍 / 👎.

Comment on lines 231 to +232
'annual_history_complete': annual_complete,
'inputs_complete': covered == 30 and annual_complete and uncategorized <= max_uncategorized,
'inputs_complete': covered == 30 and uncategorized <= max_uncategorized,

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 Propagate incomplete annual-history status

Once a vendor is configured with annual: true before a full year has been seeded, this now marks the SaaS row input-complete even while annual_history_complete is false. The admin reader selects only inputs_complete and does not return the annual-history flag, so annual bills older than the seeded window are omitted while the wall presents the result as fully measured rather than the intended disclosed partial; carry this signal through wall-finops.ts and mark the line partial.

Useful? React with 👍 / 👎.

export const FINOPS_HISTORY_QUERY = `
WITH revenue AS (
SELECT FORMAT_DATE('%F', snapshot_date) AS day, plan, mrr_usd,
SELECT FORMAT_DATE('%F', snapshot_date) AS day, plan, mrr_usd, paying_subs,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Count each subscription once in the paying denominator

When a Stripe subscription contains multiple recurring items, pull_stripe.py increments paying_subs inside the item loop, and this new reader then sums that item count as though it were paying customers. Such subscriptions inflate the denominator and understate cost.per_customer_month; aggregate item MRR separately but increment the paying count once per subscription before loading this field.

AGENTS.md reference: web/admin/AGENTS.md:L4-L4

Useful? React with 👍 / 👎.

Comment thread web/admin/lib/wall-series.ts Outdated
retention: ["curve", "retainedHistory", "establishedHistory", "growth"],
revenue: ["finops", "mauPrior", "mauDaily", "shopify"],
health: ["billing", "finops", "mauPrior", "mauDaily", "planCost"],
health: ["billing", "finops", "mauPrior", "mauDaily", "planCost", "fees"],

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 Load cost-source legs for headline cost deltas

headlineFrames calls healthFrames to construct the current and week-prior costPerMau pair, but the headline series still loads only billing and omits the planCost and fees legs added to the health series here. The current point can come from the snapshot with measured STT, Mercury cash/SaaS, and Stripe fees, while the prior point is recomputed with constants and no fees, producing a spurious headline percentage change whenever those measured sources differ; include the same cost legs in LEGS_FOR.headline.

Useful? React with 👍 / 👎.

…late modelled volume

Producer (backend/scripts/finops):
- pull_vendor_balance.py (new): daily snapshot of Soniox
  GET /v1/organization/balance with the ORG key (the only endpoint that does
  not 404); parsed numbers only — never the key or raw response, pinned by
  test; missing key / 401/403 / transport failure => status=skipped, job green
- load_bigquery.py: two new dark-able tables — vendor_balance_snapshot
  (ts, vendor, used/available, invoice flag) and vendor_balance_spend_daily,
  the derived per-UTC-day rate from consecutive snapshots (gap => even spread
  + gap_spread flag; lower cumulative value => unmeasured day + baseline_reset
  flag and a new baseline); trailing window recomputed whole each run;
  load_replace gains a vendor-scoped delete predicate
- pull_prometheus.py: per-provider VAD speech seconds
  (omi_live_stt_audio_seconds_total{provider}) for the Modulate volume
- pull_modulate_modelled.py (new): modulate series x the committed, dated
  rate-card price (rate_card_v2.json, 2026-10-18 @ f6a3589, $0.06/h,
  platform.modulate.ai; SHA-pinned card) into a modelled-only artifact;
  Modulate ORG key is bound but never used to call an endpoint (pinned)
- run_unit_cost.py: balance + modulate optional pulls, skip flags, WARNING
  surfaces for skipped artifacts
- cloudrun.py SECRET_FILES: soniox_org / modulate_org file mounts; workflow
  --set-secrets mounts FINOPS_SONIOX_ORG_KEY + FINOPS_MODULATE_ORG_KEY; the
  image ships rate_card_v2.json

Wall (web/admin):
- wall-finops.ts: fetchVendorBalanceHistory + fetchModulateModelled as
  dedicated readers (a dark table can never fail the plan/STT/SaaS legs)
- wall-cost.ts: STT line = Soniox balance-delta day-rate once >=2 snapshots
  (as-of date, gap/reset flags; reset day unmeasured, never the constant;
  dated console constant only before the series), Modulate modelled volume
  line (Mercury cash as labelled fallback), deepgram cash only without a
  measured line; modulateReconciliation = trailing-30d modelled vs Mercury
  cash variance
- wall-metrics.ts: both legs wired into the billing stack; unavailable legs
  listed under missing; STT reason shows Soniox measured as-of / reset /
  constant-with-snapshot-count and Modulate modelled price + recon variance

Tests: backend +38 (test_finops_vendor_balance.py 24, test_finops_modulate_modelled.py 14;
string parsing, delta math incl. missing day + reset, absent-key fallback, no-key-in-logs);
web/admin 591 passed (+12). Live read-only check confirmed the balance payload shape
(strings + bool, extra fields ignored).

@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: ceed0ee835

ℹ️ 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 thread web/admin/lib/wall-cost.ts Outdated
const cash = sttCash?.[date] || {};
const usage = sttMeasured?.[date];
const bal = sonioxBalance;
const inSeries = !!bal?.ready && date >= bal.firstDay;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bound the Soniox series at its latest snapshot

When at least two snapshots have ever existed but the latest snapshot predates the requested billing day—for example, after the organization-key or balance API pull skips a day—this lower-bound-only check still marks the day as inside the series. Because that day has no spend row, the branch below converts the missing value to $0 and labels it a baseline_reset, understating the all-in cost; dates after asOf should remain unavailable or use the fallback, while baseline_reset should be reserved for an explicit null row.

Useful? React with 👍 / 👎.

Comment thread web/admin/lib/wall-series.ts Outdated
Comment on lines +726 to +730
{
sttMeasured: legs.planCost?.sttMeasured,
sttCash: legs.planCost?.sttCash,
saasMeasured: legs.planCost?.saasMeasured,
stripeFees: legs.fees,

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 Load the new STT sources into the wall series

The snapshot path supplies sonioxBalance and modulateModelled, but this series path supplies only the legacy measured aggregate, Mercury cash, SaaS, and fees; SeriesSources, Legs, and legJobs likewise have no balance or Modulate legs. Consequently the health history—and the headline cost delta derived from it—continues using the console/legacy and cash fallbacks even when the new balance-delta and modelled tables are populated, so it disagrees with the current cost stat.

Useful? React with 👍 / 👎.

Comment on lines +211 to +215
export const FINOPS_STRIPE_FEE_QUERY = `
SELECT FORMAT_DATE('%F', date) AS day, fee_usd
FROM \`based-hardware.omi_finops.stripe_fee_daily\`
WHERE date >= DATE_SUB(@today, INTERVAL @days DAY) AND date <= @today
ORDER BY day`;

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 Expose foreign Stripe fees as incomplete

When a day contains any non-USD balance transaction, the producer intentionally excludes that transaction's fee from fee_usd and records it in foreign_transaction_count, but this query discards the count. Downstream code therefore labels the remaining USD subtotal as measured and adds it to the all-in total without any partial or missing indication, understating software cost on those days; propagate the foreign count so the line can be marked incomplete, or convert those fees using an explicit FX source.

Useful? React with 👍 / 👎.

const missing: string[] = [];
if (coverage.openai === false) missing.push("OpenAI invoice");
if (coverage.anthropic === false) missing.push("Anthropic invoice");
if (feesUnavailable) missing.push("Stripe processing fees");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the missing Anthropic API cost signal

When the Anthropic admin-cost read is unavailable, computeInfraCosts explicitly sets coverage.anthropic to false and marks its payload partial, but this missing-line list no longer records Anthropic. allInCost then converts the null leg to $0 and publishes understated daily and 30-day costs; reclassifying Mercury's Anthropic transactions as team-seat SaaS does not prove that unknown API usage is zero, so the unavailable API leg must remain disclosed as missing.

Useful? React with 👍 / 👎.

Comment on lines +277 to +281
for (const [day, row] of Object.entries(modelled.byDay)) {
if (day < start || day > end) continue;
modelledUsd += row.usd;
cashUsd += sttCash?.[day]?.modulate ?? 0;
observed++;

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 full coverage for the 30-day Modulate reconciliation

During the first month after rollout, or whenever Prometheus omits one or more daily samples, modelled.byDay contains fewer than 30 rows. This loop nevertheless compares only those observed modelled days with Mercury cash from the same subset and the caller labels the result a "30d reconciliation," which can report a misleading variance while silently excluding the missing days; require the requested number of daily rows or propagate the observed-day count and label the comparison partial.

Useful? React with 👍 / 👎.

…TT, customer denominator, zero-decimal currencies

Luna review rev-23289-luna.md, all 4 P1 + 6 P2:

P1 Soniox staleness: the balance series is bounded by its last covered day
(SonioxBalanceInputs.lastDay); days beyond it fall back to the dated console
constant, unmeasured and flagged — never $0 spend or a phantom baseline_reset
(reset stays reserved for an actual lower cumulative balance; a covered day
with no row is 'snapshot_gap'). A series that no longer covers the cutoff day
marks the STT estimate stale immediately and the wall text names the break.

P1 per-vendor STT: the plan-cost query keeps stt_<vendor>_measured components
separate; Deepgram combines independently (measured usage, else its own Mercury
cash) so a Soniox measurement never hides Deepgram dollars and a Deepgram-only
aggregate is never presented as Soniox.

P1 denominator: cost per paying customer uses the average of daily paying
customers over the same 30-day window as the cost (stated; window-end count
and the pre-migration item sum are labelled fallbacks). The producer counts a
customer once per plan and book-wide (paying_customers, non_usd_paying_subs:
two new nullable plan_revenue_daily columns, added to a live table by one
idempotent ALTER TABLE in the loader; old artifacts load NULL; the wall query
falls back to the legacy shape while the columns are absent).

P1 zero-decimal currencies: minor units scale by the price's currency per
Stripe's zero-/three-decimal lists (JPY is never ÷100); mrr_usd is USD only —
non-USD payers stay counted, native amounts reported per currency, wall labels
MRR partial.

P2: grafana 'STT measured' carries only measured dollars (Soniox balance/usage
+ measured Deepgram); Modulate modelled and Mercury STT cash become their own
series. Stripe fees: documented fee contract (fee positive when assessed;
refunds hand fees back via negative fee_details summing to fee — cross-checked,
disagreement is a shape error) and foreign-currency fee rows surface as a
partial label instead of silent omission. Mercury SaaS days with incomplete
annual history gate to the dated estimate (annual_complete in the wall query);
the annual flip rule is documented with the Jul-Oct ledger evidence that no
vendor qualifies. Modulate reconciliation sums Mercury cash over the whole
window, including cash-only dates. The workflow mounts the two optional
org-key secrets only when the resource exists, so a non-provisioned target
project cannot block the deploy.

CI: test_sync_silent_failure's app-source pin follows #23288's move of the
reconcile code to wal_job_reconciliation.dart (main itself is red on the old
pin).

@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: c3da2e7450

ℹ️ 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".

raise BalanceError("balance transport/JSON failure") from None


def pull(raw: pathlib.Path, now: dt.datetime | None = None) -> None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add a CLI entry point for the balance pull

When the daily job executes python pull_vendor_balance.py --raw ..., this module only defines pull and daily_deltas; it has no argument parser or if __name__ == "__main__" invocation. The process therefore exits successfully without writing vendor_balance_snapshot.json, so the job reports the optional step as successful while the Soniox snapshot and spend tables remain permanently dark; expose --raw and call pull() from the script entry point.

AGENTS.md reference: backend/AGENTS.md:L238-L245

Useful? React with 👍 / 👎.

p = it["price"]
plan = price_plan.get(p["id"], "unmapped:" + p["id"])
currency = (p.get("currency") or "usd").lower()
m = apply_coupon(monthly_amount(p, it.get("quantity") or 1), s)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Apply fixed coupons before monthly normalization

For an amount_off discount on an annual price, monthly_amount has already divided the invoice amount by 12 before this call; for example, $120/year with $12 off becomes max(0, $10 - $12) = $0 MRR instead of ($120 - $12) / 12 = $9. Because this call is also inside the item loop, a subscription-level fixed coupon is subtracted once per item. This understates the newly authoritative FinOps MRR for annual or multi-item fixed-coupon subscriptions; apply the fixed discount once to the invoice subtotal before normalizing it.

Useful? React with 👍 / 👎.

}
)
rows.sort(key=lambda x: -x["mrr_usd"])
book = summarize_book(subscriptions(), price_plan)

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 Clear the Stripe book before subscription pagination

On a retry in the same deterministic run directory, any failure while paging subscriptions occurs before stripe_plan_mrr.json is replaced. Since run_unit_cost.py launches this pull with required=False, the pipeline continues and build_rows consumes the previous artifact, publishing stale MRR and payer counts as the current FinOps book; remove or invalidate the book artifact before the first subscription request.

Useful? React with 👍 / 👎.

Comment on lines +16 to 18
MAX(paying_customers) OVER (PARTITION BY snapshot_date) AS paying_customers,
MAX(non_usd_paying_subs) OVER (PARTITION BY snapshot_date) AS non_usd_paying_subs,
ROW_NUMBER() OVER (PARTITION BY snapshot_date, plan ORDER BY computed_at DESC) AS rn

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 Select one producer run for each FinOps snapshot

When Cloud Run gap-fills multiple usage dates on the same UTC day, each run writes the same snapshot_date into a different date partition. These windows can then mix runs: a plan absent from the latest run survives through its older per-plan row, while a decreased customer count is replaced by the older maximum, so the authoritative MRR and denominator do not describe any actual subscription snapshot. Rank one run_id/computed_at per snapshot_date first and select every plan and count from that run.

Useful? React with 👍 / 👎.


stripe_fees = raw / "stripe_fee_daily.json"
if stripe_fees.exists() and json.loads(stripe_fees.read_text()).get("status") == "skipped":
sys.stderr.write("WARNING: Stripe fee line unavailable; see pull.log\n")

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 Forward the new optional-source warnings from Cloud Run

During a successful Cloud Run execution, this new warning is captured in cloudrun_entry.py rather than sent directly to Cloud Logging, and that wrapper forwards only lines beginning with WARNING: Mercury. The Stripe, Soniox, and Modulate warnings added here are therefore silently discarded in the production path, leaving operators without the promised signal when those cost sources go dark; extend the wrapper's successful-child warning allowlist to include the new sources.

Useful? React with 👍 / 👎.

Comment on lines +1152 to +1155
if (paying == null && m.denominator) {
paying = m.denominator;
basis =
"denominator = subscription-item sum (book predates the paying-customers column)";

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 payer history when restoring cached metrics

When an unrelated retryable source triggers a wall recomputation within the 15-minute source TTL, the guarded MRR job restores revenue.mrr from WallJobCache and skips its callback, leaving the invocation-local windowFinops null. This fallback then replaces the intended average of daily paying customers with the latest snapshot denominator and incorrectly labels it an item sum, so cost.per_customer_month changes solely according to cache state; retain the FinOps history alongside the cached metric or leave the already-restored derived metric untouched.

Useful? React with 👍 / 👎.

# Conflicts:
#	backend/tests/unit/test_sync_silent_failure.py

@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: 9200f67ba3

ℹ️ 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".

const stt = sttLineFor(d.date, vendor);
const measuredSaas = vendor.saasMeasured?.[d.date];
const saas = measuredSaas ?? saasEstimate;
const fees = feesUnavailable ? null : vendor.stripeFees?.[d.date] ?? null;

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 Treat a missing daily fee row as unavailable

When the fee table already exists but the latest producer run skips fees, fetchStripeFeeHistory still succeeds using historical rows, so feesUnavailable remains null while this lookup returns null for the cutoff day. The total then adds that null as zero and publishes an understated cost without adding Stripe fees to missing; detect the absent cutoff row as an unavailable fee leg rather than treating it as a zero-fee day.

Useful? React with 👍 / 👎.

Comment on lines +845 to +846
{ STT: last.sttMeasured },
{ STT: sonioxBroken && !last.sttMeasured }

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 Base Soniox estimate freshness on the Soniox leg

When Deepgram has measured usage but Soniox is using the dated console fallback—for example after the balance snapshot series stops—last.sttMeasured is still true because it combines all providers. That suppresses both age-based and broken-feed staleness for the Soniox estimate, so the dominant fallback can be presented as current indefinitely; use last.sttSonioxMeasured for the Soniox estimate status.

Useful? React with 👍 / 👎.

Comment on lines +363 to 366
("sttModulateModelledUsd", "Modulate modelled", "number"),
("sttEstimateUsd", "STT est.", "number"),
("saasMeasuredUsd", "SaaS measured (Mercury)", "number"),
("saasEstimateUsd", "SaaS est.", "number"),

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 Add Stripe fees to the cost stack

When measured fee rows are available, healthFrames emits fees and includes them in total, but this target skips directly from the SaaS fields to revenue without selecting the fee field. The visible stacked bars therefore understate cost by the processing fees and no longer reach the hidden all-in total despite the panel claiming that its stack top equals Cost / day; add a displayed Stripe-fee series and its styling.

Useful? React with 👍 / 👎.

…eads suffice

FinOps job: mount Secret Manager STRIPE_READ_API_KEY (restricted, read-only)
instead of the full STRIPE_API_KEY; cloudrun.py SECRET_FILES and pull_stripe.py's
local env read renamed to match. The job never needs the full key again; a
backend contract test pins the mount and that no full-key Stripe mount returns.

Admin dashboard (omi-admin-dashboard): web/admin/lib/stripe.ts gains
getStripeRead()/getOptionalStripeRead() on STRIPE_READ_API_KEY with a one-time
warned fallback to the full key so deploy order cannot break the wall. Every
read path (wall subscription book + cross-check, all stats routes, omi
subscriptions/payouts/all-payouts, organizations payment-intent lookups,
affiliate account verification) moves to the read client. The full-key client
remains only for the affiliate transfer write (stripe.transfers.create).
config/public-build-contract.json binds STRIPE_READ_API_KEY for the admin
service. Source-scan + client-split unit tests pin the split.

Read-key scope verified live (read-only GETs): subscriptions, payouts,
payment intents, accounts, transfers, balance transactions all 200.
Conflict resolution: main's #23279 role-based admin auth (requireScope,
hasScope, authResult.json) taken everywhere; this lane's Stripe read-client
split re-applied on top (getStripeRead/getOptionalStripeRead in the read
routes and test mocks; affiliate-payouts keeps the full key only for
stripe.transfers.create).

@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: 1ee8aa750d

ℹ️ 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".

"interval_end": cur["ts"],
}
)
return rows

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Invoke the vendor balance pull from the script entrypoint

The module ends after defining daily_deltas and never parses --raw or calls pull(). Consequently, the run_unit_cost.py subprocess exits successfully without creating vendor_balance_snapshot.json, so scheduled runs never collect Soniox snapshots and the new balance-derived cost tables remain dark even when the organization key is mounted.

Useful? React with 👍 / 👎.

}
)
rows.sort(key=lambda x: -x["mrr_usd"])
book = summarize_book(subscriptions(), price_plan)

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 Clear the fee artifact before fetching subscriptions

When a run reuses the same run directory and the Stripe authentication or subscription request fails here, execution never reaches pull_fees(), which is currently the only place that unlinks the prior stripe_fee_daily.json. Because this pull is optional, the pipeline continues and load_stripe_fees() republishes that stale artifact under the new run; remove the fee artifact at the start of main() before any operation that can fail.

Useful? React with 👍 / 👎.

Comment on lines +289 to +291
stripe_fees = raw / "stripe_fee_daily.json"
if stripe_fees.exists() and json.loads(stripe_fees.read_text()).get("status") == "skipped":
sys.stderr.write("WARNING: Stripe fee line unavailable; see pull.log\n")

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 Forward the new optional-source warnings to Cloud Logging

During a successful scheduled Cloud Run execution, cloudrun_entry.py captures the child's stderr but lines 260-263 forward only warnings beginning with WARNING: Mercury. Therefore this new Stripe warning, along with the adjacent Soniox and Modulate warnings, disappears from Cloud Logging whenever an optional source is skipped, despite this section explicitly trying to surface those failures; extend the wrapper's success-path filter to include these warning prefixes.

Useful? React with 👍 / 👎.

Comment on lines 361 to +363
("sttMeasuredUsd", "STT measured", "number"),
("sttCashUsd", "STT cash (Mercury)", "number"),
("sttModulateModelledUsd", "Modulate modelled", "number"),

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 Add Stripe fees to the cost chart stack

When measured fees are available, healthFrames() emits them as fees and includes them in the all-in total, but this Grafana target never selects that field. The visible bars therefore understate cost by the Stripe fee amount and cannot reach the advertised Cost/day stack top; add a Stripe-fees column and corresponding visual override alongside the other measured cost components.

Useful? React with 👍 / 👎.

"revenue.mrr",
"revenue.arpmau",
"cost.per_mau_month",
"cost.per_customer_month",

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 Expose the per-customer metric on the TV

Adding cost.per_customer_month to HEADLINE_IDS does not create a series frame for it: headlineFrames() only builds costPerMau, and the Health dashboard targets only netCost and costPerMau. As a result, the newly computed software-cost-per-customer metric is never displayed anywhere on the Omi TV; add a headline frame and dashboard target for it.

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: fa7f9fd8b0

ℹ️ 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".

"TYPESENSE_HOST": "WEB_ADMIN_TYPESENSE_HOST:latest",
"TYPESENSE_API_KEY": "WEB_ADMIN_TYPESENSE_API_KEY:latest",
"STRIPE_SECRET_KEY": "WEB_ADMIN_STRIPE_SECRET_KEY:latest",
"STRIPE_READ_API_KEY": "STRIPE_READ_API_KEY:latest",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Make the Stripe read-key binding optional in development

When gcp_admin.yml deploys the development environment, it consumes every runtime_secrets entry here unconditionally, and preflight_public_build_runtime.py validates each referenced secret before deployment. The FinOps workflow in this same change documents that based-hardware-dev does not have STRIPE_READ_API_KEY, so any development admin deployment now fails preflight even though getOptionalStripeRead() already supports falling back to STRIPE_SECRET_KEY; make this binding environment-specific or provision the development secret.

Useful? React with 👍 / 👎.

Comment on lines +92 to +94
"date": day,
"audio_seconds": str(amount.quantize(Decimal("0.000000001"))),
"usd": str((amount / Decimal(3600) * per_hour).quantize(Decimal("0.000000001"))),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Price provider-wire duration instead of VAD speech

For active-VAD Modulate sessions, the selected omi_live_stt_audio_seconds_total input counts only chunks classified as speech, but the provider also receives pre-roll and hangover silence; vad_gate.py explicitly adds those bytes to the sent stream. Multiplying that smaller speech duration by the per-audio-hour rate therefore systematically understates the new Modulate cost line. Use the existing omi_stt_provider_wire_audio_seconds_total{provider="modulate"}, which records successfully written PCM duration, or otherwise meter the actual billed transport bytes.

Useful? React with 👍 / 👎.

Comment on lines +297 to +303
usd: spend ?? fallbackUsd,
measured: spend != null,
flag:
spend == null
? flag ?? SONIOX_GAP_FLAG
: flag === "gap_spread"
? "gap_spread"

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 Keep gap-spread Soniox days classified as estimates

When one or more balance snapshots are missed, daily_deltas() evenly spreads the interval total and explicitly flags each resulting day as gap_spread, meaning the per-day value is an assumption rather than a measurement. This assignment nevertheless sets measured solely from the non-null dollar value, so the health series renders gap-spread dollars in the solid measured series and marginStatus() reports “STT measured.” Treat gap_spread rows as estimated while retaining their disclosed flag.

Useful? React with 👍 / 👎.

…dence detection, 400-day Mercury backfill env

Luna r3 left one open item (finding 4): a 109-day ledger cannot rule out
yearly SaaS bills, and an empty manual annual set wrongly implied a complete
annual history (mercury_costs.py:202).

- Completeness gate: annual_history_complete now requires a full preceding
  365 covered days and tolerates no above-threshold uncategorized year-window
  spend, regardless of configured annual vendors. While false, the new
  annual_history_reason names the gate (history_under_12_months or
  uncategorized_above_threshold) in the FinOps output and on the wall, and the
  measured amortized value stays the run rate, labelled partial — no longer
  dropped back to the dated constant.
- Automatic cadence detection replaces the hand-maintained annual list: a
  charge is an annual bill on a ~12-month repeat (304-426-day neighbour gap),
  at >=5x the vendor's other-charge median, or — for a vendor seen exactly
  once — as an ambiguous one-off amortized /12 and reported as estimated in
  the new annual_estimated_usd. annual: true stays as a manual correction;
  annual: false means auto-detect.
- Backfill: FINOPS_MERCURY_BACKFILL_DAYS (91..400) widens one job run's
  Mercury pull for the one-time annual-history backfill; the artifact is
  keyed (date, vendor, category) and the loader replaces per date, so the
  backfill is idempotent. One-time deploy step documented in the finops README.
- Vendor map from the 2026-10-23 read-only 13-month Mercury check: modal
  group (the $12,000 2026-01-08 compute wire -> infra_non_gcp, never SaaS),
  www deepgram com ($40,758 STT cash wire -> stt_vendor), and named SaaS
  entries for once-a-year Software posters (vanta, mintlify) plus monthly
  greptile so detection reads per-vendor series; Software Costs joins the
  saas category-data rules. Company names only, never person names.

Tests: 31 backend finops (yearly/monthly/one-off/outlier cadence, override,
<365-day and gapped history, backfill window validation + idempotence, new
aliases); web/admin npm run check green (1087 passed).

@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: f992382055

ℹ️ 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".

('category', 'STRING'),
('amount_usd', 'NUMERIC'),
('annual_monthly_usd', 'NUMERIC'),
('annual_estimated_usd', 'NUMERIC'),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Migrate the existing Mercury table before loading new columns

On deployments where mercury_saas_daily already exists, adding these fields only to SCHEMAS makes every subsequent Mercury load fail: ensure_table() returns immediately for an existing table, while ADDED_COLUMNS handles only plan_revenue_daily, so load_replace() attempts to insert annual_estimated_usd and annual_history_reason into destination columns that do not exist. Add both fields to the live-table migration path before loading rows.

Useful? React with 👍 / 👎.

Comment on lines 147 to +149
SELECT date, amount_usd,
annual_history_complete AS annual_complete,
annual_history_reason AS annual_reason,

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 Propagate estimated annual SaaS into the wall status

When a vendor has only one charge in an otherwise complete 12-month history, detect_annual_charges() classifies it as an ambiguous one_off, amortizes it by 12, and records that guessed portion in annual_estimated_usd. This query discards that field and checks only annual_history_complete, which can be true in this scenario, so the wall presents the potentially 12× understated SaaS amount as fully measured with no estimate label. Select and propagate annual_estimated_usd so any nonzero estimated portion marks the SaaS line partial.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit f16409f into main Oct 22, 2026
65 of 67 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/omi-tv-fixes branch October 22, 2026 20:44
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…y load (#23354)

## What changed and why

Incident #23289 (f16409f) added
`annual_estimated_usd`/`annual_history_reason` to the
`mercury_saas_daily` code schema; the prod table predated them, so the
first post-deploy `finops-unit-cost-job` run failed BigQuery 400 "Column
annual_estimated_usd ..." and the coordinator had to add the columns by
hand. This generalizes the one-shot `ADDED_COLUMNS` list into a schema
reconcile every FinOps loader passes through: before each load,
`ensure_table` compares the live table to its `SCHEMAS` entry and
appends missing columns as NULLABLE (`ALTER TABLE … ADD COLUMN IF NOT
EXISTS`, metadata-only, additive). Columns are never dropped or retyped
— a type disagreement fails the run with a "migration required" message
— and absent tables are still created whole with the current schema.

## Product invariants affected

none

## How it was verified

`backend/scripts/finops` is a Cloud Run job script whose real path is a
prod BigQuery write, which this workflow does not do; verification is
the hermetic test layer with a fake `bq` client. The fake reproduces the
incident shape — a live `mercury_saas_daily` missing the two #23289
columns — and the loader issues exactly one additive ALTER before the
mercury INSERT, then both tables load.

Command (from `backend/`): `BACKEND_UNIT_TEST_FILE_LIST=<list> bash
test.sh` over the four finops test files → **70 passed** (5 new
schema-reconcile, 10 stripe-book, 31 mercury, 24 vendor-balance).
`scripts/backend-python-format --check` clean; pyright delta zero (the
two pre-existing `PROJECT` constant errors on lines 42/45 are
untouched).

## Tests

New `backend/tests/unit/test_finops_schema_reconcile.py`: missing
columns are added as one nullable ALTER and the full mercury load
proceeds over the stale table (reconcile strictly precedes the INSERT);
a type mismatch fails closed with the migration message and issues no
DDL; an extra live column is never dropped and a current table produces
no DDL; an absent table is still created whole.
`test_finops_stripe_book.py`'s old `ADDED_COLUMNS`-specific coverage
moved there; the hand-maintained dict is gone.

## UI evidence

UI-Evidence: none -- backend FinOps loader scripts only; no UI change.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23354?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/23354?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23354&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. -->
Git-on-my-level added a commit that referenced this pull request Oct 23, 2026
…ry infra_non_gcp run rate) (#23356)

## Omi TV: count non-GCP infrastructure cash in the all-in software cost

Failure-Class: none

(Round 3 fixes review findings on unmerged code; no shipped failure
class.)

UI-Evidence: none -- wall lib layer (`web/admin/lib/wall-*.ts`), finops
producer scripts, README and tests only; no UI component or visual
change.

#23289 made the wall count Mercury `saas` and `stt_vendor` cash.
`infra_non_gcp` cash (Modal, AWS, Runpod, Hetzner, Cloudflare, …) was
still reconciliation-only, so "software cost per customer" was
understated. That spend is not in GCP billing, so adding it counts
nothing twice. Scope stays David's: software cost per customer —
marketing and hardware remain excluded.

### Round 2 (Luna REQUEST-CHANGES) — all three findings fixed

**P1 partial undercount — a partial run rate is now a floor, not a
replacement.** Luna: before the 400-day backfill, a fresh-but-partial
infra row (~$114/mo of visible Cloudflare/Hetzner) replaced the
$1,114/mo fallback and silently dropped the known $12,000 Modal wire
(~$1,000/mo). Fix: while the producer labels the day partial
(`annual_history_complete=false`, either reason —
`history_under_12_months` **or** `uncategorized_above_threshold`, since
a year-window above-threshold uncategorized spend can hide an unmatched
annual infra wire just as a short ledger does), the wall shows
**max(measured run rate, dated fallback)**, still labelled `partial`
with the producer's reason (`wall-cost.ts` `infraLineFor`, new
`CostDay.infraFloored`/`infraMeasuredUsd`/`infraPartial`). Why max and
not keep-the-fallback: the cadence treatment amortizes only charges the
ledger holds, so a partial run rate cannot *overcount* the complete
figure (an annual bill posted before the ledger start contributes $0,
and a vendor's first-seen charge is an ambiguous one-off ÷12) — it is a
floor; taking the max therefore never undercounts from either source,
still uses a measured run rate the moment it rises above the constant
(not hidden behind it), and cannot strand a constant past its 35-day
staleness while the backfill is pending. Once `annual_history_complete`
flips true (≥365 covered days after the backfill), the measured value
stands alone. While floored, the line reads `Infra (non-GCP) $36.60/day:
dated $1114/mo fallback as of 2026-10-23 floors the partial Mercury run
rate $3.75/day (partial: infra ledger history under 12 months; …)` and
the constant's age counts against staleness again. Effect on the round-1
evidence window (arithmetic over the committed legs, not a new read):
the fallback's ≈$36.60/day books ≈$1,098 over 2026-09-21..10-20 → all-in
≈ **$84,271 / ≈$26.26 per customer** — the wall now shows essentially
the round-1 post-backfill projection (≈$84,247 / $26.25) immediately,
labelled partial, instead of understating ≈$1,000/mo until the backfill
lands.

**P2 `stripe_fees` — conditional exclusion, never dropped from both
lines.** Luna: the producer's `stripe_fees` exclusion was unconditional,
so on a day the measured Stripe-fee line is dark the cash was on neither
line. Fix: `infra_rows` now keeps the vendor out of `amount_usd` (the
measured fee line still owns that money) but reports its own run rate in
a new **`stripe_fees_usd`** column (`mercury_costs.py`,
`load_mercury.py`); the wall adds it to the infra line **only on a day
the measured fee line has no value** (`fees == null`: source dark or day
not loaded), labelled on both lines (`+ Mercury stripe_fees cash $X/day
counted here (measured Stripe fee line unavailable for the day)` on the
infra line; a pointer on the fees line). On a day with a measured fee,
the fee line owns the money and infra carries none of it — never both,
never neither. Today the ledger holds no such Mercury rows, so both
paths are pinned by test, not by prod data.

**P1 schema — full schema on creation, no dependence on missing
columns.** The new `mercury_infra_non_gcp_daily` (which does not exist
in prod yet) is created whole from `SCHEMAS` by `ensure_table`, now
including `stripe_fees_usd`; a new test pins that **every field
`saas_rows`/`infra_rows` emits has a column** in the registered schema
(the exact failure mode of the #23289 `mercury_saas_daily` incident) and
that the loader ensures all three tables before their loads. Nothing in
this PR reads a column an older table might lack: the wall's infra read
is on the new table only, and a read that fails (a live table predating
a column) degrades to the labelled dated fallback, never a failed cost
stack. Live-table reconciliation for OLDER tables is **#23354**
(`finops-schema-evolve`, still open at push time): not duplicated here;
either merge order is safe (this PR creates the new table whole; #23354
appends missing nullable columns to any table that pre-exists). The
coordinator's 2026-10-23 manual `mercury_saas_daily` columns stand in
for #23354 on that table until it merges.

### Round 3 (Luna r2 residual P2) — the fee-cash fallback covers every
rendered frame

Luna r2: the 60-day health series drew on a 41-day source window —
`fetchStripeFeeHistory`/`fetchInfraHistory` defaulted to 40 days — so
with the measured Stripe-fee source dark, the oldest ~19 frames had
neither a measured fee row nor an `infraStripeFeesCash` row and silently
dropped the Mercury cash. Fix: both reads default to `HEALTH_COST_DAYS +
2` (62 days; the frames end at the D−2 cutoff so the oldest rendered day
is today−61, plus one spare), and `healthFrames` slices its backbone by
the same exported `HEALTH_COST_DAYS` constant — widening the chart now
widens the reads with it. The snapshot's cost stat (same fetchers,
60-day billing read filtered to the cutoff) is covered by the same
default. Tests: the fetcher defaults are pinned to reach past the oldest
frame (a row at today−61 parses through, `days ≥ HEALTH_COST_DAYS + 1`),
and a full-series test renders all 60 frames with the fee source dark
and cash on every frame — asserting each frame carries
`infraFeesCashUsd` and `infra = dated constant + cash`, the oldest frame
first.

### What changes

**Producer (`backend/scripts/finops`).** `mercury_costs.py` factors the
SaaS run-rate into a shared `run_rate_rows(rows, dates, config,
category)`; `saas_rows` is unchanged in behaviour and a new `infra_rows`
applies the *same cadence treatment from #23289* to the `infra_non_gcp`
category: 30-posted-day cash ÷ 30.4375, yearly repeats / ≥5× outliers /
ambiguous one-offs amortized ÷12 across their service year, with
one-offs reported in `annual_estimated_usd` (`estimated`), and the
identical `inputs_complete` / `annual_history_complete` +
`annual_history_reason` gates (`partial`). The excluded `stripe_fees`
vendor gets the same cadence treatment on its own and rides along in
`stripe_fees_usd` (per-vendor cadence detection is unchanged by
splitting the series). `load_mercury.py` writes it to a new table
**`based-hardware.omi_finops.mercury_infra_non_gcp_daily`** (SaaS schema
+ `stripe_fees_usd`, `category='infra_non_gcp'`, registered through the
existing `SCHEMAS` merge in `load_bigquery.py`, created whole by
`ensure_table` on the next job run). No existing table changes.

**No double counting (checked against `mercury_vendor_map.json`).**
Deepgram, Soniox and Modulate map to `stt_vendor`, GCP cash to `gcp`,
OpenAI/OpenRouter/Groq/xAI to `llm_vendor`, Anthropic to `saas` — none
can enter the infra run rate (pinned by
`test_infra_line_never_double_counts_other_wall_lines`). The one
in-category overlap is the `stripe_fees` vendor: the map files Mercury
"Stripe Fee(s)" cash under `infra_non_gcp`, but the wall already books
measured Stripe processing fees from `stripe_fee_daily`, so
`INFRA_EXCLUDED_VENDORS = {'stripe_fees'}` keeps it out of the infra
line's `amount_usd` (the fee line stays the single owner of that money;
today the ledger holds no such rows, so the exclusion is a no-op guard
whose fee-cash path is test-pinned).

**Wall (`web/admin/lib`).** `wall-finops.ts` adds `FINOPS_INFRA_QUERY` /
`fetchInfraHistory` / `parseInfra` — a separate read with the SaaS gates
(`inputs_complete`, computed within 3 days, latest run per date) plus
`stripe_fees_usd`, so a dark table can never fail the plan/STT/SaaS
read. `wall-cost.ts` adds the `infra` leg to `CostDay`,
`VendorInputs.infraMeasured` / `infraAnnualPartial` /
`infraStripeFeesCash`, the exported `infraLineFor` policy (max-rule
floor + conditional fee cash), the all-in `total`, and a dated fallback
`INFRA_MONTHLY_USD = 1114` as of 2026-10-23 with the SaaS 35-day
staleness threshold (new `"Infra"` row in `estimateStatus`; while the
fallback floors a partial day it is the price in use, so its age counts
again). `wall-metrics.ts` reads the source, builds the line text —
`measured Infra non-GCP (Mercury) $X/day` with the producer's partial
reason, the floor wording above when floored, or `Infra (non-GCP) fixed
$1114/mo estimate as of 2026-10-23 (…)` marked `STALE` past 35 days —
appends it to the `All-in:` reason, names a dark table as a `missing:`
line, and the `cost.per_customer_month` / `cost.per_mau_month`
numerators pick it up through the shared window total. `wall-series.ts`
wires the same leg into the health series (`infra*` row fields incl.
`infraFeesCashUsd`, `estimates`, margin freshness labels — a floored day
prices by the constant and says `Infra non-GCP estimate (floors partial
Mercury run rate)`).

### Before / after (read-only BigQuery, ro-prod bot, 2026-10-23)

Window = the wall's 30 settled days ending at the last day the billing
export has reached: **2026-09-21..2026-10-20**. Legs computed with the
wall's own `allInCost` over the same tables it reads
(`gcp_billing_export` net of credits with one-time detection,
`unit_cost_daily`, `mercury_saas_daily`, `mercury_vendor_spend_daily`,
`plan_revenue_daily`). The infra leg is the real `infra_rows()` run over
the actual ledger (every window day `inputs_complete`, all labelled
`history_under_12_months`); round 2 then floors those partial days at
the dated fallback (see the round-2 section for the resulting ≈$84,271
all-in).

| 30-day window 2026-09-21..10-20 | before | after (round 1,
measured-partial rows) | after (round 2 floor) |
| --- | --- | --- | --- |
| All-in software cost | **$83,172.70** | $83,261.18 | **≈$84,271**
(fallback $1,114/mo floors the $114/mo partial slice) |
| Cost per paying customer (÷ 3,209 paying subscriptions, the book's
2026-10-21 snapshot — item-sum fallback, see below) | **$25.92** |
$25.95 | **≈$26.26** |
| Settled day 2026-10-20, all-in/day | $3,541.12 | $3,544.87 | $3,574.01
(≈$36.60/day fallback) |

Legs over the window: GCP net $42,833.76 · Vertex LLM $10,848.33 ·
OpenAI $6,943.40 (FinOps `llm_openai_measured` + `llm_direct_residual`;
the Anthropic admin-API leg is not readable read-only and is $0 here) ·
STT $6,804.66 (20 days `stt_soniox_measured`, 10 days the dated Soniox
constant, Mercury Modulate/Deepgram cash) · SaaS $15,742.56 (live
`mercury_saas_daily`, 30 measured days) · **Infra ≈$1,098 (round-2
floor; measured partial slice $88.48)** · Stripe fees unavailable (fee
table dark; Mercury stripe_fees cash $0 today) · one-time excluded $0.

Denominator: `plan_revenue_daily.paying_customers` is NULL for every
snapshot in the window (the #23289 producer wrote its first value,
3,194, on 2026-10-22), so the wall applies its labelled item-sum
fallback (3,209 on 2026-10-21). Using the 2026-10-22 distinct count
instead: ≈$26.35 at the round-2 floor.

**Why the floor matters today, and what the lead should expect next.**
The ledger (`mercury_vendor_spend_daily`) covers 2026-07-04..2026-10-20
only; in that window `infra_non_gcp` is Cloudflare (~$10.5/mo) and
Hetzner (~$104/mo), both monthly repeats, ≈ $114/mo. Modal's once-a-year
$12,000 compute wire (2026-01-08, recorded in the finops README from the
2026-10-23 13-month read-only check) predates the ledger, so the
measured line cannot see it until the **#23289 one-time 400-day
backfill** (`FINOPS_MERCURY_BACKFILL_DAYS=400`, README) runs — that is
why every day is labelled `partial`. Round 1 let those partial rows
replace the fallback and understated all-in by ≈$1,000/mo
(≈$0.31/payer); round 2 books the dated fallback (`INFRA_MONTHLY_USD =
1114` = ledger run rate $114 + Modal $1,000) on every partial day, so
the wall shows the wire's amortization now and switches to the measured
value alone once the backfill makes `annual_history_complete=true` (or
earlier, on any day the measured run rate exceeds the constant).

### Deploy notes

- The new table is dark until the first FinOps job run after this
merges; the wall shows `Infra (non-GCP) fixed $1114/mo estimate as of
2026-10-23 (Mercury infra run-rate table unavailable)` and lists the
missing line — never $0, never a failed cost stack. No workflow, secret
or env change (no INV-DATA-1).
- Schema dependency: **#23354** (live-table reconcile,
`lane/finops-schema-evolve`) was still open at round-2 push time — this
PR does not duplicate it and needs nothing from it to deploy (the new
table is created whole; `mercury_saas_daily`'s columns were added to
prod by the coordinator on 2026-10-23). Merge either order; re-merge
main into this lane if #23354 lands first.
- Observation while measuring: live `mercury_saas_daily` values run
~$120–130/day above a local recompute with the merged #23289 cadence
logic, consistent with the deployed job image predating #23289 (its
one-off amortization lowers the SaaS run rate). Not touched here —
redeploying the job from main picks up both #23289 and this line.
- New query shape validated read-only against prod on the
identically-shaped SaaS table (returns `usd`, `stripe_fees_usd`,
`annual_complete`, `annual_reason`).

### Tests

- Backend via `backend/test.sh` + `BACKEND_UNIT_TEST_FILE_LIST`:
`test_finops_mercury.py` **35 passed** (round 2 +1: schema pin that
every produced run-rate field has a SCHEMAS column and load_bigquery
registers it; extended the no-double-count test with the
`stripe_fees_usd` column and the sum-equals-combined check; the loader
test now pins all three tables ensured in order and a zero
`stripe_fees_usd`), `test_finops_cloudrun.py` 25 passed,
`test_finops_unit_cost.py` 39 passed, `test_finops_stripe_book.py` 10
passed, `test_finops_stripe_fees.py` 9 passed.
`scripts/backend-python-format --check` clean.
- web/admin `npm run check`: lint 0 errors, typecheck clean, **1104
passed | 13 skipped** (round 3 +2: the two fetcher defaults reach past
the oldest health frame; the full 60-frame dark-fee series keeps its
cash on every frame). One pre-existing load-timing flake in the full run
— `sensitive-wall.test.ts` hits its 30 s timeout under the parallel
suite and passes standalone (15 s, re-verified round 2); untouched by
this diff.
- Round 3 reran the backend list (`test_finops_mercury.py` 35 passed,
`test_finops_schema_reconcile.py` 5 passed; no backend file changed this
round).


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23356?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/23356?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23356&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. -->
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Oct 23, 2026
…y load

BasedHardware#23289 (f16409f) added annual_estimated_usd/annual_history_reason to the
mercury_saas_daily code schema; the prod table predated them and the first
post-deploy finops-unit-cost-job run failed BigQuery 400 on the missing
column. Replace the one-shot ADDED_COLUMNS list with a generic reconcile in
ensure_table: before each load, missing SCHEMAS columns are appended as
nullable (metadata-only ALTER); nothing is dropped or retyped and a type
disagreement fails closed with a migration-required message. Absent tables
are still created whole.
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Oct 23, 2026
…ry infra_non_gcp run rate)

The wall counted Mercury saas and stt_vendor cash (BasedHardware#23289) but left
infra_non_gcp (Modal, AWS, Runpod, Hetzner, Cloudflare) reconciliation-only,
understating software cost per customer. That spend is outside GCP billing,
so counting it adds nothing twice.

Producer: mercury_costs.run_rate_rows shares the SaaS cadence treatment
(30-posted-day cash, yearly/outlier/one-off bills amortized /12, one-offs
labelled estimated, the same inputs_complete / annual_history gates);
infra_rows applies it to infra_non_gcp and load_mercury writes
mercury_infra_non_gcp_daily. The stripe_fees vendor is excluded: its cash is
the measured stripe_fee_daily line. STT, GCP, LLM and SaaS vendors map to
their own categories and never enter the line (pinned).

Wall: a separate dark-safe FinOps read (fetchInfraHistory), the infra leg in
CostDay / allInCost total and so in the cost-per-customer numerator, a dated
INFRA_MONTHLY_USD fallback with the SaaS 35-day staleness and an "Infra" row
in estimateStatus, the line text with its partial reason on the all-in
metric, and the same leg in the health series and margin freshness labels.

Read-only measurement (2026-09-21..2026-10-20): all-in $83,172.70 ->
$83,261.18 (+$88.48), per paying customer $25.92 -> $25.95; the ledger
starts 2026-07-04, so Modal's yearly wire enters only after the BasedHardware#23289
backfill (every day labelled partial until then).

Failure-Class: none
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