Skip to content

feat(pusher): storage PCM in-flight gauge and chart-only memory/queue alerts - #24788

Merged
Git-on-my-level merged 1 commit into
mainfrom
lane/lcbytea
Nov 6, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
lane/lcbytea

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Purpose

PR-A adds observational PCM byte accounting around pusher custody commit_pcm_window, plus chart-only storage queue and memory alerts. Follows phase 2a (#24756, cc9c71b) and the approved metrics-first split.

  • omi_pusher_storage_pcm_inflight_bytes: increment payload length before storage submission; decrement in finally on success, exception or caller cancellation. Defensive metric failures never affect commit/ACK behavior. Cancellation can leave a running thread completing storage; this gauge measures the await lifetime, not total retained RSS.
  • omi_pusher_storage_pcm_budget_limit_bytes: constant zero, meaning no budget is enforced. Both gauges are zero-initialized, label-free and registered in the source-backed metric inventory. Pusher exports directly through /metrics to the unfiltered pusher-metrics Prometheus scrape; no GMP sidecar allowlist applies.

Alert thresholds

Grafana UID Threshold Pending Tier
omi-pusher-storage-queue-warning Queued storage tasks >256 per pusher target 10m agent
omi-pusher-storage-queue-critical Queued storage tasks >512 per pusher target 10m page
omi-pusher-memory-working-set-high Pod working set / 3.5 GiB >0.75 15m page

Queue thresholds are 2x/4x the configured 128 storage workers. The real executor label is storage; custody work has task label other, so queries sum all task kinds per target. RSS uses the same container/workload selectors as dashboards/gke/pusher.json, normalized by the chart's 3.5 GiB limit. The 75% bar (2.625 GiB) follows the #24699 gate. These are sustained current-state gauges, not rates over historical incidents. Each source series must be younger than 120s before aggregation; absent data does not page. Rules have human-impact/verification/runbook annotations and agent/page routing. Split/combined rules and generated query inventory are synchronized.

Scope and rollback

No byte budget, semaphore, refusal logic/counter/alert, flags, extra reads, executor behavior, ACK/1011/close changes, deployment settings or .github changes. PR-B remains later and must first add a saturation test. No GCP/prod access, merge or deployment. Rollback: revert this PR; metrics are inert. Alert definitions require normal monitoring provisioning to become live.

Verification

  • Targeted metric lifecycle/registration, monitoring alert contracts and generated inventory: 118 passed.
  • Component suites through bin/omi-heavy + file-isolated backend/test.sh: 252 passed, 2 existing executor Future timeouts. Isolated rerun reproduced both. An archived origin/main source snapshot at cc9c71b reproduced the identical 2 failures / 34 passes with the same Python environment. No executor source/tests are changed. Other suites include durable outbox (102 passed), queue wait (28 passed), executor backpressure, metrics/cardinality/export and monitoring contracts.
  • PR metadata validation: 4 checks passed. make preflight: all 42 checks passed with the approved 900s file budget. Normal pre-push passed: 42 contract checks, backend type check (0 errors), all 83 selected tests, OpenAPI/client compatibility and formatting (HTTPS through the gh credential helper, BACKEND_UNIT_FILE_BUDGET_SECONDS=900, no skip hatches). The first Firestore guard exceeded its 300s file budget; rerunning with the approved BACKEND_UNIT_FILE_BUDGET_SECONDS=900, without skipping checks.
  • Required Grok review completed via agentctl on m5-mbp with read-only access: no findings on b103608. Reviewed gauge accounting/cancellation, metric-failure isolation, queue aggregation, per-series freshness, 3.5 GiB memory normalization, alert routing, tests and inventories.

Product invariants affected

none

Line-Count-Exception: backend/routers/pusher.py | 1857 -> 1872 | Keep the defensive observational increment/finally next to the sole custody storage await without changing its control flow.
Line-Count-Exception: backend/utils/metrics.py | 1673 -> 1683 | Register two label-free pusher gauges alongside the existing shared pusher collectors used by the metrics endpoint.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 6, 2026 12:02

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 9 files

Confidence score: 4/5

  • test_monitoring_alert_rule_contract.py only counts timestamp() calls and checks one < 120, so the memory branch can pass without proving both source series are fresh. Assert the exact freshness predicate for the memory selector and workload-owner selector.
  • test_monitoring_alert_rule_contract.py does not check notification routing, so a page rule could pass while muted or sent to the wrong receiver. Assert the expected receiver and mute state for the agent page rule.
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/tests/unit/test_monitoring_alert_rule_contract.py">

<violation number="1" location="backend/tests/unit/test_monitoring_alert_rule_contract.py:2204">
P2: This contract does not verify notification routing, so a page rule can retain `tier: page` while being muted or sent to the wrong receiver and still pass. Assert the alert receiver and the expected mute state for agent versus page rules.</violation>

<violation number="2" location="backend/tests/unit/test_monitoring_alert_rule_contract.py:2221">
P2: The memory branch does not prove that both source series are fresh: it only counts `timestamp(` calls and checks for one `< 120`. Assert the exact freshness predicate for the memory selector and the workload-owner selector so stale working-set data cannot regress into a page.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

assert 'container_memory_working_set_bytes' in expr
assert 'namespace="prod-omi-backend",container!="",image!=""' in expr
assert 'workload="prod-omi-pusher",workload_type=~"deployment"' in expr
assert expr.count('timestamp(') == 2 # memory AND workload-owner freshness

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The memory branch does not prove that both source series are fresh: it only counts timestamp( calls and checks for one < 120. Assert the exact freshness predicate for the memory selector and the workload-owner selector so stale working-set data cannot regress into a page.

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 2221:

<comment>The memory branch does not prove that both source series are fresh: it only counts `timestamp(` calls and checks for one `< 120`. Assert the exact freshness predicate for the memory selector and the workload-owner selector so stale working-set data cannot regress into a page.</comment>

<file context>
@@ -2189,3 +2189,34 @@ def test_held_dead_letter_volume_is_agent_only_and_uses_reasoned_stock_plus_uniq
+                assert 'container_memory_working_set_bytes' in expr
+                assert 'namespace="prod-omi-backend",container!="",image!=""' in expr
+                assert 'workload="prod-omi-pusher",workload_type=~"deployment"' in expr
+                assert expr.count('timestamp(') == 2  # memory AND workload-owner freshness
+                assert expr.endswith('/ 3758096384')  # chart limit: 3.5 GiB
</file context>

for uid, (threshold, pending, tier) in expected.items():
rule = rules[uid]
assert rule['for'] == pending, export_name
assert rule['labels']['tier'] == tier

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This contract does not verify notification routing, so a page rule can retain tier: page while being muted or sent to the wrong receiver and still pass. Assert the alert receiver and the expected mute state for agent versus page 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 2204:

<comment>This contract does not verify notification routing, so a page rule can retain `tier: page` while being muted or sent to the wrong receiver and still pass. Assert the alert receiver and the expected mute state for agent versus page rules.</comment>

<file context>
@@ -2189,3 +2189,34 @@ def test_held_dead_letter_volume_is_agent_only_and_uses_reasoned_stock_plus_uniq
+        for uid, (threshold, pending, tier) in expected.items():
+            rule = rules[uid]
+            assert rule['for'] == pending, export_name
+            assert rule['labels']['tier'] == tier
+            assert rule['labels']['audience'] == ('agent' if tier == 'agent' else 'human')
+            assert rule['labels']['owner'] == 'omi-lifecycle'
</file context>
Suggested change
assert rule['labels']['tier'] == tier
assert rule['labels']['tier'] == tier
assert rule['notification_settings']['receiver'] == 'Omi - Services Alerting (Telegram)'
assert ('mute_time_intervals' in rule['notification_settings']) == (tier == 'agent')

@Git-on-my-level
Git-on-my-level merged commit e005a7c into main Nov 6, 2026
71 of 72 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/lcbytea branch November 6, 2026 12:22
Git-on-my-level added a commit that referenced this pull request Nov 6, 2026
## What changed and why

Add process-wide non-waiting admission for custody PCM queued/running on
the existing storage executor. PR-A #24788 supplied the gauges and
pressure alerts. This PR adds admission, bounded refusal/error counters,
an agent-tier refusal alert, hermetic saturation tests and the runbook.
**The flag remains 0 everywhere.**

A full budget returns before submission, without a receipt, commit
callback or opcode-203 ACK. It never raises into receive supervision or
selects a close code. Original PCM, exact checkpoints, owner and start
remain charged to the socket's existing 20 MiB budget. **The first live
refusal immediately pauses intake** in that same cancellable receive
task; it probes every 50 ms until the window commits, before reading
another frame. Refusals cannot accumulate windows toward socket byte
exhaustion. There is no extra retry task or global waiter list. Enabled
windows cap at 4096 checkpoints.

Live admission uses 75% of the total; shutdown tails may use the full
limit and bypass the intake pause. A full tail returns without an ACK
and retains its producer fence. Outer-handler cancellation interrupts a
paused receive task but skips the cancellation-time tail commit
entirely. Connected or disconnected, this path submits no storage,
produces no receipt and sends no ACK; the held producer fence and client
WAL replay own recovery. Cleanup cannot wait for a new PCM storage
operation or its retries. Already-submitted storage still holds its
reservation until actual settlement and cannot send a late ACK. The
existing external-cancellation close classification is preserved. Record
begin/fail/seal/abandon/markers and projection operations remain
ungated; executor pools are unchanged. Known-deleted retained owners use
the existing gone-owner disposition. Every unresolved owner stays fenced
in finalization: A's receipt cannot certify B's uncommitted tail.

Acquire faults roll back partial mutation and fail open using flag-0
storage dispatch. Release faults retire exactly their own reservation
and are swallowed. Acquire fail-open also calls the shared fallback
helper for every fault; the caller owns the rate-limited warning. Both
acquire/release errors use `omi_pusher_storage_pcm_errors_total{reason}`
through the enum helper and logs limited to one per reason per minute.
Late post-cancellation storage failures are counted/logged through the
same bounded path. Enabled capacity remains held until actual storage
settlement, including caller cancellation.

Flag 0 preserves successful PCM/checkpoint/receipt/opcode-203 bytes,
storage dispatch/cancellation and observational gauge semantics. It does
**not** promise identical failure finalization: the new finalizer can
still hold unresolved fences and defer inline finish after genuine
failures at flag 0. Genuine storage-error handling remains in effect.

## Flag, ramp and rollback

`PUSHER_STORAGE_PCM_BUDGET_MB=0` is off / kill switch in code, manifests
and dev/prod charts. Enabled deployment values must be >=27 MiB: ceil(20
MiB x 4/3), so an idle live lane admits any legal socket window.
Smaller/malformed unvalidated startup values select off. Proposed canary
size: 512 MiB (384 MiB live / 128 MiB reserved).

Separate approved enablement train, owner uicleanup (omi-lifecycle): dev
chart -> one canary pod for 15 minutes with socket kills <=15/15min and
memory p99 <75% of 3.5 GiB; inspect refusals, accounting/GCS errors and
capacity/abandon outcomes -> fleet within one day of a clean canary, or
report the failed gate. Rollback: chart value 0 through ordinary
rollout, without rebuilding or changing custody objects/tokens. No
enablement, GCP access, PR merge or deploy in this task.

## Product invariants affected

INV-MEM-4: the runtime manifest adds only the pusher admission setting;
canonical memory admission/promotion authority is unchanged.

## How it was verified

- Test FIRST on base d478192: first run
2 passes / 1 strict xfail; expanded baseline 2 passes / 7 strict xfails.
Unbounded submitted bytes and missing refusal retention were expected
failures. Final tests have no xfail escape.
- Real commit helper/executor with event-controlled GCS: 50 producers,
512 KiB windows, synthetic 8 MiB budget, <=6 MiB live submissions and 38
refusals. Thirty further refusal probes preserve exact input without
increasing submissions; recovery commits all 50 once. Current/high-water
RSS plateaus, Python allocations fall and byte accounting drains. The
recorder retains digests, not PCM history. 50 x 4 KiB tails fit the
reserve during live saturation.
- Final focused delta: **38 saturation tests passed**. The real receive
loop is offered 30 full-minute windows while admission stays full for
>=30 probes: only the first enters, its byte charge stays below half the
socket limit, and there is no receipt/ACK/close. Recovery commits once;
cancellation keeps the original window/checkpoints and fence for WAL
replay without submitting a tail; a fully saturated normal tail keeps
its fence. Acquire/release exceptions before and after mutation preserve
another socket's reservation, still store/ACK, never close, increment
bounded counters and produce rate-limited logs. Late post-cancellation
failures are observed, counted and logged.
- Final focused validation: **168 saturation/queue-wait/outbox tests
passed** (38 + 28 + 102). New disconnected-peer and
event-stalled-storage cancellation cases complete cleanup within one
second without a new storage call, receipt or ACK; original
PCM/checkpoints and producer fences remain intact. Already-submitted
storage keeps its byte reservation until actual completion and releases
exactly once without a late ACK, on success or failure. Earlier
validation passed **362 surrounding tests**, including the closed-reason
guard, executors, metrics, alert contracts, abandonment and record
barriers. The earlier cancellation-flush behavior was removed after
focused review: cancellation of an admission pause now leaves the
unacknowledged window for WAL replay instead of starting storage during
cleanup. The final shared-fallback accounting check also passed all **4
cases**. Earlier broader implementation checks passed **456 offline
pre-deploy tests** and **55 make preflight checks**.
- Final normal pre-push **passed on
`2e94b0753d5c1951aa53a1c1110180d2a9dfbc63`**: all guards enabled,
approved 900-second file budget, two-check scheduling, zero type errors,
all 38 saturation cases and all 115 route-verifier cases rerun
successfully, OpenAPI compatibility and formatting passed. Final
metadata validation passed all 4 checks. [CI
checks](https://github.com/BasedHardware/omi/pull/24799/checks) track
the exact published head.
- Two parallel independent custody reviews, including Grok, were
completed with regressions for their findings. The final Luna FIX-FIRST
delta addresses both P1s (first-refusal pause and fail-open accounting),
plus the GLM documentation/late-failure observations. No further review
round requested; lead2 owns the focused delta review.

Not measured: listen re-offer cadence, projection-debt aggregate, GCS
client buffering, real sockets/pod, 48 kHz prevalence or production tail
distribution. The budget bounds submitted PCM, not total pod RSS;
allocator pages need not immediately return to the OS. No deployed
playback or installed-client WAL proof is claimed.

## Tests

Primary regression:
`backend/tests/unit/test_pusher_storage_pcm_saturation.py`; flag
declarations: `test_pusher_storage_pcm_config.py`; exact rendered
binding: `test_verify_pusher_config_references.py`. Heavy checks use
`bin/omi-heavy` with cloud credential/project variables unset. The
handoff-approved `BACKEND_UNIT_FILE_BUDGET_SECONDS=900` is used for the
Firestore guard, with no skipped guard.

## UI evidence

UI-Evidence: none -- backend admission/configuration only.

## Failure class (fixes)

Failure-Class: FC-cancel-path-unbounded-terminal-send

## New guards

Saturation/retention tests protect the socket-kill class exposed by
#24689: refusal cannot raise, close, trim PCM or falsely ACK. Long
refusal, accounting-fault, disconnected-peer cancellation and
stalled-storage cleanup regressions protect the review findings.
Cancelling admission skips storage and ACK while retaining the producer
fence for WAL replay.

Line-Count-Exception: backend/routers/pusher.py | 1872 -> 2032 | Keep
first-refusal intake control, fault isolation and producer-close proof
at the existing receive-loop custody seam; isolate transactional byte
accounting without pool or ACK refactors.
Line-Count-Exception: backend/utils/metrics.py | 1715 -> 1736 | Add and
zero-initialize bounded refusal and accounting-error counters alongside
the PR-A gauges.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant