Repository navigation
fix(summary): clear due indexes on durably refused conversations - #25020
Merged
Merged
Conversation
Clear donor and manual-edit debt atomically, retire enriched residue, and add a guarded counts-only backfill with lifecycle writer coverage. Failure-Class: FC-obligation-outlives-terminal-owner
Exercise the real chat codec and prevent generated summary enrollment metadata from escaping into the manual-field transaction. Failure-Class: FC-obligation-outlives-terminal-owner
Re-audit the unchanged People generation branches after conversation-only due retirement. Verified 13 strict transaction tests, 31 loopback emulator checks and 5 inventory tests before refreshing the four affected fingerprints. Failure-Class: FC-obligation-outlives-terminal-owner
Persist due retirement atomically while returning only user-editable snapshot fields. Cover real-codec title and overview edit/undo round trips and refresh the verified shared People writer audit. Failure-Class: FC-obligation-outlives-terminal-owner
Update the legacy exact-patch expectation to include summary_due_at=None on the durable manual title write. The full revision contract passes 26 tests. Failure-Class: FC-obligation-outlives-terminal-owner
Failure-Class: FC-obligation-outlives-terminal-owner
This was referenced Nov 10, 2026
Failure-Class: FC-obligation-outlives-terminal-owner
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.
Failure-Class: FC-obligation-outlives-terminal-owner
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. -->
Git-on-my-level
added a commit
that referenced
this pull request
Nov 10, 2026
#25034) ## Summary - classify both terminal empty-output block reasons (`empty_output_exhausted`, `empty_output_lifetime_exhausted`) as the existing `home_step=noise` state regardless of `structured.title_provenance`, but only when the summary has no overview or section body - reuse `summary_delivery.present` so a title, action item, or event cannot masquerade as summary output; curated rows retain their existing precedence - a banked receipt (`summary_output_present` or `summary_completed_at`) or a live `summary_due_at` outranks a stale terminal reason, so a recovered or re-opened row stays `ready`/`writing_notes` instead of disappearing - add the default-on `HOME_EMPTY_OUTPUT_NOISE` kill switch, its registry/deployment classification, and a budget exception owned by `refactor-lead` with `review_by=2026-12-10` Source: audit class 10 (2026-11-10), relay-cl1 ruling f6502a, lead `refactor-lead`. Failure-Class: FC-provisional-home-content-published-as-final ## Base and head - Base: `origin/main` `35e63b5d701f94396cd166ef22db8df37aa947d4` (merged normally; no rebase, no force-push) - Head: `c92dc8281539ab2a7a9f88db7e083fb60297f29a` (push 2/2) - Diff against the merged base: 10 files, +149/-12; 58 non-test additions. The batch adds the receipt/debt guards, docstring, and expanded regressions. ## Client impact No Flutter change is needed. `app/lib/pages/conversations/home_rows.dart` already consumes `home_step=noise` and removes that row from default Home. Its status/title fallback is only for older servers where `home_step` is absent. No `app/` files changed. ## Kill switch, default, rollback - `HOME_EMPTY_OUTPUT_NOISE` defaults on. - `false`, `0`, `off`, or `no` restores the legacy `server_minimum`-only classification. - `HOME_STEP_PROJECTION=off` remains the broader rollback that omits the field. - No deployment values change and no production data was read or written. ## Metric - No terminal empty-output row (both reasons, no overview/section body, no banked receipt, no open debt) appears on default Home. - No banked or re-opened row is hidden: `summary_output_present`, `summary_completed_at`, or a live `summary_due_at` keeps the row visible as `ready`/`writing_notes`. - Curated, failed, dead-letter, upload-failed, BYOK and local-only rows keep their existing precedence. ## Verification (measured on this head) Credentials unset before every run (`GOOGLE_APPLICATION_CREDENTIALS`, `GCP_AGENT_TIER`, `CLOUDSDK_CONFIG`, `CLOUDSDK_CORE_PROJECT`, `CLOUDSDK_PYTHON`), via `bin/omi-heavy run --`: - `tests/unit/test_home_step.py tests/unit/test_flag_budget.py tests/unit/test_summary_delivery.py tests/unit/test_summary_empty_recovery.py tests/unit/test_list_projection.py tests/unit/test_home_transcribing_hold.py` — **289 passed** - `tests/unit/test_config_refactor_w6.py` — **157 passed** - `python3 scripts/check_feature_flag_registry.py` — **OK** - `python3 .github/scripts/check_deployment_secret_boundary.py --base origin/main` — **passed** - `git diff --check` — **passed** - `scripts/pr-preflight --lane local` — **42 checks passed** - Normal full pre-push gate — **passed**, push accepted. - Fresh exact-head GitHub workflow query (2026-11-10): all 13 returned runs completed successfully, including Backend Unit Tests, Backend Hermetic E2E, Backend Emulator Proofs, OpenAPI Contract, and Runtime Image Contracts. New regressions cover: both receipt fields, open due debt, late re-open (noise -> writing_notes/ready), both terminal reasons with the switch on and off, curated-row precedence, and output-present under the switch off. The missing-provenance cases are unchanged and still asserted. ## Merge-order notes - `backend/config/flag_budget.json` `count` equals `len(names)` on this head (265 = main 264 + this flag). If corrected-base replacement #25055 (replacing #25028) or #25032 lands first, the merge must set `count` to the actual `len(names)` on that merged head, not a copied count. - `config/feature-flags.yaml`: keep #25024's rewritten `HOME_STEP_PROJECTION` line, then this `HOME_EMPTY_OUTPUT_NOISE` line, then `HOME_TRANSCRIPTION_PRESENTATION_GATE`. - `backend/tests/unit/test_flag_budget.py`: keep every peer's `HELPER_KILL_SWITCHES` entry and `elif` branch alongside `HOME_EMPTY_OUTPUT_NOISE`. - `backend/utils/conversations/home_step.py`: #25032 widens `provisional` to include row-level `summary_title_provenance`; keep that and this `empty_output` block. The two are independent. - #25020 is clean against this branch. ## Render evidence (blocker) This is Home-visible behavior and no Flutter render has been produced for this head. Before merge, the driver must obtain renders for: 1. terminal reason + no overview/section body, provenance absent -> hidden on Home, still findable in archive/search 2. same for the lifetime reason; kill switch off -> legacy absent-provenance row visible again 3. banked output-present/completed receipt -> ready; open `summary_due_at` -> Writing notes 4. overview or section body present, user-curated, and BYOK/local-only -> stay visible as applicable 5. failed/dead-letter/upload-failed -> Activity Needs attention; no failed row on Home 6. title/action-items/events only with no overview/section body -> hidden with no visible retry. This is the independent visibility review's case: the row is hidden and no automatic retry is surfaced, so David must accept that exact behavior. Do not merge until fresh renders go to relay-cl1 and David acknowledges them.
Git-on-my-level
added a commit
that referenced
this pull request
Nov 11, 2026
…#25049) # seal-speed: cut the per-row startup bill and give the repair pod real CPU ## Why A recording seal takes ~89 s per row (p50) and the seal itself is ~5 s of it. Measured 2026-11-10 on `origin/main` = `9c051da5be4b` (evidence: `omi-workspace/data/run-2026-11-08-pipeline-refactor/findings-fable-seal-time.md`): | stage | p50 | share | | --- | ---: | ---: | | `startup` (fork/exec + module imports) | 45.1 s | 51% | | `clients` (lazy imports + Firestore/GCS construction) | 32.7 s | 37% | | `proof` + `list` + `walk` + `apply` (the actual seal) | 5.3 s | 6% | Two compounding causes, both fixed here: 1. **The row process imports the web framework.** `record_seal_cluster_repair` reaches `utils.observability.fallback` -> `utils.metrics` -> `from fastapi import Response`, and `database.batch_pipeline_store` -> `utils.sync.stage` -> `from fastapi import HTTPException`. fastapi/pydantic is ~60% of the import bill. A recording seal does no HTTP work. 2. **The pod is CPU-starved.** The CronJob's `nodeAffinity` deliberately excluded `batch-pipeline-pool`, so repair landed on the monitoring pool at 101% CPU and received ~2 of its 4-core limit. The batch-pipeline pool sits at 8-19% CPU. The image also shipped no `.pyc` and the CronJob set `PYTHONDONTWRITEBYTECODE=1`, so every one of ~250 row processes per run re-parsed source. **No worker-count change.** 16 -> 24 was already measured in prod and lost 15-35% of seals per run (#24962, reverted by #24966); 48 was worse (#24729). More workers only split the same starved CPU. ## What changed **1. Placement and CPU request (chart only).** `backend/charts/batch-pipeline-worker/templates/record-seal-repair.yaml` now pins the repair pod to `batch-pipeline-pool` and carries that pool's two taints (`omi.ai/batch-pipeline=true`, `nvidia.com/gpu=present`). CPU request 2 -> 4, which equals the unchanged CPU limit. Memory remains request 4 GiB / limit 8 GiB, so the pod stays Burstable; the scheduler now reserves four CPU cores. Both are values-driven (`recordSealRepair.nodePool`, `recordSealRepair.tolerations`, `recordSealRepair.cpuRequest`); setting `nodePool=` and `tolerations=[]` restores the old exclusion from values alone. **2. Precompiled bytecode.** `backend/diarizer/Dockerfile.batch-pipeline` gains `RUN python -m compileall -q /app` after the last `COPY`, and the CronJob no longer sets `PYTHONDONTWRITEBYTECODE=1`. The repair pod runs with `readOnlyRootFilesystem: true`, so the `.pyc` must be baked at build time. `.dockerignore` now excludes `**/__pycache__` so host bytecode cannot shadow the build-time compile. **3. No web framework in the row path.** `utils/metrics.py` and `utils/sync/stage.py` import fastapi inside the one function that needs it (`metrics_response`, `require_http_stage`) and annotate with `TYPE_CHECKING`. Behaviour is unchanged: `/metrics` still returns the same `Response`, and the sync-stage HTTP dependency still raises `HTTPException(503)`. ## Follow-up: Plan v3 L2 ordering The bundle omitted the newest-first / near-dead-letter-first part of L2 (David ruling reference `6db8f2`). The follow-up adds: - Urgent pending jobs first, ordered by their stored dead-letter deadline and document name. **Implementation choice: near = final 24 hours** before the stored 14-day barrier deadline; already overdue pending jobs are included. Age never invents a deadline, and terminal jobs are excluded. - Newest enqueue/name order for ordinary jobs and newest finish/name order for conversations. The existing half-worker reservation for conversations stays. - An independent encrypted urgent cursor and new recency cursor names, keeping old ascending frontiers out of the descending scans. Frozen recency horizons, wrap, minimum-age eligibility, exact numeric cursor clocks, and checkpoints before proofs / after attempts remain covered. - Five additive indexes in the batch registry and generated manifest: job recency/deadline for both stages, and completed-conversation recency. The deployment readiness gate must confirm them before an image ships. No live index apply or deploy was run. - Default-on behavior through the existing `RECORD_SEAL_REPAIR_AGE_ORDER` kill switch. Off skips urgency and restores the original hash jobs scan. The ordinary missing-index fallback survives; a missing urgent index skips only that leg, emits content-free degraded telemetry, and continues ordinary and conversation discovery. The extra urgent page uses 128 rows **inside** the existing 10,000-row aggregate scan cap; candidate cap 1,024, worker count 16, row budget 270 seconds and run budget 1,500 seconds are unchanged. Roll back the follow-up commit to restore prior ordering; old frontier documents are untouched. No seal-proof or custody rules change. Also corrected the chart test's QoS wording and added Starlette to the coordinator-module import assertion. ## Tuning disclosure | | before | expected after | | --- | --- | --- | | per-row p50 | 89 s | ~40-55 s | | workers | 16 (unchanged) | 16 (unchanged) | | CPU actually available | ~2 cores (node at 101%) | 4 cores requested/reserved | | seals/run | ~200 | ~330-450 (estimate) | | throughput | ~390 seals/h | ~700-900 seals/h (estimate) | The "after" numbers are estimates, not measurements: they extrapolate the measured import share and the 2 -> 4 core change. They must be confirmed from the CronJob's own `record_seal_repair_row` stage events over a full run before any further tuning. **This PR does not change worker count, `rowSeconds`, the run budget, or the seal rules.** Local import measurement (warm Mac, image-shaped tree, 2,811 `.py` files): | | row import | | --- | ---: | | before, with `.pyc` | 8.0 s | | after, with `.pyc` | 1.2 s | | after, without `.pyc` | ~3.9 s | So the fastapi removal is the larger lever (~6.7x) and `compileall` is the second (~2x on the remaining import). The absolute seconds are indicative; the *share* is the load-bearing part. ### Scheduling note the reviewer should weigh `g2-standard-8` allocatable is ~7.8 vCPU and the GPU worker requests 4, so a 4-CPU repair pod does **not** co-schedule with a worker: the pool autoscaler adds a node (pool max 16, currently 4 workers). That is the cost of a four reserved CPU cores. If the lead prefers no extra node, set `recordSealRepair.cpuRequest: "3"` — 4 + 3 = 7 fits beside a worker, and the pod still gets 3 guaranteed cores instead of today's ~2. This is a values-only change; the template does not need to move. ## Rollback - **Placement only:** `--set recordSealRepair.nodePool= --set-json 'recordSealRepair.tolerations=[]'` restores the old monitoring-pool exclusion. `--set recordSealRepair.cpuRequest=2` restores the old request. - **Whole job:** `recordSealRepair.suspend: true` (already the documented rollback in `prod_omi_batch_pipeline_worker_values.yaml`). - **Code:** revert this commit. The lazy imports are behaviour-preserving, so a revert needs no data migration and no image rollback beyond the normal digest pin. ## m1 verification (2026-11-10) Merged `origin/main` through `986386ba0e48` without rebasing. Through `bin/omi-heavy` and `backend/test.sh` (file-isolated runner): import graph **4 passed**, chart render contracts **13 passed**. Worker count remains 16 in the production render. The completed follow-up also ran this explicit 12-file selection through `bin/omi-heavy run -- env -u GOOGLE_APPLICATION_CREDENTIALS -u CLOUDSDK_CONFIG -u CLOUDSDK_CORE_ACCOUNT BACKEND_UNIT_TEST_FILE_LIST=<selection> BACKEND_UNIT_FILE_BUDGET_SECONDS=3600 bash backend/test.sh`: - `test_record_seal_row_import_graph.py`: 4 passed - `test_record_seal_cluster_repair_deploy.py`: 13 passed - `test_record_seal_cluster_repair.py`: 136 passed - `test_record_pending_repair.py`: 60 passed - `test_record_seal_priority.py`: 13 passed - Seven selector-owned Firestore guard files: 842 passed, 1 deselected **Total: 1,068 passed, 1 deselected.** These are hermetic checks; no live cluster or full CUDA image build was exercised. The actual push passed the full repository pre-push hook with no skip switches: 47 shared preflight checks, whole-backend type checking (0 errors), and the selected backend test files and formatting checks. ## Original lane verification New `backend/tests/unit/test_record_seal_row_import_graph.py` (4 tests): - imports `scripts.record_seal_repair_job` in a clean interpreter and asserts `fastapi`, `pydantic` and `starlette` are absent from `sys.modules`; - the same for `utils.batch_pipeline.record_seal_cluster_repair`; - `metrics_response()` still returns a `starlette.responses` object with the Prometheus content type and `omi_*` samples; - `require_http_stage()` still raises `HTTPException` 503 on an unknown stage. New chart tests in `backend/tests/unit/test_record_seal_cluster_repair_deploy.py`: - the repair pod's `nodeAffinity` requires `batch-pipeline-pool` and its tolerations match that pool's taints; - request == limit == 4 CPU, and no GPU in the limits; - `PYTHONDONTWRITEBYTECODE` is absent from the CronJob env; - `nodePool=` + `tolerations=[]` renders the old exclusion exactly. Commands run through `bin/omi-heavy` (the host was at load 150-350 from other lanes, so every run waited for a slot). Each file below was run in its own pytest process, as the backend contract requires: ``` backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_row_import_graph.py 4 passed backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_cluster_repair_deploy.py 13 passed backend/.venv/bin/python -m pytest -q tests/unit/test_record_seal_cluster_repair.py 136 passed backend/.venv/bin/python -m pytest -q tests/unit/test_record_partial.py 67 passed backend/.venv/bin/python -m pytest -q tests/unit/test_sync_stage_isolation.py 6 passed backend/.venv/bin/python -m pytest -q tests/unit/test_omi_flags.py 84 passed backend/.venv/bin/python -m pytest -q tests/unit/test_external_list_cache.py 38 passed backend/.venv/bin/python -m pytest -q tests/unit/test_episodes_metrics_export.py 2 passed backend/.venv/bin/python -m pytest -q tests/unit/test_llm_gateway_routers_metrics.py 4 passed backend/.venv/bin/python -m pytest -q tests/unit/test_metrics_sidecar_server.py 2 passed backend/.venv/bin/python -m pytest -q tests/unit/test_metrics_cardinality_contract.py 4 passed ``` A single combined run of the record-seal and metrics files (604 passed) also covered `test_record_seal_sweeper_deploy`, `test_record_seal_worker_deploy`, `test_record_seal_worker_guards`, `test_record_seal_rules`, `test_record_seal_fast`, `test_record_seal_nojob`, `test_record_seal_sweep_budget`, `test_record_seal_sweeper` and `test_record_seal_worker`. That combined run reported two failures in `test_sync_stage_isolation.py` from cross-file `caplog` contamination, which is exactly why the contract isolates files; the file passes 6/6 on its own (above). Static checks: ``` backend/.venv/bin/python scripts/scan_import_time_side_effects.py Checked 2530 backend production file(s); 0 violation(s). backend/.venv/bin/python scripts/check_module_stub_pollution.py Checked 2919 backend test file(s); 0 violation(s). make runtime-image-source-closure Runtime-image contracts passed for 19 registered images. python3 .github/scripts/check_failure_class_guard_ratchet.py OK: every class at or above the threshold names a guard artifact. scripts/failure-class validate --pr-body-file .agent-brief/pr-body.md ok: true helm template ... -f prod_omi_batch-pipeline-worker_values.yaml renders; rollback render verified ``` Not run: a full `docker build` of `Dockerfile.batch-pipeline` (torch/CUDA wheels) and any live cluster apply. The `compileall` step is verified by inspection and by the local `.pyc` measurement above, not by a built image. ## Product invariants affected - INV-DATA-1 — preserves the existing customer data-plane authority. The selected source SHA and `vars.RUNTIME_GCP_PROJECT_ID` bind the read-only index gate to the release’s existing Firestore authority; this is not a customer data-plane migration. Failure-Class: new Line-Count-Exception: backend/utils/metrics.py | 1722 -> 1730 | Keep the HTTP Response import at its sole call boundary with a TYPE_CHECKING annotation; splitting the shared metrics registry is outside this startup fix. Line-Count-Exception: backend/utils/batch_pipeline/record_seal_cluster_repair.py | 791 -> 887 | Keep the bounded priority query and its cursor checkpoints with the existing coordinator; the follow-up adds no separate seal or mutation authority. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/25049?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/25049?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25049&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. --> ## Pre-review dispositions Consolidated fix batch after merging current `origin/main` (no rebase). - **Production safety P1-1 — fixed:** the existing `gcp_diarizer.yml` stages immutable Firestore gate controls and invokes the same readiness action/inputs as `gcp_backend.yml`, unconditional with its sparse control checkout, registered in `_LANE_SOURCE_BINDINGS`, and bound to `${{ steps.vars.outputs.source_sha }}` before build, digest promotion or Helm. No new workflow. - **Production safety P1-2 / correctness P2-3 — fixed:** catch `FailedPrecondition` around urgent discovery only, emit content-free `index_unavailable` and shared degraded fallback telemetry, then run ordinary and conversation discovery. Regression covers plan/apply and the real CronJob entrypoint returning 0; provider exception contents never enter events. - **Correctness P2-1 / Luna malformed-prefix FIX-FIRST at earlier head `7c214814` — fixed:** urgent discovery uses `record_dead_letter_deadline_at > 0` and the existing final-day upper bound. Every examined row advances the encrypted query position before eligibility checks. The urgent codec accepts raw scalar scan positions while ordinary enqueue cursors keep numeric validation, so malformed metadata cannot create an unreadable frontier. Examined invalid deadlines add to the existing content-free `invalid_clock_rows` metric and are not selected for urgent processing. A persistent full malformed prefix cannot pin valid jobs; the existing saturated-page regression is retained and now checks readable advancing progress. - **Production safety P2-7 / correctness P2-2 — fixed:** runbook names the v2 conversation/recency cursors and v1 urgent cursor, newest-first ordering, gate and degraded behavior. - **Correctness P2-4 — fixed:** direction-aware conversation query fake verifies descending finish/name ties, encrypted resume, frozen horizon and wrap. - **Production safety P2-1 / Luna FIX-FIRST at earlier head `0711777f` — fixed:** ordinary discovery runs every enabled run within the shared discovery budget. For allocation `A = max(1, workers // 2)`, reserve `R = max(1, A // 4)` ordinary places; urgent discovery gets at most `A - min(R, ordinary candidates)`. With 16 workers, ordinary retains 2 of 8 job places under sustained urgency; with no ordinary candidates, urgent can use all 8. Unused urgent capacity returns to ordinary candidates. Urgent attempts remain deadline-first. Held ordinary candidates stay ahead of their encrypted checkpoint. The hard bound is one run between ordinary scans, with no finite settlement-time guarantee. The change doc and runbook now state the bound. - **Production safety P2-2 — follow-up:** review urgent cursor wrap/fairness for newly urgent work behind the frontier. - **Production safety P2-3 — follow-up:** measure newest-first candidate yield against the unchanged 30-minute minimum age and append-proof refusals. - **Production safety P2-4 — follow-up:** validate GPU-pool scheduling, 4-CPU reservation, autoscaler headroom and cost before deployment. - **Production safety P2-5 — follow-up:** verify compiled bytecode/readability in the built batch worker image; full CUDA image build was not performed locally. - **Production safety P2-6 — follow-up:** old v1 frontiers remain stale on code rollback; clarify the urgent numeric payload naming in a later cursor change. - **Production safety P2-8 — follow-up:** `typing.get_type_hints(metrics_response)` needs a runtime `Response` resolution if a caller is introduced. ## CI regression dispositions after earlier head `783ec7ff` The complete logs for [run 42879396660](https://github.com/BasedHardware/omi/actions/runs/42879396660) reveal regressions triggered by this PR. The earlier classification as unrelated was incorrect. - **Workflow policy — fixed:** removed both unsupported service predicates from `gcp_diarizer.yml`. The sparse immutable-controls checkout and readiness gate are unconditional. Registered the workflow's real `${{ steps.vars.outputs.source_sha }}` expression in `_LANE_SOURCE_BINDINGS`. The existing policy and all its enforcement remain intact. Baseline: 2 workflow tests failed; corrected suite: 98 passed. - **Lazy HTTP import / shard 3 — fixed:** `require_http_stage()` imports `HTTPException` only inside `except InvalidSyncStage`; valid stage checks remain free of FastAPI. The import trace for the slow test was `database.conversations` → `utils.other.storage` → `utils.cloud_tasks` → FastAPI, during a test-body import. Removing earlier framework warming exposed that call-phase cost. The test now loads the real visibility dependency in module-fixture setup, as required by the CPU guard's setup/call boundary. The 1.00-second limit and all rollback/visibility assertions remain unchanged. Local call CPU: 0.575309 s before, 0.000652 s after (2026-11-10, m1; repo guard measurements). Fixture/setup still pays the dependency import. - **Multipart / shard 8 — fixed:** the isolated `test_sync_transcription_prefs.py` fixture itself replaced `python_multipart` with a plain `ModuleType`, hiding `python_multipart.exceptions`. Removed that unnecessary package shadow and retained the installed lightweight parser. Existing `stub_modules` teardown continues to restore its other fakes. Baseline isolated run: 59 setup errors; corrected file: 59 passed. CI launches one Python process per file, so another file's module state cannot leak into this failure. `test_action_items_conversation_list_malformed.py` already removes its conditional fallback stub in `finally` and skips installing it when the real package is present. - **Gacrux desktop — no voice defect found:** the old shard log's adjacent `FAILED [87%]` belongs to concurrent workflow-contract output. The voice file's own terminal summary is **119 passed**, with no failed-file status. Both baseline and corrected isolated local runs also pass all 119 tests, including Gacrux desktop; voice code is untouched. - **Row import graph — preserved:** 5 subprocess contracts pass, including the new valid-stage path assertion that FastAPI/Pydantic/Starlette stay absent and the existing invalid-stage HTTP 503 behavior. Local reproduction on the merged tree (2026-11-10, m1): - Focused regression selection: **344 passed** across workflow contracts, merge jobs, sync preferences, voices, row import graph, stage isolation, deploy and priority tests, via `backend/test.sh`. - Original shard 3: 345 original CI files, all passed locally (exit 0). - Original shard 8: 345 original CI files, all passed locally (exit 0). - Both original shard file sets contain 345 files, exactly matching the complete old CI logs. Launch order is reconstructed with the unchanged runner's LPT weights and shard-1 typecheck reservation over the original 2,741-file selection (including workflow-contract extras). Both use `BACKEND_PYTEST_WORKERS=4`, file isolation, 0.1-second warning / 1.0-second failure CPU guards and `BACKEND_UNIT_FILE_BUDGET_SECONDS=3600` through `backend/test.sh`, with the three ambient GCP credential variables unset. No policy, budget, allowlist or hook bypass. The former prod P2 follow-ups above remain as listed. No deployment or PR merge. CI correction at earlier head `0711777f1cbc2fc2c92eb833497a8a94b6affb4f`. Full local shard evidence recorded 2026-11-10T19:28:30+00:00 in `backend/docs/listen_pusher_pipeline/changes/2026-11-10-record-seal-priority.md`, including manifest hashes and the exact runner settings. Full push-hook receipt (2026-11-10T19:37:43+00:00): **passed** at earlier head `0711777f1cbc2fc2c92eb833497a8a94b6affb4f`. All 56 selected preflight checks and the bounded unit selection passed with the required credential-unset/body-file/3600-second recipe. GitHub received one update from earlier head `783ec7ff49` to that earlier head; no force-push or hook bypass. The `sealfix2` worktree was removed via lane finish. [Backend Unit Tests run 42886859875](https://github.com/BasedHardware/omi/actions/runs/42886859875) owns that earlier head's CI result. ## Luna FIX-FIRST: ordinary-job reserve The urgent leg previously filled the entire job allocation before ordinary discovery was considered. A sustained urgent backlog could suppress the ordinary query forever. Ordinary discovery now runs first with one bounded page, urgent discovery is capped by the ordinary reserve, and attempt order remains urgent deadline-first, then ordinary, then conversations. Both legs retain their existing encrypted frontiers and combined worker reservation; held ordinary candidates cannot be checkpointed past. No extra query or scan budget is added. Regression coverage uses real bounded job queries and encrypted cursors at 2, 4 and 16 workers: repeated runs under sustained urgency retain the ordinary reserve, an empty ordinary pass allows full urgent capacity, and a partially used ordinary reserve returns unused places to urgency. The one-place allocation edge, pre-attempt checkpoints, urgent index degradation and conversation capacity are covered. L1 #25018 was open at the main merge; no L1 conflict was present. Local reserve verification (2026-11-10T20:21:16+00:00, m1): all 15 record-seal unit files through `backend/test.sh` under `omi-heavy`: **436 passed, 3 skipped** (Firestore emulator unavailable), including 35 priority, 136 coordinator and 5 import-graph tests. Credential variables unset; file isolation, four file workers, 3600-second file budget and unchanged 0.1/1.0-second CPU guards. Main merged through `85de1985f0fb4fddd05e0de4b36c1ac68108d81e`, without rebasing. `git diff --check` and required invariant metadata validation pass. Ordinary-reserve fix at earlier head `d991957cab4ed220198e859660af33dec156510a`. Full push-hook receipt (2026-11-10T20:25:33+00:00): **passed** at earlier head `d991957cab4ed220198e859660af33dec156510a`. All **56 selected preflight checks** and the bounded unit selection passed with the credential-unset/body-file/3600-second recipe. Exactly one non-force push updated earlier head `0711777f1c` to that earlier head; no hook bypass. [Backend Unit Tests run 42895041539](https://github.com/BasedHardware/omi/actions/runs/42895041539) owns that earlier head's CI result. ## Sibling merge refresh after #25020 and #25063 Earlier head `7c214814536c30c5fb6b9d3f97ab5453571933a4` merged main; main parent: `75dc53a81df78643cf74c7638350fecc9082ebfc`. Fetched and merged main with `git merge --no-ff origin/main`, without rebasing or new feature scope, under lead2 ruling `1c606e`. The only textual conflict was `config/feature-flags.yaml`: retained this PR's current `RECORD_SEAL_REPAIR_AGE_ORDER` declaration and main's new `PIPELINE_LEDGER` declaration. Main's `NO_SPEECH_TERMINAL_ENABLED` entry also remains. The index sources merged automatically, retaining #25063's `record_no_speech_newest` and all five seal-repair indexes (prod/dev newest, prod/dev deadline, newest completed conversation). Regenerated `firestore.indexes.json` with `backend/.venv/bin/python backend/scripts/generate_firestore_indexes.py --write` and `backend/docs/feature-flag-registry.md` with `backend/.venv/bin/python scripts/render_feature_flag_registry.py`. Neither generated output was hand-merged. Semantic verification confirms every composite and field override from both parents remains in the manifest, all six required declarations are generated, and both parent flag registries are preserved with the current seal-order description taking precedence over main's older text. The Firestore generator's check mode also passes. Verification recorded 2026-11-10T23:22:56+00:00 on m1: **1470 passed, 3 skipped, 1 deselected** across 28 files through `backend/test.sh` under `omi-heavy`. Includes all 15 record-seal files (including import graph), Firestore index tests and the canonical seven query guards, plus `test_flag_budget.py` (24 passed). Emulator tests skip without an emulator; the standard runner deselects the slow-marked case. Credential variables unset, file isolation, four file workers, unchanged CPU guards and 3600-second file budget. `git diff --check` passes. `MERGE-OK 0175e5` applied to earlier head `d991957c`; it is not carried forward as approval for any later head. The merge desk re-verifies at the current PR head. PR remains unmerged. Sibling merge push receipt (2026-11-10T23:26:21+00:00): **passed** at earlier head `7c214814536c30c5fb6b9d3f97ab5453571933a4`. All **56 selected preflight checks** and the bounded unit selection passed with the required credential-unset/body-file/3600-second recipe. Exactly one non-force push updated earlier head `d991957cab` to that earlier head, with no hook bypass. [Backend Unit Tests run 42923202562](https://github.com/BasedHardware/omi/actions/runs/42923202562) owns that earlier head's unit CI result. Firestore CI queue observed 2026-11-10T23:36:37+00:00: earlier head `7c214814`'s [index workflow 42923203481](https://github.com/BasedHardware/omi/actions/runs/42923203481) was pending behind the shared `firestore-schema-prod` concurrency lock held by [main reconciliation 42920647780](https://github.com/BasedHardware/omi/actions/runs/42920647780) from #25063. The main run was executing, with no pending environment approval at that observation. These owning run links carry the current state; no index apply, cancellation, approval or lock change was performed as part of this conflict refresh. ## Luna FIX-FIRST: persistent malformed urgent prefix Disposition: fixed. The urgent query now has a positive lower bound and its existing final-day upper bound on the same deadline field; the current `(state ASC, record_dead_letter_deadline_at ASC, __name__ ASC)` index serves this range without a new declaration. Cursor advancement happens for every examined row before local eligibility validation. Raw scalar urgent scan positions round-trip through the encrypted maintenance codec; ordinary enqueue cursor validation is unchanged. Examined invalid deadlines contribute to the existing `invalid_clock_rows` summary, without identifiers or payloads and without urgent processing. Query-excluded rows are not enumerated or counted. The persistent-prefix regression leaves 128 malformed rows in place and proves the real query floor discovers valid urgent jobs in one run. A separate adversarial projected-page case bypasses the floor and proves encrypted cursor advancement discovers valid urgent jobs in two runs while counting all 128 examined malformed rows. The earlier saturated-page test remains, including null, boolean, string, non-positive and non-finite cases; it now asserts a readable advancing cursor. Coordinator coverage verifies discovery invalid-clock counts are combined with the existing aggregate. No worker, scan, query-count or proof budgets change. Fetched main before work; main remains the already merged parent, so no additional main merge or rebase was needed. Prior approvals apply to their earlier heads; the merge desk must re-verify the new published head. Local malformed-prefix verification (2026-11-11T00:26:25+00:00, m1): **1,310 passed, 3 skipped, 1 deselected** through the repo runner across 23 files. Includes all 15 record-seal files, the canonical seven Firestore guards and `test_flag_budget.py`; all 39 priority cases and all five row-import contracts pass. The earlier ordinary-reserve batch's priority-file subtotal is corrected from 38 to 35; its recorded total remains 436. The Firestore generator check passes with no new registry or manifest change. Credential variables unset, file isolation, four file workers, unchanged CPU guard and 3600-second per-file budget. Current head: `e47911c994d6fb0fd7b30ec5cb45da1b8761dff1`. All historical receipts above refer to earlier heads. Malformed-prefix push receipt (2026-11-11T00:31:41+00:00): **passed** at current head `e47911c994d6fb0fd7b30ec5cb45da1b8761dff1`. All **56 selected preflight checks** and the bounded unit selection passed with the required credential-unset/body-file/3600-second recipe. Exactly one non-force push updated earlier head `7c21481453` to the current head, with no hook bypass. [Backend Unit Tests run 42931834561](https://github.com/BasedHardware/omi/actions/runs/42931834561) owns the current head's unit CI result.
Git-on-my-level
added a commit
that referenced
this pull request
Nov 11, 2026
…a transcript on an untitled row (#25032) > Merge-main resolution under lead2 `b60140`; head `a2fdeb52268d`. Patch unchanged. Conflicts in `backend/config/flag_budget.json` and `backend/tests/unit/test_flag_budget.py` were resolved by keeping both sides (this PR's `SUMMARY_PROJECTION_DEBT_ENABLED` and main's `EPISODE_COMPOSER_REUSE`); `flag_budget.count` is 267, the merged name count. ## Summary A batch projection that lands a transcript on an already-completed row with no title and no summary now stamps the first-summary debt fields in the same write. Home then says "Writing notes" instead of hiding the row, and the debt repair can see it instead of refusing it as `unknown_provenance`. Source: Fable account audit 2026-11-10, class 4 ("Batch rows with a transcript and no title carry no notes debt"). Authority: relay-cl1 ruling f6502a. This is the consolidated fix batch for the three pre-reviews on #25032. It keeps the forward-only meaning of the stamp: old rows past the repair age gate are not stamped, and #25020 must exclude this cohort. ## What changed - `backend/utils/conversations/summary_delivery.py`: `stamp_projection_debt(write)` now: - evaluates the exact repair eligibility with the provenance the stamp would add, using the same `_refusal` predicate the repair uses. It skips locks, `client_processing`, finalization ownership/BYOK, every non-empty `summary_blocked_reason`, below-floor clips, curated rows, discards, local-only rows and rows that already carry debt or a summary; - sets the row-level `summary_title_provenance='server_minimum'` and the debt clocks, but does **not** write `structured.title_provenance`. `is_server_minimum` gates apps, goals, memories, folders and vectors, so the stamp must not suppress those effects on a later reprocess; - preserves non-dict `structured` data instead of replacing it; - gives a row whose `created_at` is already past the repair age gate the provenance but no debt. The repair never sees it, so it cannot park it one-way, and Home hides it instead of presenting "Writing notes" forever; - keeps the double-stamp guard and the `SUMMARY_PROJECTION_DEBT_ENABLED` kill switch. - `backend/utils/conversations/home_step.py`: `classify` treats the row-level `summary_title_provenance='server_minimum'` as provisional, so Home and the repair agree without the derived-effect suppression that `structured.title_provenance` would cause. - `backend/utils/batch_pipeline/live_projection.py`: `replace_record` calls the stamp only when the projection actually placed new transcript segments, so the debt lands in the same transaction write. - Kill switch `SUMMARY_PROJECTION_DEBT_ENABLED` (default on; `false`/`0`/`off`/`no` restores today's behavior). Registered in `config/feature-flags.yaml`, `backend/config/flag_budget.json` (owner `refactor-lead`, review_by 2026-12-10) and the generated registry doc. The YAML row is appended at the end of the active `flags:` list to reduce insertion races with other open PRs. - `backend/tests/support/lifecycle_writer_inventory.py`: reviewed the two `summary_due_at` / `summary_first_pending_at` payload sites. - `.github/failure-classes/FC-content-write-omits-implied-obligation.json`: updated the canonical prevention to the row-level provenance and age-gate behavior. ## #25020 ordering #25032 lands before #25020. `unknown_provenance` is a missing-stamp defect for this cohort, not a durable refusal. #25020's backfill must exclude rows whose only refusal is `unknown_provenance` (or whose `summary_title_provenance` is `server_minimum` with a live debt clock) until a provenance backfill exists. This PR does not edit #25020's branch. ## Tests All through `bin/omi-heavy` on this head, with GCP credentials unset: - Merge-main re-run on `a2fdeb52268d` (merge of `origin/main` `88ce231c7c83`): focused debt-stamp/registry/home/flag-budget suites 338 passed; exact schema-inventory test 1 passed; registry/render contracts OK; normal full pre-push gate passed (62 checks, 0 failed; bounded backend selection green). - Merge-main re-run on `e63cd5b3aad7` (merge of `origin/main` `75dc53a81df7`): focused debt-stamp/registry/home/flag-budget suites 338 passed; exact schema-inventory test plus deployment-contract suites 155 passed, 3 skipped; registry/render/policy-guard/release-process/runtime-image contracts all OK; normal full pre-push gate passed (62 checks, 0 failed; bounded backend selection green). - `tests/unit/test_batch_pipeline_live.py` and `tests/unit/test_home_step.py`: 213 passed. Covers the touched suite plus focused old-age, refusal, below-floor, non-dict, two-projection, double-stamp and every guard-branch case. - 25-file touched suite: 1758 passed. Includes `test_summary_delivery`, `test_short_clip_summary_debt`, `test_home_transcribing_hold`, `test_home_transcribing_readers`, `test_record_partial`, `test_sync_failure_reason`, `test_lifecycle_state_table_writers`, `test_lifecycle_invariants`, `test_flag_budget`, `test_config_refactor_w6`, `test_runtime_env_sources`, `test_live_preflight`, `test_batch_pipeline_projection{,_release,_repair}`, `test_batch_held_contract`, `test_enrichment_age_gate`, `test_summary_persistence`, `test_summary_empty_recovery`, `test_conversation_phase`, `test_delivery_outcomes`, `test_conversation_smart_merge`, `test_sync_assignment_contention_retry`, `test_capture_assignment_dedupe` and `test_final_pass_assignment`. - `python3 scripts/check_feature_flag_registry.py`: OK. `python3 scripts/render_feature_flag_registry.py --check-parsers`: OK. `python3 scripts/failure-class validate --base origin/main --head HEAD --pr-body-file .agent-brief/pr-body.md`: OK. `bash scripts/run-release-process-guards.sh`: OK. `python3 backend/config/policy/guard.py`: OK. - `python3 backend/scripts/runtime_image_contracts.py check-source` and `check-third-party`: OK. The age check is local to `summary_delivery` so the batch worker's static source closure does not pull in the testing-only parity module. - `bash scripts/pr-preflight --lane local --base origin/main --head HEAD`: 42 checks passed in 371s. No production account data was read. No deploy, no data migration, no outbox enqueue. ## Rollout and rollback Set `SUMMARY_PROJECTION_DEBT_ENABLED=false` (or `0`/`off`/`no`) to restore the pre-fix projection behavior. Reverting the PR also removes the stamp; existing stamped rows keep their debt and are handled by the normal repair. Rows past the age gate are never stamped, so no new unrepairable debt is created. Failure-Class: new Numbers-waived: no numeric capacity knob changed; the only new number is the existing `deadline_seconds()` deadline applied to the new debt. State-exit-waived: no new pipeline state; the stamp enters the existing `summary_debt:pending` state whose exit is `services/summary_debt_repair.py:tick`.
Git-on-my-level
added a commit
that referenced
this pull request
Nov 11, 2026
…25093) ## Summary Fixes a main flake introduced with #25020's backfill test. The first parametrized case of `test_backfill_cleared_discard_restore_recovers_only_owed_unarmed_debt` imported `database.conversations` and `tests.support.lifecycle_state_table` inside pytest's call phase. The lifecycle state table builds `FIELD_BUILDERS` by scanning source when it loads. On CI runners that one-time import cost exceeded the backend fast-unit 1.00s call-phase CPU guard (observed 1.01 / 1.16 / 1.19 / 1.20s). It failed unrelated PRs #25086 and #25088, for example run 42954652344, shard 8: `1.19s > 1.00s ... [None-still_refused0]`. ## Change Test-only. The imports move into a module-scoped `restore_deps` fixture, which runs in the untimed setup phase. The test body, its assertions, the CPU guard and its limits are unchanged. Nothing is allowlisted. ## Verification - m1, `pytest --durations=4 --durations-min=0 tests/unit/test_backfill_clear_refused_summary_due.py`: 101 passed, 1 skipped. The import cost now appears as `0.66s setup` on the first case; the slowest call phase in the file is 0.03s. Failure-Class: none ## Rollback Revert this commit. 🤖 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/25093?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/25093?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25093&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. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
Retire summary due indexes atomically when donor tombstones, manual title/overview edits or already-enriched merges refuse repair. Preserve
summary_first_pending_at. Undo/manual-field removal and discard restore recover owed debt in the same transaction using original acceptance plus the row's policy deadline, without replacing a non-null due or arming a refused/owned row. Internal debt metadata stays outside reversible user-field receipts.The guarded operator script clears legacy residue using the serving refusal classifier. Unknown provenance is retained for provenance repair; processing, local-only, BYOK and active finalization ownership are explicitly retained even when another refusal has precedence. Both completion metadata and output-present metadata retire copied legacy due. No serving rate, feature flag, deadline, capacity, repair-service or released-client schema changes.
Merge order — required hold
Merge after #25019 and #25032. This PR must not merge before #25032. Both dependency PRs were OPEN when this batch began. After #25019 lands, rebase onto current
origin/main, regenerate inventories and retain both sides' tests; never resolve a shared-file conflict by taking one side wholesale. Repeat exact inventory guards after any overlapping PR lands. #25032 owns its upstream registry/flag-budget train conflicts; this batch does not edit them.Operator run plan — cl2-deploy only
summary_due_atcollection-group index and inspect class/retained/eligible/conflict counts before any apply.--applyadditionally requires--confirm-production-project based-hardwarematching the actual client's project. Review canary counts.The sweep runs two disjoint passes at one cutoff instant: a numeric
summary_due_at <= nowpass, then a Timestampsummary_due_at <= datetime(now, UTC)pass. Each uses(summary_due_at, __name__)pagination, classifier-only projection and batches of at most 400 writes. Every clear retains the original snapshotupdate_timeprecondition, including individual retries after atomic batch failure. Concurrent re-arm/delete is skipped.--limitbounds the combined scanned rows across both passes, including retained rows. Aggregate counts remain available, with scanned/eligible/classes/written/conflicts also reported separately underpasses.numericandpasses.timestamp. Output is counts-only; private cursor files are written to unique same-directorymkstempfiles, explicitly set to mode0600, flushed and fsynced before atomic replacement; any failed attempt removes its temporary file and preserves the previous checkpoint. They include apassmarker plus a numeric or tagged RFC3339 due and document path, with no IDs printed. Cursors are separate for each pass: completing numeric scanning checkpoints{pass: "timestamp", due: null, __name__: null}before the first timestamp query. Resuming a timestamp checkpoint skips the completed numeric pass. Older unmarked cursors infer their pass from the due type. Keep apply/dry-run cursor files separate. This operator-only metadata cleanup is exempt from content-generation batch privacy admission: it never reads transcripts/generated summaries or changes protection levels or content. No production access or operator run was performed in this lane.Follow-up: private atomic checkpoints
Review-desk FIX-FIRST at
f940cf9dd489found that the predictable.tmppath could expose private cursor document paths through a pre-existing permissive file or symlink. Checkpoint publication now uses a unique file in the checkpoint directory, explicit0600, flush/fsync beforeos.replace, and unconditional temporary-file cleanup on failure. Atomic replacement also replaces a final-path symlink without following its target.8159c89608d86c4c67a9bfc5d077e57c7df2f48f.make preflight: 39 checks passed in 64.42s, completed approximately 2026-11-10 17:55Z. Full PR non-test scope: 397 changed lines, within the original 500-line cap. The single authorized checkpoint follow-up push succeeded as a fast-forward, approximately 2026-11-10 17:55:43–17:57:17Z. Its normal hook passed 39 shared checks (67.26s), typecheck with zero errors, 250 passing changed-file tests plus 23 explicit loopback-only skips, and pinned formatting. Exact-head CI is being monitored with a 90-minute deadline.Follow-up: two-pass sweep
Review-desk FIX-FIRST at
50f47f8058fcfound that a numeric cutoff never selects Timestamp-valued due. The backfill now queries both types and keeps the same classifier, fences, dry-run default and counts-only output in each pass. Checkpoints explicitly mark the active pass and survive interruption at the pass boundary.Read-only inspection also confirms the serving query/repair blind spot:
database/summary_debt_queries.py:13,24uses a numeric cutoff/cursor;services/summary_debt_repair.py:50rejects nonnumeric due and its overdue-age arithmetic assumes a number. Those files are unchanged, as requested; cl2-fixnow should route that finding to #25019's owner.focused-results-followup-m1.jsonin the supplied task directory.f940cf9dd4898798c72e854c0dd5226554b76866.make preflight: 39 checks passed in 46.50s, 2026-11-10 approximately 17:15–17:16Z. Full PR scope: 388 non-test changed lines, within the 500-line cap.Verification of the preceding batch
Verification is hermetic code and synthetic loopback Firestore evidence, not deployed-runtime evidence. Commands use
/Users/david/workspace/omi-workspace/bin/omi-heavy run --and the worktree's Python 3.11, with GCP credential environment scrubbed. Pytest files run in isolated processes under the backend unit contract./Volumes/scratch/cl2-fixnow-move25020/focused-results-m1.json.make preflighton commit50f47f8058fcb904bb5bd185184c1473284783cc: 39 checks passed in 55.79s, 2026-11-10 approximately 16:17–16:18Z. The full PR has 354 non-test changed lines (342 additions / 12 deletions), below 500.50f47f8058fcb904bb5bd185184c1473284783ccpassed all 39 shared checks, typecheck with zero errors, 203 passing changed-file tests plus 22 explicit loopback-only skips, and pinned formatting for all 15 PR Python files (2026-11-10 16:18:28–16:19:46Z). The single fast-forward push succeeded with no bypass.UI-Evidence: none — backend metadata and an operator script only.
Finding dispositions
tempfile.mkstemp, enforce0600viafchmod, write/flush/fsync, thenos.replace. Cleanup runs on failure, leaving the previous checkpoint intact. Regressions cover the old predictable symlink/permissive file, permissive umask, write/fsync/replace/fchmod failures, descriptor closure and safe replacement of a final-path symlink.DURABLE_REFUSALSand durable test cases. Regression retains the legacy due and first-pending anchor. Missing provenance still needs its owning repair; this batch never clears it.first_summary_policydeadline, falling back todeadline_seconds(). Refused rows and already-armed rows never acquire a replacement due. Real codec, strict transaction and loopback emulator coverage.summary_blocked_reason=blocked_byok, including a competing deleted flag and no active job. Existing finalization BYOK exclusion remains. No terminal-BYOK policy expansion.summary_output_present=Truetake the enriched return and retire due. Empty reprocessing preserves banked structured content without requiring a completion stamp.DURABLE_REFUSALSnow documents current-obligation retirement rather than permanent lifecycle finality.--applyonbased-hardwarerequires matching--confirm-production-project based-hardware; an unknown project fails closed. Synthetic unit coverage only; no operator apply was run.summary_first_pending_at, current owed rows only.summary_due_atCOLLECTION_GROUP single-field index; cl2-deploy must verify the deployed index with the serving-revision dry-run before canary. No production query in this lane.Rollback
A code revert does not restore rows whose due indexes the backfill already cleared. Preserve the operator receipts/cursors and stop the sweep. A separately authorized repair must enumerate/re-stamp keyed on the preserved
summary_first_pending_at; only rows the current classifier calls owed, with no competing owner and a null/missing due, may receivesummary_first_pending_at + stored first_summary_policy deadline(ordeadline_seconds()without a snapshot). Never reset the anchor, move a non-null due, or blindly re-arm refused rows. Do not use the due index itself to find already-cleared rows.Failure-Class: FC-obligation-outlives-terminal-owner
Line-Count-Exception: backend/database/conversations.py | 4960 -> 4969 | Keep atomic due retirement and guarded discard-restore re-arm at their owning writes.
Line-Count-Exception: backend/utils/sync/assignment.py | 1538 -> 1539 | Keep atomic summary-debt retirement at the donor redirect write.