Repository navigation
Finalization: alert on jobs stuck in blocked_byok and dead_letter - #24533
Conversation
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. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
5 issues found across 12 files
Confidence score: 3/5
test_monitoring_alert_rule_contract.pycan pass even when Grafana evaluates the wrong expression or condition. Assert thatconditionisCandB.expressionisA.test_monitoring_alert_rule_contract.pydoes not protect the agent’s silent-window routing, so an empty or unrelated mute interval could pass. Assert agent rules use['omi-tier-silent']and other rules omit it.alert-rules.jsoncan alert on stale stock and age values if Firestore publishing stops, because the rules do not require a fresh summary. Add a freshness check to these alerts.listen_finalization_jobs.mdxdescribes a paging threshold based on creation age, not current dwell time, so re-blocked jobs with short current dwell may still page. Clarify that behavior or base the page on time since the last event.
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/listen_pusher_pipeline/changes/2026-11-03-finalization-dwell-alerts.md">
<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-03-finalization-dwell-alerts.md:12">
P3: The `Initiative` link points to a claude.ai artifact, which is not a repo-owned or durable reference. Link the initiative to a ticket or repo document that other readers can access, or drop the link.</violation>
</file>
<file name="backend/docs/listen_finalization_jobs.mdx">
<violation number="1" location="backend/docs/listen_finalization_jobs.mdx:162">
P2: The paging threshold is applied to creation age, which the same section says is not dwell time. Either document that the page can fire on re-blocked jobs with short current dwell, or base the page on time since last entry into `blocked_byok` before a human is paged.</violation>
</file>
<file name="backend/tests/unit/test_monitoring_alert_rule_contract.py">
<violation number="1" location="backend/tests/unit/test_monitoring_alert_rule_contract.py:2025">
P1: This contract does not verify that Grafana evaluates the threshold over the Prometheus query: a bad `B`/`C` expression or top-level condition would still pass. Assert the `condition == "C"`, `B.expression == "A"`, and `C.expression == "B"` wiring for these rules.</violation>
<violation number="2" location="backend/tests/unit/test_monitoring_alert_rule_contract.py:2043">
P2: Checking only for `mute_time_intervals` does not protect the agent routing policy: an empty or unrelated interval would pass and alter silent-window behavior. Assert `['omi-tier-silent']` for agent rules and absence of the key for the page rule.</violation>
</file>
<file name="backend/charts/monitoring/alert-rules.json">
<violation number="1" location="backend/charts/monitoring/alert-rules.json:12381">
P2: These summary-derived alerts do not require a fresh finalization summary. If Firestore publishing stops, the process retains the previous gauge values, so the new stock/age rules can fire on stale data and the 7-day rule can page after the current state has changed. Gate the four gauge/status queries on `listen_finalization_summary_last_success_timestamp_seconds` being fresh, or otherwise suppress them while the existing summary-stale condition is active.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| rule = rules[uid] | ||
| assert rule['data'][0]['model']['expr'] == expr, (export_name, uid) | ||
| assert rule['data'][0]['datasourceUid'] == 'prometheus' | ||
| assert rule['data'][2]['model']['conditions'][0]['evaluator'] == {'params': [threshold], 'type': 'gt'} |
There was a problem hiding this comment.
P1: This contract does not verify that Grafana evaluates the threshold over the Prometheus query: a bad B/C expression or top-level condition would still pass. Assert the condition == "C", B.expression == "A", and C.expression == "B" wiring for these rules.
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_monitoring_alert_rule_contract.py, line 2025:
<comment>This contract does not verify that Grafana evaluates the threshold over the Prometheus query: a bad `B`/`C` expression or top-level condition would still pass. Assert the `condition == "C"`, `B.expression == "A"`, and `C.expression == "B"` wiring for these rules.</comment>
<file context>
@@ -1982,3 +1982,62 @@ def test_backfill_queue_wait_warning_uses_dispatched_histogram_and_sustained_p95
+ rule = rules[uid]
+ assert rule['data'][0]['model']['expr'] == expr, (export_name, uid)
+ assert rule['data'][0]['datasourceUid'] == 'prometheus'
+ assert rule['data'][2]['model']['conditions'][0]['evaluator'] == {'params': [threshold], 'type': 'gt'}
+ assert rule['for'] == pending
+ assert rule['noDataState'] == 'NoData'
</file context>
| | --- | --- | | ||
| | `listen_finalization_oldest_nonterminal_age_seconds` | Oldest `queued` + `leased` job (system-owned work); alert on sustained age above the queue/lease budget. | | ||
| | `listen_finalization_oldest_blocked_byok_age_seconds` | Oldest job waiting for the user to reconnect with keys; informational, no alert. | | ||
| | `listen_finalization_oldest_blocked_byok_age_seconds` | Informational above 3 days; page above 7 days (both sustained 15 minutes). Reconnect with valid user keys before the 14-day abandonment bound. | |
There was a problem hiding this comment.
P2: The paging threshold is applied to creation age, which the same section says is not dwell time. Either document that the page can fire on re-blocked jobs with short current dwell, or base the page on time since last entry into blocked_byok before a human is paged.
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/listen_finalization_jobs.mdx, line 162:
<comment>The paging threshold is applied to creation age, which the same section says is not dwell time. Either document that the page can fire on re-blocked jobs with short current dwell, or base the page on time since last entry into `blocked_byok` before a human is paged.</comment>
<file context>
@@ -145,21 +145,50 @@ reconciler reads a server-side bounded page of due jobs using
| --- | --- |
| `listen_finalization_oldest_nonterminal_age_seconds` | Oldest `queued` + `leased` job (system-owned work); alert on sustained age above the queue/lease budget. |
-| `listen_finalization_oldest_blocked_byok_age_seconds` | Oldest job waiting for the user to reconnect with keys; informational, no alert. |
+| `listen_finalization_oldest_blocked_byok_age_seconds` | Informational above 3 days; page above 7 days (both sustained 15 minutes). Reconnect with valid user keys before the 14-day abandonment bound. |
| `listen_finalization_jobs{status="queued"}` / `{status="leased"}` | Alert on sustained backlog, not a single recovery. |
| `listen_finalization_retries_total` | Investigate a rate increase with queue/worker error rates. |
</file context>
| assert rule['annotations']['runbook'] == 'backend/docs/listen_finalization_jobs.mdx' | ||
| assert rule['annotations']['safe_next_action'] | ||
| assert rule['notification_settings']['receiver'] == 'Omi - Services Alerting (Telegram)' | ||
| assert ('mute_time_intervals' in rule['notification_settings']) == (tier != 'page') |
There was a problem hiding this comment.
P2: Checking only for mute_time_intervals does not protect the agent routing policy: an empty or unrelated interval would pass and alter silent-window behavior. Assert ['omi-tier-silent'] for agent rules and absence of the key for the page rule.
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_monitoring_alert_rule_contract.py, line 2043:
<comment>Checking only for `mute_time_intervals` does not protect the agent routing policy: an empty or unrelated interval would pass and alter silent-window behavior. Assert `['omi-tier-silent']` for agent rules and absence of the key for the page rule.</comment>
<file context>
@@ -1982,3 +1982,62 @@ def test_backfill_queue_wait_warning_uses_dispatched_histogram_and_sustained_p95
+ assert rule['annotations']['runbook'] == 'backend/docs/listen_finalization_jobs.mdx'
+ assert rule['annotations']['safe_next_action']
+ assert rule['notification_settings']['receiver'] == 'Omi - Services Alerting (Telegram)'
+ assert ('mute_time_intervals' in rule['notification_settings']) == (tier != 'page')
</file context>
| "type": "prometheus", | ||
| "uid": "prometheus" | ||
| }, | ||
| "expr": "max(listen_finalization_oldest_blocked_byok_age_seconds)", |
There was a problem hiding this comment.
P2: These summary-derived alerts do not require a fresh finalization summary. If Firestore publishing stops, the process retains the previous gauge values, so the new stock/age rules can fire on stale data and the 7-day rule can page after the current state has changed. Gate the four gauge/status queries on listen_finalization_summary_last_success_timestamp_seconds being fresh, or otherwise suppress them while the existing summary-stale condition is active.
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 12381:
<comment>These summary-derived alerts do not require a fresh finalization summary. If Firestore publishing stops, the process retains the previous gauge values, so the new stock/age rules can fire on stale data and the 7-day rule can page after the current state has changed. Gate the four gauge/status queries on `listen_finalization_summary_last_success_timestamp_seconds` being fresh, or otherwise suppress them while the existing summary-stale condition is active.</comment>
<file context>
@@ -12357,6 +12357,778 @@
+ "type": "prometheus",
+ "uid": "prometheus"
+ },
+ "expr": "max(listen_finalization_oldest_blocked_byok_age_seconds)",
+ "instant": true,
+ "intervalMs": 1000,
</file context>
| No state transition, retention bound, credential handling, flag or wire contract | ||
| changes. The rollout lead owns deploy and monitoring provisioning. | ||
|
|
||
| Initiative: [explicit-state latch invariant](https://claude.ai/artifact/7srvSdinev4M8oiSKotRiU). |
There was a problem hiding this comment.
P3: The Initiative link points to a claude.ai artifact, which is not a repo-owned or durable reference. Link the initiative to a ticket or repo document that other readers can access, or drop the link.
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/listen_pusher_pipeline/changes/2026-11-03-finalization-dwell-alerts.md, line 12:
<comment>The `Initiative` link points to a claude.ai artifact, which is not a repo-owned or durable reference. Link the initiative to a ticket or repo document that other readers can access, or drop the link.</comment>
<file context>
@@ -0,0 +1,12 @@
+No state transition, retention bound, credential handling, flag or wire contract
+changes. The rollout lead owns deploy and monitoring provisioning.
+
+Initiative: [explicit-state latch invariant](https://claude.ai/artifact/7srvSdinev4M8oiSKotRiU).
</file context>
* fix: route critical pipeline failures through verified page alerts Promote batch timeliness, gate critical backlog and vendor signals, and export bounded guard failure logs for a page-tier metric rule. Failure-Class: FC-grafana-alert-import-omits-gated-rules * fix: route critical pipeline failures through verified page alerts Promote batch timeliness, gate critical backlog and vendor signals, and export bounded guard failure logs for a page-tier metric rule. Failure-Class: FC-grafana-alert-import-omits-gated-rules * fix: route critical pipeline failures through verified page alerts Promote batch timeliness, gate critical backlog and vendor signals, and export bounded guard failure logs for a page-tier metric rule. Failure-Class: FC-grafana-alert-import-omits-gated-rules * fix: keep production native alerts out of development imports Failure-Class: FC-grafana-alert-import-omits-gated-rules Keep enrichment and guard Cloud Monitoring queries on the production import path, preserve detached development definitions, and update batch apply docs. * fix: defer finalization alert coverage to finaldwell Remove the duplicate dead-letter stock page and reference #24533. * test: align inherited main CI with its own current contracts Main's head (a5ccd17) fails two of its own checks, which every branch based on it inherits: the pl397 emulator-proof fixtures lack the time.monotonic clock the consumer's lease hold now reads, and the Soniox 503-at-submission test still asserts the pre-#24392 contract (5xx at the paid step now preserves paid uncertainty: submitted=True). * fix(monitoring): regenerate the GMP inventory over the merged rule set and allowlist the grown telemetry contract leg The merge unioned alert-rules.json across both lanes; the committed migration inventory is now regenerated by monitoring_gmp_shadow.py --inventory instead of a hand-merged count, and the dead-letter producer-family contract leg that walks the full rule set is allowlisted at its measured CI CPU time (1.03s vs the 1.00s guard limit; all 44 contract assertions pass).
Requested by David
Finalization jobs can wait silently for BYOK keys until the fourteen-day abandonment bound, while terminal jobs accumulate without stock/age alerts. This is the second PR for the explicit-state program and latch invariant. It adds authoritative inventory and age signals without changing job transitions, credentials, or the fourteen-day bound.
The supplied 2026-11-03 audit counted 363 blocked_byok jobs, oldest 13 days, and 2,000+ dead letters (bounded probe cap). No new prod read or GCP tier was used. The rollout lead alone provisions indexes/monitoring and deploys; this lane does not merge or deploy.
The first deploy will page on the existing 13-day blocked-BYOK backlog. On-call should do nothing beyond confirming automatic conversion at 14 days. The seven-day page remains enabled; do not manually replay jobs or change the bound.
All five rules use severity-contract notification timing: informational warning rules use group_wait 5m / group_interval 1h / repeat_interval 24h, and the critical page uses 30s / 5m / 4h. They retain existing labels/routing, owner
two-lane-lead, and the finalization runbook. Only the seven-day BYOK rule pages a human. The existing terminal-arrival alert is unchanged.listen_finalization_jobs{status="dead_letter"}now comes from a Firestore COUNT on status alone, including pre-release rows without projection_generation. Other status/outcome metrics retain projection shards. The newlisten_finalization_byok_session_abandoned_last_24hgauge counts currently dead-lettered jobs with last_failure_code=byok_session_abandoned and terminal_at in[now - 24h, now]. It recovers from a crash after the terminal transaction and counts each matching document once; replay out of dead_letter removes a row from this rolling inventory. It is not a permanent event ledger. The daily alert usesmax()of this gauge across replicas, not a counter increase. The process counter remains a documented best-effort fast signal.Both COUNTs run on the existing startup/periodic summary cadence (60 seconds by default with quiet finalization enabled in production values; 300 seconds when disabled, overridable with
LISTEN_FINALIZATION_RECONCILE_INTERVAL_SECONDS), never on a request path. They download aggregate results rather than job rows; COUNT billing scales at about one read per 1,000 matching entries. Oldest-row reads remain indexed limit(1).Age decision (review item 3): dead-letter writers persist
terminal_at, so dead-letter age now measures time in the current terminal status. Rows missing terminal_at remain in stock but have unknown terminal age. Blocked-BYOK has no blocked_at/status_changed_at; updated_at is mutable bookkeeping. Its existing created_at proxy is retained and explicitly disclosed in the runbook and metric documentation. No new status-entry writes or transitions are introduced.Two indexes are declared in the Firestore registry and generated manifest: status/terminal_at for terminal age, and status/last_failure_code/terminal_at for the 24h count. The rollout lead must verify READY before publisher deployment. No index provisioning is performed by this lane. New metric names use source-backed declarations; captured production evidence is unchanged.
Latest notification/cadence revision: 158 tests passed across the complete notification contract, alert-rule contract, alert backtest, provisioning and GMP inventory test files through omi-heavy with two workers. Both exports retain the critical page timing and use informational timing for all four new warning rules.
Earlier implementation validation through omi-heavy with low workers (1,074 tests passed across 15 files; one normal marker deselection):
Failure-Class: none
Failure-Class-Reason: Adds authoritative operational visibility; state-machine behavior remains unchanged.
Product-invariant suggestions and line-growth metadata are validated by preflight.
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3138 -> 3167 | Keep all-generation stock and durable 24h COUNTs on the existing summary cadence and use the recorded terminal clock; no state writes.
Line-Count-Exception: backend/database/firestore_index_registry.py | 2250 -> 2282 | Declare the terminal-time age and abandonment-window query indexes in the existing index authority.
Line-Count-Exception: backend/utils/metrics.py | 1618 -> 1639 | Keep the document-derived daily gauge with the existing finalization metric registration lifecycle.