Server Runtime, Execution Lanes & Protocol Adapters¶
vertebra.server manages the worker lifecycle, pre-compiled batch dispatch, isolated execution lanes, sharded asyncio event loops, ASGI/RSGI/WSGI adapters, and container cgroup introspection. See the Server & Workers Usage Guide for topology and tuning guidance.
| Subsystem | Responsibility |
|---|---|
| Worker & Batch Dispatch | Poll request batches from vertebra-core, partition them by handler lane, and submit responses. |
| Lanes & Event Loops | Isolate io, cpu, and agent work and shard asyncio loops across worker threads. |
| Protocol Runners | Run ASGI 3.0, RSGI 1.6, and PEP 3333 WSGI applications such as Litestar, FastAPI, Flask, and Django. |
| Platform & GIL Audit | Read cgroup v2 CPU and shared-memory quotas, serve /healthz and /statusz, drain traffic on SIGTERM, and audit GIL state on free-threaded Python. |
Worker Lifecycle & Batch Dispatch¶
Worker drives the per-process poll loop and compiles route handlers into HandlerSpec entries partitioned per batch via BatchDispatchPlan.
Worker
¶
Single-responsibility worker orchestrating SHM validation, loop pools, and batch dispatch.
Attributes:
| Name | Type | Description |
|---|---|---|
lame_duck | LameDuckController | Return the worker's lame-duck drain controller. |
shm_policy | SHMAllocationPolicy | Return the worker's shared-memory allocation policy. |
zpages | ZPagesRegistry | Return the worker's zPages diagnostics registry. |
loop_recorder | EventLoopRecorder | None | Return the event loop telemetry recorder, or |
cgroup_quota | CgroupQuota | None | Return the detected cgroup v2 CPU quota. |
gil_report | GilAuditReport | None | Return the free-threaded GIL audit report collected at startup. |
handle_sigterm
¶
handle_sigterm(signum=SIGTERM, frame=None)
Enter lame-duck draining mode and validate SHM policy on SIGTERM/SIGINT.
run
¶
Validate the environment, initialize transport and loops, and run the batch loop.
The worker's EventLoopPool is registered with zpages as worker, so /taskz lists its
tasks per shard. When VERTEBRA_LOOP_TELEMETRY is 1 or true, or a loop_recorder was
passed, every continuously running shard samples scheduling lag and active task counts
into the recorder every VERTEBRA_LOOP_TELEMETRY_INTERVAL seconds (default 1.0).
HandlerSpec
¶
Bases: Struct
Pre-compiled dispatch specification and invoker for a route handler.
Attributes:
| Name | Type | Description |
|---|---|---|
has_params | bool | Whether the route handler declares one or more parameters. |
is_async | bool | Whether execution requires awaiting a coroutine (async handler, async DI, or async guard). |
param_names | tuple[str, ...] | Ordered tuple of parameter names declared on the handler signature. |
invoker | Callable[..., Any] | Pre-compiled single-argument callable |
sync_to_thread | bool | When True, offload synchronous handler execution onto the worker thread pool. |
status_code | int | Default HTTP response status code configured on the route. |
arg_resolver | Callable[[Any], tuple[Any, ...]] | None | Optional pre-compiled callable resolving positional arguments from a |
BatchDispatchPlan
¶
Bases: Struct
Result of partitioning a batch into dispatch groups.
Attributes:
| Name | Type | Description |
|---|---|---|
sync_native | list[tuple[int, Any, HandlerSpec]] | Inline synchronous native handlers |
sync_thread | list[tuple[int, Any, HandlerSpec]] | Thread-pool offloaded synchronous handlers |
async_native | list[tuple[int, Any, HandlerSpec]] | Asynchronous native coroutine handlers |
mounts | dict[str, list[tuple[int, Any]]] | Mounted ASGI/RSGI/WSGI sub-application requests keyed by mount path prefix. |
unmatched | list[tuple[int, Any]] | Requests with no matching route or mount |
Execution Lanes & Event Loop Shards¶
LaneConfig
¶
Bases: Struct
Per-queue worker lane concurrency and drain timeout configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
queue_name | str | Logical queue name bound to this execution lane. |
concurrency | int | Maximum number of tasks allowed to execute concurrently in this lane. |
drain_timeout_s | float | Grace period in seconds to await in-flight tasks during lame-duck shutdown. |
lane_kind | TaskLane | Workload scheduling class ( |
LaneMetrics
¶
Bases: Struct
Observability metrics for a single worker execution lane.
Attributes:
| Name | Type | Description |
|---|---|---|
queue_name | str | Logical queue name tracked by these metrics. |
in_flight | int | Number of tasks currently executing in the lane. |
processed_total | int | Cumulative count of tasks that completed without error. |
failed_total | int | Cumulative count of task executions that raised an exception. |
dlq_total | int | Cumulative count of tasks moved to the dead-letter queue after exhausting retries. |
EventLoopPool
¶
Sharded pool of persistent event loops with optional inline single-thread mode.
An EventLoopRecorder attached through the recorder keyword or attach_recorder receives one
EventLoopMetricSample per shard per interval, recorded on that shard's own loop thread. A pool
without a recorder schedules no sampling timers.
Attributes:
| Name | Type | Description |
|---|---|---|
size | int | Return the number of event loop shards in the pool. |
loops | tuple[asyncio.AbstractEventLoop, ...] | Return all event loop shards in the pool. |
primary_loop | asyncio.AbstractEventLoop | Return the primary event loop shard without mutating round-robin state. |
recorder | EventLoopRecorder | None | Return the attached |
spawn
¶
Schedule a fire-and-forget coroutine onto the target or next event loop shard.
spawn_batch
¶
Partition and schedule a batch of coroutines with at most one wakeup per loop shard.
schedule
¶
Schedule a coroutine onto a specific or round-robin shard and return its Future.
schedule_batch
¶
Schedule a batch of coroutines across all loop shards and return aligned Futures.
attach_recorder
¶
Start sampling scheduling lag and active task counts on every shard into recorder.
Each shard arms a self-rescheduling loop.call_later timer on its own loop. When the timer
fires, the lag is the actual time.monotonic() fire time minus the expected one, and the
shard records an EventLoopMetricSample on its loop thread. For zuvloop loops the shard also calls
recorder.configure_zuvloop with the same interval. An inline loop starts sampling the first
time it runs, and lag is only meaningful while that loop runs continuously. Sampling stops
and every pending timer is cancelled when the pool stops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recorder
|
EventLoopRecorder
|
Recorder receiving one sample per shard per interval. |
required |
interval_seconds
|
float
|
Sampling interval in seconds; must be greater than zero. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
RuntimeError
|
When the pool is stopped or already has a recorder attached. |
stop
¶
Drain and stop every loop shard, closing each loop only after its thread exits.
Each running shard cancels its pending tasks, waits for the cancellations, and runs
shutdown_asyncgens before the loop stops. A loop whose thread is still alive after the
join timeout is logged and left open rather than closed under a running thread.
Protocol Runners¶
AsgiRunner
¶
Drives ASGI 3.0 applications across single, batch, and streaming lifecycles.
Attributes:
| Name | Type | Description |
|---|---|---|
dispatch_app | Callable[..., Any] | Return the ASGI callable wired with any attached fastpath bypass. |
lifespan_state | dict[str, Any] | Return the shared ASGI lifespan state dictionary. |
mount_prefix | str | Return the normalized mount prefix. |
last_trailer_frames | list[bytes] | Return the most recent encoded trailer frames emitted via submit_raw_response. |
handle_path
¶
Convenience helper that builds a request from path and calls run_single.
spawn_batch
¶
Drive a batch of ASGI requests via Rust drive_asgi_batch or fallback tasks.
create_stream_queues
¶
create_stream_queues(
maxsize=DEFAULT_STREAM_QUEUE_MAXSIZE,
*,
high_watermark=DEFAULT_STREAM_HIGH_WATERMARK,
low_watermark=DEFAULT_STREAM_LOW_WATERMARK,
)
Create a bounded AsgiStreamQueuePair for SSE or WebSocket streaming.
run_stream_session
¶
Run the wrapped ASGI application against a bounded AsgiStreamQueuePair or stream queues.
AsgiLifespan
¶
ASGI 3.0 lifespan state machine driving startup/shutdown hooks and scope['state'].
Attributes:
| Name | Type | Description |
|---|---|---|
state | dict[str, Any] | Return the shared lifespan state dictionary. |
supported | bool | Return True if the application completed lifespan.startup.complete. |
SseResponse
¶
ASGI 3.0 callable that streams SseEvent items via http.response.sse or http.response.body.
WebSocketSession
¶
Manages ASGI receive and send callables for a single WebSocket connection.
RsgiAdapter
¶
Adapter that drives an RSGI v1.6 application callable (scope, protocol).
WsgiAdapter
¶
Adapts a PEP 3333 WSGI callable to Vertebra's request/response pipeline.
Attributes:
| Name | Type | Description |
|---|---|---|
app | Callable[..., Iterable[bytes]] | Return the underlying PEP 3333 WSGI callable. |
mount_prefix | str | Return the normalized mount prefix for |
FlaskWsgiApp
¶
Convenience wrapper for a Flask (or Werkzeug-compatible) WSGI application.
DjangoWsgiApp
¶
Convenience wrapper for Django's get_wsgi_application().
Cgroups, Z-Pages, Graceful Drain & GIL Audit¶
CgroupQuota
¶
Bases: Struct
Detected Linux cgroup v2 CPU and memory limits for container-aware auto-sizing.
Attributes:
| Name | Type | Description |
|---|---|---|
cpu_quota_cores | float | Detected fractional CPU core quota from Linux cgroup v2 |
effective_workers | int | Recommended worker process count ( |
memory_max_bytes | int | None | Maximum container memory limit in bytes from |
detect
¶
detect(
cpu_max_path="/sys/fs/cgroup/cpu.max",
*,
memory_max_path="/sys/fs/cgroup/memory.max",
host_cpus=None,
fallback_cpus=None,
)
Read Linux cgroup v2 cpu.max and memory.max to compute container-safe worker counts.
effective_cpu_count
¶
Return container- and affinity-aware effective CPU count for thread/worker auto-sizing.
SHMAllocationPolicy
¶
Bases: Struct
Shared-memory allocation policy for Kubernetes (64 MiB /dev/shm) and read-only rootfs.
Attributes:
| Name | Type | Description |
|---|---|---|
prefer_memfd | bool | Use anonymous |
shm_dir | str | Filesystem mount path inspected for free space when |
min_free_bytes | int | Minimum free bytes required in |
validate_environment
¶
Validate whether the current host or container environment satisfies SHM policy requirements.
allocate_anonymous_shm_fd
¶
Allocate an anonymous shared-memory file descriptor and return (fd, backend).
allocate_fd
¶
Allocate an anonymous shared-memory file descriptor using policy or defaults.
send_fd
¶
Send a file descriptor to a peer process over an AF_UNIX socket using SCM_RIGHTS.
recv_fd
¶
Receive a file descriptor from an AF_UNIX socket via SCM_RIGHTS.
LameDuckController
¶
Manages graceful lame-duck health check drain before socket closure on SIGTERM.
Attributes:
| Name | Type | Description |
|---|---|---|
is_lame_duck | bool | Return whether the server has entered lame-duck drain mode. |
is_draining | bool | Return True when the controller is actively draining requests. |
in_flight | int | Return the number of currently active in-flight requests. |
entered_at | float | None | Return the Unix timestamp when lame-duck mode started. |
ZPagesRegistry
¶
Provides diagnostic payloads for /statusz, /healthz, /varz, /rpcz, /brokerz, and /taskz.
GilAuditReport
¶
Bases: Struct
Result of auditing CPython's free-threaded GIL state around application import.
Attributes:
| Name | Type | Description |
|---|---|---|
free_threaded_build | bool | Whether the running interpreter was compiled with |
gil_enabled_before | bool | Whether the CPython GIL was active prior to importing the target application module. |
gil_enabled_after | bool | Whether the CPython GIL is active after importing the target application module. |
gil_reenabled_on_import | bool | True when importing the application caused CPython to fall back and re-enable the GIL. |
native_extensions_before | frozenset[str] | Set of native |
native_extensions_after | frozenset[str] | Set of native |
suspect_extensions | tuple[str, ...] | Newly imported native extensions present when |
quarantined_modules | tuple[str, ...] | Loaded modules known to be unsafe under free-threaded execution (e.g. |