Repository navigation
feat(observability): count Firestore writes by collection, caller and origin - #24218
Conversation
… origin
Firestore writes are about $57/day (41M/day in billing, 10-27..10-30) and
stepped up from ~22M/day on 2026-10-26, but the only write signal was
Cloud Monitoring write_count by op, and data-access audit logs are off, so
no write could be traced to code.
Add database/firestore_write_probe.py, the write twin of the read probe.
It wraps the GAPIC FirestoreClient.commit / batch_write (sync and async),
the one point every SDK write path reaches, so it counts each request as
sent, including the rows, versions and heads that list_projection and
memory_change_head append. database._client installs it before those
patches. Failed commits count nothing; BatchWrite counts OK writes only.
New counters: omi_firestore_billed_writes_total{collection,op,database},
..._by_caller_total{collection,op,caller}, ..._by_origin_total and a caller
overflow counter with its own 2048 cap. The sync Cloud Run scrape keeps the
total and by-caller counters. The read probe's collection allowlist gains
the three list-projection collections.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ite probe Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
5 issues found across 7 files
Confidence score: 3/5
test_firestore_write_probe.pyexpects the test function as the caller, but the fake transport puts_Transport.commitfirst, so this assertion fails. Update the expectation to match the fake transport’s actual label.firestore_write_probe.pycounts every write as applied when BatchWrite status and write counts disagree, which can overcount failed writes. Return no writes for unverifiable results and log the mismatch.- The coverage query in
firestore-write-attribution.mdmay not work as intended: the exporter does not scrapedocument_write_count, and the query’s denominator includes operations and databases the comment excludes. Align the scrape config and query filters. cloud_run_gmp_sync.yamlcan generate far more than the 10,000-sample scrape limit; the caller cap does not bound total series. Enforce a series limit.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/docs/firestore-write-attribution.md">
<violation number="1" location="backend/docs/firestore-write-attribution.md:40">
P2: The coverage comment and the query disagree: the comment names four Cloud Monitoring ops, but the denominator sums every op. The numerator also filters `database="default"` while the denominator does not, so the ratio mixes scopes. Filter the denominator by op and database to match, or correct the comment and explain the scope.</violation>
<violation number="2" location="backend/docs/firestore-write-attribution.md:43">
P2: The post-deploy coverage query depends on `document_write_count`, but no exporter config scrapes `firestore.googleapis.com/document/write_count`; the exporter prefixes only include `document/read_count`. Add the write_count prefix to the stackdriver exporter config, or the coverage check cannot run.</violation>
</file>
<file name="backend/tests/unit/test_firestore_write_probe.py">
<violation number="1" location="backend/tests/unit/test_firestore_write_probe.py:94">
P2: This test expects the caller frame to be the test function, but the fake transport inserts `_Transport.commit` as the first non-plumbing frame, so the by-caller assertion fails. Expect the fake transport’s actual label or move the fake behind a plumbing boundary so the test exercises the intended caller attribution.</violation>
</file>
<file name="backend/database/firestore_write_probe.py">
<violation number="1" location="backend/database/firestore_write_probe.py:242">
P2: On a BatchWrite status/write count mismatch, `_applied` returns every write, which overcounts writes that may have failed. Return nothing so the probe never counts an unverifiable result as applied, and log the mismatch.</violation>
</file>
<file name="backend/deploy/cloud_run_gmp_sync.yaml">
<violation number="1" location="backend/deploy/cloud_run_gmp_sync.yaml:41">
P2: This allowlist can exceed the 10,000-sample scrape limit: 2,048 callers × 108 collection patterns × 5 operations is over one million possible series. The caller cap bounds label values, not total series; enforce a series budget or omit this family from sync.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| # Top write call sites | ||
| topk(25, sum by (job, caller, collection, op) (rate(omi_firestore_billed_writes_by_caller_total[1h]))) | ||
|
|
||
| # Coverage against Cloud Monitoring (UPDATE + UPDATE_NOOP + CREATE + DELETE) |
There was a problem hiding this comment.
P2: The coverage comment and the query disagree: the comment names four Cloud Monitoring ops, but the denominator sums every op. The numerator also filters database="default" while the denominator does not, so the ratio mixes scopes. Filter the denominator by op and database to match, or correct the comment and explain the scope.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/firestore-write-attribution.md, line 40:
<comment>The coverage comment and the query disagree: the comment names four Cloud Monitoring ops, but the denominator sums every op. The numerator also filters `database="default"` while the denominator does not, so the ratio mixes scopes. Filter the denominator by op and database to match, or correct the comment and explain the scope.</comment>
<file context>
@@ -0,0 +1,44 @@
+# Top write call sites
+topk(25, sum by (job, caller, collection, op) (rate(omi_firestore_billed_writes_by_caller_total[1h])))
+
+# Coverage against Cloud Monitoring (UPDATE + UPDATE_NOOP + CREATE + DELETE)
+sum(rate(omi_firestore_billed_writes_total{database="default"}[30m]))
+/
</file context>
| # Coverage against Cloud Monitoring (UPDATE + UPDATE_NOOP + CREATE + DELETE) | ||
| sum(rate(omi_firestore_billed_writes_total{database="default"}[30m])) | ||
| / | ||
| (avg_over_time(sum(avg by (op) (stackdriver_firestore_instance_firestore_googleapis_com_document_write_count))[30m:1m]) / 60) |
There was a problem hiding this comment.
P2: The post-deploy coverage query depends on document_write_count, but no exporter config scrapes firestore.googleapis.com/document/write_count; the exporter prefixes only include document/read_count. Add the write_count prefix to the stackdriver exporter config, or the coverage check cannot run.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/firestore-write-attribution.md, line 43:
<comment>The post-deploy coverage query depends on `document_write_count`, but no exporter config scrapes `firestore.googleapis.com/document/write_count`; the exporter prefixes only include `document/read_count`. Add the write_count prefix to the stackdriver exporter config, or the coverage check cannot run.</comment>
<file context>
@@ -0,0 +1,44 @@
+# Coverage against Cloud Monitoring (UPDATE + UPDATE_NOOP + CREATE + DELETE)
+sum(rate(omi_firestore_billed_writes_total{database="default"}[30m]))
+/
+(avg_over_time(sum(avg by (op) (stackdriver_firestore_instance_firestore_googleapis_com_document_write_count))[30m:1m]) / 60)
+```
</file context>
|
|
||
|
|
||
| def test_document_writes_counted_by_op_and_caller(client, transport): | ||
| caller = f'{__name__}:test_document_writes_counted_by_op_and_caller' |
There was a problem hiding this comment.
P2: This test expects the caller frame to be the test function, but the fake transport inserts _Transport.commit as the first non-plumbing frame, so the by-caller assertion fails. Expect the fake transport’s actual label or move the fake behind a plumbing boundary so the test exercises the intended caller attribution.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_firestore_write_probe.py, line 94:
<comment>This test expects the caller frame to be the test function, but the fake transport inserts `_Transport.commit` as the first non-plumbing frame, so the by-caller assertion fails. Expect the fake transport’s actual label or move the fake behind a plumbing boundary so the test exercises the intended caller attribution.</comment>
<file context>
@@ -0,0 +1,177 @@
+
+
+def test_document_writes_counted_by_op_and_caller(client, transport):
+ caller = f'{__name__}:test_document_writes_counted_by_op_and_caller'
+ before = {op: _billed('users/conversations', op) for op in ('set', 'update', 'create', 'delete')}
+ by_caller = _by_caller('users/conversations', 'set', caller)
</file context>
| statuses = list(response.status) | ||
| except Exception: | ||
| return writes | ||
| if len(statuses) != len(writes): |
There was a problem hiding this comment.
P2: On a BatchWrite status/write count mismatch, _applied returns every write, which overcounts writes that may have failed. Return nothing so the probe never counts an unverifiable result as applied, and log the mismatch.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/firestore_write_probe.py, line 242:
<comment>On a BatchWrite status/write count mismatch, `_applied` returns every write, which overcounts writes that may have failed. Return nothing so the probe never counts an unverifiable result as applied, and log the mismatch.</comment>
<file context>
@@ -0,0 +1,301 @@
+ statuses = list(response.status)
+ except Exception:
+ return writes
+ if len(statuses) != len(writes):
+ return writes
+ return [write for write, status in zip(writes, statuses) if not getattr(status, 'code', 0)]
</file context>
| sourceLabels: | ||
| - __name__ | ||
| regex: 'omi_(playback_writes_total|sync_.*|journey_.*|client_journey_.*|owner_recognition_conversations_total|conversation_duration_seconds(_.*)?|conversation_relevance_decision_total|conversation_summary_vector_upserts_total|conversation_relevance_decision_total|firestore_documents_per_operation(_.*)?|capture_finalization_.*|queue_oldest_ready_.*|batch_pipeline_.*|batch_ramp_heavy_owner_excluded_total|batch_shadow_.*|accept_to_summary_seconds(_.*)?|summary_terminal_total|summary_debt_.*|live_session_transcript_outcome_total|fallback_total|parakeet_request_seconds(_.*)?|firestore_billed_reads_by_(caller|origin)_total|firestore_caller_label_overflow_total|memory_released_projection_total|fsr_leader_lease_total|held_content_.*|held_recovery_pacing_.*|stt_cap_recovery_reconciliation_total|stt_cap_recovery_cohort_narrowed|stt_cap_cohort_.*|stt_cap_launch_config_errors.*|stt_cap_dispatch_decisions_total|stt_cap_provider_audio_seconds_total|legacy_sync_.*|legacy_dark_.*|jobstore_.*|capture_coverage_.*|capture_dedupe_shadow_total|capture_retry_cap_total|speaker_evidence_.*|speaker_evidence_confident_owner_total|lifecycle_refactor_shadow_total|executor_task_(active|queued)|clients_refactor_shadow_total|notes_refactor_shadow_total|notes_refactor_results_total|stt_language_gate_.*|prerecorded_vendor_.*|episode_compose_.*)|conversation_llm_input_dedupe_.*' | ||
| regex: 'omi_(playback_writes_total|sync_.*|journey_.*|client_journey_.*|owner_recognition_conversations_total|conversation_duration_seconds(_.*)?|conversation_relevance_decision_total|conversation_summary_vector_upserts_total|conversation_relevance_decision_total|firestore_documents_per_operation(_.*)?|capture_finalization_.*|queue_oldest_ready_.*|batch_pipeline_.*|batch_ramp_heavy_owner_excluded_total|batch_shadow_.*|accept_to_summary_seconds(_.*)?|summary_terminal_total|summary_debt_.*|live_session_transcript_outcome_total|fallback_total|parakeet_request_seconds(_.*)?|firestore_billed_reads_by_(caller|origin)_total|firestore_caller_label_overflow_total|firestore_billed_writes(_by_caller)?_total|firestore_write_caller_label_overflow_total|memory_released_projection_total|fsr_leader_lease_total|held_content_.*|held_recovery_pacing_.*|stt_cap_recovery_reconciliation_total|stt_cap_recovery_cohort_narrowed|stt_cap_cohort_.*|stt_cap_launch_config_errors.*|stt_cap_dispatch_decisions_total|stt_cap_provider_audio_seconds_total|legacy_sync_.*|legacy_dark_.*|jobstore_.*|capture_coverage_.*|capture_dedupe_shadow_total|capture_retry_cap_total|speaker_evidence_.*|speaker_evidence_confident_owner_total|lifecycle_refactor_shadow_total|executor_task_(active|queued)|clients_refactor_shadow_total|notes_refactor_shadow_total|notes_refactor_results_total|stt_language_gate_.*|prerecorded_vendor_.*|episode_compose_.*)|conversation_llm_input_dedupe_.*' |
There was a problem hiding this comment.
P2: This allowlist can exceed the 10,000-sample scrape limit: 2,048 callers × 108 collection patterns × 5 operations is over one million possible series. The caller cap bounds label values, not total series; enforce a series budget or omit this family from sync.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/deploy/cloud_run_gmp_sync.yaml, line 41:
<comment>This allowlist can exceed the 10,000-sample scrape limit: 2,048 callers × 108 collection patterns × 5 operations is over one million possible series. The caller cap bounds label values, not total series; enforce a series budget or omit this family from sync.</comment>
<file context>
@@ -36,7 +38,7 @@ spec:
sourceLabels:
- __name__
- regex: 'omi_(playback_writes_total|sync_.*|journey_.*|client_journey_.*|owner_recognition_conversations_total|conversation_duration_seconds(_.*)?|conversation_relevance_decision_total|conversation_summary_vector_upserts_total|conversation_relevance_decision_total|firestore_documents_per_operation(_.*)?|capture_finalization_.*|queue_oldest_ready_.*|batch_pipeline_.*|batch_ramp_heavy_owner_excluded_total|batch_shadow_.*|accept_to_summary_seconds(_.*)?|summary_terminal_total|summary_debt_.*|live_session_transcript_outcome_total|fallback_total|parakeet_request_seconds(_.*)?|firestore_billed_reads_by_(caller|origin)_total|firestore_caller_label_overflow_total|memory_released_projection_total|fsr_leader_lease_total|held_content_.*|held_recovery_pacing_.*|stt_cap_recovery_reconciliation_total|stt_cap_recovery_cohort_narrowed|stt_cap_cohort_.*|stt_cap_launch_config_errors.*|stt_cap_dispatch_decisions_total|stt_cap_provider_audio_seconds_total|legacy_sync_.*|legacy_dark_.*|jobstore_.*|capture_coverage_.*|capture_dedupe_shadow_total|capture_retry_cap_total|speaker_evidence_.*|speaker_evidence_confident_owner_total|lifecycle_refactor_shadow_total|executor_task_(active|queued)|clients_refactor_shadow_total|notes_refactor_shadow_total|notes_refactor_results_total|stt_language_gate_.*|prerecorded_vendor_.*|episode_compose_.*)|conversation_llm_input_dedupe_.*'
+ regex: 'omi_(playback_writes_total|sync_.*|journey_.*|client_journey_.*|owner_recognition_conversations_total|conversation_duration_seconds(_.*)?|conversation_relevance_decision_total|conversation_summary_vector_upserts_total|conversation_relevance_decision_total|firestore_documents_per_operation(_.*)?|capture_finalization_.*|queue_oldest_ready_.*|batch_pipeline_.*|batch_ramp_heavy_owner_excluded_total|batch_shadow_.*|accept_to_summary_seconds(_.*)?|summary_terminal_total|summary_debt_.*|live_session_transcript_outcome_total|fallback_total|parakeet_request_seconds(_.*)?|firestore_billed_reads_by_(caller|origin)_total|firestore_caller_label_overflow_total|firestore_billed_writes(_by_caller)?_total|firestore_write_caller_label_overflow_total|memory_released_projection_total|fsr_leader_lease_total|held_content_.*|held_recovery_pacing_.*|stt_cap_recovery_reconciliation_total|stt_cap_recovery_cohort_narrowed|stt_cap_cohort_.*|stt_cap_launch_config_errors.*|stt_cap_dispatch_decisions_total|stt_cap_provider_audio_seconds_total|legacy_sync_.*|legacy_dark_.*|jobstore_.*|capture_coverage_.*|capture_dedupe_shadow_total|capture_retry_cap_total|speaker_evidence_.*|speaker_evidence_confident_owner_total|lifecycle_refactor_shadow_total|executor_task_(active|queued)|clients_refactor_shadow_total|notes_refactor_shadow_total|notes_refactor_results_total|stt_language_gate_.*|prerecorded_vendor_.*|episode_compose_.*)|conversation_llm_input_dedupe_.*'
# These eagerly initialized live-STT combinations dominate empty series
# on sync workers. Keep fallbacks from sync/summary/storage components.
</file context>
…guous commits Luna r1 P2: a Commit that applies but loses its response (DeadlineExceeded, Unavailable) was uncounted. Count those writes on a separate unlabelled omi_firestore_ambiguous_commit_writes_total so the main counters stay exact for known outcomes and the ambiguity is visible. op now separates merge (mask, no precondition: set(merge=True)) from update (exists=true precondition). Commit-boundary fences such as the batch privacy token (#23894) fence every upsert but not masked updates, so sizing them needs the split. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Luna r2 P2: update(option=LastUpdateOption(...)) carries an update_time precondition, which requires the document to exist, so it is an update, not a merge upsert. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ple cap (#24228) ## Summary Train safety for the GMP sidecar's per-scrape `samples` cap (lead ruling 3d124a). Above the cap, GMP drops the instance's **whole** scrape, not just the new series. Backend Cloud Run max scrape, read-only GMP aggregates (`scrape_samples_scraped`, job `omi-cloud-run-application-metrics`): | Service | Max scrape | Note | |---|---|---| | backend | 9,339 now; 9,873 24h max | 3 instances, median 9,224 | | backend-sync | 7,704 | | | backend-sync-backfill | 6,769 | | | backend-integration | 6,042 | | | desktop-backend | 3,151 | | The next train adds to backend, beyond the write probe: - #24211 stage histogram: 96 - #24223: up to 18, behind a default-off flag - #24214: 2 - #24212: up to 2 That is up to about 118 samples against roughly 127 of headroom. Two changes: 1. **`OMI_FIRESTORE_WRITE_PROBE_ENABLED` kill switch** for the #24218 write probe. It is on unless the literal `false`. Off means `database._client` never wraps the transport, so no labelled write series exist in that process. That leaves 2 unlabelled counter samples. It is registered in `config/feature-flags.yaml` as `ops_kill`, and the registry doc is re-rendered. 2. **Shared Cloud Run sidecar cap 10,000 → 15,000** (`backend/deploy/cloud_run_gmp_sidecar.yaml`: backend, desktop-backend, notifications-job). Today backend is about 1% from losing all metrics on any new series; this restores headroom. GMP bills per sample emitted, so the cap itself costs nothing. The sync sidecar (`cloud_run_gmp_sync.yaml`, max 7,704) is unchanged. Series behaviour: - **Write probe series are per instance.** They grow with code-path diversity (distinct caller × collection × op an instance has executed, capped), not with write volume. - **At batch 100%**, instance count may grow and each instance sees more batch callers. Per-instance cardinality rises toward the caps, not with load. Recommended for the train: merge this. If the cap raise is not wanted in this train, set `OMI_FIRESTORE_WRITE_PROBE_ENABLED=false` on backend Cloud Run only. Sync, listen and pusher keep the probe. ## Product invariants affected none. Observability config only; no data path. ## Verification All runs used `backend/test.sh` under `bin/omi-heavy` + `nice -n 19`, at the unit layer: - `test_firestore_write_probe.py`: 16 passed, including the kill switch (literal `false` and ` FALSE ` leave `FirestoreClient.commit` unwrapped; unset, empty, `true`, `0`, `off` stay on). - The other tests that read the sidecar config: `test_attach_cloud_run_gmp_sidecar` (117), `test_external_list_cache`, `test_fleet_deployment`, `test_parakeet_request_metrics`, `test_relevance_metric_is_scraped`, `test_sync_absorption_metrics`. All pass. - `scripts/check_feature_flag_registry.py`: OK. ## Rollback Set the switch to `false` on any service, or revert. The cap can return to 10,000 only if the max scrape is well below it. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24228?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/24228?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24228&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. -->
## Summary Cloud Monitoring `document/write_count` shows about 15-20% of fleet Firestore writes as `UPDATE_NOOP`: about 300k of 1.6-1.9M writes per hour on 10-30 weekdays. These writes are billed and changed nothing. That is roughly 7-8M writes/day, about $10/day at $1.385/M. Nothing names the callers. Firestore's `WriteResult.update_time` is the document's previous update time when the write did not change it. A write that changed the document carries the commit time. The write probe (#24218) therefore counts a Commit write whose result `update_time` is earlier than the response `commit_time` on a new counter, `omi_firestore_noop_writes_by_caller_total{collection, caller}`. Labels reuse the probe's bounded collection allowlist and caller set; there are no IDs. Deletes carry no `update_time` and are skipped. BatchWrite has no commit time and is not classified. The sync Cloud Run scrape keeps the new counter. The doc is updated (`backend/docs/firestore-write-attribution.md`). This finds no-op writers for the Firestore write-cost mission (anx `card:firestore-writes-about-57-day-no-lever`). The cuts come once callers are named. ## Product invariants affected none. Observe-only: the probe never changes a request, a response or an error, and recording never raises. ## Verification All runs used `backend/test.sh` under `bin/omi-heavy` + `nice -n 19`, at the unit layer: - `tests/unit/test_firestore_write_probe.py`: 10 passed. New test: one commit with a changed write (`update_time` = `commit_time`), an unchanged write (earlier `update_time`) and a delete counts exactly one no-op for the calling function. - `test_attach_cloud_run_gmp_sidecar.py` 117, `test_memory_change_head.py` 50, `test_list_projection.py` 20: pass. Not run: live traffic. The check after deploy is that fleet no-op counts track Cloud Monitoring `UPDATE_NOOP` for the default database. ## Rollback Revert. Counters only. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24226?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/24226?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24226&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. -->
## Summary **Decision PR for the rollout lead** (bus 65693f / 941502). It turns the list-projection writer (#23394) off by default until its reader ramps. Measured by the write probe (#24218) on 2026-11-01 (Sunday, 15-minute window scaled per day), the list-projection version and row writes are: - Cloud Run: **1.87M/day**, 13.6% of all Cloud Run writes. - Listen: **2.11M/day**, 45.7% of listen's writes. - Pusher: not on the probe yet. So that is **≈4.0M writes/day, about $5.5/day on a Sunday and likely $8-10 on weekdays** (weekday volume ran about 1.9x). Every conversation update carries one version write and one row write. On listen, for example: - `update_conversation_segments`: 0.38M source / 0.38M version / 0.33M row per day. - `update_conversation_finished_at`: 0.33M / 0.33M / 0.33M per day. Nothing reads them: - `OMI_LIST_VERSION_EPOCH` is empty everywhere. Its ramp (owner: two-lane lead, due 2026-10-24) never started. - `utils/list_version_check.py` and the MCP card reader in `database/released_memory_projection.py` both require the epoch. - No code reads the `*_list_rows` collections. Change: - `config/list_projection.writer_enabled()` and the matching read in `released_memory_projection.py` now default to `false`. Explicit `true` still turns the writer on. - A code default reaches every writer process (Cloud Run, listen, pusher, workers, jobs) in one place. A per-service env would need a dozen declarations to stay consistent. - Registry entry: `rollout`, default off, owner two-lane lead, `review_by` 2026-11-15. - Ramp plan in the registry: 1. Set `true` on every writer service and revision. 2. Wait until no revision without it serves. 3. Run the existing epoch ramp (5% → 100%). 4. If the reader ramp is dropped, remove the writer. ## Catch-up on re-enable (lead d8fd89 / 12:48Z conditions) Stale rows and versions never serve: - **Versions.** A version is a random token in the list ETag scope, which also includes the epoch. While the writer is off, `ListVersionCheck.start` returns before reading any version, whatever the epoch. The new test covers this for both families, with and without an epoch. - **Re-enable order:** 1. Set the writer `true` on every writer service. 2. Wait until no revision without it serves. 3. Set a **fresh** `OMI_LIST_VERSION_EPOCH`. A fresh epoch changes every ETag, so a validator issued before or during the gap can never match. The first conditional request after the new epoch reads the source and issues a new tag. Existing coverage: `test_list_projection.py` "new-rollout-after-writer-gap" asserts 200 after a gap. - **Rows.** `*_list_rows` are a migration substrate that no code reads, and a partial legacy update can never mark a row ready. Any future row reader must backfill or prove coverage after a writer gap. Re-enabling alone does not make them complete. ## Would the epoch reader save more reads than these writes cost? Not shown, and not measurable today: - Read-probe origins in a Sunday hour: `/v1/conversations` 758k, `/v1/dev/user/action-items` 602k, `/v1/action-items` 236k. That is about 38M reads/day, about $17/day at $0.461/M. - That is the ceiling, reached only if every list GET were conditional and unchanged. Each conditional request also adds one version read. - No Dart client sends `If-None-Match`. With the epoch empty, `/v1/conversations` emits no `lp0` tag for HTTP caches to revalidate. - The writes cost about $5.5 on a Sunday and $8-10 on a weekday whether or not any of that saving appears. - To measure it before any ramp, this PR adds `omi_list_conditional_requests_total{origin, validator}` (3 origins × present/absent). If the present share on these routes is high, the ramp case can be made with numbers. ## Product invariants affected - INV-DATA-1: no source data changes. The rows and versions are a derived substrate. With the writer off they stop being maintained, and the epoch ramp already requires full writer convergence and a fresh epoch after any writer gap (registry note on #23394). No serving path reads them while the epoch is empty. ## Verification All runs used `backend/test.sh` under `bin/omi-heavy` + `nice -n 19`, at the unit layer: - `test_list_projection` (20), `test_memory_change_head` (50), `test_released_memory_projection` (27), `test_conversation_smart_merge_audit_sdk` (26), and the other files that reference the projection collections or installer: all pass. - Tests that assert projection writes now set `OMI_LIST_PROJECTION_WRITER_ENABLED=true` explicitly. - `scripts/check_feature_flag_registry.py`: OK. Live check after deploy: `omi_firestore_billed_writes_total{collection=~"users/(list_serving_versions|conversation_list_rows)"}` goes to ~0, and fleet `write_count` drops by about the same amount. ## Rollback Set `OMI_LIST_PROJECTION_WRITER_ENABLED=true` fleet-wide, or revert. Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…24253) ## Summary Firestore write cut (lead ruling 268f54: "take every efficiency gain"). Every successful sync segment with a content ledger ran two transactions on the same `users/*/sync_content_ledger/{content}` document: `checkpoint_sync_content_partial_result`, then `add_processed_sync_segment_id`. Each did one read and one write. The write probe (#24218) measured both at about 0.49-0.50M writes/day on backend-sync plus backfill on Sunday 2026-11-01, so this cut saves: - **≈0.5M writes/day and ≈0.5M reads/day** on Sunday; - about $0.9/day on Sunday and about $1.7/day on weekdays, at $1.385/M writes plus $0.461/M reads. `database.sync_ledger.checkpoint_and_mark_sync_segment` now does both in one transaction (one read, one write). The pipeline uses it whenever the segment has an ID; segments without one keep the checkpoint-only call. Outcomes and failure points are unchanged: - **Foreign or stale owner:** nothing is written, and the pipeline raises `SyncJobRunLeaseLost` where the old checkpoint raised (inside the segment lock, before the job marker). - **Already-processed segment:** the partial result is still checkpointed, as the old checkpoint did, and the pipeline raises after the job marker, where the old mark raised. - **Silence-only segments** (no result to checkpoint) still use `add_processed_sync_segment_id`. The ledger's processed marker now commits atomically with its result contribution, instead of after it by ordering. The cumulative partial is still written under `segment_lock`, so concurrent segments cannot regress it. Crash windows: a retry skips a segment if either the job marker or the ledger marker is set (`pipeline.py` ~3311). - New window (ledger marked, job marker not yet written): the retry skips the segment, and its ledger partial is guaranteed present. - The old window (ledger partial written, nothing marked) reprocessed the segment. That is not weaker. ## Product invariants affected - INV-DATA-1 (path match: `utils/sync/pipeline.py`, `database/sync_ledger.py`): same document, fields, owner fence and ordering guarantees. The checkpoint and marker become one atomic commit. ## Verification All runs used `backend/test.sh` under `bin/omi-heavy` + `nice -n 19`, at the unit layer, unless noted: - New `tests/unit/test_sync_ledger_checkpoint_mark.py` (6): owned new segment → one write carrying both fields; already processed → checkpoint only; four foreign-owner shapes → no write. - `test_sync_v2` (175), `test_sync_silent_failure` (65), `test_sync_two_lane` (47), `test_sync_geolocation_enrichment` (6), `test_sync_cap_coordinator` (41), `test_wal_audio_coverage_pipeline` (10): pass. Tests that mocked the two calls now mock the combined call where a segment ID exists. - Hermetic e2e (`backend/testing/e2e/run.sh -k sync`): 11 passed. ## Rollback Revert. No data migration: the document shape is identical. Failure-Class: none Line-Count-Exception: backend/utils/sync/pipeline.py | 3937 -> 3959 | one combined ledger call beside the existing checkpoint path, with its raise points kept where the separate calls raised; no new pipeline logic 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24253?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/24253?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24253&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. -->
… batch_pipeline_privacy (firestore-reads WQ26) (#23894) ## Summary Add a writer-generation fence and a task-attempt authorization memo for batch privacy checks. Authority writes rotate an opaque token in the same Firestore Commit; each authorizing transaction reads that token and its server revision before reusing a decision. The memo is bounded to 1024 entries and closes at attempt exit. Full-row snapshot consumers retain live reads. The fence is always on in writer processes. The `bpp_generation_memo` reader lever remains absent/off; this PR changes no runtime literal. Reader enablement requires a separate change after all writer services, revisions and maintenance producers converge on the fence. Same-document source/token writes need staging or an authorized production canary before broad rollout. Reader rollback: disable the lever. Writer rollback: disable all readers first, then revert the fence. Current main through `b3dc000c577b4fe5b1ebfab777f32bd040e71b9d` is merged without rewriting history. The integration counts deferred outbox writes and owner-token writes together in the 450-write budget, preserves original write-probe caller attribution through the fence, and classifies authority/token collections using fixed labels. Keep the current sync account-deletion predicate, absent-means-enabled cloud-sync consent, repair retention rules and batch admission deadlines. ## Validation 2026-11-02 readiness refresh at `8a6ad3fc399d69a41da3ff41bcc6f90759f87cf1`: three probe/fence files passed **210 tests**; canonical hermetic E2E passed **185 tests, 3 skipped, 2 expected failures** with the documented 300s local outer budget. Original nine-file coverage passed 241 distinct cases across the initial run and focused admission rerun. The parameterized late-return test now advances a controlled clock at the selected dependency boundary; the existing real-executor timeout test remains unchanged. All checks use the repository harness under omi-heavy/nice 19. Fresh normal pre-push, CI and Luna delta review remain gates before recommendation. Latest integration head `60c535f28547c73e7e410ae5ce971b5263fb6d7a` additionally merges main's Pinecone qualification change cleanly; the two affected migration/fence files passed **108 tests** through the same harness. The earlier probe/E2E paths are unchanged by that incoming-main merge. Normal pre-push gates passed at that head. Independent canonical Luna round 2 delta returned **SHIP, no findings** on 2026-11-02, verifying the combined write budget, caller attribution and late-return coverage. Fresh exact-head CI remains the final merge-readiness gate; fleet coverage/canary requirements below remain deploy gates. Historical validation from the previous published revision: - Thirteen targeted files through `backend/test.sh`, using `BACKEND_UNIT_TEST_FILE_LIST` and four workers: **480 passed**, including fence/memo/privacy, tombstones, speaker enrollment, live/serving, admission and the newly integrated transcript/Home tests. - Real loopback Firestore emulator with the repository deny-all rules: **31 passed, zero skipped**. Covers atomic source/token commits, rollback, replay/ABA, real writer paths, recursive erasure and consent opt-out. - Canonical `backend/testing/e2e/run.sh`: **180 passed, 5 skipped**. - `make preflight`: **37/37 checks passed**; the required pre-push hook also completed **54/54 checks** before the fast-forward push to the existing branch. - All local tests run through `bin/omi-heavy` at `nice -n 19`. No production data, mutations, deploy or reader enablement. The existing reviewed fence semantics are unchanged. This integration refresh needed no new Grok round under the assigned brief. Earlier review caveats and detailed atomicity proof remain in `.agent-brief/WQ26-sol-report-1027c.md`. ## Current cost evidence Read-only `ro-prod` aggregate metrics refreshed at 2026-11-01T05:59:50Z show **137.98M bpp reads in 24h** across Cloud Run (95.43M sync, 37.09M backfill); all four expected caller-metric services are present. A separate GKE aggregate was only about 2.8k/day. Last 3h scaled to a daily run rate: 174.91M; last 1h: 169.30M. These are origin-read measurements, not realized savings. Production-project billing export on Oct 29–30 gives **$0.46144/M reads**, valuing that 24h origin at **$63.67/day**. The repeated-path test reductions (store 100→24; artifact decision-only 100→44; full-row export 100→100) imply **$35.66–$48.39/day gross potential only if traffic has those hit patterns**. Added fence writes cost about $1.385/M at the same billing basis; eligible traffic share, hit rate, write amplification and net savings still need a fenced-fleet canary. No net saving is claimed. ## Added writes and contention (fswrites, 2026-11-01) Luna's notes at `f773647` are fixed in `cda54a27`: - **P2, no-op rotation.** Sync assignment wrote `private_cloud_sync_enabled` and the other conversation authority fields into every update payload, so the fence rotated the token even when nothing changed. Assignment now omits an authority field equal to this transaction's read of the row. An omitted field is the committed value, and a concurrent change aborts the transaction. A field absent from the row is never omitted, because absent consent means enabled. A real authority change still rotates. Fence and writers share one field set (`batch_privacy_attempt.CONVERSATION_AUTHORITY_FIELDS`). - **P3, write budget.** `FirestoreTransaction.flush` now counts the one token write per owner that its `record_lane_owner` patches add. - Tests: `tests/unit/test_bpp_fence_write_budget.py` (4), plus the 69 related unit files, all passing. Sizing comes from real counts, and the PR does not ship before them: 2026-11-02 14:39Z ro-prod aggregate refresh observed **1,910,961 queried source writes/24h** and **100,312.6/1h**. This is an observed source-counter envelope, not an exact token-write forecast or fleet bound: it includes metadata writes that do not rotate tokens and repeated writes for the same owner. Four Cloud Run probes are present; listen/pusher coverage and maintenance producers remain unproven, and previously unclassified collections cannot be inferred idle from zero series. Lead owns this remaining sizing/canary gate and the fleet deploy; no net saving is claimed. The fswritesr caller-based estimate narrows the observed Cloud Run scope to at most ~1.30M added token writes/day at the measured traffic mix (~$1.80/day using the earlier $1.385/M billing basis). Its ~1.77M/day estimate at batch 100% assumes admission's average share was ~30% during the window; the likely lower figures depend on unmeasured no-op rates. These estimates omit listen/pusher and maintenance traffic, so they do not close the fleet bound. Measure actual token writes and per-caller contention during the writer canary before any reader enablement; lead sets the canary decision from complete coverage. - The write probe (#24218) counts writes per day by collection, `op` (create, update, merge, set, delete) and caller. - The fence's added writes are bounded per day by: - user-root commits of `merge`, `set`, `create` and `delete`, which includes `record_user_platform`'s merge every 10 min per active user per platform; - conversation commits of `set`, `merge`, `create` and `delete`; - conversation `update` commits from the callers that write authority fields: batch admission (`record_lane_owner`), sync assignment, and donor redirects. - The probe gives these by caller at batch 5%. The 100% forecast scales the batch-admission share by 20x and keeps the others flat. Contention: the token joins every authority transaction for its owner. Transactions on different conversations of the same owner that each change authority now conflict on one document (sustained limit about 1 write/s per document). Sync (per-uid lease) and batch owner drains are serial per owner. The cross-service overlap (listen create, sync, batch, pusher) is what to watch. Measure it as the Aborted/contention rate on those callers at the canary, before readers. Order: - **Ship:** writer fence on every writer service and revision (backend, sync, backfill, integration, listen, pusher, workers and maintenance jobs). Wait until no pre-fence revision serves traffic, then enable the `bpp_generation_memo` reader at 5%, then 100%. - **Rollback:** readers off first (lever 0), then revert the fence. ## Product invariants affected - INV-MEM-4 — privacy/deletion decisions stay live or require the exact token plus server-revision tuple; authority mutation rotates the token atomically, forcing re-read and re-denial on contention. - INV-DATA-1 — existing data planes and configuration conventions remain; client identity is part of the memo key. Failure-Class: none This is a read-cost optimization with privacy-fence and integration regression coverage, rather than an instance of a recorded production failure class. Line-Count-Exception: backend/routers/sync.py | 3736 -> 3738 | batch-privacy attempt authorization import and decorator on the existing sync entrypoint; no route logic expansion. Line-Count-Exception: backend/utils/sync/assignment.py | 1497 -> 1515 | Omit unchanged conversation authority fields inside the existing assignment transaction so no-op updates do not rotate generation tokens; share the authoritative field set with the privacy fence.
Summary
Firestore writes cost about $57/day: 41M writes/day in the billing export for 10-27..10-30, up from about 22M/day through 10-25. The step started 2026-10-26 around 00-01Z. Nothing can attribute it. The only write signal is Cloud Monitoring
document/write_count, which carries only anoplabel, and Firestore data-access audit logs are off.This adds
backend/database/firestore_write_probe.py, the write-side twin of the read probe. It wraps the GAPIC transportFirestoreClient.commit/batch_write(sync and async). Every SDK write path reaches one of them: batches,DocumentReference.set/update/create, transactions,DocumentReference.deleteand BulkWriter. The probe therefore counts each request as sent. That includes the writes the commit-boundary patches append:list_projectionadds a version write, plus a row write when list fields change, to every write underusers/*/conversations|action_items, andmemory_change_headadds a head write to every memory commit.database._clientinstalls the probe before those patches (verified: the change-head wrapper is outermost, the probe is beneath it).omi_firestore_billed_writes_total{collection,op,database}omi_firestore_billed_writes_by_caller_total{collection,op,caller}omi_firestore_billed_writes_by_origin_total{origin,collection,op}omi_firestore_write_caller_label_overflow_totalopis create/update/set/delete/transform. A failed Commit counts nothing; BatchWrite counts only OK statuses.users/list_serving_versions,users/conversation_list_rowsandusers/action_item_list_rows.other.cloud_run_gmp_sync.yaml): keeps the total and by-caller counters. It leaves out by-origin to stay under its 10k samples limit. Backend and listen already keepomi_.*.backend/docs/firestore-write-attribution.md.This is the measurement step for the Firestore write-cost mission (anx card
firestore-writes-about-57-day-no-lever). The cuts come in follow-up PRs once this serves.Product invariants affected
none. The probe only observes; it never changes the request, the response or the error. Recording never raises.
Verification
All runs used
backend/test.shunderbin/omi-heavy+nice -n 19at the unit layer:tests/unit/test_firestore_write_probe.py: 8 passed. Covers op classification, document set/merge/update/create/delete through a realfirestore.Clientwith a fake transport, batch, failed commit, BatchWrite partial status, change-head appended write, recording failure, idempotent install and the caller cap.test_attach_cloud_run_gmp_sidecar.py(117) andtest_firestore_document_probe.py(129): pass.test_list_projection,test_memory_change_head,test_conversation_smart_merge_audit_sdk,test_v3_f6_readonly_contractsand the other suites that import the commit patches: all pass.import database._client, theFirestoreClient.commitchain is change-head → write probe → SDK.Not run: live traffic. The coverage ratio against
write_countis the post-deploy check (PromQL is in the doc).Rollback
Revert this PR. The probe has no data path. Removing it removes only the counters.
Failure-Class: none
🤖 Generated with Claude Code