Writing Unified Backends
Dynamo’s unified backend path lets custom engines implement Dynamo’s shared backend lifecycle contract. The engine owns inference; Dynamo owns runtime registration, request serving, cancellation monitoring, signal handling, drain, and graceful shutdown.
Use this path for new token-in-token-out engines unless you need a feature that is still outside the unified contract.
Choose an Implementation Language
Both unified implementations follow the same shape:
The framework handles model registration, endpoint serving, cancellation plumbing, and shutdown behavior around that engine contract.
What the Unified Contract Covers
The shared contract provides:
- aggregated token-in-token-out inference
- disaggregated serving modes for supported engines
- model registration through Dynamo discovery
- request cancellation
- structured backend errors
- graceful shutdown and drain hooks
Use the lower-level Python worker path when your integration must own endpoint registration, request handling, or the request payload directly.
After you implement the backend, package it into a runtime image with
Runtime Containers. For Kubernetes deployment, place the
custom backend in a DynamoGraphDeployment and follow the
Model Deployment.
Python
Rust
Python Implementation
This guide covers the unified backend infrastructure in
dynamo.common.backend:
a shared LLMEngine abstract base class (ABC), a runtime-owned Worker, and a
sample implementation. For the Rust version of the same contract, use the Rust
tab. To own endpoint registration and request handling directly, use
Writing Python Workers.
This guide walks through building a Python backend for an inference
engine that plugs into Dynamo’s distributed runtime via
dynamo.common.backend. A “unified backend” is a Python entry point
that implements the shared LLMEngine ABC and lets the framework own
runtime lifecycle (signal handling, model registration, graceful
shutdown, cancellation monitoring) — your code just owns inference.
Your backend lives in its own package and does not need to be part
of the dynamo repository. It depends on ai-dynamo from PyPI (or
the git source) and imports dynamo.common.backend. The steps below
assume you’re starting a fresh package in your own repo.
The reference example is the sample engine at
sample_engine.py
— a complete, runnable implementation. Read it alongside this guide.
Where to look for what:
- This guide — step-by-step walkthrough for someone starting a new backend from scratch.
LLMEngineABC docstrings — authoritative method-by-method contract.- Package README
— in-tree reference:
GenerateRequest/GenerateChunkfield definitions, cancellation contract, fullDynamoExceptiontable, and file index.
Python: What you are building
A backend is two things:
- An engine class that subclasses
LLMEngine— owns the model, accepts preprocessed token requests, streams output chunks. - A
main.pyentry point — a three-line shim that hands the engine class torun()fromdynamo.common.backend.run, which drives the lifecycle.
The dynamo.common.backend package handles everything else: signal
handling, distributed runtime setup, model registration with
discovery, the serving loop, graceful shutdown, cancellation
monitoring, and error chain wrapping. (The lifecycle state machine
actually lives in Rust; dynamo.common.backend.Worker is a thin
Python shim over it.)
Python prerequisites
- Python 3.11 or newer.
dynamousestyping.Required, which is 3.11+. - NATS and etcd reachable for end-to-end runs. The dynamo repo’s
deploy/docker-compose.ymlbrings up both in one command if you don’t already have them running. uvorpipfor installing dependencies.- Familiarity with
asyncPython (asyncio, async generators) andargparse.
Python Step 1: Create the package
Minimal pyproject.toml:
For a bleeding-edge dependency on the dynamo source tree, install the runtime wheel from a clone:
Maturin is the Rust-Python bindings build tool. The patchelf extra lets maturin patch native extension library paths during the build.
Building the wheel needs a Rust toolchain plus clang, cmake,
protobuf-compiler, and libssl-dev.
Python Step 2: Subclass LLMEngine
In src/my_backend/engine.py, declare a class that subclasses
LLMEngine and owns whatever state your engine needs. Construction
must be cheap and side-effect-free — heavy work goes in start().
GenerateRequest and GenerateChunk are TypedDicts describing the
shared shape — see Step 4 for the fields.
Python Step 3: Implement from_args
from_args is a classmethod factory that parses CLI args and returns
(engine, WorkerConfig). The engine is constructed but not
started.
from_args is async to match the ABC; you can await from it if
your CLI parsing reads config from a file or hits an API. Most
backends don’t need to.
For backends that already have a DynamoRuntimeConfig-shaped
config object (e.g. one derived from an existing engine’s own
config), prefer the
WorkerConfig.from_runtime_config(runtime_cfg, model_name=...)
helper — it pulls the shared discovery / request-plane / parser
fields off the config in one line.
Python Step 4: Implement LLMEngine methods
The ABC has three required methods (start, generate, cleanup)
plus two with default no-op implementations (abort, drain).
Python: start()
Start the engine and return EngineConfig metadata. After this
returns, generate() MUST be ready for concurrent calls.
worker_id is an opaque per-worker identifier — most engines ignore
it. Backends needing a stable cluster-wide key (e.g. a
disaggregation machine ID) should derive from it instead of
hashing host/pid or asking operators for a CLI override.
Every EngineConfig field except model is optional. None means
“don’t advertise”; KV-aware routing falls back to round-robin when KV
fields are unset.
Python: generate()
An async generator that yields GenerateChunk dicts for a single
request. Called concurrently for multiple in-flight requests.
Contract (chunk shape is defined by the GenerateChunk TypedDict
— see
Request / Response Types
in the package README for the field reference):
- Every chunk carries
token_idsandindex(use0for single choice). - The final chunk additionally carries
finish_reasonandcompletion_usage. - The framework’s cancellation monitor calls
engine.abort(context)when the client disconnects or cancels; your loop should also pollcontext.is_stopped()between yields and exit cleanly with afinish_reason="cancelled"chunk.
Finish reason normalization ("abort" → "cancelled", etc.) is
handled by the Rust layer — emit whatever your engine uses
natively.
Python: Custom logits processors (optional)
Override logits_processor_spec() to expose backend-neutral activation data.
Resolve and cache the specification during startup, call
logits_processors_for_request() for each request, and construct fresh
inference-library processor instances from the returned entries. The worker
does not realize these entries automatically.
Import LogitsProcessorSpec, ForcedTokenSequenceSpec,
PythonProcessorSpec, and the serialization helpers from
dynamo.common.backend.engine. A generation-only specification runs on
aggregated and decode workers but not prefill or encode workers.
ForcedTokenSequenceSpec can cross a JSON request boundary;
PythonProcessorSpec contains a live factory and cannot be serialized.
Python: Engine management (optional)
Advertise lifecycle operations with supported_controls() and implement each
operation in engine_control(name, body). The worker registers advertised
names at POST /engine/control/<name>.
Use the separate supported_updates() and engine_update(name, body) methods
for operations that mutate engine-managed assets. These register at
POST /engine/update/<name>. Both capability sets are empty by default, and
request and response bodies are JSON objects.
Override on_endpoint_ready(endpoint) when a later management operation needs
the serving endpoint. The worker invokes this hook once after the endpoint
exists and before discovery registration or request serving.
Python: abort(context) — optional
Called by the framework only when the client disconnects or the request is cancelled. NOT called on silent stream drops. Override to release engine-side resources (KV slots, scheduler entries, remote schedulers):
For cleanup that must run on every drop path — including silent
drops — use a try/finally or a context manager inside generate,
not abort. The sample engine doesn’t override abort because it
has no engine-side state to release; the default is a no-op.
Python: drain() — optional
Runs once before shutdown, after the discovery unregister + grace-period sleep, while NATS/etcd are still alive. Use it for backend-side draining that must complete before transport teardown (e.g. in-flight NIXL KV transfers on prefill workers). Default is no-op.
Python: cleanup()
Two real requirements, both pinned by the Rust-side conformance kit:
- Null-safe against partial
start()failure. Ifstart()raises partway through, fields you allocate incrementally may still beNone.cleanup()must guard each resource (if self._engine is not None: …) so the post-failure call doesn’t crash on half-initialized state. - Idempotent. A second call after a successful first must return cleanly without re-entering teardown.
The Rust Worker drives both: it calls cleanup() after start()
returns Ok on shutdown, and the conformance kit (run_conformance)
additionally calls cleanup() on a never-started engine and twice in a
row, failing your tests with CleanupWithoutStartFailed /
SecondCleanupFailed if either invariant breaks. The guarded
single-shot pattern below covers both:
Python: Metrics and Prometheus (optional)
Unified backends have two metrics surfaces.
Use register_prometheus(metrics) to bridge vendor-prefixed Prometheus
families into the worker’s /metrics output. The framework owns the
metrics handle; do not retain it after the method returns.
Use component_metrics_dp_ranks() plus
attach_snapshot_publisher(publisher) when the engine can push per-rank
ComponentSnapshot values for dynamo_component_* gauges and the
router’s kv_used_blocks signal:
Keep the rank list stable for the engine lifetime. Worker invokes
attach_snapshot_publisher() only when the rank list is non-empty and
WorkerConfig.enable_kv_routing is enabled. register_prometheus() still
runs when enable_kv_routing=False.
A typical engine pushes per-rank snapshots from its own stats callback
(a stat logger, scheduler hook, or dedicated poll thread) and bridges
its vendor-prefixed metric families through register_prometheus().
Python: KV event publishing (optional)
Unified backends declare KV event sources; the framework constructs and owns
the KvEventPublisher instances. Do not instantiate KvEventPublisher
directly from a unified LLMEngine. Instead, implement
kv_event_sources() and return one source for each data-parallel rank hosted
by the worker.
Rust backends use the equivalent LLMEngine::kv_event_sources() trait method;
see Rust Step 4 and the
LLMEngine trait.
Use ZmqSource when the engine already emits Dynamo-compatible KV events on a
ZMQ socket:
Use PushSource when the engine needs a live publisher object and drives
publish_stored() / publish_removed() from its own event thread:
KV event publishers require EngineConfig.llm.kv_cache_block_size. If the
engine declares sources but does not return a block size, Worker skips KV
event publishers because the router cannot map token IDs to cache blocks.
WorkerConfig.enable_kv_routing=False is the operator-level kill switch; when
it is disabled, the worker does not call kv_event_sources().
Keep rank ownership stable for the engine lifetime. DP-capable engines should
also advertise the same rank shape in EngineConfig.llm.data_parallel_size and
data_parallel_start_rank so router-forced dp_rank values line up with the
published event streams.
PushSource engines own cleanup of their event producer. Stop publisher
threads or tasks in cleanup() before returning, and do not publish after
cleanup begins.
Python Step 5: Write main.py
Three lines.
run installs signal handlers, builds the distributed runtime,
calls engine.start(worker_id) with a runtime-allocated identifier,
registers the model with discovery, serves the endpoint, and runs the
graceful-shutdown orchestrator on SIGTERM/SIGINT.
Pair this with the [project.scripts] entry from Step 1’s
pyproject.toml so my-backend ... works as a console command.
Python Step 6: Errors and logging
Errors: the framework wraps non-DynamoException errors raised
from generate() (or lifecycle methods) as Unknown. For typed
error reporting, raise a DynamoException subclass directly from
dynamo.llm.exceptions
— it propagates unchanged through the Rust bridge:
The package README has the full table of exception types and which
lifecycle phase raises which one. Engine-init failures should raise
EngineShutdown from start(). Cleanup shouldn’t normally raise —
log and swallow if a subsystem fails.
Logging: keep levels consistent across unified backends so operators see the same surface regardless of which engine they’re running:
logger.info— lifecycle milestones (engine init complete, serving started, engine shutdown).logger.debug— per-request events (request abort, cancellation).logger.warning— recoverable problems (empty outputs, unexpected finish reasons).logger.error— unrecoverable failures only.
The framework also configures dynamo.runtime.logging for you; you
just call logger = logging.getLogger(__name__) at the top of your
module and use it.
Python Step 7: Test your engine
Install the dev extras (pytest, pytest-asyncio) declared in Step 1:
The sample engine has a unit-test suite that you can copy as a starting point. The shape of a useful test:
Cover the happy path, cancellation, and any backend-specific edge
cases (stop tokens, max-tokens cap, empty prompt). Three to five
focused tests is plenty — the framework already pins the lifecycle
state machine and cancellation contract with Rust-side tests in
lib/backend-common.
Python Step 8: Run it locally
Three moving parts need to come up: NATS + etcd (discovery and the event/request planes), the Dynamo frontend (HTTP → backend discovery), and your backend.
Then send a request:
A successful response has non-empty choices[0].message.content
and a finish_reason of stop or length.
jq -e '.choices[0].finish_reason' is a good one-liner for a CI
smoke test.
If your backend looks silent, set DYN_LOG=info (or
DYN_LOG=debug,dynamo=debug for finer scoping) before launching —
the framework configures tracing from DYN_LOG.
Python reference: sample engine
sample_engine.py
is the canonical minimal reference. Run it as-is:
It generates rotating token IDs with no ML dependencies, so it’s a useful stand-in for AIPerf / end-to-end pipeline smoke tests. Lift these patterns:
from_argsparses CLI args and returns(engine, WorkerConfig)with no awaits.start()returns anEngineConfigwhose KV fields are illustrative but not load-bearing (no real KV cache).generate()pollscontext.is_stopped()between yields and emits acancelledterminal on observation.cleanup()is a no-op because the engine holds no resources.
Python checklist
Before shipping:
-
LLMEnginesubclassed;from_argsreturns(engine, WorkerConfig). -
start()returnsEngineConfigwith at least a non-emptymodel. -
generate()pollscontext.is_stopped()between yields and emits a"cancelled"terminal on observation. - Final chunk has
finish_reasonandcompletion_usage. - Typed
DynamoExceptionsubclasses used for error reporting where the category matters. -
cleanup()releases all engine resources. - Logging levels match the standards in Step 6.
Python see also
LLMEngineABC — authoritative contract.- Package README — lifecycle, error model, and request/response contract.
- Sample engine — example user guide.
- Rust tab on this page — the Rust counterpart, same contract, lower-level.
Rust Implementation
This guide covers the unified backend infrastructure in
dynamo-backend-common:
a shared LLMEngine contract, a runtime-owned Worker, and a mocker
implementation.
This guide walks through building a Rust unified backend for an
inference engine that plugs into Dynamo’s distributed runtime. A
unified backend is a standalone Rust binary that owns its engine and
serves requests via the shared
LLMEngine contract in
dynamo-backend-common — no Python
worker runtime required. For the Python version of the same contract
use the Python tab on this page.
Your backend lives in its own crate and does not need to be part of
the dynamo repository. It pulls dynamo-backend-common in as a normal
git or path dependency. The steps below assume you’re starting a fresh
crate in your own repo; an optional note in Step 1 covers the in-tree
variant for contributors landing a backend inside ai-dynamo/dynamo.
For a Python engine, use the Python tab on this page. To own endpoint registration and request handling directly, use Writing Python Workers.
The reference example is the mocker backend at
lib/backend-common/examples/mocker
— a small, complete, pure-Rust implementation. Read it alongside this
guide.
Where to look for what:
- This guide — step-by-step walkthrough for someone starting a new backend from scratch.
LLMEnginetrait doc comments — authoritative method-by-method contract.- Crate README — in-tree reference: architecture, file index, disaggregation contract, error taxonomy, conformance kit.
backend-commondesign notes — rationale and invariants.
Rust: What you are building
A backend is two things:
- An engine type that implements the
LLMEnginetrait — owns the model, accepts preprocessed token requests, streams output tokens. - A
main.rsentry point — a three-line shim that hands the engine todynamo_backend_common::run, which drives the lifecycle.
The dynamo-backend-common crate handles everything else: signal
handling, model registration with discovery, the serving loop, graceful
shutdown, metrics, cancellation plumbing, and the debug-mode contract
validator.
Engines work directly with PreprocessedRequest and LLMEngineOutput
— the same types used by Dynamo’s preprocessing, routing, and frontend.
No Python-shaped translation layer.
Rust prerequisites
- Rust 1.85 or newer (the dynamo workspace is edition 2024). The
toolchain pin in Step 1 locks this in for you; older toolchains will
fail with
feature edition2024 is requireddeep inside the build. - NATS and etcd reachable for end-to-end runs. The dynamo repo’s
deploy/docker-compose.ymlbrings up both in one command if you don’t already have them running. - Familiarity with
asyncRust,tokio, andclap. The trait usesasync_trait, and the framework expects atokioruntime.
Rust Step 1: Create the crate
Your backend is a standalone Rust binary crate. It can live in its own repository — the dynamo repo is not required to be your parent workspace. Pick whatever layout you prefer:
cargo new --bin my-backend is the fastest starting point; add
src/engine.rs yourself afterwards.
Rust: Getting the dynamo-backend-common crate
dynamo-backend-common lives in the
ai-dynamo/dynamo repository and
is not on crates.io. Depend on it via git:
The testing feature pulls in the conformance kit used in Step 7.
Pick a SHA with:
No release tags yet.
dynamo-backend-commonlanded after the last tagged release (v1.1.1), sotag = "v1.1.1"won’t resolve the crate. Trackmainor pin to a specific SHA until a release tag ships that includes the crate.
Rust: Two build-time requirements you cannot skip
These are easy to miss and surface as confusing compile errors deep
inside dynamo-runtime:
-
tokio_unstablecfg flag.dynamo-runtimeuses tokio’s unstable runtime-metrics API. Create.cargo/config.tomlin your crate root:Without it, you’ll see errors like
method blocking_queue_depth not found on RuntimeMetricswhile compilingdynamo-runtime. -
Rust toolchain pin. Match dynamo’s toolchain so workspace-edition crates compile. Create
rust-toolchain.toml:Older toolchains fail with
feature edition2024 is required.
Tip — local development: while iterating against an unreleased change in
dynamo-backend-common, point the dep at a local clone:dynamo-backend-common = { path = "/path/to/dynamo/lib/backend-common" }. Switch back to the git dep before publishing your crate.
If you’d rather develop inside the dynamo workspace as a new
sub-crate, drop your crate under dynamo/lib/ and use
dynamo-backend-common = { workspace = true } instead. The trait
contract is identical, and the .cargo/config.toml plus toolchain
pin in the dynamo repo cover the two requirements above for you.
Rust Step 2: Define your engine struct
In src/engine.rs (or whatever you named it), declare a struct that
owns whatever state your engine needs. Anything you allocate inside
start() later must live behind interior mutability so the trait’s
&self methods can reach it.
async-trait lets the trait use async fn (still required for
object-safety with Arc<dyn LLMEngine>); async-stream’s stream!
macro lets the generate body yield items from inside an async block.
The mocker example uses OnceCell for Inner; RwLock<Option<_>>
also works — pick whichever fits your shutdown semantics.
Rust Step 3: Wire up CLI arguments
Every backend’s CLI shares a common base (--namespace, --component,
--endpoint, etc.) provided by CommonArgs. Flatten that into your
engine’s Args struct and add your engine-specific flags.
Define an inherent from_args constructor that parses the args and
returns both the engine and a WorkerConfig. from_args is not on
the trait — it stays inherent so the trait can remain object-safe
(Arc<dyn LLMEngine> must work).
The snippet below calls a tiny invalid_arg helper that builds a
typed BackendError::InvalidArgument. Its full definition lives in
Step 6 — for now, mentally substitute “any function that returns a
DynamoError with category InvalidArgument.”
WorkerConfig::default() sets model_input to ModelInput::Tokens,
which is the input mode supported by the LLMEngine trait. Use
RawEngine and Worker::new_raw for engines that accept raw text or
tensor inputs.
If your engine branches on the disaggregation role inside generate
(prefill vs decode), keep the same DisaggregationMode on your engine
struct so the runtime registration (WorkerConfig) and the per-request
dispatch stay in lockstep.
Rust Step 4: Implement the LLMEngine trait
The trait has three required methods (start, generate, cleanup)
plus two with default implementations you can override (abort, drain).
Rust: start()
Start the engine and return EngineConfig metadata. After this
returns, the engine MUST be ready for concurrent generate() calls.
Use interior mutability for anything you initialize here.
worker_id is an opaque per-worker identifier — most engines ignore
it with _worker_id. Backends needing a stable cluster-wide key
(e.g. a disaggregation machine ID) should derive from it.
Every EngineConfig field except model is optional. None means
“don’t advertise”; KV-aware routing falls back to round-robin when KV
fields are unset. Engines wrapping an external runtime can read these
values from the live engine after it comes up, instead of hard-coding
them. The ..Default::default() is load-bearing: EngineConfig
sometimes grows new fields (e.g. bootstrap_host/bootstrap_port
for disaggregation) and the default keeps existing engines compiling.
Rust: generate()
Yield a stream of Result<LLMEngineOutput, DynamoError> items for a
single request. Called concurrently for multiple in-flight requests.
ctx: GenerateContext is a thin wrapper that Derefs to
dyn AsyncEngineContext, so the cancellation methods (stopped(),
is_stopped(), id()) you’d expect are still there. The wrapper
additionally exposes notify_first_token() for decode-mode requests
— most engines can ignore it; the framework auto-fires on the first
non-empty chunk.
Contract (the debug-mode validator panics on violations):
- Exactly one terminal item must be the last item yielded. A
terminal is either an
Ok(chunk)withfinish_reasonset, or anErr(DynamoError). No items may be yielded after a terminal. - Non-terminal chunks use
chunk::token(id)and leavefinish_reasonunset. - The returned stream is
'static: clone or move any state from&selforrequestinto the stream body before constructing it.
Terminal chunks come from one of four LLMEngineOutput constructors,
optionally chained with the LLMEngineOutputExt setters
(.with_tokens(...), .with_usage(...)):
LLMEngineOutput::stop()— natural completion (e.g. you reached your echo limit, the engine hit a stop string).LLMEngineOutput::length()—max_tokenscap reached.LLMEngineOutput::cancelled()— you observedctx.stopped().LLMEngineOutput::error(msg)— message-only error terminal (loses the typedBackendErrorvariant — yieldErr(DynamoError)instead when the category matters).
Non-terminal chunks use chunk::token(id) (single-token convenience).
A streaming-generate template:
biased is load-bearing for the channel-receiving pattern above:
- When cancellation and a pending token are both ready, yield the cancellation, not one more token.
- During cleanup the stream sees both
ctx.stopped()andrx.recv() -> Nonesimultaneously;biasedpicks the clean cancellation path instead of erroring on a closed channel. The mocker’s stream body spells this out.
If your engine doesn’t have a receiver — e.g. you’re computing tokens inline like a deterministic echo backend — the body collapses to a plain loop that polls cancellation between yields:
No channel-close race to worry about; biased is still cheap and
recommended for consistency.
Cancellation rules:
- The stream must poll
ctx.is_stopped()(orawait ctx.stopped()) between yields. - On cancellation, emit a terminal with
FinishReason::Cancelled— notLengthorStop. The conformance kit treats any other terminal after cancellation as ignoring the signal.
Typed errors vs. string errors:
Use typed errors when the failure category matters to the caller. Use string errors when it doesn’t.
Rust: abort() and per-request cleanup
abort is called by the framework only when ctx.stopped() or
ctx.killed() fires — i.e. an explicit client/operator cancel. It is
NOT called when the stream is silently dropped (TCP reset, consumer
timeout without cancellation).
For cleanup that must run on any drop path (releasing a scheduler
slot, freeing a request handle), use RAII inside the generate stream
body:
The mocker’s ActiveRequestGuard is the canonical example.
Use abort only for out-of-band notifications (e.g. telling a remote
scheduler to stop computing for this request).
Rust: drain() and cleanup()
drain()runs once before shutdown, after the discovery unregister + grace-period sleep, while NATS/etcd are still alive. Use it for backend-side draining that must complete before the transport layer goes away (e.g. in-flight NIXL KV transfers on prefill workers). Default is no-op.cleanup()is called once on shutdown. Release all engine resources. The framework guaranteescleanup()runs exactly once afterstart()is invoked, whetherstart()succeeds or returns an error. It is not called whenstart()was never invoked. Release resources allocated during construction throughDroprather than relying oncleanup().
Make cleanup() idempotent and tolerant of being called from a
half-initialized state. An engine that tears down NCCL groups in
cleanup() can hang on a second attempt.
Rust Step 5: Write main.rs
Three lines. That’s it.
run installs signal handlers, builds the distributed runtime, calls
engine.start(), registers the model with discovery, serves the
endpoint, and runs the full graceful-shutdown orchestrator on
SIGTERM/SIGINT.
Rust Step 6: Errors and logging
Errors: every error returned from start, generate, cleanup,
and from_args uses ErrorType::Backend(BackendError::X). From the
frontend’s perspective, anything bubbling up through the backend has
“originated from the backend” — engine code vs. framework code is not
distinguished. Top-level ErrorType::X variants are reserved for
non-backend paths.
A small helper module per backend keeps the call sites clean:
Common nested categories: InvalidArgument, CannotConnect,
EngineShutdown, StreamIncomplete, Cancelled, ResponseTimeout,
Disconnected, ConnectionTimeout, Unknown.
Logging: keep levels consistent across Rust backends so operators see the same surface everywhere.
tracing::info!for lifecycle milestones (engine started, cleanup complete).Workeralready logs “Serving {model} on …” and “Engine cleanup complete” — add your own only for events those don’t cover.tracing::debug!for per-request events (cancellation, abort).tracing::warn!for recoverable problems.tracing::error!only for unrecoverable failures.
Rust Step 7: Run the conformance kit
Before merging, prove your engine satisfies the contract. The conformance kit is one call:
The kit runs start/generate/cleanup directly against your engine
— no external service is involved. If your engine needs a real GPU,
remote model server, or other heavyweight resource to construct, gate
the test with #[ignore] and require an explicit opt-in env var.
What it asserts:
For tests that don’t need a real engine, use testing::mock_context()
or testing::cancelling_context(after) to drive generate manually.
Rust Step 8: Run it locally
Three moving parts need to come up: NATS + etcd (discovery and the event/request planes), the Dynamo Python frontend (HTTP → backend discovery), and your backend.
The fastest path is to copy the mocker example’s
docker-compose.yml
and Dockerfile.frontend,
swap in your image, and run docker compose up --build. That brings
up NATS + etcd + the Python frontend (built from the dynamo workspace
at the same SHA as your backend) + your backend, all on one network.
For a non-Docker dev loop:
Then send a request:
A successful response has non-empty choices[0].message.content and a
finish_reason of stop or length. jq -e '.choices[0].finish_reason'
is a good one-liner for a CI smoke test.
run initializes tracing from the DYN_LOG env var (defaults to
info); set DYN_LOG=debug or
DYN_LOG=info,dynamo_backend_common=trace for more detail. RUST_LOG
is not honored — DYN_LOG replaces it.
Rust reference: mocker backend
lib/backend-common/examples/mocker
is the canonical small-but-complete reference. Lift these patterns:
- Single shared scheduler driving many concurrent streams via a
fan-out task and per-request
mpscchannels. ActiveRequestGuardfor RAII cleanup that runs on any stream drop.biasedselect withctx.stopped()first, channel second — the shutdown-race fix discussed in Step 4.cleanup()signals every active stream viactx.stop_generating()so each yields a cleanCancelledterminal instead of an error from channel-close.
Rust checklist
Before shipping:
-
LLMEngineimplemented;from_argsis inherent (not on the trait). - All errors use
ErrorType::Backend(BackendError::X). -
generatepollsctx.is_stopped()between yields and emitsFinishReason::Cancelledon cancel. - Per-request cleanup uses RAII guards, not just
abort. -
cleanupis idempotent. - Conformance kit runs green:
testing::run_conformance(|| ...). - Logging levels match the standards in Step 6.
Rust see also
- Crate README — in-tree reference (architecture, file index, contracts at a glance).
LLMEnginetrait — authoritative contract.- Design notes — rationale and invariants.
Worker— runtime lifecycle internals (signal handling, graceful shutdown, model registration).- Conformance kit —
run_conformance,mock_context,cancelling_context. - Mocker backend — example user guide.
- Python sibling — Python ABC layered over this crate.