Skip to content

Handler System

The handler is the user-facing entry point into Drakkar. You subclass BaseDrakkarHandler, override hooks, and the framework calls them at the right time during the message-processing pipeline. See Configuration for the full YAML reference. The Pipeline Map shows which hooks run for each input form and what happens to a message when a step fails.

Hook Reference

Hook When called Frequency Returns
on_startup(config) Before any components are created Once per worker lifetime Modified DrakkarConfig
on_ready(config, db_pool) After sinks connected, before polling Once per worker lifetime None
arrange(messages, pending) A window of messages is ready to process Once per window per partition list[ExecutorTask]
arrange_stream(message) Instead of arrange: one message is ready to process; an async generator Once per message; one group per yield yields list[ExecutorTask]
split(message) Optional; one message is accepted, and split.enabled is true; an async generator Once per source message, and again for each new attempt of a job; one part per yield yields a pydantic model or bytes
part_data(group) Optional; after on_message_complete of a part and its delivery Once per part, only with split BaseModel \| None
part_key(message, part, index) Optional, synchronous; split yielded a part, before the part is published Once per part, on the owner, only with split str \| bytes \| None
aggregate(job) Optional; every part of a split job has a result Once per job, on the owner, only with split CollectResult \| JobAction \| None
on_job_timeout(job) Optional; a timeout of a split job fired Once per timed-out job, on the owner, only with split CollectResult \| JobAction \| None
http_job_result(job) Optional; an HTTP split job ended normally, after aggregate Once per end of an HTTP job, on the owner, only with split.http.enabled a pydantic model, dict, list, str, int, float, bool or None
on_task_complete(result) A single task completes successfully (exit 0) Once per successful task CollectResult \| None
on_group_complete(group, results, errors) All tasks of one group of arrange_stream reached a terminal state, with their hooks and deliveries Once per group (stream handlers only) CollectResult \| None
on_message_complete(group) All tasks derived from a single source message reached a terminal state Once per source message CollectResult \| None
on_window_complete(results, source_messages) All tasks in a window finished Once per window per partition CollectResult \| None
on_error(task, error) A single task fails (non-zero exit, timeout, crash) Once per failed task ErrorAction \| list[ExecutorTask]
on_delivery_error(error) A sink’s deliver() raises an exception Once per failed attempt of a sink’s delivery (not for an open circuit) DeliveryAction
on_assign(partitions) Kafka assigns partitions during rebalance Once per rebalance event None
on_revoke(partitions) Kafka revokes partitions during rebalance Once per rebalance event None
message_label(msg) Before logging each message in arrange Once per message str
request_id(msg) After the message is parsed; for HTTP, before the request is processed Once per message and HTTP request str
task_priority(task) Before each task waits on the executor pool Once per task (incl. retries) sortable key (any <-comparable value)
task_run_seconds(result) Optional; right after a task’s subprocess exits, before its task_completed / task_failed event Once per task that ran a process, only when overridden float \| None
agent_notes() Once after on_startup, when agent.enabled is true Once per worker lifetime AgentNotes \| None
arrange_http_request(req, pending) One HTTP request passed auth + rate-limit + body parsing Once per HTTP request (webapp only) list[ExecutorTask]
on_http_request_complete(group) All tasks from one HTTP request reached a terminal state Once per HTTP request (webapp only) HttpResponseT (a Pydantic model)
http_request_label(req, request_id) Before logging each HTTP request Once per HTTP request (webapp only) str

Which hooks are required follows the enabled input sources. Exactly one of arrange() and arrange_stream() is required when sources.kafka.enabled is true; the four *http* hooks at the bottom are required when sources.http.enabled is true (except with split.http.enabled, where every POST stores a split job and these hooks are not used), together with concrete types in the HttpRequestT / HttpResponseT slots (see Generic type parameters below). A worker running both sources needs both sets. An HTTP-only worker implements only the HTTP hooks and may leave arrange() unimplemented; a Kafka-only worker is the mirror of that. Every other hook has a safe default.


BaseDrakkarHandler

from drakkar import BaseDrakkarHandler

Generic type parameters

BaseDrakkarHandler accepts up to four optional type parameters. The first two control Kafka-path message (de)serialization; the third and fourth opt the handler into the HTTP source pipeline:

# Two-param form (Kafka only). HttpRequestT / HttpResponseT default to None.
class MyHandler(BaseDrakkarHandler[MyInput, MyOutput]): ...


# Four-param form (Kafka + HTTP). Required when sources.http.enabled=true.
class MyHandler(BaseDrakkarHandler[KafkaIn, KafkaOut, HttpReq, HttpResp]): ...

The HTTP slots use PEP 696 default TypeVars, so existing two-param subclasses keep working unchanged – the third and fourth slots materialise to None and the framework never invokes the HTTP hooks. Four-param subclasses opt into the webapp pipeline by declaring concrete Pydantic models in the new slots; the framework reads those at startup and raises ConfigurationError when sources.http.enabled=true but a slot is left at the default. See Webapp → Enabling for the full setup.

All declared type arguments must be Pydantic BaseModel subclasses. At class creation time (__init_subclass__), the framework inspects the generic arguments and sets four class attributes:

Attribute Value
input_model The InputT class, or None
output_model The OutputT class, or None
http_request_model The HttpRequestT class, or None
http_response_model The HttpResponseT class, or None

When input_model is set, every consumed message is automatically deserialized before arrange() is called:

# Framework calls this internally:
msg.payload = MyInput.model_validate_json(msg.value)

If deserialization fails, msg.payload is set to None and the raw bytes remain available in msg.value.

When http_request_model is set, every HTTP request body is parsed into the model before arrange_http_request() is called; parse failures return a flat 422 response without invoking the runner.

Non-generic usage

If you do not need typed deserialization, omit the type parameters:

class RawHandler(BaseDrakkarHandler):
    async def arrange(self, messages, pending):
        for msg in messages:
            raw: bytes = msg.value  # no auto-deserialization
            ...

input_model, output_model, http_request_model, and http_response_model will all be None.


Handler Hooks

Hooks are listed in lifecycle order. All hooks except arrange() have no-op defaults, so you only override what you need.

on_startup

async def on_startup(self, config: DrakkarConfig) -> DrakkarConfig

Called once, before the sinks, the executor pool, the consumer, the recorder and the HTTP servers are created. Receives the loaded config and must return a (possibly modified) DrakkarConfig. This is the only point where config can be changed at runtime.

A few settings are already consumed by then

DrakkarApp.__init__ runs before this hook and builds some things from the config it was given. Changing these in on_startup has no effect, because the object built from the old value already exists:

setting what already consumed it
app the handler’s app-config model (see Application config)
cluster.name, cluster.name_env the worker’s resolved cluster name
worker.name, worker.name_env the worker’s resolved id
sources.kafka.enabled handler validation and source construction
sources.http.enabled handler validation and source construction
storage.dir the worker creates its own-files folder before on_startup runs
sinks.defaults, and on each sink on_failure, max_retries, delivery_timeout, breaker_failures, breaker_cooldown, depends_on, depends_on_wait each sink’s policy is resolved when the worker is constructed

Set those in the config file or through their DK_ environment overrides instead. The worker does not fail on such a change — it logs one on_startup_config_change_ignored warning naming every setting it dropped, so the gap is visible rather than silent.

Everything else — executor, connections, the other sink keys (a sink added here is built too), ui, dlq, cache, logging, metrics, and every sources.* field other than the two enabled switches — is read after the hook and a change to it takes effect.

import os


async def on_startup(self, config: dk.DrakkarConfig) -> dk.DrakkarConfig:
    cpu_count = os.cpu_count() or 4
    config.executor.max_executors = cpu_count * 2
    return config

on_ready

async def on_ready(self, config: DrakkarConfig, db_pool: object) -> None

Called after all sinks are connected and the executor pool is created, but before the consumer starts polling. Use it to initialize handler state, run database migrations, or load lookup tables.

The db_pool argument is an asyncpg.Pool if at least one postgres sink is configured; otherwise it is None.

async def on_ready(self, config: dk.DrakkarConfig, db_pool) -> None:
    self.lookup_table = {}
    if db_pool:
        rows = await db_pool.fetch('SELECT id, name FROM categories')
        self.lookup_table = {r['id']: r['name'] for r in rows}

arrange (required with the Kafka source)

async def arrange(
    self,
    messages: list[SourceMessage],
    pending: PendingContext,
) -> list[ExecutorTask]

Required whenever sources.kafka.enabled is true, and never called otherwise — an HTTP-only worker may leave it unimplemented. Transforms source messages into subprocess tasks. See ExecutorTask for the full task model reference.

Partition isolation. Each call receives messages from exactly one Kafka partition. Drakkar runs an independent pipeline per partition, so arrange() never mixes messages from different partitions in a single call. The maximum number of concurrent arrange() invocations equals the number of partitions assigned to this worker – one per partition at a time.

Windowing. The framework collects up to executor.window_size messages from the partition queue before calling arrange(). A window may contain fewer messages if the queue drains before reaching the limit. While the tasks from one window are executing, the next window can already be collected and arrange() called again for the same partition – windows are processed concurrently within a partition.

When it is called. The partition processor polls messages into a queue. Once enough messages accumulate (or a short timeout passes), they are batched into a window, deserialized (if input_model is set), and passed to arrange(). This happens continuously while the worker is running and the partition is assigned.

pending.pending_task_ids is a set[str] of task IDs currently in-flight for this partition. Use it for O(1) deduplication — but deduplication only works with CONTENT-DERIVED task IDs. A freshly generated make_task_id is random and can never match an in-flight ID (the check below would be dead code); derive the ID from the work itself with make_stable_task_id, so a redelivered message (e.g. after a rebalance) arranges to the same ID and the pending check genuinely fires. Note the pending check dedupes against in-flight tasks from earlier windows; two content-identical messages inside the same window still arrange to one shared ID — keep a local seen set inside arrange() if your topic can carry duplicates within one poll:

async def arrange(self, messages, pending):
    tasks = []
    for msg in messages:
        req = msg.payload
        if req is None:
            continue

        task_id = dk.make_stable_task_id('rg', req.pattern, req.file_path)
        if task_id in pending.pending_task_ids:
            continue

        tasks.append(
            dk.ExecutorTask(
                task_id=task_id,
                args=[req.pattern, req.file_path],
                metadata={'request_id': req.request_id},
                source_offsets=[msg.offset],
            )
        )
    return tasks

If arrange() returns an empty list, all message offsets are immediately marked complete and committed.

Precomputed task results (skip the subprocess)

Sometimes the handler already knows what a task would output — from a cache, a lookup table, deterministic logic, or any other shortcut. Attach a PrecomputedResult to the task via the precomputed field and the framework will skip the subprocess entirely:

async def arrange(self, messages, pending):
    tasks = []
    for msg in messages:
        cached = await self.cache.get(msg.payload.request_id)
        if cached is not None:
            # Short-circuit: handler supplies the outcome directly.
            tasks.append(
                dk.ExecutorTask(
                    task_id=dk.make_task_id('direct'),
                    source_offsets=[msg.offset],
                    metadata={'request_id': msg.payload.request_id},
                    precomputed=dk.PrecomputedResult(stdout=cached),
                )
            )
        else:
            tasks.append(
                dk.ExecutorTask(
                    task_id=dk.make_task_id('run'),
                    args=['--process', msg.payload.request_id],
                    source_offsets=[msg.offset],
                )
            )
    return tasks

Semantics:

  • The framework synthesises an ExecutorResult from the precomputed stdout / stderr / exit_code / duration_seconds and invokes on_task_complete immediately. Downstream hooks (on_message_complete, on_window_complete) see the result indistinguishably from a real subprocess outcome — except result.pid is None and result.task.precomputed is not None if they want to distinguish.
  • No pool slot is consumed. Precomputed tasks bypass the executor semaphore entirely; a cache-hit-heavy workload is not capped by max_executors. A separate counter (drakkar_tasks_precomputed_total) tracks the volume.
  • Non-zero exit_code routes through on_error exactly like a real subprocess failure — RETRY, SKIP, and replacement-list return values all work. This lets the handler cache error outcomes too (uncommon but valid).
  • args is not required when precomputed is set (it defaults to [] and the subprocess never runs).
  • Framework-agnostic about the source. precomputed says “a result was supplied in arrange()”; the framework does NOT interpret it as “cache hit” specifically. The UI event metadata is marked precomputed=true, not cached=true.

Observability:

  • task_started and task_completed events still fire (with metadata.precomputed=true) so the flight recorder timeline stays coherent.
  • executor_duration is observed with the supplied duration_seconds (default 0.0) — set a realistic value if you care about the histogram, or filter on drakkar_tasks_precomputed_total when the synthetic durations would skew your view of real subprocess runs.
  • drakkar_tasks_precomputed_total increments once per precomputed task; operators can chart it against drakkar_executor_tasks_total{status="completed"} to see the short-circuit rate.

When to use it:

Situation Fit
Previously computed result in Redis / in-memory LRU Direct fit — attach to tasks in arrange()
Deterministic input → deterministic output (no binary needed) Direct fit — compute in Python, wrap in PrecomputedResult
Lookup table / enrichment where subprocess would add nothing Direct fit
Expensive subprocess that’s rarely worth running Direct fit — decide in arrange()
Async I/O you don’t want to do in arrange() Less good — moves cache lookup into arrange’s hot path; consider prefetching in on_ready() instead

arrange_stream

async def arrange_stream(self, message: SourceMessage) -> AsyncIterator[list[ExecutorTask]]

Optional, and the other way to the work of arrange(): a handler overrides exactly one of the two. Write it as an async generator. Each yield gives one non-empty list of tasks, a group; the framework starts the group at once and pulls the next one only when the pending budget has room, so a message with many thousands of tasks holds a bounded number of them in memory. A bare return or the end of the function ends the stream. An empty list is ignored.

  • Every task must have source_offsets == [message.offset].
  • Each task gets task.group, its TaskGroup.
  • The worker takes one message at a time: executor.window_size has no effect, and on_window_complete is refused at startup.
  • The offset completes only when the whole message ends; a replay runs every group again.
  • A raise inside the generator fails the stream: the started groups finish and the message never completes. The first such error restarts the partition loop, which goes on with the next messages; the offset stays pending, so the commits of that partition stop and its lag grows until a restart or a rebalance, when the message is read again. A second error marks the partition dead, and /readyz shows it. Catch the errors of side calls inside the generator.
  • At a stop the generator sees GeneratorExit at a yield or CancelledError inside an await; put cleanup in try/finally.

The full rules, the memory bound, the failure and stop behaviour and an example are on the Fan-out page.

group_labels

class ImportHandler(dk.BaseDrakkarHandler):
    group_labels = ('directory', 'file_size')

A class attribute: the label names whose values each group collects into TaskGroup.labels. Default empty. It must be a sequence of unique, non-empty strings, and it may be set only together with arrange_stream(); startup fails otherwise.

Startup checks

Startup fails with a ConfigurationError that names the handler class when:

  • the handler overrides both arrange() and arrange_stream();
  • it overrides arrange_stream() and on_window_complete();
  • group_labels is not a sequence of unique, non-empty strings;
  • it overrides on_group_complete() or sets group_labels without arrange_stream();
  • the Kafka source is on and it overrides neither arrange() nor arrange_stream().

The exact messages are listed on the Fan-out page. With arrange_stream() the worker logs one info line arrange_stream_enabled at startup: it says that executor.window_size has no effect.

The framework finds every hook on the handler class. A function set on an instance (handler.arrange_stream = ...) is not seen.

Splitting a message

The six hooks of this section, and part_data_model, are used only when split.enabled is true. With split.enabled false a handler that overrides split() starts, never calls it, and logs split_disabled once; no hook of this section is checked then. With split.enabled true a handler may override part_data(), part_key(), aggregate(), on_job_timeout() or set part_data_model only together with split(). The Split page explains the whole feature: the topics, restarts, failures and what to know before you turn it on.

class ItemHandler(dk.BaseDrakkarHandler[Request, Output]):
    part_data_model = PartSummary                       # optional

    async def split(self, message: dk.SourceMessage):   # an async generator
        items = message.payload.items
        if len(items) <= 500:
            return                                      # local: process here as usual
        for start in range(0, len(items), 100):
            yield message.payload.model_copy(update={'items': items[start : start + 100]})

    async def part_data(self, group: dk.MessageGroup) -> PartSummary | None:
        return PartSummary(items_done=group.succeeded)

    async def aggregate(self, job: dk.SplitJob) -> dk.CollectResult | dk.JobAction | None:
        if job.failed_parts > job.total_parts // 100:
            return dk.JobAction.DLQ
        return dk.CollectResult(kafka=[dk.KafkaPayload(sink='summaries', data=Summary(parts=job.total_parts))])

    async def on_job_timeout(self, job: dk.SplitJob) -> dk.CollectResult | dk.JobAction | None:
        return dk.JobAction.DLQ                         # the default
  • split(message) is an async generator with one form. Each yield gives one part: a pydantic model (written as its JSON) or bytes (written as they are); any other value fails the job. It is called once for each accepted source message, on the owner, and again for each new attempt of a job after a restart or a takeover (see Timeouts and attempts); under sources.kafka.on_parse_error: skip a message that cannot be parsed reaches it with payload None. A generator that ends before its first yield makes the message local: it runs on the owner as one part, and its end calls aggregate. A raise fails the job with a DLQ record of stage split. The generator is closed like the one of arrange_stream: at most 5 seconds, and try/finally works. The code before the first yield runs while the window holds its reservation of the pending budget, so keep it short. A part is never split again.
  • part_data(group) returns a small model that travels in the result of the part. It runs where the part ran, after on_message_complete and its delivery. Larger than split.max_part_data, or a raise: the data is dropped, data_error says why, and the part still counts as finished.
  • part_key(message, part, index) gives a part an affinity key. It is synchronous and runs on the owner once for each part that split() yields, before the part is published. Parts with the same key go to the same partition of the parts topic. None or an empty key keeps the even spread. A raise, or an answer that is not str, bytes or None, fails the job with a DLQ record of stage split. See Keeping the parts of one entity on one worker.
  • aggregate(job) runs on the owner once every part has a result. It returns a CollectResult (delivered to the aggregate sinks, then the job is done), None or JobAction.DONE (done, nothing delivered), or JobAction.DLQ (the original message goes to the DLQ, then the job is done). A raise, a value of another type, or a result that names a part sink sends the original message to the DLQ with stage aggregate. The default returns JobAction.DLQ when job.failed_parts is above 0, else None.
  • on_job_timeout(job) runs on the owner when a timeout fires. It returns the same types, and its answer is handled like the answer of aggregate; the job is closed as timeout whatever it answers. The default returns JobAction.DLQ. An override can accept a partial job, for example with return await self.aggregate(job).
  • part_data_model is a class attribute: the model that PartResult.data is parsed with. Without it, data is a dict.
  • http_job_result(job) builds the result that the client of an HTTP split job reads with its GET. It runs on the owner after the answer of aggregate was acted on, only for an HTTP job that ends normally, in the scope of aggregate. A pydantic model is dumped with model_dump(mode='json'). A raise, an answer that is not JSON, or JSON larger than split.http.max_response makes the status failed with the outcome response_failed (http_job_result_failed is logged); the job still closes as it ended, and nothing goes to the DLQ. The default returns None. See The result hook.
  • message.http_job is None for every message except the message of an HTTP split job; there it is an HttpJob with request_id, client and deliver_sinks. A part of such a job has message.split.origin == 'http' and message.split.deliver_sinks.

SplitJob

Field Meaning
source_message The original SourceMessage.
job_id The job as log lines show it: <partition>:<offset>#<attempt>.
attempt The number of the attempt.
local True when the message ran on the owner as one part.
total_parts The number of parts; None while the split has not finished (only after a timeout); 1 for a local message.
received_parts How many parts have a result.
failed_parts How many parts failed.
dlq_parts How many parts ended in a dlq outcome.
tasks_succeeded, tasks_failed, tasks_replaced Task counts, summed over the parts.
deliveries For each part sink <type>/<name>: delivered, skipped, failed.
timed_out '', job or idle.
opened_at Epoch seconds of the first open record of the job.
duration_seconds Seconds since opened_at.
missing_parts() The part numbers that have no result. It checks every part number in one go, so its time grows with the number of parts (about 3 seconds for 16 million parts). Call it in on_job_timeout, not for every job.
results() An async iterator of PartResult.

PartResult

Field Meaning
index The part number inside its job, from 0.
worker The name of the worker that ran the part.
outcome ok, or failed when the part did not run to a normal end.
tasks_succeeded, tasks_failed, tasks_replaced Task counts of the part.
deliveries Counts per part sink <type>/<name>: delivered, skipped, failed.
dlq None, or stage, sink, task_id, error, attempts of the dlq outcome.
error The text of a parse failure or of an arrange error.
data The answer of part_data: a model of part_data_model, else a dict; None when absent. Data that does not validate against part_data_model stays a dict.
data_error Why the data was dropped, when it was.
duration_seconds The run time of the part.
finished_at Epoch seconds when the part finished.

A part is failed when it did not run to a normal end: a parse failure, an error of arrange or of the stream, or a dlq outcome. A task that failed and was skipped does not make the part failed; it counts in tasks_failed.

Read the part results in a loop:

async def aggregate(self, job):
    total = 0
    async for result in job.results():     # reads the results topic; seconds for a large job
        if isinstance(result.data, PartSummary):
            total += result.data.items_done
    return dk.CollectResult(...)

Each call of job.results() reads the results topic again, so it costs seconds for a large job. Use the counters of SplitJob and the data of part_data when a total is enough, and read the list only when you need every part. For a local message it yields the one result from memory. The loop raises SplitResultsUnavailable when the read fails (the hook is then called again after 30 seconds, at most 20 times) and SplitResultsExpired when the records of the job are gone (handled as a raise of the hook). See Reading the part results.

Startup checks for split

Condition Result
split.enabled is true and the handler does not override split() startup fails
split.enabled is true and the handler overrides part_data(), part_key(), aggregate() or on_job_timeout(), or sets part_data_model, without split() startup fails
split.enabled is true and split() is not an async generator function startup fails
split.enabled is true, split.http.enabled is false, and the handler overrides http_job_result() startup fails
split.enabled is false no split hook is checked: the worker starts and never calls them. A handler that has a split() method logs split_disabled once

on_task_complete

async def on_task_complete(self, result: ExecutorResult) -> CollectResult | None

Called after each task completes successfully (exit code 0). Runs in the context of the same partition that produced the task via arrange(). Multiple on_task_complete() calls from the same window may run concurrently as tasks finish in any order.

Process the ExecutorResult and return a CollectResult with payloads for one or more sinks, or None to skip per-task delivery (for example when you aggregate in on_message_complete instead). See Sinks for all available payload types.

The result.task field carries the original ExecutorTask, including its metadata dict.

async def on_task_complete(self, result: dk.ExecutorResult) -> dk.CollectResult | None:
    meta = result.task.metadata
    matches = result.stdout.strip().splitlines()

    output = SearchResult(
        request_id=meta['request_id'],
        match_count=len(matches),
        duration_seconds=result.duration_seconds,
    )

    summary = SearchSummary(
        request_id=meta['request_id'],
        match_count=len(matches),
    )

    sinks = dk.CollectResult(
        kafka=[dk.KafkaPayload(data=output, key=meta['request_id'].encode())],
        postgres=[dk.PostgresPayload(table='results', data=summary)],
        redis=[dk.RedisPayload(key=f'search:{meta["request_id"]}', data=summary, ttl=3600)],
    )

    # conditional routing based on business logic
    if len(matches) > 20:
        notification = AlertPayload(request_id=meta['request_id'], count=len(matches))
        sinks.http.append(dk.HttpPayload(data=notification))

    return sinks

on_message_complete

async def on_message_complete(self, group: MessageGroup) -> CollectResult | None

Called once per source message, after every task derived from that message has reached a terminal state. Receives a MessageGroup summarising the whole fan-out — use for N-in → 1-out aggregation where one message produces many subprocess tasks but you want a single aggregated record as output.

Offsets are committed after this hook fires — any sink emissions here are guaranteed delivered-or-failed before the consumer offset advances for this message.

The tasks in group.tasks (and in result.task) have stdin set to None: the framework frees a task’s stdin when the task reaches its last outcome. Keep what you need from it in task.metadata. The stdout and stderr of the kept results count in executor.max_pending_bytes until this hook has run. Without this hook a result’s output counts only while on_task_complete and its delivery run (see Backpressure).

async def on_message_complete(self, group: dk.MessageGroup) -> dk.CollectResult | None:
    req: SearchRequest = group.source_message.payload
    if req is None or group.is_empty:
        return None

    total_matches = sum(sum(1 for line in r.stdout.split('\n') if line) for r in group.results)

    aggregate = RequestSummary(
        request_id=req.request_id,
        total_tasks=group.total,
        succeeded=group.succeeded,
        failed=group.failed,
        total_matches=total_matches,
    )

    return dk.CollectResult(
        kafka=[dk.KafkaPayload(data=aggregate, key=req.request_id.encode(), sink='summaries')],
    )

See the Fan-out page for a complete walkthrough, the full MessageGroup schema with properties, error-path semantics, replacement-chain tracing via parent_task_id, and offset commit ordering.

on_group_complete

async def on_group_complete(
    self,
    group: TaskGroup,
    results: list[ExecutorResult],
    errors: list[ExecutorError],
) -> CollectResult | None

Valid only with arrange_stream(). Called once for each group, after every task of the group has a terminal outcome and the on_task_complete hook and delivery of each task have ended. results are the terminal successes in completion order, errors the terminal failures, as in MessageGroup; result.task.stdin is None.

The framework keeps both lists only for a handler that overrides this hook, and drops them after the hook and its delivery end; their output counts in executor.max_pending_bytes until then. Write small scalar values into group.notes to keep them until on_message_complete.

The returned CollectResult is delivered with the message context, so the sink failure policy and the DLQ apply. A raise is logged (on_group_complete_failed) and ignored; the group counts as finished. on_message_complete always fires after every group hook and its delivery.

TaskGroup

The group of one list yielded by arrange_stream(). Reached as task.group, result.task.group, the first argument of on_group_complete and MessageGroup.groups. It never holds a task, a result or an output text.

Field Type Meaning
index int order of the group in its message, from 0
source_message SourceMessage the message of the group
task_count int tasks in the yielded list
succeeded, failed int terminal outcomes so far
replaced int tasks that on_error replaced
labels dict[str, list[str]] values of each group_labels name on the yielded tasks, in list order
skipped_deliveries dict[str, int] per sink <type>/<name>, deliveries of the group that ended in skip
notes dict[str, str \| int \| float \| bool] small values the hooks keep; a value of another type, or a float that is NaN or infinite, is removed when the group ends (group_notes_invalid)
started_at, finished_at float monotonic times: received; last task settled

A deep copy of a task gets its own copy of the group, whose counters the framework never updates. See the Fan-out page for every rule.

MessageGroup

Passed to on_message_complete. Contains every task scheduled for a single source message, the terminal outcomes, and the wall-clock timing.

Field Type Meaning
source_message SourceMessage the original Kafka input
tasks list[ExecutorTask] full history — includes replaced tasks
results list[ExecutorResult] terminal successes
errors list[ExecutorError] terminal failures (SKIP / retries exhausted)
started_at, finished_at float monotonic timestamps
groups list[TaskGroup] the groups of a stream handler, in index order; empty for arrange()

In stream mode tasks, results and errors are empty; succeeded, failed and replaced are the sums over groups, and total is their sum.

Convenience properties: succeeded, failed, total, replaced, all_succeeded, any_failed, is_empty, duration_seconds.

Full details and examples on the Fan-out page.

PrecomputedResult

Attached to an ExecutorTask via precomputed= when the handler already knows what the subprocess would have produced. See Precomputed task results above for the full story.

Field Type Default Meaning
stdout str '' stdout the framework would have captured
stderr str '' stderr the framework would have captured
exit_code int 0 non-zero routes through on_error like a real failure
duration_seconds float 0.0 set if you want the UI / recorder to show a non-zero duration (e.g. reflect a cache lookup time)

The cache (self.cache)

When cache.enabled=true in config, every handler instance gains a self.cache attribute — a framework-provided key/value cache, memory-backed and periodically flushed to a per-worker SQLite file. It pairs naturally with PrecomputedResult for the classic memoization pattern:

async def arrange(self, messages, pending):
    tasks = []
    for msg in messages:
        cache_key = f'search|{msg.payload.pattern}'

        # Fast path: synchronous memory peek (zero I/O)
        cached = self.cache.peek(cache_key)
        if cached is None:
            # Slower path: memory miss, check SQLite (local + pulled from peers)
            cached = await self.cache.get(cache_key)

        if cached is not None:
            tasks.append(
                dk.ExecutorTask(
                    task_id=dk.make_task_id('search'),
                    source_offsets=[msg.offset],
                    precomputed=dk.PrecomputedResult(stdout=cached),
                )
            )
        else:
            tasks.append(
                dk.ExecutorTask(
                    task_id=dk.make_task_id('search'),
                    args=[msg.payload.pattern],
                    source_offsets=[msg.offset],
                )
            )
    return tasks


async def on_task_complete(self, result):
    if result.pid is not None:  # skip precomputed — already cached
        cache_key = f'search|{result.task.args[0]}'
        self.cache.set(cache_key, result.stdout, ttl=3600)
    # ... return CollectResult as usual

When cache.enabled=false (the default), self.cache is a no-op stub — peek/get return None, set/delete silently discard. Handler code can call the cache unconditionally.

Full API, cross-worker sync behavior, scope rules (MEMORY / LOCAL / CLUSTER / GLOBAL), and the documented “delete is local-only” sharp edge are covered on the dedicated Cache page.

on_window_complete

async def on_window_complete(
    self,
    results: list[ExecutorResult],
    source_messages: list[SourceMessage],
) -> CollectResult | None

Called after all tasks in a window have finished (successes and failures). The results and source_messages belong to the same partition and the same window that was passed to arrange(). Use for cross-task aggregation or batch-level outputs. Returns a CollectResult or None.

As in on_message_complete, result.task.stdin is None here, and the kept results count in executor.max_pending_bytes until the hook has run.

async def on_window_complete(self, results, source_messages):
    succeeded = [r for r in results if r.exit_code == 0]
    if not succeeded:
        return None

    summary = WindowSummary(
        window_size=len(results),
        success_count=len(succeeded),
        avg_duration=sum(r.duration_seconds for r in succeeded) / len(succeeded),
    )
    return dk.CollectResult(
        postgres=[dk.PostgresPayload(table='window_stats', data=summary)],
    )

on_error

async def on_error(
    self,
    task: ExecutorTask,
    error: ExecutorError,
) -> ErrorAction | list[ExecutorTask]

Called when a subprocess task fails (non-zero exit, timeout, or launch error). Runs in the context of the partition that owns the task. Replacement tasks returned here are added to the same window and partition, and count in executor.max_pending_tasks. task.stdin is still set here, so a replacement can be built from it; after the task’s last outcome the framework sets it to None. Return one of:

Return value Behavior
ErrorAction.RETRY Re-run the same task (up to executor.max_retries; then executor.on_failure applies)
ErrorAction.SKIP Drop the task, continue processing
ErrorAction.DLQ Write the task’s source messages to the DLQ; no later delivery of those messages starts
list[ExecutorTask] Spawn replacement tasks instead

The default on_error returns executor.on_failure: SKIP unless the config sets executor.on_failure: dlq. A handler that does not override the hook gets the configured answer.

executor.on_failure also decides two cases the hook does not answer, as a sink’s declared on_failure does for a spent sink budget and a raising on_delivery_error:

  • RETRY when executor.max_retries is spent. The worker logs max_retries_exceeded with action (skip or dlq); with dlq the record is written as for ErrorAction.DLQ, and dk-attempts is max_retries + 1.
  • An on_error that raises (see below).

ErrorAction.DLQ writes the record at once, while the other tasks of the message may still run. The record carries dk-stage: execute, the task id in dk-task-id and the task’s attempts in dk-attempts (see The DLQ record). The task counts as failed, and the message is done: tasks already running finish, but no later result of the message is delivered, and the offset completes when every task settled. A task of a message that is already on the DLQ adds no second record; the worker logs message_already_dlq. If the record cannot be written, dlq.on_send_failure applies (see When the DLQ itself fails) and the worker logs execute_dlq_failed.

The message probe runs the same hook. There ErrorAction.DLQ (an answer, or executor.on_failure: dlq for a spent budget or a raising hook) is a terminal failure of the task, and nothing is written to the DLQ.

If on_error itself raises, the framework contains the exception, logs on_error_hook_failed (its action names the policy), increments drakkar_handler_hook_errors_total{hook="on_error"}, and then applies executor.on_failure: skip makes the task a terminal failure, dlq also writes its record (dk-attempts is the task’s attempts so far). A handler bug must not wedge offset commits: an uncontained exception here would leave the message’s offset pending forever, and since the commit watermark only advances over a gap-free prefix, that would freeze every later commit on the partition and force a full replay from the wedge point on restart. Alert on a non-zero rate of that counter — the pipeline keeps flowing, so nothing else will tell you the hook is broken. The framework contains the equivalent hook error identically.

The ExecutorError fields:

Field Type Description
task ExecutorTask The task that failed
kind 'nonzero_exit' \| 'timeout' \| 'launch_failure' \| 'internal' Structured failure classification. 'nonzero_exit' (default) – non-zero exit code. 'timeout' – exceeded executor.task_timeout. 'launch_failure' – process could not be started. '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 or None Process exit code; None if never started/timeout
stderr str Process stderr or error description
exception str or None Exception message for timeout/launch failures
pid int or None Process ID; None if 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.

async def on_error(self, task, error):
    if error.exit_code == 1 and 'TRANSIENT' in error.stderr:
        return dk.ErrorAction.RETRY
    return dk.ErrorAction.SKIP

on_delivery_error

async def on_delivery_error(self, error: DeliveryError) -> DeliveryAction

Called after every failed attempt of a sink’s deliver(). See Delivery Lifecycle for the full delivery flow and Failure policy for the per-sink settings. The DeliveryError fields:

Field Type Description
sink_name str The configured name of the sink
sink_type str The sink type (kafka, postgres, …)
error str The error text, URL credentials redacted
payloads list[BaseModel] The payloads of the failed group
attempt int The failed attempt, from 1. The quick internal retries of an idempotent write are not counted.
retries_left int Retries left of the sink’s max_retries
declared_policy DeliveryAction The sink’s on_failure: DLQ or SKIP
Return value Behavior
DeliveryAction.DLQ Write the source message to the dead letter queue; the message is done
DeliveryAction.RETRY Re-deliver the whole group while retries_left > 0
DeliveryAction.SKIP Drop this sink’s payloads, continue
  • The default on_delivery_error returns error.declared_policy, so a handler that does not override it gets the sink’s configured on_failure (dlq unless the sink says skip).
  • RETRY with retries_left == 0 is the declared on_failure; the worker logs sink_retry_budget_spent.
  • A hook that raises is logged delivery_error_hook_failed and the declared on_failure applies. The exception does not stop the delivery or the partition. The HTTP source follows the same rule.
  • The hook is not called while the sink’s circuit is open: the declared on_failure decides alone (see Circuit Breaker).

RETRY re-delivers the entire payload group, including any payload the failed attempt already applied — see RETRY is at-least-once over the whole group. Return it when re-applying is harmless; prefer DLQ for operations that count.

async def on_delivery_error(self, error):
    if error.sink_type == 'redis':  # SETs are safe to re-apply
        return dk.DeliveryAction.RETRY
    return error.declared_policy  # the sink's on_failure for everything else

on_assign

async def on_assign(self, partitions: list[int]) -> None

Called when new Kafka partitions are assigned to this worker during a rebalance. Use for per-partition initialization (loading state, resetting caches).

async def on_assign(self, partitions):
    for p in partitions:
        self.partition_cache[p] = {}

on_revoke

async def on_revoke(self, partitions: list[int]) -> None

Called when partitions are revoked from this worker during a rebalance. Use for cleanup (flushing buffers, saving state). A detach of this worker revokes every partition it holds, so this hook runs then too; on_assign runs again when the worker attaches.

async def on_revoke(self, partitions):
    for p in partitions:
        self.partition_cache.pop(p, None)

task_priority

def task_priority(self, task: ExecutorTask) -> Any

Returns a sortable priority key used to order tasks waiting on the executor pool. Smaller keys are scheduled first. Called once per task right before the task waits on the ExecutorPool’s priority gate; retries call it again, but since task.source_offsets does not change between retries the result is identical.

Default:

def task_priority(self, task):
    return min(task.source_offsets) if task.source_offsets else 0

This drains older Kafka messages first, which keeps MessageTracker / OffsetTracker state in front of the watermark small — the slowest task in a fan-out no longer anchors the whole message in memory while later messages pile up behind it.

Why this matters. With a plain FIFO semaphore (the pre-priority behaviour), one slow message in the middle of a window could keep its MessageTracker alive long after later messages had already finished, blocking offset-commit progress and inflating _message_trackers. Priority ordering by oldest-offset turns that into “oldest first → fastest commit watermark progress”.

Override patterns:

class PartitionAwareHandler(BaseDrakkarHandler):
    """Keep partition fairness AND prefer older messages within each partition."""

    def task_priority(self, task):
        offset = min(task.source_offsets)
        # Group every 1000 offsets into one tier so partitions roughly take turns.
        return (offset // 1000, offset)


class TieredHandler(BaseDrakkarHandler):
    """Read a business-priority field stamped on the task by ``arrange()``."""

    def task_priority(self, task):
        # 0 = highest, 9 = lowest. Equal-tier tasks tiebreak by offset.
        tier = task.metadata.get('tier', 5)
        return (tier, min(task.source_offsets))

The return value can be any heapq-comparable object — int, tuple, or a class with __lt__. Equal-priority tasks tiebreak FIFO via the gate’s internal sequence counter.

Tasks with precomputed set bypass the gate entirely — task_priority is not called for them.

Error handling. If task_priority raises, the framework logs a priority_fn_failed warning, ticks drakkar_executor_priority_fn_errors_total, and falls back to the default key. A buggy override never stalls a task.

task_run_seconds

def task_run_seconds(self, result: ExecutorResult) -> float | None

Optional. Returns the run time to draw for this task, or None to use the framework measure.

The framework measures every task’s run time itself: result.duration_seconds runs from just before the spawn to the process exit, and the exit time is read off the event loop (see Task run time and the exit notice). That measure includes everything the process does, such as the start-up of an interpreter. When your binary knows its real work time better, it can print it, and this hook can hand it to the framework. The value sets the length of the task’s bar in the timeline and is recorded as reported_run_seconds in the task_completed / task_failed metadata. duration, drakkar_executor_duration_seconds and every other metric keep the framework measure, so the two can be compared.

Read only the last line. The hook runs once per task on the event loop, so it must be cheap. Parsing the last line costs a few microseconds; a regex over the whole stdout costs time in proportion to its size, for every task:

class TimedHandler(BaseDrakkarHandler):
    def task_run_seconds(self, result):
        # The binary prints its own work time as its last line: "elapsed=0.212"
        last_line = result.stdout.rstrip().rpartition('\n')[2]
        if not last_line.startswith('elapsed='):
            return None  # no time printed for this task: use the framework measure
        return float(last_line.removeprefix('elapsed='))

When it runs. Once per task that ran a subprocess, on success and on failure (a timed-out task is passed too, but its result carries no output: stdout is empty, so a hook that parses the last line returns None there), right before the task’s event is recorded. It is not called for a precomputed result or a launch failure, and not at all when the worker has no recorder. The framework calls it only when your handler overrides it; the default costs nothing. It must be a plain method: an async def task_run_seconds fails the worker at startup.

Invalid answers. Every answer that is not a valid run time falls back to the framework measure:

Answer What happens
None Framework measure; no log line, no count.
A finite number from 0 to duration_seconds + 0.05 Recorded as reported_run_seconds; the bar uses it.
The hook raises Framework measure; a task_run_seconds_hook_failed warning (task_id, error, at most one line per 60 s with suppressed) and drakkar_handler_hook_errors_total{hook="task_run_seconds"}.
Anything else: not a number, NaN, infinite, below 0, or longer than the process ran (duration_seconds + 0.05) The same as a raise, with error = value out of range: <value>.

Limits. The reported time has no start offset inside the process lifetime, so its bar starts at the spawn and can end before the real exit. A capped stdout (executor.max_stdout) can cut the line off: print the time on stderr instead, or keep the line short and last.


Offset Commit Logic

Drakkar uses watermark-based offset tracking to guarantee at-least-once delivery. Understanding this is important for designing arrange() and source_offsets.

How it works

Each partition has an OffsetTracker that maintains a sorted list of offsets and their state (PENDING or COMPLETED):

  1. When messages enter arrange(), their offsets are registered as PENDING.
  2. When a task finishes and all its sink payloads are delivered (or routed to DLQ/skipped), the offsets from task.source_offsets are marked COMPLETED.
  3. The framework asks: what is the highest consecutive completed offset starting from the lowest tracked offset? That value + 1 is committed to Kafka.

Example

A window of 5 messages from partition 3 with offsets [100, 101, 102, 103, 104]:

Step 1: All registered as PENDING
  100=PENDING  101=PENDING  102=PENDING  103=PENDING  104=PENDING
  committable() → None (100 is not completed)

Step 2: Offset 104 finishes first (fastest subprocess)
  100=PENDING  101=PENDING  102=PENDING  103=PENDING  104=COMPLETED
  committable() → None (100 is still pending)

Step 3: Offsets 100 and 101 finish
  100=COMPLETED  101=COMPLETED  102=PENDING  103=PENDING  104=COMPLETED
  committable() → 102 (consecutive run: 100, 101 → commit 101+1)

Step 4: Offsets 102 and 103 finish
  100=COMPLETED  101=COMPLETED  102=COMPLETED  103=COMPLETED  104=COMPLETED
  committable() → 105 (all consecutive → commit 104+1)

The key property: a fast task finishing before earlier tasks does not advance the commit position. Drakkar will never commit offset 105 while offset 100 is still in flight. This prevents message loss on worker crash — Kafka will redeliver from the last committed offset.

What this means for your handler

  • source_offsets must be accurate. Every offset in source_offsets blocks the commit watermark until its task completes and all payloads are delivered. If you include an offset you don’t actually process, it will stall commits for the entire partition.

  • Fewer tasks per window = lower commit latency. A window of 100 messages producing 100 tasks won’t commit until the slowest task finishes. If commit latency matters, use a smaller window_size.

  • One task can cover multiple offsets. If your arrange() batches several messages into one task, list all their offsets in source_offsets. They’ll all be marked complete together when the task finishes.

  • Empty arrange = instant commit. If arrange() returns [], all offsets in the window are marked complete immediately and committed.

When commits happen

Commits are attempted at three points:

  1. As messages settle — when a message’s tasks finish and its sink deliveries succeed, its offset becomes committable. Commits are batched per partition: the commit is sent at once when the watermark has advanced by 300 offsets, otherwise 0.5 s after the first advance that was not yet committed. A message does not wait for the rest of its window.
  2. On partition revocation — pending offsets are drained (up to executor.drain_timeout). Only if drain completes cleanly is the highest committable offset committed before the partition is released. If drain times out, the final commit is skipped — in-flight tasks may still be running, and committing past them would silently skip their messages on reassign. Those messages will replay instead (at-least-once).
  3. On shutdown — same drain-then-commit-if-clean behavior as revocation.

Commits are per-partition. Each commit is awaited until the broker confirms it (commit(asynchronous=False)), but the wait does not block the event loop, so the processing loop keeps running.


Typed Messages

Define Pydantic models for your input and output schemas, then pass them as type parameters to BaseDrakkarHandler:

from pydantic import BaseModel


class SearchRequest(BaseModel):
    request_id: str
    pattern: str
    file_path: str


class SearchResult(BaseModel):
    request_id: str
    match_count: int
    duration_seconds: float


class MyHandler(dk.BaseDrakkarHandler[SearchRequest, SearchResult]):
    async def arrange(self, messages, pending):
        for msg in messages:
            req: SearchRequest = msg.payload  # auto-deserialized
            ...

The framework calls SearchRequest.model_validate_json(msg.value) before arrange(). If parsing fails, msg.payload is None and the raw bytes remain in msg.value.

Access either form in your hooks:

req = msg.payload  # SearchRequest instance (or None on parse error)
raw_bytes = msg.value  # always available

message_label()

def message_label(self, msg: SourceMessage) -> str

Override to provide a human-readable label used in structured log lines and the operator web UI. The default returns partition:offset.

def message_label(self, msg):
    if msg.payload:
        return f'{msg.partition}:{msg.offset} [{msg.payload.request_id[:8]}]'
    return f'{msg.partition}:{msg.offset}'

request_id()

def request_id(self, msg: SourceMessage) -> str

Every Kafka message and every HTTP request gets a request id. The framework asks this hook once per message, right after the message is parsed (so msg.payload is set), and once per HTTP request before the request is processed. The default returns a generated id, req_<UTC time>_<8 random hex per process>_<counter>, for example req_20261111T093000_3f9a1c2e_0042, which is unique across workers.

The id is used everywhere the framework names a message:

  • msg.request_id, set right after the hook, so every later hook can read it;
  • every log line written while the message is processed (see Request ID);
  • task.request_id and the task label request_id of its tasks (a task built from several messages gets their ids joined with ,);
  • its recorder rows, the dk-request-id header of its DLQ record, and the HTTP response.

Override it to use an id the message already carries:

def request_id(self, msg):
    if msg.topic == '__webapp__':  # an HTTP request
        upstream = dict((name.lower(), value) for name, value in msg.headers).get('x-request-id')
        if upstream:
            return upstream.decode()
    elif msg.payload is not None:
        return f'order-{msg.payload.order_id}'
    return dk.make_request_id('req')

For an HTTP request msg has the topic __webapp__, partition -1, offset 0, no key, the raw request body as value, the request headers as headers and the parsed request as payload. Keep the id unique: the framework does not check that. The answer must be at most 64 ASCII characters with no whitespace. A hook that raises or answers something else gets a generated id, and the worker logs request_id_hook_failed (at most one line per minute). The hook runs for every message, so keep it fast.


Task Labels

ExecutorTask.labels is a dict[str, str] of user-defined key-value pairs displayed alongside task details in the operator UI. Set them in arrange():

dk.ExecutorTask(
    task_id=dk.make_task_id('rg'),
    args=[req.pattern, req.file_path],
    metadata={'request_id': req.request_id},
    labels={
        'request_id': req.request_id,
        'pattern': req.pattern,
    },
    source_offsets=[msg.offset],
)

Labels appear on:

  • The live timeline view
  • The task detail page
  • Running and finished task tables
  • The trace view on the Debug page

Labels are purely for display. Use metadata for data you need in on_task_complete(), on_message_complete(), or on_error().

Labels only carry short strings, and only on a task. When you want to expose structured diagnostics — the candidates a hook considered, the flag that explains a decision — and attach them to a message or a whole window as well as a task, use annotations:

self.annotate(msg, 'input_selection', {'candidates': paths, 'chosen': p})

Annotations

self.annotate(target, kind, data, labels=...) records structured diagnostics against a window, a source message, or a task, visible on that entity’s trace in the debug UI and expiring with the flight recorder’s normal retention. The optional labels keyword attaches string labels stored on the row, indexed and searchable the same way ExecutorTask.labels are. See Annotations for scopes, budgets, and the drop policy.


UI Class Attributes

Two optional class attributes let a handler extend the operator UI without any client-side code:

probe_details_model — a Pydantic model class that opts the handler into the Message Probe’s user-defined details tab: during a probe run, hooks write into the model’s fields via the module-level probe.set / probe.append / probe.update verbs (from drakkar import probe), and the UI renders the result as its own tab. See Probe User Details for the model conventions, probe_field() views, and the write caps.

Any handler code can ask whether it runs inside a Message Probe run: probe.is_active() (from drakkar import probe) is True in every hook that a probe calls, and False in the pipeline. Use it to keep a probe from an effect that the framework cannot see, such as a call that changes another service. See Checking for a probe run.

ui_pages — a list of Page declarations, each describing a custom dashboard page built from widgets over built-in data sources. Registered pages appear as extra navigation entries and are validated at startup, so a broken declaration fails the boot rather than a page render. See Declared UI Pages for the page/widget vocabulary.

App Config Class Attributes

app_config_model and app_env_prefix declare a user-defined application config: your own Pydantic model, loaded by the framework from the reserved app: section of the same drakkar.yaml plus env vars under your own prefix (e.g. MYAPP_PRIORITY_THRESHOLD=20), validated fail-fast at startup, and exposed as self.app_config in every hook — on_startup included. Secrets (SecretStr or the drakkar_secret marker) mask in the Debug UI’s config reference, where the model appears as its own group. See App Config.


Offloading CPU-bound Work

await self.offload(fn, *args, **kwargs) runs a plain synchronous function on a small thread pool and returns its result — for hooks whose heavy pure-Python computation (nested loops deriving task parameters, result crunching) would otherwise stall the event loop for seconds. The sync cache ops and self.annotate work inside the offloaded function. See Offload for the full contract, the cache warm-then-peek pattern, and the observability that comes with it.


Periodic Tasks

Decorate async handler methods with @periodic to run them on a schedule: an interval in seconds, or a five-field cron expression in UTC. A worker task (the default) runs on every worker; a cluster task runs on exactly one worker of the cluster at each slot. The schedules, the slot rule, the YAML overrides and the definition hash are on Periodic Tasks.

from drakkar import periodic


class MyHandler(dk.BaseDrakkarHandler[MyInput, MyOutput]):
    @periodic(60)
    async def reload_country_lookup_table(self):
        self.country_lookup = await fetch_country_lookup()

    @periodic(cron='*/10 * * * *', scope='cluster')
    async def refresh_shared_exchange_rates(self):
        await copy_exchange_rates_into_reporting_table()

    @periodic(30, on_error='stop')
    async def check_corpus_directory_exists(self):
        if not os.path.isdir('/data/corpus'):
            raise RuntimeError('Corpus directory missing')

Behavior

  • The decorator checks the declaration when the module is imported and raises PeriodicRuleError (a ValueError) that names the method.
  • Periodic tasks start after on_ready() completes.
  • They run in the same async event loop as the rest of the worker.
  • Runs of one task never overlap on one worker: a worker interval task sleeps its interval from the end of the previous run.
  • All periodic tasks are cancelled during shutdown. A cluster task’s lease is not released then; it ends by itself.

Error handling

on_error value Behavior on exception
'continue' (default) Log the error, keep running on schedule
'stop' Log the error, cancel this task permanently

Detach, attach and stop

Four members let the handler take the worker out of its Kafka consumer group for a bounded time, bring it back, and stop the whole worker. They are not hooks: the handler calls them. The full rules, the answers and the risks are on Detach from the Consumer Group.

Member What it does
await self.detach(duration=None, reason='') Leave the consumer group for duration seconds (None: sources.kafka.detach.default_duration; below 10 seconds or above max_duration raises ValueError). Returns a DetachResult (detached, reason, until) when the revoke drain has ended, or with a refusal reason. Needs sources.kafka.detach.enabled.
await self.attach(reason='') Join the consumer group again. Returns an AttachResult (attached, reason). It does not end an operator detach (held_by_operator).
self.detach_state The state now: state (attached, detaching, detached, attaching), origin, reason, since, until.
self.request_stop(reason='', exit_code=0) Shut the worker down gracefully, as on SIGTERM, and exit with exit_code (0 to 255). Not awaited; the first call wins. Works with the detach feature off.

detach() is refused with inside_pipeline_hook from code that runs as part of a partition’s work: arrange, arrange_stream, the completion hooks, on_error and on_delivery_error, also through asyncio.gather or asyncio.wait_for. Call it from a periodic task, on_assign, on_revoke, the HTTP hooks, or a task the handler started itself. Inside a Message Probe run, detach() and attach() answer probe and request_stop() does nothing.

@dk.periodic(30)
async def leave_the_group_while_the_disk_is_slow(self):
    seconds = await asyncio.to_thread(time_disk_write, DISK_PROBE_FILE)
    if self.detach_state.state == 'attached' and seconds > SLOW_DISK_SECONDS:
        result = await self.detach(duration=15 * 60, reason=f'disk write took {seconds:.1f}s')
        if not result.detached:
            # The next probe asks again; a refusal never stops the worker.
            await logger.awarning('slow_disk_detach_refused', reason=result.reason)

The names come from the full example on Detach.

A handler class that defines its own attribute named detach, attach, detach_state or request_stop hides the framework member of the same name.


Custom Prometheus Metrics

Declare prometheus_client metrics as class attributes on your handler. The framework auto-discovers them and exposes them on the operator UI metrics page alongside built-in Drakkar metrics.

from prometheus_client import Counter, Gauge, Histogram


class MyHandler(dk.BaseDrakkarHandler[MyInput, MyOutput]):
    items_processed = Counter(
        'app_items_processed_total',
        'Total items processed',
    )
    active_sessions = Gauge(
        'app_active_sessions',
        'Currently active sessions',
    )
    match_count = Histogram(
        'app_match_count',
        'Matches per request',
        buckets=(0, 1, 5, 10, 50, 100, 500),
    )

    async def on_task_complete(self, result):
        self.items_processed.inc()
        self.match_count.observe(len(result.stdout.splitlines()))
        ...

The auto-discovery scans the handler’s class hierarchy (MRO) for attributes that are instances of MetricWrapperBase (Counter, Gauge, Histogram, Summary, Info). Use an app_ prefix to distinguish your metrics from Drakkar’s built-in drakkar_ metrics in dashboards and queries.

Agent Notes

When agent.enabled is true, the worker serves the agent routes under /api/v1/agent: a read-only surface that explains the worker to an AI agent (see Agent Surface). The framework knows its own concepts, metrics and rules. Your handler can add the business knowledge with agent_notes():

import drakkar as dk
from prometheus_client import Counter


def refunds_waiting(snapshot: dk.AgentSnapshot) -> dk.AgentFinding | None:
    budget = snapshot.part('budget')
    if budget is None or budget['tasks'] < 100:
        return None
    return dk.AgentFinding(evidence={'tasks': budget['tasks']})


class BillingHandler(dk.BaseDrakkarHandler[BillingInput, BillingOutput]):
    refunds_written = Counter('app_refunds_written', 'Refunds written to the ledger.')

    def agent_notes(self) -> dk.AgentNotes | None:
        return dk.AgentNotes(
            concepts=[
                dk.AgentTopic(
                    key='refund',
                    summary='Each task writes the refunds of one customer.',
                    body='The task label `customer` holds the customer id.',
                    related=['concept:pipeline', 'app:recipe:missing-refund'],
                ),
            ],
            recipes=[
                dk.AgentRecipe(
                    key='missing-refund',
                    summary='Find a refund that was not written.',
                    question='Why is the refund of a customer missing?',
                    steps=[
                        dk.AgentRecipeStep(
                            do='Call /api/v1/agent/state?parts=recent_failures.',
                            why='A failed task names the customer in its label.',
                        ),
                    ],
                    causes=[
                        dk.AgentRecipeCause(
                            cause='The ledger sink failed.',
                            check='The sink row of the ledger has breaker_open true.',
                            fix='Fix the ledger database, then replay the DLQ records.',
                        ),
                    ],
                ),
            ],
            metrics={
                'app_refunds_written_total': dk.AgentMetricNote(
                    meaning='Refunds the ledger accepted.',
                    healthy='Grows while refund messages arrive.',
                    promql=[dk.AgentPromql(title='Refunds per second', query='rate(app_refunds_written_total{{{worker}}}[5m])')],
                ),
            },
            app_config={'ledger.url': 'The address of the ledger service.'},
            rules=[
                dk.AgentRule(
                    key='refunds-waiting',
                    severity='warning',
                    title='Many refund tasks wait',
                    suggestion='Check the ledger latency before you add executors.',
                    explain='app:concept:refund',
                    check=refunds_waiting,
                ),
            ],
        )

What each field adds.

Field Where it appears
concepts, recipes The manual part app (/api/v1/agent/manual?parts=app), as app:concept:<key> and app:recipe:<key>.
metrics The meaning, healthy and (with detail=full) promql of the handler metric on /api/v1/agent/metrics, and an entry app:metric:<name> in the manual part app. The key is the name the metric is exposed with (app_refunds_written_total) or its family name (app_refunds_written); it must be a metric that the handler declares.
app_config The meaning of the app keys on /api/v1/agent/config. The key is a path below app (ledger.url; app.ledger.url is the same path).
rules Run by /api/v1/agent/diagnose after the framework rules, named app:<key>, and listed in the manual part app as app:rule:<key>.

References. related and a rule’s explain hold references: a framework entry (concept:pipeline, metric:drakkar_pending_tasks, rule:budget-saturated), a config path (config:executor.max_executors), or another note (app:concept:<key>, app:recipe:<key>, app:metric:<name>, app:rule:<key>). In app:metric:<name>, the name is the exposed name (app_refunds_written_total); a family name there names nothing. A rule with no explain points at its own entry app:rule:<key>.

Checks. The models refuse a key that is not lower-case letters, digits, - and _, a summary longer than 200 characters, and text with a line break where one line is expected. The worker calls agent_notes() once after on_startup, only when agent.enabled is true. Then it checks the notes:

Problem Result
The hook raises, is an async def, or returns something that is not AgentNotes or None agent_notes_failed (error, category handler); the worker runs without notes.
A key used twice in one kind, a metric the handler does not declare, a reference that names nothing (also a note that names a dropped note) That note is dropped; one agent_notes_invalid warning (category agent) lists every reason; the other notes stay.

Rules. A rule gets an AgentSnapshot: state holds every part of /api/v1/agent/state (a part that could not be read is None; the rows of recent_failures never hold stderr_tail, args or args_truncated, also with agent.include_payloads: true), and metrics holds three framework counters by exposed name: drakkar_recorder_dropped_events_total, drakkar_recorder_postgres_dropped_rows_total and drakkar_sink_dlq_messages_total. The snapshot is read-only: maps cannot be changed and lists are tuples. Return an AgentFinding with JSON evidence (numbers, names, ids; never payload text), or None. Read your own metric objects directly when a rule needs them.

Each rule runs on a thread of its own, never on the event loop, with a limit of 1 second. The rules of one call run at the same time.

Rule outcome Diagnose answer
Returns None Listed in checked, no finding.
Returns an AgentFinding A finding with the rule’s severity, title, suggestion and explain.
Raises, returns another type, or gives evidence that is not plain JSON with finite numbers Listed in failed with the error text, cut to 500 bytes; the other rules still run.
Gives evidence larger than 4096 bytes of compact JSON Listed in failed with the evidence is larger than 4096 bytes.
Runs longer than 1 second Listed in failed with timed out after 1 s; the worker logs agent_rule_abandoned (warning, category agent, rule) once and does not wait for it. Python cannot stop a running thread, so the rule goes on; until it returns, later calls list it as failed at once and do not start it a second time.

Two diagnose calls at the same time share one run of a rule: the second call waits for the run the first call started and gets its result, as long as the run is within its 1 second.

Keep rules fast and pure: a rule that blocks holds its thread, not the API server, the event loop or the other rules.