Repository navigation
fix(jobstore): keep reason-bound custody deferral episodes in Postgres and sim outboxes (#24556) - #25290
fix(jobstore): keep reason-bound custody deferral episodes in Postgres and sim outboxes (#24556)#25290shubhxho wants to merge 9 commits into
Conversation
…s and sim outboxes (BasedHardware#24556) PostgresOutbox and SimOutbox persisted only the requested available_at on defer, so a callback custody cause that had deferred a row for six hours kept polling at its 120 s cadence instead of hourly like FirestoreEnrichmentOutbox. Both now keep deferred_reason/deferred_since (migration 0007 for Postgres) and apply utils.enrichment.outbox.custody_deferred_since/custody_defer_until, the same rule the Firestore outbox uses. A different cause starts a new episode; a closed row never reopens, so a new obligation starts fresh. Removes the strict xfail on the PL-342 parity proof for sim and postgres.
Codex Review Summary: ✅ CompletedThis 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: cd055e3759
ℹ️ 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".
| def _enrichment_outbox(): | ||
| # Same call-time import as database/outbox_firestore.py: the custody episode rule and its constants stay | ||
| # owned by utils.enrichment.outbox, so both store backends read one definition. | ||
| from utils.enrichment import outbox |
There was a problem hiding this comment.
Keep the shared policy import at module scope
Both this helper and the simulator now import utils.enrichment.outbox from inside a function, contrary to the backend guide's requirement that imports be at module scope; if the helper cannot be imported in a worker, this defers the failure until a claimed task is being settled. Move the shared rule to an allowed module-level dependency boundary rather than adding another call-time import.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8d3c061: the episode rule and its constants now live in the pure config/outbox_custody.py, imported at module scope by the Postgres, sim and Firestore outboxes; utils.enrichment.outbox re-exports them. No call-time import remains.
…rom config/ (BasedHardware#24556) Move custody_deferred_since/custody_defer_until and the PL-342 constants to the pure config/outbox_custody.py so the Postgres, sim and Firestore outboxes import them at module top level instead of a call-time import of utils.enrichment.outbox. utils.enrichment.outbox re-exports them unchanged.
…nused Firestore defer import (BasedHardware#24556)
Git-on-my-level
left a comment
There was a problem hiding this comment.
This needs one mechanical fix before merge — the port itself looks right.
Blocking: backend/database/jobstore/migrations/0007_outbox_custody_episode.sql — main already has 0007_ready_owners.sql (merged 2026-11-14, after your branch point), and database/jobstore/migrate.py refuses non-contiguous migration versions, so the merged tree (two 0007s) would make every migrate() call raise MigrationError at load time. Your CI is green only because your branch predates main's 0007. Please rebase on current main and rename the file to 0008_outbox_custody_episode.sql.
On the substance, this is a clean port of the Firestore custody-episode rule:
config/outbox_custody.py— constants andcustody_deferred_since/custody_defer_untilmoved verbatim into a pure shared module; good factoring.database/jobstore/outbox_pg.py—defer()keeps the exact lease fence of the old_fenced_updatepath (id + namespace + lease_token + done_at IS NULL) viaSELECT ... FOR UPDATEin one transaction;created_at(NOT NULL since 0002) as the episode bound is sound because a closed Postgres row never reopens. Only behavior change: past the 6h grace a stuck cause re-arms hourly instead of at the requested cadence — the intended fix.database/outbox_firestore.py— delegation swap only, behavior unchanged.testing/outbox_sim.py— sim rows now carrycreated_at/deferred_reason/deferred_since, mirroring Postgres;_enqueue's single caller passesnow.scripts/enrichment_recovery_emulator_test.py— un-xfailing the PL-342 test for sim/postgres and asserting the backoff everywhere is exactly right.tests/unit/test_sync_enrichment_custody.py— retargeting the grace monkeypatch toconfig.outbox_custodyis correct; the old patch site would no longer reach the rule.utils/enrichment/outbox.py— re-exports keep all existing importers working; public contract unchanged.
Performance: the win itself — the ~1.7k stuck rows that dominated backend-sync deliveries poll hourly past the grace instead of every ~120s; one extra SELECT per defer.
Blast radius: Postgres jobstore; worst case if wrong is a deferred obligation resuming up to an hour late past grace, which the Firestore path already accepts.
Security: additive nullable columns only, nothing user-facing.
USER IMPACT: none visible — enrichment obligations resume as before; stuck ones just stop being re-polled every two minutes after six hours, cutting background load.
Still wanted after the rename: a green emulator run against a Postgres with main's real migration history (both migrations in sequence), so the contiguity check is exercised on the merged shape. Happy to re-review once rebased.
Merge decision stays with the maintainers given this adds a jobstore schema migration; no urgent escalation.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
Preserve main migration 0007 and move unmerged dark migrations to 0008-0025 with identical SQL bodies. Clarify G2 registry retention and the separate #25290 landing-order collision.
|
Since my last review:
The port is correct and nicely scoped — thank you for the clean follow-up. File notes:
Performance: Postgres defer goes from one UPDATE to a two-statement transaction on the same primary-key row (lock held only for the re-arm), and the point of the change is to cut write volume — rows stuck past the six-hour grace poll hourly instead of every 30–120s. Security: parameterized SQL, expand-only migration, no new data exposure. Blast radius: confined to the enrichment outbox claim/defer loop; the only behavior change is matching Firestore's existing backoff. CI note: Backend unit shard 5/8 is red on tests/services/users/test_account_deletion.py::test_background_wipe_uses_immediate_idempotent_stripe_cancellation[resource_missing] — the fast-unit CPU-time guard at 1.01s vs the 1.00s limit (that runner also warned it fell back to pure-Python crc32c). Your diff doesn't touch that file or subsystem, so this reads as an environment flake; a re-run should clear it. USER IMPACT: none — internal change; Postgres-backend enrichment rows deferred for over six hours by a stuck cause now back off to hourly checks instead of re-polling every couple of minutes, matching what Firestore already did. Action item: re-run the red shard to confirm the flake clears. Leaving the merge call to a human maintainer. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
Resolved: the migration was renumbered to 0010_outbox_custody_episode.sql and current main's jobstore migrations end at 0009, so the version collision flagged in this review no longer exists on the merged tree. Verified against main's migrations directory.
|
Since my last review:
The port remains correct and merge-ready from my side. Migration 0010 is still contiguous with current main (which stops at 0009), and utils.enrichment.outbox's re-exports keep reprocess's star-import surface intact. USER IMPACT: none — internal change; stuck Postgres enrichment rows back off to hourly polling, matching Firestore. Leaving the merge call to a human maintainer. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
Resolve conflicts with main's v3 custody defer counter and ownership parking: keep the episode rule in config/outbox_custody.py, keep main's OWNERSHIP_PROBE_SECONDS. Main added 0010_projection_outbox_due.sql, so renumber this PR's migration to 0011_outbox_custody_episode.sql.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ac02a9f76d
ℹ️ 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".
| import functools | ||
| import logging | ||
|
|
||
| from config.outbox_custody import custody_defer_until, custody_deferred_since |
There was a problem hiding this comment.
Keep Firestore defer constants bound at module scope
When a valid Firestore claim is deferred, rearm() still evaluates outbox.FINALIZATION_OWNER_REFUSAL (and later outbox.V3_CUSTODY_*), but this change removes the only outbox = _outbox() binding and adds no module-level outbox; every such defer raises NameError before clearing the lease or scheduling a new wake. Keep those constants available through a module-scope dependency, or move them into the pure config module, before removing the binding.
AGENTS.md reference: backend/AGENTS.md:L168-L168
Useful? React with 👍 / 👎.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Since my last review: addressed: nothing was left open — migration numbering re-verified on this head (the episode migration is now 0011_outbox_custody_episode.sql, contiguous with main's newly landed 0010_projection_outbox_due, confirmed against main's migrations directory) · still open: nothing from my prior reviews · newly introduced: one blocking merge regression, below.
This needs a one-line fix before merge: the Nov 25 merge of origin/main silently dropped outbox = _outbox() from FirestoreEnrichmentOutbox.defer (backend/database/outbox_firestore.py), while main's new expedite-path code in the same function still uses the outbox local — outbox.FINALIZATION_OWNER_REFUSAL at line 497, plus outbox.park_for_ownership, outbox.V3_CUSTODY_DEFER_REASON, outbox.V3_CUSTODY_MAX_DEFERS and outbox.ownership_parked (lines 498–525). Every defer call on the Firestore outbox now raises NameError: name 'outbox' is not defined. Your branch's removal was correct against the older main, where rearm's only outbox.* uses were the two custody calls you replaced with the shared module functions; main's expedite path re-introduced outbox.* references, and the auto-merge combined both sides without a textual conflict. Restoring outbox = _outbox() as the first statement of defer's body — matching every other _outbox()-using method in the file — fixes it.
Rest of the merge checks out: migration 0011 is expand-only and contiguous; the Postgres defer transaction, the sim port, and the shared config/outbox_custody.py rule are untouched by the merge. Verified against the head, not assumed from the commit message.
Blast radius: without the fix, the Firestore enrichment defer path (the C3 consumer route) fails on every call; with it, behavior is the intended hourly backoff. Performance and cost are unchanged from the earlier reviews — the change exists to cut write volume, and it still does. CI: Backend unit shards 1/8, 2/8, 4/8 and 8/8, the emulator proofs, and the aggregate suite are red, all tracing to this one dangling reference (the type-check shard flags exactly lines 497/498/502/504/523/525; the runtime failures show the NameError in test_outbox_firestore.py, test_sync_reprocess_coalesce.py, test_sync_processing_hold.py and the PL-342 emulator proofs). Shard 4 also shows test_byok_security_quota and test_batch_pipeline_merge_head_wait failures I could not cleanly attribute from the interleaved log — please confirm they clear once this is fixed.
USER IMPACT: none once fixed — internal change; stuck enrichment rows back off to hourly polling, matching what the Firestore route already did.
Action items: (1) restore outbox = _outbox() at the top of defer; (2) push and confirm the full backend unit suite and the emulator proofs are green on the new head.
The port itself remains correct and nicely scoped — thank you. The merge decision stays with a human maintainer once CI is green.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
…defer lost in the main merge Main's expedite path in defer() uses outbox.FINALIZATION_OWNER_REFUSAL, park_for_ownership, V3_CUSTODY_* and ownership_parked; the Nov 25 merge kept those references but dropped the outbox = _outbox() binding, so every Firestore defer raised NameError.
No textual conflicts. Main's new Postgres selector census test (test_batch_census_registry.py) requires every jobstore function that SELECTs from outbox to have an executable profile; this PR's PostgresOutbox.defer now does a keyed SELECT ... FOR UPDATE, so add its profile. The merge also picks up utils/observability/speaker_evidence_erasure.py, which CI's import of utils.metrics needs.
Dismissing my earlier change request: its only blocking item is the outbox = _outbox() binding dropped from FirestoreEnrichmentOutbox.defer by the Nov 25 main merge. Commit 32e1262 restores it and the full backend unit suite, Hermetic Merge Gate and Pipeline Lab Scenarios are green on 4cf0752. Follow-up notes are in the PR comment.
|
Since my last review: addressed — Verdict: merge-ready from my side — the port is correct and the merge regression is fixed. Thank you for the quick turnaround. Re-checked on this head:
Performance: one extra primary-key USER IMPACT: none — internal change; Postgres-backed enrichment rows stuck on one cause for more than six hours back off to hourly polling instead of every couple of minutes, matching Firestore. Nothing further needed from you. This adds a schema migration to the Postgres jobstore by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
What changed and why
Fixes #24556 (PL-342).
PostgresOutboxandSimOutboxdropped the reason-bound custody deferral episode thatFirestoreEnrichmentOutboxkeeps. Theirdeferstored only the requestedavailable_atand the reason. A cause such asconversation_missingthat had deferred a row for longer than the six-hour grace went on polling every 120 s, where Firestore backs off to hourly.Root cause: the episode state (
deferred_reason/deferred_since) and thecustody_deferred_since/custody_defer_untilrule were only ported to the Firestore outbox (#24264). The replacement Postgres outbox had no columns for it, and the sim reference model mirrors Postgres.Fix:
0011_outbox_custody_episode.sql(expand-only; renumbered from 0007, then 0010, as main landed0007_ready_owners,0008_allowance_holds,0009_protected_shareand0010_projection_outbox_due) addsdeferred_reason textanddeferred_since float8tooutbox.custody_deferred_since/custody_defer_until) and its constants (LIVE_DEFER_SECONDS,STUCK_DEFER_*) move to the pure moduleconfig/outbox_custody.py.utils.enrichment.outboxre-exports them unchanged, and the Postgres, sim and Firestore outboxes import them at module scope (no call-time import, per backend/AGENTS.md import rules).PostgresOutbox.defernow runs in one transaction. It reads the held row (lease-token fenced,FOR UPDATE), computes the episode start and due time with that shared rule, and writesavailable_at,deferred_reasonanddeferred_sincetogether with the existing re-arm fields.created_atplays the part offirst_pending_at. A Postgres row is never reopened (a new obligation inserts a new open row), so an episode can't predate its obligation.SimOutboxfollows the same rule (created_at,deferred_reason,deferred_sinceon the row).now. Lease and wake fencing, the wake hook and custody are unchanged, and the contract signature is unchanged.Product invariants affected
none
How it was verified
Hermetic, with no cloud or vendor IO. Postgres ran as a local throwaway server (the
pgserverpath intesting/store_fixtures.py), withOMI_REQUIRE_STORE_BACKENDS=sim,postgresso neither backend could skip.mainat 7966062:python -m pytest scripts/enrichment_recovery_emulator_test.py -k pl342gave2 passed, 2 skipped, 2 xfailed. The strict xfails were sim and postgres fortest_pl342_long_custody_episode_slows_polling_without_retiring_debt.scripts/enrichment_recovery_emulator_test.pygave44 passed, 22 skipped. The skips are the Firestore emulator leg, which isn't available on this machine.tests/integration/test_outbox_conformance.pyplustest_parity_outbox_durability.pygave71 passed, 37 skipped(emulator only).outbox_pg,outbox_sim,store_fixturesor the jobstore migrations, each in its own pytest process: 27 files, all passed. That coverstest_jobstore_migrations_postgres,test_store_conformance,test_held_custody_conformance,test_recovery_custody_conformance,test_pull_batch_parity,test_dual_store_postgres,test_pipeline_goldens_postgres, the other*_emulator_test.pyproofs, and others.test_outbox_firestore,test_sync_enrichment_custody,test_enrichment_route,test_jobstore_migrations,test_jobstore_sql_composition,test_jobstore_protocol_parityandtest_provider_stt_outboxall passed.Not verified: the Firestore emulator leg, because no emulator is available here. The Firestore outbox's behaviour is unchanged; it only now imports the same rule from
config/outbox_custody.py.scripts/provider_merge_emulator_test.py(the failing step in the firstBackend emulator proofsrun) failed the same sim/postgres cases on unmodifiedmainat 7966062, so it was not caused by this PR. After merging currentmain(92b6970) it passes locally on sim and postgres (40 passed, 20 skipped), the same as on unmodifiedmain.Re-verified on 2026-11-25 after merging main, which landed
0010_projection_outbox_due, and renumbering this migration to 0011. Sim and Postgres were required viaOMI_REQUIRE_STORE_BACKENDS=sim,postgres, against a local Postgres 17, with migrations 0001 to 0011 applied in sequence:tests/unit/test_jobstore_migrations.py7 passed;tests/integration/test_jobstore_migrations_postgres.py3 passed (contiguity holds)scripts/enrichment_recovery_emulator_test.py44 passed, 22 skipped (Firestore emulator leg only)tests/integration/test_outbox_conformance.py63 passed, 33 skipped (emulator only);test_store_conformance,test_held_custody_conformanceandtest_recovery_custody_conformancepass (emulator legs skipped)test_sync_enrichment_custody(19) andtest_jobstore_protocol_parity(159)scripts/pr-preflightpassed (39 checks)Re-verified after merging main and renumbering the migration to 0010 (2026-11-18) (sim + Postgres required via
OMI_REQUIRE_STORE_BACKENDS=sim,postgres; Postgres is a throwaway localpgserver, so migrations 0001 to 0010 are applied in sequence on a fresh database, including main's real 0007 to 0009):tests/unit/test_jobstore_migrations.py7 passed;tests/integration/test_jobstore_migrations_postgres.py3 passed (contiguity check passes on the merged shape)scripts/enrichment_recovery_emulator_test.py44 passed, 22 skipped (Firestore emulator leg only)tests/integration/test_outbox_conformance.py63 passed, 33 skipped (emulator only)test_sync_enrichment_custody19,test_outbox_firestore23,test_jobstore_protocol_parity136,test_jobstore_sql_composition18 passedscripts/pr-preflight --base origin/mainpassedThe branch picks up main by a merge commit rather than a rebase, so the already-reviewed commits keep their SHAs.
Tests
The regression test is the existing PL-342 parity proof
scripts/enrichment_recovery_emulator_test.py::test_pl342_long_custody_episode_slows_polling_without_retiring_debt. Its strictAssertionErrorxfail forsimandpostgres, which linked this issue, is removed: it now passes on both.test_pl342_reason_change_and_reopening_start_fresh_custody_episodeskeeps covering the reset on a reason change and on a reopened obligation.UI evidence
UI-Evidence: none -- backend store change, no UI
Failure class (fixes)
Failure-Class: none