Skip to content

harden(finops): reconcile live BigQuery tables to SCHEMAS before every load - #23354

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/finops-schema-evolve
Oct 22, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/finops-schema-evolve

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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

View guided diff Turn on auto-fix

…y load

#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.
@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-22T22:28:46.076527Z 88d0b7a PR opened
ℹ️ 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.

@Git-on-my-level
Git-on-my-level merged commit 5c1dec0 into main Oct 22, 2026
69 of 71 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/finops-schema-evolve branch October 22, 2026 23:27
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
…lback, conditional stripe_fees cash, schema pin

P1 partial undercount: while annual_history_complete=false (either reason)
the infra run rate is a floor - it cannot see annual bills posted before the
ledger starts - so the wall shows max(measured, INFRA_MONTHLY_USD), still
labelled partial with the producer's reason; a complete row or one above the
constant stands alone (wall-cost.ts infraLineFor, wall-metrics/wall-series
labels and staleness).
P2 stripe_fees: the producer reports the excluded fee-vendor cash in a new
stripe_fees_usd column (mercury_infra_non_gcp_daily); the wall counts it on
the infra line only on a day the measured fee line has no value, labelled on
both lines - never on both, never on neither.
P1 schema: mercury_infra_non_gcp_daily is created whole from SCHEMAS (SaaS
columns + stripe_fees_usd); pinned that every produced run-rate field has a
column and that all three tables are ensured before their loads. Older
live-table reconcile stays with #23354, not duplicated here.
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. -->
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