Skip to content

fix(enrichment): reserve fresh admission for pending first summaries - #25021

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

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

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Problem

Recent refreshes were admitted to the reserved enrichment-fresh queue by recency alone, competing with pending first summaries. The task's refactor-lead root-cause record 6c0bc0 (2026-11-10), under lead2 ruling c7af73, reports 24,785 owed first summaries across 1,675 users, about 32k queued tasks at 2026-11-10 05:59 UTC, and a mean scheduled-to-attempt delay of 6.76 hours. These are supplied incident measurements, not a new production measurement by this PR.

Change and expected effect

Require first_summary_pending(row) before the existing conversation-recency check at new/reopened admission, sweep promotion, and unbound-binding repair. Completed-summary refreshes use the primary queue; effects and completed-summary backfill preserve their existing routing. Pending first summaries, including backfill first summaries, retain fresh eligibility within the existing recency window.

No extra Firestore read: summary state is already in the CAS row. Refreshes now skip the clock-metadata read. The binding API and its other callers (speaker final-pass retries and effects dispatch), handler/audience/invoker identity checks, lease fences, and task-token rotation remain unchanged. In-flight rows keep their current binding until their next re-bind. This does not migrate existing fresh tasks. No queue configuration, summary-debt repair, or summary-due writers change.

Expected effect after deployment: newly bound recent refreshes stop consuming reserved fresh dispatch slots, leaving that admission path for pending first summaries. Existing queued refreshes must still drain; throughput/latency improvement has not been measured by this code-only change. No new flag. Rollback is a revert.

Verification

  • Via omi-heavy from backend/: .venv/bin/python -m pytest tests/unit/test_enrichment_route.py -q -p no:langsmith_plugin — initial run: 117 passed; final-head rerun in the full suite: 118 passed.
  • All outbox/enrichment unit files plus sync-reprocess coalescing, using the repository's file-isolated pytest executor via omi-heavy — 538 passed across 21 files, including the final-head route suite (118 passed); completed by 2026-11-10 06:45:48 UTC.
  • make preflight with OMI_PR_BODY_FILE via omi-heavy — passed at 2026-11-10 06:57:51 UTC with BACKEND_UNIT_FILE_BUDGET_SECONDS=900. The initial default-300-second runs timed out in the Firestore query-shape suite with no failed assertion reported; the 900-second rerun passed. Standalone async blocker scan: 0 findings.
  • Regression coverage includes seen and disabled first-summary state, pending first summaries, promotion and unbound repair, unchanged effects/backfill routing, active leases, identity checks, stale-token fencing, and no clock read for refreshes.
  • Normal pre-push gate passed at 2026-11-10 07:24 UTC: all 38 manifest checks, backend typecheck (0 errors), and 118 route tests.
  • No production access or deploy; GCP tier: none.

Product invariants

None selected by scripts/pr-preflight --suggest for this change.

Failure-Class: none

The registry has no matching class for summary-refresh admission consuming first-summary queue capacity; the task excludes .github/ changes. The behavioral guard is backend/tests/unit/test_enrichment_route.py.

View guided diff Turn on auto-fix

Gate new bindings and sweep promotion/repair on persisted first-summary state before reading conversation clocks. Preserve existing bindings, identity checks and token fences.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
Summary repair currently walks the oldest debt in its bounded window
before recent user-visible debt. Apply David's 2026-11-10 03:19Z ruling
(`relay-cl1 6db8f2`): serve rows at risk of expiry first, then newest to
oldest.

## Behavior

- Scan the first 600 seconds above the age-gate cutoff oldest-first,
then the remaining window by pending time DESC, with due/path
tie-breaks. The margin spans five 120-second ticks: up to 40 attempts at
the default eight-attempt cap. This provides headroom, not an overload
guarantee.
- Share the scan/admission budgets across both phases, with independent
versioned cursors. Owner fairness allows at most three attempts per
owner per tick across both phases, including failed/blocked attempts.
Each durable phase cursor continues after every examined row, including
owner-quota deferrals, so later owners remain discoverable across ticks
even when one owner fills multiple scan budgets. Deferred rows are
retained separately as unchanged conversation debt (`summary_due_at`);
later passes/wraps select them again. Admission/time interruptions
preserve the unexamined fetched tail. Exhausted phases wrap as before,
with no additional retry queue or cursor schema. Legacy phase cursors
reset safely.
- With the age gate disabled, preserve the legacy `summary_due_at <=
now` query ordered by `(summary_due_at, __name__)` and its flat due/path
cursor. Rows with missing or explicitly null pending time remain
admissible, using their due time to bound admission pending time.
Gate-enabled cursors advance on finite numeric due values, including
zero/negative values; datetime handling is preserved.
- Fetch chunks of at most 500 rows. Stop starting work at the admission
cap, total scan budget, or a 90-second cooperative scan-work deadline
checked between rows/chunks; an in-flight RPC can finish later.
`scanned` includes the fetched-but-unexamined tail: it counts returned
document rows, not examined rows or admissions.
- If the newest query raises `FailedPrecondition` (including an
unavailable DESC index), emit
`event=summary_debt_repair_newest_index_unavailable outcome=error` once,
count one error, skip that phase and still finish the near-expiry cursor
and counters. No alternate query is used; other exceptions propagate. An
empty near-expiry page followed by a newest-phase precondition failure
still finishes the cursor lease and publishes all five counters with one
error. Pagination uses the last examined row directly and never indexes
an earlier phase’s page tail. Both sweep callers accept an older
tick-result shape without `near_expiry_admitted`.

No extra per-user ranking reads are added. Eligible rows have no
reliable denormalized Home-today or active-user rank, so that preference
is deferred. Existing lifecycle/local-only exclusions remain.

## Settings and capacity

Three startup settings are registered in the flag catalog and
deployment-setting classification:

| Setting | Default | Bounds |
|---|---:|---:|
| `SUMMARY_DEBT_REPAIR_ADMISSION_LIMIT` | 8 | 1..60 |
| `SUMMARY_DEBT_REPAIR_PER_OWNER_LIMIT` | 3 | 1..10 |
| `SUMMARY_DEBT_REPAIR_SCAN_LIMIT` | 100 | 1..5000 |

Invalid values restore defaults. At 120 seconds/tick there are 30
ticks/hour, so the admission-attempt ceiling is the per-tick limit x 30:
default 240/hour, maximum 1800/hour. Lead2 `8b9c8f` sets
prod/backend-integration to eight attempts/tick in the runtime overlay
and ops inputs; the runtime manifest is regenerated. No other service
receives an override. Lead2 `d233ac` also sets the code default/fallback
to eight. The owning capacity record
`/Users/dazheng/workspace/omi/data/run-2026-11-08-retro-fixnow/out-sd-capacity.md`
uses a $0.0054/repair mean: 8/tick = 5760/day = $31.104/day (~$31.1),
within David's $36 planning budget. This is the ruling's worst-case
full-admission estimate using a mean, not a hard dollar bound or a
billing measurement by this task. Production cap rollback is explicit 10
in both inputs followed by regeneration and an authorized deploy; unset
now restores default 8.

Owner `215fdc` raises the scan maximum to 5000 without changing default
100 or adding an overlay value. Full-utilization row-read arithmetic:
720 ticks/day x 100 rows = 72000 document reads/day per 100 rows/tick.
At 2800 rows: **2800 document reads/tick and 2016000/day**; at 5000:
3600000/day. These figures exclude retries, empty-query minimums,
index-entry charges, cursor transactions and admission/fence/outbox
reads. The supplied ~84k-row window (`refactor-lead a7dc6f`, original
measurement timestamp not supplied) implies an ideal ~28h pass at
100/tick and ~1h at 2800/tick. Strictly under one hour needs more than
2800 if 84k is exact, before admission/time stops and cursor rewinds. A
debt-only index/filter that skips refusals is the structural fix and is
out of scope.

## Index readiness and telemetry

Keep the ASC composite and add `(summary_first_pending_at DESC,
summary_due_at ASC, __name__ ASC)` for the conversations collection
group, with index/query-shape/driver registries and generated manifest
updated. **The new DESC index must be READY in the target project before
deploy**, through the existing provisioning/readiness lane. The
selective phase error handling preserves urgent progress but does not
remove this deployment prerequisite. No deploy, index apply, flag flip
or production access is performed here.

Keep expired_seen/overdue/oldest/sample gauges and add
`near_expiry_admitted` to tick/sweep counts plus its gauge.
`omi_summary_debt_repair_total{outcome}` accumulates exactly the
returned tick values for `scanned`, `admitted`, `error` (returned
`errors`), `expired_seen` and `near_expiry_admitted`. It increments once
after cursor completion, outside transactional callbacks; unclaimed
ticks and transaction retries do not duplicate increments. All metric
names/outcomes are declared and pinned in tests.

Post-deploy admissions readback:
`sum(rate(omi_summary_debt_repair_total{outcome="admitted"}[10m]))`,
alongside `near_expiry_admitted`, `error`, the serving release identity,
sample freshness and summary receipts. Admissions are redrives, not
completed summaries. No live backlog, throughput, index readiness or
vendor spend was measured by this task.

## Validation

Current fix verification runs on m1 through
`/Users/david/workspace/omi-workspace/bin/omi-heavy`, with file-isolated
unit processes and `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`. Local
results: **2675 passed** across 12 targeted files (104 summary/age-gate,
1729 lifecycle inventory, 842 index/query guards; one test deselected by
the standard marker filter) at 2026-11-10T17:03:08+00:00; **225 passed**
across the repair-cap, production-policy and sweep-caller files at
2026-11-10T16:59:25+00:00; **49 passed** against the real loopback
Firestore emulator at 2026-11-10T17:02:41+00:00. `make preflight`: **51
checks passed** before the final hardening at 2026-11-10T17:00:13+00:00,
including the complete query-shape guard (560 passed). Final PR-body
preflight: **51 checks passed** against `1112536b8397` at
2026-11-10T17:05:26+00:00. Normal pre-push hooks remain enabled.
Detailed evidence is recorded in
`/Volumes/scratch/cl2-fixnow-push25019/out-25019-fix4.md` with
timestamps. CI after this push is the authority for the complete backend
suite.

Regressions cover three persistent failing urgent rows for A and more
than two scan budgets of A's newest rows before B; B must be discovered
within a bounded number of ticks. After the obstruction is removed,
every retained deferred row must be admitted across wrap. Both enabled
and disabled age-gate modes are covered. The index-failure regression is
parameterized over empty urgent and owner-deferred urgent pages. The
emitted version-2 phase cursors remain usable by existing phase readers;
cleared flat fields cause older enabled-gate readers to rewind, while
disabled-gate readers retain the compatible flat due/path continuation.
No lifecycle field, query shape, or cursor field is added, so the
existing inventory and query-driver declarations remain applicable.

Existing tests retain near-expiry priority, the shared owner cap of
three and admission cap of eight, scan/time limits, preservation of
fetched tails, lease fencing, `FailedPrecondition` completion and
counter publication.

## Merge order

**#25019 merges first. #25020 and #25021 rebase and regenerate after
it**, then rerun their summary/enrichment/sync suites. For overlapping
generated artifacts (also touched by #25018/#25012/#24731/#24857),
regenerate from the combined sources rather than hand-resolving output
ordering: runtime-env compose, Firestore index manifest and flag
registry, followed by exact-match guards. This PR performs no merge or
review request.

Rollback: revert this PR, leaving the additive index. Unset restores
admission 8 / owner 3 / scan 100; prior admission rollback is explicit
10. The cursor schema remains version 2. Existing phase readers continue
correctly; cleared flat fields make older code rewind safely with the
gate enabled; disabled-gate mode keeps its compatible flat due/path
cursor. Deferred conversation debt remains queryable after rollback.

## Product invariants affected

- INV-MEM-4 — the generated runtime-manifest diff adds only the summary
repair cap on prod/backend-integration. Canonical memory intake,
consolidation, promotion receipts and projection authority remain
unchanged.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page

Failure mechanism: repair order: oldest-first starves user-visible debt.

Line-Count-Exception: backend/database/firestore_index_registry.py |
2336 -> 2342 | Declare the additive newest-first repair composite beside
the existing ASC requirement.

Line-Count-Exception: backend/routers/sync.py | 3820 -> 3821 | Expose
near-expiry admission counts through the existing scheduled sweep
response.
@Git-on-my-level
Git-on-my-level merged commit 9fc3d64 into main Nov 10, 2026
64 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/freshadmit branch November 10, 2026 18:02
Git-on-my-level added a commit that referenced this pull request Nov 10, 2026
…25067)

## What and why

Publish the already-reviewed #25027 queue-config patch as one
replacement on current main. Supersedes #25027 because main churn after
#25019/#25021 left the old PR DIRTY and its two-push limit is exhausted.
Do not push the old branch again; leave #25027 open for merge-desk to
close after the replacement is green.

Permanent production values remain `enrichment-fresh` 30 concurrent / 10
dispatches/s and primary `enrichment` 300 concurrent / 25 dispatches/s,
per lead2 ruling `008024` (2026-11-10). Independent config hunks
preserve primary capacity during a fresh-only rollback. Named, asserted
intentional staging divergences retain primary 50/25 and fresh 5/2. This
publication adds no behavior or scope beyond the reviewed candidate;
retry and admission policy are unchanged.

The existing operational Firestore-pressure guard may temporarily lower
live fresh concurrency to 15 while retaining 10 dispatches/s; Git
remains 30/10. Re-evaluate the 168h age gate after the backlog drains.
Only `cl2-deploy` applies production configuration; this work applied
none.

## Refs and prior verdict

- Previous published candidate:
`44e120beae04e94153c263a8201f04cfeafb6c2b` on #25027. [Earlier review
verdict](#25027 (comment)):
Codex review completed at that exact head with no findings (2026-11-10
17:12:31 UTC). This is historical evidence, not a replacement-head CI or
review verdict.
- Reviewed local candidate carried here:
`909a2e8bd516380bf9a6a3d698fa117e501d6216`, based on
`720f078b33dde3872f5156fb87a961ffec2300c7`; its recorded result was
1,079 focused tests and 37 preflight checks green.
- Replacement base: `9fc3d64dc2e62c14acbfe4e77d33344cb13fdda0`
(`origin/main`, fetched 2026-11-10).
- Replacement head: `a69af6cd4bf075b0780e561d9c63cfea25017447`
(replacement push 1/2).
- Branch: `lane/pipeline-25027-replacement`.
- Diff against base: 5 files, +53/-15; 40 changed lines outside tests,
below the 500-line cap.

The candidate merge commit was cherry-picked relative to its second
parent (`git cherry-pick -m 2 909a2e8`) onto current main. It applied
cleanly. The stable patch ID is identical for the reviewed diff and
replacement diff: `8839886f923ca8e0a10ee366e7ab8fe630318db8`. No rebase,
force push, or additional PR merge. #25019
(`720f078b33dde3872f5156fb87a961ffec2300c7`) and #25021
(`9fc3d64dc2e62c14acbfe4e77d33344cb13fdda0`) are already merged in this
base. #25019's production repair admission limit of 8, service-env
spend-cap assertions, and debt ordering are preserved exactly as merged.
#25021's pending-first-summary admission is preserved.
Query/index/registry, repair service, summary config, and runtime
manifests remain identical to this base; only the five reviewed files
differ.

Plan row: L3 notes queue bundle, replacement of #25027 -> #25032 ->
#25020. #25021 and #25019 are already merged. Stop after publication for
fresh CI and delta-only Luna review; no deploy or merge.

## Verification

Repository: `BasedHardware/omi`, replacement worktree on m1. Evidence
layer: local source/config/docs contracts and pre-push checks; no live
production measurement. All checks use the worktree-owned
`backend/.venv` through `bin/omi-heavy run --`, with GCP credentials
unset:

```bash
env -u GOOGLE_APPLICATION_CREDENTIALS -u GOOGLE_CLOUD_PROJECT -u GCLOUD_PROJECT -u CLOUDSDK_CONFIG -u CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE -u SERVICE_ACCOUNT_JSON -u FIREBASE_AUTH_CREDENTIALS_PATH -u GCP_AGENT_TIER -u CLOUDSDK_CORE_PROJECT -u CLOUDSDK_PYTHON /Users/david/workspace/omi-workspace/bin/omi-heavy run -- bash -c 'set -euo pipefail
backend/.venv/bin/python -m pytest backend/tests/unit/test_config_train.py -q
backend/.venv/bin/python -m pytest backend/tests/unit/test_cloud_run_rightsizing_pins.py backend/tests/unit/test_sync_two_lane.py -q
backend/.venv/bin/python -m pytest backend/tests/unit/test_drift_check.py -q
for suite in test_summary_delivery test_summary_repair_limits test_firestore_query_shapes test_firestore_outside_query_contract test_firestore_caller_witnesses test_firestore_runtime_witnesses test_firestore_index_rules test_firestore_query_contract test_firestore_field_indexes test_vad_cache_ttl_config; do
  backend/.venv/bin/python -m pytest "backend/tests/unit/${suite}.py" -q
done'
```

| Contract | Result |
| --- | --- |
| Config-train (spend cap + queue/staging assertions) | 52 passed |
| Cloud Run rightsizing + sync two-lane | 52 passed |
| Drift check | 32 passed |
| Summary delivery | 63 passed |
| Summary repair limits | 35 passed |
| Firestore query shapes | 560 passed |
| Outside-query contract | 31 passed |
| Firestore caller witnesses | 40 passed |
| Firestore runtime witnesses | 25 passed |
| Firestore index rules | 96 passed |
| Firestore query/registry contract | 50 passed |
| Firestore field indexes | 41 passed |
| Existing pipeline-doc config contract | 2 passed |

All 1,079 focused tests passed on this exact head, including all seven
canonical Firestore index-guard suites (843 tests). PR-body preflight:
37 checks passed (43.74s). Normal full pre-push: passed, including
backend type checking, the selected 52-test config-train suite, and
pinned Python formatting. Replacement push 1/2 was accepted; no skip
hatch. Local logs: `.agent-brief/replacement-focused.log`,
`.agent-brief/replacement-preflight.log`,
`.agent-brief/replacement-push.log`. No skip hatch.

Product invariants: none — ops capacity, contract assertions, and
existing operational docs only.
UI-Evidence: none — backend configuration only.
Failure-Class: none

## Rollback and success metric

Use a targeted fresh-value config edit to 15 concurrent / 10
dispatches/s, applied by `cl2-deploy`; primary stays 300/25 and
summary-debt repair admission is preserved. Never fully revert to
primary 50/25 plus fresh 5/2 during backlog. The operational fallback is
temporary and leaves the permanent Git target at 30/10. Keep both queues
running to drain admitted obligations; never delete or purge their
tasks.

Acceptance metric: owed first summaries older than 15 minutes < 1%. This
is the owed success metric, not a new measured result or alert. Check
handler 5xx, 409 delivery-budget cuts, executor wait, LLM request
latency/errors, and title age before subsequent capacity decisions.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25067?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/25067?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25067&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. -->
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