Repository navigation
feat(webhooks): add PgNotificationOutbox.enqueue_prepared_sync for synchronous business transactions - #1665
Merged
Conversation
…nchronous business transactions PgNotificationOutbox.enqueue_prepared only accepted a psycopg 3 AsyncConnection, so a seller whose business writes run on synchronous SQLAlchemy, psycopg2 or psycopg 3 could not queue a notification in the same transaction as the change it announces (#1607). enqueue_prepared_sync takes the same arguments and accepts a psycopg 3 Connection, a psycopg2 connection, or a SQLAlchemy Connection on either driver (session.connection() for an ORM unit of work). The pure work moves into _prepare_insert (validation, _protected, _scope, _aad, AES-GCM, deadline) and _existing_binding_id (the duplicate-binding check), which both methods call; only the two statements differ. Transaction detection per driver, refused with ValueError before any SQL: - psycopg 3 and psycopg2: the session must be in a transaction block (INTRANS), the async method's rule. - SQLAlchemy: in_transaction() must be true and the driver connection must not be in autocommit (AUTOCOMMIT isolation). SQLAlchemy begins the driver transaction on the first statement, so the notification may be the first write. Any other object, including a psycopg AsyncConnection, raises TypeError. Driver dispatch reads sys.modules, so no optional driver is imported. Both paths now ask the driver for tuple rows. An adopter connection with row_factory=dict_row made enqueue_prepared fail with KeyError: 0 on main. Tests against real PostgreSQL, for psycopg 3, psycopg2, and SQLAlchemy on each: the row commits with the business write and the existing async worker (a fresh outbox instance) delivers the same PreparedWebhook; a rollback leaves neither row and delivers nothing; sync and async share one binding (identical re-enqueue returns the id, different headers raise, the transaction stays usable); per-driver refusal outside a transaction; SQLAlchemy enqueue-first, AUTOCOMMIT refusal and Session use; dict-row connections on all three paths. Docs section and an adopter type-check fixture. Closes #1607 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — clean additive PR, no blocking or medium findings.
Checked:
enqueue_prepared_syncis a new public method (correctfeat:signal);enqueue_preparedsignature is unchanged, so no breaking change to the public surface.- Shared
_prepare_insert/_existing_binding_idkeep validation, AES-GCM encryption, and the duplicate-binding rule identical across async/sync paths. self._sql_existingreuses the 11-columnself._columns, keeping_open'srow[:11]unpacking consistent (notification_outbox_pg.py:418).- Transaction detection verified across all four driver combos (raw psycopg/psycopg2 accept INTRANS; SQLAlchemy requires
in_transaction()AND non-AUTOCOMMIT dbapi), matching the async rule and allowing lazy enqueue-first (notification_outbox_pg.py:136). - Dict-row bug fix is real (
row[0]KeyError on dict_row) and resolved by forcing tuple rows on both paths. - No new external I/O: the row rides the caller's transaction; the unchanged async worker handles delivery; FOR UPDATE lock lifetime matches existing behavior.
- Tests cover commit/rollback/shared-binding/refusal/accept per driver plus a no-Postgres pre-SQL guard (test_pg_notification_outbox.py:590).
Decision table: no critical/high/medium findings; gated_paths false; high_risk false; no author team gate. Row 2 does not apply (gated_paths is false despite REVIEW_REQUIRED). Falls through to row 9 → approve.
| with business_transaction(driver, business_table) as conn: | ||
| enqueue_sync(outbox, conn) | ||
| raise RuntimeError("rollback") | ||
| assert business_rows(business_table) == 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1607.
What
PgNotificationOutbox.enqueue_prepared_sync(conn, prepared, *, notification_type, caller_scope_id, account_id=None, signing_scope_id=None) -> inttakes the same arguments asenqueue_prepared. It accepts:Connection,connection, orConnectionon either driver (for an ORM unit of work, passsession.connection()).The row commits or rolls back with the caller's transaction, and the existing async worker delivers it. The worker is unchanged.
Shared logic, not duplicated.
enqueue_preparedis split into:_prepare_insert: validation,_protected,_scope,_aad, AES-GCM, and the deadline;_existing_binding_id: the duplicate-binding comparison.Both the async and sync methods call these two. The only difference between them is how the two statements (
INSERT … ON CONFLICT DO NOTHING RETURNING id, thenSELECT … FOR UPDATE) run.How "in a transaction" is detected
If the connection is not in a transaction, the call raises
ValueErrorbefore any SQL runs:Connectioninfo.transaction_status == INTRANS, the same rule as the async method (after a statement, or insideconn.transaction())connectionget_transaction_status() == TRANSACTION_STATUS_INTRANS(psycopg2 opens the block on the first statement, so a fresh connection is refused)Connectionin_transaction()is true and the driver connection is not in autocommit mode (AUTOCOMMITisolation is refused even insideconn.begin()). SQLAlchemy begins the driver transaction on the first statement, so here the notification may be the first write.Any other object, including a psycopg
AsyncConnection, raisesTypeError. Driver dispatch readssys.modules, so no optional driver is ever imported.Bug fixed on the way
When an adopter's connection defaults to dict rows (
row_factory=dict_row),enqueue_preparedonmainfails withKeyError: 0. I reproduced this against real Postgres. Both paths now ask the driver for tuple rows. Test:test_enqueue_ignores_dict_row_factories, which also covers psycopg2RealDictCursor.Tests (real PostgreSQL 16)
These are added to
tests/conformance/decisioning/test_pg_notification_outbox.py, which is already in the CIpg-conformancecore lane. psycopg2-binary and SQLAlchemy (through alembic) are already dev dependencies, so CI runs every driver:PreparedWebhook.ValueError, and the transaction stays usable afterwards.AUTOCOMMITinsidebegin().engine.begin(), and an ORMSession.AsyncConnectionand an arbitrary object both raiseTypeError. A no-Postgres unit test checks that this happens before any call on the connection.Docs: a "Synchronous business transactions" section in
docs/webhooks/notification-outbox.md. Type-check fixture:tests/type_checks/notification_outbox_sync.pycovers psycopgConnection, SQLAlchemyEngine.begin()andSession.connection()under mypy--strictand pyright. psycopg2 ships no type information, so it has no fixture.Coordination:
webhook_supervisor_pg.py(#1606, merged as #1651) is untouched.Checks run locally
make lint: passedmake typecheck-all: passedADCP_PG_TEST_URLset:test_pg_notification_outbox.py,test_notification_outbox.py,test_notification_outbox_artifacts.pyandtest_pg_task_webhook_outbox.py, 91 passedenqueue_prepared's signature and behaviour are unchanged, except that it now works with dict-row connections.🤖 Generated with Claude Code