Skip to content

fix(summary): prioritize expiring debt, then newest repairs - #25019

Merged
Git-on-my-level merged 14 commits into
mainfrom
fix/summary-debt-newest-first
Nov 10, 2026
Merged

Git-on-my-level merged 14 commits into
mainfrom
fix/summary-debt-newest-first

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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-bounded-discovery-pinned-by-blocked-page

Failure mechanism: repair order: oldest-first starves user-visible debt.
Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Apply lead2 ruling 8b9c8f on the scheduled integration owner only; retain the code default and the declared rollback at ten.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Keep the approved integration spend cap out of staging while preserving strict parity for every shared ops key.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Apply d233ac and 215fdc: admission default eight, scan default 100 with a 5000 maximum, queries capped at 500, and a scan-work deadline. Preserve phase priority, owner deferrals and fetched tails across chunked cursor walks.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Integrate the reviewed held-input retention fix before the fast-forward PR update.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Git-on-my-level and others added 4 commits November 10, 2026 14:18
Keep due/name ordering and the flat cursor when the age gate is disabled, including due rows without pending metadata. Use their existing due time for repair admission in that mode and pin the query and cursor behavior in fake-client and Firestore regressions.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Register the due-only start_after map restored for disabled-age-gate repair, retaining the strict lifecycle payload inventory check.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
The default admission cap is 8, so the worst-case default budget is
100 + 1 + 1 + 8 x 8 = 166 reads per winning tick (119,520/day), not 182.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep owner-deferred conversations as due debt for later passes and wraps while persisting scan continuation across ticks. Preserve unexamined tails at admission and deadline stops and keep the existing cursor schema.

Failure-Class: FC-bounded-discovery-pinned-by-blocked-page
@Git-on-my-level
Git-on-my-level merged commit 720f078 into main Nov 10, 2026
67 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/summary-debt-newest-first branch November 10, 2026 17:44
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
)

## 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

1. Deploy the merged code first, then identify the exact serving
revision. Old writer sites keep re-arming due during the sweep, so a
pre-deploy sweep or dry-run is insufficient.
2. Re-run a fresh dry-run **after deployment on that serving revision**.
Verify the deployed `summary_due_at` collection-group index and inspect
class/retained/eligible/conflict counts before any apply.
3. Run a bounded **5,000 scanned-row canary**, using an apply cursor
separate from the dry-run cursor. Production `--apply` additionally
requires `--confirm-production-project based-hardware` matching the
actual client's project. Review canary counts.
4. Run the full sweep **only on lead2's go**. Re-run the
serving-revision dry-run after any intervening code deployment; restart
without a cursor to reconsider conflicts as needed.

The sweep runs **two disjoint passes** at one cutoff instant: a numeric
`summary_due_at <= now` pass, then a Timestamp `summary_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 snapshot `update_time`
precondition, including individual retries after atomic batch failure.
Concurrent re-arm/delete is skipped. `--limit` bounds the combined
scanned rows across both passes, including retained rows. Aggregate
counts remain available, with scanned/eligible/classes/written/conflicts
also reported separately under `passes.numeric` and `passes.timestamp`.
Output is counts-only; private cursor files are written to unique
same-directory `mkstemp` files, explicitly set to mode `0600`, flushed
and fsynced before atomic replacement; any failed attempt removes its
temporary file and preserves the previous checkpoint. They include a
`pass` marker 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 `f940cf9dd489` found that the predictable
`.tmp` path 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, explicit `0600`, flush/fsync
before `os.replace`, and unconditional temporary-file cleanup on
failure. Atomic replacement also replaces a final-path symlink without
following its target.

- Backfill suite through omi-heavy: **101 passed / 1 existing
loopback-only skip**, 1.33s, completed approximately 2026-11-10 17:51Z.
All eight new filesystem/security cases passed. This follow-up changes
only the backfill script and its test file; no operator --apply or
production access.
- Checkpoint follow-up head: `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 `50f47f8058fc` found 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,24` uses a numeric cutoff/cursor;
`services/summary_debt_repair.py:50` rejects 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 selection re-run through omi-heavy, 2026-11-10 approximately
17:12Z: **2,209 passed / 23 skipped / 86 xfailed**. Adjacent **117
passed**; extra chat/tool/strict transaction selection **55 passed**.
Per-file commands, exact timestamps and results:
`focused-results-followup-m1.json` in the supplied task directory.
- Backfill tests against synthetic loopback Firestore: **94 passed**,
receipt completed 2026-11-10T17:12:06.668829+00:00. Includes actual
mixed-type inequality behavior, refused clears, owed/future retention,
shared limits, both cursor types, interruption at the pass boundary and
bounded/fenced writes. Emulator shut down normally.
- Follow-up at earlier head `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.
- Only the backfill script and its test file changed in this follow-up.
Serving query and repair files remain untouched. The single follow-up
fast-forward push succeeded on 2026-11-10 approximately
17:16:32–17:17:52Z. Its normal hook passed 39 shared checks (57.04s),
typecheck with zero errors, 242 passing changed-file tests plus 23
explicit loopback-only skips, and pinned formatting. CI is being
monitored on this exact head with a 90-minute deadline.


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

- Requested focused selection on this batch: **2,170 passed, 22 skipped
(loopback tests run separately), 86 xfailed**, 2026-11-10
16:14:30–16:15:06Z. The old ae48104 selection measured 2,087/4/86; new
guards add passing cases and the new emulator cases increase the
explicit loopback-only skips.
- Adjacent selection: **117 passed**, 16:15:06–16:15:13Z; additional
chat/tool/strict People transaction selection: **55 passed**,
16:15:13–16:15:18Z. Exact per-file commands, timestamps and logs:
`/Volumes/scratch/cl2-fixnow-move25020/focused-results-m1.json`.
- Synthetic loopback Firestore: **22 chat edit/undo tests passed** and
**31 People-generation emulator checks passed**, 2026-11-10
approximately 16:13–16:14Z. Emulator stopped. Used the installed Java 21
in the process environment only.
- `make preflight` on commit `50f47f8058fcb904bb5bd185184c1473284783cc`:
**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.
- Regenerated the lifecycle payload inventory for changed owners and all
People fingerprints (only the four already-audited chat scopes differ);
People generator check reports no delta. Exact lifecycle
inventory/state-table guard is included above; serving lifecycle write
guard passed in preflight. Normal pre-push on
`50f47f8058fcb904bb5bd185184c1473284783cc` passed 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

| Finding (review sources) | Disposition in this batch |
|---|---|
| Predictable checkpoint temp path can follow a symlink or reuse
permissive permissions (review-desk 72a878, FIX-FIRST) | Use exclusive
unique same-directory `tempfile.mkstemp`, enforce `0600` via `fchmod`,
write/flush/fsync, then `os.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. |
| Numeric-only cutoff misses timestamp-valued due (review-desk e7b7dc,
FIX-FIRST) | Replaced with numeric and Timestamp passes, distinct
pass-aware checkpoints and per-pass counts. Tests cover
refused/owed/future rows in both types, shared limits, resumable pass
boundary, update-time conflicts and 400-write caps. A loopback Firestore
regression verifies actual mixed-type query behavior. |
| Unknown provenance retired as durable; #25032 late projection stranded
(pd correctness/custody/tests/merge/Kimi) | Removed from
`DURABLE_REFUSALS` and durable test cases. Regression retains the legacy
due and first-pending anchor. Missing provenance still needs its owning
repair; this batch never clears it. |
| Manual undo loses owed debt (all correctness/custody/test reviews, old
merge/CI) | Chat restore and explicit null/DELETE_FIELD removals re-arm
atomically from preserved first pending plus the stored
`first_summary_policy` deadline, falling back to `deadline_seconds()`.
Refused rows and already-armed rows never acquire a replacement due.
Real codec, strict transaction and loopback emulator coverage. |
| Every other manual removal path needs coverage (sdclear-fix1) | Title
UI and offline empty titles remain non-null manual values, covered by
retirement tests. Chat tools reject blank title/overview edits before
IO. Sync restore and generated persistence preserve manual fields. All
actual removal writers are declared in the lifecycle inventory. |
| Summary BYOK reason not excluded; terminal BYOK semantics untested (pd
correctness/custody/tests) | Explicitly retain
`summary_blocked_reason=blocked_byok`, including a competing deleted
flag and no active job. Existing finalization BYOK exclusion remains. No
terminal-BYOK policy expansion. |
| Detached queued/leased finalization rows (pd correctness) | Explicitly
retain both statuses even without a job ID, including competing
manual/discard flags. Re-arm also respects these owners. |
| Output-present enriched row can retain copied due (pd custody) | Both
completion metadata and `summary_output_present=True` take the enriched
return and retire due. Empty reprocessing preserves banked structured
content without requiring a completion stamp. |
| Discarded rows recoverable after sweep (pd correctness/tests) | The
existing restore transaction re-arms only currently owed, unarmed rows
from original acceptance and policy. Tests cover cleared legacy rows
without receipts, manual/enriched/locked refusal, existing due and
writer ownership. |
| Refusal classes can later reopen (pd correctness/custody) | Manual and
discard inverses now recover debt. Empty-output revision re-arm stays
intact and is covered by the adjacent recovery suite.
Privacy/content-floor decisions remain governed by their existing
policy; this metadata cleanup does not introduce a new privacy/content
transition. `DURABLE_REFUSALS` now documents current-obligation
retirement rather than permanent lifecycle finality. |
| Backfill bypasses batch privacy fence (pd custody) | Documented
metadata-only operator exemption: no transcript or generated summary is
read or written; only the due index is cleared with a snapshot
update-time fence. Serving content-generation fences remain unchanged. |
| Non-JSON due checkpoint (pd custody) | Timestamp cursors use private
tagged RFC3339 values and decode on resume, preserving Firestore
timestamp type and nanoseconds. Numeric cursor format remains supported.
|
| No explicit prod apply guard (pd custody) | `--apply` on
`based-hardware` requires matching `--confirm-production-project
based-hardware`; an unknown project fails closed. Synthetic unit
coverage only; no operator apply was run. |
| CLI failure path / deleted cursor not tested (pd tests) | Added
counts-only CLI error regression and resume after a deleted numeric
cursor; timestamp cursor also resumes after a missing cursor document. |
| Unchanged-title path lacks assertion (pd tests nit) | Added
no-write/no-due-move assertion for an unchanged offline title. |
| Legacy exact title assertion fails CI (old CI/merge) | Already
corrected at ae48104; retained and re-run the full revision-contract
file. |
| Update-time fence, dry-run, bounded cursor, counts-only output (all
reviews) | Preserved; original race, atomic-batch, tie/resume,
scanned-row limit, batch-size and privacy tests remain intact. |
| Deploy must precede sweep (old merge, sdclear-fix1) | Run plan below
requires code serving first and a fresh post-deploy dry-run on that
exact serving revision before the 5k canary. Old writers would keep
re-arming due during a sweep. |
| Code revert cannot restore cleared rows (pd merge, old custody) |
Rollback explicitly requires a separately authorized re-stamp keyed on
preserved `summary_first_pending_at`, current owed rows only. |
| #25019 / #25032 ordering and same-file inventories (pd merge, old
merge, sdclear-fix1) | Must merge after both, never before #25032. Both
were OPEN at intake; no premature rebase. After #25019 lands, rebase and
regenerate inventories, preserving both sides and tests rather than
taking a side wholesale. |
| Upstream #25032 registry / #25034 flag-budget conflicts (pd merge) |
Dependency-owner work outside this batch. The merge train must resolve
those before #25020; no workflow/flag-budget edits here. |
| #25018 / #24866 / #24801 / #24897 / stale #24607 overlaps (old and pd
merge) | Re-fetch before integration; if these land first, rebase and
re-run exact inventories and both branches' tests. No unrelated PR
changes or merges performed here. |
| Operator query excluded from serving-query inventory (pd merge) |
Preserve script scope. Uses the existing `summary_due_at`
COLLECTION_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. |
| People audit and lifecycle inventories after shared-scope changes (all
test reviews) | Regenerated reviewed entries and four existing People
fingerprints after strict transaction and loopback emulator proof;
exact-match guards re-run. |

## 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 receive `summary_first_pending_at + stored first_summary_policy
deadline` (or `deadline_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.
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