Search and contents

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_UP or Outcome.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() -> int sets every row still claimed back to pending (clearing claimed_at) and returns how many it reset. It is safe to call unconditionally when the single consumer loop per Node starts, because any claimed row found then is a previous crashed run's leftover.
  • release(entry_id) puts a claimed row back to pending to be claimed again; its attempt_count stays. It does nothing if the row is not claimed.
  • merge_payload(entry_id, patch) adds the keys of patch to a claimed row's payload, replacing any it already has, so a consumer can leave a note on a row across a failure or restart. It raises RowNotClaimedError if the row is not claimed (released, ended or gone).
  • mark_done(entry_id, *, attempts, payload=None) and mark_dead_lettered(entry_id, *, attempts, payload=None) resolve a row; a given payload replaces 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 the TriggerQueueEntry, or None if 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_name is the queue's physical table name, and drop_schema() drops the table (test teardown, not a production operation).

Pitfalls

  • Retry isn't queue-level re-claiming. attempt_count reflects Try/Catch's own internal retry attempts within one claim, not repeated claim cycles — once a row resolves to dead_lettered, nothing re-queues it as pending for a fresh claim. A dead-lettered row needing a genuine second chance (a fixed upstream service, a corrected payload) needs a new enqueue call with a new stable id, a deliberate decision, not automatic.
  • A genuine bug in step — anything other than UnresponsiveServiceFailure/PromptCausedFailure — propagates out of dispatch_claimed_entry uncaught, the same "any other exception is a genuine bug" stance engine/try_catch.py already takes. The row is left claimed, not resolved to dead_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 left claimed is not stuck forever: reclaim_orphaned_claims() (see "Other operations" below) runs when the Trigger Dispatch consumer loop starts (engine/node_runtime.py) and puts every claimed row back to pending, 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. NoReachablePeerError and EnvelopeVersionError are neither of the two exceptions above, so left as they are they take the Node down with them.
    • The MES order_release step, which reports the release to ERP, converts a NoReachablePeerError to UnresponsiveServiceFailure and an EnvelopeVersionError to its PermanentServiceFailure subtype.
    • 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 PermanentServiceFailure is 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_release row 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.
  • table_name isolation is a test convenience, not a production knob. Production code should use the default (TriggerQueue(), table trigger_queue) — a custom table_name exists so concurrent test runs (claim's SKIP LOCKED semantics need a clean, isolated set of pending rows) don't interfere with each other, the same reason engine/embedding_store.py's EmbeddingStore is parameterized per Node Type, for an unrelated underlying reason (pgvector column width).

Release: v0.11.0