Workflow execution system
The workflow execution system turns a document-processing request into durable asynchronous work. It records the run, sends coordination work through the queue, distributes files to workers, and combines their outcomes into one final execution state.
Execution lifecycle
An execution is the durable record for one workflow run. It connects the workflow to its input and tracks progress, errors, file outcomes, dispatch state, and terminal state. Parent progress stays separate from file progress so the system can report totals while workers finish at different times.
flowchart LR
R[Workflow request] --> E[Execution record]
E --> O[Orchestration task]
O --> B[File batches]
B --> W[File workers]
W --> F[Fan-in barrier]
F --> C[Final callback]
C --> S[Final execution state]
References: backend/…/execution.py• L122-227 backend/…/enums.py• L1-8 backend/…/workflow_helper.py• L151-183
Request dispatch
The backend creates the execution before it sends the orchestration task. The PostgreSQL-backed queue stores the task until a consumer claims it. The execution records a positive dispatch time as soon as enqueue succeeds, while transport-specific handles remain separate. This lets recovery distinguish accepted work from work that never reached the queue, even when later handle bookkeeping fails.
Queue messages carry the task name, arguments, organization context, priority, and optional fairness data. The producer converts values to JSON-safe forms before storage. A reply key requests a result row. A success or error continuation requests follow-up work. These are different completion paths and cannot be combined.
Delayed work becomes ready after its requested time when the queue reaper promotes it. A dispatch error reaches the caller rather than silently switching to another transport.
References: backend/…/producer.py• L76-221 backend/…/workflow_helper.py• L543-799 backend/…/execution.py• L436-519 backend/…/execution.py• L138-227
Undispatched execution recovery
An execution can exist before its orchestration message reaches the queue. The undispatched sweep finds old pending records without positive dispatch evidence and marks them as errors with a retry message. This path is separate from queue recovery, which handles work that reached the queue but stopped making progress.
References: backend/…/undispatched_sweep.py• L1-37 backend/…/undispatched_sweep.py• L161-302 backend/…/execution.py• L209-227
Orchestrator handoff
The async_execute_bin task moves work from request handling to workflow coordination. It restores organization context, loads the workflow and execution, validates the run, and prepares file batches.
PostgreSQL orchestration uses one durable claim per execution. The first delivery performs the fan-out. A duplicate delivery is a no-op. A failed orchestration releases the claim so a retry can run, while a successful claim blocks late redelivery from starting a second fan-out. Scheduled pipeline runs use the same handoff after the scheduler creates an execution.
References: backend/…/workflow_helper.py• L801-930 backend/…/models.py• L512-571 workers/…/pg_barrier.py• L406-509 workers/…/tasks.py• L160-223
File processing fan-out
File fan-out separates workflow coordination from document work. The orchestrator marks the parent active, groups files into batches, and sends batch tasks to file-processing workers. A fan-in barrier waits for each batch outcome before it releases the final callback.
Each batch carries the parent execution ID, organization context, file data, and workflow settings. The execution ID and batch index connect the parent record to file results, duplicate protection, barrier state, and callback work.
The following flow shows how batch work returns to one parent result.
sequenceDiagram
participant O as Orchestrator
participant Q as PostgreSQL queue
participant W as File workers
participant B as Fan-in barrier
participant C as Final callback
participant S as Status store
O->>S: Mark execution active
O->>B: Arm barrier for batches
O->>Q: Enqueue batch tasks
Q->>W: Deliver batch context
W-->>B: Report batch result
B->>C: Release after all batches
C->>S: Save counts and terminal status
The queue transports work. The barrier coordinates completion. Barrier state also keeps organization context and recent progress data so stalled work can be found and reported.
References: backend/…/workflow_helper.py• L151-256 backend/…/models.py• L198-319 workers/…/__init__.py• L27-35 workers/…/pg_barrier.py• L553-751
Input acceptance
Input acceptance decides whether a document can enter processing. The system checks upload bytes rather than trusting the declared request type. Unsupported files stay out of storage and dispatch, while each rejection becomes a terminal file error that remains visible in parent counts.
Connector workers apply the same supported-type rule when they copy source files into the execution volume. This keeps API and connector inputs on the same acceptance path.
References: backend/…/source.py• L1206-1251 backend/…/source.py• L1296-1459 workers/…/file_types.py• L16-71 workers/…/service.py• L1211-1251
Worker execution
The file-processing worker owns the document-level run. It loads execution context, checks prior work, prepares the input, invokes the workflow operation, and stores a file result. Progress records let a retry reuse completed stages instead of repeating tool or destination work.
Long executor work uses request-reply over the PostgreSQL queue. The file worker sends execution context with a reply key. The executor writes a result row, and the caller waits for it for a bounded time. A file-level failure remains attached to that file so other files in the batch can still finish.
Structure-tool work now sends the regular document path as one structure_pipeline request. The executor owns the extract, summarize, index, and answer stages inside that request, which keeps the file-processing worker available while the document runs. Agentic projects use a separate extraction request, while mixed projects combine agentic table results with the regular pipeline result before file output is saved.
The structure-tool path preserves one result contract for regular and agentic work. It writes the document result to workflow storage and records metadata for downstream destination handling. Agentic table settings can carry extraction priority, raw extraction, engine choice, highlight data, and per-prompt metrics into the combined result.
The shared executor supports extraction and indexing operations. Image-mode extraction resolves the limits of the LLMs that will read the converted pages before conversion starts. If supplied adapter settings cannot be resolved, the operation fails closed and does not convert or charge pages. With no adapter IDs, or when model-aware limits are disabled, it uses the fixed safety cap. Multiple LLM limits use the strictest applicable limit.
Indexing turns extracted text into chunks and stores them in a vector store. It can reuse an existing document index or replace it when reindexing is requested. These executor results flow back through the same file and batch completion path as extraction results.
References: workers/…/service.py• L103-248 workers/…/service.py• L275-477 workers/…/structure_tool_task.py• L293-384 workers/…/structure_tool_task.py• L432-458 workers/…/structure_tool_task.py• L552-727 workers/…/structure_tool_task.py• L827-932 workers/…/executor_rpc.py• L43-108 workers/…/legacy_executor.py• L196-299 workers/…/image_limits.py• L107-170 workers/…/index.py• L92-169 workers/…/test_structure_tool_pipeline.py• L157-270 workers/…/test_structure_tool_pipeline.py• L1227-1662 workers/…/test_extract_image_limits.py• L89-209
Batch completion
Each batch produces a stable summary of file outcomes. The summary includes counts and per-file results, including files rejected before dispatch. The callback can therefore update the parent without running documents again.
Batch claims make a batch decrement the barrier at most once. A redelivered batch skips work that was already claimed. When the last batch completes, the barrier releases the callback.
References: backend/…/models.py• L198-256 workers/…/tasks.py• L1760-1859 workers/…/worker_patterns.py• L98-117 backend/…/execution.py• L568-607
Status and result coordination
The database is the durable source for execution status. A short-lived cache supports fast active reads, but recovery and later reads can rebuild the view from database records. Workers update parent and file records through the internal API with organization context attached.
Status and file-count updates are committed together when a worker or recovery path finalizes a run. A row lock serializes status writers without blocking child file-row inserts. The guarded path uses the persisted queue marker and status under that lock, so a stale object cannot route a PostgreSQL execution through the wrong update path or overwrite newer counters. The guard protects COMPLETED and STOPPED from stale updates while still allowing a later callback to correct an earlier ERROR.
Terminal updates also release an API deployment rate-limit slot only after the surrounding transaction commits. This keeps capacity aligned with the durable execution state when a final status write rolls back.
flowchart LR
W[Worker or callback] --> I[Internal API client]
I --> L[Execution row lock]
L --> D[Execution and file records]
D --> C[Active status cache]
D --> R[Queue reaper]
R --> I
References: backend/…/execution.py• L399-623 backend/…/internal_views.py• L518-639 backend/…/internal_views.py• L799-873 backend/…/internal_views.py• L958-1013
Execution list status
Execution list views turn run outcomes into a stable row status for pipelines and API deployments. They use the latest finished run, ignore runs still in progress, and let an inactive row override its run result. A completed run with both successful and failed files is shown as partial_success; a completed run with no successful files and a stopped run are shown as error.
The list and its aggregate endpoint use the same filters and status rules. They report total rows, counts by status, and active rows whose last five finished runs all ended in ERROR. The failing-row list is capped for response size, but its count covers all matching rows and is ordered by the newest failure.
References: backend/…/list_aggregates.py• L1-11 backend/…/list_aggregates.py• L45-206 backend/…/failing_streaks.py• L1-13 backend/…/list_aggregate_serializers.py• L16-100 backend/…/test_list_aggregates.py• L41-173
Finalization recovery
The final callback turns batch outcomes into the parent result. If a terminal status write fails on the PostgreSQL path, the callback remains a failed delivery so the queue can retry it. The status guard prevents a late error or stale callback from replacing a protected COMPLETED or STOPPED result.
The reaper provides a second safety net. It finds dispatched executions whose files are terminal while the parent is not. It excludes work that never dispatched or still has active files. It then recomputes the terminal outcome from file results and can cascade the recovered state to unfinished file rows.
References: backend/…/models.py• L259-319 workers/…/pg_barrier.py• L42-62 backend/…/internal_views.py• L635-933 workers/…/reaper.py• L1-220 backend/…/execution.py• L399-602
Asynchronous waiting
An asynchronous request can return at once or wait for a bounded period for a terminal state. During a wait, the caller polls execution status and reads the cached result if the run finishes. The request releases idle database connections between polls. Once the transport accepts work, the worker path owns final state; later bookkeeping errors return the current in-progress view instead of turning that work into a false failure.
References: backend/…/workflow_helper.py• L492-577 backend/…/workflow_helper.py• L621-799 backend/…/workflow_helper.py• L1030-1063 backend/…/execution.py• L458-519 backend/…/test_execute_workflow_async_wait.py• L25-67
Result acknowledgement
The result store keeps executor results until the caller reads them. A successful read then acknowledges and removes the row. The acknowledgement updates only its own durable field and then clears the cached result and active execution view, so it cannot publish stale status or counters. A timeout does not remove the result because the executor may still write a late result.
Workflow API results follow the same read-before-clear order. Durable execution status remains available after a result payload is consumed.
References: backend/…/models.py• L462-509 workers/…/executor_rpc.py• L77-95 workers/…/test_executor_rpc.py• L254-301 backend/…/workflow_helper.py• L401-466
Related worker systems
Worker operations describe task entry points and document actions. Queue-backed worker orchestration describes consumers, scheduling, recovery, barriers, leases, and result signals. Backend workflow management describes the workflow and execution controls around this system. Agent key-value extraction and the MCP server describe adjacent product flows that can use workflow execution. Read these pages for the adjacent views:
- Worker operations and execution plugins
- Queue-backed worker orchestration
- Backend workflow management
- Agent key-value extraction
- MCP server
Change checklist
When these files or sections are changed, remember to consider these:
- Keep execution IDs and batch indexes in batch, claim, barrier, and callback data. These fields join parent results and block duplicate completion.
- Keep the positive dispatch marker separate from transport handles. Recovery must distinguish accepted work from work that never reached a transport.
- Keep the dispatch marker write immediately after enqueue and before handle bookkeeping. A post-dispatch bookkeeping error must not make a live execution look undispatched.
- Keep the producer payload aligned with the worker consumer contract. A stored task still needs the expected name and fields.
- Keep reply keys separate from continuations. They use different result and acknowledgement paths.
- Keep the executor dispatcher contract aligned with every worker caller. Structure-tool requests use the supported dispatch arguments and send the full regular pipeline as one operation.
- Keep regular and agentic structure-tool results joined by prompt name before writing the file result. Mixed workflows must retain both result types and their optional raw, highlight, and metric data.
- Keep barrier counts, batch claims, and callback release atomic. A repeated decrement can release incomplete results.
- Keep image-mode LLM adapter IDs aligned with the workflow context. Missing or stale IDs can select a fixed cap or stop extraction before conversion.
- Keep image-limit failures machine-readable and free of adapter metadata. The worker uses their status and message to decide whether retry can help.
- Keep indexing identity tied to the file and adapter settings. A change in source or processing settings must not reuse the wrong vector index.
- Keep terminal status, file counts, and recovery cascades in one transaction. A parent can otherwise report a final state with incomplete counts.
- Keep PostgreSQL status routing based on the locked persisted queue marker. A stale in-memory marker can bypass the terminal-state guard or overwrite newer fields.
- Release API deployment rate-limit capacity only after the transaction that stores terminal state commits. Otherwise a rollback can free a slot for work that is still active.
- Keep list status rules aligned with terminal execution status and file counts. A mixed completed run must remain
partial_successin both the list and aggregate views. - Keep the failing-row rule limited to active rows and five finished
ERRORruns. A stopped run must break the streak even though it counts aserrorin row status. - Keep aggregate totals, status counts, failing counts, and capped failing rows based on the same filtered row set. Otherwise the list and its summary can disagree.
- Keep reaper liveness with delayed delivery and finalization recovery. Scheduled or stranded work cannot recover without it.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No PostgreSQL queue consumer is running | Messages remain stored and work does not start | Run the required workflow and file worker roles. |
| A scheduled message has no live reaper | Due work remains scheduled | Treat reaper liveness as part of delayed delivery. |
| A batch loses its execution ID or index | Results cannot join the parent or duplicate work can decrement the barrier twice | Carry both fields through dispatch and claims. |
| A structure-tool caller sends an unsupported executor argument | File processing fails before document extraction starts | Keep dispatcher calls aligned with the executor RPC contract and test the real call signature. |
| A mixed structure workflow drops one result branch | The file completes with missing fields or review data | Merge regular and agentic results by prompt name before writing output. |
| An unsupported upload is accepted from its declared type | Invalid bytes reach storage and fail later | Validate the file bytes before storage and record a terminal file error. |
| Image adapter limits cannot be resolved | Pages are not converted and the file fails before extraction | Keep the fail-closed policy and preserve its retry guidance. |
| Image-limit errors expose adapter metadata | Secrets or private configuration can reach logs or users | Report only safe error types and fixed guidance. |
| A limit policy is built for text mode | An unnecessary adapter lookup can fail a valid text extraction | Resolve image limits only for image-mode extraction. |
| An existing vector index is reused for changed inputs | Search can return stale document content | Include file and adapter settings in the index identity and honor reindex requests. |
| Dispatch bookkeeping fails after the queue accepts work | A live execution can be marked as never dispatched or the caller can report a false error | Stamp positive dispatch evidence before handle bookkeeping and keep post-dispatch failures non-terminal. |
| The final status write is swallowed | The callback is acknowledged while the parent remains active | Re-raise the finalization error for queue redelivery. |
| A stale worker updates a protected terminal execution | A final run can reopen or change state | Lock the execution row and protect COMPLETED and STOPPED. |
| A stale execution object writes through the wrong transport path | A PostgreSQL run can lose its queue marker or bypass the terminal guard | Route status updates from the locked persisted marker and use field-scoped writes. |
| A terminal transaction rolls back after rate-limit release | The deployment gains capacity while its execution remains active | Release the slot with the outer transaction's commit hook. |
| A completed mixed-result run is treated as success | List cards and aggregate counts hide file failures | Derive partial_success from both successful and failed file counts. |
| A stopped run is included in the failing streak | The list marks an intentional stop as a repeated failure | Count only the last five finished ERROR runs for active rows. |
| Aggregate data uses a different filter scope than the list | Row counts and failing counts do not match the visible list | Build both views from the same filtered row set. |
| A result row is removed before it is read | The caller has status but no result payload | Read first, then acknowledge. |
Key files
| File | Why to read it |
|---|---|
| backend/…/workflow_helper.py | Shows request dispatch, positive dispatch evidence, orchestration handoff, fan-out, waiting, and result retrieval. |
| backend/…/execution.py | Connects workflow execution helpers to durable status changes and terminal counters. |
| backend/…/execution.py | Defines the durable execution record, transport markers, guarded status changes, and terminal capacity release. |
| backend/…/producer.py | Defines the queue message contract and dispatch boundary. |
| backend/…/models.py | Defines claims, batch deduplication, barriers, and result rows. |
| workers/…/pg_barrier.py | Shows fan-in, callback release, progress tracking, and duplicate guards. |
| workers/…/executor_rpc.py | Shows request-reply execution and bounded result polling. |
| workers/…/service.py | Shows per-file resume, duplicate protection, workflow execution, and result tracking. |
| workers/…/structure_tool_task.py | Shows how regular and agentic structure work is dispatched and combined into file output. |
| workers/…/test_structure_tool_pipeline.py | Shows the executor request contract and the result guarantees for regular, mixed, and agentic flows. |
| workers/…/legacy_executor.py | Shows how executor operations are routed and how extraction receives image limits. |
| workers/…/image_limits.py | Defines the safety policy for image-mode extraction before billed conversion. |
| workers/…/index.py | Shows the document-to-vector-index product flow. |
| backend/…/internal_views.py | Shows status coordination, file counts, terminal updates, and recovery. |
| backend/…/list_aggregates.py | Defines the shared row status, list filters, aggregate counts, and failing-row summary. |
| backend/…/failing_streaks.py | Defines when an active pipeline or API deployment is considered repeatedly failing. |
| backend/…/list_aggregate_serializers.py | Defines the list filter and aggregate response contract. |
| workers/…/reaper.py | Shows delayed-message promotion and recovery of stalled work. |
| workers/…/tasks.py | Shows batch completion and file-result aggregation. |
| workers/…/__init__.py | Shows queue registration for the worker path. |