Executor System¶
Drakkar runs external binaries as subprocesses – not through a shell, but directly via asyncio.create_subprocess_exec. Arguments are passed as a list, making the execution safe from shell injection by design. Concurrency is controlled by a PriorityGate (a semaphore-like gate that wakes contended waiters in priority order) sized to executor.max_executors, and each task is bounded by a wall-clock timeout via asyncio.wait_for.
ExecutorTask¶
Every subprocess execution starts with an ExecutorTask created in your arrange() hook. The task carries everything the framework needs to launch the process and track its lifecycle.
| Field | Type | Default | Description |
|---|---|---|---|
task_id |
str |
(required) | Unique identifier. Use make_task_id(prefix) to generate a time-sortable hex ID (e.g., t-0194a3b2c1d4e5f6-a7c2f1e3). |
args |
list[str] |
[] |
CLI arguments appended to the binary path when launching the process. May be empty, especially when precomputed is set and no subprocess will run. |
source_offsets |
list[int] |
(required) | Kafka offsets of the source messages that produced this task. Used for offset watermark tracking – offsets are committed only after all sinks confirm delivery. A task built by arrange_http_request has no Kafka offset: pass source_offsets=[]. |
metadata |
dict |
{} |
Arbitrary key-value data carried through the pipeline. Accessible in on_task_complete() via result.task.metadata. |
labels |
dict[str, str] |
{} |
User-defined key-value labels shown in the operator UI (live timeline, task detail page, trace view). Useful for request_id, user_id, or other domain identifiers. |
env |
dict[str, str] |
{} |
Per-task environment variables. Merged on top of executor.env from config (task overrides config on key conflict). See Environment Variables. |
binary_path |
str \| None |
None |
Per-task binary override. Takes precedence over executor.binary_path from config. |
stdin |
str \| None |
None |
Optional string piped to the process stdin after launch. When None, stdin is not connected. |
precomputed |
PrecomputedResult \| None |
None |
If set, the framework SKIPS subprocess execution entirely and synthesises an ExecutorResult from the precomputed values. Use for cache hits, lookup-table answers, or any deterministic shortcut. See Precomputed task results. |
parent_task_id |
str \| None |
None |
task_id of the task this one was created to REPLACE. Auto-populated by the framework on on_error list-returned tasks; the handler can override. Useful for walking the replacement chain in on_message_complete. |
Generating Task IDs¶
The make_task_id() helper produces short, time-sortable, unique IDs:
from drakkar import make_task_id
task_id = make_task_id('search')
# "search-0194a3b2c1d4e5f6-a7c2f1e3"
The format is {prefix}-{timestamp_hex}-{random_hex}. Lexicographic order matches creation order, and the nanosecond timestamp combined with a 32-bit random suffix ensures uniqueness.
Binary Path Resolution¶
The binary to execute is resolved per-task using this priority:
task.binary_path– set on the individualExecutorTaskexecutor.binary_path– from the YAML/env config
If neither is set, the task fails immediately with exit_code=-1 and a descriptive error message. No process is launched.
This two-level resolution lets you run different binaries for different task types within the same handler:
async def arrange(self, messages, pending):
tasks = []
for msg in messages:
binary = '/usr/bin/fast-search' if msg.payload.priority == 'high' else '/usr/bin/deep-search'
tasks.append(
ExecutorTask(
task_id=make_task_id('search'),
args=['--query', msg.payload.query],
source_offsets=[msg.offset],
binary_path=binary,
)
)
return tasks
If all tasks use the same binary, set executor.binary_path in your config and omit binary_path from individual tasks.
Execution Flow¶
Each task goes through these steps:
1. Enter Priority Queue¶
The task enters the waiting state (waiting_count incremented). The framework asks the handler for the task’s priority key (default: min(task.source_offsets) – earliest message wins) and inserts the task into the executor pool’s priority gate. While slots are available the gate behaves like a plain semaphore (acquire returns immediately); under saturation, contended waiters wake up in ascending priority order rather than FIFO arrival order. See Task priority below for the override hook.
2. Acquire Slot¶
When the gate releases the next slot to this task, waiting_count is decremented, active_count is incremented, and a slot ID (0 to max_executors - 1) is assigned from the available pool.
3. Launch Process¶
The framework calls asyncio.create_subprocess_exec with:
- First argument: the resolved binary path
- Remaining arguments:
task.args(passed as individual arguments, not via shell) stdin:PIPEiftask.stdinis set, otherwise not connectedstdout:PIPE(always captured)stderr:PIPE(always captured)
The run starts right before this call: the framework reads the monotonic
clock (for the run time) and the wall clock (run_started_at) with no
await between them and the fork. On the line right after the call returns
it starts watching the process for its exit (see Run time).
4. Communicate¶
proc.communicate(input=stdin_bytes) writes stdin (if any) and waits for the process to exit. All stdout and stderr are captured in memory. With executor.max_stdout / max_stderr set, the framework streams the pipes instead, retaining up to the cap per stream and discarding the rest — see Output Caps.
5. Enforce Timeout¶
The entire capture call (communicate(), or the capped streaming reader when output caps are set) is wrapped in asyncio.wait_for(timeout=executor.task_timeout) (default: 120 seconds).
6. Handle Outcome¶
Four outcomes are possible:
Success (exit code 0) – Returns an ExecutorResult with captured output. The on_task_complete() hook is called next.
Non-zero exit – Raises ExecutorTaskError. The on_error() hook decides what to do.
Timeout – The whole process tree is killed with os.killpg(SIGKILL) (the subprocess starts in its own process group, so grandchildren die too — also when the child itself already exited and a grandchild still holds its pipes; on Windows, which has no process groups, this falls back to proc.kill()), and ExecutorTaskError is raised with stderr='task timed out'. The run ends where the timeout fired. A child that survives SIGKILL (wedged in the kernel) is left after one bounded wait of 5 seconds and one executor_kill_reap_timeout warning.
OSError (binary not found) – ExecutorTaskError is raised immediately with kind launch_failure. No process was ever started. An exec that fails with ETIMEDOUT (a binary on a hung network mount) is a launch failure too.
7. Release Slot¶
In the finally block (guaranteed to run), the slot ID is returned to the pool, active_count is decremented, and the priority gate is released. The gate then pops the highest-priority waiter (smallest priority key) and resolves it – skipping any cancellation tombstones from waiters that were cancelled while pending. If the process is still running (e.g., after a timeout), it is killed before release.
ExecutorResult¶
Returned on successful execution (exit code 0). Also attached to ExecutorTaskError on failures for inspection.
| Field | Type | Description |
|---|---|---|
exit_code |
int |
Process exit code. 0 on success, non-zero on failure, -1 for timeout/launch errors. |
stdout |
str |
Captured process stdout, decoded as UTF-8 with errors='replace'. |
stderr |
str |
Captured process stderr, decoded as UTF-8 with errors='replace'. |
duration_seconds |
float |
Run time of the subprocess, from just before the spawn to its exit, rounded to 3 decimal places. The exit time is read off the event loop (see Run time), so a busy loop does not stretch it. When a descendant kept the output pipes open past the exit, the run ends when they close; a timed-out run ends where the timeout fired. For a launch failure: the time until the failure; for a precomputed result: the handler’s value. |
run_started_at |
float \| None |
Unix seconds of the spawn, read right before it. The run spans run_started_at to run_started_at + duration_seconds. None for a launch failure and a precomputed result. |
exit_notice_seconds |
float \| None |
Seconds from the exit to the moment the worker handled it: a few milliseconds on a healthy worker, more when the event loop is busy. 0 when the worker handled the exit before the exit watcher reported it. None when the exit could not be timed off the loop, when a descendant held the output pipes, for a timeout, for a launch failure and for a precomputed result. |
spawn_seconds |
float \| None |
Wall-clock time creating the subprocess took (fork/exec plus any event-loop scheduling delay around it) — the parent-side share of duration_seconds. Single-digit milliseconds on a healthy host; grows when the worker process itself is the bottleneck. None for precomputed results. |
task |
ExecutorTask |
The original task that produced this result. Carries metadata and labels through the pipeline. |
pid |
int \| None |
OS process ID. None if the process never started. |
stdout_truncated |
bool |
True when stdout retention stopped at executor.max_stdout and the remainder was discarded. Always False with unlimited caps and for precomputed results. |
stderr_truncated |
bool |
Same for stderr, governed by executor.max_stderr. |
Run time¶
asyncio learns about a child’s exit on the event loop: it reads the exit notification, reaps the child, and resumes the waiting task, each step a loop callback. When the loop is busy, all of that waits, and a duration measured there grows by the length of the stall.
So the framework reads the exit time somewhere else. One daemon thread per
worker process (drakkar-exit-watcher) waits for task subprocesses to exit
and reads the clock when the kernel reports the exit:
| Platform | Mechanism |
|---|---|
| Linux | one pidfd per child in one epoll set; a pidfd becomes readable when its process exits |
| macOS | one EVFILT_PROC / NOTE_EXIT event per child in one kqueue |
| anything else | no watcher: the run time is measured on the loop |
The watcher never reaps a child, so asyncio keeps the exit status. Its only
wait call is a waitid(..., WNOWAIT) probe that proves the watched pid is
still this worker’s own unreaped child. The thread writes the stamp into
the task’s watch; the task does not wait for it. If the loop handles the
exit before the watcher reports it, the loop’s own reading is used, because
the loop was not stalled.
After each batch of exits the thread pauses 5 ms, so its wake-ups stay few (measured near 2 % of one core at 1,200 task exits per second). A stamp can therefore be up to about 5 ms late; the stalls this corrects are much longer.
These cases fall back to timing on the loop, counted on
drakkar_executor_exit_watch_fallbacks_total{reason}:
exited_before_watch— the child exited and was reaped before the watch started.create_subprocess_execawaits its pipe set-up after the fork, and on a busy loop a short task can finish in that gap. On macOS asyncio reaps each child on a thread of its own the moment it exits, so a short task is also counted here when the loop is slow to reach the watch after the spawn returns. The run then ends at the watch time.unavailable— the host cannot watch: no backend for the platform, or the kernel refused (for example a seccomp profile withoutpidfd_open; then the watcher turns off for the process). A resource error of one watch (EMFILE,ENOMEM,EAGAIN) makes only that task fall back. A watch still pending when the watcher stops falls back too.descendant_held_pipes— the child exited, but a descendant kept its output pipes open more than 50 ms longer. A task ends when its child has exited and its pipes have closed, so the run ends when the pipes close. The framework compares the two moments as the loop saw them (it subclasses asyncio’s subprocess stream protocol for that), so a loop stall during the run delays both and is not taken for a descendant. A single callback longer than 50 ms that runs between the two (they are a few loop callbacks apart) is counted here too, so on a busy worker this reason can also rise with loop stalls.
A timed-out task ends where the timeout fired. Its process group is killed
once with killpg(<child pid>, SIGKILL), also when the child itself already
exited and only a descendant was still running; the group is never looked up
with getpgid, because a reaped child’s pid may name another process. Neither a timeout nor a descendant records an exit notice.
exit_notice_seconds is recorded as exit_notice_ms and observed on
drakkar_executor_exit_notice_seconds — see Observability.
A handler can report its own run time for the timeline bar with the
optional task_run_seconds hook.
Error Handling (on_error Hook)¶
When a task fails, the framework calls your on_error() hook. The error argument is an ExecutorError:
| Field | Type | Description |
|---|---|---|
task |
ExecutorTask |
The task that failed. |
kind |
'nonzero_exit' \| 'timeout' \| 'launch_failure' \| 'internal' |
Structured failure classification. 'nonzero_exit' (default) – the subprocess or precomputed result finished with a non-zero exit code. 'timeout' – exceeded executor.task_timeout. 'launch_failure' – the process could not be started (missing binary or spawn error). 'internal' – synthesized by the framework with no subprocess outcome behind it (e.g. a hook raised or the pool violated its contract). |
exit_code |
int \| None |
Process exit code. None if the process failed to start or timed out. |
stderr |
str |
Process stderr or a short error description (e.g., 'task timed out'). |
exception |
str \| None |
Exception message for timeout/launch failures. None for normal non-zero exits. |
pid |
int \| None |
Process ID. None if the process never started. |
internal ⇔ the error was synthesized by the framework rather than produced from a subprocess outcome. Discriminate failures by kind – never by parsing exception text.
Return Values¶
The hook must return one of:
ErrorAction.RETRY – Re-execute the same task. The framework retries up to executor.max_retries (default: 3) times. Retries are immediate (no backoff). If retries are exhausted, executor.on_failure applies: skip marks the task as failed and the window continues; dlq also writes its source messages to the DLQ. The worker logs max_retries_exceeded with action (skip or dlq).
ErrorAction.SKIP – Mark the task as failed, append its result to the window, and continue.
ErrorAction.DLQ – Mark the task as failed and write its source messages to the DLQ at once (dk-stage: execute). No later delivery of those messages starts; tasks already running finish. See on_error.
The default on_error returns executor.on_failure, which is SKIP unless the config sets executor.on_failure: dlq. The same policy applies when on_error raises: the worker logs on_error_hook_failed and then skips the task or writes its record.
list[ExecutorTask] – Replace the failed task with new tasks. The new tasks are added to the current window and execute immediately. The window’s total_tasks grows dynamically to include them. Use this to split a large failing task into smaller ones, or to substitute a fallback binary.
Example¶
from drakkar import BaseDrakkarHandler, ErrorAction, ExecutorError, ExecutorTask
class MyHandler(BaseDrakkarHandler):
async def on_error(self, task, error):
# Retry transient failures (simulated by exit code 75)
if error.exit_code == 75:
return ErrorAction.RETRY
# Timeout: try a lighter binary as fallback
if error.kind == 'timeout':
return [
ExecutorTask(
task_id=make_task_id('fallback'),
args=task.args + ['--fast-mode'],
source_offsets=task.source_offsets,
metadata=task.metadata,
binary_path='/usr/bin/lightweight-search',
)
]
# Everything else: skip
return ErrorAction.SKIP
Concurrency and Backpressure¶
Priority-gated Concurrency¶
executor.max_executors (default: 4) controls how many subprocesses run in parallel across all partitions. The ExecutorPool maintains an internal PriorityGate of this size that behaves like an asyncio.Semaphore with one extra rule: contended waiters wake up in priority order rather than FIFO. Tasks from any partition compete for the same pool, so a low-priority task on partition 7 can step ahead of a high-priority task on partition 3 when both are waiting.
When all slots are occupied, additional tasks wait in the gate’s heap. The waiting_count property tracks how many tasks are queued, while active_count tracks how many are running.
Task priority¶
The framework asks the handler for each task’s priority key via task_priority(task) before the task enters the gate. The default returns min(task.source_offsets) so older Kafka messages drain first – this keeps MessageTracker / OffsetTracker state in front of the watermark small and lets on_message_complete fire sooner.
Override task_priority on your handler to inject business priority. Any value that supports __lt__ (int, tuple, custom class) works; equal-priority tasks tiebreak FIFO via the gate’s internal sequence counter, so within a priority band behaviour matches the pre-priority semaphore.
class MyHandler(BaseDrakkarHandler):
def task_priority(self, task):
# Partition-aware: keep partition fairness AND prefer older
# messages within each partition.
return (task.source_offsets[0] // 1000, task.source_offsets[0])
If task_priority raises, the framework logs a warning, ticks drakkar_executor_priority_fn_errors_total, and falls back to the default key so the task is still scheduled. A buggy override never stalls a task.
Tasks with precomputed set bypass the gate entirely (no slot, no priority) – they were already shaped by the handler at arrange() time and run instantly.
Window admission and Kafka backpressure¶
Two limits keep the work a worker holds bounded. See Performance: Backpressure for the memory model and sizing.
| Key | Default | What it bounds |
|---|---|---|
executor.max_pending_tasks |
2000 |
Tasks created and not yet settled (waiting for a slot, running, or in on_task_complete and its delivery). Must be at least max_executors. |
executor.max_pending_bytes |
1GiB |
The stdin of those tasks plus the stdout and stderr of their results while on_task_complete, on_error and the sink delivery run, and of results kept for on_group_complete, on_message_complete and on_window_complete. Large outputs slow admission. At least 16MiB. |
sources.kafka.max_queued_messages |
1000 |
Polled messages waiting in partition queues. Must be at least max_poll_records. |
- A partition loop takes a new window only while both pending counts are below their limits. Otherwise it waits; a release that makes room wakes the oldest waiting loop first.
- A loop that takes a window reserves its estimated tasks and bytes at once,
so other loops see the room as taken while
arrange()runs. A partition takes one message per window during its warm-up (its first 3 windows, with tasks or without), and after it a message never reserves less thanmax_pending_tasks / window_size. With a steady message shape the peak is about the cap plus one message for the whole worker. After the warm-up, a sudden jump in tasks per message can pass the cap by the size of that jump. A task’s output is known only when the task ends, so the outputs of the pending tasks can also pass the byte limit;max_stdoutandmax_stderrbound each one. Thedrakkar_pending_tasksanddrakkar_pending_bytesgauges show the real counts. - The Kafka fetch pauses when the queues of the live partitions hold
max_queued_messagesmessages and resumes at half of it. Stalled and dead partitions stay paused. - HTTP requests count in the pending budget but never wait for it.
Configuration¶
executor:
max_executors: 8
max_pending_tasks: 2000 # new windows wait at 2000 unsettled tasks
max_pending_bytes: 1GiB # ... or at 1 GiB of stdin and task output
sources:
kafka:
max_queued_messages: 1000 # pause the fetch at 1000 queued messages, resume at 500
Windowing¶
Messages are collected into windows before being passed to arrange(). A window contains 1 to executor.window_size (default: 100) messages from a single partition.
Window Lifecycle¶
- The partition processor waits for the first message (blocks up to 1 second).
- It waits until the worker has room under
max_pending_tasksandmax_pending_bytes(each wait at most 1 second, then the loop retries a commit and comes back). - It drains more messages from the queue without blocking, up to the admitted size. During the partition’s warm-up (its first 3 windows, whether they created tasks or not) that is one message, and the window reserves all the free room. After it:
min(free tasks / tasks per message, free bytes / bytes per message), at least 1 and at mostwindow_size, where the per-message numbers are the moving averages (bytes = stdin plus the output the message and window hooks keep; the output of a task in its own hooks and delivery is charged but not estimated) raised to a floor ofmax_pending_tasks / window_sizetasks andmax_pending_bytes / window_sizebytes, and the free room excludes other windows’ reservations. The estimate is reserved at once. The worker’s first window takes one message. - The window of messages is passed to arrange(), which returns
ExecutorTaskobjects. - All tasks in the window are launched concurrently.
- The window tracks
completed_countvstotal_tasksto know when it is done. - As each source message’s tasks all reach a terminal state, on_message_complete() is called for that message, the offset is marked complete, and a commit is attempted. When every task in the window has finished, on_window_complete() fires once for the whole batch.
Concurrent Windows¶
Multiple windows can be in-flight concurrently for the same partition. The processor does not wait for window N to complete before starting window N+1. This keeps throughput high when tasks have variable execution times.
Each window’s tasks execute independently. Offset commits follow watermark semantics – offsets are committed only when all preceding messages have been fully processed and delivered. A slow task in window 1 blocks offset advancement even if window 2 has already finished.
Dynamic Window Growth¶
If on_error() returns replacement tasks, the window’s total_tasks count grows. The window only completes when all tasks – including dynamically added ones – have finished.
Stdin Support¶
The stdin field on ExecutorTask lets you pipe data to a subprocess without passing it as CLI arguments. When set, the framework connects a pipe to the process stdin and writes the string immediately after launch.
This is useful for passing structured input (JSON, configuration) that would be awkward or unsafe as command-line arguments.
Example¶
import json
from drakkar import ExecutorTask, make_task_id
async def arrange(self, messages, pending):
tasks = []
for msg in messages:
payload = {
'query': msg.payload.query,
'filters': msg.payload.filters,
'options': {'max_results': 100, 'timeout_ms': 5000},
}
tasks.append(
ExecutorTask(
task_id=make_task_id('search'),
args=['--mode', 'stdin'],
source_offsets=[msg.offset],
metadata={'request_id': msg.payload.request_id},
stdin=json.dumps(payload),
)
)
return tasks
The subprocess reads the JSON from stdin:
#!/usr/bin/env python3
import json
import sys
request = json.load(sys.stdin)
# process request...
print(json.dumps(result))
When stdin is None (the default), the process stdin is not connected at all.
Output Caps¶
By default the executor retains everything a task writes to stdout and stderr. Processes that emit very large output can make that retention the peak memory cost of the worker — one string per task, multiplied by max_executors. Two opt-in caps bound it:
executor:
max_stdout: 1MiB # keep at most 1 MiB of stdout per task
max_stderr: 64KiB # keep at most 64 KiB of stderr per task
0(the default) means unlimited — behavior is unchanged.- The process is never throttled or blocked: past the cap the framework keeps reading and discards the excess, so a chatty child cannot deadlock on a full pipe.
- The retained prefix is cut at a UTF-8 character boundary (at most 3 bytes below the cap), so the decoded string never ends mid-character.
- Output exactly equal to the cap is not considered truncated.
- When a stream is cut,
ExecutorResult.stdout_truncated/stderr_truncatedis set, a warning (executor_output_truncated) is logged, anddrakkar_executor_output_truncated_total{stream}increments. - Caps apply to real subprocess output only: handler-supplied precomputed results pass through untouched, and a timed-out task still discards all captured output.
Environment Variables¶
Custom environment variables can be passed to executor subprocesses at
two levels: globally via config and per-task via ExecutorTask.env.
Merge order¶
The subprocess environment is built by merging three layers, where later layers override earlier ones on key conflict:
- Parent process env – the worker’s own environment, filtered
through
executor.env_inherit_deny(see below) - Config env (
executor.env) – applied to all tasks - Task env (
ExecutorTask.env) – applied to one task, overrides config
When neither config nor task defines custom env vars and no deny patterns are configured, the subprocess inherits the parent environment directly (no copy overhead).
Parent-env filtering (secrets guard)¶
By default, the parent environment is not passed to subprocesses
verbatim. A deny-list of fnmatch patterns (executor.env_inherit_deny)
is applied case-insensitively to env var names, and matching vars are
stripped before the subprocess starts. The default patterns are:
DK_* # framework internals (KAFKA__BROKERS, SINKS__*__DSN, ...)
*PASSWORD*
*PASSWD*
*SECRET*
*TOKEN*
*_KEY
*_DSN
*CREDENTIAL*
*SALT*
This keeps operator-configured secrets — most commonly the DK_*
env overrides like DK_CONNECTIONS__POSTGRES__MAIN__DSN — from reaching
the executor binary where they could be read, logged, or exfiltrated.
This list is deliberately more conservative than the recorder’s
redaction patterns (see Per-task env is visible in the
UI): a pattern here withholds the variable from
your binary, so *_KEY stays suffix-anchored and names with common
non-secret uses (AUTH_SERVICE_URL, CERT_PATH, PRIVATE_SUBNET) are
deliberately excluded.
Two knobs control the behavior:
executor:
env_inherit_parent: true # false = fully isolated from parent env
env_inherit_deny: # override the default patterns
- DK_*
- '*PASSWORD*'
- '*PASSWD*'
- '*SECRET*'
- '*TOKEN*'
- '*_KEY'
- '*_DSN'
- '*CREDENTIAL*'
- '*SALT*'
Set env_inherit_deny: [] to trust the full parent environment (e.g.,
if you already gate the process environment externally). Set
env_inherit_parent: false to run subprocesses with only
executor.env + ExecutorTask.env — nothing from the parent at all.
The PATH and other standard vars are still subject to the deny list;
if you rely on them, make sure your patterns don’t match them (they
don’t with the defaults).
The filtered parent environment is computed once, on the first task, and reused for every subsequent subprocess — the result depends only on the process environment and the deny patterns, neither of which changes while the worker runs. Two consequences worth knowing:
- Mutating
os.environafter the first task does not affect later subprocesses. Useexecutor.env(config-level) orExecutorTask.env(per-task) for anything that needs to vary; both are applied fresh on every task and still override the parent snapshot. - Variables exported by startup hooks are picked up, because the snapshot is taken lazily on first use rather than at pool construction.
Config-level env¶
Set executor.env in your YAML config to pass variables to every task:
executor:
binary_path: "/usr/local/bin/my-tool"
env:
DATABASE_URL: "postgresql://localhost/mydb"
LOG_LEVEL: "warn"
CORPUS_PATH: "/data/corpus"
These are useful for connection strings, feature flags, or paths that are the same for every task but shouldn’t be hardcoded in the binary.
Environment variable override: DK_EXECUTOR__ENV='{"KEY": "value"}'
Per-task env¶
Set env on ExecutorTask in arrange() for task-specific values:
async def arrange(self, messages, pending):
tasks = []
for msg in messages:
tasks.append(
ExecutorTask(
task_id=make_task_id('proc'),
args=['--process'],
source_offsets=[msg.offset],
env={
'REQUEST_ID': msg.payload.request_id,
'PRIORITY': str(msg.payload.priority),
},
)
)
return tasks
Per-task env is useful when the binary reads configuration from environment variables and different messages need different settings.
Per-task env is visible in the UI (after redaction)
Values in task.env are surfaced on the Message Trace and Task
Results tabs of the operator UI — the full env dict is stored in the
recorder’s task_started event metadata. Before storage, values
whose names match secret patterns (*PASSWORD*, *PASSWD*,
*SECRET*, *TOKEN*, *KEY*, *API_KEY*, *CREDENTIAL*, *_DSN,
*AUTH*, *PRIVATE*, *CERT*, *SALT*) are replaced with ***;
other values have URL-embedded credentials stripped. This list is
intentionally broader than executor.env_inherit_deny (above) — a
redaction miss here only leaks into a debug DB, not into a running
subprocess. The subprocess still receives the real values — only the
recorded copy is redacted. For secrets whose names don’t match the
patterns, use ExecutorConfig.env (framework-level, never written
to the recorder) or pass them via files on disk. See
Secrets are redacted before they reach disk.
Override example¶
Config sets a default, task overrides it for specific messages:
# handler.py — arrange()
ExecutorTask(
task_id=make_task_id('proc'),
args=['--run'],
source_offsets=[msg.offset],
env={'MODE': 'turbo'}, # overrides config's "standard"
# TIMEOUT: "30" is still inherited from config
)
The subprocess sees MODE=turbo and TIMEOUT=30.
Configuration Reference¶
All executor settings live under the executor key in your YAML config:
executor:
binary_path: /usr/local/bin/my-worker # default binary (optional)
max_executors: 4 # concurrent subprocess limit
task_timeout: 2m # per-task wall-clock timeout
max_stdout: 0 # stdout bytes retained (0 = unlimited)
max_stderr: 0 # stderr bytes retained (0 = unlimited)
window_size: 100 # max messages per arrange() call
max_retries: 3 # retry limit per failed task
on_failure: skip # skip | dlq: what the default on_error returns
drain_timeout: 30s # max wait for in-flight tasks on shutdown
max_pending_tasks: 2000 # new windows wait while this many tasks are unsettled
max_pending_bytes: 1GiB # ... or while this much stdin and task output is held
| Field | Type | Default | Min | Description |
|---|---|---|---|---|
binary_path |
str \| None |
None |
1 char | Default subprocess binary. None requires per-task override via ExecutorTask.binary_path. |
max_executors |
int |
4 |
1 | Concurrent subprocess limit (PriorityGate size). |
executor.task_timeout |
int |
120 |
1 | Per-subprocess wall-clock timeout in seconds. |
max_stdout |
int |
0 |
0 | Maximum bytes of stdout retained per task. 0 = unlimited. Excess output is still read and discarded (the process never blocks on a full pipe); the retained prefix is cut at a UTF-8 character boundary and ExecutorResult.stdout_truncated is set. |
max_stderr |
int |
0 |
0 | Same as max_stdout, for stderr; sets ExecutorResult.stderr_truncated. |
window_size |
int |
100 |
1 | Max messages per arrange() window. |
max_retries |
int |
3 |
0 | Max retries per failed task. 0 disables retries. |
on_failure |
'skip' \| 'dlq' |
'skip' |
– | What the default on_error returns, and what a spent retry budget and a raising on_error become. dlq sends the source messages of a failed task to the DLQ. Any other value fails the load: executor.on_failure must be skip or dlq, got '<v>'. |
executor.drain_timeout |
int |
30 |
1 | Max wait for in-flight tasks during graceful shutdown. On timeout, those tasks are cancelled and their offsets are not committed (they replay on restart). |
max_pending_tasks |
int |
2000 |
max_executors |
New windows wait while this many tasks are created and not settled. A soft limit: it can be passed by the admitted window’s fan-out beyond its estimate, normally one message; a sudden jump in tasks per message passes it by that jump. Below max_executors the load fails: executor.max_pending_tasks (<n>) must be >= executor.max_executors (<m>). |
max_pending_bytes |
size | 1GiB |
16MiB |
New windows wait while task stdin plus task output (in hooks and delivery, or kept for the message and window hooks) reach this size. A soft limit, like max_pending_tasks. |
Environment variable overrides use the DK_EXECUTOR__ prefix: