Skip to content

feat: add Firestore read-volume instrumentation and alerting - #12193

Merged
Git-on-my-level merged 2 commits into
mainfrom
feat/firestore-read-metrics
Aug 25, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
feat/firestore-read-metrics

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Summary

A Firestore cost runaway has been burning ~$728/month since 2026-08-23 and was structurally invisible: GCP's document/read_count is absent from all 1,705 Prometheus metric names, 0 of 48 Grafana dashboards mention Firestore/cost, and 0 of 62 alert rules cover it. This change makes Firestore read volume visible and alertable.

  • Ingest the metric. Add firestore.googleapis.com/document/read_count to the Stackdriver exporter's metric prefixes in both prod_omi_stackdriver_exporter.yaml and dev_omi_stackdriver_exporter.yaml. Measured: 3 series (type=LOOKUP/NOT_FOUND/QUERY), resource type firestore_instance, DELTA/INT64, single page. Marginal cost 1,440 extra ListTimeSeries calls/day ($0.43/month) against ~$728/month of waste it makes visible.
  • Two Grafana alert rules (mirrored in backend/charts/monitoring/alerts/firestore.json and the combined alert-rules.json export), both severity=warning (cost signal, not an outage — the hermes prod watchdog pages on any active severity=critical):
    • omi-firestore-notfound-dod-step — day-over-day step detector: sum(rate(...NOT_FOUND...[1h])) > 1.5 * sum(rate(...[1h] offset 24h)), sustained 2h. Survives organic growth and diurnal swing.
    • omi-firestore-notfound-ceiling — absolute ceiling backstop: sum(rate(...NOT_FOUND...[30m])) > 600, sustained 2h. Catches a leak that is already running and steady, which the day-over-day comparison cannot see (both sides equally elevated). Measured baseline ~361/sec before the incident, ~936/sec during it; 600/sec sits between the two.
    • Annotations name the metric, explain that NOT_FOUND reads are documents that don't exist (near-pure waste), and note that attribution requires either extending omi_firestore_read_operations_total coverage or a short window of Firestore DATA_READ audit logging, since the Cloud Monitoring series carries module="__unknown__".
  • Contract test in backend/tests/unit/test_monitoring_telemetry_contract.py asserting both exporter values files declare the Firestore prefix. The existing test_alert_uids_are_short_enough_for_grafana_to_accept in test_monitoring_alert_rule_contract.py automatically covers the two new UIDs (31 and 30 chars, well under the 40-char Grafana limit).

Test plan

  • backend/.venv/bin/python -m pytest backend/tests/unit/test_monitoring_telemetry_contract.py backend/tests/unit/test_monitoring_alert_rule_contract.py -q — 50 passed
  • make preflight — 26 checks passed
  • CI green

🤖 Generated with Claude Code

Review in cubic

r added 2 commits August 25, 2026 13:13
Firestore document/read_count was absent from all 1,705 Prometheus metric
names, 0 of 48 Grafana dashboards, and 0 of 62 alert rules -- so a Firestore
cost runaway (~$728/month since 2026-08-23) was structurally invisible.

- Scrape firestore.googleapis.com/document/read_count via the existing
  Stackdriver exporter in both prod and dev (marginal cost ~$0.43/month).
- Add two Grafana alert rules (mirrored in alerts/firestore.json and the
  combined alert-rules.json export): a day-over-day step detector for
  NOT_FOUND reads (survives diurnal swing and organic growth) and an
  absolute-ceiling backstop at 600/sec (catches a leak already running,
  which the day-over-day comparison cannot see). Both severity=warning --
  cost signal, not an outage.
- Add a contract test asserting both exporter values files declare the
  Firestore prefix.
… not product

A Firestore read-volume cost regression is an infrastructure concern, not
product impact. (warning, infrastructure) is an established pairing for this
class; (warning, product) would misdirect triage toward user-facing work.

Label correction within this unmerged PR — nothing has shipped, so there is
no production failure to classify.
@Git-on-my-level
Git-on-my-level merged commit 4930f10 into main Aug 25, 2026
34 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/firestore-read-metrics branch August 25, 2026 17:47
Git-on-my-level added a commit that referenced this pull request Aug 25, 2026
Registry-only lifecycle change. An alert merged in #12193 used rate() on
a metric the stackdriver exporter publishes as a gauge; it provisioned
cleanly, evaluated green, and could never have fired. No existing class
covers a monitor that is syntactically valid and structurally inert.

Co-authored-by: r <r@r>
Git-on-my-level added a commit that referenced this pull request Aug 25, 2026
The two rules merged in #12193 use rate() on a metric the stackdriver
exporter publishes as a gauge, so both evaluated to a plausible wrong
number and neither could ever cross its threshold. Rebuild both on
avg_over_time(...)/60, and reset the thresholds from the metric's
measured distribution rather than a remembered baseline: normal
day-over-day noise reaches 1.94x (so 1.5x false-positives) and healthy
hours reach 1124/sec (so a 600/sec hourly ceiling false-positives).
A 6h rolling mean separates the regimes cleanly at 750/sec.

Also commits the exporter configuration already applied to prod at helm
revision 7 -- descriptor caching, 503 retries, and the 3m query window
that the ~2.4min Firestore ingestion lag requires.

Co-authored-by: r <r@r>
Git-on-my-level added a commit that referenced this pull request Aug 26, 2026
…iveness (#12241)

* feat: alert when the Firestore read-volume metric stops being collected

Both Firestore cost rules use `expr > threshold`, which returns an empty
vector when not firing; with noDataState=OK that is indistinguishable
from the metric having disappeared. The exporter published zero firestore
series for hours today while reporting healthy, so this is a live failure
mode, not a hypothetical one.

Proven both ways against prod: absent() is silent while the metric is
present and returns 1 for a selector that matches nothing.

* feat: alert on Firestore read spend, per-family steps, and metric staleness

The NOT_FOUND leak is not the money. Measured 2026-08-25: total Firestore
read spend is ~$344-368/day, of which action_items_list alone is ~36%
(~5,100 docs/sec, ~$4,315/month) against the NOT_FOUND leak's ~$715/month.
Every Firestore rule shipped so far watches type="NOT_FOUND", roughly 7%
of read volume, so nothing would have noticed the largest line item
doubling.

Adds a dollars-per-day ceiling that is agnostic to read shape and covers
principals the app-side probe cannot see, a per-family day-over-day step
that names which path regressed, and a staleness guard for a series that
is present but frozen.

Also ratchets the authoring bug behind the two inert alerts in #12193:
rate() over a stackdriver_ gauge. 14 pre-existing rules do this, 6 of
which page; they are recorded as debt rather than rewritten, because
their thresholds were calibrated against the wrong values and a
mechanical sweep would silently re-tune paging alerts.

---------

Co-authored-by: r <r@r>
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
…12446)

## Why this change

On 2026-08-30 a voice-capture outage left `capture_finalization` success
at **0% for hours** while every existing critical stayed Normal: listen
ready=5, listen WS≈325, pusher WS≈326, LB traffic flowing, 5xx rps=0.
The existing criticals only watch zero LB traffic, zero ready pods, WS <
10, and 5xx rates. The rules that did read user outcomes
(`omi-journey-*-fail`, #11991) are **warning-class**, and the [Omi Core
Features
dashboard](https://monitor.omi.me/d/omi-core-features/omi-core-features)
that plots these SLIs is visualization-only — panel thresholds, zero
alert rules. **Dashboard ≠ alert**: the signal existed, nothing paged on
it.

Incident fingerprint (last 1h at peak):
`omi_journey_terminal_total{journey="capture_finalization"}` success=0,
failure≈360, stale≈290; accepted≈750; oldest unfinished finalization job
≈ 5.9 days; dead letters ≈ 2.5k/24h.

## What was added

Six `severity: critical` rules in the `Resilience` group (split source
`backend/charts/monitoring/alerts/resilience.json`, mirrored into the
combined `backend/charts/monitoring/alert-rules.json`), plus one rule
change. Every rule links the Core Features panel that plots its own
signal.

| Metric / SLI | Existing rule (git = live mirror) | False-negative
class this incident hit | New / changed UID | noDataState | Traffic gate
|
|---|---|---|---|---|---|
| `capture_finalization` success share | `omi-journey-capture-fail`
(warning, #11991; reads `listen_finalization_durable_jobs` deltas) |
warning-class — ticket lane, no page; incident kept it out of the paging
path | `omi-journey-capture-success-critical` | `NoData` | ≥ 20 accepted
/ 30m |
| accepted-without-terminal (accepted vs settled) |
`omi-capture-finalization-dead-emission` (warning; fires only on
**zero** terminal movement) | incident had *flowing* failure/stale
terminals, so the zero-terminal condition never applied at page class |
`omi-journey-capture-settle-gap` | `NoData` | ≥ 100 accepted / 1h |
| `listen_finalization_dead_letter_total` | **missing** (dashboard panel
only) | ~2.5k dead letters/day with zero alerts reading it |
`omi-capture-dead-letter-surge` | `Alerting` | none — each dead letter
is a lost capture (> 50/1h) |
| `listen_finalization_oldest_nonterminal_age_seconds` | **missing**
(backlog panel from #12211 only) | oldest job aged to 5.9 days with zero
alerts reading it | `omi-capture-oldest-nonterminal` | `Alerting` | none
— queue age is traffic-independent (> 3600s) |
| `pusher_session` success share | `omi-journey-pusher-fail` (warning) |
warning-class only | `omi-journey-pusher-success-critical` | `NoData` |
≥ 20 accepted / 30m |
| `chat_response` success share | `omi-journey-chat-fail` (warning;
unfirable for its whole life before the Cloud Run bridge) |
warning-class + counter historically absent from Prometheus |
`omi-journey-chat-success-critical` | `NoData` | ≥ 20 accepted / 30m |
| journey counter liveness | `omi-journey-signal-dead` covered only
`pusher_session\|capture_finalization`; `chat_response` exempt | a dead
chat counter would silently disarm every chat alert (the exact
2026-08-19 hole) | `omi-journey-signal-dead` **changed** — adds a
`chat_response` arm | `Alerting` | chat arm gated on
`llm_gateway_requests_total{lane_id="omi:auto:chat-agent"} > 20/1h` |

### PromQL

Success-rate rules pair numerator and denominator from the same emitter
(`omi_journey_terminal_total` for one `journey`), gated on that
journey's accepted counter (example: capture):

```promql
# A — gate
sum(increase(omi_journey_accepted_total{journey="capture_finalization"}[30m]))
# B — success share (a total terminal stall with real traffic reads 0 and pages)
sum(increase(omi_journey_terminal_total{journey="capture_finalization",outcome="success"}[30m]))
  / clamp_min(sum(increase(omi_journey_terminal_total{journey="capture_finalization",outcome=~"success|failure"}[30m])), 1)
# C — $A >= 20 && $B < 0.90, for 10m
```

Settle gap (accepted minus all terminal outcomes, 1h): `$A >= 100 && $B
> 50`, for 15m.
Oldest job: `max(listen_finalization_oldest_nonterminal_age_seconds) >
3600`, for 15m.
Dead letters: `sum(increase(listen_finalization_dead_letter_total[1h]))
> 50`, for 15m.
Liveness chat arm (added to `omi-journey-signal-dead`):

```promql
or (sum by (journey) (increase(omi_journey_accepted_total{journey="chat_response"}[1h])) < bool 1)
   * on() group_left() (sum(increase(llm_gateway_requests_total{lane_id="omi:auto:chat-agent"}[1h])) > bool 20)
```

### noData semantics

- Success-rate and gap rules: `NoData` (the documented
`traffic_gated_journey` class) — missing series are visible as NoData,
never healthy; counter death pages via `omi-journey-signal-dead` and
`omi-journey-scrape-missing`.
- Queue rules (`oldest-nonterminal`, `dead-letter`): `Alerting` — both
series are unlabeled and zero-initialized on every backend-listen
replica, so absence during real traffic means the emitter or its scrape
is gone. Documented as `finalization_queue_health` in
`expected-targets.prod.yaml`.

### Threshold calibration (documented in
`backend/docs/runbooks/real-traffic-journeys.md`)

- 0.90 paging floor vs the dashboard's 95/99 display thresholds; the
incident sat at 0%.
- ≥ 20 accepted/30m gate (same floor the existing warning rules use);
the incident ran ~375 accepted/30m.
- Gap > 50/h at ≥ 100 accepted/h: the incident left ~100/h
accepted-but-never-settled; healthy in-flight work settles in minutes.
- Oldest job > 1h: healthy drain is minutes; incident oldest was ~5.9
days.
- Dead letters > 50/h: incident ran ~104/h (2.5k/day).
- Chat liveness gate > 20/h sits above the chat-agent lane's measured
p05 (min 9, p01 15, p05 23, median 55 req/h over 7 prod days), so quiet
hours do not page.

These are incident-calibrated initial values; replay them against
production history when importing (the repo has no live Prometheus
access from a PR-checkout environment).

## Live vs git reconciliation

- Live Grafana (issue-verified 2026-08-30 ~23:30 UTC): **68 unified
rules**; git before this PR: **80**. The 12-rule delta is recently
merged rules not yet imported (Firestore #12193/#12201/#12241, cloud-run
ingestion #11998/#12146, etc.) — the documented apply path is a
maintainer import of `alert-rules.json`; no CI writes Grafana, and this
PR follows that path (no API writes).
- The pre-incident journey rules (from #11991, merged 2026-08-22)
predate the outage window; their gap was severity class, not presence.
- Metric label sets were discovered from the emitter contract, not
guessed: `utils/metrics.py`, `utils/observability/journeys.py`
(`journey` ∈ {`chat_response`, `pusher_session`,
`capture_finalization`}; `outcome` ∈ {`success`, `failure`, `cancelled`,
`stale`}), `services/conversation_finalization.py` (unlabeled
dead-letter counter, unlabeled oldest-age gauge, `state`-labeled durable
gauge), and the closed vocabulary in
`backend/docs/runbooks/real-traffic-journeys.md`. Direct live
Prometheus/Grafana queries were not available from this environment
(auth required); the `chat_response` ingestion path is evidenced by
#12146's measured live prod scrape (~28MB, 52,662 `omi_*` series).

## Tests

Extended `test_monitoring_alert_rule_contract.py`:

- `LIVENESS_EXEMPT_JOURNEYS` is now empty — the `chat_response`
exemption's own deletion clause fired once the Cloud Run bridge was
verified live;
`test_every_alerted_journey_is_covered_by_the_liveness_rule` now
enforces chat coverage instead.
- New:
`test_page_class_journey_rules_cover_the_capture_outage_fingerprint`
(severity, component, noData, `for` window, receiver, exact math gates),
`test_page_class_success_rules_pair_numerator_and_denominator_from_one_emitter`,
`test_finalization_queue_rules_read_the_replicated_series_correctly`
(max-aggregation for the replicated gauge).

## Verification

```bash
cd backend && .venv/bin/python -m pytest \
  tests/unit/test_journey_observability.py \
  tests/unit/test_monitoring_alert_rule_contract.py \
  tests/unit/test_monitoring_dashboard_absence_contract.py \
  tests/unit/test_monitoring_telemetry_contract.py -q
# 63 passed  (the exact set scripts/select_backend_unit_tests.py selects for these changed files)

make preflight   # PR preflight passed: 11 checks in 28.55s
```

Closes SCA-379


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12446?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.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