Worker operations and execution plugins
Workers turn workflow and IDE requests into asynchronous work. A shared entrypoint builds a worker for a selected role, while task modules handle workflow coordination, file batches, callbacks, notifications, logs, and extraction operations. The design keeps long-running work outside the API process and lets new execution strategies plug into stable request and result contracts.
Worker runtime
The worker runtime consumes named queues and reports status through internal APIs, result stores, and log channels. workers/worker.py is the common entrypoint: it selects a worker role, builds its app, loads its tasks, starts shared infrastructure, and exports the app for the worker command. Some transport paths use dedicated poll-loop processes instead of a Celery worker while keeping the same task contracts.
The runtime supports these main roles:
| Role | Main responsibility |
|---|---|
| General | Start non-API workflow runs and discover source files |
| API deployment | Start API workflow runs and prepare cached or incoming files |
| File processing | Process file batches and produce per-batch results |
| Callback | Combine batch results and finish execution state |
| Executor | Run extraction operations through registered execution strategies |
| IDE callback | Persist Prompt Studio results and notify the browser |
| Notification | Deliver status notifications through provider types |
| Log consumer | Store execution logs and emit live browser events |
| Scheduler | Create scheduled workflow runs and maintain dashboard metrics |
The worker type maps to its queue set and task routes through workers/…/registry.py. The builder applies the registry data with broker and result settings from WorkerConfig, so a worker role has one source for its queue, health, and task-routing behavior. Launch scripts can also start PostgreSQL queue roles or a Redis log consumer when those paths are enabled. The PostgreSQL consumer imports the selected source worker in each child before polling, so tasks remain available even though they run in-process. See Workflow execution system for the wider dispatch and completion model, and Queue-backed worker orchestration for queue transport, barriers, and recovery.
Startup sequence
Startup resolves the worker identity before task imports. It then configures logging, creates the worker app, installs process hooks, initializes shared clients, loads task registrations, and checks that the app has work to process.
The sequence below shows the runtime boundary between process setup and task execution.
flowchart TD
A[Worker type] --> B[Worker builder]
B --> C[App and routing]
C --> D[Process safety hooks]
D --> E[Shared infrastructure]
E --> F[Task registration]
F --> G[Registered task check]
G --> H[Celery worker or PG consumer]
H --> I[Graceful completion and shutdown]
The entrypoint keeps broker heartbeats active during warm shutdown. This gives in-flight tasks time to finish instead of allowing the broker to requeue them while the process is still being stopped. Forked child processes ignore the parent signal handlers and create process-safe client state after the fork. Dedicated PostgreSQL consumers follow the same shutdown goal: the parent signals all children, waits within one shared drain window, and kills only children that do not finish.
The PostgreSQL supervisor owns fleet health. It reports stale when the oldest child stops polling or when a child crash-loops. Readiness stays false until every child has completed bootstrap. An optional child watchdog can kill one stale child and let its lease expire for redelivery while the other children continue.
References: workers/worker.py• L34-55 workers/worker.py• L59-133 workers/worker.py• L338-442 workers/worker.py• L445-541 workers/…/registry.py• L27-74 workers/…/registry.py• L209-326 workers/…/consumer.py• L1078-1137 workers/…/supervisor.py• L353-398 workers/…/supervisor.py• L485-540 workers/…/supervisor.py• L543-607
Worker configuration
Worker configuration joins role-level defaults with deployment settings. WorkerBuilder turns the selected registry entry into worker settings, while WorkerConfig builds the broker, result backend, and cache connections from environment values.
Configuration precedence for worker settings is:
- Explicit command-line values.
- A worker-specific environment value.
- A global
CELERY_...environment value. - The worker default.
The registry supplies queues and route patterns. The configuration model supplies common behavior such as late acknowledgements, task time limits, retries, serialization, scaling, and monitoring events. Health checks use a worker-specific port and can include checks registered for that role.
The PostgreSQL consumer uses its own typed configuration boundary. Queue names, batch size, lease and visibility limits, poll backoff, and poison-message limits are read by the same builder for both the single-process consumer and supervisor children. Invalid values fail during construction instead of after the poll loop starts.
References: workers/…/builder.py• L24-85 workers/…/builder.py• L87-139 workers/…/worker_models.py• L81-133 workers/…/worker_models.py• L287-452 workers/…/worker_config.py• L101-187 workers/…/worker_config.py• L311-379 workers/…/consumer.py• L1170-1203 workers/…/supervisor.py• L99-198
Workflow task operations
Workflow tasks separate run coordination from file work. The general and API deployment workers fetch execution context through InternalAPIClient, validate workflow tools, set the execution to EXECUTING, and send file batches to the file-processing worker. They return after dispatch rather than waiting for every file to finish.
The normal workflow path is:
sequenceDiagram
participant S as Scheduler or API caller
participant W as General/API worker
participant F as File-processing worker
participant C as Callback worker
participant B as Backend API
S->>W: Start execution
W->>B: Fetch context and validate tools
W->>W: Discover, filter, and batch files
W->>F: Dispatch file batches
F->>F: Process each file
F-->>C: Batch result
C->>B: Set execution and pipeline status
C-->>S: Completion notification and result state
General workflows discover files through the configured source connector. Source discovery applies file-pattern, history, active-file, and count limits before batches are made. API workflows can reuse successful file history while still using the common file-processing path, so the final response remains complete. Scheduled runs create an execution first and then select the transport for downstream dispatch.
The task boundary uses serialized data models. Organization, workflow, execution, pipeline, file, manual-review, and transport values travel in the task payload. This lets workers use internal APIs instead of direct backend ORM access and keeps API and non-API execution paths aligned.
The scheduler also registers thin dashboard metric tasks. These tasks keep the names used by scheduled jobs and ask the backend to run aggregation or retention cleanup. The worker stays focused on dispatch while the backend performs database-heavy work.
References: workers/…/tasks.py• L194-415 workers/…/tasks.py• L599-711 workers/…/tasks.py• L719-910 workers/…/tasks.py• L143-285 workers/…/tasks.py• L406-485 workers/…/tasks.py• L487-714 workers/…/tasks.py• L13-26 workers/…/tasks.py• L115-231 workers/…/dashboard_metrics_tasks.py• L35-126
File processing
The file-processing worker turns one batch payload into typed file results. It validates the batch, builds an organization-scoped execution context, pre-creates file execution records, processes each eligible file, and returns counts and timing for the callback worker.
Each file follows the same broad path:
- Parse the batch and validate its execution identity.
- Load workflow state and establish organization and log context.
- Skip stale terminal executions on the PostgreSQL queue path.
- Pre-create file execution records to prevent duplicate work.
- Check active-file and file-history state.
- Run the file through the workflow tool.
- Record success or failure and publish file progress.
- Compile a serializable batch result.
The worker supports files that need manual review. Manual-review decisions are attached to file data before processing, so each file can go to the review path or the destination path without changing the batch contract. Already completed files count in the total but are not failures. Active duplicates fail the current run. A duplicate skip does not update the database because another execution owns the file.
structure_tool_task.py is the bridge from file processing into executor operations. It loads either Prompt Studio or agentic tool metadata, applies profile values, and routes regular prompts and agentic table prompts to the executor worker through the PostgreSQL executor RPC. Regular prompts use one compound structure-pipeline request. Agentic prompts can run beside them or as an agentic-only path. The task merges their output and metrics, then writes the JSON result and metadata layout that destination processing expects.
References: workers/…/tasks.py• L321-436 workers/…/tasks.py• L439-634 workers/…/tasks.py• L637-907 workers/…/tasks.py• L910-1083 workers/…/tasks.py• L1127-1230 workers/…/structure_tool_task.py• L293-321 workers/…/structure_tool_task.py• L363-455 workers/…/structure_tool_task.py• L552-727 workers/…/structure_tool_task.py• L754-824 workers/…/structure_tool_task.py• L827-932 workers/…/structure_tool_task.py• L935-1040
Execution plugin model
The executor worker exposes one task, execute_extraction, for all extraction work. An ExecutionContext is the serialized request envelope. It names the executor and operation, carries run and tenant identity, identifies the request source, and holds operation-specific parameters. An ExecutionResult is the shared response envelope with success, data, metadata, and an error message.
The executor selection flow is:
flowchart LR
A[Workflow or IDE caller] --> B[Execution context]
B --> C[Executor task]
C --> D[Executor registry]
D --> E[Executor instance]
E --> F[Operation handler]
F --> G[Execution result]
G --> H[Caller or callback]
An execution strategy implements BaseExecutor. It has a unique name and receives the complete context. The registry stores executor classes and creates a fresh instance for each request. Bundled executors register when their modules load. Installed cloud executors are discovered through the unstract.executor.executors entry-point group; importing a plugin activates its registration.
The bundled legacy executor covers the established prompt-service strategy. Its operation set includes text extraction, indexing, prompt answering, single-pass extraction, summarization, IDE indexing, and the compound structure pipeline. Compound operations keep related steps in one executor call. For example, a structure pipeline can extract text, summarize it, build indexes, answer prompts, and merge the output without blocking the file-processing worker between each step.
Operation names are a contract between dispatch callers and executor implementations. A new operation needs a context value, an executor route, and a result shape that the caller or callback understands. An unsupported operation returns a failed result instead of silently selecting another strategy.
Prompt answering is one operation family inside the legacy strategy. It builds the question, instructions, context, and output rules into a model request. Optional text processing can add source highlights and word confidence to execution metadata. Structured answers can also pass through an HTTPS postprocessing webhook; invalid or unavailable webhook results leave the original answer in place.
References: unstract/…/context.py• L14-46 unstract/…/context.py• L48-142 unstract/…/executor.py• L14-44 unstract/…/registry.py• L19-112 unstract/…/orchestrator.py• L21-82 workers/…/tasks.py• L1-162 workers/…/legacy_executor.py• L45-163 workers/…/legacy_executor.py• L545-731 workers/…/answer_prompt.py• L86-168 workers/…/postprocessor.py• L58-127 workers/…/__init__.py• L1-16 workers/…/loader.py• L19-58
Execution dispatch
The execution dispatcher is the caller-side helper for workflow tools and Prompt Studio. It derives a queue from the executor name, serializes the context, and supports wait-for-result, fire-and-forget, and callback-based dispatch.
| Dispatch mode | Caller receives | Use |
|---|---|---|
| Synchronous | ExecutionResult | Work that needs the output before the caller continues |
| Asynchronous | Task ID | Work that the caller polls or tracks later |
| With callback | Async result handle | Work that must persist output or signal success or failure |
The dispatcher separates the caller wait limit from the worker task limit. It converts transport or result errors into a failed ExecutionResult for synchronous calls. The routing dispatcher used by structure-tool work can select the PostgreSQL executor RPC path when enabled; otherwise it preserves the Celery path.
References: unstract/…/dispatcher.py• L31-55 unstract/…/dispatcher.py• L59-135 unstract/…/dispatcher.py• L137-212 unstract/…/dispatcher.py• L214-316 workers/…/structure_tool_task.py• L24-45 workers/…/structure_tool_task.py• L605-727 workers/…/structure_tool_task.py• L883-909
Executor support plugins
Executor support plugins add optional behavior without making the open worker import cloud code. The loader discovers utility plugins lazily through unstract.executor.plugins, while small protocol definitions state the calls that the worker may make.
Supported plugin roles include:
- Highlight data for source attribution and word confidence.
- Challenge checks that verify an answer with another model.
- Evaluation of prompt output.
- Lookup enrichment that adds data after extraction and returns usage metrics.
If an optional plugin is not installed, the worker can continue with the base execution path where the operation permits it. Executor classes use the same registration contract whether they are bundled or installed from a cloud package.
References: workers/…/loader.py• L1-81 workers/…/protocols.py• L11-77 workers/…/text_processor.py• L1-19 workers/…/__init__.py• L7-14
PostgreSQL queue operations
The PostgreSQL queue path is an alternative task transport for workers that need queueing without a Celery broker. PgQueueClient provides the queue contract, while PgQueueConsumer resolves registered tasks and runs them in the consumer process. The queue uses at-least-once delivery, so task identity and task-side idempotency remain important.
The queue lifecycle is:
flowchart LR
A[Producer] --> B[Ready message]
B --> C[Atomic claim]
C --> D[Short renewable lease]
D --> E[In-process task]
E -->|success| F[Delete acknowledgment]
E -->|failure or crash| G[Lease expiry]
G --> H[Reaper re-arms message]
H --> C
Claims use PostgreSQL row locking to prevent concurrent readers from taking the same visible row. A claimed row is hidden by its lease while the task runs. The consumer renews the lease for a live task, and the reaper makes an expired claim ready again after a crash. A task can still run more than once after a lease or acknowledgment failure, so the consumer passes the stable task ID into the task request.
One consumer can drain several queues through one claim cycle. It rotates the starting queue after each cycle so busy queues receive equal turns, while priority orders messages within each queue. A failed claim backs off and keeps the loop alive. A failure during a batch stops later work in that batch; unstarted messages remain available for later redelivery.
Malformed messages and unknown task names are dropped with a failure signal when one exists. Repeated failures become poison messages. Request-reply tasks store a result or error and acknowledge after one execution to avoid an expensive duplicate. Callback tasks enqueue a success or error continuation before acknowledging. Pipeline poison messages attempt to mark the execution as ERROR; if the backend is temporarily unavailable, the message is re-parked for a bounded period instead of being dropped without a terminal state.
The queue client recovers an owned connection after a connection failure. It retries a reused stale connection once for enqueue and acknowledgment, but does not retry a fresh connection or a caller-owned connection. Enqueue remains at-least-once because a connection can fail after the database commits but before the client receives the result. Acknowledgment is idempotent, so retrying a delete is safe.
References: workers/…/client.py• L1-31 workers/…/client.py• L69-180 workers/…/client.py• L233-305 workers/…/client.py• L306-400 workers/…/client.py• L434-610 workers/…/consumer.py• L1-21 workers/…/consumer.py• L273-417 workers/…/consumer.py• L440-537 workers/…/consumer.py• L582-714 workers/…/consumer.py• L901-1049 workers/…/consumer.py• L1078-1137 workers/…/supervisor.py• L1-51
Callback completion
Callback workers convert per-file or per-batch results into final execution state. They read the execution as the source of truth, aggregate counts and wall-clock time, decide between completed and error states, update the pipeline when a pipeline record applies, and trigger status notifications.
The callback keeps API deployments distinct from ETL, TASK, and APP workflows. API deployments do not receive pipeline status writes because they use an API deployment record. Other workflows map execution status to pipeline status and update last-run details. A legitimate empty run can complete, while an expected file set with no processed files is treated as a failure signal such as a timeout.
The callback also owns post-run cleanup. Non-API runs clear execution cache and remove workflow execution files. API runs preserve cache for later requests and can clean both API and workflow execution directories. Cleanup returns a result even when one part fails, so the final callback can report partial cleanup without hiding the execution outcome.
References: workers/…/tasks.py• L56-138 workers/…/tasks.py• L255-358 workers/…/tasks.py• L361-444 workers/…/tasks.py• L446-573 workers/…/tasks.py• L576-642 workers/…/tasks.py• L901-928 workers/…/tasks.py• L1039-1122 workers/…/tasks.py• L1125-1289
IDE callbacks
IDE callback tasks complete the browser-facing side of executor work. They use internal API clients to persist Prompt Studio state and send a prompt_studio_result event to the browser room.
The callback families cover:
- Index completion and failure, including indexing flags and index-manager state.
- Prompt completion and failure, including output persistence and error events.
- Text extraction completion and failure, including extraction state and optional live events.
Success callbacks keep the event payload small and avoid sending sensitive extracted data in worker logs. Failure callbacks resolve an explicit error when the dispatch path provides one, or use the task result store as a fallback. Subscription usage tracking is best effort and does not block the main callback.
References: workers/…/tasks.py• L47-119 workers/…/tasks.py• L122-145 workers/…/tasks.py• L156-312 workers/…/tasks.py• L315-360 workers/…/tasks.py• L363-495 workers/…/tasks.py• L498-535 workers/…/tasks.py• L553-690
Notifications
The notification worker turns a notification request into provider-specific delivery. A provider registry maps notification type and platform to a provider class, so task code does not need to know how each destination works. The universal task supports the current webhook path and returns a clear failure for notification types that have no provider.
The common provider contract validates input, prepares data, sends it, and returns a result with success, destination, attempt count, and provider details. Unsupported notification types fail as explicit errors rather than being sent through an unrelated provider. Webhook delivery has both a current provider path and a compatibility task for the older webhook shape.
The compatibility path retries delivery failures when configured. A terminal refusal from the destination is dead-lettered without retrying a URL that cannot work. Retry exhaustion can return the legacy result or raise when the caller needs a failed task signal. Buffered notification rows are marked through the internal API; if that mark fails, a backend reaper can reclaim the lease.
NotificationRequest, NotificationResult, and NotificationBatch provide typed data for validation, delivery state, aggregation, and serialization. They keep notification inputs and outcomes stable as more providers are added.
References: workers/…/tasks.py• L35-177 workers/…/tasks.py• L180-236 workers/…/tasks.py• L238-400 workers/…/tasks.py• L403-486 workers/…/registry.py• L17-135 workers/…/base_provider.py• L16-64 workers/…/webhook_provider.py• L27-183 workers/…/notification_models.py• L17-135 workers/…/notification_models.py• L138-269 workers/…/notification_models.py• L312-427
Logging and progress
Worker logging serves two audiences: operators need process logs, and users need workflow progress. WorkerLogger provides one standard log format with task, request, trace, and span fields. Context is attached per task and cleared after the task so one execution cannot leak identifiers into another.
Workflow progress uses WorkerWorkflowLogger and the shared LogPublisher. It publishes stage updates and file messages to a Socket.IO channel. When execution and organization identifiers exist, the same progress can also be attributed to persistent execution logs. A missing browser channel disables live delivery but does not stop the work.
The executor-side ExecutorToolShim adapts SDK tools to the worker environment. It supplies per-execution environment values, writes through Python logging, publishes progress when a log channel exists, and publishes persistent workflow logs when workflow identity is available. Structure-tool work creates this shim before executor dispatch, so tool-level logs can stream during metadata loading and execution. Performance decorators record duration and success or failure with a bounded in-process history.
The log consumer stores log messages in the Redis log queue and emits JSON-safe events through Socket.IO. A Redis stream consumer can drain that queue without a Celery deployment. It parks in-flight messages, recovers messages left by the same pod, and then calls the existing log handler.
References: workers/…/logger.py• L26-157 workers/…/logger.py• L235-359 workers/…/logger.py• L439-536 workers/…/logger.py• L677-751 workers/…/workflow_logger.py• L41-137 workers/…/workflow_logger.py• L139-230 workers/…/workflow_logger.py• L232-322 workers/…/workflow_logger.py• L402-557 workers/…/executor_tool_shim.py• L42-127 workers/…/executor_tool_shim.py• L129-234 workers/…/tasks.py• L72-152 workers/…/redis_stream_consumer.py• L1-16 workers/…/redis_stream_consumer.py• L81-159 workers/…/structure_tool_task.py• L336-355 workers/…/structure_tool_task.py• L883-901
Execution helpers
Shared helpers keep task code focused on business flow while preserving common safety rules. They create organization-scoped API clients, carry execution context, validate workflow tools before expensive work, apply retry and circuit-breaker behavior, and convert model objects to JSON-safe task payloads. The internal API client presents one worker-facing interface over specialized clients, with optional caching, manual-review plugins, and shared HTTP session reuse.
The most important helper boundaries are:
| Helper area | System purpose |
|---|---|
| Execution context | Carries tenant, workflow, execution, and transport identity |
| File processing utilities | Convert file data and form bounded batches |
| Workflow orchestration | Create batch fan-out and callback work |
| Cache and active-file checks | Avoid repeat work and detect concurrent processing |
| Retry and circuit breakers | Limit repeated calls to unstable services |
| Internal API clients | Keep workers independent from backend ORM access |
| File-system adapters | Read and write execution files across storage types |
Usage records are part of execution metadata. The executor task flushes them to the usage API after an operation. If an executor fails after collecting records, the failure result keeps those records so a retry can recover billing data. The same client boundary supports recovery calls for PostgreSQL-backed executions, so queue recovery can finalize stuck work without direct backend database access.
References: workers/…/context.py• L1-181 workers/…/orchestration_utils.py• L1-240 workers/…/active_file_manager.py• L1-220 workers/…/utils.py• L1-220 workers/…/utils.py• L1-220 workers/…/internal_client.py• L76-221 workers/…/internal_client.py• L260-314 workers/…/internal_client.py• L600-646 workers/…/tasks.py• L75-161 unstract/…/orchestrator.py• L48-70
Change checklist
When these files or sections are changed, remember to consider these:
- Add a worker type to the enum, queue registry, task-route registry, health-port map, and task-loading path as one contract.
- Keep task names, route patterns, queue names, and compatibility aliases aligned across producers and worker registries.
- Keep
ExecutionContext.operation, executor support, dispatcher payloads, and callback result parsing aligned when adding or renaming an operation. - Keep executor entry-point discovery and import-time registration active in every worker bootstrap path, including each PostgreSQL executor consumer child.
- Preserve output file names and METADATA.json fields when changing structure-tool output because destination connectors read that stored contract.
- Keep structure-tool prompt partitioning, executor names, operation names, and parameter shapes aligned with the legacy and agentic executor contracts.
- Keep the immutable
SOURCEinput separate from the output-bearingINFILEwhen agentic and regular processing share an execution directory. - Keep agentic output, highlight data, and extraction-time metrics merged into the result shape expected by downstream consumers.
- Preserve callback payload identity fields such as organization, execution, workflow, file, and log-channel IDs across Celery links and PostgreSQL self-chained paths.
- Keep PostgreSQL queue lease, visibility, batch, and health limits compatible with the longest legitimate task and the supervisor shutdown grace.
- Keep stable task IDs in PostgreSQL payloads so redelivery reaches the same task-side idempotency guards.
- Keep request-reply result storage and callback self-chaining aligned with the acknowledgment rule that avoids executor re-runs.
- Keep poison-message identity recovery aligned with the payload shapes used by pipeline callbacks and positional orchestration tasks.
- Keep secret redaction and customer-data summaries in poison logs when notification payloads change.
- Keep notification provider combinations, notification type values, and compatibility task arguments aligned with backend notification configuration.
- Keep structured-output webhook payloads, HTTPS-only URL checks, and fallback behavior aligned between prompt answering and the postprocessing service.
- Keep terminal webhook refusals separate from retryable delivery errors so buffer rows are dead-lettered once.
- Keep log channel and persistent execution-log identifiers distinct when changing progress or executor shim behavior.
- Keep the Redis log queue name, envelope task name, processing-list recovery rules, and socket timeout aligned when changing the Redis log transport.
- Keep scheduler task names identical across the periodic-job source and both Celery and PostgreSQL task registries.
- Keep dashboard metric proxy paths, backend authentication, and long-running request limits aligned with the backend metric endpoints.
- Keep transport markers, scheduler dispatch backends, and PostgreSQL consumer role queues aligned when adding a new execution transport.
- Keep the internal client facade and its specialized clients aligned when adding recovery or scheduler API calls.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A non-pluggable worker has no task directory or tasks.py | Startup fails instead of running a worker that consumes nothing | Entrypoint checks the directory and task file before worker start |
| A PostgreSQL consumer starts without application tasks | Every message would look unknown and be dropped | Consumer refuses to start when its application registry is empty |
| A PostgreSQL child imports the wrong source worker type | Valid messages are dropped as unknown tasks | Bootstrap selects the source worker type before importing worker, and startup logs the registered task names |
A pluggable executor is not imported before execute_extraction runs | Executor lookup returns a failed result with no registered strategy | Executor task imports the executor package before task registration |
| A task route names a queue that the worker does not consume | Work remains queued or is handled by the wrong role | Registry validation compares route queues with worker queue configuration |
| A PostgreSQL claim expires before a task is acknowledged | The task can run again and side effects can repeat | Renewable leases protect live tasks, while task IDs and task-side idempotency handle redelivery |
| A PostgreSQL child dies after claiming work | The message stays claimed until lease expiry | Reaper re-arms expired claims, and the supervisor can replace the child |
| A PostgreSQL child crash-loops or stops polling | The pod can appear alive while losing a consumer slot | Fleet liveness uses the oldest child heartbeat and marks crash loops unhealthy |
| Supervisor watchdog settings are below legitimate task time | A live child is killed and its task is redelivered | Enable the watchdog only with a stale threshold above the longest valid task |
| Shutdown grace is shorter than the visibility or task window | In-flight work is killed during rollout or scale-down | The supervisor uses a shared drain window based on the visibility timeout unless explicitly overridden |
| Callback status write fails on the PostgreSQL path | Execution can remain EXECUTING after the barrier is gone | Callback re-raises so at-least-once delivery can retry the write |
| A request-reply result cannot be stored | The caller times out, but a retry must not spend again | Consumer acknowledges after the one execution and logs the result-store failure |
| A callback continuation cannot be enqueued | The executor message is acknowledged and the user event can be lost | Consumer records task status first and logs the run, task, and organization identity |
A poison pipeline message cannot be marked ERROR | Dropping it can strand an execution | Consumer re-parks transient backend failures for a bounded budget and logs manual-replay details when the budget ends |
| Notification buffer marking fails | Rows remain leased in SENDING | Backend reaper reclaims the rows after the lease |
| Workflow progress has no log channel | Live browser logs are not delivered | Worker logs remain available and execution identity can route persistent logs |
| An exported agentic-table prompt lacks its required settings | The task fails clearly instead of producing an invalid legacy result | Structure-tool processing validates the target table and JSON structure before dispatch |
Agentic processing reads the output-bearing INFILE after it is overwritten | The executor can reject the document as invalid input | Agentic processing reads the immutable SOURCE file |
| A structure-tool output write fails | Destination stage cannot find the expected result | The task returns a failed execution result after reporting the write error |
| A postprocessing webhook URL is unsafe or its response has an invalid shape | Structured output could go to an unsafe destination or be replaced with unusable data | The sink accepts safe HTTPS URLs and keeps the original data when validation or delivery fails |
| A webhook provider refuses a URL as non-retryable | Repeated retries waste work and can dead-letter the same buffer rows more than once | Compatibility delivery marks terminal refusals separately from retryable failures |
| Redis log consumer uses a socket timeout at or below its blocking read timeout | Idle reads fail repeatedly and an already moved envelope can remain parked | Keep the client socket timeout above the server-side block interval |
| Redis log consumer dies after moving an envelope | The in-flight log is not available on the source queue until recovery | Park messages on a per-pod processing list and recover that pod's list at startup |
| Scheduler loads dashboard metric tasks under a different task name or import path | Periodic metric work is not registered or the scheduler worker can crash on startup | Keep the absolute registration import and exact periodic task names |
| Scheduled execution transport is not carried into the dispatch call | Work is sent to the wrong queue system or is not consumed | Normalize the execution transport before dispatch and bind it to the matching worker role |
Key files
| File | Why to read it |
|---|---|
| workers/worker.py | Common worker entrypoint, task loading, process hooks, and shutdown safety |
| workers/…/registry.py | Worker roles, queues, routes, and dynamic worker configuration |
| workers/…/builder.py | Construction of a configured worker app and health monitor |
| workers/…/worker_models.py | Queue, route, health, and setting contracts |
| workers/run-worker.sh | Local worker groups, transport-specific roles, process control, and log management |
| workers/run-worker-docker.sh | Container worker launch paths for Celery, PostgreSQL queue, and Redis log consumers |
| workers/…/supervisor.py | PostgreSQL child process fleet, liveness, readiness, watchdog, and shutdown behavior |
| workers/…/consumer.py | PostgreSQL claim loop, task resolution, leases, callbacks, poison handling, and health |
| workers/…/client.py | PostgreSQL enqueue, claim, lease, acknowledgment, and connection recovery contract |
| workers/…/tasks.py | Non-API workflow discovery and batch orchestration |
| workers/…/tasks.py | API workflow execution and file-history behavior |
| workers/…/tasks.py | Scheduled pipeline dispatch, transport choice, and scheduler task registration |
| workers/…/dashboard_metrics_tasks.py | Backend proxy tasks for dashboard aggregation and metric cleanup |
| workers/…/tasks.py | Batch validation, duplicate control, per-file processing, and result compilation |
| workers/…/structure_tool_task.py | Prompt and agentic routing, executor RPC calls, result merging, and destination-compatible output storage |
| workers/…/tasks.py | Execution finalization, pipeline updates, cleanup, and notifications |
| workers/…/tasks.py | Single executor task entrypoint and usage-record handling |
| unstract/…/context.py | Serialized operation request contract |
| unstract/…/registry.py | Executor registration and lookup contract |
| unstract/…/dispatcher.py | Caller-side executor routing and dispatch modes |
| workers/…/legacy_executor.py | Bundled extraction strategy and compound workflow operations |
| workers/…/answer_prompt.py | Prompt construction, model completion, caching choice, and answer metadata |
| workers/…/postprocessor.py | Safe structured-output webhook processing and fallback validation |
| workers/…/tasks.py | Prompt Studio persistence and browser result events |
| workers/…/registry.py | Notification type and platform provider mapping |
| workers/…/workflow_logger.py | User-facing workflow and file progress events |
| workers/…/executor_tool_shim.py | SDK adapter boundary for worker logging and environment access |
| workers/…/tasks.py | Log persistence and live Socket.IO emission |
| workers/…/redis_stream_consumer.py | Reliable Redis transport for the existing log consumer task |
| workers/…/internal_client.py | Unified worker API boundary, caching, plugins, and execution recovery calls |