### Set up development environment and run tests Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Sets up a virtual environment, installs the package in editable mode with dev dependencies, runs the test suite, runs mypy with strict settings, and executes the concurrency demo script. ```sh python3 -m venv .venv && .venv/bin/pip install -e '.[dev]' .venv/bin/python -m pytest -q .venv/bin/python -m mypy src --strict python examples/concurrency_demo.py ``` -------------------------------- ### Install pgoutbox with pip Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Install the pgoutbox package. Requires Python >= 3.11 and Postgres >= 9.5 (for SKIP LOCKED). No runtime dependencies. ```sh pip install pgoutbox ``` -------------------------------- ### Set up LISTEN/NOTIFY listener for Outbox Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Wire up an optional LISTEN/NOTIFY hook for the Outbox. This example shows a psycopg2-based listener that polls the connection with select and invokes on_notify for each notification. Without this hook, dispatch still works correctly but only discovers new messages within poll_interval (default 1.0s). ```python import threading import select import psycopg2 listen_conn = psycopg2.connect(DATABASE_URL) listen_conn.autocommit = True def listen(channel, on_notify): cur = listen_conn.cursor() cur.execute(f"LISTEN {channel}") stop = threading.Event() def loop(): while not stop.is_set(): if select.select([listen_conn], [], [], 1.0) == ([], [], []): continue listen_conn.poll() while listen_conn.notifies: listen_conn.notifies.pop() on_notify() threading.Thread(target=loop, daemon=True).start() return stop.set # the "unlisten" callback outbox = Outbox(query=query, listen=listen) ``` -------------------------------- ### dispatch(handler, ...) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Starts a dispatch loop that processes messages using the provided handler. Supports batch_size, worker_id, on_error, poll_interval, and stop_event options. ```APIDOC ## dispatch(handler, ...) ### Description Starts a dispatch loop that processes messages using the provided handler. The loop polls for new messages and calls the handler for each message. ### Method N/A (Python method) ### Endpoint N/A ### Parameters #### Parameters - **handler** (callable) - Required - The handler function to process each message. - **batch_size** (int) - Optional - Default: `10`. Messages claimed per pass; at most one per distinct key. - **worker_id** (string) - Optional - Default: hostname + pid + random. Recorded on claimed rows (`locked_by`), for logs and manual inspection. - **on_error** (callable) - Optional - `(error, message) -> None`, called on every handler failure. - **poll_interval** (float) - Optional - Default: `1.0`. Fallback poll interval in seconds. - **stop_event** (threading.Event) - Optional - Stops the loop. ### Request Example ```python outbox.dispatch(handler, batch_size=20, poll_interval=0.5) ``` ### Response #### Success Response Runs indefinitely until stopped. #### Response Example N/A ``` -------------------------------- ### Create outbox schema with create_schema() or print schema_sql Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Use create_schema() for prototyping; it runs outbox.schema_sql idempotently. For production, print outbox.schema_sql and include the output in your own migration to ensure schema changes go through the same review and rollout process as the rest of the database. ```python outbox.create_schema() # runs outbox.schema_sql, idempotent (IF NOT EXISTS) print(outbox.schema_sql) # print it and put it in your own migration instead ``` -------------------------------- ### Concurrency demo output Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Output from running python examples/concurrency_demo.py against a real Postgres with six dispatchers. Shows 500/500 delivered, no duplicates, no concurrency or ordering violations, and ~190ms elapsed. ```text 6 concurrent workers, 500 messages across 25 keys delivered 500 / 500 duplicate deliveries 0 concurrency violations 0 (two workers holding the same key at once) ordering violations 0 / 25 keys elapsed ~190ms ``` -------------------------------- ### Outbox(query, ...) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Constructor for the Outbox class. Configures the outbox with required query function and optional settings. ```APIDOC ## Outbox(query, ...) ### Description Initializes an Outbox instance. The query function is required and used for dispatch/admin operations, not for enqueue. ### Method N/A (Python constructor) ### Endpoint N/A ### Parameters #### Constructor Parameters - **query** (callable) - Required - Runs SQL, returns rows. Used for dispatch/admin, not enqueue. - **table** (string) - Optional - Default: `outbox_messages`. Must be a bare identifier (`^[a-zA-Z_][a-zA-Z0-9_]*$`). - **channel** (string) - Optional - Default: `pg_outbox`. NOTIFY/LISTEN channel. Same identifier rule. - **max_attempts** (int) - Optional - Default: `5`. Default attempt budget; overridable per message. - **backoff** (callable) - Optional - Default: capped exponential. `(attempts: int) -> float`, delay in seconds before the next try. - **listen** (optional) - Optional - Optional LISTEN fast path. ### Request Example ```python outbox = Outbox(query, table='my_table', channel='my_channel', max_attempts=3) ``` ### Response #### Success Response Returns an Outbox instance. #### Response Example N/A ``` -------------------------------- ### SQLAlchemy query wrappers for Outbox (enqueue and dispatch) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md SQLAlchemy wrappers: use tx() for enqueue (joins the ORM Session's transaction via exec_driver_sql) and a separate dedicated AUTOCOMMIT connection for dispatch, because pgoutbox issues its own BEGIN/COMMIT that would conflict with SQLAlchemy's transaction tracking. ```python # SQLAlchemy — for enqueue, join the ORM Session's own transaction with # exec_driver_sql, which bypasses SQLAlchemy's bind-parameter parsing and # passes %s straight to the DBAPI driver (pgoutbox's paramstyle): def tx(sql, params=()): result = session.connection().exec_driver_sql(sql, params) return [dict(row._mapping) for row in result] if result.returns_rows else [] # For dispatch, use a *separate*, dedicated connection in autocommit/ # AUTOCOMMIT isolation, not the ORM Session -- pgoutbox issues its own # literal BEGIN/COMMIT (see "How claiming works"), which would otherwise # fight SQLAlchemy's own transaction tracking on the Session. dispatch_conn = engine.connect().execution_options(isolation_level="AUTOCOMMIT") def query(sql, params=()): result = dispatch_conn.exec_driver_sql(sql, params) return [dict(row._mapping) for row in result] if result.returns_rows else [] ``` -------------------------------- ### Using pgoutbox Outbox: enqueue and dispatch Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Shows the core outbox usage: create an Outbox with a query function, enqueue a message in the same transaction as business data, and dispatch it in a separate process. The query function is for dispatch/admin, not enqueue. ```python from pgoutbox import Outbox outbox = Outbox(query=my_query_fn) # this `query` is for dispatch/admin, not enqueue outbox.enqueue(tx, topic="order.created", payload={"id": order_id}) # same transaction outbox.dispatch(lambda msg: publish(msg)) # separate process ``` -------------------------------- ### asyncpg bridge for Outbox Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Asyncpg bridge for Outbox. Runs a persistent event loop in a background thread, translates %s to $1-style placeholders, and uses the simple query protocol for multi-statement text when no params are given. Requires careful event-loop handling; consider an async-first library instead. ```python # asyncpg -- async-only and its connections are bound to the event loop # that created them, which doesn't mix well with a plain, per-call # asyncio.run() (each call gets a *new* loop). The straightforward fix is # to run one persistent event loop, in a dedicated background thread, that # every query() call submits work to -- not just an asyncpg.connect() per # call, and not a fresh asyncio.run() reusing an old connection across # loops (that raises). asyncpg also needs native $1-style placeholders, # not %s, hence the translation. If you're this deep into asyncio already, # also weigh whether an async-first library fits better -- see # "Where this sits" above. import asyncio import re import threading import asyncpg def _to_dollar(sql: str) -> str: n = 0 def repl(_): nonlocal n n += 1 return f"${n}" return re.sub(r"%s", repl, sql) class AsyncpgBridge: def __init__(self, dsn: str) -> None: self._loop = asyncio.new_event_loop() self._conn: asyncpg.Connection | None = None threading.Thread(target=self._loop.run_forever, daemon=True).start() asyncio.run_coroutine_threadsafe(self._connect(dsn), self._loop).result() async def _connect(self, dsn: str) -> None: self._conn = await asyncpg.connect(dsn) def query(self, sql: str, params=()) -> list[dict]: async def run(): if not params: # simple query protocol: the only one of asyncpg's that # allows multi-statement text, which schema_sql needs. await self._conn.execute(sql) return [] rows = await self._conn.fetch(_to_dollar(sql), *params) return [dict(r) for r in rows] return asyncio.run_coroutine_threadsafe(run(), self._loop).result() bridge = AsyncpgBridge(DATABASE_URL) outbox = Outbox(query=bridge.query) ``` -------------------------------- ### enqueue(tx, *, topic, payload, key=None, max_attempts=None) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Enqueues a message into the outbox table. Requires a transaction, topic, and payload. Key and max_attempts are optional. ```APIDOC ## enqueue(tx, *, topic, payload, key=None, max_attempts=None) ### Description Enqueues a message into the outbox table. The payload must be JSON-serializable and is stored as jsonb. ### Method N/A (Python method) ### Endpoint N/A ### Parameters #### Parameters - **tx** (transaction) - Required - The database transaction. - **topic** (string) - Required - The topic for the message. - **payload** (JSON-serializable) - Required - The message payload, stored as jsonb. - **key** (string) - Optional - Default: `topic`. Ordering key. - **max_attempts** (int) - Optional - Default: outbox-level default. Per-message override. ### Request Example ```python outbox.enqueue(tx, topic='user.created', payload={'id': 123}) ``` ### Response #### Success Response No return value. #### Response Example N/A ``` -------------------------------- ### psycopg2 query wrapper for Outbox Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Ready-made wrapper for psycopg2. Uses a single connection with autocommit=True and RealDictCursor. The query function closes over the same conn to keep all calls on one session. ```python # psycopg2 import psycopg2 import psycopg2.extras conn = psycopg2.connect(DATABASE_URL) conn.autocommit = True def query(sql, params=()): with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: cur.execute(sql, params) return cur.fetchall() if cur.description else [] ``` -------------------------------- ### psycopg v3 query wrapper for Outbox Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Ready-made wrapper for psycopg v3. Uses a single connection with autocommit=True and dict_row cursor factory. The query function closes over the same conn to keep all calls on one session. ```python # psycopg (v3) import psycopg from psycopg.rows import dict_row conn = psycopg.connect(DATABASE_URL, autocommit=True) def query(sql, params=()): with conn.cursor(row_factory=dict_row) as cur: cur.execute(sql, params) return cur.fetchall() if cur.description else [] ``` -------------------------------- ### Claim batch with FOR UPDATE SKIP LOCKED (pgoutbox.sql.claim_sql) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Claim a batch of pending outbox messages, one per key, using a snapshot read to pick candidates and FOR UPDATE SKIP LOCKED to lock only those rows. Runs as the first statement of an explicit transaction that stays open until all claimed messages are resolved; the connection must be stable for the whole cycle. ```sql WITH candidates AS ( SELECT DISTINCT ON (key) id FROM outbox_messages WHERE status = 'pending' AND available_at <= now() ORDER BY key, id ), locked AS ( SELECT m.id FROM outbox_messages m JOIN candidates c ON c.id = m.id ORDER BY m.id LIMIT %s FOR UPDATE OF m SKIP LOCKED ) UPDATE outbox_messages m SET status = 'processing', attempts = m.attempts + 1, locked_by = %s FROM locked WHERE m.id = locked.id RETURNING m.*; ``` -------------------------------- ### create_schema Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Creates the outbox schema in the database. This is a convenience for prototyping; for production, use the schema_sql output in your own migration. ```APIDOC ## create_schema ### Description Runs outbox.schema_sql to create the outbox schema. Idempotent (IF NOT EXISTS). ### Method N/A (Python method) ### Endpoint N/A ### Parameters None ### Request Example ```python outbox.create_schema() ``` ### Response #### Success Response No return value. #### Response Example N/A ``` -------------------------------- ### Enqueue outbox message inside transaction Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Enqueue an outbox message inside the same transaction as your business write. The first argument to `enqueue` must be the same `query` your business-data write goes through; passing the exact `query` the `Outbox` was constructed with raises an error. The `key` defaults to `topic` and keeps same-order events ordered. ```python from pgoutbox import Outbox outbox = Outbox(query=query) # this `query` is for dispatch/admin, not enqueue with psycopg.connect(DATABASE_URL) as conn: with conn.cursor(row_factory=dict_row) as cur: def tx(sql, params=()): cur.execute(sql, params) return cur.fetchall() if cur.description else [] cur.execute("INSERT INTO orders (id, total) VALUES (%s, %s)", [order.id, order.total]) outbox.enqueue(tx, topic="order.created", payload={"id": order.id, "total": order.total}, key=str(order.id)) # same-order events stay ordered; defaults to `topic` conn.commit() ``` -------------------------------- ### schema_sql Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Provides the SQL schema definition for the outbox table. This is intended to be copied into your own migration scripts. ```APIDOC ## schema_sql ### Description Returns the SQL schema definition for the outbox table. Use this output in your own migration instead of calling create_schema. ### Method N/A (Python attribute) ### Endpoint N/A ### Parameters None ### Request Example ```python print(outbox.schema_sql) ``` ### Response #### Success Response - **schema_sql** (string) - The SQL schema definition. #### Response Example N/A ``` -------------------------------- ### Define the required query function for Outbox Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Defines the required query function signature for Outbox. The query must be bound to a stable connection/session, not a connection pool, because process_batch runs BEGIN, the claim, and message resolution as one transaction across multiple query() calls. ```python from typing import Any, Mapping, Sequence def query(sql: str, params: Sequence[Any] = ()) -> Sequence[Mapping[str, Any]]: ... # run sql with params bound to %s placeholders, return dict-like rows ``` -------------------------------- ### process_batch(handler, ...) Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Processes a single batch of messages using the provided handler. Supports batch_size, worker_id, and on_error options. ```APIDOC ## process_batch(handler, ...) ### Description Processes a single batch of messages using the provided handler. This is a one-shot operation, unlike dispatch which runs a loop. ### Method N/A (Python method) ### Endpoint N/A ### Parameters #### Parameters - **handler** (callable) - Required - The handler function to process each message. - **batch_size** (int) - Optional - Default: `10`. Messages claimed per pass; at most one per distinct key. - **worker_id** (string) - Optional - Default: hostname + pid + random. Recorded on claimed rows (`locked_by`), for logs and manual inspection. - **on_error** (callable) - Optional - `(error, message) -> None`, called on every handler failure. ### Request Example ```python outbox.process_batch(handler, batch_size=20) ``` ### Response #### Success Response No return value. #### Response Example N/A ``` -------------------------------- ### Dispatch with custom error handler Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Dispatch a message with a custom error handler. The handler is called when delivery fails, receiving the exception and the message. The default backoff is 0.5s * 2^(attempts-1) capped at 30s, and the default max_attempts is 5. After exhausting attempts, the message is moved to status = 'dead_letter' and remains in the table for manual inspection and requeueing. ```python outbox.dispatch(handler, on_error=lambda err, msg: logger.warning( "delivery failed", exc_info=err, extra={"message_id": msg.id, "attempt": msg.attempts} )) ``` -------------------------------- ### Dispatch outbox messages in separate process Source: https://github.com/agentscopes-java/pgoutbox/blob/main/README.md Dispatch messages in a separate process. `dispatch` runs until stopped via `stop_event: threading.Event`, claiming and delivering messages as they become available. It is a blocking call, so run it in its own thread or process; for cron or serverless environments, use `process_batch(handler)` instead. ```python outbox.dispatch(lambda msg: publish(msg.topic, msg.payload)) # msg.id is here too, for dedup — see below ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.