Skip to content

perf(enrichment): poll long-stuck custody deferrals hourly - #24264

Merged
Git-on-my-level merged 3 commits into
mainfrom
lane/syncdiet
Nov 1, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
lane/syncdiet

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

  • perf(enrichment): poll long-stuck custody deferrals hourly

The enrichment outbox (kind=sync_reprocess on /v2/sync-jobs/run) re-arms a callback custody deferral every
30–120s with no bound. Four reasons can outlive the obligation: redirect_unresolved, conversation_missing,
open_live_target and pending_live_bridge. Once one of those reasons has deferred a row continuously for 6h,
the row polls hourly (custody_defer_until). The outbox records deferred_since for the current reason. A
different reason or a completed callback starts a new episode, and an episode never predates the obligation's
first_pending_at, so a reopened dormant row doesn't inherit an old one. Fresh deferrals and every other reason
keep their cadence. Custody, sweep repair and the eventual resume or redirect are unchanged. No row is retired or
discarded.

Scope: this covers the sync-handler outbox (outbox.run → defer), which is the serving route
(ENRICHMENT_ROUTE is unset on backend-sync). The C3 consumer (/v2/enrichment/run) is unchanged: its store
records the consumer's own not_due reason, so it needs its own episode field before the route flips. Existing
stuck rows have no deferred_since, so they back off 6h after deploy.

Why (prod measurements 2026-11-01, ro-prod, aggregates only)

  • About 80% of backend-sync /v2/sync-jobs/run 200s carry the 21-byte {"status":"deferred"} body: ~53k
    deliveries/h at a mean of 2.39s, roughly a third of the service's request wall. Measured from the request-log
    census by status and responseSize, 16:10–16:20Z.
  • Open outbox rows by deferred_reason (Firestore COUNT): redirect_unresolved 1,625, pending_live_bridge
    123, open_live_target 83, conversation_missing 12.
  • Ages from a projection histogram of first_pending_at:
    • redirect_unresolved: 98% are older than 6h and 67% are 7–30 days old; 95% are due within 150s.
    • pending_live_bridge: 69% are older than 6h.
  • At the old cadence that is ~49k + ~15k + ~2.5k polls/h. Each poll costs a cohort warm, two outbox CAS writes,
    resolver reads and a new Cloud Task.

Delivery reduction (hermetic)

test_stuck_redirect_deliveries_per_day_drop_from_719_to_198 drives a stuck redirect through the real
outbox.run for 24h of fake time. It makes 719 deliveries before the change and 198 after. The first 181
deliveries (the 6h grace) are identical. After the grace, the largest gap between deliveries is one poll interval
(3600s).

Worst-case added delay: one hour, and only for a row that one reason has deferred continuously for more than 6h.
That covers a redirect that resolves late, or a live target or bridge that settles after 6h.

Review round 1 (Luna, FIX-FIRST)

  • P2 "an old obligation delays a new bridge by up to an hour": fixed. The grace is now per-reason
    deferred_since, not first_pending_at. See test_new_deferral_reason_on_an_old_obligation_restarts_the_grace
    and test_completed_callback_ends_the_deferral_episode.
  • P2 "the sync_hold loop is unchanged": not a live loop. That was an early hypothesis in the context file, and
    measurement then disproved it. Open outbox rows with effects_only=true: 0. Open rows with
    deferred_reason=sync_hold: 0 (Firestore COUNT, 16:45Z). The measured loops are the four reasons covered here.
    Changing sync_hold would add risk with no measured saving.

Lane / contract

Lane syncdiet (two-lane rollout, margin50). Edits fswrites' outbox area: coordinated on the bus (msgs 25ebd3,
1d75c9). The change touches only the defer horizon, not the CAS mechanics.

Product invariants affected

none

Verification

  • backend/test.sh with BACKEND_UNIT_TEST_FILE_LIST: test_sync_enrichment_custody, test_enrichment_route,
    test_outbox_firestore, test_sync_pending_live_bridge, test_sync_reprocess_coalesce,
    test_enrichment_callback_parity and test_sync_processing_hold all pass (unit layer).
  • backend/testing/sync_cloud_tasks_stack/run.sh --only sync passes: the hermetic emulator gauntlet.
  • Not measured: live savings. These need a deploy to backend-sync. Expect the size-121 share of sync-jobs/run to
    fall from ~80% toward ~5%.

Rollback

Revert this commit. Or raise STUCK_DEFER_GRACE_SECONDS in a hotfix. No flag; no data or config changes.

Failure-Class: none

🤖 Generated with Claude Code

A callback custody deferral (unresolvable merge redirect, missing row, live
target or live bridge that never settles) re-armed its outbox wake every
30-120s with no bound. On 2026-11-01 ~1.7k such rows, mostly days old, were
~80% of backend-sync /v2/sync-jobs/run deliveries (~53k/h at ~2.4s each).

After a 6h grace (measured from first_pending_at) these reasons poll hourly.
Fresh deferrals keep their cadence; custody, sweep repair and resume are
unchanged. Worst-case added delay: one hour, only for obligations already
deferred more than six hours. Both the sync-handler outbox and the C3
consumer use the same horizon.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-01T17:00:09.805240Z
We couldn’t complete this review. Comment @codex review to try again.
7b0d53e PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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.

No issues found across 4 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

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

Git-on-my-level and others added 2 commits November 2, 2026 00:07
Review round 1: first_pending_at measures the obligation, not the current
deferral, so a new live bridge on an old obligation would have waited an
hour. The outbox now records deferred_since for the current reason; a new
reason or a completed callback starts a new episode, and an episode never
predates the obligation's acceptance (reopened dormant rows).

The C3 consumer keeps its previous cadence: its store records the
consumer's own reason, not the callback's, and the route is not serving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit e95842a into main Nov 1, 2026
60 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/syncdiet branch November 1, 2026 17:53
Git-on-my-level added a commit that referenced this pull request Nov 1, 2026
…24303)

## Problem and change

backend-sync is pinned at its service cap of 40 instances (syncdiet,
2026-11-01): bursty hot instances
keep the autoscaler at the cap, so the instance saving from #24264
(hourly re-poll of long-stuck
custody deferrals, ~45k fewer sync-jobs/run deliveries per hour) only
lands through a lower cap.

This PR changes the ops source of truth only:
`backend/deploy/ops/prod.yaml`
`cloud_run.backend-sync.max_instances` 40 → 30 (min stays 5), and pins
`test_cloud_run_rightsizing_pins.py` to (5, 30).

**Merging applies nothing.** `config_train.yml` is `workflow_dispatch`
only. Backend deploys
live-resolve the sync maxScale, so no train reverts the live value
either way.

Expected: −10 instances × 24 h × $0.1789/inst-h ≈ **−$43/day**
(syncdiet's instance-based rate),
visible only after the apply.

## Apply (lead, after the gates)

Gates (syncdiet §1, lead ruling 92aecb), each held for 1 h:
1. #24264 has served ≥ 7 h. It is in train fbc7973 (image digest
`d1024bc3e84f`, serving since
2026-11-01 19:11:16Z), so the earliest apply time is **02:11Z 11-02**.
2. sync-jobs-fresh `task_attempt_delays` p95 < 2 s.
3. backend-sync request latency p95 ≤ 12 s.
4. backend-sync `max_request_concurrencies` p95 ≤ 13.5.
5. The size-121 (`{"status":"deferred"}`) share of sync-jobs/run 200s <
10%.

Read-only checker (ro-prod, aggregates only), held outside the repo:
`python3 -I /Volumes/Ephemeral/scratch/margin20/g1_gates.py --census`.
Baselines by the same
method: gate 4 = 13.4 (16–17Z 11-01), 17.4 (18–19Z), 18.7
(19:28–20:28Z). Gate 4 may not clear
on a Sunday evening.

Apply, canonical path:
```
gh workflow run config_train.yml -R BasedHardware/omi -f environment=prod -f mode=plan -f ref=main
# plan must show only: backend-sync run.googleapis.com/maxScale 40 -> 30
gh workflow run config_train.yml -R BasedHardware/omi -f environment=prod -f mode=apply -f ref=main
```
Break-glass equivalent: `infra/rollout/bin/cr_apply.sh backend-sync
--max=30`. The service-level
annotation is the authoritative cap (the sentinel reads it), and `--max`
creates no revision.

The sentinel's hard-coded sync target
(`sentinel/scripts/cloud_run_state.py` `TARGETS`) still reads
80, which is already stale against live 40. The lead updates it to 30 at
apply.

## Rollback

`cr_apply.sh backend-sync --max=40`, which takes minutes. Then revert
this PR (or set 40) so the
next config-train keeps it. Roll back on any of: attempt-delay p95 > 2 s
for 15 min,
latency p95 > 12 s for 15 min, or sync-jobs-fresh depth above 2× its
pre-apply hour.

## Relation to #23973

#23973 edits the same key. Its body describes 5/50 → 3/20, but main is
now 5/40, and the author holds
it until fresh qualification. It must not merge as-is. If it is revived
after this PR, rebase it
onto 5/30. G1 does not depend on it.

## Validation

`backend/test.sh` with `BACKEND_UNIT_TEST_FILE_LIST` =
test_cloud_run_rightsizing_pins.py,
test_config_train.py, test_drift_check.py: 88 passed (4 + 52 + 32), run
through `bin/omi-heavy` with
no GCP credentials. The bounded pre-push gate passed.

Owns: this PR only. Review: Luna, via review.sh.

🤖 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/24303?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/24303?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24303&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. -->
ocakciomursel-pixel pushed a commit to ocakciomursel-pixel/omi that referenced this pull request Nov 1, 2026
Source change only. The config-train is workflow_dispatch, so merging this
applies nothing; the lead dispatches config_train.yml (prod, plan then apply)
after BasedHardware#24264 has served 7h and syncdiet's gates hold for 1h. Backend deploys
live-resolve the sync maxScale, so a train cannot revert the applied value.

Pins test_cloud_run_rightsizing_pins.py to (min 5, max 30). Rollback: 40.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
… G1) (#24329)

## Problem and change

#24303 set `backend/deploy/ops/prod.yaml`
`cloud_run.backend-sync.max_instances` to 30 for a gated apply. The lead
held the apply at 02:11Z, and it never ran: live is still 40. Leaving 30
in source means the next config-train
dispatch, for any reason, would apply it without the gates.

This PR puts the source back to 40 and the
`test_cloud_run_rightsizing_pins.py` pin back to (5, 40). Live does not
change.

## Why the cap is dropped, not delayed (measured, ro-prod Cloud
Monitoring, backend-sync)

| hour | requests/h | avg instances | max_request_concurrencies p95 |
latency p95 |
|---|---:|---:|---:|---:|
| 16–17Z 11-01 (before #24264) | 133.4k | 39.9 | 13.4 | 8.82 s |
| 01–02Z 11-02 | 93.1k | 33.3 | 18.4 | 12.01 s |

#24264 removed the short (~2.4 s) deferred re-polls, so the remaining
requests are long sync jobs. In-flight per
instance rose while instances fell 40 → 33 on their own. At concurrency
p95 18–20 of `containerConcurrency` 20, a cap of
30 would queue work rather than trim idle capacity. The instance saving
the cap targeted has already happened.

## Validation

`backend/test.sh` with `BACKEND_UNIT_TEST_FILE_LIST` =
test_cloud_run_rightsizing_pins.py, test_config_train.py,
test_drift_check.py: 88 passed (4 + 52 + 32), via `bin/omi-heavy`, with
no GCP credentials. The bounded pre-push gate passed.

Rollback: revert this PR. Applying nothing either way: config-train is
`workflow_dispatch` only.

🤖 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/24329?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/24329?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24329&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. -->
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Nov 2, 2026
… G1)

BasedHardware#24303 set the source cap to 30 for a gated apply that never happened (lead
held it at 02:11Z). After BasedHardware#24264 removed the short deferred re-polls, sync runs
long jobs at max_request_concurrencies p95 18-20 of containerConcurrency 20 on
~33 instances, so a lower cap would queue work rather than trim idle capacity.
Live stays 40; this puts the source back so no config-train dispatch can apply
30 without the gates. Pins test_cloud_run_rightsizing_pins.py to (5, 40).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
…sumer route (#24377)

## Summary

#24264 made long-stuck custody deferrals (`redirect_unresolved`,
`conversation_missing`, `open_live_target`, `pending_live_bridge`) poll
hourly after a 6h grace. It only did this in the sync handler's `run()`.
Prod serves enrichment through the C3 consumer
(`ENRICHMENT_ROUTE=enrichment_queue`). There,
`FirestoreEnrichmentOutbox.claim_key` + `defer` still re-arm the same
rows every 30-120s.

This PR brings the same episode rule to the consumer route:

- `Result.defer_cause` carries the domain cause. `EnrichmentConsumer`
sets it from the callback's `defer_reason`, `run_push` passes it to
`outbox.defer` instead of `not_due`, and metrics keep
`ConsumerReason.NOT_DUE`.
- `FirestoreEnrichmentOutbox.defer` records `deferred_since` with the
shared `custody_deferred_since` / `custody_defer_until` helpers, so
`due_at`, `task_due_at` and `wake_check_after` move to `now + 1h` once a
cause has held the row for 6h.
- A completed callback (`ack`) drops `deferred_since`, so a new deferral
starts a new episode, as in the sync handler.

Custody, sweep repair and the eventual resume are unchanged. The only
difference is that a long-stuck row is checked hourly instead of every
minute or two. The PG and provider-STT outboxes store the cause string
where they used to store `not_due`; both columns are plain text.

## Measurement (prod, ro-prod, aggregates only, 2026-11-02 ~10:40Z)

- Write probe, last 1h: `outbox_firestore:claim_key` 81.1k,
`outbox_firestore:defer` 75.6k writes/h (about 157k/h together).
- `sync_reprocess_outbox` rows with `deferred_reason == not_due`: 7,554.
Rows waking within 2 min (the hot loop): 1,800 are ≥6h old and about 170
are newer. 4.1k old rows already wake more than 1h out.
- Every consumer custody cause (`utils/enrichment/callback.py`) is in
`STUCK_DEFER_REASONS`.
- Expected effect: about 91% of the hot loop goes from roughly 40
cycles/h to 1, so claim_key+defer should fall from ~157k/h to ~20k/h.
That is about 3.3M writes/day ≈ **$4.6/day** at the billed $1.385/M,
plus about 3.3M reads/day ≈ $1.5/day, along with Cloud Tasks deliveries
and consumer CPU.
- Timing: existing rows have no consumer `deferred_since`, so each
episode starts at the row's first deferral after deploy. The drop
appears about 6h after the deploy.
- Verify with
`omi_firestore_billed_writes_by_caller_total{caller=~"database.outbox_firestore:(claim_key|defer)"}`
from deploy+6h onward.

## Rollout

Ships on by default. It reuses #24264's constants, so there is no new
flag. Deploy: `backend-integration` (the prod `/v2/enrichment/run`
target, `API_WORKERS` role). The lead batches it into a train.

## Tests

`backend/test.sh` with the targeted list (outbox_firestore,
enrichment_route, workers_consumer_contract, sync_enrichment_custody,
sync_reprocess_coalesce, enrichment_callback_parity,
sync_processing_hold, sync_pending_live_bridge, live_demand_consumers,
feedback_media_consumers): all pass. `make preflight`: passed.

🤖 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/24377?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/24377?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24377&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. -->
knowaguy4u-cell pushed a commit to knowaguy4u-cell/omi that referenced this pull request Nov 2, 2026
…sumer route

BasedHardware#24264 bounded long-stuck custody deferrals (redirect_unresolved,
conversation_missing, open_live_target, pending_live_bridge) to an hourly
poll after a 6h grace, but only in the sync handler's run(). Prod serves
enrichment through the C3 consumer (ENRICHMENT_ROUTE=enrichment_queue),
whose claim_key/defer loop re-armed the same rows every 30-120s.

The consumer now passes the custody cause through Result.defer_cause, and
FirestoreEnrichmentOutbox.defer records deferred_since with the same
episode rule as the sync handler. A completed callback ends the episode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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