cadet.core¶
Decorator-based app plugin registry (framework, app-agnostic).
- What this is for:
Apps register themselves here. Each plugin advertises its
nameand its typedparams_model, so the loader can validateapp.paramsagainst the right model. The framework ships no app registrations; apps live underexamples/and register on import (e.g.--app-module examples.braking.flat.app).- What it contains:
AppPlugin: the abstract base every app subclasses.register_app(): class decorator that adds a plugin to the registry.get_app()/available_apps(): registry lookup.
- How it fits into CADET:
experiment.app/app.pluginname a registered plugin. The CLI imports the requested app module(s) before dispatch;cadet.config.loader.resolve_app_params()then validates the config’sapp.paramsagainst the plugin’s model. Nothing undercadet/importsexamples/.
- class cadet.core.apps.AppPlugin¶
Bases:
ABCBase class for an app plugin.
Subclasses set
name(the plugin key used in configs) andparams_model(the pydantic model validatingapp.paramsfor 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_appis the app’s own client object, so it is read through the samemessage_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
LaunchSpecso the ego exists before the client attaches). Returns a list ofLaunchSpec; the orchestrator starts them first and tears them down last.
-
name:
- exception cadet.core.apps.UnknownAppError¶
Bases:
KeyErrorNo app plugin is registered under the requested name.
A
KeyErrorsubclass, because that is whatget_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, aKeyError, 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_appplugins register.Used by the CLI (
--app-module). Keepscadet/free ofexamples/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
cadetpackage on the path and nothing else, and a console script’s ownsys.path[0]is the directory the script lives in - the virtualenv’sbin- socadet run --app-module examples.distributed_sensing.appfrom a fresh clone could not importexamplesat all, while the same command aspython -m cadetcould, 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 namedexamples.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.pycannot 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/recvbyte payloads between roles over a real TCP socket, optionally shaped by aNetworkModelso network effects (delay, jitter, loss, bandwidth) can be emulated.- What it contains:
Transport: the abstract send/recv contract.the wire layers
protocolandmodeselect:_SocketChanneland_WebSocketChannelcarry bytes;_LengthFramingand_StreamFramingfind 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.SourceMessageandMultiConnectionEndpoint: a server side that accepts several clients at once and merges them into one queue.LinkCountersandcounters_for()/counter_snapshot(): per-link, per-direction byte and message counters, which is where thebandwidthcollector (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/reversenetworkmodels attach to the recv/send delay lines.Two independent choices, from ``transport``.
protocolpicks what carries the bytes -tcpis the socket itself,websocketputs 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.modepicks how a payload’s boundaries are found on top of that -frameprefixes each payload with its length (cadet.core.service, what every example has always used),streamsends 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 needstransport.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,
MultiConnectionEndpointand 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.MultiConnectionEndpointis 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), theloadrole (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.protocolandtransport.modeselect the wire layers above, and the role runtimes pass them toconnect(),serve_one()andMultiConnectionEndpoint.serve(). The counters are always maintained (an integer add per message) and are only recorded whenmetrics.collectorsnamesbandwidth.
- class cadet.core.transport.LinkCounters(label)¶
Bases:
objectPayload bytes and messages one connection carried, per direction.
sentis what this node handed to the link andrecvwhat 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
sizepayload bytes.- Return type:
None- Parameters:
size (int)
- add_recv(size)¶
Count one inbound message of
sizepayload bytes.- Return type:
None- Parameters:
size (int)
- snapshot()¶
A detached copy, so a sampler reads consistent totals.
- Return type:
- cadet.core.transport.counters_for(label)¶
Return (creating if needed) the counters for the link called
label.- Return type:
- 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:
ABCAbstract bidirectional payload transport.
- abstractmethod send(payload)¶
Enqueue/transmit a payload.
- Return type:
None- Parameters:
payload (Any)
- abstractmethod recv()¶
Return the next payload, or
Noneif 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:
TransportReal 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.protocolandmodeselect the alternatives (websocket, and a self-delimitedstream); see this module’s docstring. Optionalrecv_model(forward direction) andsend_model(reverse direction) attach proper delay lines so network effects are emulated per-message without serializing on processing.server_sideis 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.labelnames 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 abandwidth_<node>.csvnames 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 toretry_s).- Return type:
- 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:
- 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
Noneif 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:
objectOne inbound payload and the connection it arrived on.
source_idis 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:
objectA 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.policydecides the order messages leave the endpoint:fifoOne 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_robinA 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()returnsNoneonly 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:portand acceptexpectclients, then serve them.recv_model/send_modelapply to every connection.model_foroverrides 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/modeare the wire every accepted connection uses; they are one endpoint-wide choice because they come from onetransportsection, and a peer cannot negotiate its own.All
expectclients 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:
- 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
Nonewhen every connection has closed.timeout_sbounds the wait;Nonewaits 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:
ABCPer-message network perturbation sampler.
- abstractmethod sample_delay_s()¶
Sample a propagation delay (seconds) for the next message.
- Return type:
float
- abstractmethod drops()¶
Return
Trueif the current message should be dropped (loss).- Return type:
bool
- abstractmethod serialization_s(size_bytes)¶
Transmission (serialization) delay for
size_bytesat the link rate.- Return type:
float- Parameters:
size_bytes (int)
- class cadet.core.network.NullNetworkModel¶
Bases:
NetworkModelPass-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
Trueif the current message should be dropped (loss).- Return type:
bool
- serialization_s(size_bytes)¶
Transmission (serialization) delay for
size_bytesat 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:
NetworkModelDelay 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
Trueif the current message should be dropped (loss).- Return type:
bool
- serialization_s(size_bytes)¶
Transmission (serialization) delay for
size_bytesat the link rate.- Return type:
float- Parameters:
size_bytes (int)
- class cadet.core.network.CompositeNetworkModel(models)¶
Bases:
NetworkModelSeveral 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 isdelay: 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
Trueif the current message should be dropped (loss).- Return type:
bool
- serialization_s(size_bytes)¶
Transmission (serialization) delay for
size_bytesat the link rate.- Return type:
float- Parameters:
size_bytes (int)
- cadet.core.network.build_network_model(net, rng=None)¶
Build a runtime
NetworkModelfrom a schemaNetworkModelconfig.Only
mode: delayyields aSampledNetworkModel; every other mode gives a pass-through.nonehas no emulation at all, and thenetemandnetwagglebackends 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.rngmakes the samples reproducible (seed it from the experiment seed in runs; fix it in tests).- Return type:
- Parameters:
rng (Random | None)
- cadet.core.network.build_path_network_model(nets, rng=None)¶
Build one model for a path of hop
networkconfigs, 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 aCompositeNetworkModel, each hop seeded fromrngso the streams are independent but the run is still reproducible from one seed.- Return type:
- 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
sourceunion.- What it contains:
Frame: a minimal frame container (image + metadata).Source: the abstractopen/next_frame/close/metadatalifecycle.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(seecadet.sources), pulls frames withSource.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.removedis True only when the source says so;checked_atis the timestamp to keep for the next call, unchanged when the rate limit meant no question was asked. A source with noego_is_aliveis 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_alivenor a lookup by id stops answering for an actor the server has destroyed - only the world’s own actor list does, andcadet.sources.carla.CarlaSource.ego_is_alive()is where that lives.
- class cadet.core.source.Frame(image=None, meta=None)¶
Bases:
objectA single input frame: an image payload plus arbitrary metadata.
- Parameters:
image (Any)
meta (Dict[str, Any] | None)
- class cadet.core.source.Source¶
Bases:
ABCAbstract 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, orNoneif none is available now.Noneis 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. Askexhausted()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()returnedNone, 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:
ModelResolution: a resolved (name, device, artifact, path) record.ModelRegistry: resolve + preflight, built from a schemaModels.PreflightError: raised when a required artifact is missing.
- 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 callsModelRegistry.preflight()up front so missing weights fail fast rather than mid-experiment.- How to configure it:
models.registrymaps logical names toper_deviceartifacts;models.devicepicks the active device type. Artifacts are looked up under the search directories passed topreflight()/resolve().
- cadet.core.model_registry.device_for_models(config)¶
Return the device type of the node that hosts the model.
Inference runs on the
servernode, so itsdeviceis the one the model registry resolves against. Falls back to asimnode, then tocpu.- 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_DEVICESrenumbers: 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=Nfilters 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:1from its config and ultralytics refused withInvalid CUDA 'device=1' requestedandtorch.cuda.is_available(): False, whilecuda:0is 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>, whereiis that device’s index as this process sees it (seevisible_gpu_index()); a gpu/edgedevicetype ->cuda; otherwisecpu. 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:
ExceptionRaised 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:
objectA 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:
objectResolve 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
Modelsobject and the hosting node’s device.devicecomes from the node that runs the model (seedevice_for_models()), not from the models section itself.- Return type:
- Parameters:
device (str)
- artifact(name, device=None)¶
Return the artifact filename for
nameon the active/given device.- Return type:
str- Parameters:
name (str)
device (str | None)
- resolve(name, search_dirs, device=None)¶
Resolve
nameto an artifact and locate it undersearch_dirs.- Return type:
- 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
PreflightErrorlisting 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
Noneif the peer closed first.
- cadet.core.service.recvall(sock, n)¶
Read
nbytes fromsock, orNoneif 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
LaunchSpecper 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 byLauncher.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: abstractlaunch/wait_ready/poll/stop.LocalLauncher: spawns real local subprocesses (the only launcher implemented today).IMAGE_PYTHON/IMAGE_PYTHON_VERSION, androle_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 perconfig.nodes[*].launcherand 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:dockerandssh_dockerincadet.core.docker_launcher,ssh_venvincadet.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_venvthis 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:
objectString 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:
objectEverything needed to start one role process.
readiness_markeris 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.Nonemeans “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:
objectA started process, its spec, and the open log file handle.
- Parameters:
spec (LaunchSpec)
- property pid: int | None¶
- class cadet.core.launcher.Launcher¶
Bases:
ABCAbstract process launcher for a role on a node.
- abstractmethod launch(spec)¶
Start the process described by
specand return aHandle.- Return type:
- Parameters:
spec (LaunchSpec)
- abstractmethod wait_ready(handle, timeout_s=None)¶
Block until the handle’s readiness marker appears (or it exits/timeouts).
timeout_soverrides the spec’s own timeout, which the orchestrator uses to cut a wait down to what is left ofexperiment.max_startup_s.- Return type:
bool- Parameters:
handle (Handle)
timeout_s (float | None)
- abstractmethod poll(handle)¶
Return one of
LaunchStatusfor a handle.- Return type:
str- Parameters:
handle (Handle)
- 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_HANDLERSis 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:
LauncherSpawns local subprocesses and supervises them via their log + exit code.
- launch(spec)¶
Start the process described by
specand return aHandle.- Return type:
- 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
LaunchStatusfor a handle.- Return type:
str- Parameters:
handle (Handle)