Skip to content

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_duckLameDuckController

Return the worker's lame-duck drain controller.

shm_policySHMAllocationPolicy

Return the worker's shared-memory allocation policy.

zpagesZPagesRegistry

Return the worker's zPages diagnostics registry.

loop_recorderEventLoopRecorder | None

Return the event loop telemetry recorder, or None when loop telemetry is disabled.

cgroup_quotaCgroupQuota | None

Return the detected cgroup v2 CPU quota.

gil_reportGilAuditReport | 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

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_paramsbool

Whether the route handler declares one or more parameters.

is_asyncbool

Whether execution requires awaiting a coroutine (async handler, async DI, or async guard).

param_namestuple[str, ...]

Ordered tuple of parameter names declared on the handler signature.

invokerCallable[..., Any]

Pre-compiled single-argument callable invoker(request) executing guards, DI, and the handler.

sync_to_threadbool

When True, offload synchronous handler execution onto the worker thread pool.

status_codeint

Default HTTP response status code configured on the route.

arg_resolverCallable[[Any], tuple[Any, ...]] | None

Optional pre-compiled callable resolving positional arguments from a Request.

BatchDispatchPlan

Bases: Struct

Result of partitioning a batch into dispatch groups.

Attributes:

Name Type Description
sync_nativelist[tuple[int, Any, HandlerSpec]]

Inline synchronous native handlers (batch_index, request, spec).

sync_threadlist[tuple[int, Any, HandlerSpec]]

Thread-pool offloaded synchronous handlers (batch_index, request, spec).

async_nativelist[tuple[int, Any, HandlerSpec]]

Asynchronous native coroutine handlers (batch_index, request, spec).

mountsdict[str, list[tuple[int, Any]]]

Mounted ASGI/RSGI/WSGI sub-application requests keyed by mount path prefix.

unmatchedlist[tuple[int, Any]]

Requests with no matching route or mount (batch_index, request).

Execution Lanes & Event Loop Shards

LaneConfig

Bases: Struct

Per-queue worker lane concurrency and drain timeout configuration.

Attributes:

Name Type Description
queue_namestr

Logical queue name bound to this execution lane.

concurrencyint

Maximum number of tasks allowed to execute concurrently in this lane.

drain_timeout_sfloat

Grace period in seconds to await in-flight tasks during lame-duck shutdown.

lane_kindTaskLane

Workload scheduling class ("io", "cpu", or "agent").

LaneMetrics

Bases: Struct

Observability metrics for a single worker execution lane.

Attributes:

Name Type Description
queue_namestr

Logical queue name tracked by these metrics.

in_flightint

Number of tasks currently executing in the lane.

processed_totalint

Cumulative count of tasks that completed without error.

failed_totalint

Cumulative count of task executions that raised an exception.

dlq_totalint

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
sizeint

Return the number of event loop shards in the pool.

loopstuple[asyncio.AbstractEventLoop, ...]

Return all event loop shards in the pool.

primary_loopasyncio.AbstractEventLoop

Return the primary event loop shard without mutating round-robin state.

recorderEventLoopRecorder | None

Return the attached EventLoopRecorder, or None when no loop telemetry is sampled.

get_loop

get_loop(worker_index)

Return the event loop shard assigned to worker_index.

next_loop

next_loop()

Return the next event loop shard in round-robin order.

spawn

spawn(coro, *, worker_index=None, name=None)

Schedule a fire-and-forget coroutine onto the target or next event loop shard.

spawn_batch

spawn_batch(coros)

Partition and schedule a batch of coroutines with at most one wakeup per loop shard.

schedule

schedule(coro, *, worker_index=None, name=None)

Schedule a coroutine onto a specific or round-robin shard and return its Future.

schedule_batch

schedule_batch(coros)

Schedule a batch of coroutines across all loop shards and return aligned Futures.

attach_recorder

attach_recorder(recorder, *, interval_seconds=1.0)

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 interval_seconds is not greater than zero.

RuntimeError

When the pool is stopped or already has a recorder attached.

stop

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_appCallable[..., Any]

Return the ASGI callable wired with any attached fastpath bypass.

lifespan_statedict[str, Any]

Return the shared ASGI lifespan state dictionary.

mount_prefixstr

Return the normalized mount prefix.

last_trailer_frameslist[bytes]

Return the most recent encoded trailer frames emitted via submit_raw_response.

run_single

run_single(request)

Drive self._app for a single request and return its AsgiResponse.

handle_path

handle_path(
    path, *, method="GET", headers=None, body=None, query=None, request_id=0
)

Convenience helper that builds a request from path and calls run_single.

run_batch

run_batch(requests)

Drive self._app concurrently across requests.

spawn_single

spawn_single(request)

Spawn a single request as a background task on the event loop.

spawn_batch

spawn_batch(requests)

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_stream_session(scope_or_request, queues, send=None)

Run the wrapped ASGI application against a bounded AsgiStreamQueuePair or stream queues.

close

close()

Shut down the owned event loop pool if one was created.

AsgiLifespan

ASGI 3.0 lifespan state machine driving startup/shutdown hooks and scope['state'].

Attributes:

Name Type Description
statedict[str, Any]

Return the shared lifespan state dictionary.

supportedbool

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).

run_single

run_single(request)

Execute a single HTTP request against the RSGI application.

run_batch

run_batch(requests, loop=None)

Execute a batch of requests against the RSGI application.

spawn_batch

spawn_batch(requests, *, loop=None)

Drive a batch of RSGI HTTP requests via Rust drive_rsgi_batch or fallback tasks.

handle_http

handle_http(
    *,
    method="GET",
    path="/",
    query_string="",
    headers=None,
    body=b"",
    request_id=0,
)

Convenience helper to invoke the RSGI app directly with explicit HTTP fields.

WsgiAdapter

Adapts a PEP 3333 WSGI callable to Vertebra's request/response pipeline.

Attributes:

Name Type Description
appCallable[..., Iterable[bytes]]

Return the underlying PEP 3333 WSGI callable.

mount_prefixstr

Return the normalized mount prefix for SCRIPT_NAME.

spawn_batch

spawn_batch(
    requests, *, server_name="localhost", server_port=8000, url_scheme="http"
)

Execute a batch of WSGI requests via the adaptive inline/concurrent Rust WSGI executor.

handle_request

handle_request(
    request, *, server_name="localhost", server_port=8000, url_scheme="http"
)

Execute the WSGI application for request and return a Response.

run_environ

run_environ(environ, request_id=0)

Execute the WSGI application against an existing WsgiEnviron.

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_coresfloat

Detected fractional CPU core quota from Linux cgroup v2 cpu.max.

effective_workersint

Recommended worker process count (max(1, ceil(cpu_quota_cores))).

memory_max_bytesint | None

Maximum container memory limit in bytes from memory.max, or None when unbounded.

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

effective_cpu_count(cpu_max_path='/sys/fs/cgroup/cpu.max')

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_memfdbool

Use anonymous memfd_create file descriptors when supported by the kernel.

shm_dirstr

Filesystem mount path inspected for free space when memfd_create is unavailable.

min_free_bytesint

Minimum free bytes required in shm_dir before falling back to temporary files.

validate_environment

validate_environment()

Validate whether the current host or container environment satisfies SHM policy requirements.

allocate_anonymous_shm_fd

allocate_anonymous_shm_fd(name, size)

Allocate an anonymous shared-memory file descriptor and return (fd, backend).

allocate_fd

allocate_fd(name, size, policy=None)

Allocate an anonymous shared-memory file descriptor using policy or defaults.

send_fd

send_fd(sock, fd, payload=b'VTB_SHM')

Send a file descriptor to a peer process over an AF_UNIX socket using SCM_RIGHTS.

recv_fd

recv_fd(sock, max_payload_bytes=64)

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_duckbool

Return whether the server has entered lame-duck drain mode.

is_drainingbool

Return True when the controller is actively draining requests.

in_flightint

Return the number of currently active in-flight requests.

entered_atfloat | 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_buildbool

Whether the running interpreter was compiled with Py_GIL_Disabled (e.g. Python 3.14t/3.15t).

gil_enabled_beforebool

Whether the CPython GIL was active prior to importing the target application module.

gil_enabled_afterbool

Whether the CPython GIL is active after importing the target application module.

gil_reenabled_on_importbool

True when importing the application caused CPython to fall back and re-enable the GIL.

native_extensions_beforefrozenset[str]

Set of native .so/.pyd/.dylib extension module names loaded before import.

native_extensions_afterfrozenset[str]

Set of native .so/.pyd/.dylib extension module names loaded after import.

suspect_extensionstuple[str, ...]

Newly imported native extensions present when gil_reenabled_on_import is True.

quarantined_modulestuple[str, ...]

Loaded modules known to be unsafe under free-threaded execution (e.g. uvloop<=0.21.99).