Skip to content

fix(sync): retain expired obligations in durable redrive custody (dark) - #22063

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/sol-redrive-guard-20261018
Oct 17, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/sol-redrive-guard-20261018

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Accepted sync requests can outlive Redis and staged-source retention. This dark change moves expired requests into durable redrive_required custody 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=false and SYNC_LEGACY_COMPLETION_CONVERGENCE=false default 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 19 heavy-command wrapper):

backend/.venv/bin/python -m pytest backend/tests/unit/test_sync_backfill_uid_sequencer.py -q  # 99 passed
backend/.venv/bin/python -m pytest backend/tests/unit/test_sync_cloud_tasks.py -q  # 133 passed
backend/.venv/bin/python -m pytest backend/tests/unit/test_sync_redrive.py backend/tests/unit/test_sync_redrive_endpoint.py -q  # 8 passed
FIRESTORE_EMULATOR_HOST=127.0.0.1:19087 backend/.venv/bin/python -m pytest backend/tests/integration/test_sync_backfill_retirement_emulator.py -q  # 22 passed
make preflight OMI_PR_BODY_FILE=/path/to/this-body.md  # 35 checks passed

The HTTP tests POST the real /v2/sync-jobs/run route 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 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-17T20:03:12.840690Z 6355f26 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: 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".

Comment thread backend/routers/sync.py
Comment on lines +2168 to +2172
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})

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 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 👍 / 👎.

Comment on lines +305 to +306
if sync_redrive.enabled():
sync_redrive.refresh_metrics()

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 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'])

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 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 👍 / 👎.

Comment thread backend/routers/sync.py
Comment on lines +2233 to +2236
elif redrive_policy.legacy_convergence_enabled():
converged = await run_blocking(
db_executor,
sync_redrive.converge_legacy_completion,

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

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

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

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 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 👍 / 👎.

Comment on lines +65 to +66
transaction.set(prepared['ref'], prepared['row'])
transaction.set(prepared['stats_ref'], prepared['stats'])

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

@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: 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".

Comment on lines +305 to +306
if sync_redrive.enabled():
sync_redrive.refresh_metrics()

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 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 👍 / 👎.

Comment thread backend/routers/sync.py
Comment on lines +2233 to +2236
elif redrive_policy.legacy_convergence_enabled():
converged = await run_blocking(
db_executor,
sync_redrive.converge_legacy_completion,

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 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 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 4776b04 into main Oct 17, 2026
57 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sol-redrive-guard-20261018 branch October 17, 2026 20:10
Git-on-my-level added a commit that referenced this pull request Oct 18, 2026
…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.
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