Repository navigation
fix(sync): retain expired obligations in durable redrive custody (dark) - #22063
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9620b94b34
ℹ️ 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".
| if not job and redrive_policy.enabled(): | ||
| custody = await run_blocking(db_executor, sync_redrive.preserve_missing_job, uid, job_id, payload) | ||
| # ACK only after durable custody. Neither branch deletes staged | ||
| # bytes or releases a partial ledger claim to blind provider retry. | ||
| return JSONResponse(status_code=200, content={'status': custody}) |
There was a problem hiding this comment.
Release the backfill slot before acknowledging custody
When the guard handles an expired backfill job, this early return bypasses the release_backfill_slot call in the existing missing-job branch below. This also happens when preserve_missing_job returns completed, where there is no unresolved custody that could justify retaining the slot; because the per-UID slot has a two-day TTL, subsequent backfill uploads for that user can be rejected until it expires. Release the matching slot before returning for backfill payloads.
AGENTS.md reference: backend/AGENTS.md:L145-L145
Useful? React with 👍 / 👎.
| if sync_redrive.enabled(): | ||
| sync_redrive.refresh_metrics() |
There was a problem hiding this comment.
Isolate metric refresh failures from the sequencer sweep
When durable redrive is enabled, any exception while reading or decoding the new stats document escapes before the guarded due_owners and due_pending processing begins. A transient Firestore read failure or malformed aggregate therefore aborts the entire scheduler tick and prevents unrelated UID reconciliation, even though this read only updates gauges. Catch and record refresh failures so the sweep can continue.
Useful? React with 👍 / 👎.
| def retain(transaction: Any, prepared: dict) -> None: | ||
| """Write the handoff atomically with caller's scheduling changes.""" | ||
| if not prepared['existing']: | ||
| transaction.set(prepared['ref'], prepared['row']) |
There was a problem hiding this comment.
Purge custody records during account deletion
Each custody row stores the UID and complete accepted payload in a new top-level collection, but the account-deletion implementation in database/user_data_deletion.py:10-33 only purges registered top-level batch stores and the users/{uid} subtree, and no deletion path references sync_redrive_required. Consequently, any user who enters custody and later deletes their account retains this data indefinitely; a missing-job delivery can also create such a row before the later account-cutover check. Add this collection to the fenced account wipe and prevent custody writes after deletion begins.
Useful? React with 👍 / 👎.
| elif redrive_policy.legacy_convergence_enabled(): | ||
| converged = await run_blocking( | ||
| db_executor, | ||
| sync_redrive.converge_legacy_completion, |
There was a problem hiding this comment.
Converge legacy success on the final task attempt
The new legacy convergence runs only before provider work. If the pipeline durably marks the content ledger completed and then throws before updating Redis on the final Cloud Tasks delivery, the exception path at routers/sync.py:2371-2420 still attempts convergence only when ledger_fence_active and otherwise publishes failed_final. There is no subsequent retry to reach this new branch, so a proven legacy success is exposed as a failed job. Invoke the legacy convergence helper in the final-attempt exception path as well.
Useful? React with 👍 / 👎.
|
|
||
| from database._client import get_firestore_client | ||
| from database.sync_ledger import is_valid_completed_sync_content_result, sync_content_reference | ||
| from utils.sync.redrive_policy import enabled as enabled, legacy_convergence_enabled as legacy_convergence_enabled |
There was a problem hiding this comment.
Keep database dependencies below the utils layer
database.sync_redrive now imports its rollout policy from utils.sync, reversing the backend's required dependency hierarchy and making this persistence module vulnerable to circular initialization as utils code imports database helpers. Move the pure flag policy into a lower-level configuration/database module rather than introducing a database-to-utils dependency.
AGENTS.md reference: backend/AGENTS.md:L163-L169
Useful? React with 👍 / 👎.
| """ | ||
| if not content_id or run_lock_token is None: | ||
| return None | ||
| from database.sync_jobs import fenced_finalize_sync_job_from_durable_ledger |
There was a problem hiding this comment.
Move the sync-jobs import to module scope
This function-local import violates the backend's explicit requirement that all imports remain at module scope. database.sync_jobs does not depend on this new module, so the finalizer can be imported normally at the top of the file without needing a deferred import.
AGENTS.md reference: backend/AGENTS.md:L161-L163
Useful? React with 👍 / 👎.
| claim = sync_content_reference(client, uid, content_id).get(transaction=transaction).to_dict() or {} | ||
| if claim.get('status') == 'completed' and is_valid_completed_sync_content_result(claim.get('result')): | ||
| return 'completed' | ||
| prepared = prepare(transaction, client, uid, job_id, payload, datetime.now(timezone.utc)) |
There was a problem hiding this comment.
Preserve the original admission time for missing jobs
The missing-job path passes the current time as accepted_at, even though every durable task payload already carries its original numeric enqueued_at. For a task discovered after its 24-hour Redis expiry, this moves the fallback attention deadline forward by roughly a day, so sync_redrive_nearest_deadline_timestamp_seconds can report remaining time after the staged source has already expired. Convert the validated enqueued_at value to UTC and use it here, falling back to now only when it is absent or invalid.
Useful? React with 👍 / 👎.
| transaction.set(prepared['ref'], prepared['row']) | ||
| transaction.set(prepared['stats_ref'], prepared['stats']) |
There was a problem hiding this comment.
Shard the global custody counter
Every newly retained obligation updates the same sync_redrive_stats/backlog document inside its custody transaction. Concurrent missing-job deliveries or scheduler instances therefore serialize unrelated UIDs on one Firestore document; transaction conflicts and retry exhaustion can prevent custody from committing and leave tasks or sequencer heads stuck precisely during a large expiry backlog. Use sharded aggregates or otherwise remove the global document write from each custody-transfer transaction.
Useful? React with 👍 / 👎.
…d-20261018 # Conflicts: # config/feature-flags.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6355f261ef
ℹ️ 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".
| if sync_redrive.enabled(): | ||
| sync_redrive.refresh_metrics() |
There was a problem hiding this comment.
Refresh custody gauges after disabling the guard
When SYNC_DURABLE_REDRIVE_GUARD is turned off after custody records have been created, this condition stops reading their durable aggregate even though rollback intentionally retains those records. Existing processes leave the gauges frozen at their last values, while restarted processes expose the default zero values, so monitoring can incorrectly report that the unresolved backlog disappeared. Refresh these gauges independently of whether new custody transfers are enabled.
Useful? React with 👍 / 👎.
| elif redrive_policy.legacy_convergence_enabled(): | ||
| converged = await run_blocking( | ||
| db_executor, | ||
| sync_redrive.converge_legacy_completion, |
There was a problem hiding this comment.
Converge legacy completion before stale polling can fail it
When a legacy worker commits a valid completed ledger result and then fails before publishing the Redis result, a client poll can acquire the released run lock after the job becomes stale and finalize that Redis job as failed in get_sync_job_status. The next task delivery then returns from the terminal-status branch above, so this new convergence block is never reached and the proven success remains exposed as a failed job. Apply the legacy convergence check in the lock-owning stale-poll path, or otherwise ensure it runs before terminal acknowledgement.
Useful? React with 👍 / 👎.
…ed levers (#22071) FIRESTORE_READ_LEVERS: singleton_loops 100 -> 0, backfill_task_reads/ historical_scan_memo/ledger_purge_coalesce/people_scan_dedupe 5 -> 0; the seven graduated levers stay 100 (missing keys default OFF, so the literal must stay complete). Generated with avo/firestore-reads/set_levers.py. - singleton_loops: verify UNSAFE at 2026-10-17T20:00Z (five reconcile loops acquired=0, lease starvation); starvation window coincides with sync-owner revision rolls #22061/#22063 (18:20Z/20:26Z) and leases recovered by 21Z, off stands pending lease rework (decision-2026-10-18T00Z-flagoff-five.md). - The four 5% levers: shared guard service backend-sync-backfill exempt only until 2026-10-18T01:00Z with 5xx at 7-8%/h and rising (630->2737/h 15Z-22Z) through sync-owner sequencer rework; evidence ambiguous -> off per loop judgment rules; re-enable at 5% after recovery exonerates. Reviewed by zcode glm-5.3: r1 exec-erupt-ordinary-quote-scrap-observe-reject (singleton-only, SAFE); r2 exec-print-tortoise-fire-panda-sustain-enforce caught replace-mode literal dropping the seven graduated levers (FIX-REQUIRED, fixed by restoring the complete 12-key literal + rebase onto #22066). Contract tests 79/79 green.
Accepted sync requests can outlive Redis and staged-source retention. This dark change moves expired requests into durable
redrive_requiredcustody before removing them from dispatch, and retains staged bytes when a missing-job worker ACKs. Canonical completed content permits retirement without a handoff; partial checkpoints and bound/competing claims remain protected.SYNC_DURABLE_REDRIVE_GUARD=falseandSYNC_LEGACY_COMPLETION_CONVERGENCE=falsedefault off. Legacy retries can read durable success after taking the run lock and finalize Redis through the existing token CAS before download/provider execution. Scheduler gauges read a durable unresolved-handoff aggregate plus nearest exact/attention deadline and unknown-deadline count. This PR enables no source holds, automatic redriver, configuration rollout, or deploy. Rollback leaves durable custody intact.Validation: actual FastAPI HTTP missing-job custody and legacy Redis-CAS convergence tests; focused sequencer, custody/CAS and task-handler tests; real loopback Firestore transaction/deletion tests; async-blocker scan; manifest preflight. An existing emulator assertion was corrected to preserve the dispatching epoch while requiring higher epochs for expired running leases. Production apply and inference were not run.
Failure-Class: FC-durable-queue-outlives-executable-work
The incident follow-up tightens the old retirement boundary: Redis absence is execution-cache evidence, not permission to discard the accepted obligation. The retained payload is committed atomically with scheduling removal; the new tests exercise custody and durable completion separately from terminal cache state.
Product invariants affected
none
Line-Count-Exception: backend/routers/sync.py | 2887 -> 2903 | Wire durable missing-job custody and under-lock convergence at the existing worker boundary; implementation lives in database/sync_redrive.py.
Reproduction from the product worktree (run through the host's
nice -n 19heavy-command wrapper):The HTTP tests POST the real
/v2/sync-jobs/runroute with local Redis/Firestore doubles and OIDC dependency override, proving custody-before-ACK and legacy Redis-CAS convergence before provider/download. The emulator suite passed on rerun after one existing contention test exhausted its five transaction retries. The final push hook also passed full backend type checking with zero errors. No production endpoint, provider, account data or storage mutation was used for these tests.