Skip to content

feat(webhooks): add PgNotificationOutbox.enqueue_prepared_sync for synchronous business transactions - #1665

Merged
bokelley merged 1 commit into
mainfrom
claude/issue-1607-sync-enqueue-prepared
Oct 27, 2026
Merged

bokelley merged 1 commit into
mainfrom
claude/issue-1607-sync-enqueue-prepared

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Closes #1607.

What

PgNotificationOutbox.enqueue_prepared_sync(conn, prepared, *, notification_type, caller_scope_id, account_id=None, signing_scope_id=None) -> int takes the same arguments as enqueue_prepared. It accepts:

  • a psycopg 3 Connection,
  • a psycopg2 connection, or
  • a SQLAlchemy Connection on either driver (for an ORM unit of work, pass session.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_prepared is 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, then SELECT … FOR UPDATE) run.

How "in a transaction" is detected

If the connection is not in a transaction, the call raises ValueError before any SQL runs:

Connection Accepted when
psycopg 3 Connection info.transaction_status == INTRANS, the same rule as the async method (after a statement, or inside conn.transaction())
psycopg2 connection get_transaction_status() == TRANSACTION_STATUS_INTRANS (psycopg2 opens the block on the first statement, so a fresh connection is refused)
SQLAlchemy Connection in_transaction() is true and the driver connection is not in autocommit mode (AUTOCOMMIT isolation is refused even inside conn.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, raises TypeError. Driver dispatch reads sys.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_prepared on main fails with KeyError: 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 psycopg2 RealDictCursor.

Tests (real PostgreSQL 16)

These are added to tests/conformance/decisioning/test_pg_notification_outbox.py, which is already in the CI pg-conformance core lane. psycopg2-binary and SQLAlchemy (through alembic) are already dev dependencies, so CI runs every driver:

  • Commit: for each of psycopg 3, psycopg2, SQLAlchemy+psycopg and SQLAlchemy+psycopg2, the row commits with a business write. Another connection cannot see it before the commit. A fresh async outbox instance then delivers the identical PreparedWebhook.
  • Rollback: for each driver, rolling back leaves neither the business row nor the notification, and nothing is sent.
  • Shared binding: for each driver, sync and async share one binding. An identical re-enqueue returns the async row's id, different headers raise ValueError, and the transaction stays usable afterwards.
  • Refusals: psycopg 3 autocommit outside a block, and idle non-autocommit; psycopg2 autocommit, and idle before the first statement; SQLAlchemy before autobegin, and AUTOCOMMIT inside begin().
  • Accepted cases: SQLAlchemy enqueue-first in engine.begin(), and an ORM Session.
  • Unsupported types: AsyncConnection and an arbitrary object both raise TypeError. 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.py covers psycopg Connection, SQLAlchemy Engine.begin() and Session.connection() under mypy --strict and 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: passed
  • make typecheck-all: passed
  • Postgres 16, ADCP_PG_TEST_URL set: test_pg_notification_outbox.py, test_notification_outbox.py, test_notification_outbox_artifacts.py and test_pg_task_webhook_outbox.py, 91 passed
  • Non-breaking: enqueue_prepared's signature and behaviour are unchanged, except that it now works with dict-row connections.

🤖 Generated with Claude Code

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

@aao-secretariat aao-secretariat 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.

Ladon verdict: Approve

Approve — clean additive PR, no blocking or medium findings.

Checked:

  • enqueue_prepared_sync is a new public method (correct feat: signal); enqueue_prepared signature is unchanged, so no breaking change to the public surface.
  • Shared _prepare_insert/_existing_binding_id keep validation, AES-GCM encryption, and the duplicate-binding rule identical across async/sync paths.
  • self._sql_existing reuses the 11-column self._columns, keeping _open's row[: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
@bokelley
bokelley merged commit e081fe4 into main Oct 27, 2026
47 checks passed
@bokelley
bokelley deleted the claude/issue-1607-sync-enqueue-prepared branch October 27, 2026 06:00
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.

feat(webhooks): let PgNotificationOutbox enqueue on a synchronous DB-API transaction

1 participant