This is the full developer documentation for Peppy # Peppy Guide > A guide to start using Peppy This guide covers the installation of Peppy and introduces you to creating nodes so you can understand how the system operates. In a hurry? The [Quickstart](/quickstart/) gets a simulated bimanual robot running in your browser in three steps, without writing any code. Peppy runs on Ubuntu 24.04 or later and the Linux distributions built on it, on Debian 13 or later (x86_64/aarch64, tested on Ubuntu 24.04), on Raspberry Pi OS (64-bit, based on Debian 13 or later), and on macOS (Apple Silicon). Of the Raspberry Pi boards, it runs on the Raspberry Pi 5, the Pi 500 and the Compute Module 5. Other Linux distributions, Fedora and Arch Linux among them, are not supported, and neither are Ubuntu 22.04, Debian 12, 32-bit systems and the older Raspberry Pi boards: the installer stops on them before it changes anything. LLM-friendly versions of this documentation are available at [`/llms.txt`](/llms.txt) and [`/llms-full.txt`](/llms-full.txt). # Page not found > Check the URL or return to the Peppy documentation. # Actions > How to use actions in Peppy Actions are for **long-running tasks** that need feedback during execution and support cancellation. A client sends a goal to an action node, which can provide periodic feedback while working and delivers a final result upon completion. Use actions for tasks like navigation, arm movement, or any operation that runs over time and benefits from progress updates. (For a *continuous* bidirectional exchange with no defined end, an inner control loop rather than a discrete job, use a [pairing](/advanced_guides/pairing/#pairing-vs-actions) instead.) For the full map of mechanisms, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). A node can drive **multiple goals concurrently** for the same action. Each accepted goal yields its own `GoalContext` (owning that goal’s feedback stream, cancel signal, and result), so one server can route by a discriminator in the request (e.g. `arm_id`) and drive several independent resources in parallel. The framework routes each client’s cancel and result requests to the right goal by `goal_id`; deciding whether to accept a second concurrent goal is up to your goal handler. ## Action lifecycle [Section titled “Action lifecycle”](#action-lifecycle) An action consists of four communication channels built on top of services and topics: 1. **Goal** (service): the client sends a goal request; the server accepts or refuses it. 2. **Feedback** (topic): the server publishes progress updates while working on the goal. 3. **Cancel** (service): the client asks a live goal to stop, at any time; delivery is a signal the worker may honor or ignore. 4. **Result** (service): the client requests how the goal ended once the server finishes. ```plaintext Client Server │ │ │──── fire_goal (request) ──────────>│ │<─── goal ack (+ GoalResponse) ─────│ │ │ │<─── feedback ──────────────────────│ (repeated) │<─── feedback ──────────────────────│ │ │ │──── get_result (request) ─────────>│ │<─── ResultResponse ────────────────│ ``` ### How a goal ends [Section titled “How a goal ends”](#how-a-goal-ends) The server answers each goal with its acceptance or its refusal. An accepted goal then ends with one terminal status: | Status | What ends the goal | What the client gets | | ----------- | ----------------------------------------------------------------- | ------------------------------------------- | | `completed` | The worker calls `complete` | The result. The goal is a success. | | `failed` | The worker calls `fail` | A failure kind and a message, and no result | | `cancelled` | The worker calls `complete_cancelled` | The reason of the cancel and a result | | `abandoned` | The worker drops the goal without an end, or the producer is gone | Nothing | | `expired` | The goal ended, and the producer no longer keeps its result | Nothing | A refusal and a failed goal give a **failure kind** and a message for a person. The kind says why, so that the client can try again, plan again or call a person. A member gives a kind from a closed set: the kinds of peppy, and the kinds of its contract that the member lists (see [failure kinds](/advanced_guides/contract_implementation/#failure-kinds)). A native action, which no contract declares, gives the kinds of peppy only: | `failure_kind` | Meaning | | ---------------------- | --------------------------------------------------------- | | `attempt_failed` | The attempt gave no result | | `timeout` | The bound of the provider passed | | `precondition_failed` | A precondition failed | | `resource_unavailable` | A robot, limb or host is gone | | `rejected` | The provider refused the goal, and no other kind says why | The peppy daemon gives one kind of its own beside these, as a contract does: `busy`, other work runs on the daemon (a stack change, a node goal, a repository refresh or a benchmark), and the same request can succeed once that work ends (see [How a stack command ends](/guides/launch_files/#how-a-stack-command-ends)). The generated code of each action declares these kinds as a `FailureKind` enum and a `Failure` type (`kind`, `message`). The generated provider can give no other kind: in Rust a kind that the member does not declare is not a variant of the enum, so the node does not compile; in Python `Failure` raises `ValueError` for it before anything reaches the wire. The generated client parses each failure from the wire into the same type: a kind that the member does not declare is an error, never a failure of an unknown kind. The error of an undeclared kind keeps the message of the failure in its text. In Python, `Failure` also raises `TypeError` for a message that is not a `str`: give the text of an exception `error` with `Failure(kind, str(error))`. So no result reports a refusal or a failure in a field of its own, such as `success: false` and an error text. A field that gives the answer of a check, such as whether a pose is reachable, is data and stays in the result. `peppy node call` sends a goal to any action of a running instance from the command line and gives each of these ends an exit status of its own (see [Calling a running instance](/advanced_guides/calling_instances/)). ## Exposing an action [Section titled “Exposing an action”](#exposing-an-action) A node that handles action goals declares its actions under `interfaces.actions.exposes` in its `peppy.json5`. Each action defines a `name` and a [`description`](/reference/concepts/#descriptions) that tells its goal, its feedback and its result, and can define a `goal_service`, a `feedback_topic`, and a `result_service`: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "brain", tag: "v1", description: ["The brain of a robot with arms: it moves an arm to a position on request. It needs no device."], }, interfaces: { actions: { exposes: [ { name: "move_arm", description: "Move an arm to a position. The goal gives the arm and the position, each feedback gives the new position of the arm, and the result gives its final position.", goal_service: { request_message_format: { arm_id: "u16", desired_position: { $type: "array", $items: "i32", $length: 3 } } }, feedback_topic: { message_format: { new_position: { $type: "array", $items: "i32", $length: 3 } } }, result_service: { response_message_format: { final_position: { $type: "array", $items: "i32", $length: 3 } } } } ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "brain"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "brain", tag: "v1", description: ["The brain of a robot with arms: it moves an arm to a position on request. It needs no device."], }, interfaces: { actions: { exposes: [ { name: "move_arm", description: "Move an arm to a position. The goal gives the arm and the position, each feedback gives the new position of the arm, and the result gives its final position.", goal_service: { request_message_format: { arm_id: "u16", desired_position: { $type: "array", $items: "i32", $length: 3 } } }, feedback_topic: { message_format: { new_position: { $type: "array", $items: "i32", $length: 3 } } }, result_service: { response_message_format: { final_position: { $type: "array", $items: "i32", $length: 3 } } } } ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/brain"] }, } ``` The `goal_service` payloads and the `result_service` response are all optional: any of `goal_service.request_message_format`, `goal_service.response_message_format`, and `result_service.response_message_format` is omitted when the corresponding payload carries no fields. For example, a `calibrate` action can omit `goal_service.request_message_format` because it has no goal parameters, and a `result_service` that only signals completion can omit its `response_message_format` too. The `result_service` block itself is also optional: the goals of an action without it end with `complete`, `fail` or `complete_cancelled` all the same, with an empty result. The `result_service` never carries a user-defined request. A `get_result` call is correlated to its goal by the `goal_id` the framework assigns at `fire_goal`, so the only payload you declare on the result side is `response_message_format`, which the producer supplies through `complete` or `complete_cancelled`. Declaring a `result_service.request_message_format` is rejected when the config is parsed, since no generated API, wire message, or producer handler could ever read it. The `feedback_topic` block is optional: actions that don’t stream progress can omit it entirely. When you do declare `feedback_topic`, however, its `message_format` is required and cannot be empty: every feedback message must carry a non-empty payload, since empty payloads are reserved as the framework’s per-goal end-of-stream signal (see [Receiving feedback](#receiving-feedback)). A `feedback_topic` declared without a `message_format`, or with an empty one, is rejected when the config is parsed, identically for Rust and Python nodes. Feedback is live only: `feedback_topic` takes no `retention`. The server always publishes feedback with the `reliable` profile’s settings; a `qos_profile` key on `feedback_topic` is not read by the generated code. The client sets how many unread feedback messages its handle keeps with the feedback bound of `fire_goal` (see [Receiving feedback](#receiving-feedback)). ### Handling goals [Section titled “Handling goals”](#handling-goals) After running `peppy node sync`, the code generator creates a module for each exposed action under `peppygen::exposed_actions`. Use `ActionHandle::expose` to set up the action, then loop accepting goals. `handle_goal_next_request` returns the next *accepted* goal as a `GoalContext`; refused goals are answered and skipped for you, so the accept loop ends only when the goal stream closes (the node is shutting down). Spawn a worker per context so goals run concurrently; each context owns that goal’s feedback, cancel signal, and result, so nothing crosses between goals: * Python ```python import asyncio from peppygen import NodeBuilder from peppygen.exposed_actions import move_arm # Drive one accepted goal concurrently with any others already running. The # context owns this goal's feedback, cancel signal, and result. async def drive(ctx): # Feedback goes through this goal's context, not a shared slot. await ctx.publish_feedback([7, 31, 43]) # Deliver the result for this specific goal; the client's # get_result(handle) is routed back here by goal_id. await ctx.complete([98, 4, 26]) async def run_action(node_runner): action = await move_arm.ActionHandle.expose(node_runner) # The decider sets the concurrency policy: e.g. refuse a goal for a busy # arm_id. Refused goals are answered and skipped internally. def decide(request): print( f"goal from {request.instance_id}: arm_id={request.data.arm_id} " f"desired={request.data.desired_position}", flush=True, ) return move_arm.GoalDecision.accept() while True: ctx = await action.handle_goal_next_request(decide) if ctx is None: break # goal stream closed (node shutting down) asyncio.create_task(drive(ctx)) async def setup(parameters, node_runner): # Spawn the accept loop so setup returns and the node starts serving. return [asyncio.create_task(run_action(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use peppygen::exposed_actions::move_arm; use peppygen::{NodeBuilder, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let mut action = move_arm::ActionHandle::expose(&node_runner).await?; // Spawn the accept loop so this setup closure returns and the node // starts serving. The loop runs for the life of the node. tokio::spawn(async move { // Each call returns the next accepted goal; refused goals are // answered and skipped, so the loop ends only when the stream // closes (None) or errors. while let Ok(Some(ctx)) = action .handle_goal_next_request(|request| -> Result { println!( "goal from {}: arm_id={} desired={:?}", request.instance_id, request.data.arm_id, request.data.desired_position ); // The decider sets the concurrency policy: e.g. refuse a // goal for a busy `arm_id`. Ok(move_arm::GoalDecision::accept()) }) .await { // Drive this goal concurrently with any others already running. tokio::spawn(async move { // Feedback goes through this goal's context, not a shared slot. ctx.publish_feedback([7, 31, 43]).await.ok(); // Deliver the result for this specific goal; the client's // get_result(handle) is routed back here by goal_id. ctx.complete([98, 4, 26]).await.ok(); }); } }); Ok(()) }) } ``` `GoalDecision` controls admission. The decision and the failure of a refusal travel in a framework-owned envelope wrapped around the goal reply, so they never appear in your schema: `GoalResponse` contains exactly the fields declared in `goal_service.response_message_format`, and the framework never adds an `accepted` or error field to it. * `GoalDecision::accept()` (`GoalDecision.accept()` in Python) admits the goal, replies to the client, and yields a `GoalContext`. When the action declares a `response_message_format`, the constructor takes the declared response instead: `GoalDecision::accept(response)`. * `GoalDecision::refuse(kind, message)` (`GoalDecision.refuse(kind, message)` in Python) refuses it with a [failure kind](#how-a-goal-ends) of the action and a message: the client sees `accepted == false` and the failure on its handle, no context is created, and the accept loop transparently moves on to the next goal. A refusal carries no goal response. This is where you enforce per-resource concurrency limits. In Python, the constructor `GoalDecision(response, refusal)` takes an accept with the declared response, or a refusal with no response, and raises `ValueError` for any other pair. The server builds the decision of the decider again as a decision of its own action before it answers the goal, so a decider shared between two actions can give the decisions of either. A decider that raises, or that gives a decision that the serving action cannot send (a refusal with a kind that the action does not declare, an accept without the declared response), refuses the goal with the kind `attempt_failed` and the text of the error. Nothing of that decision reaches the wire, the client gets an answer, and the server keeps serving the next goal. In Rust, a decider that returns `Err` does the same: the goal is refused with `attempt_failed` and the text `the goal decider failed: `, and `handle_goal_next_request` keeps polling. A goal whose request bytes do not decode into the declared `request_message_format` (a field missing, a fixed-length array of the wrong length) never reaches your decider: the generated server refuses it with the kind `rejected` and the decode error as the message, and keeps serving the next goal. The client sent something this server’s shape does not admit, which is the client’s problem to learn about, not a reason to stop serving. The `GoalRequest` passed to the decider contains: * `instance_id`: the client instance that sent the goal. The producer is binding-agnostic; it doesn’t know which slot on the client this goal is heading to. * `core_node`: the core node of the caller. * `data`: the deserialized goal parameters (only present when `request_message_format` is defined). The `GoalContext` (`ctx`) is the only handle you need to drive the goal: * `ctx.request()`: the decoded `GoalRequest`. * `ctx.goal_id()`: this goal’s correlation id. * `ctx.sender()` (Rust): the process that sent the goal (see [Goals that end with their sender](#goals-that-end-with-their-sender)). * `ctx.publish_feedback(...)`: publish a feedback message on this goal’s stream. * `ctx.cancel_signal()` / `ctx.is_cancelled()` / `ctx.cancel_cause()`: observe cancellation and why it came (see below). In Python, `ctx.cancel_reason()` gives the reason of that cause in words. * `ctx.complete(...)`: end the goal with its result, a success. * `ctx.fail(kind, message)`: end the goal failed, with a failure kind of the action, a message, and no result. * `ctx.complete_cancelled(reason, ...)`: end the goal cancelled, for `reason`, with its result. The first of `complete`, `fail` and `complete_cancelled` ends the goal; later calls do nothing. A producer exposes its action once and serves any client that fires a goal at it. Starting the producer before or after the client is equally valid. To enforce a concurrency limit (say, one in-flight goal per arm), refuse a goal whose arm is already busy, and release the arm when the goal finishes. The decider and the per-goal workers share the busy set: * Python ```python # Arms currently driving a goal. Shared by the decider and the workers; # asyncio is single-threaded, so a plain set is safe here. busy: set[int] = set() async def drive(ctx): arm_id = ctx.request().data.arm_id await ctx.complete([98, 4, 26]) # Release the arm so future goals for it are accepted again. busy.discard(arm_id) def decide(request): arm_id = request.data.arm_id if arm_id in busy: # The failure rides back to the client in the goal ack. return move_arm.GoalDecision.refuse( move_arm.FailureKind.REJECTED, f"arm {arm_id} is already moving" ) busy.add(arm_id) return move_arm.GoalDecision.accept() while True: ctx = await action.handle_goal_next_request(decide) if ctx is None: break asyncio.create_task(drive(ctx)) ``` * Rust ```rust use std::collections::HashSet; use std::sync::{Arc, Mutex}; // Arms currently driving a goal. Shared by the decider and the workers. let busy: Arc>> = Arc::new(Mutex::new(HashSet::new())); while let Ok(Some(ctx)) = action .handle_goal_next_request({ let busy = Arc::clone(&busy); move |request| -> Result { // `HashSet::insert` returns false when the arm is already busy. if busy.lock().unwrap().insert(request.data.arm_id) { Ok(move_arm::GoalDecision::accept()) } else { // The failure rides back to the client in the goal ack. Ok(move_arm::GoalDecision::refuse( move_arm::FailureKind::Rejected, format!("arm {} is already moving", request.data.arm_id), )) } } }) .await { let busy = Arc::clone(&busy); tokio::spawn(async move { let arm_id = ctx.request().data.arm_id; ctx.complete([98, 4, 26]).await.ok(); // Release the arm so future goals for it are accepted again. busy.lock().unwrap().remove(&arm_id); }); } ``` ### Failing a goal [Section titled “Failing a goal”](#failing-a-goal) A worker that cannot reach the end of its goal ends it with `fail`: a failure kind of the action and a message. A failed goal gives no result, so the client never reads a result that only reports the failure: * Python ```python async def drive(ctx): plan = await plan_motion(ctx.request().data.desired_position) if plan is None: await ctx.fail(move_arm.FailureKind.ATTEMPT_FAILED, "no plan to the target") return await ctx.complete(plan.final_position) ``` * Rust ```rust tokio::spawn(async move { let Some(plan) = plan_motion(ctx.request().data.desired_position).await else { ctx.fail(move_arm::FailureKind::AttemptFailed, "no plan to the target") .await .ok(); return; }; ctx.complete(plan.final_position).await.ok(); }); ``` A contract can declare kinds of its own, such as `unreachable` for “No plan to the target”. The action of a node that implements the contract then gives them too: `FailureKind::Unreachable` in Rust, `FailureKind.UNREACHABLE` in Python. ### Handling cancellation [Section titled “Handling cancellation”](#handling-cancellation) A worker reacts to a cancel for **its** goal via `ctx.cancel_signal()`, which resolves when the goal receives its cancel signal: a cancel request of its caller arrives for that `goal_id`, or [its sender is gone](#goals-that-end-with-their-sender). `ctx.cancel_cause()` tells which: `CancelCause::Caller` or `CancelCause::SenderGone` in Rust (`CancelCause::reason()` gives a reason in words), `"caller"` or `"sender_gone"` in Python (`ctx.cancel_reason()` gives a reason in words). Pair the signal with the goal’s work and end the goal with `complete_cancelled`, its reason and its result: * Python ```python async def drive(ctx): cancel_task = asyncio.ensure_future(ctx.cancel_signal()) work_task = asyncio.ensure_future(run_arm(ctx.request().data.arm_id)) done, pending = await asyncio.wait( [cancel_task, work_task], return_when=asyncio.FIRST_COMPLETED ) for task in pending: task.cancel() if cancel_task in done: # This goal received its cancel signal; wind down and report it. await ctx.complete_cancelled( ctx.cancel_reason(), False, None, last_known_position ) else: outcome = work_task.result() for position in outcome.steps: await ctx.publish_feedback(position) await ctx.complete(outcome.final_position) ``` * Rust ```rust tokio::spawn(async move { tokio::select! { outcome = run_arm(ctx.request().data.arm_id) => { for position in outcome.steps { ctx.publish_feedback(position).await.ok(); } ctx.complete(outcome.final_position).await.ok(); } _ = ctx.cancel_signal() => { // This goal received its cancel signal; wind down and report it. let reason = ctx.cancel_cause().map_or("cancelled", |cause| cause.reason()); ctx.complete_cancelled(reason, false, None, last_known_position) .await .ok(); } } }); ``` Cancellation is **auto-acknowledged** by the framework: the client’s `cancel_goal` returns a typed `CancelState`: `Signalled` when a goal with that `goal_id` is in flight (the signal was delivered), `AlreadyTerminal` when it had already finished, or `Unknown`. `Signalled` means *delivered*, not *will stop*; a worker is free to ignore the signal and keep running. The worker decides the goal’s fate: calling `complete_cancelled` (or `complete`, or `fail`) is what a subsequent `get_result` returns. Whichever end runs first wins; the framework closes this goal’s feedback stream when the goal ends, so the client’s `on_next_feedback_message` loop ends cleanly. The clean close is not the only way a stream ends: if the producer instance dies mid-goal, the client’s loop ends with a producer-gone error instead (see [Receiving feedback](#receiving-feedback)). A goal’s cancel never affects other concurrent goals. A member that ends the goals of other clients, such as a `stop` that ends every running move, ends each of them with `complete_cancelled` and a reason of its own, such as `"stopped by a stop request"`. The clients of those goals read the reason with the `Cancelled` outcome. ### Goals that end with their sender [Section titled “Goals that end with their sender”](#goals-that-end-with-their-sender) A goal ends when the process that sent it is gone, so no robot goes on for a client that is gone. Each client process advertises its presence, and each goal carries the presence of its sender. The action watches the sender of each goal. When the sender is gone and the **sender grace** of the action passed, each goal of that sender that did not end receives its cancel signal, with the cause `SenderGone` (`"sender_gone"` in Python). The worker then ends the goal with `complete_cancelled`, as for any other cancel. The sender grace is zero unless the provider sets it. Set it when a client that stops and starts again within some time must find its goals still running, such as a robot initializer that attaches a robot to a simulation: * Python ```python action = await move_arm.ActionHandle.expose(node_runner) await action.set_sender_grace(5.0) # seconds ``` * Rust ```rust let action = move_arm::ActionHandle::expose(&node_runner).await?; action.set_sender_grace(std::time::Duration::from_secs(5)); ``` The sender grace applies to each sender that is found gone after the call. A sender is found gone when its presence disappears and two probes confirm it. ## Consuming an action [Section titled “Consuming an action”](#consuming-an-action) A node that sends goals declares what it consumes under `interfaces.actions.consumes`. Dependencies are declared in `manifest.depends_on` and referenced by `link_id` in the interface: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "controller", tag: "v1", description: ["A controller that sends the goals of its arm motions to a brain. It needs no device."], depends_on: { nodes: [ { name: "brain", tag: "v1", link_id: "brain" }, ] }, }, interfaces: { actions: { consumes: [ { link_id: "brain", // References depends_on.nodes[].link_id name: "move_arm", // Action name on that node }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "controller"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "controller", tag: "v1", description: ["A controller that sends the goals of its arm motions to a brain. It needs no device."], depends_on: { nodes: [ { name: "brain", tag: "v1", link_id: "brain" }, ] }, }, interfaces: { actions: { consumes: [ { link_id: "brain", // References depends_on.nodes[].link_id name: "move_arm", // Action name on that node }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/controller"] }, } ``` Note By default, the `node add` and `node sync` commands require every dependency node to already be in the node stack so the proper interfaces can be generated. When a dependency node is not present in the stack, pass `peppy node sync --include-repositories` (`-r`) to let the daemon fall back to the [repository cache](/advanced_guides/repositories/#syncing-against-repositories) for dependencies that aren’t in the stack. ### Firing a goal [Section titled “Firing a goal”](#firing-a-goal) The code generator creates a module for each consumed action under `peppygen::consumed_actions`. Use `fire_goal` to send a goal, then listen for feedback and request the result: * Python ```python import asyncio from peppygen import NodeBuilder from peppygen.consumed_actions.brain import move_arm async def run(node_runner): # `one`: the accessor returns the slot's sole producer directly. arm = move_arm.bound_producer(node_runner) request = move_arm.GoalRequest(arm_id=7, desired_position=[10, 20, 30]) action_handle = await move_arm.ActionHandle.fire_goal( node_runner, arm, # which bound instance executes the goal request, 5.0, # timeout (seconds) feedback_bound=None, # unread feedback messages kept; None: 1024 ) if action_handle.refusal is not None: print( f"goal refused kind={action_handle.refusal.kind.value} " f"message={action_handle.refusal.message}", flush=True, ) async def setup(parameters, node_runner): return [asyncio.create_task(run(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use peppygen::consumed_actions::brain::move_arm; use peppygen::{DEFAULT_FEEDBACK_BOUND, NodeBuilder, Parameters, Result}; use std::time::Duration; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // `one`: the accessor returns the slot's sole producer directly. let arm = move_arm::bound_producer(&node_runner); let request = move_arm::GoalRequest { arm_id: 7, desired_position: [10, 20, 30], }; let action_handle = move_arm::ActionHandle::fire_goal( &node_runner, arm, // which bound instance executes the goal Duration::from_secs(5), // timeout request, DEFAULT_FEEDBACK_BOUND, // unread feedback messages kept: 1024 ) .await?; if let Some(refusal) = &action_handle.refusal { println!("goal refused kind={} message={}", refusal.kind, refusal.message); } Ok(()) }) } ``` `fire_goal` requires the caller to pass one explicit target for every [cardinality](/advanced_guides/topics/#dependency-cardinality), including the default `one`; obtain it from the slot’s cardinality-typed accessor (the singular, infallible `bound_producer()` on a `one` slot, the same name returning an `Option` on a `zero_or_one` slot, where a vacant slot has no target to fire at and the caller branches on that first, and `bound_producers()` on the multi cardinalities, never empty for `one_or_more`). The target must belong to the slot’s own set; anything else fails with a runtime error before the goal reaches the wire. Firing a goal at every bound producer of a multi-cardinality slot is a plain loop over `bound_producers()`; each returned handle drives its own feedback stream, cancel, and result, exactly as a single goal does. `fire_goal` returns an `ActionHandle`. Its `accepted` flag and its `refusal` are decoded from the framework goal ack: `refusal` is the `Failure` of a refused goal (`kind`, a [failure kind](#how-a-goal-ends) of the action, and `message`), and absent for an accepted goal. When the action declares a `response_message_format`, its `data` field holds the declared goal response of an accepted goal; a refused goal has none. The handle retains the selected target: goal submission, feedback, result retrieval, and cancellation all stay pinned to that same producer; no stage uses a wildcard, fallback producer, discovery, or automatic retargeting. The handle is what you use for subsequent feedback, result, and cancel calls. You can fire multiple goals concurrently, and each returns its own handle, so the server can drive them in parallel. ### Receiving feedback [Section titled “Receiving feedback”](#receiving-feedback) Use `on_next_feedback_message` on the handle to receive feedback. The idiomatic pattern is a loop that drains feedback until a terminal error ends the stream: * Python ```python import peppylib while True: try: feedback = await action_handle.on_next_feedback_message() print(f"new_position={feedback.new_position}", flush=True) except ConnectionError: break # producer instance died; get_result yields ABANDONED except peppylib.FeedbackOverflowError: break # this caller fell behind its bound; the handle cancelled the goal except Exception: break # the goal ended ``` * Rust ```rust use peppygen::Error; loop { match action_handle.on_next_feedback_message().await { Ok(feedback) => println!("new_position={:?}", feedback.new_position), Err(Error::ActionFeedbackProducerGone { .. }) => { break; // producer instance died; get_result yields Abandoned } Err(Error::ActionFeedbackOverflow { bound, .. }) => { // This caller fell behind by more than `bound` unread messages; // the handle cancelled the goal. println!("lost feedback beyond {bound} unread messages"); break; } Err(_) => break, // the goal ended } } ``` Feedback the handle has not read yet waits in the handle’s buffer. The buffer keeps **every** message until the handle reads it, up to the feedback bound that you pass to `fire_goal`: a number of unread messages, `DEFAULT_FEEDBACK_BOUND` (1024) in Rust, or `feedback_bound=None` for the same default in Python. The end of the stream is always kept. Receiving never waits for the handle: feedback read late, or never, does not hold up `get_result` or any other message to the node. A handle that falls behind by more unread messages than its bound **overflows**: the buffer drops the unread messages and takes no message after them. A handle that reads the feedback follows the goal, so from its first read on the overflow cancels the goal at once, and the next read gives the loss as an error, `ActionFeedbackOverflow` (`peppylib.FeedbackOverflowError` in Python): a client never misses a feedback message without notice. A handle that never reads the feedback keeps its goal: its buffer stops at the bound, and `get_result` gives the outcome as usual. Set a bound that holds every message your client can fall behind by, or read the feedback as it arrives. Each goal has its own feedback stream, addressed by `goal_id`, so feedback for one goal never reaches another handle, even when several goals run concurrently on the same server. Three terminal errors end the drain loop: * **Clean close** (`ActionFeedbackChannelClosed`; `RuntimeError` in Python): the server closed this goal’s stream: its worker ended the goal (`complete`, `fail` or `complete_cancelled`) or abandoned it without an end (an early return or a panic). Call `get_result` to learn the outcome. * **Producer gone** (`ActionFeedbackProducerGone`; `ConnectionError` in Python): the producer instance this goal is pinned to died without closing the stream (process killed, host lost). Feedback already in flight (including a clean close that did make it out) is drained first, so a graceful shutdown never surfaces as producer-gone. After this error, `get_result` resolves to the `Abandoned` outcome. * **Overflow** (`ActionFeedbackOverflow`; `peppylib.FeedbackOverflowError` in Python): this caller fell behind its bound, and the handle cancelled the goal. `get_result` then gives the outcome the worker ended the goal with, usually `Cancelled`. Either way, a client draining feedback always terminates rather than hanging. In Python, catch `ConnectionError` and `peppylib.FeedbackOverflowError` before the generic handler when you want to tell them from a clean close; a bare `except Exception` treats all three as end-of-stream. Note Producer death is confirmed via liveliness probes, so a transport outage (e.g. a router restart) that outlasts the confirmation window can surface as producer-gone even though the process survived. The `Abandoned` outcome remains the correct consumer-side interpretation: the goal’s results are unreachable. ### Getting the result [Section titled “Getting the result”](#getting-the-result) Use `get_result` on the handle to request the final result. The call is routed to this goal by `goal_id` and **parks until the goal reaches a definitive terminal state**, then returns a typed outcome: * Python ```python result = await action_handle.get_result(5.0) if result.status == move_arm.ResultStatus.COMPLETED: print(f"completed at {result.data.final_position}", flush=True) elif result.status == move_arm.ResultStatus.FAILED: print( f"failed: kind={result.failure.kind.value} message={result.failure.message}", flush=True, ) elif result.status == move_arm.ResultStatus.CANCELLED: print( f"cancelled ({result.cancel_reason}) at {result.data.final_position}", flush=True, ) elif result.status == move_arm.ResultStatus.ABANDONED: print("the worker abandoned the goal without producing a result", flush=True) elif result.status == move_arm.ResultStatus.EXPIRED: print("the result expired before it was fetched", flush=True) ``` * Rust ```rust let result = action_handle.get_result(Duration::from_secs(5)).await?; match result.outcome { move_arm::ResultOutcome::Completed(data) => { println!("completed at {:?}", data.final_position) } move_arm::ResultOutcome::Failed(failure) => { println!("failed: kind={} message={}", failure.kind, failure.message) } move_arm::ResultOutcome::Cancelled { reason, data } => { println!("cancelled ({reason}) at {:?}", data.final_position) } move_arm::ResultOutcome::Abandoned => { println!("the worker abandoned the goal without producing a result") } move_arm::ResultOutcome::Expired => { println!("the result expired before it was fetched") } } ``` A poll on a still-running goal **parks** until the goal reaches a terminal state, then returns a typed outcome, so you can call `get_result` whenever you like; a forwarding/relaying node does not have to time its poll to the worker’s lifecycle. The returned outcome (a Rust `ResultOutcome` enum, or `result.status` with `result.data`, `result.failure` and `result.cancel_reason` in Python) tells you exactly what happened: * **`Completed`**: the worker delivered a result via `complete`; the goal is a success and the payload is in `data`. * **`Failed`**: the worker ended the goal via `fail`; the `Failure` gives the kind and the message, and there is no result. * **`Cancelled`**: the worker ended the goal via `complete_cancelled`; the outcome gives the `reason` (`cancel_reason` in Python), and the payload is in `data`. * **`Abandoned`**: the worker dropped the goal without ever delivering a result (an early return or a panic), or the producer instance itself died mid-goal. A poll on a goal whose producer is confirmed gone resolves to `Abandoned` instead of parking forever. * **`Expired`**: the goal finished, but its result was retained only for a bounded window (30 s by default) that has since elapsed, or the result was already evicted. A terminal result stays fetchable for that retention window, and you can fetch it more than once within it, which makes relaying it reliable. If the poll outlives the caller’s own `timeout`, you get a normal timeout error like any other request. ### Cancelling a goal [Section titled “Cancelling a goal”](#cancelling-a-goal) Use `cancel_goal` on the handle to request cancellation of that specific goal. It returns a typed `CancelState`: * Python ```python cancel_response = await action_handle.cancel_goal(5.0) if cancel_response.state == move_arm.CancelState.SIGNALLED: print("cancel delivered to a live goal", flush=True) elif cancel_response.state == move_arm.CancelState.ALREADY_TERMINAL: print("goal had already finished", flush=True) elif cancel_response.state == move_arm.CancelState.UNKNOWN: print("no goal with that id is known", flush=True) ``` * Rust ```rust let cancel_response = action_handle.cancel_goal(Duration::from_secs(5)).await?; match cancel_response.state { move_arm::CancelState::Signalled => println!("cancel delivered to a live goal"), move_arm::CancelState::AlreadyTerminal => println!("goal had already finished"), move_arm::CancelState::Unknown => println!("no goal with that id is known"), } ``` The `CancelState` reports what the cancel found: * **`Signalled`**: a live goal received the cancel signal. *Delivered*, not necessarily *will stop*: the worker may ignore it. * **`AlreadyTerminal`**: the goal had already reached a terminal state, so there was nothing to cancel. This answer survives result eviction: a bounded tombstone set remembers terminal goals after their results are dropped. * **`Unknown`**: no goal with that `goal_id` is known (it never existed, or its tombstone has aged out of the bounded set). The cancel targets only this goal; other concurrent goals are unaffected. To learn the goal’s final state, call `get_result`: if the worker reacted with `complete_cancelled` you get a `Cancelled` outcome with its reason; if it ignored the cancel and finished normally you get `Completed`. ## Bindings and routing [Section titled “Bindings and routing”](#bindings-and-routing) Routing for actions uses the same consumer-side model as topics and services. A binding `KEY: VALUE` creates a private channel from producer instance `VALUE` to one of the client’s declared slots; the action server itself is binding-agnostic. An action slot resolves through its bindings: the generated `fire_goal` checks the caller-selected target against the slot’s bound set and pins the goal, cancel, result, and feedback channels to that one producer’s full `(core_node, instance_id)` wire address. How many producers may be bound to the slot is its declared [cardinality](/advanced_guides/topics/#dependency-cardinality) (`one` when omitted); because the whole goal cycle needs exactly one server, every fired goal selects exactly one member of the bound set, and a `one` / `one_or_more` slot with no binding is rejected at launch validation, before anything spawns. In a launcher / stack config: ```json5 { source: { name: "consumer:v1" }, instances: [{ instance_id: "my_consumer", links: { brain: "left-arm-1" }, }], } ``` or, when launching a single node during development: ```sh peppy node run --link brain@left-arm-1 consumer:v1 ``` ### Worked example: `openarm01_backbone` [Section titled “Worked example: openarm01_backbone”](#worked-example-openarm01_backbone) A client that wires two depth cameras to two dedicated slots: openarm01_backbone/peppy.json5 ```json5 { manifest: { name: "openarm01_backbone", tag: "v1", description: ["The backbone of an OpenArm with a depth camera on each wrist."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "wrist_left_camera" }, { name: "depth_camera", tag: "v1", link_id: "wrist_right_camera" }, ], }, }, // ... } ``` peppy_launcher.json5 ```json5 { description: ["An OpenArm backbone with a depth camera on each wrist. It needs the arm and the two cameras."], deployments: [ { source: { name: "depth_camera:v1" }, instances: [ { instance_id: "left_cam" }, { instance_id: "right_cam" }, ]}, { source: { name: "openarm01_backbone:v1" }, instances: [ { instance_id: "backbone_inst_1", links: { wrist_left_camera: "left_cam", wrist_right_camera: "right_cam", }}, ]}, ], } ``` Three contract statements follow from this manifest: 1. `fire_goal` on the nested `wrist_left_camera.` (Python) / `wrist_left_camera::` (Rust) module reaches `left_cam`. 2. `fire_goal` on the nested `wrist_right_camera.` (Python) / `wrist_right_camera::` (Rust) module reaches `right_cam`. 3. If the `wrist_right_camera` binding line were removed, validation would reject the launch (a declared slot has a binding, or a written vacancy where its cardinality is `zero_or_one`): a goal cycle has no wildcard fallback. ### Why an explicit single target? [Section titled “Why an explicit single target?”](#why-an-explicit-single-target) Without a pinned target, a goal request would be broadcast to every matching producer and each one would execute the goal concurrently, which for state-changing actions (motor commands, file writes, payment dispatches) is a real-world hazard. Requiring every `fire_goal` to name one member of the slot’s validated bound set removes that hazard by construction: the selected target carries the producer’s full `(core_node, instance_id)` wire address, so the goal addresses exactly one producer with no probe round-trip, the goal, cancel, result, and feedback channels all stay on that producer for the whole goal cycle, and an out-of-set target (never checked by plan-time binding validation) is rejected before it reaches the wire. If the selected producer dies mid-cycle, the failure surfaces per stage: `fire_goal` and `cancel_goal` report `ServiceUnreachable`, `get_result` reports `ActionResultUnreachable` (or resolves the goal `Abandoned` once the producer is confirmed gone), and the feedback stream ends with `ActionFeedbackProducerGone`. The caller can retry once the producer is back: a producer dying never changes the bound set. On a `one_or_more` or `zero_or_more` slot a [copy joining or leaving](/guides/launch_files/#copies) does, so read `bound_producers()` at the point of use. ### Validator rules [Section titled “Validator rules”](#validator-rules) The launcher validator runs these checks before the stack starts: 1. **Every `KEY` must name a declared slot, and every declared slot must resolve.** A binding whose `KEY` matches no `depends_on` `link_id` is rejected; there are no free-form keys. A declared `one` / `zero_or_one` / `one_or_more` slot with no `links` entry fails the launch before anything is spawned; a `zero_or_more` slot with no entry resolves to the empty set, and so does a `zero_or_one` slot the deployment declared vacant. 2. **The value’s shape must match the slot’s cardinality.** A scalar slot (`one` or `zero_or_one`) takes a scalar, a multi slot takes an array, an empty array meets only `zero_or_more`, and duplicate targets within one slot are rejected. Repeated `--link KEY@…` flags accumulate on a multi-slot and are a hard error on a scalar slot. 3. **Every target must satisfy the slot, checked per bound instance.** A target `instance_id` that deploys a different node than the slot expects (or one that does not implement the requested contract) is rejected. 4. **Stack-wide `instance_id` uniqueness.** Every `instance_id` must be unique across the entire stack, not just within a `(node_name, node_tag)` group. The `--link` syntax names producers by `instance_id`, so a duplicate would make the binding ambiguous. 5. **Bindings are stamped with the producer’s `core_node`.** The wire addresses producers by the full `(core_node, instance_id)` pair; the validator stamps each target producer instance’s resolved `core_node` into the binding (equal to the launching daemon’s only in the single-machine case), preserving plan order, so generated calls address exactly the selected producer and never match on `instance_id` alone. Plan order is the launcher’s array order, then the members each joined copy adds, in the order the copies joined (see [validator rule 5](/advanced_guides/topics/#validator-rules)). ## Concurrent processing [Section titled “Concurrent processing”](#concurrent-processing) A single action server can drive many goals at once. The accept loop only waits for the next goal; each accepted goal runs in its own spawned task with its own `GoalContext`. The framework routes every cancel and result request to the right goal by `goal_id`, and each goal has its own feedback stream, so goals never interfere with one another. This makes the “one server, many resources” pattern natural: include a discriminator in the goal request (e.g. `arm_id` or `device_id`) and route to a per-resource worker. Your goal handler is responsible for the concurrency policy: accept goals to run them in parallel, or refuse a goal (with `GoalDecision::refuse(kind, message)`) when its target resource is already busy. A goal that is not accepted yields no `GoalContext` and cannot be cancelled or ended. # The senders of the calls to a daemon > How a daemon knows the true sender of each call that it receives, what the signature of a call proves and what it does not, and how the machines of a federation prove their calls to each other A daemon reads the sender of each call to its raw services, its raw actions and its daemon interfaces (`robot_leases:v1` and `robot_membership:v1`). It checks the [scopes](/advanced_guides/fleet/#scopes-and-raw-calls) of the daemon targets, the raw-call rules and the rights of the command line against the sender that the call proves, not against the instance id and the machine that the call gives. A node cannot call a daemon under the id of another client, such as `peppy-cli` or a lease holder. ## Keys [Section titled “Keys”](#keys) Each client of a daemon signs each of its calls to a daemon with an Ed25519 key: | Client | Key | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | An instance | A key pair for each start of the instance. The daemon writes it to a key file of that start and names the file in the runtime configuration of the instance. The file goes when the process of that start ends, and a restart gets a new key. | | The command line | The key pair in `credentials/command_line.key` of the data root, which the daemon makes at its first boot and keeps. The daemon state names the file. | | A daemon | A key pair for each boot, which the daemon keeps in memory. | Only the user of the daemon reads the `credentials` directory of the data root and each file in it (modes 0700 and 0600). The generated code, `peppylib` for Rust and Python, the codec API and the MCP server of peppy sign through the session that the runtime configuration of the instance opens. The `peppy` commands sign with the key of the command line. Topics, the calls between nodes and the calls of a daemon to a node carry no signature. A signature covers the namespace of the session, the key expression of the call (which holds its sender and its receiver), the kind of the call, its payload, a timestamp and a nonce. It rides on the attachment of the query, so a node that calls a daemon needs nothing more than its session. ## What the daemon refuses [Section titled “What the daemon refuses”](#what-the-daemon-refuses) The daemon verifies each call before it reads the sender, and refuses with the failure kind `rejected`: * A call with no signature. A node that an earlier peppy built does not sign its calls: build it again with this peppy. * A signature that does not verify with the key of the sender that the call gives, such as a node that calls under the id of `peppy-cli` or of another instance. * A sender with no key on the daemon, such as an instance whose process does not run. * A timestamp more than 30 seconds away from the clock of the daemon. * A nonce that a call of the last 30 seconds carried: a replayed call. * A call of another machine with no machine proof, or with one that does not verify (see [Machines of a federation](#machines-of-a-federation)). The message of the refusal says which check failed. A probe of a service, which tells a client that the service is there, needs no signature. A daemon takes the cancel of a goal only from the sender of the goal. A goal id travels on the wire, so without this check any client with a key could end the goals of another client, such as the `lease` goal of a lease holder. ## Limits [Section titled “Limits”](#limits) * A process that can read the key file of another client can act as that client. A native node runs as the same Unix user as the daemon and the command line, so it can read their key files and act as any client of its machine. A container node does not see the data root (see [What a container node sees of the data root](/advanced_guides/containers/#what-a-container-node-sees-of-the-data-root)), and reads its own key file alone. * The replies of a daemon carry no signature: a program on the network can give a false reply to a client. * The leases and the halt stay cooperative: a robot node does not check a lease, and the signatures do not change who may send a command to a node. ## Machines of a federation [Section titled “Machines of a federation”](#machines-of-a-federation) A machine proves its calls to the daemons of the other machines of a [federation](/advanced_guides/federation/) with its machine certificate: a certificate of a CA and the private key of that certificate. * An enrolled machine uses its platform certificate (`conf/peer/peer.crt` with the issuer chain `chain.crt` and the key `peer.key`), and checks the other machines against the CA of its project (`ca.crt`). * A machine of a federation that the operator forms, through an operator-run router or a router configuration that the operator pins, uses the certificate that the operator gives in [`machine_certificate`](/advanced_guides/daemon_config/#machine_certificate-the-certificate-of-the-machine). Its common name is the core node of the machine. At each boot, the daemon signs a boot statement with the key of its machine certificate: the namespace, the core node, the instance id of the boot and the public key of the boot. With the key of its boot, it endorses the key of the command line and the key of each instance that it starts. A call to the daemon of another machine carries the boot statement, the certificate chain and the endorsement. The daemon that receives it checks the chain against its own CA, the boot statement and the endorsement, and that they name its namespace and the core node and the instance id that the call gives. * A daemon with no machine certificate takes no call of another machine, and the daemons of the other machines refuse its calls. * The coordinator of a launch takes a call of an instance of another machine as that instance only when the launch places the instance on that machine. * A platform certificate names a peer of the project, not a core node, so a machine of the project can give the core node name of another machine of the project. A peer that the platform removes keeps the trust of the other daemons until its certificate expires. * The machines of a federation keep their wall clocks within 30 seconds of each other. # Calling a running instance > Call any service or action of a running instance, print the messages of its topics, and show its interfaces from the command line, with no new code Three commands reach the members of a running instance from the command line, with no code of your own: * `peppy node describe ` shows the interfaces of the instance with their descriptions and their message formats. * `peppy node call ` calls one service or action and prints how the call ends. * `peppy node echo ` prints the messages of one topic until Ctrl+C. People at a robot and scripts use the same commands. Example: a person sends an arm to its home position with `peppy node call`, and a CI script checks the exit status of the same command. ## What the commands read [Section titled “What the commands read”](#what-the-commands-read) The commands read the pinned documents of the instance, never the code of its node. The daemon that runs the instance gives them: * The manifest of the node, as the stack holds it. * Each contract document and each pairing document that the manifest names, at the bytes that the node’s code was generated from. `peppy node add` reads each of these documents once and the daemon keeps their bytes with the node. An edit of a document file after the add changes nothing that the commands read; to use the edited document, add the node again. Each document comes with its name, its tag and the SHA-256 of its content. So the commands reach every member that the pinned manifest declares: * The members of the contracts that the node implements (`manifest.implements`). * The members that the node declares itself, such as `set_depth_gain` of a RealSense camera. These are the entries of `interfaces` with no `link_id`. * The topics that the node emits through its [pairing](/advanced_guides/pairing/) slots. Each message format is the one of the manifest. A manifest can [refine](/advanced_guides/contract_implementation/) the format of a contract, for example to give an array a fixed length, and the commands use the refined format. The `--core-node` flag selects the daemon that runs the instance. Without it, the commands ask the local daemon. ## Naming a member [Section titled “Naming a member”](#naming-a-member) Each member has a full name, which is its path in the code generated for its node: | Member | Full name | | -------------------------------------------------- | ------------------------------------------------------- | | A member of a contract that the node implements | `.`, for example `motion.move_arm` | | A topic that the node emits through a pairing slot | `.`, for example `controller.joint_states` | | A member of the node’s own | ``, for example `set_depth_gain` | `` is the `link_id` of the slot in the manifest of the node. The slots of a manifest have distinct names, so a node that implements two tags of one contract, or holds one pairing in two slots, gives each member a full name for each slot. The name of a member without its slot is enough when no member has that full name and one member of the instance has that name: `peppy node call arm_inst move_arm`. `peppy node call` looks among the services and the actions, and `peppy node echo` among the topics. A name that no member has, or that two members have, is refused, and the error lists the full names that it could mean. A service and an action can have one full name. `peppy node call --kind service` or `--kind action` then selects one of them. ## `peppy node describe` [Section titled “peppy node describe”](#peppy-node-describe) ```sh peppy node describe arm_inst ``` ```text Instance arm_inst of arm:v1 on core node robot-7 Manifest sha256: 3629…a5a7 An arm with three joints on a bench. It needs the arm on a USB port of its machine. Contract limb_motion:v1 through slot `motion` (sha256: d2d4…e307) The motions of the arms and the grippers of a robot. Each joint position is in radians. service motion.check_move Check that the arm can reach the joint positions, with no motion. request: { joints: { $type: "array", $items: "f64", $description: "The target position of each joint." } } response: { reachable: "bool" } failure kind unreachable: No plan to the target action motion.move_to Move the arm to the joint positions. The goal gives the positions, each feedback gives the progress from 0 to 1, and the result says if the arm reached them. goal: { joints: { $type: "array", $items: "f64", $length: 3 } } goal_response: none feedback: { progress: "f64" } result: { reached: "bool" } failure kind unreachable: No plan to the target Own members of arm:v1 service set_gain Set the gain of the joint controllers, and give the gain that the arm applied. request: { value: "i32" } response: { current_value: "i32" } Pairing arm_link:v1 through slot `controller`, role `arm` (sha256: dbfa…d07c) The link between one controller and one arm: the controller commands the joints of the arm, and the arm gives back the state of its joints. topic controller.joint_states (qos: SensorData) The measured position of each joint of the arm. message: { positions: { $type: "array", $items: "f64" } } ``` The [description](/reference/concepts/#descriptions) of the node follows the first lines, and the description of each contract and pairing follows its heading, one paragraph at a time. Each member shows the full name that `call` and `echo` take, its description, its message formats with the `$description` of their fields, and the [failure kinds](/advanced_guides/actions/#how-a-goal-ends) of its contract that it lists. Every member can also give the failure kinds of peppy, which the listing does not repeat. The descriptions wrap to the width of the terminal. `--json` prints the same as one JSON document, for a program: the node and each contract and pairing have `description`, the list of their paragraphs, and each member has `description`. ## `peppy node call` [Section titled “peppy node call”](#peppy-node-call) ```sh peppy node call arm_inst move_to --set 'joints=[0.1, 0.2, 0.3]' ``` ### The message [Section titled “The message”](#the-message) Three flags give the request of a service or the goal of an action: * `--args ` gives the whole message. * `--set =` gives one field. A field whose JSON value is a string (a string, bytes, a time, a 64-bit integer) takes the value as written. Any other field takes the value as JSON5. * `--file =@` gives one field from a file: the text of the file for a string field, its bytes for a bytes field. A directory, `@`, gives a list of `{ path, content }`, one item for each file under the directory, with paths relative to it, in the order of the paths. The field must be a list of objects with a string `path` and a string or bytes `content`. `--set` and `--file` name a field by its path from the root of the message, with `.` between the names: `--set pose.position.x=0.2`. They complete the message that `--args` gives. A field that two flags name, or a field in an object that another flag gives, is refused. The values follow the JSON of the MCP server: a 64-bit integer is a decimal string, bytes are base64, and a time is an RFC 3339 string. So `--set count=18446744073709551615` and `--set stamp=2026-10-25T10:00:00Z` take the value as written. Message formats have no map type. A contract that carries a map, such as the roles of a run, declares a string field that holds JSON5 text, and `--set roles='{ arm: "openarm" }'` gives that text as written. The command checks the message against the format of the pinned manifest before it sends it, and names the field that does not fit. ### The output [Section titled “The output”](#the-output) The command sends the call itself, as a client with no node, with the sender identity of its process. It prints JSON lines on standard output, and its log lines on standard error: * A `{"feedback": …}` line for each feedback message of a goal. * Then one line that says how the call ended, with an `outcome`: | `outcome` | Fields | Exit status | | ----------- | ---------------------------------------------- | ----------- | | `completed` | `response` of a service, or `result` of a goal | 0 | | `refused` | `failure_kind`, `message` | 3 | | `failed` | `failure_kind`, `message` | 4 | | `cancelled` | `reason`, `result` | 5 | | `abandoned` | `message` | 6 | | `expired` | `message` | 7 | ```text {"feedback":{"progress":0.5}} {"feedback":{"progress":1.0}} {"outcome":"completed","result":{"reached":true}} ``` An error reply of a service is a refusal by its provider: `outcome` is `refused`, and the command exits with 3. A response that lists errors, such as that of a checker, is a response: the command exits with 0, and the caller reads the errors in the output. A provider that gives a failure kind that the contract of the member does not list breaks its contract. The command writes a warning on standard error, and reports the refusal or the failure as the provider gave it, with its exit status. An error of the command itself, such as an instance that the daemon does not run, a member that the instance does not have, or a message that does not fit its format, prints no line on standard output and exits with 1. A command line that does not parse exits with 2. ### Ctrl+C [Section titled “Ctrl+C”](#ctrlc) The first Ctrl+C during a goal sends the provider a cancel, and the command follows the goal to its end. A goal that the cancel ends gives `cancelled` and the exit status 5, also for a member whose normal end is a cancel, such as `record_episode`, which saves its episode at the cancel: the caller reads that status as the end that it asked for. A goal that ended before the cancel reached it keeps its end. A second Ctrl+C exits at once, with 130. The process of the command ends, so the provider cancels the goal of its sender, which is gone. A command whose process ends for another reason, for example when its terminal closes, cancels its goal the same way. A service cannot be cancelled: a Ctrl+C while the command waits for a response exits at once, with 130. ### Members that move a robot [Section titled “Members that move a robot”](#members-that-move-a-robot) For a member with the mark `moves_robot` (see [Marks](/advanced_guides/contract_implementation/#marks)), the command keeps the fleet rules of the stack, as an MCP server does (see [Robot leases and the halt](/advanced_guides/fleet/)). It has no scope: it acts for the person or the program that runs it. * Before it sends the call, the command asks `check_move` of the daemon of the coordinator of the stack, on the instance that it calls. When the daemon refuses the move, the command sends nothing to the provider, prints a `refused` line with the `failure_kind` (`halted`, `leased` or `not_leased`) and the `message` of the daemon, and exits with 3. For example, a person at the robot who sends an arm home gets a refusal while a run leases that robot. * While its goal on such a member runs, the command follows the changes of the fleet. At a halt it sends the provider a cancel, as at a first Ctrl+C, and follows the goal to its end. * With `--core-node`, the command reads the stack listing of the daemon that it targets, and asks the daemon of the coordinator of its launch. ## `peppy node echo` [Section titled “peppy node echo”](#peppy-node-echo) ```sh peppy node echo arm_inst limb_states ``` ```text {"joints":[0.1,0.2,0.3]} {"joints":[0.11,0.2,0.3]} ``` The command prints each message of the topic as one JSON object on a line, until Ctrl+C, and exits with 0. It subscribes to the topic by its key, as a client with no node, so it needs no slot that a launcher binds: * A topic of a contract or of the node’s own comes from the instance alone. A topic that keeps its newest messages for late subscribers (`retention`) gives them first. * A topic of a pairing comes as an observer of every pair that the slot of the instance holds. A slot that holds no pair publishes nothing, so the command prints nothing until the instance pairs. A message that does not fit the format of the pinned manifest is a warning on standard error. The command also ends with 0 when the program that reads its output closes it, for example `peppy node echo arm_inst limb_states | head -n 5`. The command never slows the instance down. When it prints slower than the topic publishes, for example on a paused terminal or behind a slow reader of its output, it skips the oldest messages that it did not print yet. ## Exit statuses of the other commands [Section titled “Exit statuses of the other commands”](#exit-statuses-of-the-other-commands) The commands that send the daemon a goal give an exit status for each end of the goal, by the same rules: `peppy stack launch`, `build`, `join`, `remove` and `benchmark`, `peppy node add`, `build` and `run`, and `peppy repo refresh`. | Exit status | End | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 0 | The goal completed | | 1 | An error of the command, for example a budget that ran out | | 2 | The command line does not parse | | 3 | The daemon refused the goal, or answered a request with an error reply. A join or a removal that a lease refuses gives the failure kind `leased` | | 4 | The goal failed | | 5 | The goal was cancelled | | 6 | The daemon abandoned the goal | | 7 | The end of the goal expired before the command read it | | 130 | A second Ctrl+C stopped the wait for the end of the goal, or a Ctrl+C stopped a command with more goals to send, such as `peppy node add --run`, after a goal that completed before the cancel took effect | Each of these commands sends a cancel at the first Ctrl+C and exits with the status of the end that the goal then has (see [Stopping a stack command with Ctrl+C](/guides/launch_files/#stopping-a-stack-command-with-ctrlc)). `peppy node stop`, `remove`, `init` and `sync`, and `peppy repo add`, `list`, `exclude` and `remove` send the daemon a request that is not a goal, and exit with 3 when the daemon answers with an error reply. # The codec API > Call the members of contracts that your node was not built with, parse contract documents with their descriptions, enums and marks, and convert messages of any format A node calls the members of the contracts that its manifest names through its generated code. The codec API serves the calls to any other contract, such as a contract that a document names, from the contract document alone. Example: a workflow director runs a workflow that names a new skill contract, and calls the members of that contract with no new build of the director. The codec API has three parts: * **The parser of contracts.** It reads a contract document and gives the [description](/reference/concepts/#descriptions) of the contract, the description and the message formats of each member, the [enums](/reference/message_format/#enum-modifier), the [marks](/reference/message_format/#marks-modifier) and the [descriptions](/reference/message_format/#description-modifier) of their fields, and the [marks](/advanced_guides/contract_implementation/#marks) and the [failure kinds](/advanced_guides/contract_implementation/#failure-kinds) of its members. * **The codec.** It converts a message of any format between its canonical JSON values and the bytes on the wire. The bytes are the bytes that a generated node writes for the same values. * **The clients.** They call a service, send the goal of an action and follow it, and read a topic of a contract, on one producer. The [MCP server](/advanced_guides/mcp/) of peppy and the commands that [call a running instance](/advanced_guides/calling_instances/) use the same codec. ## Ask for the codec API [Section titled “Ask for the codec API”](#ask-for-the-codec-api) A node asks for the codec API in the `execution` block of its manifest: ```json5 { peppy_schema: "node/v1", manifest: { name: "workflow_director", tag: "v1", description: ["A director of workflows: it calls the members of the contracts that each workflow names, with no new build."], }, execution: { language: "rust", run_cmd: ["./target/release/workflow_director"], codec_api: true, }, } ``` `codec_api` is `false` when you leave it out. It is a choice of the build of the node, so a launcher cannot change it. `peppy node sync` and `peppy node add` give the codec API to a node that asks, and only to it: | Language | What the node gets | | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rust | A path dependency on the crate `peppy-codec` in the `Cargo.toml` of the node, and the crates `peppy-codec` and `peppy-mcp-catalog` in `.peppy/libs`, beside `peppylib` | | Python | The module `peppylib.codec` in the `peppylib` of the node | A node that stops asking loses the dependency and the crates, or the module, at its next generation. ### The Cap’n Proto compiler [Section titled “The Cap’n Proto compiler”](#the-capn-proto-compiler) The codec lays out each message format with the Cap’n Proto compiler, at run time. So a node that asks for the codec API carries the compiler: * The crate `peppy-codec` embeds the compiler of the build target of the node. * The `peppylib` of a Python node gets the compiler of the platform of the node as the file `peppylib/capnp_compiler`. A node that runs in a container gets the Linux compiler of the architecture of the host. At its first layout, the codec writes the compiler into the `bin` directory of the peppy data root: `$PEPPY_HOME/bin`, else `~/.peppy/bin`. The name of the file holds the digest of its bytes, so nodes built by different releases of peppy share the directory with no conflict. When `CAPNP_BINARY_PATH` is set, the codec runs the compiler that it names instead. Peppy never runs a `capnp` from `PATH`. A layout runs the compiler once for each format. Build the codecs and the clients of a node at its start, not at each call. ## Parse a contract [Section titled “Parse a contract”](#parse-a-contract) * Rust ```rust use peppy_codec::contract::{InterfaceKind, MessageSide, PeppyContractParser}; let contract = PeppyContractParser::from_content(&document)?; // The format of the goal of `move_gripper`. let goal = contract.message_format(InterfaceKind::Action, "move_gripper", MessageSide::Goal); // The field `target.item` of that goal, with its enum, its marks and its description. let item = contract .field(InterfaceKind::Action, "move_gripper", MessageSide::Goal, &["target", "item"]) .expect("the goal has the field"); let holds_an_item_id = item.marks().contains("item_id"); let values = item.enum_values().map(|values| values.values()); let item_about = item.description().map(|description| description.as_str()); // The marks of the member. let moves_robot = contract.marks.moves_robot(InterfaceKind::Action, "move_gripper"); // The description of the contract and of the member. let summary = contract.description().summary().as_str(); let paragraphs = contract.description().paragraphs(); let about = contract.member_description(InterfaceKind::Action, "move_gripper"); ``` `description()` gives the `DocumentDescription` of the contract: `summary()` is its first paragraph, and `paragraphs()` gives each paragraph. `member_description(kind, name)` gives an `Option<&Description>`, `None` for a member that the contract does not declare. `field_description(kind, name, side, path)` gives the description of a field by its path, as `field(...)?.description()` does: `None` for a field that the format does not have, or that has no `$description`. `peppy_codec::contract` also gives the types of a format that the API names, such as `MessageFormat`, `SchemaType`, `Marks`, `Description` and `DocumentDescription`. `PeppyContractParser::from_path` reads a file. * Python ```python from peppylib import codec contract = codec.Contract.parse(document) goal = contract.message_format("action", "move_gripper", "goal") marks = contract.field_marks("action", "move_gripper", "goal", ["target", "item"]) values = contract.field_enum("action", "move_gripper", "goal", ["target", "item"]) member_marks = contract.member_marks("action", "move_gripper") paragraphs = contract.description about = contract.member_description("action", "move_gripper") item_about = contract.field_description("action", "move_gripper", "goal", ["target", "item"]) ``` `description` is the list of the paragraphs of the contract, the first one its summary. `member_description` gives a `str`, and raises `KeyError` for a member that the contract does not declare. `field_description` gives a `str`, or `None` for a field with no `$description`, and raises `KeyError` for a field that the format does not have. `Contract.from_path` reads a file. A text that is not a contract raises `codec.ContractError`, which names the key that the parser refused. A member is named by its kind and its name. A message side is named by its member: `message` of a topic, `request` and `response` of a service, `goal`, `goal_response` (the reply that accepts a goal), `feedback` and `result` of an action. A field is named by its path in its format: the key of each object that it sits in, from the root of the format, with the items of an array passed through. So the field `angle` of each item of `joints` is `["joints", "angle"]`. The parser gives each mark as written, `moves_robot` and the marks of your own alike. Your node defines the marks that it reads, and checks them. ## Convert a message [Section titled “Convert a message”](#convert-a-message) The codec converts the canonical JSON values of a format, the values of the [MCP server](/advanced_guides/mcp/#the-published-schemas) and of [`peppy node call`](/advanced_guides/calling_instances/#the-message): | Type | Canonical value | | -------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | `bool`, `string`, `f32`, `f64`, and the integers up to 32 bits | The matching JSON value | | `u64`, `i64` | A decimal string, such as `"18446744073709551615"` | | `time` | An RFC 3339 UTC string with nanoseconds, such as `"2026-10-25T10:00:00.000000000Z"` | | `bytes`, an array of `u8` | A base64 string | | An `$optional` field that is absent | No key in the object | * Rust The values are `serde_json::Value`s: add `serde_json` to the dependencies of the node. ```rust use peppy_codec::MessageCodec; let codec = MessageCodec::new("move_gripper_goal", goal.expect("a goal format"))?; let bytes = codec.encode(&serde_json::json!({ "target": { "item": "cup_3" } }))?; let value = codec.decode(&bytes)?; ``` * Python ```python goal_codec = codec.MessageCodec("move_gripper_goal", goal) data = goal_codec.encode({"target": {"item": "cup_3"}}) value = goal_codec.decode(data) ``` A value that does not convert raises `codec.ConversionError`, which names the field. The first argument names the schema of the format. It seeds the id of the schema, and does not appear in messages. ## Call a member [Section titled “Call a member”](#call-a-member) Each client calls one member of a contract on one producer, a `(core node, instance id)` pair, as the instance of your node. The producer serves the member under the name and the tag of the contract, as each node that implements the contract does. * Rust ```rust use peppy_codec::consumer::{ActionClient, ConsumerIdentity, MemberBinding, ServiceClient}; use peppylib::messaging::{DEFAULT_FEEDBACK_BOUND, ProducerRef}; use std::time::Duration; let processor = node_runner.processor(); let caller = ConsumerIdentity { core_node: processor.bound_core_node().to_owned(), instance_id: processor.bound_instance_id().to_owned(), }; let robot = ProducerRef::new("robot-7", "arm_backbone"); // A service. let home = ServiceClient::of_contract(&contract, "move_to_home")?; let binding = MemberBinding::of_contract(&contract, "move_to_home")?; let response = home .call(node_runner.messenger(), &caller, &binding, &robot, &request, Duration::from_secs(30)) .await?; // An action. let grip = ActionClient::of_contract(&contract, "move_gripper")?; let binding = MemberBinding::of_contract(&contract, "move_gripper")?; let mut goal = grip .fire_goal(node_runner.messenger(), &caller, &binding, &robot, &goal_value, DEFAULT_FEEDBACK_BOUND, Duration::from_secs(5)) .await?; while let Some(feedback) = goal.next_feedback().await? { // ... } let outcome = goal.result(node_runner.messenger(), Duration::from_secs(5)).await?; ``` `TopicConsumer::of_producer` subscribes to a topic of the producer, with the codec that `peppy_codec::consumer::contract_topic_codec` lays out. * Python ```python from peppylib import ProducerRef messenger = node_runner.messenger() core_node = node_runner.bound_core_node() instance_id = node_runner.bound_instance_id() robot = ProducerRef("robot-7", "arm_backbone") # A service. home = codec.ServiceClient(contract, "move_to_home") response = await home.call(messenger, core_node, instance_id, robot, request, 30.0) # An action. grip = codec.ActionClient(contract, "move_gripper") goal = await grip.send_goal(messenger, core_node, instance_id, robot, goal_value) while (feedback := await goal.next_feedback()) is not None: ... outcome = await goal.result(messenger, 5.0) # A topic. states = await codec.TopicConsumer.subscribe( messenger, core_node, instance_id, contract, "limb_states", robot ) producer, state = await states.next_message() ``` The clients keep the rules of the generated clients: * A request, a goal and each message are canonical values, and a response, each feedback message and a result too. A message side with no format carries no payload, and reads as an empty object. * An error reply of a service, and a refusal or a failure of a goal, give a [failure kind](/advanced_guides/actions/#how-a-goal-ends) and a message. A kind that is neither a kind of peppy nor a kind of the contract that the member lists is an error of the provider: the Rust clients give `ConsumerError::UndeclaredFailureKind`, and the Python clients raise `codec.UndeclaredFailureKindError`. * A goal ends as `completed`, `cancelled`, `failed`, `abandoned` (the producer dropped the goal) or `expired` (the producer no longer keeps its result). A cancel gives what the producer acknowledges: the goal received the cancel signal, the goal had ended, or the producer knows no such goal. * The handle of a goal keeps a bounded number of unread feedback messages. A caller that reads the feedback and falls behind by more loses the stream: the handle cancels the goal, and the next read gives the loss as an error. A caller that never reads the feedback keeps its goal. * A topic subscription keeps the newest unread messages: a reader slower than the producer loses the oldest unread ones, and never holds up the producer. A topic that keeps messages for late subscribers (`retention`) gives them first. ## Find the instances to call [Section titled “Find the instances to call”](#find-the-instances-to-call) A generated client calls only the instances that the launcher binds to the slots of its node. The clients of the codec API take any producer. A node that asks for the codec API and has a `robot_leases` [daemon target](/advanced_guides/core_node_functions/#daemon-targets) with `list` in its scope reads the fleet listing (`robot_leases.list`) and calls a member on any instance of the listing, with no link from the launcher. With `contract` in its scope, it reads the pinned document of each contract of the listing (`robot_leases.contract`), from which the codec lays out each message. With `changes` in its scope, it follows the listing, and calls a robot that joins later. The fleet listing does not give the right to move a robot. Before each call of a member with the mark `moves_robot`, the node asks `robot_leases.check_move`, and refuses its call when the daemon refuses the move: a lease gives one client the right to move one robot (see [Robot leases and the halt](/advanced_guides/fleet/)). # Choosing a communication pattern > Pick between topics, services, actions, pairing, contract implementation, and the datastore with a side-by-side decision guide Peppy gives nodes five ways to exchange data: [topics](/advanced_guides/topics/), [services](/advanced_guides/services/), [actions](/advanced_guides/actions/), [pairing](/advanced_guides/pairing/), and the [datastore](/advanced_guides/datastore/). On top of the first three, [contract implementation](/advanced_guides/contract_implementation/) changes not *what* flows but *who* can be on the other end. Each mechanism has its own guide; this page is the map for picking the right one before you write a manifest. Each of them joins two nodes: for code that a node calls as a function, see [Choosing between a node and a shared library](/advanced_guides/node_or_library/). The choice comes down to two independent questions: 1. **What shape is the exchange?** A continuous stream, a quick request, a bounded job, a standing two-way conversation, or a value left for later. 2. **How is the peer chosen?** A producer node named in the manifest, any node implementing a shared contract, or exactly one paired instance. ## What shape is the exchange? [Section titled “What shape is the exchange?”](#what-shape-is-the-exchange) | | Exchange | Initiated by | Lifecycle | Reach for it when | | ---------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | [Topics](/advanced_guides/topics/) | One-way stream from a producer to its consumers | The producer, whenever it has data | Continuous while the producer runs | Sensor readings, camera frames, state updates | | [Services](/advanced_guides/services/) | One request, one response or one error reply | The consumer | One bounded exchange per call | Queries, toggles, quick one-shot computations | | [Actions](/advanced_guides/actions/) | Goal in, feedback stream out, result on completion | The consumer fires a goal; the producer drives it to an end | A discrete job with an explicit start, end, and cancel; it ends when its sender is gone | Navigation, arm movements, calibration runs | | [Pairing](/advanced_guides/pairing/) | Two independent one-way streams under one two-role contract | Either side, whenever it has data | Continuous while both instances live; dissolves when either dies | Inner control loops between two specific instances | | [Datastore](/advanced_guides/datastore/) | Write a small value, read it back later | Writer and reader, at independent times | The value persists on the core node until overwritten or removed; a key an instance owns through `store_exclusive` is removed when its owner’s process ends | Calibration results and other values that outlive the node that wrote them | The same choices, phrased the way the requirement usually sounds: * “The camera publishes frames and whoever cares can watch.” A **topic**: one producer, any number of consumers, no coordination between them. * “The dashboard starts after the robot and still shows its current mode.” A **topic that retains** its latest value: a consumer that subscribes later reads it at once. See [Retaining the latest value](/advanced_guides/topics/#retaining-the-latest-value). * “Is the gripper open right now?” A **service**: you need an answer, you wait briefly for it, and the exchange is over. * “Move the arm to this pose, stream progress, tell me when it is done.” An **action**: the job has a defined end, reports feedback along the way, and can be cancelled mid-flight. * “The controller streams setpoints at 100 Hz and the arm streams joint states back at 1 kHz.” A **pairing**: both directions belong to one continuous conversation between two specific instances. * “Leave the calibration result somewhere the planner can pick it up when it starts.” The **datastore**: the reader does not have to be running, or subscribed, at the moment the value is produced. Two boundaries account for most wrong first guesses: * **Service or action?** Duration and observability, not importance. If the caller only needs a result and the work is quick, a service is enough. The moment you want progress updates or a cancel button, it is an action. A node can drive several goals of the same action concurrently; its goal handler sets the acceptance policy. Services and actions say why they fail in the same way. An error reply of a service, and a refused or failed goal, give a [failure kind](/advanced_guides/actions/#how-a-goal-ends) and a message, from the closed set that peppy and the contract of the member declare. So a client can try again, plan again or call a person without reading a text. * **Action or pairing?** Whether the exchange ends. “Do this and report when done” is an action. “Keep exchanging state for as long as we are both up” is a pairing. The two coexist happily on the same nodes; see [Pairing vs. actions](/advanced_guides/pairing/#pairing-vs-actions). ## How is the peer chosen? [Section titled “How is the peer chosen?”](#how-is-the-peer-chosen) The shape says nothing about which node sits on the other end. A consumer couples to the other end at one of four levels: | | Declared under | Who can fill the slot | Instances per slot | | ------------------------------------------------------------------------------------------ | ------------------------------ | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Direct node dependency | `depends_on.nodes` | Instances of that exact producer node | The producer instance(s) bound to the slot, sized by its cardinality (one by default); a `zero_or_one` slot may also run empty | | [Contract dependency](/advanced_guides/contract_implementation/) | `depends_on.contracts` | Any node whose `manifest.implements` names the contract | The implementing instance(s) bound to the slot, sized by its cardinality (one by default); a `zero_or_one` slot may also run empty | | [Pairing slot](/advanced_guides/pairing/) | `depends_on.pairings` | Instances playing the complementary role of the pairing | One pair per peer, both directions, sized by its cardinality (one by default, exclusive); a `zero_or_one` slot may also run with none | | [Observer slot](/advanced_guides/pairing/#observers-watching-a-pairing-without-joining-it) | `depends_on.pairing_observers` | Instances playing the observed role of the pairing | The observed pairing(s) bound to the slot, sized by its cardinality (`one` by default, or `zero_or_one` / `one_or_more` / `zero_or_more`), non-exclusive, read-only | Note Every slot takes an application-selected set sized by its declared [cardinality](/advanced_guides/topics/#dependency-cardinality): exactly one by default (`one`), at most one for `zero_or_one`, at least one for `one_or_more`, possibly empty for `zero_or_more`; a launch that leaves a `one` / `one_or_more` slot unbound is rejected. A participant pairing slot counts pairs, each between this instance and one peer. A slot that boots empty is declared vacant explicitly, with the reason, and only a `zero_or_one` slot of any kind may be. A topic slot receives from its bound producers and from no one else; a service or action call is answered by the one bound producer the caller selects, addressed directly. A consumer that needs several producers can declare several `one` slots (one role each) or one multi-cardinality slot. See [Why an explicit single target?](/advanced_guides/services/#why-an-explicit-single-target). * Use a **direct node dependency** when exactly one implementation exists and substitution is not a goal. It is the simplest wiring and the default. * Use a **contract** when several nodes implement the same contract (a hardware driver and its sim twin, several camera vendors), or when several producers should feed one consumer (telemetry, monitoring), with one slot declared per producer. The consumer names the contract; the launcher picks the producer behind each slot. See [Pairing vs. contracts](/advanced_guides/pairing/#pairing-vs-contracts) for the boundary on the other side. * Use a **pairing** when two specific instances belong together and both directions form one conversation, like a controller and *its* arm. The pair is established explicitly at start, is exclusive while it lasts, and dissolves when either side dies. * Use an **observer slot** when a third node only wants to watch one side of a pairing, like a recorder logging an arm’s states. It taps the topics the observed role emits, follows that source instance rather than any pair, and never talks back. The contract’s home follows the same ladder: a direct dependency’s message formats live on the producer’s own manifest, a contract’s live in a standalone `contract/v1` document both sides cite, and a pairing’s live in a standalone `pairing/v1` document naming the two roles. ## Rules that veto a design [Section titled “Rules that veto a design”](#rules-that-veto-a-design) A few system-wide rules reject otherwise-plausible wirings. Check your plan against them early: * **Only caller-driven cycles are cycles.** Topic subscriptions are passive, so two nodes may consume each other’s topics; pairing is built on exactly this property. Mutual service or action relationships deadlock, so the daemon rejects them however they are wired, directly or through contracts; see [Caller-driven cycles are rejected](/advanced_guides/contract_implementation/#caller-driven-cycles-are-rejected). When two nodes need both directions, make at least one direction a topic (or model both directions as a pairing), or model the bounded direction as an action from client to server. * **Pairings carry topics only.** No services or actions inside a pairing contract. Keep the continuous streams in the pairing and expose the bounded jobs as ordinary actions alongside it; the reasoning is in [Why topics only?](/advanced_guides/pairing/#why-topics-only). * **A stream is live unless its topic retains.** A subscriber of a live-only topic receives messages from the moment it attaches, and a pairing slot delivers nothing while unpaired. When a new subscriber must see the latest value of a state a node publishes, that node declares [`retention`](/advanced_guides/topics/#retaining-the-latest-value) on the topic. When the value must outlive the node that produced it, put it in the [datastore](/advanced_guides/datastore/). * **The datastore is a blackboard, not a database.** It lives in the core node’s memory: a key no instance owns survives node restarts but not a daemon restart. It holds small values, not history. See [When to use this](/advanced_guides/datastore/#when-to-use-this). ## Worked example: one arm, every mechanism [Section titled “Worked example: one arm, every mechanism”](#worked-example-one-arm-every-mechanism) The mechanisms compose freely on the same nodes. A complete robot arm setup might touch every one of them: * `robot_arm` and `arm_controller` exchange `joint_commands` and `joint_states` through a **pairing**: continuous, both directions, exactly these two instances, and the arm’s slot goes silent if its controller dies. * `robot_arm` exposes a `calibrate` **action**: run on demand, streams progress, ends with a result, can be cancelled. * `robot_arm` exposes an `enable_motors` **service**: a quick toggle with an immediate answer. * `robot_arm` also implements a `joint_state_source` **contract**; a dashboard declares one contract slot per arm on the floor and consumes each arm’s state **topic** through it, feeding one monitor without disturbing any pairing. * The calibration result is written to the **datastore**, so a restarted controller reads it back instead of re-running the calibration. One relationship, one mechanism: the pairing carries the control loop, the action carries the bounded job, the contract slots carry the monitoring feeds, and the datastore carries the state that outlives any single exchange. # Containers > Make your nodes truly portable Containers package a node and all of its dependencies into a single, self-contained image. A containerized node runs identically regardless of what is installed on the host: no more “works on my machine” issues. Use containers when you need: * **Portability**: ship a node to another machine without worrying about system dependencies. * **Reproducibility**: guarantee the same runtime environment every time. * **Isolation**: prevent conflicts between nodes that need different versions of the same library. Peppy uses [Apptainer](https://apptainer.org/) as its container runtime. On macOS, Apptainer runs transparently inside a [Lima](https://lima-vm.io/) virtual machine; no extra setup is needed. ## Setup (Linux) [Section titled “Setup (Linux)”](#setup-linux) On Linux, container nodes need three packages of the distribution, and Apptainer uses unprivileged user namespaces which may require a one-time system configuration. The installer handles this automatically, on a host and in a Docker or Podman container, but if you skipped it or installed Peppy manually you can run: ```sh peppy container setup ``` This configures the following (through `sudo` for a user that is not root, and with no `sudo` for root): 1. **Packages**: installs the package of each program of the table below that is missing. It reads the package lists first (`apt-get update`), so it also works in a container of a bare image, which has none. 2. **AppArmor profile** (on systems that restrict unprivileged user namespaces via AppArmor): installs a profile for the `apptainer` and `starter` programs of the installation, which allows them to create user namespaces, and loads it into the kernel. When the profile already exists but is not loaded, it is reloaded without being rewritten. The setup installs `fuse2fs` last, in an installation of its own. When that installation fails (the distribution of the machine does not have the package, for example), each other fix is made: the setup writes a warning and exits with `0`. In a terminal, the setup asks before it makes its fixes. When you answer `n`, it prints the commands and makes no change. It then exits with `1` when a container build or the daemon needs one of the fixes, and with `0` when the only fix is the installation of `fuse2fs`. Peppy bundles Apptainer, and Apptainer runs three programs that come from the distribution: | Program | Package | What uses it | Without it | | ------------ | ---------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `newuidmap` | `uidmap` | The fakeroot build of a user that is not root. | Each container build of a user that is not root stops. Root builds with no fakeroot, so the checks do not ask root for `newuidmap`. | | `mksquashfs` | `squashfs-tools` | Each node build: it packs the image. | Each container build stops. | | `fuse2fs` | `fuse2fs` | The mount of an EXT3 image. | Each container start writes `fuse2fs not found, will not be able to mount EXT3 filesystems`. The images that Peppy builds are squashfs images, which build and run without it. | A bare `ubuntu:24.04` or `debian:trixie` image has none of the three packages. To check the current state without making any changes: ```sh peppy container status ``` This prints a pass/fail summary of each prerequisite and exits with code `0` (all pass) or `1` (something needs fixing). A missing `fuse2fs` is a warning: its line shows `WARNING`, and the status exits with `0`. For root, the line of `newuidmap` shows `not required`. The daemon makes the same checks at its start: * Without the AppArmor profile, on a system that needs one, the daemon stops. Its error gives the commands that repair each failing check. * Without `newuidmap` or `mksquashfs`, the daemon starts and writes a warning. Only a container build runs these two programs, so the images that the daemon has and the nodes that are not containers run. Each container build stops before it starts Apptainer, with an error that gives the command that installs each missing package. A build finds a package that you install while the daemon runs. * Without `fuse2fs`, the daemon starts. The status also asks the kernel for a user namespace, as Apptainer does before each container build: it runs `unshare --user /bin/true` as the user of the builds, which is the caller of `sudo` when `sudo` runs the command. The `User namespace` line shows the answer: | Line | Meaning | | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `OK` | The kernel gives the namespace. | | `FAILED ()` | The kernel refuses the namespace, for example because a sysctl turns user namespaces off or because of the seccomp profile of a Docker container. | | `not required` | The user of the builds is root, which builds with no user namespace. | | `not tested ()` | The request gives no answer for Apptainer. `unshare` did not run, or AppArmor refuses `unshare` on a system whose kernel does not have the profile `unprivileged_userns` (`apparmor.service` is stopped). Apptainer does not need that profile: it has the profile of its installation. | The setup has no fix for a namespace that the kernel refuses. `peppy container status` then exits with `1`. `peppy container setup` makes the fixes of the other prerequisites, writes a warning with the message of `unshare`, and exits with `0`. The daemon writes the same warning at its start: the nodes that are not containers run, and each container build fails. The `Node images` line tells how each node gets the files of its image: `mounted`, or `unpacked at each start` for a user that is not root where a node can write to a directory on overlayfs, as in a Docker container (see [Node images on overlayfs](#node-images-on-overlayfs)). An unpacked image is not a failure, and the status exits with `0`. To check the packages alone, add `--packages`: ```sh peppy container status --packages ``` It exits with `1` when a container build stops without a package that is missing, and gives the command that installs each missing package. Note On macOS, no setup is needed; containers run inside a Lima VM which handles permissions transparently. ### Host files in a container [Section titled “Host files in a container”](#host-files-in-a-container) Apptainer binds `/etc/localtime` and `/etc/hosts` of the host into each container, so a node has the time zone and the host names of the host. They are the `bind path` entries of the `apptainer.conf` that Peppy installs. When the host does not have the source of a `bind path` entry, Peppy skips that bind, and the node has what its image has at that path. A minimal host can be without `/etc/localtime`: the `ubuntu` Docker image has none until it gets the `tzdata` package. ### Node images on overlayfs [Section titled “Node images on overlayfs”](#node-images-on-overlayfs) Apptainer gives a node the files of its image in one of two ways: it mounts the image, or it unpacks the image and starts the node from the copy. Peppy asks for the copy (`--unsquash`) when these two conditions apply together: * The daemon is not root. * A directory that the node can write to is on overlayfs: `/tmp`, `/var/tmp`, the home directory of the user of the daemon, the working directory of the node (which is in the data root), the source of one of its mounts, or a path of the host that a flag of its `apptainer_run_extra_args` names (`--bind`, `--mount`, `--home`, `--workdir`, `--overlay`). The root file system of a Docker or Podman container is on overlayfs. So a daemon of a user that is not root starts each node from a copy of its image there, unless a volume or a tmpfs holds each of these directories. The cause is in the kernel. For a user that is not root, the mounted image is a FUSE file system in the user namespace of the node, and that namespace maps this user only. Overlayfs reads and writes a file with the credentials of the user that mounted it, and FUSE refuses a request of a user that the namespace does not map. A node that writes data of its mounted image to a file on overlayfs, for example a file that is compiled into its program, stops with `Bad address (os error 14)`. The copy is made of files of the disk, so a node that starts from it has no such fault. The copy has a cost: * Each start of a node unpacks its image with `unsquashfs`, which comes with the `squashfs-tools` package. A 400 MB image takes about one second on a fast disk. * The copy uses disk space while the node runs: as much as the files of the image, which can be some gigabytes for one node. It is in the data root, in `tmp/container_scratch`. Apptainer removes it when the node ends. Peppy removes what a node that was killed left, when the process of the node is over and before a restart of the node starts, and removes at the start of the daemon each copy that an earlier daemon left. The `Node images` line of `peppy container status` shows which of the two ways applies: | Line | Meaning | | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `mounted` | Apptainer mounts the image of each node. | | `unpacked at each start ( are on overlayfs)` | Each node starts from a copy of its image. The line names each directory on overlayfs among `/tmp`, `/var/tmp`, the home directory and the data root. It does not name a directory that is below another one of the list, such as a data root in the home directory. | The line is for the directories that each node has. A node with a mount whose source is on overlayfs starts from a copy also when the line shows `mounted`. The daemon writes the same information in its log. The status reads the data root as the command resolves it: `PEPPY_HOME` when the command has that variable, or else the default data root in the home directory of the user of the builds. `sudo` does not give the `PEPPY_HOME` of its caller to the command, so for a daemon with a data root that `PEPPY_HOME` names, give the variable to the command also (`sudo PEPPY_HOME= peppy container status`). To get mounted images in a container, do one of these: * Put a volume or a tmpfs at each directory that the line names. For `/tmp` and `/var/tmp` of a Docker container, add `--tmpfs /tmp:exec --tmpfs /var/tmp:exec` to `docker run`, and put a volume at the home directory. * Run the daemon as root (see [Running the daemon as root](#running-the-daemon-as-root)). ### Running the daemon as root [Section titled “Running the daemon as root”](#running-the-daemon-as-root) Apptainer mounts the image of a container in one of two ways. For a daemon that is not root, it runs the container in a user namespace and mounts the image with its bundled `squashfuse_ll`. For a daemon that runs as root, the kernel mounts the image. Root inside a rootless container is not this root: Apptainer uses a user namespace and `squashfuse_ll` there too. A kernel mounts an image only when it is built with the compression of that image. Peppy packs each image with zstd, and some kernels cannot mount a zstd squashfs. The WSL2 kernel, which Docker Desktop on Windows also runs on, and the kernel of the NVIDIA Jetson are two of them. So a daemon that runs as root reads the compression of each image that it runs. For an image that its kernel cannot mount, Peppy passes `--userns` to Apptainer, and the container runs in a user namespace as it does for every other user. Peppy reads the kernel configuration from `/proc/config.gz`, then from `/boot/config-`, and looks for the line of the compression: `CONFIG_SQUASHFS_ZSTD=y` for zstd. In that user namespace: * A node has none of the capabilities of the real root. It cannot, for example, take a real-time priority. * Root has its rights on the files of root only. The Peppy installation, the working directory of the node and the source of each mount of the node must be in directories that root owns, that a group of the daemon can enter, or that every user can enter, and not below the private home directory of another user. When the installation is not, the daemon starts and writes a warning in its log. A container with one of these paths out of reach stops at its start with an error that names the directory and how to open it. A process node does not use the user namespace, so it works. A build works too: only the prune of the uv cache after the build of a Python node runs the image, and with a path out of reach the build output says that the cache is not pruned. A container whose image the kernel mounts runs without a user namespace, with the capabilities of the real root. On a kernel that mounts zstd squashfs, this is each container of a root daemon. On a kernel that does not, a node that needs these capabilities packs its image with a compression that the kernel mounts, with `apptainer_build_extra_args: ["--mksquashfs-args", "-comp gzip"]` (see [Extra runtime arguments](#extra-runtime-arguments)). Note When Peppy can read no kernel configuration, it passes no flag. If a node of a root daemon then stops with `kernel reported a bad superblock for squashfs image partition`, set `APPTAINER_USERNS=1` in the environment of the daemon. ## Initializing a container node [Section titled “Initializing a container node”](#initializing-a-container-node) Pass the `--container` flag to `peppy node init`: * Python ```sh peppy node init --toolchain uv --container my_node "A node that runs in an Apptainer container." ``` * Rust ```sh peppy node init --toolchain cargo --container my_node "A node that runs in an Apptainer container." ``` This generates the same project scaffolding as a regular node, plus an `apptainer.def` file that describes how the container image is built. ## The `peppy.json5` configuration [Section titled “The peppy.json5 configuration”](#the-peppyjson5-configuration) A container node includes a `container` block inside its `execution` section instead of the usual `build_cmd` and `run_cmd` fields. The two are mutually exclusive: a node is either a container node or a process node, never both. * Python peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs in an Apptainer container."], }, interfaces: {}, execution: { language: "python", container: { def_file: "apptainer.def", }, } } ``` * Rust peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs in an Apptainer container."], }, interfaces: {}, execution: { language: "rust", container: { def_file: "apptainer.def", }, } } ``` The `def_file` field points to the Apptainer definition file relative to the node root. You can rename or relocate it as long as `def_file` matches. Compare this with a standard process node, which defines `build_cmd` and `run_cmd` instead: * Python peppy.json5 (process node) ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs as a process on its machine."], }, interfaces: {}, execution: { language: "python", build_cmd: ["uv", "sync", "--no-editable"], run_cmd: ["./.venv/bin/python", "-m", "my_node"] } } ``` * Rust peppy.json5 (process node) ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs as a process on its machine."], }, interfaces: {}, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/my_node"] } } ``` Container nodes don’t need `build_cmd` or `run_cmd`; the definition file takes care of both building and running the node. ## The `apptainer.def` file [Section titled “The apptainer.def file”](#the-apptainerdef-file) The generated definition file is a standard [Apptainer definition file](https://apptainer.org/docs/user/latest/definition_files.html). Here is what `peppy node init --container` generates: * Python apptainer.def ```apptainer Bootstrap: docker From: peppybot/python-uv-base:latest %labels Name my_node Version v1 %environment export PATH="/opt/my_node/.venv/bin:$PATH" %files . /opt/my_node %post set -eux export DEBIAN_FRONTEND=noninteractive export UV_PYTHON_INSTALL_DIR=/opt/uv-python cd /opt/my_node uv python install uv sync --no-editable %runscript cd /opt/my_node exec ./.venv/bin/python -m my_node ``` * Rust apptainer.def ```apptainer Bootstrap: docker From: peppybot/rust-cargo-base:latest %labels Name my_node Version v1 %files . /opt/my_node %post set -eux cd /opt/my_node cargo build --release %runscript cd /opt/my_node exec ./target/release/my_node ``` Each section serves a specific purpose: | Section | Purpose | | -------------------- | ---------------------------------------------------------------------- | | `Bootstrap` / `From` | Base image to build from (Ubuntu 24.04 by default) | | `%labels` | Metadata embedded in the image | | `%environment` | Environment variables set when the container runs | | `%files` | Copies the node source into the image at `/opt/` | | `%post` | Build steps: install system packages, toolchains, and compile the node | | `%runscript` | Entry point executed when the container starts | Note The `%files` section copies the entire node directory into the container. Peppy automatically copies (rather than symlinks) internal libraries like `peppylib` so that they are fully available inside the image. Caution Keep whatever the build produces out of the container user’s home directory. At run time apptainer mounts the home of the user running the daemon over the image’s own home, so anything the build left there is hidden. That is what `UV_PYTHON_INSTALL_DIR` above is for: uv installs managed interpreters under `$HOME`, so without it the interpreter lands in `/root` and a daemon running as root hides it, leaving the node to fail at startup with `./.venv/bin/python: not found`. ## Adding a container node [Section titled “Adding a container node”](#adding-a-container-node) Adding a container node works the same as a regular node: first stage it, then build. ```sh peppy node add ./my_node peppy node build my_node:v1 ``` You can also combine both steps with `peppy node add ./my_node --build` (shorthand `-b`). If you’ve just edited `peppy.json5`, add `--sync`/`-s` as well, e.g. `peppy node add ./my_node -sb` to sync, add, and build in one shot. Under the hood, Peppy runs `apptainer build` during the build phase to produce a `.sif` (Singularity Image Format) file. This replaces the `build_cmd` step used by process nodes; the entire build happens inside the container according to the `%post` section of the definition file. The resulting `.sif` file is stored under `~/.peppy/built_nodes/_/`, named after the fingerprint of the staged sources (see [Build caching](#build-caching)), and is ready to be started. Note Container builds can take longer than regular builds because they install system packages and toolchains from scratch. ## Starting a container node [Section titled “Starting a container node”](#starting-a-container-node) Starting a container node also uses the same command: ```sh peppy node run my_node:v1 ``` Peppy runs the `.sif` image with `apptainer run` and a clean environment: the daemon’s own environment is not inherited. The environment of the instance (the forwarded environment on the coordinator, the values of its [`env_from_launch`](/guides/launch_files/#env_from_launch-optional) and its declared [`env_vars`](/guides/launch_files/#env_vars-optional), minus `HOME`, which is dropped) and `PEPPY_RUNTIME_CONFIG` are passed in explicitly, and the image’s `%environment` section applies as usual. Each one reaches apptainer as an `APPTAINERENV_` variable, never on a command line: on Linux in the environment of the apptainer process, and on macOS on the standard input of the command in the Lima VM, whose shell exports each one before it starts apptainer. The container executes the `%runscript` section, which runs the compiled binary (Rust) or the Python module entry point. ## What a container node sees of the data root [Section titled “What a container node sees of the data root”](#what-a-container-node-sees-of-the-data-root) The data root of Peppy (`~/.peppy`, or `PEPPY_HOME`) holds the keys that the clients of the daemon sign their calls to it with, and the machine certificate (see [The senders of the calls to a daemon](/advanced_guides/call_senders/)). A container node does not see it: the daemon mounts an empty directory over the data root, and over that directory the container sees its own working directory, its own runtime configuration and its own key file, and nothing else of the data root. Apptainer binds the home directory of the user into the container, so a node keeps its caches and its other files there. ## Mounting host directories [Section titled “Mounting host directories”](#mounting-host-directories) By default, a container is isolated from the host filesystem. Use `mount_paths` to bind-mount host directories into the running container, useful for sharing datasets, persisting output, or exposing device files. Add a `mount_paths` array to the `container` block inside `execution` in `peppy.json5`: peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs in an Apptainer container."], }, interfaces: {}, execution: { language: "python", container: { def_file: "apptainer.def", mount_paths: [ "/data/models:/opt/models:ro", "/tmp/my_node_output:/output:rw" ] }, } } ``` Each entry follows the format `host_path:container_path[:options]`: | Format | Example | Behaviour | | ---------------------------------- | ------------------------------- | ----------------------------------------------------------------------- | | `host_path` | `"/data/models"` | Mounted at the same path inside the container | | `host_path:container_path` | `"/data/models:/opt/models"` | Mounted at a different path inside the container | | `host_path:container_path:options` | `"/data/models:/opt/models:ro"` | Mounted with explicit options (`ro` for read-only, `rw` for read-write) | `host_path` may start with `~`, which expands to the home directory of the user running the daemon **on the machine where the instance runs**. In a federated launch, each machine expands `~` against its own home, so a single manifest works across machines with different usernames (`"~/.cache/my_node:/cache:rw"`). The `~user` form is not supported and is rejected while the launch is being validated, before any stack is replaced. Only the host side is expanded: a `~` in `container_path` is passed to the container verbatim. A source under `/dev` with no remap (no destination, or a destination equal to the source) is passed through rather than bound: host devices reach the container through Apptainer’s device mount, and only a remapped device bind emits an explicit `--bind`. A missing mount source is created on the host as a directory before the container starts, and a warning names each auto-created path, so a typo in a file bind shows up as an unexpectedly created empty directory. Sources under the host runtime trees (`/dev`, `/proc`, `/run`, `/sys`) are used as-is and never created. Note A bind path that holds a `:` or a `,`, on the host side or the container side, is refused: Apptainer’s `src:dest:opts` spec reads both characters as separators and offers no way to escape them, so such a path cannot be expressed. A path produced by `${parameters:...}` substitution is checked the same way, once the parameter resolves. Note A mount whose source is the data root of Peppy, a path in it, or a directory that holds it, such as `~` with the default data root `~/.peppy`, is refused when the launch prepares the mounts of the machine and when the instance starts, with a message that names the mount: a container node does not see the data root. Note Top-level system directories such as `/`, `/tmp`, `/var`, `/etc`, `/dev`, `/usr`, `/home`, `/opt`, `/bin`, and `/sbin` cannot be used as mount sources, and on macOS neither can their `/private/*` equivalents (`/private/tmp`, `/private/var`, `/private/etc`). Subdirectories of these paths are fine; for example, `/tmp/my_app_data` is allowed but `/tmp` is not. Note On macOS, Peppy automatically configures the Lima VM to make mounted paths accessible inside the guest, including paths outside your home directory. Sources under the host runtime trees (`/dev`, `/proc`, `/run`, `/sys`) are the exception: a device plugged into the Mac cannot be forwarded into the Linux guest, so such a bind is refused with an error naming the path; run that node on a Linux daemon instead. Registering a new path with the VM restarts it, which stops every container node running on that machine. `peppy stack launch` prepares a machine’s mount paths before it starts anything, so a launch never pays that cost in stopped nodes: the restart, when needed, happens before anything is running. A `peppy node run` that would introduce a new path while container nodes are already running is refused instead, naming the instances it would have stopped: stop them first, or launch them together. ### Using parameters in mount paths [Section titled “Using parameters in mount paths”](#using-parameters-in-mount-paths) Mount paths can reference runtime [parameters](/guides/parameters/) using the `${parameters:}` syntax. This lets each node instance mount a different host path based on its configuration. peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "uvc_camera", tag: "v1", description: ["The driver of a UVC camera, in an Apptainer container. It needs a UVC camera at the device path that its parameter gives."], }, interfaces: {}, execution: { language: "rust", parameters: { device_path: "string", }, container: { def_file: "apptainer.def", mount_paths: [ "${parameters:device_path}:/dev/video0:rw" ] }, }, } ``` When the node runs, `${parameters:device_path}` is replaced with the actual value provided in the deployment configuration. For example, if the instance supplies `device_path: "/dev/video2"`, the resulting bind mount is `/dev/video2:/dev/video0:rw`. For nested parameters, use dot notation: peppy.json5 (nested example) ```json5 { // ... execution: { // ... parameters: { video: { device_path: "string", frame_rate: "u16", }, }, container: { def_file: "apptainer.def", mount_paths: [ "${parameters:video.device_path}:/dev/video0:rw" ] }, }, // ... } ``` Note Only parameters of type `"string"` can be referenced in mount paths. Numeric or object parameters are rejected at parse time. Note A literal blocked source (e.g., `/tmp`) is rejected at parse time. A source containing `${parameters:...}` is checked at runtime instead, against the resolved path. ## Build caching [Section titled “Build caching”](#build-caching) ### Build artifact cache [Section titled “Build artifact cache”](#build-artifact-cache) Every `peppy node build`, including the ones `peppy stack launch` and `peppy stack build` run for each deployment, fingerprints the staged node tree before building: the node sources, `peppy.json5`, the def file, the generated `.peppy/` code and the vendored peppylib, mixed with the peppy version, the platform of the artifact and the artifact kind. The artifact is stored under that fingerprint, and the file of a container node also names its platform (`linux-amd64` or `linux-arm64`): ```plaintext ~/.peppy/built_nodes/_/.linux-.sif container node ~/.peppy/built_nodes/_/.tar.zst process node ``` When the fingerprint already has an artifact on disk, the build reuses it instead of running `apptainer build` (or `build_cmd` for a process node), and the build log carries one line: ```plaintext Reusing cached build of my_node:v1 (fingerprint 3f9a1c2e5d7b8a4f) at ~/.peppy/built_nodes/my_node_v1/3f9a1c2e5d7b8a4f.linux-amd64.sif ``` The cache is a plain directory tree keyed by content, so it survives daemon restarts and reboots, and a disk prepared on one machine carries its built nodes to every machine that boots from it with the same peppy version, OS and architecture. A process node’s archive also embeds what the host toolchain produced, which the fingerprint does not cover, so those machines need a compatible build environment as well. Each node identity keeps one artifact for each platform: a build whose fingerprint differs replaces the previous one of its platform. A node that an [`oci` repository](/advanced_guides/repositories/#oci-repositories) supplies is pulled, not built: its image is stored as `~/.peppy/built_nodes/_/.linux-.sif`. Pass `--rebuild` to `peppy node build`, `peppy stack launch` or `peppy stack build` to build from the staged sources even when a matching artifact exists; the result replaces it. Use it when something outside the fingerprint changed: * A floating base image tag (`From: peppybot/rust-cargo-base:latest`) that now resolves to a different image. Pin the image with `@sha256:` in the def file to make base image changes part of the fingerprint. * For a process node, the host toolchain or the environment `build_cmd` runs with. `--rebuild` is independent of `--force`, which cancels an in-flight build of the same node. ### Build caches inside container builds [Section titled “Build caches inside container builds”](#build-caches-inside-container-builds) Rust and Python container builds reuse a shared cache across builds, without any per-node configuration. The daemon bind mounts `~/.peppy/cache/container_build` into the build at `/peppy-cache` and points the `%post` toolchain at it. A Rust container build gets: * The crates.io registry in `cargo-home/`, via `CARGO_HOME`, so dependencies are downloaded once instead of on every build. * [sccache](https://github.com/mozilla/sccache) caches rustc invocations in `sccache-cache//`, via `RUSTC_WRAPPER` and `SCCACHE_DIR`, so unchanged crates are not recompiled. Each architecture has its directory, since the output of a compiler of one architecture is no use to a build of the other. The executable ships inside `peppybot/rust-cargo-base`, so nothing needs to be installed on the host, on Linux or macOS; the wrapper is activated only for defs that bootstrap from that image. A Python container build gets: * The packages uv downloads and builds in `uv-cache/`, via `UV_CACHE_DIR`, so a rebuild installs every package it already downloaded from the cache. * The interpreter archives `uv python install` downloads in `uv-python/`, via `UV_PYTHON_CACHE_DIR`, so each Python version is downloaded once. * `UV_LINK_MODE=copy`: uv copies the files of the packages it installs from its cache into the image. The cache is a bind mount, where uv cannot hard-link into the image, and a copy keeps every file of the image independent of the host cache. Both get `PEPPY_DOWNLOAD_CACHE`, which names `/peppy-cache/downloads`, a directory for the files a `%post` downloads. No tool reads it on its own: a def that pins a download by its sha256 looks the file up there under that checksum before it downloads it, and stores what it downloaded there once the checksum matches. A rebuild then reaches the network only for a pin it has not seen yet. A def tests for `PEPPY_DOWNLOAD_CACHE`, not for `/peppy-cache`: the variable is set only when the cache is bind mounted, while `/peppy-cache` also exists as a plain directory of the base image, where anything written ends up in the built image. Because the directory is shared, a def checks a cached file against its pin before it uses it, and stores a file under a temporary name before it renames it, so concurrent builds never read a partial file: ```bash # fetch_pinned URL SHA256 DEST fetch_pinned() { local cached="${PEPPY_DOWNLOAD_CACHE:-}/$2" part if [ -n "${PEPPY_DOWNLOAD_CACHE:-}" ] && [ -f "$cached" ] \ && echo "$2 $cached" | sha256sum -c --status; then cp "$cached" "$3" return fi curl -fsSL --retry 3 --retry-all-errors -o "$3" "$1" echo "$2 $3" | sha256sum -c - [ -n "${PEPPY_DOWNLOAD_CACHE:-}" ] || return 0 part=$(mktemp "$PEPPY_DOWNLOAD_CACHE/.$2.XXXXXX") \ && cp "$3" "$part" && mv -f "$part" "$cached" \ || { rm -f "$part"; echo "warning: $1 not stored in the download cache"; } } ``` Both also get `PEPPY_NODE_BUILD_CACHE`, which names `/peppy-cache/nodes//_`: a directory of the node being built for the architecture of the build, which no build of another node or of another architecture uses. Peppy never reads it. A def keeps there what its next build can use, such as a part of the image that it builds again only when the inputs of that part change, stored under a hash of those inputs. A build of the node can start while an earlier one still ends (after a `--force` build, say), so a def stores a file there under a temporary name and then renames it, as with the downloads. Nothing prunes the directory: a def that stores a new entry removes the entries it no longer needs. Caution Caching requires a `/peppy-cache` directory in the base image: build-time binds cannot create their destination. The peppy base images (`peppybot/rust-cargo-base`, `peppybot/python-uv-base`) ship it, and the daemon enables caching automatically when a def file bootstraps from one of them. Any other base image must create the directory itself (`RUN mkdir /peppy-cache` in its Dockerfile) and the def file must mention `/peppy-cache` to opt in. Such a Rust build gets registry and download caching but not sccache, which the daemon activates only for defs that bootstrap from `peppybot/rust-cargo-base`. Such a Python build gets the uv package, interpreter and download caches. Caching is best effort and never fails a build: when the main directory of the cache of a build (`cargo-home/` or `uv-cache/`) is unavailable, the build runs exactly as it would without caching, and when another part is unavailable, the build runs without that part only. Set `PEPPY_NO_CONTAINER_BUILD_CACHE=1` in the daemon’s environment to disable caching entirely. The daemon also skips the cache for one build when the def file or `apptainer_build_extra_args` mention one of the markers of the build’s language: | Language | Markers | | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rust | `rustup` (installing it in `%post` is incompatible with the `CARGO_HOME` override), `CARGO_HOME`, `RUSTC_WRAPPER`, `SCCACHE_DIR`, `SCCACHE_SERVER_PORT` | | Python | `UV_CACHE_DIR`, `UV_PYTHON_CACHE_DIR`, `UV_LINK_MODE`, `--link-mode` (the flag of uv overrides `UV_LINK_MODE`) | A Python def that installs rustup, to build a Rust extension for example, keeps its uv cache: the Python cache sets no cargo variable. After each Python container build that uses the cache and succeeds, the daemon prunes `uv-cache/` with `uv cache prune`, run with the uv of the image that the build wrote. Each build stages the local projects of the node again (the node itself, and `.peppy/libs/peppylib` with its native extension), so uv builds them again and keeps every earlier build of them, which no later build uses. The prune removes these. It also removes each file or directory at the top of `uv-cache/` that is not a cache directory of uv, and each archive in `archive-v0/` that no cache entry names; other files in the cache directories of uv stay. A line of the build output gives the result, for example `Container build cache: uv cache pruned: Removed 15 files (6.8MiB)`. A failed prune does not fail the build. A build that fails or is cancelled does not prune. A build prunes only when no other Python container build uses the cache; else a later build that succeeds prunes it. A Python build that starts while another build prunes waits until the prune ends, and a line of the build output says so: `Container build cache: waiting for another build to prune the uv cache`. The prune runs the first `uv` on the `PATH` of the image that is not in a Python virtual environment, as `%post` does not see the virtual environment that a `%environment` puts on `PATH`. There is no prune when the image has no such `uv`, and the daemon stops a prune that runs for 30 seconds. Where Apptainer unpacks the image before the prune (see [Node images on overlayfs](#node-images-on-overlayfs)), the prune has 10 minutes more, for the time that the extraction takes. uv also removes the entries of a cache layout that is not its own: nodes whose images have uv versions with different cache layouts remove each other’s entries. Note The cache lives at `~/.peppy/cache/container_build` and is safe to delete at any time; the next build recreates it. Each directory of `sccache-cache/` prunes itself to sccache’s size limit (10 GiB by default). `cargo-home/` grows with every dependency version ever built, `uv-python/` with every Python version ever installed, `downloads/` with every pin ever fetched, and `nodes/` with what the defs keep there; they are only reclaimed by deleting them. `uv-cache/` grows with every package version ever installed. Because the directory is shared and writable, what a `%post` writes there can persist into later builds on the same machine, the same trust the build itself already runs with. On macOS, builds run inside the Lima VM: the cache directory is bind mounted through it and the environment rides the guest command, so container builds cache the same way as on Linux. ### PyPI mirror for Python builds [Section titled “PyPI mirror for Python builds”](#pypi-mirror-for-python-builds) Python builds download their packages from PyPI. When PyPI is slow from the host, set `pypi_mirror` in the [daemon configuration](/advanced_guides/daemon_config/#pypi_mirror-pypi-mirror-for-python-builds) to the packages base URL of a PyPI mirror, and restart the daemon: ```json5 pypi_mirror: "https://pypi.tuna.tsinghua.edu.cn/packages/", ``` Before a Python node builds, a container node or a process node alike, the daemon reads each `uv.lock` in the staged copy of the node. It collects the files that the lock pins by sha256 for packages from a registry, at a URL below `https://files.pythonhosted.org/packages/`. It asks the mirror for each of these files with a `HEAD` request, 8 at a time, and puts the mirror in the URL of each file that the mirror has with the size the lock records. Every other file keeps its PyPI URL, so a file that the mirror does not have yet still comes from PyPI. Only the staged copy changes: the node sources stay as they are, and the [build artifact cache](#build-artifact-cache) keys the build by the staged tree as it was before the change, so a build finds the same artifact with and without a mirror. The image or the archive of the node holds the rewritten `uv.lock`. A mirror that you do not control is safe: uv checks each file it downloads against the sha256 in the lock, and the lock comes from the repository of the node. A mirror can make a build slow or make it fail, but it cannot change what the build installs. uv accepts the rewritten lock with `uv sync`, `uv sync --locked` and `uv sync --frozen`, and the uv cache stays valid when you change or remove the mirror. Packages from other sources (a direct URL, git, a path), registry files on another host (such as the files that `download.pytorch.org` serves itself), and files that no lock pins do not use the mirror. Files that no lock pins include the build requirements uv installs to build the node and its `.peppy/libs` projects (such as hatchling and setuptools), the Python interpreter, GitHub release assets, apt packages and base image layers. The presence check uses the proxy that `ALL_PROXY`, `HTTPS_PROXY` or `HTTP_PROXY` names in the environment of the daemon (HTTP or SOCKS), and skips the hosts in `NO_PROXY`, as uv does. Each build that uses the mirror shows one line per `uv.lock`, which names the lock, as the build may not read every lock of the node (the lock of a test project, for example): ```plaintext PyPI mirror: pypi.tuna.tsinghua.edu.cn; uv.lock: 868 of 870 locked files from the mirror, 2 from files.pythonhosted.org ``` A check that takes more than a few seconds also shows how many files it checked. When the mirror does not answer, when a `uv.lock` cannot be read or written, or when the check cannot run, the build shows a warning and downloads the files concerned from PyPI. A mirror that answers the `HEAD` request for a file but then fails to send the file makes uv fail the build: build again, or set `pypi_mirror` back to `null`. A packages base URL is the URL under which a mirror keeps the files of PyPI with the path layout of `https://files.pythonhosted.org/packages/`: the path of a file after the packages base URL is the same on both. It is not the index URL of the mirror, which ends with `/simple/`. Some mirrors and their packages base URL: | Mirror | Location | Packages base URL | | -------------------------- | ----------- | -------------------------------------------------------- | | OSSO | Netherlands | `https://pypi.osso.nl/packages/` | | Yandex | Russia | `https://mirror.yandex.ru/pypi/web/packages/` | | Tsinghua University (TUNA) | China | `https://pypi.tuna.tsinghua.edu.cn/packages/` | | USTC | China | `https://mirrors.ustc.edu.cn/pypi/packages/` | | Nanjing University | China | `https://mirror.nju.edu.cn/pypi/web/packages/` | | SJTU | China | `https://mirror.sjtu.edu.cn/pypi-packages/` | | Huawei Cloud | CDN | `https://repo.huaweicloud.com/repository/pypi/packages/` | To check that a mirror has a file, take the URL of the file from your `uv.lock`, replace `https://files.pythonhosted.org/packages/` with the packages base URL of the mirror, and send a `HEAD` request that follows redirects. The mirror has the file when the last answer is `200` with a `Content-Length` equal to the `size` in the lock, and does not come from `files.pythonhosted.org`: some mirrors redirect every file to PyPI, and the daemon then keeps the PyPI URL: ```sh curl -sIL https://pypi.tuna.tsinghua.edu.cn/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl ``` A mirror can be hours behind PyPI, and PyPI is fast from most places, so set a mirror only when PyPI is slow from the host. ## Extra runtime arguments [Section titled “Extra runtime arguments”](#extra-runtime-arguments) You can pass additional command-line arguments directly to Apptainer or Lima using `apptainer_build_extra_args`, `apptainer_run_extra_args`, and `lima_shell_extra_args` in the `container` block inside `execution`. peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "my_node", tag: "v1", description: ["A node that runs in an Apptainer container."], }, interfaces: {}, execution: { language: "python", container: { def_file: "apptainer.def", apptainer_build_extra_args: ["--no-setgroups"], apptainer_run_extra_args: ["--no-setgroups"], }, } } ``` | Field | Purpose | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `apptainer_build_extra_args` | Extra flags appended to `apptainer build` (e.g., `["--no-setgroups"]`) | | `apptainer_run_extra_args` | Extra flags appended to `apptainer run` (e.g., `["--no-setgroups"]`) | | `lima_shell_extra_args` | Extra flags passed to `limactl shell` whenever a build runs in a Lima VM: every container build on macOS, and on Linux a build for another architecture (`peppy node publish --platforms`, `peppy stack build --publish --platforms`), which runs in an emulated VM. Ignored for a native Linux build of this machine’s own platform | All fields are optional and default to an empty list when omitted. Peppy packs every image it builds with zstd at level 3 (`--mksquashfs-args "-comp zstd -Xcompression-level 3"`), which packs a node image about ten times faster than Apptainer’s default gzip, at the same size. The extra build arguments come after that flag, and Apptainer reads the last `--mksquashfs-args`, so `apptainer_build_extra_args: ["--mksquashfs-args", "-comp xz"]` packs the image with xz. A node that renders or computes on the host’s NVIDIA GPU passes `apptainer_run_extra_args: ["--nv"]`: Apptainer then binds the host’s driver libraries (CUDA, EGL, GLX, NVML) into the container at start. Apptainer’s own list of these libraries covers NVIDIA’s desktop driver. The L4T driver of a Jetson board loads more libraries, and the set changes from one L4T release to the next. Each L4T release lists them in its container manifest, the `*.csv` files in `/etc/nvidia-container-runtime/host-files-for-container.d`. Before it starts a `--nv` node, peppy adds every shared library of that manifest to the list of the bundled Apptainer. So the same node configuration renders and computes through the GPU on a desktop and on a Jetson. Note These arguments are passed verbatim; no validation is performed beyond basic string checks. Incorrect flags will cause Apptainer or Lima to fail at build or start time. ## macOS support [Section titled “macOS support”](#macos-support) On macOS, Apptainer is not natively available. Peppy bundles a [Lima](https://lima-vm.io/) virtual machine that runs Apptainer inside a lightweight Linux guest. This is handled transparently and requires no additional installation or configuration; `peppy node` commands work the same way on macOS and Linux, with one exception: mount sources under the host runtime trees (`/dev`, `/proc`, `/run`, `/sys`) are refused, since a device plugged into the Mac cannot be forwarded into the Linux guest. The guest has the architecture of the Mac, so a node runs as a `linux/arm64` container on a Mac with Apple silicon. A [publish for another architecture](/advanced_guides/publishing/#build-for-another-architecture) builds in a second VM, which emulates that architecture with QEMU, on macOS and on Linux. ## Customizing the definition file [Section titled “Customizing the definition file”](#customizing-the-definition-file) The generated `apptainer.def` is a starting point. You can modify it freely to fit your needs. Common customizations include: ### Adding system dependencies [Section titled “Adding system dependencies”](#adding-system-dependencies) Add packages to the `%post` section: ```apptainer %post apt-get update apt-get install -y --no-install-recommends \ libopencv-dev libudev-dev rm -rf /var/lib/apt/lists/* ``` #### The Ubuntu snapshot of the peppy base images [Section titled “The Ubuntu snapshot of the peppy base images”](#the-ubuntu-snapshot-of-the-peppy-base-images) In the peppy base images (`peppybot/python-uv-base`, `peppybot/rust-cargo-base`), `apt` reads the Ubuntu packages from one dated snapshot of the Ubuntu archive, which the [Ubuntu snapshot service](https://snapshot.ubuntu.com) serves. The snapshot is the archive as it was one hour before the build of the base image started, and its package index and package files do not change. While the snapshot service answers, a node build on a peppy base image gets this from it: * Two builds of the node on the same base image install the same versions of the Ubuntu packages. * The build upgrades no package of the base image: each package of the image is at its version in the snapshot. * The node has the Ubuntu security updates up to the date of the snapshot, not up to the day of its build. A newer base image reads a newer snapshot. Pass `--rebuild` to build a node on it (see [Build artifact cache](#build-artifact-cache)). For a file that the snapshot service does not serve (it does not answer, or it answers with an error), `apt` asks the regular Ubuntu mirror: `archive.ubuntu.com` on `linux/amd64`, `ports.ubuntu.com` on `linux/arm64`. A build that the snapshot service does not answer at all reads the current state of the archive, as a build on another Ubuntu image does: it is slower, by about 30 seconds for each `apt-get` command when the service does not answer, and it can install newer versions than the snapshot and upgrade packages of the base image. The date of the snapshot is a UTC time in the form `YYYYMMDDTHHMMSSZ`. The image holds it in its `bot.peppy.apt-snapshot` label: ```sh docker pull peppybot/python-uv-base:latest docker inspect --format '{{ index .Config.Labels "bot.peppy.apt-snapshot" }}' peppybot/python-uv-base:latest ``` Inside a build, `/etc/apt/peppy-ubuntu-mirrors.txt` lists the snapshot first and the regular mirror second, and each line that `apt` prints for a package names the source it downloads the package from: ```text Get:1 https://snapshot.ubuntu.com/ubuntu/20261110T073833Z noble/main amd64 libudev-dev amd64 255.4-1ubuntu8 [22.0 kB] ``` `apt` reads a repository that the definition file adds itself (a PPA, the repository of a vendor) as the definition file names it: the packages of that repository do not come from the snapshot. A definition file with another base image reads the sources of that image. ### Changing the base image [Section titled “Changing the base image”](#changing-the-base-image) Swap the `From` line to use a different base: ```apptainer Bootstrap: docker From: nvidia/cuda:12.4.0-devel-ubuntu24.04 ``` ### Using a pre-built base image for faster builds [Section titled “Using a pre-built base image for faster builds”](#using-a-pre-built-base-image-for-faster-builds) Every `peppy node add` runs the full `%post` section from scratch, installing system packages, toolchains, and compiling dependencies each time. For nodes with heavy dependencies this can be slow. You can speed things up by baking those slow steps into a custom Docker image and using it as your base. The first build pays the cost once; every subsequent `node add` starts from the cached image and only rebuilds your application code. 1. **Create a `Dockerfile`** with the dependencies your node needs: * Python Dockerfile ```dockerfile FROM ubuntu:24.04 RUN set -eux \ && export DEBIAN_FRONTEND=noninteractive \ && apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates curl python3 python3-venv \ && rm -rf /var/lib/apt/lists/* \ && curl -LsSf https://astral.sh/uv/install.sh | sh ``` * Rust Dockerfile ```dockerfile FROM ubuntu:24.04 RUN set -eux \ && export DEBIAN_FRONTEND=noninteractive \ && apt-get update \ && apt-get install -y --no-install-recommends \ ca-certificates curl build-essential pkg-config \ && rm -rf /var/lib/apt/lists/* \ && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y ``` 2. **Build and push the image** to a registry your build machine can reach: ```sh docker build -t my-registry/my_node-base:latest . docker push my-registry/my_node-base:latest ``` 3. **Point your `apptainer.def`** at the new image and remove the steps that are already baked in: * Python apptainer.def ```apptainer Bootstrap: docker From: my-registry/my_node-base:latest %labels Name my_node Version v1 %environment export PATH="/root/.local/bin:/opt/my_node/.venv/bin:$PATH" %files . /opt/my_node %post set -eux cd /opt/my_node uv sync --no-editable %runscript cd /opt/my_node exec ./.venv/bin/python -m my_node ``` * Rust apptainer.def ```apptainer Bootstrap: docker From: my-registry/my_node-base:latest %labels Name my_node Version v1 %environment export PATH="/root/.cargo/bin:$PATH" %files . /opt/my_node %post set -eux cd /opt/my_node cargo build --release %runscript cd /opt/my_node exec ./target/release/my_node ``` Now `peppy node add` only runs the application-specific build steps; package installation and toolchain setup are already in the base image. Tip If multiple nodes share the same system dependencies, a single base image can serve all of them. Update the base image when dependencies change and tag it with a version so builds stay reproducible. ### Pulling from a private registry [Section titled “Pulling from a private registry”](#pulling-from-a-private-registry) On Linux, a build reads registry credentials from the same file Apptainer reads: `$APPTAINER_AUTH_FILE` when it is set, else `~/.apptainer/docker-config.json` (written by `apptainer registry login`) when it exists, else `~/.docker/config.json` (written by `docker login`). Log in to the registry that holds your base image with either tool before you build. Peppy gives Apptainer a copy of that file without the `https://index.docker.io/v1/access-token` and `https://index.docker.io/v1/refresh-token` entries that Docker’s browser login adds. These entries hold Docker’s own session tokens, not registry passwords, and Apptainer would otherwise use one of them at random in place of your Docker Hub credential. Peppy writes the copy before each build, so a new `docker login` applies to the next build without a daemon restart. If Peppy cannot read or parse the file, the build fails and names the file. On macOS, builds run inside the Lima guest, so they use the credential files in the guest user’s home directory. ### Adding environment variables [Section titled “Adding environment variables”](#adding-environment-variables) Add variables to the `%environment` section so they are available at runtime: * Python ```apptainer %environment export PATH="/opt/my_node/.venv/bin:$PATH" export PYTHONUNBUFFERED=1 ``` * Rust ```apptainer %environment export PATH="/root/.cargo/bin:$PATH" export RUST_LOG=info ``` # Contract implementation > Declare reusable message contracts and let nodes implement them explicitly, so consumers can bind any implementing producer at launch time A peppy node can either declare its `topics`, `services` and `actions` natively in its own `peppy.json5`, or it can implement a separately-defined **contract**. A contract is a standalone document with its own `peppy_schema: "contract/v1"` that names a set of topics, services and actions. Producers implement the contract; consumers depend on the contract. Both sides cite the contract by `(name, tag)`, and the launcher binds an implementing producer to the consumer at launch time. Contract implementation is the abstraction you reach for when several nodes provide the same capability. A `realsense_d405` driver, a `zed_2i` driver, and a `mujoco_depth_camera_sim` all expose the same `video_stream` topic. Without contracts, every consumer would have to hard-code one of those producer names. With contracts, the consumer asks for the `depth_camera:v1` contract and the launcher decides which physical driver (or its sim equivalent) fills the slot. For how contract implementation compares with the other ways of wiring nodes together, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## The three pieces [Section titled “The three pieces”](#the-three-pieces) ### 1. The contract document [Section titled “1. The contract document”](#1-the-contract-document) A contract lives in its own file under a repository Peppy scans (see [Repositories](/advanced_guides/repositories/)). It uses `peppy_schema: "contract/v1"` and declares the same `topics` / `services` / `actions` shapes you would put on a node, except the `interfaces` block is the contract itself, with no `emits` / `consumes` split: ```json5 // depth_camera/peppy.json5 (inside a registered repo) { peppy_schema: "contract/v1", manifest: { name: "depth_camera", tag: "v1", description: ["A depth camera: a stream of its frames, and a service that gives the settings of that stream."], }, interfaces: { topics: [ { name: "video_stream", description: "Each frame of the camera, with its size and its encoding.", qos_profile: "sensor_data", message_format: { header: { $type: "object", stamp: "time", frame_id: "u32" }, encoding: "string", width: "u32", height: "u32", frame: { $type: "array", $items: "u8", $description: "The pixels of the frame, row by row, in its encoding." }, }, }, ], services: [ { name: "video_stream_info", description: "The size, the frame rate and the encoding of the stream.", response_message_format: { width: "u32", height: "u32", frames_per_second: "u8", encoding: "string", }, }, ], }, } ``` #### Failure kinds [Section titled “Failure kinds”](#failure-kinds) A refused or failed goal, and the error reply of a service, give a **failure kind**: why the provider refused or failed, from a closed set. Every provider can give the kinds of peppy: | `failure_kind` | Meaning | | ---------------------- | --------------------------------------------------------- | | `attempt_failed` | The attempt gave no result | | `timeout` | The bound of the provider passed | | `precondition_failed` | A precondition failed | | `resource_unavailable` | A robot, limb or host is gone | | `rejected` | The provider refused the goal, and no other kind says why | A contract declares the kinds of its own in its `failure_kinds` block, between `manifest` and `interfaces`: each name with its meaning, a short sentence. Each service and action then lists in a `failure_kinds` list of its own the kinds of the block that it gives. A member gives a kind of peppy or a kind that it lists, and no other: ```json5 { peppy_schema: "contract/v1", manifest: { name: "limb_motion", tag: "v1", description: ["The motions of the arms and the grippers of a robot."] }, failure_kinds: { unreachable: "No plan to the target", leader_streaming: "A leader streams a limb of the goal", }, interfaces: { actions: [ { name: "move_arm", /* ... */ failure_kinds: ["unreachable", "leader_streaming"] }, { name: "move_gripper", /* ... */ failure_kinds: ["leader_streaming"] }, ], services: [ { name: "stop", /* ... */ }, ], }, } ``` A kind name is 1 to 64 lowercase ASCII letters, digits and `_`, and starts with a letter. A contract does not declare a kind of peppy, and no meaning is blank. A member lists only kinds that the block declares, each once, and each declared kind is listed by at least one member: the parser refuses the contract otherwise. The block and the lists are optional; a member that lists no kind, such as `stop` above, gives the kinds of peppy only. The generated code of each action and service declares the kinds of its member, the kinds of peppy first and then the kinds it lists, as a `FailureKind` enum with a `Failure` type: the generated provider can give no other kind, and the generated client and the [MCP server](/advanced_guides/mcp/) refuse any other kind from the wire. So a new kind of a node changes that node and its contract, never peppy. See [How a goal ends](/advanced_guides/actions/#how-a-goal-ends) and [Error replies](/advanced_guides/services/#error-replies). #### Marks [Section titled “Marks”](#marks) A contract can give marks, names, to its members: a `marks` list on a topic, a service or an action. Peppy defines one mark, `moves_robot`: the mark of a member that can move a part of a robot, the gripper included, or change the state of a device. A member that only stops a motion, such as `stop`, has no mark: ```json5 { peppy_schema: "contract/v1", manifest: { name: "limb_motion", tag: "v1", description: ["The motions of the arms and the grippers of a robot."] }, interfaces: { actions: [ { name: "move_arm", marks: ["moves_robot"], /* ... */ }, ], services: [ { name: "stop", /* ... */ }, ], }, } ``` A mark name follows the rule of a failure kind name: words of lowercase ASCII letters and digits that each start with a letter, joined by one `_`, 64 bytes at most. A `marks` list holds at least one mark, each once; a member with no mark leaves the key out. Peppy keeps each other mark as written and gives it to the clients of the contract, such as the [codec API](/advanced_guides/codec_api/): each client defines the marks that it reads. The fields of a message format carry marks with `$marks`, and a `string` field declares a closed set of strings with `$enum` (see [Message format](/reference/message_format/#enum-modifier)). #### Descriptions [Section titled “Descriptions”](#descriptions) A contract describes itself and each of its members as data. `manifest.description` gives the paragraphs of the contract, the first one its summary. Each topic, service and action gives a `description` after its `name`, and a field can give a [`$description`](/reference/message_format/#description-modifier), as `video_stream` and its `frame` field do above. The rules are in [Descriptions](/reference/concepts/#descriptions). The [codec API](/advanced_guides/codec_api/#parse-a-contract) gives these descriptions with the document, `peppy repo show` and [`peppy node describe`](/advanced_guides/calling_instances/#peppy-node-describe) print them, and the [MCP server](/advanced_guides/mcp/#the-published-schemas) publishes the description of each field. The comments of a contract are notes for its maintainers, and no reader shows them. After `peppy repo refresh`, the contract is cached and addressable by `(name, tag)`. Files use whatever filename you like as long as it ends in `.json5`; Peppy identifies a `contract/v1` document by its `peppy_schema` field. `peppy repo show :` lists the indexed nodes that implement or consume it (see [Show what a query matches](/advanced_guides/repositories/#show-what-a-query-matches)). ### 2. A producer that implements the contract [Section titled “2. A producer that implements the contract”](#2-a-producer-that-implements-the-contract) A producer node claims a contract in `manifest.implements`. Each entry names a contract by `(name, tag)` and mints a `link_id` for the slot. The producer then lists **every** member of the contract as an explicit contract-backed entry in its `interfaces` section, referencing the slot via that `link_id`: * Python realsense_d405/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "realsense_d405", tag: "v1", description: ["The driver of an Intel RealSense D405 depth camera. It needs a D405 on a USB port of its machine."], implements: [ { name: "depth_camera", tag: "v1", link_id: "cam" }, ], }, interfaces: { topics: { emits: [ { link_id: "cam", name: "video_stream" }, ], }, services: { exposes: [ { link_id: "cam", name: "video_stream_info" }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "realsense_d405"], }, } ``` * Rust realsense_d405/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "realsense_d405", tag: "v1", description: ["The driver of an Intel RealSense D405 depth camera. It needs a D405 on a USB port of its machine."], implements: [ { name: "depth_camera", tag: "v1", link_id: "cam" }, ], }, interfaces: { topics: { emits: [ { link_id: "cam", name: "video_stream" }, ], }, services: { exposes: [ { link_id: "cam", name: "video_stream_info" }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/realsense_d405"], }, } ``` A contract-backed entry is `{link_id, name}`, plus an optional `refine` block described [below](#refining-the-contracts-generic-arrays). The description, the shape, QoS and [retention](/advanced_guides/topics/#retaining-the-latest-value) come from the contract document, never from the manifest: an inline `description`, `message_format`, `qos_profile`, `retention`, or service/action payload field on a contract-backed entry is rejected at parse time. The `name` is a strict selector, byte-equal to a member the contract declares. The producer node is named `realsense_d405`, not `depth_camera`. The two names are unrelated. The only thing that makes `realsense_d405` a valid `depth_camera` is the explicit `implements` claim. After `peppy node sync`, code generation emits the same `video_stream` and `video_stream_info` modules that a node declaring the shapes natively would get, nested under the implements slot’s `link_id` (`emitted_topics/cam/video_stream`), not the contract’s name or tag. #### Full coverage is mandatory [Section titled “Full coverage is mandatory”](#full-coverage-is-mandatory) The set of contract-backed entries referencing a slot must cover every member of its contract, exactly once, with no extras. A partial implementation is rejected at `node add` / `node sync` with one aggregated diff per broken slot, listing every missing, unknown, duplicated, and wrong-kind entry at once: ```plaintext contract `uvc_camera:v1` (implements slot `cam`) is not fully implemented: every contract member needs exactly one contract-backed entry in `interfaces` referencing link_id `cam`; missing: [video_stream_info (service), set_contrast (service)] ``` This is the point of the explicit-entry design: the node’s `peppy.json5` shows what the node actually emits and exposes, and the daemon enforces that the listing is complete. #### link_id rules [Section titled “link_id rules”](#link_id-rules) Implements link_ids share one flat namespace with `depends_on.{nodes,contracts,daemon,pairings,pairing_observers}` link_ids; a collision is rejected at parse time. Direction matters: * `services.exposes` and `actions.exposes` may only reference a `manifest.implements` slot. * `topics.emits` may reference a `manifest.implements` slot or a `depends_on.pairings` slot, because a [pairing](/advanced_guides/pairing/) role produces the document’s topics as well as consuming them. * `services.consumes` and `actions.consumes` may only reference a `depends_on.{nodes,contracts}` slot; a pairing document declares topics only, so it exposes no service or action to consume. * `topics.consumes` may additionally reference a `depends_on.pairings` slot, naming a topic the counterpart role emits, or a `depends_on.pairing_observers` slot, naming a topic the observed role emits. Pick semantic short names for implements link_ids (`cam`, `collision`, `hw_ready`, `moves`), matching the consumer-side style, rather than echoing the contract name. A single node can implement multiple contracts (e.g. `depth_camera:v1` and `uvc_camera:v1` under distinct link_ids) and then satisfies any consumer slot that asks for either. A node may implement each contract `(name, tag)` at most once; several instances of one capability are the job of node instances and [pairings](/advanced_guides/pairing/), not repeated implements entries. A node may also implement a contract *and* depend on the same contract under a different link_id (the relay shape). A native entry and a contract-backed entry may share a name on the same producer: the two are namespaced apart in generated modules, schema keys, and wire keys. #### Refining the contract’s generic arrays [Section titled “Refining the contract’s generic arrays”](#refining-the-contracts-generic-arrays) A contract keeps an array generic when its length is a property of the implementing device rather than of the interface. A `limb_motion` contract declares `joint_positions: { $type: "array", $items: "f64" }` with “one entry per joint of the arm”, because a contract for arms cannot say how many joints every arm has. The node that drives a particular arm knows, and says so with a `refine` block on the entry: ```json5 actions: { exposes: [ { link_id: "moves", name: "move_arm_joints", // This arm has seven joints: pin the contract's generic joint vectors. refine: { goal_service: { request_message_format: { joint_positions: { $length: 7 } } }, result_service: { response_message_format: { final_joint_positions: { $length: 7 } } }, }, }, ], }, ``` The block mirrors the member’s structure down to the array and carries `{ $length: N }` at the leaf: a topic entry refines `message_format`, a service entry `request_message_format` and/or `response_message_format`, an action entry `goal_service`, `feedback_topic`, and/or `result_service`. Nested objects are stepped into by naming their fields, and an array of objects by `$items`: ```json5 refine: { message_format: { header: { frame: { $length: 4 } }, transforms: { $items: { translation: { $length: 3 } } }, }, }, ``` The generated code is the contract’s shape with those lengths set and nothing else changed: `[f64; 7]` instead of `Vec` in Rust, a length-checked `list[float]` in Python, exactly what a native `$length: 7` produces. Consumers keep generating from the contract as written and stay generic. The two interoperate because a fixed-length and a variable-length array share one wire encoding; `$length` only pins the refining node’s types and adds its length checks. A goal whose array does not have the pinned length is rejected by the generated action server before the node’s own goal handler runs, like any other goal that does not decode (see [Handling goals](/advanced_guides/actions/#handling-goals)). Refinements are not visible to anyone else: the MCP exposure schema, `stack benchmark`, and launch-time binding checks all read the contract document. What a `refine` block may say is checked when the contract resolves, at `node add` / `node sync`, with every problem of an entry reported at once: * every pinned path must name an array the contract declares, and the array must be generic: an array the contract already pins is refused, whether or not the lengths agree, because the contract is the place where that length lives; * the array’s items must be scalars (the same rule as a native `$length`): `string`, `bytes`, `time`, and object items cannot be pinned; * `$items` steps into an array of objects only, and nested field names step into an object only. ```plaintext entry `move_arm_joints` (link_id `moves`) refines contract `limb_motion:v1` in ways the document does not admit: `goal_service.request_message_format.arm_id`: `$length` and `$items` apply to arrays, but the document declares a `u8`; `result_service.response_message_format.position`: the document already fixes the length at 3 ``` A coverage failure on the slot is reported first; refinements are checked once the slot lists the right members. The block’s own structure (a leaf that is exactly `$length`, no empty block, no shape modifier such as `$type` inside it) is checked at parse time, and `refine` on a native entry is rejected there as well: a native entry owns its shape and sets `$length` in its own `message_format`. Refinement works the same way on the consuming side: a `depends_on.contracts` entry in `topics.consumes`, `services.consumes`, or `actions.consumes` may carry the same `refine` block, for a consumer that knows the device it will be bound to. A `depends_on.nodes` entry may not: a node dependency resolves to the producer’s native shape, which is taken as is. Pairing-backed entries refine their pairing document’s topics the same way; see [Pairing](/advanced_guides/pairing/#refining-the-pairings-generic-arrays). ### 3. A consumer that depends on the contract [Section titled “3. A consumer that depends on the contract”](#3-a-consumer-that-depends-on-the-contract) A consumer references a contract through `manifest.depends_on.contracts` rather than `depends_on.nodes`. Every contract dep carries a `link_id` (exactly like a node dep), but its `(name, tag)` names the contract instead of a concrete producer: * Python video_reconstruction/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "video_reconstruction", tag: "v1", description: ["A node that makes a video from the frames of one depth camera. It needs no device."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "rear_camera" }, ], }, }, interfaces: { topics: { consumes: [ { name: "video_stream", link_id: "rear_camera", }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "video_reconstruction"], }, } ``` * Rust video_reconstruction/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "video_reconstruction", tag: "v1", description: ["A node that makes a video from the frames of one depth camera. It needs no device."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "rear_camera" }, ], }, }, interfaces: { topics: { consumes: [ { name: "video_stream", link_id: "rear_camera", }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/video_reconstruction"], }, } ``` The consumer never names a producer node. It names the contract, and the launcher does the matchmaking. #### Node dependencies expose native interfaces only [Section titled “Node dependencies expose native interfaces only”](#node-dependencies-expose-native-interfaces-only) A consumed entry whose `link_id` names a `depends_on.nodes` slot resolves exclusively against the producer’s **native** (no-`link_id`) entries. A contract-backed interface is consumable solely through a `depends_on.contracts` slot. The two namespaces cannot overlap, so there is no precedence rule to learn: consuming a name the producer provides only contract-backed fails with an error pointing at the contract dependency to declare instead. This keeps the wire addressing unambiguous: node-dep consumption is always node-addressed, contract-dep consumption is always contract-addressed. ## Binding an implementing producer [Section titled “Binding an implementing producer”](#binding-an-implementing-producer) The matching predicate at binding time is: *a producer satisfies a contract slot if its `manifest.implements` includes the slot’s `(name, tag)`*. The producer’s own node name is irrelevant. A `zed_2i:v1` node that implements `depth_camera:v1` is just as valid for a `depth_camera:v1` slot as a `realsense_d405:v1` node that implements it. The two instances must also read the same clock. A binding whose producer and consumer resolve to different [clock domains](/advanced_guides/system_clock/#clock-domains) is refused before anything starts, because the timestamps it would carry mean nothing on the other side. ### Binding a contract slot [Section titled “Binding a contract slot”](#binding-a-contract-slot) A contract slot is bound with `--link link_id@producer_instance_id` (or a launcher `links:` entry) whose value points at an instance whose node implements the requested contract: peppy_launcher.json5 ```json5 { peppy_schema: "launcher/v1", description: ["A RealSense D405 camera and a video reconstruction of its frames. It needs a D405 on a USB port."], deployments: [ { source: { name: "realsense_d405:v1" }, instances: [{ instance_id: "depth_cam_inst1" }], }, { source: { name: "video_reconstruction:v1" }, instances: [{ instance_id: "video_rec_1", links: { rear_camera: "depth_cam_inst1" }, }], }, ], } ``` The same example from the command line, launching the producer against an already-running consumer: ```sh peppy node run --instance-id depth_cam_inst1 realsense_d405:v1 peppy node run --instance-id=video_rec_1 --link rear_camera@depth_cam_inst1 video_reconstruction:v1 ``` If `depth_cam_inst1` were instead an instance of a node with no `implements`, the launcher rejects the binding with a `BindingContractNotImplemented` error citing the expected contract and the producer’s actual `(name, tag)`. The producer’s node name does **not** save it: a node called `depth_camera:v1` that fails to declare `implements: [{ depth_camera, v1, link_id }]` is treated like any other non-implementing node. ### One slot per implementing producer [Section titled “One slot per implementing producer”](#one-slot-per-implementing-producer) How many implementing producers a slot binds is its declared [cardinality](/advanced_guides/topics/#dependency-cardinality): exactly one by default, at most one for `zero_or_one`, an application-selected set for `one_or_more` / `zero_or_more`. A consumer that reads from several implementing producers can either declare one contract slot per producer (giving each a distinct role in code) or one multi-cardinality slot bound to the whole set behind a single API. Both keep contract slots the natural shape for many-to-one consumption whose membership the application controls: telemetry, monitoring, any consumer that reads data from a launch-chosen set of producers. Every declared `one` / `one_or_more` slot must be bound, and a `zero_or_one` slot is bound or declared vacant; a launch that leaves one unfulfilled is rejected. (For an exclusive 1:1 bidirectional relationship between two specific instances, use a [pairing](/advanced_guides/pairing/) instead.) ```json5 manifest: { depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "left_cam" }, { name: "depth_camera", tag: "v1", link_id: "right_cam" }, { name: "depth_camera", tag: "v1", link_id: "overhead_cam" }, ], }, } ``` Each binding key names its slot’s `link_id` directly, and every bound producer must implement the contract. The same routing rules as node deps apply; see [Bindings and routing](/advanced_guides/topics/#bindings-and-routing). #### Multiple producer instances under the same node identity [Section titled “Multiple producer instances under the same node identity”](#multiple-producer-instances-under-the-same-node-identity) A common case is several instances of the same implementing node (say, three `realsense_d405:v1` cameras plugged into the same robot). Each camera gets a slot of its own: the consumer declares one contract dep per camera and consumes each camera’s topic through that slot’s `link_id`: * Python video_reconstruction/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "video_reconstruction", tag: "v1", description: ["A node that makes one video from the frames of three depth cameras: front, back left and back right. It needs no device."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "front" }, { name: "depth_camera", tag: "v1", link_id: "back_left" }, { name: "depth_camera", tag: "v1", link_id: "back_right" }, ], }, }, interfaces: { topics: { consumes: [ { name: "video_stream", link_id: "front" }, { name: "video_stream", link_id: "back_left" }, { name: "video_stream", link_id: "back_right" }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "video_reconstruction"], }, } ``` * Rust video_reconstruction/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "video_reconstruction", tag: "v1", description: ["A node that makes one video from the frames of three depth cameras: front, back left and back right. It needs no device."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "front" }, { name: "depth_camera", tag: "v1", link_id: "back_left" }, { name: "depth_camera", tag: "v1", link_id: "back_right" }, ], }, }, interfaces: { topics: { consumes: [ { name: "video_stream", link_id: "front" }, { name: "video_stream", link_id: "back_left" }, { name: "video_stream", link_id: "back_right" }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/video_reconstruction"], }, } ``` Then the launcher binds each slot to its producer instance: peppy_launcher.json5 ```json5 { peppy_schema: "launcher/v1", description: ["Three RealSense D405 cameras, front, back left and back right, and one video reconstruction of their frames. It needs the three cameras."], deployments: [ { source: { name: "realsense_d405:v1" }, instances: [ { instance_id: "rs_front" }, { instance_id: "rs_back_left" }, { instance_id: "rs_back_right" }, ], }, { source: { name: "video_reconstruction:v1" }, instances: [ { instance_id: "recon_1", links: { front: "rs_front", back_left: "rs_back_left", back_right: "rs_back_right", }, }, ], }, ], } ``` The three bindings feed the three slots, and the consumer receives the streams through the generated `video_stream` modules under the `front`, `back_left`, and `back_right` slots. A fourth camera launched without a slot of its own would reach no consumer at all: only bound producers feed a slot. Inside the consumer, every consumed-topic API returns the **producer’s full `(core_node, instance_id)` identity** alongside the message payload. The consumer never hard-codes the launcher’s instance ids; it just uses the returned identity as a runtime key to keep per-producer state (latest frame, frame count, last-seen timestamp, etc.) when merging its slots into one aggregate, so the launcher can re-point a slot at a different implementing instance with no consumer code change. * Python ```python import asyncio from peppylib import ProducerRef from peppygen.consumed_topics.front import video_stream as front_video_stream from peppygen.consumed_topics.back_left import video_stream as back_left_video_stream from peppygen.consumed_topics.back_right import video_stream as back_right_video_stream frames_by_producer: dict[ProducerRef, Frame] = {} async def pump(subscription): async for producer, frame in subscription: # Key by the returned ProducerRef (its full core_node/instance_id # identity); do not compare against a hard-coded name. frames_by_producer[producer] = frame reconstruct(frames_by_producer) await asyncio.gather( pump(await front_video_stream.subscribe(node_runner)), pump(await back_left_video_stream.subscribe(node_runner)), pump(await back_right_video_stream.subscribe(node_runner)), ) ``` * Rust ```rust use peppygen::consumed_topics::{ front::video_stream as front_video_stream, back_left::video_stream as back_left_video_stream, back_right::video_stream as back_right_video_stream, }; use peppylib::messaging::ProducerRef; use std::collections::HashMap; let mut frames_by_producer: HashMap = HashMap::new(); let mut front = front_video_stream::subscribe(&node_runner).await?; let mut back_left = back_left_video_stream::subscribe(&node_runner).await?; let mut back_right = back_right_video_stream::subscribe(&node_runner).await?; loop { let next = tokio::select! { next = front.next() => next?, next = back_left.next() => next?, next = back_right.next() => next?, }; let Some((producer, frame)) = next else { break }; // Key by the returned producer identity; do not compare against a // hard-coded name. frames_by_producer.insert(producer, frame); reconstruct(&frames_by_producer); } ``` The same applies when the producers are a mix of node identities, as long as each implements `depth_camera:v1`: a launcher can bind `front` to a `realsense_d405:v1` instance and `back_left` to a `zed_2i:v1` instance, since the matching predicate is the implements claim, not node identity. The `(core_node, instance_id)` identity returned with each message still pinpoints the exact producer, regardless of which node implementation it came from. ## sha256 pinning [Section titled “sha256 pinning”](#sha256-pinning) Both sides can optionally pin a specific contract revision by `sha256`: ```json5 // consumer side depends_on: { contracts: [{ name: "depth_camera", tag: "v1", sha256: "aaaa…", link_id: "rear_camera" }], } // producer side manifest: { implements: [{ name: "depth_camera", tag: "v1", sha256: "aaaa…", link_id: "cam" }], } ``` Each side independently verifies its pinned `sha256` against the on-disk contract document at cache-resolution time. Peppy refuses to start a node whose pinned contract revision is not in the cache. The two sides are not cross-checked: a producer that pins `sha256` against the cached contract and a consumer that does not pin can still bind, as long as both pass their own checks. `peppy repo show :` shows every implementer’s and consumer’s pin next to the published document’s fingerprint, so a pin a sync would refuse is visible before the sync. ## Worked example: multi-camera reconstruction [Section titled “Worked example: multi-camera reconstruction”](#worked-example-multi-camera-reconstruction) Combining the pieces above, a typical setup looks like this: ```plaintext ┌─ depth_camera:v1 (contract) │ topics: [video_stream] │ services: [video_stream_info] │ ├─ realsense_d405:v1 (node) implements: [{depth_camera, v1, link_id: cam}] ├─ zed_2i:v1 (node) implements: [{depth_camera, v1, link_id: cam}] └─ mujoco_depth_camera_sim:v1 (node) implements: [{depth_camera, v1, link_id: cam}] video_reconstruction:v1 (consumer) depends_on.contracts: [ { depth_camera, v1, link_id: left_cam }, { depth_camera, v1, link_id: right_cam }, { depth_camera, v1, link_id: overhead_cam }, ] ``` A launcher can wire the three slots to any mix of implementing producers: ```json5 { peppy_schema: "launcher/v1", description: ["Two RealSense D405 cameras and a ZED 2i camera, and a video reconstruction of their frames. It needs the three cameras."], deployments: [ { source: { name: "realsense_d405:v1" }, instances: [ { instance_id: "rs_left" }, { instance_id: "rs_right" }, ], }, { source: { name: "zed_2i:v1" }, instances: [ { instance_id: "zed_overhead" }, ], }, { source: { name: "video_reconstruction:v1" }, instances: [ { instance_id: "recon_1", links: { left_cam: "rs_left", right_cam: "rs_right", overhead_cam: "zed_overhead", }, }, ], }, ], } ``` Every binding key names its slot’s `link_id`, and the launcher checks each target implements `depth_camera:v1`: `rs_left` and `rs_right` do via the `realsense_d405:v1` producer node, and `zed_overhead` does via `zed_2i:v1`. Node identity never matters, only the implements claim. Swapping `realsense_d405:v1` for `mujoco_depth_camera_sim:v1` in the launcher requires no change to the consumer node, since both producers implement the same contract and the binding works unchanged. Once the stack is running, these contract-resolved dependencies surface in the tooling alongside direct ones. `peppy stack list` includes them in its **Dependencies** section, annotated `(via depth_camera:v1 contract implementation)`, and [`peppy stack benchmark`](/advanced_guides/stack_benchmark/) measures each consumed topic, service, and action across the resolved edge. `peppy stack benchmark` draws a heavy `➔` arrow for a contract-implementation edge to distinguish it from a direct `depends_on.nodes` edge (`→`); in `peppy stack list` every dependency edge uses `➔` and the `(via ...)` annotation is what marks the contract-resolved ones. ## Caller-driven cycles are rejected [Section titled “Caller-driven cycles are rejected”](#caller-driven-cycles-are-rejected) A contract dependency is deliberately invisible to the node dependency graph, which is what lets two nodes depend on each other’s contracts without forming a structural cycle (the same property [pairings](/advanced_guides/pairing/) rely on). For **topics** this is always safe: a topic dependency is passive (“I receive whatever is published”), so two nodes can each receive from the other with no runtime ordering between them. **Services and actions are different.** Consuming a service or action contract means “I will actively call the provider and wait for its reply.” If two nodes each call a service (or action) the other provides, neither can make progress until the other does: a request/response deadlock. Routing the calls through contracts hides that cycle from the static graph, but it does not make the deadlock go away. Peppy therefore rebuilds the *caller-driven* edges separately, resolving each contract dep to its implementing providers via `manifest.implements`, and rejects any service/action cycle it finds. ### An example that is rejected [Section titled “An example that is rejected”](#an-example-that-is-rejected) Two service contracts, one provided by each node: ```json5 // pose_service/peppy.json5 (contract) { peppy_schema: "contract/v1", manifest: { name: "pose_service", tag: "v1", description: ["The pose of a robot on its map."] }, interfaces: { services: [ { name: "current_pose", description: "The current position and heading of the robot on the map.", response_message_format: { x: "f64", y: "f64", theta: "f64" }, }, ], }, } // obstacle_service/peppy.json5 (contract) { peppy_schema: "contract/v1", manifest: { name: "obstacle_service", tag: "v1", description: ["The obstacles of a map."] }, interfaces: { services: [ { name: "nearest_obstacle", description: "The distance and the bearing of the obstacle nearest to a point of the map.", request_message_format: { x: "f64", y: "f64" }, response_message_format: { distance: "f64", bearing: "f64" }, }, ], }, } ``` `localizer` provides `pose_service` and *calls* `obstacle_service`; `mapper` provides `obstacle_service` and *calls* `pose_service`. Each node implements the contract it provides and consumes the service it calls through a `link_id`, exactly like a mutual-topic wiring, except both consumed links are **services**: * Python localizer/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "localizer", tag: "v1", description: ["A localizer: it gives the pose of the robot on the map, and asks the mapper for the nearest obstacle."], implements: [ { name: "pose_service", tag: "v1", link_id: "pose_out" }, // provides current_pose ], depends_on: { contracts: [ { name: "obstacle_service", tag: "v1", link_id: "obstacles" }, ], }, }, interfaces: { services: { exposes: [ { link_id: "pose_out", name: "current_pose" }, ], consumes: [ { name: "nearest_obstacle", link_id: "obstacles" }, // calls mapper ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "localizer"], }, } // mapper/peppy.json5 { peppy_schema: "node/v1", manifest: { name: "mapper", tag: "v1", description: ["A mapper: it gives the obstacle nearest to a point, and asks the localizer for the pose of the robot."], implements: [ { name: "obstacle_service", tag: "v1", link_id: "obstacles_out" }, // provides nearest_obstacle ], depends_on: { contracts: [ { name: "pose_service", tag: "v1", link_id: "pose" }, ], }, }, interfaces: { services: { exposes: [ { link_id: "obstacles_out", name: "nearest_obstacle" }, ], consumes: [ { name: "current_pose", link_id: "pose" }, // calls localizer ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "mapper"], }, } ``` * Rust localizer/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "localizer", tag: "v1", description: ["A localizer: it gives the pose of the robot on the map, and asks the mapper for the nearest obstacle."], implements: [ { name: "pose_service", tag: "v1", link_id: "pose_out" }, // provides current_pose ], depends_on: { contracts: [ { name: "obstacle_service", tag: "v1", link_id: "obstacles" }, ], }, }, interfaces: { services: { exposes: [ { link_id: "pose_out", name: "current_pose" }, ], consumes: [ { name: "nearest_obstacle", link_id: "obstacles" }, // calls mapper ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/localizer"], }, } // mapper/peppy.json5 { peppy_schema: "node/v1", manifest: { name: "mapper", tag: "v1", description: ["A mapper: it gives the obstacle nearest to a point, and asks the localizer for the pose of the robot."], implements: [ { name: "obstacle_service", tag: "v1", link_id: "obstacles_out" }, // provides nearest_obstacle ], depends_on: { contracts: [ { name: "pose_service", tag: "v1", link_id: "pose" }, ], }, }, interfaces: { services: { exposes: [ { link_id: "obstacles_out", name: "nearest_obstacle" }, ], consumes: [ { name: "current_pose", link_id: "pose" }, // calls localizer ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/mapper"], }, } ``` The two caller-driven edges close a cycle: ```plaintext localizer ── calls obstacle_service (nearest_obstacle) ──▶ mapper ▲ │ └────────── calls pose_service (current_pose) ◀──────────┘ ``` Whichever node is added second is rejected at add time with a `ServiceActionContractCycle` error. The offending node is **not** committed and the stack is left unchanged: ```plaintext service dependency cycle through contracts involving localizer:v1 -> mapper:v1 (closing dependency `obstacle_service:v1`). service request/response cycles deadlock and are not allowed; only topics may be bidirectional. If these providers are not actually cross-bound, pin the binding or split the contract. ``` The same rejection applies however you wire it: directly through `depends_on.nodes`, through contracts, through the launcher (`peppy stack launch`), or incrementally across separate commands. Bringing the nodes up one at a time does not relax the rule: the first node is added because its provider is not present yet, but the moment the second node makes both directions resolvable, the daemon’s stack-wide check sees the cycle and rejects that second node. ### Two properties of the check [Section titled “Two properties of the check”](#two-properties-of-the-check) * **It is conservative (type-level).** The check reasons about node identities and their declared `implements`, not about which producer a specific `--link` resolves to. If a service or action contract has several implementing providers and only one of them closes a cycle, the configuration is still rejected, because *any* implementing provider could be bound into the cyclic slot. If you hit this, pin the binding to a non-cyclic provider or split the contract so the cyclic capability is not declared on the shared contract. * **Topics never count.** Only links consumed as a *service* or *action* contribute a caller-driven edge. The very same two nodes wired to consume each other’s `link_id` as a **topic** are accepted, because passive subscriptions cannot deadlock, which is exactly what [pairing](/advanced_guides/pairing/) relies on. ### How to fix it [Section titled “How to fix it”](#how-to-fix-it) If the two nodes genuinely need to exchange data, model it without a caller-driven cycle: * Make at least one direction a **topic** stream rather than a service or action: passive subscriptions never deadlock. If the two nodes form an exclusive 1:1 relationship, model both directions as a [pairing](/advanced_guides/pairing/). * Or model the request/response exchange as an [action](/advanced_guides/actions/), which is one-directional by construction (the client depends on the server), so it never needs a back-edge. See [Why topics only?](/advanced_guides/pairing/#why-topics-only) for the full rationale behind the topic/service/action distinction. ## What contract implementation is not [Section titled “What contract implementation is not”](#what-contract-implementation-is-not) * **Implementation is explicit.** A node that natively emits `video_stream` but does not declare `implements: [{ depth_camera, v1, link_id }]` does **not** satisfy a `depth_camera:v1` contract slot, even if every field matches. The contract is the explicit `implements` claim plus the explicit per-member entries, not structural duck typing. * **Node identity is irrelevant.** A producer whose node name and tag coincidentally equal a contract’s `(name, tag)` is treated like any other producer: it only satisfies the slot if it declares `implements`. The reverse is also true: a producer named `realsense_d405:v1` satisfies a `depth_camera:v1` slot as soon as it implements the contract. * **Implementation does not flow through node deps.** `depends_on.nodes` still names a specific producer node by `(name, tag)` and exposes only that node’s *native* interfaces; `depends_on.contracts` is what introduces implementation-based matching and contract-addressed consumption. The two coexist on the same consumer. # Core node functions > Inspect a running Peppy stack from your own code: uptime, host, the live node graph, and the daemon interfaces of its daemon targets Every Peppy stack has a **core node** that tracks which nodes have been added, which instances are running, and a few facts about the host it is running on. `peppylib` exposes two helpers that let any node query the core node at runtime: * `info`: a typed snapshot of the core node (uptime, hostname, node count, git version, container runtimes). * `stack.list`: the live node graph, with the serving daemon’s hostname and every node’s owning core node, stage, and running instances. `info` is a single top-level call; `stack.list` and the `StackList` type it returns live in the `stack` submodule. They are available from Rust as `peppylib::info`, `peppylib::stack::list`, and `peppylib::stack::StackList`, and from Python as `from peppylib import info` and `from peppylib import stack` (then `stack.list`, `stack.StackList`). They are not re-exported by `peppygen`; import them from `peppylib` directly. Both take a `NodeRunner`, the same handle your node receives from `NodeBuilder::new().run(...)` (see the [services guide](/advanced_guides/services/) for a typical setup). A node also calls the daemon interfaces of peppy, such as the fleet listing and the leases of `robot_leases:v1`, through the [daemon targets](#daemon-targets) of its manifest, with the client that `peppygen` generates for them. ## When to use these [Section titled “When to use these”](#when-to-use-these) * **Runtime introspection of instances.** A node can call `stack.list` to discover, at runtime, how many instances of a given dependency are currently up and what their instance IDs are. A router or load-balancer node, for example, can iterate `graph.nodes`, find the entry whose `name` matches its target, and read `instances` (keeping only those whose `state` is `"running"`) to decide where to dispatch work. * **Health checks and dashboards.** `info` returns uptime, hostname, node count, git version, and container runtime versions, enough to drive a status page or a liveness probe without scraping logs. * **Topology inspection.** `stack.list` returns nodes and dependency edges as structured data, so tooling can filter, render, or analyze the graph without scraping CLI output. * **Tests and tooling.** Integration tests or CLI utilities that need to assert “node X is up with N instances” or “edge A→B exists in the graph” can use the same helpers production code does. ## `info` [Section titled “info”](#info) `info` polls the core node’s `info` service and returns a typed response. The response carries: * `uptime_secs`: how long the core node has been up, in seconds. * `core_node_name`, `core_node_instance_id`: identity of the core node. * `host_name`: the machine hosting the core node. * `node_count`: how many nodes are currently in the stack. * `git_version`: the Peppy build the core node was compiled from. * `container_info.apptainer_version`, `container_info.lima_version`: container runtime versions. * `messaging_port`: the port the messaging layer is listening on. The second argument is a timeout. Rust accepts anything that converts to `Option`; Python accepts a `float` in seconds. Pass `None` (or omit it in Python) to use the default of 10 seconds. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib import info async def setup(_params: Parameters, node_runner: NodeRunner) -> None: response = await info(node_runner, 3.0) print( f"{response.core_node_name} on {response.host_name}: " f"{response.node_count} nodes, up {response.uptime_secs}s" ) def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::info; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let response = info(&node_runner, Duration::from_secs(3)).await?; println!( "{} on {}: {} nodes, up {}s", response.core_node_name, response.host_name, response.node_count, response.uptime_secs, ); Ok(()) }) } ``` ## `stack.list` [Section titled “stack.list”](#stacklist) `stack.list` returns a `StackList` with eight fields: * `graph`: the node graph, with every node’s metadata and its tracked instances. * `copies`: the copies the serving daemon runs. * `copy_change`: the join or the removal of a copy that holds the serving daemon’s stack now, with its `action` (`join` or `remove`), the copy’s `name` and its `option`; none while no such change runs. A copy that joins is in `copies` only once its join ends. * `launch_copies`: the copies the launch of the serving daemon’s stack started, each as the launch started it, in the form of `copies`. A join or a removal leaves them as they are. * `shutdown_grace_secs`: the serving daemon’s cooperative shutdown grace. * `core_node`: the core-node name of the daemon that served this stack snapshot. * `instance_id`: the serving daemon’s own generation instance id. * `host_name`: the hostname of the daemon that served this stack snapshot. Each node entry carries its required `core_node` owner plus its `name`, `tag`, `config_path`, optional `artifact_path`, `stage` (`Added`, `Building`, `Ready`, or `Root`), and its `instances`. Each instance has an `instance_id`, a `state` (`starting`, `running`, `restarting` while the daemon waits to start it again, or the terminal `finished` / `failed`), a `healthy` flag, its `slot_bindings`, and its `pairing_slots`. A router or load-balancer keeps only the `running` ones, which excludes both still-warming and already-exited instances. Its [restart policy](/guides/launch_files/#restart-policy) comes with it: `restart`, the policy as a launcher writes it (`"on_failure"`, or `{ policy, max_restarts }` with a cap); `restart_origin`, the level that set it (`instance`, `flag`, `node`, `launcher_root` or `default`); `restart_count`, the times a restarted process reached `running`; `attempt`, the count of restart attempts in a row that `max_restarts` caps (0 before the first exit the policy restarts; each such exit or failed start takes the next, and one after a run of two minutes or more takes attempt 1 again, where a run the health monitor ended counts only up to its last answered health check; at the cap it names the attempt refused; an exit `peppy node remove` asked for sets 0, and any other exit the policy does not restart leaves it as it was); `last_exit`, how the last start ended, a process’s exit or a start failure (`{ code }`, `{ signal: { number, name, core_dumped } }`, `{ health_kill: { unanswered_secs } }` or `{ message }`, null before any exit); and `running_since_ms` and `next_start_ms`, milliseconds since the Unix epoch, null when there is none. The graph’s `edges` list the dependency relationships, with each edge pointing from one node entry to another. The list covers both direct `depends_on.nodes` dependencies and those resolved through [contract implementation](/advanced_guides/contract_implementation/): a contract edge carries a `via_contract` of `name:tag` (the contract it was resolved through), while a direct edge has none. Rust and Python expose the graph differently: * In Rust, `result.graph` is a typed `SerializedNodeGraph` with `nodes: Vec` and `edges: Vec`. Field access is direct (`node.name`, `node.instances`), and an instance’s restart fields sit on its `restart_status` (`instance.restart_status.restart_count`), whose policy reads through `restart.policy()` and `restart.max_restarts()`. * In Python, `result.graph` is a plain `dict` of the same shape: `{"nodes": [...], "edges": [...]}`. Access fields by key (`node["name"]`, `node["instances"][0]["state"]`). The example below uses `stack.list` to count the running instances of each node and print their IDs, a typical pattern for a router or load-balancer node that needs to dispatch work across instances of a dependency. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib import stack async def setup(_params: Parameters, node_runner: NodeRunner) -> None: result = await stack.list(node_runner, 3.0) print(f"served by {result.host_name}") for node in result.graph["nodes"]: running = [i for i in node["instances"] if i["state"] == "running"] print( f"{node['name']} on {node['core_node']} ({node['stage']}): " f"{len(running)} running instance(s)" ) for instance in running: print(f" - {instance['instance_id']}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::stack; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let result = stack::list(&node_runner, Duration::from_secs(3)).await?; println!("served by {}", result.host_name); for node in &result.graph.nodes { println!( "{} on {} ({:?}): {} running instance(s)", node.name, node.core_node, node.stage, node.running_instance_ids().len(), ); for instance_id in node.running_instance_ids() { println!(" - {instance_id}"); } } Ok(()) }) } ``` ### Looking up instances by `(name, tag)` [Section titled “Looking up instances by (name, tag)”](#looking-up-instances-by-name-tag) When you know which dependency you want, skip the manual iteration with `running_instance_ids_by_node(name, tag)`, exposed on the `StackList` result in Python and on `result.graph` in Rust. The Rust signature is `Result, NodeNotFound>`; Python raises `KeyError` for the same condition. In both languages, an empty list (not an error) means the node is present but none of its instances is `running`: each is `starting`, `restarting`, or `finished` or `failed` for good. A router can back off while one starts or restarts, and read the states in the graph to tell a node that is coming back from one that is not. * Python src/my_node/\_\_main\_\_.py ```python result = await stack.list(node_runner, 3.0) try: ids = result.running_instance_ids_by_node("router_target", "v1") except KeyError as e: print(e) else: if ids: print(f"dispatch to {ids}") else: print("router_target:v1 is present but none of its instances is running") ``` * Rust src/main.rs ```rust let result = stack::list(&node_runner, Duration::from_secs(3)).await?; match result.graph.running_instance_ids_by_node("router_target", "v1") { Ok(ids) if !ids.is_empty() => println!("dispatch to {ids:?}"), Ok(_) => println!("router_target:v1 is present but none of its instances is running"), Err(err) => println!("{err}"), } ``` Note Both `info` and `stack.list` default to a 10-second timeout. Pass an explicit timeout when calling from a latency-sensitive path so a slow or unreachable core node does not stall your node. ## Daemon targets [Section titled “Daemon targets”](#daemon-targets) A node calls a **daemon interface**, an interface that the peppy daemon serves and no node implements, through a **daemon target** of its manifest. A daemon interface is a document in the contract format that is compiled into `peppy`. [The interfaces peppy serves](/advanced_guides/mcp/#the-interfaces-peppy-serves) lists them. For example, `robot_leases:v1` holds the fleet listing, the leases of the robots and the halt of the stack (see [Robot leases and the halt](/advanced_guides/fleet/)). ### Declaring a daemon target [Section titled “Declaring a daemon target”](#declaring-a-daemon-target) `manifest.depends_on.daemon` lists the daemon targets of the node. Each entry names the interface by `name` and `tag`, and the slot of the target by `link_id`. The node lists the members that it calls in the `consumes` lists of its `interfaces` with that `link_id`, as it does for a [contract slot](/advanced_guides/contract_implementation/#3-a-consumer-that-depends-on-the-contract). This lease holder lists the fleet, takes robots and holds a `lease` goal: * Python lease_holder/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "lease_holder", tag: "v1", description: ["A lease holder: it lists the robots of the fleet and leases them, through the daemon. It needs no device."], depends_on: { daemon: [{ name: "robot_leases", tag: "v1", link_id: "fleet" }], }, }, interfaces: { services: { consumes: [ { link_id: "fleet", name: "list" }, { link_id: "fleet", name: "take" }, ], }, actions: { consumes: [{ link_id: "fleet", name: "lease" }], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "lease_holder"], }, } ``` * Rust lease_holder/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "lease_holder", tag: "v1", description: ["A lease holder: it lists the robots of the fleet and leases them, through the daemon. It needs no device."], depends_on: { daemon: [{ name: "robot_leases", tag: "v1", link_id: "fleet" }], }, }, interfaces: { services: { consumes: [ { link_id: "fleet", name: "list" }, { link_id: "fleet", name: "take" }, ], }, actions: { consumes: [{ link_id: "fleet", name: "lease" }], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/lease_holder"], }, } ``` - **Never pinned.** An entry takes no `sha256`. The document of the interface ships with the peppy release that serves its tag, and peppy serves one tag of each interface. - **One producer.** An entry takes no `cardinality`. The daemon that serves the interface is the one producer of the slot: the daemon of the coordinator of the launch that started the instance, or the daemon that runs an instance of no launch. The daemon binds the slot each time the instance starts, by a launch, a join, `peppy node run` or a restart, under the core node name and the per-boot instance id of that daemon. A launcher writes no `links` entry for a daemon target, and a launch refuses one. - **One target of each interface.** A node names each interface once. A call names no target, so a call of an interface goes with the one scope of that interface that the instance has. - **One link_id namespace.** The `link_id` of a daemon target shares one namespace with the other slots of `depends_on` and with `implements`. The add and the sync of the node read the members of the interface from the document compiled into `peppy`, never from the contract cache. They refuse an entry that names an interface or a tag that this peppy does not serve, with the interfaces and the tags that it serves, and a consumed entry that names no member of the interface. The `instance_documents` service, which `peppy node describe` reads, gives the document of each daemon target of an instance after its pinned contract documents. ### The client of a daemon target [Section titled “The client of a daemon target”](#the-client-of-a-daemon-target) The generator writes the client of each consumed member as for a contract slot, under the `link_id` of the target: `consumed_services//` and `consumed_actions//`. `bound_producer()` gives the daemon, and each call goes to the daemon as the provider of the interface. Each member gives the failure kinds of the interface that it lists, beside the kinds of peppy: `take` of `robot_leases:v1` gives `halted` and `leased`. * Python src/lease_holder/\_\_main\_\_.py ```python from peppygen.consumed_actions.fleet import lease from peppygen.consumed_services.fleet import list as fleet_list from peppygen.consumed_services.fleet import take async def hold_leases(node_runner) -> None: daemon = fleet_list.bound_producer(node_runner) fleet = await fleet_list.poll(node_runner, daemon, 5.0) goal = await lease.ActionHandle.fire_goal(node_runner, daemon, 5.0) if goal.refusal is not None: print(f"the lease goal is refused: {goal.refusal.message}") return for robot in fleet.data.robots: try: await take.poll(node_runner, daemon, take.Request(robot=robot.name, name="a run"), 5.0) except take.Failure as failure: if failure.kind not in (take.FailureKind.LEASED, take.FailureKind.HALTED): raise print(failure.message) feedback = await goal.on_next_feedback_message() print(feedback.event, feedback.robot, feedback.cause) await goal.cancel_goal(5.0) ``` * Rust src/main.rs ```rust use peppygen::consumed_actions::fleet::lease; use peppygen::consumed_services::fleet::{list, take}; use std::time::Duration; async fn hold_leases(node_runner: &peppygen::NodeRunner) -> peppygen::Result<()> { let daemon = list::bound_producer(node_runner); let fleet = list::poll(node_runner, daemon, Duration::from_secs(5)).await?; let mut goal = lease::ActionHandle::fire_goal( node_runner, daemon, Duration::from_secs(5), peppygen::DEFAULT_FEEDBACK_BOUND, ) .await?; if let Some(refusal) = &goal.refusal { println!("the lease goal is refused: {}", refusal.message); return Ok(()); } for robot in &fleet.data.robots { let request = take::Request::new(robot.name.clone(), "a run".to_owned()); match take::poll(node_runner, daemon, Duration::from_secs(5), request).await { Ok(()) => println!("leased {}", robot.name), Err(error) => match take::Failure::of(&error) { Some(take::Failure { kind: take::FailureKind::Leased | take::FailureKind::Halted, message, }) => println!("{message}"), _ => return Err(error), }, } } let feedback = goal.on_next_feedback_message().await?; println!("{} {} {}", feedback.event, feedback.robot, feedback.cause); goal.cancel_goal(Duration::from_secs(5)).await?; Ok(()) } ``` A long goal of an interface, such as `changes` and `lease` of `robot_leases:v1`, runs until its client cancels it. The handle of the goal keeps every feedback message until the client reads it, up to the feedback bound of `fire_goal`. A client that reads the feedback and falls behind by more messages than its bound cancels the goal, and its next read gives the loss as an error (see [Receiving feedback](/advanced_guides/actions/#receiving-feedback)). ### Scoping a daemon target [Section titled “Scoping a daemon target”](#scoping-a-daemon-target) The launcher gives each daemon target of an instance a scope in the [`daemon_scopes`](/guides/launch_files/#daemon_scopes-optional) of the instance, keyed by the `link_id` of the target, or with a `set_daemon_scopes` adjustment on the instance. `{ vacant: "" }` leaves the target unserved. A `robot_leases` scope names the members of `robot_leases:v1` that the client may call: `members` names at least one of `list`, `contract`, `changes`, `lease`, `check_move`, `halt` and `clear_halt`, each once, and `lease` brings `take`, `release`, `offer`, `open` and `close`. peppy_launcher.json5 ```json5 { peppy_schema: "launcher/v1", description: ["A lease holder that may list the fleet, lease its robots and check a move. It needs no device."], deployments: [ { source: { name: "lease_holder", tag: "v1" }, instances: [ { instance_id: "lease_holder", daemon_scopes: { fleet: { members: ["list", "lease", "check_move"] } }, }, ], }, ], } ``` The launch, each join and `peppy stack resolve` hold each daemon target of a node to [the checks of daemon scopes](/guides/launch_files/#daemon_scopes-optional) before anything starts. The instance runs on the coordinator, the machine of the daemon that runs the stack, outside every [copy](/guides/launch_files/#copies), so it declares no `core_node`, and the option of an axis that runs as copies does not deploy it. `peppy node run` of the node starts its instance with no scope: only a launcher gives scopes. # Daemon configuration > Configure a Peppy-managed or operator-run Zenoh router, messaging behavior, node lifecycle grace periods, the PyPI mirror of Python builds, the OCI repository nodes are published to, and the OpenTelemetry log export through peppy_config.json5 By default, the Peppy daemon reads one global configuration file, `~/.peppy/conf/peppy_config.json5`. It sets the daemon’s core-node name, selects either a Peppy-managed or operator-run Zenoh router, controls the managed router’s messaging behavior, defines the grace periods that govern node lifecycle, can name a PyPI mirror for Python builds, can name the OCI repository that container nodes are published to, and can name an OpenTelemetry endpoint the daemon exports its log files to. The daemon applies it to its own core-node session and to every node it spawns. The same file also records the backend resource-server URL the `peppy platform` commands talk to; that block is read by the CLI, not the daemon. [`PEPPY_CONFIG`](#override-with-peppy_config) can supply a read-only alternative source. Note The daemon reads its settings (`core_node_name`, `zenoh`, `lifecycle`, `pypi_mirror`, `publish_repository`, `otlp_endpoint`, `otlp_min_severity`) from the active source **once, at daemon startup**. Editing them has no effect on a running stack; restart the daemon (`peppy service serve`, or `systemctl restart` your service) to apply changes. The `resource_servers` block in the active source is read fresh by each `peppy platform` command, so an edit there takes effect on the next one without a daemon restart. ## How the file is managed [Section titled “How the file is managed”](#how-the-file-is-managed) In the normal on-disk flow, you never need to create or migrate this file by hand: * **First load.** If the file does not exist, Peppy creates it with every setting at its default value, annotated with explanatory comments. * **Missing settings.** If the file exists but omits settings this release defines, Peppy detects every omission and appends each setting it can safely place, together with its default value and comments. Your own values, comments, formatting, and any unrecognized top-level keys are otherwise preserved exactly as you wrote them; when appending defaults, completion may add a structural separator comma after the prior final entry. Peppy logs each setting it added. An unusual JSON5 spelling or layout, such as an escaped section key that the text scanner cannot safely pair with its block, produces a warning naming every setting that could not be inserted; the daemon continues with those defaults in memory. Fields required inside a non-default variant are not invented: if you select `zenoh.external`, you must supply `zenoh.external.endpoint`. * **Malformed file.** If the file cannot be parsed, or a value is out of range, Peppy refuses to continue and reports the error instead of silently falling back to defaults. A file that fails to load is never modified. In a normally spelled section, a defaulted setting you delete from the file therefore comes back with its default the next time Peppy loads the configuration. To change one, edit its value instead of removing it. If Peppy warns that an unusual spelling or layout prevented insertion, add the named setting manually if you want it written; the daemon already uses its default in memory. Removing `zenoh.external.endpoint` from an external block instead makes the file invalid and leaves it untouched. ### Override with `PEPPY_CONFIG` [Section titled “Override with PEPPY_CONFIG”](#override-with-peppy_config) Set `PEPPY_CONFIG` to inject the complete daemon configuration at launch. A non-empty value has two forms: a path to a JSON5 config file, or an inline JSON5 document. Peppy expands `~` and `~/` in path form, and resolves relative paths from the command’s current working directory, which is the daemon’s working directory for `peppy service serve`. Classification always tries the value as a file first. If the file can be read, file form is committed, so a later parse, validation, or completeness error does not fall back to interpreting the path text as inline JSON5. Only a file read or path-expansion failure triggers the inline parse. If both attempts fail, the error reports both reasons. An empty value is treated as unset and uses the normal file flow; whitespace alone is not empty and fails if it is neither a readable path nor valid inline JSON5. An override is read-only. Peppy ignores `$PEPPY_HOME/conf/peppy_config.json5` and never creates, completes, or rewrites either that file or the override source. The override must parse, pass validation, and explicitly spell out every setting the running release defines. Missing settings are a startup error that names their paths and explains that override sources are never completed with defaults. This differs from the normal on-disk flow, which appends safe defaults and warns when an unusual source spelling prevents an insertion. The override applies to `peppy service serve` and to every `peppy platform` command, all of which read the daemon configuration. `PEPPY_HOME` still controls credentials, repositories, and all other Peppy state. Edits to a file-form override take effect on the daemon’s next restart, just like edits to the default file. Both examples below use the same complete config file. The second passes its full contents inline, including any leading JSON5 comments: ```sh PEPPY_CONFIG=./deploy/peppy_config.json5 peppy service serve PEPPY_CONFIG="$(cat ./deploy/peppy_config.json5)" peppy service serve ``` ## The default file [Section titled “The default file”](#the-default-file) ```json5 // Daemon settings are read once at startup, so edits to them take effect only // after restart. resource_servers is refreshed by each CLI authentication command. { // Fixed name for this daemon's core node, or null to derive a // machine-specific default (cn-...). Names must be unique across all // daemons reachable over the same router/federation: a daemon whose name is // already in use refuses to boot. At most 63 characters from // "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-". // `peppy service serve --core-node-name` overrides this for one run. core_node_name: null, // The zenoh messaging transport. Configure exactly one of two blocks: // managed: peppy starts, monitors, restarts, and stops its bundled // zenohd router, and every knob inside `managed` applies. // external: you run the router and peppy only dials it; peppy never // starts, reconfigures, restarts, stops, or federates it, // local nodes always relay through it, and the managed knobs // do not exist. Spelled, in place of `managed`, as: // external: { endpoint: "tcp/:" }, zenoh: { // Settings peppy can only honor because it owns the router process. Replace // this whole block with `external` to use your own router. managed: { // How the nodes on this machine exchange data with each other. Traffic to // and from other machines always relays through the local zenohd router and // its federation, regardless of this setting (each node seeds gossip from // the local router, so direct peer links form only between co-located nodes). // "peer" - Zenoh peer sessions with gossip: local nodes form direct // peer-to-peer links and data stops relaying through the router. // Each session binds a wildcard listener on an ephemeral port, // reachable from the network. // "router" - gossip off: all traffic relays through the central zenohd // router, and a session binds no listener of its own. // Container nodes in a separate network namespace (Lima on macOS) always use // the router path regardless of this setting. local_nodes_topology: "peer", // Subscriber channel buffer sizes (number of in-flight messages) per QoS // tier, used by local node sessions in both managed topologies. They matter // most in peer mode, where no router relay buffers between a publisher and // a subscriber. Defaults match peppy's built-in behavior; only edit to tune // backpressure. subscriber_buffers: { standard_buffer_size: 128, high_throughput_buffer_size: 1024, }, }, }, lifecycle: { // Node lifecycle knobs. `daemon_grace_secs` is the grace period a spawned node // waits, after the daemon's heartbeat goes silent, before shutting itself down // to avoid orphaning. daemon_grace_secs: 180, // How long a clean shutdown (ctrl+C / `systemctl stop`) and `peppy node // stop` wait for a node to exit cooperatively before force-killing its // process group. Seconds; minimum 1. A robot node uses this window to park // actuators and release hardware before it is killed. shutdown_grace_secs: 5, }, // Packages base URL of a PyPI mirror, or null. When set, Python node builds // download the PyPI files that their uv.lock pins from this mirror, and a file // the mirror does not have still comes from files.pythonhosted.org. uv checks // every file against the sha256 in the lock. Example: // "https://pypi.tuna.tsinghua.edu.cn/packages/". pypi_mirror: null, // The OCI repository that `peppy node publish` and `peppy stack build // --publish` push the .sif of container nodes to, for example // "oci://ghcr.io/acme/peppy-nodes", or null to publish nothing. publish_repository: null, // OTLP/HTTP URL of an OpenTelemetry collector or an intake, or null. When set, // the daemon exports the launch, add, build, run and stack logs to // /v1/logs, or to the URL as written when its path already // ends in /v1/logs. Request headers, such as an API key, go in // ~/.peppy/conf/otlp_headers.json5. Example: "http://localhost:4318". otlp_endpoint: null, // Lowest severity the daemon exports, or null to export every line. One of // "trace", "debug", "info", "warn". A line below it stays in its log file // only. A line that prints no level is always exported. otlp_min_severity: null, // The certificate of this machine from a CA of the operator of its federation, // or null. The daemons of a federation prove their calls to each other with // it; null uses the platform certificate of an enrolled machine. Absolute // paths, example: { trust_anchor: "/etc/peppy/ca.crt", certificate: // "/etc/peppy/machine.crt", private_key: "/etc/peppy/machine.key" }. machine_certificate: null, // Backend resource-server URL the `peppy platform` commands talk to. Baked in // at compile time (the dev backend in debug builds, prod in release); // --api-url / PEPPY_API_URL override it at runtime. resource_servers: { api: "https://api.peppy.bot", }, } ``` ## `core_node_name`: the daemon’s core-node name [Section titled “core_node_name: the daemon’s core-node name”](#core_node_name-the-daemons-core-node-name) `core_node_name` fixes the name of this daemon’s [core node](/reference/concepts/#the-core-node). Leave it `null` (the default) and the daemon derives a stable, machine-specific name of the form `cn-{adjective}-{animal}`; set a string to pin an explicit one. Core-node names must be **unique across every daemon reachable over the same router or federation**. Each daemon advertises an ephemeral presence token; on boot it refuses to start if that name is already live, and while running it logs a rate-limited collision alarm if another daemon later claims the same name. If two daemons end up sharing a name, give one of them a unique `core_node_name` (or pass `peppy service serve --core-node-name ` for a single run) and restart it. This most commonly matters when enrolling federates several machines into one project, or when cloning a disk image reuses another machine’s derived name. The value must be non-empty, at most **63 characters**, and use only the node-name character set (letters, digits, `_`, `-`); the literal name `self` is reserved and rejected. An invalid value stops the daemon at startup with an error instead of failing later when the core node boots. `peppy service serve --core-node-name ` overrides the config for one run (the flag wins over the file); if both are absent, the derived default is used. ## `zenoh`: managed or external router [Section titled “zenoh: managed or external router”](#zenoh-managed-or-external-router) The `zenoh` section holds exactly one of `managed` or `external`. Block presence selects the mode. `managed` is the default: omitting `zenoh` or writing `zenoh: {}` loads all managed defaults, and normal file completion materializes the explicit `managed` block. Use `managed` when Peppy should start, monitor, restart, and stop its bundled `zenohd`: ```json5 zenoh: { managed: { local_nodes_topology: "peer", subscriber_buffers: { standard_buffer_size: 128, high_throughput_buffer_size: 1024, }, }, }, ``` Use `external` when Peppy should dial a router that you run: ```json5 zenoh: { external: { endpoint: "tcp/127.0.0.1:7448", }, }, ``` The managed knobs exist only because Peppy controls that router process. Under `external`, `local_nodes_topology` and `subscriber_buffers` are not part of the document, and writing them is an error. Local nodes always relay through the external router, local subscriber queues use Peppy’s built-in capacity defaults, and router federation belongs entirely to the operator. ## `zenoh.managed.local_nodes_topology`: local messaging topology [Section titled “zenoh.managed.local_nodes_topology: local messaging topology”](#zenohmanagedlocal_nodes_topology-local-messaging-topology) `zenoh.managed.local_nodes_topology` selects how the nodes **on this machine** exchange data with each other: * **`"peer"`** (default): nodes run Zenoh peer sessions with gossip discovery enabled. After discovery, nodes form direct peer-to-peer links and data stops relaying through the central router, which removes a network hop from every message. * **`"router"`**: gossip is off and all traffic relays through the central `zenohd` router. Use this when direct node-to-node connectivity is unreliable or undesirable, or to simplify debugging by funneling all traffic through one process. The setting is local by construction, which is why it carries the `local_nodes_` prefix: each node seeds gossip discovery from the local router, so a peer session only ever discovers, and forms direct links with, sessions co-located on this machine. Traffic to and from nodes on other machines always relays through the local router and its link to the project’s cloud router (see [Platform](/advanced_guides/platform/#enrolling)), whichever topology you pick. In `"peer"` mode a session binds a wildcard listener (`0.0.0.0` on an ephemeral port) so Zenoh can advertise the host’s routable interface addresses for those direct links; that listener is therefore reachable from the network, not confined to loopback. This widens an existing exposure class rather than opening a new one: the Zenoh transport is unauthenticated, and the managed router’s own listener already binds `0.0.0.0`. The calls to a daemon carry the signature of their sender, which the daemon verifies, so a program on the network cannot call a daemon as one of its clients (see [The senders of the calls to a daemon](/advanced_guides/call_senders/)); topics and the calls between nodes carry no signature. Only `"router"` mode leaves a session with no listener at all, because with gossip off nothing needs to advertise a dialable address, so pick it for a deployment that must not accept inbound peer links. [Container nodes](/advanced_guides/containers/) that live in a separate network namespace (such as the Lima VM peppy uses on macOS) always take the router path, regardless of this setting: gossip cannot establish direct links across the namespace boundary. ## `zenoh.managed.subscriber_buffers`: subscriber buffer sizes [Section titled “zenoh.managed.subscriber_buffers: subscriber buffer sizes”](#zenohmanagedsubscriber_buffers-subscriber-buffer-sizes) Each Peppy subscriber buffers in-flight messages in a bounded process-local queue. The `zenoh.managed.subscriber_buffers` block sets that queue’s capacity (number of messages, not bytes) per QoS tier: * **`standard_buffer_size`** (default `128`): the local queue for topics on the standard QoS tier, which most topics use. The same capacity also sizes the queues behind service requests and replies. * **`high_throughput_buffer_size`** (default `1024`): the local queue for topics on the high-throughput QoS tier, such as sensor-data streams, where short bursts well above the average rate are normal. These sizes do not apply to [action feedback](/advanced_guides/actions/#receiving-feedback): the client of a goal keeps every feedback message until it reads it, up to the feedback bound it passes to `fire_goal`. These are local Peppy queue capacities, not Zenoh router buffers, and they apply under both managed local topologies. They matter most in the peer topology: with nodes peering directly there is no router relay between a publisher and a subscriber, so the local queue is all that absorbs a burst. When a topic subscriber falls behind and its local queue fills up, its session stops taking messages from the connection the topic arrives on until the subscriber takes one. This holds up every message on that connection, not only the topic’s: in the router topology that is all of the node’s traffic; in the peer topology it is the traffic from the publishing peer, or from the router for a publisher on another machine. Once the network buffers of that connection are full, the stall reaches the sending side: messages published with the `standard` or `sensor_data` profile are dropped there, and messages published with the `reliable` or `critical` profile wait for room. When one of them waits five seconds, Zenoh closes the connection to the slow session. An action goal’s feedback buffer never makes its session wait: when the caller falls behind by more unread messages than its bound, the buffer drops the unread messages, a caller that reads the feedback cancels the goal, and its next read gives the loss as an error. The subscriptions of the [test harness](/advanced_guides/testing/#emitted-topics) to a node’s emitted topics, and those of its pairing mocks, do the same. Raise a capacity to absorb longer bursts at the cost of memory and worst-case latency; lower it to surface backpressure, or message loss, sooner. The defaults match Peppy’s built-in behavior, so you only need to touch this block to tune backpressure. A subscription to a topic that [retains](/advanced_guides/topics/#retaining-the-latest-value) holds at least as many messages as the topic retains, whatever these capacities say. Both values must be greater than `0`; the daemon rejects a zero buffer size at startup. ## `zenoh.external`: use an operator-run router [Section titled “zenoh.external: use an operator-run router”](#zenohexternal-use-an-operator-run-router) To use a router you start yourself, configure `zenoh.external` with the Zenoh endpoint Peppy should dial: ```json5 zenoh: { external: { endpoint: "tcp/127.0.0.1:7448", }, }, ``` `endpoint` is a **dial address**, not a listener bind address. It must use `tcp/:` with a hostname, an IPv4 address, or a bracketed IPv6 address, for example `tcp/router.internal:7448` or `tcp/[::1]:7448`. The port is required and must be from `1` through `65535`. Listener wildcards such as `0.0.0.0`, `[::]`, and `*` are rejected because Peppy cannot connect to them. Metadata/config suffixes and reserved delimiters (`?`, `#`, `;`, `=`) are rejected, and `tcp/` is the only supported transport. Peppy propagates this host and port to its CLI sessions and spawned nodes, so the address must be reachable from every environment that runs a node. For Lima containers on macOS, Peppy rewrites a host-local address such as `127.0.0.1` to the VM’s host gateway; a genuinely remote hostname or IP address is preserved. Start the external router before Peppy. Its listener may bind a wildcard even though Peppy’s dial endpoint must be connectable. For a router on the same machine, for example: ```sh zenohd -l tcp/0.0.0.0:7448 ``` At startup, Peppy requires a responsive Zenoh router at the configured endpoint. Nothing listening is a startup error; a non-Zenoh service at the address is a distinct startup error. Peppy observes a responsive router’s health but never kills it on daemon exit, restarts it after a failure, or changes its configuration to federate it to the cloud router. The operator controls the router’s lifecycle and federation. If it becomes unresponsive while the daemon is running, the watchdog logs a prominent warning but leaves it alone; sessions reconnect automatically after the operator restores it. `peppy platform enroll` and `unenroll` leave external federation untouched and print a note instead of poking the daemon. They do not restart the daemon; an enrollment change reaches its sessions on the next manual daemon restart. `PEPPY_MESSAGING_PORT` configures the listener for Peppy’s managed router, while external mode uses the port written in `zenoh.external.endpoint`. ## `machine_certificate`: the certificate of the machine [Section titled “machine_certificate: the certificate of the machine”](#machine_certificate-the-certificate-of-the-machine) The daemons of a federation prove their calls to each other with the certificates of their machines (see [Machines of a federation](/advanced_guides/call_senders/#machines-of-a-federation)). An enrolled machine uses the certificate of its enrollment and needs nothing here. A federation that the operator forms, through an operator-run router (`zenoh.external`) or through a router configuration that the operator pins, uses a CA of the operator: give the daemon of each machine its certificate. ```json5 machine_certificate: { trust_anchor: "/etc/peppy/ca.crt", certificate: "/etc/peppy/machine.crt", private_key: "/etc/peppy/machine.key", }, ``` Each path is absolute. `trust_anchor` is the CA, in PEM: the daemon checks the certificates of the other machines against it. `certificate` is the certificate of this machine, in PEM, then the certificates above it; its common name is the core node of this machine, and it allows client authentication when it names the extended key usages. `private_key` is its PKCS#8 private key, in PEM: ECDSA P-256, ECDSA P-384, Ed25519 or RSA. Keep the key where the container nodes do not mount it. A certificate that does not read stops the start of the daemon. `null` uses the platform certificate of an enrolled machine; a daemon with no certificate takes no call of another machine. ## `lifecycle`: grace periods [Section titled “lifecycle: grace periods”](#lifecycle-grace-periods) The `lifecycle` block tunes the two windows Peppy uses to guarantee that no node outlives the daemon. The full mechanics are described in [Daemon shutdown and orphan prevention](/guides/node_stack/#daemon-shutdown-and-orphan-prevention). * **`daemon_grace_secs`** (default `180`, minimum `30`): every spawned node runs a watchdog that listens for the daemon’s periodic heartbeat (published every 5 seconds). If the heartbeat goes silent for this many seconds, the node shuts itself down rather than lingering as an orphan. This only governs **unclean** daemon death (crash, OOM, `SIGKILL`); a clean shutdown does not wait for it. The minimum exists so a brief daemon stall or a restart of the daemon’s messaging router never trips every node’s watchdog. Only the heartbeats of the node’s own daemon restart this period: each daemon process draws an instance id when it starts and writes it into the runtime config of every node it starts. A new daemon does not wait for this period: a node shuts itself down at the first heartbeat of another daemon of its core node once its own daemon no longer holds its presence token, because the new daemon starts with an empty stack. * **`shutdown_grace_secs`** (default `5`, minimum `1`): the node’s cooperative-cleanup budget. A clean daemon shutdown (`Ctrl+C`, `systemctl stop`), `peppy node stop` and the stop of a starting instance that answered ready wait this window, plus a fixed allowance for the node’s runtime to finish tearing down (in Rust, the async runtime dropping; in Python, the event-loop join and interpreter finalize), before force-killing its process group. Raise it for nodes that need longer to park actuators or release hardware before dying; the force-kill deadline rises with it. ## `pypi_mirror`: PyPI mirror for Python builds [Section titled “pypi_mirror: PyPI mirror for Python builds”](#pypi_mirror-pypi-mirror-for-python-builds) `pypi_mirror` names a PyPI mirror that Python node builds download the PyPI files that their `uv.lock` pins from. Leave it `null` (the default) to download them from PyPI; set the packages base URL of a mirror to use it: ```json5 pypi_mirror: "https://pypi.tuna.tsinghua.edu.cn/packages/", ``` With a mirror set, each Python build that does not reuse a cached artifact asks the mirror for the files that its `uv.lock` pins from PyPI, and downloads each file the mirror has from the mirror. A file the mirror does not have still comes from PyPI, and uv checks every file against the sha256 in the lock, so a mirror cannot change what a build installs. See [PyPI mirror for Python builds](/advanced_guides/containers/#pypi-mirror-for-python-builds) for what the daemon changes, the line each build shows, and a list of mirrors. The value must be the **packages base URL** of the mirror: an `https` URL under which the mirror keeps the files of PyPI with the path layout of `https://files.pythonhosted.org/packages/`, so its path ends with `packages/`. The index URL of a mirror (ending with `/simple/`) is not a packages base URL. The URL must not hold credentials, a query, or a fragment. Any other value stops the daemon at startup with an error that names `pypi_mirror`. ## `publish_repository`: where nodes are published [Section titled “publish_repository: where nodes are published”](#publish_repository-where-nodes-are-published) `publish_repository` names the OCI repository that [`peppy node publish`](/advanced_guides/publishing/#publish-a-node) and [`peppy stack build --publish`](/advanced_guides/publishing/#publish-the-nodes-of-a-stack) push the `.sif` of container nodes to. Leave it `null` (the default) and both commands refuse to publish, with an error that names this setting; set the URL of a repository to publish to it: ```json5 publish_repository: "oci://ghcr.io/acme/peppy-nodes", ``` The value has the form `oci:///`, as the `url` of an [`oci` repository](/advanced_guides/repositories/#oci-repositories). The URL must not hold credentials, a query, or a fragment: the daemon reads the credentials of the registry from the auth file of Apptainer (see [Registry credentials](/advanced_guides/publishing/#registry-credentials)). Any other value stops the daemon at startup with an error that names `publish_repository`. In a `peppy stack build --publish`, each machine of the stack pushes to the `publish_repository` of the daemon that runs the command, and the setting of the other machines has no effect. The setting does not make this machine read the repository. To pull the nodes of the repository, add it with [`peppy repo add`](/advanced_guides/repositories/#add-a-repository). ## `otlp_endpoint`: export the log files [Section titled “otlp_endpoint: export the log files”](#otlp_endpoint-export-the-log-files) `otlp_endpoint` names the OTLP/HTTP endpoint the daemon exports its launch, add, build, run and stack logs to, as OpenTelemetry log records. Leave it `null` (the default) and the daemon exports nothing; set the URL of an OpenTelemetry collector or of an intake to turn the export on: ```json5 otlp_endpoint: "http://localhost:4318", ``` The value is the base URL of the collector or intake, and the daemon posts to `/v1/logs`; a URL whose path already ends with `/v1/logs` is the URL the daemon posts to. It must be an `http` or `https` URL with no credentials, query, or fragment. Any other value stops the daemon at startup with an error that names `otlp_endpoint`. Request headers, such as an API key, go in `~/.peppy/conf/otlp_headers.json5`, never in the URL. See [OpenTelemetry log export](/advanced_guides/opentelemetry/) for what is exported, the fields of a record, the headers file, and what happens while the endpoint is unreachable. ## `otlp_min_severity`: lowest exported severity [Section titled “otlp_min_severity: lowest exported severity”](#otlp_min_severity-lowest-exported-severity) `otlp_min_severity` holds the lowest severity the daemon exports: one of `"trace"`, `"debug"`, `"info"`, `"warn"`. Leave it `null` (the default) to export every line. A line below it stays in its log file only, and a line that prints no level is always exported. The setting goes up to `"warn"`: the stack log line that reports records the export discarded is a warning, and every setting exports it. The setting has no effect while `otlp_endpoint` is `null`. Any other value stops the daemon at startup with an error that names `otlp_min_severity` and lists the four names. See [Severity](/advanced_guides/opentelemetry/#severity) for how the daemon reads the severity of a line. ## `resource_servers`: backend URL [Section titled “resource_servers: backend URL”](#resource_servers-backend-url) This block holds the platform-backend base URL the CLI platform commands talk to. The daemon ignores it; the `peppy platform` commands read it. See [Platform](/advanced_guides/platform/) for the sign-in and enrollment flows. * **`api`** (default `https://api.peppy.bot` in release builds, `https://api.dev.peppy.bot` in debug): the backend the auth commands talk to. There is no dev/prod selection at runtime; the file stores exactly the build’s backend. The URL is resolved in precedence order: `--api-url`, then `PEPPY_API_URL`, then `api` here. An empty block falls back to the build’s default backend. In release builds, plain `http` is accepted only for local backends (loopback / `*.localhost`) and any other host must be `https`, validated when the command runs; debug builds accept remote plain `http` with a warning. ## Reference [Section titled “Reference”](#reference) | Setting | Default | Constraint | Effect | | -------------------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `core_node_name` | `null` (derived `cn-...`) | Non-empty, ≤ 63 chars, node-name charset, `self` reserved | Fixed name for this daemon’s core node; must be unique across all daemons on the same router/federation or the daemon refuses to boot. Overridable per run with `--core-node-name`. | | `zenoh.managed.local_nodes_topology` | `"peer"` | `"peer"` or `"router"` | Topology of this machine’s nodes: direct peer links with gossip, or relay everything through the central router. Cross-machine traffic always goes through the routers. | | `zenoh.managed.subscriber_buffers.standard_buffer_size` | `128` | `> 0` | Local Peppy subscriber queue capacity (messages) for standard-QoS topics; also sizes service request/reply queues. | | `zenoh.managed.subscriber_buffers.high_throughput_buffer_size` | `1024` | `> 0` | Local Peppy subscriber queue capacity (messages) for high-throughput-QoS topics such as sensor-data streams. | | `zenoh.external.endpoint` | No default | Required inside `external`; `tcp/:`; no wildcard host | Network endpoint of the operator-run router. Peppy dials it without changing its federation or managing its lifecycle. | | `machine_certificate` | `null` (the platform certificate of an enrolled machine) | `null`, or a block of the absolute paths `trust_anchor`, `certificate` and `private_key` | The certificate of this machine from a CA of the operator, which proves the calls of this machine to the daemons of the other machines and gives the CA that the daemon checks their calls against. | | `lifecycle.daemon_grace_secs` | `180` | `>= 30` | Seconds without a daemon heartbeat before a spawned node self-terminates (unclean daemon death only). | | `lifecycle.shutdown_grace_secs` | `5` | `>= 1` | Seconds a clean shutdown and `peppy node stop` wait for cooperative exit (plus a fixed runtime-teardown allowance) before force-killing. | | `pypi_mirror` | `null` (PyPI) | `null`, or an `https` URL whose path ends with `packages/`, with no credentials, query, or fragment | Packages base URL of the PyPI mirror Python builds download the PyPI files of their `uv.lock` from; a file the mirror does not have comes from PyPI. | | `publish_repository` | `null` (no publish) | `null`, or an `oci:///` URL with no credentials, query, or fragment | OCI repository that `peppy node publish` and `peppy stack build --publish` push the `.sif` of container nodes to. | | `otlp_endpoint` | `null` (no export) | `null`, or an `http` or `https` URL with no credentials, query, or fragment | OTLP/HTTP endpoint the daemon exports its log files to, as OpenTelemetry log records. | | `otlp_min_severity` | `null` (every line) | `null`, or one of `"trace"`, `"debug"`, `"info"`, `"warn"` | Lowest severity the daemon exports; a line that prints no level is always exported. | | `resource_servers.api` | `https://api.peppy.bot` (release), `https://api.dev.peppy.bot` (debug) | `https`, or `http` for local hosts | Backend the CLI auth commands talk to. Read by the CLI, not the daemon. | Both Zenoh variants at once, a value outside its constraint, an unsupported `zenoh.external.endpoint`, an unknown `zenoh.managed.local_nodes_topology` value, an unknown key inside `zenoh` or either variant, or a syntax error all stop the operation that loaded the configuration with an error pointing at the problem. An out-of-range value names the offending field, and a parse error reports the bad value or its position, so a typo can never silently revert your stack to defaults. Unknown top-level keys remain accepted and preserved. # Datastore > Share small values across nodes through the core node's in-memory key/value store Topics and services move data between nodes that are up at the same time. Sometimes you instead want a place to *leave* a value so another node can pick it up later, or so a node can read back what it wrote before it restarted. The **datastore** is that place: a small in-memory key/value store that lives in the core node and is shared by every node in the stack. `peppylib::datastore` exposes five helpers: * `store`: upsert a value under a key. * `store_exclusive`: store a value under a key and make the calling instance its only writer while its process runs. * `get`: read the value back, or `None` when the key holds no value. * `list`: list every key’s metadata (encoding and last writer), without the value bytes. * `remove`: delete a key, reporting whether it existed. Each value is a pair of *raw bytes* and an *encoding tag* (a short string such as `"text/plain"`, `"application/json"`, or `"application/octet-stream"`). This mirrors Zenoh’s `(payload, encoding)` value model: the store keeps your bytes verbatim and hands back the tag you chose, so any value type round-trips faithfully. The store never inspects either field. The store also records, for each key, the `instance_id` of the node that last wrote it. Both `get` (on the returned `StoredValue`) and `list` surface this as `last_modified_by`. For a key written with `store_exclusive` it is the owner’s `instance_id`. `get` and `list` do not mark a key as owned; an instance learns that a key is owned from the refusal of its `store_exclusive`, `store` or `remove`. `peppylib::datastore` ships an `Encoding` helper with constants for the common tags: `Encoding::TEXT_PLAIN`, `Encoding::APPLICATION_JSON`, `Encoding::APPLICATION_OCTET_STREAM` in Rust, and the same members on Python’s `Encoding` (a `StrEnum`). Like Zenoh’s own encoding, the set is **open**: the constants are a convenience, but any string is a valid tag, so you are never boxed in to the listed ones. They are available from Rust as `peppylib::datastore::{store, store_exclusive, get, list, remove, StoredValue, DatastoreEntry, ExclusiveStore, Encoding}`, and from Python as `from peppylib.datastore import store, store_exclusive, get, list, remove, StoredValue, DatastoreEntry, ExclusiveStore, Encoding`. Like the other core node helpers, they are not re-exported by `peppygen`; import them from `peppylib::datastore` directly. Each takes a `NodeRunner`, the same handle your node receives from `NodeBuilder().run(...)` in Python / `NodeBuilder::new().run(...)` in Rust (see the [services guide](/advanced_guides/services/) for a typical setup), and talks to the node’s bound core node. ## When to use this [Section titled “When to use this”](#when-to-use-this) * **A shared blackboard.** One node computes a value (a calibration result, a chosen target, a mode flag) and another reads it later. The reader asks for the key whenever it needs it, also after the writer stopped. A [topic that retains](/advanced_guides/topics/#retaining-the-latest-value) hands its latest value to late subscribers too, for as long as its producer runs. * **Last-known-value handoff.** A node that restarts can read back a value it stored under a key no instance owns, as long as the core node stayed up. * **Small cross-node state that does not warrant a service contract.** When defining a request/response service is more ceremony than the data is worth, a well-known key is often enough. * **One writer at a time.** When two instances must never both drive one thing, such as the left arm, the instance that drives it owns a key through `store_exclusive` for as long as its process runs. Another instance that tries is refused and learns which instance owns the key. A value that must outlive its writer, such as a calibration result, belongs in a key written with `store`. It is **not** a database. The store is in-memory and process-local to the core node (see the notes below), so reach for topics when you need streaming data, for services when you need a node to *act* on a request, and for a real persistence layer when you need durability. The full map of mechanisms is in [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## `store` [Section titled “store”](#store) `store` writes `value` (arbitrary bytes) under `key`, tagged with `encoding`, on the node’s bound core node. It returns once the core node acknowledges the write. Storing a key that already exists overwrites the previous value and encoding. Storing a key that another instance owns through [`store_exclusive`](#store_exclusive) fails with an error reply of the kind `precondition_failed` whose message names the owner: `PeppyError::ServiceFailed` in Rust, `peppylib.FailureError` in Python. The final argument is a response timeout. Rust accepts anything that converts to `Option`; Python accepts a `float` in seconds. Pass `None` (or omit it in Python) to use the default of 10 seconds. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.datastore import store, Encoding async def setup(_params: Parameters, node_runner: NodeRunner) -> None: await store( node_runner, "calibration/wrist_offset", b'{"x": 0.1, "y": -0.4}', Encoding.APPLICATION_JSON, 3.0, ) print("stored wrist offset") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::datastore::{store, Encoding}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { store( &node_runner, "calibration/wrist_offset", br#"{"x": 0.1, "y": -0.4}"#.to_vec(), Encoding::APPLICATION_JSON, Duration::from_secs(3), ) .await?; println!("stored wrist offset"); Ok(()) }) } ``` ## `store_exclusive` [Section titled “store_exclusive”](#store_exclusive) `store_exclusive` takes the same arguments as `store`. It stores the value and makes the calling instance the key’s owner: every other instance’s `store` and `remove` of the key fail with an error that names the owner, another copy of the same node included. The owner’s own `store` and `store_exclusive` update the value and keep the key owned, and its `remove` deletes the key. The key lasts as long as the process that stored it. When that process ends, however it ends (a clean exit, a stop, a crash, a kill or a restart), the core node removes the key, and the next `store_exclusive` of any instance takes it. The core node sends no notice when a key goes: an instance that was refused calls `store_exclusive` again to take the key once its owner is gone. A restarted process does not own the key its previous process stored. It calls `store_exclusive` again, and is refused when another instance took the key in between. A request carries only its sender’s `instance_id`, so a request still on its way when its process ends acts for the next process under that id: a `store_exclusive` sent just before a crash can make the restarted process the owner, and a `remove` sent just before a crash can delete the key the restarted process stored. When another instance owns the key, nothing is written and the answer is `ExclusiveStore::Refused { current }` (Rust) / `ExclusiveStore.Refused(current)` (Python). `current` is the `StoredValue` the owner stored, and `current.last_modified_by` is the owner’s `instance_id`. Otherwise the answer is `ExclusiveStore::Stored` (Rust) / `ExclusiveStore.Stored()` (Python). `store_exclusive` takes a key that is absent, one whose owner’s process ended, or one your instance already owns. A key’s kind is fixed when it is created: an exclusive store of a key that exists with no owner, as `store` writes it, fails with an error reply of the kind `precondition_failed` (`PeppyError::ServiceFailed` in Rust, `peppylib.FailureError` in Python) whose message names the remedy, to remove the key or use another one. The owner is an instance the core node runs. `store_exclusive` from an `instance_id` the core node runs no process under fails with an error reply of the kind `precondition_failed`: `PeppyError::ServiceFailed` in Rust, `peppylib.FailureError` in Python. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.datastore import Encoding, ExclusiveStore, store_exclusive async def setup(_params: Parameters, node_runner: NodeRunner) -> None: answer = await store_exclusive( node_runner, "arm/left/driver", b'{"mode": "teleop"}', Encoding.APPLICATION_JSON, 3.0, ) match answer: case ExclusiveStore.Stored(): print("this instance drives the left arm") case ExclusiveStore.Refused(current=current): print(f"{current.last_modified_by} drives the left arm") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::datastore::{store_exclusive, Encoding, ExclusiveStore}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let answer = store_exclusive( &node_runner, "arm/left/driver", br#"{"mode": "teleop"}"#.to_vec(), Encoding::APPLICATION_JSON, Duration::from_secs(3), ) .await?; match answer { ExclusiveStore::Stored => println!("this instance drives the left arm"), ExclusiveStore::Refused { current } => { println!("{} drives the left arm", current.last_modified_by) } } Ok(()) }) } ``` ## `get` [Section titled “get”](#get) `get` reads the value stored under `key` from the node’s bound core node. A key that holds no value (never stored, removed, or owned by a process that ended) reads as `None`: the helper folds the wire response’s `found` flag into `Option::None` (Rust) / `None` (Python). When the key is present you get a `StoredValue` with three fields: * `value`: the raw bytes, exactly as stored (`Vec` in Rust, `bytes` in Python). * `encoding`: the encoding tag they were stored with. * `last_modified_by`: the `instance_id` of the node that last wrote this key. The second argument is the same response timeout as above. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.datastore import get async def setup(_params: Parameters, node_runner: NodeRunner) -> None: stored = await get(node_runner, "calibration/wrist_offset", 3.0) if stored is None: print("no wrist offset stored yet") else: print(f"wrist offset ({stored.encoding}): {stored.value!r}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::datastore::get; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let key = "calibration/wrist_offset"; match get(&node_runner, key, Duration::from_secs(3)).await? { Some(stored) => println!("wrist offset ({}): {:?}", stored.encoding, stored.value), None => println!("no wrist offset stored yet"), } Ok(()) }) } ``` ## `list` [Section titled “list”](#list) `list` returns the metadata of **every** key currently in the store: one entry per key carrying the `key`, its `encoding` tag, and `last_modified_by` (the `instance_id` of the node that last wrote it). The value bytes are deliberately **not** included. A list stays cheap no matter how large your values are; fetch the bytes for a specific key with `get`. The entries come in key order, and the result is a point-in-time snapshot (another node may store or remove keys immediately after). The only argument is the same response timeout as above. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.datastore import list async def setup(_params: Parameters, node_runner: NodeRunner) -> None: entries = await list(node_runner, 3.0) for entry in entries: print(f"{entry.key} ({entry.encoding}) last written by {entry.last_modified_by}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::datastore::list; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { for entry in list(&node_runner, Duration::from_secs(3)).await? { println!( "{} ({}) last written by {}", entry.key, entry.encoding, entry.last_modified_by ); } Ok(()) }) } ``` ## `remove` [Section titled “remove”](#remove) `remove` deletes (unsets) `key` from the store. It returns a boolean: `true` if the key existed and was removed, `false` if it was already absent, so removing a missing key is a no-op, not an error. Removing a key that another instance owns through [`store_exclusive`](#store_exclusive) fails with an error reply of the kind `precondition_failed` whose message names the owner: `PeppyError::ServiceFailed` in Rust, `peppylib.FailureError` in Python. The second argument is the same response timeout as above. * Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.datastore import remove async def setup(_params: Parameters, node_runner: NodeRunner) -> None: removed = await remove(node_runner, "calibration/wrist_offset", 3.0) print("removed" if removed else "key was already absent") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::Duration; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::datastore::remove; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let key = "calibration/wrist_offset"; if remove(&node_runner, key, Duration::from_secs(3)).await? { println!("removed {key}"); } else { println!("{key} was already absent"); } Ok(()) }) } ``` ## Behavior notes [Section titled “Behavior notes”](#behavior-notes) * **In-memory, never written to disk.** The store lives inside the core node process. A key no instance owns lasts as long as the core node does; restarting the core node starts from an empty store. Treat it as fast shared scratch space, not durable storage. * **Shared across the whole stack, with no namespacing.** Every node bound to the same core node reads and writes one flat keyspace. Coordinate on key names (a prefix convention like `calibration/...` works well) so two nodes do not clobber each other by accident. * **Keys are arbitrary non-empty strings.** A key rides inside the request payload, not as a Zenoh keyexpr, so any character is allowed: slashes, spaces, `*`, `{}`, anything. `"robot/state**{1}"` is a perfectly valid key; only the empty string is rejected, before any request is sent. * **Store is an upsert; last writer wins.** A later store under an existing key overwrites the value, the encoding, and the recorded writer. The store records the storing node’s `instance_id` on every write and surfaces it as `last_modified_by` on `get` and `list`. There is no atomic read-modify-write, so two nodes that both do get-then-store on the same key can race. When a key must have one writer, store it with `store_exclusive`. * **An owned key has one writer for the life of one process.** The core node refuses every other instance’s `store` and `remove` of it, and removes the key when the process that stored it ends, however it ends. Two instances that call `store_exclusive` on the same key at the same moment get one owner; the other is refused and told who owns it. * **`list` is a metadata snapshot.** It returns every key’s `encoding` and `last_modified_by` but never the value bytes (fetch those with `get`), in key order, reflecting the store at the moment it was answered. * **The encoding tag is yours to interpret.** The store treats it as an opaque label and returns it unchanged. Reach for the `Encoding` constants for the common tags and pass any string for the rest (the Zenoh-style MIME-like tags are a good default), then have readers branch on it when you store more than one value type. A tag read back from `StoredValue.encoding` compares equal to its `Encoding` member, so `stored.encoding == Encoding.APPLICATION_JSON` (Python) / `stored.encoding == Encoding::APPLICATION_JSON` (Rust) works. * **Default timeout is 10 seconds.** Pass an explicit timeout from a latency-sensitive path so a slow or unreachable core node does not stall your node. # Federation > Run one Peppy stack across several machines. Declare core node links in a launcher, wire them with stack launch --place, and let producer links, pairings, and observations cross daemon boundaries. Two machines enrolled in the same project share one namespace and can address each other. A core node is one machine, and typically one robot, so a federation is a network of robots and the machines that support them. Federation is what lets a single stack span that network: one launcher file, one command, and one graph whose instances are spread across several core nodes. ## The problem it solves [Section titled “The problem it solves”](#the-problem-it-solves) Consider a manipulation system with two very different pieces. A **large vision-language-action model** plans over tens of seconds. Its weights are proprietary and are not shipped to customer hardware, it wants a datacenter accelerator that no mobile platform carries, and it thinks at roughly 1 Hz, so a WAN round trip is a small fraction of its own cycle. Latency is close to free for it. A **small reactive policy** closes a 200 Hz loop against hardware it must reach in microseconds. A link outage has to degrade it, not stop it. Those two want opposite machines. Without federation, you pick one and compromise, or hand-roll a bridge between two independent stacks and give up Peppy’s wiring, ordering, and lifecycle guarantees at the seam. **What Peppy provides:** one launcher describes both halves, one command starts them, producer links and pairings and observations all work across the boundary, and consumers still start after their producers no matter which machine each is on. **What it deliberately does not:** it does not make a network partition invisible. See [Ordering, degradation, and failure](#ordering-degradation-and-failure). ## Prerequisites [Section titled “Prerequisites”](#prerequisites) Both machines must be enrolled in the same project and visible to each other: ```bash peppy platform peers ``` ```plaintext Project 550e8400-e29b-41d4-a716-446655440000 PEER STATUS CERT EXPIRES ID cn-robot-7 connected 2027-01-01 9d2c… (this machine) cn-atlas-h100 connected 2027-01-01 41f0… ``` Both rows must read `connected`: the machine’s router holds a live link to the project’s cloud router. A machine that is not `connected` has a stopped daemon (`peppy service serve`) or has not completed [`peppy platform enroll`](/advanced_guides/platform/); `peppy platform status` on that machine says which. `peppy platform peers` is the human-facing view. A launch does not depend on it: liveness is checked against the live federation at launch time, because what matters is whether the coordinator can *talk to* a machine right now. Every daemon in a federation runs the same Peppy version. A mixed-version federation is refused during preflight, with a message naming both versions and the machine to upgrade; versions are never negotiated. Each call to the daemon of another machine carries the proof of its sender: the daemon checks it against the CA of the machine certificates, the CA of the project for enrolled machines (see [Machines of a federation](/advanced_guides/call_senders/#machines-of-a-federation)). A federation that the operator forms needs a certificate of a CA of the operator on each machine ([`machine_certificate`](/advanced_guides/daemon_config/#machine_certificate-the-certificate-of-the-machine)). The machines keep their wall clocks within 30 seconds of each other: a daemon refuses a call whose timestamp is further from its own clock. Only the coordinator’s repositories matter to a launch. The daemon you submit to resolves every deployment from its own caches and ships the result to the others as pinned content, so `peppy repo refresh` is the submitting machine’s business and the other machines’ caches can be stale, differently prioritized, or empty. ## Core node links [Section titled “Core node links”](#core-node-links) A launcher does not name machines. It declares **core node links**, which are placeholders: ```json5 core_nodes: ["robot_onboard", "cloud_inference"], ``` and each instance says which one it runs on: ```json5 { instance_id: "planner_inst", core_node: "cloud_inference", /* ... */ } ``` The file describes a *topology*; the command binds it to today’s hardware: ```bash peppy stack launch --place robot_onboard@self \ --place cloud_inference@cn-atlas-h100 \ split_compute_manipulation ``` That separation is the point. The same file works against a rented H100 today and your own rack tomorrow, and nobody edits the launcher to redeploy it. Rules, all checked before anything starts: * Every declared link must be wired exactly once. A partial wiring is refused rather than silently collapsing half the topology onto the coordinator. * `--place` may only name links the launcher declares, and the [copies](#adding-copies) the launcher file lists, by name. A listed copy that no `--place` names runs on the coordinator. A copy that `--join` adds runs where its `--join OPTION:NAME@CORE_NODE` says, and `--place` on its name is refused. * Two links may share one machine. A two-machine topology must still be runnable on one box. * `self` means the daemon the launch is sent to, in `--place`, `--join` and a `--with` word alike. It is reserved: no core node may be named `self`. * `core_node` is **optional** on an instance. One that omits it runs on the coordinator. ### Developing without a second machine [Section titled “Developing without a second machine”](#developing-without-a-second-machine) ```bash peppy stack launch --local split_compute_manipulation ``` `--local` wires every declared link to this daemon, so the whole topology runs on your workstation with no cloud account and no uplink. The launcher is unmodified. It is a flag rather than a key in the file because the launcher’s author declares a topology and cannot know what machines the person running it has. Mixing `--local` with `--place` is an error: pick one way to say where things go. For the same reason, under `--local` a `--with` word that names a machine is refused, `@self` included, and so is a `--join` copy that names a machine other than `self`. ## The worked example [Section titled “The worked example”](#the-worked-example) split_compute_manipulation.json5 ```json5 // Split-compute manipulation: a fast reactive policy on the robot, a large // deliberative planner in the cloud, wired as one stack. // // Launch from the robot: // peppy stack launch --place robot_onboard@self \ // --place cloud_inference@cn-atlas-h100 \ // split_compute_manipulation // // Or, to run the whole topology on one machine with no cloud account and no // uplink, which is how you develop against it: // peppy stack launch --local split_compute_manipulation { peppy_schema: "launcher/v1", description: ["Manipulation split between two machines: a fast reactive policy on the robot and a large deliberative planner in the cloud. It needs the two machines, or `--local` to run the whole stack on one."], // Core node links: placeholders this file names, wired to real machines at // launch time via `stack launch --place @`. // The file describes a topology; the command binds it to today's hardware, // so the same launcher works against a rented H100 now and your own rack // later. Every declared link must be wired, and every wired core node must // be live in the federation, or the launch is refused. core_nodes: ["robot_onboard", "cloud_inference"], deployments: [ // ---- On the robot: everything the control loop touches ---- { source: { name: "uvc_camera_python_mock", tag: "v1" }, instances: [ { instance_id: "wrist_cam_inst", // Places this instance on the daemon wired to `robot_onboard`. // OPTIONAL: an instance that omits it runs on the coordinator. core_node: "robot_onboard", arguments: { device_path: "/dev/video0", video: { frame_rate: 30, resolution: { width: 1280, height: 720 }, camera_encoding: "mjpeg", topic_encoding: "rgb8", }, }, }, ], }, { source: { name: "my_python_robot_arm", tag: "v1" }, instances: [ { instance_id: "arm_inst", core_node: "robot_onboard" }, ], }, { // The small onboard model. Closes the servo loop at 200 Hz against // hardware that is one process away, and escalates anything it cannot // resolve within its horizon to the planner over the `deliberation` pair. source: { name: "reactive_policy", tag: "v1" }, instances: [ { instance_id: "reflex_inst", core_node: "robot_onboard", arguments: { control_rate_hz: 200, // How long a subgoal from the planner stays authoritative before // this node falls back to its own local behavior. Bounds how much // a slow or severed uplink can affect the robot. subgoal_ttl_ms: 2000, }, links: { // Both on this machine: the servo loop never crosses the WAN. camera: "wrist_cam_inst", arm: "arm_inst", // Cross-daemon PAIRING. Bidirectional by nature: this node pushes // the current situation up, the planner pushes subgoals back down. // Declaring the pair on one side covers both endpoints' slots. deliberation: "planner_inst/deliberation", }, }, ], }, // ---- In the cloud: the parts that want a datacenter GPU ---- { // The large vision-language-action / world model. Proprietary weights, // multi-second horizon, ~1 Hz. Resolved by `name:tag` through the // repository index like every deployment, which is what lets the plan // place it off-coordinator. source: { name: "deliberative_planner", tag: "v1" }, instances: [ { instance_id: "planner_inst", core_node: "cloud_inference", arguments: { plan_rate_hz: 1, horizon_s: 30 }, links: { // Cross-daemon PRODUCER LINK. The same camera instance the reflex // policy reads locally, named exactly the same way. Placement is // declared once, on the instance, and never repeated at the point // of use. scene: "wrist_cam_inst", }, }, ], }, { // Captures what the robot actually did, for later training. Taps the // executor side of the pairing without joining it. source: { name: "episode_recorder", tag: "v1" }, instances: [ { instance_id: "recorder_inst", core_node: "cloud_inference", // Cross-daemon OBSERVATION. An observer link names the instance it // watches; passive, so it claims no slot and cannot perturb control. links: { observed_execution: "reflex_inst" }, }, ], }, ], } ``` Run it from either machine. The daemon you send it to coordinates, and the only thing that changes is what `self` binds to: from the robot that is `--place robot_onboard@self`, from the cloud instance the same launch reads `--place robot_onboard@cn-robot-7 --place cloud_inference@self`. Coordinating is a planning role, not a privileged one, so the topology does not depend on where the command was typed. One thing does follow the coordinator, and it argues for the robot here: an instance that omits `core_node` runs on the coordinating daemon. ```bash peppy stack launch --place robot_onboard@self \ --place cloud_inference@cn-atlas-h100 \ split_compute_manipulation ``` ```plaintext This launch will REPLACE the node stack on 1 remote daemon(s): cn-atlas-h100 Parsing launcher configuration Resolving 5 deployment(s) Retrieving node config for deliberative_planner:v1 Validating dependencies Adding uvc_camera_python_mock:v1 on `cn-robot-7` Adding deliberative_planner:v1 on `cn-atlas-h100` [cn-atlas-h100] Materializing 1 pinned node(s) for node `deliberative_planner:v1` ... Starting uvc_camera_python_mock:v1 instance wrist_cam_inst on `cn-robot-7` Starting my_python_robot_arm:v1 instance arm_inst on `cn-robot-7` Starting reactive_policy:v1 instance reflex_inst on `cn-robot-7` Starting deliberative_planner:v1 instance planner_inst on `cn-atlas-h100` Starting episode_recorder:v1 instance recorder_inst on `cn-atlas-h100` Node log files: ... Launch configuration applied successfully ``` (The `Node log files:` listing, elided here, names every machine’s per-node add, build, and run logs, one `node:tag@core-node: path` line each. Each daemon [exports](/advanced_guides/opentelemetry/) the log files it writes, when its own `otlp_endpoint` is set.) Two things in that output are worth pointing at. The first line: a launch is destructive on every machine it touches, and you typed one command, so Peppy names the remote daemons whose stacks are about to be replaced before it replaces them. And the `[cn-atlas-h100]` prefix: the peer’s own output is relayed into this one stream and attributed, because a launch that ran half its work somewhere you cannot see is not one you can debug. Each machine builds and runs its slice with its own environment. Nothing from the machine the launch was typed on crosses over: not its `PATH`, not its shell environment. A node’s `build_cmd` names its toolchain (`uv` for the default Python template, or whatever the node declares), and every machine a launch places that node on must have that toolchain installed where its daemon can find it; a machine that lacks it fails the launch with an error naming the missing program. The one way to hand a value to a remote instance is the `env_vars` of that instance in the launcher file, which apply wherever the instance is placed. An instance with [`env_from_launch`](/guides/launch_files/#env_from_launch-optional) runs on the coordinator’s machine only: a value of the launching shell stays on the machine where you typed it. A launch or a join that places such an instance on a peer is refused, naming the instance and the peer. ## Verifying placement [Section titled “Verifying placement”](#verifying-placement) `peppy stack list` from either machine shows both slices, each attributed to the daemon serving it: ```plaintext ┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Core node: cn-robot-7 (host: robot-7) │ ├──────────────────────────────────────────────────────────────────────────────────────────┤ │ Instance bindings │ │ │ │ ┌────────────────────────────┬──────────────────┬─────────┬─────────┬──────────┬───────┐ │ │ │ NODE │ INSTANCE │ STATUS │ HEALTH │ RESTARTS │ CLOCK │ │ │ ├────────────────────────────┼──────────────────┼─────────┼─────────┼──────────┼───────┤ │ │ │ uvc_camera_python_mock:v1 │ wrist_cam_inst │ running │ healthy │ 0 │ wall │ │ │ │ my_python_robot_arm:v1 │ arm_inst │ running │ healthy │ 0 │ wall │ │ │ │ reactive_policy:v1 │ reflex_inst │ running │ healthy │ 0 │ wall │ │ │ └────────────────────────────┴──────────────────┴─────────┴─────────┴──────────┴───────┘ │ └──────────────────────────────────────────────────────────────────────────────────────────┘ ┌──────────────────────────────────────────────────────────────────────────────────────────┐ │ Core node: cn-atlas-h100 (host: atlas) │ ├──────────────────────────────────────────────────────────────────────────────────────────┤ │ Instance bindings │ │ │ │ ┌────────────────────────────┬──────────────────┬─────────┬─────────┬──────────┬───────┐ │ │ │ NODE │ INSTANCE │ STATUS │ HEALTH │ RESTARTS │ CLOCK │ │ │ ├────────────────────────────┼──────────────────┼─────────┼─────────┼──────────┼───────┤ │ │ │ deliberative_planner:v1 │ planner_inst │ running │ healthy │ 0 │ wall │ │ │ │ episode_recorder:v1 │ recorder_inst │ running │ healthy │ 0 │ wall │ │ │ └────────────────────────────┴──────────────────┴─────────┴─────────┴──────────┴───────┘ │ └──────────────────────────────────────────────────────────────────────────────────────────┘ ``` (Abridged: the real output opens each section with a `Slice of launch ...` ownership line, and also carries a `Node stack` table, `Instance pairings` and `Dependencies` sections, and a `BINDINGS` column, all trimmed here to keep the placement visible.) Both slices report the same launch id and the same coordinator. That is what ties them together, and it is recorded on each slice rather than in the coordinator’s memory, which is why a coordinator restart does not lose the launch. ## What crosses a daemon boundary [Section titled “What crosses a daemon boundary”](#what-crosses-a-daemon-boundary) Each kind appears exactly once in the example. **Producer link.** `wrist_cam_inst`, the camera on the robot, feeds two consumers. The reflex policy reads it locally through the slot its manifest calls `camera`; the planner reads it from the cloud through the slot its manifest calls `scene`. The slot names differ because each belongs to its own node, but both sides name the producer the same way and neither says where it is: reflex_inst (on the robot) ```json5 links: { camera: "wrist_cam_inst" } ``` planner_inst (in the cloud) ```json5 links: { scene: "wrist_cam_inst" } ``` Nothing at the point of use records which machine the producer sits on. Placement is declared once, on the instance. See [Node stack](/guides/node_stack/). **Pairing.** `deliberation` connects the policy and the planner. It is a pairing rather than two producer links because the relationship is genuinely bidirectional and exclusive: the policy pushes its situation up and escalates what it cannot solve, the planner pushes subgoals back down, and each side holds a pinned view of the other. Declaring the pair on one side covers both endpoints’ slots. See [Pairing](/advanced_guides/pairing/). A pair is recorded on both machines, because only the daemon hosting a node can hand that node its peer. The later-starting side establishes the pair and asks the other daemon to record its half; if that is refused, the first side undoes its own, so a pair is never established on one machine and missing on the other. **Observation.** The recorder taps the executor side of that pairing without joining it. An observer claims no slot and holds no peer, so it cannot perturb control however it behaves. Because the source is not told its observers exist, it cannot report to them on its own. The launch works out which machines are watching each instance and tells that instance’s daemon, which is what makes a source restart drop and redeclare a remote observer’s subscription exactly as it does a local one. **The bytes themselves.** The coordinator resolves every node in the launch, the ones placed elsewhere included: the named node, every transitive dependency, and every contract and pairing document any of their manifests reference. What crosses the boundary is that decision, pinned: the exact content it read, identified by fingerprint, plus the repository, commit, and published path it came from. A machine holding content with the same fingerprint reuses its own copy, whichever repository it arrived from; one that does not fetches the pinned commit. No machine but the coordinator resolves a name, so a peer’s cache freshness, repository priorities, and exclusions never decide what a launch runs. Here `cn-atlas-h100` runs the planner the robot’s caches describe, even if its own were refreshed a week apart. An [`exposures` deployment](/advanced_guides/mcp/#placement) crosses the same way: the pinned exposure documents and the contracts they reference, from which the machine hosting the instance derives the same MCP server the coordinator planned. **A clock domain.** A [clock domain](/advanced_guides/system_clock/#clock-domains) is supplied by one instance and read by any number, and those may sit on different machines. The domain’s ticks ride the `clock` topic of the machine hosting its publisher, under a key carrying the domain’s name and incarnation, and a consumer addresses that whole identity wherever it runs. A daemon hosts wall time and any number of simulated domains at once, so a launch spreads a domain across its machines the way it spreads anything else. What placement decides is the domain’s identity, which names the machine its publisher runs on. **Container bind sources.** A [container node](/advanced_guides/containers/) declares the host paths it mounts, and a mount path may name an instance parameter, so what a given instance binds is known only to the coordinator that resolved the whole plan. Every machine prepares the paths its own instances bind, and does it while running nothing: a participant is handed its share and prepares it the moment it is told to replace its slice, and the coordinator prepares its own once every machine’s nodes are added and built, before the first instance starts anywhere. Preparing creates a missing path as a directory and makes it visible to that machine’s container runtime; a missing `/dev`, `/proc`, `/run`, or `/sys` path is the host’s to provide and is left alone. A path a machine had to create is reported back and shown in the launch output against that machine, the same warning you would get had the instance run on your own machine, and it is worth reading for the same reason, since a bind meant to name a file looks exactly like this when the name is misspelled. The thing to notice is that none of this looks different from the single-machine case. Federation changes where instances run, not how they are wired, and every machine runs the same bytes the submitting machine resolved. ## Ordering, degradation, and failure [Section titled “Ordering, degradation, and failure”](#ordering-degradation-and-failure) **Consumers still start after producers, across machines.** `wrist_cam_inst` is Running on the robot before `planner_inst` starts in the cloud, because the planner’s `scene` slot is bound to it. The coordinator computes one global order and starts instances strictly one at a time along it, whichever machine each one is on, so the guarantee is the same one a single-machine launch gives. Fetching and building do run concurrently across machines, since nothing orders one machine’s build against another’s. That is where a launch spends its time, so a two-machine launch is not two launches long. **Peppy guarantees the servo path never crosses the WAN.** Placement puts the camera, the arm, and the policy on one daemon, so the 200 Hz loop is entirely local by construction. **Peppy does not guarantee instant notification of a partition.** A cleanly stopped or dead peer instance produces a cross-daemon dissolution notification, but an unreachable daemon cannot send one. A node whose correctness depends on freshness therefore owns a staleness watchdog. In the example that is `subgoal_ttl_ms`: a subgoal is authoritative for two seconds after the policy adopts it, and then the policy falls back to its own local behavior. The uplink is an *enhancement path*, not a dependency. **A launch reserves every participant before it touches anything.** Preflight reserves each machine in the launch, all or nothing: if any machine refuses, every reservation just taken is released and no stack anywhere is torn down. A reservation is machine-wide while it lasts. A reserved daemon refuses local `peppy node add`, `peppy node run`, `peppy node remove`, and `peppy node stop` too, naming the launch and coordinator holding it, and `peppy stack list` shows a `Reserved for launch ...` line naming the exact reset command that clears it. These refusals, and the refusal of a reservation while other work holds the stack of the machine, have the failure kind `busy`: the same command can succeed once that launch or that work ends. A launch fails with `busy` too when each machine that refuses its reservation refuses it as `busy`. A reservation lasts while its coordinator is present in the federation, and ends when its coordinator is gone: a coordinator that disappears frees the machines it held rather than leaving them wedged. A coordinator’s own next launch also takes over its own stale reservation, so a lost release never blocks the machine that made it. A participant restarts its own instances under their [restart policy](/guides/launch_files/#restart-policy) while the coordinator is unreachable; a restart waits for its last exit’s notices to other daemons, and for a stack launch, build, join or removal or a `peppy node remove` in progress on that daemon to end. **A pin that cannot be honored is a refusal, never a fallback.** A peer that does not hold a pinned content and cannot reach the pinned repository refuses its part of the launch and names the location it could not reach. One that fetches the pinned commit and reads different bytes than the pin’s fingerprint refuses naming both fingerprints, because that means the remote moved under the pin or the location resolved to something else. In neither case does the peer fall back to resolving the name against its own cache: that would reintroduce per-machine resolution at exactly the moment nobody is watching. **On failure, the launch stops and clears every slice it started.** There is no rollback, because a launch REPLACES the previous stack: by the time anything can fail there is nothing to roll back to. What Peppy does instead is leave an empty slice on every machine it touched and name each one. If a machine cannot be reached to be cleared, that machine is named too, with the remedy: clear it with `peppy stack reset` from that machine, or target it remotely with `peppy stack reset --core-node `. ```bash peppy stack reset --federated ``` tears down every slice and reservation of the launch. It works from any machine in the federation, and after a coordinator restart, because it *rediscovers* the targets by asking the federation rather than reading a remembered list: any machine holding a slice **or a reservation** is swept, matched by the launch id when the daemon you point the command at holds a slice, and by that daemon’s own coordinator name otherwise. A wedged participant that holds only a reservation, because its launch died before populating a slice, is therefore still reachable, and a daemon whose own earlier launch went stale sweeps by both keys. Both forms take the global `--core-node ` flag to target a specific daemon: `peppy stack reset --core-node ` clears that one machine (the escape hatch the reservation refusals name), and adding `--federated` sweeps the launch that daemon belongs to. Without `--federated`, `peppy stack reset` clears one daemon’s slice and tells you what it left running: ```plaintext Note: `cn-atlas-h100` holds one slice of launch `launch-brave-otter`, coordinated by `cn-robot-7`. This clears only this daemon's slice; the other participants keep running. Use `peppy stack reset --federated` to tear down the whole launch. ``` ## Limits [Section titled “Limits”](#limits) * **Same Peppy version on every participant.** A mixed-version federation is refused during preflight, before any stack is touched. * **A filesystem repository cannot back a deployment placed on another machine.** A deployment is pinned to wherever the coordinator’s cache resolved it, and a filesystem repository entry (a directory registered with `peppy repo add `) is a path only the coordinator can read. Two things still work: keep that deployment’s instances on one core node, or serve the node from a git repository, which every machine can fetch. The same holds for an `exposures` deployment, whose exposure documents and contracts are what gets pinned. * **The unit of byte coherence is one launch.** Two launches submitted while a repository moves between them may run different revisions of it; each launch is internally coherent, and nothing synchronizes one launch with the next. * **A launcher file path cannot target a remote daemon.** `peppy stack launch ./my_launcher.json5 --core-node cn-atlas-h100` is refused for the same reason. Use a repository launcher, or run the command from the machine holding the file. * **No re-placement of a running instance.** Moving an instance to another machine means launching again. ## Adding copies [Section titled “Adding copies”](#adding-copies) A launcher whose `components` include a `zero_or_more` or `one_or_more` axis runs that axis as copies, added and removed while its other instances keep running. The coordinator snapshots the launcher at launch and composes every join against that snapshot: ```sh peppy stack launch physical peppy stack join openarm:alpha@jetson-1 --with openarm_v2 peppy stack join openarm:bravo@jetson-2 --with openarm_v1,ai_brain_vla@cn-gpu-box peppy stack list peppy stack remove bravo peppy stack reset --federated ``` A copy’s name is its placement link and the prefix of every instance it creates. A copy runs where it is named: `OPTION:NAME@CORE_NODE` on `peppy stack join` and on `--join` at launch, `--place NAME@CORE_NODE` for a copy the launcher file lists, and the coordinator when nothing names a machine. Its machine runs its base. A part of the copy, the instances that one of its own axes brings, runs where the word that selects it says: `option@CORE_NODE` or `axis=option@CORE_NODE` at join, `NAME.option@CORE_NODE` at launch. Above, `bravo` runs on `jetson-2` and its brain on `cn-gpu-box`. A join’s preflight checks every machine of the copy, and refuses one that is not live before any machine changes, naming the live ones. Run join and remove on the coordinator, with `--core-node NAME` from another machine. A join reserves the machines it touches, the providers its instances link to, the machines supplying the clocks its instances read, and the machine of every instance whose set it grows. A join is refused when the machine of an instance whose set it grows is offline on the federation; a removal is not, and it names the sets it left unchanged there. A machine outside that set that is offline blocks neither a join nor a removal. Launch replaces every participating slice. Join adds each of the copy’s instances to the slice of its machine; remove stops the copy alone and refuses while another instance links to it. A removal, and the undo of a failed join, stop the copy’s instances one at a time, the last started first, across its machines, and print a line for each instance before they stop it: an instance on another machine stops through one request of its own. A removal stops nothing on a machine of the copy that is not live, and warns for it, naming the instances of the launch that a `peppy stack reset` there stops once it returns; it also stops nothing on a live machine that holds no slice of the launch, because someone reset it, and a line says so. Reset cancels the operation in flight, waits for its cleanup, and clears the targeted slices; with `--federated` it clears every machine of the launch, which is also how the machines a cancelled join reached are cleared. See [copies](/guides/launch_files/#copies) for argument overrides, the words that place a part and their refusals, and the listing of a copy, whose line pastes back into `peppy stack join`. ## The fleet of a federated launch [Section titled “The fleet of a federated launch”](#the-fleet-of-a-federated-launch) The daemon of the coordinator serves the fleet of the launch, its leases and its halt, in `robot_leases:v1`, and its copies in `robot_membership:v1` (see [Robot leases and the halt](/advanced_guides/fleet/#federation)). It takes the call of an instance of another machine as that instance only when the launch places the instance on that machine. The daemon of each machine tells the coordinator each start and each end of the process of an instance of the launch, so the fleet listing gives the software of each robot on every machine. A daemon target of an instance of the launch, the `fleet` slot of an MCP server on a robot machine included, reaches the daemon of the coordinator. A participant refuses the calls of these interfaces and names the coordinator. `peppy fleet` and `peppy node call` on any machine reach the coordinator through the stack listing of the daemon that they target, so a halt on one machine halts the whole stack. # Robot leases and the halt > The fleet of a stack, the leases that give one client the right to move one robot, the move check, the halt and the changes, which the daemon serves in robot_leases:v1 The **fleet** of a stack is the robots of the launch that the daemon coordinates. Each [copy](/guides/launch_files/#copies) of the launch is a robot of the fleet, a device that a client changes included, such as a hob. An instance that the launcher deploys outside every copy, or that `peppy node run` starts, is in no robot. The fleet holds the launch from its commit point on, the step at which it replaces the stack before it: while the launch starts its instances, each robot is in the listing with its software `stopped`, and each instance that started calls the daemon within the scopes of the launch. A launch that fails then drops its robots again. The daemon serves the fleet in the daemon interface `robot_leases:v1`, a document in the contract format that is compiled into `peppy`. It gives the fleet listing, the **leases** that give one client the right to move one robot, the **move check**, the **halt** of the stack, and the **changes** of the fleet. Its clients are: | Client | What it uses | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | An MCP server of peppy | `check_move` before each call of a member that moves a robot, and `changes` while such a call runs (see [Members that move a robot](/advanced_guides/mcp/#members-that-move-a-robot)) | | `peppy node call` | The same as an MCP server, with no scope: it acts for the person or the program that runs it (see [Calling a running instance](/advanced_guides/calling_instances/)) | | A lease holder, a node with a `robot_leases` daemon target | `lease` with its services, `changes` and `check_move`, within the scope of its target (see [Daemon targets](/advanced_guides/core_node_functions/#daemon-targets)) | | The command line | [`peppy fleet`](#the-command-line): the listing, the halt and its end | The leases and the halt bind only the clients that ask the daemon before they move a robot. They prevent conflicts between clients. They are not a safety function: the emergency stop of each robot stays in its certified layers. The daemon knows a client by the sender that its call proves: each call to a daemon carries the signature of its sender, and the daemon verifies it before it reads the sender (see [The senders of the calls to a daemon](/advanced_guides/call_senders/)). A node cannot call under the id of the command line or of a lease holder. The scopes and the raw-call rules below read the sender that the call proves. ## Members that move a robot [Section titled “Members that move a robot”](#members-that-move-a-robot) A contract marks each member that moves a robot or changes the state of a device with `marks: ["moves_robot"]` (see [Marks](/advanced_guides/contract_implementation/#marks)). Each MCP server of peppy, `peppy node call` and each lease holder asks `check_move` before each call of a marked member. A provider reads no lease: a node that serves a goal and calls the nodes of its robot for it, such as a skill node, asks nothing, because the client of that goal asked before its call. `check_move` takes exactly one of `instance`, the instance that the client calls, and `robot`, a robot of the listing by its name: a client that streams to a robot and calls no member names the robot. It answers every sender, with no scope. Its answer gives the `revision` of the fleet that it read (see [Changes](#changes)), and no `refusal` when the client may move the robot, else a `refusal` with a `failure_kind` and a `message`, which the client refuses its call with: * During a halt it refuses every call, also on an instance outside every copy, with `halted`. * On an instance outside every copy it allows every call. * On a robot whose lease is open it allows every client. * On a robot that a client leases it allows that client, and refuses every other client with `leased`. The message names the holder and the lease name. * On a robot with no lease it allows a client that is not a lease holder, and refuses a lease holder with `not_leased`. The message says how the last lease of the asker on the robot ended, or that the asker does not lease it. ## The fleet listing [Section titled “The fleet listing”](#the-fleet-listing) `list` gives the fleet listing, and `peppy fleet list --json` prints it: * `version`, the release tag of the peppy that runs the stack, or `unknown`; `core_node`, the machine that coordinates the stack; `launcher`, the launcher of the stack, empty when no launch runs. * `halted`, and `halted_by`, the client that halted the stack. * `robots`, each robot in name order: `name`, the name of its copy; `option`; `core_node`, its machine; `kind`, `simulated` when each instance of the robot reads the clock of a simulation, else `physical`; `clock`; `software`, `running` while the process of each instance of the robot runs, else `stopped`; `robot_commander`; `instances`, each with its `name` in the copy, `instance`, the id that the stack runs it under, `core_node`, `node` and `node_tag`; and `contracts`, each contract that an instance of the robot implements, with `name`, `tag`, `sha256`, the hash of its pinned document, and `instances`, the instances that implement it. A client reads the model and the limbs of a robot from the instances of `robot_identity:v1` and `limb_state:v1` in it. * `leases`, each lease in robot order: `robot`; `holder` and `holder_core_node`; `name`, the name that the holder gave the lease, such as the name of a run; `open`; `giver` and `giver_core_node`, the client that gave the lease to its holder, empty for a lease that the holder took; and `receiver` and `receiver_core_node`, the client that the holder offers the lease to, empty when no offer runs. * `options`, each option and feature that a [`robot_membership` scope](/advanced_guides/mcp/#scopes) of the launch names, with its `kind` and the contracts of its instances; `documents`, the pinned document of each of these contracts; and `nodes`, each node of the launch with the manifest and the commit that each machine runs, and its instances, each with the robot that it belongs to. The robot commander of a robot is the option of its copy on the axis that the launcher marks with `role: "robot_commander"` (see [Copies](/guides/launch_files/#copies)). The option `none` of that axis, or a launcher that marks no axis, gives no robot commander. A robot commander, such as a leader arm or the browser panel of the robot, drives its own robot outside the leases and the halt. The daemon of each machine tells the coordinator each start and each end of the process of an instance of the launch, so the `software` of a robot follows its instances on every machine. `contract` takes `name`, `tag` and `sha256` and gives the pinned `document` of a contract of the listing, as written. It refuses a document that the daemon does not hold with `rejected`. A client reads the [descriptions](/reference/concepts/#descriptions) of a contract, of its members and of their fields from its pinned document, for example through the [codec API](/advanced_guides/codec_api/#parse-a-contract). ## Leases [Section titled “Leases”](#leases) A lease gives one client the right to move one robot. Only a client whose `lease` goal runs holds leases: a node whose `robot_leases` scope gives `lease`. MCP servers and the command line hold none. * `lease` is a long goal. While it runs, its sender holds leases, and its feedback gives each event of its leases: `offer`, another client offers the sender the lease of a robot; `offer_end`, an offer to the sender ended; `lease_end`, a lease of the sender ended; and `lease_back`, a lease that the sender gave came back to it. Each feedback gives the `robot`, the `giver` and its machine, and the `cause`. A process runs one `lease` goal: a second one is refused with `precondition_failed`, and a new `lease` goal of a restarted process ends the goal of the process before it. * `take` takes the lease of a `robot` under a `name`, which a refusal gives to the other clients. It refuses a robot that another client leases with `leased`, unless that client offers the lease to the sender, a sender whose `lease` goal does not run and a robot that a removal takes off the stack with `precondition_failed`, a robot that is not on the stack and has no lease with `rejected`, and every lease during a halt with `halted`. The call returns once the daemon records the lease. * `release` ends a lease of the sender, and returns once the daemon records the release. A lease that the sender received goes back to its giver. * `offer` offers leases of the sender, `robots`, to another instance of the launch, `receiver`. Each lease stays its own, and a lease that the sender received is not offered again. The receiver takes each lease with `take`, which changes the holder in one step. An offer ends at the take, at a release by the giver, at the end of the lease, at an offer of the same lease to another receiver, and when the giver or the receiver is gone; the `lease` goal of the receiver gives `offer_end` with the cause. An offer of a lease to the receiver that it is offered to already changes nothing. * `open` lets any client move the robot of a lease of the sender, and the sender keeps the lease; `close` ends that. A lease ends at its release, at a halt, and when its holder is gone: the process of the holder ends, or its `lease` goal ends. A lease that the holder received goes back to its giver instead, or ends when the giver is gone too. A restart of the holder, also under the same instance id, or of the daemon, keeps no lease and no offer. A new launch and `peppy stack reset` end every lease and offer. A lease stays when its robot leaves the stack, until its release. A join and a removal follow the leases. The daemon refuses a join under the name of a robot that another client leases, and the removal of a robot that another client leases, with the failure kind `leased`: only the holder of the lease, or the giver of a lease that its holder received, removes a leased robot. While a removal runs, no client takes the lease of its robot. A lease holder that joins a robot through its daemon target of `robot_membership:v1` leases it under the name of the robot, and its join is refused during a halt. A join or a removal acts for its sender: the daemon refuses a stack goal of another sender that names the client it acts for, a field that the daemon alone gives the goals that its `robot_membership:v1` provider sends for its clients. ## The halt [Section titled “The halt”](#the-halt) `halt`, or `peppy fleet halt`, halts the stack with no wait for the clients: * The daemon ends every lease with no give-back, and every offer, then writes the halt to its data root. * Until `clear_halt`, it refuses every lease, and `check_move` refuses every call, from every client. * Each lease holder, each MCP server and `peppy node call` cancel each goal that they sent on a marked member, and send no new command, not even a safe state, so the safety layer of each robot acts. A lease holder that streams setpoints, such as the teleoperation headset, ends its stream with a short burst of the measured pose, which holds the robot where it is: that burst is a stop, which the halt allows. A lease holder keeps its `lease` and `changes` goals, and each goal that is not on a marked member. * The halt stays after a restart of the daemon. A second halt changes nothing else. A halt that the daemon cannot write to its data root, such as on a full disk, holds all the same, and the call fails with `attempt_failed`: that halt ends at a restart of the daemon, and a next halt writes it again. `clear_halt`, or `peppy fleet clear-halt`, ends the halt. It starts nothing again: each client takes its leases again. A clear that the daemon cannot remove from its data root fails with `attempt_failed`, and the stack stays halted. ## Changes [Section titled “Changes”](#changes) `changes` is a long goal. Its first feedback gives the listing, with the change `listing`. Then it gives one feedback per change of the fleet, in order, each with the `change`, its `robot`, empty for a change of the whole stack, and the listing after the change, so a client misses no change: `join`, `removal`, `software_stop`, `software_start`, `lease_start`, `lease_end`, `lease_open`, `lease_close`, `offer_start`, `offer_end`, `holder_change`, `halt_start` and `halt_end`. A robot that joins the stack gets its software state in the listing of its `join`. Each change counts one **revision** of the fleet, which each feedback gives, the first one the revision of its listing. A client orders an answer of `check_move` and a change by their revisions: the halt of a change of a later revision than the move check of a goal cancels the goal, and an older one does not. The documents of the listing are those that the nodes of the stack hold, so a launch adds them as it adds its nodes, with no change. ## Scopes and raw calls [Section titled “Scopes and raw calls”](#scopes-and-raw-calls) The daemon checks each call of `robot_leases:v1` against its sender: * The command line calls every member: it has no scope. * An instance of the launch calls the members that the scope of its daemon target of `robot_leases:v1` gives (see [Scoping a daemon target](/advanced_guides/core_node_functions/#scoping-a-daemon-target)). An instance of another machine has its scope only when the launch places it on that machine. * `check_move` answers every sender, and `changes` answers each MCP server of peppy. A node reaches the daemon only through its daemon targets. The daemon refuses each of its raw actions, such as a launch, a join, a removal, a build or a run of a node, and each of its raw services that changes the stack, a node, a repository or a federated launch, such as a reset or the stop of a node, from an instance, of its machine or of another one, with the failure kind `rejected`. A node keeps the raw services that read or that it needs to run: the clock, the datastore, health, info, the stack listing, the node information, the documents of an instance and the repository listing. The command line and the daemons call every raw service. ## Federation [Section titled “Federation”](#federation) The daemon of the coordinator serves the fleet of a [federated](/advanced_guides/federation/) launch, so a client on any machine reaches the same leases and the same halt: * The daemon binds each daemon target of an instance of the launch to the daemon of the coordinator, under the per-boot instance id that began the slice of its machine. So the `fleet` slot of an MCP server on a robot machine reaches the coordinator. * A daemon that runs a slice of a launch of another machine refuses every call of `robot_leases:v1` and `robot_membership:v1` with `precondition_failed`, and names the coordinator. * `peppy fleet` and `peppy node call` read the stack listing of the daemon that they target, and call the daemon of the coordinator of its launch. ## The command line [Section titled “The command line”](#the-command-line) | Command | What it does | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `peppy fleet list` | Prints the launcher, the halt, and one line per robot: its option, machine, kind and software, its robot commander and its lease. `--json` prints the whole listing | | `peppy fleet halt` | Halts the stack | | `peppy fleet clear-halt` | Ends the halt | `peppy node call` asks `check_move` before it calls a marked member, and ends a refused call with the exit code of a refusal, 3. While its goal on a marked member runs, it follows `changes`, and at a halt it cancels the goal as at a Ctrl-C. `peppy stack join` and `peppy stack remove` end a join or a removal that a lease refuses with the exit code 3, and print the failure kind and the message of the daemon. # Content pins > How a manifest pins the exact contract or pairing document it was written against, and how that composes with launch-time pinning Two mechanisms fix which bytes a node’s interfaces are generated from, and they answer different questions: what an author requires, and what a launch decides. ## Author pins: what a manifest may state [Section titled “Author pins: what a manifest may state”](#author-pins-what-a-manifest-may-state) Every place a manifest references a contract or pairing document by `name:tag` accepts an optional `sha256`, the fingerprint of the exact document file the author wrote the node against: ```json5 depends_on: { contracts: [ { link_id: "cam", name: "rgb_camera", tag: "v1", sha256: "3f9c0e21ab7e5f6d8a4b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f" } ], } ``` An unpinned reference resolves to whatever the repository caches hold for that `name:tag`; a pinned one resolves only to the exact stated content. When the caches hold different bytes, `node add` and `node sync` name each cached copy of that `name:tag`, with its fingerprint and where it was read, and advise running `peppy repo refresh`, then changing the pin or registering the repository that serves those bytes; a launch refuses the resolution naming both fingerprints. Pin when a node’s correctness depends on a specific revision of a document that a tag alone does not identify; leave unpinned to follow the document as its repository evolves. An author pin is a statement about authorship: it travels with the manifest, so every machine that ever adds the node enforces it. A node uses one content for each document that its manifest names. Two references to one `name:tag` of a contract, or of a pairing, with two different `sha256` values make the manifest invalid, so `node sync` and `node add` refuse it and name both values. A reference without a `sha256` resolves when the node is added: an add whose references resolve to two contents of one document is refused, naming both fingerprints. The contract references of an [MCP exposure](/advanced_guides/mcp/#contracts-are-referenced-by-identity-and-optionally-by-content) take the same optional `sha256` with the same meaning: a launch serving the exposure resolves the contract through the pin, and refuses naming both fingerprints when the caches hold other bytes. ## Launch pins: what a launch decides [Section titled “Launch pins: what a launch decides”](#launch-pins-what-a-launch-decides) A launch pins everything, whether the manifests do or not. The machine the launch is submitted to resolves every node, every transitive dependency, and every contract and pairing document once, and every machine in the launch runs exactly the content it resolved; see [Federation](/advanced_guides/federation/#what-crosses-a-daemon-boundary). A launch pin exists for the duration of one launch and is minted from whatever the submitting machine’s caches held at that moment. The two compose rather than compete. Where a manifest carries an author pin, the launch resolves the reference through it, so the launch pin and the author pin name the same bytes. A launch whose closure would need one document at two different contents is refused up front, naming both fingerprints, because a single launch runs a single answer for each identity. # MCP exposure > Publish selected parts of a Peppy stack to MCP clients as resources, tools, and tasks through the server built into peppy An **MCP exposure** makes selected parts of a running Peppy stack available to [Model Context Protocol](https://modelcontextprotocol.io) clients. A client can read camera frames, look through a camera, call services, and run long-running actions through one HTTP endpoint. The client does not need a Peppy session, access to the messaging layer, or knowledge that the system uses Peppy. An exposure is an allowlist. In one document, you choose the contract members to publish and give each one a stable public name, a description, and operational policies. A launcher names the exposures to serve, and the daemon runs the MCP server that is built into the `peppy` binary for them: one process, one loopback port, one endpoint per exposure. Nothing is generated or built. **Anything you do not name is not reachable through the endpoint.** This remains true even if a client guesses a name or knows the internal one. A client sees only the selected members, even when the underlying stack contains more. You do not write the public request and response schemas by hand. Peppy derives them from the referenced contracts and [daemon interfaces](#daemon-targets), at check time and again when the server starts, so the published schemas cannot drift from the definitions behind them. ## What an exposure publishes [Section titled “What an exposure publishes”](#what-an-exposure-publishes) An exposure draws from [contracts](/advanced_guides/contract_implementation/), which node instances implement, and from the [daemon interfaces](#daemon-targets) that peppy serves. Each Peppy communication type has an MCP equivalent: | Contract member | Published as | What a client can do | | -------------------------------------------------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | [Topic](/advanced_guides/topics/) | **Resource** | Read the latest policy-approved snapshot and subscribe to updates | | [Topic](/advanced_guides/topics/) with a [`picture`](#picture-tools) | **Picture tool**, beside the resource | Call it and get the latest frame as an image, with the rest of the message | | [Service](/advanced_guides/services/) | **Tool** | Call it and get the answer in the same request; under a [`representation`](#service-policies), the answer’s frame as an image | | [Action](/advanced_guides/actions/) | **Action-backed tool** | Run the goal inside the call, or as an MCP task: get a task handle, watch progress, confirm, cancel, and reconnect | An exposure that declares a [`call_record`](#the-call-record) also publishes one tool of its own: the last calls of every tool that is not read-only, with the client that made each and how it ended. The server supports MCP revision `2026-07-28` over Streamable HTTP. It includes the tasks extension (SEP-2663), which a client opts into per request; an action-backed tool runs as a task for a client that declares it and inside the call for one that does not. ## The exposure document [Section titled “The exposure document”](#the-exposure-document) An exposure is a standalone JSON5 document with `peppy_schema: "mcp_exposure/v1"`. Its filename does not matter. The `name:tag` in its manifest identifies it, [`peppy repo index`](/advanced_guides/repositories/#index-a-repository) discovers it by its content, and a launcher lists it by that `name:tag`. The manifest may also carry `labels`, a list of free-form strings for whoever browses the repository. Here is a complete example with two targets. The camera provides an image resource, the picture tool that shows its frame, and two tools. The recorder provides a `record_episode` tool that creates a task and requires confirmation. exposures/camera_and_recording.json5 ```json5 // The public MCP surface of one robot: a live camera to look through and an // episode recorder to drive. Everything an MCP client can ever see is named // in this file; anything the running stack also carries stays private. // // This document is the whole artifact. A launcher lists it under // `source: { exposures: [...] }` and the daemon serves it from the server // built into peppy; `peppy repo index --check --validate-mcp-exposures` // checks it against the contracts it references, and `peppy mcp catalog` // prints what an endpoint for it advertises. { peppy_schema: "mcp_exposure/v1", manifest: { name: "camera_and_recording", tag: "v1" }, // Advertised to clients through `server/discover`. `instructions` is the // prose a model reads before it decides what to call. server: { title: "OpenArm camera and recording", instructions: "Observe the front camera and record teleoperation episodes.", }, targets: { // A LOGICAL target, not an instance. `front_camera` becomes the `link_id` // of a `depends_on.contracts` slot of the server's node, so the launcher // decides which running instance fills it. The same exposure serves a // simulated camera and a real one. front_camera: { contract: { name: "rgb_camera", tag: "v1", // An optional author pin: the sha256 of the exact contract document // this file was written against (`sha256sum contracts/rgb_camera.json5`). // With it, a launch that resolves other bytes for `rgb_camera:v1` // refuses instead of publishing schemas this file never saw. sha256: "44527ab0542ac56389806315f21c6977c535a1874527926fcc480dd57fb736ab", }, // A topic becomes a resource: the latest policy-approved snapshot, // which clients read and subscribe to. Under a representation a read // serves the message without its frame, and the frame as a blob. topics: [ { member: "video_stream", resource: "front_camera.latest_frame", description: "Latest frame from the front-facing camera, JPEG encoded.", // A snapshot older than this reads as stale rather than serving // yesterday's frame as if it were current. freshness: { max_age_ms: 2000 }, // Frames arriving faster than this are dropped before any decoding // or transcoding runs. A 30 Hz camera does not become 30 Hz of // JPEG encoding for a client that reads twice a minute. update: { max_hz: 2 }, // Interpret the message as an image and publish it as JPEG. The // roles name members of THIS topic's message format. representation: { image: "jpeg", quality: 80, fields: { data: "frame", encoding: "encoding", width: "width", height: "height", }, }, // The frame is a variable-length byte array, so its serialized size // has no static maximum and the runtime size policy is mandatory. max_result_bytes: 524288, on_oversize: "downscale", // The same frame through a tool: a model that calls it gets the // picture as an image, beside the rest of the message. It reads // the snapshot the resource serves and takes no argument. picture: { tool: "front_camera.look", description: "Look through the front-facing camera: the latest frame as a picture.", }, }, ], // A service becomes a tool that answers within one request. services: [ { member: "video_stream_info", tool: "front_camera.info", description: "Report the camera's resolution, frame rate, and encoding.", operation: "read_only", deadline_ms: 2000, }, { member: "set_brightness", tool: "front_camera.set_brightness", description: "Set the camera brightness in device units.", operation: "mutating", deadline_ms: 2000, // Narrows what the published input schema accepts. The contract's // `i8` would allow -128..127; this exposure allows -64..64, and the // refusal happens at the endpoint, before the Peppy graph is // touched. restrict: { value: { min: -64, max: 64 } }, }, ], }, recorder: { // No pin: the exposure follows `episode_recording:v1` as its repository // evolves, and each launch validates it against the bytes it resolves. contract: { name: "episode_recording", tag: "v1" }, // An action becomes a tool. For a client that declares the MCP tasks // extension the call returns a task handle, feedback drives the // status message, and `tasks/cancel` forwards to the action's cancel // path; for any other client the goal runs inside the call. actions: [ { member: "record_episode", tool: "recorder.record_episode", description: "Record one teleoperation episode to the local dataset.", operation: "long_running", // Advertised to the client: this one moves the robot. safety_sensitive: true, // The task parks in `input_required` until the client confirms // through `tasks/update`. No goal is sent before that, and only // a client with the tasks extension can call the tool. confirmation_required: true, deadline_ms: 900000, }, ], // `finish_session` is live on the recorder and deliberately absent // here. A member that is not selected is not reachable through the // endpoint at all. }, }, } ``` It selects from these two contracts: contracts/rgb_camera.json5 ```json5 { peppy_schema: "contract/v1", manifest: { name: "rgb_camera", tag: "v1", description: ["A color camera: its frames, the settings of its stream and its brightness."], }, interfaces: { topics: [ { name: "video_stream", description: "Each frame of the camera, with its size and its encoding.", qos_profile: "sensor_data", message_format: { frame: { $type: "array", $items: "u8", $description: "The pixels of the frame, in its encoding." }, encoding: "string", width: "u32", height: "u32", }, }, ], services: [ { name: "video_stream_info", description: "The size, the frame rate and the encoding of the stream.", response_message_format: { width: "u32", height: "u32", frames_per_second: "u8", encoding: "string", }, }, { name: "set_brightness", description: "Set the brightness of the camera, and give the brightness that it applied.", request_message_format: { value: "i8" }, response_message_format: { applied: "i8" }, }, ], }, } ``` contracts/episode_recording.json5 ```json5 { peppy_schema: "contract/v1", manifest: { name: "episode_recording", tag: "v1", description: ["A recorder of episodes: it records one episode for each goal, and counts the episodes of its session."], }, interfaces: { actions: [ { name: "record_episode", description: "Record an episode. The goal gives the name of the episode, each feedback gives the last frame that the recorder wrote, and the result gives the number of frames of the episode.", goal_service: { request_message_format: { episode_name: "string" } }, feedback_topic: { message_format: { frame: "u32" } }, result_service: { response_message_format: { frames: "u32" } }, }, ], services: [ { name: "finish_session", description: "End the session, and give the number of episodes that it recorded.", response_message_format: { episodes_recorded: "u32" }, }, ], }, } ``` `finish_session` is live on the running recorder and absent from the exposure. It stays private. ### Targets are logical, not instances [Section titled “Targets are logical, not instances”](#targets-are-logical-not-instances) Each key under `targets` names a **role**, not a running node. A target names exactly one source: `contract` for the members of a contract, or `daemon` for the members of a [daemon interface](#daemon-targets). The server’s manifest declares one `depends_on.contracts` slot per contract target, with the target name as its `link_id`, and the launcher connects that slot to a running instance at [deploy time](#deploy-it). The same exposure can therefore work with a simulated camera or a real one without being changed. A target name follows the rules of a node name, because it becomes a slot’s `link_id`. A target must select at least one member, and an exposure must declare at least one target. ### Contracts are referenced by identity and, optionally, by content [Section titled “Contracts are referenced by identity and, optionally, by content”](#contracts-are-referenced-by-identity-and-optionally-by-content) A target’s `contract` names the contract by `name:tag`, and selects members of the contract that resolves under that identity. A contract can change under its tag: the fields of a message, or the [failure kinds](#refused-and-failed-calls) it declares. The `sha256` is optional. It is an [author pin](/advanced_guides/lockfiles/#author-pins-what-a-manifest-may-state) with the meaning pins have everywhere in Peppy: * **Present:** the contract resolved for the exposure must fingerprint to exactly that value. A launch or a repository check that resolves different bytes refuses, naming the pinned fingerprint and the resolved one. * **Absent:** the launch pins the contract bytes it resolves, and the exposure is validated against those. The exposure follows the contract as its repository evolves. The value is the SHA-256 hash of the contract document’s exact bytes: `sha256sum contracts/rgb_camera.json5`. Pin when the schemas you published to clients must not change under you without a deliberate republication of the exposure. ### Daemon targets [Section titled “Daemon targets”](#daemon-targets) A **daemon target** names `daemon: { name, tag }` instead of a contract. Its members are functions of the peppy daemon, for example the addition of a robot to the stack. A daemon interface is a document in the contract format that is compiled into `peppy`. No node implements it: the daemon serves it on the messaging layer, and the server calls it there as it calls a contract. exposures/framework_controls.json5 ```json5 // An exposure whose two targets name daemon interfaces: // `robot_membership:v1`, the copies of the launch, and `robot_leases:v1`, the // fleet of the stack and its halt. The peppy daemon of the coordinator serves // them, and no node implements them, so the targets take no `links`: the // launcher gives each a scope. The scope of `stack` gives the robot options a // client may add, the features of each, and the most robots of them on the // stack; the scope of `fleet` names the members its client may call. { peppy_schema: "mcp_exposure/v1", manifest: { name: "framework_controls", tag: "v1" }, server: { title: "Robot stack (peppy framework)", instructions: "Add robots to the stack and remove them. stack.list reports the robot options this stack offers with their features, the machines of the stack and the robots it can remove. A robot and each of its features run on a machine: a peppy daemon, named by its core node name.", }, call_record: { tool: "stack.recent_calls", description: "List the last calls of this endpoint that could change the stack, newest first, each with its outcome, and the failure kind and message of a refused or failed call.", keep: 200, }, targets: { stack: { // A daemon interface is compiled into peppy and is never pinned: // `daemon` takes a name and a tag, and no `sha256`. daemon: { name: "robot_membership", tag: "v1" }, services: [ { member: "list", tool: "stack.list", description: "Report the robot options this stack can add with their features, the machines of the stack and this stack's machine, the robots of these options on the stack with their features and machines, the most robots it holds, and the addition or removal of a robot that runs now. launch_copies lists the robots of these options that the launch of this stack started, each as the launch started it, in the form of an item of copies without its running field: they stay listed whether or not each one is on the stack now, from the launch of the stack until its reset, the next launch or the end of this machine's daemon, and stack.join and stack.remove do not change them; the list is empty after a reset, until the next launch. Each item of launch_copies, and each item of copies with its running field left out, is a valid stack.join input: for a robot that stack.join added, it makes the same robot on the same machines; a robot that the command line added can differ from the robot that its item makes.", operation: "read_only", deadline_ms: 5000, }, ], actions: [ { member: "join", tool: "stack.join", description: "Add a robot of option to the stack under name on the machine core_node, with the features it names, each on its own machine, and wait until its software runs on each of its machines.", operation: "long_running", progress_timeout_ms: 660000, }, { member: "remove", tool: "stack.remove", description: "Remove a robot from the stack, and wait until its software has stopped.", operation: "long_running", progress_timeout_ms: 660000, }, ], }, fleet: { daemon: { name: "robot_leases", tag: "v1" }, services: [ { member: "list", tool: "fleet.list", description: "Report the robots of this stack with their software and their leases, and the halt of the stack.", operation: "read_only", deadline_ms: 5000, }, { member: "halt", tool: "fleet.halt", description: "Halt the stack: end every lease, and refuse every move until fleet.clear_halt.", operation: "mutating", deadline_ms: 5000, }, { member: "clear_halt", tool: "fleet.clear_halt", description: "Clear the halt of the stack. It starts nothing again.", operation: "mutating", deadline_ms: 5000, }, ], }, }, } ``` * **Never pinned.** A daemon target takes no `sha256`. peppy serves one tag of each interface, the tag of its release, and no older one. A change of members, or of what a member means, takes a new tag, so a document that names an interface ships with the peppy release that serves its tag. * **One grammar.** Members, public names, descriptions and every policy are the same as on a contract target. The member rules also apply: a member that the interface does not declare, a member selected twice, a target with no member and a public name used twice are refused. * **Fixed surface only.** A daemon target sits on a fixed surface. On a [per-robot surface](#per-robot-surfaces) every tool is routed by `robot`, so a daemon target belongs in an exposure without `robots`. * **A slot that the daemon binds.** The derived node has a daemon slot for each daemon target, and consumes the members of its entries on it. The daemon binds the slot to the daemon that serves the interface each time it starts the server, so the launcher writes no link. It gives the target a **scope** instead: what a client of the target may do. A deployment whose exposures hold only daemon targets is valid. * **The coordinator.** An instance that serves a daemon target runs on the coordinator, the daemon that the launch was sent to: it reads and changes the stack of that daemon. A node calls a daemon interface through a daemon target of its own manifest, a `depends_on.daemon` entry, which the launcher scopes the same way: see [Daemon targets](/advanced_guides/core_node_functions/#daemon-targets). #### The interfaces peppy serves [Section titled “The interfaces peppy serves”](#the-interfaces-peppy-serves) | Interface | Members | What a client does | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `robot_membership:v1` | service `list`, actions `join` and `remove` | Lists, adds and removes the robots of the stack, the [copies](/guides/launch_files/#copies) of the running launch, within the options and the features the scope names, on the machines of the federation | | `robot_leases:v1` | services `list`, `contract`, `take`, `release`, `offer`, `open`, `close`, `check_move`, `halt` and `clear_halt`, actions `changes` and `lease` | Lists the robots of the launch with their software and their leases, leases robots, checks a move, and halts the stack (see [Robot leases and the halt](/advanced_guides/fleet/)) | The daemon of the coordinator of the launch serves both interfaces. It checks each call against the scope of the daemon target of its sender, the sender that the call proves (see [The senders of the calls to a daemon](/advanced_guides/call_senders/)), refuses a call outside it with `rejected`, and refuses each call of a sender that has no daemon target of the interface, except for `check_move` of `robot_leases:v1`, which answers every sender, and `changes`, which answers each MCP server of peppy. The command line has no scope: it calls every member of `robot_leases:v1`, and changes the copies with `peppy stack join` and `peppy stack remove`. Every MCP server has a daemon slot of `robot_leases:v1`, through which it keeps the [rules of the members that move a robot](#members-that-move-a-robot): the slot of the target of its exposures that names `robot_leases:v1`, or a slot `fleet` that the planner adds. A target of another source under the name `fleet` is refused. A machine is the core node name of a peppy daemon: the name that presence lists and that `--place NAME@CORE_NODE` takes. The members of `robot_membership:v1`: | Member | Request | Feedback | Response or result | | ----------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list` (service) | none | | `options`: each `{ option, model, description, features, kind }` of the scope, `features` each `{ feature, description }`, empty when the option has none, and `kind` `simulated` when each instance that the option and its features can bring reads the clock of a simulation, else `physical`. `core_nodes`: this machine and every live daemon of the same workspace or project, each once, in name order. `this_core_node`: the machine of this stack, the coordinator. `copies`: each `{ name, option, core_node, features }`, the copies of the scope’s options on the stack, in name order: `core_node` is the copy’s machine, which runs its base, and `features` holds each feature of the option that the copy holds, as `{ feature, core_node }` with the machine of its part, and `running` is `true` while the process of each instance of the copy runs. `max_copies`: the most copies of the scope’s options on the stack. `change`: `{ action, name, option }`, the addition (`join`) or the removal (`remove`) of a copy of a scoped option that runs now; absent while none runs. `launcher`: the launcher of the stack. `launch_copies`: the copies of the scope’s options that the launch started, each as the launch started it, in the form of `copies` without its `running` and in name order; a join or a removal leaves them as they are, and a reset empties them | | `join` (action) | `name`, `option`, `core_node`, `features`: each `{ feature, core_node }` | `step` (`launch`, `add`, `build` or `run`) and `line`, one message per line of the join’s log | none: a join that completes gives an empty result, and a join that fails gives a failure kind and a message that says why and names the log files | | `remove` (action) | `name` | `step` and `line`, one message per line of the removal’s log | none: a removal that completes gives an empty result, and a removal that fails gives a failure kind and a message | Beside the kinds of peppy, `robot_membership:v1` declares three failure kinds in its `failure_kinds` block, the kinds of the daemon. `busy`, “Other work runs on the daemon; the same request can succeed once that work ends”: `join` and `remove` are refused with it while another stack change or node operation runs on the daemon, and a client that reads `busy` can call again once that work ends. `halted`, “The stack is halted”: a lease holder joins no robot during a halt. `leased`, “Another client holds the lease of the robot”: a join under the name of a robot that another client leases, and the removal of such a robot, are refused with it, and the message names the holder and the lease name (see [Leases](/advanced_guides/fleet/#leases)). `join` adds a copy of `option` under `name` on the machine `core_node`, with the features it names, each part on its own machine, as `peppy stack join OPTION:NAME@CORE_NODE` does with one `--with axis=option@CORE_NODE` word for each feature, the axis and the option that the scope gives that feature: the option’s entry in the launcher decides the rest of the copy’s selection. Every field is required, and `features` is empty for the copy of the launcher’s entry. So each item of `copies`, without its `running`, and each item of `launch_copies` is a valid `join` input, and for a copy that `join` added, it adds the same copy on the same machines. `remove` stops and removes a copy, as `peppy stack remove NAME` does. #### Scopes [Section titled “Scopes”](#scopes) The launcher gives each daemon target its scope with [`daemon_scopes`](/guides/launch_files/#daemon_scopes-optional) on the instance, or with a `set_daemon_scopes` adjustment. The launch parses every scope into the type of its interface before anything starts. The scope of a daemon target of `robot_membership:v1` is the value under its target’s name: launchers/mcp_framework_controls.json5 ```json5 // Deploying an exposure with a daemon target: the robots run as copies, and // the framework's endpoint lets a client add and remove them. // // peppy stack launch mcp_framework_controls { peppy_schema: "launcher/v1", description: ["Simulated robots that run as copies, OpenArm or SO-101, and the MCP endpoint framework_controls:v1, through which a client adds and removes them. It needs a machine that runs the simulation."], components: [ { name: "robot", cardinality: "zero_or_more", options: { // Its fragment declares the own axis `brain`, whose option // `ai_brain_vla` deploys the brain's instance. openarm_sim: "robots/fragments/openarm_sim.json5", so101_sim: "robots/fragments/so101_sim.json5", }, }, ], deployments: [ { source: { exposures: ["framework_controls:v1"] }, instances: [ { instance_id: "framework_controls_inst", arguments: { port: 8903 }, // The daemon targets take no link. Each takes a scope, keyed by // the target's name. The instance has no `core_node`: an instance // that serves a daemon target runs on the coordinator. daemon_scopes: { // The members of robot_leases:v1 that the endpoint calls: a client // lists the fleet and halts the stack. Without `clear_halt`, the // endpoint serves no fleet.clear_halt, and the halt ends with // `peppy fleet clear-halt`. fleet: { members: ["list", "halt"] }, stack: { max_copies: 4, options: [ { option: "openarm_sim", // The robot model a robot of the option is, which a // client reads before it adds one. model: "openarm_v2", description: "A simulated OpenArm v2 standing on the floor: two arms with grippers", // A feature selects one option of one own axis of the // option, here `brain=ai_brain_vla`. A client adds a robot // with it, and names the machine of its part. features: [ { feature: "ai_brain", axis: "brain", option: "ai_brain_vla", description: "An AI brain that finds items by words, then grabs and places them", }, ], }, { option: "so101_sim", model: "so101", description: "A simulated SO-101 clamped on the edge of a table: one arm with a gripper", }, ], }, }, }, ], }, ], } ``` * `options` names at least one option, each option once. `option` is an option of an axis of the launcher that runs as copies. `model` is the id of the robot model that a copy of the option is, for example `openarm_v2`: letters, digits, `_` and `-`. A client reads it before it adds a copy, for example to show a picture of that model. `description` is one line of at most 200 characters that says what a copy of the option is. * `features` is optional: leave it out for an option with no feature, because `features: []` is refused. It lists at most 6 features. A feature is one choice that the author offers on a copy of the option: `feature` is its name, `axis` and `option` are the one option of one own axis of the scoped option that a copy with the feature holds, and `description` is one line of at most 200 characters that says what the feature adds. Two features of one option with the same name, or on the same axis, are refused. * The description of an option says what the robot is, and the description of a feature says what it adds. * `max_copies` is a number from 1 to 65535: the most copies of these options on the stack. The launch and [`peppy stack resolve`](/guides/launch_files/#auditing-a-composed-launch) also hold a `robot_membership` scope against the launcher and the stack selection, in three steps. A step runs only when the steps before it hold: 1. Each option is an option of an axis that runs as copies. In a launcher that declares no such axis, a flat launcher included, the scope gets one refusal that says so. 2. Each feature selects an own axis of its option and an option of that axis, and that option brings at least one instance, because a feature’s part can run on another machine. This step composes nothing, and each refusal names what the option offers: “feature `ai_brain` of option `so101_sim` selects `brain=ai_brain_vla`, but `so101_sim` has no own axis `brain`; its own axes: `robot_commander`, `recorder`, `camera_rig`”. 3. Every feature set of each option (no feature, each feature, each combination of features) composes as a join over the bare stack that the selection resolves, never over the copies the launch starts. A refusal names the option and the features of the set, then the reason of the composition: “option `openarm_sim` with the features `ai_brain`: …”. The copy with no feature must hold none of the option’s features: a feature that the option’s launcher entry already selects adds nothing, and is refused. The nodes of these trial copies are the joinable nodes that the launch builds on the coordinator before any join (see [Building the nodes a join brings](/guides/launch_files/#building-the-nodes-a-join-brings)). The verdict depends only on the launcher and the stack selection, which a join does not change, so a join holds each scope to the rules of its instance and not to these steps. The server narrows the published schemas of a daemon target with its scope. For `robot_membership`, `join.option` takes only the options of the scope; `join.name`, `join.core_node`, the `core_node` of each feature item and `remove.name` take only a core node name: 1 to 63 letters, digits, `_` or `-`, and not `self`, the rule that the daemon and the CLI apply to a copy and to a machine; and the `feature` of a feature item takes only a feature of the scope, of any of its options. In a scope with no feature, `features` takes only an empty array. For `robot_leases`, the server serves only the tools of the members that the scope gives: a scope of `["list", "halt"]` serves `fleet.list` and `fleet.halt`, and no `fleet.clear_halt`. No schema lists the machines, because the machines of the federation change while the endpoint runs: a machine that joins the federation after the launch can take a copy or a feature. The endpoint refuses input outside the narrowed schema before the call reaches the daemon, and the [call record](#the-call-record) writes the call as `refused`. [`peppy mcp catalog`](#check-it) prints the tools and the schemas of the interface without the narrowing, because the scope belongs to an instance of the server and not to the exposure. #### What the tools of `robot_membership` do [Section titled “What the tools of robot_membership do”](#what-the-tools-of-robot_membership-do) The tools call `robot_membership:v1` on the daemon of the coordinator, which runs each join and each removal as `peppy stack join` and `peppy stack remove` do, for the sender of the call. * `list` answers the options of the scope with their models, their descriptions, their features and their kinds, `core_nodes`, `this_core_node`, the copies whose option is in the scope in name order, `max_copies`, the launcher and the copies of the scope’s options that the launch started, within the deadline of the tool. It reads the stack and presence at the same time, on every call, so a machine that starts after the launch is in the next `core_nodes`, and a machine that stops is not. A presence read that fails makes `list` fail: “the live machines of the federation could not be read: …”. * Each copy in `copies` names its machine, and the features of its option that its selections hold, in the scope’s order, each with the machine of its part, which is the copy’s machine when the part runs with the copy. A part on another machine that no feature of the scope selects is not listed. A copy that `peppy stack join` or `--join` added is listed the same way, and its item can then make another copy than the one listed, when a word of the command line selects or places a part that no feature of the scope names. A copy whose machine, or the machine of one of its features, is not in `core_nodes` has software on a machine that is not live now, and a copy whose software stopped stays listed with `running` false until its removal. * While the daemon adds or removes a copy of an option of the scope, from any client, `list` also answers that change: `"change": { "action": "join", "name": "bravo", "option": "so101_sim" }`. A copy that joins is in `copies` only once its join ends, so `change` is where a client sees it in the meantime, also after a call that stopped waiting. While the daemon has not yet admitted or refused a `join` of `robot_membership:v1`, `list` waits for that answer, so the join is in `change` from the moment the daemon takes it. * `launch_copies` holds the copies of the scope’s options that `peppy stack launch` started, the file’s copies and the `--join` ones, each as the launch started it, in the form of `copies` without its `running`. The daemon keeps them from the launch until `peppy stack reset`, the next launch or the end of the daemon, and a join or a removal leaves them as they are: a copy that a removal took off the stack stays in `launch_copies`. Each item is a valid `join` input, under the rules of `join`: a lease of the copy stays when it leaves the stack, so the join of its item by another client is refused with `leased` until that lease ends. The item of a copy that a word of the launch, or the copy’s entry in the launcher, shaped with a part that no feature of the scope names, or with `arguments` or `adjustments` of its own, can make another copy than the one the launch started. A copy in `copies` whose item, without its `running`, is not in `launch_copies` is one `join` or `peppy stack join` added. * `join` first parses its goal: the name as a copy name, the option as an option of the scope, each machine as a core node name, and each feature as a feature of the option, named once. It refuses, with `rejected`, a feature that the option does not offer (“`ai_brain` is not a feature of option `so101_sim`, which has no feature”, or with the list of the option’s features) and a feature named twice (“`features` names feature `ai_brain` twice; name each feature once”). * `join` then reads the copies of the stack. It refuses, with `precondition_failed`, a name that a copy of any option has (“a copy `bravo` is already on the stack; choose another name”), and a stack that holds `max_copies` copies of the scope’s options, naming them. It then runs the join of the option under the name on its machine, with the word `axis=option` of each feature on the machine of its part, as `peppy stack join OPTION:NAME@CORE_NODE --with axis=option@CORE_NODE` does: a machine equal to `this_core_node` travels as the coordinator, and a feature on the copy’s machine names no machine, so its part runs with the copy’s base. The join carries no argument and no environment, and it runs under the [default budgets](/guides/launch_files/#launch-timeouts) of the CLI. Each instance that it starts runs with its `env_vars` and the kept values of its [`env_from_launch`](/guides/launch_files/#env_from_launch-optional): the values of the launch environment that the daemon keeps for the stack. The add and build steps of the join get no environment. The join is the join of the sender of the call, which the [leases](/advanced_guides/fleet/#leases) read. * The launch builds on the coordinator every node that a `join` of a scoped option can bring (see [Building the nodes a join brings](/guides/launch_files/#building-the-nodes-a-join-brings)), so a `join` on `this_core_node` adds and starts nodes and builds none. A part that a `join` places on another machine builds on that machine when the join runs, which can take minutes the first time, and so do the nodes of every join after a launch with `--no-prebuild`. * The daemon reads presence when it plans a join that names another machine, and refuses a machine that is not live before any machine changes. The join then fails with the kind `resource_unavailable`, and its message lists the live machines: “these core nodes are not live on the federation: `cn-gpu-box`. Live right now: `cn-desk`. …”. A machine in `core_nodes` can still refuse a join, for example one that runs another peppy version, that another launch holds, or that holds instances outside this launch, and a node of a filesystem repository runs on the coordinator alone (see [Federation](/advanced_guides/federation/#limits)). These joins fail the same way, with the kind and the reason of the daemon. * When the daemon accepts the join, its first feedback says so, `{ "step": "launch", "line": "the daemon accepted the addition of bravo (so101_sim)" }`, and each line of the join’s log follows as `{ step, line }`, where the step is `launch`, `add`, `build` or `run`. The endpoint shows each feedback to the client as its JSON text. The lines of a starting instance are in it. A join that completes gives an empty result: the copy is on the stack. A join that fails is undone, and fails with the kind of its failure and a message that says why and names the log files, “the addition of bravo failed: …. Log files: …”: the log of the join, then the log of the node phase that failed. The kind is `precondition_failed` for a stack that does not allow the join, for example a copy of that name that joined since the read of the stack, `resource_unavailable` for a machine that is not live, `timeout` for a budget that ran out, and `attempt_failed` for a step that failed, such as a build. When the undo cannot clean up, the message says that the copy remains listed. * The daemon runs one `join` of `robot_membership:v1` at a time, from its read of the stack until its work ends, also after the call ended. Another `join` in that time is refused with the kind `busy`: “a `join` of robot_membership:v1 is in progress on this daemon; wait for it to finish”. The daemon refuses a `join` with the kind `busy` too while another stack change or node operation runs on it: “the daemon refused the addition of bravo: …”. * `remove` reads the copies of the stack, and refuses, with `rejected`, a name that is not a copy of an option of the scope (“no copy `zulu` of the options openarm_sim and so101_sim on the stack”). It then runs the removal, which reports each instance that it stops, the last started first, on each machine of the copy, and what it leaves on a machine where nothing stops (see [copies](/guides/launch_files/#copies)). A removal that completes gives an empty result: the copy is off the stack. A removal that the stack does not allow, for example of a copy whose clock the stack reads, or of the last copy of a `one_or_more` axis, fails with the kind `precondition_failed`. The daemon refuses a removal while another stack change or node operation runs, with the kind `busy`. * A client that cancels a `join` or a `remove`, with `tasks/cancel` on a task or by closing the call (see [Goals and connections](#goals-and-connections)), makes the endpoint send the daemon the cancel of the goal. The daemon gives the feedback `{ "step": "launch", "line": "the client cancelled the addition of bravo; the daemon stops it and undoes it" }`, stops the change at the step it reached, and ends it as a failure at that step ends it: a join is undone, and a removal keeps the copy, with the instances that it did not stop yet. The endpoint follows the goal to that end, and the call or the task ends cancelled, “the addition of bravo was cancelled by its caller”. A change that the daemon ended before the cancel keeps its end. A task whose connection closes cancels nothing. Call `list` before you add or remove again: its `change` reports the change until it ends. * A goal of `join` or `remove` follows the [action policies](#action-policies) of any goal: when the daemon sends nothing for one progress window of the document, the call fails with “no progress within 660000 ms; the endpoint stopped following the goal and cancelled it”, and the daemon stops the change at its cancel. A goal that ends with no result, for example because the daemon is gone, fails the call. The [call record](#the-call-record) writes: | Call | `outcome` | `failure_kind` | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ---------------------- | | Input outside the narrowed schema | `refused` | | | A refusal of the daemon before the change: a feature that the option does not offer or that the input names twice, a name that is no copy of the scope, or a sender outside the scope | `refused` | `rejected` | | A refusal of the daemon before the change: a name in use or the limit | `refused` | `precondition_failed` | | A refusal of the daemon before the change: a second `join`, or another stack change or node operation | `refused` | `busy` | | A refusal of the daemon by a lease or by a halt | `refused` | `leased` or `halted` | | A join or a removal that completed | `completed` | | | A join or a removal that failed, a join refused for a machine that is not live included | `failed` | the kind of the daemon | | A join or a removal that the client cancelled | `cancelled` | | | A silent daemon, or a goal with no end | `failed` | | ### Public names [Section titled “Public names”](#public-names) `resource`, `tool` and `picture.tool` set the names that clients see. You choose these names, and they do not need to match the internal member names. All public names share **one namespace across the whole exposure**. A resource and a tool cannot share a name, even across targets. Names must be 1 to 128 characters long and use only ASCII letters, digits, `_`, `-`, or `.`. A `.` cannot be the first or last character or appear next to another `.`. A resource’s URI is derived from its name as `peppy://resource/`. Each exposure is its own endpoint with its own catalog, so two exposures served by one process may reuse a public name without conflict. ## Policies [Section titled “Policies”](#policies) Policies limit how each published member can be used. You declare them for each member, and the running server enforces them. ### Topic policies [Section titled “Topic policies”](#topic-policies) | Field | Required | What it does | | ---------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `freshness.max_age_ms` | yes | Treat a snapshot older than this as stale instead of returning it as current | | `update.max_hz` | yes | Limit how often the snapshot refreshes and notifies subscribers. Faster messages are dropped **before** decoding or transcoding | | `representation` | no | Interpret the message as an image and publish its frame in a codec, as a blob apart from the rest of the message (see below) | | `max_result_bytes` | conditional | Cap on the snapshot content after representation runs: the serialized document plus, under a representation, the base64 text of the blob | | `on_oversize` | conditional | What to do when the content exceeds that cap: `downscale` (re-encode small enough to fit) or `reject` (report the read as failed) | | `picture` | no | Publish the frame through a [picture tool](#picture-tools) as well. Requires a `jpeg` representation | The message format determines whether the size policy is required: * A payload with a **static maximum size** contains only fixed-size scalars, fixed-length arrays, or nested objects made from those types. `max_result_bytes` is optional. If you set it, it must be at least the maximum possible size. Do not set `on_oversize`, because the payload cannot exceed that limit. * A payload with **no static maximum size** contains a `string`, `bytes`, or a variable-length array, such as a camera frame. You must set both `max_result_bytes` and `on_oversize` to limit what a read can return. An image `representation` names members of the topic’s own message format by role: ```json5 representation: { image: "jpeg", // `png16` for a 16-bit single-channel frame, or `raw`, which passes the frame bytes through untouched quality: 80, // `jpeg` only; `png16` is lossless and `raw` has no encode step fields: { data: "frame", // `bytes` or an array of `u8` encoding: "encoding", // `string` width: "width", // `u8`, `u16`, or `u32` height: "height", // `u8`, `u16`, or `u32` }, depth_range: { near: 100, far: 10000 }, // `jpeg` only; how a `z16` depth frame renders } ``` All four fields must refer to required, non-`$optional` top-level members of the correct type. The runtime needs all four values to interpret a frame. `jpeg` transcodes `rgb8` and `bgr8` frames, and `z16` depth frames under a `depth_range`; `png16` transcodes frames of one unsigned 16-bit little-endian sample per pixel, labeled `z16`, `mono16` or `16UC1`, such as a depth map, and writes the frame as a 16-bit PNG under the encoding `png`. A frame already labeled `jpeg` or `mjpeg` under `jpeg` passes through untouched; a `png` frame under `png16` passes through once it decodes as 16-bit single-channel, and any other PNG is refused. A 16-bit frame keeps one source sample per output pixel. A `jpeg` representation renders `rgb8` and `bgr8` frames in color, and 16-bit depth frames, labelled `z16`, `mono16` or `16UC1` (one little-endian `u16` reading per pixel, 0 for a pixel with no reading) as a grayscale picture. `depth_range` sets the readings that picture spans, in the frame’s own counts, so one shade means one distance on every frame a client reads: a reading at `near` or nearer renders white, one at `far` or farther black, readings between them in linear proportion, and 0 black. `near` must be above 0 and below `far`. A `z16` frame that arrives on a representation without a `depth_range` is refused, and a `depth_range` on a `raw` representation is a parse error. A snapshot under a representation has two parts, and a read serves each as a content of its own: * The **document** is the message as JSON, without the member `fields.data` names. After a transcode it carries the encoding label and the dimensions of the published frame. * The **blob** is the frame in the codec of the representation, under the MIME type of that codec: | `representation.image` | Blob MIME type | | ---------------------- | -------------------------- | | `jpeg` | `image/jpeg` | | `png16` | `image/png` | | `raw` | `application/octet-stream` | A snapshot of a topic with no representation is a document alone: the whole message as JSON. A target may select one topic member more than once, each entry with its own `resource` name, representation and policies, and each keeping its own snapshot: a depth frame reads as a `jpeg` picture a model judges distance from and as a lossless `png16` frame a program decodes. #### Picture tools [Section titled “Picture tools”](#picture-tools) `picture` publishes the frame of a topic through a tool, beside the resource, for a model that looks on its own: the image of a tool result is the form in which a client hands a picture to the model. ```json5 picture: { tool: "front_camera.look", // a public name, in the one namespace of the exposure description: "Look through the front-facing camera: the latest frame as a picture.", } ``` The topic must carry `representation.image: "jpeg"`: a `png16` or a `raw` frame is data for a program, not a picture for a model. The tool answers inside the call, from the snapshot a read of the topic’s resource serves, under the same freshness policy. It sends nothing to the Peppy graph. On a fixed surface it takes no argument, and on a [per-robot surface](#per-robot-surfaces) it takes the routing arguments of its target. ### Service policies [Section titled “Service policies”](#service-policies) | Field | Required | What it does | | ------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `operation` | yes | `read_only` or `mutating`, advertised to the client. Long-running work is an action, so there is no third value | | `deadline_ms` | yes | How long the call waits before it comes back as a tool error | | `restrict` | no | Inclusive `min`/`max` bounds narrowing numeric request fields | | `representation` | no | Interpret the response as an image and answer its frame as a picture, apart from the rest of the response (see below) | | `max_result_bytes` | no | Cap on the serialized tool result: the serialized document plus, under a representation, the base64 text of the frame. A larger response is a tool error | | `on_oversize` | no | What to do when the result exceeds that cap: `downscale` (re-encode the frame small enough to fit; needs a `jpeg` or `png16` representation) or `reject` (a tool error). Needs `max_result_bytes` | A service `representation` is the [topic `representation`](#topic-policies), on the members of the service’s response: `fields.data` names the response member that carries the frame, and the other three its encoding label and dimensions, all of the same types a topic needs. The tool answers with the frame first and the rest of the response as the text and the structured content. A `jpeg` or a `png16` frame is an image block in the codec of the representation, as a [picture tool](#picture-tools) answers. A `raw` frame is data for a program, not a picture, so it is an embedded resource of type `application/octet-stream` at `peppy://tool//frame`, which a client does not hand to its model as a picture. Its published output schema is the schema of that document: the response without the member the frame is taken from. A response whose frame is empty carries no picture and is answered as the document alone. A service that cannot answer gives an error reply, which reaches the client as the tool error of a [failed call](#refused-and-failed-calls). A frame that does not decode is a tool error. ```json5 { member: "render_view", tool: "scene.look", description: "Look at the simulated world from a free viewpoint.", operation: "read_only", deadline_ms: 10000, representation: { image: "jpeg", quality: 80, fields: { data: "frame", encoding: "encoding", width: "width", height: "height" }, }, max_result_bytes: 524288, on_oversize: "downscale", } ``` `restrict` narrows a numeric range without changing the contract’s type. Each key names a **top-level member of the request format**. Peppy adds the bounds to the published input schema as `minimum` and `maximum`, so clients can see the allowed range. The endpoint rejects values outside that range before sending anything to the Peppy graph. Each bound must fit the member’s type. For example, validation rejects `min: -200` for an `i8`. You cannot restrict a `u64` or `i64` member because its public schema uses a decimal string instead of a JSON number. Use a narrower type in the contract if you need numeric bounds. ### Action policies [Section titled “Action policies”](#action-policies) | Field | Required | What it does | | ----------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `operation` | yes | `long_running`, the only value; actions are long-running by definition | | `deadline_ms` | one of the two | Whole-goal deadline: the longest time the goal may run. The advertised task TTL is this plus a short grace window | | `progress_timeout_ms` | one of the two | The longest time the goal may go without a sign of progress. The goal may run for as long as it makes progress, up to one day as a task. The action must declare a `feedback_topic` | | `safety_sensitive` | no | Advertises that the call changes the physical world. Defaults to `false` | | `confirmation_required` | no | The task waits in `input_required` and sends no goal until the client confirms through `tasks/update`. A client without the tasks extension cannot call the tool. Cannot go with `progress_timeout_ms`. Defaults to `false` | An action declares exactly one of `deadline_ms` and `progress_timeout_ms`. `deadline_ms` bounds the whole goal. Feedback does not extend it. When it passes, the call or the task fails with a message that names the deadline, and the endpoint sends the provider a cancel: no goal runs on with no one following it. `progress_timeout_ms` bounds the silence, not the work. Use it for a goal whose length depends on something the robot does not control, such as assets that download over a slow link. The signs of progress are the admission of the goal, each feedback message, and the end of the feedback stream when the goal settles. Each sign starts a new window, and the request for the result after the end of the stream gets one window. When a window goes by without a sign of progress, the call or the task fails with `no progress within ms; the endpoint stopped following the goal and cancelled it`, and the endpoint sends the provider a cancel. When the client cancels a goal under `progress_timeout_ms`, the endpoint sends the provider the cancel and continues to follow the goal under the same rule: * A goal that completes returns its result, as usual. * A goal that ends cancelled returns the provider’s result as a [cancelled goal](#cancelled-goals). * A goal that stays silent for one window fails with `no progress within ms; a cancel was sent and the provider did not answer it`. The provider’s reply to the cancel is read too. A reply that the goal had already ended means the end of its feedback stream did not come through: the endpoint reads the result at once and returns it, or fails with `the goal ended, but its result is no longer readable` when the provider no longer keeps it. A reply that the provider does not know the goal fails with `a cancel was sent and the provider does not know the goal`. A cancel that fails, for example because no reply came within one window, fails with `a cancel was sent and failed: `, and the endpoint logs it as a warning, because the goal can still run on the provider. A tool of a [daemon target](#daemon-targets) follows the same rule: its goal is a goal of the daemon interface (see [What the tools of `robot_membership` do](#what-the-tools-of-robot_membership-do)). A goal on a [member that moves a robot](#members-that-move-a-robot) is the exception: after one window without a sign of progress, the call fails with `no progress within ms; the goal moves a robot, so the endpoint follows it on until it ends, and cancels it at a halt of the stack`, and the goal gets no cancel. A feedback message that does not decode is logged and not shown to the client. It is still a message the provider sent for the goal, so it counts as a sign of progress. The bound relies on the provider: it publishes a feedback message each time its progress changes, and none while nothing changes. A message sent on a timer while nothing moves would hide a goal that is stuck. The wait for a confirmation is no progress of the goal, and nothing would bound it, so an action cannot declare `progress_timeout_ms` together with `confirmation_required`. Under both bounds, the first wait is for the provider to admit the goal, and it is bounded too: by `deadline_ms`, or by one window of `progress_timeout_ms`. When that wait runs out, the call or the task fails. A provider that acknowledged the goal and did not answer in time gets a cancel of it. A provider that the goal did not reach gets none, and has no goal to run. ### Members that move a robot [Section titled “Members that move a robot”](#members-that-move-a-robot) A contract marks each member that moves a robot or changes the state of a device with `moves_robot` (see [Marks](/advanced_guides/contract_implementation/#marks)). For each tool of such a member, on any target, the server keeps the fleet rules of the stack (see [Robot leases and the halt](/advanced_guides/fleet/)): * Before each call, the server asks `check_move` of the daemon of the coordinator, on the instance that the call goes to. When the daemon refuses the move, the call does not reach the provider. It fails with the text `the stack refused the move: : `, where the kind is `halted`, `leased` or `not_leased`, and its `structuredContent`, or the error of its task, holds `outcome` `refused`, `failure_kind` and `message`. The [call record](#the-call-record) writes it `refused`. A move check that the daemon does not answer refuses the call too: “the daemon did not answer the move check of ``: …”. * While a goal on such a member runs, the server follows `changes` of the fleet. At a halt that a change of a later revision than the move check of the goal gives, it cancels the goal as its client does, and follows the goal to the end that the provider gives. A halt that the follow still shows from before the move check, after the daemon ended it, does not cancel the goal. * A server that cannot see a halt runs no such goal: when the follow of `changes` ends before the server stops it, as when the daemon refuses it or ends it, or its router restarts, the server cancels each goal on such a member, and the next goal follows `changes` again. * The server follows such a goal until it ends, also after its call stopped waiting for it: at the deadline, after a window of `progress_timeout_ms` with no sign of progress, and at the TTL of a task. It sends no cancel then: the goal runs on, and a halt cancels it. A request for the end of the goal that reaches no provider while the provider lives is asked again. A cancel of the client, with `tasks/cancel` or by closing the call, cancels the goal, as for every goal. * The server holds no lease. A call on a robot that another client leases is refused with `leased`, until the holder opens or releases the lease. ### The call record [Section titled “The call record”](#the-call-record) An exposure can keep a record of the state-changing calls its endpoint takes, and publish it through a tool: ```json5 // Beside `server` and `targets`. call_record: { tool: "robot.recent_calls", // a public name, in the one namespace of the exposure description: "The last state-changing calls of this endpoint, newest first, each with how it ended: its outcome, and the failure kind and message of a refused or failed call.", keep: 200, // how many calls the endpoint keeps, 1 to 1000 }, ``` The endpoint records every call of a tool that is not read-only (a `mutating` service, and every action, whether it runs inside the call or as a task) and keeps the last `keep` of them in memory for the life of the process. The tool takes no argument, is listed read-only, leaves no entry of its own, and answers `{ calls: [...] }`, newest first. Each entry carries: | Field | What it says | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `started_at` | When the call started, RFC 3339 on the wall clock of the host, also on an endpoint whose freshness runs on simulated time | | `client` | The `name` and `version` the client declared as its implementation, or `null` when its request named none | | `tool` | The tool called | | `arguments` | The arguments as sent, when their JSON is 1024 bytes or fewer; `null` otherwise | | `arguments_bytes` | The size of the arguments’ JSON | | `outcome` | `running`, `completed`, `failed`, `cancelled` or `refused` | | `failure_kind` | The [failure kind](#refused-and-failed-calls) the provider gave a refused or failed call, else `null` | | `message` | What ended a call that did not complete: the provider’s message of a refused or failed call, the reason of a cancelled call, or the endpoint’s words; `null` for a running or completed call | | `duration_ms` | How long the call ran, once it ended | The entry keeps nothing of a result: a completed goal and a response are a success. A task’s entry is `running` until the task ends, and so is the entry of a call whose client closed it, until the provider ends the cancelled goal. A call ends: * `completed` when the goal completed or the service answered with its response. * `refused` when the provider refused the goal, with the kind it gave; or when the call never reached the provider: its arguments failed the published schema, it named a robot or a member that is not there, it needed the tasks extension the client did not declare, or no provider was bound. Only a refusal of the provider has a `failure_kind`. * `failed` when the goal failed or the service gave an error reply, with the kind the provider gave; or when the call did not reach an end that the provider gave: a deadline, a progress window without a sign of progress, a transport error, a goal that the provider abandoned, a kind that the member does not declare, feedback that overflowed, a task whose TTL passed before its goal ended, `the task expired before its goal ended; the endpoint cancelled the goal`, or before its goal started, `the task expired before its goal started`. Only a failure of the provider has a `failure_kind`. * `cancelled` when the goal ended cancelled, with its reason, for example because its client cancelled the task or closed the call; or when the task ended before its goal started: its confirmation was declined, or its client cancelled it while the confirmation waited. The record holds the calls of MCP clients on that endpoint. A motion that a teleoperation or another node of the stack commanded is not in it. When a client finds the robot in a state it did not command, the record says whether another client of the endpoint did it, and, when no entry accounts for it, that no client did. ## The published schemas [Section titled “The published schemas”](#the-published-schemas) You do not define request and response shapes in the exposure. Peppy derives them from the contract’s [`message_format`](/reference/message_format/) declarations. The catalog records the version of the mapping used to create the schemas. The schema of a resource with a representation is the schema of its document: the message without the member the blob carries. It is also the output schema of the topic’s picture tool, and a service with a representation publishes the schema of its document the same way. Most types map directly to JSON. These are the important mapping rules, including the types that JSON cannot represent directly: | `message_format` | Published JSON Schema | Why | | ---------------------------------------------------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `bool`, `string`, `f32`, `f64` | `boolean`, `string`, `number` | Direct | | `u8`…`u32`, `i8`…`i32` | `integer` with `minimum`/`maximum` | The type’s own range is published | | `u64`, `i64` | `string` with a canonical decimal `pattern` | JSON numbers lose precision above 253 | | `time` | `string`, `format: "date-time"` | RFC 3339, fractional seconds carrying full nanosecond precision | | `bytes`, array of `u8` | `string`, `contentEncoding: "base64"` | Identical on the wire, so they share one rendering. A fixed byte length pins the exact base64 length | | Other arrays | `array` with `items`; fixed length pins `minItems`/`maxItems` | Direct | | Nested objects | `object` with every property required | `$optional` is legal only at the top level | | `$optional` top-level field | Omitted from `required` | Direct | | [`$description`](/reference/message_format/#description-modifier) of a field | `description` of its property | Direct | The input and output schemas of each tool, resource and task carry the `$description` of each field, and a [scope](#scopes) that narrows a property keeps its description. The description of a tool, a resource or a task is the one that the exposure gives it. Public property names use the DSL’s `snake_case` spelling. The internal wire encoding uses `lowerCamelCase` instead. Every derived object schema sets `additionalProperties: false`. ## Check it [Section titled “Check it”](#check-it) An exposure is checked where it is published, by the repository check, and again by every launch that serves it. Both read the contracts through the local repository caches, so run [`peppy repo refresh`](/advanced_guides/repositories/#refresh-the-index) on the machine first, and both read the daemon interfaces from the `peppy` that runs them. Neither check needs a running daemon. ```sh peppy repo index . --check --validate-mcp-exposures # the index, then every exposure against its contracts peppy mcp catalog camera_and_recording:v1 # the catalog an endpoint for the exposure advertises ``` `peppy repo index --check --validate-mcp-exposures` validates every exposure the repository’s index lists against the contracts and the daemon interfaces it references and reports **every** violation of **every** exposure at once, so you fix a document in one pass. A contract the caches cannot resolve is an error naming that contract, never a pass. A file that declares the exposure schema but does not parse as one (a document claiming a public name twice, say) is listed by no index, so the check reports it by path rather than letting it pass unseen. Run the check in the repository’s CI, as [mcp-hub](https://github.com/Peppy-bot/mcp-hub) does: a hub cannot then merge an exposure that a launch would refuse. ```text 2 exposures do not validate: - mcp_exposure `camera_and_recording:v1` (exposures/camera_and_recording.json5): - target `front_camera` selects service member `set_brightnes`, but contract `rgb_camera:v1` declares no such service (declared services: `video_stream_info`, `set_brightness`) - mcp_exposure `recording_only:v1` (exposures/recording_only.json5): - contract `episode_recording:v1` not in contract cache; run `peppy repo refresh` ``` `peppy mcp catalog ` prints the catalog the server derives for one exposure: every resource, tool, task, and picture tool with its public name, description, policies, and derived JSON Schemas, the call record when the exposure declares one, plus the identity the endpoint advertises, the contract slots its contract targets become (`contracts`), and the interface each daemon target names (`daemon_targets`). It is what a running endpoint answers through discovery and the list methods, so it is the thing to read when you want to see what a client will see. For a daemon target it prints the schemas of the interface without the narrowing of a [scope](#scopes): a running endpoint narrows them with the scope its launcher gives the target, which belongs to the instance and not to the exposure. The catalog is derived on demand and is never committed. ```json { "bundle_format": 1, "schema_mapping_version": 1, "exposure": { "name": "camera_and_recording", "tag": "v1" }, "server": { "title": "OpenArm camera and recording", "instructions": "Observe the front camera and record teleoperation episodes." }, "contracts": [ { "name": "rgb_camera", "tag": "v1", "sha256": "44527ab0…fb736ab", "link_id": "front_camera" }, { "name": "episode_recording", "tag": "v1", "sha256": "a4cfd6ec…f177c0d2", "link_id": "recorder" } ], "resources": [ { "name": "front_camera.latest_frame", "uri": "peppy://resource/front_camera.latest_frame", "…": "…" } ], "tools": [ { "name": "front_camera.info", "…": "…" }, { "name": "front_camera.set_brightness", "…": "…" } ], "tasks": [ { "name": "recorder.record_episode", "…": "…" } ], "pictures": [ { "name": "front_camera.look", "resource": "front_camera.latest_frame", "…": "…" } ] } ``` ## Deploy it [Section titled “Deploy it”](#deploy-it) A launcher deploys exposures with `source: { exposures: [...] }`, listing each as `":"`. The deployment takes one argument, `port`, and one `links` entry per contract target of every exposure it lists. Each link connects a logical role to a running instance. A [per-robot surface](#per-robot-surfaces) takes no `links`: the launcher’s `adjustments` under each robot’s option fill its targets. A [daemon target](#daemon-targets) takes no link either: it takes a scope. launchers/mcp_camera_and_recording.json5 ```json5 // Deploying an MCP exposure: the providers by instance, and the server built // into peppy serving the exposure, its logical targets filled through // `links`. // // peppy stack launch mcp_camera_and_recording { peppy_schema: "launcher/v1", description: ["A front camera and an episode recorder, and the MCP server of peppy that serves the exposure camera_and_recording:v1 of the two. It needs a UVC camera."], deployments: [ { source: { name: "uvc_camera:v1" }, instances: [{ instance_id: "front_cam_inst" }], }, { source: { name: "episode_recorder:v1" }, instances: [{ instance_id: "recorder_inst" }], }, { // The exposures to serve, each as `:`. The daemon derives // the server from these documents and the contracts they reference, // and runs one `peppy mcp serve` process for the list: nothing is // generated or built. Its node is named after the set, here // `mcp_camera_and_recording_v1:builtin`. source: { exposures: ["camera_and_recording:v1"] }, instances: [ { instance_id: "mcp_server", // The only argument the server takes. It binds `127.0.0.1:` // and serves each exposure at `///mcp`, so this one is // reached at http://127.0.0.1:8900/camera_and_recording/v1/mcp. arguments: { port: 8900 }, // One entry per target in the exposure document: the launcher // binds each logical target to a concrete running instance. This is // where "the front camera" stops being a role and becomes a robot. links: { front_camera: "front_cam_inst", recorder: "recorder_inst", }, }, ], }, ], } ``` ```sh peppy stack launch mcp_camera_and_recording ``` The daemon resolves each exposure through the machine’s [repository caches](/advanced_guides/repositories/), then every contract the exposures reference, validates every exposure against those contracts and the daemon interfaces it serves, and derives the server’s node from the result: its identity, its manifest (one contract slot per contract target, consuming exactly the selected members), and the catalog of each endpoint. Nothing is added or built. The node lands in the stack ready to run, with the installed `peppy` binary as its artifact, and its instance runs `peppy mcp serve`. You never run that command yourself: the daemon hands it the pinned documents through the environment, and run by hand it refuses, naming `PEPPY_MCP_SERVE_SPEC`. The derived manifest and the documents the server reads are written under `~/.peppy/built_in//`. On Linux, replacing the `peppy` binary on disk while the daemon runs (an upgrade, a rebuild) does not strand it: the daemon keeps serving built-in nodes from its own running image, warns in the add log that the file was replaced, and picks up the new binary when it restarts. The node’s identity is derived from the exposures it serves, so a relaunch, a peer, and a reader of `peppy stack list` all name it the same way: `mcp` followed by `__` for each exposure in name-then-tag order, at the tag `builtin`. The launcher above registers `mcp_camera_and_recording_v1:builtin`. The instance prefers `127.0.0.1:` (default `8900`) and serves each exposure at its own path: ```text http://127.0.0.1:8900///mcp ``` Every other path returns 404, a bare `/mcp` included. Point a client at `http://127.0.0.1:8900/camera_and_recording/v1/mcp`. A deployment of an exposure with a daemon target gives the target its scope, keyed by the target’s name, as the launcher of [Scopes](#scopes) does. The scope reaches the server with the runtime configuration of its instance, and the server parses it when it starts. A launch and a join check every scope before they start the server. A server that starts without a scope for one of its daemon targets, with a scope that does not parse, or with a scope key that names no daemon target, for example under `peppy node run` of its node, serves nothing and stops. Its run log names each daemon target that lacks a scope and says how to give one: in the instance’s `daemon_scopes`, or with a `set_daemon_scopes` adjustment on the instance. `port` is a preference. A server that finds the port free takes it. A server that finds it held by another process takes a port the operating system picks on the same loopback address, says so in its run log with a warning naming both ports, and announces the port it holds. Only a held port falls back: any other bind failure stops the process, its run log says `cannot bind 127.0.0.1:`, and the launch fails naming that instance. The URL the server ended up on is never a guess: the launch or the join that started it prints it under `MCP endpoints:`, and [`peppy stack list`](#seeing-what-is-served) shows it for as long as the instance runs. The derived manifest declares one entry under `execution.endpoints` per exposure, labelled `_` (the tag spelled as generated code spells it, `-` becoming `_`), of kind `mcp`, described by the exposure’s title. The server announces each one when it binds, and the daemon reports the URL under that label. The launch ends with them under `MCP endpoints:`; the server binds loopback only, so each exposure has exactly one URL: ```text MCP endpoints: mcp_server (mcp_camera_and_recording_v1:builtin) @cn-sweet-edison camera_and_recording_v1 http://127.0.0.1:8900/camera_and_recording/v1/mcp Launch completed successfully ``` ### Per-robot surfaces [Section titled “Per-robot surfaces”](#per-robot-surfaces) An exposure that declares `robots` is a **per-robot surface**: one endpoint for every robot of the stack, whatever their models, where every call names its robot. Its targets are the contracts a robot may bring, and each robot of the stack fills the targets its own instances implement. ```json5 { peppy_schema: "mcp_exposure/v1", manifest: { name: "robot_control", tag: "v1" }, server: { title: "Robots", instructions: "Call robot.list first; every other tool names a robot it lists." }, robots: { list: { tool: "robot.list", description: "The robots of the stack, with what each one fills." }, describe: { identity: { target: "identity", service: "get_identity" }, limbs: { target: "limb_state", service: "get_limbs" }, }, }, targets: { identity: { contract: { name: "robot_identity", tag: "v1" }, services: [ { member: "get_identity", tool: "robot.get_identity", description: "Who the robot is.", operation: "read_only", deadline_ms: 2000 }, ], }, limb_state: { contract: { name: "limb_state", tag: "v1" }, topics: [ { member: "limb_states", resource: "robot.limb_state", description: "The robot's limbs.", freshness: { max_age_ms: 2000 }, update: { max_hz: 2 }, max_result_bytes: 65536, on_oversize: "reject" }, ], services: [ { member: "get_limbs", tool: "robot.get_limbs", description: "The robot's arms and grippers, by name.", operation: "read_only", deadline_ms: 2000 }, ], }, camera: { contract: { name: "rgb_camera", tag: "v1" }, argument: "camera", topics: [ { member: "video_stream", resource: "camera.latest_frame", description: "The camera's latest frame, JPEG encoded.", freshness: { max_age_ms: 2000 }, update: { max_hz: 2 }, representation: { image: "jpeg", fields: { data: "frame", encoding: "encoding", width: "width", height: "height" } }, max_result_bytes: 524288, on_oversize: "downscale", picture: { tool: "camera.look", description: "Look through one of the robot's cameras." } }, ], }, }, } ``` Every tool of a per-robot surface takes a required `robot` argument, the robot’s name as the listing tool reports it under `robot`. A target with an `argument` of its own is filled any number of times per robot (a camera), and every call on it names the member with that argument; a target without one is filled at most once per robot. A target’s `argument` cannot be `robot`. The published input schema of every tool carries the routing arguments as required string properties beside the contract’s own fields, and a contract request field of the same name is refused at validation. `robots.describe` says what the listing reports of each robot beyond the targets it fills, keyed by the field of the listing entry: the whole response of a service, read through a target the robot fills once and selects as a tool. The listing calls it with the robot alone, so a service taking a request of its own cannot fill a listing field. A `describe` key cannot be `robot`, `tools`, `resources`, `members` or `notes`, the fields every entry carries. Every target of a per-robot surface is a `zero_or_more` contract slot the stack’s robots fill: the deployment’s instance takes no `links`, and the launcher adds each robot’s instances to the targets with `add_links` on the server’s instance, written under the option that selects the robot, at launch as any adjustment and afterwards as a [join](/guides/launch_files/#copies) grows a running set. The robot’s name is its copy’s name, so only copies fill a per-robot surface, and a target with no `argument` holds one member per robot. `peppy stack launch`, `peppy stack join` and `peppy stack resolve` hold a launcher to both rules before anything is added, built or started, naming the copy, the instances it bound and the `add_links` entry to write. A member bound outside a launch, as `peppy node run` binds one, is left out of the fleet: the server logs it, and a robot’s second member on such a target is named under the robot’s `notes`, where its calls are refused. ```json5 { source: { exposures: ["robot_control:v1"] }, instances: [{ instance_id: "robot_control_inst", arguments: { port: 8900 } }], } ``` ```json5 // In the launcher, under the option that selects the robot: the robot's own // instances fill the targets. options: { openarm: { fragments: ["openarm/fragments/openarm.json5"], adjustments: [ { target: "robot_control_inst", add_links: { identity: ["init_inst"], limb_state: ["backbone_inst"] } }, { target: "robot_control_inst", when: { camera_rig: "cameras" }, add_links: { camera: ["wrist_left", "wrist_right"] } }, ], }, } ``` The server reads the fleet from the targets’ bound sets on every list and call, so a robot is listed the moment the join that starts it returns and gone the moment its removal returns, with no restart and no effect on the calls, tasks and subscriptions of the other robots. With no robot the endpoint serves an empty fleet, and the first join onto it is accepted. What a client sees on a per-robot surface: * **The listing tool** takes no arguments and answers `{ robots: [...] }`, one entry per robot, in the order of the document’s targets and of the members the stack binds to each: `robot`, its name; `tools`, sorted, the tools that answer for it, each called with its name; `resources`, sorted, the resources it publishes, each read at `peppy://resource/`; `members`, for each target with an `argument`, the names a call addresses its members by, each the id the robot’s fragment wrote for that instance; `notes`, what could not be read or served for it and why; and one field per `describe` key, `null` when it could not be read, with the reason under `notes`. A tool’s `description` is where the model reads what a tool answers; the listing is where it reads which robot answers it. * **Tools** are the union of every target’s tools, picture tools included, fixed for the life of the server and cached as on a fixed surface. A picture tool takes the routing arguments of its target and nothing else: `camera.look` above takes `robot` and `camera`. A call naming a robot that is not on the stack, a target the robot does not fill, or a member the robot does not have is refused before anything reaches the Peppy graph, naming what is there: the robots, the targets the robot fills, or the members it has. A refused member also names the other targets the robot fills with a member of that name, so a `camera.look` naming `chest` on a robot whose RGBD camera `chest` fills `depth_camera` and not `camera` says that its `chest` fills `depth_camera`. * **Resources** are published per robot and member: `alpha/robot.limb_state` at `peppy://resource/alpha/robot.limb_state` for a target filled once, `alpha/wrist_left/camera.latest_frame` for a camera. `resources/list` follows the fleet and carries no cache hint, and the server sends `notifications/resources/list_changed` to listening clients when a robot joins or leaves. A resource of a robot that just joined reads as unavailable until its first snapshot arrives. ### Several exposures on one endpoint [Section titled “Several exposures on one endpoint”](#several-exposures-on-one-endpoint) One deployment can list several exposures, two tags of the same exposure included. They share one process and one port, and nothing else: each endpoint keeps its own catalog, snapshots, subscriptions, and task handles, so a public name, a subscription, or a task handle on one endpoint is unknown to the others. Targets with the same name across the listed exposures **share one slot** when they name the same contract, and the manifest consumes the union of the members they select. One `links` entry then fills the slot for every exposure using it. Daemon targets with the same name share one scope when they name the same interface. The same target name bound to different sources (two contracts, a contract and a daemon interface, or two daemon interfaces) is refused, naming both exposures and both sources: two exposures sharing a target name must name the same source. ```json5 { source: { exposures: ["camera_and_recording:v1", "camera_only:v2"] }, instances: [ { instance_id: "mcp_server", arguments: { port: 8900 }, // `front_camera` is a target of both exposures, bound to `rgb_camera:v1` // in each, so one link fills it for both endpoints. links: { front_camera: "front_cam_inst", recorder: "recorder_inst" }, }, ], } ``` The launch refuses, before anything starts, when: * an exposure or a contract it references is not in the caches, or an exposure does not parse; * an exposure names a daemon interface, or a tag of it, that this peppy does not serve. The refusal names the tag that this peppy serves; * an exposure does not validate against its contracts and daemon interfaces. The report lists every violation of every listed exposure at once; * an exposure’s `sha256` disagrees with the contract bytes the launch resolved, or two listed exposures pin one contract at different bytes. One deployment carries one content per contract; * an exposure is listed twice in one deployment; * two deployments list the same set of exposures. They would derive the same node identity, so the error names the set and points at the remedy: to serve one set on several hosts, declare one deployment with one instance per host; * a deployment lists a per-robot surface beside a fixed one, or two surfaces sharing a target name its member by different arguments; * a `links` entry names no target of the listed exposures, or a contract target is left without a link, as for any node’s slot; * a daemon target has no scope, a scope does not parse into the type of its interface or does not hold against the launcher, or a scope or a link is on the wrong instance or target. See [the checks of `daemon_scopes`](/guides/launch_files/#daemon_scopes-optional); * on a [per-robot surface](#per-robot-surfaces), a robot fills a target with no `argument` twice, or an instance the launcher deploys outside every copy fills a target. `peppy stack join` refuses the same two before the copy starts. Any number of instances run on one machine, whatever port each prefers. The first to reach a port holds it and the others take another, so a launcher that needs a known URL for each server names a different `port` for each, and a joined copy gets one with `--set-arguments .port=`. Two servers that start together and prefer one port settle between themselves which of them holds it. Read a server’s run log with [`peppy node info`](/guides/node_stack/#inspecting-a-node-with-peppy-node-info) on the node’s identity. ### Seeing what is served [Section titled “Seeing what is served”](#seeing-what-is-served) `peppy stack list` adds an **`Instance endpoints`** table when any instance serves an endpoint: one row per endpoint URL, under the node and instance serving it, with the endpoint’s kind and label. ```text Instance endpoints ┌──────────────────────────────────────┬────────────┬──────┬─────────────────────────┬───────────────────────────────────────────────────┐ │ NODE │ INSTANCE │ KIND │ LABEL │ ENDPOINT │ ├──────────────────────────────────────┼────────────┼──────┼─────────────────────────┼───────────────────────────────────────────────────┤ │ mcp_camera_and_recording_v1:builtin │ mcp_server │ mcp │ camera_and_recording_v1 │ http://127.0.0.1:8900/camera_and_recording/v1/mcp │ └──────────────────────────────────────┴────────────┴──────┴─────────────────────────┴───────────────────────────────────────────────────┘ ``` `peppy node info mcp_camera_and_recording_v1:builtin` lists the same endpoint under the instance as `camera_and_recording_v1 (mcp) http://127.0.0.1:8900/camera_and_recording/v1/mcp`. `peppy stack resolve` derives the same node from the same caches and holds the deployment’s `links` to its slots, so a launcher can be checked before it is launched. See [Auditing a composed launch](/guides/launch_files/#auditing-a-composed-launch). ### Placement [Section titled “Placement”](#placement) An exposure deployment is placed like any other: `core_node` on the instance names the machine it runs on, and the coordinator ships the pinned exposure documents and the contracts they reference, from which the other machine derives the same server. An instance that serves a [daemon target](#daemon-targets) is the exception: it runs on the coordinator, so it declares no `core_node` and belongs to no copy. The [federation limits](/advanced_guides/federation/#limits) apply: an exposure or a contract resolved from a filesystem repository cannot back an instance placed on another machine. The server reads the messaging layer like any node, so a topic-heavy exposure belongs on the machine that produces the topic. ## What a client sees [Section titled “What a client sees”](#what-a-client-sees) **Discovery.** `server/discover` returns the exposure’s `title` and `instructions`, the implementation identity (the exposure’s name at its tag), and `2026-07-28` as the only supported revision. Discovery and `tools/list` include private caching hints with a one-hour TTL, and so does `resources/list` on a fixed surface; on a [per-robot surface](#per-robot-surfaces) the resource list follows the robots and carries none. The tools do not change while the server is running. To change them, change the exposure document, refresh the repositories, and launch again. **Resources.** A read returns a snapshot that passed the policies, as typed contents under the resource’s URI: the document as `application/json` text and, for a resource with a representation, the blob after it under the MIME type of its codec. `resources/list` gives a resource with a representation the MIME type of its blob, and every other resource `application/json`. The `ttlMs` value of a read says how long the snapshot remains fresh. The resource is unavailable until the first published value arrives. A resource reads live messages only, also on a topic that [retains](/advanced_guides/topics/#retaining-the-latest-value). After the stored value is older than `freshness.max_age_ms`, reads report it as stale instead of returning old data as current. If the size policy rejects a new snapshot, the server keeps the previous one until it becomes stale. A read answers with the first message the endpoint receives after the read arrived, whatever `update.max_hz` admits: a client that changes something and reads at once sees a message from after its change, not the snapshot the last gate interval stored. The wait is bounded by `freshness.max_age_ms` of wall time; a topic that stays silent that long answers with the stored snapshot when it is still fresh, and with the stale refusal when it is not. Readers that wait together get the same message, so the cost is at most one decode per message. Subscribers keep their rate: a message admitted for a waiting reader alone sends no `notifications/resources/updated`, and every message the interval admits does. The guarantee is about when the endpoint received the message, not about when the source captured it. A message carries the source’s stamp, on the source’s clock (in a simulation, simulated time), and a frame that the source captured before a change and delivered after the read arrived still shows the old state. A client that needs the picture after a change reads the stamp. **Tools.** The endpoint checks input against the published schema, including `restrict` bounds, before sending anything to the Peppy graph. It rejects invalid input and unknown tool names. If a service does not respond within `deadline_ms`, the client receives a readable tool error. A service that gives an error reply ends the call with the tool error of a [failed call](#refused-and-failed-calls). A service with a [`representation`](#service-policies) answers with its frame, as an image block or, for a `raw` frame, as an embedded resource, then the rest of the response as the text and the structured content, and the document alone when the response carries no frame. **Picture tools.** A picture tool is listed read-only (`readOnlyHint: true`, `destructiveHint: false`) and answers inside the call for every client: it is never a task. Its result carries the snapshot a read of its resource serves at that moment: ```json { "content": [ { "type": "image", "data": "", "mimeType": "image/jpeg" }, { "type": "text", "text": "{\"encoding\":\"mjpeg\",\"width\":1280,\"height\":720}" } ], "structuredContent": { "encoding": "mjpeg", "width": 1280, "height": 720 }, "isError": false } ``` While the resource has no snapshot, or a stale one, the tool returns a tool error whose text is the message a read of the resource gives for that state. It waits for the next message as a read does. **Actions.** An action-backed tool runs its goal on whichever surface the calling client can drive. The client’s request capabilities decide, per call. For a client that declares the tasks extension (`io.modelcontextprotocol/tasks` in its `extensions`), the call returns a task handle and follows this sequence: 1. If `confirmation_required`, the task waits in `input_required` until the client confirms through `tasks/update`. No goal is sent before that. 2. The server sends the goal. Action feedback updates the task’s status message. 3. `tasks/cancel` forwards a request to the action’s cooperative cancellation path. It is the one way a client cancels a task. A declined confirmation, or a cancel before the client confirms, ends the task as `cancelled`, and no goal is sent. 4. A goal that completes completes the task with the structured result. A goal that ends cancelled ends the task as `cancelled`, and the task’s status message says why, as a [cancelled goal](#cancelled-goals) describes. A goal that the provider refuses or fails ends the task as `failed`, with the failure in its error, as a [refused or failed call](#refused-and-failed-calls) describes. A goal that is abandoned, expired, or past its bound ends the task as `failed` with a message saying which event occurred. Task handles outlive connections, and do not outlive the process. A client that disconnects while its goal runs cancels nothing: the goal runs on, and a client that reconnects can continue and observe the same task. Stopping the stack ends every task the endpoint was running (see [Goals and connections](#goals-and-connections)). A task under `deadline_ms` advertises a TTL of the deadline plus a short grace window. A task under `progress_timeout_ms` advertises a TTL of one day (86400000 ms): the progress window fails a task whose goal goes silent, and the TTL is the longest a goal that keeps making progress may run as a task. When the TTL passes, the task fails with a generic expiry, the endpoint sends the provider a cancel, and the [call record](#the-call-record) keeps the task `failed`. Every task stays readable for one more TTL after it ends. For a client without the extension, the goal runs inside the call: 1. The server sends the goal and the call stays open until the goal settles or its bound fails it. Under `progress_timeout_ms` the endpoint sets no limit on the total time of the call: a goal that keeps making progress runs until it settles or the client closes the call. 2. Action feedback is sent as `notifications/progress` under the call’s progress token, in order, before the result. The first notification also opens the response: the endpoint sends the response headers with it. The endpoint holds one notification for the client at a time: while the client has not taken it, the endpoint reads no more feedback of the goal, and new feedback waits in the goal’s feedback buffer (see below). A call without a progress token gets no feedback, and nothing arrives on it, not even the response headers, until the goal settles. 3. Closing the call forwards a request to the action’s cooperative cancellation path at once, also while a notification waits for the client (see [Goals and connections](#goals-and-connections)). The endpoint follows the goal to the end that its provider gives it after the cancel, and the [call record](#the-call-record) keeps that end, `cancelled` when the provider honours the cancel. 4. A goal that completes returns the structured result. A goal that ends cancelled returns the tool error of a [cancelled goal](#cancelled-goals). A goal that the provider refuses or fails returns the tool error of a [refused or failed call](#refused-and-failed-calls). A goal that is abandoned, expired, or past its bound returns a readable tool error saying which event occurred. On both surfaces, every feedback message of a goal waits in the goal’s [feedback buffer](/advanced_guides/actions/#receiving-feedback) until the endpoint shows it, up to 1024 unread messages: the default bound of the buffer. On a task the endpoint shows each message as it comes. On a call it shows the next message once the client took the one before, so a client that reads its call slowly keeps the messages in the buffer. A goal whose unread feedback goes past the bound loses the stream: the buffer drops the unread messages and cancels the goal, and the call or the task fails with `the action failed: the endpoint fell behind the feedback of the goal by more than 1024 unread messages, so it cancelled the goal`. A tool with `confirmation_required` cannot run inside a call: the confirmation is an input request only a task can carry. The endpoint refuses it with error `-32021` (Missing Required Client Capability), naming the tool and the extension in the message and the capability in the error data. ### Goals and connections [Section titled “Goals and connections”](#goals-and-connections) The MCP server is the sender of the goals of its tools: the provider sees the server’s node, never the MCP client. A goal ends when its provider ends it, when the client cancels it, when the endpoint stops following it, or when the server stops. When the server’s process stops, its providers see that their sender is gone and cancel its goals after their sender grace. How a client cancels a goal depends on the surface it runs on: * A task outlives the connection that started it. A client that disconnects while its goal runs cancels nothing: the goal runs on, and a client that reconnects reads the same task. `tasks/cancel` is the one cancel of a task. * A goal that runs inside a call is cancelled when its call closes. In Streamable HTTP a client cancels a call by closing it, and a client that disconnects closes it too: the endpoint cannot tell the two apart, and takes both as a cancel. Closing the call sends the provider a cancel, so a client that stops waiting, for example when its user interrupts it, stops the robot it moves. A client that must keep a goal running after it goes away declares the tasks extension. The endpoint cancels a goal for its client, when the client cancels its task or closes its call. It also cancels a goal that it stops following before the goal ended: at a deadline, after a window of `progress_timeout_ms` without a sign of progress, at the TTL of a task, and when the unread feedback of the goal goes past its bound (see [What a client sees](#what-a-client-sees)). The call or the task then fails, and no goal runs on with no one following it. A goal on a [member that moves a robot](#members-that-move-a-robot) is the exception: the endpoint follows it on until it ends, and cancels it at a halt. The endpoint sends a goal one cancel at most. ### Refused and failed calls [Section titled “Refused and failed calls”](#refused-and-failed-calls) A provider that refuses a goal, fails a goal, or gives the error reply of a service, gives a **failure kind** and a message. The kind is a kind of peppy, which every provider can give, or a kind of the contract of the member that the member lists, such as `unreachable` of `move_arm`. A [daemon interface](#the-interfaces-peppy-serves) declares its kinds the same way, such as `busy` of `robot_membership:v1`: | Kind of peppy | Meaning | | ---------------------- | --------------------------------------------------------- | | `attempt_failed` | The attempt gave no result | | `timeout` | The bound of the provider passed | | `precondition_failed` | A precondition failed | | `resource_unavailable` | A robot, limb or host is gone | | `rejected` | The provider refused the goal, and no other kind says why | In a call, the endpoint returns a tool error: * `isError` is `true`. * The one text says what happened, with the kind and the message: `the provider refused the goal: : `, `the provider failed the goal: : `, or `the provider gave an error reply: : `. * `structuredContent` holds `outcome` (`refused` for a refused goal, which never ran; `failed` for a failed goal or an error reply), `failure_kind` and `message`. It is not in the tool’s output schema, which describes a result: read `isError` first. ```json { "content": [ { "type": "text", "text": "the provider refused the goal: unreachable: no plan reaches the pose" } ], "structuredContent": { "outcome": "refused", "failure_kind": "unreachable", "message": "no plan reaches the pose" }, "isError": true } ``` In a task, the task ends `failed`. Its `error` has the same text as its `message` and the same object as its `data`: ```json { "code": -32603, "message": "the provider failed the goal: unreachable: no plan reaches the pose", "data": { "outcome": "failed", "failure_kind": "unreachable", "message": "no plan reaches the pose" } } ``` A failed goal gives no result. The [call record](#the-call-record) keeps the outcome, the kind and the message of the call. A provider can give only a kind of peppy or of the contract of the member. A kind that neither declares is a fault of the provider: the call fails with a readable tool error that names the member and the kind, such as ``the action failed: the provider of `move_arm` gave the failure kind `melted`, which neither peppy nor the contract of the member declares``, and with no structured content. ### Cancelled goals [Section titled “Cancelled goals”](#cancelled-goals) A goal ends cancelled when the client cancels its task or closes its call, or when the provider cancels it for a reason of its own, for example because a newer goal replaced it or another client stopped the robot. In each case the provider ends the goal with a result and a reason. In a call that is still open, the endpoint returns the result in a tool error: * `isError` is `true`, whatever the result says: the goal did not run to its end. * The first text says that the goal was cancelled and why: `the action was cancelled: `, with the reason of the provider. * `structuredContent` is the provider’s result, in the tool’s output schema, and the second text is the same result as JSON. In a task, the task ends `cancelled`, which carries no result. Its status message is the same first text, followed by `: `and the provider’s result as JSON. The [call record](#the-call-record) keeps the reason as the `message` of the call. ## What validation refuses [Section titled “What validation refuses”](#what-validation-refuses) Validation reports **every** violation at once, so you can fix the document in one pass. It rejects an exposure when: * A selected member does not exist in its contract or exists as a different kind. The error lists the contract’s members and points to the correct section when the name exists elsewhere. * A message definition cannot be converted to a public schema. * A representation role names a missing, `$optional`, or wrongly typed member, of a topic’s message or of a service’s response. * A `restrict` bound does not fit its member’s type, names a non-numeric member, or targets a `u64`/`i64`. * A `max_result_bytes` is smaller than a payload’s static maximum, or a topic with an unbounded payload omits the size policy. * An action with `progress_timeout_ms` has no `feedback_topic` in its contract. * A contract `sha256` does not match the resolved document’s bytes. * A daemon target names an interface, or a tag of it, that this peppy does not serve. The error names the tag that this peppy serves, or the interfaces that it serves for an unknown name. Parsing catches document-level errors before these checks. Examples include: * An exposure with no targets or a target that selects no members. * A target that names both `contract` and `daemon`, or neither. * A daemon target with a `sha256`: a daemon interface is compiled into peppy and is never pinned. * A daemon target on a document with `robots`: every tool of a per-robot surface is routed by `robot`. * A public name claimed twice anywhere in the document, the names of picture tools and of the call record’s tool included, or a service or action member selected twice by one target. * A target `argument` on a document without `robots`, a target `argument` of `robot`, a `describe` entry naming a target the robot fills any number of times or a service its target does not select as a tool, or an argument name that is not `snake_case`. * A blank `title`, `instructions`, or `description` value. * An action that declares both or neither of `deadline_ms` and `progress_timeout_ms`, or declares `progress_timeout_ms` together with `confirmation_required`. * A zero `deadline_ms` or `progress_timeout_ms`, or a `max_hz` value that is not positive and finite. * A `quality` value on a `raw` or `png16` representation. * A `depth_range` on a `raw` or `png16` representation, or one whose `near` is 0 or not below `far`. * `on_oversize` without `max_result_bytes`, on a topic or a service. * `downscale` without a `jpeg` or `png16` representation, on a topic or a service. * A `call_record` whose `keep` is 0 or above 1000. * A `picture` on a topic whose representation is `png16` or `raw`, or that has no representation. * A `restrict` entry with neither bound, or with `min` above `max`. ## What stays private [Section titled “What stays private”](#what-stays-private) An exposure keeps everything else private: * The MCP endpoint is **not** a bridge to the messaging layer. It cannot pass through arbitrary messages or access an internal member that the exposure did not select. For example, the running stack includes `finish_session`, but the exposure does not publish it. * The catalog contains exactly the selected members. `tools/list` and `resources/list` return only what is in the catalog. The endpoint rejects unknown names. * Endpoints served by one process are isolated from each other. A name, a subscription, or a task handle belongs to the endpoint it was created on. * The endpoint binds to `127.0.0.1`. It is available from another machine only if you deliberately configure network access. # Choosing between a node and a shared library > Decide whether a piece of robot code runs as a node of its own or as a shared library inside the nodes that call it Code that more than one part of a robot uses has two possible homes. A [**node**](/reference/concepts/#node) is a process of its own: the daemon starts it, and the other nodes reach it through [topics](/advanced_guides/topics/), [services](/advanced_guides/services/) and [actions](/advanced_guides/actions/). A **shared library** is a Rust crate or a Python package: each node that uses it takes it into its own build and calls its functions in its own process. This page is the map for that choice. When the answer is a node, [Choosing a communication pattern](/advanced_guides/communication_patterns/) is the map for the step after it. The choice comes down to two questions: 1. **Does the code need a life of its own?** A node starts, stops, fails and restarts apart from its callers, and Peppy shows each of these. A library has no life of its own: it runs when a node calls it, in the process of that node. 2. **What can one exchange cost?** A call to a node is a message: one side encodes it, the messaging layer carries it, and the other side decodes it. A call to a library is a function call. ## Side by side [Section titled “Side by side”](#side-by-side) | | Node | Shared library | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | | Where it runs | In a process of its own, one for each instance | In the process of each node that calls it | | How its callers reach it | Through the topics, services and actions that its `peppy.json5` declares | Through a function call | | Who can call it | Nodes in Rust and in Python, on each machine of the stack, and a person or a program through [`peppy node call`](/advanced_guides/calling_instances/) and [MCP](/advanced_guides/mcp/) | Nodes in the language of the library | | What crosses | Messages of a declared [message format](/reference/message_format/) | Each type of the language, by value or by reference | | What one exchange costs | An encoding, a trip through the messaging layer and a decoding | A function call | | What a failure does | It ends the process of the node alone, and the [restart policy](/guides/launch_files/#restart-policy) of the instance says whether the daemon starts it again | It ends the node that called the library | | What Peppy shows | An instance with a state, a health, a count of restarts and a run log | Nothing: the library is a part of the node that calls it | | Its state | One state, which all its consumers read | One separate state in each node that links it | | Its version | The one that the launch resolves, the same for all its consumers | The one that each node was built with | | How it is shared | Through a [repository](/advanced_guides/repositories/) of Peppy | Through the package manager of the language | ## Make it a node [Section titled “Make it a node”](#make-it-a-node) Make the code a node when one of these is true: * **It is a part of the robot that stands alone.** A camera driver, an arm controller and a planner each have a clear set of inputs and outputs, and each can run with nothing else of the robot around it. The `peppy.json5` of the node declares these inputs and outputs as data, so [`peppy node describe`](/advanced_guides/calling_instances/#peppy-node-describe) shows them and [`peppy node call`](/advanced_guides/calling_instances/) reaches them with no code. * **Other stacks reuse it as it is.** A launcher names the node, gives each instance its [parameters](/guides/parameters/) and binds its slots. A [repository](/advanced_guides/repositories/) shares it, and each machine that reads the repository adds it by `name:tag` (see [Sharing nodes](/guides/sharing_nodes/)). * **Other nodes must record or watch its outputs.** A third node can read only the data that travels between nodes. A recorder consumes the frames of a camera through a [contract slot](/advanced_guides/contract_implementation/) and the streams of an arm through an [observer slot](/advanced_guides/pairing/#observers-watching-a-pairing-without-joining-it), and [`peppy stack benchmark`](/advanced_guides/stack_benchmark/) measures the latency of each interface. A value that a library returns to its caller stays in that process, and no other node sees it. * **Its callers are in another language.** A node in Rust and a node in Python exchange the same messages, each through the bindings that `peppy node sync` generates from its own `peppy.json5`. So a critical control loop in Rust serves a stack whose other nodes are in Python, and nobody writes bindings between the two languages. * **It serves more than one robot.** Parameters give each instance the data of its robot, and a [contract](/advanced_guides/contract_implementation/) lets the node work with each node that implements it. One node that solves the kinematics of each arm with a spherical shoulder, a revolute elbow and a spherical wrist runs as one instance for each such arm, whatever its maker, and the launcher binds each instance to its arm. * **It must fail and restart alone.** Each instance has a [restart policy](/guides/launch_files/#restart-policy): `never`, `on_failure` or `always`, with an optional cap on the restarts in a row. The daemon waits one second before the first restart and doubles the wait at each further failure, up to one minute. The daemon also checks the health of each running instance: three missed checks in a row mark the instance `unhealthy`, and under `on_failure` or `always` an instance that answers no check for a minute is killed and started again (see [Instance health and lifecycle](/guides/node_stack/#instance-health-and-lifecycle)). The consumers of a restarted instance receive from it again with no further action. * **You must see it run.** [`peppy stack list`](/guides/node_stack/#checking-node-status) shows each instance of each machine with its state, its health and its count of restarts. Each instance writes a run log of its own. With the [OpenTelemetry log export](/advanced_guides/opentelemetry/) on, each record carries the name of the node as `service.name` and the name of the core node as `service.namespace`, so the logs of all the machines [filter by node and by machine](/advanced_guides/opentelemetry/#filtering-by-node-and-by-machine). * **It needs an environment of its own.** A node can run in a [container](/advanced_guides/containers/) with its own system dependencies, so two nodes can use two versions of one system library. A launcher can also place a node on another machine than its consumers, such as the machine that has the GPU (see [Federation](/advanced_guides/federation/)). * **It owns one thing that several nodes use.** A device that only one process can open, a map that several nodes read and a model that fills the memory of a GPU each have one owner. One node owns the thing and serves each consumer. ## Make it a shared library [Section titled “Make it a shared library”](#make-it-a-shared-library) Make the code a shared library when one of these is true: * **A fast loop calls it.** A function call returns in the thread of its caller, with no encoding and no trip through the messaging layer. A control loop that needs a result in each tick, such as the inverse kinematics of an arm in a 1 kHz loop, calls a library. [`peppy stack benchmark`](/advanced_guides/stack_benchmark/) measures what a call to a node costs on your machines: compare its numbers with the period of the loop. * **A critical path must not go through the messaging layer.** A call to a node can end with no answer: the node is gone, the link between two machines is down, or the time limit of the call passes. A call to a library has none of these ends. Code that must run on each command, such as the limit check of a motor driver, runs in the process that sends the command. * **Several nodes reuse it, but it has no job of its own.** Math, parsers, device protocols and robot descriptions have no stream of inputs, no state to share and nothing to start or stop. As a node, such code is one function behind a service, and each caller pays a message for each call. * **Its data does not fit a message.** A message holds the types of the [message format](/reference/message_format/), and each exchange copies it. A library takes and returns each type of its language: a reference into a large map, a function, a generic type. A library gives up what a node has: * **It fails with its caller.** A crash in a library is a crash of the node that called it, and the restart policy of that node applies. * **Peppy does not see it.** It has no instance, no state and no health, and the lines it prints are lines of the run log of the node that called it. * **It has one language.** A node in the other language needs bindings to it, which are a library to build and to maintain. * **Each node has its own copy.** Two nodes that link one library share no state through it, and each node runs the version it was built with. A change of the library reaches a node only when that node is built again. ## A node built on a library [Section titled “A node built on a library”](#a-node-built-on-a-library) The two choices combine. Put the logic in a library that has no dependency on the messaging layer, and write a node around it: the node declares the interfaces, reads its parameters, and turns each message into a call to the library. Then: * A node with a fast loop links the library, and each other consumer calls the node. Code that is generic across robots, such as the kinematics above, can thus serve a 1 kHz loop and a planner that runs once a second. * A hardware driver and its simulated twin link the same library and implement the same [contract](/advanced_guides/contract_implementation/), so the launcher fills one slot with one or the other. * The tests of the logic need only the test tool of the language, and the [generated harness](/advanced_guides/testing/) tests the node around it. The bindings that `peppy node sync` generates belong to one node, because they come from the `peppy.json5` of that node. A library has no `peppy.json5`, so the node converts between its messages and the types of the library. The Peppy hubs are built this way. The libraries of [`public-peppy-libs`](https://github.com/Peppy-bot/public-peppy-libs) hold the kinematics, the collision geometry and the motion planning with no dependency on the messaging layer. In [`nodes-hub`](https://github.com/Peppy-bot/nodes-hub), the arm nodes link the kinematics, and the `motion_planner` node links the planning library and serves its plans through the `motion_planning` contract. ## How a node takes a shared library [Section titled “How a node takes a shared library”](#how-a-node-takes-a-shared-library) Peppy builds a node with the build tool of its language, so a node takes a library as each Rust or Python project does. Where the library is decides how: * **In the directory of the node**: a path dependency. This is for code that one node alone uses. * **Outside the directory of the node**: a dependency that the package manager fetches from a git repository or from a package registry. [`peppy node add`](/guides/node_stack/#adding-hello_world-to-the-stack) copies the directory of the node and nothing around it, and it copies no symlink. So a relative path that leaves the directory does not resolve when the node builds, and neither does a symlink to a shared directory. A node names a library of a git repository and the commit it builds with: * Python pyproject.toml ```toml [project] dependencies = ["arm_kinematics"] [tool.uv.sources.arm_kinematics] git = "https://github.com/acme/robot-libs" subdirectory = "arm_kinematics" rev = "" ``` * Rust Cargo.toml ```toml [dependencies] arm_kinematics = { git = "https://github.com/acme/robot-libs", rev = "" } ``` Pin a commit, not a branch: each build of the node then gives the same code on each machine. To take a change of the library, change the pin and build the node again. Each node holds its own pin, so two nodes of one stack can run two versions of one library. When the two ends of an exchange must agree on what the library computes, such as the conversion of a unit, give the two nodes the same pin. ## Worked example: one arm [Section titled “Worked example: one arm”](#worked-example-one-arm) A complete robot arm setup uses both homes: * The **protocol of the motors** is a library. The arm driver calls it in each tick of its control loop, and it has no state that another node reads. * The **arm driver** is a node. It owns the bus of the motors, it restarts alone when it fails, and its joint states go to its controller, to a dashboard and to a recorder. * The **kinematics of the arm** is a library. The controller calls it in each tick, and the planner calls it for each state that it checks. * The **planner** is a node. One request takes it a second or more, so the cost of a message is small beside it. It serves each robot that implements the contracts it consumes, and the launcher can place it on a machine with more compute. * The **description of the robot**, its joints, its limits and its meshes, is a library. The driver, its simulated twin and the planner link it at one pin, so the three agree on the robot. * The **recorder** is a node. It consumes what the driver and the cameras publish, and no change to these nodes is necessary to record them. One rule gives each answer: code with a life of its own is a node, and code that only computes for its caller is a library. # OpenTelemetry log export > Export the launch, add, build, run and stack logs of a daemon as OpenTelemetry log records over OTLP/HTTP The daemon writes log files on its own machine: a launch log for each `peppy stack launch`, `build`, `join` and `remove`, an add log and a build log for each node, a run log for each instance, and the stack log. With `otlp_endpoint` set, the daemon also exports each line it writes to these files as an [OpenTelemetry](https://opentelemetry.io/) log record, over standard OTLP/HTTP, so the logs of every machine reach one place where they filter by node and by machine. The export is off by default. `otlp_endpoint` is the only setting that turns it on, and records go to that URL and nowhere else: the daemon reads no `OTEL_*` environment variable, follows no redirect, and uses no proxy of its environment. ## Turning it on [Section titled “Turning it on”](#turning-it-on) Set `otlp_endpoint` in the [daemon configuration](/advanced_guides/daemon_config/#otlp_endpoint-export-the-log-files) to the OTLP/HTTP URL of an OpenTelemetry collector or of an intake, and restart the daemon: ```json5 otlp_endpoint: "http://localhost:4318", ``` The value is the base URL of the collector or intake, and the daemon posts to `/v1/logs`. A URL whose path already ends with `/v1/logs` is the URL the daemon posts to, without a trailing slash. Requests carry a protobuf body (`Content-Type: application/x-protobuf`). When the export is on, `peppy service serve` prints one line at startup, prefixed like every line of its output: ```plaintext Exporting the log files to localhost:4318 over OTLP/HTTP ``` ### An OpenTelemetry Collector on the same machine [Section titled “An OpenTelemetry Collector on the same machine”](#an-opentelemetry-collector-on-the-same-machine) A collector on the robot is the usual endpoint: it takes the records over loopback, and forwards them to wherever the logs are kept. This configuration prints each record it receives, which is enough to see the export work: collector.yaml ```yaml receivers: otlp: protocols: http: endpoint: 127.0.0.1:4318 exporters: debug: verbosity: detailed service: pipelines: logs: receivers: [otlp] exporters: [debug] ``` ```sh docker run --rm --network host \ -v "$PWD/collector.yaml:/etc/otelcol-contrib/config.yaml" \ otel/opentelemetry-collector-contrib:latest ``` To forward the records, give the collector the exporter of your backend. With the `file_storage` extension the collector keeps the records it has not delivered on disk, so they survive an outage of the backend and a restart of the collector. A collector that runs in a container needs that directory mounted from the host: collector.yaml ```yaml receivers: otlp: protocols: http: endpoint: 127.0.0.1:4318 extensions: file_storage: directory: /var/lib/otelcol/storage create_directory: true exporters: otlphttp: endpoint: https://otlp.example.com headers: x-api-key: ${env:OTLP_API_KEY} sending_queue: storage: file_storage service: extensions: [file_storage] pipelines: logs: receivers: [otlp] exporters: [otlphttp] ``` A collector is also the place to drop or sample records, to add attributes such as an environment name, to redact node output before it leaves the machine, and to reach a backend through a proxy. ## What is exported [Section titled “What is exported”](#what-is-exported) One entry of a log file is one record. An entry is one line, except for an error the daemon writes after a command failed: that entry quotes the last lines the command printed on stderr, under a `--- stderr (last lines) ---` heading, and its record holds the error without the quoted lines, since each of them is already a record of the log that captured it. | Log | File | What its records hold | | ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Launch | `~/.peppy/logs/launch/` | The steps, warnings and errors of a `peppy stack launch`, `build`, `join` or `remove` | | Add | `~/.peppy/logs/add/` | Each step `peppy node add` prints, and its error when it fails | | Build | `~/.peppy/logs/build/` | The build commands and their output | | Run | `~/.peppy/logs/run/` | The run command and the output of the instance | | Stack | `~/.peppy/stack_log.log` | Each exit of an instance’s process, as a `finished` or `failed` line whether or not a restart follows (an exit that `peppy node stop`, `peppy node add` over its node, a stack launch, removal or reset, or a daemon shutdown caused is not logged, nor one `peppy node remove` caused once it claimed the instance; one on the removal’s shutdown request before its claim is); each change between `healthy` and `unhealthy`; each health kill and each kill held for a messaging outage; each restart scheduled, completed, failed to start, refused or capped by `max_restarts`; and each report of records the export discarded | The log files keep their paths and their line format, and they hold every line whether the export is on or off. A few lines stay in the files only: * **A line a launch log repeats from a node’s log.** A launch log holds the add, build and run output of the nodes it starts. Each such line is exported once, as the record of the node’s own log. * **A line relayed from another machine.** In a [federated launch](/advanced_guides/federation/) the launch log of the coordinator holds lines of the other daemons. Each daemon exports the log files it writes, so those lines are exported by the daemon that wrote them, when its own `otlp_endpoint` is set. * **Repaints and empty lines.** The fragments a progress bar repaints, and lines of node or build output that hold only white space once their terminal escape sequences are removed. * **A line below `otlp_min_severity`**, when that setting holds a severity. Progress samples that repeat while a transfer or a build goes on, such as `received 120/480 objects` and `Build progress: 463.6 MB written`, reach the terminal only. They are in no log file and in no record. The diagnostic output of the daemon process itself, which `peppy service serve` prints, and the log of the zenoh router are not exported. ## The fields of a record [Section titled “The fields of a record”](#the-fields-of-a-record) Each record belongs to a resource. Every record of one daemon has the same resource attributes except `service.name`: | Resource attribute | Value | | ---------------------- | --------------------------------------------------------------------------------------- | | `service.name` | The name of the node the line belongs to, or `peppy` for a line that belongs to no node | | `service.namespace` | The core node name of the daemon | | `host.name` | The host name of the machine, or `unknown` when the daemon cannot read it | | `peppy.core_node.name` | The core node name of the daemon | | `peppy.version` | The version of peppy | A line belongs to a node when its log does: every line of a build log and of a run log, each line of the stack log about an instance, and the lines of an add log once the daemon knows the node. An add from a directory, from a repository entry or from a launcher knows its node from the first line, and the add log of a node with dependencies belongs to that node, including the lines about its dependencies. An add from a git or HTTP URL learns its node when it has read the node’s config: the steps before that carry `service.name` `peppy`. | Record field | Value | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Body | The text of the line, without the timestamp and the marker of the file and without terminal escape sequences. A body is cut at 16 KiB | | Severity number, severity text | See [Severity](#severity) | | Observed time | The daemon’s clock, in UTC, when it wrote or read the line | | Time | The same instant for a line the daemon wrote itself. Unset for node and build output, whose own clock the daemon does not know | | `peppy.log` | `launch`, `add`, `build`, `run` or `stack` | | `peppy.stack.action` | `launch`, `build`, `join` or `remove`, on the records of a launch log | | `peppy.node.name`, `peppy.node.tag` | The node the log belongs to, when it belongs to one | | `peppy.instance.id` | The instance, on the records of a run log and on the records of the stack log about an instance | | `peppy.launch.id` | The launch the log was written for, when there is one | | `log.iostream` | `stdout` or `stderr`, on node and build output | | `log.file.path` | The log file | | `peppy.body.truncated` | `true` on a record whose body was cut | ### Filtering by node and by machine [Section titled “Filtering by node and by machine”](#filtering-by-node-and-by-machine) `service.name` is the node, on every record about that node: its add, its build, the output of its instances and what became of them. `service.namespace` is the machine. A query for one `service.name` across every namespace follows a node over the fleet, and one `service.namespace` shows everything a machine logged. ### Severity [Section titled “Severity”](#severity) A line the daemon writes itself has a fixed severity: an error, a `failed` line, and a `start failed`, `restart refused` or `` `max_restarts` reached `` line are `ERROR`; a warning, an `unhealthy` instance, a `restarting` line, a health kill and a kill held for an outage are `WARN`; and every other such line is `INFO`. For node and build output, the daemon reads the level the line prints. The level is the first word of the line, after an optional timestamp: | Line | Severity | | ----------------------------------------------------------------------------------------- | ------------------ | | `2026-09-21T23:33:54.318976Z WARN node::control: scouting delay elapsed` (Rust `tracing`) | `WARN` | | `2026-09-21 16:33:46,774 - ERROR - the arm stopped` (Python `logging`) | `ERROR` | | `WARNING:root:battery low` (Python `logging`, default format) | `WARN` | | `error[E0308]: mismatched types` and `warning: unused variable` (cargo) | `ERROR` and `WARN` | | `FATAL: could not open image` (Apptainer) | `FATAL` | | `hello world count 3` | none | A word that ends at `:` or `[` is read in any letter case. A word that ends at a space or at `]` is read in uppercase only, so a sentence that starts with a level word, such as `Error handling is on`, has no severity. `WARNING` is `WARN` and `CRITICAL` is `FATAL`. The severity text of the record is the word as printed. A line that prints no level has no severity: the record leaves the severity number unset. ## `otlp_min_severity`: the lowest severity exported [Section titled “otlp_min_severity: the lowest severity exported”](#otlp_min_severity-the-lowest-severity-exported) `otlp_min_severity` in the [daemon configuration](/advanced_guides/daemon_config/#otlp_min_severity-lowest-exported-severity) holds the lowest severity the daemon exports: one of `"trace"`, `"debug"`, `"info"`, `"warn"`, or `null` (the default) to export every line. ```json5 otlp_min_severity: "info", ``` A line below `otlp_min_severity` stays in its log file only, whether a node printed it or the daemon wrote it. A line that prints no level is always exported. Set it when a node logs at debug level in a fast loop, so those lines leave room in the queue of the export for the others. ## Request headers [Section titled “Request headers”](#request-headers) An intake that needs an API key, or a tenant, takes it as a request header. Headers go in `~/.peppy/conf/otlp_headers.json5`, a JSON5 object of header name to value: ```json5 { "x-api-key": "", } ``` Create the file readable by its owner alone. The daemon sets it to owner-only (`0600`) each time it reads it, like `credentials.json5`, and it reads the file only while `otlp_endpoint` is set. Header values appear in no log file, in no error, and not in the output of `peppy service serve`. A file that does not parse stops the daemon at startup with an error that names the file and what is wrong with it: the line and column of a syntax fault, a name that is no header name, a value a header cannot carry, or one header named twice. When the endpoint answers `401` or `403`, the daemon reads the file again. If the headers changed, it sends the request again with the new ones, so a key rotates without a daemon restart: write the new key to the file, and the first request the old key is refused for is the one that picks it up. Send headers over `https`. When `otlp_endpoint` is plain `http` on another machine and the headers file holds headers, `peppy service serve` prints a warning at startup. Plain `http` to a collector on the same machine stays on loopback. ## When the endpoint is unreachable [Section titled “When the endpoint is unreachable”](#when-the-endpoint-is-unreachable) `peppy node add`, `build`, `run` and `peppy stack launch` take their usual course whatever the endpoint does. The log files are written first and never wait for the export. * **Retries.** A request that gets no answer, or the answer `429`, `502`, `503` or `504`, is sent again after a wait. The first wait is between half a second and a second, and each later one is up to twice as long, up to 30 seconds. A `Retry-After` header that holds a number of seconds lengthens the wait, up to 30 seconds. Because a request with no answer is sent again, the collector or intake can get the same records twice after a network fault. * **The queue.** Records that are not sent yet wait in memory, up to 16 MiB. The stack log has room of its own on top, so the output of a build or of a node never crowds out the `failed` record of an instance. * **Discards.** A record that arrives while the queue is full is discarded. So are the records of a request the endpoint refuses for good: a `401` or `403` when the headers file has not changed or cannot be read again, and every other answer that is not a success, such as `400`, `404` or a redirect. When a request is next delivered or refused, the daemon writes one line to the stack log, and exports it: ```plaintext [2026-10-02T14:03:11.209] Log export discarded 4096 records while the queue was full or the endpoint refused requests ``` The daemon writes such a line at most once a minute, and once more when it stops, for every record discarded since the previous line; that last line reaches the stack log file alone. The line is a warning, and `otlp_min_severity` goes up to `"warn"`, so every setting exports it. * **Daemon stop.** When the daemon stops or restarts, it sends what is queued for up to 3 seconds, one attempt per request, and discards the rest. Records that were discarded are not exported later, and neither are lines written while the export was off. The log files hold them. `peppy service serve` prints what the export runs into, once per failure until a request is delivered again: ```plaintext OTLP log export to collector.lan:4318: cannot connect (Connection refused (os error 111)); retrying OTLP log export to collector.lan:4318 recovered OTLP log export to otlp.example.com: the endpoint refused the request (401) and its records are discarded; check /home/ubuntu/.peppy/conf/otlp_headers.json5 OTLP log export to otlp.example.com: the endpoint refused the request (404) and its records are discarded; set otlp_endpoint to the base URL of the collector, such as http://localhost:4318 ``` ## What leaves the machine [Section titled “What leaves the machine”](#what-leaves-the-machine) Node and build output is exported as printed. A node that prints a secret exports it, and a build that prints a token exports it too. Redact in a collector on the machine when that matters. The lines the daemon writes itself hold no credentials of a git or HTTP source: the daemon writes such a URL without its password and its query string, and without its user name unless the URL is an `ssh` one, in the log files and in the records alike. The commands of a node’s `build_cmd` and `run_cmd` are written as the node’s config spells them. A build log is the largest log by far: a container build prints tens of thousands of lines in a few seconds, and most of them print no level. Filter on `peppy.log` in a collector when build output is not worth keeping remotely. # Pairing > First-class bidirectional communication between node instances through a named, two-role contract with explicit pairing In a standard Peppy setup, a node subscribes to topics from its declared dependencies using `link_id`. This creates a directed graph: if `arm_controller` depends on `robot_arm`, it can expect topics from `robot_arm`, but not the other way around, since a return dependency would make the graph circular. **Pairing** is Peppy’s first-class mechanism for the cases where two nodes genuinely talk to each other. A *pairing* is a named, versioned contract with exactly **two roles**; two node **instances** (one per role) are *paired* over it, and each side’s topics flow only to its paired peer: * **Explicit**: a pair is established by an operator action (`--link` on `peppy node run`, or `links:` in a launcher), never by discovery. * **Exclusive**: a pair is between two instances. A slot holds one pair by default; how many pairs it may hold is its declared [cardinality](#pairing-with-several-peers-through-one-slot). A second instance trying to pair at a taken scalar slot is rejected. * **Pair-before-traffic**: pairs are established when an instance starts. While unpaired, a slot is silent: publishes go nowhere and subscriptions receive nothing. * **Unpair on death**: when either instance dies, the pair dissolves automatically. The survivor keeps running with its slot unpaired until a new peer instance is started against it. A pairing dependency is deliberately **invisible to the node dependency graph**: two nodes paired with each other never form a cycle, and neither requires the other to be present at build time. Pairings are **topics only**; see [Why topics only?](#why-topics-only). For where pairing sits among the other mechanisms, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## Example: robot arm control loop [Section titled “Example: robot arm control loop”](#example-robot-arm-control-loop) Consider a robot arm that needs bidirectional communication between two nodes: * **`arm_controller`**: plans trajectories and sends joint commands. * **`robot_arm`**: drives the physical joints and reports their state. ```plaintext arm_controller (role: controller) robot_arm (role: arm) │ │ slot "arm" │─ emits joint_commands ───────────────▶│ slot "controller" │ │ │◀─────────────────── emits joint_states│ │ │ └─────────────── ⇌ ───────────────────┘ one pair over arm_link/v1 ``` One pairing document models both directions. Each topic declares which **role** emits it; the other role consumes it. ## Define the pairing [Section titled “Define the pairing”](#define-the-pairing) A pairing is a standalone `pairing/v1` document in a repository Peppy scans (see [Repositories](/advanced_guides/repositories/)). Like a contract, the `message_format` lives here once and both sides inherit it by reference, but unlike a contract, a pairing names *both* directions and the two roles playing them. pairings/arm_link/peppy.json5 ```json5 { peppy_schema: "pairing/v1", manifest: { name: "arm_link", tag: "v1", description: [ "The link between one controller and one arm: the controller commands the joints of the arm, and the arm gives back the state of its joints.", ], }, // Exactly two roles. Each paired instance plays one of them. roles: ["controller", "arm"], // One flat topic list; `emitted_by` names the role that publishes it, // and the other role consumes it. Pairings are topics-only. topics: [ { emitted_by: "controller", name: "joint_commands", description: "The joint positions that the controller wants, and the highest joint velocity on the way to them.", qos_profile: "reliable", message_format: { target_positions: { $type: "array", $items: "f64", $length: 3 }, max_velocity: "f64", }, }, { emitted_by: "arm", name: "joint_states", description: "The measured positions and velocities of the joints, with the time of the measure.", qos_profile: "sensor_data", message_format: { positions: { $type: "array", $items: "f64", $length: 3 }, velocities: { $type: "array", $items: "f64", $length: 3 }, timestamp: "time", }, }, ], } ``` The rules: * `roles` declares **exactly two** distinct roles. * `topics` is one flat list; every topic’s `emitted_by` must name one of the two roles, and topic names must be unique across the whole list. * Pairings declare **topics only**: no services, no actions. * A pairing topic is **live only**: it takes no `retention`. * The pairing describes itself in `manifest.description`, and each topic in a `description` after its `name`; a field can add a `$description`. See [Descriptions](/reference/concepts/#descriptions). After `peppy repo refresh`, the pairing is cached and addressable by `(name, tag)`. `peppy repo show :` lists the indexed nodes that play its roles and the ones that observe them, and `peppy repo show :` answers the same question from a node’s side, one section per pairing slot it declares (see [Show what a query matches](/advanced_guides/repositories/#show-what-a-query-matches)). ## Configure the nodes [Section titled “Configure the nodes”](#configure-the-nodes) Each node declares a **pairing slot** under `depends_on.pairings`: the contract, the role this node plays, and a `link_id` naming the slot. The `link_id` is how the node’s own code and the pairing commands refer to *the other end*; while paired, one peer instance sits behind each pair the slot holds. A slot holds one pair unless its `cardinality` says otherwise (see [Pairing with several peers through one slot](#pairing-with-several-peers-through-one-slot)); the rest of this page describes that default. The slot says *which* conversation the node joins. `interfaces.topics` says *what the node uses through it*, exactly like a contract implementer and a contract consumer. A pairing-backed entry is `{ link_id, name }`, plus an optional `refine` block (see [below](#refining-the-pairings-generic-arrays)): the pairing document remains the single source of description, shape and QoS, so an inline `description`, `message_format`, `qos_profile` or `retention` on one of these entries is rejected. * Python robot_arm/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "robot_arm", tag: "v1", description: ["The arm role of arm_link:v1: it moves to the joints that its controller commands and gives back the state of its joints."], depends_on: { pairings: [ // One pairing slot: this node plays the `arm` role of arm_link/v1. // The slot's link_id names the OTHER end from this node's point of // view; while paired, one controller instance sits behind it. // `cardinality: "zero_or_one"` says this node runs fine with nobody // commanding it, so a deployment may write the slot vacant; at the // default `one`, every deployment must pair the slot. { name: "arm_link", tag: "v1", role: "arm", link_id: "controller", cardinality: "zero_or_one" }, ], }, }, interfaces: { topics: { // The `arm` role's side of the conversation, declared the same way a // contract implementer declares its contract members. The pairing // document stays the source of shape and QoS; these entries only say // which of its topics this node uses. emits: [ { link_id: "controller", name: "joint_states" }, ], consumes: [ { link_id: "controller", name: "joint_commands" }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "robot_arm"], }, } ``` * Rust robot_arm/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "robot_arm", tag: "v1", description: ["The arm role of arm_link:v1: it moves to the joints that its controller commands and gives back the state of its joints."], depends_on: { pairings: [ // One pairing slot: this node plays the `arm` role of arm_link/v1. // The slot's link_id names the OTHER end from this node's point of // view; while paired, one controller instance sits behind it. // `cardinality: "zero_or_one"` says this node runs fine with nobody // commanding it, so a deployment may write the slot vacant; at the // default `one`, every deployment must pair the slot. { name: "arm_link", tag: "v1", role: "arm", link_id: "controller", cardinality: "zero_or_one" }, ], }, }, interfaces: { topics: { // The `arm` role's side of the conversation, declared the same way a // contract implementer declares its contract members. The pairing // document stays the source of shape and QoS; these entries only say // which of its topics this node uses. emits: [ { link_id: "controller", name: "joint_states" }, ], consumes: [ { link_id: "controller", name: "joint_commands" }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/robot_arm"], }, } ``` - Python arm_controller/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "arm_controller", tag: "v1", description: ["The controller role of arm_link:v1: it commands the joints of one arm and reads the state of its joints."], depends_on: { pairings: [ // The complementary slot: this node plays the `controller` role of // the same contract, and its slot points at one arm. `cardinality: // "zero_or_one"` says it also runs with no arm behind the slot, so a // deployment may write the slot vacant. { name: "arm_link", tag: "v1", role: "controller", link_id: "arm", cardinality: "zero_or_one" }, ], }, }, interfaces: { topics: { // The mirror image of the arm's block: this role emits the commands and // consumes the states. emits: [ { link_id: "arm", name: "joint_commands" }, ], consumes: [ { link_id: "arm", name: "joint_states" }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "arm_controller"], }, } ``` - Rust arm_controller/peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "arm_controller", tag: "v1", description: ["The controller role of arm_link:v1: it commands the joints of one arm and reads the state of its joints."], depends_on: { pairings: [ // The complementary slot: this node plays the `controller` role of // the same contract, and its slot points at one arm. `cardinality: // "zero_or_one"` says it also runs with no arm behind the slot, so a // deployment may write the slot vacant. { name: "arm_link", tag: "v1", role: "controller", link_id: "arm", cardinality: "zero_or_one" }, ], }, }, interfaces: { topics: { // The mirror image of the arm's block: this role emits the commands and // consumes the states. emits: [ { link_id: "arm", name: "joint_commands" }, ], consumes: [ { link_id: "arm", name: "joint_states" }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/arm_controller"], }, } ``` The two manifests are mirror images, which is what makes the conversation legible from either side alone: | Node | Role in `arm_link` | Slot (`link_id`) | Emits to the peer | Consumes from the peer | | ---------------- | ------------------ | ---------------- | ----------------- | ---------------------- | | `robot_arm` | `arm` | `controller` | `joint_states` | `joint_commands` | | `arm_controller` | `controller` | `arm` | `joint_commands` | `joint_states` | ### Coverage: emit side complete, consume side free [Section titled “Coverage: emit side complete, consume side free”](#coverage-emit-side-complete-consume-side-free) The two directions are checked differently, and for the same reasons contracts are: * **`emits` must be exact.** The entries for a slot are precisely the document’s topics whose `emitted_by` is the slot’s role: no missing entry, no unknown name, no duplicate, and never a topic the *counterpart* role emits. A role that silently stopped emitting one of its topics would break its peer, and the pairing document is the promise that it will not. * **`consumes` may be partial.** List any subset of the counterpart role’s topics. Omitting one is a legitimate way to ignore part of a pairing: no module is generated for that topic, so no subscription can be created for it. This is a local decision with no effect on the peer. Declaring zero consumes is fine, including for a slot whose counterpart role emits nothing. Naming a topic under `consumes` that this node’s own role emits is an error, as is naming a topic that is absent from the document. Both are reported as one aggregated diff per slot, so a manifest with several wrong entries produces one readable report rather than a cascade. Every participant slot must be covered: starting the instance without pairing the slot, or without declaring it vacant, fails loudly. A deployment that runs the node with a slot unpaired says so with `--vacant-link 'SLOT='` / `links: { : { vacant: "" } }`, and the reason is required, so an unpaired slot is always something the deployment wrote down, with its rationale, rather than something it forgot. Whether a slot *may* be vacated at all is the node’s own call, made once in its manifest with `cardinality: "zero_or_one"` on the `depends_on.pairings` entry. That is the deployment-independent half of the statement: a reader of the node can tell which of its slots run without a peer without sweeping every launcher, and a slot that must never boot unpaired cannot be waived by any deployment. The manifest says “may be empty”, the deployment says “is empty here, because”, and a slot nobody mentioned is uncovered either way. A vacancy on a required slot is refused with the manifest key that would lift the bar. Coverage is a launch-time question and has no bearing on what the node declares through the slot: a slot that boots vacant is interface-checked exactly like a paired one. ### Refining the pairing’s generic arrays [Section titled “Refining the pairing’s generic arrays”](#refining-the-pairings-generic-arrays) A pairing between a leader and any jointed device keeps its joint vectors generic (`positions: { $type: "array", $items: "f64" }`, one entry per joint), because the document cannot know every device’s joint count. The device node does, and pins it with a `refine` block on its pairing-backed entries, in both directions of the slot: ```json5 topics: { emits: [ { link_id: "leader", name: "joint_states", refine: { message_format: { positions: { $length: 7 } } } }, ], consumes: [ { link_id: "leader", name: "joint_setpoints", refine: { message_format: { positions: { $length: 7 } } } }, ], }, ``` The generated modules carry the pinned length (`[f64; 7]` in Rust, a length-checked `list[float]` in Python) while the peer, generating from the document as written, stays generic; both encode the array the same way on the wire. An observer’s `consumes` entries may refine the observed role’s topics the same way. The block’s syntax and the rules for what it may pin are those of contract entries, described in [Contract implementation](/advanced_guides/contract_implementation/#refining-the-contracts-generic-arrays); an inadmissible pin is reported per entry once the slot’s coverage is clean, naming the pairing the slot resolved through. ## Establishing pairs [Section titled “Establishing pairs”](#establishing-pairs) Pairs are established **when an instance starts**; there is no runtime “pair” command. The instance being started names the peer it pairs with; the peer must already be running (or starting) with a complementary unpaired slot. The peer must also read the same clock. A pair whose two endpoints resolve to different [clock domains](/advanced_guides/system_clock/#clock-domains) is refused as the pair is established, at launch and at `peppy node run` alike. ```sh peppy repo refresh peppy node add -s ./robot_arm # sync interfaces, then add to the stack peppy node add -s ./arm_controller # The first instance has no peer yet. Its manifest declares the slot # `cardinality: "zero_or_one"`, so this deployment may declare it vacant; it # boots with the slot silent. peppy node run --instance-id arm_1 robot_arm:v1 \ --vacant-link 'controller=the commander starts after this arm' # The second instance pairs its `arm` slot with arm_1 at start. peppy node run --instance-id ctrl_1 arm_controller:v1 --link arm@arm_1 ``` The `--link` value is `LINK_ID@PEER_INSTANCE[/PEER_LINK]`: your slot, the running peer instance, and (only when the peer declares several complementary slots of the same pairing) which of the peer’s slots to claim. The `--vacant-link` value is `SLOT=`, split on the first `=`, so the reason may itself contain `=` and needs no escaping. Running a node whose slot is neither `--link`ed nor `--vacant-link`ed is a hard error naming the missing slot, and the remedies it offers follow the manifest. A `zero_or_one` slot’s error names both: ```sh $ peppy node run arm_controller:v1 Error: instance `brave-lovelace-4821` declares pairing slot `arm` (pairing `arm_link:v1`, role `controller`, cardinality `zero_or_one`) with no pair. Pair it (launcher `links: { arm: "" }` / `--link arm@`), or leave it empty on purpose (`links: { arm: { vacant: "" } }` / `--vacant-link 'arm='`) ``` A `one` slot’s error names the pairing and both steps to an empty slot, the manifest key and the vacancy, so it never advertises an escape hatch the node forbids: ```sh Error: instance `brave-lovelace-4821` declares pairing slot `arm` (pairing `arm_link:v1`, role `controller`, cardinality `one`) with no pair. Pair it (launcher `links: { arm: "" }` / `--link arm@`), or, if it is meant to run empty, declare `cardinality: "zero_or_one"` on its `depends_on.pairings` entry and then leave it empty on purpose (`links: { arm: { vacant: "" } }` / `--vacant-link 'arm='`) ``` In a launcher, the pair is declared once, on either instance, with `links:`; a slot left intentionally unpaired takes a `{ vacant: "" }` value in that same map: peppy_launcher.json5 ```json5 { peppy_schema: "launcher/v1", description: ["One arm and its controller, paired over arm_link:v1. It needs no device."], deployments: [ { source: { name: "robot_arm:v1" }, instances: [{ instance_id: "arm_1" }], }, { source: { name: "arm_controller:v1" }, instances: [{ instance_id: "ctrl_1", // My `arm` slot pairs with the arm_1 instance. Declaring the same // pair from arm_1's side instead (or as well) is equivalent. links: { arm: "arm_1" }, }], }, ], } ``` `peppy stack launch` validates the whole pair plan up front (coverage, complementary roles, exclusivity, ambiguity) and establishes each pair as its second endpoint comes up. `peppy stack list` shows every pairing participant slot, paired or not, with a bidirectional `⇌` arrow, one row per pair the slot holds ([observer slots](#observers-watching-a-pairing-without-joining-it) are not listed there): ```plaintext Instance pairings NODE INSTANCE PAIRINGS robot_arm:v1 arm_1 controller ⇌ ctrl_1:arm@cn-adoring-zebra (arm_link:v1) arm_controller:v1 ctrl_1 arm ⇌ arm_1:controller@cn-adoring-zebra (arm_link:v1) ``` ## Using the generated API [Section titled “Using the generated API”](#using-the-generated-api) `peppy node sync` generates a module per declared slot topic under `peppygen.paired_topics..` (Python) / `peppygen::paired_topics::::` (Rust); both directions of a slot live under the same `link_id`. The modules follow the manifest’s entries, not the document’s full topic list, so a counterpart topic you left out of `consumes` simply has no module. Pairing topics never appear under `consumed_topics` or `emitted_topics`, whichever direction they travel. Emitting and consuming look exactly like ordinary topics, plus the slot’s state on every module: `paired()` returns the current peer’s identity (`None` while unpaired) and `wait_paired()` awaits one. A slot that holds several pairs exposes `peers()` in their place (see [Pairing with several peers through one slot](#pairing-with-several-peers-through-one-slot)). * Python src/robot_arm/\_\_main\_\_.py ```python import asyncio import logging import time from peppygen import NodeBuilder, NodeRunner from peppygen.paired_topics.controller import joint_commands, joint_states from peppygen.parameters import Parameters logger = logging.getLogger(__name__) # `robot_arm` plays the `arm` role of the `arm_link` pairing. Both # directions of its `controller` slot live under # `peppygen.paired_topics.controller`: it consumes `joint_commands` from and emits # `joint_states` to whichever single controller instance is currently # paired on the slot. Unpaired, the subscription stays silent and # publishes go nowhere; the code does not change either way. async def handle_commands(node_runner: NodeRunner): # Declare the publisher once, then publish each state on it. try: publisher = await joint_states.declare_publisher(node_runner) except Exception: logger.exception("Failed to declare joint_states publisher") return # Subscribing while unpaired is legal: the held subscription yields # nothing until a controller pairs, then only that controller's messages. try: subscription = await joint_commands.subscribe(node_runner) except Exception: logger.exception("Failed to subscribe to joint_commands") return # Optional: block until a controller is paired and log who it is. try: peer = await joint_commands.wait_paired(node_runner) print( f"paired with controller {peer.producer.core_node}/{peer.producer.instance_id}" ) except Exception: logger.exception("Failed to wait for a paired controller") return while True: try: received = await subscription.next() except Exception: # Log the failure, then pause before retrying so a persistent # receive error does not spin the loop at full speed. logger.exception("Error receiving joint command") await asyncio.sleep(1.0) continue if received is None: break # subscription closed peer, command = received # `peer` is always the paired controller's identity. print( f"command from {peer.producer.core_node}/{peer.producer.instance_id}: " f"target={command.target_positions} max_vel={command.max_velocity}" ) # Drive the joints, then report the resulting state back to the # paired controller. try: await publisher.publish( joint_states.build_message( command.target_positions, [0.0, 0.0, 0.0], time.time(), ) ) except Exception: logger.exception("Failed to publish joint state") async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(handle_commands(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use peppygen::paired_topics::controller::{joint_commands, joint_states}; use peppygen::{NodeBuilder, Parameters, Result}; // `robot_arm` plays the `arm` role of the `arm_link` pairing. Both // directions of its `controller` slot live under // `peppygen::paired_topics::controller`: it consumes `joint_commands` from and // emits `joint_states` to whichever single controller instance is // currently paired on the slot. Unpaired, the subscription stays silent // and publishes go nowhere; the code does not change either way. fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { tokio::spawn(async move { // Declare the publisher once; every publish below is then lock-free. let publisher = match joint_states::declare_publisher(&node_runner).await { Ok(publisher) => publisher, Err(e) => { eprintln!("Failed to declare joint_states publisher: {e}"); return; } }; // Subscribing while unpaired is legal: the held subscription // yields nothing until a controller pairs, then only that // controller's messages. let mut subscription = match joint_commands::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe to joint_commands: {e}"); return; } }; // Optional: block until a controller is paired and log who it is. match joint_commands::wait_paired(&node_runner).await { Ok(peer) => println!( "paired with controller {}/{}", peer.producer.core_node, peer.producer.instance_id ), Err(e) => { eprintln!("Failed to wait for a paired controller: {e}"); return; } } loop { let (peer, command) = match subscription.next().await { Ok(Some(received)) => received, Ok(None) => break, Err(e) => { eprintln!("Error receiving joint command: {e}"); continue; } }; // `peer` is always the paired controller's identity. println!( "command from {}/{}: target={:?} max_vel={}", peer.producer.core_node, peer.producer.instance_id, command.target_positions, command.max_velocity ); // Drive the joints, then report the resulting state back to // the paired controller. match joint_states::build_message( command.target_positions, [0.0, 0.0, 0.0], std::time::SystemTime::now(), ) { Ok(payload) => { if let Err(e) = publisher.publish(payload).await { eprintln!("Failed to publish joint state: {e}"); } } Err(e) => eprintln!("Failed to build joint_states message: {e}"), } } }); Ok(()) }) } ``` On the other side, `arm_controller` emits `joint_commands` and consumes `joint_states` through its `arm` slot: * Python src/arm_controller/\_\_main\_\_.py ```python import asyncio import logging from peppygen import NodeBuilder, NodeRunner from peppygen.paired_topics.arm import joint_commands, joint_states from peppygen.parameters import Parameters logger = logging.getLogger(__name__) # `arm_controller` plays the `controller` role of the `arm_link` pairing. # Both directions of its `arm` slot live under `peppygen.paired_topics.arm`: it # emits `joint_commands` to and consumes `joint_states` from the single # arm instance currently paired on the slot. If that arm dies, the slot # unpairs and the loop simply stops receiving until a new arm is paired. def compute_next_target(current: list[float]) -> list[float]: # Trajectory planning logic return [current[0] + 0.1, current[1], current[2]] async def control_loop(node_runner: NodeRunner): # Declare the publisher once, then publish each command on it. try: publisher = await joint_commands.declare_publisher(node_runner) except Exception: logger.exception("Failed to declare joint_commands publisher") return # Subscribing while unpaired is legal: the subscription follows the # slot's live pin, silent until an arm is paired. try: subscription = await joint_states.subscribe(node_runner) except Exception: logger.exception("Failed to subscribe to joint_states") return # Optional: block until an arm is paired and log who it is. try: peer = await joint_states.wait_paired(node_runner) print(f"paired with arm {peer.producer.core_node}/{peer.producer.instance_id}") except Exception: logger.exception("Failed to wait for a paired arm") return while True: try: received = await subscription.next() except Exception: # Log the failure, then pause before retrying so a persistent # receive error does not spin the loop at full speed. logger.exception("Error receiving joint state") await asyncio.sleep(1.0) continue if received is None: break # subscription closed peer, state = received # `peer` is always the paired arm's identity. print( f"state from {peer.producer.core_node}/{peer.producer.instance_id}: " f"positions={state.positions}" ) # Compute the next target from the reported state, then command it. target = compute_next_target(state.positions) try: await publisher.publish( joint_commands.build_message( target, 1.0, # max_velocity ) ) except Exception: logger.exception("Failed to publish joint command") async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(control_loop(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use peppygen::paired_topics::arm::{joint_commands, joint_states}; use peppygen::{NodeBuilder, Parameters, Result}; // `arm_controller` plays the `controller` role of the `arm_link` pairing. // Both directions of its `arm` slot live under `peppygen::paired_topics::arm`: it // emits `joint_commands` to and consumes `joint_states` from the single // arm instance currently paired on the slot. If that arm dies, the slot // unpairs and the loop simply stops receiving until a new arm is paired. fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { tokio::spawn(async move { // Declare the publisher once; every publish below is then lock-free. let publisher = match joint_commands::declare_publisher(&node_runner).await { Ok(publisher) => publisher, Err(e) => { eprintln!("Failed to declare joint_commands publisher: {e}"); return; } }; // Subscribing while unpaired is legal: the subscription follows // the slot's live pin, silent until an arm is paired. let mut subscription = match joint_states::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe to joint_states: {e}"); return; } }; // Optional: block until an arm is paired and log who it is. match joint_states::wait_paired(&node_runner).await { Ok(peer) => println!( "paired with arm {}/{}", peer.producer.core_node, peer.producer.instance_id ), Err(e) => { eprintln!("Failed to wait for a paired arm: {e}"); return; } } loop { let (peer, state) = match subscription.next().await { Ok(Some(received)) => received, Ok(None) => break, Err(e) => { eprintln!("Error receiving joint state: {e}"); continue; } }; // `peer` is always the paired arm's identity. println!( "state from {}/{}: positions={:?}", peer.producer.core_node, peer.producer.instance_id, state.positions ); // Compute the next target from the reported state, then command it. let target = compute_next_target(&state.positions); match joint_commands::build_message(target, 1.0) { Ok(payload) => { if let Err(e) = publisher.publish(payload).await { eprintln!("Failed to publish joint command: {e}"); } } Err(e) => eprintln!("Failed to build joint_commands message: {e}"), } } }); Ok(()) }) } fn compute_next_target(current: &[f64; 3]) -> [f64; 3] { // Trajectory planning logic [current[0] + 0.1, current[1], current[2]] } ``` The key behavioral guarantees, all handled by the runtime with no application code: * **Silent while unpaired.** Publishing on an unpaired slot is a legal no-op, and a subscription on an unpaired slot just waits. Nodes never need pairing-state conditionals around their control loops. * **Only the paired peer.** A subscription delivers messages from the paired peer instance and nothing else: not from other instances of the same node, not from implementing third parties. A publish reaches the paired peer alone, and a pairing emission is addressed to the peer it is for, so a peer paired elsewhere on the same pairing hears nothing of it. The slot *is* the identity; there is no payload-level demultiplexing (`arm_id` fields and the like) to write. * **A pairing is a live stream, not a mailbox.** Messages published before the pair was established are never delivered. * **Re-pinning is seamless.** When the daemon re-pairs a surviving slot to a new peer, the held subscription switches over internally; no stale messages from the old peer leak through. ## Lifecycle: death, failover, exclusivity [Section titled “Lifecycle: death, failover, exclusivity”](#lifecycle-death-failover-exclusivity) A pair lives exactly as long as both endpoints. When an instance dies (crashes, is stopped with `peppy node stop`, or is torn down by a stack operation), the daemon dissolves its pairs and live-notifies each survivor that its slot is now unpaired. The survivor keeps running; its slot goes silent. An instance the daemon starts again under its [restart policy](/guides/launch_files/#restart-policy) requests every pair it held, so the survivor is paired again once the restarted peer is running. A slot that takes one peer keeps only the pair made last. A pair whose peer has no process at the restart (it is restarting, `finished` or `failed`), or whose peer’s node or daemon does not take it, stays held and is requested again when either end restarts. A pair whose peer’s slot another instance took meanwhile is forgotten, so a restart does not take the slot back: on one daemon when the slot is taken, and across daemons when the restart asks for the pair, where the run log says so and to launch the stack again on its coordinator with `peppy stack launch`, or, for a pair a copy’s `peppy stack join` made, to remove that copy with `peppy stack remove NAME` and join it again there. A pair whose peer the other daemon no longer tracks is forgotten the same way. A peer stopped on purpose (`peppy node stop`, `peppy node remove`, `peppy node add` over its node, `peppy stack remove`) is forgotten by its survivors on its own daemon and on every other daemon that hears of the stop, so a survivor restarted later requests no pair with it. A survivor whose daemon was unreachable at the stop keeps the pair until its next restart asks the stopped peer’s daemon for it, which makes it only while the instance under that id keeps that pair itself, and otherwise refuses it, so the survivor forgets it. A new instance started under that id pairs only through a link of its own. Failover is then just another `--link` at start: ```sh # ctrl_1 died (or was stopped). arm_1 keeps running, slot unpaired. peppy node run --instance-id ctrl_2 arm_controller:v1 --link arm@arm_1 ``` `ctrl_2` pairs with the surviving `arm_1`, whose subscription and publisher switch to the new peer live; the arm’s code never restarts and never notices beyond `paired()` reporting a new identity. Exclusivity is enforced at establishment: while `arm_1`’s slot is paired, a third instance running with `--link arm@arm_1` is rejected naming the existing pair. To hand an arm to a different controller, stop the old controller first (or run the new one against a different arm). A [multi slot](#pairing-with-several-peers-through-one-slot) is open to every peer it does not already hold; only the same pair declared twice is rejected. Pairs do not survive a daemon restart Pairing state lives in the daemon, alongside the node stack itself. Like the stack, it is in-memory: after a daemon restart, instances are gone and so are their pairs; a fresh launch re-establishes them. ## Multiple slots: the two-arm commander [Section titled “Multiple slots: the two-arm commander”](#multiple-slots-the-two-arm-commander) Because the slot, not the node, is the unit of pairing, a node can declare several slots of the *same* pairing and hold one peer per slot, each a fully isolated stream. Each slot is declared and covered on its own, so the two arms stay independent all the way down to the generated modules: ```json5 // two_arm_commander/peppy.json5 (manifest excerpt) depends_on: { pairings: [ { name: "arm_link", tag: "v1", role: "controller", link_id: "left_arm" }, { name: "arm_link", tag: "v1", role: "controller", link_id: "right_arm" }, ], }, interfaces: { topics: { // Emit coverage is per slot, so the controller role's `joint_commands` // is listed once for each arm. emits: [ { link_id: "left_arm", name: "joint_commands" }, { link_id: "right_arm", name: "joint_commands" }, ], consumes: [ { link_id: "left_arm", name: "joint_states" }, { link_id: "right_arm", name: "joint_states" }, ], }, }, ``` ```sh peppy node add -s ./two_arm_commander peppy node run --instance-id arm_l robot_arm:v1 \ --vacant-link 'controller=the commander starts after both arms' peppy node run --instance-id arm_r robot_arm:v1 \ --vacant-link 'controller=the commander starts after both arms' peppy node run --instance-id cmd_1 two_arm_commander:v1 \ --link left_arm@arm_l --link right_arm@arm_r ``` The generated code addresses each arm through its slot module (`paired_topics.left_arm.joint_commands` vs `paired_topics.right_arm.joint_commands` in Python, `paired_topics::left_arm::joint_commands` vs `paired_topics::right_arm::joint_commands` in Rust), and each subscription receives only its own arm’s states. When a peer instance declares several complementary slots (pairing two commanders’ arms to each other, say), disambiguate the target with `--link left_arm@cmd_2/right_arm`. ## Pairing with several peers through one slot [Section titled “Pairing with several peers through one slot”](#pairing-with-several-peers-through-one-slot) A participant slot carries a [`cardinality`](/advanced_guides/topics/#dependency-cardinality) the way a producer-binding slot does, counted in pairs: a simulation engine holding every backbone’s `arm_link` pair through one `limbs` slot, a fleet coordinator paired with each robot’s planner. Each pair is still between two instances, the slot at this end and one peer’s slot at the other, and each direction of each pair is a stream of its own. ```json5 // sim_engine/peppy.json5 (manifest excerpt) depends_on: { pairings: [ // One pair per backbone limb; a fleet with no robots yet holds none. { name: "arm_link", tag: "v1", role: "arm", link_id: "limbs", cardinality: "zero_or_more" }, ], }, ``` | `cardinality` | Launcher `links:` value | Omitting the slot | | ------------------- | --------------------------------------- | -------------------------------------------------------------- | | `one` (the default) | a single peer, `limbs: "ctrl_1"` | rejected: it holds exactly one pair, so it takes a peer | | `zero_or_one` | a single peer, or `{ vacant: "" }` | rejected: link it or declare it vacant | | `one_or_more` | an array, `limbs: ["ctrl_1", "ctrl_2"]` | rejected: it has no empty state, so it takes at least one peer | | `zero_or_more` | an array, possibly empty | valid, and means no pair | On the CLI the array becomes repetition: `--link limbs@ctrl_1 --link limbs@ctrl_2`. Each target is a pair of its own, so the peer’s slot must be open to it: a peer’s scalar slot already paired elsewhere is rejected as it is for any pair, and a peer’s multi slot takes the new pair alongside the ones it holds. A pair declared twice on the same slot is rejected as a duplicate. A multi slot’s set grows and shrinks with the stack. `peppy stack join` pairs a joining copy’s instances into a running instance’s multi slot, so a robot added to a running fleet pairs its backbone with the engine that is already simulating the others; `peppy stack remove` dissolves exactly those pairs, and an instance that dies takes its pairs with it, as on a scalar slot. Each pair carries the copy its peer was launched in, so a node holding four limb pairs per robot groups them by copy without naming conventions; an instance run outside a copy pairs with no copy name. `peppy stack list` renders one row per pair. Each row names the copy its peer was launched in, so an engine simulating several robots reads them apart with no naming convention (a pair whose peer runs outside a copy carries no `[copy ...]`): ```plaintext Instance pairings NODE INSTANCE PAIRINGS sim_engine:v1 engine_1 limbs ⇌ alpha_backbone:engine@cn-adoring-zebra [copy alpha] (arm_link:v1) limbs ⇌ bravo_backbone:engine@cn-adoring-zebra [copy bravo] (arm_link:v1) ``` Before any robot joins, the same slot holds nothing, which reads as `(no pairs)`, not `(unpaired)`: an empty `zero_or_more` slot is its steady state rather than a slot missing a peer it expects. ```plaintext Instance pairings NODE INSTANCE PAIRINGS sim_engine:v1 engine_1 limbs ⇌ (no pairs) [role arm of arm_link:v1] ``` The declared cardinality names the generated accessor. A scalar slot (`one`, `zero_or_one`) exposes `paired()` and `wait_paired()`. A multi slot (`one_or_more`, `zero_or_more`) exposes `peers()` returning every pair the slot holds as a list. A `one_or_more` slot’s floor is what the plan guarantees at launch, so its accessor reads the live set like any other and the list empties once every peer has stopped. Each member is a `PeerMember`: its `info` is the peer’s identity, the same `PeerInfo` a scalar slot’s `paired()` answers, and its `copy` is the copy the peer belongs to. The set is live and read in establishment order. Publishing names the peer. `declare_publisher` on a multi slot answers a `PeerPublisher` whose `publish_to(peer, payload)` addresses one member’s `info`; a peer the slot does not hold is refused, so a message never leaves for a pair that ended. On a scalar slot `declare_publisher` answers the same `TopicPublisher` an ordinary topic does, whose `publish(payload)` reaches the one paired peer and is a no-op while unpaired. `subscribe` keeps its shape at every cardinality and fans in across the whole set, tagging each message with the `PeerInfo` that published it. * Python ```python from peppygen.paired_topics.limbs import joint_commands, joint_states # `limbs` is zero_or_more: read every pair the slot holds, with the copy # each peer was launched in, and command each peer by name. commands = await joint_commands.declare_publisher(node_runner) for member in joint_commands.peers(node_runner): print(member.info.producer.instance_id, member.copy) await commands.publish_to(member.info, joint_commands.build_message([0.0, 0.5, 1.0], 0.25)) # One subscription covers every pair; the peer tag says which limb spoke. subscription = await joint_states.subscribe(node_runner) async for peer, states in subscription: print(peer.producer.instance_id, states.positions) ``` * Rust ```rust use peppygen::paired_topics::limbs::{joint_commands, joint_states}; // `limbs` is zero_or_more: read every pair the slot holds, with the copy // each peer was launched in, and command each peer by name. let commands = joint_commands::declare_publisher(&node_runner).await?; for member in joint_commands::peers(&node_runner)? { println!("{} {:?}", member.info.producer.instance_id, member.copy); commands .publish_to(&member.info, joint_commands::build_message([0.0, 0.5, 1.0], 0.25)?) .await?; } // One subscription covers every pair; the peer tag says which limb spoke. let mut subscription = joint_states::subscribe(&node_runner).await?; while let Some((peer, states)) = subscription.next().await? { println!("{} {:?}", peer.producer.instance_id, states.positions); } ``` The instance’s own copy is `node_runner.copy()` in both languages, `None` outside a copy, so a node paired into several copies can tell its own from its peers’. ## Observers: watching a pairing without joining it [Section titled “Observers: watching a pairing without joining it”](#observers-watching-a-pairing-without-joining-it) A pair is exclusive between two instances, but sometimes a third node just wants to *watch* one side’s stream: a recorder logging every `joint_states` an arm emits, a dashboard tailing a controller’s setpoints. Joining the pair is wrong (the watcher has nothing to send back), and a separate contract would duplicate the topic shape. An **observer slot** solves this: it passively taps the topics a chosen role emits, following that source instance’s own lifecycle rather than any pairing. An observer reads the source’s clock too: an observation whose watcher and source resolve to different [clock domains](/advanced_guides/system_clock/#clock-domains) is refused, on the same rule that governs pairs and producer bindings. Declare an observer slot in `depends_on.pairing_observers`, where `role` names the role being observed rather than one this node plays, and list the topics it taps in `interfaces.topics.consumes` under its `link_id`. An observer plays no role, claims no endpoint, and emits nothing, so it never needs coverage on an emit side: ```json5 // recorder/peppy.json5 (manifest excerpt) depends_on: { pairing_observers: [ // Watch whatever the `arm` role of arm_link/v1 publishes. { name: "arm_link", tag: "v1", role: "arm", link_id: "watch" } ] }, interfaces: { topics: { // The `arm` role emits joint_states; tap it through the `watch` slot. consumes: [{ link_id: "watch", name: "joint_states" }] } } ``` Link the observer to a **source instance** the same way you establish a pairing, with `--link` (or a launcher `links:` entry); the target is the instance to observe, not a peer to pair with: ```sh peppy node add -s ./recorder # Observe arm_1, whichever controller it happens to be paired with (or none). peppy node run --instance-id rec_1 recorder:v1 --link watch@arm_1 ``` The runtime guarantees mirror pairing’s, with the lifecycle twist that defines an observer: * **Follows the source, not a pair.** The observer receives `arm_1`’s emissions whichever controller `arm_1` is paired with, and it is unaffected when `arm_1` re-pairs to a different controller. It is pinned to the source instance itself. While `arm_1` is unpaired, its slot is silent, so the observer receives nothing. * **Many observers, one source.** Observation is not exclusive: any number of recorders can watch the same arm at once, and none of them affects the pair. * **Incarnation-isolated.** If the source instance restarts, the observer transparently drops the old stream and picks up the new incarnation: the drop discards everything its subscription buffered before the switch, so no buffered message from a previous run of the source leaks into the new stream. The switch happens when the daemon’s lifecycle notify records the new incarnation and delivers it, which follows the restart by the notify latency; isolation is enforced at that boundary, not by wall-clock simultaneity with the restart. * **Read-only.** The generated module for an observer topic exposes the same subscription surface as a consumed topic, plus a helper reporting the pairings the slot observes. There is no publisher and no `paired()`; an observer never talks back. * **Not shown in `peppy stack list`.** The `Instance pairings` table renders participant slots only; inspect an observer’s links through its generated source helper instead. The generated modules live alongside participant slots under `peppygen.paired_topics..` (Python) / `peppygen::paired_topics::::` (Rust). ### Naming a pair by its other end [Section titled “Naming a pair by its other end”](#naming-a-pair-by-its-other-end) A slot that holds several pairs, say a simulation engine playing `arm` for a fleet of controllers through one `zero_or_more` slot, publishes one copy of `joint_states` per pair, and `watch: "engine_1"` hears every copy under the one source tag. To watch one pair, name it by its other end: the target is the instance and slot playing the *other* role, and the observation is pinned to the one pair that end holds. ```json5 // The recorder of copy `alpha` records its own controller's pair with the engine. links: { watch: "alpha_ctrl/arm" } ``` The stream is still what the `arm` role publishes: `source()` reports the engine as the source and carries the controller end as `peer`, and the subscription hears that pair’s copy alone. A `commanded` slot observing the `controller` role names the same pair by the same end, `commanded: "alpha_ctrl/arm"`, so a launcher writes one target for both directions of a pair. The end named must hold exactly one pair in the plan or the running stack; an end holding none, or several, is refused with the fix. ### Observing several pairings through one slot [Section titled “Observing several pairings through one slot”](#observing-several-pairings-through-one-slot) An observer slot carries a [`cardinality`](/advanced_guides/topics/#dependency-cardinality) the way a producer-binding slot does, so one slot can watch a whole fleet: | `cardinality` | Launcher `links:` value | Omitting the slot | | ------------------- | ----------------------------------------- | ---------------------------------------------------------------- | | `one` (the default) | a single target, `watch: "arm_1"` | rejected: it observes exactly one pairing, so it takes a source | | `zero_or_one` | a single target, or `{ vacant: "" }` | rejected: link it or declare it vacant | | `one_or_more` | an array, `watch: ["arm_1", "arm_2"]` | rejected: it has no empty state, so it takes at least one source | | `zero_or_more` | an array, possibly empty | valid, and means the empty set | Among observer slots vacancy is only for the `zero_or_one` row, the same key a participant slot uses: the node declaring it is the node saying it runs fine watching nothing. A `one` slot observes exactly one pairing, a `one_or_more` slot has no empty state to write, and a `zero_or_more` slot already writes its empty set as `[]`. A producer-binding slot reads the same key the same way (see [dependency cardinality](/advanced_guides/topics/#dependency-cardinality)). Only `zero_or_more` may be omitted, because it is the only one whose absence has no failure mode; every other slot needs an explicit line, which is what keeps a slot you forgot distinguishable from one you emptied on purpose. On the CLI the array becomes repetition: `--link watch@arm_1 --link watch@arm_2`. Either way the order you write is the order the node reads back, so a deployment can associate the Nth observed pairing with its own Nth command slot. A running observer’s `one_or_more` or `zero_or_more` slot grows when a [copy joins](/guides/launch_files/#copies) and adds its own instances to it, and shrinks when that copy is removed. The daemon delivers the whole new set: `sources()` returns it on the next read, and a held subscription starts receiving from the new members and stops receiving from the departed ones, with no restart. A member a join adds behaves like one the launch wrote: it holds its position in the order the copies joined, it is incarnation-isolated, and it reads as not live while its source is down. The declared cardinality types the generated accessor, name and return type together, so flipping it surfaces at every call site rather than silently reading one member of many, or an empty set the plan said could not happen. A `one` slot exposes `source()` returning the observed pairing directly, with no absent case to handle. A `zero_or_one` slot exposes the same singular `source()` returning `Optional[ObservedSource]` in Python and `Option` in Rust, empty wherever the deployment wrote the slot vacant. A `one_or_more` slot exposes `sources()` returning a set that is never empty, so its head needs no unwrap: in Rust that is a `NonEmptyObservedSources` whose `first()` is infallible, and in Python a `List` documented never-empty, since Python has no non-empty list type and the name flip is what surfaces the change. A `zero_or_more` slot exposes `sources()` returning a plain, possibly empty list in plan order, so the empty branch exists exactly where a deployment can produce one. `subscribe` keeps its shape at every cardinality and fans in across the whole set, tagging each message with the `ObservedSource` that published it: the producer’s wire address plus the producer-side link_id, and the pair’s other end when the link named the pair by it (see [Naming a pair by its other end](#naming-a-pair-by-its-other-end)), the same identity the accessors enumerate, so members stay distinct even when several observe the same instance. * Python ```python from peppygen.paired_topics.watch import joint_states # `watch` is one_or_more: read the whole observed set, in plan order. The # set is never empty at that cardinality, so `[0]` is always valid. sources = joint_states.sources(node_runner) print("lead arm:", sources[0].producer.instance_id) for source in sources: print(source.producer.instance_id, source.source_link_id) # One subscription covers every member; the source tag says which pairing # sent what, even when members share one instance. subscription = await joint_states.subscribe(node_runner) async for source, states in subscription: print(source.producer.instance_id, source.source_link_id, states.positions) ``` * Rust ```rust use peppygen::paired_topics::watch::joint_states; // `watch` is one_or_more: read the whole observed set, in plan order. The // set is never empty at that cardinality, so `first()` needs no unwrap. let sources = joint_states::sources(&node_runner)?; println!("lead arm: {}", sources.first().producer.instance_id); for source in &sources { println!("{} {}", source.producer.instance_id, source.source_link_id); } // One subscription covers every member; the source tag says which pairing // sent what, even when members share one instance. let mut subscription = joint_states::subscribe(&node_runner).await?; while let Some((source, states)) = subscription.next().await? { println!( "{} {} {:?}", source.producer.instance_id, source.source_link_id, states.positions ); } ``` An observed set is **seeded at spawn and live after**. The boot config the daemon hands the process carries the planned member set of every slot the deployment wrote, stamped with each source’s incarnation and liveness at that moment, so `sources()` answers the deployment’s membership from the node’s first instruction, setup included: a node can discover the robot’s shape before it starts serving. After that the set is live: the daemon replaces it whole whenever the plan’s observed pairings change or a member’s source starts, stops or restarts, so `sources()` can return a different set between reads. A member whose source is down (or has not started yet) stays in the set, at its position, so the slot’s shape does not flicker with the fleet’s health. A `zero_or_more` slot the deployment omitted carries no seed and reads the empty set until a copy joins and adds a member to it. The planner sizes every set a slot holds, at launch and at each join or removal, and the node re-checks its seed, and every set the daemon delivers, against the same rule, so each cardinality’s floor holds on every read: only `zero_or_one` and `zero_or_more` ever read empty, and an empty read there means the plan observes nothing through that slot. That is what lets the accessor be typed. ## Why topics only? [Section titled “Why topics only?”](#why-topics-only) Peppy has three communication patterns (topics, services, and actions), but a pairing may declare **topics only**. The reason is the distinction that shapes the rest of the dependency model: a topic dependency is passive, while service and action dependencies are caller-driven. | | Topics | Services | Actions | | --------------------- | ------------------------------------ | -------------------------------------------------- | ---------------------------------------------------- | | Pattern | Publish-subscribe | Request-response | Goal-feedback-result | | Runtime data flow | One-way: producer → consumer | Two-way: consumer calls provider, provider replies | Multi-step: consumer drives the provider’s lifecycle | | Consuming means | “I passively receive these messages” | “I actively call this provider” | “I actively orchestrate this provider” | | Allowed in a pairing? | Yes | No | No | A pairing’s two directions are two independent one-way streams: each side publishes whenever it has data, and neither ever *blocks on* the other at the protocol level. That is what makes the mutual relationship safe to hide from the static dependency graph. Services and actions are caller-driven: each side would actively invoke the other, forming a real request-response cycle at runtime, which is exactly the deadlock hazard the acyclic dependency model exists to prevent. The same rule applies to [contract implementation](/advanced_guides/contract_implementation/#caller-driven-cycles-are-rejected): mutual service or action relationships are rejected, however they are wired. If two paired nodes also need a bounded request-response exchange, keep the continuous streams in the pairing and model the bounded job as an [action](/advanced_guides/actions/) in one direction (the client depends on the server, no cycle). ## Pairing vs. contracts [Section titled “Pairing vs. contracts”](#pairing-vs-contracts) Pairing and [contract implementation](/advanced_guides/contract_implementation/) both decouple nodes from each other through a shared contract. They answer different questions: | | Pairing | Contract | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | Declaration model | The node enumerates what it uses in `interfaces.topics`; the document owns shape and QoS | The node enumerates what it uses in `interfaces`; the document owns shape, QoS and retention | | Coverage | Produced side (`emits`) exact per slot, consumed side free | Produced side (`implements`) exact per slot, consumed side free | | Cardinality | Declared per slot, in pairs: exactly one by default, at most one for `zero_or_one`, a live set for `one_or_more` / `zero_or_more`; each pair exclusive between its two instances | Declared per slot: exactly one by default, at most one for `zero_or_one`, an application-selected set for `one_or_more` / `zero_or_more` | | Directionality | Both directions in one contract (two roles) | One direction per contract | | Establishment | Declared once on either side (`--link arm@peer`), covering both endpoints, at instance start | Each consumer slot bound to its producer(s) (`--link slot@producer`), at instance start | | Peer identity | The slot *is* the identity; the runtime guarantees whose messages you get, and each message rides with the peer’s `PeerInfo` | Per-message `ProducerRef`; the consumer tells producers apart itself | | Lifecycle | Pair dissolves on death; survivor’s slot goes silent until re-paired | Producers come and go freely | | Natural fit | Control loops, teleoperation, any “these two specific instances belong together” relationship | Telemetry, monitoring, swappable sources (dedicated slots or one multi-cardinality slot) | Use a **pairing** when the relationship is exclusive and both directions belong to one conversation, like a controller and *its* arm. Use **contracts** when several loosely-coupled producers should feed a consumer, like every arm on the floor publishing diagnostics to one observer (one `one_or_more` slot bound to all arms, or one slot per arm when each has a distinct role). The two compose: `robot_arm` can be paired with its controller *and* implement a one-way `joint_state_source` contract so dashboards can watch it. ## Pairing vs. actions [Section titled “Pairing vs. actions”](#pairing-vs-actions) Pairing and [actions](/advanced_guides/actions/) can both look like “two nodes talking back and forth”, but they model different shapes of interaction. The distinction is **lifecycle**: does the exchange have a defined start and end, or does it run continuously for as long as the nodes are up? | | Pairing | Actions | | --------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | Lifecycle | Continuous; runs for as long as the pair is live | Bounded; each goal has an explicit start (goal accepted) and end (result delivered, cancelled, or errored) | | Initiator | Either side publishes whenever it has data | Client issues a goal; server responds | | Concurrency | Both streams flow in parallel, indefinitely | Concurrent goals allowed; the server’s goal handler sets the acceptance policy | | Per-exchange feedback | Implicit (each side publishes its own stream) | Explicit feedback channel during the goal | | Cancellation | Unpair (stop an endpoint); or just stop publishing | First-class cancel request mid-flight | | Natural fit | Inner control loops, continuous state mirroring | Discrete jobs with a clear “done” condition | A useful test: if you find yourself wanting to say *“the controller asks the arm to do X and waits until it’s done”*, that is an action. If you find yourself saying *“the controller streams setpoints at 100 Hz and the arm streams state back at 1 kHz”*, that is a pairing. Both shapes can coexist on the same pair of nodes. A `robot_arm` might expose a `calibrate` action (run once at startup, has a definite end) **and** exchange `joint_commands` / `joint_states` continuously with its paired controller. # Platform > Sign in to the Peppy platform with peppy platform login (OAuth device flow), which enrolls this machine in a project's cloud router, select the workspace and the project the commands act on, and check the link with peppy platform status `peppy platform` connects this machine to the Peppy platform. **Signing in** gives the CLI a session for the platform API. **Enrolling** joins this machine to a project’s cloud messaging router: the CLI mints a private key and a certificate signing request, the platform signs it, and the daemon dials the project’s router with that certificate from then on. `peppy platform login` does both, one after the other: it signs you in, then enrolls this machine in the project you select, unless you decline. `peppy platform enroll` enrolls a machine that already has a session. The session is yours; the enrollment is the machine’s. Logging out does not unenroll, and the daemon stays connected with no session for as long as its certificate is valid. The daemon needs the session for one thing: to renew that certificate. Peppy is a public OAuth client of the platform’s identity provider (Zitadel): the CLI obtains a bearer token through the browser and sends it to the backend, which validates it. The CLI never sees your Google/passkey credentials. Those stay in the browser. ## Commands [Section titled “Commands”](#commands) | Command | What it does | | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `peppy platform login [--api-url ] [--no-browser] [--workspace ] [--project ] [--no-enroll] [--yes]` | Signs in via the OAuth 2.0 Device Authorization Grant, caches the tokens, then enrolls this machine in the project you select. | | `peppy platform logout` | Revokes the session’s tokens at the identity provider and deletes them locally, with the selection. The enrollment stays. | | `peppy platform workspace show [--json]` | Shows the selected workspace. | | `peppy platform workspace list [--json]` | Lists the workspaces you belong to, the selected one marked. | | `peppy platform workspace use []` | Selects the workspace the commands act on. | | `peppy platform workspace clear` | Removes the selected workspace and its project. | | `peppy platform project show [--json]` | Shows the selected project. | | `peppy platform project list [--workspace ] [--json]` | Lists the projects of a workspace, the selected one marked. | | `peppy platform project use [] [--workspace ]` | Selects the project the commands act on. | | `peppy platform project clear` | Removes the selected project; its workspace stays selected. | | `peppy platform whoami [--json]` | Shows the signed-in identity, backend, and token validity. | | `peppy platform enroll [--workspace ] [--project ] [--replace] [--yes]` | Enrolls this machine as a peer of a project’s cloud router and restarts the daemon under the new identity. | | `peppy platform unenroll [--local-only] [--yes]` | Removes this machine’s peer from the platform, deletes the local enrollment, and restarts the daemon standalone. | | `peppy platform status [--json]` | Shows the enrollment, whether the daemon runs under it with a verified link, and what the platform reports about the router and this peer. | | `peppy platform peers [--workspace ] [--project ] [--json]` | Lists the peers of a project’s cloud router, this machine’s project by default. | | `peppy platform router restart [--workspace ] [--project ] [--yes]` | Restarts a project’s cloud router, which applies every pending change. | | `peppy platform router start [--workspace ] [--project ]` | Starts a stopped router. | `--api-url` overrides the backend on any command. `--yes` (`-y`) skips the confirmation prompt of the command: the daemon restart described under [Enrolling](#enrolling), or the router restart described under [The project router](#the-project-router). `login` and `enroll` need the peppy daemon to run on this machine: the machine enrolls under the name of its core node, and the daemon is what joins the project router. Start it with `peppy service serve`, or install it as a background service with `peppy service install`. ## Signing in [Section titled “Signing in”](#signing-in) ```sh peppy platform login ``` On a terminal this prints a verification URL and a user code, then opens your browser at that URL (with the code pre-filled). Approve the request in the browser and the CLI stores the tokens. Subsequent commands reuse them: you sign in once and stay signed in until the refresh token expires; expired access tokens are refreshed automatically. Then `login` enrolls this machine; see [Enrolling at sign-in](#enrolling-at-sign-in). Over SSH or anywhere without a browser, use `--no-browser`: the CLI prints the URL and code and waits for you to approve them on another device. ```sh peppy platform login --no-browser ``` ### How it works [Section titled “How it works”](#how-it-works) 1. The CLI fetches the public `GET {api_url}/cli/auth-config`, which returns the `issuer`, the `client_id`, and the exact `scopes` to request. 2. It runs OIDC discovery against the `issuer` (`{issuer}/.well-known/openid-configuration`) to find the device, token and revocation endpoints. 3. It starts the device flow, opens the browser, and polls until you approve. 4. It caches the tokens (and the `issuer`/`client_id`, so refresh works offline) under `~/.peppy/conf/credentials.json5`. Every later call to the platform API sends the cached access token as a bearer. When it is about to expire, or the backend answers `401`, the CLI exchanges the refresh token for a new one and persists the rotation. ### Enrolling at sign-in [Section titled “Enrolling at sign-in”](#enrolling-at-sign-in) After the sign-in, `login` enrolls this machine in a project, as [`enroll`](#enrolling) does: * `--workspace` and `--project` name the project, by id or by exact name. * With no flag, the only workspace, and the only project of the workspace, are selected with no question. Archived projects do not count. An account with one project is enrolled in it at once. * With more than one, a menu asks for the workspace, then for the project. Move with the arrow keys (or `k` and `j`) and select with Enter. The last entry of each menu, **Do not enroll this machine (sign in only)**, declines the enrollment, and so do Esc, `q` and Ctrl-C. ```plaintext Logged in as alice@example.com (dev) ✔ Workspace to enroll this machine in: Robotics lab (team) ? Project of Robotics lab to enroll this machine in ↑/↓ to move, enter to select, esc to cancel Lab ❯ Field Do not enroll this machine (sign in only) ``` The selected workspace and project become the [selection](#the-selected-workspace-and-project), and the enrollment follows: ```plaintext ✔ Project of Robotics lab to enroll this machine in: Field Enrolling cn-faithful-hare in project Field (ef2288ee-81d8-402e-922b-dbe4a4edbf25) in workspace Robotics lab. The platform signed the peer certificate. It expires on 2027-01-01, and the daemon renews it from 2026-12-02, while this machine has a session. Router link verified (tls/rtr-p.us-east-1.robocloud.dev.peppy.bot:7447). ``` `--no-enroll` signs in only. A machine that is enrolled already keeps its enrollment, and `login` prints the project it is enrolled in; `peppy platform enroll --replace` moves it. `login` succeeds when the machine is enrolled, or when you declined the enrollment. Every other way the enrollment does not happen fails the command, with a message that says the session is kept and the command to run next: * No daemon runs. `login` stops before the device flow starts, so you never approve a code for nothing. Start the daemon, or pass `--no-enroll`. * `--workspace` or `--project` on an enrolled machine. `login` stops before the device flow starts: it does not move an enrolled machine. * More than one choice and no terminal to show a menu on. `login` lists the choices and names `peppy platform enroll` with the flag to pass. * The platform refuses the enrollment. See [Enrolling](#enrolling). A stored selection of a different identity or backend is removed at sign-in: its ids mean nothing to the new account. ## The selected workspace and project [Section titled “The selected workspace and project”](#the-selected-workspace-and-project) The selection is the workspace, and the project of that workspace, that you selected. It is the default target of the platform commands, so you name a project one time and not on each command. It lives in `~/.peppy/conf/platform_selection.json5` and belongs to one backend and one signed-in identity. `login` selects the project it enrolls this machine in. ### Selecting [Section titled “Selecting”](#selecting) ```sh peppy platform workspace use # select from a menu peppy platform workspace use "Robotics lab" peppy platform project use # select from a menu peppy platform project use Field peppy platform project use Arm --workspace "Robotics lab" ``` Each `use` command picks one candidate: * The argument names it, by id or by exact name. * With no argument, the only candidate is selected with no question. Archived projects do not count. * With more than one, a menu asks on a terminal. It starts on the selected candidate, and Esc cancels it. * With more than one and no terminal, the command stops, lists the choices, and names the argument to pass. `project use` looks for the project in the workspace that `--workspace` names, else in the selected workspace, else in the only one; with none of them it asks for the workspace first. `workspace use` keeps the selected project when it selects the workspace of that project again. A different workspace starts with no project: run `project use` next. ### Showing and clearing [Section titled “Showing and clearing”](#showing-and-clearing) ```sh peppy platform workspace list peppy platform project list peppy platform workspace show peppy platform project show peppy platform project clear peppy platform workspace clear ``` `workspace list` lists your workspaces, and `project list` the projects of the selected workspace (or of `--workspace`); a `*` marks the selected ones. `project clear` removes the selected project and keeps its workspace; `workspace clear` removes both. ### Which project a command uses [Section titled “Which project a command uses”](#which-project-a-command-uses) | Command | Order | | ----------------------------------------- | ----------------------------------------------------------------------------------- | | `login` | The flags, then the only choice, then the menu. | | `enroll`, `project list` | The flags, then the selection, then the only choice. | | `peers`, `router restart`, `router start` | The flags, then the selected project, then the project this machine is enrolled in. | | `status`, `unenroll` | The project this machine is enrolled in. | ### Selection and enrollment [Section titled “Selection and enrollment”](#selection-and-enrollment) The selection is for the CLI only. A new selection does not move this machine to a different project and does not restart the daemon. When this machine is enrolled in a different project than the selected one, `project use`, `project show` and `status` say so. To move the machine, run `peppy platform enroll --replace`. ### A selection that is out of date [Section titled “A selection that is out of date”](#a-selection-that-is-out-of-date) The selection holds the ids and the names from the time you made it. A project can be archived, or you can lose access to it, after that. The platform then refuses the call, and the command adds that the selected project can be out of date. Run `peppy platform project use` to select again. ## Enrolling [Section titled “Enrolling”](#enrolling) ```sh peppy platform enroll ``` Enrollment joins this machine to one project’s cloud router: the [selected project](#the-selected-workspace-and-project), or the one that `--workspace` and `--project` name (an id or the exact name). `login` runs the same enrollment after a sign-in. The daemon must run. The peer takes the name of the daemon’s core node, so the platform and the other machines of the project know this machine by the name `peppy stack list` shows. Set that name with [`core_node_name`](/advanced_guides/daemon_config/#core_node_name-the-daemons-core-node-name) in `~/.peppy/conf/peppy_config.json5`, or with `peppy service serve --core-node-name `; when neither is set, the daemon derives a name that stays the same for the machine. With no daemon running, `enroll` stops before it calls the platform. What happens: 1. The CLI reads the core-node name of the running daemon, and resolves the workspace and project. 2. It mints a P-256 key pair and a certificate signing request whose only subject is the peer name. The private key never leaves the machine. 3. It posts the request to the project’s `router/peers` endpoint. The platform signs it and answers with the certificate, the project CA, the address of the project router, the routing namespace (the project id), and the zenoh identity the daemon’s router must run under. 4. It writes the enrollment bundle under `~/.peppy/conf/peer/`: `enrollment.json5` (the record), `peer.key` (the private key, owner-only), `peer.crt` (the signed certificate alone), `ca.crt` (the project CA), `chain.crt` (the chain above the certificate, for `openssl verify`), and `zenohd.platform.json5` (the peer config the platform rendered, kept for inspection). The daemon presents `peer.crt` and nothing above it, so the cloud router closes the link when that certificate expires. 5. Under `zenoh.managed`, it pokes the running daemon over its control socket. The daemon’s router identity and session namespace cannot change while live, so the daemon restarts its generation under the new identity and the CLI waits for it to come back. A second poke then verifies the mutual-TLS link to the cloud router with a real handshake; a link that does not validate is reported with its reason, and the enrollment is kept. The restart wipes the running node stack. When a daemon is running with user nodes on a terminal, the command asks for confirmation first; `--yes` skips the prompt, and a script (no TTY) is never prompted. Under `zenoh.external` the daemon is left alone and the command prints where the material is for the operator’s router to use. When the platform refuses the enrollment, the command prints the platform’s reason. Two refusals come with a remedy: * **The router admits no more peers.** A removed peer keeps its slot until the router restarts. When the platform says how many slots a restart frees, the command prints the `router restart` command for a number above zero, and tells you to remove a peer first for zero. When the platform does not say, the command lists the peers of the router: each one that reads `pending_restart` is a slot that a restart frees. * **The platform could not sign the certificate in time.** The command prints the delay the platform asks for. Run it again after that delay. ### The local listener [Section titled “The local listener”](#the-local-listener) The managed router listens on all interfaces in plain TCP, so that container nodes and the other machines of a LAN stack can reach it. On an enrolled machine this also means that a machine on the same network can open a session to this router and, through it, reach the project under this peer’s certificate. Where that is not acceptable, close the messaging port to other machines with the firewall of the host. ### The certificate [Section titled “The certificate”](#the-certificate) The peer certificate is valid for 90 days, and the daemon renews it. The renewal becomes due after two thirds of the lifetime of the certificate, which is day 60 of 90. The lifetime is the one the certificate in `peer.crt` states, so the schedule follows the certificate and not a clock of this machine. The daemon then asks the platform for a new certificate for the same key and writes it over `peer.crt`. The peer keeps its id, its zenoh identity and its slot on the router. The daemon does not restart, and the router does not restart. The running link keeps the certificate it opened with. The cloud router closes that link when that certificate expires, and the daemon’s router opens it again at once with the renewed certificate. The platform accepts a renewal from a signed-in person only, so the daemon uses the session of this machine: | Condition | Result | | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | A session is on the machine and the daemon runs | The daemon renews the certificate when the renewal is due. | | No session (you ran `logout`, or the refresh token expired) | The renewal fails. The daemon tries again each hour. Run `peppy platform login`. | | The session is one of a different backend than the enrollment | The renewal fails, and the daemon log names the backend to sign in to. | | The daemon does not run | No renewal. The daemon renews when it starts, also when the certificate expired. | | The platform asks for a delay | The daemon tries again after that delay. | | The platform cannot renew the peer (the peer was removed) | The daemon stops the renewal and the log names the remedy: `peppy platform enroll --replace`. | `peppy platform status` shows the expiry of the certificate, the date from which the daemon renews it, and what the daemon needs for the renewal and does not have: ```plaintext cert : expires on 2027-01-01 (in 80 days) renewal : automatic, from 2026-12-02 needs a session: run `peppy platform login` ``` To mint a new certificate by hand, run: ```sh peppy platform enroll --replace ``` This enrolls anew (a new key, a new peer and a new zenoh identity), restarts the daemon under it, and removes the previous peer from the platform. The previous peer keeps its slot until the router restarts; see [The project router](#the-project-router). ### Namespace [Section titled “Namespace”](#namespace) An enrolled daemon opens its own session, and every node it spawns, under the project’s routing namespace. Two machines enrolled in the same project share a namespace and address each other across the cloud router, which is the foundation for running one stack across both; see [Federation](/advanced_guides/federation/). An unenrolled daemon runs under `local`. The namespace is routing context only. It is not proof of project membership, a tenant-isolation boundary, or an authorization policy: isolation comes from each project having its own router and its own certificate authority. ### Checking the link [Section titled “Checking the link”](#checking-the-link) ```sh peppy platform status ``` The report has these parts: the enrollment on disk (project, peer, router, certificate expiry and renewal, files), the daemon (running, under the enrolled identity, and whether a fresh handshake to the cloud router validates), the selection, and, when you are signed in, the platform’s view (the router’s phase, the changes that wait for a restart, and this peer’s connection status). `peppy platform peers` lists every peer of the project as the platform sees them, marking this machine. A peer reads `connected`, `pending_restart`, or “not reported by the platform”. The last one is not a failure: the platform could not read the sessions of the router, so it has nothing to say about the peer. The daemon part of `status` answers from this machine: it makes a TLS handshake with the router and says if the link is good. ## Unenrolling [Section titled “Unenrolling”](#unenrolling) ```sh peppy platform unenroll ``` This removes the peer on the platform, deletes `~/.peppy/conf/peer/`, and pokes the daemon, which restarts standalone under `local`. Removing the peer needs a session; a machine that cannot sign in can delete only its local enrollment with `--local-only` and have the peer removed from the web app. The same restart prompt and `--yes` bypass apply as for `enroll`. The cloud router reads its trust anchors when it starts. It refuses the removed peer, and frees its slot, from its next restart. The platform does not restart a router by itself: the command prints each change that waits and the `router restart` command that applies it. ## The project router [Section titled “The project router”](#the-project-router) One project has one cloud router, so a project names its router. ```sh peppy platform router restart peppy platform router start ``` Which router a command acts on: | Flags | Selected project | This machine | Router | | -------------------------- | ---------------- | --------------- | ------------------------------------------------ | | `--project`, `--workspace` | set or not | enrolled or not | The project the flags name, by id or exact name. | | none | set | enrolled or not | The selected project. | | none | not set | enrolled | The project this machine is enrolled in. | | none | not set | not enrolled | None. The command stops and lists your projects. | The command prints the router it found, its phase, its peers and the changes that wait, before it acts. A restart applies every pending change: a removed peer, a new size. It drops each peer link for a moment, and the peers connect again on their own. The command asks for confirmation on a terminal; `--yes` skips the prompt. `start` starts a router that was stopped. `peppy platform status` shows the phase of the router and names this command when the router is stopped. A stopped router takes two commands to apply its changes. The platform refuses the restart of a stopped router, and a start alone does not apply a removal. So `router restart` on a stopped router stops with the two commands to run, in order: `router start`, then `router restart`. `unenroll` prints the same two commands when the router is stopped. Both commands need the permission to manage the infrastructure of the project. This is a different permission from the one an enrollment needs, so a person who can enroll a machine cannot always restart the router. ## Federation outside the Peppy platform [Section titled “Federation outside the Peppy platform”](#federation-outside-the-peppy-platform) You do not need the Peppy platform to run nodes across several machines. Point every machine at a Zenoh router you run yourself with [`zenoh.external`](/advanced_guides/daemon_config/#zenohexternal-use-an-operator-run-router) in `~/.peppy/conf/peppy_config.json5`: ```json5 zenoh: { external: { endpoint: "tcp/router.internal:7448", }, }, ``` `endpoint` is a dial address, so start the router first (for example `zenohd -l tcp/0.0.0.0:7448`) and make sure every machine, and every node environment on it, can reach that host and port. Peppy dials this router, adopts it, and never starts, restarts, reconfigures, or federates it: its lifecycle is yours. No sign-in, no backend, and no cloud router is involved. Every session carries a namespace under `zenoh.external` exactly as it does under `zenoh.managed`: `local` when the machine is not enrolled, the project namespace when it is. A shared router forwards traffic between namespaces without matching it, so an enrolled machine and an unenrolled one discover nothing from each other even though both are connected to your router. Keep every machine on the same namespace; without the platform that is `local`, so unenroll each machine (`peppy platform unenroll --local-only` when it has no session) and restart its daemon. External mode has no federation control socket, so `enroll` and `unenroll` never restart the daemon: a namespace change reaches sessions only when you restart it by hand (`peppy service stop`, then start it again). ## Backend [Section titled “Backend”](#backend) By default the CLI talks to the prod backend, `https://api.peppy.bot`. That URL is stored in the `resource_servers` block of `~/.peppy/conf/peppy_config.json5` (see [Daemon configuration](/advanced_guides/daemon_config/)), seeded on first run and editable in place. To point at a different backend without editing the file, use `--api-url` or `PEPPY_API_URL`. The URL is resolved in precedence order: `--api-url`, then `PEPPY_API_URL`, then `resource_servers.api`. In release builds, plain `http` is allowed only for local backends (loopback / `*.localhost`); anything else must be `https`. Debug builds accept remote plain `http` with a warning. ## Credential storage [Section titled “Credential storage”](#credential-storage) Tokens live at `~/.peppy/conf/credentials.json5`, written owner-only (`0600`). The selection lives beside it in `platform_selection.json5`; it holds ids and names, no secret. The enrollment lives under `~/.peppy/conf/peer/`, with the private key and the record owner-only. The root honors `PEPPY_HOME`. Tokens are never printed and `Authorization` headers are redacted in verbose output. ## Signing out [Section titled “Signing out”](#signing-out) ```sh peppy platform logout ``` This revokes the refresh token and then the access token at the identity provider, then deletes the local session. The backend checks every bearer with the identity provider, so a revoked token stops working at once. It revokes only the tokens this machine holds; a session on another device keeps working. Signing out removes the selection with the session. It leaves the enrollment in place: the daemon keeps its certificate and its link to the project router. The CLI’s platform calls need a new `peppy platform login`, and so does the renewal of the certificate: with no session the daemon cannot renew it, and the link stops when the certificate expires. On an enrolled machine, `logout` prints that expiry date. ## Environment variables [Section titled “Environment variables”](#environment-variables) | Variable | Purpose | | --------------- | --------------------------------------------------------------------------------------- | | `PEPPY_API_URL` | Override the backend base URL. | | `PEPPY_HOME` | Override the `~/.peppy` data root (also moves the credentials file and the enrollment). | | `NO_COLOR` | Disable colored output. | ## Running one stack across your project’s machines [Section titled “Running one stack across your project’s machines”](#running-one-stack-across-your-projects-machines) Once two machines are enrolled in the same project they share a namespace and can address each other through the project’s cloud router, which is the foundation for running a single Peppy stack across both. See [Federation](/advanced_guides/federation/). # Publishing nodes > Push the prebuilt image of a container node to an OCI registry, and pull it on other machines instead of building it A container node builds into one Apptainer image, a `.sif` file. Peppy pushes that image to an OCI registry, such as the GitHub Container Registry, Docker Hub, or a registry of your own, and each machine that reads the registry as an [`oci` repository](/advanced_guides/repositories/#oci-repositories) pulls the image instead of building the node. A pull takes the time of a download. A build of the same node can take many minutes, and much longer on a small machine such as a Raspberry Pi. Only [container nodes](/advanced_guides/containers/) are published. A process node (`build_cmd` / `run_cmd`) builds on each machine. ## Set up a repository [Section titled “Set up a repository”](#set-up-a-repository) 1. Pick an OCI repository that holds all your nodes, for example `oci://ghcr.io/acme/peppy-nodes`. A repository holds the nodes of every Peppy version: each artifact has a tag of its own (see [Registry layout](#registry-layout)). 2. On the machine that publishes, set [`publish_repository`](/advanced_guides/daemon_config/#publish_repository-where-nodes-are-published) in `~/.peppy/conf/peppy_config.json5`, and restart the daemon: ```json5 publish_repository: "oci://ghcr.io/acme/peppy-nodes", ``` 3. Log in to the registry on each machine that pushes, and on each machine that pulls from a private repository (see [Registry credentials](#registry-credentials)). 4. On each machine that pulls, add the repository with a lower `id` than the repositories that hold the sources of the same nodes, and refresh: ```sh peppy repo add oci://ghcr.io/acme/peppy-nodes --top peppy repo refresh ``` Artifacts are made for one Peppy version each, so only a release build of Peppy publishes and pulls. A build of Peppy without a release version refuses both, with an error that tells why. ## Registry credentials [Section titled “Registry credentials”](#registry-credentials) Peppy reads the credentials of a registry from the same auth file as Apptainer: `$APPTAINER_AUTH_FILE` when it is set, else `~/.apptainer/docker-config.json` (written by `apptainer registry login`) when it exists, else `~/.docker/config.json` (written by `docker login`). Log in with either tool: ```sh docker login ghcr.io apptainer registry login --username docker://ghcr.io ``` For a registry, the credential comes from, in this order: 1. The credential helper that `credHelpers` names for the registry. 2. The credential helper that `credsStore` names. 3. The entry of the registry under `auths`, with a user name and a password or token, or an `identitytoken`. A credential helper is the program `docker-credential-`, on the `PATH` of the daemon. Without a credential, Peppy asks the registry without one, which a public repository accepts for a pull. Peppy reads the file again before each pull and each push, so a login while the daemon runs applies to the next one. A push needs a credential that can write to the repository. On the GitHub Container Registry, that is a personal access token with the `write:packages` scope. ## Publish a node [Section titled “Publish a node”](#publish-a-node) ```sh peppy node publish : [--platforms ,...] [--idle-timeout ] [--max-timeout ] [--force] ``` The node must be in the node stack (`peppy node add :`). The daemon builds the node for the platform of this machine as `peppy node build` does, and pushes its `.sif` to the publish repository under the tag `...linux-`. For example, Peppy `v0.32.0` on an amd64 machine pushes `camera:v1` as `camera.v1.v0.32.0.linux-amd64`. | Flag | Effect | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--platforms` | Platforms to build and push beside the one of this machine, comma-separated: `linux/amd64`, `linux/arm64`. See [Build for another architecture](#build-for-another-architecture). | | `--idle-timeout` | Idle timeout in seconds of each platform build, as for `peppy node build`. | | `--max-timeout` | Maximum duration in seconds of each platform build. The platforms build one after another, so the publish takes at most this value times the number of platforms. | | `--force` | Cancel a build of the node that runs, and start the publish. | ### The checks [Section titled “The checks”](#the-checks) Before any build, the publish runs these checks in this order. The first check that fails ends the command with a message that names its fix, and nothing is built or pushed: 1. A publish repository is set: `publish_repository` in the configuration of the daemon. 2. This Peppy has a release version. 3. The node is a container node. A process node is refused with a link to the [container guide](/advanced_guides/containers/). 4. The node does not come from an `oci` repository: such a node has no sources on this machine. 5. Each value of `--platforms` is `linux/amd64` or `linux/arm64`. The command refuses another value before it reaches the daemon. 6. The registry accepts a push from this machine with its credentials. 7. This machine can build each other platform of `--platforms`: the QEMU system emulator and the UEFI firmware of the architecture are installed, this Peppy has Lima and the Apptainer of the architecture, the base image of the definition file has the platform, and for a Python node, this Peppy holds the peppylib native extension of the platform. A release of Peppy holds Lima, and the Apptainer and the peppylib native extension of every Linux platform. 8. For each platform whose tag the repository has already, the artifact under the tag was built from the same revision of the node. A tag is immutable, so Peppy never pushes over a tag. The revision of a node is its source digest: the sha256 of the staged tree of the node, without the vendored peppylib of a Python node. The same sources give the same digest on each machine and for each platform. The publish shows it, for example ``Source digest of `camera:v1`: sha256:9c1e...``. A platform whose tag holds the same revision is published already: the publish does not build or push it, and reports it as `already published`. A tag that holds another revision refuses the publish, with both digests: publish the change under another tag of the node (`v2`), or with another Peppy version. Each Peppy version has tags of its own, so the publish of a node with a new Peppy release pushes new artifacts. ### What the command prints [Section titled “What the command prints”](#what-the-command-prints) The publish shows the output of each build, and the progress of the hash and of the push of each image: a line for each percent of the image, and a line at least every 10 seconds while bytes move. It ends with one line for each platform: ```text linux/amd64: pushed camera.v1.v0.32.0.linux-amd64 (sha256:4b7f...) linux/arm64: already published as camera.v1.v0.32.0.linux-arm64 Published node camera:v1 ``` The command exits with an error when a platform of the request was not published, for example when the build of a platform fails, and names how many. ### Build for another architecture [Section titled “Build for another architecture”](#build-for-another-architecture) With `--platforms`, the daemon also builds the node for the other architecture: an amd64 machine builds `linux/arm64` with `--platforms linux/arm64`, and an arm64 machine builds `linux/amd64` with `--platforms linux/amd64`. A platform that is the one of this machine builds only once. The build of another architecture runs in a [Lima](https://lima-vm.io/) VM that emulates the architecture with QEMU, on Linux and on macOS: `peppy-aarch64` for `linux/arm64`, `peppy-x86_64` for `linux/amd64`. Peppy creates the VM at its first build and keeps it. Lima and the Apptainer of both architectures come with each Peppy release. The QEMU system emulator and the UEFI firmware of the architecture do not; install them: | Operating system | For `linux/arm64` on an amd64 machine | For `linux/amd64` on an arm64 machine | | ---------------- | -------------------------------------------------------- | ------------------------------------------------- | | macOS | `brew install qemu` | `brew install qemu` | | Debian, Ubuntu | `sudo apt install qemu-system-arm qemu-efi-aarch64` | `sudo apt install qemu-system-x86 ovmf` | | Fedora | `sudo dnf install qemu-system-aarch64-core edk2-aarch64` | `sudo dnf install qemu-system-x86-core edk2-ovmf` | | Arch Linux | `sudo pacman -S qemu-system-aarch64 edk2-aarch64` | `sudo pacman -S qemu-system-x86 edk2-ovmf` | An emulated build is much slower than a native one: each instruction of the build runs through the emulator. Each platform builds from its own copy of the staged tree, with the build caches of its architecture (see [Build caches inside container builds](/advanced_guides/containers/#build-caches-inside-container-builds)). The base image of the definition file must have the platform: the peppy base images (`peppybot/rust-cargo-base`, `peppybot/python-uv-base`) have both. ## Publish the nodes of a stack [Section titled “Publish the nodes of a stack”](#publish-the-nodes-of-a-stack) ```sh peppy stack build --publish [--platforms ,...] ``` With `--publish`, each machine of the stack builds its nodes as `peppy stack build` does, and pushes the `.sif` of each container node it builds to the `publish_repository` of the daemon that runs the command, with its own credentials. With `--platforms`, each machine also builds and pushes those platforms, as `peppy node publish` does. `--platforms` needs `--publish`. Before any build, the daemon that runs the command does [checks](#the-checks) 1, 2 and 6 for itself, and each other machine of the stack checks that the registry accepts a push from it when the launch reserves it. A machine that fails its check stops the build with an error that names the machine. The other checks do not stop the build: a platform that a check refuses is not built, and the other nodes and platforms go on. The command ends with a report of one line for each node, machine and platform: ```text Publish report: camera:v1@cn-atlas linux/amd64: pushed camera.v1.v0.32.0.linux-amd64 (sha256:4b7f...) camera:v1@cn-atlas linux/arm64: not published: the base image docker.io/acme/camera-base:1.2 of apptainer.def has no linux/arm64 planner:v2@cn-atlas: not published: process node arm_driver:v1@cn-pi: not published: comes from the oci repository oci://ghcr.io/acme/peppy-nodes ``` A platform of a container node that was not published fails the command, after the whole report, with exit code 4, the exit status of a failed goal. A process node and a node that comes from an `oci` repository show in the report and do not fail the command. ## Registry layout [Section titled “Registry layout”](#registry-layout) One OCI repository holds every published node. Each artifact is one node, Peppy version and platform: * The tag is `...linux-`, with `` `amd64` or `arm64`. A registry accepts at most 128 characters in a tag, so a node whose tag would be longer cannot be published. * The manifest is an OCI image manifest with the artifact type `application/vnd.peppy.node.v1` and the empty configuration `application/vnd.oci.empty.v1+json`. * The first layer is the `.sif` image, with the media type `application/vnd.sylabs.sif.layer.v1.sif`. * The second layer is the `peppy.json5` of the node, with the media type `application/vnd.peppy.node.manifest.v1+json5`. A refresh reads the node from it without the image. * The annotations of the manifest name the node (`bot.peppy.node.name`, `bot.peppy.node.tag`), the Peppy version (`bot.peppy.version`), the platform (`bot.peppy.platform`), and the source digest (`bot.peppy.source-digest`). A node that comes from a `git` repository also has the URL of the repository, the commit, and the path of the node in it (`bot.peppy.source.url`, `bot.peppy.source.commit`, `bot.peppy.source.path`). Peppy never deletes or overwrites a tag. To remove the artifacts of a Peppy version that no machine uses, delete their tags with the tools of the registry. # Repositories > Manage where Peppy discovers nodes, launchers, contracts, pairings, and MCP exposures Repositories tell Peppy where to look for nodes, launchers, contracts, pairings, and MCP exposures. Each repository states what it publishes through a committed [`peppy_repository.json5`](#the-repository-index) at its root; `peppy repo refresh` reads that index from every configured repository and caches the result. The index itself is written by [`peppy repo index`](#index-a-repository), which walks the tree and records: * **Nodes**, identified by content: every `.json5` file whose body declares `peppy_schema: "node/v1"` is treated as a node config, regardless of its filename, keyed by the `name:tag` declared in its manifest. * **Launchers**, identified by content: every `.json5` file whose body declares `peppy_schema: "launcher/v1"` is treated as a launcher, regardless of its filename. The launcher is keyed by the file stem (e.g. `openarm01_sim_teleop.json5` becomes the launcher named `openarm01_sim_teleop`). * **Contracts**, identified by content: every `.json5` file whose body declares `peppy_schema: "contract/v1"` is treated as a contract, regardless of its filename. A contract is a reusable declaration of topics, services, and actions, keyed by the `name:tag` declared in its manifest; nodes claim contracts by `name:tag` in `manifest.implements`. * **Pairings**, identified by content: every `.json5` file whose body declares `peppy_schema: "pairing/v1"` is treated as a pairing, regardless of its filename. A pairing is a two-role, topics-only contract that two node instances pair 1:1 over, keyed by the `name:tag` declared in its manifest; see [Pairing](/advanced_guides/pairing/). * **MCP exposures**, identified by content: every `.json5` file whose body declares `peppy_schema: "mcp_exposure/v1"` is treated as an MCP exposure, regardless of its filename, keyed by the `name:tag` declared in its manifest. An exposure selects members of contracts and gives them stable public names, MCP-facing prose, and operational policies; a launcher lists exposures by `name:tag` and the server built into `peppy` serves them, and [`peppy repo index --check --validate-mcp-exposures`](#check-the-exposures-a-repository-publishes) validates each one against the contracts and the daemon interfaces it references. See [MCP exposure](/advanced_guides/mcp/). Out of the box, five repositories are configured: * **`nodes-hub`** (`https://github.com/Peppy-bot/nodes-hub.git`, `ref: "@{peppy-release}"`, id `1000`): a curated collection of ready-to-use nodes. * **`launchers-hub`** (`https://github.com/Peppy-bot/launchers-hub.git`, `ref: "@{peppy-release}"`, id `1001`): community launch files that compose nodes from the hubs. * **`contracts-hub`** (`https://github.com/Peppy-bot/contracts-hub.git`, `ref: "@{peppy-release}"`, id `1002`): shared contract definitions that nodes claim by `name:tag` in `manifest.implements`. * **`mcp-hub`** (`https://github.com/Peppy-bot/mcp-hub.git`, `ref: "@{peppy-release}"`, id `1003`): [MCP exposure](/advanced_guides/mcp/) documents that a launcher lists by `name:tag` and the server built into `peppy` serves. * **`pairings-hub`** (`https://github.com/Peppy-bot/pairings-hub.git`, `ref: "@{peppy-release}"`, id `1004`): shared pairing definitions that nodes play roles in by `name:tag` in `depends_on.pairings`; see [Pairing](/advanced_guides/pairing/). A release build of Peppy reads, in each default hub, the tag `peppy-release/`: Peppy `v0.32.0` reads `peppy-release/v0.32.0`. The Peppy release tests these hub commits together with that version before it creates the tags, and nobody can move or delete the tags. So the content of the default hubs changes only when you install another Peppy version. A build of Peppy without a release version reads the hubs’ `main` branch. Peppy writes these entries when it creates `repositories.json5`. Neither the start of the daemon nor `peppy repo init` changes an entry the file already holds, so an entry of a default hub with another `ref` reads that ref. To read the hub content released with your Peppy version, set its `ref` to `"@{peppy-release}"`, or delete `~/.peppy/conf/repositories.json5` and run [`peppy repo init`](#initialize-the-defaults) to write the default entries again, then `peppy repo refresh`. The `id` is the priority key when several repositories provide the same `name:tag`, so the defaults resolve in this order. Add your own local directory with `peppy repo add /path/to/my/nodes`, then `peppy repo index /path/to/my/nodes` and `peppy repo refresh`, so Peppy can discover nodes you create locally. A repository publishes through its committed index, so all three steps are needed before a local node resolves. ## Configuration files [Section titled “Configuration files”](#configuration-files) Repository configuration lives in `~/.peppy/conf/`, and the indexes built by `peppy repo refresh` are written to `~/.peppy/cache/`: | File | Purpose | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `conf/repositories.json5` | Repositories to scan | | `conf/excluded_repositories.json5` | Repositories (or subdirectories) to skip | | `cache/nodes.json5` | Index of nodes discovered across repositories, with the contract and pairing links each node’s manifest declares and the description of each node | | `cache/launchers.json5` | Index of launch files discovered across repositories, with the description of each launcher | | `cache/contracts.json5` | Index of contract definitions discovered across repositories, with the descriptions of each contract, of its members and of their fields | | `cache/pairings.json5` | Index of pairing definitions discovered across repositories, with the descriptions of each pairing, of its topics and of their fields | | `cache/mcp_exposures.json5` | Index of MCP exposure documents discovered across repositories | | `cache/repo_status.json5` | Per-repository read status: when each one was last read successfully, and how its most recent read failed | The two `conf/` files are JSON5 arrays. Each entry has an `id` (auto-assigned if missing), a `type`, and source-specific fields: repositories.json5 ```json5 [ { id: 1, type: "fs", path: "/home/user" }, { id: 2, type: "git", url: "https://github.com/Peppy-bot/nodes-hub.git", ref: "@{peppy-release}" }, { id: 3, type: "git", url: "https://github.com/org/robot-nodes.git", ref: "feature/gripper" }, { id: 4, type: "oci", url: "oci://ghcr.io/acme/peppy-nodes" }, ] ``` ### Source types [Section titled “Source types”](#source-types) | Type | Fields | Description | | ----- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fs` | `path` | A local directory, read through its committed [`peppy_repository.json5`](#the-repository-index). | | `git` | `url`, `ref` (optional) | A git repository. Peppy fetches the one commit that `ref` names, without its history, and reads the same committed index. Use `ref` to pin a branch, tag, or commit, or write `@{peppy-release}` to read the hub content released with your Peppy version (see below). The `url` is HTTPS or an SSH URL (see [Private git repositories over SSH](#private-git-repositories-over-ssh)). | | `oci` | `url` | An OCI repository of a container registry, `oci:///`, that holds the prebuilt `.sif` images of container nodes. Peppy pulls the image of a node instead of building it. It holds nodes only, and has no `ref` and no index (see [OCI repositories](#oci-repositories)). | These are the only three source types. An entry with any other `type` fails its read as `unreachable` with an “unrecognized repository entry” detail. `ref: "@{peppy-release}"` always resolves to a tag, never to a branch. In a release build of Peppy it reads the tag `peppy-release/` of that build; in a build without a release version it reads `main`. Only the Peppy-bot hubs carry `peppy-release/` tags, so for a repository of another organization, `ref` names a branch, a tag, or a commit. Git refuses every branch or tag name that contains `@{`, so no ref of a repository can clash with `@{peppy-release}`; any other `ref` value that contains `@{` (such as `main@{1}` or `@{upstream}`) is refused, and the entry fails its read as `unreachable`. Of the other `ref` values, 40 hexadecimal characters name a commit, and any other value is looked up among the refs of the repository as written (such as `refs/tags/v1`), then as a branch, then as a tag, so `ref: "peppy-release/v0.31.2"` pins the hubs of that one release. Without `ref`, Peppy reads the commit of the repository’s `HEAD`. An `fs` repository is a path only this machine can read, so a deployment resolved from one must keep all of its instances on this daemon in a federated launch; serve the nodes from a `git` repository to place them on other machines (see [Federation limits](/advanced_guides/federation/#limits)). ### Private git repositories over SSH [Section titled “Private git repositories over SSH”](#private-git-repositories-over-ssh) A `git` repository’s `url` may be HTTPS or SSH, so a private repository is reachable without embedding a credential in `repositories.json5`. Give it either the scp-style `git@host:owner/repo.git` or an `ssh://` URL, and Peppy authenticates the way `ssh` itself does for that host. It reads what `~/.ssh/config` selects for the URL’s host, user and port through `ssh -G`, so every `Host` and `Match` block, `Include` file and system default applies exactly as it does to `ssh`: * The keys of the agent the host’s `IdentityAgent` names are offered first, as the URL’s user (`git` when the URL names none). Without that directive the agent is the one `SSH_AUTH_SOCK` names; `IdentityAgent none` offers no agent. * The host’s `IdentityFile` list follows, in `ssh`’s order, each path offered when it exists as a file. That list is `ssh`’s own defaults under `~/.ssh` unless the configuration names others. * The host key is checked against `~/.ssh/known_hosts` before any key is offered, so a host missing from that file, or one whose key has changed, is refused. A refusal names everything that was offered: the agent socket, the identity files that exist, and the configured paths that do not, so a typo in `~/.ssh/config` is visible in the message. Without `ssh` on the PATH, Peppy offers the agent `SSH_AUTH_SOCK` names and the default identity files `id_ed25519`, `id_ecdsa` and `id_rsa` under `~/.ssh`. The daemon binds one agent for its lifetime. When it starts, it points `SSH_AUTH_SOCK` at the agent `~/.ssh/config` selects for a host with no host-specific configuration (a `Host *` block, the way 1Password, Secretive and gpg-agent are wired in), and logs which one. That is what makes those agents reachable from a daemon installed with `peppy service install`, which starts with a clean environment, and from a shell whose `SSH_AUTH_SOCK` names another agent. A host whose own block selects a different agent is refused by name; give every host the same `IdentityAgent` and restart the daemon. Load a key the remote accepts into the agent `ssh` uses, or keep an unencrypted identity file at one of the configured paths, and both [`peppy repo add`](#add-a-repository) and `peppy node add` reach the repository over SSH. ### OCI repositories [Section titled “OCI repositories”](#oci-repositories) An `oci` repository holds container nodes as prebuilt Apptainer images: one artifact for each node, Peppy version and platform, which [`peppy node publish`](/advanced_guides/publishing/) pushes. A machine that reads the repository pulls the image of a node in the time of a download, instead of building it. Add one with its URL: ```sh peppy repo add oci://ghcr.io/acme/peppy-nodes --top peppy repo refresh ``` The URL has the form `oci:///`. The host is lowercase and can have a port. Each component of the path holds lowercase letters and digits, joined by `.`, `_`, `__` or `-`. The URL holds no credentials, query, or fragment: Peppy reads the credentials of the registry from the auth file of Apptainer (see [Registry credentials](/advanced_guides/publishing/#registry-credentials)), and a public repository needs none. Peppy reaches a registry on this machine (`localhost`, a `127.0.0.0/8` address, or `::1`) over plain HTTP, and every other registry over HTTPS. An `oci` entry has no `ref`, so `--ref` is refused for it. The artifacts of a repository are made for one Peppy version each, so only a release build of Peppy reads an `oci` repository. A build of Peppy without a release version refuses `peppy repo add` of an `oci` URL, and a refresh reports an `oci` entry of `repositories.json5` as `unreachable`. A refresh lists the tags of the repository and reads the artifacts of the version of this Peppy only: Peppy `v0.32.0` reads the tags that end with `.v0.32.0.linux-amd64` and `.v0.32.0.linux-arm64`. It records a node when the repository holds an artifact of the node for the platform of this machine: `linux/amd64` or `linux/arm64`, after the architecture of the machine, also on macOS. A node that the repository holds no artifact of for this platform is not recorded, and the refresh shows a line for it, so a repository with a higher `id` that holds the sources of the node supplies it. The refresh also leaves out a node, with a line that tells why, when one of its tags holds no node artifact, when the registry does not give the manifest of one of its tags, when two of its tags claim the same platform, or when its platforms were built from different revisions of the node. Without that last rule, a stack across an amd64 and an arm64 machine could run two revisions of one node. A registry that cannot be reached, or that does not take the credential of this machine, fails the read of the whole repository as `unreachable`. The refresh keeps the `peppy.json5` of each node it records in `~/.peppy/cache/oci_node_manifests/`, under its digest, so `peppy repo search`, `peppy repo show` and `peppy stack resolve` read it without the registry. A later refresh reads a `peppy.json5` that this directory holds from it, not from the registry. `peppy node add :` of a node that an `oci` repository supplies pulls the `.sif` of the platform of this machine by its digest, checks the bytes against the digest while they arrive, and adds the node ready to start: there is nothing to stage, generate or build. A pull that fails fails the add, with the repository, the tag, the digest and the cause; Peppy does not build the node from sources instead. A machine of a federated launch pulls the artifact of its own platform. A node of an `oci` repository has no sources on this machine, so: * `peppy node build` and `peppy node rebuild` refuse it: `` `:` comes from the oci repository `` and has no sources. To build it, add a git or fs repository that holds it, with a lower id. `` * `peppy node publish` refuses it, and `peppy stack build --publish` shows it in its report as not published. * A repository with a lower `id` that holds the same `name:tag` supplies the node, as for every other source type. To pull a node that a `git` repository also holds, give the `oci` repository the lower `id` (`--top`). To build it from its sources again, give the `git` or `fs` repository the lower `id`. ## Commands [Section titled “Commands”](#commands) ### Initialize the defaults [Section titled “Initialize the defaults”](#initialize-the-defaults) ```sh peppy repo init ``` Syncs `repositories.json5` with the bundled default template. If the file does not yet exist it is created verbatim; otherwise any missing default entries are appended without touching your existing entries. Use this after upgrading Peppy to pick up new defaults without having to restart the daemon. The command operates directly on the local config file; no daemon connection is required. ### List repositories [Section titled “List repositories”](#list-repositories) ```sh peppy repo list ``` Shows the indexed nodes grouped by the repository that provides them. Each group is headed by the repository’s display label (path for `fs`, `url (ref: r)` for `git`) followed by the node count and source kind, then lists each node’s name, tag, and path. A `git` repository on `@{peppy-release}` also names the ref this Peppy reads for it, as in `https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0)`. The list reflects the index, not the filesystem, so it shows what will actually resolve at launch. A node added to a local repository does not appear until you run `peppy repo index ` and then `peppy repo refresh`, which is also when it becomes launchable. One situation is flagged: `(shadowed by )` means another repository with a lower `id` provides the same `name:tag`. This resolves deterministically to the named repository; the shadowed entry is recorded and inspectable but not used. A supported arrangement, not a problem. A repository whose last refresh failed is marked `[retained, last read ]`, with the reason on the following line. Its entries are the ones it last published successfully, so anything referencing them keeps working; the date tells you how old they are. ### Search the repositories [Section titled “Search the repositories”](#search-the-repositories) ```sh peppy repo search [--text] [:][@] ``` Finds any indexed item: nodes, launchers, contracts, pairings, and MCP exposures. Each query part is an unanchored regular expression, matched the way `apt search` matches its patterns: `camera` finds `rgb_camera`, `^rgb_camera$` only the exact name, `cam(era)?:v[12]` any combination of the alternatives. Matching is case-sensitive; prepend `(?i)` to a part for case-insensitive matching. A missing tag part matches every tag. Launchers carry no tag, so a bare name finds them, while a tag pattern only matches them when it matches the empty string (`demo:.*` does, `demo:v1` does not). The `:` splits the query, so a POSIX class like `[[:digit:]]` cannot be written; use `[0-9]`. `@` keeps only the copies carrying exactly those bytes, wherever they are published, so `.*@` finds a document knowing only its fingerprint. Every matching identity is listed with the summary of its description and where it is stored, names the pattern matches outright first, then by name: ```text camera 3 items match `camera` ┌──────────────┬─────────────────────────┬────────────────────────────────────────────────────────────────────────────────┬─────────────────────────────────────────────────────────────────────────────────────────────────────┬──────────────────────────────────────┬──────────┐ │ KIND │ ITEM │ SUMMARY │ REPOSITORY │ PATH │ SHA256 │ ├──────────────┼─────────────────────────┼────────────────────────────────────────────────────────────────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────┼──────────────────────────────────────┼──────────┤ │ mcp exposure │ camera_and_recording:v1 │ │ https://github.com/Peppy-bot/mcp-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0) │ recording/camera_and_recording.json5 │ 583f9ac9 │ │ contract │ rgb_camera:v1 │ A color camera: its frames, the settings of its stream and its brightness. │ https://github.com/Peppy-bot/contracts-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0) │ cameras/rgb_camera.json5 │ 4594da02 │ │ node │ sim_rgb_camera:v1 │ A color camera in the simulation. It needs a machine that runs the simulation. │ https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0) │ sim_rgb_camera/peppy.json5 │ 9f2c1a77 │ └──────────────┴─────────────────────────┴────────────────────────────────────────────────────────────────────────────────┴─────────────────────────────────────────────────────────────────────────────────────────────────────┴──────────────────────────────────────┴──────────┘ ``` The `SUMMARY` column shows the first paragraph of the [description](/reference/concepts/#descriptions) of each document. An MCP exposure has no description, so its cell is empty. The `SHA256` column shows the first eight characters of each document’s fingerprint, as the `PIN` cells of [`peppy repo show`](#show-what-a-query-matches) do. A `@` query takes the complete 64-character fingerprint; `--json` carries fingerprints whole. With `--text`, the name part of the query also matches the descriptions, with no regard to case: the paragraphs of each contract, pairing, node and launcher, and, for a contract or a pairing, the description of each member or topic and of each field. The hits by name come first, then the hits by description. The tag part and `@` still filter the matches, and an MCP exposure matches by its name only: ```sh peppy repo search --text gripper # `gripper` in a name, then in a description peppy repo search --text GPU # the nodes and launchers whose descriptions name a GPU ``` The search reads this machine’s caches, so it reflects the last `peppy repo refresh` and needs no daemon (`--core-node` has no effect). A query nothing matches is an answer, not an error: the command says so and, when repositories are excluded, that one of them may have provided the item. `--json` prints the same answer as one JSON document with `query` (the parsed `raw`, `name`, `tag`, and `sha256` parts, and `text`, `true` with `--text`), `matches` (each with its `kind`, `name`, `tag`, `by_name`, `exact`, `summary`, and `published` document), and `excluded`. `by_name` is `false` for a match that a description alone found, and `summary` is `null` for an MCP exposure. ### Show what a query matches [Section titled “Show what a query matches”](#show-what-a-query-matches) ```sh peppy repo show [:][@] ``` Takes the same query as [`peppy repo search`](#search-the-repositories) and prints the full report of every identity it matches, in the search’s order, the way `apt show` prints one record per named package: `peppy repo show '^rgb_camera$:^v1$'` reports the one contract (the anchors keep names like `sim_rgb_camera` out, since each unanchored part matches anywhere in the name or tag), and `peppy repo show 'rgb_camera:v[12]'` answers who still uses each version in one pass. A report’s first lines name each document of the identity with its kind, repository, path, and sha256, each line followed by the full [description](/reference/concepts/#descriptions) of the document: each paragraph, indented, then, for a contract, `Members:`, and for a pairing, `Topics:`, with one line per member, ` : `. Contracts and pairings are separate namespaces, so an identity published as both is reported as both, and one report covers them. For a contract or pairing, one section per way a node uses it follows: implementing it (`manifest.implements`), consuming it (`depends_on.contracts`), playing a role in it (`depends_on.pairings`), or observing one of its roles (`depends_on.pairing_observers`). Sections are grouped by repository like `peppy repo list`, each group a table with one row per slot: `NODE` and `TAG`, `ROLE` (pairing sections only), `SLOT` (the `link_id`, with its cardinality), `PIN`, and `PATH` (the manifest path). A launcher or an MCP exposure has no usage sections: the published line and the description of a launcher are the whole answer, and an MCP exposure has its published line only. A table wider than the terminal gives up width from its widest columns first, never below a header’s width, and wraps over-long cells onto continuation lines inside the outline; piped output is never wrapped. ```text ^rgb_camera$:^v1$ contract rgb_camera:v1 published by https://github.com/Peppy-bot/contracts-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0) at cameras/rgb_camera.json5 (sha256 a4e66999c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8) A color camera: its frames, the settings of its stream and its brightness. Members: topic video_stream: Each frame of the camera, with its size and its encoding. service video_stream_info: The size, the frame rate and the encoding of the stream. service set_brightness: Set the brightness of the camera, and give the brightness that it applied. Implemented by 2 indexed nodes https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0): ┌──────────────────┬─────┬────────┬────────────────────────┬──────────────────────────────┐ │ NODE │ TAG │ SLOT │ PIN │ PATH │ ├──────────────────┼─────┼────────┼────────────────────────┼──────────────────────────────┤ │ uvc_camera_linux │ v1 │ camera │ pin a4e66999 (current) │ uvc_camera/linux/peppy.json5 │ │ realsense_d4xx │ v1 │ camera │ unpinned │ realsense_d4xx/peppy.json5 │ └──────────────────┴─────┴────────┴────────────────────────┴──────────────────────────────┘ Consumed by 1 indexed node https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0): ┌──────────────────┬─────┬──────────────────────┬──────────┬────────────────────────────────────────────┐ │ NODE │ TAG │ SLOT │ PIN │ PATH │ ├──────────────────┼─────┼──────────────────────┼──────────┼────────────────────────────────────────────┤ │ episode_recorder │ v1 │ camera (one_or_more) │ unpinned │ example_robot/episode_recorder/peppy.json5 │ └──────────────────┴─────┴──────────────────────┴──────────┴────────────────────────────────────────────┘ ``` For a **node**, the report reads the same cache the other way: one section per pairing slot the node declares (`depends_on.pairings`), in manifest order, listing the nodes whose own slot plays the pairing’s other role. The title names the slot, the pairing it resolves through, the role this node plays, and its cardinality; the rows are the peers’ own slots, in the columns a pairing’s own report uses, and the count is of nodes, so a node offering two complementary slots takes two rows and counts once. Being listed here is a match of pairing and role, which is what pairing requires and what the caches record; whether a stack of the two is one worth running is a launcher’s business (see [Launch files](/guides/launch_files/)). ```text ^sim_rgb_camera$:^v1$ node sim_rgb_camera:v1 published by https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0) at sim_rgb_camera/peppy.json5 (sha256 34d40c0140066c9055879c2d4bd022a7f665752ab834247a9ff69e4fd68a1899) A color camera in the simulation. It needs a machine that runs the simulation. Slot engine (sim_rgb_camera_link:v1 as viewer, one) can pair with 2 indexed nodes https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0): ┌────────────┬─────┬────────┬────────────────────────────┬──────────┬────────────────────────┐ │ NODE │ TAG │ ROLE │ SLOT │ PIN │ PATH │ ├────────────┼─────┼────────┼────────────────────────────┼──────────┼────────────────────────┤ │ sim_isaac │ v1 │ camera │ rgb_cameras (zero_or_more) │ unpinned │ sim_isaac/peppy.json5 │ │ sim_mujoco │ v1 │ camera │ rgb_cameras (zero_or_more) │ unpinned │ sim_mujoco/peppy.json5 │ └────────────┴─────┴────────┴────────────────────────────┴──────────┴────────────────────────┘ ``` A slot nothing complements keeps its line and says so, which on a slot whose cardinality has a floor of one means no indexed node completes a launch of this one: ```text Slot engine (sim_rgb_camera_link:v1 as viewer, one): no indexed node plays the other role ``` A node’s other links have no such section: a contract slot’s candidates are that contract’s own implementers, one `peppy repo show` away, and an observer slot watches a pair two other nodes form rather than filling a role itself. A node that declares no pairing slot has no section at all, so its published line is the whole answer. The `PIN` column says what a sync does with the claim’s `sha256`: | `PIN` value | Meaning | | ----------------------------------------- | -------------------------------------------------------------------------------------- | | `unpinned` | No pin: the claim resolves to the published document. | | `pin (current)` | The pin equals the published document’s fingerprint. | | `pin (cached copy in )` | Another repository’s cached copy carries that fingerprint; a sync resolves through it. | | `pin (not in cache)` | No cached copy carries the pin; a sync fails. | | `unusable pin ()` | The pin is not a fingerprint; a sync refuses the manifest. | `(shadowed by )` means what it means in `peppy repo list`: a lower-`id` repository provides the same `name:tag`, so a launch resolves to that node, which may not make this claim at all. The show reads the same caches as the search and needs no daemon. A query nothing matches is an error, since the command was asked for a report it cannot print, and so is an identity one repository publishes twice: its report has no answer a launch would accept. `--json` prints one JSON document with `query`, `matches`, and `excluded` as the search prints them, with `descriptions` on each match, plus `reports`. `descriptions` is `null` for an MCP exposure, else `{ description, members }`: `description` is the list of the paragraphs, and `members` lists each member of a contract or topic of a pairing as `{ kind, name, description, fields }`, with `fields` each `{ side, path, description }` of a field that has a `$description`. A list with no entry is left out. `reports` holds one usage report per matched identity in match order, each with its `implementers`, `consumers`, `participants`, `observers`, and `pairing_slots` (one entry per pairing slot a matched node declares, with its `link_id`, `pairing`, `role`, `cardinality`, and the `peers` that could fill it). ### Refresh the index [Section titled “Refresh the index”](#refresh-the-index) ```sh peppy repo refresh [--strict] ``` Re-scans all configured repositories and rebuilds the node, launcher, contract, pairing, and MCP exposure indexes. `peppy repo update` is accepted as an alias. During refresh, Peppy: * Reads `repositories.json5` (creates it with defaults on first run). * Resolves `ref: "@{peppy-release}"` to the ref this Peppy reads: the tag `peppy-release/` in a release build, `main` in any other build. * Skips any repository or path listed in `excluded_repositories.json5`. * Reads local directories in place. Of each git repository, it fetches only the commit that its `ref` names, at depth 1: no history, no other branch, and no other tag. * Of each `oci` repository, lists the tags and reads the manifests of the artifacts of this Peppy version, and records the container nodes that have an artifact for the platform of this machine (see [OCI repositories](#oci-repositories)). * Reads up to 8 repositories at once, so a refresh takes about as long as its slowest repository. * Records what each `fs` and `git` repository’s committed [`peppy_repository.json5`](#the-repository-index) publishes: nodes and their tags, together with the contract and pairing links each node’s manifest declares, launchers (one per name, no tag), and contracts, pairings, and MCP exposures (keyed by their manifest `name:tag`). A repository without that file fails its read with instructions to run `peppy repo index`. * Keeps the [descriptions](/reference/concepts/#descriptions) of each node, launcher, contract and pairing in the caches, so `peppy repo search` and `peppy repo show` read no document. * Reports each excluded repository and the progress of each read in real time, and each discovered node, launcher, contract, pairing, and MCP exposure when every repository is read, in priority order. * Caches results in `~/.peppy/cache/nodes.json5`, `~/.peppy/cache/launchers.json5`, `~/.peppy/cache/contracts.json5`, `~/.peppy/cache/pairings.json5`, and `~/.peppy/cache/mcp_exposures.json5`, and records per-repository read status in `~/.peppy/cache/repo_status.json5`. On completion it prints a summary, for example `Repository refresh complete. 12 node(s), 3 launcher(s), 5 contract(s), 2 pairing(s), 1 MCP exposure(s) found.` A command that reads a cache that does not parse, for example a cache whose entries have no descriptions, refuses it and tells you to run `peppy repo update`, which writes the caches again. When you install another Peppy version, the daemon reads the repositories on `@{peppy-release}` again at its next start, at the tags of the new version, before it answers any request. That start takes as long as the fetch of those repositories. If a repository cannot be read then, it keeps the entries it holds and the daemon tries again at its next start. When **multiple repositories** provide the same `name:tag` pair, the repository with the lower `id` takes priority. The shadowed entry is still recorded and shown in `repo list` but does not override the primary source. When **one repository** provides the same `name:tag` twice, there is no winner to pick. That repository fails its refresh; see [When a repository fails](#when-a-repository-fails) below. ### When a repository fails [Section titled “When a repository fails”](#when-a-repository-fails) A failure is scoped to the repository that caused it. The repositories that read cleanly are indexed as usual, so a problem in one hub never blocks picking up changes from the others. A repository that fails **keeps the entries it last published**. Nothing disappears out from under a launcher that references it, and the machine keeps launching everything it could launch before. `peppy repo list` marks those entries as retained, with the date they were read. The run itself still succeeds. A repository that could not be read is a state to report, not a reason to stop: everything the run could do, it did. It names every repository that failed in one message, so you fix everything after one run rather than running repeatedly, and ends by pointing you back at the retry: ```text Repository refresh complete. 26 node(s), 4 launcher(s), 8 contract(s), 2 pairing(s), 0 MCP exposure(s) found. 2 of the configured repositories could not be updated. Every other repository was updated normally. - repository 1000 (https://github.com/Peppy-bot/nodes-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0)) contradicts itself [conflict]: duplicate key `v1`: already declared at uvc_camera_video_reconstruction/python/peppy.json5, declared again at uvc_camera_video_reconstruction/rust/peppy.json5. Kept 18 entries from its last successful read - repository 1002 (https://github.com/Peppy-bot/contracts-hub.git (ref: @{peppy-release}, reads peppy-release/v0.32.0)) could not be read [unreachable]: failed to connect to github.com. Kept 8 entries from its last successful read Run `peppy repo refresh` again to pick those repositories up. ``` This is also what lets the [installer](/guides/installation/) finish on a machine whose network is flaky. Its last step is a refresh, and a hub that happens to be unreachable does not end an install that otherwise worked: the install completes, tells you which repositories it could not read, and leaves you the same retry. With `--strict`, the same report fails the command: `peppy repo refresh --strict` prints it and exits with an error. The repositories that read cleanly are still indexed and the failed ones still keep their entries; only the exit status differs. Use it where a repository that cannot be read must stop what comes next, as in CI, where a later step would otherwise fail with an error that does not name the repository. Only a refresh that could not run at all fails: a `repositories.json5` that does not parse or that lists the same `id` twice, or caches that cannot be written. Nothing was read in that case, so there is nothing to contain. The command then prints the failure kind and the reason, `Repository refresh failed (attempt_failed): …`, and exits with code 4, the exit status of a failed goal. A Ctrl+C sends the daemon a cancel of the refresh. The read of each repository that runs ends first, no other read starts, and the refresh publishes nothing, as a refresh that fails: the caches keep what they held. The command prints `Repository refresh was cancelled by its caller.` and exits with code 5, the exit status of a cancelled goal. A second Ctrl+C stops the wait for the end once the cancel reached the daemon and exits with code 130, and a third one ends the command at once. Two read failures are reported, and the distinction matters because they send you to different places: | Read failure | Meaning | Typical cause | | ------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `unreachable` | The repository could not be read at all. | Network outage, a bad git ref, a `peppy-release/` tag that the hub does not carry, a local path that is not mounted, a root with no committed `peppy_repository.json5`, an unrecognized entry in `repositories.json5`, a registry that refuses the credentials of this machine, an `oci` repository read by a build of Peppy without a release version. | | `conflict` | The repository was read fine, but its committed index contradicts itself or the tree. | An index that fails to parse (a duplicate key, an unknown field, an illegal path), or a listed path that is missing, is of another kind, or declares another identity. | An `unreachable` repository is an outage, so the fix is usually to wait or fix connectivity. A `conflict` is a content bug in the repository, and the message names the exact files, so the fix is a change to that repository. The report is ordered by repository `id` and never inherits the filesystem’s directory order, so two machines seeing the same problem report it identically. Caution A machine that has **never** read a repository successfully has nothing to fall back to. Containment gets it every other repository, but a broken repository gives it nothing, and excluding a repository is the only local lever: it removes every identity that repository provides, not just the offending one. The real fix for a broken shared repository is to stop it being published broken. ### Add a repository [Section titled “Add a repository”](#add-a-repository) ```sh peppy repo add [--ref ] [--top | --id ] ``` Adds a new repository to `repositories.json5`. The source format is auto-detected: ```sh # Local directory peppy repo add /path/to/my/nodes # Git repository peppy repo add https://github.com/org/repo.git # Private git repository over SSH (see "Private git repositories over SSH" above) peppy repo add git@github.com:org/private-repo.git # Git repository pinned to a branch or tag peppy repo add https://github.com/org/repo.git --ref v2.0 # OCI repository of prebuilt container nodes (see "OCI repositories" above) peppy repo add oci://ghcr.io/acme/peppy-nodes # A Peppy-bot hub that follows the Peppy release, at a pinned id peppy repo add git@github.com:Peppy-bot/private-nodes-hub.git --ref @{peppy-release} --id 2000 # Give the new repo top priority (lower `id` than every existing entry) peppy repo add /path/to/my/nodes --top # Pin the repo under an exact id from the reserved band (>= 2000) peppy repo add /path/to/my/nodes --id 2000 ``` The `--ref` flag is only valid for git sources. By default the new repository is appended with `id = max(existing ids) + 1`, so it has the lowest priority among configured repositories; pass `--top` to assign it an `id` just below the current minimum, giving it the highest priority. The priority `id` decides which repository wins when several of them provide the same `name:tag` (see [Refresh the index](#refresh-the-index)). Pass `--id ` to pin the new repository under that exact id instead of a derived one. Take ids from the reserved band `>= 2000`: Peppy’s bundled defaults stay below 2000, so a pinned id never collides with a default. `--id` conflicts with `--top`, since both decide which id the entry takes. Pinning an id another entry already holds is refused, naming the id: `Failed to add repository (precondition_failed): repository id 2000 is already in use; …`. Each refusal of `peppy repo add`, `peppy repo remove` and `peppy repo exclude` names its [failure kind](/guides/launch_files/#how-a-stack-command-ends): `rejected` for a value that is not valid or an id that the list does not hold, `precondition_failed` for a repository that the list already holds, and `attempt_failed` for a list that the daemon cannot read or write. ### Remove a repository [Section titled “Remove a repository”](#remove-a-repository) ```sh peppy repo remove ``` Removes a repository by its numeric ID (shown by `peppy repo list`). The repository index is automatically refreshed after removal. ### Exclude a repository [Section titled “Exclude a repository”](#exclude-a-repository) ```sh peppy repo exclude [--ref ] ``` Adds a source to `excluded_repositories.json5`. Excluded repositories are skipped during `peppy repo refresh`, and the repository index is automatically refreshed after the exclusion. You can exclude an entire repository or a specific subdirectory within a local repository: ```sh # Exclude a whole git repository peppy repo exclude https://github.com/org/repo.git # Exclude a default hub peppy repo exclude https://github.com/Peppy-bot/mcp-hub.git --ref @{peppy-release} # Exclude a subdirectory of a local repository peppy repo exclude /home/user/projects/private-nodes ``` An exclusion matches a git repository by its `url` and its `ref` as written in `repositories.json5`, so a default hub is excluded with `--ref @{peppy-release}`. ## The repository index [Section titled “The repository index”](#the-repository-index) A repository index is a `peppy_repository.json5` at the root of the tree Peppy scans, stating what the repository publishes and where each item is declared. [`peppy repo index`](#index-a-repository) writes it and `--check` verifies it against the tree, and it is committed alongside the items it lists, so a contested identity is caught on the branch that created it rather than on every machine that later refreshes. The nesting is the uniqueness rule: name, then tag, then the file that declares the item. A second claim on one identity has nowhere to go except a key that is already taken, so a repository cannot state two answers to the same question. ```json5 // peppy_repository.json5, at the root of the tree Peppy scans { peppy_schema: "repository/v1", nodes: { uvc_camera: { v1: { path: "uvc_camera/rust/peppy.json5" }, v2: { path: "uvc_camera/python/peppy.json5" }, }, }, contracts: { rgb_camera: { v1: { path: "cameras/rgb_camera.json5" } } }, pairings: { joint_link: { v1: { path: "robot/joint_link.json5" } } }, mcp_exposures: { camera_surface: { v1: { path: "exposures/camera_surface.json5" } } }, // One level deep: a launcher is identified by its file stem and carries no tag. launchers: { openarm_v1_teleop: { path: "openarm/openarm_v1_teleop.json5" } }, } ``` Rules worth knowing before you hand-edit one: * **`path` names the declaring file, not a directory.** One rule across all five kinds, since only nodes are directory-shaped. * **A repeated key is an error**, not a last-one-wins overwrite. The message names the identity and both files. * **Paths stay inside the repository.** Absolute paths, `..`, `.`, repeated separators, backslashes and trailing separators are all refused, as is a path that reaches its target through a symlink out of the tree. * **Only the mapping belongs here.** Nothing is copied out of an item’s own manifest, because a copy would drift from the thing it copied. * **Unknown fields and unknown versions are refused** rather than ignored, so an index Peppy does not fully understand is rejected outright instead of silently losing part of itself. * **An empty index is valid; a missing one is not.** A repository that publishes nothing has an index with no sections, and `--check` fails on a repository that carries no index at all. “Publishes nothing” and “has no index” are different situations and get different answers. * **The file is generated.** Comments survive `--check`, but the next `peppy repo index` run discards them. A launcher fragment file (`peppy_schema: "launcher_fragment/v1"`) declares no item of its own: it is a piece of a composed launcher, referenced by the option that wants it (see [Launch files](/guides/launch_files/#fragments-splitting-a-launcher-across-files)), so it gets no entry here, takes no launcher name, and is never listed as a launchable stack. The indexer recognizes the kind, and `peppy repo index --check` validates every fragment a launcher references and flattens every legal selection of its component axes, so a broken combination is refused on the branch that introduced it rather than at the first launch that picks it. ### Index a repository [Section titled “Index a repository”](#index-a-repository) ```sh peppy repo index [PATH] # write PATH/peppy_repository.json5 (PATH defaults to .) peppy repo index [PATH] --check # verify the committed index instead of writing it peppy repo index [PATH] --check --validate-mcp-exposures # also validate every listed exposure against its contracts ``` No form needs a running daemon, so all of them work in CI and on a branch before anything is merged. Writing walks the repository and records what it finds. If one identity is claimed twice, generation refuses and names both files: ```plaintext 2 node manifests claim `uvc_camera_video_reconstruction:v1`: uvc_camera_video_reconstruction/python/peppy.json5, uvc_camera_video_reconstruction/rust/peppy.json5 ``` `--check` verifies four things against the repository, and reports everything it finds at once: * every item in the tree is listed (the mistake people actually make is adding an item and forgetting the index, which would otherwise leave it silently invisible); * every listed path is a real file inside the repository; * every listed path declares exactly the kind and identity it is filed under; * every listed path is where the identity is actually declared: an item whose declaring file moved is reported as moved, not as missing. Run it on every pull request to a repository others consume. Catching a contested identity on the branch of the person who caused it is the entire point: the alternative is every machine in the fleet reporting it the next morning, none of which can fix it. The remedy for any failure is the same: re-run `peppy repo index` and commit the result. ### Check the exposures a repository publishes [Section titled “Check the exposures a repository publishes”](#check-the-exposures-a-repository-publishes) ```sh peppy repo index [PATH] --check --validate-mcp-exposures ``` The structural check above reads nothing outside the repository. An MCP exposure document (`peppy_schema: "mcp_exposure/v1"`) also has to agree with contracts that live elsewhere: every member it selects must exist in its contract with the expected kind, every policy must fit the member’s message format, and an author `sha256` must match the contract’s bytes. Passing `--validate-mcp-exposures` adds that check. After the structural check, every exposure the index lists is validated against the contracts it references, resolved through this machine’s repository caches, and every violation of every exposure is reported at once. A target that names a [daemon interface](/advanced_guides/mcp/#daemon-targets) is validated against the interface that the running `peppy` serves, and a target that names an interface or a tag of it that this `peppy` does not serve is a problem that names the tag it serves. The report names each exposure by identity and path, so one run tells an author everything to fix. The check is only as good as the caches, so a contract the caches cannot resolve is a problem naming that contract, never a pass: register and refresh the contract repository first (`peppy repo add`, then `peppy repo refresh`). A hub’s CI does exactly that, starting a throwaway daemon for the refresh, then running the check without one. A file that declares the exposure schema but does not parse as an exposure declares no item and is listed by no index, so the check reports it by path rather than letting it pass unseen. [MCP exposure](/advanced_guides/mcp/) is the guide to writing an exposure and deploying it, and `peppy mcp catalog ` prints the catalog an endpoint for an exposure advertises, from the same caches. ## Using a repository-indexed node [Section titled “Using a repository-indexed node”](#using-a-repository-indexed-node) Once a node appears in `peppy repo list`, you can add it by its `name:tag` without supplying a path or URL; Peppy resolves the source through the cached index at `~/.peppy/cache/nodes.json5`: ```sh peppy node add uvc_camera:v1 ``` This is the shortest form of `peppy node add`. It works for any node provided by any repository listed in `repositories.json5`, including the default [nodes-hub](https://github.com/Peppy-bot/nodes-hub.git) community repository. When several repositories provide the same `name:tag`, the [resolution rule from `repo refresh`](#refresh-the-index) applies: the repository with the lower `id` wins. Resolving a `name:tag` has three outcomes, not two: * **Resolved.** Exactly one repository wins, either because it is the only one providing the identity or because it has the lowest `id`. * **Not found.** No repository provides it. The error names the cache file it looked in, and if you have excluded any repositories it says so, since an excluded repository is never indexed and may well have been the one that provided it. * **Ambiguous.** The cache states that the winning repository claims the identity more than once. A generated index cannot express this (each identity is a key that exists once), so hitting it means the cache file was edited by hand. It is a distinct error naming both files, never a “not found”, since reporting it as missing would send you to add a node that is already there twice: ```text 2 node entries in repository 1000 claim `uvc_camera_video_reconstruction:v1`: uvc_camera_video_reconstruction/python/peppy.json5, uvc_camera_video_reconstruction/rust/peppy.json5; fix the repository so one manifest claims it, then run `peppy repo refresh` ``` One constraint applies to this source shape: * `--ref` is rejected. The git ref (if any) is pinned once in `repositories.json5` when you register the repo, not per-add. If the node you want to add lives in a repository that is **not** in `repositories.json5`, keep using the full git URL or HTTP archive form shown in [Sharing nodes](/guides/sharing_nodes/). That git URL may be HTTPS or SSH; an SSH URL (`git@host:owner/repo.git`) reaches a private repository under the same authentication described in [Private git repositories over SSH](#private-git-repositories-over-ssh). A manifest can also pin the exact content of a contract or pairing document it references with a `sha256` fingerprint, independent of which repository provides it; see [Content pins](/advanced_guides/lockfiles/). ## Syncing against repositories [Section titled “Syncing against repositories”](#syncing-against-repositories) `peppy node sync` regenerates a node’s interface code (peppygen) from its `peppy.json5`. By default, every dependency the node declares must already be in the [node stack](/guides/node_stack/), otherwise the sync fails with an “X does not exist in the stack” error. Pass `-r` (or `--include-repositories`) to let Peppy fall back to the repository cache when a dependency is missing from the stack: ```sh peppy node sync -r ``` The lookup order is: 1. **Node stack**: wins whenever the dependency is already in the stack. Stack-resolved deps are listed under `Synchronized from node stack:` in the command output. 2. **Repository cache** (`~/.peppy/cache/nodes.json5`): consulted only when the stack does not have the dependency. Repo-resolved deps are listed under `Synchronized from repositories:`, each tagged with its source kind (`fs` or `git`). Repository-resolved git dependencies reuse the same persistent checkout cache as `peppy node add`, so the same repository is never cloned more than once during a single sync run. Example output when both layers contribute: ```text Syncing node from /workspace/my_robot_brain via daemon 'cn-...' Synced node interfaces at /workspace/my_robot_brain Synchronized from node stack: - already_added_dep:v1 Synchronized from repositories: - uvc_camera:v1 (git) - lidar_sensor:v1 (fs) ``` A dependency that is missing from **both** the node stack and every configured repository is a hard failure: ```text dep `gps_module:v2` not found in node stack or repository cache; run `peppy repo refresh` ``` `peppy node add` applies the same stack-then-cache lookup automatically, without a flag, but only for the direct dependencies of empty-admitting slots (`cardinality: "zero_or_one"` or `"zero_or_more"`) that are absent from the stack: their interfaces still feed code generation, each cache resolution is reported in the add output, and a dependency missing from both sources refuses the add with the same error. A dependency whose slot demands an instance must still be in the stack before the add. ### Tip: register your local workspace as a repository [Section titled “Tip: register your local workspace as a repository”](#tip-register-your-local-workspace-as-a-repository) When a node depends on another node you maintain locally, registering your workspace directory as a `fs` repository removes the need to `peppy node add` every dependency just to regenerate peppygen for a downstream node: ```sh peppy repo add ~/code/my-nodes peppy repo index ~/code/my-nodes # writes peppy_repository.json5, stating what the directory publishes peppy repo refresh peppy node sync -r # picks up uvc_camera, lidar_sensor, ... from ~/code/my-nodes ``` Re-run `peppy repo index ~/code/my-nodes` and `peppy repo refresh` after adding, moving, or renaming a node in that directory: the refresh reads the committed index, and `repo list` and `node sync -r` both read the cache, not the filesystem. Particularly useful during the early phase of a multi-node project, when the dependency graph is still in flux and you don’t want to re-add nodes after every interface change. ## Directory pruning [Section titled “Directory pruning”](#directory-pruning) When `peppy repo index` walks a repository to write its index, it skips hidden files and directories (any name with a leading `.`) plus the following directories: * `.git` * `.peppy` * `target` * `node_modules` * `.venv` * `__pycache__` A repository’s own `.gitignore` and `.ignore` files are honoured too, while a contributor’s global gitignore and the clone’s `.git/info/exclude` are not read. `peppy repo refresh` does not walk the tree at all: it resolves exactly the paths the committed index names. # Services > How to use services in Peppy Services implement a **request-response** communication pattern between nodes. A node *exposes* a service to handle incoming requests, and other nodes *consume* that service to send requests and receive responses. Use services for operations that need a result, such as querying a node’s state, toggling a feature, or triggering a one-time computation. For long-running work that needs progress feedback or cancellation, use an [action](/advanced_guides/actions/) instead; for the full map of mechanisms, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## Exposing a service [Section titled “Exposing a service”](#exposing-a-service) A node that handles service requests declares its services under `interfaces.services.exposes` in its `peppy.json5`. Each service defines a `name`, a [`description`](/reference/concepts/#descriptions), an optional `request_message_format`, and an optional `response_message_format`: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "uvc_camera", tag: "v1", description: ["The driver of a UVC camera: it turns the camera on and off, and gives its settings. It needs a UVC camera on its machine."], }, interfaces: { services: { exposes: [ { name: "enable_camera", description: "Turn the camera on or off, and give its state after the change.", request_message_format: { enable: "bool", }, response_message_format: { enabled: "bool", }, }, { // A service without a request body; the caller just needs the response. name: "get_camera_info", description: "The type of the camera card, the size of its frames and the interval between two frames.", response_message_format: { card_type: "string", size: "string", interval: "string" }, }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "uvc_camera"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "uvc_camera", tag: "v1", description: ["The driver of a UVC camera: it turns the camera on and off, and gives its settings. It needs a UVC camera on its machine."], }, interfaces: { services: { exposes: [ { name: "enable_camera", description: "Turn the camera on or off, and give its state after the change.", request_message_format: { enable: "bool", }, response_message_format: { enabled: "bool", }, }, { // A service without a request body; the caller just needs the response. name: "get_camera_info", description: "The type of the camera card, the size of its frames and the interval between two frames.", response_message_format: { card_type: "string", size: "string", interval: "string" }, }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/uvc_camera"] }, } ``` Both `request_message_format` and `response_message_format` are optional. A service with no request body acts like a simple getter, and a service with no response body acts like a fire-and-forget trigger. ### Handling requests [Section titled “Handling requests”](#handling-requests) After running `peppy node sync`, the code generator creates a module for each exposed service under `peppygen.exposed_services` (Python) / `peppygen::exposed_services` (Rust). Use `handle_requests` to serve the service: it listens once and answers each request with your handler, so the service stays reachable between two requests. Run it in a separate task so that the main async block is not blocked: * Python ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppygen.exposed_services import enable_camera async def serve_requests(node_runner: NodeRunner): def handler(request): print( f"enable_camera request from {request.instance_id}: " f"enable = {request.data.enable}" ) return enable_camera.Response(enabled=request.data.enable) await enable_camera.handle_requests(node_runner, handler) async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(serve_requests(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` The handler may be a plain function or an `async def`; an async handler is awaited before the response is sent. * Rust ```rust use peppygen::exposed_services::enable_camera; use peppygen::{NodeBuilder, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { tokio::spawn(async move { enable_camera::handle_requests( &node_runner, |request| -> std::result::Result { println!( "enable_camera request from {}: enable = {}", request.instance_id, request.data.enable ); Ok(enable_camera::Response::new(request.data.enable)) }, ) .await }); Ok(()) }) } ``` The `request` argument contains: * `instance_id`: the consumer instance that sent the request, read straight from the request context. The producer is binding-agnostic; it doesn’t know which slot on the consumer this call is heading to. * `core_node`: the core node hosting that consumer instance, read from the request context. * `data`: the deserialized request payload (only present when a `request_message_format` is defined). The handler answers with its response, a success, or with a failure. A failure gives the caller an **error reply**: a failure kind and a message for a person (see [Error replies](#error-replies)). `handle_requests` answers one request at a time: a request that arrives while the handler runs waits until the handler is done with the request before it. A reply that does not reach its caller, such as one to a caller that has gone, is logged, and the service answers the next request. It returns when the request stream of the service ends, and gives an error (Rust) or raises (Python) when the service cannot listen. For a service without a request body, the handler receives a `Request` with only the request context (`instance_id` and `core_node`): * Python ```python from peppygen.exposed_services import get_camera_info async def serve_info_requests(node_runner: NodeRunner): def handler(request): print(f"get_camera_info request from {request.instance_id}") return get_camera_info.Response( card_type="UVC Webcam", size="1920x1080", interval="30fps", ) await get_camera_info.handle_requests(node_runner, handler) ``` * Rust ```rust use peppygen::exposed_services::get_camera_info; tokio::spawn(async move { get_camera_info::handle_requests( &node_runner, |request| -> std::result::Result { println!("get_camera_info request from {}", request.instance_id); Ok(get_camera_info::Response::new( "UVC Webcam".to_owned(), "1920x1080".to_owned(), "30fps".to_owned(), )) }, ) .await }); ``` A producer exposes its service exactly once and serves any consumer that calls it. Starting the producer before any consumer (or after them) is equally valid. ### Error replies [Section titled “Error replies”](#error-replies) A service answers each request with its response, or with an error reply: a **failure kind** and a message. The response is a success. So no response reports a failure in a field of its own, such as `success: false` and an error text; a field that gives the answer of a check, such as whether a pose is reachable, is data and stays in the response. A service gives a kind from a closed set: the kinds of peppy, and the kinds of its contract that the service lists (see [failure kinds](/advanced_guides/contract_implementation/#failure-kinds)). A native service gives the kinds of peppy only (`attempt_failed`, `timeout`, `precondition_failed`, `resource_unavailable`, `rejected`; see [How a goal ends](/advanced_guides/actions/#how-a-goal-ends)). The generated module of each service declares them as a `FailureKind` enum and a `Failure` type (`kind`, `message`), and the generated handler can give no other kind: in Rust a kind the service does not declare is not a variant of the enum, so the node does not compile; in Python `Failure` raises `ValueError` for it. * Python ```python def handler(request): if not camera_is_connected(): # Raise, or return, the Failure of this service. raise enable_camera.Failure( enable_camera.FailureKind.RESOURCE_UNAVAILABLE, "the camera is unplugged" ) return enable_camera.Response(enabled=request.data.enable) ``` The handler can also raise or return any other `peppylib.FailureError`, such as the `Failure` of another service. It gives an error reply of its kind when this service declares that kind, and else an error reply of the kind `attempt_failed`, whose message keeps the message of the failure. A handler that raises any other exception gives an error reply of the kind `attempt_failed`, with the text of the exception. `Failure` raises `TypeError` for a message that is not a `str`, so a handler that gives `Failure(kind, error)` with an exception `error` gives an error reply of the kind `attempt_failed`: write `Failure(kind, str(error))`. * Rust ```rust |request| -> std::result::Result { if !camera_is_connected() { return Err(enable_camera::Failure::new( enable_camera::FailureKind::ResourceUnavailable, "the camera is unplugged", )); } Ok(enable_camera::Response::new(request.data.enable)) } ``` A request that does not decode into the declared `request_message_format` never reaches the handler: the generated server gives it an error reply of the kind `rejected`, with the decode error as the message. A response that does not serialize gives an error reply of the kind `attempt_failed`. ## Consuming a service [Section titled “Consuming a service”](#consuming-a-service) A node that calls a service declares what it consumes under `interfaces.services.consumes`. Dependencies are declared in `manifest.depends_on` and referenced by `link_id` in the interface: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "robot_brain", tag: "v1", description: ["The brain of a robot: it turns its UVC camera on and off. It needs no device."], depends_on: { nodes: [ { name: "uvc_camera", tag: "v1", link_id: "uvc_camera" }, ] }, }, interfaces: { services: { consumes: [ { link_id: "uvc_camera", // References depends_on.nodes[].link_id name: "enable_camera", // Service name on that node }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "robot_brain"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "robot_brain", tag: "v1", description: ["The brain of a robot: it turns its UVC camera on and off. It needs no device."], depends_on: { nodes: [ { name: "uvc_camera", tag: "v1", link_id: "uvc_camera" }, ] }, }, interfaces: { services: { consumes: [ { link_id: "uvc_camera", // References depends_on.nodes[].link_id name: "enable_camera", // Service name on that node }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/robot_brain"] }, } ``` Note By default, the `node add` and `node sync` commands require the target node to already be in the node stack so the proper interfaces can be generated. If the target node is missing, you will see an error like: ```plaintext Error: `robot_brain:v1` depends on `uvc_camera:v1`, but it does not exist in the stack ``` Pass `peppy node sync --include-repositories` (`-r`) to let the daemon fall back to the [repository cache](/advanced_guides/repositories/#syncing-against-repositories) for dependencies that aren’t in the stack. ### Calling a service [Section titled “Calling a service”](#calling-a-service) The code generator creates a module for each consumed service under `peppygen.consumed_services` (Python) / `peppygen::consumed_services` (Rust). Use `poll` to send a request and wait for a response. The caller selects which bound producer handles the call by passing one explicit `target`, obtained from the slot’s [cardinality](/advanced_guides/topics/#dependency-cardinality)-typed accessor: on a `one` slot `bound_producer()` returns the sole producer directly, on a `zero_or_one` slot it returns an `Option` the caller branches on first (a vacant slot has no target, so there is nothing to poll), on a `one_or_more` slot `bound_producers()` returns a never-empty set whose `first()` needs no unwrap, and on a `zero_or_more` slot it returns a possibly empty list whose empty case the caller must handle. The explicit `target` parameter itself has the same shape for every cardinality. The candidates are the slot’s bound set when the call is made, every member of it validated by the plan that bound it, so by the time `poll` runs the route set is already validated. * Python ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppygen.consumed_services.uvc_camera import enable_camera async def call_service(node_runner: NodeRunner): # `one`: launch resolved the slot to exactly one producer, so the # accessor is singular and infallible; no emptiness handling exists. # The target is still passed explicitly, same discipline as the # multi cardinalities. camera = enable_camera.bound_producer(node_runner) request = enable_camera.Request(enable=True) response = await enable_camera.poll( node_runner, camera, # the slot's sole producer request, 5.0, # timeout (seconds) ) print( f"enable_camera result: instance={response.instance_id} " f"enabled={response.data.enabled}" ) async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(call_service(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use peppygen::consumed_services::uvc_camera::enable_camera; use peppygen::{NodeBuilder, Parameters, Result}; use std::time::Duration; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // `one`: launch resolved the slot to exactly one producer, so the // accessor is singular and infallible; no emptiness handling exists. // The target is still passed explicitly, same discipline as the // multi cardinalities. let camera = enable_camera::bound_producer(&node_runner); let request = enable_camera::Request::new(true); let response = enable_camera::poll( &node_runner, camera, // the slot's sole producer Duration::from_secs(5), // timeout request, ) .await?; println!( "enable_camera result: instance={} enabled={}", response.instance_id, response.data.enabled, ); Ok(()) }) } ``` The `target` must be a member of the slot’s own bound set, the one its bound-producer accessor returns; a target outside the set (including a producer bound to a different slot of the same consumer) fails with `TargetNotBound` (`ValueError` in Python) before anything reaches the wire. A `ProducerRef` yielded by the slot’s own topic subscription is a member by construction, so the natural receive-a-frame-then-call-that-camera flow needs no defensive code. The response contains: * `instance_id`: the producer instance that handled the request, read from the response context. * `core_node`: the core node hosting that producer instance, read from the response context. * `data`: the deserialized response payload. For a service without a request body, `poll` simply takes no request: * Python ```python from peppygen.consumed_services.uvc_camera import get_camera_info camera = get_camera_info.bound_producer(node_runner) response = await get_camera_info.poll(node_runner, camera, 5.0) print(f"Camera: {response.data.card_type} {response.data.size}") ``` * Rust ```rust use peppygen::consumed_services::uvc_camera::get_camera_info; let camera = get_camera_info::bound_producer(&node_runner); let response = get_camera_info::poll( &node_runner, camera, Duration::from_secs(5), ).await?; println!("Camera: {} {}", response.data.card_type, response.data.size); ``` ### Calling every bound producer [Section titled “Calling every bound producer”](#calling-every-bound-producer) Codegen provides only single-target operations; calling every member of a multi-cardinality slot is a plain loop at the call site (a `one` slot has no set to loop over: its singular `bound_producer()` is the sole target). Sequential versus concurrent execution, partial-result collection, and whether one failure cancels the other calls are application decisions; there is no atomic broadcast. Here the `camera` slot declares `cardinality: "one_or_more"`: * Python ```python # Runs once per bound producer, in plan order. # `one_or_more`: the list is never empty, so the body runs at least once. # `zero_or_more`: an empty list makes the loop a no-op; no request is sent. for camera in enable_camera.bound_producers(node_runner): request = enable_camera.Request(enable=True) response = await enable_camera.poll(node_runner, camera, request, 5.0) print(f"{response.instance_id}@{response.core_node}: enabled={response.data.enabled}") ``` * Rust ```rust // Runs once per bound producer, in plan order. // `one_or_more`: the set is never empty, so the body runs at least once. // `zero_or_more`: an empty list makes the loop a no-op; no request is sent. let cameras = enable_camera::bound_producers(&node_runner); for camera in cameras { let request = enable_camera::Request::new(true); let response = enable_camera::poll( &node_runner, &camera, Duration::from_secs(5), request, ) .await?; println!( "{}@{}: enabled={}", response.instance_id, response.core_node, response.data.enabled, ); } ``` To address one member of a multi slot instead of all of them, pick it from the same set; on a `one_or_more` slot the set is never empty, so selecting the first member needs no unwrap: * Python ```python camera = enable_camera.bound_producers(node_runner)[0] ``` * Rust ```rust let cameras = enable_camera::bound_producers(&node_runner); let camera = cameras.first(); ``` ## Bindings and routing [Section titled “Bindings and routing”](#bindings-and-routing) Routing for services is the same consumer-side model used by topics. A binding `KEY: VALUE` creates a private channel from producer instance `VALUE` to one of the consumer’s declared slots; the producer itself doesn’t know or care about bindings. A service slot resolves through its bindings: the generated `poll` checks the caller-selected target against the slot’s bound set and sends the wire request directly to it, carrying the producer’s full `(core_node, instance_id)` wire address. No discovery is involved. How many producers may be bound to the slot is its declared [cardinality](/advanced_guides/topics/#dependency-cardinality) (`one` when omitted); a multi-cardinality slot takes an array of instance ids, and a `one` / `one_or_more` slot with no binding is rejected at launch validation, before anything spawns. Because a request/response call needs exactly one responder, every call selects exactly one member of the bound set. In a launcher / stack config: ```json5 { source: { name: "consumer:v1" }, instances: [{ instance_id: "my_consumer", links: { uvc_camera: "my-camera-instance" }, }], } ``` or, when launching a single node during development: ```sh peppy node run --link uvc_camera@my-camera-instance consumer:v1 ``` ### Worked example: `openarm01_backbone` [Section titled “Worked example: openarm01_backbone”](#worked-example-openarm01_backbone) A consumer that wires two depth cameras to two dedicated slots: openarm01_backbone/peppy.json5 ```json5 { manifest: { name: "openarm01_backbone", tag: "v1", description: ["The backbone of an OpenArm with a depth camera on each wrist."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "wrist_left_camera" }, { name: "depth_camera", tag: "v1", link_id: "wrist_right_camera" }, ], }, }, // ... } ``` peppy_launcher.json5 ```json5 { description: ["An OpenArm backbone with a depth camera on each wrist. It needs the arm and the two cameras."], deployments: [ { source: { name: "depth_camera:v1" }, instances: [ { instance_id: "left_cam" }, { instance_id: "right_cam" }, ]}, { source: { name: "openarm01_backbone:v1" }, instances: [ { instance_id: "backbone_inst_1", links: { wrist_left_camera: "left_cam", wrist_right_camera: "right_cam", }}, ]}, ], } ``` Three contract statements follow from this manifest: 1. `poll` on the nested `wrist_left_camera.` (Python) / `wrist_left_camera::` (Rust) module reaches `left_cam`. 2. `poll` on the nested `wrist_right_camera.` (Python) / `wrist_right_camera::` (Rust) module reaches `right_cam`. 3. If the `wrist_right_camera` binding line were removed, validation would reject the launch (a declared slot is bound, or declared vacant where its cardinality is `zero_or_one`): a service call has no wildcard fallback. ### Why an explicit single target? [Section titled “Why an explicit single target?”](#why-an-explicit-single-target) The underlying Zenoh transport would broadcast an untargeted service query to every matching producer (`QueryTarget::All`), and every producer’s user handler would run even though the consumer only ever consumes the first reply. For idempotent reads that wastes work; for state-changing services it can cause real-world side effects on producers the consumer never intended to reach. Requiring every call to name one member of the slot’s validated bound set removes that hazard by construction: the selected target carries the producer’s full `(core_node, instance_id)` wire address, so the call addresses exactly one producer with no probe round-trip and no discovery race, both the request and the response stay pinned to it, and an out-of-set target (which plan-time binding validation cannot check) is rejected before it reaches the wire. If the selected producer dies, the call surfaces `ServiceUnreachable` (a `ConnectionError` in Python) and the caller can retry once the producer is back: a producer dying never changes the bound set. On a `one_or_more` or `zero_or_more` slot a [copy joining or leaving](/guides/launch_files/#copies) does, so read `bound_producers()` at the point of use. ### Validator rules [Section titled “Validator rules”](#validator-rules) The launcher validator runs these checks before the stack starts: 1. **Every `KEY` must name a declared slot, and every declared slot must resolve.** A binding whose `KEY` matches no `depends_on` `link_id` is rejected; there are no free-form keys. A declared `one` / `zero_or_one` / `one_or_more` slot with no `links` entry fails the launch before anything is spawned; a `zero_or_more` slot with no entry resolves to the empty set, and so does a `zero_or_one` slot the deployment declared vacant. 2. **The value’s shape must match the slot’s cardinality.** A scalar slot (`one` or `zero_or_one`) takes a scalar, a multi slot takes an array, an empty array meets only `zero_or_more`, and duplicate targets within one slot are rejected. Repeated `--link KEY@…` flags accumulate on a multi slot and are a hard error on a scalar slot. 3. **Every target must satisfy the slot, checked per bound instance.** A target `instance_id` that deploys a different node than the slot expects (or one that does not implement the requested contract) is rejected. 4. **Stack-wide `instance_id` uniqueness.** Every `instance_id` must be unique across the entire stack, not just within a `(node_name, node_tag)` group. The `--link` syntax names producers by `instance_id`, so a duplicate would make the binding ambiguous. 5. **Bindings are stamped with the producer’s `core_node`.** The wire addresses producers by the full `(core_node, instance_id)` pair; the validator stamps each target producer instance’s resolved `core_node` into the binding (equal to the launching daemon’s only in the single-machine case), preserving plan order, so generated calls address exactly the selected producer and never match on `instance_id` alone. Plan order is the launcher’s array order, then the members each joined copy adds, in the order the copies joined (see [validator rule 5](/advanced_guides/topics/#validator-rules)). ## Error handling [Section titled “Error handling”](#error-handling) Service calls can fail with four error types: * **TargetNotBound** (`ValueError` in Python): the selected target is not a member of the slot’s bound set; raised before anything reaches the wire. * **ServiceUnreachable** (`ConnectionError` in Python): no instance is listening for that service. * **ServiceTimeout** (`TimeoutError` in Python): no response was received within the timeout. * **ServiceFailed** (the `Failure` of the service in Python): the provider gave an [error reply](#error-replies), with a failure kind and a message. The error reply of a handler reaches the caller as fast as a response, rather than as a timeout, and the service goes on to accept new requests. The generated `poll` parses the error reply into the `Failure` of its service. In Rust, `Failure::of(&error)` reads it from the `Error::ServiceFailed` of the call; in Python, `poll` raises the `Failure` of the service, a `peppylib.FailureError`: * Python ```python try: response = await enable_camera.poll(node_runner, camera, request, 5.0) except enable_camera.Failure as failure: if failure.kind is enable_camera.FailureKind.RESOURCE_UNAVAILABLE: print(f"the camera is gone: {failure.message}") ``` * Rust ```rust match enable_camera::poll(&node_runner, camera, Duration::from_secs(5), request).await { Ok(response) => println!("enabled={}", response.data.enabled), Err(error) => match enable_camera::Failure::of(&error) { Some(failure) if failure.kind == enable_camera::FailureKind::ResourceUnavailable => { println!("the camera is gone: {}", failure.message) } _ => return Err(error), }, } ``` An error reply with a kind that the service does not declare breaks the contract of the service: the generated `poll` gives a deserialization error (`ValueError` in Python) instead of a failure of an unknown kind. The text of the error keeps the message of the provider. # Shutdown lifecycle > How a node stops: the stop paths, the cancellation token, shutdown hooks, grace windows, and the force-kill backstops. A node instance rarely gets to decide when it stops, and a robot node that stops carelessly leaves motors energized, instance locks held, and state unflushed. This guide is the full contract for how a node shuts down: which events trigger it, what the runtime guarantees (and does not guarantee) about your code during it, and how the grace windows bound every step. For the quick-start version, see [Graceful shutdown](/guides/first_node/#graceful-shutdown) in the first node guide; for the daemon-side operations view, see [Daemon shutdown and orphan prevention](/guides/node_stack/#daemon-shutdown-and-orphan-prevention). The runtime gives your node two shutdown primitives, and they are deliberately not the same thing: * The **cancellation token** (`node_runner.cancellation_token()`) is a *signal*: it resolves when shutdown begins, so in-flight work can notice and stop. Nothing waits for the code that follows it. * **Shutdown hooks** (`node_runner.on_shutdown(...)`) are *awaited obligations*: registered cleanup that the runtime itself runs to completion (bounded by a grace window) before `run()` returns. Use the token to stop working; use a hook to finish cleaning up. ## The stop paths [Section titled “The stop paths”](#the-stop-paths) Every way a node can be asked to stop converges on the same cancellation token, and therefore on the same sequence below: * [`peppy node stop `](/guides/node_stack/#stopping-your-node): the daemon sends an in-band shutdown request over messaging. No unix signal is involved. * **Daemon teardown**: a clean daemon shutdown (`Ctrl+C`, `systemctl stop`) sends the same in-band request to every spawned node, as does `peppy node add` when it replaces a node that has running instances. * **A start that the daemon gives up after the ready signal**: a setup that outlasts its [setup budget](/guides/node_stack/#how-an-instance-starts), an endpoints step that fails, a launch or join whose run budget runs out, a `peppy stack reset` during the start, and a cancel of the goal that starts the instance (a Ctrl+C on `peppy node run` or `peppy stack launch`, or a command that goes away while it waits) send the same in-band request to the starting instance. The runtime listens for the request before it answers ready, so a setup that the daemon stops still runs the hooks that it registered. A start that the daemon gives up before the ready signal gets no request: the daemon kills the process group of the instance at once, and no hook runs. * **`SIGINT` / `SIGTERM` delivered to the node process**: the runtime installs its own signal handlers, so a plain `kill` (or `Ctrl+C` on a standalone node) is just another route to the token. Your node needs no signal handling of its own. * **Daemon-liveness loss**: the node’s watchdog cancels the token after `daemon_grace_secs` without a heartbeat of its own daemon, or at the first heartbeat of a new daemon of its core node, so an orphaned node tears itself down. * **A setup error**: if your setup function returns an error, the runtime still cancels the token and runs the hooks registered up to that point (so a lock acquired early in setup is released even when bringup fails halfway). * **Programmatic cancel**: your own code may cancel the token to request shutdown from inside the node. This is how a one-shot node ends itself once its work is done. A node that exits on its own stays listed: `restarting` when its [restart policy](/guides/launch_files/#restart-policy) starts it again, else in a terminal state, `finished` for the clean exit that follows a cancel-and-return, or `failed` if it exits with an error. A one-shot node declares `framework: { restart: "never" }` in its `peppy.json5`, so a launcher root’s `always` does not start it again. See [Instance health and lifecycle](/guides/node_stack/#instance-health-and-lifecycle). ## The shutdown sequence [Section titled “The shutdown sequence”](#the-shutdown-sequence) Once any of those paths fires, the runtime drives one ordered sequence: 1. **The cancellation token is cancelled.** Every `token.cancelled()` resolves; loops that select on it should stop doing work. Background tasks keep running for now; services (health, your own endpoints) remain reachable. 2. **Shutdown hooks run**, sequentially, in **reverse registration order** (last registered, first run), all within **one shared grace window** (`lifecycle.shutdown_grace_secs`). The messenger is still connected, so hooks can use the [datastore](/advanced_guides/datastore/), services, and topics. 3. **Task teardown.** In Python, the runtime now cancels the node’s remaining asyncio tasks and waits for them to finish (their `try`/`finally` blocks run, best effort). In Rust, `run()` returns and the tokio runtime is dropped: spawned tasks are simply dropped wherever they last yielded, which is why cleanup must not live in them. 4. **The process exits.** On the stop paths driven by the daemon, the daemon has been waiting in parallel since step 1. It does not force-kill at the hook deadline: it allows for the node’s whole cooperative exit (the hook grace window, then task teardown, and in Python the event-loop join and interpreter finalize) and only `SIGKILL`s the process group of a node still alive at that later force-kill deadline, reporting it as force-killed. Reverse registration order mirrors how resources are acquired: setup acquires the lock first and brings hardware up second, so teardown disables hardware first and releases the lock last, like destructors. ## Registering hooks [Section titled “Registering hooks”](#registering-hooks) Register hooks during setup, as soon as the resource they release exists. A hook registered after shutdown has begun may never run. * Python The callback may be a plain function or an `async def`; a returned awaitable runs on the node’s event loop. Exceptions raised by a hook are printed and the remaining hooks still run: ```python async def setup(params, node_runner: NodeRunner): async def clear_latest(): await remove(node_runner, LATEST_KEY, response_timeout_secs=2.0) node_runner.on_shutdown(clear_latest) ``` * Rust The hook is any `Future + Send + 'static`. Capture an `Arc` clone if the cleanup needs messaging; a panicking hook is contained and logged, and the remaining hooks still run: ```rust NodeBuilder::new().run(async |params: Parameters, node_runner| { let runner = node_runner.clone(); node_runner.on_shutdown(async move { if let Err(e) = datastore::remove(&runner, LATEST_KEY, TIMEOUT).await { tracing::warn!("failed to clear the latest value: {e}"); } }); Ok(()) }) ``` Long-running work still belongs in spawned tasks that watch the token: * Python ```python token = node_runner.cancellation_token() while not token.is_cancelled(): do_work() await asyncio.sleep(interval) # stop working; cleanup happens in hooks ``` * Rust ```rust loop { tokio::select! { _ = token.cancelled() => break, // stop working; cleanup happens in hooks _ = interval.tick() => { /* do work */ } } } ``` Inside a hook the token is already cancelled, so `token.is_cancelled()` reports true and awaiting `token.cancelled()` returns immediately. ## Grace windows [Section titled “Grace windows”](#grace-windows) Two settings in `~/.peppy/conf/peppy_config.json5` bound the lifecycle (see [Daemon configuration](/advanced_guides/daemon_config/)); the daemon resolves both once and ships them to every node it spawns: * **`lifecycle.shutdown_grace_secs`** (default **5**, minimum 1) is the node’s cooperative-cleanup budget, and it bounds two nested windows. Node-side, the runtime bounds the *entire hook phase* by this value, so a stuck hook is abandoned at the deadline and the node still exits on its own. Daemon-side, a stop path waits this window **plus** a fixed runtime-teardown allowance (the asyncio event-loop join, bounded by an internal 5s backstop, plus interpreter finalize) before force-killing, so a node that spends its full hook budget and then tears down cleanly is never mistaken for stuck. Raise it if your node legitimately needs longer to park actuators; the daemon’s force-kill deadline rises with it. * **`lifecycle.daemon_grace_secs`** (default **180**, minimum 30) decides *when* shutdown starts on the daemon-death path (how long a node tolerates a silent daemon before tearing itself down). A new daemon of the core node starts the shutdown at its first heartbeat, before this period ends. It does not change how long cleanup gets once shutdown starts. Caution On the daemon-death path there is no force-kill backstop: the daemon that would have delivered the `SIGKILL` is gone. The node-side bound on the hook phase is the only thing standing between a hung cleanup and an orphaned process, which is why all hooks share one hard window rather than getting one each. The window is enforced at await points. A hook that blocks synchronously (a stuck CAN read, a `while True: pass`) cannot be interrupted by the node itself; on daemon-driven stop paths the force-kill covers it, on the daemon-death path it cannot. Keep synchronous work inside hooks short. ## Python specifics [Section titled “Python specifics”](#python-specifics) Python nodes get the same sequence with a few extra mechanics: * Hook coroutines run on the node’s own asyncio event loop, which is still serving background tasks at that point. Tasks are cancelled only **after** the last hook finishes, so a hook can still await results produced by the rest of the node. * After the hooks, the runtime cancels the remaining tasks and gathers them: `try`/`finally` blocks run, but as cancelled code racing process exit they are best effort. Cleanup that must happen (or that needs messaging) belongs in `on_shutdown`, not in `finally`. * A node whose setup function is synchronous has no persistent event loop; its async hooks run on a dedicated one-off loop (`asyncio.run`) instead. Sync hooks are called directly in both cases. * The event-loop thread is joined (bounded by an internal 5 second backstop) before `run()` returns, so no Python frame is executing native code when the interpreter finalizes. * An in-band stop, a signal or the daemon watchdog that arrives while an **async setup** is still running cancels the setup at its next `await`. The runner waits until the setup has unwound (its `except` and `finally` blocks have run), then runs the hooks registered before the stop, and exits without setup completing. The other tasks of the node keep running until the hooks end. The wait for the setup is part of the hook phase and shares its grace window, so a setup that catches the cancellation and goes on awaiting holds the hooks back until the window ends. * One limitation: a **synchronous setup** holds the runner until it returns, so a stop that arrives while it runs takes effect only once setup returns. A synchronous setup that does not return within the force-kill deadline is ended by the daemon’s force-kill. ## Force backstops [Section titled “Force backstops”](#force-backstops) Cooperative shutdown is bounded at every level, so a misbehaving node can always be removed: * **Daemon force-kill**: any daemon-driven stop path `SIGKILL`s the node’s whole process group once the force-kill deadline (the grace window plus the runtime-teardown allowance, see [Grace windows](#grace-windows)) elapses. `peppy node stop` reports whether the instance exited gracefully or had to be force-killed. A start that the daemon gives up before the ready signal skips the request and the deadline: the daemon `SIGKILL`s the process group at once. * **What a killed node leaves**: a `SIGKILL` runs no hook. Neither does an abort, the OOM killer or a power cut. The operating system closes the process’s files, sockets and file locks. Nothing else is cleaned up: actuators stay energized, and a datastore key no instance owns stays until the daemon restarts, because the datastore is the daemon’s memory. The daemon removes a key the node owns through [`store_exclusive`](/advanced_guides/datastore/#store_exclusive) when the process ends. Therefore make exclusivity end with the process: a file lock for a device, which also excludes processes outside peppy, or a key owned through `store_exclusive` for something only one peppy instance may drive at a time. Keep a hook for the work only the node can do, such as parking an actuator. * **Second signal**: while a signal-initiated shutdown is in flight, a second `SIGINT`/`SIGTERM` makes the node exit immediately with the conventional `128 + signo` code (130 or 143), skipping the remaining cleanup. Pressing `Ctrl+C` twice always works. ## What a node never needs [Section titled “What a node never needs”](#what-a-node-never-needs) The runtime owns the whole lifecycle, so a node should contain none of the following; each one either duplicates the runtime or defeats its guarantees: * **Signal handlers.** `SIGINT`/`SIGTERM` are routed to the cancellation token for you. * **Cleanup in a spawned task.** A task watching the token races the teardown in step 3 of [the sequence](#the-shutdown-sequence) and is not guaranteed to run again after the token fires; only `on_shutdown` hooks are awaited. * **`std::process::exit` / `sys.exit` after cleanup.** `run()` returns once the hooks finish and the process exits normally; an explicit exit skips the remaining teardown. To stop the node from inside, cancel the token and return. Exiting cleanly this way has the daemon record the instance as terminal `finished`, and a non-zero exit or crash as `failed`, unless its restart policy starts it again ([Instance health and lifecycle](/guides/node_stack/#instance-health-and-lifecycle)). # Stack benchmark > Measure the messaging latency of every interface in your running stack `peppy stack benchmark` reports the **latency** of the topics, services, and actions that wire each node to its dependencies, measured against the **already-running** stack. It prints p50 / p90 / mean per interface as **two separate tables**, because the two kinds of numbers answer different questions and must not be read side by side: * **Synthetic probes**: handler-free round-trips with payloads sized from the message schema. This is the fixed cost of the messaging plumbing, per edge, for every topic, service, and action. * **Real traffic**: the observe-only one-way delivery latency of a topic’s live messages, full payload included. This is what a consumer actually experiences: a camera topic streaming multi-megabyte frames can legitimately read 30× above its own plumbing cost, and that difference is payload, not overhead. It covers **both** ways a node can depend on another: * **direct** dependencies (`depends_on.nodes`), drawn with a light arrow `→`; and * dependencies resolved through **contract implementation** (`depends_on.contracts` matched by a producer’s `manifest.implements`), drawn with a heavy arrow `➔`. See [Contract implementation](/advanced_guides/contract_implementation/). Topics backed by [pairing or observer slots](/advanced_guides/pairing/) (`depends_on.pairings` / `depends_on.pairing_observers`) are not benchmarked: those edges produce no rows. The report covers one daemon’s slice of the stack: the benchmark goal goes to a single daemon and enumerates only its own node stack. In a federated launch, benchmark each machine separately, targeting a participant with the global `--core-node ` flag. Use it to answer questions like “is this service round-trip as fast as I expect?”, “how long does a frame take to reach its consumer?”, or “did my last change make a hot path slower?” (each run is compared against the previous run on the same machine). ## Running it [Section titled “Running it”](#running-it) The daemon must be running with a launched stack (see [Core node functions](/advanced_guides/core_node_functions/)). ```sh # Benchmark every dependency edge with the defaults (200 samples, 20 warmup). peppy stack benchmark # Tune the sample counts and per-sample timeout. peppy stack benchmark --samples 500 --warmup 50 --per-sample-timeout-ms 1000 ``` | Flag | Default | Meaning | | ------------------------- | ------- | --------------------------------------------------------- | | `--samples` | `200` | Timed samples per interface, after warmup. | | `--warmup` | `20` | Warmup samples per interface, discarded before measuring. | | `--per-sample-timeout-ms` | `2000` | Per-sample probe/observe timeout. | The report opens with an `env:` line summarizing the host CPU, which is what makes `Δp50` comparisons against the previous run interpretable, plus a warning when turbo or shared-host load makes absolute latency swing run-to-run. With no interface edges in the running stack it prints `No interface edges found in the running stack; nothing to benchmark.`, and a second benchmark started while one is in flight is refused, with the failure kind `busy`. A Ctrl+C sends the daemon a cancel: the measurement in progress stops, no other one starts, and the command prints `Benchmark was cancelled by its caller.` and exits with code 5, the exit status of a cancelled goal. A benchmark changes nothing on the stack, so the next one runs at once. A second Ctrl+C stops the wait for the end of the benchmark once the cancel reached the daemon and exits with code 130, and a third one ends the command at once. ## Reading the tables [Section titled “Reading the tables”](#reading-the-tables) One row is emitted **per consumed artifact** (each topic, service, or action a consumer is wired to), so a node that consumes the same producer as both a topic and a service gets one row for each. A **topic edge appears in both tables**: a synthetic `node-probe` row for its plumbing cost and a `delivery` row for its real traffic. The `edge` and `binding` columns together keep rows distinct even when several share a producer. The **synthetic table** collects every handler-free round-trip probe. All of its rows are timed on a single clock (no `clock` column needed) and carry payloads sized from the message schema, so they are comparable with each other: ```plaintext Synthetic probes: handler-free round-trips, schema-sized payloads (200 samples/interface) ┌──────────────────┬──────────┬────────────┬────────┬────────┬────────┬─────┬──────┬────────────────────┐ │ edge │ binding │ measure │ p50 │ p90 │ mean │ n │ Δp50 │ note │ ├──────────────────┼──────────┼────────────┼────────┼────────┼────────┼─────┼──────┼────────────────────┤ │ brain:v1 │ left_arm │ act-probe │ 240µs │ 310µs │ 255µs │ 200 │ - │ payload 32B → 16B │ │ → arm:v1 │ │ │ │ │ │ │ │ │ │ /move_arm │ │ │ │ │ │ │ │ │ │ brain:v1 │ camera │ node-probe │ 195µs │ 250µs │ 207µs │ 200 │ - │ camera:v1; payload │ │ ➔ camera_mock:v1 │ │ │ │ │ │ │ │ 0B → ≥56B │ │ /frames │ │ │ │ │ │ │ │ │ │ brain:v1 │ camera │ svc-probe │ 180µs │ 220µs │ 191µs │ 200 │ - │ camera:v1; payload │ │ ➔ camera_mock:v1 │ │ │ │ │ │ │ │ 0B → ≥32B │ │ /frame_info │ │ │ │ │ │ │ │ │ └──────────────────┴──────────┴────────────┴────────┴────────┴────────┴─────┴──────┴────────────────────┘ ``` The **real-traffic table** collects the observe-only measurements of live messages, full payload included. All of its rows are one-way `delivery` measurements (no `measure` column needed), so it carries the `clock` column instead: ```plaintext Real traffic: observe-only one-way delivery of live topic messages (200 samples/interface) ┌──────────────────┬──────────┬───────────┬────────┬────────┬────────┬─────┬──────┬────────────┐ │ edge │ binding │ clock │ p50 │ p90 │ mean │ n │ Δp50 │ note │ ├──────────────────┼──────────┼───────────┼────────┼────────┼────────┼─────┼──────┼────────────┤ │ brain:v1 │ camera │ same-host │ 1.20ms │ 1.80ms │ 1.31ms │ 200 │ - │ camera:v1 │ │ ➔ camera_mock:v1 │ │ │ │ │ │ │ │ │ │ /frames │ │ │ │ │ │ │ │ │ └──────────────────┴──────────┴───────────┴────────┴────────┴────────┴─────┴──────┴────────────┘ ``` * **edge**: the dependency, wrapped over three lines: the **consumer**, then the kind arrow + **producer**, then the consumed `/interface` (topic, service, or action name). `→` is a direct `depends_on.nodes` edge; `➔` is one resolved through contract implementation (the `note` names the contract). * **binding**: the dependency binding (`link_id`) this edge was measured through. A node can consume the same interface from one producer via several bindings; this column tells those rows apart. * **measure** (synthetic table): how the row was probed, color-coded in the terminal for a quick scan: **svc-probe** (service round-trip, blue), **act-probe** (action round-trip, magenta), and **node-probe** (topic edge’s producer-node round-trip, cyan). What each one measures is detailed below. * **clock** (real-traffic table): clock-alignment confidence for the one-way delivery measurement. * **p50 / p90 / mean**: the latency distribution, in ns / µs / ms. * **n**: how many samples were collected (an unreachable or idle edge shows `0`). * **Δp50**: change in the median versus the previous run **on this machine** (baselines are machine-local, so numbers are never compared across machines). * **note**: for `➔` rows, the contract the edge was resolved through; for probe rows, the measured payload sizes (see [Payload sizing](#payload-sizing)); plus any diagnostic (e.g. a suppressed cross-host value, or a topic with no live traffic). A legend repeating all of this prints beneath the tables: ```plaintext Legend: edge → direct dependency (depends_on.nodes) ➔ resolved through contract implementation (the note names the contract) synthetic round-trips on a single clock; the producer's framework replies and handlers never run, with payloads sized from the message schema svc-probe round-trip to the service act-probe round-trip to the action's goal service (no goal is created) node-probe topic edge: round-trip to the producer node's framework, reply sized from the topic schema (the topic itself is never published; topic QoS does not apply) real observe-only: delivery is the one-way receive−source latency of the topic's own live messages, full payload included binding the dependency binding this edge was measured through; a node can consume the same interface from one producer via several bindings clock same-host exact (producer shares this host's clock) corrected cross-host, adjusted via the producer's measured offset flagged implausible delta, suppressed (deploy PTP/NTP) note the contract (➔ edges) and, for probe rows, the measured payload sizes (request → response; `≥` = schema lower bound) Δp50 median vs the previous run on this machine Benchmarking never triggers a real handler, never publishes onto a real topic, and never creates a goal. ``` ## What each metric means (and what it does not) [Section titled “What each metric means (and what it does not)”](#what-each-metric-means-and-what-it-does-not) * **`svc-probe` / `act-probe` (services and actions)**: the round-trip time of a framework **probe** to the endpoint: caller → router → producer → framework reply → back. The probe carries a **real-payload-sized** request and asks the producer to reply with a real-payload-sized body, so the round-trip reflects real serialization and transport. But the framework answers it **before** your handler runs, so it **excludes the handler’s own execution time** (and probing an action’s goal service **does not create a goal**). It is clock-independent (a single-clock round-trip), so it is trustworthy regardless of host or clock sync. * **`node-probe` (topic edges, synthetic table)**: a topic is fire-and-forget on the wire, so there is nothing on the topic path that can answer a probe without publishing real traffic. Instead, the topic edge’s synthetic row probes the **producer node’s always-on framework service** (`node_health`) over the same session and links the topic uses, asking for a reply sized from the **topic’s message schema**. Like the other probes it is clock-independent and no handler runs. Two honesty caveats: it rides the query path, so the topic’s QoS (priority / congestion / express) does not apply; and for a schema with variable-length fields the payload is a lower bound, so a `≥56B` probe says nothing about moving a real 6MB frame. That cost is exactly what the `delivery` row shows. * **`delivery` (topics, real-traffic table)**: the **real** producer → consumer one-way delivery latency on live traffic (`receive_time − source_time`). This is observe-only: the benchmark subscribes to the producer’s actual stream and times real messages, so for a camera it reflects the cost of moving a full frame, not a token-sized probe. It times live messages only: the messages a [retaining topic](/advanced_guides/topics/#retaining-the-latest-value) keeps are not replayed to it. It is **exact when the producer and the core node share a host**. Across hosts it depends on clock synchronization (see below). This is why the report is two tables: a one-way `delivery` row carrying a multi-megabyte frame can easily read 30× above the same edge’s `node-probe`, because the probe prices the plumbing while delivery prices the payload. Comparing across the tables tells you *where the time goes* (fixed messaging cost vs payload transfer); comparing within a table compares like with like. Services and actions have no real-traffic rows **by design**: passively timing a real service call would require real callers, and issuing one ourselves would run your handler (see [Safety](#safety-benchmarking-never-triggers-your-handlers)). ### Payload sizing [Section titled “Payload sizing”](#payload-sizing) Probe rows note the payload they measured in a `payload request → response` form (for example `payload 32B → 16B`), sized from the interface’s message schema. A `node-probe` row’s response side is sized from the **topic’s** message schema (a topic has no request leg, so its request side reads `0B`): * A `≥` prefix (e.g. `≥32B`) marks a **schema lower bound**: the format has a variable-length field (a string, bytes, or unbounded array), so the real message is at least that big. * `payload 0B → …` means the request side carries no schema fields (the probe still sends a tiny framing header on the wire). If a row adds **`(rebuild producer for sized replies)`**, the producer node never returned the requested response size, because its framework does not honor sized probe replies, so its response side wasn’t really measured. Rebuild that producer node and re-run. (The daemon and CLI versions don’t matter for this; it’s keyed off the *producer node’s* framework version.) ## Clocks and cross-host timing [Section titled “Clocks and cross-host timing”](#clocks-and-cross-host-timing) One-way **topic delivery** is the only measurement that depends on clocks: * **Same host**: `receive − source` is exact. The `clock` column reads `same-host`. * **Multiple hosts**: the two hosts’ clock offset can equal or exceed sub-millisecond latencies. The benchmark handles this in layers: * With **PTP** (gPTP / IEEE-1588) deployed on your network, the system clocks are disciplined to each other and cross-host numbers are trustworthy with no extra work, so Peppy benefits transparently. * Otherwise, the benchmark asks each producer for its measured offset to the core node (an NTP-style exchange) and **corrects** the number. The `clock` column reads `corrected`. Accuracy is roughly the LAN sync asymmetry (tens of µs to sub-ms); running NTP/chrony keeps this bounded. * If a corrected delta still comes back **negative or implausibly large**, the clocks are not adequately synchronized: the number is **suppressed** and the `clock` column reads `flagged`. Rely on the round-trip probe rows for that edge, and deploy PTP or NTP. An instance reading a simulated [clock domain](/advanced_guides/system_clock/#clock-domains) answers that exchange with its domain and an offset of zero. Both endpoints of every connection the benchmark measures read one clock, so their timestamps already sit on one timeline and are compared as they arrive. The round-trip probe rows never depend on clocks, so they are always reported. ## Safety: benchmarking never triggers your handlers [Section titled “Safety: benchmarking never triggers your handlers”](#safety-benchmarking-never-triggers-your-handlers) A benchmark message can **never** run the real handler of any topic, service, or action, by construction: * Services and actions are measured only with framework **probe** queries, which the framework auto-answers, so your service handler is never called, and probing an action’s goal service **does not create a goal** or start the action engine. The probe carries a real-payload-sized body purely to size the transport; the framework reads only its small size header to shape the reply and never decodes the body into a request or passes it to your handler. * A topic edge’s **node-probe** targets the producer node’s built-in `node_health` framework service with the same auto-answered probe queries: it **never publishes onto the topic**, so no subscriber can ever receive a synthetic message, and no user code runs on the producer. * Real topic latency is **observe-only**: the benchmark subscribes but never publishes onto a real topic. So you can safely benchmark a live, production stack without side effects. # System clock > Read the clock an instance is bound to, declare simulated clock domains in a launcher, and measure a node's offset against the core node Every instance reads one clock for its whole lifetime, and its deployment decides which. By default that is its own machine’s OS wall clock; a launch can instead put it on a [clock domain](#clock-domains), a named timeline one instance supplies. Wall time is fine on a single host. The trouble starts when two nodes need to compare timestamps. For example, matching a sensor reading to the controller command that triggered it, or merging logs from multiple machines into a single timeline. Their clocks drift independently, so “1.7 s ago” on one node no longer points to the same instant as “1.7 s ago” on another. `peppylib::clock` exposes two helpers that let any node measure the offset between its local clock and the core node’s clock: * `synchronize`: a one-shot NTP-style request/response. Returns the offset and the observed round-trip delay. * `subscribe`: a long-lived subscription to the periodic `clock` topic the core node publishes. Each `ClockTick` carries the core node’s clock at emission. They are available from Rust as `peppylib::clock::synchronize` and `peppylib::clock::subscribe`, and from Python as `from peppylib.clock import synchronize, subscribe`. Note Neither helper adjusts the local OS clock. They measure and report; aligning a timestamp is left to the caller (`local_now() + sync.offset_ns`). ## When to use each [Section titled “When to use each”](#when-to-use-each) | | `synchronize` | `subscribe` | | ------------ | ------------------------------------------------------------- | -------------------------------------------------------------- | | Pattern | Request/response | Topic subscription | | Result | Offset **and** observed RTT | Snapshot of this instance’s clock | | Staleness | Bounded by the RTT you just measured | \~one one-way network delay (uncorrected) | | Cost per use | One round trip | Passive (ticks arrive at 10 Hz) | | Use when | You need a precise offset before stamping a recorded artifact | You want continuous correlation, e.g. driving a status display | If unsure, start with `synchronize`; it gives you both numbers and you can call it once at startup. Reach for `subscribe` when you need the steady drumbeat. ## `synchronize` [Section titled “synchronize”](#synchronize) `synchronize` performs the standard NTP 4-timestamp exchange against the core node’s `clock` service: the helper stamps `t0` before sending, the core node stamps `t1` on receive and `t2` before responding, and the helper stamps `t3` on receive. It returns a `ClockSync` with three fields: * `offset_ns` (`i64` in Rust, `int` in Python): signed nanoseconds. `local + offset_ns ≈ core_node`. Negative means the local clock leads the core node. * `round_trip_delay_ns` (`u64` in Rust, `int` in Python): the round-trip delay observed on this exchange. * `raw`: the wire response with `server_recv_time` (t1), `server_send_time` (t2), and the echoed `client_send_time` (t0), exposed for callers that want to do their own analysis. Both sides of the exchange read OS wall time: the caller stamps `t0`/`t3` from its own machine’s clock, and a daemon serves the `clock` service from its machine’s clock whatever its instances read. The measurement is therefore the same one in every domain, the offset between two machines’ wall clocks. The second argument is a response timeout. Rust accepts `Option`; Python accepts `float | None` in seconds. Pass `None` (or omit it in Python) to use the default of 10 seconds. * Python src/my_node/\_\_main\_\_.py ```python import time from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib.clock import synchronize async def setup(_params: Parameters, node_runner: NodeRunner) -> None: sync = await synchronize(node_runner, response_timeout_secs=3.0) local_ns = time.time_ns() aligned_ns = local_ns + sync.offset_ns print( f"offset {sync.offset_ns} ns, RTT {sync.round_trip_delay_ns} ns; " f"local={local_ns}, aligned={aligned_ns}" ) def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::time::{Duration, SystemTime, UNIX_EPOCH}; use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::clock::synchronize; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let sync = synchronize(&node_runner, Some(Duration::from_secs(3))).await?; let local_ns = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("clock before unix epoch") .as_nanos() as i128; let aligned_ns = local_ns + sync.offset_ns as i128; println!( "offset {} ns, RTT {} ns; local={}, aligned={}", sync.offset_ns, sync.round_trip_delay_ns, local_ns, aligned_ns, ); Ok(()) }) } ``` ## `subscribe` [Section titled “subscribe”](#subscribe) `subscribe` opens a long-lived subscription to the ticks of this instance’s own clock and returns a `ClockSubscription`. On wall time that is the bound core node’s `clock` topic; on a simulated domain it is that domain’s stream, whichever machine its publisher runs on. Call `on_next_tick` in a loop to receive each tick; it returns `None` when the subscription closes (typically because the producing side went away). `subscribe` also takes a `TopicBuffer`, which says what the subscription does with the ticks you have not read yet. The subscription lives on the node’s own session. `KeepLatest` keeps the newest ticks, up to the [high-throughput buffer size](/advanced_guides/daemon_config/#zenohmanagedsubscriber_buffers-subscriber-buffer-sizes) (1024 ticks by default), and drops the oldest unread one when it is full: a reader that falls behind skips older ticks and holds up nothing. `Backpressure` waits for the reader instead, and what waits with it depends on where the ticks come from. Ticks that arrive over a connection (wall time, or a domain your node consumes) hold up every message that arrives over that connection while the subscription is full. When your node publishes its domain itself, its own publish call waits, because the node’s session hands a publish to its own subscriptions inside the publish. A clock reader usually wants the newest tick, so the examples below use `KeepLatest`. The core node publishes wall ticks at **10 Hz** (every 100 ms) by default: high enough to correlate logs across nodes, low enough not to flood the bus. The rate is set on the core node side via `CoreNodeArguments.clock_publish_interval`. A simulated domain ticks whenever its publisher publishes. Each `ClockTick` carries a single instant, read with `time()` in Rust and the `time` attribute in Python: nanoseconds on the clock it came from, stamped at emission. On wall time that is the Unix epoch; on a simulated domain it is whatever origin its publisher counts from. The value is never `0`, which is the wire’s “no tick observed yet” sentinel. Because the tick is one-way, the value is stale by roughly one one-way network delay on receipt; there is no RTT correction. Use `synchronize` if you need bounded staleness. * Python src/my_node/\_\_main\_\_.py ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppylib import TopicBuffer from peppylib.clock import subscribe async def follow_clock(node_runner: NodeRunner) -> None: sub = await subscribe(node_runner, TopicBuffer.KeepLatest) while True: tick = await sub.on_next_tick() if tick is None: # The producing side closed the subscription. return print(f"clock: {tick.time} ns") async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(follow_clock(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use peppygen::{NodeBuilder, Parameters, Result}; use peppylib::clock::subscribe; use peppylib::messaging::TopicBuffer; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { tokio::spawn(async move { let mut sub = subscribe(&node_runner, TopicBuffer::KeepLatest) .await .expect("subscribe should succeed"); while let Some(tick) = sub .on_next_tick() .await .expect("on_next_tick should not error") { println!("clock: {} ns", tick.time()); } // Subscription closed; the producing side went away. }); Ok(()) }) } ``` ## Behavior notes [Section titled “Behavior notes”](#behavior-notes) * **QoS profile is `SensorData`.** On a congested link the transport drops ticks rather than holding up the publisher: a clock value the network could not deliver fresh is not worth delivering late. Ticks that reach the node and wait unread follow the subscription’s buffer: a `KeepLatest` subscription drops its oldest unread tick when it is full, and a `Backpressure` subscription keeps every tick and holds up the connection the ticks arrive over, or the node’s own publish when the node publishes its domain. * **`synchronize` is hardened against a misbehaving server.** Offset and delay are computed in widened arithmetic and saturated when narrowed back to `i64` / `u64`, so a peer returning extreme `t1`/`t2` cannot wrap the result or flip its sign. * **`on_next_tick` returning `None` is terminal.** Treat it as “the producing side went away” and rebuild the subscription if you need to keep listening. * **Default timeout for `synchronize` is 10 seconds.** Pass an explicit timeout from latency-sensitive paths so a slow or unreachable core node does not stall your node. ## Clock domains [Section titled “Clock domains”](#clock-domains) A **clock domain** is one timeline with a name. `wall` is built in and is the time every machine already keeps. A simulated domain is supplied by one instance, which publishes the instants every other instance bound to it reads, so a simulator or a bag replay drives the same node binaries a physical robot drives. One daemon hosts wall time and any number of simulated domains at once, and the launch decides which: running a simulation beside a physical robot is a matter of launching it. ### Declaring a domain [Section titled “Declaring a domain”](#declaring-a-domain) A launcher, or a fragment it selects, names its domains in a root-level `framework` block: simulated_robot.json5 ```json5 // Two timelines in one launch: the simulation the robot runs in, and the // wall clock the operator's panel reads. `peppy clock list` shows both once // the launch is up. { peppy_schema: "launcher/v1", description: ["An OpenArm in the Waldo simulation, with a recorder of its episodes and an operator panel that reads the wall clock. It needs a machine that runs the simulation."], // The clock domains this launch declares. `simulation` is supplied by one // instance, and naming that instance here is what makes it the publisher. // `operator_station` is a name for the time every machine already keeps. framework: { clocks: { simulation: { publisher: "simulation_inst" }, operator_station: "wall", }, }, deployments: [ { // The publisher carries no `framework.clock` of its own: the // declaration above already assigns it `simulation`. source: { name: "waldo", tag: "v1" }, instances: [{ instance_id: "simulation_inst" }], }, { source: { name: "openarm_sim_arm", tag: "v1" }, instances: [ { instance_id: "arm_inst", framework: { clock: "simulation" }, links: { simulation: "simulation_inst" }, }, ], }, { // Both ends of a binding read one clock, so the recorder that stamps // the arm's episodes runs on the simulation too. source: { name: "session_recorder", tag: "v1" }, instances: [ { instance_id: "recorder_inst", framework: { clock: "simulation" }, links: { arm: "arm_inst" }, }, ], }, { // The operator's panel reads wall time. It holds no clock-dependent // connection to the simulated instances. source: { name: "web_viewer", tag: "v1" }, instances: [ { instance_id: "viewer_inst", framework: { clock: "operator_station" } }, ], }, ], } ``` A declaration takes one of two forms: * `{ publisher: "" }` is a simulated domain. Naming the instance is what assigns it the domain and the publisher role together, so the declaration is the one place that instance’s clock is written, and one instance supplies at most one domain. The publisher must be an instance the launch deploys. * `"wall"` is a name for the time every machine already keeps. Two such names are aliases of one timeline, which is how a launcher gives wall time a name that says what reads it. `wall` itself cannot be declared: it is built in, and every instance can name it directly. ### Binding an instance to a domain [Section titled “Binding an instance to a domain”](#binding-an-instance-to-a-domain) Any instance in a `deployments` entry names the domain it reads: ```json5 { instance_id: "backbone_inst", framework: { clock: "simulation" } }, ``` An instance that omits `framework.clock` reads wall time. Naming a domain the launch does not declare is refused, naming the instance, the clock and the domains that do exist: ```plaintext instance `backbone_inst` binds clock `sim`, which no `framework.clocks` entry declares. Declare it, or name one of `wall`, `operator_station`, `simulation` ``` An [adjustment](/guides/launch_files/#adjustments) binds an instance a fragment deploys, written in the launcher under the option that selects the fragment, which is how one commander fragment serves a physical robot and a simulated one: ```json5 options: { openarm_sim: { fragments: ["openarm/fragments/openarm_sim.json5"], adjustments: [ { target: "commander_inst", set_framework: { clock: "simulation" } }, ], }, }, ``` An instance the fragment deploys itself declares its own clock where it is written, so only the instances a launcher shares between a physical robot and a simulated one need this. ### Composing declarations [Section titled “Composing declarations”](#composing-declarations) A launch’s domains are the root launcher’s and every selected fragment’s, merged. Two documents may declare one domain, and identical declarations agree: a robot fragment and the simulation it runs in can both name the same timeline. Two different declarations of one name are refused, naming both documents. A fragment the selection leaves out contributes nothing. [Copies](/guides/launch_files/#copies) bind the domains the stack declares, naming them exactly as the stack does, and a copy’s adjustments write those bindings onto the instances it mints. A copy that also writes to a stack instance must write what already runs there, its clock included. ### Reading the clock in a node [Section titled “Reading the clock in a node”](#reading-the-clock-in-a-node) Hot-path code reads whichever clock the instance was bound to through the generated clock module: `peppygen::clock` in Rust, `peppygen.clock` in Python. * `init(node_runner)`: async; a consumer opens its domain’s subscription here, so the first `now_ns` after a tick lands returns without setup latency. Idempotent per node: repeat calls for the same node are no-ops, and initializing a different node rebinds (how consecutive test-harness boots in one process each read their own clock). Call it once at the top of your setup function. * `now_ns()`: sync; reads the current time on this instance’s clock. A wall instance reads its machine’s OS clock. A consumer reads the last instant its domain published, and returns `Err(PeppyError::ClockNotReady)` (Rust) or raises `RuntimeError` (Python) until the first one lands. A publisher reads back the instant it last committed. - Python src/my_node/\_\_main\_\_.py ```python from peppygen import NodeBuilder, NodeRunner, clock from peppygen.parameters import Parameters async def setup(_params: Parameters, node_runner: NodeRunner) -> None: # Idempotent. On a simulated domain this opens the subscription so # the background feeder is already running before `now_ns()` is # called below. await clock.init(node_runner) try: # A wall instance always returns its machine's OS time. A # consumer raises RuntimeError until its domain's first tick. now = clock.now_ns() print(f"now: {now} ns") except RuntimeError: # Reachable on a simulated domain before its first tick. Real # apps retry or wait on a tick. print("clock not ready yet") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` - Rust src/main.rs ```rust use peppygen::{NodeBuilder, NodeRunner, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // Idempotent. On a simulated domain this opens the subscription // so the background feeder is already running before `now_ns()` // is called below. peppygen::clock::init(&node_runner).await?; match peppygen::clock::now_ns() { // A wall instance always lands here. A consumer reaches this // arm once its domain has published an instant. Ok(t) => println!("now: {t} ns"), // Reachable on a simulated domain before its first tick. // Real apps retry or wait on a tick. Err(e) => println!("clock not ready yet: {e}"), } Ok(()) }) } ``` Prefer `synchronize` over the generated module when you need a bounded-staleness offset, since it observes a round trip and reports the RTT. `subscribe` is the right pick if you want every raw tick. ### Publishing a domain [Section titled “Publishing a domain”](#publishing-a-domain) The instance a declaration names as `publisher` supplies its domain’s time. `ClockPublisher::for_node` returns `Some` (Rust) or the publisher (Python) exactly on that instance, and `None` everywhere else, so holding a publisher IS being one and a node that may or may not be a source branches on this one call. `domain` names the domain it supplies, and each `publish` commits the instant locally and sends one tick. * Python src/my_simulator/\_\_main\_\_.py ```python import asyncio from peppylib.clock import ClockPublisher async def setup(_params, node_runner) -> None: # None unless this deployment named the instance a domain's # publisher. Build it once and keep the handle. engine.clock_publisher = await ClockPublisher.for_node(node_runner) if engine.clock_publisher is None: return print(f"supplying clock {engine.clock_publisher.domain}") # Called from the engine's step callback. `publish` is async, so an engine # running its physics on its own thread schedules it onto the node loop # rather than awaiting it there. def on_step(engine) -> None: if engine.clock_publisher is None: return loop.call_soon_threadsafe( lambda: asyncio.ensure_future( engine.clock_publisher.publish(engine.time_ns()) ) ) ``` * Rust src/main.rs ```rust use peppylib::clock::ClockPublisher; // None unless this deployment named the instance a domain's publisher. // Build it once and keep the handle. if let Some(publisher) = ClockPublisher::for_node(&node_runner).await? { println!("supplying clock {}", publisher.domain()); // Then publish the engine's own clock from each step. Every instance // bound to the domain reads this instant, wherever it runs. loop { engine.step(); publisher.publish(engine.time_ns()).await?; } } ``` `publish` commits the instant before it sends it, so the publisher’s own `now_ns()` reports the instant it is publishing and can stamp the very data it emits for that step. How often a publisher publishes is how finely its domain can be read: `now_ns` returns the last tick, so a publisher ticking at 100 Hz gives every reader a 10 ms grid. Publish on the cadence the readers compare against, not on the physics step, which is usually far finer than anything reads. ### What makes two clocks the same [Section titled “What makes two clocks the same”](#what-makes-two-clocks-the-same) A domain is identified by three things: its name, the machine hosting its publisher, and an **incarnation** minted for each lifetime of that name. Written out, a domain reads `simulation@cn-sim`. Two domains are the same timeline only when all three agree, so a `simulation` on one machine and a `simulation` on another are two timelines, and relaunching under the same name is a third: anything still reading the previous lifetime keeps reading it, frozen at its last tick. You never type an incarnation; it is minted for you and shows up in `peppy clock list --json`. ### Every connection reads one clock [Section titled “Every connection reads one clock”](#every-connection-reads-one-clock) Producer bindings, pairings and observations all carry timestamps one side stamps and the other interprets, so each of them joins two instances that read the same clock. Two aliases of wall time are one timeline and connect freely. Two simulated domains never are, however closely their instants happen to run. A launch checks this before anything starts, and names both endpoints and both clocks: ```plaintext `viewer_inst` reads clock wall and `arm_inst` reads simulation@cn-sim, so their binding `camera` would carry timestamps neither side can read on its own clock. Bind both instances to one domain, or give each domain its own instance of the node ``` `peppy stack resolve` runs the same check with no daemon, and a `peppy node run` that links a new instance to running ones is held to it too. ### On the command line [Section titled “On the command line”](#on-the-command-line) `peppy node run` puts one instance on a clock, which is how a domain is driven outside a launcher: ```sh # Start the simulation as a new domain's publisher. peppy node run waldo:v1 -i simulation_inst --publish-clock simulation # Start a consumer on it. `peppy clock list` shows what is running. peppy node run openarm_sim_arm:v1 -i arm_inst --clock simulation # Qualify the name when one name runs on several machines. peppy node run openarm_sim_arm:v1 -i arm_inst --clock simulation@cn-sim ``` `--clock` takes `wall`, a short name, or a qualified `name@core_node`, and names a domain that is already running: an unknown name is refused, pointing at `peppy clock list`, at `--publish-clock`, and at `peppy stack list` for a publisher that is restarting, and a short name that is ambiguous across machines is refused listing the qualified names to pick from. `--publish-clock` declares a domain and mints its lifetime on the daemon the command targets. The two flags conflict, and both are also accepted by `peppy node add --run`. `peppy clock list` prints every domain the federation is running, gathered from the daemons that host them: ```plaintext $ peppy clock list ┌───────────────────┬───────────┬─────────────────┬────────────────────────────────────┬───────┬───────────┐ │ CLOCK │ SOURCE │ PUBLISHER │ OWNER │ READY │ CONSUMERS │ ├───────────────────┼───────────┼─────────────────┼────────────────────────────────────┼───────┼───────────┤ │ wall │ built-in │ - │ - │ ready │ - │ │ simulation@cn-sim │ simulated │ simulation_inst │ launch launch-brave-otter (cn-sim) │ ready │ 3 │ └───────────────────┴───────────┴─────────────────┴────────────────────────────────────┴───────┴───────────┘ ``` `OWNER` is the launch that started the publisher, or `peppy node run` for a domain a command declared. `READY` reads `waiting` until the domain’s first tick reaches its host and `ready` afterwards, so a publisher that has yet to publish is visible beside the instance supplying it. `CONSUMERS` counts the instances reading the domain anywhere in the federation. `--json` prints the same listing with each domain’s `name`, `core_node`, `incarnation`, `last_tick_ns` and the `instance@core_node` of every consumer. Two more commands report what each instance reads: `peppy stack list` carries a `CLOCK` column per instance, showing `wall` or the domain as `name@core_node`, and `peppy stack resolve` reports the clock and the restart policy of every instance of a plan before anything runs, once this machine’s nodes cache holds the plan’s manifests (`peppy repo refresh`): ```plaintext simulation_inst: publishes clock `simulation`, restart on_failure (default) arm_inst: clock `simulation`, restart on_failure (default) viewer_inst: clock `wall`, restart on_failure (default) ``` A launch names each domain and its publisher in its feedback as it starts: ```plaintext instance `simulation_inst` publishes clock `simulation` (simulation@cn-sim) ``` ### Lifetime, replacement and removal [Section titled “Lifetime, replacement and removal”](#lifetime-replacement-and-removal) `peppy stack launch` mints a fresh lifetime for every domain it declares, so relaunching a stack under the same names produces new timelines, exactly as it produces new instances. `peppy stack join` follows the domains the stack is already publishing, and the machines supplying the clocks a copy reads take part in the join. `peppy stack remove` takes a domain’s lifetime out with the instance that supplied it, and refuses while anything still reads it: ```plaintext `alpha` supplies clock `simulation` to copies `bravo`; remove them first ``` ```plaintext `alpha` supplies clock `simulation` to `backbone_inst` and to copies `bravo`; run peppy stack reset, then launch without `alpha`: drop its deployments entry from the launcher, or leave it out of the copies you join ``` Stopping a publisher freezes its domain: the instances bound to it keep reading the last instant it committed. A domain is listed for as long as the instance supplying it is live, so a publisher that stops or crashes takes its domain out of `peppy clock list` while the instances bound to it hold that instant. A publisher that is stopped, or that ends `finished` or `failed`, frees the name for a replacement publisher to declare it again. A publisher that its [restart policy](/guides/launch_files/#restart-policy) starts again keeps its domain. Through the wait the domain is absent from `peppy clock list` and its name stays taken, so a publisher declared under it meanwhile is refused; the instances bound to it hold the last instant, then read the new process’s ticks. Time on the domain is whatever the new process publishes, so a simulator that starts its time over at zero takes its readers’ time back with it. On the publisher’s machine, an instance reading the domain does not start again while its publisher waits for its own restart: each attempt in that wait fails and counts toward its `max_restarts`, and the instance runs at its first attempt after the publisher starts. A first start of an instance reading the domain in that wait is refused: `peppy node run --clock` finds no such domain and says to run again once the publisher `peppy stack list` shows `restarting` is running, and a join names the publisher to wait for. A reader that exits after its publisher was stopped, or ended `finished` or `failed` with no restart to come, is refused its restart and stays `failed`; its stack log line names the ended domain and what publishes its name now, and [Starting a failed instance again](/guides/launch_files/#starting-a-failed-instance-again) says how to start it again. An instance reading the domain from another machine starts again after its own wait, whatever its publisher’s state: it reads the domain once its publisher publishes, and reads no instant while the publisher waits, or at all once it was stopped, until a relaunch of the stack brings both back. ### Domains across machines [Section titled “Domains across machines”](#domains-across-machines) A publisher and the instances reading it may sit on different machines. The domain’s ticks ride the `clock` topic of the machine hosting the publisher, under a key carrying the domain’s name and incarnation, and a consumer addresses that whole identity, so it reads the same timeline wherever the launch places it. Placement decides one thing about a domain: the machine in its identity, which is where its publisher landed. See [Federation](/advanced_guides/federation/). # Testing > Test a node without standing up its real dependencies: generated typed mocks and an in-process harness over the real wire, with deterministic readiness and no sleeps A node is rarely testable on its own: it consumes topics, polls services, and fires actions against dependency nodes that a unit test has no business standing up. `peppy node sync` therefore generates a **test surface** alongside the production bindings: typed **mocks** that play each dependency slot over the real wire, and a **harness** that boots your node in-process against them. The tests this enables are not simulations of the messaging layer. The mocks publish real Cap’n Proto payloads through a real (ephemeral, per-test) Zenoh router, the node runs its real `setup` against its real generated bindings, and services and actions run on the same engines a production producer uses. What you save is everything else: no daemon, no stack, no dependency binaries, and no sleeps, because every step of the boot is gated on a deterministic readiness barrier rather than a timer. ## What sync generates [Section titled “What sync generates”](#what-sync-generates) After `peppy node sync`, two module trees sit next to the production bindings, regenerated on every sync: * `peppygen.mock` (Python) / `peppygen::mock` (Rust) provides one module per dependency, pairing, and observer slot, named by `link_id` and grouped by namespace: `mock.deps.`, `mock.pairings.`, `mock.observed.`. Each holds a `Mock` with one typed sub-surface per interface the slot carries, named after the interface. An interface whose name the `Mock` uses for itself (`start`, `stop`, `session`, `router`, `instance_id`, `node_instance_id`, `self`, `cls`) is reached as `_`: the `stop` service of a `limb_motion` slot is `mocks.deps.limb_motion.limb_motion_stop`, beside the mock’s own `stop()`. * `peppygen.fixtures` (Python) / `peppygen::fixtures` (Rust) provides the harness (`fixtures.harness`), plus typed observation of the node’s **own** surface: `fixtures.emitted_topics.`, `fixtures.exposed_services.`, `fixtures.exposed_actions.`. Neither tree can leak into a production build: * In Rust, the modules compile only under peppygen’s `testing` feature, and sync enables that feature from the node’s **dev-dependencies**: ```toml [dev-dependencies] peppygen = { path = ".peppy/libs/peppygen", features = ["testing"] } ``` `cargo build` never resolves dev-dependencies, so `cargo test` is the only place the test surfaces exist; production binaries cannot reach them even by accident. Sync writes and maintains this entry for you. * In Python, the `mock` and `fixtures` packages ship inert: `peppygen/__init__.py` never imports them, so nothing loads unless a test file imports them explicitly. ### The lib/main split [Section titled “The lib/main split”](#the-libmain-split) The harness boots your node by calling its `setup` function directly, so `setup` must be importable from test code. `peppy node init` scaffolds this from the start: * **Python** already has it: `setup` lives in `src//__main__.py`, importable as `from .__main__ import setup`. * **Rust** gets a lib/main split: `src/lib.rs` holds `pub async fn setup(...)`, and `src/main.rs` only delegates: ```rust fn main() -> peppygen::Result<()> { peppygen::NodeBuilder::new().run(my_node::setup) } ``` `init` also scaffolds a smoke test (`tests/smoke.rs` / `tests/test_smoke.py`) that boots the node through the harness and shuts it down cleanly, plus, for Python, a `dev` dependency group carrying `pytest` and `pytest-asyncio` with `asyncio_mode = "auto"`. ## A first test [Section titled “A first test”](#a-first-test) The [`hello_receiver`](/guides/communication/#consumed-interfaces) node consumes one topic, `message_stream`, from its `hello_world_param` dependency slot. Its node code: * Python src/hello_receiver/\_\_main\_\_.py ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.consumed_topics.hello_world_param import message_stream from peppygen.parameters import Parameters async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(receive_messages(node_runner))] async def receive_messages(node_runner: NodeRunner): # Subscribe once; the held subscription buffers every message in order, so # iterating never drops a message published between iterations. subscription = await message_stream.subscribe(node_runner) async for producer, message in subscription: print(f"Received from {producer.instance_id}: {message.message}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/lib.rs ```rust use std::sync::Arc; use peppygen::consumed_topics::hello_world_param::message_stream; use peppygen::{NodeRunner, Parameters, Result}; /// The node's entry point. It lives in the library crate so tests can import /// it: the generated test harness (`peppygen::fixtures::harness::Harness`) /// boots it in-process, and `main.rs` delegates here for production runs. pub async fn setup(_params: Parameters, node_runner: Arc) -> Result<()> { tokio::spawn(receive_messages(node_runner)); Ok(()) } async fn receive_messages(node_runner: Arc) { // Subscribe once; the held subscription buffers every message in order, so // looping on `next` never drops a message published between iterations. let mut subscription = match message_stream::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe: {e}"); return; } }; loop { match subscription.next().await { Ok(Some((producer, message))) => { println!("Received from {}: {}", producer.instance_id, message.message) } Ok(None) => break, Err(e) => { eprintln!("Error receiving message: {e}"); break; } } } } ``` And its complete test, runnable with `cargo test` / `uv run --group dev pytest` with nothing else running on the machine: * Python tests/test_hello.py ```python """Boots `hello_receiver` in-process under the generated test harness and drives one message through its consumed topic from the mocked producer: no daemon, no real `hello_world_param` node, and no sleeps.""" from peppygen.consumed_topics.hello_world_param import message_stream from peppygen.fixtures import harness from hello_receiver.__main__ import setup async def test_receives_a_message_from_the_mocked_producer(): async with harness.start(setup) as h: # The first publish waits for the node's subscription to match before # delivering, so this is deterministic: a return means the node # received the message, and no subscriber within the readiness # timeout is a loud error instead of a silent drop. await h.mocks.deps.hello_world_param.message_stream.publish( message_stream.Message(message="hello from the mock") ) # The matched subscription is opened by the task `setup` spawned, # and that task cannot run before `setup` returned: a returned # publish proves the node's setup finished. assert h.setup_finished() ``` * Rust tests/hello.rs ```rust //! Boots `hello_receiver` in-process under the generated test harness and //! drives one message through its consumed topic from the mocked producer: //! no daemon, no real `hello_world_param` node, and no sleeps. use peppygen::fixtures::harness::Harness; use peppygen::mock::deps::hello_world_param::message_stream; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn receives_a_message_from_the_mocked_producer() { let (harness, mocks) = Harness::start(hello_receiver::setup) .await .expect("the harness should boot the node"); // The first publish waits for the node's subscription to match before // delivering, so this is deterministic: an `Ok` means the node received // the message, and no subscriber within the readiness timeout is a loud // error instead of a silent drop. mocks .deps .hello_world_param .message_stream .publish(&message_stream::Message { message: "hello from the mock".to_string(), }) .await .expect("the node's subscription should receive the message"); // The matched subscription is opened by the task `setup` spawned, and // that task cannot run before `setup` returned: a returned publish // proves the node's setup finished. assert!( harness.setup_finished(), "the matched publish proves setup returned" ); harness .shutdown() .await .expect("the node should shut down cleanly"); } ``` Note what is absent: no `hello_world_param` process, no daemon, no launcher, and no sleep before the publish. The mock’s first publish waits for the node’s subscription to become visible on the router, so “the node is ready” is observed, never assumed. Even the assertion is deterministic, not a hope: the publish can only return once the node’s subscription matched, that subscription is opened by the task `setup` spawns, and that task cannot run before `setup` returned. A returned publish therefore proves `setup` finished, which is exactly what `setup_finished()` asserts. (For a node whose `setup` itself loops forever, `setup_finished()` stays `false` by design; assert on the surfaces instead.) ## The harness lifecycle [Section titled “The harness lifecycle”](#the-harness-lifecycle) `start` takes your `setup` function, the exact shape `NodeBuilder().run` takes, and returns with the node running: * Python ```python from peppygen.fixtures import harness from my_node.__main__ import setup async def test_something(): # As a context manager, shutdown runs even when the test body fails: async with harness.start(setup) as h: assert h.instance_id # the generated unique id ... # drive the node; assert on the mocks and h.emitted # Or awaited directly, with an explicit shutdown: h = await harness.start(setup) ... await h.shutdown() ``` * Rust ```rust use peppygen::fixtures::harness::Harness; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_something() -> peppygen::Result<()> { let (mut harness, mut mocks) = Harness::start(my_node::setup).await?; assert!(harness.instance_id().starts_with("test-")); // ... drive the node through `mocks` / `harness.emitted`, asserting as you go ... harness.shutdown().await?; Ok(()) } ``` By the time `start` returns, all of the following happened, in order: 1. **An ephemeral Zenoh router started** on a free port, private to this harness. Every test gets its own router and shares no messaging state with any other test. Routers within one test binary are serialized by a process-wide guard (running several peer meshes at once makes gossip discovery flaky), so parallel tests queue on `start` instead of contending. 2. **One mock started per link** (dependency, pairing, and observer slots alike; a `zero_or_more` slot starts none by default, see [Configuration](#configuration)), each on its own messaging session, with every publisher, service queryable, and action engine declared up front. In Rust the started mocks come back as the second element of the `start` tuple (`mocks.deps.`, `mocks.pairings.`, `mocks.observed.`); in Python they hang off the harness as `h.mocks.deps.` and so on. 3. **The harness subscribed to every topic the node emits**, before the node booted, so even the very first message your setup publishes is captured. 4. **A standalone configuration was seeded** so the node boots exactly as if a launcher had wired it: the router’s address, a unique instance id, your parameters, and, per slot, a bound producer, peer pin, or observed source pointing at the matching mock’s wire identity. 5. **Readiness barriers passed**: the harness’s subscriptions to the node’s emitted topics are visible from the node’s session, and every mock service and action answers a reachability probe. Only then does the node’s `setup` run, so a setup that immediately polls a dependency service cannot race the mock’s declaration. `shutdown` tears down in lifecycle order: it cancels the node and awaits its convergence (a `setup` that returned an error propagates that error out of `shutdown`, and [shutdown hooks](/advanced_guides/shutdown/) run, bounded exactly as in production), then closes the observation session and the mocks, then stops the router. In Python the `async with` form calls it for you; in Rust, dropping the harness without calling `shutdown` still cancels and aborts the node, but skips the error propagation and the shutdown hooks, so tests should end with `harness.shutdown().await`. That propagation is itself a plain assertion: `start` returns normally even when `setup` is doomed, because `setup` has only been spawned; the error surfaces out of `shutdown` instead. * Python ```python import pytest from peppygen.fixtures import harness async def broken_setup(_params, _node_runner): raise RuntimeError("hardware missing") async def test_a_failing_setup_fails_through_shutdown(): h = await harness.start(broken_setup) # returns normally with pytest.raises(RuntimeError, match="hardware missing"): await h.shutdown() ``` * Rust ```rust use peppygen::fixtures::harness::Harness; async fn broken_setup( _parameters: peppygen::Parameters, _node_runner: std::sync::Arc, ) -> peppygen::Result<()> { Err(peppygen::Error::Io(std::io::Error::other("hardware missing"))) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_failing_setup_fails_through_shutdown() { let (harness, _mocks) = Harness::start(broken_setup).await.unwrap(); // normal let error = harness.shutdown().await.expect_err("the setup error surfaces here"); assert!(error.to_string().contains("hardware missing")); } ``` The harness also exposes the running node directly: `node_runner()` (`h.node_runner`) for calling its runtime surface in-process, `instance_id()` (`h.instance_id`) for the generated instance id, `setup_finished()` to ask whether `setup` has returned, and `session()` (`h.session`), the fixture caller/observer session the `fixtures` callers drive the node through. Under the harness, the node reads the [setup budget](/guides/node_stack/#how-an-instance-starts) of its manifest (`setup_timeout()` in Rust, `setup_timeout_secs()` in Python), as it does under a daemon that applies that budget; the harness itself does not stop a setup at the end of the budget. ## Driving each surface [Section titled “Driving each surface”](#driving-each-surface) The sections below use one example node: it consumes a `video_stream` topic and an `enable_camera` service from a `camera` slot, a `plan_motion` action from a `brain` slot, participates in an `arm` pairing (emits `joint_commands`, consumes `joint_states`), observes the same pairing through an `observed_arm` observer slot, and exposes a `status` emitted topic, a `ping` service, and a `move_arm` action of its own. Every fragment in the rest of this page is the body of a test with the harness running as [the lifecycle](#the-harness-lifecycle) starts it: `h` in Python (`async with harness.start(setup) as h:`), `harness` and `mocks` in Rust (`let (mut harness, mut mocks) = Harness::start(setup).await?;`). The `assert`s and `?`s land where they would in that test. ### Consumed topics [Section titled “Consumed topics”](#consumed-topics) Each consumed topic gets a typed publisher on the slot’s mock. Messages are the same generated `Message` type the node’s subscription yields: * Python ```python from peppygen.consumed_topics.camera import video_stream # Wait for the node's subscription alone; the publish below then skips # its own lazy wait: assert await h.mocks.deps.camera.video_stream.wait_for_subscriber(10.0) await h.mocks.deps.camera.video_stream.publish( video_stream.Message(width=640, frame=b"\x01\x02") ) ``` * Rust ```rust use peppygen::mock::deps::camera::video_stream; use std::time::Duration; // Wait for the node's subscription alone; the publish below then skips // its own lazy wait: assert!( mocks .deps .camera .video_stream .wait_for_subscriber(Duration::from_secs(10)) .await? ); mocks .deps .camera .video_stream .publish(&video_stream::Message { width: 640, frame: vec![1, 2] }) .await?; ``` The first `publish` lazily waits for the node’s subscription to match before delivering, so the first message is never lost to a subscribe race, and a node that never subscribes turns the publish into a loud error after the readiness timeout (10 seconds) rather than a silent drop. To separate “the node is subscribed” from “deliver now”, `wait_for_subscriber(timeout)` waits for the match alone and returns whether it happened. ### Consumed services [Section titled “Consumed services”](#consumed-services) Each consumed service gets a typed mock server. A background pump captures every inbound request, and you answer them in one of two modes: **Manual**: `next_request` parks until the node polls, then hands you the decoded request and a one-shot responder: * Python ```python from peppygen.consumed_services.camera import enable_camera request, responder = await h.mocks.deps.camera.enable_camera.next_request(10.0) assert request.enable await responder.respond(enable_camera.ResponseData(enabled=True)) # or: await responder.respond_failure( # enable_camera.FailureKind.RESOURCE_UNAVAILABLE, "hardware fault" # ) ``` * Rust ```rust use peppygen::mock::deps::camera::enable_camera; use std::time::Duration; let (request, responder) = mocks .deps .camera .enable_camera .next_request(Duration::from_secs(10)) .await?; assert!(request.enable); responder.respond(enable_camera::ResponseData::new(true)).await?; // or: responder // .respond_failure(enable_camera::FailureKind::ResourceUnavailable, "hardware fault") // .await?; ``` **Scripted**: `enqueue_response` queues typed responses served automatically, FIFO, to the next inbound requests. Only unscripted requests park for `next_request`, so a test that does not care about per-request choreography scripts the answers up front and asserts afterwards: * Python ```python h.mocks.deps.camera.enable_camera.enqueue_response( enable_camera.ResponseData(enabled=True) ) # ... let the node run ... requests = h.mocks.deps.camera.enable_camera.captured() assert [r.enable for r in requests] == [True] ``` * Rust ```rust mocks .deps .camera .enable_camera .enqueue_response(enable_camera::ResponseData::new(true))?; // ... let the node run ... let requests = mocks.deps.camera.enable_camera.captured()?; assert_eq!(requests.len(), 1); ``` `respond_failure` answers with an [error reply](/advanced_guides/services/#error-replies): a failure kind of the service (a kind of peppy, or a kind of the contract of the slot) and a message. The node’s generated `poll` reads it as the typed `Failure` of the service, so the test drives the node’s failure branches with the kinds a real producer gives. `captured()` decodes every request received so far, scripted and manual alike, in arrival order, so both modes leave a complete audit trail. A mock torn down with parked requests, or with scripted responses the node never consumed, reports them loudly at teardown, so a call the test forgot to answer cannot pass silently. ### Consumed actions [Section titled “Consumed actions”](#consumed-actions) Each consumed action gets a mock server on the real action engine, so the goal lifecycle is exactly the production one. The test plays the producer’s side of it: receive the goal, admit it, feed it, finish it. * Python ```python from peppygen.consumed_actions.brain import plan_motion pending = await h.mocks.deps.brain.plan_motion.next_goal(10.0) assert pending.request.arm_id == 7 active = await pending.accept(plan_motion.GoalResponseData(planner="rrt")) # or: await pending.refuse(plan_motion.FailureKind.REJECTED, "busy") await active.publish_feedback(plan_motion.FeedbackMessage(progress=0.5)) await active.complete(plan_motion.ResultResponseData(waypoint_count=12)) # or: await active.fail(plan_motion.FailureKind.ATTEMPT_FAILED, "no plan") ``` * Rust ```rust use peppygen::mock::deps::brain::plan_motion; use std::time::Duration; let pending = mocks .deps .brain .plan_motion .next_goal(Duration::from_secs(10)) .await?; assert_eq!(pending.request.arm_id, 7); let active = pending .accept(plan_motion::GoalResponseData::new("rrt".to_owned())) .await?; // or: pending.refuse(plan_motion::FailureKind::Rejected, "busy").await?; active.publish_feedback(&plan_motion::FeedbackMessage { progress: 0.5 }).await?; active.complete(&plan_motion::ResultResponseData::new(12)).await?; // or: active.fail(plan_motion::FailureKind::AttemptFailed, "no plan").await?; ``` `next_goal` parks until the node fires a goal (bounded by the timeout) and returns it with the decoded `request`. `refuse(kind, message)` refuses it with a [failure kind](/advanced_guides/actions/#how-a-goal-ends) of the action; `accept` returns the active goal handle. From there `publish_feedback` streams typed feedback, and `complete`, `fail(kind, message)` and `complete_cancelled(reason, ...)` end the goal. The node’s generated client reads a refusal and a failure as the typed `Failure` of the action, and a cancelled goal with its reason. To test your node’s cancellation path, await `cancel_signal()` on the active goal (it resolves when the node requests cancellation, or when the node is gone), read why with `cancel_cause()` (in Python, `cancel_reason()` gives the reason of that cause in words), then answer with `complete_cancelled`. `is_cancelled()` polls the same state non-blocking. ### Pairing peers [Section titled “Pairing peers”](#pairing-peers) A [pairing](/advanced_guides/pairing/) slot’s mock is a peer: it publishes the topics your node consumes on the slot and subscribes to the topics your node emits on it, pinned to your node’s identity exactly as a real paired peer would be. The harness seeds the peer pin, so from the node’s point of view the pairing is established at boot: `paired()` / `wait_paired()` resolve immediately to the mock’s identity, exposed as `peer_info()` on the mock module. * Python ```python from peppygen.mock.pairings import arm as mock_arm from peppygen.paired_topics.arm import joint_states # What the node's paired() resolves to under the harness. assert mock_arm.peer_info().peer_link_id == mock_arm.PEER_LINK_ID # The direction the node consumes: publish as the peer. await h.mocks.pairings.arm.joint_states.publish( joint_states.Message(positions=[0.0, 0.5, 1.0]) ) # The direction the node emits: receive as the peer. command = await h.mocks.pairings.arm.joint_commands.next() assert command.max_velocity == 0.5 ``` * Rust ```rust use peppygen::mock::pairings::arm as mock_arm; use peppygen::paired_topics::arm::joint_states; // What the node's paired() resolves to under the harness. assert_eq!(mock_arm::peer_info().peer_link_id, mock_arm::PEER_LINK_ID); // The direction the node consumes: publish as the peer. mocks .pairings .arm .joint_states .publish(&joint_states::Message { positions: [0.0, 0.5, 1.0] }) .await?; // The direction the node emits: receive as the peer. let command = mocks .pairings .arm .joint_commands .next() .await? .expect("pairing subscription should be open"); assert!((command.max_velocity - 0.5).abs() < f64::EPSILON); ``` Both directions carry the pairing’s deterministic delivery guarantees: the consuming direction’s first publish waits for the node’s pinned subscription, and the emitting direction’s subscription was opened before the node booted. The mock’s subscriptions keep the newest messages your test has not read, as the [emitted topic subscriptions](#emitted-topics) do, so a test can leave them unread without holding up the mock’s session. A [multi slot](/advanced_guides/pairing/#pairing-with-several-peers-through-one-slot) gets one mock per member, delivered as a list in the order the configuration names them, each under its own instance id and the copy the configuration put it in; `peer_info_for(instance_id)` is the `info` the node’s `peers()` lists for that member. The node’s `publish_to` reaches the one mock it names: * Python ```python async with harness.start( setup, limbs_members={"left": "robot_a", "right": "robot_b"} ) as h: left, right = h.mocks.pairings.limbs command = await left.joint_commands.next() ``` * Rust ```rust use peppygen::fixtures::harness::{Config, Harness, PeerMemberSpec}; let config = Config { limbs_members: vec![ PeerMemberSpec { instance_id: "left".into(), copy: Some("robot_a".into()) }, PeerMemberSpec { instance_id: "right".into(), copy: Some("robot_b".into()) }, ], ..Config::default() }; let (mut harness, mut mocks) = Harness::start_with(config, my_node::setup).await?; let command = mocks.pairings.limbs[0].joint_commands.next().await?; ``` ### Observed sources [Section titled “Observed sources”](#observed-sources) An [observer slot](/advanced_guides/pairing/#observing-several-pairings-through-one-slot)’s mock is a source: it publishes the observed topics under the identity the harness seeded into the slot, so the node’s `source()` / `sources()` accessor and observation subscription see it as a live member. * Python ```python from peppygen.mock.observed import observed_arm as mock_arm from peppygen.paired_topics.observed_arm import joint_states # The node's source() resolves to the mock's seeded identity: assert joint_states.source(h.node_runner) == mock_arm.source() await h.mocks.observed.observed_arm.joint_states.publish( joint_states.Message(positions=[0.0, 0.5, 1.0]) ) ``` * Rust ```rust use peppygen::mock::observed::observed_arm as mock_arm; use peppygen::paired_topics::observed_arm::joint_states; // The node's source() resolves to the mock's seeded identity: assert_eq!( joint_states::source(harness.node_runner())?, mock_arm::source() ); mocks .observed .observed_arm .joint_states .publish(&joint_states::Message { positions: [0.0, 0.5, 1.0] }) .await?; ``` A multi-cardinality observer slot starts as many mock sources as the [configuration](#configuration) asks for; they arrive as a list (`h.mocks.observed.fleet_arms[0]` / `mocks.observed.fleet_arms[0]`), each publishing under its own instance identity, in the same order the node’s `sources()` reports them. ### Emitted topics [Section titled “Emitted topics”](#emitted-topics) The harness subscribes to every topic the node emits **before the node boots**, and barriers on those subscriptions being visible, so the very first message your setup publishes is captured, not raced. Each emitted topic is a typed subscription on `harness.emitted`: * Python ```python status = await h.emitted.status.next() assert status.outcome == "done" ``` * Rust ```rust let status = harness .emitted .status .next() .await? .expect("status subscription should be open"); assert_eq!(status.outcome, "done"); ``` `next` awaits the node’s next message on the topic, in order, and returns `None` once the harness’s session closes. Each subscription keeps the newest messages your test has not read: up to 128 messages, or 1024 for a `sensor_data` topic, or the topic’s retention depth when that is larger. When a message arrives while the subscription is full, the oldest unread message is dropped. A test can therefore read an emitted topic late, or not at all: its unread messages never hold up the other messages to the harness’s session, such as the next message of another emitted topic or the reply of a service or action the test calls. A test that must see every message of a topic never leaves more messages unread than the subscription holds. ### Exposed services [Section titled “Exposed services”](#exposed-services) The `fixtures` callers drive the node’s exposed surface from the outside, as a fresh consumer with its own wire identity, the same path a real consumer node would take. Every call gates on a reachability probe first, so a test cannot race the node’s own declaration of the service: * Python ```python from peppygen.fixtures.exposed_services import ping # Poll the node's service once. response = await ping.poll(h, ping.RequestData(value=21), 10.0) assert response.doubled == 42 ``` * Rust ```rust use peppygen::fixtures::exposed_services::ping; use std::time::Duration; // Poll the node's service once. let response = ping::poll( &harness, &ping::RequestData { value: 21 }, Duration::from_secs(10), ) .await?; assert_eq!(response.doubled, 42); ``` `poll` sends one request and awaits the node’s typed response; `timeout` bounds the reachability gate and the poll individually. An error reply of the node is the `Failure` of the service: in Rust `ping::Failure::of(&error)` reads it from the error of `poll`, in Python `poll` raises it. ### Exposed actions [Section titled “Exposed actions”](#exposed-actions) The node’s exposed actions get the same treatment from the fixture session: `send_goal` gates on the reachability probe, then drives the goal through its full lifecycle: * Python ```python from peppygen.fixtures.exposed_actions import move_arm goal = await move_arm.send_goal(h, move_arm.GoalRequestData(arm_id=7), 10.0) assert goal.accepted feedback = await goal.on_next_feedback() assert feedback.progress > 0.0 result = await goal.get_result(10.0) assert result.status == move_arm.ResultStatus.COMPLETED assert result.data.distance_mm == 120 ``` * Rust ```rust use peppygen::fixtures::exposed_actions::move_arm; use std::assert_matches; use std::time::Duration; let mut goal = move_arm::send_goal( &harness, &move_arm::GoalRequestData { arm_id: 7 }, peppygen::DEFAULT_FEEDBACK_BOUND, Duration::from_secs(10), ) .await?; assert!(goal.accepted); let feedback = goal.on_next_feedback().await?; assert!(feedback.progress > 0.0); let result = goal.get_result(Duration::from_secs(10)).await?; assert_matches!( result.outcome, move_arm::ResultOutcome::Completed(move_arm::ResultData { distance_mm: 120 }) ); ``` The goal handle carries the decoded admission reply (`accepted`, the `refusal` of a refused goal as the typed `Failure` of the action, and the typed goal-response `data`), streams typed feedback with `on_next_feedback`, and finishes with `get_result`, whose outcome is one of completed, failed, cancelled, abandoned, or expired: the typed result payload on completed and cancelled, the `Failure` on failed, and the reason on cancelled. `cancel_goal(timeout)` requests cancellation, exercising the `cancel_signal` path in your node’s goal handler. ## Producer loss, deterministically [Section titled “Producer loss, deterministically”](#producer-loss-deterministically) Every mock owns one messaging session, so `stop()` is a whole-producer loss: every declaration and the session drop together, releasing the liveliness the node’s subscriptions and calls latch on. Live action goals are disarmed first so their teardown emits **no clean close**: the node observes exactly what it would observe if the producer process died mid-goal, and observes it deterministically rather than after an arbitrary timeout. * Python ```python pending = await h.mocks.deps.brain.plan_motion.next_goal(10.0) active = await pending.accept(plan_motion.GoalResponseData(planner="rrt")) # The producer dies with the goal still active. The node's # on_next_feedback_message raises ConnectionError: not a clean # end-of-stream, and not a hang. await h.mocks.deps.brain.stop() # The node's recovery branch ran and reported the loss on its status # topic, so the branch is an ordinary assertion: status = await h.emitted.status.next() assert status.outcome == "producer-gone" ``` * Rust ```rust let pending = mocks .deps .brain .plan_motion .next_goal(Duration::from_secs(10)) .await?; let _active = pending .accept(plan_motion::GoalResponseData::new("rrt".to_owned())) .await?; // The producer dies with the goal still active. The node's // on_next_feedback_message returns // Err(Error::ActionFeedbackProducerGone { .. }): not a clean close, // and not a hang. mocks.deps.brain.stop(); // The node's recovery branch ran and reported the loss on its status // topic, so the branch is an ordinary assertion: let status = harness .emitted .status .next() .await? .expect("status subscription should be open"); assert_eq!(status.outcome, "producer-gone"); ``` On the node side the loss is typed: a feedback drain loop in Rust distinguishes `Error::ActionFeedbackChannelClosed` (the producer closed the stream cleanly) from `Error::ActionFeedbackProducerGone` (the producer instance disappeared without closing it); Python raises `RuntimeError` for the clean close and `ConnectionError` for the loss. Your node’s recovery branch for a dead dependency, usually untestable without killing processes, becomes an ordinary assertion. A stopped mock stays stopped for the rest of the test; the bound set never rebinds, exactly as in [production](/advanced_guides/topics/#dependency-cardinality). ## Configuration [Section titled “Configuration”](#configuration) `start` with no configuration uses the schema-default parameters, a unique generated instance id, one mock per `one`, `zero_or_one`, and `one_or_more` slot, and no mocks for `zero_or_more` slots. Every knob is an override: * Python ```python from peppygen.parameters import Parameters async with harness.start( setup, parameters=Parameters(gain=2.5), # typed override; None uses schema defaults instance_id="my_test_node", # explicit instead of generated clock="consumer", # the test supplies time; see "The clock" fleet_arms_instances=2, # per multi-cardinality slot: mock count # per zero_or_one dependency or observer slot: boot the slot # empty, no mock started # _vacant=True, node_dir="/path/to/node", # see below ) as h: ... ``` * Rust ```rust use peppygen::fixtures::harness::{Config, Harness}; let (mut harness, mut mocks) = Harness::start_with( Config { parameters: Some(peppygen::Parameters { gain: 2.5 }), instance_id: Some("my_test_node".to_string()), // The test supplies time; see "The clock" clock: peppylib::testing::HarnessClock::Consumer, fleet_arms_instances: 2, // per zero_or_one dependency or observer slot: boot the // slot empty, no mock started // _vacant: true, ..Config::default() }, my_node::setup, ) .await?; ``` - **`parameters`** is the node’s typed `Parameters`; leaving it unset hydrates the schema defaults exactly as a launch would (a required parameter without a default is then an error at boot, as in production). - **`instance_id`** replaces the generated unique id (`test--`). The node’s wire identity under the harness is `("standalone-core", )`, returned by `harness.node_producer_ref()`. - **`clock`** is the clock the node boots on, the test-side spelling of a deployment’s `framework.clock` and of the publisher a domain declaration names: `wall` (the default), `consumer` for a node reading a simulated domain the test supplies, or `publisher` for one that supplies the domain itself. See [The clock](#the-clock). - **`_vacant`** (per `zero_or_one` dependency or observer slot) boots the slot [written vacant](/advanced_guides/topics/#dependency-cardinality): no mock is started (the mock field is `None`), and the node’s `bound_producer()` / `source()` accessor answers `None`, the branch this cardinality exists for. - **`_instances`** (per multi-cardinality dependency or observer slot) sets how many mock instances to start, each under its own instance identity, delivered as a list. The default is 1 for `one_or_more` and 0 for `zero_or_more`. - **`_instance_ids`** (same slots) names those instances explicitly, overriding the count when set. Reach for it when the node classifies producers by instance name (a health monitor keying reports on `left_arm`/`right_gripper` identities, a recorder naming limbs after its sources), so the mocks wear identities the node’s classifier accepts. - **`_vacant`** (per `zero_or_one` pairing slot) boots the slot unpaired: the peer pin is never seeded, so the node’s `paired()` answers `None`, `wait_paired()` pends, and its publishes on the slot are no-ops. The peer mock still starts; its subscriptions simply stay silent (and publishing from it reaches nothing), so a test can assert the slot’s silence. A `one` pairing slot offers no such knob. - **`_instances`** (per multi-cardinality pairing slot) sets how many mock peers to pair into the slot, each under its own instance id and outside any copy, delivered as a list. The default is 1 for `one_or_more` and 0 for `zero_or_more`. - **`_members`** (same slots) names those peers explicitly with the copy each belongs to, overriding the count when set: a list of `PeerMemberSpec` in Rust, a dict of instance id to copy (or `None`) in Python. Reach for it when the node groups pairs by copy or classifies peers by instance name. - **`node_dir`** (Python only) points at the directory holding the node’s `peppy.json5` when neither of the automatic resolutions finds it: the harness first walks up from the current working directory to the nearest `peppy.json5`, then falls back to the absolute node path baked in at sync time. Running `pytest` from anywhere inside the node directory needs nothing; a runner with a foreign working directory on a moved checkout passes `node_dir` explicitly. The error on failure names all three sources. (Rust needs no equivalent: the config path is resolved from the generated crate’s own manifest directory at compile time.) ## The clock [Section titled “The clock”](#the-clock) The harness serves the daemon’s clock surface on the `standalone-core` identity, through the same request handler the daemon runs, so everything in [System clock](/advanced_guides/system_clock/) works under it: `peppylib::clock::synchronize` / `peppylib.clock.synchronize` completes its NTP-style exchange (gated by the pre-`setup` readiness barrier, so a synchronize inside `setup` cannot race discovery), `subscribe` receives ticks, and `peppygen::clock::init` + `now_ns` read whichever clock the boot resolved. The serving side is `harness.clock`, and the `clock` config knob picks which of three the node boots on. The `clock` service answers from the OS clock in all three, as a daemon does whatever its instances read, so `synchronize` completes in every mode. **`wall` (the default)** mirrors an instance reading its own machine’s clock: service stamps and the 10 Hz tick stream come from the OS clock. `set_offset_ns` skews every timestamp the clock serves by a signed offset, which is how a test scripts “the daemon’s clock disagrees with mine” and asserts the node’s offset handling without touching a host clock: * Python ```python harness.clock.set_offset_ns(3_600_000_000_000) # daemon runs 1h ahead sync = await synchronize(h.node_runner) assert sync.offset_ns > 1_800_000_000_000 ``` * Rust ```rust harness.clock.set_offset_ns(3_600_000_000_000); // daemon runs 1h ahead let sync = peppylib::clock::synchronize(harness.node_runner(), None).await?; assert!(sync.offset_ns > 1_800_000_000_000); ``` **`consumer`** mirrors an instance bound to a simulated [clock domain](/advanced_guides/system_clock/#clock-domains), with the test playing its publisher: the node reads the harness’s domain, and no time exists on it until the test drives it. Each `tick` is published on the domain’s stream for the node’s `peppygen::clock` subscription. Before the first tick the node’s `now_ns` reports not-ready, exactly as against a real domain whose publisher has not started publishing: * Python ```python async with harness.start(setup, clock="consumer") as h: await h.clock.tick(1_000_000_000) # the node's now_ns() reads 1s ... await h.clock.tick(2_500_000_000) # time advances only when the test says so ``` * Rust ```rust let (harness, mocks) = Harness::start_with( Config { clock: peppylib::testing::HarnessClock::Consumer, ..Config::default() }, my_node::setup, ) .await?; harness.clock.tick(1_000_000_000).await?; // the node's now_ns() reads 1s // ... harness.clock.tick(2_500_000_000).await?; // time advances only when the test says so ``` The first `tick` waits until the node’s clock subscription is visible (the subscription `peppygen::clock::init` opens on a simulated domain), so it cannot be dropped by discovery; ticking a node that reads no domain raises a loud error. `tick` belongs to this mode alone: on a `wall` clock, which ticks itself, and on a `publisher` node, which supplies its own domain, it is an error naming the mode the harness booted. **`publisher`** mirrors the instance a [domain declaration](/advanced_guides/system_clock/#declaring-a-domain) names: `ClockPublisher::for_node` hands the node a publisher for the harness’s domain, and the test never calls `tick`, since the node supplies the time. The harness publishes nothing itself, so a clock subscription on the node runner sees the node’s ticks in the order the node published them, and the node’s stamps can be checked against those ticks. The subscription lives on the node’s own session, so the test opens it with `KeepLatest`: when more ticks than it holds (1024 by default) wait unread, it drops the oldest, and ticks the test reads late, or never, do not hold up the node, its own publishes included. * Python ```python async with harness.start(setup, clock="publisher") as h: ticks = await peppylib.clock.subscribe(h.node_runner, peppylib.TopicBuffer.KeepLatest) first = await ticks.on_next_tick() # published by the node, not the test assert first.time >= 1 # 0 is the wire's "no tick yet" ``` * Rust ```rust let (harness, mocks) = Harness::start_with( Config { clock: peppylib::testing::HarnessClock::Publisher, ..Config::default() }, my_simulator::setup, ) .await?; let mut ticks = peppylib::clock::subscribe( harness.node_runner(), peppylib::messaging::TopicBuffer::KeepLatest, ) .await?; let first = ticks.on_next_tick().await?.expect("the node publishes its clock"); assert!(first.time() >= 1); // 0 is the wire's "no tick yet" ``` ## Caveats [Section titled “Caveats”](#caveats) Caution * **`cargo test` and `cargo build` compile peppygen differently.** The `testing` feature is on for test builds (via the dev-dependency) and off for production builds, so alternating between `cargo build` and `cargo test` recompiles peppygen each time. This is the cost of the guarantee that test surfaces cannot reach production binaries; it does not affect correctness. Everything under `peppygen::mock` and `peppygen::fixtures` is regenerated by every `peppy node sync`, like the rest of peppygen: add an interface to your `peppy.json5`, re-sync, and its mock and fixtures appear with it. Never edit the generated files; your tests, like your node, live outside `.peppy/`. # Topics > How to use topics in Peppy Topics implement a **publish-subscribe** communication pattern between nodes. A node *emits* a topic to publish messages, and other nodes *consume* that topic to receive them. Use topics for continuous, unidirectional data streams such as sensor readings, camera frames, state updates, or any information that flows over time. Multiple consumers can listen to the same topic simultaneously. Topics also underpin two higher-level constructs: [contract implementation](/advanced_guides/contract_implementation/), where a topic’s contract lives in a standalone contract document that producers implement, and [pairing](/advanced_guides/pairing/), where two node instances exchange topics 1:1 in both directions over a two-role contract. For a side-by-side decision guide across every mechanism, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## Emitting a topic [Section titled “Emitting a topic”](#emitting-a-topic) A node that publishes messages declares its topics under `interfaces.topics.emits` in its `peppy.json5`. Each topic defines a `name`, a [`description`](/reference/concepts/#descriptions), a `qos_profile`, and a `message_format`, and can declare a [`retention`](#retaining-the-latest-value): * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "uvc_camera", tag: "v1", description: ["The driver of a UVC camera: it streams the frames of the camera. It needs a UVC camera on its machine."], }, interfaces: { topics: { emits: [ { name: "video_stream", description: "Each frame of the camera, with its size and its encoding.", qos_profile: "sensor_data", message_format: { header: { $type: "object", stamp: "time", frame_id: "u32" }, encoding: "string", width: "u32", height: "u32", frame: { $type: "array", $items: "u8" } } } ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "uvc_camera"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "uvc_camera", tag: "v1", description: ["The driver of a UVC camera: it streams the frames of the camera. It needs a UVC camera on its machine."], }, interfaces: { topics: { emits: [ { name: "video_stream", description: "Each frame of the camera, with its size and its encoding.", qos_profile: "sensor_data", message_format: { header: { $type: "object", stamp: "time", frame_id: "u32" }, encoding: "string", width: "u32", height: "u32", frame: { $type: "array", $items: "u8" } } } ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/uvc_camera"] }, } ``` The `qos_profile` sets the **publisher’s** delivery behavior for this topic; consumers always subscribe with the standard profile. Available profiles are: * **`sensor_data`**: optimized for high-frequency data where occasional drops are acceptable. * **`standard`**: balanced defaults suitable for most use cases. This is the default when `qos_profile` is omitted. * **`reliable`**: blocks on congestion instead of dropping, at the cost of higher latency. * **`critical`**: the same block-on-congestion guarantee as `reliable`, dispatched at the highest scheduling priority with express batching, for the lowest latency on safety-critical data. ### Retaining the latest value [Section titled “Retaining the latest value”](#retaining-the-latest-value) A topic is **live only** by default: a consumer receives the messages published after it subscribes. A topic that carries state, such as a robot’s mode or its battery level, can **retain** its newest message. A consumer that starts later reads that message at once, then follows the live updates through the same subscription. Set `retention` on the emitted topic: ```json5 { name: "robot_mode", description: "The mode of the robot, each time it changes.", qos_profile: "reliable", retention: { latest: 1 }, message_format: { mode: "string" } } ``` | `retention` | A consumer that subscribes later receives | | --------------- | -------------------------------------------------------------------------------------------------- | | `{ latest: 1 }` | The newest message. | | `{ latest: 5 }` | The newest 5 messages, oldest first. The number goes up to 1024, and `{ latest: 0 }` is live only. | A [contract](/advanced_guides/contract_implementation/) declares `retention` on its topic the same way, and every producer that implements the contract retains accordingly: ```json5 interfaces: { topics: [ { name: "robot_mode", description: "The mode of the robot, each time it changes.", retention: { latest: 5 }, message_format: { mode: "string" } } ] } ``` The producer declares the policy and consumers follow it. `peppy node sync` reads the policy from the producer’s manifest, or from the [contract](/advanced_guides/contract_implementation/) that defines the topic, and the generated `subscribe` applies it. A consumer’s manifest and code stay as they are. Note Sync a consumer again after its producer changes its `retention`. Until then the consumer subscribes with the policy it was generated with, and a consumer generated for a live-only topic receives the live messages of a retaining one. A retaining topic keeps these promises: * **One set of messages per producer instance.** Each running producer instance keeps its own newest messages. On a slot bound to several producers, the consumer receives each producer’s retained messages, tagged with that producer. * **For as long as the instance runs.** The messages stay in the producer’s process from its first publication until it stops, also after its code drops the publisher. A producer that restarts has nothing retained until it publishes. For a value that must outlive the node, use the [datastore](/advanced_guides/datastore/). * **Nothing before the first publication.** A consumer of a topic that has not published yet waits for the first publication. * **The newest value, as old as it is.** A retained message was published at some earlier time. Carry a timestamp in the message when its age matters. * **In order.** A consumer that subscribes while the producer publishes reads each producer’s messages in the order they were published, ending on the newest. A message still in transit when the consumer subscribed can arrive first, and the retained messages older than it are then not delivered. The order relies on message timestamps, so it holds while the clocks of the machines between the producer and the consumer agree to within 500 ms. * **After a reconnect.** A consumer whose connection to its producer drops and returns reads the messages its producer published during the outage and still retains, then the live messages. A message it read before the outage is delivered once. * **Again when a producer enters the slot again.** A consumer receives a producer’s retained messages each time that producer enters the slot’s bound set, including a producer that left the set and came back. Caution Retention fits state. A retained **event** or **command** reaches every node that subscribes later, and again when its producer enters the slot again, so a consumer acts on it once more. Keep those topics live only. The retained messages travel under the topic’s own `qos_profile`. Under `reliable` or `critical` they wait for room. Under `standard` or `sensor_data` congestion drops them as it drops live messages. A producer holds each retained message in memory, and a consumer’s queue holds at least as many messages as the topic retains. A new subscription fetches a producer’s retained messages twice, once when it starts and once when it detects the producer, so keep the number small for large messages. [Pairing](/advanced_guides/pairing/) topics, pairing observers and [action](/advanced_guides/actions/) feedback are live only, and so are the resources an [MCP server](/advanced_guides/mcp/) reads. ### Publishing messages [Section titled “Publishing messages”](#publishing-messages) After running `peppy node sync`, the code generator creates a module for each emitted topic under `peppygen.emitted_topics` (Python) / `peppygen::emitted_topics` (Rust). Each module exposes `declare_publisher(node_runner)`, which returns a `TopicPublisher`, and `build_message(...)`, which serializes the message fields into a payload. Declare the publisher once, then publish each message on it: * Python ```python import asyncio import time from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppygen.emitted_topics import video_stream async def emit_frames(node_runner: NodeRunner): # Declare the publisher once; every publish below then reuses it. publisher = await video_stream.declare_publisher(node_runner) frame_id = 0 while True: payload = video_stream.build_message( video_stream.MessageHeader(stamp=time.time(), frame_id=frame_id), "rgb8", 640, 480, bytes([1, 2, 3]), ) await publisher.publish(payload) frame_id = (frame_id + 1) % (2**32) await asyncio.sleep(0.1) async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(emit_frames(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use peppygen::emitted_topics::video_stream; use peppygen::{NodeBuilder, Parameters, Result}; use std::time::Duration; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let node_runner_clone = node_runner.clone(); tokio::spawn(async move { // Declare the publisher once; every publish below is then lock-free. let publisher = video_stream::declare_publisher(&node_runner_clone) .await .expect("failed to declare video_stream publisher"); let mut frame_id = 0u32; loop { if let Ok(payload) = video_stream::build_message( video_stream::MessageHeader { stamp: std::time::SystemTime::now(), frame_id, }, "rgb8".to_owned(), 640, 480, vec![1, 2, 3], ) { let _ = publisher.publish(payload).await; } frame_id = frame_id.wrapping_add(1); tokio::time::sleep(Duration::from_secs_f64(0.1)).await; } }); Ok(()) }) } ``` `build_message` takes each field from the `message_format` in order (no `node_runner` argument) and returns the payload that `publisher.publish` sends; in Rust it returns a `Result` you unwrap, in Python it returns the payload directly and raises on invalid input. Nested objects become generated types whose fields match the object definition: a struct in Rust (`video_stream::MessageHeader`), a dataclass in Python (`video_stream.MessageHeader`). A producer publishes a **single stream** regardless of how many consumers are listening, and it never knows about the bindings consumers use to address it. Starting the producer before any consumer (or after them) is equally valid; consumers attach when they show up. A consumer that attaches later starts from the next publication, or from the retained messages of a topic that [retains](#retaining-the-latest-value). For a topic with a simple message format: ```json5 { name: "message_stream", description: "Each greeting, as text.", qos_profile: "sensor_data", message_format: { message: "string" } } ``` `build_message` takes a single string argument: * Python ```python from peppygen.emitted_topics import message_stream publisher = await message_stream.declare_publisher(node_runner) payload = message_stream.build_message("hello world") await publisher.publish(payload) ``` * Rust ```rust use peppygen::emitted_topics::message_stream; let publisher = message_stream::declare_publisher(&node_runner).await?; let payload = message_stream::build_message("hello world".to_owned())?; publisher.publish(payload).await?; ``` ## Consuming a topic [Section titled “Consuming a topic”](#consuming-a-topic) A node that receives messages declares what it consumes under `interfaces.topics.consumes`. Dependencies are declared in `manifest.depends_on` and referenced by `link_id` in the interface: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "web_video_stream", tag: "v1", description: ["A web page that shows the video of one UVC camera. It needs no device."], depends_on: { nodes: [ { name: "uvc_camera", tag: "v1", link_id: "uvc_camera" }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "uvc_camera", // References depends_on.nodes[].link_id name: "video_stream", // Topic name on that node }, ], }, }, execution: { language: "python", build_cmd: ["uv", "sync"], run_cmd: ["uv", "run", "web_video_stream"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "web_video_stream", tag: "v1", description: ["A web page that shows the video of one UVC camera. It needs no device."], depends_on: { nodes: [ { name: "uvc_camera", tag: "v1", link_id: "uvc_camera" }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "uvc_camera", // References depends_on.nodes[].link_id name: "video_stream", // Topic name on that node }, ], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/web_video_stream"] }, } ``` Note By default, the `node add` and `node sync` commands require the target node to already be in the node stack so the proper interfaces can be generated. The exception is a dependency whose slot admits an empty bound set (`cardinality: "zero_or_one"` or `"zero_or_more"`): `node add` resolves it through the repository cache automatically when it is absent from the stack. If the target node is missing, you will see an error like: ```plaintext Error: `web_video_stream:v1` depends on `uvc_camera:v1`, but it does not exist in the stack ``` Pass `peppy node sync --include-repositories` (`-r`) to let the daemon fall back to the [repository cache](/advanced_guides/repositories/#syncing-against-repositories) for dependencies that aren’t in the stack. Tip To depend on a contract instead of a specific producer node, so any implementing node can fill the slot at launch time, declare the dep under `depends_on.contracts` rather than `depends_on.nodes`. See the [Contract implementation](/advanced_guides/contract_implementation/) guide. ### Receiving messages [Section titled “Receiving messages”](#receiving-messages) The code generator creates a module for each consumed topic under `peppygen.consumed_topics` (Python) / `peppygen::consumed_topics` (Rust). Every slot-backed module lives at `//`, keyed on the author’s `link_id`. The consumed module is therefore `consumed_topics//`, imported as `from peppygen.consumed_topics.uvc_camera import video_stream` (Python) / `peppygen::consumed_topics::uvc_camera::video_stream` (Rust); here the `link_id` is `uvc_camera` and the topic is `video_stream`. Call `subscribe` once to obtain a held `Subscription`, then await `next` for each message: * Python ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppygen.consumed_topics.uvc_camera import video_stream async def receive_frames(node_runner: NodeRunner): # Same subscribe() as every cardinality: it covers the slot's complete # bound set, which for `one` is exactly one producer. The yielded # ProducerRef is constant here, so the loop ignores it. subscription = await video_stream.subscribe(node_runner) async for _producer, frame in subscription: print(f"frame: {frame.width}x{frame.height}") async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(receive_frames(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use peppygen::consumed_topics::uvc_camera::video_stream; use peppygen::{NodeBuilder, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // Same subscribe() as every cardinality: it covers the slot's complete // bound set, which for `one` is exactly one producer. The yielded // ProducerRef is constant here, so the loop ignores it. let mut subscription = video_stream::subscribe(&node_runner).await?; while let Some((_, frame)) = subscription.next().await? { println!("frame: {}x{}", frame.width, frame.height); } Ok(()) }) } ``` `subscribe` takes only `node_runner` (the node runner reference) and returns a `Subscription` covering the slot’s **complete bound producer set**: one producer-pinned wire subscription per bound producer, merged client-side behind the single `subscribe()` API. The shape is identical for every [cardinality](#dependency-cardinality); only the size of the bound set changes. Awaiting `subscription.next()` yields: * a `(producer, message)` pair for each message (`Ok(Some((producer, message)))` in Rust), where `producer` is a `ProducerRef` carrying the publisher’s full `(core_node, instance_id)` wire identity, so the consumer can tell messages from different bound producers apart, and `message` is the deserialized message, with fields matching the topic’s `message_format`. * `None` (`Ok(None)` in Rust) once the node is shutting down and no queued message remains, or once the runtime is torn down. * an error if a received payload fails to deserialize: `Err(..)` in Rust, a raised exception in Python. The error names the message type that failed to decode, and neither tears down the subscription nor shrinks the bound set. Each underlying subscription holds an in-order buffer, so a message published between `next` calls is kept, not dropped; loop on `next` and nothing is lost in the gap between iterations. On a topic that [retains](#retaining-the-latest-value), `next` yields the messages a producer retains before its later ones, and a message still in transit when the subscription started can arrive first, in which case the older retained ones are not delivered. Message order is preserved independently per producer (no total ordering across producers is promised), and ready producers are merged fairly so one busy producer cannot indefinitely starve another. `ProducerRef` is `Eq + Hash`, so it keys per-producer state directly; to follow a single producer, filter on the yielded producer. There are no call-site producer-targeting arguments at all. Which producers reach a slot is decided entirely by application bindings (see [Bindings and routing](#bindings-and-routing) below): a slot receives messages only from the producer instances bound to it, and each resolved binding carries the producer’s full `(core_node, instance_id)` wire address, so the slot can never match a producer that merely shares the instance_id on another core node. The producer segments of a keyexpr are never wildcarded: a federated router forwards traffic only for the explicitly bound producers, and every subscriber stays fully pinned (and auditable) in the zenoh admin space. That same full identity is what `next` returns with every message, so a consumer can pass it straight back into any producer-targeting call (a `ProducerRef` yielded by the slot’s own subscription is a member of the slot’s bound set by construction). Every generated consumed topic, service, and action module also exposes a bound-producer accessor for its slot, returning the producers bound to the slot when it is called, in plan order. The accessor’s return type encodes exactly the guarantee [launch validation](#validator-rules) established for the slot’s [cardinality](#dependency-cardinality): ```rust // Generated for every consumed module of a `cardinality: "one"` slot, // replacing bound_producers() for that slot. pub fn bound_producer(node_runner: &crate::NodeRunner) -> &ProducerRef; // Generated for every consumed module of a `cardinality: "zero_or_one"` slot: // the same singular name returning an Option, `None` wherever the deployment // wrote the slot vacant. pub fn bound_producer(node_runner: &crate::NodeRunner) -> Option<&ProducerRef>; // Generated for every consumed module of a `cardinality: "one_or_more"` slot: // a never-empty ordered set whose first() is infallible. pub fn bound_producers(node_runner: &crate::NodeRunner) -> NonEmptyProducers; // Generated for every consumed module of a `cardinality: "zero_or_more"` slot: // a plain, possibly empty list, so the empty branch is forced by the type // and is never dead code. pub fn bound_producers(node_runner: &crate::NodeRunner) -> Vec; // Generated beside bound_producers() for every consumed module of a // `one_or_more` slot: the same set, each member with the copy its instance // belongs to. pub fn bound_members(node_runner: &crate::NodeRunner) -> NonEmptyMembers; // Generated beside bound_producers() for every consumed module of a // `zero_or_more` slot. pub fn bound_members(node_runner: &crate::NodeRunner) -> Vec; ``` Python mirrors the split by name and annotation: a `one` slot generates `bound_producer(node_runner) -> peppylib.ProducerRef`, a `zero_or_one` slot `bound_producer(node_runner) -> Optional[peppylib.ProducerRef]`, and the multi cardinalities generate `bound_producers(node_runner) -> List[peppylib.ProducerRef]` (documented never-empty for `one_or_more`) and `bound_members(node_runner) -> List[peppylib.BoundMember]`. A member of a `one_or_more` or `zero_or_more` slot is a `BoundMember`: its `producer` is the `ProducerRef` the slot’s subscription tags messages with, and its `copy` is the [copy](/guides/launch_files/#copies) the producer’s instance belongs to, `None` for an instance the launcher file deploys outside any copy. A `copy` carries the copy’s `name` and the `instance_id` the copy’s fragment wrote, which is the instance’s name inside the copy. A node that holds members from several copies groups them by `copy.name` and names each one inside its copy by `copy.instance_id`; one that addresses a member passes its `producer` to the slot’s service and action calls. `peppy stack list` prints the copy beside each member (`alpha_arm_inst@cn-robot [copy alpha]`). An [observer slot](/advanced_guides/pairing/#observing-several-pairings-through-one-slot) types its own `source()` / `sources()` accessor the same four ways against its own cardinality. Every module sharing the slot’s `link_id` returns the same set in the same order. The set is the one the deployment binds: a producer disconnecting does not shrink it, trigger discovery, or cause automatic rebinding. On a `one_or_more` or `zero_or_more` slot the deployment changes it while the node runs when a [copy joins or leaves](/guides/launch_files/#copies), so the accessor returns the set as it is when called, and a `subscribe` follows it. A cardinality change is therefore visible at compile time in the consuming node: the accessor’s type changes and every call site that relied on the old guarantee must be revisited. This is intended: a cardinality flip is a semantic change to the node. ### Receiving messages continuously [Section titled “Receiving messages continuously”](#receiving-messages-continuously) To receive messages continuously, subscribe once and loop on `next`. The held subscription keeps every message in arrival order, so the loop never misses a message published between iterations. Each message is processed in a separate task so that the receive loop is not blocked: * Python ```python import asyncio import sys from peppygen import NodeBuilder, NodeRunner from peppygen.parameters import Parameters from peppygen.consumed_topics.uvc_camera import video_stream async def process_frame(producer, frame): print( f"got {frame.width}x{frame.height} frame " f"from {producer.core_node}/{producer.instance_id}" ) async def receive_frames(node_runner: NodeRunner): try: subscription = await video_stream.subscribe(node_runner) except Exception as e: print(f"Failed to subscribe: {e}", file=sys.stderr) return # The subscription is an async iterator; the loop ends when it closes. # Hold a reference to each task until it finishes, otherwise the event # loop may garbage-collect it mid-flight. tasks: set[asyncio.Task] = set() async for producer, frame in subscription: task = asyncio.create_task(process_frame(producer, frame)) tasks.add(task) task.add_done_callback(tasks.discard) async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(receive_frames(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust ```rust use std::sync::Arc; use peppygen::consumed_topics::uvc_camera::video_stream; use peppygen::{NodeBuilder, NodeRunner, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { tokio::spawn(receive_frames(node_runner)); Ok(()) }) } async fn receive_frames(node_runner: Arc) { let mut subscription = match video_stream::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe: {e}"); return; } }; loop { match subscription.next().await { Ok(Some((producer, frame))) => { tokio::spawn(async move { println!( "got {}x{} frame from {}/{}", frame.width, frame.height, producer.core_node, producer.instance_id ); }); } Ok(None) => break, Err(e) => { eprintln!("Error receiving frame: {e}"); break; } } } } ``` In Python the `Subscription` is also an async iterator: `async for producer, message in subscription` is equivalent to looping on `next` and stops cleanly once the subscription closes. ### Consuming a multi-cardinality bound set [Section titled “Consuming a multi-cardinality bound set”](#consuming-a-multi-cardinality-bound-set) Nothing changes at the call site when the slot’s [cardinality](#dependency-cardinality) allows several producers: the same single `subscribe()` covers every bound producer, and the yielded `ProducerRef` tells the streams apart. `ProducerRef` is `Eq + Hash`, so it keys per-producer state directly: * Python ```python from peppygen.consumed_topics.camera import video_stream async def count_frames(node_runner): # One subscription covering every producer bound to the `camera` # slot; the yielded producer tells per-camera streams apart. subscription = await video_stream.subscribe(node_runner) frames_per_camera: dict = {} async for producer, frame in subscription: frames_per_camera[producer] = frames_per_camera.get(producer, 0) + 1 print( f"frame from {producer.instance_id}@{producer.core_node}: " f"{frame.width}x{frame.height} " f"(total from this camera: {frames_per_camera[producer]})" ) ``` * Rust ```rust use peppygen::consumed_topics::camera::video_stream; use peppygen::{NodeBuilder, Parameters, ProducerRef, Result}; use std::collections::HashMap; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // One subscription covering every producer bound to the `camera` // slot. The shape is identical for every cardinality; only the // size of the bound set changes. // `one`: the subscription covers exactly one producer. // `one_or_more`: the merged subscription covers at least one producer. // `zero_or_one` written vacant, or `zero_or_more` bound to nothing: // the slot is empty; the subscription then yields nothing until the // node stops. let mut subscription = video_stream::subscribe(&node_runner).await?; let mut frames_per_camera: HashMap = HashMap::new(); while let Some((producer, frame)) = subscription.next().await? { *frames_per_camera.entry(producer.clone()).or_insert(0) += 1; println!( "frame from {}@{}: {}x{} (total from this camera: {})", producer.instance_id, producer.core_node, frame.width, frame.height, frames_per_camera[&producer], ); } Ok(()) }) } ``` To follow a single camera instead, filter on the yielded producer (`bound_producers()` lists the members in plan order). ## Bindings and routing [Section titled “Bindings and routing”](#bindings-and-routing) Routing is **entirely consumer-side**. Producers publish unconditionally and are binding-agnostic; only the consumer’s `depends_on` slots and the application bindings that fill them decide which producer instance reaches which slot. ([Pairing](/advanced_guides/pairing/) topics are the one exception: a pairing slot is routed by the pair itself, established with `--link` at instance start, not by a binding.) A binding takes the form `KEY: VALUE`, where `KEY` is a `link_id` declared in the consumer’s `depends_on` and `VALUE` selects the slot’s target producer instance(s). Each bound target creates a private one-way channel from that producer instance to the consumer’s slot: a multi-cardinality slot expands into N independent application-selected bound edges sharing the same `link_id`. How many targets a slot takes is the slot’s declared [cardinality](#dependency-cardinality); there is no wildcard fallback and no discovery, only explicitly bound producers. In a launcher / stack config: ```json5 { source: { name: "consumer:v1" }, instances: [{ instance_id: "my_consumer", links: { uvc_camera: "my-camera-instance" }, }], } ``` or, when launching a single node during development: ```sh peppy node run --link uvc_camera@my-camera-instance web_video_stream:v1 ``` Note `peppy node run` and `peppy node add --run` refuse a `--link` whose target instance has no process, which is a target that is `restarting`, `finished`, or `failed`. Wait for a `restarting` target to reach `running` and link to it then, or stop a `finished` or `failed` target with `peppy node stop` to clear it, then start it again as it was started before linking. ### Dependency cardinality [Section titled “Dependency cardinality”](#dependency-cardinality) Every `depends_on.contracts`, `depends_on.nodes`, `depends_on.pairing_observers` and `depends_on.pairings` entry may declare a `cardinality`, constraining how many sources the application may bind to the slot: producers for the first two, [observed pairings](/advanced_guides/pairing/#observing-several-pairings-through-one-slot) for the third, [pairs](/advanced_guides/pairing/#pairing-with-several-peers-through-one-slot) for the fourth. ```json5 depends_on: { contracts: [ { name: "uvc_camera", tag: "v1", link_id: "camera", cardinality: "one_or_more" }, ], } ``` | Cardinality | Valid unique targets | Slot kinds it is valid on | Omitted binding | At join and remove | | --------------- | -------------------- | ------------------------------- | ------------------------------------------------- | ------------------------------------------------------ | | `one` / omitted | exactly 1 | producer, observer, participant | error | unchanged | | `zero_or_one` | 0 or 1 | producer, observer, participant | error: link it, or write it `{ vacant: "" }` | unchanged, except a participant slot a copy pairs into | | `one_or_more` | 1 or more | producer, observer, participant | error | grows and shrinks | | `zero_or_more` | 0 or more | producer, observer, participant | empty set | grows and shrinks | `zero_or_one` is the one cardinality a [vacancy](/guides/launch_files/#links-optional) is legal on, on a producer slot, an observer slot and a participant slot alike: its empty state is written rather than omitted, so a slot nobody mentioned stays an error and “this rig deliberately has none” stays distinguishable from “whoever wrote this launcher forgot it”. The binding value’s shape mirrors the slot’s cardinality. A scalar slot (`one` or `zero_or_one`) takes a scalar string only, exactly as above. A `one_or_more` or `zero_or_more` slot takes an **array** of instance ids; for `zero_or_more` the empty array `[]` is a valid definition, equivalent to omitting the binding entirely: ```json5 links: { camera: ["front_camera", "rear_camera"], } ``` Any other combination is an error: an array on a scalar slot (single-element arrays included), a scalar on a multi slot, and an empty array on a `one_or_more` slot (cardinality unmet). The CLI mirrors the array form by repetition, which accumulates on a multi slot and stays a hard error on a scalar slot. A `zero_or_more` slot’s empty set has no flag spelling, omission is it; a `zero_or_one` slot’s is `--vacant-link 'SLOT='`, because that one has to be said out loud: ```sh peppy node run --link camera@front_camera --link camera@rear_camera web_video_stream:v1 ``` Cardinality applies to a consumer’s dependency slot; it does not permit undeclared or unbound launched node instances. On a producer-binding slot it constrains the bound set the deployment writes, not runtime availability: a producer disconnecting does not shrink the set, trigger discovery, or cause automatic rebinding. An observer slot’s member set is delivered live by the daemon, so what the set says about each member moves while the node runs. On both kinds the members change only when the deployment does: a [copy](/guides/launch_files/#copies) joining adds its own instances to a running instance’s `one_or_more` or `zero_or_more` slot, removing it takes them out, and the daemon delivers the whole new set, each producer member carrying the copy its instance belongs to, while a `one` or `zero_or_one` slot keeps what its launch bound. The planner checks every set it delivers against the slot’s cardinality, and a removal that would empty a `one_or_more` slot is refused. A participant pairing slot is sized in pairs: its set is seeded at spawn, grows when a `stack join` pairs a copy into it and shrinks when a pair’s other end stops. Its floor holds when the launch is planned, since the planner checks coverage then, and a read while the node runs can find fewer pairs, since a pair ends whenever either endpoint stops. `zero_or_one` is, on every slot kind, the node’s own statement that a deployment may leave the slot empty, and the deployment still has to write down that it did. The consuming API is uniform across cardinalities in everything except the [bound-producer accessor](#receiving-messages): topics subscribe to the slot’s complete bound set and yield the producing `ProducerRef` with every message, and [services](/advanced_guides/services/) and [actions](/advanced_guides/actions/) require the caller to select one explicit, membership-checked member of that set, whatever its size. The accessor itself is cardinality-typed: `one` generates the singular, infallible `bound_producer()`, `zero_or_one` generates `bound_producer()` returning an `Option`, `one_or_more` generates `bound_producers()` returning a never-empty set whose `first()` needs no unwrap, and `zero_or_more` generates `bound_producers()` returning a possibly empty list, so the empty branch is forced by the type. An [observer slot](/advanced_guides/pairing/#observing-several-pairings-through-one-slot) types its accessor the same four ways: `one` generates the singular, infallible `source()`, `zero_or_one` generates `source()` returning an `Option`, `one_or_more` generates `sources()` returning a never-empty set, and `zero_or_more` generates `sources()` returning a possibly empty one. For an empty slot (a vacant `zero_or_one`, or a `zero_or_more` bound to nothing) the subscription simply yields nothing until the node stops. #### Worked example: a slot that may bind nothing [Section titled “Worked example: a slot that may bind nothing”](#worked-example-a-slot-that-may-bind-nothing) A receiver whose `greeter` slot is declared `zero_or_one`: a rig that ships with a greeter links one, and a rig that ships without one says so. The manifest is the whole declaration: * Python peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "optional_receiver", tag: "v1", description: ["A node that prints the greetings of a hello_world_param instance when a launcher links one, and runs without one."], depends_on: { nodes: [ { name: "hello_world_param", tag: "v1", link_id: "greeter", cardinality: "zero_or_one", }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "greeter", name: "message_stream", } ], } }, execution: { language: "python", build_cmd: [ "uv", "sync" ], run_cmd: [ "uv", "run", "optional_receiver" ] }, } ``` * Rust peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "optional_receiver", tag: "v1", description: ["A node that prints the greetings of a hello_world_param instance when a launcher links one, and runs without one."], depends_on: { nodes: [ { name: "hello_world_param", tag: "v1", link_id: "greeter", cardinality: "zero_or_one", }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "greeter", name: "message_stream", } ], } }, execution: { language: "rust", build_cmd: [ "cargo", "build", "--release" ], run_cmd: [ "./target/release/optional_receiver" ] }, } ``` The generated accessor is scalar and answers with the two cases the cardinality allows, so the node reads its own wiring without a set to interpret: * Python src/optional_receiver/\_\_main\_\_.py ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.consumed_topics.greeter import message_stream from peppygen.parameters import Parameters async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: # The `greeter` slot declares `cardinality: "zero_or_one"`, so its accessor # is `Optional`: a producer where the deployment linked one, `None` where it # wrote the slot vacant. There is no third case, and no empty list to # interpret. greeter = message_stream.bound_producer(node_runner) if greeter is None: print("no greeter bound: running without greetings") return [] print(f"greeter bound: {greeter.instance_id}") return [asyncio.create_task(receive_messages(node_runner))] async def receive_messages(node_runner: NodeRunner): subscription = await message_stream.subscribe(node_runner) async for producer, message in subscription: print(f"Received from {producer.instance_id}: {message.message}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::sync::Arc; use peppygen::consumed_topics::greeter::message_stream; use peppygen::{NodeBuilder, NodeRunner, Parameters, Result}; fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { // The `greeter` slot declares `cardinality: "zero_or_one"`, so its // accessor is an `Option`: `Some` where the deployment linked a // producer, `None` where it wrote the slot vacant. There is no third // case, and no empty set to interpret. match message_stream::bound_producer(&node_runner).cloned() { Some(greeter) => { println!("greeter bound: {}", greeter.instance_id); tokio::spawn(receive_messages(node_runner)); } None => println!("no greeter bound: running without greetings"), } Ok(()) }) } async fn receive_messages(node_runner: Arc) { let mut subscription = match message_stream::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe: {e}"); return; } }; loop { match subscription.next().await { Ok(Some((producer, message))) => { println!("Received from {}: {}", producer.instance_id, message.message) } Ok(None) => break, Err(e) => { eprintln!("Error receiving message: {e}"); break; } } } } ``` Both states are deployments of the same node. Bound: ```sh peppy node run --link greeter@hello_world_param_1 optional_receiver:v1 ``` Empty, with the reason recorded on the instance: ```sh peppy node run --vacant-link 'greeter=this rig ships without a greeter' optional_receiver:v1 ``` Leaving `greeter` out of the run entirely stays an error, which is what keeps the second command distinguishable from a launcher that forgot the slot. ### Per-message routing [Section titled “Per-message routing”](#per-message-routing) For every message a producer publishes, each consumer instance applies one rule on its own slots: the message is delivered to every slot whose bound set names the producer, and to no other slot. A producer named by no binding is ignored by the consumer entirely; there is no wildcard fallback. Wildcard-subscribe-and-filter-in-process is deliberately not offered: a wildcard expresses interest in every same-namespace producer of the contract, so a federated router would forward traffic from unbound producers across the mesh, and the bound set would stop being auditable from the zenoh admin space. ### Worked example: `openarm01_backbone` [Section titled “Worked example: openarm01_backbone”](#worked-example-openarm01_backbone) A consumer that wires two specific depth cameras to dedicated wrist slots: openarm01_backbone/peppy.json5 ```json5 { manifest: { name: "openarm01_backbone", tag: "v1", description: ["The backbone of an OpenArm with a depth camera on each wrist."], depends_on: { contracts: [ { name: "depth_camera", tag: "v1", link_id: "wrist_left_camera" }, { name: "depth_camera", tag: "v1", link_id: "wrist_right_camera" }, ], }, }, // ... } ``` And the launcher that binds it: peppy_launcher.json5 ```json5 { description: ["An OpenArm backbone with a depth camera on each wrist. It needs the arm and the two cameras."], deployments: [ { source: { name: "depth_camera:v1" }, instances: [ { instance_id: "left_cam" }, { instance_id: "right_cam" }, ]}, { source: { name: "openarm01_backbone:v1" }, instances: [ { instance_id: "backbone_inst_1", links: { wrist_left_camera: "left_cam", wrist_right_camera: "right_cam", }}, ]}, ], } ``` Three contract statements follow from this manifest: 1. A frame from `left_cam` arrives only on the `wrist_left_camera` slot. 2. A frame from `right_cam` arrives only on the `wrist_right_camera` slot. 3. If the `wrist_right_camera` binding line were removed, the launch would be rejected: every declared slot except `zero_or_more` must be bound. A producer named by no binding is simply ignored, but a declared `one` or `one_or_more` slot with no binding is an error, not a silent gap. Dedicated slots (one `link_id` per camera, as here) and one multi-cardinality slot (`cameras: ["left_cam", "right_cam"]`) are both valid designs. Dedicated slots give each producer a distinct role in code; a multi slot treats the producers as an N-of-a-kind set behind one API. ### Validator rules [Section titled “Validator rules”](#validator-rules) The launcher validator runs these checks before the stack starts: 1. **Every `KEY` must name a declared slot, and every declared slot must resolve.** A `--link KEY@VALUE` (or launcher `links:` entry) whose `KEY` matches no `depends_on.{nodes,contracts}` `link_id` is rejected; there are no free-form keys. In the other direction, a declared `one` or `one_or_more` slot the bindings leave out fails the launch with one error per unfulfilled slot; a `zero_or_more` slot with no binding resolves to the empty set. 2. **The value’s shape must match the slot’s cardinality.** A `one` slot takes a scalar only (an array is rejected, single-element and empty included), a multi slot takes an array only (a scalar is rejected), and an empty array meets only `zero_or_more` (on `one_or_more` it is a cardinality-unmet error). Repeated `--link KEY@…` flags carry no shape and are checked by count: more than one occurrence on a `one` slot is rejected. Duplicate targets within one slot are rejected rather than deduplicated. 3. **Every target must satisfy the slot, checked per bound instance.** For node slots, each target producer’s `(node_name, node_tag)` must equal the slot’s declared pair (`BindingTargetMismatch` otherwise). For contract slots, each target’s `manifest.implements` must include the slot’s `(name, tag)` (`BindingContractNotImplemented` otherwise); see [Contract implementation](/advanced_guides/contract_implementation/) for the implementation rules. 4. **Stack-wide `instance_id` uniqueness.** Every `instance_id` must be unique across the entire stack, not just within a `(node_name, node_tag)` group. The `--link` syntax names producers by `instance_id`, so reusing one across two different node kinds would make the binding ambiguous. 5. **Bindings are stamped with the producer’s `core_node`.** The `--link KEY@instance_id` syntax names producers by `instance_id` alone, but the wire addresses producers by the full `(core_node, instance_id)` pair, since `instance_id` is only unique within one stack. The validator stamps each target producer instance’s resolved `core_node` into the binding (the machine the launcher places that instance on, which is the launching daemon only in the single-machine case), so the runtime never matches on `instance_id` alone: a slot subscribes with both wire fields set. A producer on another core node that happens to share an `instance_id` can never feed a bound slot. Bound-set member order is plan order: the launcher’s array order (or the CLI’s flag order), then the members each joined copy adds, in the order the copies joined, preserved verbatim into the runtime configuration and into every set the daemon delivers. ## Message format types [Section titled “Message format types”](#message-format-types) The `message_format` supports the following field types (see the [message format reference](/reference/message_format/) for the full type system, including aliases and nesting rules): | Type | Rust type | Python type | | ---------- | ----------------------- | ---------------------------- | | `"bool"` | `bool` | `bool` | | `"u8"` | `u8` | `int` | | `"u16"` | `u16` | `int` | | `"u32"` | `u32` | `int` | | `"u64"` | `u64` | `int` | | `"i8"` | `i8` | `int` | | `"i16"` | `i16` | `int` | | `"i32"` | `i32` | `int` | | `"i64"` | `i64` | `int` | | `"f32"` | `f32` | `float` | | `"f64"` | `f64` | `float` | | `"string"` | `String` | `str` | | `"bytes"` | `Vec` | `bytes` | | `"time"` | `std::time::SystemTime` | `float` (Unix epoch seconds) | Fields can also use complex types: * **Object**: a nested struct in Rust, a generated dataclass in Python: ```json5 header: { $type: "object", stamp: "time", frame_id: "u32" } ``` * **Array**: a variable-length list (`Vec` in Rust, `list[T]` in Python; an array of `u8` maps to `Vec` / `bytes`): ```json5 frame: { $type: "array", $items: "u8" } ``` * **Fixed-length array**: an array with a known size (`[T; N]` in Rust, a `list[T]` that must hold exactly `N` items in Python; the `u8` item type is the exception, arriving as `bytes` in Python regardless of `$length`): ```json5 position: { $type: "array", $items: "f32", $length: 3 } ``` * **Optional**: a field that may be absent (`Option` in Rust, `T | None` in Python): ```json5 label: { $type: "string", $optional: true } ``` # Node communication > Learn how to make nodes send messages to each other A node by itself isn’t very useful without the ability to communicate with other nodes in the node stack. Each node is only aware of the interfaces it exposes and the ones it consumes, as defined in its `peppy.json5` configuration. For example: * Python ```json5 { peppy_schema: "node/v1", manifest: { name: "controller", tag: "v1", description: ["A controller that declares no topic, service or action yet."], }, interfaces: { topics: { emits: [], consumes: [], }, services: { exposes: [], consumes: [], }, actions: { exposes: [], consumes: [], }, }, execution: { language: "python", build_cmd: ["uv", "sync", "--no-editable"], run_cmd: ["uv", "run", "controller"] }, } ``` * Rust ```json5 { peppy_schema: "node/v1", manifest: { name: "controller", tag: "v1", description: ["A controller that declares no topic, service or action yet."], }, interfaces: { topics: { emits: [], consumes: [], }, services: { exposes: [], consumes: [], }, actions: { exposes: [], consumes: [], }, }, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/controller"] }, } ``` Here we have `interfaces` organized by kind (`topics`, `services`, `actions`). Topics use `emits` and `consumes` lists, while services and actions use `exposes` and `consumes` lists. Each entry of `emits` and `exposes` that the node declares itself gives a [`description`](/reference/concepts/#descriptions) of the member. `interfaces` declares what a node produces and consumes; the `manifest.depends_on` block declares the dependency slots those `consumes` entries bind to through their `link_id`. ## Topics, services, and actions [Section titled “Topics, services, and actions”](#topics-services-and-actions) Peppy provides three primary communication patterns for nodes to exchange data: * **Topics** are used for continuous, unidirectional data streams. A node *publishes* messages to a topic, and any number of nodes can *subscribe* to receive them. This is ideal for sensor data, state updates, or any information that flows continuously (e.g., camera images, odometry). * **Services** implement a request-response pattern. A node connects to another node and waits for a response. Use services for quick operations that need a result, like querying a node’s state or triggering a one-time computation. * **Actions** are for long-running tasks that need feedback and cancellation support. A client sends a goal to an action node, which provides periodic feedback during execution and a final result upon completion. Actions are built on top of topics and services internally. Use them for tasks like navigation or arm movement. A node can drive multiple goals of the same action concurrently; its goal handler decides whether to accept a new goal or reject it, for example while the arm it targets is already moving. These three are not the whole story: [pairing](/advanced_guides/pairing/) covers exclusive bidirectional exchanges between two instances, and [contract implementation](/advanced_guides/contract_implementation/) lets any implementing producer fill a consumer’s slot. For a side-by-side decision guide, see [Choosing a communication pattern](/advanced_guides/communication_patterns/). ## Consumed interfaces [Section titled “Consumed interfaces”](#consumed-interfaces) In our `hello_world_param` node, we’ve already emitted a topic. Let’s try to make this topic communicate with another node. We first need to initialize the `hello_receiver` node in a new folder: 1. Initialize the node: * Python ```sh peppy node init --toolchain uv hello_receiver "A node that receives the greetings of one hello_world_param instance and prints them." ``` * Rust ```sh peppy node init --toolchain cargo hello_receiver "A node that receives the greetings of one hello_world_param instance and prints them." ``` 2. Navigate into the directory: ```sh cd hello_receiver ``` with the following `peppy.json5`: * Python peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_receiver", tag: "v1", description: ["A node that receives the greetings of one hello_world_param instance and prints them."], depends_on: { nodes: [ { name: "hello_world_param", tag: "v1", link_id: "hello_world_param", }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "hello_world_param", name: "message_stream", } ], } }, execution: { language: "python", build_cmd: [ "uv", "sync" ], run_cmd: [ "uv", "run", "hello_receiver" ] }, } ``` * Rust peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_receiver", tag: "v1", description: ["A node that receives the greetings of one hello_world_param instance and prints them."], depends_on: { nodes: [ { name: "hello_world_param", tag: "v1", link_id: "hello_world_param", }, ] }, }, interfaces: { topics: { consumes: [ { link_id: "hello_world_param", name: "message_stream", } ], } }, execution: { language: "rust", build_cmd: [ "cargo", "build", "--release" ], run_cmd: [ "./target/release/hello_receiver" ] }, } ``` and the following source file: * Python src/hello_receiver/\_\_main\_\_.py ```python import asyncio from peppygen import NodeBuilder, NodeRunner from peppygen.consumed_topics.hello_world_param import message_stream from peppygen.parameters import Parameters async def setup(_params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(receive_messages(node_runner))] async def receive_messages(node_runner: NodeRunner): # Subscribe once; the held subscription buffers every message in order, so # iterating never drops a message published between iterations. subscription = await message_stream.subscribe(node_runner) async for producer, message in subscription: print(f"Received from {producer.instance_id}: {message.message}") def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/lib.rs ```rust use std::sync::Arc; use peppygen::consumed_topics::hello_world_param::message_stream; use peppygen::{NodeRunner, Parameters, Result}; /// The node's entry point. It lives in the library crate so tests can import /// it: the generated test harness (`peppygen::fixtures::harness::Harness`) /// boots it in-process, and `main.rs` delegates here for production runs. pub async fn setup(_params: Parameters, node_runner: Arc) -> Result<()> { tokio::spawn(receive_messages(node_runner)); Ok(()) } async fn receive_messages(node_runner: Arc) { // Subscribe once; the held subscription buffers every message in order, so // looping on `next` never drops a message published between iterations. let mut subscription = match message_stream::subscribe(&node_runner).await { Ok(subscription) => subscription, Err(e) => { eprintln!("Failed to subscribe: {e}"); return; } }; loop { match subscription.next().await { Ok(Some((producer, message))) => { println!("Received from {}: {}", producer.instance_id, message.message) } Ok(None) => break, Err(e) => { eprintln!("Error receiving message: {e}"); break; } } } } ``` For Rust, `peppy node init` scaffolds the node’s logic in `src/lib.rs` with a `src/main.rs` that only delegates to it (`peppygen::NodeBuilder::new().run(hello_receiver::setup)`); the split makes `setup` importable, so the [generated test harness](/advanced_guides/testing/) can boot the same node in-process. Finally, add this new node to the stack: 1. Sync the node interfaces: ```sh peppy node sync ``` 2. Add the node to the stack: ```sh peppy node add . ``` Tip You can combine both steps into a single command with `peppy node add . --sync` (or `-s`). Add `-b`/`-r` to also build or run in the same invocation, e.g. `peppy node add . -sb`. Note Make sure `hello_world_param` is already in the node stack, otherwise you might get the following error: ```text Error: `hello_receiver:v1` depends on `hello_world_param:v1`, but it does not exist in the stack ``` The `node add` and `node sync` commands both require the consumed nodes to be present in the node stack to generate the proper interfaces for the programming language they are written in. (`peppy node sync -r` can instead resolve missing dependencies from your configured repositories; see [Syncing against repositories](/advanced_guides/repositories/#syncing-against-repositories).) ## Starting the nodes [Section titled “Starting the nodes”](#starting-the-nodes) Now we need to make sure our nodes are started. If we take a look at our node stack: ```plaintext $ peppy stack list ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Core node: cn-sweet-buffalo (host: robot-host) │ ├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ │ Node stack │ │ │ │ ┌──────────────────────────────────────┬───────┬───────────┬────────────────────────────────────────────────────────────────────┐ │ │ │ NODE │ STAGE │ INSTANCES │ PATH │ │ │ ├──────────────────────────────────────┼───────┼───────────┼────────────────────────────────────────────────────────────────────┤ │ │ │ cn-sweet-buffalo:v0.10.0 │ Root │ 1 running │ ~/workspace/peppy │ │ │ │ hello_receiver:v1 │ Ready │ 0 │ ~/.peppy/built_nodes/hello_receiver_v1/a0c3e8f51b72d946.tar.zst │ │ │ │ hello_world_param:v1 │ Ready │ 0 │ ~/.peppy/built_nodes/hello_world_param_v1/4e7b2d19c6a8f053.tar.zst │ │ │ └──────────────────────────────────────┴───────┴───────────┴────────────────────────────────────────────────────────────────────┘ │ │ │ │ Instance bindings │ │ │ │ ┌──────────────────────────────────────┬──────────────────────────────┬─────────┬─────────┬──────────┬───────┬──────────┐ │ │ │ NODE │ INSTANCE │ STATUS │ HEALTH │ RESTARTS │ CLOCK │ BINDINGS │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────┤ │ │ │ cn-sweet-buffalo:v0.10.0 │ cn-sweet-buffalo │ running │ healthy │ 0 │ wall │ (none) │ │ │ └──────────────────────────────────────┴──────────────────────────────┴─────────┴─────────┴──────────┴───────┴──────────┘ │ │ │ │ Dependencies │ │ hello_receiver:v1 ➔ hello_world_param:v1 │ └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` We need to make sure that at least one instance is started for `hello_receiver:v1` and another one for `hello_world_param:v1`. Starting order does not affect message delivery: a subscriber started later still receives everything published after it binds, and the retained messages of a topic that [retains](/advanced_guides/topics/#retaining-the-latest-value). It does constrain `--link`, though: the producer instance must already exist to be named in the flag, so the producer starts first. Let’s start a `hello_world_param:v1` instance: ```plaintext $ peppy node run hello_world_param:v1 name=planet Running node hello_world_param:v1... Starting node hello_world_param:v1 with instance_id 'gifted-moser-9365' and 1 argument(s)... Calling node_run for hello_world_param:v1 (instance_id=gifted-moser-9365)... Log file: /home/ubuntu/.peppy/logs/run/gifted-moser-9365_20260124_100215_412.log Started node instance 'gifted-moser-9365' (pid: 76981) ``` Since our node requires a `name`, we provide it with that argument on startup. Note the producer’s instance id in the output (`gifted-moser-9365` here): a consumer receives messages only from the producers explicitly bound to its slots, so we need that id to start the receiver. Now let’s start the `hello_receiver` node, binding its `hello_world_param` slot to the producer instance with `--link LINK_ID@INSTANCE_ID`: ```plaintext $ peppy node run hello_receiver:v1 --link hello_world_param@gifted-moser-9365 Running node hello_receiver:v1... Starting node hello_receiver:v1 with instance_id 'vigorous-buck-8117' and 0 argument(s)... Calling node_run for hello_receiver:v1 (instance_id=vigorous-buck-8117)... Log file: /home/ubuntu/.peppy/logs/run/vigorous-buck-8117_20260124_100243_907.log Started node instance 'vigorous-buck-8117' (pid: 77190) ``` A producer slot left without a `--link` is an error: every declared producer slot must be bound (unless its cardinality is `zero_or_more`), and the run is rejected before the node spawns. A slot whose manifest declares `cardinality: "zero_or_one"` may instead be started unresolved with `--vacant-link 'SLOT='`, saying why it runs empty. (Pairing and observer slots follow the same shape: a `zero_or_one` participant or observer slot takes the same flag, and a `zero_or_more` slot of either kind needs no link at all.) When you start the node, you can see a path to the logs. In my case: `/home/ubuntu/.peppy/logs/run/vigorous-buck-8117_20260124_100243_907.log`. Each process of an instance writes its own file, named after the instance and the time it started. If we open it up: ```plaintext [2026-01-24T10:02:47.630] [stderr] Finished `release` profile [optimized] target(s) in 0.21s [2026-01-24T10:02:47.635] [stderr] Running `target/release/hello_receiver` [2026-01-24T10:02:51.243] [stdout] Received from gifted-moser-9365: hello planet count 7 [2026-01-24T10:02:54.243] [stdout] Received from gifted-moser-9365: hello planet count 8 [2026-01-24T10:02:57.244] [stdout] Received from gifted-moser-9365: hello planet count 9 ``` We can see the messages received from the `hello_world_param:v1` instance! ## Starting a second instance with different parameters [Section titled “Starting a second instance with different parameters”](#starting-a-second-instance-with-different-parameters) Now let’s push things a little further. Imagine we need a second instance with different parameters; we can start one like this: ```plaintext $ peppy node run hello_world_param:v1 name=you Running node hello_world_param:v1... Starting node hello_world_param:v1 with instance_id 'admiring-black-0614' and 1 argument(s)... Calling node_run for hello_world_param:v1 (instance_id=admiring-black-0614)... Log file: /home/ubuntu/.peppy/logs/run/admiring-black-0614_20260124_100412_118.log Started node instance 'admiring-black-0614' (pid: 78063) ``` The running receiver is still bound to `gifted-moser-9365` only, so it will not see the new producer: this slot has the default cardinality `one`, so it binds exactly one producer, and only the bound producer reaches it. To read the new instance instead, restart the receiver bound to it: ```plaintext $ peppy node stop vigorous-buck-8117 $ peppy node run hello_receiver:v1 -i vigorous-buck-8117 \ --link hello_world_param@admiring-black-0614 Running node hello_receiver:v1... Starting node hello_receiver:v1 with instance_id 'vigorous-buck-8117' and 0 argument(s)... ``` And we check the new run’s log: ```plaintext $ tail /home/ubuntu/.peppy/logs/run/vigorous-buck-8117_20260124_100441_052.log [2026-01-24T10:04:47.085] [stdout] Received from admiring-black-0614: hello you count 1 [2026-01-24T10:04:50.085] [stdout] Received from admiring-black-0614: hello you count 2 [2026-01-24T10:04:53.086] [stdout] Received from admiring-black-0614: hello you count 3 [2026-01-24T10:04:56.085] [stdout] Received from admiring-black-0614: hello you count 4 ``` The receiver now follows `admiring-black-0614`, and only it. `gifted-moser-9365` keeps publishing, but no binding names it anymore, so its messages reach no slot. (To consume both producers at once, declare the slot with `one_or_more` cardinality and repeat `--link` with one producer per flag, or declare two `one` slots with one `link_id` per producer; see [Bindings and routing](/advanced_guides/topics/#bindings-and-routing).) ```plaintext $ peppy stack list ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Core node: cn-sweet-buffalo (host: robot-host) │ ├────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ │ Node stack │ │ │ │ ┌──────────────────────────────────────┬───────┬───────────┬────────────────────────────────────────────────────────────────────┐ │ │ │ NODE │ STAGE │ INSTANCES │ PATH │ │ │ ├──────────────────────────────────────┼───────┼───────────┼────────────────────────────────────────────────────────────────────┤ │ │ │ cn-sweet-buffalo:v0.10.0 │ Root │ 1 running │ ~/workspace/peppy │ │ │ │ hello_receiver:v1 │ Ready │ 1 running │ ~/.peppy/built_nodes/hello_receiver_v1/a0c3e8f51b72d946.tar.zst │ │ │ │ hello_world_param:v1 │ Ready │ 2 running │ ~/.peppy/built_nodes/hello_world_param_v1/4e7b2d19c6a8f053.tar.zst │ │ │ └──────────────────────────────────────┴───────┴───────────┴────────────────────────────────────────────────────────────────────┘ │ │ │ │ Instance bindings │ │ │ │ ┌──────────────────────────────────────┬──────────────────────────────┬─────────┬─────────┬──────────┬───────┬───────────────────────────┐ │ │ │ NODE │ INSTANCE │ STATUS │ HEALTH │ RESTARTS │ CLOCK │ BINDINGS │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼───────────────────────────┤ │ │ │ cn-sweet-buffalo:v0.10.0 │ cn-sweet-buffalo │ running │ healthy │ 0 │ wall │ (none) │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼───────────────────────────┤ │ │ │ hello_receiver:v1 │ vigorous-buck-8117 │ running │ healthy │ 0 │ wall │ hello_world_param → │ │ │ │ │ │ │ │ │ │ admiring-black-0614@cn-sw │ │ │ │ │ │ │ │ │ │ eet-buffalo │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼───────────────────────────┤ │ │ │ hello_world_param:v1 │ gifted-moser-9365 │ running │ healthy │ 0 │ wall │ (none) │ │ │ │ │ admiring-black-0614 │ running │ healthy │ 0 │ wall │ (none) │ │ │ └──────────────────────────────────────┴──────────────────────────────┴─────────┴─────────┴──────────┴───────┴───────────────────────────┘ │ │ │ │ Dependencies │ │ hello_receiver:v1 ➔ hello_world_param:v1 │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` The `Instance bindings` table makes the routing explicit: `hello_receiver`’s instance resolved its `hello_world_param` slot to the one producer we bound, rendered as `instance_id@core_node` (its full wire address). A slot only ever receives from the producer bound to it: that is exactly why `vigorous-buck-8117` prints messages from `admiring-black-0614` and nothing from `gifted-moser-9365` above. *** We’ll explore [services](/advanced_guides/services/) and [actions](/advanced_guides/actions/) in the advanced guides, although they fundamentally work the same way. Refer to nodes in [this repository](https://github.com/Peppy-bot/nodes-hub.git) for more examples of topic/service/action usage. # Creating your first node > Learn how to create and run your first Peppy node Now that you have Peppy installed, let’s create your first node. A node is the fundamental unit of computation in Peppy - it represents a runnable application or service. In this guide, we’ll explore how nodes work and how they communicate with each other. You can think of nodes as compute units that are each responsible for a single job. For example, a node can: * Emit frames from a USB camera * Move a single actuator * Act as the brain of a robot by receiving input from sensors (audio, video, etc.) and emitting actions The key point is that **a node is responsible for performing a single function**. Code that several nodes share and that has no job of its own goes in a shared library; see [Choosing between a node and a shared library](/advanced_guides/node_or_library/). ## Project structure [Section titled “Project structure”](#project-structure) Run: * Python 1. Initialize the node: ```sh peppy node init --toolchain uv hello_world "A node that says hello to the world." ``` 2. Navigate into the directory: ```sh cd hello_world ``` Note [`uv`](https://docs.astral.sh/uv/) is the default Python toolchain in Peppy, but you can use any toolchain you prefer ([`pixi`](https://prefix.dev/), [`poetry`](https://python-poetry.org/), [`pip`](https://pip.pypa.io/en/stable), etc.). To do so, first initialize the node with `peppy node init --toolchain uv`, then add `peppygen = { path = ".peppy/libs/peppygen" }` and `peppylib = { path = ".peppy/libs/peppylib" }` as dependencies in your toolchain’s configuration, and update `build_cmd` and `run_cmd` in `peppy.json5` to match your toolchain’s commands. Peppy is designed to work with whichever tools you prefer. * Rust 1. Initialize the node: ```sh peppy node init --toolchain cargo hello_world "A node that says hello to the world." ``` 2. Navigate into the directory: ```sh cd hello_world ``` Note [`cargo`](https://doc.rust-lang.org/cargo/) is the default Rust toolchain in Peppy, but you can use any build system you prefer. To do so, first initialize the node with `peppy node init --toolchain cargo`, then add `peppygen = { path = ".peppy/libs/peppygen" }` and `peppylib = { path = ".peppy/libs/peppylib" }` as dependencies in your build configuration, and update `build_cmd` and `run_cmd` in `peppy.json5` to match your build system’s commands. Peppy is designed to work with whichever tools you prefer. `peppylib` needs Rust 1.100 or later. The second argument is the description of the node: what it does, and what it needs to run, such as a GPU or a device. The command refuses to run without it, or with a blank one. It becomes the first paragraph of `manifest.description` in `peppy.json5`, the summary that [`peppy repo search`](/advanced_guides/repositories/#search-the-repositories) prints (see [Descriptions](/reference/concepts/#descriptions)). In the node folder, you’ll find the following: * A `peppy.json5` file * A `.peppy` folder local to your node * A `.gitignore` that already excludes `.peppy` and the toolchain’s build artifacts * Your project scaffolding based on the selected toolchain ## Exploring the `peppy.json5` file [Section titled “Exploring the peppy.json5 file”](#exploring-the-peppyjson5-file) This is the entry point and the single source of truth for every node. All node interfaces and communication are defined in the `peppy.json5` configuration file, regardless of the programming language used. A developer who needs to understand or share a node can simply look at this configuration file and immediately know how it works without digging into the code. Everything in a `peppy.json5` is meant to be shared and distributed, so nothing local to your system should be added to this file. ## The `.peppy` folder [Section titled “The .peppy folder”](#the-peppy-folder) This is a cache folder that contains everything automatically generated by the `peppy` daemon. Nothing here should be modified manually, and the scaffolded `.gitignore` already keeps it out of version control. ## Writing your first node [Section titled “Writing your first node”](#writing-your-first-node) Let’s open the `peppy.json5` file of the node we just created and explore it together. * Python peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_world", tag: "v1", description: ["A node that says hello to the world."], }, interfaces: {}, execution: { language: "python", build_cmd: [ "uv", "sync", "--no-editable" ], run_cmd: [ "./.venv/bin/python", "-m", "hello_world" ] } } ``` * Rust peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_world", tag: "v1", description: ["A node that says hello to the world."], }, interfaces: {}, execution: { language: "rust", build_cmd: [ "cargo", "build", "--release" ], run_cmd: [ "./target/release/hello_world" ] } } ``` Let’s go through the different options: * `peppy_schema`: Identifies the structure of the configuration file. For node configs always set this to `"node/v1"` * `manifest`: Contains information about the node. Each node is identified by its `name` and `tag` * `description`: What the node does and what it needs to run, as a list of paragraphs. Add paragraphs after the first one when a reader needs more (see [Descriptions](/reference/concepts/#descriptions)) * `execution`: Contains the language and execution commands for the node * `language`: The programming language used by the node (e.g. `"python"`, `"rust"`) * `build_cmd`: Command run during the build phase of the node (e.g. via `peppy node build`, `peppy node add --build`, or the combined shorthands `peppy node add -sb` / `-sr`). This is typically the place where you want to run heavy operations like code compilation. * `run_cmd`: Command run when a node instance is started * `endpoints`: The sockets the node binds during setup, when it serves something an operator opens (see [Serving a page or an MCP endpoint](#serving-a-page-or-an-mcp-endpoint)) * `setup_timeout_secs`: Optional. The setup budget of the node: how long the daemon waits for the node’s `setup` function to return, from 1 to 540 seconds. Without it, the default setup budget of 15 seconds applies (see [How an instance starts](/guides/node_stack/#how-an-instance-starts)) * `interfaces`: This is where the interfaces used to communicate with the other nodes are defined Tag format A tag is **not** a semver version; bumping a tag always means “incompatible with the previous one”. Pick a short label that identifies the contract: `v1`, `v2`, `donut`, `experimental`, etc. Validation rules: * Must start with an ASCII letter (`a-z`, `A-Z`). * May contain letters, digits, `_` and `-` (same character set as node names). * Dots (`.`) are forbidden; `0.1.0` and `v1.2` are rejected. Let’s modify this configuration file to expose a topic that sends a “hello world” message. A topic that the node declares itself says what it carries in its `description`. * Python peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_world", tag: "v1", description: ["A node that publishes a greeting with a count, every 3 seconds."], }, interfaces: { topics: { emits: [ { name: "message_stream", description: "Each greeting, as text.", qos_profile: "sensor_data", message_format: { message: "string" }, } ], } }, execution: { language: "python", build_cmd: [ "uv", "sync" ], run_cmd: [ "uv", "run", "hello_world" ] }, } ``` * Rust peppy.json5 ```json5 { peppy_schema: "node/v1", manifest: { name: "hello_world", tag: "v1", description: ["A node that publishes a greeting with a count, every 3 seconds."], }, interfaces: { topics: { emits: [ { name: "message_stream", description: "Each greeting, as text.", qos_profile: "sensor_data", message_format: { message: "string" }, } ], } }, execution: { language: "rust", build_cmd: [ "cargo", "build", "--release" ], run_cmd: [ "./target/release/hello_world" ] }, } ``` To apply these changes, the node needs to synchronize with the cache in the `.peppy` folder. Run: ```sh peppy node sync ``` This command will generate the interfaces to use in our source code. If you’d rather sync, add, and build in a single step (useful once you’re iterating quickly), use `peppy node add -sb`, or `-sr` to also start an instance after the build. We can now modify the code and access those interfaces: * Python src/hello_world/\_\_main\_\_.py ```python import asyncio import logging from peppygen import NodeBuilder, NodeRunner from peppygen.emitted_topics import message_stream from peppygen.parameters import Parameters logger = logging.getLogger(__name__) async def emit_hello_world_loop(node_runner: NodeRunner): # Declare the publisher once, then publish each message on it. try: publisher = await message_stream.declare_publisher(node_runner) except Exception: logger.exception("Failed to declare message_stream publisher") return counter = 0 while True: counter += 1 message = f"hello world count {counter}" print(message, flush=True) try: await publisher.publish(message_stream.build_message(message)) except Exception: logger.exception("Failed to publish hello world") await asyncio.sleep(3) async def setup(params: Parameters, node_runner: NodeRunner) -> list[asyncio.Task]: return [asyncio.create_task(emit_hello_world_loop(node_runner))] def main(): NodeBuilder().run(setup) if __name__ == "__main__": main() ``` * Rust src/main.rs ```rust use std::sync::Arc; use std::time::Duration; use peppygen::emitted_topics::message_stream; use peppygen::{NodeBuilder, NodeRunner, Parameters, Result}; use peppylib::runtime::CancellationToken; /// Emits a "hello world count X" message every 3 seconds, starting immediately. /// The loop runs until the cancellation token is triggered. async fn emit_hello_world_loop(runner: Arc, token: CancellationToken) { // Declare the publisher once; every publish below is then lock-free. let publisher = match message_stream::declare_publisher(&runner).await { Ok(publisher) => publisher, Err(e) => { eprintln!("Failed to declare message_stream publisher: {e}"); return; } }; let mut counter: u64 = 0; let mut interval = tokio::time::interval(Duration::from_secs(3)); loop { tokio::select! { _ = token.cancelled() => break, _ = interval.tick() => { counter += 1; let message = format!("hello world count {counter}"); println!("{message}"); match message_stream::build_message(message) { Ok(payload) => { if let Err(e) = publisher.publish(payload).await { eprintln!("Failed to publish hello world: {e}"); } } Err(e) => eprintln!("Failed to build hello world message: {e}"), } } } } } fn main() -> Result<()> { NodeBuilder::new().run(async |_args: Parameters, node_runner| { let runner = node_runner.clone(); let token = node_runner.cancellation_token().clone(); // We use tokio::spawn to avoid blocking the closure tokio::spawn(emit_hello_world_loop(runner, token)); Ok(()) }) } ``` As you can see, the topic interface has already been generated. We didn’t need to implement serialization, encoding, or communication layers; Peppy handles all of that automatically. Additionally, the tag and name assigned to your node provide contract isolation. When the node’s interfaces change in a way that breaks consumers, you publish under a new tag (e.g. `v2`); dependent nodes that pin the old tag keep working until they are explicitly migrated. ## Graceful shutdown [Section titled “Graceful shutdown”](#graceful-shutdown) A node instance rarely gets to decide when it stops: [`peppy node stop`](/guides/node_stack/#stopping-your-node) stops it on demand, `peppy node add` stops running instances when it replaces a node, the daemon tears every node down when it shuts down cleanly, the daemon stops a start that it gives up after the node answered ready (a setup that outlasts its [setup budget](/guides/node_stack/#how-an-instance-starts), a `peppy stack reset`), and a plain `SIGINT`/`SIGTERM` works too. Every one of these paths gives your node the same two things: * The **cancellation token** (`node_runner.cancellation_token()`) fires. This is the signal to *stop working*: have long-running tasks watch it and break out of their loops. * **Shutdown hooks** registered with `node_runner.on_shutdown(...)` then run to completion, with messaging still connected. This is where *cleanup* belongs (parking actuators, releasing hardware, flushing state): unlike a task watching the token, a hook is awaited before the node exits on every path above. A node that ends any other way runs no hook: a `SIGKILL`, an abort, the OOM killer and a power cut end the process where it stands. So a hook carries the work only the node can do. Exclusivity belongs on something that ends with the process: a file lock for a device, or a key owned through [`store_exclusive`](/advanced_guides/datastore/#store_exclusive) for something only one peppy instance may drive at a time. The [shutdown lifecycle guide](/advanced_guides/shutdown/) says what a killed node leaves behind. - Python The hook callback may be a plain function or an `async def`: ```python async def setup(params, node_runner: NodeRunner): async def clear_latest(): # runs on the stop paths above, before the node's tasks are torn down await datastore.remove(node_runner, "hello_world_latest", response_timeout_secs=2.0) node_runner.on_shutdown(clear_latest) ``` The background tasks returned from `setup` are cancelled automatically after the hooks: their pending `await` raises `asyncio.CancelledError`, and the node exits once they finish. Keep `try`/`finally` for last-moment tidy-up; cleanup that must be guaranteed belongs in `on_shutdown`. - Rust The hello_world node above already follows the recommended pattern for stopping work: every spawned task `select!`s on `token.cancelled()` next to its work. Cleanup goes in a hook: ```rust let runner = node_runner.clone(); node_runner.on_shutdown(async move { // runs on the stop paths above, after the token fires, before run() returns if let Err(e) = datastore::remove(&runner, "hello_world_latest", TIMEOUT).await { tracing::warn!("failed to clear the latest message: {e}"); } }); ``` Do **not** put cleanup in a spawned task that watches the token instead: once the token fires the runtime begins tearing down, and a detached task is not guaranteed to run again. The whole shutdown is bounded by a grace period (`lifecycle.shutdown_grace_secs`, 5 seconds by default) for your cleanup to run: a node that shuts down cooperatively is reported as a clean stop, one that ignores the ask is force-killed, and `peppy node stop` warns about the latter. The [shutdown lifecycle guide](/advanced_guides/shutdown/) covers the full contract: every stop path, hook ordering, the grace windows, and Python’s task-teardown mechanics. ## Serving a page or an MCP endpoint [Section titled “Serving a page or an MCP endpoint”](#serving-a-page-or-an-mcp-endpoint) A node that serves something over the network, an operator panel, a viewer page, an MCP server, declares the sockets it binds under `execution.endpoints`. Each entry has a label, a `kind` (`page` for a URL an operator opens in a browser, `mcp` for one an MCP client attaches to) and a `description`. The declaration says *that* a socket is served under the label, never *where*: the port stays an ordinary parameter, the node decides the address at bind time (a port that is already taken can fall back to one the operating system picks) and announces what it got. peppy.json5 ```json5 { // ... execution: { language: "rust", parameters: { http_host: { $type: "string", $default: "0.0.0.0" }, http_port: { $type: "u16", $default: 8765 }, }, endpoints: { panel: { kind: "page", description: "The operator panel, HTTP and WebSocket." }, }, }, } ``` Inside `setup`, right after the bind, the node announces the socket under its label. Every declared label must be announced before `setup` returns, and nothing can be announced after: a label left unannounced fails the start with a message naming it. * Python ```python async def setup(params, node_runner: NodeRunner): server = ThreadingHTTPServer((params.http_host, params.http_port), Handler) host, port = server.server_address[:2] node_runner.announce_endpoint("panel", "http", host, port) threading.Thread(target=server.serve_forever, daemon=True).start() return [] ``` * Rust ```rust async fn setup(params: Parameters, node_runner: Arc) -> Result<()> { let listener = TcpListener::bind((params.http_host.as_str(), params.http_port)).await?; node_runner.announce_endpoint( "panel", EndpointBinding { scheme: "http".to_string(), address: listener.local_addr()?, path: String::new(), }, )?; tokio::spawn(serve(listener)); Ok(()) } ``` A Rust node that treats its port as a preference binds with `peppylib::runtime::bind_preferred(address)` in place of `TcpListener::bind`: it takes the address asked for, or a port the operating system picks on the same host address when another process holds that one, and answers the listener with whether it fell back. Any other bind failure is returned as it is. Announcing `listener.local_addr()` reports the port taken either way, which is how several copies of one node run side by side on one machine. The daemon that hosts the instance reads the announced sockets once the node is healthy and turns each one into the URLs an operator opens, one per address of that machine (a socket bound on `0.0.0.0` answers on every interface, so loopback comes first, then the others). Every command that starts or inspects instances prints them: `peppy node run` and `peppy stack launch` end with a `Web pages:` block and an `MCP endpoints:` block, `peppy stack list` has an `Instance endpoints` table, and `peppy node info` lists them under each instance. # Installation > How to install Peppy on your system To install `peppy`, run the following command in your terminal: ```sh curl -fsSL https://peppy.bot/install.sh | sh ``` The installer supports Ubuntu 24.04 or later and the Linux distributions built on it, Debian 13 or later (x86_64 and aarch64, tested on Ubuntu 24.04), Raspberry Pi OS (see [Raspberry Pi](#raspberry-pi)), and macOS on Apple Silicon. It recognises an Ubuntu-based distribution by `ID` or `ID_LIKE` in `/etc/os-release`, and Debian by `ID=debian` alone: a distribution that names Debian in `ID_LIKE` only, such as Devuan, is not supported. On Linux, Peppy needs a 64-bit system with glibc 2.38 or later. The installer reads the architecture of the packages with `dpkg --print-architecture`, because a 64-bit kernel can run a 32-bit system, and the glibc version with `getconf GNU_LIBC_VERSION`. It reads the glibc and not the release number, because a distribution built on Ubuntu numbers its releases its own way: Linux Mint 21, for example, is built on Ubuntu 22.04. On a 32-bit system, on an older glibc (glibc 2.35 on Ubuntu 22.04 and the distributions built on it, 2.36 on Debian 12), and on any other system, Fedora and Arch Linux among them, the installer stops with an error before it changes anything. On Linux, the installer runs `peppy container setup`, which installs the packages that container nodes need (`uidmap`, `squashfs-tools` and `fuse2fs`) and, where AppArmor restricts user namespaces, an AppArmor profile (see [Containers](/advanced_guides/containers/#setup-linux)). It does this in a Docker or Podman container also, where a bare image such as `ubuntu:24.04` or `debian:trixie` has none of these packages. In a container, the installer does not set up D-Bus and linger, which the background service of a host needs. A user that is not root in such a container starts each node from an unpacked copy of its image (see [Node images on overlayfs](/advanced_guides/containers/#node-images-on-overlayfs)). This installer also sets up the `peppy` background service and populates the repository index that name-based launches resolve from. To skip that step, set `PEPPY_NO_SERVICE_INSTALL=1`. The flag skips the repository setup along with the service, so a launch by name then fails with `nodes.json5 not found or empty` until you run `peppy repo init` and `peppy repo update` yourself. Note To install a specific version, set the `PEPPY_VERSION` environment variable: ```sh curl -fsSL https://peppy.bot/install.sh | PEPPY_VERSION="v0.20.0" sh ``` The installer can also unpack a release archive you already have, instead of downloading one: ```sh curl -fsSL https://peppy.bot/install.sh | sh -s -- ./peppy-x86_64-unknown-linux-gnu.tgz ``` If a daemon is already running, the installer asks for confirmation before replacing it; set `PEPPY_FORCE_REINSTALL=1` for non-interactive installs. Each Peppy version reads the content of the default repositories that was released with it (see [Repositories](/advanced_guides/repositories/)). Installing another Peppy version therefore also changes the hub content those repositories read, and the daemon reads it again at its next start. ### Raspberry Pi [Section titled “Raspberry Pi”](#raspberry-pi) Of the Raspberry Pi boards, the installer supports those built on the BCM2712 SoC: the Raspberry Pi 5, the Raspberry Pi 500 and the Compute Module 5. It recognises a Raspberry Pi board by a `raspberrypi,` entry in the `compatible` list of the device tree (`/sys/firmware/devicetree/base`), and the BCM2712 by `brcm,bcm2712` in the same list. The rule holds whatever the distribution: on an older board, such as the Raspberry Pi 4 or the Raspberry Pi 3, the installer stops with an error that names the board, on Raspberry Pi OS, Ubuntu and Debian alike. On these boards, the installer supports Raspberry Pi OS (64-bit) based on Debian 13 (trixie) or later, and the other distributions above. It recognises Raspberry Pi OS by the `/etc/rpi-issue` file of its image, and stops with an error before it changes anything on: * Raspberry Pi OS where the device tree names no board. Raspberry Pi OS runs on Raspberry Pi boards only. * the 32-bit Raspberry Pi OS. On a Raspberry Pi 5 it also runs a 64-bit kernel, and its packages are `armhf`, not `arm64`. * Raspberry Pi OS based on Debian 12 (bookworm), the release Raspberry Pi Imager lists as Legacy. Its glibc (2.36) is older than the 2.38 that Peppy needs. To install Raspberry Pi OS (64-bit), use [Raspberry Pi Imager](https://www.raspberrypi.com/software/). ### Installer environment variables [Section titled “Installer environment variables”](#installer-environment-variables) | Variable | Effect | | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PEPPY_VERSION` | Version to install (default: latest) | | `PEPPY_HOME` | Install prefix (default: `~/.peppy`) | | `PEPPY_BIN_DIR` | Binary install directory (default: `$PEPPY_HOME/bin`) | | `PEPPY_REPOURL` | Base URL for downloads (default: `https://peppy.bot`) | | `PEPPY_DOWNLOAD_URL` | Override the full download URL | | `PEPPY_NO_PATH_UPDATE` | If set, do not update the shell PATH config | | `PEPPY_FORCE_REINSTALL` | If set, skip the confirmation prompt when a daemon is running | | `PEPPY_NO_ROOT_INSTALL` | If set, never use sudo and install no package. The installer stops with an error that names each missing package that a container build needs and the command that installs them; a missing `fuse2fs` is a warning. The AppArmor profile is left to `peppy container setup` | | `PEPPY_NO_SERVICE_INSTALL` | If set, skip the service install and the repository init/refresh | | `PEPPY_NO_CONTAINER_SETUP` | If set, skip the Apptainer container setup, and so the packages that it installs | ## Verifying the installation [Section titled “Verifying the installation”](#verifying-the-installation) The service installs at user level by default; run `peppy service install` with sudo for a system-wide install. The snippets below assume the default user-level install. You can verify the service is running with: * Linux ```sh systemctl --user status peppy ``` * macOS ```sh launchctl list bot.peppy ``` **Managing the service (optional)** `peppy` ships its own platform-independent service commands, which are what the installer itself runs: ```sh peppy service install # install the background service peppy service stop # stop it peppy service uninstall # remove it ``` To drive the service through the platform’s own service manager instead: * Linux Start the service: ```sh systemctl --user start peppy ``` Stop the service: ```sh systemctl --user stop peppy ``` Restart the service: ```sh systemctl --user restart peppy ``` * macOS Start the service: ```sh launchctl load ~/Library/LaunchAgents/bot.peppy.plist ``` Stop the service: ```sh launchctl unload ~/Library/LaunchAgents/bot.peppy.plist ``` Restart the service: 1. Unload the service: ```sh launchctl unload ~/Library/LaunchAgents/bot.peppy.plist ``` 2. Reload the service: ```sh launchctl load ~/Library/LaunchAgents/bot.peppy.plist ``` # Launch files > Learn how to run all your nodes with a single launch file Launch files let you start multiple nodes simultaneously, including those with dependencies on each other. With a single launch file, you or your team can recreate an entire node environment using just one command. ## Running the example [Section titled “Running the example”](#running-the-example) Start by cloning [this repository](https://github.com/Peppy-bot/launchers-hub): 1. Clone the repository: ```sh git clone https://github.com/Peppy-bot/launchers-hub ``` 2. Navigate into the directory: ```sh cd launchers-hub ``` In the `examples/` directory, you’ll find a launcher file for each language. Opening it reveals the following structure: * Python [`examples/python_robot.json5`](https://github.com/Peppy-bot/launchers-hub/blob/main/examples/python_robot.json5) * Rust [`examples/rust_robot.json5`](https://github.com/Peppy-bot/launchers-hub/blob/main/examples/rust_robot.json5) 1. The file is identified by `peppy_schema: "launcher/v1"` at the root: peppy uses this to distinguish launcher files from node `peppy.json5` files (which use `"node/v1"`) 2. The `description` at the root says what the launcher starts and what it needs to run, such as a GPU, hardware or a simulation, as a list of paragraphs. It is required, and its first paragraph is the summary that `peppy repo search` prints. A launcher has no manifest, so its description sits at the root (see [Descriptions](/reference/concepts/#descriptions)). A [fragment](#fragments-splitting-a-launcher-across-files) has no description 3. All deployments are defined in the `deployments` array 4. Each deployment requires a `source` (the node to run, or the MCP exposures to serve) and an `instances` array (how many copies to start, and how each one is configured). Every entry needs an `instance_id`; `arguments`, `env_vars`, `env_from_launch`, `framework`, `core_node`, and `links` are optional. See [Instance attributes](#instance-attributes) for what each one does The `source` attribute references a node from your configured repositories by `name` and `tag`. Specify them as separate fields, or use the combined `name: ":"` shorthand. The node is resolved against your local nodes cache at `~/.peppy/cache/nodes.json5`. A source can instead list [MCP exposures](/advanced_guides/mcp/) to serve, as shown [below](#serving-mcp-exposures). If a node you want to deploy lives outside your configured repositories, add its location first: register a local directory with `peppy repo add /path/to/my/nodes`, or a git repository with `peppy repo add https://github.com/org/repo.git`. A repository states what it publishes through a committed `peppy_repository.json5`, so run `peppy repo index /path/to/my/nodes` to write it, and re-run it after adding, moving, or renaming a node, since the refresh reads the index rather than the filesystem. Then `peppy repo refresh` makes the nodes resolvable (see [Repositories](/advanced_guides/repositories/)). Note The source resolves nodes from the locally cached index of the machine the launch is submitted to. Run `peppy repo refresh` on that machine before launching to ensure its cache is up to date. In a federated launch it is the only machine whose cache matters: it resolves every deployment and its dependencies once and ships the result to the other machines as pinned content, so their caches need no refresh and cannot change what the launch runs. If a node or tag is missing from the cache, the launch fails with a “not found” error. If the cache instead contains the same `name:tag` **twice from one repository**, the launch fails with a distinct ambiguity error naming both manifests, never “not found”, since the node is present rather than absent. The refusal happens while sources are being resolved, before anything is added, built, or run, and it covers transitive dependencies too: an ambiguity two levels down is exactly as fatal as one at the top. See [Using a repository-indexed node](/advanced_guides/repositories/#using-a-repository-indexed-node). ```json5 // Repository source (long form) { source: { name: "openarm01_controller", tag: "v1", }, instances: [ { instance_id: "the_nervous_system" } ] } ``` ```json5 // Repository source (combined shorthand, equivalent to the example above) { source: { name: "openarm01_controller:v1", }, instances: [ { instance_id: "the_nervous_system" } ] } ``` #### Serving MCP exposures [Section titled “Serving MCP exposures”](#serving-mcp-exposures) A deployment whose `source` lists `exposures` runs the MCP server built into `peppy` for them instead of a node. Each entry is an [MCP exposure](/advanced_guides/mcp/) as `":"`, resolved against `~/.peppy/cache/mcp_exposures.json5`, and the contracts the exposures reference resolve through the contracts cache. The daemon derives the server’s node from those documents, so the deployment behaves like any other: its instances take `arguments` (the server’s single `port`), `links` for the contract slots the exposures’ contract targets become, and `core_node` for placement. A [daemon target](/advanced_guides/mcp/#daemon-targets) takes no link: the instance gives it a scope in [`daemon_scopes`](#daemon_scopes-optional). The list must not be empty or repeat an exposure, and two deployments cannot list the same set. ```json5 // Exposure source: the built-in MCP server serving two exposures on one port { source: { exposures: ["camera_and_recording:v1", "arm_status:v1"], }, instances: [ { instance_id: "mcp_server", arguments: { port: 8900 }, links: { front_camera: "front_cam_inst", recorder: "recorder_inst", arm: "arm_inst" }, } ] } ``` Caution A git ref pinned in `repositories.json5` and the node `tag` declared in `peppy.json5` are independent values, and they do not share the same format: git refs can contain dots (e.g. `v0.1.0`), but node tags must start with an ASCII letter and forbid dots (e.g. `v1`, `donut`). This means a repository could be pinned to the git ref `v0.1.0` while `peppy.json5` specifies `tag: "v1"`. Keep them coordinated so a checkout of a given git ref lines up with the tag your launcher expects. From within the cloned repository, execute the launcher: * Python ```sh peppy stack launch ./examples/python_robot.json5 ``` * Rust ```sh peppy stack launch ./examples/rust_robot.json5 ``` Peppy automatically inspects the `name` and `tag` of each node, verifies that all dependencies are met, and constructs the node stack in the correct order. ### Launching from a repository [Section titled “Launching from a repository”](#launching-from-a-repository) Launchers discovered by `peppy repo refresh` (see [Repositories](/advanced_guides/repositories/)) can be invoked by bare name, no path required: ```sh peppy stack launch openarm01_sim_teleop ``` An argument that contains a path separator or ends in `.json5` is resolved as a filesystem path: `./my_launcher.json5`, `/abs/my_launcher.json5`, `my_launcher.json5`. A bare name (no separator, no extension) is a repository launcher and is never looked up on disk, whatever the current directory holds: `peppy stack launch my_launcher` resolves through the repository cache at `~/.peppy/cache/launchers.json5` even when a `my_launcher.json5` sits next to the caller. Run `peppy repo refresh` first on the machine you submit the launch to; the launcher document, like every repository source, resolves on that machine alone. If the name resolves neither to a file nor to a cached launcher, the launch fails with an explicit “not found” error. If one repository provides two launcher files with that name, the launch fails with a distinct ambiguity error naming both: launchers are keyed by filename, so two identically named `.json5` files anywhere in one repository contest the same name even in different directories. Caution Running the `peppy stack launch` or `peppy stack build` command clears the existing node stack and stops all running instances A launch ends with the log file of every node it added, built and started, then the URLs the started instances serve, and the completion line. The URLs come from the nodes that declare [`execution.endpoints`](/guides/first_node/#serving-a-page-or-an-mcp-endpoint): the daemon hosting each instance expands the socket the node announced into one URL per address of its machine, loopback first, and the core node name after the `@` says which machine that is. Pages an operator opens in a browser and endpoints an MCP client attaches to are printed under separate headings, `Web pages:` before `MCP endpoints:`, and a heading appears only when it has an entry. `peppy stack join` prints the same blocks for the instances the copy started. ```plaintext Node log files: ... Web pages: alpha_commander_inst (openarm_web_commander:v1) @cn-sweet-edison panel http://127.0.0.1:8765 http://100.123.58.116:8765 simulation_inst (waldo:v1) @cn-sweet-edison viewer https://127.0.0.1:8080/ https://100.123.58.116:8080/ MCP endpoints: robot_control_inst (mcp_robot_control_v1:builtin) @cn-sweet-edison robot_control_v1 http://127.0.0.1:8900/robot_control/v1/mcp world_control_inst (mcp_simulation_v1:builtin) @cn-sweet-edison simulation_v1 http://127.0.0.1:8902/simulation/v1/mcp Launch completed successfully ``` Verify that the node stack was configured correctly: ```plaintext $ peppy stack list ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Core node: cn-adoring-zebra (host: robot-host) │ ├───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ │ Slice of launch launch-brave-otter (coordinator: cn-adoring-zebra) │ │ │ │ Node stack │ │ │ │ ┌──────────────────────────────────────┬───────┬───────────┬────────────────────────────────────────────────────────────────────────────┐ │ │ │ NODE │ STAGE │ INSTANCES │ PATH │ │ │ ├──────────────────────────────────────┼───────┼───────────┼────────────────────────────────────────────────────────────────────────────┤ │ │ │ cn-adoring-zebra:v0.10.0 │ Root │ 1 running │ ~/workspace/peppy │ │ │ │ fake_openarm01_controller:v1 │ Ready │ 1 running │ ~/.peppy/built_nodes/fake_openarm01_controller_v1/b81d0e4c72a5f936.tar.zst │ │ │ │ fake_robot_brain:v1 │ Ready │ 1 running │ ~/.peppy/built_nodes/fake_robot_brain_v1/6c2e9f0a1d47b385.tar.zst │ │ │ │ fake_uvc_camera:v1 │ Ready │ 2 running │ ~/.peppy/built_nodes/fake_uvc_camera_v1/e57a3b91c0d64f28.tar.zst │ │ │ │ fake_video_reconstruction:v1 │ Ready │ 1 running │ ~/.peppy/built_nodes/fake_video_reconstruction_v1/19d4c7e2a8b03f65.tar.zst │ │ │ └──────────────────────────────────────┴───────┴───────────┴────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ Instance bindings │ │ │ │ ┌──────────────────────────────────────┬──────────────────────────────┬─────────┬─────────┬──────────┬───────┬──────────────────────────────────────────────────────────────────────────────┐ │ │ │ NODE │ INSTANCE │ STATUS │ HEALTH │ RESTARTS │ CLOCK │ BINDINGS │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────────────────────────────────────────────────────────────────────────┤ │ │ │ cn-adoring-zebra:v0.10.0 │ cn-adoring-zebra │ running │ healthy │ 0 │ wall │ (none) │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────────────────────────────────────────────────────────────────────────┤ │ │ │ fake_openarm01_controller:v1 │ vibrant-keller-2310 │ running │ healthy │ 0 │ wall │ (none) │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────────────────────────────────────────────────────────────────────────┤ │ │ │ fake_robot_brain:v1 │ zealous-bohr-5512 │ running │ healthy │ 0 │ wall │ fake_openarm01_controller → vibrant-keller-2310@cn-adoring-zebra │ │ │ │ │ │ │ │ │ │ fake_uvc_camera → mystic-galois-7701@cn-adoring-zebra │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────────────────────────────────────────────────────────────────────────┤ │ │ │ fake_uvc_camera:v1 │ mystic-galois-7701 │ running │ healthy │ 0 │ wall │ (none) │ │ │ │ │ brave-noether-3098 │ running │ healthy │ 0 │ wall │ (none) │ │ │ ├──────────────────────────────────────┼──────────────────────────────┼─────────┼─────────┼──────────┼───────┼──────────────────────────────────────────────────────────────────────────────┤ │ │ │ fake_video_reconstruction:v1 │ gallant-curie-4417 │ running │ healthy │ 0 │ wall │ fake_uvc_camera → brave-noether-3098@cn-adoring-zebra │ │ │ └──────────────────────────────────────┴──────────────────────────────┴─────────┴─────────┴──────────┴───────┴──────────────────────────────────────────────────────────────────────────────┘ │ │ │ │ Dependencies │ │ fake_robot_brain:v1 ➔ fake_openarm01_controller:v1 │ │ fake_robot_brain:v1 ➔ fake_uvc_camera:v1 │ │ fake_video_reconstruction:v1 ➔ fake_uvc_camera:v1 │ └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` The output confirms that all nodes have been added to the stack along with their dependency relationships. When an instance serves an endpoint, an `Instance endpoints` table follows the bindings, one row per URL with the endpoint’s `KIND` and `LABEL`. The `Instance bindings` table breaks that down per instance: the consumers (`fake_robot_brain`, `fake_video_reconstruction`) list the `depends_on` slots they resolved, while the producers (`fake_openarm01_controller`, `fake_uvc_camera`) and the core node declare no slots and show `(none)`. A resolved binding shows the chosen producer(s) as `instance_id@core_node`, ordered by link ID; a multi-cardinality slot lists every bound member in plan order, and an empty slot, whether a `zero_or_more` slot bound to nothing or a `zero_or_one` slot declared vacant, shows `(empty set)`. Every declared producer slot (`depends_on.nodes` / `depends_on.contracts`) is either bound or, where its manifest declares `cardinality: "zero_or_one"`, declared [`vacant`](#links-optional); only a `zero_or_more` slot may be left out entirely, and a launcher that leaves any other one out is rejected at validation (see [dependency cardinality](/advanced_guides/topics/#dependency-cardinality)). Pairing and observer slots follow the same shape: a participant slot is paired and an observer slot is linked, or, where its manifest declares it `cardinality: "zero_or_one"`, declared vacant, unless its cardinality is `zero_or_more`, where omitting it IS its empty set. The launch also prints a `Slice of launch ...` line above the tables naming the launch that produced this stack and its coordinator. ## Instance attributes [Section titled “Instance attributes”](#instance-attributes) Every entry in an `instances` array configures one running copy of the deployment’s node. Two instances of the same node are independent: they get their own arguments, their own environment, and their own bindings. peppy_launcher.json5 ```json5 { source: { name: "uvc_camera:v1" }, instances: [ { instance_id: "camera_front", arguments: { device: { path: "/dev/video0" }, frame_rate: 30 }, env_vars: { GST_DEBUG: "2" }, framework: { clock: "simulation" }, }, { instance_id: "camera_rear", arguments: { device: { path: "/dev/video1" }, frame_rate: 15 }, }, ], } ``` ### `instance_id` (required) [Section titled “instance_id (required)”](#instance_id-required) The name this copy runs under. It labels the instance in `peppy stack list`, in its log file, and in every `links` value that points at it. Allowed characters are letters, digits, `_` and `-`. The id must be unique across the whole stack, not just within its own deployment: two deployments cannot both declare `camera_front`, and no instance may take the core node’s own id. A collision is reported before anything starts. ### `arguments` (optional) [Section titled “arguments (optional)”](#arguments-optional) Values for the parameters the node declares in its `execution.parameters` block, written with the same nesting as that schema. See the [Parameters reference](/reference/parameters/) for the full syntax. A parameter that declares a `$default` may be omitted, and the daemon fills it in before the node starts. A required parameter left without a value fails the launch as that instance starts, naming the leaf it is missing (`Missing required parameters: device.serial`). Unknown keys and type mismatches are caught by the node itself as it boots, so they surface as that instance failing to come up. A [container node](/advanced_guides/containers/) can also reference these values in its `mount_paths` with `${parameters:}`, which is how two instances of one node mount two different host devices. ### `env_vars` (optional) [Section titled “env_vars (optional)”](#env_vars-optional) Environment variables for this instance’s process. `peppy stack launch` forwards a filtered copy of your shell environment to the instances it starts on the machine you launch from, so a node there already sees your `PATH` and the rest. The filter drops `PWD`, `OLDPWD`, `TMPDIR`, `TEMP`, `TMP`, `PYTHONPATH`, and `PYTHONHOME`, plus any name that is not a shell identifier, any value with whitespace or shell metacharacters, and the injection-prone names listed below. `PYTHONPATH` and `PYTHONHOME` are stripped so a caller shell that exports them cannot displace a container node’s vendored `peppylib`/`peppygen` path; a node that genuinely needs either sets it through its own `env_vars`. An instance placed on another machine receives only its declared `env_vars`. `env_vars` is layered on top of the forwarded set for what differs per instance (a device path, a board serial, a log level), and a name declared here replaces the forwarded value: ```json5 { source: { name: "esp32_board:v1" }, instances: [ { instance_id: "esp32_left", env_vars: { ESP32_DEVICE: "/dev/ttyUSB0" } }, { instance_id: "esp32_right", env_vars: { ESP32_DEVICE: "/dev/ttyUSB1" } }, ], } ``` Entries are checked when the launcher file is read, before the running stack is touched: * **Names** must be shell identifiers: a letter or `_` first, then letters, digits and `_`. `ESP32_DEVICE` is fine, `esp32-device` is not. * **Values** may hold letters, digits and `_ - . / : , = @ + %`. Whitespace, quotes and shell metacharacters (`;`, `$`, `` ` ``, `|`, and friends) are rejected, so a value like `"--flag other"` has to reach the node another way, typically as an [argument](#arguments-optional). * **Injection-prone names** are rejected outright: the dynamic-linker and shell hooks (`LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`, `BASH_ENV`, `IFS`, and the rest of that family). Note The name and value rules exist because a container node receives its environment through Apptainer, which forwards each variable under the `APPTAINERENV_` prefix into a script the container sources at startup, where the shell expands the value. A name that is not a shell identifier would not parse as an assignment, and a value carrying `$`, a backtick or a quote would be expanded or run inside the container rather than arriving as written. The same rule applies to process nodes so that adding a `container` block to a node later cannot break the launchers that already deploy it. `env_vars` reach the instance when it starts. Fetching and building a node happen once for the node, not once per instance, so a variable your build needs (a registry token, a toolchain path) belongs in the shell you run `peppy stack launch` or `peppy stack build` from, where it is forwarded to build steps on that machine too, unless the launcher names it in an [`env_from_launch`](#env_from_launch-optional): such a variable reaches only the run of the instances that name it. A build on another machine sees none of your caller environment: your environment describes your machine, so it stays there. A value that must not be in a launcher file, such as the API key of a hosted model, goes in [`env_from_launch`](#env_from_launch-optional) instead. ### `env_from_launch` (optional) [Section titled “env_from_launch (optional)”](#env_from_launch-optional) The variables this instance takes from the environment of the launch, by name. Use it for a value that no launcher file holds: a secret, such as the API key of a hosted model, or a value that each user sets in their own shell. Use `env_vars` for a value that the launcher file can hold, such as a device path or a log level. hosted_brain_arm.json5 ```json5 // A simulated arm whose brain asks a hosted model: the launch starts no arm, // and each stack.join of the framework's endpoint adds one. // // GEMINI_API_KEY=... peppy stack launch hosted_brain_arm { peppy_schema: "launcher/v1", description: [ "A simulated arm whose brain asks a hosted model, added over MCP with stack.join.", "The shell that launches exports GEMINI_API_KEY: the daemon keeps it and gives it to the brain of each arm that joins.", ], components: [ { name: "simulation", cardinality: "one", provides: ["simulation_inst"], options: { waldo: "../simulation/fragments/waldo.json5" }, }, { name: "robot_control", cardinality: "one", options: { robot_control: { fragments: ["fragments/framework_controls.json5", "fragments/robot_control.json5"], }, none: "../common/fragments/none.json5", }, }, { name: "robot", cardinality: "zero_or_more", options: { demo_arm: { deployments: [ { source: { name: "demo_arm_backbone", tag: "v1" }, instances: [ { instance_id: "backbone_inst", links: { arm: "simulation_inst/arms" } }, ], }, { source: { name: "demo_hosted_brain", tag: "v1" }, instances: [ { instance_id: "brain_inst", arguments: { model: "gemini-robotics-er-2-preview" }, links: { limb_motion: "backbone_inst" }, // The key of the provider of the model: the daemon takes it // from the launch environment and gives it to this instance // in the launch and in each later join. env_from_launch: ["GEMINI_API_KEY"], }, ], }, ], }, }, }, ], // No copy is listed: the launch starts no arm, and each stack.join adds one. deployments: [ { simulation: "waldo" }, { robot_control: "robot_control" }, { robot: "demo_arm" }, ], adjustments: [ // The framework's endpoint adds up to two arms. { target: "framework_controls_inst", when: { robot_control: "robot_control" }, set_daemon_scopes: { stack: { max_copies: 2, options: [ { option: "demo_arm", model: "demo_arm", description: "A simulated arm with a brain on a hosted model", }, ], }, }, }, ], } ``` The launch gives the instance the value of each variable from the environment that `peppy stack launch` forwards. A launch variable is each name that an `env_from_launch` or a `set_env_from_launch` of the launcher or of the fragments of its options holds. Its value reaches the run of each instance that names it, and nothing else: no other instance, and no add or build step, gets it, also on the coordinator. An empty value counts as no value, as when a shell sources a `.env` template that leaves the key unset. The daemon keeps, in memory only, the value of each launch variable that the forwarded environment of the launch holds. A later join gives each instance that it starts the kept value of each variable that the instance names. So a robot that a client adds through `stack.join` gets the key of its brain, and no file holds the key. The values belong to the stack: `peppy stack reset` and a stop of the daemon drop them. A launch that replaces the running stack drops the values of that stack and keeps the values of its own forwarded environment. A launcher that deploys an instance from a shared fragment names its variables with a [`set_env_from_launch`](#adjustments) adjustment, for example beside the models that it sets: ```json5 { target: "brain_inst", when: { brain: "vlm_router_brain" }, set_arguments: { perception_model: "gemini-robotics-er-2-preview", manipulation_model: "gemini-robotics-er-2-preview", }, set_env_from_launch: ["GEMINI_API_KEY"] }, ``` A node that changes the service that it calls while it runs, for example a brain that switches its model, needs the key of each service that it can switch to: the launcher names them all. A switch to a model whose key the instance does not have fails in the node, with the node’s message. The environment of an instance in each case: | The instance starts | Its environment | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | In the launch, on the coordinator | The forwarded environment of the launch without its launch variables, then the value of each variable of its `env_from_launch`, then its `env_vars`. The launch environment holds each variable of its `env_from_launch`, or the launch does not start. | | In `peppy stack join`, on the coordinator | The forwarded environment of the join without its launch variables, then the value of each variable of its `env_from_launch`: the one that the join forwards, else the kept one, then its `env_vars`. | | In a join through `robot_membership:v1`, from the framework’s endpoint or from the applier of worlds | The kept value of each variable of its `env_from_launch`, then its `env_vars`. Such a join forwards no environment, so a variable of the launch environment that the instance does not name does not reach it. | | On a peer | Its `env_vars` only. An instance with `env_from_launch` does not run on a peer. | Launch variables reach the run of an instance only. The add and build steps of a join through `robot_membership:v1` get no environment, and the add and build steps of a launch and of `peppy stack join` get the forwarded environment of that command without its launch variables. A name follows the name rules of `env_vars` and is none of the names that the CLI never forwards: `PWD`, `OLDPWD`, `TMPDIR`, `TEMP`, `TMP`, `PYTHONPATH` and `PYTHONHOME`. A list names each variable once, and an empty list is the same as no list. A list is a set: its order does not matter, `peppy stack resolve` writes it in name order, and two lists of the same names in another order are the same list, so a copy that writes them on a running instance changes nothing. Each refusal names the launcher file, the instance or the adjustment, and the variable. A name that is in the `env_vars` and in the `env_from_launch` of the same instance after the adjustments is refused, because the variable would get two values: the launch checks it on the stack and on each trial copy of its scopes, each join on the copy that it composes, and [`peppy stack resolve`](#auditing-a-composed-launch) on the file that it prints. One refusal names every such instance and variable. `peppy stack resolve` prints the `env_from_launch` of each instance after the adjustments, names only, so the flat file launches the same. The launch is refused when an instance that it starts, or that a join through a `robot_membership` scope of the launch can start, takes a variable that its forwarded environment does not hold. The instances that a join can start are those of the trial copies of the scope, each option with its launcher entry and with each set of its features (see [Building the nodes a join brings](#building-the-nodes-a-join-brings)), also with `--no-prebuild`. So a `set_env_from_launch` under the `when` of a feature counts. The refusal comes before the launch stops the running stack, builds or starts anything: the running stack and its kept values stay as they are. One message names each missing variable, each instance that needs it, and the option or the feature that can start that instance, with each instance whose scope offers it. Without `GEMINI_API_KEY`, the launch of the example above stops with: ```plaintext the launch needs `GEMINI_API_KEY`, and the launch environment does not hold it, or holds it empty or with characters that a node cannot receive: `brain_inst` of option `demo_arm` takes it from the launch, and stack.join through `framework_controls_inst` can add a copy of `demo_arm`. Export `GEMINI_API_KEY` in the shell that launches. A value must not be empty, and must hold letters, digits and `_ - . / : , = @ + %` only ``` The CLI does not forward a value with characters that a node cannot receive (see [`env_vars`](#env_vars-optional)), and the daemon counts an empty value as no value, so the message names these causes too. [`peppy stack resolve`](#auditing-a-composed-launch) names each variable that a launch needs before you launch. With `robot_control=none`, no `stack.join` can add an arm, so the same launch needs no key. An instance that only a word of the CLI selects, such as an option of an own axis that no feature of a scope offers, does not make each launch need its variables. A `peppy stack join` that starts it is refused, with the same message, when neither the forwarded environment of the join nor the kept values hold one of them. `peppy stack build` starts nothing, so it checks no variable and keeps no value. An instance with launch variables runs on the coordinator’s machine only: a value of the launching shell stays on the machine where you typed it. A launch or a join that places such an instance on a peer is refused, naming the instance and the peer. No value of a launch variable appears in a log line, a feedback line, an error, the output of `peppy stack list`, the fleet listing, an MCP answer, a file of the data root or a command line: logs and errors name the variables only. On macOS, the environment of a container node reaches apptainer in the Lima VM on the standard input of the command, not on a command line that the process list shows. ### `framework` (optional) [Section titled “framework (optional)”](#framework-optional) Framework knobs peppy reads the same way for every node. The block holds two knobs: * `clock`: the timeline this instance reads, naming `wall` or a domain the launcher declares under [`framework.clocks`](#clock-domains). An instance that omits it reads wall time. An instance a declaration names as a domain’s publisher carries no `clock` of its own, since that declaration already assigns it one. See [System clock](/advanced_guides/system_clock/#clock-domains). * `restart`: what the daemon does when this instance’s process exits on its own or stops answering health checks, `never`, `on_failure` or `always`, or `{ policy, max_restarts }`. It wins over the node’s own `framework.restart` and the launcher root’s. See [Restart policy](#restart-policy). An unknown key inside `framework` fails the launch, so a typo surfaces where it is written. ### `core_node` (optional) [Section titled “core_node (optional)”](#core_node-optional) The machine this instance runs on, named by one of the placeholders the launcher declares under `core_nodes`. An instance that omits it runs on the daemon you launched from. See [Running one launcher across several machines](#running-one-launcher-across-several-machines). ### `links` (optional) [Section titled “links (optional)”](#links-optional) One map filling every kind of `depends_on` slot the node declares, keyed by the slot’s `link_id`. A value is interpreted against the slot it names: * a producer slot (`depends_on.nodes` / `depends_on.contracts`) takes the producer instance to bind: a scalar for a `one` or `zero_or_one` slot, an array for a multi-cardinality slot; * a [pairing](/advanced_guides/pairing/) participant slot takes the peer instance(s) to pair with, each `""` or `"/"` to disambiguate which of the peer’s slots to use: a scalar for a `one` or `zero_or_one` slot, an array for a [multi-cardinality slot](/advanced_guides/pairing/#pairing-with-several-peers-through-one-slot), one pair per entry; * an [observer](/advanced_guides/pairing/#observing-several-pairings-through-one-slot) slot takes the source instance(s) to observe, each `""` or `"/"`: a scalar for a `one` slot, an array for a multi-cardinality slot, in the order the node reads them back. A slot that starts unresolved on purpose says so here too, as `{ vacant: "" }`. That value binds nothing and covers the slot, so the fate of every declared slot is one entry in this one map and a slot you forgot is an absence rather than a value. The reason is required, is trimmed, and travels with the instance, so `peppy stack launch` reports it back when the node starts. Vacancy is a two-sided contract, and the node owns one side of it. A slot is vacatable only where the node’s own manifest declares it emptiable, with `cardinality: "zero_or_one"` on the `depends_on.pairings`, `depends_on.pairing_observers`, `depends_on.nodes` or `depends_on.contracts` entry. On a slot the manifest declares required, a vacancy is rejected and the error names the manifest key that would lift the bar. Every other slot is rejected with the spelling it does have: a `zero_or_more` slot, producer or observer, writes its empty set as `[]` (or omits the key), and a `one_or_more` slot of either kind has no empty state at all. The manifest says “may be empty”, the launcher says “is empty here, because”, and forgetting the slot entirely stays an error whichever the manifest says. One instance filling all three kinds, plus a slot left deliberately empty: ```json5 { source: { name: "session_recorder:v1" }, instances: [ { instance_id: "rec_1", links: { // Producer slots: `storage` is `one`, `cameras` is multi-cardinality. storage: "disk_1", cameras: ["cam_left", "cam_right"], // A participant slot names the peer to pair with, with // `/` when the peer declares more than one slot. arm: "arm_1/limb", // A scalar observer slot names a single source instance to observe. // The multi cardinalities take these same values in an array. watch: "ctrl_1", // A slot this deployment leaves empty on purpose, and why. The // manifest declares `gripper` `cardinality: "zero_or_one"`, which is // what makes this legal. gripper: { vacant: "bench rig: no gripper on this frame" }, }, }, ], } ``` Every target must name an `instance_id` declared somewhere in the same launcher. Two instances of the same node can choose different fates for the same slot, which is why the decision is written per instance rather than in the node’s manifest (whose `cardinality: "zero_or_one"` on this slot only says that some deployment may make it): ```json5 instances: [ { instance_id: "backbone_governed", links: { leader_left_arm: "commander_inst/left_arm" }, }, { instance_id: "backbone_monitor", links: { leader_left_arm: { vacant: "monitor rig: nothing commands this backbone" } }, }, ] ``` ### `daemon_scopes` (optional) [Section titled “daemon_scopes (optional)”](#daemon_scopes-optional) The scope of each daemon target of the instance, keyed by the target’s name: what a client of the target may do through the daemon interface it names. An instance has the daemon targets of its deployment: those of the exposures of an [exposure deployment](#serving-mcp-exposures) (see [daemon targets of an exposure](/advanced_guides/mcp/#daemon-targets)), or those that the manifest of a node lists in `depends_on.daemon`, each named by its `link_id` (see [daemon targets of a node](/advanced_guides/core_node_functions/#daemon-targets)). Only an instance with a daemon target takes `daemon_scopes`. A daemon target takes a scope and no link. mcp_framework_controls.json5 ```json5 // Deploying an exposure with a daemon target: the robots run as copies, and // the framework's endpoint lets a client add and remove them. // // peppy stack launch mcp_framework_controls { peppy_schema: "launcher/v1", description: ["Simulated robots that run as copies, OpenArm or SO-101, and the MCP endpoint framework_controls:v1, through which a client adds and removes them. It needs a machine that runs the simulation."], components: [ { name: "robot", cardinality: "zero_or_more", options: { // Its fragment declares the own axis `brain`, whose option // `ai_brain_vla` deploys the brain's instance. openarm_sim: "robots/fragments/openarm_sim.json5", so101_sim: "robots/fragments/so101_sim.json5", }, }, ], deployments: [ { source: { exposures: ["framework_controls:v1"] }, instances: [ { instance_id: "framework_controls_inst", arguments: { port: 8903 }, // The daemon targets take no link. Each takes a scope, keyed by // the target's name. The instance has no `core_node`: an instance // that serves a daemon target runs on the coordinator. daemon_scopes: { // The members of robot_leases:v1 that the endpoint calls: a client // lists the fleet and halts the stack. Without `clear_halt`, the // endpoint serves no fleet.clear_halt, and the halt ends with // `peppy fleet clear-halt`. fleet: { members: ["list", "halt"] }, stack: { max_copies: 4, options: [ { option: "openarm_sim", // The robot model a robot of the option is, which a // client reads before it adds one. model: "openarm_v2", description: "A simulated OpenArm v2 standing on the floor: two arms with grippers", // A feature selects one option of one own axis of the // option, here `brain=ai_brain_vla`. A client adds a robot // with it, and names the machine of its part. features: [ { feature: "ai_brain", axis: "brain", option: "ai_brain_vla", description: "An AI brain that finds items by words, then grabs and places them", }, ], }, { option: "so101_sim", model: "so101", description: "A simulated SO-101 clamped on the edge of a table: one arm with a gripper", }, ], }, }, }, ], }, ], } ``` `{ vacant: "" }` leaves a daemon target unserved: the server of an exposure serves none of its entries, and the daemon refuses each call of a node through it. The reason is required. For example, a launcher whose robots no client may add or remove leaves the `stack` target of its framework endpoint vacant. When the launcher is read, a scope is a free value, because only the resolution of the deployments knows which targets are daemon targets. A launcher that writes its options in its own file and its endpoint in a fragment gives the scope with a top-level [`set_daemon_scopes`](#adjustments) adjustment instead. A scope belongs to the stack: a [copy](#copies) writes none. The launch, each join and [`peppy stack resolve`](#auditing-a-composed-launch) parse every scope into the type of its interface before anything starts. These checks read the launcher, the exposure documents and the node manifests only, so `peppy stack resolve` runs those of the exposure deployments also when the nodes cache is empty. It reads the manifest of a node from the nodes cache, and its report names each node deployment whose manifest this machine’s caches do not hold, whose checks did not run. A launch refuses a node whose daemon target names an interface, or a tag of it, that this peppy does not serve. The checks refuse: * `daemon_scopes` on an instance that has no daemon target; * a scope key that is not a daemon target of the instance; the refusal says so when the key is a target or a slot that takes `links`; * a daemon target with no scope; * a scope that does not parse into the type of its interface, for example a [`robot_membership` scope](/advanced_guides/mcp/#scopes) with no option, with an option that names no `model`, with `max_copies` 0, with `features: []`, or with two features of one option on the same axis, or a [`robot_leases` scope](/advanced_guides/core_node_functions/#scoping-a-daemon-target) with no member or with a member named twice; * an instance with a daemon target that does not run on the coordinator: one that declares `core_node`, or one of a copy; * a `links` key that names a daemon target: the refusal says that the target takes a scope; * an instance with two daemon targets of one interface: a call names no target, so a call of an interface goes with the one scope of that interface that the instance has. The launch and `peppy stack resolve` also hold each scope against the launcher and the stack selection, and refuse: * a `robot_membership` scope that names an option that is not an option of an axis that runs as copies, with the menu of the options a join can add; in a launcher that declares no such axis, a flat launcher included, every `robot_membership` scope; * a feature of a `robot_membership` scope that selects an axis that is not an own axis of its option, an option that its axis does not have, or an option that brings no instance; * an option of a `robot_membership` scope whose copy does not compose as a join over the bare stack with one of its feature sets (no feature, each feature, each combination), or whose copy with no feature already holds one of its features. The refusal names the option and the features of the set. Each of these three checks runs only when the ones before it hold (see [the scope checks](/advanced_guides/mcp/#scopes)). A join holds each scope to the first list only: the launcher and the stack selection of a launch do not change, so a join cannot change the verdict of the second. The refusals of every instance are reported at once. An instance reads its scopes from its runtime configuration. A node with a daemon target that starts without these checks, for example with `peppy node run`, has no scope. The server reads its scopes from the runtime configuration of its instance when it starts. A server that starts without these checks, for example with `peppy node run` of its node, and finds a daemon target with no scope or a scope that does not parse, serves nothing and stops, and its run log says which target lacks a scope and how to give one (see [Deploy it](/advanced_guides/mcp/#deploy-it)). ## Clock domains [Section titled “Clock domains”](#clock-domains) A launcher declares the timelines its instances read in a root-level `framework` block, beside `deployments`: peppy_launcher.json5 ```json5 { peppy_schema: "launcher/v1", description: ["An OpenArm in the Waldo simulation, on the clock of the simulation. It needs a machine that runs the simulation."], framework: { clocks: { // One instance supplies this timeline, and naming it here is what // makes `simulation_inst` the domain's publisher. simulation: { publisher: "simulation_inst" }, // A name for the time every machine already keeps. physical_robot: "wall", }, }, deployments: [ { source: { name: "waldo", tag: "v1" }, instances: [{ instance_id: "simulation_inst" }], }, { source: { name: "openarm_sim_arm", tag: "v1" }, instances: [{ instance_id: "arm_inst", framework: { clock: "simulation" } }], }, ], } ``` A declaration is `{ publisher: "" }` for a timeline one instance supplies, or `"wall"` for a name the time every machine already keeps answers to. `wall` itself is built in and cannot be declared. Every other instance names the domain it reads with [`framework.clock`](#framework-optional). The launcher’s declarations and those of every [fragment](#fragments-splitting-a-launcher-across-files) the selection pulls in are merged: identical declarations agree, two different declarations of one name are refused naming both documents, and an unselected fragment contributes nothing. A [copy](#copies) binds the domains the stack declares, naming them as the stack does. Every producer binding, pairing and observation joins two instances that read one clock, so a launcher wiring an instance on one domain to an instance on another is refused before anything starts. See [System clock](/advanced_guides/system_clock/#clock-domains). The launcher’s `framework` also takes `restart`, the policy of every instance whose entry and node declare none; a fragment writes a policy on its instance entries or through an adjustment’s `set_framework`, never at its root. ## Restart policy [Section titled “Restart policy”](#restart-policy) When a node process exits on its own, the daemon records the exit in the stack log and moves the instance by its restart policy: under `never` to `finished` (exit code 0) or `failed` (any other code, or a signal), where it stays; under `on_failure` to `restarting` after a failed exit (any code but 0, a signal, or the health kill below); under `always` to `restarting` after any exit, a clean one included. Under `on_failure` or `always` the daemon also kills an instance that stops answering health checks, and its policy treats that exit as a failure; the rule and its outage guard are in [Instance health and lifecycle](/guides/node_stack/#instance-health-and-lifecycle). The most specific level wins: 1. the instance: `framework.restart` on its launcher entry, `set_framework.restart` in an adjustment, or `--restart` on `peppy node run` or `peppy node add --run` (with `--max-restarts` for a cap); 2. the node: `framework.restart` in its `peppy.json5`; 3. the launcher root: `framework.restart` at the root of the launcher; 4. the default: `on_failure`. A node declares its own policy in `peppy.json5`, under the same `framework` key the launcher uses: peppy.json5 ```json5 // A node that declares its own restart policy: an instance of it is // started again after a failed exit, whatever launcher deploys it, unless a // launcher entry, an adjustment or `--restart` writes one. { peppy_schema: "node/v1", manifest: { name: "wrist_camera", tag: "v1", description: ["The camera on the wrist of a robot arm. It needs the camera on its machine."] }, interfaces: {}, execution: { language: "rust", build_cmd: ["cargo", "build", "--release"], run_cmd: ["./target/release/wrist_camera"], }, framework: { restart: "on_failure" }, } ``` A launcher declares a policy at its root and an instance entry its own. An adjustment under an option writes the same key on its target with `set_framework: { restart: "never" }`, as the [adjustments](#adjustments) table shows. In the launcher below, the root’s `always` covers the rear camera, the front camera’s entry writes its own, and the wrist camera takes the `on_failure` of the node above: cameras.json5 ```json5 // A launcher whose root policy is `always`: an instance is started again // after any exit, which is what the rear camera gets. The front camera's // entry writes its own, `on_failure` capped at five attempts in a row, and // the wrist camera takes the `on_failure` its node declares. { peppy_schema: "launcher/v1", description: ["Three cameras of a robot: front, rear and wrist. It needs the UVC cameras at the device paths that its instances name."], framework: { restart: "always" }, deployments: [ { source: { name: "uvc_camera_linux", tag: "v1" }, instances: [ { instance_id: "front_cam_inst", framework: { restart: { policy: "on_failure", max_restarts: 5 } }, arguments: { device_path: "/dev/video0", video: { frame_rate: 30, resolution: { width: 1280, height: 720 }, camera_encoding: "mjpeg", topic_encoding: "rgb8", }, }, }, { instance_id: "rear_cam_inst", arguments: { device_path: "/dev/video2", video: { frame_rate: 30, resolution: { width: 1280, height: 720 }, camera_encoding: "mjpeg", topic_encoding: "rgb8", }, }, }, ], }, { source: { name: "wrist_camera", tag: "v1" }, instances: [{ instance_id: "wrist_cam_inst" }], }, ], } ``` The value is a string, `restart: "on_failure"`, or an object, `restart: { policy: "on_failure", max_restarts: 5 }`, where `max_restarts` caps the restart attempts in a row, failed starts included, and the next exit or failed start past them leaves the instance `failed`; a level writes the value whole, so a cap written at one level never combines with a policy from another. `max_restarts` needs a policy that restarts, `on_failure` or `always`; with `never` it is refused. The policy applies once an instance has been `running`: a first start that fails still fails the launch or the `peppy node run`. A restart is a new process under the same id, with the arguments, environment, clock, core node and slots the instance had. It pairs and observes again, and the consumers bound to it receive from it again with no further action. When the previous process crashed, its shutdown hooks did not run, so write the node’s setup to bring its hardware to a known state before it enables anything. The daemon waits between the exit and the next start. The first wait is one second; each further exit or failed start doubles it, up to one minute, and from then on every attempt waits a minute. The new process clears the same startup health gate as a first start. An exit after a run of two minutes or more starts the backoff over: its wait is one second and its attempt is 1 again. A run the health monitor ended counts only up to the last health check the process answered, so a node that hangs again after each start keeps backing off and reaches its `max_restarts`. The exit or failed start past `max_restarts` attempts in a row leaves the instance `failed`, and the stack log says `` `max_restarts` reached ``. An instance that publishes a clock domain takes its policy like any other and keeps its domain when it restarts; [System clock](/advanced_guides/system_clock/#lifetime-replacement-and-removal) says what the instances reading it see. A fragment or option body that writes `framework.restart` at its root is refused when a selection composes it, naming the launcher root. While the daemon waits, the instance shows `restarting` in `peppy stack list`, whose `RESTARTS` column counts the times a restarted process reached `running`; `peppy node info` adds the attempt, the last exit and the next start. The stack log records a `restarting` line with the attempt and the wait, a `restarted` line once the new process is `running`, a `start failed` line when the new process did not reach `running` (the run log holds the whole failure), a `restart refused` line when the daemon refused to start the process again (for example a clock domain whose publisher, on the same machine, has ended), and the `` `max_restarts` reached `` line. Once this machine’s nodes cache is filled (`peppy repo refresh`), `peppy stack resolve` prints each instance’s policy with its origin on its clock line. Each process writes its own run log, `_.log`, as add and build logs are named: a crash’s output stays in its file, a restart’s file opens with a line naming the attempt and the previous file, and `peppy node info` lists the latest one. For a single instance, `--restart` and `--max-restarts` on `peppy node run` set the policy: ```bash peppy node run wrist_camera:v1 -i wrist_cam_inst --restart on_failure --max-restarts 5 ``` A crash of that instance and its restart read in the stack log as: ```text [2026-10-07T14:02:11.204] Instance 'wrist_cam_inst' of node 'wrist_camera:v1' failed: signal 11 (SIGSEGV), core dumped [2026-10-07T14:02:11.209] Instance 'wrist_cam_inst' of node 'wrist_camera:v1' restarting in 1 s (attempt 1) [2026-10-07T14:02:13.487] Instance 'wrist_cam_inst' of node 'wrist_camera:v1' restarted (attempt 1) ``` `peppy node stop`, `peppy node remove`, `peppy node add` over its node, `peppy stack reset`, `peppy stack remove`, `peppy stack launch` of the stack again and a daemon shutdown end an instance for good and cancel a waiting restart; `peppy node stop` also clears a `finished`, `failed` or `restarting` instance, which frees its id, and ends the start of an instance its restart is starting again. While a restart holds its daemon, from its start through the pairs its new process asks for again, a `peppy stack launch`, build, join or removal on that daemon answers busy, naming the instance and the stop that ends its restart. A start waits ten minutes for a node that never signals ready before it fails, and each attempt holds the daemon for its own start, so an instance whose every start hangs keeps its daemon busy, between its waits, until that stop or its `max_restarts` ends the restarts. `peppy node remove` holds restarts off while it runs: an instance that exits on the removal’s shutdown request ends there whatever its policy, and one whose restart falls due waits, so a removal that succeeds removes both. An instance starting when the removal reaches it, or running a process that reached `running` after the removal began, keeps its node; the removal’s error names it, and `peppy node remove : --stop-instances` run again once none is starting removes it. `peppy stack join` refuses a copy whose adjustment changes the policy of an instance the stack runs, and a join that grows a `restarting` instance’s slot. ### Starting a failed instance again [Section titled “Starting a failed instance again”](#starting-a-failed-instance-again) An instance whose restarts ended, with a `restart refused` or `` `max_restarts` reached `` line in the stack log, stays `failed`, as does one that failed under `never`, and one that finished stays `finished`. Either starts again by how it was started: an instance `peppy stack resolve` of the launcher lists, with the launch’s `--with` words, was started by the launch, and a launch also starts each member on the `Instances:` line under a `Copy` line of `peppy stack list` that a `Launch copy` line repeats, with the same text after its keyword: the same name, option, machine and selection. Compare the whole line, since a join can add a copy under the name of a launch copy that a removal took off, with another option, machine or selection. A member under any other `Copy` line belongs to a copy `peppy stack join` added; any other instance was started by `peppy node run` or `peppy node add --run`. * `peppy node run` or `peppy node add --run`: `peppy node stop ` clears it and frees its id; then start it with `peppy node run :` and the same arguments, links and flags (a `peppy node add` of its node again stops and clears every other instance of the node, and one from git or a URL does so without asking). The stop makes the instances paired with it forget those pairs. A pair the instance made itself, by its own `--link`, is already among those flags. A peer that made a pair with it by `--link`, or asked for one again at its own restart, names the pair in its run log under `~/.peppy/logs/run/` as `paired: CORE/PEER_INSTANCE:PEER_LINK ⇌ CORE/INSTANCE:LINK_ID`, and `grep -l '⇌ [^ ]*/:' ~/.peppy/logs/run/*.log` lists those logs; for each pair they name that the new run’s `--link` flags do not already cover, add `--link LINK_ID@PEER_INSTANCE[/PEER_LINK]` (see [Pairing](/advanced_guides/pairing/)), in place of a `--vacant-link` on the same slot. * A launch: `peppy stack launch` on the coordinator, with the launcher, placement, `--with` words and `--join` copies it was launched with. A launch replaces the whole stack, which ends the copies `peppy stack join` added and the instances `peppy node run` started: note first the `Copy` lines of `peppy stack list` that no `Launch copy` line repeats, and join each again after the launch. * A member of a copy `peppy stack join` added: read the copy’s `Copy` line in `peppy stack list` first, since the removal drops it. Then, on the coordinator or with `--core-node `, run `peppy stack remove NAME`, which clears the copy’s instances, and `peppy stack join OPTION:NAME@CORE_NODE` with the line’s option and machine, its `axis=option` words as `--with`, and the `--set-arguments` it was joined with. Where the removal is refused, as for the last copy of a `one_or_more` axis, launch the stack again. For `arm_1` of the [Pairing](/advanced_guides/pairing/) example, which `ctrl_1` paired with `--link arm@arm_1`, `ctrl_1`’s run log holds `paired: cn-adoring-zebra/ctrl_1:arm ⇌ cn-adoring-zebra/arm_1:controller`, and these commands start `arm_1` again with that pair: ```sh peppy node stop arm_1 peppy node run --instance-id arm_1 robot_arm:v1 --link controller@ctrl_1 ``` For the copy `bravo`, whose backbone reached its `max_restarts`, `peppy stack list` on the coordinator shows its `Copy` line beside the line of `alpha`, which the launch started. No `Launch copy` line repeats the line of `bravo`, so a join added it: ```plaintext Copy alpha of openarm on jetson-1: model=openarm_v2 Instances: alpha_backbone_inst, alpha_camera_inst Copy bravo of openarm on jetson-2: model=openarm_v1,robot_commander=ker_commander Instances: bravo_backbone_inst, bravo_camera_inst Launch copies Launch copy alpha of openarm on jetson-1: model=openarm_v2 ``` and these commands start it again as it was joined: ```sh peppy stack remove bravo peppy stack join openarm:bravo@jetson-2 --with model=openarm_v1,robot_commander=ker_commander ``` A `restart refused` line names its cause. When the cause is a clock domain whose publisher ended, the line also says what publishes the name now. For a reader a launch or `peppy stack join` started, a launch of the stack starts the reader and its publisher again; join again, after the launch, each copy `peppy stack join` added. For one `peppy node run` started, stop it and run it again with its `--clock`, after starting a publisher with `--publish-clock` when nothing publishes the name. ## Reusing built nodes across launches [Section titled “Reusing built nodes across launches”](#reusing-built-nodes-across-launches) Every node build a launch performs goes through the [build artifact cache](/advanced_guides/containers/#build-caching): when a deployment’s staged sources match an earlier build byte for byte, and that build ran with the same peppy version, OS, architecture and artifact kind, the launch reuses its artifact. Launching the same launcher again, after a daemon restart or on another machine booted from the same disk, therefore spends seconds on the build phase instead of rebuilding every node. Each reuse is reported in the launch output and in that node’s build log: ```plaintext Reusing cached build of waldo:v1 (fingerprint 3f9a1c2e5d7b8a4f) at ~/.peppy/built_nodes/waldo_v1/3f9a1c2e5d7b8a4f.linux-amd64.sif ``` `peppy stack launch --rebuild` and `peppy stack build --rebuild` build every node of the launch from its staged sources even when a matching artifact exists, on the coordinator and on every peer; use it when something the fingerprint does not cover changed, such as the image behind a floating base image tag. ### Building without starting [Section titled “Building without starting”](#building-without-starting) `peppy stack build` runs a launch up to its builds. It replaces the node stack as a launch does, then adds and builds each node the launch would run on the machine the launch places it on, and each [joinable node](#building-the-nodes-a-join-brings) on this machine, and starts no instance. It takes every argument `peppy stack launch` takes, so a later `peppy stack launch` with the same launcher, placement, `--with` words and `--join` copies starts from these builds, and so do the joins of its scoped options. Build a launcher on a disk, save the disk as an image, and every machine booted from that image launches without building: ```sh peppy stack build openarm_simulation --with mujoco # Save the disk as an image and boot each machine from it, then on each one: peppy stack launch openarm_simulation --with mujoco ``` On Linux the daemon derives its default core node name from the machine id the disk stores, read from `/var/lib/dbus/machine-id`, else `/etc/machine-id`. Machines booted from one image therefore derive the same name, and a daemon whose name is already live on its router or federation refuses to start. Give each machine its own [`core_node_name`](/advanced_guides/daemon_config/#core_node_name-the-daemons-core-node-name); a name set on the imaged disk is shared the same way. After a build, `peppy stack list` shows each node at stage `Ready` with `0` instances, under a `Slice of launch ` line naming the build that replaced this machine’s stack. A build records no launcher, so `peppy stack join` is refused until `peppy stack launch` starts the stack. A machine booted from the image starts with an empty stack: its builds wait under `~/.peppy/built_nodes/`, and its launch names each one it reuses with a `Reusing cached build of` line. `peppy stack build --publish` also pushes the image of each container node that each machine builds to an OCI registry, from which other machines pull the node instead of building it. See [Publish the nodes of a stack](/advanced_guides/publishing/#publish-the-nodes-of-a-stack). ### Building the nodes a join brings [Section titled “Building the nodes a join brings”](#building-the-nodes-a-join-brings) A launcher whose MCP endpoint serves a [`robot_membership` daemon target](/advanced_guides/mcp/#daemon-targets) lets a client add robots after the launch. The launch builds their nodes first, so that a join on the coordinator adds and starts nodes and builds none. The launch checks of a `robot_membership` scope compose one trial copy of each feature set of each scoped option: no feature, each feature, and each combination (see [Scopes](/advanced_guides/mcp/#scopes)). The nodes of these copies are the **joinable nodes** of the launch: every node that a join of a scoped option can bring. With two scopes, the joinable nodes are those of both. The built-in MCP server of a copy builds nothing, so it is no joinable node. The launch resolves the joinable nodes with its own deployments and pins their contract and pairing documents with its own, all before it changes a machine. In its add-and-build phase, it adds and builds each joinable node on the coordinator, after its own nodes there and in the same build slots, so with a long build of the launch, the builds of the joinable nodes run beside it. A node that the launch adds on the coordinator anyway is added and built once. A node that the launch places only on another machine is added and built on the coordinator too, because a join can run it there. `--place` and `--local` move no joinable node: a joinable node is for the coordinator, where the endpoint that adds the robots runs. The launch starts no instance of a joinable node, and it starts its own instances only once every build has ended. `peppy stack list` then shows each joinable node at stage `Ready` with `0` instances. The add line of a joinable node names the scoped options that bring it: ```plaintext Adding so101_backbone:v1 on `cn-desk` for stack joins of `so101_sim` ``` A later join of a scoped option on the coordinator, through the MCP `join` tool or with `peppy stack join` and the words of its features, finds each node it brings built: it adds the node again, and the build reuses the artifact in a few seconds. A join runs the resolution that the launch recorded for each joinable node, so it stages the trees that the launch built, also after a `peppy repo refresh`; launch again to run newer node content. A part that a join places on another machine builds on that machine when the join runs, and so does a node that a `--with` word selects and that no feature of the scope selects. `--set-arguments` selects no node, so it never causes a build. A joinable node that does not resolve refuses the launch before any machine changes, so the stack that runs keeps running. A joinable node that does not build fails the launch, which clears the stack, as the failure of any node of the launch does. Each refusal names the node, the scoped options that bring it, and `--no-prebuild`. A trial copy that does not compose refuses the launch, as the launch checks of the scope do. `--no-prebuild` on `peppy stack launch` and `peppy stack build` makes the launch resolve and build only the nodes it runs. A join then resolves the nodes of its robot against the repositories as they are when it runs, and builds them on each of their machines, so you change a robot’s node, run `peppy repo refresh` and join it again with no new launch. `--rebuild` builds the joinable nodes again too. A launcher with no `robot_membership` scope has no joinable node, and neither has a selection that deploys no instance with such a scope. ## Launch timeouts [Section titled “Launch timeouts”](#launch-timeouts) A launch adds, builds and starts its nodes one phase at a time, and each phase runs under an idle budget: the clock resets whenever the phase produces output (a git or http download’s progress, a `build_cmd`’s lines, a starting node’s lines, the ready signal of a starting instance), and the phase fails when it goes quiet for longer than its budget. The budgets are per phase and per node: | Flag | Phase | Default | | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `--node-add-idle-timeout-secs` | fetching a node’s source and generating its bindings | 600 | | `--node-build-idle-timeout-secs` | running its `build_cmd`, or downloading and assembling its image; bytes landing on disk and CPU time the build burns count as output too | 180 | | `--node-run-idle-timeout-secs` | starting an instance, until its setup ends and the daemon records it as running | 600 | These defaults are the only ones: the daemon has no budgets of its own, and every launch, build and join carries the budgets of its caller. When no output arrives, the command waits for the largest of the three budgets plus 60 s before it stops, so the daemon’s error for the silent phase comes first. A command that stops waiting sends no cancel, but it exits with code 1 and its process ends: the daemon then sees that the sender of the goal is gone and cancels the change, as for [a command whose process goes away](#stopping-a-stack-command-with-ctrlc). A join over MCP, through the `join` tool of a [`robot_membership` daemon target](/advanced_guides/mcp/#what-the-tools-of-robot_membership-do), sends these same defaults, with no overall budget. Give such a tool a progress window of the largest of the three budgets plus the same 60 s, 660 s for the defaults, so that the daemon’s error for a silent phase comes first. Every build runs with `CARGO_TERM_PROGRESS_WHEN=always` and `CARGO_TERM_PROGRESS_WIDTH=80`, in a `build_cmd` and in a container def’s `%post` alike. Without them, cargo prints a line only when a crate download completes when its output is not a terminal, and until then the download writes nothing to disk and burns no CPU, so a large crate on a slow connection reads as an idle build. With these settings cargo reprints its progress line each time the bytes left to download change, and each reprint counts as output. A download that receives nothing changes nothing, so it still runs out the budget. If you set either variable yourself, a `build_cmd` gets your value; a def sets its own by exporting it in `%post`. `--max-timeout-secs` adds a budget for the whole launch on top of the idle ones; without it, only the idle budgets apply. When a budget runs out the launch fails, names the phase and, for an idle budget, the flag that raises it, and clears the stack as any failed launch does. What the interrupted phase leaves behind depends on the phase: * An interrupted **add** never publishes its node. The daemon generates a node’s bindings into the node’s staged copy on a worker thread of its own, so a generation that is already running when the add’s budget runs out finishes on that thread, and the staged copy is removed once it does; a queued generation whose add is gone is skipped. Either way the node never enters the stack and nothing of it is built. * An interrupted **build** has its `build_cmd` or image build killed. * An interrupted **run** has its half-started instance torn down before the failure is reported. An instance that has not answered ready has its process group killed at once; an instance that answered ready gets the shutdown request and the grace first, so its shutdown hooks run (see [How an instance starts](/guides/node_stack/#how-an-instance-starts)). `peppy stack build` takes the same flags and ends after the build phase, so `--node-run-idle-timeout-secs` bounds nothing in a build. `peppy stack join` takes the same flags and runs its copy’s nodes through the same phases, `--max-timeout-secs` bounding the whole join. A join whose budget runs out fails as any [failed join](#copies) does: it stops what it started and removes the nodes it added, leaving the stack it joined running. Only the node’s own output and, in the run phase, the ready signal of the instance reset a phase’s clock; the launcher’s progress lines do not. Inside the run phase, the daemon also waits for each setup for the [setup budget](/guides/node_stack/#how-an-instance-starts) of its node, at most 540 seconds, which is less than the default run idle budget. ## How a stack command ends [Section titled “How a stack command ends”](#how-a-stack-command-ends) `peppy stack launch`, `build`, `join` and `remove` each send the daemon one goal and follow it to its end. The daemon refuses a goal that it cannot start, for example while another stack change runs, and the command prints the refusal with its failure kind: ```text Error: Launch refused (busy): a stack launch, build, join, removal or reset, or a coordinator's change to this daemon's slice, is in progress on this daemon; run this again once it ends ``` A goal that fails ends the command with its failure kind, the reason, and the launch log, after the log files of the nodes: ```text Error: Launch failed (attempt_failed): failed to build node arm:v1: build_cmd `cargo build --release` failed with status exit status: 101. Log file: /home/ubuntu/.peppy/logs/launch/launch_20261023_101500_123.log ``` | Kind | What it says | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `rejected` | The launcher, a word of the command or a value in it is not valid, or it names something that is not there | | `busy` | Other work holds the stack of a machine: another stack change runs, a node command or a restart runs, a `peppy stack reset` runs, or another launch holds the machine. The same command can succeed once that work ends | | `precondition_failed` | The stack or a machine does not allow the change: an instance or a copy is in the way, or the stack has no launcher | | `resource_unavailable` | A machine of the change is not live, or did not answer | | `timeout` | A budget ran out | | `attempt_failed` | A step failed, for example a build or the start of an instance | `busy` is the kind of the daemon itself. The other kinds are kinds of peppy (see [How a goal ends](/advanced_guides/actions/#how-a-goal-ends)). A federated launch fails with `busy` when each machine that refused it is busy. The command exits with code 3 when the goal is refused, and 4 when it fails. Each end of a goal has an exit status of its own (see [Exit statuses of the other commands](/advanced_guides/calling_instances/#exit-statuses-of-the-other-commands)). The command keeps up to 65536 lines of the change’s output that it did not show yet. A command that falls further behind, for example on a terminal that shows lines slower than a build prints them, cancels the change, says `The command fell behind the output of the launch by more than 65536 unread messages and cancelled it.`, and exits with code 1. ### Stopping a stack command with Ctrl+C [Section titled “Stopping a stack command with Ctrl+C”](#stopping-a-stack-command-with-ctrlc) The first Ctrl+C sends the daemon a cancel of the goal, and the command says so: ```text Cancelling the launch; press Ctrl-C again to stop waiting for its end ``` The daemon stops the change at the step it reached, and ends it as a failure at that step ends it: a launch or a build clears the stack, a join is undone, and a removal keeps its copy, with the instances that it did not stop yet. A join or a removal reads the cancel before it changes a machine, so a cancel that comes early leaves every stack as it was. A step that runs on another machine gets the cancel too. The command follows the change to that end, prints how it ended, and exits with the status of that end, 5 for a cancel. The rollback can be silent for longer than the idle budgets, so after a Ctrl+C only `--max-timeout-secs` bounds the wait: ```text Error: Launch was cancelled by its caller. Log file: /home/ubuntu/.peppy/logs/launch/launch_20261023_101500_123.log ``` A change that ended before the cancel reached it keeps its end, and the command says so: `Launch completed before the cancel took effect.`, with the exit status 0. A change that failed for a cause of its own, for example a build that failed before the cancel reached it, ends failed with its kind and the exit status 4, also when the cancel arrives during its rollback. A second Ctrl+C stops the wait for the end: the command waits only until the cancel reaches the daemon, which goes on with it, and exits with code 130. A third Ctrl+C ends the command at once. A command whose process goes away, for example when its terminal closes or the process is killed, cancels its goal too: the daemon sees that the sender of the goal is gone, and cancels the goal one minute later. The launch log then ends with `cancelled: its sender is gone`. The minute outlasts a restart of the messaging router by its watchdog, during which the daemon cannot see the commands that still run, so a change goes on through a router restart or a short loss of the link between two machines. Each `peppy` process is a sender of its own, so the goals of other `peppy` processes go on. A `peppy stack reset` cancels the change that runs: the change ends, `Launch was cancelled by a stack reset.`, and the command exits with code 5, as for any cancel. ## Running one launcher across several machines [Section titled “Running one launcher across several machines”](#running-one-launcher-across-several-machines) A launcher can span machines. It declares named placeholders under `core_nodes`, each instance says which one it runs on via `core_node`, and `peppy stack launch --place @` binds those placeholders to real hardware at launch time. Producer links, pairings, and observations all work across the boundary, and consumers still start after their producers. See [Federation](/advanced_guides/federation/). Every placeholder the launcher declares must be bound with `--place`; a launch that leaves one unwired is refused. The escape hatch is `peppy stack launch --local`, which ignores the launcher’s placements and runs every instance on the daemon you launched from. `--local` and `--place` are mutually exclusive, and under `--local` no `--join` and no `--with` word names a machine. A [copy](#copies) runs where it is named, and each part of it where the word that selects it says. ## Swapping parts at launch time [Section titled “Swapping parts at launch time”](#swapping-parts-at-launch-time) A launcher file can describe a family of stacks whose members differ in which implementation fills a slot: a real robot or a simulator, a browser panel or a headset, with or without a recorder. The launcher declares **component axes**, `deployments` says which option of each it starts, and the launch command swaps one with `--with`. A launcher without `components` is a plain flat stack, and that stays the ordinary way to write a one-off. The whole feature fits in one file. Here is a viewer stack with two swappable cameras: viewer.json5 ```json5 // One file, two swappable cameras: the viewer stack declares a `camera` // axis whose options are written inline, so composition needs no second // file. `peppy stack launch ./viewer.json5` runs the camera the file // deploys (`uvc`); the same launcher with `--with=zed` swaps it. { peppy_schema: "launcher/v1", description: ["A viewer of one camera: a UVC camera, or a ZED camera with `--with=zed`. It needs the camera that it selects."], components: [ { name: "camera", provides: ["cam_inst"], options: { uvc: { deployments: [ { source: { name: "uvc_camera_linux", tag: "v1" }, instances: [ { instance_id: "cam_inst", arguments: { device_path: "/dev/video0", video: { frame_rate: 30, resolution: { width: 1280, height: 720 }, camera_encoding: "mjpeg", topic_encoding: "rgb8", }, }, }, ], }, ], }, zed: { deployments: [ { source: { name: "zed_camera", tag: "v1" }, instances: [ { instance_id: "cam_inst", arguments: { resolution: "hd720", frame_rate: 30, depth: { min_depth_m: 0.4, downscale: 2, block_size: 3 }, }, }, ], }, ], }, }, }, ], deployments: [ { source: { name: "web_viewer", tag: "v1" }, instances: [{ instance_id: "viewer_inst", links: { camera: "cam_inst" } }], }, { camera: "uvc" }, ], } ``` ```sh peppy stack launch ./viewer.json5 # runs the camera the file deploys (uvc) peppy stack launch ./viewer.json5 --with=zed # runs the ZED camera instead ``` Components declare what may run; `deployments` says what runs. An axis entry has four fields: | Field | Meaning | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | The axis’s name, unique in the launcher. Used in `--with axis=option`, in `deployments`, and in adjustment guards. | | `options` | The alternatives that fill this axis, at least one. Each option is a fragment: a body using the same `deployments` grammar the launcher’s own `deployments` use, written inline, or a path string naming its own [file](#fragments-splitting-a-launcher-across-files), or the object `{ fragments: ["fragments/relays.json5", "fragments/mujoco.json5"], ... }`, which is how an option names more than one file and how, in a launcher, it carries the [adjustments](#adjustments) that run when the option is selected. | | `cardinality` | How many selections of the axis a stack allows. `one` (the default): exactly one option runs. `zero_or_one`: at most one. `zero_or_more`: any number, each a named [copy](#copies). `one_or_more`: the same copies, with at least one started by every launch and `stack remove` refusing the last one. | | `provides` | Instance IDs every option defines, so a link written against one is valid whichever option is selected. On an axis that runs as copies the IDs are checked as written, before a copy’s name prefixes them. | A `deployments` entry deploys a node, `{ source, instances }`, or a component’s option, `{ : "