Trigger Dispatch Queue: enqueue, claim, resolve
How engine/trigger_queue.py's TriggerQueue and dispatch_claimed_entry implement the
Trigger Dispatch Queue.
A trigger_queue row is the mechanism between a Trigger firing and its Task actually running: one
row per fired Trigger instance, a trigger_type column (so a new Trigger type needs no schema
change), and a status — pending → claimed → done, or claimed → dead_lettered.
1. Enqueue
import uuid
from engine.trigger_queue import TriggerQueue, TriggerQueueEntry
queue = TriggerQueue() # production default table name: trigger_queue
queue.ensure_schema()
entry = TriggerQueueEntry(
id=stable_id, # the same idempotent-ID shape Milestone delivery guarantee uses
trigger_type="order_release",
payload=canonicalized_payload, # the Data Transformation Layer's already-canonicalized output
)
inserted = queue.enqueue(entry) # True if newly inserted, False if id already existed (a no-op)
id must be stable across redelivery, not freshly generated per call — enqueue is
idempotent (ON CONFLICT (id) DO NOTHING), so redelivering the same real-world Trigger instance
with its own already-used id is a silent no-op rather than a second row or an error. This is what
lets a duplicate/late-arriving event route to Reconciliation instead of creating a
duplicate Task run.
2. Claim
claimed = queue.claim() # TriggerQueueEntry | None
claim() uses SELECT ... FOR UPDATE SKIP LOCKED — the standard Postgres job-queue pattern.
Concurrent claimers never block on a row someone else is claiming and never claim the same row
twice; a claimer just skips straight to the next unlocked pending row. Returns None once nothing
is pending. A claim increments attempt_count and sets claimed_at, but leaves the row claimed
— it's dispatch_claimed_entry (below) that resolves it to done or dead_lettered.
3. Dispatch a claimed row through Try/Catch, logged via Activity Log
from engine.task_activity_log import TaskRunContext
from engine.trigger_queue import dispatch_claimed_entry
from engine.try_catch import RetryPolicy
context = TaskRunContext(
node_type="MES",
node_instance_id="mes-line-3",
trigger=claimed.trigger_type,
task_type="ingestion-time classification",
)
result = dispatch_claimed_entry(
queue,
activity_log,
claimed,
step=process_order_release, # Callable[[dict], Any] - the actual work
context=context,
retry=RetryPolicy(max_attempts=3),
repair=None, # only meaningful for a prompt-caused failure - see engine/try_catch.py
)
step is a Try/Catch-wrapped custom function call (docs/operations/orchestration-engine.md) —
it signals which of Try/Catch's two failure classes applies by raising
UnresponsiveServiceFailure or PromptCausedFailure. dispatch_claimed_entry hands step to
log_try_catch_task, which wraps it in a TryCatch, wraps that as a trivial one-step Prompt
Chaining Task, and runs it through log_task_execution
(docs/operations/wiring-task-execution-to-activity-log.md) — reusing that
logging rather than inventing a second way to write an ActivityLogEntry. The logged
entry's outcome is the Try/Catch Outcome value (succeeded/gave_up/exhausted), and
reference_ids always carries {"trigger_queue_id": str(entry.id)}.
result.outcome decides how the row resolves:
Outcome.SUCCEEDED→queue.mark_done(entry.id, attempts=result.attempts)Outcome.GAVE_UPorOutcome.EXHAUSTED→queue.mark_dead_lettered(entry.id, attempts=result.attempts)
Both are handled inside dispatch_claimed_entry itself — a caller never needs to call
mark_done/mark_dead_lettered directly for the normal path.
Other operations
The rest of TriggerQueue's surface (the class docstring marks these as internal to the public
engine.public surface, which covers only the constructor and ensure_schema):
reclaim_orphaned_claims() -> intsets every row stillclaimedback topending(clearingclaimed_at) and returns how many it reset. It is safe to call unconditionally when the single consumer loop per Node starts, because anyclaimedrow found then is a previous crashed run's leftover.release(entry_id)puts aclaimedrow back topendingto be claimed again; itsattempt_countstays. It does nothing if the row is notclaimed.merge_payload(entry_id, patch)adds the keys ofpatchto aclaimedrow's payload, replacing any it already has, so a consumer can leave a note on a row across a failure or restart. It raisesRowNotClaimedErrorif the row is notclaimed(released, ended or gone).mark_done(entry_id, *, attempts, payload=None)andmark_dead_lettered(entry_id, *, attempts, payload=None)resolve a row; a givenpayloadreplaces the row's payload in the same statement, for a queue whose payload holds data that must not outlive the work.get(entry_id)returns theTriggerQueueEntry, orNoneif there is no such row.held_ids(entry_ids)returns which of the ids the queue holds, in any status, in one query. The queue never deletes a row, so a producer that sees the same source row more than once can ask this of a batch before doing any work for a row.table_nameis the queue's physical table name, anddrop_schema()drops the table (test teardown, not a production operation).
Pitfalls
- Retry isn't queue-level re-claiming.
attempt_countreflects Try/Catch's own internal retry attempts within one claim, not repeated claim cycles — once a row resolves todead_lettered, nothing re-queues it aspendingfor a fresh claim. A dead-lettered row needing a genuine second chance (a fixed upstream service, a corrected payload) needs a newenqueuecall with a new stableid, a deliberate decision, not automatic. - A genuine bug in
step— anything other thanUnresponsiveServiceFailure/PromptCausedFailure— propagates out ofdispatch_claimed_entryuncaught, the same "any other exception is a genuine bug" stanceengine/try_catch.pyalready takes. The row is leftclaimed, not resolved todead_lettered— a stuck-claimed row from an unexpected exception is a different failure mode than an exhausted, well-understood retry budget, and conflating the two by silently dead-lettering on any exception would mask real bugs as routine failures. A row leftclaimedis not stuck forever:reclaim_orphaned_claims()(see "Other operations" below) runs when the Trigger Dispatch consumer loop starts (engine/node_runtime.py) and puts everyclaimedrow back topending, so after a Node restart the row is claimed and run again, bounded by that dispatch's own Try/Catch retry policy. - A peer that cannot be reached is not a bug, so a step that asks one converts the failure.
NoReachablePeerErrorandEnvelopeVersionErrorare neither of the two exceptions above, so left as they are they take the Node down with them.- The MES
order_releasestep, which reports the release to ERP, converts aNoReachablePeerErrortoUnresponsiveServiceFailureand anEnvelopeVersionErrorto itsPermanentServiceFailuresubtype. - Either way the row is dead-lettered (
gave_up), and the Node keeps running and answering its peers. The failure's class name leads the logged reason. - Retries. An unreachable ERP is tried three times first. A
PermanentServiceFailureis not retried, because a peer in an incompatible version stays that way, so a mismatch is dead-lettered on its first attempt. - Timing. The three attempts at an unreachable ERP follow one another at once, so they help against a failed call but not against a peer that is down. The row is dead-lettered within one health-check timeout (5 seconds by default, the time the query spends looking again before it gives up). A peer that only started since the last scheduled rescan is found by that look-again, and the report goes out.
- What a dead-lettered row means. The reconciliation and the First Article check ran before the report and have their own Activity Log entries. A dead-lettered
order_releaserow therefore means only that the outward report is missing. The dead-lettered row is where a release ERP never heard about shows. - Re-sending. Nothing sends it again (see the first pitfall). Entering the row again with a new id repeats the report and also the local work, which is safe to repeat.
- The MES
table_nameisolation is a test convenience, not a production knob. Production code should use the default (TriggerQueue(), tabletrigger_queue) — a customtable_nameexists so concurrent test runs (claim'sSKIP LOCKEDsemantics need a clean, isolated set of pending rows) don't interfere with each other, the same reasonengine/embedding_store.py'sEmbeddingStoreis parameterized per Node Type, for an unrelated underlying reason (pgvector column width).
Release: v0.11.0