API Reference#

binomic.client#

class binomic.client.Binomic(broker_dsn: str, module_name: str, config: BinomicConfig, **broker_kwargs: Any)#

The client tying task discovery, scheduling and submission together.

Constructing one discovers the task modules of module_name into a private registry. start/close manage the broker and the scheduler; the async context manager additionally assembles the Master, registers cron/interval tasks and tears everything down on exit. dead_letters resolves the broker and returns a per-queue operations handle over its dead-letter surface (inspect and replay) when the broker implements the capability.

async close() → None#

Stop the scheduler and close the broker; safe to call repeatedly.

async dead_letters(queue: str) → DeadLetters#

Resolve the broker and return its dead-letter operations handle.

Client-side resolution: lazily creates and starts the broker, probes the DLQ capability, then hands the narrowed broker to a DeadLetters handle bound to queue (inspect, replay, and on-demand pruning; the worker’s retention sweep is the automatic default).

async start() → None#

Start the broker and the scheduler; safe to call repeatedly.

async submit(message: Message) → MessageEntry | None#

Submit a message for delivery according to its task’s mode.

direct enqueues immediately and returns the broker’s MessageEntry. None means the enqueue degraded internally (already logged). A full target queue raises QueueCapacityError. cron and interval tasks are periodic and reject submit — they are registered when the async context starts.

class binomic.client.BinomicConfig(queues: list[str], workers: int = 1, concurrency: int = 5, max_attempts: int = 3, task_timeout: float = 600.0, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, capacity: int | None = None, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#

Binomic configuration.

workers is the number of worker subprocesses the master spawns and concurrency the number of tasks each worker executes concurrently; every stream in queues is consumed by all workers. max_attempts is how many times a message may be delivered before it is moved to the DLQ. task_timeout is a message’s total delivery deadline in seconds, measured from enqueue; execution receives the part still left after the queue wait. read_count and poll_interval shape each worker’s fetch loop; heartbeat_interval and reclaim_interval set the liveness beat and crash-recovery cadence. capacity caps every queue’s unacknowledged total (its stream length: messages stay in the stream from submission until ack or dead), so submissions onto a full queue are rejected immediately; unlimited by default. Retry and reclaim re-entries keep the total constant and never consume capacity. dlq_retention is how long a record may sit in a queue’s dead-letter queue before the worker’s periodic sweep deletes it; None disables the sweep and keeps DLQ records forever. worker_init runs once per worker subprocess before its event loop starts (the hook for installing OpenTelemetry SDK providers), and otel_enabled gates all telemetry — with the default False binomic emits nothing and leaves message envelopes untouched. Structlog logs are not affected by the switch.

class binomic.client.BinomicFactory(broker_dsn: str, module_name: str, config: BinomicConfig, **broker_config: Any)#

Binomic working client factory.

create() → Binomic#

Return the client, creating it on the first call.

class binomic.client.DeadLetters(broker: BrokerDeadLetterCapability, queue: str)#

Operations on one queue’s dead letters.

Constructed by Binomic.dead_letters with a broker already resolved and probed for the DLQ capability; a thin, stateless facade — the queue is fixed at creation and every call delegates to the broker. Cleanup runs two ways: the worker’s retention sweep (dlq_retention) is the automatic default, and prune is the explicit on-demand trigger.

async depth() → int#

Return how many dead letters the queue currently holds.

async list(limit: int = 50, cursor: str | None = None) → tuple[list[DeadLetterEntry], str | None]#

Page through the dead letters oldest-first.

async prune(retention: float) → int#

Delete dead letters older than retention seconds; return the count.

The explicit counterpart of the worker’s automatic sweep — same primitive, invoked on demand. retention must be positive; deletion is irreversible, including records never replayed.

async read(entry_id: str) → DeadLetterEntry | None#

Return one full record by stream entry id, or None.

async replay(entry_id: str) → MessageEntry | None#

Re-deliver a dead letter as a brand-new message; the record stays.

binomic.client.config#

class binomic.client.config.BinomicConfig(queues: list[str], workers: int = 1, concurrency: int = 5, max_attempts: int = 3, task_timeout: float = 600.0, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, capacity: int | None = None, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#

Binomic configuration.

workers is the number of worker subprocesses the master spawns and concurrency the number of tasks each worker executes concurrently; every stream in queues is consumed by all workers. max_attempts is how many times a message may be delivered before it is moved to the DLQ. task_timeout is a message’s total delivery deadline in seconds, measured from enqueue; execution receives the part still left after the queue wait. read_count and poll_interval shape each worker’s fetch loop; heartbeat_interval and reclaim_interval set the liveness beat and crash-recovery cadence. capacity caps every queue’s unacknowledged total (its stream length: messages stay in the stream from submission until ack or dead), so submissions onto a full queue are rejected immediately; unlimited by default. Retry and reclaim re-entries keep the total constant and never consume capacity. dlq_retention is how long a record may sit in a queue’s dead-letter queue before the worker’s periodic sweep deletes it; None disables the sweep and keeps DLQ records forever. worker_init runs once per worker subprocess before its event loop starts (the hook for installing OpenTelemetry SDK providers), and otel_enabled gates all telemetry — with the default False binomic emits nothing and leaves message envelopes untouched. Structlog logs are not affected by the switch.

binomic.task#

exception binomic.task.DuplicateTaskError#

Exception raised when a task with the same name already exists.

binomic.task.OnDeadReason#

alias of str

exception binomic.task.TaskNotFoundError#

Exception raised when a task with the given name does not exist.

class binomic.task.TaskRegistry#

An in-process name-to-spec map.

Registries are per-owner, not global: the client and every worker handler build their own from autodiscover and never share one across processes.

get(name: str) → TaskSpec#

Return the spec registered under name.

Raises TaskNotFoundError when the name is unknown.

register(spec: TaskSpec) → None#

Add spec under its name.

Raises DuplicateTaskError when the name is already taken.

class binomic.task.TaskScheduler(timezone: tzinfo = datetime.timezone.utc)#

A thin APScheduler wrapper over plain callables.

It knows nothing about task specs: callers supply the callable, the trigger value and the arguments. The client owns one for cron/interval delivery; every handler owns one for retry backoff. Times default to UTC.

property client: AsyncIOScheduler#

The underlying scheduler, created and started on first access.

close() → None#

Shut the scheduler down without waiting for running jobs.

cron(func: Callable[[...], Any | Awaitable[Any]], *, cron: str, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func on the crontab expression cron.

delay(func: Callable[[...], Any | Awaitable[Any]], *, delay: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func once, delay seconds from now.

Misfire grace is disabled, so a late job still runs instead of being silently dropped.

interval(func: Callable[[...], Any | Awaitable[Any]], *, interval: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func every interval seconds.

property running: bool#

Whether start has been called and close has not.

start() → None#

Start the scheduler; idempotent while already running.

class binomic.task.TaskSpec(name: str, queue: str, func: Callable[[P], T], mode: Literal['direct', 'cron', 'interval'], cron: str | None = None, interval: float | None = None, on_dead_hook: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None)#

A declared task: its name, queue, callable and scheduling mode.

direct tasks run on submission; cron and interval tasks run periodically and take no arguments. The queue belongs to the declaration, not to the message.

binomic.task.autodiscover(package: str) → list[TaskSpec]#

Import every tasks module under package and collect its specs.

A tasks module is a tasks.py or tasks/__init__.py at any depth below the package. A missing package raises ValueError; an ImportError raised while importing a tasks module skips that module, and any other error propagates. Specs are returned, not registered.

binomic.task.task(queue: str, *, mode: Literal['direct'] = 'direct', on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) → Callable[[Callable[P, T]], TaskSpec[P, T]]#
binomic.task.task(queue: str, *, mode: Literal['cron'], cron: str, on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) → Callable[[Callable[P, T]], TaskSpec[P, T]]
binomic.task.task(queue: str, *, mode: Literal['interval'], interval: float, on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) → Callable[[Callable[P, T]], TaskSpec[P, T]]

Declare a task in queue and return its TaskSpec.

direct tasks are submitted by name and execute as soon as a worker picks the message. cron and interval tasks are periodic: the client registers them when its async context starts, so they take no arguments and reject submit. on_dead is an optional notification hook, called once after the message enters the DLQ.

binomic.task.scheduler#

class binomic.task.scheduler.TaskScheduler(timezone: tzinfo = datetime.timezone.utc)#

A thin APScheduler wrapper over plain callables.

It knows nothing about task specs: callers supply the callable, the trigger value and the arguments. The client owns one for cron/interval delivery; every handler owns one for retry backoff. Times default to UTC.

property client: AsyncIOScheduler#

The underlying scheduler, created and started on first access.

close() → None#

Shut the scheduler down without waiting for running jobs.

cron(func: Callable[[...], Any | Awaitable[Any]], *, cron: str, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func on the crontab expression cron.

delay(func: Callable[[...], Any | Awaitable[Any]], *, delay: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func once, delay seconds from now.

Misfire grace is disabled, so a late job still runs instead of being silently dropped.

interval(func: Callable[[...], Any | Awaitable[Any]], *, interval: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) → None#

Run func every interval seconds.

property running: bool#

Whether start has been called and close has not.

start() → None#

Start the scheduler; idempotent while already running.

binomic.broker#

class binomic.broker.Broker(*args, **kwargs)#

The delivery-path surface every broker implements.

Messages are enqueued into a queue, acquired by a named consumer, then acked, dead-lettered or requeued. retry preserves the original enqueued_at; reclaim rewrites it for recovered deliveries.

class binomic.broker.BrokerDeadLetterCapability(*args, **kwargs)#

Optional DLQ management surface a broker may implement.

Kept out of Broker so custom brokers stay valid without it; callers (the Binomic convenience methods and the worker’s prune sweep) probe for the capability with isinstance. Reads are plain commands whose connection errors propagate — management is an explicit operation, not a delivery-path concern — while the prune script keeps the ScriptResponse degrade contract.

async dlq_depth(queue: str) → int#

Return how many records the queue’s DLQ currently holds.

async dlq_list(queue: str, limit: int = 50, cursor: str | None = None) → tuple[list[DeadLetterEntry], str | None]#

Page through the DLQ oldest-first.

Returns (records, next_cursor); next_cursor is None at the end of the stream, otherwise feed it back as cursor (an exclusive bound, so pages never repeat or skip). Entries whose hash record is missing are skipped, not errors.

async dlq_prune(queue: str, retention: float) → int#

Delete records that entered the DLQ more than retention seconds ago.

The entry age comes from the DLQ stream entry id’s millisecond stamp, so the payload is never decoded; at most one bounded batch is deleted per call. retention must be positive. Returns the number of records deleted; script failures degrade to 0.

async dlq_read(queue: str, entry_id: str) → DeadLetterEntry | None#

Return one full record by DLQ stream entry id, or None.

async dlq_replay(queue: str, entry_id: str) → MessageEntry | None#

Re-deliver a DLQ record as a brand-new message.

The replay carries a fresh UUID and attempt = 1 (a full retry budget) and targets the record’s original queue; the source record is kept. Raises DeadLetterEntryNotFoundError when the id is unknown, and QueueCapacityError out of enqueue on a full queue; None means the enqueue degraded (warning already logged).

class binomic.broker.BrokerFactory(dsn: str, queues: list[str], namespace: str, capacity: int | None = None, **broker_config: Any)#

A factory class for creating broker instances.

create() → Broker#

Build the broker selected by the DSN scheme.

redis/rediss return a RedisBroker; amqp is recognized but not implemented; any other scheme raises ValueError.

class binomic.broker.BrokerLifecycleCapability(*args, **kwargs)#

The start/stop half of the broker surface.

Clients and workers bring a broker up through this mixin, so any implementation that wires its own connections on start fits the framework regardless of inheritance.

class binomic.broker.BrokerTelemetryCapability(*args, **kwargs)#

Optional observability probes a broker may implement.

Kept out of Broker so custom brokers stay valid without them; the framework probes this capability and degrades (root spans, no queue gauges) when it is absent.

async observe(queue: str) → tuple[int, float | None] | None#

Probe queue depth for observability, outside the delivery path.

Returns (depth, oldest entry age in seconds); the age is None on an empty stream and the whole result None when the probe degrades, so a hiccup never reads as an empty queue.

async trace_context(queue: str, message_id: str) → dict[str, str] | None#

Read the delivery trace context stored for a message id.

None means no context was stored or the read degraded; telemetry then falls back to a root span.

class binomic.broker.DeadLetterEntry(id: str, queue: str, message: Message, enqueued_at: float, dead_at: float)#

A DLQ record: a message entry plus when it entered the DLQ.

dead_at is derived from the DLQ stream entry id, whose prefix is the Redis server timestamp in milliseconds.

classmethod from_entry(entry: MessageEntry) → Self#

Build a DLQ record from entry, deriving dead_at from its id.

exception binomic.broker.DeadLetterEntryNotFoundError(queue: str, entry_id: str)#

Exception raised when a DLQ entry id has no record to operate on.

Broker.dlq_replay raises it when the entry was never in the DLQ or has since been pruned; the DLQ keeps no tombstones, so the id is simply gone.

class binomic.broker.Message(*, id: UUID = <factory>, task: str, attempt: int = 1, args: Iterable[Any] | None = None, kwargs: Mapping[str, ~typing.Any] | None=None)#

The payload submitted to a queue.

task names the registered task; the queue comes from that task’s declaration, never from the message. attempt starts at 1 and is incremented by the broker on retry and reclaim, so it survives redelivery because it is serialized with the payload.

class binomic.broker.MessageEntry(id: str, queue: str, message: Message, enqueued_at: float)#

A message plus its delivery envelope, as stored by the broker.

id is the stream entry id, queue the owning queue, and enqueued_at the enqueue time in seconds. Retry keeps the original stamp (the deadline is measured from first delivery); reclaim rewrites it.

exception binomic.broker.QueueCapacityError(current: int, capacity: int)#

Exception raised when a submission is rejected on a full queue.

Broker.enqueue raises it when the target queue’s unacknowledged total has reached the effective capacity; current is the depth observed at rejection and capacity the limit that was applied.

class binomic.broker.RedisBroker(dsn: str, queues: Sequence[str], namespace: str, capacity: int | None = None, **config: Any)#

Redis Streams broker backed by atomic Lua scripts.

namespace is both the key prefix ({namespace}:{queue}:stream) and the consumer group name. Payloads live in a per-queue hash while stream entries carry only the message id; dead messages land in :dlq:stream plus :dlq:hash. capacity caps every queue’s unacknowledged total (the stream length); unlimited by default. It stays an explicit constructor parameter, kept out of **config: everything there feeds the Redis connection pool, so the broker’s own options do not compete for that namespace.

async dlq_depth(queue: str) → int#

Return how many records the queue’s DLQ currently holds.

async dlq_list(queue: str, limit: int = 50, cursor: str | None = None) → tuple[list[DeadLetterEntry], str | None]#

Page through the DLQ oldest-first.

Returns (records, next_cursor); next_cursor is None at the end of the stream, otherwise feed it back as cursor (an exclusive bound, so pages never repeat or skip). Entries whose hash record is missing are skipped, not errors.

async dlq_prune(queue: str, retention: float) → int#

Delete DLQ records older than retention seconds; return the count.

retention must be positive. Deletion is bounded to one batch per call and degrades to 0 on script failure.

async dlq_read(queue: str, entry_id: str) → DeadLetterEntry | None#

Return one full record by DLQ stream entry id, or None.

async dlq_replay(queue: str, entry_id: str) → MessageEntry | None#

Re-deliver a DLQ record as a brand-new message.

The replay carries a fresh UUID and attempt = 1 (a full retry budget) and targets the record’s original queue; the source record is kept. Raises DeadLetterEntryNotFoundError when the id is unknown, and QueueCapacityError out of enqueue on a full queue; None means the enqueue degraded (warning already logged).

async enqueue(queue: str, message: Message, context: Mapping[str, str] | None = None) → MessageEntry | None#

Enqueue a message, raising on a full queue.

Raises QueueCapacityError when the queue’s unacknowledged total has reached its effective capacity; internal script failures keep degrading to None.

async observe(queue: str) → tuple[int, float | None] | None#

Probe queue depth for observability, outside the delivery path.

Returns (depth, oldest entry age in seconds); the age is None on an empty stream and the whole result None when the probe degrades, so a hiccup never reads as an empty queue.

async trace_context(queue: str, message_id: str) → dict[str, str] | None#

Read the delivery trace context stored for a message id.

None means no context was stored or the read degraded; telemetry then falls back to a root span.

binomic.worker#

class binomic.worker.Master(broker_dsn: str, module_name: str, policy: MasterPolicy, method: Literal['spawn'] = 'spawn', **broker_kwargs: Any)#

Supervises a fleet of worker subprocesses.

Every worker beats on a heartbeat cell the master created; the visor restarts any worker whose beat stalls or whose process dies, and hands the replacement a fresh cell.

async close() → None#

Terminate every supervised worker, escalating to kill on timeout.

async start() → None#

Spawn the configured workers and run the supervision loop.

class binomic.worker.MasterPolicy(workers: int, worker_policy: WorkerPolicy)#

Settings for the master process.

workers is how many worker subprocesses to spawn, each configured by the same worker_policy.

class binomic.worker.MasterPresence#

The master’s view of every worker’s heartbeat cell.

Cells are shared-memory values created by the master and handed to each worker. Reads deliberately skip the cell lock: the lock exists for read-modify-write, and waiting on it would block the visor forever if a worker died while holding it.

presence() → dict[str, float]#

Return each watched worker’s last beat, keyed by consumer name.

watch(ident: str, slave: Synchronized[float]) → None#

Track slave’s heartbeat cell under ident.

Re-watching the same ident replaces the cell, so a restarted worker starts from a fresh beat instead of inheriting its predecessor’s.

class binomic.worker.SlavePresence(heartbeat: Synchronized[float])#

The worker side: write the current time into its heartbeat cell.

heartbeat() → None#

Stamp the current wall-clock time into the shared cell.

class binomic.worker.Worker(broker_dsn: str, module_name: str, consumer: str, policy: WorkerPolicy, presence: SlavePresence, **broker_config: Any)#

One consumer process: pull from the broker, execute, ack or requeue.

run is the subprocess entry point; arun builds the broker and the handler, then pumps acquired entries through an anyio memory stream to a pool of consumers until terminated. Liveness is reported by beating on the presence cell the master handed in.

async arun() → None#

Run the pull/execute loop until close sets the terminate event.

async close() → None#

Stop pulling, cancel in-flight tasks and release the broker.

run() → None#

Subprocess entry point: run the init hook, then arun.

async start() → None#

Build the broker, handler and terminate event without consuming.

class binomic.worker.WorkerHandler(module_name: str, consumer: str, broker: Broker, worker_policy: WorkerPolicy)#

Execute one acquired entry and own the retry/backoff decisions.

A handler autodiscovers module_name into a private registry, so the task functions run from the worker’s own imports. handle enforces the delivery deadline, dispatches the task, then acks, dead-letters or schedules a retry according to the outcome.

static backoff(attempt: int) → float#

Return the delay before the next delivery of attempt.

The curve starts at 1.5 seconds for the second attempt and doubles up to a 30-second ceiling.

close() → None#

Stop the scheduler; pending retry jobs are dropped with it.

async handle(entry: MessageEntry) → None#

Process one entry: execute, then ack, dead-letter or retry.

Entries older than task_timeout go straight to the DLQ without running. Execution gets the remaining part of that deadline; a timeout dead-letters without retrying, an unknown task is acked, and cancellation or process exit propagates without an ack so reclaim can recover the message. Other failures schedule a backoff retry, or dead-letter once max_attempts is exhausted.

async reclaim() → int#

Re-deliver entries whose consumer went silent.

Entries idle past the task deadline (10-second floor) are claimed and requeued; consumer metadata is swept once it has been idle for ten reclaim intervals. Returns how many entries were reclaimed.

start() → None#

Start the handler’s own scheduler, which carries retry backoff.

class binomic.worker.WorkerPolicy(queues: list[str], concurrency: int, task_timeout: float = 600.0, max_attempts: int = 3, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#

Settings for one worker subprocess.

queues are consumed by every worker and concurrency bounds the tasks one worker executes at once. task_timeout is the total delivery deadline from enqueue; max_attempts is the retry budget before the message enters the DLQ. read_count and poll_interval shape the fetch loop; heartbeat_interval and reclaim_interval set the liveness beat and crash-recovery cadence. dlq_retention is the age after which the periodic sweep deletes DLQ records (None disables it).

worker_init runs once per subprocess, in Worker.run before the event loop starts — the hook where an embedding application installs its OpenTelemetry SDK providers. otel_enabled gates every telemetry call: with the default False binomic emits no spans, metrics and never touches the envelope’s trace fields.

binomic.otel#

class binomic.otel.Telemetry(scope: str = 'binomic')#

Thin wrapper over the OpenTelemetry tracer and meter.

Constructing one requires opentelemetry-api; the module-level otel instance is None when the dependency is missing, so callers gate on it instead of catching import errors. Spans and instruments are created lazily against whatever SDK providers the embedding application installed.

static capture_context() → dict[str, str]#

Serialize the current trace context into a header carrier.

create_counter(name: str, unit: str) → Counter#

Create a monotonically increasing counter instrument.

create_histogram(name: str, unit: str) → Histogram#

Create a histogram instrument for value distributions.

create_observable_gauge(name: str, unit: str, observe: Callable[[], Iterable[tuple[float, dict[str, str]]]]) → ObservableGauge#

Create a gauge whose value is read from observe at collection.

observe returns (value, attributes) pairs, so one instrument covers every queue or worker the caller tracks.

create_up_down_counter(name: str, unit: str) → UpDownCounter#

Create a counter that can increase and decrease.

static extract_context(carrier: Mapping[str, str] | None) → Any#

Rebuild a trace context from carrier, falling back to current.

static mark_span_error(exc: BaseException) → None#

Record exc on the current span and mark it as error.

start_process_span(task: str, carrier: Mapping[str, str] | None, attributes: dict[str, str | int]) → Any#

Start the consumer span for task, continuing carrier.

A None or unreadable carrier yields a root span rather than breaking execution.

start_producer_span(queue: str, attributes: Mapping[str, str | None]) → Any#

Start the span that represents enqueueing into queue.

binomic.base#

class binomic.base.BaseStruct#

Base structure for data schemas.

Adds dict/JSON/TOML/YAML round trips on top of msgspec’s Struct. Encoding and decoding errors are raised by msgspec unchanged, so callers can catch TypeError, msgspec.ValidationError and msgspec.DecodeError directly.

exception binomic.base.BinomicError#

Base class for binomic exceptions.

binomic.plugin.litestar#

class binomic.plugin.litestar.BinomicPlugin(*args: Any, **kwargs: Any)#

Wire a Binomic client into a Litestar application.

app_name doubles as the client’s module_name, so task discovery and the Redis namespace follow it. The plugin registers a BinomicFactory in app.state, exposes a binomic dependency, and enters the client’s async context from the application lifespan.