Repository navigation
feat(monitoring): detect bounded lifecycle pair drift and repair stock - #24609
Conversation
…ce stock Retain independently fresh per-leg observations behind a fleet-wide cursor lease. Page only on recent job-created cohorts; keep legacy and unclocked stock at agent tier. Register indexes, exporter routes, gate UIDs and hermetic contracts without workflow edits.
Use severity timing and byte-identical split/combined rule exports, refresh the offline consumer inventory, and expect the added conversation field-index mode.
Exclude nested archived collection-group rows while retaining their valid keyset cursors so a full excluded page cannot stall the scan. Cover both count exclusion and cursor continuation without weakening the 402-read budget.
Keep three bounded keyset cursors and rotate after every page, including full pages, so legacy jobs cannot starve queued or processing mirror observations. Cover cursor resumption, the shared read cap and queued-mirror progress under a full jobs backlog; retain pre-map checkpoint compatibility.
Integrate the merged lifecycle dwell alarms and current approved main changes before publishing alarms 3+4 against main, per thread-owner ruling b75318.
Use the recent-cohort metric queried by the merged BYOK dwell page. Expand actual PhaseMetrics instances from source-declared Gauge suffixes, and reject invented prefixes and suffixes without weakening assertions. Scoped B1 integration authorized by rulings 6cac95 and cf1a59.
Correct copied BYOK example thresholds in the six pair/repair rules and describe repair stock without claiming it measures a pair census. Keep expressions, thresholds, pending durations and routes unchanged.
Integrate the seal-repair scheduling fix and current speaker changes before the final PR2 validation and publication. Preserve the scoped BYOK test correction shared with priority PR #24605.
Build PR2 on the exact standalone #24605 head while lead2 owns its green merge. The equivalent test correction is already present; preserve the validated source tree and make the parent relationship explicit.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e34b389287
ℹ️ 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".
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "max((sum without(kind) (omi_finalization_pair_new_mismatch)) and (time() - omi_finalization_pair_observed_at_seconds < 2100))", |
There was a problem hiding this comment.
Select the newest observation per leg before evaluating drift
When census ownership moves between still-running replicas, this expression retains the previous owner's high count even after the new owner observes zero for the same leg. observe() leaves nonleaders' gauges unchanged, and main.py::_run_fsr_loop does not withdraw finalization metrics on ownership loss. For example, an old owner's count of 30 at minute 0 continues to win this max() until minute 35, despite a new owner's zero at minute 15, allowing the 30-minute human page to fire after the mismatch has cleared. Filter each leg to its newest observation across replicas before evaluating its count, rather than treating every observation within the freshness window as equally current. Apply the equivalent correction to the combined rule export.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
6 issues found across 25 files
Confidence score: 4/5
- In
alert-rules.json, the stock alert can stay above 25 after another replica takes over because it isn't joined to the observer clock. Align it with the drift rule's clock join. - In
lifecycle_pair_census.py, a futurecreated_atsilently suppressesNEW_MISMATCH, so the freshness alarm can report a confident zero with an untrusted clock. Treat future timestamps as untrusted. - In
test_lifecycle_pair_census.py, the test bypassesrun_pagecursor persistence andobservemetric publication, so it doesn't verify the behavior in its title. Exercise the failure through those boundaries. - In
resilience.json,safe_next_actionrefers to an observed state pair that this rule doesn't measure. Replace it with guidance for summary-repair stock.
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/charts/monitoring/lifecycle-alarms.md">
<violation number="1" location="backend/charts/monitoring/lifecycle-alarms.md:12">
P3: Name the metric families the exporter allowlists must keep instead of 'the lifecycle metric families'. The exporter filters now include `omi_finalization_pair_`, `omi_enrichment_summary_repair_`, `omi_enrichment_obligation_`, and `omi_finalization_byok_`, so the runbook should list them.</violation>
</file>
<file name="backend/charts/monitoring/prometheus-stackdriver-exporter/dev_sync_omi_cloud_run_metrics_exporter.yaml">
<violation number="1" location="backend/charts/monitoring/prometheus-stackdriver-exporter/dev_sync_omi_cloud_run_metrics_exporter.yaml:35">
P3: The file header requires every added family to name its consumer, but these two prefixes have no entry there. Add a header line naming the lifecycle alerts (`alerts/resilience.json`) as their consumer, and move the new prefixes below the `# WP-C lifecycle` comment so that comment keeps labeling its group.</violation>
</file>
<file name="backend/tests/unit/test_lifecycle_pair_census.py">
<violation number="1" location="backend/tests/unit/test_lifecycle_pair_census.py:337">
P3: This test cannot verify the behavior named in its title because it bypasses both `run_page` cursor persistence and `observe` metric publication. Exercise the failure through those boundaries and assert the scan document and gauges remain unchanged.</violation>
</file>
<file name="backend/charts/monitoring/alerts/resilience.json">
<violation number="1" location="backend/charts/monitoring/alerts/resilience.json:6943">
P3: This `safe_next_action` is copied from the pair-drift rules and refers to an "observed state pair", which this rule does not measure. Replace it with guidance for summary-repair stock, e.g. assign the enrichment summary-repair backlog to its owner and confirm the cohort before any repair.</violation>
</file>
<file name="backend/charts/monitoring/alert-rules.json">
<violation number="1" location="backend/charts/monitoring/alert-rules.json:27312">
P2: The stock expr is not joined to the observer clock, unlike the drift rule. Each replica keeps its last `omi_finalization_pair_mismatch` values after another replica takes over the leg, so this stock can stay above 25 on stale counts. Join it per series: `max(sum without(kind) (omi_finalization_pair_mismatch) and (time() - omi_finalization_pair_observed_at_seconds < 2100))`. The contract test pins the current expr and will need updating with it.</violation>
</file>
<file name="backend/utils/lifecycle_pair_census.py">
<violation number="1" location="backend/utils/lifecycle_pair_census.py:173">
P2: Future `created_at` values silently suppress `NEW_MISMATCH` without marking the page blind. Treat a timestamp later than `current` as an untrusted clock so the freshness alarm cannot report a confident zero.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "max(sum without(kind) (omi_finalization_pair_mismatch))", |
There was a problem hiding this comment.
P2: The stock expr is not joined to the observer clock, unlike the drift rule. Each replica keeps its last omi_finalization_pair_mismatch values after another replica takes over the leg, so this stock can stay above 25 on stale counts. Join it per series: max(sum without(kind) (omi_finalization_pair_mismatch) and (time() - omi_finalization_pair_observed_at_seconds < 2100)). The contract test pins the current expr and will need updating with it.
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/charts/monitoring/alert-rules.json, line 27312:
<comment>The stock expr is not joined to the observer clock, unlike the drift rule. Each replica keeps its last `omi_finalization_pair_mismatch` values after another replica takes over the leg, so this stock can stay above 25 on stale counts. Join it per series: `max(sum without(kind) (omi_finalization_pair_mismatch) and (time() - omi_finalization_pair_observed_at_seconds < 2100))`. The contract test pins the current expr and will need updating with it.</comment>
<file context>
@@ -27130,5 +27130,957 @@
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "expr": "max(sum without(kind) (omi_finalization_pair_mismatch))",
+ "instant": true,
+ "intervalMs": 1000,
</file context>
| entered = None | ||
| if entered is None: | ||
| blind = True # No clock can prove a new regression. | ||
| elif max(COHORT_START, current - 86400) <= entered <= current: |
There was a problem hiding this comment.
P2: Future created_at values silently suppress NEW_MISMATCH without marking the page blind. Treat a timestamp later than current as an untrusted clock so the freshness alarm cannot report a confident zero.
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/utils/lifecycle_pair_census.py, line 173:
<comment>Future `created_at` values silently suppress `NEW_MISMATCH` without marking the page blind. Treat a timestamp later than `current` as an untrusted clock so the freshness alarm cannot report a confident zero.</comment>
<file context>
@@ -0,0 +1,239 @@
+ entered = None
+ if entered is None:
+ blind = True # No clock can prove a new regression.
+ elif max(COHORT_START, current - 86400) <= entered <= current:
+ fresh[kind] += 1
+ next_state = {
</file context>
| elif max(COHORT_START, current - 86400) <= entered <= current: | |
| + elif entered > current: | |
| + blind = True | |
| + elif max(COHORT_START, current - 86400) <= entered <= current: |
| needed. Deploy emitters and reconcile their indexes before importing rules. | ||
| The dev/prod Cloud Run exporter allowlists and sync-sidecar keep filter carry | ||
| these four metric families. Their existing ten-minute collection and one-minute | ||
| the lifecycle metric families. Their existing ten-minute collection and one-minute |
There was a problem hiding this comment.
P3: Name the metric families the exporter allowlists must keep instead of 'the lifecycle metric families'. The exporter filters now include omi_finalization_pair_, omi_enrichment_summary_repair_, omi_enrichment_obligation_, and omi_finalization_byok_, so the runbook should list them.
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/charts/monitoring/lifecycle-alarms.md, line 12:
<comment>Name the metric families the exporter allowlists must keep instead of 'the lifecycle metric families'. The exporter filters now include `omi_finalization_pair_`, `omi_enrichment_summary_repair_`, `omi_enrichment_obligation_`, and `omi_finalization_byok_`, so the runbook should list them.</comment>
<file context>
@@ -1,15 +1,15 @@
needed. Deploy emitters and reconcile their indexes before importing rules.
The dev/prod Cloud Run exporter allowlists and sync-sidecar keep filter carry
-these four metric families. Their existing ten-minute collection and one-minute
+the lifecycle metric families. Their existing ten-minute collection and one-minute
offset, plus the five-minute producer cadence, need a 20-minute freshness
budget for enrichment/BYOK. Direct batch samples keep the 15-minute budget.
</file context>
| the lifecycle metric families. Their existing ten-minute collection and one-minute | |
| the lifecycle metric families (omi_finalization_pair_, omi_enrichment_summary_repair_, omi_enrichment_obligation_, omi_finalization_byok_). Their existing ten-minute collection and one-minute |
| - "based-hardware-dev" | ||
| metrics: | ||
| prefixes: | ||
| - 'prometheus.googleapis.com/omi_finalization_pair_' |
There was a problem hiding this comment.
P3: The file header requires every added family to name its consumer, but these two prefixes have no entry there. Add a header line naming the lifecycle alerts (alerts/resilience.json) as their consumer, and move the new prefixes below the # WP-C lifecycle comment so that comment keeps labeling its group.
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/charts/monitoring/prometheus-stackdriver-exporter/dev_sync_omi_cloud_run_metrics_exporter.yaml, line 35:
<comment>The file header requires every added family to name its consumer, but these two prefixes have no entry there. Add a header line naming the lifecycle alerts (`alerts/resilience.json`) as their consumer, and move the new prefixes below the `# WP-C lifecycle` comment so that comment keeps labeling its group.</comment>
<file context>
@@ -32,6 +32,8 @@ stackdriver:
- "based-hardware-dev"
metrics:
prefixes:
+ - 'prometheus.googleapis.com/omi_finalization_pair_'
+ - 'prometheus.googleapis.com/omi_enrichment_summary_repair_'
# WP-C lifecycle dwell and observer health (closed labels).
</file context>
| {'users/synthetic/conversations/one': {'finalization_status': 'queued', 'finalization_job_id': 'one'}} | ||
| ) | ||
| monkeypatch.setattr(client, 'get_all', lambda *a, **kw: []) | ||
| with pytest.raises(ValueError, match='incomplete counterpart'): |
There was a problem hiding this comment.
P3: This test cannot verify the behavior named in its title because it bypasses both run_page cursor persistence and observe metric publication. Exercise the failure through those boundaries and assert the scan document and gauges remain unchanged.
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_lifecycle_pair_census.py, line 337:
<comment>This test cannot verify the behavior named in its title because it bypasses both `run_page` cursor persistence and `observe` metric publication. Exercise the failure through those boundaries and assert the scan document and gauges remain unchanged.</comment>
<file context>
@@ -0,0 +1,370 @@
+ {'users/synthetic/conversations/one': {'finalization_status': 'queued', 'finalization_job_id': 'one'}}
+ )
+ monkeypatch.setattr(client, 'get_all', lambda *a, **kw: [])
+ with pytest.raises(ValueError, match='incomplete counterpart'):
+ census.sample(client, {'phase': 'queued'})
+ assert client.writes == []
</file context>
| "user_impact": "Conversation/job split states can leave captured conversations unprocessed or display stale completion.", | ||
| "scope": "Leader-fenced cursor census: active jobs, queued mirrors, processing conversations. <=200 indexed source docs + <=200 counterpart docs + 2 lease/cursor reads per admitted pass; >=300s cadence. Counts are bounded-page mismatches, not global stock. Deleted/discarded/merged/deferred conversations and superseded generations are excluded. Page cohort requires job.created_at within24h AND at/after2026-11-04T09:27Z. Missing jobs/entry clocks, idle terminal history and bare processing rows without a job link are outside fresh-page coverage; unknown clocks mark blind. Owner uicleanup tracks missing-clock debt. Each leg retains its last page independently, so another leg cannot reset the alert.35m freshness covers the nominal15m three-leg rotation plus10m bridge/1m offset; stale checks the freshest observer of every leg. Only users/{uid}/conversations/{cid} mirrors are inspected; other collection-group paths mark blind and are skipped, while the cursor still advances past them.", | ||
| "verification": "Check observation freshness, scan incompleteness and consecutive page samples. The pair gauge measures one bounded page, not the fleet mismatch total.", | ||
| "safe_next_action": "Assign the observed state pair or repair-fence debt to its owning lifecycle lane. Confirm the exact generation before any repair. Never replay or delete rows automatically from this alert.", |
There was a problem hiding this comment.
P3: This safe_next_action is copied from the pair-drift rules and refers to an "observed state pair", which this rule does not measure. Replace it with guidance for summary-repair stock, e.g. assign the enrichment summary-repair backlog to its owner and confirm the cohort before any repair.
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/charts/monitoring/alerts/resilience.json, line 6943:
<comment>This `safe_next_action` is copied from the pair-drift rules and refers to an "observed state pair", which this rule does not measure. Replace it with guidance for summary-repair stock, e.g. assign the enrichment summary-repair backlog to its owner and confirm the cohort before any repair.</comment>
<file context>
@@ -6813,5 +6813,957 @@
+ "user_impact": "Conversation/job split states can leave captured conversations unprocessed or display stale completion.",
+ "scope": "Leader-fenced cursor census: active jobs, queued mirrors, processing conversations. <=200 indexed source docs + <=200 counterpart docs + 2 lease/cursor reads per admitted pass; >=300s cadence. Counts are bounded-page mismatches, not global stock. Deleted/discarded/merged/deferred conversations and superseded generations are excluded. Page cohort requires job.created_at within24h AND at/after2026-11-04T09:27Z. Missing jobs/entry clocks, idle terminal history and bare processing rows without a job link are outside fresh-page coverage; unknown clocks mark blind. Owner uicleanup tracks missing-clock debt. Each leg retains its last page independently, so another leg cannot reset the alert.35m freshness covers the nominal15m three-leg rotation plus10m bridge/1m offset; stale checks the freshest observer of every leg. Only users/{uid}/conversations/{cid} mirrors are inspected; other collection-group paths mark blind and are skipped, while the cursor still advances past them.",
+ "verification": "Check observation freshness, scan incompleteness and consecutive page samples. The pair gauge measures one bounded page, not the fleet mismatch total.",
+ "safe_next_action": "Assign the observed state pair or repair-fence debt to its owning lifecycle lane. Confirm the exact generation before any repair. Never replay or delete rows automatically from this alert.",
+ "runbook": "backend/charts/monitoring/lifecycle-alarms.md",
+ "threshold": "max((sum without(kind) (omi_finalization_pair_new_mismatch)) and (time() - omi_finalization_pair_observed_at_seconds < 2100)) > 25 for 30m",
</file context>
| "safe_next_action": "Assign the observed state pair or repair-fence debt to its owning lifecycle lane. Confirm the exact generation before any repair. Never replay or delete rows automatically from this alert.", | |
| "safe_next_action": "Assign the summary-repair stock to its owning enrichment lane. Confirm the cohort before any repair. Never replay or delete rows automatically from this alert.", |
A prior leader's retained mismatch must not override a later clear sample. Select the latest observation clock per leg before aggregating page, stock and blind values; keep the cohort, thresholds and freshness budgets. Add an offline Prometheus regression for clear, continuing drift, separate legs, stale data and missing observers. The old expressions fail it and the corrected expressions pass. Regenerate the source query inventory.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 92de62500b
ℹ️ 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".
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "max(omi_enrichment_summary_repair_count)", |
There was a problem hiding this comment.
Exclude stale observers from the repair-stock alert
If an observer samples 101 repair obligations and subsequently cannot refresh, PhaseMetrics.refresh() retains its count gauge while leaving its observation timestamp unchanged. This unconditional maximum continues using that value for as long as the process is scraped, even if another observer successfully reports zero. Consequently, a transient backlog can satisfy the one-hour pending timer after recovery and keep the agent alert firing indefinitely; the stale companion can remain healthy because it uses the newest timestamp across observers. Select the newest successful repair-stock observation and apply its freshness budget before aggregating the count. Update the combined rule export equivalently.
Useful? React with 👍 / 👎.
WP-C alarms 3+4, following #24595 and built on the exact test-only correction in #24605.
The finalization observer rotates through three indexed domains: active jobs, queued mirrors and processing conversations. Each domain retains its own last bounded page and observation clock. A full jobs page cannot starve the mirror domains, and another domain's zero cannot reset an ongoing mismatch. Page, stock and blind queries select the newest successful observer for each domain before aggregating values, so a later clear supersedes an older replica's bad snapshot even when leadership changes between services.
Page only when a retained page has more than 25 recent-job mismatches for 30 minutes. The job creation timestamp must be within 24 hours and at or after 2026-11-04 09:27Z. Historical mismatch stock remains agent tier. A 35-minute freshness budget covers the nominal 15-minute rotation and the existing bridge delay. Stale checks the freshest observer of every domain; stale/blind companions and all new UIDs are in the existing import gate. Rules use the already-triggered resilience JSON; no workflow edit is needed.
The second alarm reports agent-tier active summary_repair=true stock, using COUNT capped at 101 to prove stock above 100. It does not claim to measure retry attempts or cap hits: no numeric retry cap exists in the source. This is the approved substitute in ruling4256d5.
Read budget and coverage:
Missing clocks, sparse coverage and the actual retry-cap policy remain owner uicleanup under card:lcalarm-lifecycle-alarms, next 2026-11-04 18:00Z. The observer performs no repair, notification, deletion or admission/retry leak fix. No live.py or serving.py changes.
Validation: canonical backend/test.sh with the explicit 32-file integration list passed 1,443 tests with 79 inherited strict expected failures and three existing monitoring skips at c65d7c1 (source-identical to first published head e34b389). That head's guarded push passed full preflight, 829 Firestore guards, type checking and 330 selected backend tests. Luna R1 then identified the stale-replica false page. The real Prometheus engine regression fails against those old expressions and passes after correction c3f972d, including a newer clear, continuing drift, independent legs, stale data and absent observers. The focused 23-file monitoring/semantic shard passes 579 tests with three existing skips. The optional engine test takes PROMTOOL_BIN and performs no download/network/server startup; CI explicitly skips that engine check if the binary is absent, while always-on contracts pin the reviewed query. Local correction validation and its guarded push provide the real engine proof. CI state remains authoritative in the PR checks; the final independent review is delta-only under the two-round limit. Every local check/push uses default omi-heavy run -- nice -n 19 and scrubs the five GCP credential/project variables. No GCP calls or live validation.
Deploy needed: reconcile the added repair composite and conversation-group field index; backend/listen and sync emitter train including the revision-local GMP profile; then existing metrics-egress/Grafana import. Lead owns every merge and deployment. Current-head CI must supply stack proof under ruling39e8fe's local teardown limitation.
Initiative: capture/transcription/speakers
Failure-Class: none
Line-Count-Exception: backend/database/firestore_index_registry.py | 2284 -> 2285 | Register the conversation group field index for the bounded pair census beside its existing owner.