cadet.core

Decorator-based app plugin registry (framework, app-agnostic).

What this is for:

Apps register themselves here. Each plugin advertises its name and its typed params_model, so the loader can validate app.params against the right model. The framework ships no app registrations; apps live under examples/ and register on import (e.g. --app-module examples.braking.flat.app).

What it contains:
How it fits into CADET:

experiment.app/app.plugin name a registered plugin. The CLI imports the requested app module(s) before dispatch; cadet.config.loader.resolve_app_params() then validates the config’s app.params against the plugin’s model. Nothing under cadet/ imports examples/.

class cadet.core.apps.AppPlugin

Bases: ABC

Base class for an app plugin.

Subclasses set name (the plugin key used in configs) and params_model (the pydantic model validating app.params for this app).

name: str = ''
params_model: Type[BaseModel]
static client_success(client_app)

Return (ok, detail): did this client actually produce output?

Only the app knows what its output is, so the app declares it. The default is the weakest claim that still means something happened: the client transmitted at least one message. An app whose run is not meaningful without a reply - a decision coming back, a command acted on - overrides this and says so.

This exists because a client that set up, sent nothing and exited cleanly used to be indistinguishable from one that ran the experiment: success was decided by exit codes, and exiting zero having done nothing is still exiting zero.

client_app is the app’s own client object, so it is read through the same message_stats() the link report uses rather than through a second accounting of the same thing.

static sim_hooks(config, model_search_dirs)

Sim-side processes to start before servers/clients (default: none).

An app declares what its simulator needs (e.g. the braking app returns a ScenarioRunner LaunchSpec so the ego exists before the client attaches). Returns a list of LaunchSpec; the orchestrator starts them first and tears them down last.

cadet.core.apps.register_app(cls)

Class decorator that registers an AppPlugin by its name.

Return type:

Type[AppPlugin]

Parameters:

cls (Type[AppPlugin])

exception cadet.core.apps.UnknownAppError

Bases: KeyError

No app plugin is registered under the requested name.

A KeyError subclass, because that is what get_app() has always raised and callers catch it; the message is readable so the name reaches the person running the command rather than only a traceback.

cadet.core.apps.get_app(name)

Return the plugin registered under name.

Raises UnknownAppError, a KeyError, naming what is registered.

Return type:

Type[AppPlugin]

Parameters:

name (str)

cadet.core.apps.available_apps()

Return the sorted names of all registered app plugins.

Return type:

List[str]

cadet.core.apps.import_app_modules(modules)

Import each module so its @register_app plugins register.

Used by the CLI (--app-module). Keeps cadet/ free of examples/ imports: the app module path is supplied at run time.

The working directory is searched, which is not the default and is the reason this is more than one line. An editable install puts the cadet package on the path and nothing else, and a console script’s own sys.path[0] is the directory the script lives in - the virtualenv’s bin - so cadet run --app-module examples.distributed_sensing.app from a fresh clone could not import examples at all, while the same command as python -m cadet could, because that form puts the working directory on the path. That difference is invisible from the command line and the error it produced said only that no module was named examples.

A module named on the command line is a path into whatever project the caller is standing in, so the working directory is where it is looked for. It is appended rather than prepended: an installed module of the same name keeps winning, so a directory that happens to hold a json.py cannot shadow the standard library.

Return type:

None

Parameters:

modules (List[str])

Transport interface: how roles exchange length-framed payloads over a link.

What this is for:

One abstract way to send/recv byte payloads between roles over a real TCP socket, optionally shaped by a NetworkModel so network effects (delay, jitter, loss, bandwidth) can be emulated.

What it contains:
  • Transport: the abstract send/recv contract.

  • the wire layers protocol and mode select: _SocketChannel and _WebSocketChannel carry bytes; _LengthFraming and _StreamFraming find a payload’s boundaries in them.

  • _RecvDelayLine / _SendDelayLine: per-direction delay lines (reader/sender threads with a non-decreasing release schedule).

  • FramedSocketTransport: the real TCP transport used by the runtimes.

  • SourceMessage and MultiConnectionEndpoint: a server side that accepts several clients at once and merges them into one queue.

  • LinkCounters and counters_for() / counter_snapshot(): per-link, per-direction byte and message counters, which is where the bandwidth collector (cadet.metrics.bandwidth) reads from.

How it fits into CADET:

Built from config.links; the client and server runtimes hold a transport each. The link’s forward/reverse network models attach to the recv/send delay lines.

Two independent choices, from ``transport``. protocol picks what carries the bytes - tcp is the socket itself, websocket puts the same bytes inside RFC 6455 binary frames after one HTTP upgrade (cadet.core.websocket), which is what lets a link cross infrastructure that forwards HTTP and nothing else. mode picks how a payload’s boundaries are found on top of that - frame prefixes each payload with its length (cadet.core.service, what every example has always used), stream sends no prefix at all and lets the receiver read each record’s extent out of the record itself (cadet.core.codec.record_length()), which is why stream mode needs transport.encoding: safe: a pickle payload carries no length and cannot be delimited in a byte stream.

The two choices compose, and everything above them is unchanged: the delay lines, the counters, MultiConnectionEndpoint and the apps see the same payloads whichever pair is configured.

One connection or many. FramedSocketTransport.serve_one() is the single-client server every example used, and it keeps working unchanged. MultiConnectionEndpoint is the general form: it accepts N clients, gives each its own reader and its own delay line, and merges them into one inbound queue with every message tagged by the connection it came from. Three things need that shape - V2I fan-in (an ego and an infrastructure stream into one roadside node), the load role (N synthetic clients into one server), and a pipeline fan-in boundary.

Each connection keeping its own delay line is the point, not an implementation detail: a link’s delay is a property of that connection, so merging first and delaying afterwards would attribute one client’s latency to another and make per-connection statistics meaningless.

Counted where the bytes are. A transport knows how much it carried and which connection carried it, so the byte counters live here rather than being inferred from a payload size somewhere else. They count payload bytes and messages per direction; the 4-byte length prefix from cadet.core.service, the websocket frame header and everything TCP adds are excluded, so framing overhead stays derivable from the message count and the configured protocol instead of being folded into the byte count.

How to configure it:

Link network models come from the config; this module only defines behaviour, not values. transport.protocol and transport.mode select the wire layers above, and the role runtimes pass them to connect(), serve_one() and MultiConnectionEndpoint.serve(). The counters are always maintained (an integer add per message) and are only recorded when metrics.collectors names bandwidth.

class cadet.core.transport.LinkCounters(label)

Bases: object

Payload bytes and messages one connection carried, per direction.

sent is what this node handed to the link and recv what the link delivered to it, so the pair read from the two ends of one link describes both directions without either end guessing about the other.

Parameters:

label (str)

label
bytes_sent
bytes_recv
messages_sent
messages_recv
add_sent(size)

Count one outbound message of size payload bytes.

Return type:

None

Parameters:

size (int)

add_recv(size)

Count one inbound message of size payload bytes.

Return type:

None

Parameters:

size (int)

snapshot()

A detached copy, so a sampler reads consistent totals.

Return type:

LinkCounters

cadet.core.transport.counters_for(label)

Return (creating if needed) the counters for the link called label.

Return type:

LinkCounters

Parameters:

label (str)

cadet.core.transport.counter_snapshot()

Return a detached copy of every link’s counters, in label order.

Return type:

List[LinkCounters]

cadet.core.transport.reset_counters()

Forget every link’s counters (used between tests, and by a re-run role).

Return type:

None

class cadet.core.transport.Transport

Bases: ABC

Abstract bidirectional payload transport.

abstractmethod send(payload)

Enqueue/transmit a payload.

Return type:

None

Parameters:

payload (Any)

abstractmethod recv()

Return the next payload, or None if none is available.

Return type:

Optional[Any]

class cadet.core.transport.FramedSocketTransport(conn, recv_model=None, send_model=None, node=None, label=None, protocol='tcp', mode='frame', server_side=False)

Bases: Transport

Real socket transport carrying byte payloads over the configured wire.

The default wire is the one every example has used: plain TCP with the 4-byte length framing in cadet.core.service. protocol and mode select the alternatives (websocket, and a self-delimited stream); see this module’s docstring. Optional recv_model (forward direction) and send_model (reverse direction) attach proper delay lines so network effects are emulated per-message without serializing on processing.

server_side is the one thing the two ends cannot share: a websocket handshake has a requesting and an accepting half, and the RFC’s masking rule is the other way round on each. It is False for a connecting transport and True for an accepted one, and is ignored over plain TCP.

label names the link this connection is, for the byte counters; it defaults to the peer’s address, which is the only identity a transport has on its own. A caller that knows the link or node name passes it, so a bandwidth_<node>.csv names links rather than ports.

Parameters:
  • conn (socket)

  • recv_model (NetworkModel | None)

  • send_model (NetworkModel | None)

  • label (str | None)

  • protocol (str)

  • mode (str)

  • server_side (bool)

classmethod connect(host, port, recv_model=None, send_model=None, retry_s=0.0, node=None, label=None, protocol='tcp', mode='frame')

Open a client connection to host:port (retrying up to retry_s).

Return type:

FramedSocketTransport

Parameters:
  • host (str)

  • port (int)

  • retry_s (float)

  • label (str | None)

  • protocol (str)

  • mode (str)

classmethod serve_one(host, port, recv_model=None, send_model=None, backlog=1, node=None, label=None, protocol='tcp', mode='frame')

Bind host:port, accept one client, and return its transport.

Return type:

FramedSocketTransport

Parameters:
  • host (str)

  • port (int)

  • backlog (int)

  • label (str | None)

  • protocol (str)

  • mode (str)

send(payload)

Enqueue/transmit a payload.

Return type:

None

Parameters:

payload (bytes)

recv()

Return the next payload, or None if none is available.

Return type:

Optional[bytes]

close()

Close the underlying socket, saying goodbye on the wire first.

Return type:

None

class cadet.core.transport.SourceMessage(source_id, payload, received_at)

Bases: object

One inbound payload and the connection it arrived on.

source_id is what makes a merged queue usable: once several clients feed one queue, a payload without its origin cannot be replied to, attributed to a stream, or counted per connection.

Parameters:
  • source_id (str)

  • payload (bytes)

  • received_at (float)

source_id
payload
received_at
class cadet.core.transport.MultiConnectionEndpoint(policy='fifo')

Bases: object

A server endpoint that serves several clients through one queue.

Each accepted connection gets its own FramedSocketTransport, and so its own reader thread and its own delay line; a drain thread per connection moves released messages into the inbound queue. The delay a message waited is therefore the delay configured for its connection, which is what keeps per-connection latency statistics meaningful.

policy decides the order messages leave the endpoint:

fifo

One shared queue. A message is returned as soon as its own delay line releases it, so the order across connections is release order - the order the messages actually became available.

round_robin

A queue per connection, served in rotation, at most one message per connection per turn. A client sending fast cannot starve a slow one, which is what makes a load experiment’s scheduling the experiment’s rather than an accident of arrival order.

A connection that closes is removed from service and the others continue; recv() returns None only once every connection has closed, so one client dying does not end the run for the rest.

Parameters:

policy (str)

POLICY_FIFO = 'fifo'
POLICY_ROUND_ROBIN = 'round_robin'
POLICIES = ('fifo', 'round_robin')
classmethod serve(host, port, expect=1, recv_model=None, send_model=None, policy='fifo', accept_timeout_s=60.0, node=None, model_for=None, protocol='tcp', mode='frame')

Bind host:port and accept expect clients, then serve them.

recv_model/send_model apply to every connection. model_for overrides that per connection: given the source id it returns (recv_model, send_model), which is what a config with a different link per stream needs - an ego and an infrastructure feed into one roadside node are not the same link.

protocol/mode are the wire every accepted connection uses; they are one endpoint-wide choice because they come from one transport section, and a peer cannot negotiate its own.

All expect clients are accepted before serving begins, which matches what the roles need (they are started together by the orchestrator) and makes the readiness barrier meaningful. A client that connects later is not accepted; that is a deliberate limitation, not an oversight.

Return type:

MultiConnectionEndpoint

Parameters:
  • host (str)

  • port (int)

  • expect (int)

  • policy (str)

  • accept_timeout_s (float)

  • protocol (str)

  • mode (str)

recv(timeout_s=None)

Return the next message, or None when every connection has closed.

timeout_s bounds the wait; None waits until a message arrives or all connections close.

Return type:

Optional[SourceMessage]

Parameters:

timeout_s (float | None)

send(source_id, payload)

Reply to one connection, by the id its message carried.

Return type:

None

Parameters:
  • source_id (str)

  • payload (bytes)

broadcast(payload)

Send to every connection still open.

Return type:

None

Parameters:

payload (bytes)

sources()

Every connection ever accepted, in accept order.

Return type:

List[str]

active_sources()

Connections still open, in accept order.

Return type:

List[str]

transport_for(source_id)

Return one connection’s transport, for per-connection measurement.

Return type:

Optional[FramedSocketTransport]

Parameters:

source_id (str)

delay_stamps(source_id)

Return one connection’s (arrival, release) stamps.

Per connection on purpose: this is how a test or a metric checks that the delay a stream saw is the delay its own link configured, rather than an average over whatever else shared the queue.

Return type:

List[tuple]

Parameters:

source_id (str)

close()

Close every connection and the listener, if one is still open.

Return type:

None

Network model for the message-level link backend (mode: delay).

Defines how a link perturbs traffic at the message level: a delay sampled per application message, message loss, and bandwidth serialization. The queuing and release is done by the delay line in cadet.core.transport; this module only supplies the samples.

This is one of two emulation layers (see “Link backend semantics” in docs/config-reference.md). At the message level (mode: delay), whole application messages are held and dropped. direction: forward delays requests and leaves replies untouched. The sampled distribution is reproduced at the application level because nothing between the two processes reacts to it. At the packet level (mode: netem, mode: netwaggle), a kernel qdisc holds packets and the transport reacts. A configured 60 ms forward link measures p50 60.4 ms here and about 149 ms through a packet-level backend; that gap is TCP’s behaviour rather than emulator error.

Contains: NetworkModel (sample_delay_s / drops / serialization_s), NullNetworkModel (pass-through), distribution samplers (constant / normal / lognormal / trace), and build_network_model(). Built from config.links[*].network; only mode: delay is realised here. none, netem and netwaggle all yield a NullNetworkModel so kernel-level backends are not counted twice.

class cadet.core.network.NetworkModel

Bases: ABC

Per-message network perturbation sampler.

abstractmethod sample_delay_s()

Sample a propagation delay (seconds) for the next message.

Return type:

float

abstractmethod drops()

Return True if the current message should be dropped (loss).

Return type:

bool

abstractmethod serialization_s(size_bytes)

Transmission (serialization) delay for size_bytes at the link rate.

Return type:

float

Parameters:

size_bytes (int)

class cadet.core.network.NullNetworkModel

Bases: NetworkModel

Pass-through: zero delay, no loss, no bandwidth limit.

sample_delay_s()

Sample a propagation delay (seconds) for the next message.

Return type:

float

drops()

Return True if the current message should be dropped (loss).

Return type:

bool

serialization_s(size_bytes)

Transmission (serialization) delay for size_bytes at the link rate.

Return type:

float

Parameters:

size_bytes (int)

class cadet.core.network.SampledNetworkModel(distribution, loss=0.0, bandwidth_mbps=None, rng=None)

Bases: NetworkModel

Delay from a distribution, plus optional loss and bandwidth.

Parameters:
  • distribution (_Distribution)

  • loss (float)

  • bandwidth_mbps (float | None)

  • rng (Random | None)

sample_delay_s()

Sample a propagation delay (seconds) for the next message.

Return type:

float

drops()

Return True if the current message should be dropped (loss).

Return type:

bool

serialization_s(size_bytes)

Transmission (serialization) delay for size_bytes at the link rate.

Return type:

float

Parameters:

size_bytes (int)

class cadet.core.network.CompositeNetworkModel(models)

Bases: NetworkModel

Several hops in series, as one per-message model.

A composed multi-hop path (routes[*].realise: compose) keeps one end-to-end connection, so the hops cannot each hold the message in turn: their effects are added up instead. Per message that is

  • delay: the sum of the hops’ samples. Each hop samples from its own distribution with its own RNG stream, so two hops configured alike still vary independently, which is the point of modelling them as two hops.

  • loss: lost if any hop loses it. A message does not arrive by surviving the worst hop; it has to survive all of them.

  • bandwidth: the slowest hop’s serialisation time, not the sum. The hops are a pipeline, not a queue: the bottleneck sets the rate, and a store-and-forward chain that really did add them up is realise: relay, which is a relay process per hop and not this.

Parameters:

models (List[NetworkModel])

sample_delay_s()

Sample a propagation delay (seconds) for the next message.

Return type:

float

drops()

Return True if the current message should be dropped (loss).

Return type:

bool

serialization_s(size_bytes)

Transmission (serialization) delay for size_bytes at the link rate.

Return type:

float

Parameters:

size_bytes (int)

cadet.core.network.build_network_model(net, rng=None)

Build a runtime NetworkModel from a schema NetworkModel config.

Only mode: delay yields a SampledNetworkModel; every other mode gives a pass-through. none has no emulation at all, and the netem and netwaggle backends shape traffic outside this process (in a qdisc or in an emulated network), so sampling a delay here as well would apply the configured delay twice.

rng makes the samples reproducible (seed it from the experiment seed in runs; fix it in tests).

Return type:

NetworkModel

Parameters:

rng (Random | None)

cadet.core.network.build_path_network_model(nets, rng=None)

Build one model for a path of hop network configs, in order.

One hop gives exactly what build_network_model() gives, so a direct link and a one-hop path cannot behave differently. Several hops give a CompositeNetworkModel, each hop seeded from rng so the streams are independent but the run is still reproducible from one seed.

Return type:

NetworkModel

Parameters:

rng (Random | None)

Source interface: where pipeline input frames come from.

What this is for:

A uniform way to pull input frames regardless of backend: CARLA, replay, synthetic, and live. Mirrors the schema’s discriminated source union.

What it contains:
  • Frame: a minimal frame container (image + metadata).

  • Source: the abstract open/next_frame/close/metadata lifecycle.

  • ego_removed(): whether a simulated source’s ego has left the world, asked at a bounded rate. Here rather than in either client app so the two cannot answer the same question differently.

How it fits into CADET:

A runner opens a source built from config.source (see cadet.sources), pulls frames with Source.next_frame(), feeds them through the pipeline, and closes it.

cadet.core.source.ego_removed(source, checked_at, now=None)

Return (removed, checked_at) for a source whose ego may be gone.

removed is True only when the source says so; checked_at is the timestamp to keep for the next call, unchanged when the rate limit meant no question was asked. A source with no ego_is_alive is never reported as having lost one, so a replay or synthetic source is unaffected.

Why a client needs this at all: a scenario that ends before the vehicle stops destroys the ego, and the client then waits for a stop that cannot arrive until something else times out. Why it is asked of the source rather than of the handle: in the simulator version this was measured against, neither is_alive nor a lookup by id stops answering for an actor the server has destroyed - only the world’s own actor list does, and cadet.sources.carla.CarlaSource.ego_is_alive() is where that lives.

class cadet.core.source.Frame(image=None, meta=None)

Bases: object

A single input frame: an image payload plus arbitrary metadata.

Parameters:
  • image (Any)

  • meta (Dict[str, Any] | None)

class cadet.core.source.Source

Bases: ABC

Abstract frame source with an explicit open/close lifecycle.

abstractmethod open()

Acquire the backend (connect to sim, open file, start sensor).

Return type:

None

abstractmethod next_frame()

Return the next Frame, or None if none is available now.

None is not by itself the end of the stream. A file or a generator has nothing left when it returns None, but a live source returns None whenever nothing has arrived yet - which is always true on the first tick, before its first sensor callback. Ask exhausted() to tell the two apart.

Return type:

Optional[Frame]

abstractmethod close()

Release backend resources.

Return type:

None

abstractmethod metadata()

Return static source metadata (resolution, fps, map, …).

Return type:

Dict[str, Any]

prepare()

Do the setup that does not need the scene to exist yet.

Called before the client announces it is ready. For a simulator source this is connecting to the simulator; for everything else there is nothing to do, and open() remains the whole of the startup.

Return type:

None

await_scene(timeout_s)

Block until the scene this source needs exists. True if it appeared.

Called after the client has announced it is ready and the scenario has been started. The default returns True immediately: a source with no external scene is always ready.

Return type:

bool

Parameters:

timeout_s (float)

exhausted()

True if no further frames will ever arrive.

Only meaningful straight after next_frame() returned None, which is the one case where a consumer has to know whether to wait or to stop. The default is True, which is the behaviour a file or a generator wants and what the interface used to imply unconditionally; a live source overrides it, because its empty moments are not its end.

Return type:

bool

Model registry: logical model name -> concrete artifact per device.

What this is for:

Resolves a logical model (e.g. yolo11x) to the artifact file for a given device type (e.g. gpu -> yolo11x.pt, edge -> yolo11x.engine, hailo -> yolo11x.hef), and preflights that the needed artifacts actually exist before a run starts.

What it contains:
How it fits into CADET:

Built from config.models (cadet.config.schema). Detection/tracking roles ask it for the artifact matching the node’s device type; the runner calls ModelRegistry.preflight() up front so missing weights fail fast rather than mid-experiment.

How to configure it:

models.registry maps logical names to per_device artifacts; models.device picks the active device type. Artifacts are looked up under the search directories passed to preflight()/resolve().

cadet.core.model_registry.device_for_models(config)

Return the device type of the node that hosts the model.

Inference runs on the server node, so its device is the one the model registry resolves against. Falls back to a sim node, then to cpu.

Return type:

str

cadet.core.model_registry.visible_gpu_index(gpu_index)

Map a host GPU index onto the index torch will actually see.

CUDA_VISIBLE_DEVICES renumbers: whatever it lists becomes 0, 1, … in that order, so a config’s host index is not what torch indexes once the variable is set - and the container launchers set it, because --gpus device=N filters the devices through the device cgroup and the one that survives is renumbered to 0.

Measured, with the server in a container pinned to the host’s second GPU: the role was told cuda:1 from its config and ultralytics refused with Invalid CUDA 'device=1' requested and torch.cuda.is_available(): False, while cuda:0 is that same card. Unset, nothing is renumbered and the host index is the right answer, which is the case for a role that runs as a host process.

Return type:

int

Parameters:

gpu_index (int)

cadet.core.model_registry.torch_device_for(config)

Return the preferred torch device string for the hosting node.

Maps the server/sim node to a torch device: an explicit gpu_index -> cuda:<i>, where i is that device’s index as this process sees it (see visible_gpu_index()); a gpu/edge device type -> cuda; otherwise cpu. This is torch-free (returns a string); callers fall back to cpu if cuda is absent.

Return type:

str

exception cadet.core.model_registry.PreflightError(missing)

Bases: Exception

Raised when one or more required model artifacts are missing.

Parameters:

missing (List[ModelResolution])

class cadet.core.model_registry.ModelResolution(name, device, artifact, path=None)

Bases: object

A logical model resolved to a concrete artifact for one device type.

Parameters:
  • name (str)

  • device (str)

  • artifact (str)

  • path (str | None)

class cadet.core.model_registry.ModelRegistry(registry, device)

Bases: object

Resolve logical models to per-device artifacts and preflight them.

Parameters:
  • registry (Dict[str, Dict[str, str]])

  • device (str)

classmethod from_config(models, device)

Build from a schema Models object and the hosting node’s device.

device comes from the node that runs the model (see device_for_models()), not from the models section itself.

Return type:

ModelRegistry

Parameters:

device (str)

artifact(name, device=None)

Return the artifact filename for name on the active/given device.

Return type:

str

Parameters:
  • name (str)

  • device (str | None)

resolve(name, search_dirs, device=None)

Resolve name to an artifact and locate it under search_dirs.

Return type:

ModelResolution

Parameters:
  • name (str)

  • search_dirs (List[str])

  • device (str | None)

preflight(search_dirs, device=None)

Resolve every model for the active device; raise if any are missing.

Returns the list of successful resolutions. Raises PreflightError listing everything that could not be located.

Return type:

List[ModelResolution]

Parameters:
  • search_dirs (List[str])

  • device (str | None)

Length-framed message framing over a byte stream (TCP socket).

TCP is a byte stream with no message boundaries. These helpers put a 4-byte big-endian length prefix in front of every payload so the receiver can read one message at a time. cadet.core.transport.FramedSocketTransport uses this framing for all client/server traffic; the delay lines operate on whole framed messages. This is fixed wire framing with no user-facing configuration.

Functions: send_msg() (length-prefix and send), recv_msg() (read one framed payload, None at EOF), recvall() (read n bytes, None if the peer closes early).

cadet.core.service.send_msg(sock, msg)

Send msg (bytes) prefixed with its _LEN_BYTES-byte length.

cadet.core.service.recv_msg(sock)

Receive one length-framed message, or None if the peer closed first.

cadet.core.service.recvall(sock, n)

Read n bytes from sock, or None if it closes early.

Launcher interface: start/stop/supervise a role process on a node.

What this is for:

Abstracts how a role process is started on a node, independent of whether the node is local, a docker container, ssh-into-docker, or ssh-into-venv. The orchestrator builds a LaunchSpec per node and hands it to a launcher; only the launcher knows how to turn that into a running process.

What it contains:
  • LaunchStatus: status constants returned by Launcher.poll().

  • LaunchSpec: everything needed to start one process (argv, cwd, env, log file, optional readiness marker).

  • Handle: a started process + its spec and log path.

  • Launcher: abstract launch/wait_ready/poll/stop.

  • LocalLauncher: spawns real local subprocesses (the only launcher implemented today).

  • IMAGE_PYTHON / IMAGE_PYTHON_VERSION, and role_executable() / role_python_version(): which interpreter a role placed with a given launcher kind will actually run under, which is not in general the one running the orchestrator.

How it fits into CADET:

The orchestrator (cadet.orchestrator) selects a launcher per config.nodes[*].launcher and uses it to bring servers, clients and sim hooks up and down in order, tearing everything down on exit. The other launcher kinds implement this same interface: docker and ssh_docker in cadet.core.docker_launcher, ssh_venv in cadet.core.venv_launcher.

How to configure it:

Launcher choice comes from nodes[*].launcher; process details come from the spec the orchestrator builds. This module defines behaviour, not values.

cadet.core.launcher.role_executable(launcher_kind)

Return the interpreter that will run a role placed with this launcher.

A local role is a child of this process, so it runs the same interpreter. Every other kind starts the role somewhere this process’s interpreter does not exist, so the value is a statement about the interpreter there rather than a path any of them uses verbatim: the docker launchers strip the prefix from argv, since the image’s entry point is cadet, and the venv launcher substitutes the venv’s own interpreter path, which only it knows. Stating it is what the version check reads.

Return type:

str

Parameters:

launcher_kind (str)

cadet.core.launcher.role_python_version(launcher_kind)

Return the “major.minor” Python a role placed with this launcher gets.

This - not the orchestrator’s own version - is the question the CARLA client egg check has to ask. The egg is imported by the role that opens the simulator and never by the orchestrator, so asking about the orchestrator refused a sound run whenever the two differed, which is exactly the case where the orchestrator runs on a host python and its roles run in the image.

For ssh_venv this is a requirement and not an observation: a venv is whatever version it was created with, so the placement asks the venv its version and refuses one that is not this (cadet.orchestrator.placement.require_venv()). Without that the check above would be sound and its premise false.

Return type:

str

Parameters:

launcher_kind (str)

class cadet.core.launcher.LaunchStatus

Bases: object

String status constants for a launched role.

STOPPED = 'stopped'
RUNNING = 'running'
FAILED = 'failed'
class cadet.core.launcher.LaunchSpec(name, argv, cwd=None, env=None, log_path=None, readiness_marker=None, readiness_timeout_s=60.0)

Bases: object

Everything needed to start one role process.

readiness_marker is a substring the process prints to its log once it is ready to accept work (e.g. a server that is listening); the orchestrator waits for it before starting dependents. None means “ready as soon as started”.

Parameters:
  • name (str)

  • argv (List[str])

  • cwd (str | None)

  • env (Dict[str, str] | None)

  • log_path (str | None)

  • readiness_marker (str | None)

  • readiness_timeout_s (float)

class cadet.core.launcher.Handle(spec, proc, log_fh)

Bases: object

A started process, its spec, and the open log file handle.

Parameters:

spec (LaunchSpec)

property pid: int | None
class cadet.core.launcher.Launcher

Bases: ABC

Abstract process launcher for a role on a node.

abstractmethod launch(spec)

Start the process described by spec and return a Handle.

Return type:

Handle

Parameters:

spec (LaunchSpec)

abstractmethod wait_ready(handle, timeout_s=None)

Block until the handle’s readiness marker appears (or it exits/timeouts).

timeout_s overrides the spec’s own timeout, which the orchestrator uses to cut a wait down to what is left of experiment.max_startup_s.

Return type:

bool

Parameters:
  • handle (Handle)

  • timeout_s (float | None)

abstractmethod poll(handle)

Return one of LaunchStatus for a handle.

Return type:

str

Parameters:

handle (Handle)

abstractmethod stop(handle, grace_s=5.0)

Stop the process (idempotent); escalate to kill after grace_s.

Return type:

None

Parameters:
  • handle (Handle)

  • grace_s (float)

cadet.core.launcher.child_env(spec)

Return the environment overrides for spec’s child process.

Child stdout is forced unbuffered. Every launcher decides readiness by watching for a marker in the child’s log, and block buffering kicks in as soon as stdout is a file rather than a tty - which it always is here - so a marker that is already printed can sit unseen until the wait times out. The startup timeouts attributed to ScenarioRunner were this.

SDL_NO_SIGNAL_HANDLERS is the second one, and it is a teardown fix. SDL installs its own SIGINT and SIGTERM handlers when it initialises, so a role that renders anything through pygame stops responding to the signal this orchestrator stops it with: its own handler never runs, and it is SIGKILLed when the grace expires. Measured on the braking client with the ported visualiser: teardown 5.2 s with SDL’s handlers against 0.2 s without, on every backend, in every case where a worker has to be stopped rather than exiting by itself.

A spec’s own variables win over it: they are the app’s, and the app knows what its hook needs.

Return type:

Dict[str, str]

Parameters:

spec (LaunchSpec)

class cadet.core.launcher.LocalLauncher

Bases: Launcher

Spawns local subprocesses and supervises them via their log + exit code.

launch(spec)

Start the process described by spec and return a Handle.

Return type:

Handle

Parameters:

spec (LaunchSpec)

wait_ready(handle, timeout_s=None)

Block on the spec’s readiness marker using the ported barrier.

The barrier itself lives in cadet.orchestrator.lifecycle, ported from the original orchestrators, so the host path, the emulated path and this launcher all wait in the same way.

Return type:

bool

Parameters:
  • handle (Handle)

  • timeout_s (float | None)

poll(handle)

Return one of LaunchStatus for a handle.

Return type:

str

Parameters:

handle (Handle)

stop(handle, grace_s=5.0)

Stop the process (idempotent); escalate to kill after grace_s.

Return type:

None

Parameters:
  • handle (Handle)

  • grace_s (float)