Skip to content

feat: poll for pending messages whose NOTIFY was missed - #88

Merged
danfimov merged 10 commits into
mainfrom
feat/poll-pending
Nov 25, 2026
Merged

danfimov merged 10 commits into
mainfrom
feat/poll-pending

Conversation

@danfimov

@danfimov danfimov commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

PostgreSQL drops a NOTIFY nobody is listening to, so its message stayed pending forever. That happened to:

  • messages kicked while no worker was running, e.g. during a deploy;
  • messages kicked while a worker was reconnecting;
  • delayed messages whose producer exited before sending the delayed NOTIFY.

Adds poll_interval (default 5 s). A listening worker claims the oldest ready pending message right after it starts listening, after reconnecting, and every poll_interval.

  • The claim uses UPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1), so workers never claim the same row, and a backlog is drained without waiting between messages.
  • A delayed message is ready once created_at + delay has passed.
  • NOTIFY stays the fast path.
  • A partial index on pending rows is created on startup.

Commits:

  • one per driver;
  • isolate reconnect/keepalive tests in their own tables (a polling broker would otherwise claim rows left by other tests);
  • psycopg kick() no longer waits for the delay of a delayed message. This was deliberately left out of fix(psycopg): commit delayed message before sending its NOTIFY #76 until polling made it safe;
  • serialize schema setup. Worker processes start together, and concurrent CREATE TABLE/INDEX IF NOT EXISTS fail with a unique violation in pg_class/pg_type. The stress harness caught workers failing to start. The table race existed before; the index made it more likely. Setup now runs in one transaction that first takes pg_advisory_xact_lock.

Behaviour change after upgrading: rows already stuck in pending are executed right after the first start.

Stress harness:

fault lost before lost after
connection slots exhausted, LISTEN killed 111–197 0
producer restarted after 20 delayed kicks 20/20 (asyncpg, psqlpy) 0
LISTEN backends frozen 30 s (with keepalive) ~55 0
PostgreSQL restart 4–7 0

Note: until #90 is merged, startup needs ownership of the table for CREATE INDEX IF NOT EXISTS.

Part of a stack; review and merge bottom-up. Stress-harness numbers are from a local run: 4 drivers, ~250–550 kicks per scenario, 2 worker processes per driver.

Review follow-ups:

  • test: the concurrent-startup test uses small pools. Eight asyncpg brokers with the default 10-connection pool exhausted CI's max_connections.
  • fix (Greptile): a pending row whose delay label is not a plain number no longer breaks the poll query for every row behind it. Such a label counts as no delay, and an absurdly large one is never ready.
  • fix: kick() parses the delay label before inserting, so a malformed label no longer leaves a row that polling would execute.

@danfimov
danfimov added this pull request to stack #93 November 25, 2026 19:38
Comment thread src/taskiq_pg/psycopg/broker.py Resolved
@greptile-apps

greptile-apps Bot commented Nov 25, 2026

Copy link
Copy Markdown

security Security Review

This PR does not appear safe to merge because one pending row with a malformed delay label permanently stops a psycopg worker from receiving any message, and quietly disables recovery polling in the other drivers.

What was checked
  • The NOTIFY fast path still parses payloads with int() and claims rows atomically with status='pending', so a forged pg_notify can't crash a worker or grab someone else's message.
  • The new poll claim uses FOR UPDATE SKIP LOCKED on pending rows only, so two workers can't claim the same message twice.
  • The empty-string POLL_NOW sentinel can also be sent by a foreign pg_notify, but it only triggers a harmless poll.
  • Schema setup is serialized with pg_advisory_xact_lock and no untrusted value reaches the SQL text there.
  • poll_interval and the keepalive parameters are validated as positive, and no secrets or payloads are newly logged.

Findings

  • P1 One bad label kills the whole worker ▶
  • P2 Bad delay label blocks recovery polling

@greptile-apps

greptile-apps Bot commented Nov 25, 2026

Copy link
Copy Markdown

Comments Outside Diff

  • P2 security Bad delay label blocks recovery polling — src/taskiq_pg/asyncpg/queries.py:117

    A single pending row with a malformed delay label makes the poll claim query fail on every attempt, silently switching off the missed-NOTIFY recovery this PR adds. The query evaluates (labels->>'delay')::double precision for each pending row it scans in id order, so a row whose label isn't castable ("abc") or overflows make_interval (about 10^16 seconds) aborts the whole statement each time it runs. The identical query exists in aiopg/queries.py and psqlpy/queries.py. In those workers the outer except Exception in the listen loop swallows the error, so the row is never claimed by polling and no pending row with a higher id is either — including every message kicked while no worker was listening, the exact case this PR is meant to fix. Each worker also logs a full traceback every poll_interval (5 s by default). Example: a kick with labels={"delay": "abc"} commits the row before int() raises, so the poison row is already in the table; from then on all backlog recovery behind it is dead until someone deletes the row. Guard the cast (e.g. a validity check that falls back to 0) or bound the delay.

@danfimov
danfimov force-pushed the feat/poll-pending branch 3 times, most recently from 62c63b5 to 97fab98 Compare November 25, 2026 22:14
@danfimov
danfimov force-pushed the feat/poll-pending branch 2 times, most recently from 616a791 to d86ed7d Compare November 25, 2026 22:30
Base automatically changed from feat/listen-keepalive to main November 25, 2026 22:30
A NOTIFY nobody is listening to is lost, and its message stayed pending
forever: messages kicked while no worker was running (e.g. during a deploy)
or while a worker was reconnecting, and delayed messages whose producer
exited before sending the delayed NOTIFY.

Add poll_interval (default 5 s) to the brokers. The asyncpg worker claims the
oldest ready pending message (FOR UPDATE SKIP LOCKED, so workers never claim
the same row) right after it starts listening, after reconnecting and every
poll_interval, draining a backlog without waiting between messages. A
delayed message is ready once created_at + delay has passed. NOTIFY stays
the fast path. A partial index on pending messages is created on startup.
The notification loop now also yields a poll marker: right after start and
after every reconnect, then every poll_interval. The connection is read in
slices up to the next poll or keepalive query (notifies(timeout=...)), and
listen() drains every ready pending message when the marker arrives. A
database error while polling is logged and retried on the next poll instead
of ending listen().
Same as for asyncpg: the worker claims ready pending messages right after
it starts listening, after the listener is restored and every
poll_interval; a partial index on pending messages is created on startup.
Same as for the other brokers: the worker claims ready pending messages
right after it starts listening, after the LISTEN connection is restored and
every poll_interval; a partial index on pending messages is created on
startup.
With polling, a listening broker also claims pending rows left in the shared
taskiq_messages table by other tests, so tests that expect a specific
message got someone else's.
kick() with a delay label waited for the whole delay before returning,
because the delayed NOTIFY was the only way the message could reach a worker.
Workers now poll for messages whose delay has elapsed, so the NOTIFY is sent
from a background task like in the other brokers, and pending ones are
cancelled on shutdown.
Worker processes of one deployment start together, and concurrent
CREATE TABLE / CREATE INDEX IF NOT EXISTS on a new table fail with a unique
violation in the system catalogs, so some of them failed to start (taskiq
restarted them). The race existed for the table before; the pending index
made it more likely.

Create the table and its indexes in one transaction that first takes an
advisory lock derived from the table name, so brokers wait for each other.
Eight asyncpg brokers with the default pool (10 connections each) exhausted the CI server's connection slots.
The poll query cast every pending row's delay label to a number, so one label that could not be cast
("abc") or overflowed make_interval made the query fail on every poll. Polling stopped for all messages
behind that row, and a psycopg worker stopped receiving messages at all.
A label that is not a plain non-negative number now counts as no delay; an absurdly large one is never ready.
kick() inserted the message before int(delay) raised, leaving a row the caller believed was not sent;
polling would now execute it.
@danfimov danfimov self-assigned this Nov 25, 2026
@danfimov
danfimov merged commit 81c49d9 into main Nov 25, 2026
12 checks passed
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.

1 participant