Skip to content

fix(sync): drain expired backlog and coalesce sync enrichment - #21679

Merged
Git-on-my-level merged 13 commits into
mainfrom
lane/backlog-drain-train1
Oct 15, 2026
Merged

Git-on-my-level merged 13 commits into
mainfrom
lane/backlog-drain-train1

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Durable backfill entries can outlive their 24-hour Redis job. The sequencer currently makes each expired head wait for a full Cloud Tasks dispatch before dropping it, serially blocking executable work for that UID. A production metadata investigation correlated a six-day-old entry to a 146-second empty turn and measured thousands of expired dispatches.

Retire Redis-absent heads before dispatch: raw EXISTS, a per-job compare-delete lock, a second EXISTS under that lock, then a Firestore transaction checking the exact pending/owner and unbound ledger claim. A competing retirement lock leaves the head unclaimed; the transactional reservation must match the head whose Redis key was inspected, so a newly inserted or replaced head cannot bypass its own proof. Release only the matching unbound processing claim to retryable; preserve live keys, held locks, running/bound/completed work and newer claims. Redis errors fail closed. Bound ordinary kicks to 50 retirements and scheduler kicks to one pending retirement per UID. Budget exhaustion and an expected-head race schedule one deduplicated future wake when an unowned pending head remains; empty queues, held locks and refused retirements never wake. Refused absent heads remain pending and unreserved. Sweep summary includes pending retirements. Proactively retire Redis-absent dispatching owners under the same fences. Emit sync_backfill_expired_retired_total and a content-free structured event separately from completed transcriptions.

SYNC_BACKFILL_RETIRE_EXPIRED_AT_CLAIM defaults false in code/dev and true in the prod sync/worker manifest. Existing action worker revision and service caps become 40 (concurrency 6, 8 GiB retained); both queue create/update branches become 90 concurrent / 15 dispatches per second. This is the first Train 1 step, not the later 200/25 target. Update capacity/retirement runbooks and the feature-flag registry.

Current Flutter and macOS WAL clients retain .uploaded audio after HTTP 202; completion gates normal cleanup and expired jobs trigger re-upload from retained files. This source contract does not prove what remains on a particular user's device. Retirement deletes no audio/conversation, performs no provider call and is not transcription success.

Validation:

  • backend/test.sh: 250 passed across six focused sync/Cloud Tasks/ledger/stage/capacity/corrupt-job files; 165 runtime-validator tests passed after completing the new flag in dev drift fixtures; seven required Firestore guard files passed separately through the same runner.
  • Real loopback Firestore emulator: 11 passed, including candidate identity fencing, atomic retirement, bound/completed/newer-claim protection and a worker-begin race.
  • Pyright: 0 errors. OMI_PR_BODY_FILE=/tmp/backlog-pr-body.md make preflight: all 42 checks passed, including manifest composition, feature registry, Firestore guards and runtime/deployment contracts.

Rollout gates: release and verify worker capacity first, then hold 90/15 at least 15 minutes. Keep one active job per UID and GPU/final-pass admission unchanged. Require durable-completion improvement, <10% comparable pipeline/live-STT latency regression, live STT p95 <3s, no GPU OOM/fatal or sustained Cloud Run capacity 429/5xx, no Firestore resource exhaustion/persistence contention, and observable Redis CPU/memory/latency with no eviction/rejected connections. Unknown Redis health blocks later ramp steps. Watch retired entries, expired dispatches, dead letters, oldest waiting age and client re-uploads separately from successful content completions. Ownership overlap or nonterminal ACK stops the ramp.

Rollback queue first to 60/10, leave expanded workers until in-flight requests drain, then restore both worker caps to 18. Set the retirement flag false on both prod sync services to restore the original claim path. Retired metadata is not recreated by rollback; retained WALs follow existing 404 recovery. Later 135/20 → 180/25 → 200/25 operator steps require the same gates and a follow-up config train. No production mutation, merge or deployment was performed for this PR.

Failure-Class: new

Invariant: INV-MEM-4 — canonical Long-term promotion authority is unchanged; retirement only releases exact sync-processing claims and does not promote or mutate memory records.

Train 1: settle sync enrichment and reuse exact successful inputs

Sync appends currently regenerate whole-conversation notes and L1 per job. The added default-off coalescer creates one durable per-conversation obligation and processes the latest transcript after a trailing 600-second quiet window. Re-marks extend that window without one task per append; named task generations, a CAS lease and the existing bounded sweep recover enqueue/worker crashes. Recovery retains the original queue, worker and OIDC identity, including backfill ownership. Explicit Process Now remains immediate.

Notes/L1 reuse only exact successful effective-input fingerprints, including language, capture dates, rendered context, schemas/dependency versions and enabled L1 owner-adjudication context. Notes bind the fingerprint to matching persisted output through the existing revision fence. L1 stamps only after successful canonical source replacement and refuses newer/deleted transcripts. Rollback invalidates old checkpoints; failed feature runs never stamp success. Counters: sync_reprocess_coalesced_total and conversation_llm_input_dedupe_skipped_total{feature}.

The production Train 1 manifest enables SYNC_REPROCESS_COALESCE_ENABLED=true, SYNC_REPROCESS_SETTLE_SECONDS=600, and CONVERSATION_LLM_INPUT_DEDUPE_ENABLED=true only on backend-sync/backend-sync-backfill. Code defaults and dev stay off. This is candidate source/config; no deployment or production write was performed. Flag rollback restores immediate future append processing/full model calls while retained outbox obligations drain on the new binary; drain the new task kind before reverting to an older binary.

Combined-head local verification: 1,078 passed across 23 selected files via backend/test.sh, including 24 new coalescing/hash/rollout cases; 17 real loopback Firestore emulator/HTTP cases (six coalescing, eleven retirement); 307 hermetic pre-deploy cases. The real worker router runs over loopback with fake OIDC/provider leaves; it checks403/400, one pass over settled appends, stale replay, and a later second pass. No deployed-dev or real-model quality acceptance is claimed. Scoped Python3.11 Pyright: 0 errors, 318 warnings over six changed production files (warning delta not measured). All 44 required preflight checks and normal push gates passed on the published head, including full backend Pyright (0 errors), runtime validation, units, OpenAPI and formatting. Hosted CI is separate and was running at publication.

For N eligible per-job passes in a quiet window, primary notes/L1 calls become 1 instead of N (80% fewer for 5,90% for 10). This is a mechanism expectation, not measured fleet savings; the request/first-completion populations do not join.

Coalescing commits on this branch: aad53a66bca2, f715c282751e, 65c37ffa7177, ab2f299a7e92, bf8a3d54b5bf, b5e950c8cb14. This stays in the same Train 1 PR and excludes the unrelated provider-metrics history.

Invariant: INV-TASK-2 — notes still propose through the existing capture boundary; no task writer or automatic promotion is added. INV-MEM-4 remains unchanged.

Line-Count-Exception: backend/routers/sync.py | 2714 -> 2746 | Keep authenticated worker routing and sweep orchestration at their existing boundary; durable state and dispatch live in the new reprocess module.
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3474 -> 3554 | Capture exact inputs at existing notes/L1 boundaries and commit successful checkpoints through the revision-fenced writer; hashing lives in a new module.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3217 -> 3234 | Preserve retry/fence and Process Now policy at the reprocess boundary while the new outbox owns scheduling and leases.

CI follow-up and Grok round 2 lows

L1 checkpoint reads, successful stamps and flag-off invalidation now use the Firestore client already injected into canonical extraction. This preserves revision fences and rollback invalidation without resolving ADC from a second global client. The hermetic network guard remains unchanged. The two upstream-boundary cases pass, with explicit flag-on/off injection regression coverage.

The notes/L1 implementation fingerprints now include model_config, model_constants, clients and providers route modules. Changes to any of these invalidate both feature checkpoints. Outbox repair errors are reported as reprocess_repair_errors, separately from sequencer retirement errors; successful retirement returns HTTP 200 even if optional repair fails, including query exceptions. Sequencer errors still return HTTP 500.

Local follow-up: the exact 305-file hosted shard list passed via backend/test.sh (5,888 tests), plus 110 focused tests and 17 Firestore/HTTP emulator tests. Scoped Python3.11 Pyright: 0 errors. The production fix also has direct injected-client regression tests; extractor-only fixture stubs from the shared branch are retained.

Failure-Class: FC-durable-queue-outlives-executable-work
Failure-Class: FC-durable-queue-outlives-executable-work
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T13:36:19.767293Z 91de80d New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86f5d1f20a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +55 to +57
retired = registry.retire_expired(uid, job_id, epoch=epoch)
finally:
release_job_run_lock(job_id, token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Delete the retired job's epoch counter

When a fence-aware worker acquires a sync-job lock and then dies before binding the ledger, sync_job_lock_epoch:<job_id> remains while the claim is still eligible for this retirement path. After the Redis job expires, retirement succeeds but only releases the generic run lock; the epoch counter is never removed even though delete_sync_job_run_lock_epoch() documents that these counters have no TTL and normal retired-claim paths clean them up. Repeated failures of this kind therefore leave permanent Redis keys and can grow Redis memory without bound; clean up the epoch counter after the Firestore retirement succeeds.

Useful? React with 👍 / 👎.

Failure-Class: FC-durable-queue-outlives-executable-work
@Git-on-my-level Git-on-my-level changed the title fix(sync): retire expired backfill heads before dispatch fix(sync): drain expired backlog and coalesce sync enrichment Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 878a7f56db

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +69 to +72
'event=sync_backfill_expired_retired source=%s outcome=retired job_id=%s uid=%s',
source,
job_id,
uid,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Hash the UID in retirement logs

Whenever an expired entry is retired in production, this log writes the raw Firebase UID into both the formatted message and the structured json_fields, exposing a persistent user identifier to the logging pipeline. Use the existing backfill_cutover.uid_hash(uid) pattern used by the other sequencer events, or pass the value through the required PII sanitizer, rather than emitting uid directly.

AGENTS.md reference: backend/AGENTS.md:L77-L77

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Coalescing/exact-input dedupe is pushed into this shared Train 1 PR at b5e950c8cb1468894b9a8c824b837c2ed0e4a6ec, rebased onto backlog commit 878a7f56db6d4.

Validation: 1,078 selected unit tests and 17 loopback Firestore/HTTP emulator tests via backend/test.sh; 307 hermetic deployment-contract cases; all 44 exact-head preflight checks and normal push gates passed, including full backend type check with zero errors. SSH keepalives were needed during the long hook; no checks were bypassed. Hosted CI was still running at publication.

The combined body retains the latest backlog description and lists the six coalescing commits, counters, Train 1-only production manifest controls and flag rollback. Code/dev defaults stay off. No merge, deployment or production data access was performed. The durable local handoff is data/run-2026-10-13-two-lane-nemotron/sol-reprocess-coalesce.md.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b5e950c8cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/sync.py
@router.post('/v2/sync-backfill-sequencer/sweep', include_in_schema=False)
async def sweep_sync_backfill_sequencer(_retry_count: int = Depends(verify_cloud_tasks_oidc)):
outcomes = await run_blocking(db_executor, uid_sequencer.sweep)
from utils.sync import reprocess

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new runtime imports to module scope

Move this import, the imports in _run_sync_reprocess, and the other newly added function-scoped imports in process_conversation.py and pipeline.py to module scope. Loading these dependencies only when a scheduler or worker request arrives bypasses startup import validation and can defer dependency or cycle failures to production traffic; the backend guide explicitly requires every import to be declared at module scope.

AGENTS.md reference: backend/AGENTS.md:L161-L163

Useful? React with 👍 / 👎.

limit = max(1, min(100, limit))
client = get_firestore_client()
# One range/order field uses the automatic single-field index.
snapshots = client.collection(COLLECTION).where('due_at', '<=', current).order_by('due_at').limit(limit).stream()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Advance past the first repair page

When at least 100 overdue obligations remain in the collection—such as scheduled tasks waiting behind queue capacity or rows whose saved dispatch binding now fails—this query returns the same oldest page on every sweep because neither successful duplicate enqueue nor enqueue failure advances due_at. A crash-before-enqueue obligation with a later due time is therefore never inspected until every earlier row disappears, and permanently invalid rows can starve it indefinitely. Track a separate next-repair timestamp, paginate beyond already-attempted rows, or otherwise defer each inspected row so the bounded sweep eventually reaches the whole overdue set.

Useful? React with 👍 / 👎.

Comment on lines +62 to +84
paths = [
'conversations/process_conversation.py',
'conversations/owner_jev.py',
'llm/jev_client.py',
'../config/jev_decisions.py',
'llm/conversation_prompt_context.py',
'llm/memories.py',
'llm/working_observations.py',
'llm/conversation_processing.py',
'llm/conversation_notes_prompts.py',
'llm/conversation_title_people.py',
'llm/meeting_notes_rich_prompts.py',
'llm/meeting_notes_presentation.py',
'llm/meeting_notes_validation.py',
'memory/belief_model.py',
'memory/rejected_memory_feedback.py',
'prompts.py',
'../models/structured.py',
'../models/structured_extraction.py',
'../models/memory_contracts.py',
'../models/conversation.py',
'../models/memories.py',
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include the resolved model route in dedupe hashes

The implementation digest omits llm/model_config.py, llm/model_constants.py, and the resolved model/provider itself. Consequently, changing MODEL_QOS or deploying a model-route/model-ID update without modifying one of these listed files leaves an existing notes or L1 fingerprint valid, so a later exact replay skips the newly configured model and keeps output generated by the previous route. Include the resolved feature route and relevant generation options in the fingerprint, or include every model-routing source in the implementation digest.

Useful? React with 👍 / 👎.

Stub the newly added L1 checkpoint persistence boundary in two extractor contract tests. Keep hermetic network blocking and production checkpoint behavior unchanged.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4ed300dd74

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

conversation.id,
replacement_payloads,
)
llm_input_dedupe.l1_succeeded(uid, conversation, l1_digest, db_client=db_client)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Checkpoint L1 only after completing required side effects

When extraction produces memories and record_usage fails—or the worker terminates before reaching it—the hash written here survives even though the enrichment attempt fails. The exact-input retry then returns early from l1_input as a cache hit, so the non-idempotent memories_created usage update is never retried and the task eventually reports success with permanently undercounted usage. Make the remaining side effects independently idempotent and complete them before stamping the success hash, or track their completion separately.

Useful? React with 👍 / 👎.

Comment thread backend/routers/sync.py
Comment on lines +1831 to 1832
outcomes['reprocess_repair_errors'] = repair['error']
return JSONResponse(status_code=500 if outcomes.get('error') else 200, content={'outcomes': outcomes})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Fail or alert when outbox repair fails

In the production sync-backfill-uid-sequencer Scheduler path, a failed reprocess query or any number of per-row enqueue failures only populate reprocess_repair_errors; the response still returns 200 whenever the unrelated UID sweep succeeded. The configured Scheduler-failure alert therefore remains green, and the UID sweep emits its normal heartbeat before this repair runs, so a persistent Firestore or Cloud Tasks failure can strand durable enrichment obligations indefinitely without either existing alert firing. Include repair errors in the HTTP failure decision or provision a separate alert for this counter.

Useful? React with 👍 / 👎.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Production CI fix is published at 4ed300dd74821335ee6fd352b20596f3ad776556: L1 checkpoints now use the existing injected Firestore client, including flag-off invalidation; the hermetic network guard is unchanged. Both Grok lows are fixed. Exact original shard replay: 305 files / 5,888 passed; focused checks: 110 passed; emulator: 17 passed; all normal local push gates passed. The fixture-only commit 84e1e2b6c8c81 is preserved.

GitHub suppressed PR unit workflows because the branch now conflicts with main in one documentation file: both branches appended sections to backend/docs/listen_pusher_pipeline.mdx. A separate documentation-only commit 91de80d02f7d0 preserves both assignment and retirement sections and combines cleanly with main 550388f62f1b8 (git merge-tree exit 0). Its normal push gate is running. No merge commit, PR merge, force push or deployment. I will wait for hosted CI on the final head and record it in sol-reprocess-coalesce.md.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

CI follow-up complete on 91de80d02f7d01ebaad2f0a6faac077fef8c6562, remote/PR/workflow SHA verified at 13:41:57 UTC.

Backend Unit Tests run38743225934 passed every shard, guardrails and the aggregate unit suite; previously failing shard5/6 is SUCCESS. PR rollup: 35 success,22 skipped,0 failed/pending/cancelled. Emulator proofs, hermetic E2E, metadata and hygiene are green too.

4ed300dd7482 fixes the production injected-client seam and both Grok lows; 91de80d02f7d resolves the runbook append conflict so PR CI can run. The network guard is unchanged. The exact original305-file shard passed locally with5,888 tests before the peer extractor-fixture stubs; focused110 and emulator17 also passed. Every normal push gate passed.

The full head/CI receipt and rollout/rollback handoff are recorded in data/run-2026-10-13-two-lane-nemotron/sol-reprocess-coalesce.md and coalesce-evidence/round2/. PR remains open; no merge or deployment.

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