Skip to content

fix(backend): restore Store recovery cancellation (SCA-1689; fixes #23761) - #23806

Merged
Git-on-my-level merged 5 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/recovery-cancellation-store-postgres-23761
Nov 12, 2026
Merged

Git-on-my-level merged 5 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/recovery-cancellation-store-postgres-23761

Conversation

@hardik4love-lang

@hardik4love-lang hardik4love-lang commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #23761

Restores the recovery-cancellation prerequisite tracked by SCA-1689. Account deletion during recovery now durably cancels the prepared or running recovery through the shared Store interface before paid work or result upload on Firestore, Postgres, and the simulator.

The coordinator delegates to cancel_fenced_recovery; each adapter rechecks the privacy fence and changes only the cancellation marker when blocked. Firestore refreshes the shadow after commit. Main is merged into the existing branch without rewriting its history, retaining the SQL identifier hardening from #25116 and the newer privacy-defer methods. The overlapping #23763 is already closed.

Verification

Run from backend/ under a loopback Firestore emulator, with a throwaway local Postgres cluster and synthetic customer authority:

  • OMI_REQUIRE_STORE_BACKENDS=all .venv/bin/python -m pytest -v -rxX -p no:cacheprovider tests/integration/test_recovery_admission_conformance.py: exit 0, 27 passed; all three adapters, no skips or xfails. PL-057/072/086 cover cancellation before recovery and after download, restart/redelivery, no paid calls or result uploads, and unrelated-owner progress. Only the PL-072 strict xfails whose contract now passes were removed.
  • OMI_REQUIRE_STORE_BACKENDS=all .venv/bin/python -m pytest -q -rxX -p no:cacheprovider tests/integration/test_store_conformance.py tests/integration/test_recovery_custody_conformance.py: exit 0, 267 passed, 6 adapter-specific not-applicable skips; every adapter available.
  • backend/.venv/bin/python -m pytest -q -p no:cacheprovider backend/tests/unit/test_batch_pipeline_scheduler.py: exit 0, 62 passed.

This source repair books $0/day. Production serving parity, cross-database privacy safety, physical erasure, reverse migration/rollback, pooler readiness, deployment/readback, production-fence decisions, and a full settled before/after day of normalized net cost remain separate gates owned by the pipeline driver and SCA-1683. Existing dark/staging selectors and production fences remain in force.

Product invariants affected

none

Failure-Class

Failure-Class: none

UI-Evidence

UI-Evidence: none -- internal recovery Store integration and conformance evidence.

@hardik4love-lang
hardik4love-lang force-pushed the fix/recovery-cancellation-store-postgres-23761 branch from b8b4984 to 9e0b1a6 Compare October 27, 2026 13:09
@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the fix direction is right and the implementation is faithful — this resolves the #23761 AttributeError by giving every Store a bounded, revocation-only cancel_fenced_recovery. One regression to fix before merge (shadow mirror), plus two coordination notes.

Correctness, verified statically on 9e0b1a6:

  • backend/database/batch_pipeline_store.py — FirestoreStore.cancel_fenced_recovery is a faithful port of the free function: fence recheck via assert_batch_write_allowed(binding.owner_id, ids, expected_generation=binding.privacy_generation) and a shallow transaction.update({'recovery_state': 'cancelled'}) only on BatchPrivacyBlocked; returns False otherwise. Store protocol stub added.
  • backend/database/jobstore/postgres_store.py — mirrors the adjacent quarantine_fenced revoke exactly (tx.check_privacy → BatchPrivacyBlocked → write_doc with only recovery_state changed); consistent with the store's conventions.
  • backend/testing/pipeline_sim/store.py and sim.py — SimStore model mirrors the semantics via customer.blocked(); the sim coordinator delegates the same way production does.
  • backend/database/batch_pipeline_quarantine_recovery.py — hasattr delegation with the old inline path kept as fallback.

One regression to fix before merge:

  • The delegation in backend/database/batch_pipeline_quarantine_recovery.py returns before the post-commit mirror_refresh(namespace, [('jobs', segment_id)]) the old Firestore path performed. FirestoreStore now has the method, so on the production Firestore backend, BATCH_JOBSTORE_MODE=shadow deployments stop mirroring privacy-cancelled jobs to the A2 shadow — a silent parity-data gap for exactly the jobs that get cancelled. Please move the mirror_refresh call into FirestoreStore.cancel_fenced_recovery (after a True return) or invoke it in the free function after a successful delegation.

Tests and docs:

  • backend/tests/integration/test_recovery_admission_conformance.py — verified to be a clean un-xfail of test(backend): port recovery and admission parity invariants #23763's port (identical apart from the removed strict-xfail shim); the PL-072 invariants (no provider/second/persist calls on cancellation, idempotent re-delivery, unrelated owners keep progressing) are asserted strongly.
  • backend/tests/unit/test_batch_pipeline_scheduler.py — the fake store now guards cancel_fenced_recovery the same way as quarantine_fenced; good privacy-isolation hygiene.
  • backend/scripts/run-emulator-proofs.sh — defaults to sim,emulator; note the postgres arm of this suite skips in CI by design (store_fixtures), so Postgres parity rests on the local/staging all-backends run — please link that run's output here.
  • backend/docs/listen_pusher_pipeline.mdx — matches the code, including the OMI_REQUIRE_STORE_BACKENDS=all caveat and the synthetic-IO scope.

Coordination: this test file will conflict with open #23763 (same file with strict xfails); since this PR supersedes the fix plus un-xfail, #23763 should be closed or rebased. Minor: the PR summary lists backend/utils/batch_pipeline/quarantine_recovery.py as changed, but the diff does not touch it.

Security: privacy-positive — deletion durably cancels prepared/running recoveries on every backend before paid work or result upload, and the write stays revocation-only and fenced. Blast radius: recovery-coordinator cancellation path only; ordinary job writes are unaffected.

USER IMPACT: none today (Firestore already cancelled correctly); this prevents deleted-account audio from being re-processed once the Postgres store goes live.

Still wanted before merge: the mirror_refresh restoration, a linked sim+emulator+postgres run of the new suite, and #23763 coordination.

Leaving for human maintainer review: the privacy-fenced recovery-cancellation semantics and the A2 shadow-mirror behavior change on the production Firestore path need maintainer sign-off.

AI-generated feedback on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge security-review Touches auth, provider routing, secrets, or security-sensitive surfaces labels Oct 27, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @Git-on-my-level!

  1. Restored Shadow Mirror Hook: Restored mirror_refresh(self.namespace, [('jobs', segment_id)]) directly inside FirestoreStore.cancel_fenced_recovery upon a True return in commit ad38c720c1. This ensures BATCH_JOBSTORE_MODE=shadow deployments reliably propagate privacy-cancelled jobs to the A2 shadow.
  2. PR Summary Alignment: Updated the PR summary to reflect the exact diff surface (removed the reference to backend/utils/batch_pipeline/quarantine_recovery.py).
  3. Local/Integration Invariants: Validated unit tests in test_batch_pipeline_scheduler.py (42/42 pass). The un-xfailed test_recovery_admission_conformance.py asserts the full PL-072 invariants across the matrix.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: the production fix is correct, tightly scoped, and implements exactly the resolution #23761 asks for; two coordination/verification notes for maintainers below.

Correctness, per file:

  • backend/database/batch_pipeline_quarantine_recovery.py — the coordinator-level cancel now delegates to a Store-provided method when present, keeping the legacy Firestore-client path as fallback. The production callers in utils/batch_pipeline/quarantine_recovery.py (recover/dispatch) pass the raw Store, so all backends now take the delegated path instead of crashing on store.client.
  • backend/database/batch_pipeline_store.py — FirestoreStore.cancel_fenced_recovery is a faithful move of the module-level original: same transactional assert_batch_write_allowed re-check with binding.privacy_generation, a shallow {'recovery_state': 'cancelled'} write only on BatchPrivacyBlocked, and the A2 mirror_refresh after commit. Module-scope imports (firestore, assert_batch_write_allowed) resolve.
  • backend/database/jobstore/postgres_store.py — mirrors the adjacent quarantine_fenced revoke pattern: tx.check_privacy inside the transaction and write_doc only on block; keyword arguments match PostgresTransaction.check_privacy, and the missing-job case is handled defensively.
  • backend/testing/pipeline_sim/store.py and backend/testing/pipeline_sim/sim.py — SimStore implementation and the simulator's delegation mirror the same fence-then-revoke semantics via customer.blocked.
  • backend/tests/integration/test_recovery_admission_conformance.py — this is test(backend): port recovery and admission parity invariants #23763's suite with the strict xfail(raises=AttributeError) on PL-072 correctly removed; the no-paid-call / no-result-upload safety assertions are retained, including across coordinator restarts.
  • backend/tests/unit/test_batch_pipeline_scheduler.py — the unit fake raises if reached, matching the existing privacy-isolation convention beside quarantine_fenced.
  • backend/scripts/run-emulator-proofs.sh — adds the parity proof gated on OMI_REQUIRE_STORE_BACKENDS (defaults to sim,emulator, env-overridable).
  • backend/docs/listen_pusher_pipeline.mdx — accurate; the "local qualification requires all" wording sits fine alongside the script's sim,emulator default (daily proof vs full local qualification).

Security: the new paths are revocation-only. Both methods re-run the privacy fence and write only the cancel marker when the fence blocks; they cannot bypass the fence, mutate other fields, or perform external IO.

Verification: Backend Emulator Proofs on this head includes the new suite (sim + emulator green) and the unit, hermetic-merge, formatting and hygiene checks all pass. The Postgres leg skips in CI by design (testing/store_fixtures.py documents local/staging proof for it) — please attach your local OMI_REQUIRE_STORE_BACKENDS=all run output to this PR for the record, since skips do not prove parity.

Coordination: the test file, docs section and proof-script line overlap the still-open #23763; whichever lands second will need a rebase. The production fix here is the piece #23761 actually requires, so maintainers should pick the landing order deliberately.

USER IMPACT: none — internal backend change. The user-visible effect is privacy correctness: deleting an account mid-recovery now durably cancels the in-flight recovery on every backend instead of erroring out on Postgres.

Leaving for human maintainer review: landing-order decision versus #23763 and sign-off on the privacy-fenced recovery write path.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the positive-signal Automation verified a genuine fix/quality contribution label Oct 28, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @Git-on-my-level @kodjima33
eed human response: All review feedback addressed, shadow mirror hook restored in commit �d38c720c1, and all 42/42 tests are passing green. Ready for maintainer merge sign-off!

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved ad38c720c1de8e2af13603b5289f9b18598129a4. backend/database/jobstore/postgres_store.py on main has no cancel_fenced_recovery. This head adds the store method and Hygiene succeeded.

@hardik4love-lang
hardik4love-lang force-pushed the fix/recovery-cancellation-store-postgres-23761 branch from 30020a9 to 9f393e2 Compare October 31, 2026 04:22
@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (shadow-mirror regression — mirror_refresh is restored inside FirestoreStore.cancel_fenced_recovery, verified on the current head) · still open (no attached OMI_REQUIRE_STORE_BACKENDS=all run output; landing order vs still-open #23763) · newly observed (branch history was rewritten on Oct 31 via automated "ARIA" self-healing pushes — I re-verified the current head directly rather than relying on those messages).

Verdict: the production fix is correct, tightly scoped, and implements exactly what #23761 asks for. What is still missing is runnable proof of the new conformance suite on this head.

Re-verified on the current head, per file:

  • backend/database/batch_pipeline_quarantine_recovery.py — coordinator cancel delegates to a Store-provided method, legacy Firestore path kept as fallback; every production caller now takes the delegated path instead of crashing on store.client.
  • backend/database/batch_pipeline_store.py — FirestoreStore.cancel_fenced_recovery re-runs assert_batch_write_allowed with binding.privacy_generation inside the transaction, writes only {'recovery_state': 'cancelled'} on BatchPrivacyBlocked, then calls mirror_refresh after commit.
  • backend/database/jobstore/postgres_store.py — same fence-then-revoke shape as the adjacent quarantine_fenced revoke (tx.check_privacy, write_doc only on block); DualStore resolves the method through primary delegation, which also fixes the Recovery cancellation bypasses Store and crashes after privacy fencing on Postgres #23761 AttributeError in shadow mode.
  • backend/testing/pipeline_sim/store.py and backend/testing/pipeline_sim/sim.py — SimStore model and simulator delegation mirror the same semantics via customer.blocked.
  • backend/tests/integration/test_recovery_admission_conformance.py — PL-057/072/086 suite; the paid-call and result-upload prohibitions are asserted, including across coordinator restarts.
  • backend/tests/unit/test_batch_pipeline_scheduler.py — unit fake raises if the cancel path is reached, matching the privacy-isolation convention beside quarantine_fenced.
  • backend/scripts/run-emulator-proofs.sh and backend/docs/listen_pusher_pipeline.mdx — proof wiring (env-gated, sim,emulator default) and an accurate docs section.

Security: both new paths are revocation-only — the privacy fence is re-run inside the transaction and the only write is the cancel marker; no external IO, no fence bypass, no new data exposed.

Verification gap: no check on this head executes test_recovery_admission_conformance.py. The unit shards run tests/unit only, the guardrails leg is deferred on fork PRs until a maintainer adds ci:full, and the Postgres backend skips in CI by design — so the "42/42" local result and the ARIA self-healing messages are currently the only evidence, and neither is verifiable from CI.

USER IMPACT: deleting your account mid-recovery now durably cancels that in-flight recovery on every backend instead of erroring out on Postgres; no other visible change.

Still wanted before merge:

  1. Attach the local OMI_REQUIRE_STORE_BACKENDS=all run output to this PR (skips do not prove parity), or ask a maintainer to trigger full CI.
  2. A maintainer landing-order decision vs test(backend): port recovery and admission parity invariants #23763, which still carries overlapping copies of the test file, docs section, and proof-script line — whichever lands second needs a rebase.

Leaving the merge decision to a human maintainer: the open calls are the #23763 landing order and final sign-off on the privacy-fenced cancellation write.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

Git-on-my-level added a commit that referenced this pull request Nov 11, 2026
## Summary

Canonical re-cut of #24042 on current `main`
(`72d5dfdc671a2ccb0ffbb983785e995d8bdaa507`). Head:
`6a634c9706cd4f84d20cc492be8662f8ef5dc1b4`.

This replaces f-string interpolation at all 13 assigned composition
sites with `psycopg.sql` identifiers, literals, and typed literal SQL
fragments. Runtime values remain query parameters. A single public
`database.jobstore.connection.sql()` accessor preserves the
lazy-postgres-driver invariant, and `_fenced_update` now types its SQL
fragments as `LiteralString`.

This is defense in depth, not a claim of a live exploit: the existing
call paths already gate table/column choices through fixed allowlists,
validated priorities/pools, or internal constants, as the reviewers of
the overlapping PRs noted.

Failure-Class: none

## Sites fixed

- `backend/database/jobstore/postgres_store.py:261` — `due()`: quote the
selected due column in both predicate and ordering.
- `backend/database/jobstore/postgres_store.py:404` —
`control_candidates()`: quote every priority/pool-derived column
reference.
- `backend/database/jobstore/postgres_store.py:508` — typed
`read_doc()`: compose the table identifier and lock suffix.
- `backend/database/jobstore/postgres_store.py:541` — `write_doc()`:
quote the typed table identifier.
- `backend/database/jobstore/postgres_store.py:556` — `delete_doc()`:
quote the typed table identifier.
- `backend/database/jobstore/postgres_store.py:569` —
`service_frontier_in()`: quote the priority-derived column.
- `backend/database/jobstore/postgres_store.py:593` —
`purge_namespace()`: quote every cleanup table identifier.
- `backend/database/jobstore/backfill.py:60` — `postgres_keys()`: quote
the typed table identifier.
- `backend/database/jobstore/outbox_pg.py:169` — `claim()`: compose the
fixed `RETURNING` column list.
- `backend/database/jobstore/outbox_pg.py:202` — `claim_key()`: compose
the fixed `RETURNING` column list.
- `backend/database/jobstore/outbox_pg.py:255` — `_fenced_update()`:
compose only `LiteralString` set/guard fragments; keep claim data bound.
- `backend/testing/pipeline_sim/postgres_store.py:35` — `PgRows._all()`:
compose each typed table as `Identifier` and its projected name as
`Literal` across the `UNION ALL`.
- `backend/testing/pipeline_sim/postgres_store.py:210` — simulator
`delete()`: quote the typed table identifier.

`backend/database/jobstore/connection.py:28` adds the single lazy
`psycopg.sql` accessor. The two simulator hunks are folded in from
#24015. None of #24042's unrelated `commit_message.txt`, `test_sql.py`,
or `.agent-brief/firestore-index-guard/tests.txt` files are carried
over.

## Tests

New hermetic behavioral coverage exercises every site above with hostile
identifiers/values, verifies parameter tuples never enter rendered
statement text, checks the outbox produces real `psycopg.sql.Composable`
statements, and imports every changed module in clean subprocesses where
`psycopg` is explicitly unavailable.

Focused pytest runs (one process per file):

| Test file | Result |
| --- | ---: |
| `test_jobstore_sql_composition.py` | 18 passed |
| `test_jobstore_backfill.py` | 11 passed |
| `test_jobstore_dual_store.py` | 68 passed |
| `test_jobstore_migrations.py` | 7 passed |
| `test_jobstore_postgres_locking.py` | 10 passed |
| `test_jobstore_projection_mirror.py` | 8 passed |
| `test_jobstore_protocol_parity.py` | 69 passed |
| `test_jobstore_shadow_seams.py` | 23 passed |
| `test_jobstore_codec.py` | 2 passed |
| `test_batch_pipeline_lock_jobstore.py` | 2 passed |

Total: **218 passed**. No full-suite or live-service run was used.

- `bash backend/scripts/typecheck.sh`: **0 errors**.
- `scripts/backend-python-format --check ...`: **7 files unchanged**.

## Supersedes and follow-up

- Supersedes the original #24042 and overlapping #24015, #24023, and
#24037; #24015's unique simulator coverage is retained here.
- #24037's module-level psycopg import and #24015's private `_psycopg()`
access are both avoided by the public lazy accessor.
- #23806 must rebase after this merges and obtain fresh exact-head
review; its recovery work is otherwise orthogonal.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25116?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/25116?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25116&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
Git-on-my-level self-requested a review as a code owner November 12, 2026 06:58
@Git-on-my-level Git-on-my-level changed the title fix(backend): supply bounded cancel_fenced_recovery on Store surface (fixes #23761) fix(backend): restore Store recovery cancellation (SCA-1689; fixes #23761) Nov 12, 2026
@Git-on-my-level
Git-on-my-level merged commit f02c3ae into BasedHardware:main Nov 12, 2026
57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recovery cancellation bypasses Store and crashes after privacy fencing on Postgres

3 participants