cadet.orchestrator

Orchestrator: turn a config into running processes and back again, cleanly.

This module owns the lifecycle of a run and a sweep. For a run it clears its own leftovers, runs preflight, starts the servers and waits for readiness, starts the sim-side hooks and waits for their marker, starts clients/load, waits for the run to end by its experiment.end_on rule, then tears everything down in reverse order so no process is orphaned. For a sweep it enumerates the matrix and runs each cell; with experiment.resume (or --resume) it skips cells whose output is already complete, and by default it reruns them. An interrupted run is part of that lifecycle, not an exception to it: SIGTERM and SIGHUP are turned into an exception (cadet.orchestrator.lifecycle.interrupt_guard()) so the teardown runs, and whatever a harder kill leaves behind is removed by cadet down (cadet.orchestrator.recovery.sweep()). It provides PreflightError, preflight(), RunResult and Orchestrator.

It is called by cadet run / cadet sweep in cadet.cli, and spawns the role entry points (cadet serve / cadet client / cadet load) through the launcher each node’s config asks for: a host process, a container on this machine, or (in dry-run) a container on another machine. cadet.orchestrator.placement owns that dispatch, the per-run docker network and the per-node containers; this module keeps the ordering and the teardown, which do not change with where a role runs. Sim hooks come from the app plugin’s AppPlugin.sim_hooks().

It also records what a cross-node timestamp is worth: with metrics.collectors: clock_offset it measures each node’s clock against its own before the run and again after the roles have stopped, and writes the offset and its uncertainty into run.json (cadet.metrics.clock_offset). Nothing is corrected by it.

It also owns the lifetime of each link’s network backend, installing netem qdiscs before any role starts and removing them on teardown so a failed run cannot leave traffic shaped. For a containerised node the qdisc goes inside that node’s own namespace, through a runner the placement supplies, because the interface to shape is the container’s and not the host’s. The delay backend needs nothing here (it lives inside the transport), and netwaggle is driven by cadet emulate inside the emulation container.

Driven entirely by the experiment config (nodes, nodes.launcher, outputs) plus --app-module / --model-dir passed to role processes.

exception cadet.orchestrator.runner.PreflightError

Bases: Exception

Raised when a run cannot safely start (bad model, port in use, …).

cadet.orchestrator.runner.preflight(config, model_dirs, log=<built-in function print>, check_ports=True, allow_experimental=None)

Check a run can start: model artifacts resolve and listening ports are free.

Raises PreflightError with a readable message on the first problem. Throughput is a warning rather than a problem: a saturated link is a valid experiment, and only the experimenter can say whether this one is intended.

check_ports is False for the emulated backend, whose servers bind inside their own network namespaces: a port busy on the container’s localhost says nothing about the port an emulated host will bind, and refusing on it would reject runs that are fine.

allow_experimental accepts config options that are implemented but unverified; None defers to experiment.allow_experimental.

Return type:

None

Parameters:
  • model_dirs (List[str])

  • check_ports (bool)

  • allow_experimental (bool | None)

class cadet.orchestrator.runner.RunResult(run_id, out_dir, ok, detail='', reason='')

Bases: object

Outcome of a single run.

Parameters:
  • run_id (str)

  • out_dir (str)

  • ok (bool)

  • detail (str)

  • reason (str)

class cadet.orchestrator.runner.Orchestrator(launcher=None, log=<built-in function print>)

Bases: object

Starts and supervises the processes of a run or sweep (local launcher).

is_complete(config, run_id)

True if the run’s output dir already has a success marker (resume).

Return type:

bool

Parameters:

run_id (str)

run_one(config_path, overrides, run_index, rep, app_modules, model_dirs, allow_experimental=None)

Run one (run_index, rep) cell end-to-end, tearing everything down after.

Return type:

RunResult

Parameters:
  • config_path (str)

  • overrides (List[str])

  • run_index (int)

  • rep (int)

  • app_modules (List[str])

  • model_dirs (List[str])

  • allow_experimental (bool | None)

sweep(config_path, overrides, app_modules, model_dirs, reps=None, allow_experimental=None, resume=None)

Run every (run_index, rep) cell.

A completed cell is re-run unless resume is asked for, which is what the original did; resume (or experiment.resume) skips cells that already have a run.json.

Cells are separated by experiment.inter_run_pause_s, five seconds as in the original. It is not idle time: on a shared simulator it is what gave the previous run’s actors time to be cleared before the next scenario reloaded the world.

Stops early if a run is interrupted: a terminating signal is a request to stop the sweep, and the cells it never reached are left absent from the output.

Return type:

List[RunResult]

Parameters:
  • config_path (str)

  • overrides (List[str])

  • app_modules (List[str])

  • model_dirs (List[str])

  • reps (int | None)

  • allow_experimental (bool | None)

  • resume (bool | None)

status()

Return the current run-state (recorded active processes).

Return type:

dict

down()

Remove every CADET-owned leftover; return what was removed.

This is the recovery path for a run that never reached its teardown - a SIGKILL, or a stop before the signal guard was installed. It covers more than the processes it used to: containers, docker networks, emulated namespaces, OVS bridges, veths and the qdiscs a run recorded, each matched by ownership rather than by kind. See cadet.orchestrator.recovery.

Run-lifecycle steps, ported from the original orchestrator scripts.

The original experiment orchestrators already solved the lifecycle of a braking run: clear orphans and the server port, start the server and ScenarioRunner, block on a marker line in the scenario log, run the client to completion, then kill the scenario’s whole process group. This module is that logic, ported once so both the host orchestrator and the emulated session share one ordering and one teardown. Their hard-coded constants (port 10000, script names) became config fields; the readiness marker and its timeout come from the hook’s LaunchSpec. Three behaviours here are additions without an original equivalent: wall-clock limits on each phase (startup_limit_s(), active_limit_s()), treating a sim hook or server failure as the end of the run, and an explicit run-end rule (experiment.end_on). The original’s fuser -k port cleanup was narrowed: only CADET-owned processes are killed; a foreign holder is named by preflight and refused. Used by cadet.orchestrator.runner and cadet.network.netwaggle.session. Phase limits come from experiment.max_startup_s (defaults to the sum of readiness timeouts) and experiment.max_active_s (defaults to source.scenario.timeout_s plus a margin). experiment.end_on and experiment.end_grace_s control when and how cleanly a run stops.

exception cadet.orchestrator.lifecycle.StartupLimitExceeded

Bases: Exception

The startup phase ran past experiment.max_startup_s.

class cadet.orchestrator.lifecycle.RunTiming

Bases: object

How long each phase of a run took, and which limit ended it.

Recorded in run.json so a run that hit a limit can be told apart from one that was merely slow, without re-reading the logs: the phase durations say where the time went and limit says whether a bound was reached.

as_dict()
Return type:

Dict[str, object]

exception cadet.orchestrator.lifecycle.RunInterrupted

Bases: Exception

A terminating signal arrived while a run was active.

cadet.orchestrator.lifecycle.install_interrupt_guard()

Turn SIGTERM and SIGHUP into RunInterrupted; return the undo.

Default SIGTERM handling ends the process immediately, so a finally block never runs and an interrupted run leaves its processes, qdiscs and emulated network behind. Raising instead routes the interruption through the teardown the run already has, which is why this adds no teardown logic of its own. SIGINT already raises KeyboardInterrupt and is left alone.

Returned as a function rather than a context manager because the callers install it around a try/finally they already have, and wrapping that in another block would re-indent the whole run for no behavioural gain; interrupt_guard() is the block form for callers that want one. Signals cannot be installed from a non-main thread, where this is a no-op.

cadet.orchestrator.lifecycle.interrupt_guard()

Block form of install_interrupt_guard().

cadet.orchestrator.lifecycle.wait_for_line(file_handle, target_line, timeout=60.0)

Read forward through an open log until target_line appears.

Ported unchanged from the original orchestrators: it reads incrementally from wherever the handle is, so a marker already written is still seen, and the timeout applies to waiting for new output rather than to the total wait. A scenario that keeps logging therefore keeps its barrier open, which is the behaviour the original runs depended on.

Return type:

bool

cadet.orchestrator.lifecycle.wait_for_marker(log_path, target_line, proc=None, timeout=60.0)

Wait for target_line in log_path, giving up if proc exits.

The barrier itself is wait_for_line(). The process check is the addition: the original would sit in readline for the full timeout after ScenarioRunner had already died, so a crash cost a minute per run and reported only “did not start properly”.

Return type:

bool

Parameters:
  • log_path (str)

  • target_line (str)

  • timeout (float)

cadet.orchestrator.lifecycle.readiness_failure(name, proc=None, log_path=None)

Describe a failed readiness wait: who, whether it died, and its last words.

A wait can fail two ways that call for opposite fixes - the process exited, or it is alive and never printed its marker - and the message used to say neither. The log tail is included because the log a sweep writes is per-rep and the next rep overwrites the directory, so by the time the failure is read the evidence can be gone.

Return type:

str

Parameters:
  • name (str)

  • log_path (str | None)

cadet.orchestrator.lifecycle.orphan_patterns(config, sim_hook_specs=())

Return pkill -f patterns for the processes a previous run may have left.

The original listed its two script names and scenario_runner literally. Here the role processes are always cadet <sub> and the sim-side programs come from the app’s own hook specs, so the list is derived rather than hard-coded.

Return type:

List[str]

Parameters:

sim_hook_specs (Sequence)

cadet.orchestrator.lifecycle.listen_ports(config)

Return the ports this config’s listening nodes will bind.

These are the ports the original freed with fuser -k 10000/tcp, taken from the config instead of a constant.

Return type:

List[int]

cadet.orchestrator.lifecycle.process_cmdline(pid)

Return pid’s command line, or “” if it is gone or unreadable.

Return type:

str

Parameters:

pid (int)

cadet.orchestrator.lifecycle.process_cwd(pid)

Return pid’s working directory, or “” if it is gone or unreadable.

Evidence of ownership that does not depend on a record: a role started from a checkout runs with that checkout as its working directory, so a pattern-matched process can be attributed to a tree rather than guessed at. Unreadable for a process owned by another account, which is the right answer - a process this account cannot inspect is not one it should kill.

Return type:

str

Parameters:

pid (int)

cadet.orchestrator.lifecycle.process_start_ticks(pid)

Return pid’s start time in clock ticks since boot, or None.

Field 22 of /proc/<pid>/stat. It is what makes a recorded pid checkable after the fact: a pid is reused, a (pid, start time) pair is not, so a cleanup can tell the process it recorded from whatever now holds that number.

Parsed from after the last ) rather than by splitting the whole line, because field 2 is the executable name in parentheses and may itself contain spaces and parentheses.

Parameters:

pid (int)

cadet.orchestrator.lifecycle.all_pids()

Return every pid visible in /proc.

Return type:

List[int]

cadet.orchestrator.lifecycle.pids_matching(pattern)

Return the pids whose command line contains pattern, excluding ours.

The original used pkill -f, which also matches the shell running the cleanup and so kills itself. Reading /proc instead makes it possible to exclude this process and its group, to report what was killed, and to work in an image that has no procps.

Return type:

List[int]

Parameters:

pattern (str)

cadet.orchestrator.lifecycle.listening_socket_inodes(port)

Return the inodes of the sockets listening on port, from /proc/net.

/proc/net/tcp writes the local address as HEXIP:HEXPORT and the state as a two-digit hex code, of which 0A is LISTEN.

Return type:

Set[int]

Parameters:

port (int)

cadet.orchestrator.lifecycle.port_holders(port)

Return (pid, command line) for every process listening on port.

This is the information the original threw away: it passed the port to fuser -k and never learned whose socket it had just closed. Resolved from /proc alone - the listening socket’s inode, then the descriptors pointing at it - because the images this runs in have neither fuser nor ss, and a cleanup that silently cannot identify a holder is the failure mode this removes.

Return type:

List[Tuple[int, str]]

Parameters:

port (int)

cadet.orchestrator.lifecycle.describe_port_holders(port)

Return a readable “pid N (cmdline)” list for whoever holds port.

Return type:

str

Parameters:

port (int)

cadet.orchestrator.lifecycle.is_cadet_owned(pid, owned=(), patterns=())

True if pid was recorded by this orchestrator and still looks like it.

The record is the evidence of ownership, and a command line cannot replace it: every CADET server’s is cadet serve, so matching on it alone cannot distinguish a leftover of our own from a live process belonging to someone else’s run on the same machine - and killing the latter is what a pre-run cleanup must never do. Measured, before that was narrowed: two orchestrators in one container, and every run of the second failed with the first’s server SIGTERMed during model warm-up.

But a record is not sufficient either, because pids are reused. A stale record names a number, and by the time a later run reads it the kernel may have given that number to something else - including a role belonging to a run in another checkout, which is how this was found: the route equivalence test failed about one run in five with serve:server exited with code -15, while other streams were running their own suites on the same machine. Nothing in the record can notice that; the process can.

So ownership is the record and a command line that still matches one of patterns. With no patterns given the check is the record alone, which is what cadet down wants, where sweeping everything recorded is the point.

A process that looks like a role but is not recorded is reported by looks_like_a_role() and left alone.

Return type:

bool

Parameters:
  • pid (int)

  • owned (Iterable[int])

  • patterns (Sequence[str])

cadet.orchestrator.lifecycle.looks_like_a_role(pid, patterns)

True if pid’s command line is a CADET role or an app’s sim program.

Evidence for a report, not for a kill: see is_cadet_owned().

Return type:

bool

Parameters:
  • pid (int)

  • patterns (Sequence[str])

cadet.orchestrator.lifecycle.kill_pids(pids, log=<built-in function print>)

SIGTERM a pid’s process group, escalating to SIGKILL. Returns those killed.

Return type:

List[int]

Parameters:

pids (Iterable[int])

cadet.orchestrator.lifecycle.port_free(port, host='127.0.0.1')

True if host:port can be bound, i.e. nothing is listening there.

Return type:

bool

Parameters:
  • port (int)

  • host (str)

cadet.orchestrator.lifecycle.wait_for_ports_free(ports, timeout_s=5.0, log=<built-in function print>)

Wait until every port is actually free, after the holders were killed.

Killing a process does not release its listening socket synchronously, so a bind check run straight after the cleanup still sees the port in use and the run is refused for a port that is about to become free. The original papered over this with a fixed sleep between runs; this waits on the condition instead. Returns False if a port is still held when the time runs out, which means something CADET did not start is holding it.

Return type:

bool

Parameters:
  • ports (Sequence[int])

  • timeout_s (float)

cadet.orchestrator.lifecycle.kill_orphans(patterns, ports, log=<built-in function print>, owned=())

Kill the leftover processes CADET owns, and free only the ports they held.

Ported from the original’s kill_orphans, with its one indiscriminate step narrowed. The original ran pkill -f over its script names and then fuser -k over its port, which frees the port whoever is holding it. Here a port is freed only by killing a holder that is CADET’s own - recorded in owned, or matching one of patterns - so a run can never take down a process the experimenter started.

Every kill is best-effort: “nothing to kill” is the normal case and must not fail the run. Returns the holders left alone, as (port, pid, cmdline), which is what preflight reports when it then refuses the run.

Return type:

List[Tuple[int, int, str]]

Parameters:
  • patterns (Sequence[str])

  • ports (Sequence[int])

  • owned (Iterable[int])

cadet.orchestrator.lifecycle.print_final_client_report(client_log_path, log=<built-in function print>)

Echo the client’s final report, as the original did after every run.

Return type:

None

Parameters:

client_log_path (str)

cadet.orchestrator.lifecycle.client_output_failures(out_dir, config=None, log=<built-in function print>)

Return a reason per client that reported producing no output.

The verdict is the client’s, written beside its metrics: it holds the counts and its app declares what counts as output (see cadet.core.apps.AppPlugin.client_success()). A missing file is not a failure - a client that never got far enough to write one has already failed the run for a reason that is recorded.

Whether that verdict fails the run is experiment.require_output, off by default because the original judged a run by the client’s exit code alone. With it off the verdict is still logged: the information is the client’s own and worth having, it just does not change the outcome.

Return type:

List[str]

Parameters:

out_dir (str)

cadet.orchestrator.lifecycle.active_limit_s(config)

Return the wall-clock limit for the worker phase, in seconds.

experiment.max_active_s wins; otherwise the scenario’s own timeout plus ACTIVE_LIMIT_MARGIN_S, so the limit always sits outside the scenario’s own ending and only catches a run that failed to end at all.

Return type:

float

cadet.orchestrator.lifecycle.startup_limit_s(config, readiness_timeouts=())

Return the wall-clock limit for everything before the workers start.

experiment.max_startup_s wins; otherwise the sum of the readiness timeouts this run will wait on. The sum is the right default because it is already the phase’s bound, taken one step at a time: a startup that every individual wait would have allowed can never be refused by the total, and a phase that stalls between the waits still cannot run past it.

Return type:

float

Parameters:

readiness_timeouts (Sequence[float])

cadet.orchestrator.lifecycle.remaining_startup_s(deadline, step_timeout, what)

Return how long a readiness wait may take, given the startup deadline.

Raises StartupLimitExceeded if the budget is already spent, which is what makes the limit a bound on the phase rather than a note written afterwards.

Return type:

float

Parameters:
  • deadline (float)

  • step_timeout (float)

  • what (str)

cadet.orchestrator.lifecycle.end_rule(config)

Return (end_on, grace_s) for this config, with the schema’s defaults.

Return type:

Tuple[str, float]

class cadet.orchestrator.lifecycle.RunOutcome(codes, reason, detail='')

Bases: object

Why a run ended, and with what exit codes.

Parameters:
  • codes (List[int | None])

  • reason (str)

  • detail (str)

property ok: bool

True if the run ended the way its end_on rule says it should.

For client_report that means the workers exited cleanly. For a run ended by its sim hook the workers were stopped on purpose, so their exit codes are absent rather than zero; what disqualifies the run is a worker that had already failed.

as_dict()
Return type:

Dict[str, object]

cadet.orchestrator.lifecycle.wait_for_workers(workers, limit_s, guards=(), log=<built-in function print>, sim_hooks=(), end_on='client_report', grace_s=0.0)

Block until the run’s end_on rule fires, the limit passes, or a guard dies.

workers are the processes whose completion is the run under the client_report rule (clients and load generators); the original ran its single client in the foreground, which is that rule. guards are processes that must stay alive for the run to mean anything - the sim hooks and the servers - and sim_hooks is the subset whose clean exit can end a run, under the sim_hook_exit and first rules.

Without an explicit rule a clean sim-hook exit only got recorded, so a scenario that had finished left the client streaming into a world that no longer had an ego, until the run limit caught it minutes later. end_on makes the choice a config field instead of an accident of which process happened to exit first, and grace_s gives the workers a bounded chance to write their own report before they are stopped.

Return type:

RunOutcome

Parameters:
  • workers (Sequence[Tuple[str, object]])

  • limit_s (float)

  • guards (Sequence[Tuple[str, object]])

  • sim_hooks (Sequence[Tuple[str, object]])

  • end_on (str)

  • grace_s (float)

Run-state store for cadet status / cadet down.

A JSON record under <cwd>/.cadet/state.json tracks what an orchestrator run has started: a map of run_id -> {dir, procs, netem_interfaces}, with one pid file per launched process under <cwd>/.cadet/pids/<run_id>/<name>.pid. The pid files make ownership checkable: a pattern match on a command line cannot distinguish a CADET role from any other process listening on the same port, so cleanup needs direct evidence that CADET started something; a file written at launch is that evidence, and it persists even if the orchestrator dies mid-run. Used by cadet.orchestrator.runner (records each process at launch and clears on teardown) and by cadet.orchestrator.recovery.sweep() (reads the pid files and interfaces to power cadet down). The state root is fixed at <cwd>/.cadet so cadet status and cadet down need no config.

class cadet.orchestrator.state.StateStore(root=None)

Bases: object

A JSON file mapping run_id -> run record (processes started for that run).

Parameters:

root (str)

pid_dir(run_id)

Return the directory holding run_id’s pid files.

Return type:

str

Parameters:

run_id (str)

load()
Return type:

Dict[str, Any]

record(run_id, out_dir, procs)

Record (or replace) the process list for run_id.

Return type:

None

Parameters:
  • run_id (str)

  • out_dir (str)

  • procs (List[Dict[str, Any]])

add_proc(run_id, out_dir, name, pid)

Record one process as soon as it is started.

Called per launch rather than once per run: a run that is interrupted between its first and last process must still leave a complete record of what it started, which is the case the old end-of-startup record missed.

Return type:

None

Parameters:
  • run_id (str)

  • out_dir (str)

  • name (str)

  • pid (int | None)

record_netem(run_id, out_dir, interfaces)

Record the interfaces this run installed netem qdiscs on.

Return type:

None

Parameters:
  • run_id (str)

  • out_dir (str)

  • interfaces (List[str])

recorded_pids()

Return every pid in every pid file, whether or not it is still alive.

Return type:

List[int]

abandoned_pids()

Return the recorded pids a pre-run cleanup may kill.

The store lives in the working directory, so two orchestrators started in the same repository share it, and “recorded” is therefore not the same as “mine to kill”. A run’s processes are fair game when this process is the one that recorded them, or when the orchestrator that did is no longer alive - that run is abandoned and its processes are the orphans the cleanup exists for. A run another live orchestrator recorded is left alone: killing it was measured to fail every concurrent run with the server SIGTERMed during warm-up.

recorded_pids keeps its meaning for cadet down, where sweeping everything is the point.

Return type:

List[int]

pids_for(run_id)

Return the pids recorded for one run.

Return type:

List[int]

Parameters:

run_id (str)

records_for(run_id, directory=None)

Return (pid, start_ticks) for one run; start_ticks may be None.

None for a pid file written before the start time was recorded, or for one whose process had already gone when it was written. A caller that verifies the start time must treat None as “cannot verify” and decide what that means for it, rather than as “verified”.

Parameters:
  • run_id (str)

  • directory (str | None)

recorded_process_records()

Return (pid, start_ticks) for every recorded process.

recorded_netem_interfaces()

Return every interface any recorded run installed a netem qdisc on.

Return type:

List[str]

clear(run_id)

Drop run_id’s pid files, then remove it from the store (idempotent).

The pid files go first. They are what a cleanup reads, and the record entry is what says who owns them, so removing the entry first would leave pid files behind that no entry claims - and an unclaimed pid file is one a cleanup may kill. The reverse leftover, an entry with no pid files, is read by nothing.

Return type:

None

Parameters:

run_id (str)

clear_all()

Remove every recorded run.

Return type:

None

cadet.orchestrator.state.pid_alive(pid)

True if a process group / pid is still alive.

Return type:

bool

Parameters:

pid (int)

cadet.orchestrator.state.kill_pid(pid)

Terminate a process group by leader pid (SIGTERM), ignoring if gone.

Return type:

None

Parameters:

pid (int)