9. Compartment Framework (fleetmesh_node.compartment)

The fleetmesh_node.compartment package is the architectural backbone of Meshnode. It isolates functionalities into modular, self-declaring components with strict lifecycle boundaries, dependency resolution, refusal logging, and typed state stores.

9.1. Compartment Base

BASE: the abstract compartment every mechanism in this node extends.

A compartment is one mechanism of the node - link, budget, announce - and it is written as a set of declarations rather than wired into the node by hand. Six of them, each a tuple of frozen records on the class, each with a census behind it and a package that defines it:

PARAMS what it can be told its config block (node/config) CHANNELS what it says fleetmesh_node/channels METRICS what it measures fleetmesh_node/metrics COMMANDS what it can be asked to do fleetmesh_node/compartment/command.py LIFECYCLE how it fails, and restarts fleetmesh_node/lifecycle STORES what it keeps in memory fleetmesh_node/stores

The base class is abstract in two senses, both enforced:

  • It cannot be built. Compartment(node) raises, and so does any class that says class X(Compartment, abstract=True) - a KIND of compartment, like sidecar_bridge.Bridge, which is extended rather than run.

  • Its declarations are linted when a subclass is DEFINED, not when a node happens to build it. A concrete compartment must have a name; a store, command, channel or metric must be unique within it; a snapshot must have something to carry; a command’s reads/writes must name a store this compartment declares, or one of a compartment it requires or uses. A class that breaks one of those fails at import, with every problem listed - which is what makes the declarations a lint rather than prose.

And it is a working default for everything a compartment need not say: no tick, no state, no trouble, and a snapshot derived from its SNAPSHOT stores.

class fleetmesh_node.compartment.base.EveryJobReport[source]

Bases: TypedDict

One EVERY job as report() gives it. seconds and next_run are None for a job that is off (Every.is_off).

seconds: int | float | None
last_run: int | None
next_run: int | None
fleetmesh_node.compartment.base.wall()[source]

The wall clock in whole seconds: every compartment’s default clock.

Return type:

int

class fleetmesh_node.compartment.base.CompartmentProtocol[source]

Bases: Protocol

The contract the Registry relies on, stated structurally.

Compartment below is the convenient base class and every compartment in fleetmesh_node/ extends it, but the registry’s verbs need only this surface. Naming it lets a test double or a foreign compartment be typed against the contract without inheriting the base.

property name: str | None
property attr: str | None
property requires: tuple[str, ...]
property uses: tuple[str, ...]
property optional: bool
property enabled_by: str | None
property reads: tuple[str, ...]
property live: tuple[str, ...]
property config_cls: type[Any] | None
property api: str
property protocol: str
property piuris: tuple[str, ...]
property exact_types: tuple[str, ...]
property commands: Mapping[str, CommandSpec]
property CHANNELS: tuple[Any, ...]
property METRICS: tuple[Any, ...]
property COMMANDS: tuple[Any, ...]
property EVERY: tuple[Any, ...]
property WORKERS: tuple[Any, ...]
property LIFECYCLE: Lifecycle
property STORES: tuple[Any, ...]
property NEEDS: tuple[Any, ...]
property SCHEMA: tuple[Any, ...]
property MIGRATIONS: tuple[Any, ...]
property HANDLERS: tuple[Any, ...]
property holdings: Holdings | None
property db: Any
property refusals: Refusals
property cli: tuple[tuple[str, Callable[[...], Any]], ...]
property sidecars: tuple[Any, ...]
wire(registry, ctx)[source]
Parameters:
Return type:

None

start()[source]
Return type:

None

start_workers()[source]
Return type:

None

stop_workers()[source]
Return type:

None

tick(now)[source]
Parameters:

now (int)

Return type:

list[tuple[Any, …]]

run_tick(now)[source]
Parameters:

now (int)

Return type:

list[tuple[Any, …]]

stop()[source]
Return type:

Any

state()[source]
Return type:

Mapping[str, Any]

trouble()[source]
Return type:

list[str]

notes()[source]
Return type:

list[str]

report()[source]
Return type:

Mapping[str, Any]

sections()[source]
Return type:

Mapping[str, Any]

snapshot()[source]
Return type:

Mapping[str, Any]

restore(state)[source]
Parameters:

state (Mapping[str, Any])

Return type:

None

command(name, args)[source]
Parameters:
Return type:

Any

handle(inbound)[source]
Parameters:

inbound (Any)

Return type:

Any

capability_protocols()[source]
Return type:

Sequence[str]

descriptor_tags()[source]
Return type:

Sequence[Sequence[str]]

__init__(*args, **kwargs)
class fleetmesh_node.compartment.base.Compartment[source]

Bases: object

One compartment of the node. Assembled, ticked and read uniformly.

The subsystem/1 declaration. Every compartment states, as class attributes, what it is and what it needs, and Registry.assemble() reads those to build the node in dependency order:

name the one word the CLI, status.json and the docs use requires names of compartments this one must be built after

(it receives them already constructed through ctx)

uses names of OPTIONAL compartments this one reaches when

they are present; it must still work without them. The assembler holds them to the same manifest order as requires (listed earlier) but does not demand they be built. Resolve each once in from_context with ctx.optional(name); never probe the node per call.

optional True if the node runs without it; it is then built only

when enabled_by names a config section that is present

enabled_by the config key whose presence turns an optional one on reads / live config keys read; of those, the ones re-read each tick api the declaration version this class was written against protocol the schema digest it was built against, or ‘’ if it

reads no schema (checked at assembly when set)

piuris the wire protocols (PIURI prefixes) this one handles;

the registry routes each to its handle(inbound)

exact_types whole message types it handles, routed exactly

from_context(ctx) is the one constructor the assembler calls. The default forwards to cls(node=ctx.node) so a compartment that has not been migrated still builds; a migrated one overrides it and names its dependencies there and nowhere else.

API: str = 'subsystem/1'
TROUBLE_WINDOW: int = 1800
name: str | None = None
attr: str | None = None
requires: tuple[str, ...] = ()
uses: tuple[str, ...] = ()
optional: bool = False
enabled_by: str | None = None
reads: tuple[str, ...] = ()
live: tuple[str, ...] = ()
config_cls: type[Any] | None = None
api: str = 'subsystem/1'
protocol: str = ''
piuris: tuple[str, ...] = ()
exact_types: tuple[str, ...] = ()
commands: Mapping[str, CommandSpec] = {}
CHANNELS: tuple[Any, ...] = ()
METRICS: tuple[Any, ...] = ()
COMMANDS: tuple[Any, ...] = ()
EVERY: tuple[Any, ...] = ()
WORKERS: tuple[Any, ...] = ()
LIFECYCLE: Lifecycle = Lifecycle(breaker=Breaker(failures=5, window=300, backoff=(30, 600)), restart=False, snapshot=0)
STORES: tuple[Store, ...] = ()
NEEDS: tuple[Any, ...] = ()
SCHEMA: tuple[Any, ...] = ()
MIGRATIONS: tuple[Any, ...] = ()
HANDLERS: tuple[Any, ...] = ()
cli: tuple[tuple[str, Callable[[...], Any]], ...] = ()
sidecars: tuple[Any, ...] = ()
STORE_CLS: type | None = None
abstract: ClassVar[bool] = True
classmethod declaration_problems()[source]

Everything wrong with this class’s declarations, as sentences.

Collected rather than raised one at a time, like Metric.problems and config.Problems: whoever fixes one wants to see them all. Returns Problems (a list subclass) holding typed Problem instances.

Return type:

list[str]

classmethod store_refs()[source]

(command, compartment, store) for every store of ANOTHER compartment this one’s commands read.

Return type:

tuple[tuple[str, str, str], …]

static __new__(cls, *args, **kw)[source]
Parameters:
Return type:

Compartment

__init__(node=None, clock=None, cfg=None, says=None, db=None)[source]
Parameters:
Return type:

None

node: Any
clock: Callable[[], int]
refusals: Refusals = None
holdings: Holdings | None = None
db: Any = None
classmethod open_store(locator, directory, clock)[source]

This compartment’s store, where the node keeps it. The one place a compartment’s database is opened: __init__ and from_context each had a copy of this, and both ran for one build (audit D5).

STORE_CLS when named, else the generic adapter over SCHEMA. Through the node’s locator when it has one, its directory when not, and in memory for a compartment built with neither, as a suite builds it.

Parameters:
Return type:

Any

property stop_event: Event
property stopping: bool
relay_destination(default=None)[source]

Where this node’s own signed events go (plan D2): the node decides - its public relays, or its network relays while it is fully private and publishes no public descriptor. A compartment built without a node (a suite) or against a node that does not answer gets default (its own configured relays), so nothing changes outside a running node. A node that answers with an empty list means nowhere: a fully private node with no network publishes its peer-directed events to nobody.

Parameters:

default (Sequence[str] | None)

Return type:

list[str]

classmethod from_context(ctx)[source]

Build from a NodeContext. When NEEDS is declared, constructs from declarations.

Parameters:

ctx (Any)

Return type:

T

settings()[source]

This compartment’s own config block, typed, as the file says now.

config_cls names the Block; its key is read through config() so the read is counted against reads like any other. Parsed on each call, so a compartment that lists its key in live sees an edit without a restart; the others call it once at construction.

Return type:

Any

wire(registry, ctx)[source]

Reach the compartments built after this one, once all exist.

The assembler builds in tick order and some edges run against it: link records into strain, which ticks later; peering refuses through capacity, built after budget. Each compartment names those edges here, with registry.get(name), and nowhere else - the node used to hold every one of them in one block that nothing checked. Called once, after the whole manifest is built and before start().

Parameters:
Return type:

None

start_workers()[source]

Start all declared WORKERS that are not already running.

Return type:

None

stop_workers()[source]

Signal and join all running worker threads.

Return type:

None

start()[source]

Everything that needs the rest of the node to exist already.

Return type:

None

run_every(now)[source]

Run each declared EVERY job that is due at now, recording last run time.

Parameters:

now (int)

Return type:

list[tuple[Any, …]]

tick(now)[source]

Periodic work. Runs due EVERY jobs when not overridden.

Parameters:

now (int)

Return type:

list[tuple[Any, …]]

run_tick(now)[source]

Run periodic work (EVERY) and any custom tick logic.

Parameters:

now (int)

Return type:

list[tuple[Any, …]]

stop()[source]

Anything that must be said before the node goes. Must not raise.

Return type:

Any

state()[source]

What this compartment is, as plain data. Never raises. A compartment with a shape worth naming returns its TypedDict.

Return type:

Mapping[str, Any]

trouble_with(message, *, code='fault', severity='trouble', since=None, hint=None, **metadata)[source]

Create a typed Trouble instance associated with this compartment.

Parameters:
  • message (str)

  • code (str)

  • severity (str)

  • since (int | None)

  • hint (str | None)

  • metadata (Any)

Return type:

Trouble

trouble()[source]

What an operator should be told without having to ask for it.

Everything here is WRONG: a watcher reds on it and a deploy fails on it. Something worth reading that is not a fault goes in notes(). May return a list of strings or typed Trouble instances.

Return type:

list[str]

note_with(message, *, topic='general', level='info', since=None, **metadata)[source]

Create a typed Note instance associated with this compartment.

Parameters:
Return type:

Note

notes()[source]

What an operator would want to read, that is not a fault.

A relay cooling after a rate-limit, a peer that announced it is leaving: the node behaving, and the reason a quiet mesh is quiet. Kept apart from trouble() so no reader has to classify prose. May return a list of strings or typed Note instances.

Return type:

list[str]

report()[source]

state plus refusals, which is what health and the CLI both render. Plus, for a compartment that declares stores, what each one holds now (sizes and counts only - a report never carries the entries).

Return type:

Mapping[str, Any]

sections()[source]

What a KIND of compartment adds to every report of its kind - a bridge, its link - so that a subclass’s own state() stays its own.

Return type:

Mapping[str, Any]

snapshot()[source]

What this compartment hands the next process: every SNAPSHOT store, by key. Override only for state that is not in a store, and then override restore() with it.

Return type:

Mapping[str, Any]

restore(state)[source]

Take back what snapshot() handed on. All or nothing: every store checks its part before any is loaded, so a raise leaves it fresh.

Parameters:

state (Mapping[str, Any])

Return type:

None

get_command(name)[source]

Look up a declared command by key, bound to this compartment.

Parameters:

name (str)

Return type:

Any | None

property bound_commands: tuple[Any, ...]

All declared commands bound to this compartment instance.

command(name, args)[source]

Answer a declared command: its arguments checked against the declaration, then what its run names. A KeyError for a name this compartment does not declare; a CommandError for arguments it does not take.

The KeyError is the declared contract and a dozen suites assert it, so it stays. Registry.dispatch is what turns this one shape into a ControlError on the way to the control socket - see the note there (audit I14).

Parameters:
Return type:

Any

handle(inbound, *args, **kw)[source]

Answer an inbound wire protocol message according to HANDLERS declarations.

Parameters:
Return type:

Any

config(key, default=None)[source]

A config key, or default. Safe on a compartment with no node.

Parameters:
Return type:

Any

say(name, *args, **kw)[source]

Raise a declared channel to the node log, if a log is reachable.

In a running node, delegates to the injected says logger or self.node.says.say(). In tests or standalone runs without a full node log, formats the channel’s declared line and prints to journal.line, preserving the existing format and avoiding regressions.

Parameters:
Return type:

Any

capability_protocols()[source]

Protocols (PIURIs or dialects) this compartment advertises in kind 11801 descriptor.

Return type:

Sequence[str]

descriptor_tags()[source]

Extra Nostr tags this compartment adds to the kind 11801 descriptor.

Return type:

Sequence[Sequence[str]]

9.2. Registry & Assembly

The Registry: the compartments a node has, and the uniform ways to reach them.

Split out of fleetmesh_node/compartment.py when it became a package.

class fleetmesh_node.compartment.registry.Registry[source]

Bases: object

The compartments a node has, and the uniform ways to reach all of them.

It also owns where each one is in its lifecycle (fleetmesh_node/lifecycle): every verb below moves a compartment’s Tracker, a tick that raises degrades it, enough of them trip its breaker, and a quarantined compartment is left alone until its backoff passes. say, when given, is the node log’s say, and every transition goes out on a declared lifecycle channel.

__init__(say=None, clock=None)[source]
Parameters:
Return type:

None

add(sub)[source]
Parameters:

sub (T)

Return type:

T

state_of(name)[source]
Parameters:

name (str)

Return type:

str | None

lifecycle()[source]

Where every compartment is, for health and meshnode lifecycle.

Return type:

dict[str, LifecycleRecord]

resume(name, why='resumed by the operator')[source]

End a compartment’s quarantine now. Returns the state it is left in.

Raises KeyError for a compartment this node does not have. Resuming one that is not quarantined is not an error - it is already ticking - and the state it is in is returned unchanged.

Parameters:
Return type:

str

quarantined()[source]
Return type:

list[str]

failed()[source]
Return type:

list[str]

restartable(name)[source]
Parameters:

name (str)

Return type:

bool

restart(name, why='by the operator')[source]

Stop and start one compartment in place. Returns the state it is left in.

Only for a compartment that declares Lifecycle(restart=True); any other is refused with ValueError, because a stop() and start() nobody designed to run twice could leave threads or sockets behind and call it a recovery. KeyError for a name this node does not have.

The same instance is stopped and started: every other compartment that reached it in wire() still holds it, and a fresh instance would leave them holding the old one. A start() that raises quarantines it with backoff; the trial that follows restarts it again.

Parameters:
Return type:

str

snapshot()[source]

What every started compartment that declares snapshot hands on.

One whose snapshot() raises, or returns something that is not a JSON object, is a refusal against itself and is left out: the next process starts it fresh, and every other compartment’s state still goes across.

Return type:

dict[str, SnapshotEntry]

restore(saved, at=0)[source]

Hand each compartment the state the last process left for it. Before start(), so a compartment starts from where it was.

Returns {name: what happened} for every compartment that declares snapshot, and records the same in its lifecycle. Refused - and so started fresh - when there is no entry, the entry’s version is not the one the compartment reads now, or restore() raises. Never raises itself: continuity is worth having, not worth refusing to start for.

Parameters:
Return type:

dict[str, str]

lifecycle_metrics()[source]

The lifecycle’s counters, and gauges sampled from these trackers.

Return type:

tuple[Any, …]

store_metrics()[source]

Every declared store, metered without its compartment writing a metric: size, bound and high-water as gauges, and the writes, the evictions and the refusals as counters. One series per (compartment, store), sampled from the containers when /metrics is read.

Return type:

tuple[Any, …]

store_trouble()[source]

A REFUSE store is trouble once it is nearly full, and while it has refused anything: the state it holds is the kind that must not be lost, so the write that failed was a decision the compartment had to make without it. A ring at its bound is a log doing its job.

Return type:

list[str]

store_notes()[source]

A TABLE or SET that has evicted is dropping state it was keeping on purpose. Not a fault - the bound is the decision - but worth reading when something it tracked is unexpectedly gone.

Return type:

list[str]

get(name)[source]
Parameters:

name (str)

Return type:

CompartmentProtocol | None

names()[source]
Return type:

list[str]

assemble(ctx, manifest, enabled=None)[source]

Build every compartment in the manifest from one context, in the manifest’s order, and register each as it is built.

The manifest is the node’s declared tick order. It is validated against each class’s requires rather than re-sorted from it, because tick order is a reviewed decision with reasons the dependency graph does not carry (the relay journal ticks first so a dropped subscription is said before anything that depends on it; the operator’s decisions tick before the mechanisms they outrank). A manifest that lists a compartment before one it requires, or omits one it requires, is a programming error and is refused at startup with the two names in the message - not discovered three ticks in.

Optional compartments are built only when enabled(name) says so; the default asks whether enabled_by is a present config key. A compartment whose api major differs from this registry’s, or whose protocol is set and differs from the digest in ctx, is refused the same way: the node would rather not start than start wrong.

Returns the names built, in order. The context’s node (when it is a NodeApp) gets each compartment set on it under its name, which is what the rest of the node and the tests reach for today.

Parameters:
Return type:

list[str]

store_ref_problems(sub)[source]

Every other.key a command of sub reads, where other is built and declares no store key.

The class lint (Compartment._command_data_problems) holds the ref to requires/uses; only here do both sides exist, so only here can the store itself be checked. The manifest puts every required and used compartment before sub, so all that will be built already is. One that is not built is an absent uses - optional by definition, and the command must cope without it - and is skipped.

Parameters:

sub (Any)

Return type:

list[str]

wire(ctx)[source]

Every compartment’s back-edges, in manifest order, once all are built.

Parameters:

ctx (Any)

Return type:

None

route(router)[source]

Register every compartment’s declared protocols on the router.

Returns [(compartment, piuri)] as registered. A compartment that declares a protocol and has no handle is a programming error and is refused here, at startup, with its name.

Parameters:

router (Any)

Return type:

list[tuple[str, str]]

start()[source]

Start every compartment, in manifest order, each isolated.

One that raises is a refusal against itself, and what happens next depends on whether the node can run without it (audit L1):

required (not optional) every compartment already started is

stopped, newest first, and the raise goes on and stops the node. A node that cannot begin is a configuration the operator must hear about at boot - and it must not have half-begun, with a farewell sent by something that never served.

optional the rest still start. It is QUARANTINED

when it declares restart (its trial restarts it), FAILED when it does not.

Return type:

None

tick(now)[source]

Every compartment’s periodic work. One that raises does not stop the others, and its failure is a refusal against itself rather than a traceback nobody reads.

A raise also moves the compartment: to DEGRADED, or to QUARANTINED once its breaker trips. A quarantined compartment is skipped until its backoff passes, then given one trial tick - restarted first when it declares restart, because “turn it off and on again” is the recovery a stuck connection or a wedged worker needs. A retired or failed one is skipped.

Parameters:

now (int)

Return type:

list[tuple[Any, …]]

stop()[source]

Stop every compartment, and hand back what each had to say.

Returns [(name, whatever stop returned)]. One that raises does not stop the others: a node that cannot say goodbye must still stop. One whose start() raised is not stopped - it never began - and returns None.

Return type:

list[tuple[str | None, Any]]

report()[source]

Every compartment’s report, each isolated as trouble() and notes() already were.

This is what health(), status() and status.json are made of, and the tick writes status.json. One compartment whose report() raised used to raise here, so the node did its work and then failed the tick, every tick, and meshnode health failed with it (audit 2026-10-15, B2). A report that raises is now that compartment’s entry, an error, and a report_error trouble until a later report() succeeds - the others still report.

Return type:

dict[str, Mapping[str, Any]]

trouble()[source]
Return type:

list[str]

trouble_items()[source]

All active troubles as structured Trouble instances.

Return type:

list[Trouble]

notes()[source]
Return type:

NoteList

note_items()[source]

All active notes as structured Note instances.

Return type:

list[Note]

refusals(n=5)[source]

Every no this node said, across every compartment, newest last.

Parameters:

n (int)

Return type:

list[tuple[str | None, Refusal]]

live_keys()[source]
Return type:

tuple[str, …]

commands()[source]

name -> spec, prefixed by subsystem, for the control socket.

Return type:

OrderedDict[str, CommandSpec]

declared_commands()[source]

Every Command declared across compartments.

Return type:

tuple[Any, …]

dispatch(name, args)[source]
Parameters:
Return type:

Any

9.3. Lifecycle State Transitions

How a compartment lives: built, wired, running, degraded, quarantined, retired.

The fifth thing a compartment declares, beside PARAMS (what it can be told), CHANNELS (what it says), METRICS (what it measures) and COMMANDS (what it can be asked to do): LIFECYCLE, how it behaves when it fails.

Before this a compartment had no state. It was built or it was not, and once built it was ticked forever. A tick that raised was recorded as a refusal and then raised again on the next tick, and the one after, for as long as the node ran - a broken compartment cost a traceback per cycle, filled its refusal ring with one reason, and could not tell an operator anything they did not already know after the first one. Nothing distinguished “failed once and recovered” from “has been failing for a day”.

So the Registry now carries one Tracker per compartment and moves it through

CONFIGURED -> WIRED -> RUNNING <-> DEGRADED -> QUARANTINED -> RUNNING
^ (breaker) (trial / resume)

v | restart (only when declared)

DRAINING

v

RETIRED start() raised: -> FAILED, or

-> QUARANTINED when restartable

and each move is a declared channel, so the journal, the control socket and the metrics all see the same transition.

CONFIGURED built from its config block; not yet reaching its neighbours WIRED back-edges reached (wire() ran) RUNNING started and ticking cleanly DEGRADED the last tick raised; still ticked, and back to RUNNING after

one clean tick. A note, not trouble: one failure is weather.

QUARANTINED Breaker.failures ticks raised within Breaker.window

seconds. Not ticked until the backoff passes, then given one trial tick: clean returns it to RUNNING, a raise sends it back with the backoff doubled (to Breaker.backoff[1] at most). Trouble, because something is wrong now. resume lets an operator end it early.

FAILED an optional compartment’s start() raised and it does not

declare restart, so nothing here can safely try again. Not ticked, not stopped. Trouble. (A required compartment whose start() raises still stops the node - see Registry.start.)

DRAINING being stopped - for good, or for a restart RETIRED stopped; never ticked again

Lifecycle(restart=True) is a promise the compartment makes: its stop() and then start() on the SAME instance leave it as good as new. Only a compartment that makes it is restarted - by the restart control command, by a config reload that changes its own block, by a quarantine’s trial (which restarts it before the trial tick), and after a start() that raised (which quarantines it rather than failing it). The default is False because most compartments were written to start once: a restart nobody designed for would read as resilience the node does not have.

Lifecycle(snapshot=N) is the other promise, and it is about the PROCESS restarting rather than one compartment: a core upgrade, a digest change, a systemctl restart. The compartment implements snapshot() - a JSON-able mapping of the state worth carrying - and restore(state), and N is the version of that mapping’s shape. On a clean stop the node writes every started compartment’s snapshot to SNAPSHOT_FILE; the next start hands each one back BEFORE start() runs, but only when the version still matches, the file is recent (SNAPSHOT_MAX_AGE), and restore() returns. Anything else is a refusal recorded in the compartment’s lifecycle (restored), and it starts fresh - which is what it did before snapshots existed, so a refused restore costs continuity and nothing else. The file is removed once a start succeeds: a snapshot is handed over once.

restore() must be all-or-nothing: validate first, then assign. A raise is caught, but a half-applied restore is not something the node can see.

A package rather than a root module for the reason fleetmesh_node/channels is one: fleetmesh_node/*.py is held to a monotone baseline (fleetmesh.org/scripts/check-root.py). Standard library only, beside the two surfaces it emits through.

class fleetmesh_node.compartment.lifecycle.BreakerDecl[source]

Bases: TypedDict

failures: int
window: int
backoff: list[int]
class fleetmesh_node.compartment.lifecycle.Breaker[source]

Bases: object

When repeated failure stops being weather and becomes a fault.

failures ticks that raise within window seconds trip it. backoff is (first, ceiling) in seconds: the first quarantine lasts first, each failed trial doubles it, and it never exceeds ceiling. failures=0 turns the breaker off for a compartment that must be ticked whatever happens - the old behaviour, chosen rather than defaulted into.

failures: int = 5
window: int = 300
backoff: tuple[int, int] = (30, 600)
delay(trips)[source]

Seconds a compartment stays quarantined on its trips-th trip.

Parameters:

trips (int)

Return type:

int

problems()[source]
Return type:

list[str]

__init__(failures=5, window=300, backoff=(30, 600))
Parameters:
Return type:

None

class fleetmesh_node.compartment.lifecycle.Lifecycle[source]

Bases: object

How a compartment behaves when it fails. The default suits nearly all.

restart: stop() then start() on the same instance is safe and leaves it as good as new. snapshot: the version of what snapshot() returns and restore() reads; 0 carries nothing across a process restart. See the module docstring for everything that acts on either.

breaker: Breaker = Breaker(failures=5, window=300, backoff=(30, 600))
restart: bool = False
snapshot: int = 0
problems()[source]
Return type:

list[str]

describe()[source]
Return type:

LifecycleDecl

__init__(breaker=Breaker(failures=5, window=300, backoff=(30, 600)), restart=False, snapshot=0)
Parameters:
Return type:

None

class fleetmesh_node.compartment.lifecycle.LifecycleDecl[source]

Bases: TypedDict

breaker: BreakerDecl
restart: bool
snapshot: int
class fleetmesh_node.compartment.lifecycle.LifecycleRecord[source]

Bases: TypedDict

One compartment’s lifecycle as meshnode lifecycle and health read it.

state: str
since: int
failures: int
trips: int
until: int
last_error: str
started: bool | None
restarts: int
restored: str
transitions: dict[str, int]
declared: LifecycleDecl
class fleetmesh_node.compartment.lifecycle.SnapshotEntry[source]

Bases: TypedDict

version: int
state: Mapping[str, Any]
class fleetmesh_node.compartment.lifecycle.SnapshotFile[source]

Bases: TypedDict

format: int
at: int
compartments: dict[str, SnapshotEntry]
class fleetmesh_node.compartment.lifecycle.Tracker[source]

Bases: object

One compartment’s place in the lifecycle. Owned by the Registry.

Not thread-safe on its own: the Registry ticks from one thread and the control socket’s resume goes through the same lock the tick holds.

__init__(name, lifecycle, at=0)[source]
Parameters:
Return type:

None

name: str
lifecycle: Lifecycle
state: str
since: int
fails: Deque[int]
trips: int
until: int
last_error: str
started: bool | None
restarts: int
restored: str
transitions: Counter[str]
move(to, at, why='')[source]

Go to to. Returns the transition, or None when already there.

Parameters:
Return type:

Transition | None

due(now)[source]

Whether the Registry should tick this compartment now.

Parameters:

now (int)

Return type:

bool

succeeded(now)[source]

A clean tick. Clears the failure record and recovers if it was down.

Parameters:

now (int)

Return type:

Transition | None

failed(now, error)[source]

A tick that raised. Degrades, or trips the breaker.

Parameters:
Return type:

Transition | None

resume(now, why='resumed by the operator')[source]

End a quarantine now. The next tick is an ordinary one.

Parameters:
Return type:

Transition | None

start_failed(now, error)[source]

start() raised. Quarantined when a restart can try again, else FAILED.

From QUARANTINED (a trial restart that raised) this is a failed trial: the breaker’s failed already doubles the backoff and says so.

Parameters:
Return type:

Transition | None

restarted(now, why)[source]

stop() and start() both returned: as good as new, so a clean record.

Parameters:
Return type:

Transition | None

describe()[source]
Return type:

LifecycleRecord

class fleetmesh_node.compartment.lifecycle.Transition[source]

Bases: NamedTuple

Transition(compartment, was, now, at, why)

compartment: str

Alias for field number 0

was: str

Alias for field number 1

now: str

Alias for field number 2

at: int

Alias for field number 3

why: str

Alias for field number 4

static __new__(_cls, compartment, was, now, at, why)

Create new instance of Transition(compartment, was, now, at, why)

Parameters:
fleetmesh_node.compartment.lifecycle.channel_for(t)[source]

Which declared channel a transition is said on.

Parameters:

t (Transition)

Return type:

str

fleetmesh_node.compartment.lifecycle.discard_snapshots(directory)[source]

A snapshot is handed over once: gone after the start that used it.

Parameters:

directory (str)

Return type:

None

fleetmesh_node.compartment.lifecycle.gauge(count, name, description)[source]

A sampled gauge over the Registry’s trackers, built where they live.

Parameters:
Return type:

Metric

fleetmesh_node.compartment.lifecycle.read_snapshots(directory, now)[source]

(compartments, written at, why none) from the snapshot file.

An empty mapping with a reason when there is a file and it cannot be used - unreadable, another format, or older than SNAPSHOT_MAX_AGE - and with ‘’ when there is simply no file. Never raises: a node must start whatever the last one left behind.

Parameters:
Return type:

tuple[dict[str, SnapshotEntry], int, str]

fleetmesh_node.compartment.lifecycle.write_snapshots(directory, at, compartments)[source]

Write the snapshot file atomically. Returns its path.

Parameters:
Return type:

str

9.4. Execution Context

The shared surface a compartment is built from.

Every compartment used to be constructed by hand in fleetmesh_node/app/core.py from whichever of the node’s stores and services it happened to need, in one of six different signature styles, with node=self passed alongside so the compartment could reach anything the signature forgot. NodeContext is the one typed object that replaces that: the stores, the transport, the face, the clock, the config, and the handful of node-level callables a compartment still has to reach. A compartment’s from_context(ctx) says, in one place, what it takes from the node, and a third party writing a compartment against subsystem/1 has a stable thing to write against.

node stays on the context as a labelled escape hatch, not a hidden one: scheduler calls node.propose/node.pull and trust calls node.regrant, which are NodeApp methods and not stores. Anything reaching for ctx.node beyond those is a dependency that should be named here instead.

Standard library only.

class fleetmesh_node.compartment.context.NodeStores[source]

Bases: NamedTuple

The four durable stores a node keeps, as one argument.

events: Any

Alias for field number 0

grants: Any

Alias for field number 1

accounts: Any

Alias for field number 2

blobs: Any

Alias for field number 3

static __new__(_cls, events, grants, accounts, blobs)

Create new instance of NodeStores(events, grants, accounts, blobs)

Parameters:
  • events (Any)

  • grants (Any)

  • accounts (Any)

  • blobs (Any)

class fleetmesh_node.compartment.context.NodeContext[source]

Bases: object

Explicit, typed context handed to every compartment at assembly.

cfg is the live config dict the node mutates on reload; a compartment that must see changes reads through cfg_of(key) on each tick rather than copying a section at construction. descriptor is a getter because the descriptor is mined or loaded in start() and does not exist at the time the context is made.

dir: str
ks: Any
cfg: NodeConfigDict
clock: Callable[[], int]
events: NodeEventBus
stores: NodeStores
relays: list[str]
transport: Any | None = None
router: Any | None = None
face: Any | None = None
host: Any | None = None
peers: Any | None = None
policy: Any | None = None
ledger: Any | None = None
timeout: float = 15.0
stop: Event
descriptor()
Return type:

NostrEvent | None

public_descriptor()
Return type:

NostrEvent | None

digest: str | None = None
node: Any | None = None
says: Any | None = None
persist_cfg()
redescribe()
regrant(**kw)
propose(**kw)
pull(**kw)
amend(**kw)
wire_request(**kw)
build_descriptor()
property pubkey: str
property did: str
property node_class: str
cfg_of(key, default=None)[source]

A top-level config key as it is now, for compartments that read live. The same contract Compartment.config() keeps.

Parameters:
Return type:

Any

cfg_getter()[source]

The lambda: self.cfg several compartments take, named.

Return type:

Callable[[], Mapping[str, Any]]

block(block_cls)[source]

A compartment’s config section as its typed block, now.

block_cls.key names the section; an absent section is the default block. The file was checked at the door (load_config) and on every reload, so from_dict here cannot meet a shape it refuses - a block that reads live calls this each tick and gets the current values.

Parameters:

block_cls (type[B])

Return type:

B

block_getter(block_cls)[source]

lambda: ctx.block(cls), for a compartment that reads live.

Parameters:

block_cls (type[B])

Return type:

Callable[[], B]

path(*parts)[source]
Parameters:

parts (str)

Return type:

str

optional(name)[source]

A compartment named in the caller’s uses, if the node built it; None when it is off. Resolved once at construction: the manifest orders uses before the user, so a present one is already built. Tests that assemble without a node fall back to the attribute set on node by assemble(), which is the same object either way.

Parameters:

name (str)

Return type:

Any | None

classmethod build(directory, ks, cfg, clock, events, stores, relays, transport=None, router=None, **more)[source]
Parameters:
Return type:

NodeContext

__init__(dir, ks, cfg, clock, events, stores, relays, transport=None, router=None, face=None, host=None, peers=None, policy=None, ledger=None, timeout=15.0, stop=<factory>, descriptor=<function _no_descriptor>, public_descriptor=<function _no_descriptor>, digest=None, node=None, says=None, persist_cfg=<function NodeContext.<lambda>>, redescribe=<function NodeContext.<lambda>>, regrant=<function NodeContext.<lambda>>, propose=<function NodeContext.<lambda>>, pull=<function NodeContext.<lambda>>, amend=<function NodeContext.<lambda>>, wire_request=<function NodeContext.<lambda>>, build_descriptor=<function NodeContext.<lambda>>)
Parameters:
Return type:

None

9.5. Dependency Needs

Declared dependencies a compartment takes from the node.

class fleetmesh_node.compartment.need.Need[source]

Bases: object

One dependency a compartment takes from the node, declared where the compartment is.

Resolved against NodeContext at assembly by the base from_context:
  • a field (ks, transport, stores.grants, clock, propose, pull, regrant, etc.)

  • a typed config block (Need(‘settings’, block=SettlementConfig))

  • a compartment, which must appear in requires or uses, resolved from registry / context

  • a live config getter (Need(‘cfg’, ‘cfg’, getter=True) or Need(‘cfg’, block=UpdatesConfig, getter=True))

  • a node-relative path (Need(‘db_path’, path=’DB’) or Need(‘db_path’, path=’updates.sqlite’))

  • or late=True: resolved and bound after all compartments are assembled, replacing wire().

key: str
source: str | None = None
block: type | None = None
late: bool = False
getter: bool = False
path: str | None = None
field: str | None = None
__init__(key, source=None, *, block=None, late=False, getter=False, path=None, field=None)[source]
Parameters:
Return type:

None

resolve(ctx, cls)[source]
Parameters:
Return type:

Any

resolve_late(ctx, instance, registry)[source]
Parameters:
Return type:

Any

problems(cls)[source]
Parameters:

cls (type)

Return type:

list[str]

9.6. Refusal & Problem Reporting

Every ‘no’ a compartment says, counted by reason and kept with detail.

Split out of fleetmesh_node/compartment.py when it became a package; see that package’s docstring for why a refusal that is not recorded is indistinguishable from silence.

class fleetmesh_node.compartment.refusals.Refusal[source]

Bases: NamedTuple

Refusal(at, kind, subject, why, detail)

at: int

Alias for field number 0

kind: str

Alias for field number 1

subject: str | None

Alias for field number 2

why: str

Alias for field number 3

detail: Mapping[str, Any]

Alias for field number 4

static __new__(_cls, at, kind, subject, why, detail)

Create new instance of Refusal(at, kind, subject, why, detail)

Parameters:
  • at (int)

  • kind (str)

  • subject (Optional[str])

  • why (str)

  • detail (Mapping[str, Any])

class fleetmesh_node.compartment.refusals.RefusalRecentSummary[source]

Bases: TypedDict

at: int
kind: str
subject: str | None
why: str
detail: Mapping[str, Any]
class fleetmesh_node.compartment.refusals.RefusalsStateReport[source]

Bases: TypedDict

total: int
by_reason: dict[str, int]
recent: list[RefusalRecentSummary]
class fleetmesh_node.compartment.refusals.Refusals[source]

Bases: object

Every ‘no’ one compartment said, counted by reason and kept with detail.

Counted so a rate is visible; kept so the last few can be read. A reason is a short stable string and never a formatted id, because a reason is a category and the ids belong in the detail where they cannot explode the key space.

__init__(name, keep=200, clock=None)[source]
Parameters:
Return type:

None

name: str | None
keep: int
clock: Callable[[], int]
counts: Counter[str]
recent: Deque[Refusal]
refuse(kind, why, subject=None, detail=None, at=None)[source]
Parameters:
Return type:

Refusal

total()[source]
Return type:

int

last(n=5)[source]
Parameters:

n (int)

Return type:

list[Refusal]

within(seconds, now=None, kind=None, why=None)[source]

Refusals from the last seconds, which is what trouble means.

Trouble is what is wrong NOW. Reading the whole buffer reports a fault that has been fixed until the buffer happens to roll, and an operator who is shouted at about something already mended learns to stop reading the shouting. The counts keep the history; this answers the present.

Parameters:
  • seconds (int)

  • now (int | None)

  • kind (str | None)

  • why (str | None)

Return type:

list[Refusal]

state(n=5)[source]
Parameters:

n (int)

Return type:

RefusalsStateReport

fleetmesh_node.compartment.refusals.why_detail(e)[source]
Parameters:

e (BaseException)

Return type:

dict[str, str]

Class-driven problem and runtime trouble definitions for compartments.

Every compartment declares what it is (SCHEMA, COMMANDS, NEEDS, STORES, WORKERS, EVERY, CHANNELS, METRICS, LIFECYCLE). When a declaration is invalid, declaration_problems collects Problem instances rather than loose strings, carrying the surface, semantic code, target, and human-readable message.

Similarly, when a compartment is in an abnormal state, trouble() returns Trouble instances carrying the fault code, severity, timestamp, and optional remediation hint.

Both Problem and Trouble inherit from str so that:
  • String formatting (str(p), f”{p}”) produces the sentence directly.

  • Substring checks (‘twice’ in p, ‘relay’ in t) continue to pass.

  • List comparisons ([p] == [‘message’]) evaluate True against raw strings.

  • Existing callers, tests, and json encoders require zero breaking changes.

class fleetmesh_node.compartment.problem.ProblemDict[source]

Bases: TypedDict

Concrete dictionary structure for a declaration problem.

message: str
surface: str
code: str
target: str
hint: str | None
reference: str
expected: str
got: str
owner: str
class fleetmesh_node.compartment.problem.Problem[source]

Bases: str

A structured declaration problem.

Subclasses str for complete backwards compatibility with tests and callers expecting str messages, while exposing structured metadata for linters, checkers, and IDE diagnostics.

surface: str
code: str
target: str
message: str
hint: str | None
static __new__(cls, message, *, surface='', code='', target='', hint=None)[source]
Parameters:
Return type:

P

to_dict()[source]

Dictionary representation for structured reporting.

Return type:

ProblemDict

class fleetmesh_node.compartment.problem.DuplicateProblem[source]

Bases: Problem

An item was declared twice on the same surface.

static __new__(cls, surface, target, message=None, hint=None)[source]
Parameters:
  • surface (str)

  • target (str)

  • message (str | None)

  • hint (str | None)

Return type:

DuplicateProblem

class fleetmesh_node.compartment.problem.InvalidIdentifierProblem[source]

Bases: Problem

An identifier name does not follow the required naming pattern.

static __new__(cls, surface, target, message=None, hint=None)[source]
Parameters:
  • surface (str)

  • target (str)

  • message (str | None)

  • hint (str | None)

Return type:

InvalidIdentifierProblem

class fleetmesh_node.compartment.problem.ReferenceProblem[source]

Bases: Problem

A declaration references an entity that is unknown or missing.

reference: str
static __new__(cls, surface, target, reference, message=None, hint=None)[source]
Parameters:
  • surface (str)

  • target (str)

  • reference (str)

  • message (str | None)

  • hint (str | None)

Return type:

ReferenceProblem

to_dict()[source]

Dictionary representation for structured reporting.

Return type:

ProblemDict

class fleetmesh_node.compartment.problem.TypeMismatchProblem[source]

Bases: Problem

A declaration entry has the wrong type or does not implement the expected class.

expected: str
got: str
static __new__(cls, surface, expected, got, message=None, hint=None)[source]
Parameters:
  • surface (str)

  • expected (str)

  • got (str)

  • message (str | None)

  • hint (str | None)

Return type:

TypeMismatchProblem

to_dict()[source]

Dictionary representation for structured reporting.

Return type:

ProblemDict

class fleetmesh_node.compartment.problem.ShadowingProblem[source]

Bases: Problem

A declared key would shadow a method or class attribute.

owner: str
static __new__(cls, surface, target, owner, message=None, hint=None)[source]
Parameters:
  • surface (str)

  • target (str)

  • owner (str)

  • message (str | None)

  • hint (str | None)

Return type:

ShadowingProblem

to_dict()[source]

Dictionary representation for structured reporting.

Return type:

ProblemDict

class fleetmesh_node.compartment.problem.IncompatibleProblem[source]

Bases: Problem

Two declarations or declarations and method implementations are incompatible.

static __new__(cls, surface, target, message, hint=None)[source]
Parameters:
  • surface (str)

  • target (str)

  • message (str)

  • hint (str | None)

Return type:

IncompatibleProblem

class fleetmesh_node.compartment.problem.Problems[source]

Bases: list[Any]

A list of Problem instances providing query methods and surface filtering.

for_surface(surface)[source]

Return all problems recorded for a specific declaration surface.

Parameters:

surface (str)

Return type:

list[Problem]

by_code(code)[source]

Return all problems with a specific semantic code.

Parameters:

code (str)

Return type:

list[Problem]

surfaces()[source]

Set of surfaces that have problems.

Return type:

set[str]

codes()[source]

Set of unique problem codes.

Return type:

set[str]

to_dicts()[source]

Serialize all problems to dictionaries.

Return type:

list[ProblemDict]

add(problem_or_message, *, surface='', code='', target='', hint=None)[source]

Append a problem or wrap a string message into a Problem.

Parameters:
  • problem_or_message (Any)

  • surface (str)

  • code (str)

  • target (str)

  • hint (str | None)

Return type:

None

class fleetmesh_node.compartment.problem.TroubleDict[source]

Bases: TypedDict

Concrete dictionary structure for runtime trouble.

message: str
code: str
severity: str
compartment: str
since: int | None
hint: str | None
metadata: Mapping[str, Any]
class fleetmesh_node.compartment.problem.Trouble[source]

Bases: str

What an operator should be told without having to ask for it.

Subclasses str so that existing tests asserting against trouble() strings, substring matches (‘relay’ in t), list equality ([t] == [‘foo’]), and string formatting continue to work 100% identically without breaking changes.

code: str
compartment: str
message: str
severity: str
since: int | None
hint: str | None
metadata: Mapping[str, Any]
static __new__(cls, message, *, code='fault', compartment='', severity='trouble', since=None, hint=None, **metadata)[source]
Parameters:
  • cls (type[T_tr])

  • message (str)

  • code (str)

  • compartment (str)

  • severity (str)

  • since (int | None)

  • hint (str | None)

  • metadata (Any)

Return type:

T_tr

to_dict()[source]

Serialize to a JSON-compatible dictionary.

Return type:

TroubleDict

class fleetmesh_node.compartment.problem.TroubleList[source]

Bases: list[Any]

A list of Trouble items offering filtering and serialization.

for_compartment(compartment)[source]

Filter troubles belonging to a specific compartment.

Parameters:

compartment (str)

Return type:

list[Trouble]

by_code(code)[source]

Filter troubles by fault code.

Parameters:

code (str)

Return type:

list[Trouble]

by_severity(severity)[source]

Filter troubles by severity (‘trouble’, ‘warning’, ‘fatal’, etc.).

Parameters:

severity (str)

Return type:

list[Trouble]

codes()[source]

Set of unique trouble codes.

Return type:

set[str]

compartments()[source]

Set of compartments reporting trouble.

Return type:

set[str]

to_dicts()[source]

Serialize all troubles to dictionaries.

Return type:

list[TroubleDict]

add(trouble_or_message, *, code='fault', compartment='', severity='trouble', since=None, hint=None, **kw)[source]

Append a trouble item or wrap a raw string into a Trouble instance.

Parameters:
  • trouble_or_message (Any)

  • code (str)

  • compartment (str)

  • severity (str)

  • since (int | None)

  • hint (str | None)

  • kw (Any)

Return type:

None

class fleetmesh_node.compartment.problem.NoteDict[source]

Bases: TypedDict

Concrete dictionary structure for runtime notes.

message: str
topic: str
level: str
compartment: str
since: int | None
metadata: Mapping[str, Any]
class fleetmesh_node.compartment.problem.Note[source]

Bases: str

What an operator would want to read, that is not a fault.

A relay cooling after a rate-limit, a peer that announced it is leaving: the node behaving, and the reason a quiet mesh is quiet. Kept apart from trouble() so no reader has to classify prose. Subclasses str so that existing tests asserting against notes() strings, substring matches, or list equality continue to work 100% identically.

topic: str
compartment: str
message: str
level: str
since: int | None
metadata: Mapping[str, Any]
static __new__(cls, message, *, topic='general', compartment='', level='info', since=None, **metadata)[source]
Parameters:
  • cls (type[T_note])

  • message (str)

  • topic (str)

  • compartment (str)

  • level (str)

  • since (int | None)

  • metadata (Any)

Return type:

T_note

to_dict()[source]

Serialize to a JSON-compatible dictionary.

Return type:

NoteDict

class fleetmesh_node.compartment.problem.NoteList[source]

Bases: list[Any]

A list of Note items offering filtering and serialization.

for_compartment(compartment)[source]

Filter notes belonging to a specific compartment.

Parameters:

compartment (str)

Return type:

list[Note]

by_topic(topic)[source]

Filter notes by topic.

Parameters:

topic (str)

Return type:

list[Note]

by_level(level)[source]

Filter notes by level (‘info’, ‘notice’, ‘debug’, etc.).

Parameters:

level (str)

Return type:

list[Note]

topics()[source]

Set of unique note topics.

Return type:

set[str]

compartments()[source]

Set of compartments reporting notes.

Return type:

set[str]

to_dicts()[source]

Serialize all notes to dictionaries.

Return type:

list[NoteDict]

add(note_or_message, *, topic='general', compartment='', level='info', since=None, **kw)[source]

Append a note item or wrap a raw string into a Note instance.

Parameters:
  • note_or_message (Any)

  • topic (str)

  • compartment (str)

  • level (str)

  • since (int | None)

  • kw (Any)

Return type:

None

9.7. Storage Collections

What a compartment holds: its in-memory collections, declared and bounded.

The sixth thing a compartment declares, beside PARAMS (what it can be told), CHANNELS (what it says), METRICS (what it measures), COMMANDS (what it can be asked to do) and LIFECYCLE (how it fails): STORES, what it keeps.

Before this a compartment’s memory was whatever attributes its __init__ happened to assign. Nothing outside it knew they existed, so nobody could ask how much announce was holding, which collections grow with the number of peers, or what a command reads. Some were trimmed by hand (del self.log [:-200] in capacity) and some were not trimmed at all, and the difference was visible only to someone reading the code.

A Store declares one collection:

key the attribute it is reached under, and its name everywhere else kind RING a log, newest last, oldest dropped at bound

TABLE a mapping, keyed by keyed_by SET members, keyed by keyed_by COUNTERS a fixed set of named integers, the fields of shape

shape the type of one entry (one row, one member, one record). A

TypedDict is checked on every write: required keys present, no key it does not name. A class is checked with isinstance. A write that does not fit raises TypeError - a programming error, and the lifecycle degrades the compartment that made it.

bound how many entries it may hold. Required: a collection that grows

with the outside world and says nothing about how far is the failure this exists to prevent. COUNTERS are bounded by their shape and take no bound.

evict what happens at the bound. OLDEST drops the earliest written,

LRU the least recently read or written, REFUSE refuses the write (StoreFull, or False from put) - for state that must not be silently lost, where the caller has to decide.

keyed_by what makes it grow: ‘peer’, ‘event’, ‘url’. Required on a

TABLE and a SET, because that is the question an operator asks.

persist MEMORY (gone with the process) or SNAPSHOT (carried across a

process restart by the lifecycle, fleetmesh_node/lifecycle phase 4)

sensitive its entries are never shown in a report, only its size

and the compartment base class builds a container for each one - Ring, Table, Members, Counters - that enforces the bound and the shape, and counts itself: inserts, evictions, refusals and its high-water mark. So the declaration and the behaviour cannot drift apart, and the node meters every compartment’s memory without the compartment writing a metric.

What is NOT a store: a list of callbacks (wiring), a config cache, a small fixed lookup table, a per-packet buffer on a hot path. The rule is whether the collection grows with the outside world.

Durable data (the event store, grants, the change log) lives in sqlite and is not declared here yet. A persist value for it arrives with the code that honours it.

A package rather than a root module for the reason fleetmesh_node/channels is one: fleetmesh_node/*.py is held to a monotone baseline (fleetmesh.org/scripts/check-root.py). Standard library only.

class fleetmesh_node.compartment.stores.Counters[source]

Bases: _Container

A fixed set of named integers - the fields of the store’s TypedDict.

__init__(store)[source]
Parameters:

store (Store)

Return type:

None

incr(field, n=1)[source]
Parameters:
Return type:

int

as_dict()[source]
Return type:

dict[str, int]

items()[source]
Return type:

list[tuple[str, int]]

keys()[source]
Return type:

list[str]

values()[source]
Return type:

list[int]

get(field, default=None)[source]
Parameters:
  • field (str)

  • default (int | None)

Return type:

int | None

dump()[source]

The contents as JSON-able data.

Return type:

object

check(data)[source]

Raise ValueError unless data is a dump this store can load whole. Separate from load() so a compartment’s restore is all or nothing.

Parameters:

data (object)

Return type:

None

load(data)[source]

Replace the contents with a checked dump. Not counted as inserts.

Parameters:

data (object)

Return type:

None

class fleetmesh_node.compartment.stores.Holdings[source]

Bases: object

One compartment’s containers, built from its STORES. Owned by the base.

__init__(stores)[source]
Parameters:

stores (Sequence[Store])

Return type:

None

items()[source]
Return type:

list[tuple[str, Ring[Any] | Table[Any, Any] | Members[Any] | Counters]]

live()[source]
Return type:

dict[str, StoreLive]

persisted()[source]
Return type:

dict[str, Ring[Any] | Table[Any, Any] | Members[Any] | Counters]

snapshot()[source]
Return type:

Mapping[str, Any]

restore(state)[source]

All or nothing: every persisted store checks its dump, then all load.

Parameters:

state (Mapping[str, Any])

Return type:

None

class fleetmesh_node.compartment.stores.Members[source]

Bases: _Container, Generic[K]

A bounded set. Evicts in the order members were added (or touched, LRU).

__init__(store)[source]
Parameters:

store (Store)

Return type:

None

add(member)[source]

Add one. False - and counted - when a REFUSE set is full.

Parameters:

member (K)

Return type:

bool

discard(member)[source]
Parameters:

member (K)

Return type:

None

remove(member)[source]
Parameters:

member (K)

Return type:

None

clear()[source]
Return type:

None

dump()[source]

The contents as JSON-able data.

Return type:

object

check(data)[source]

Raise ValueError unless data is a dump this store can load whole. Separate from load() so a compartment’s restore is all or nothing.

Parameters:

data (object)

Return type:

None

load(data)[source]

Replace the contents with a checked dump. Not counted as inserts.

Parameters:

data (object)

Return type:

None

class fleetmesh_node.compartment.stores.Ring[source]

Bases: _Container, Generic[V]

A log: newest last, the oldest dropped at the bound.

__init__(store)[source]
Parameters:

store (Store)

Return type:

None

append(item)[source]
Parameters:

item (V)

Return type:

None

extend(items)[source]
Parameters:

items (Iterable[V])

Return type:

None

last(n)[source]
Parameters:

n (int)

Return type:

list[V]

discard(item)[source]

Take back the newest entry equal to item; False if none is kept.

For a log written before the thing it records, and undone when that thing failed (sync records a handover, then sends it). The newest, because the entry being undone is the one just written. Not an eviction: nothing was dropped for room, so the counts stay as they are.

Parameters:

item (V)

Return type:

bool

clear()[source]
Return type:

None

dump()[source]

The contents as JSON-able data.

Return type:

object

check(data)[source]

Raise ValueError unless data is a dump this store can load whole. Separate from load() so a compartment’s restore is all or nothing.

Parameters:

data (object)

Return type:

None

load(data)[source]

Replace the contents with a checked dump. Not counted as inserts.

Parameters:

data (object)

Return type:

None

class fleetmesh_node.compartment.stores.Store[source]

Bases: object

One collection a compartment keeps. See the module docstring.

key: str
description: str
kind: str
shape: type | None = None
bound: int = 0
evict: str = 'oldest'
keyed_by: str = ''
persist: str = 'memory'
sensitive: bool = False
tags: tuple[str, ...] = ()
property limit: int

declared, or a COUNTERS store’s field count.

Type:

The bound in force

problems()[source]

Everything wrong with this declaration, in sentences, collected.

Return type:

list[str]

describe()[source]
Return type:

StoreRecord

build()[source]

The container that keeps this declaration’s promises.

Return type:

Ring[Any] | Table[Any, Any] | Members[Any] | Counters

__init__(key, description, kind, shape=None, bound=0, evict='oldest', keyed_by='', persist='memory', sensitive=False, tags=())
Parameters:
Return type:

None

exception fleetmesh_node.compartment.stores.StoreFull[source]

Bases: Exception

A REFUSE store at its bound was asked to take a new entry.

class fleetmesh_node.compartment.stores.StoreLive[source]

Bases: TypedDict

What a store is holding now, for a compartment’s report.

kind: str
size: int
bound: int
high_water: int
inserts: int
evictions: int
refused: int
class fleetmesh_node.compartment.stores.StoreRecord[source]

Bases: TypedDict

A store as the census, meshnode subsystems and the docs read it.

key: str
description: str
kind: str
shape: str
bound: int
evict: str
keyed_by: str
persist: str
sensitive: bool
tags: list[str]
compartment: str
class fleetmesh_node.compartment.stores.Table[source]

Bases: _Container, MutableMapping[K, V]

A bounded mapping. Reads refresh an entry’s place when evict is LRU.

__init__(store)[source]
Parameters:

store (Store)

Return type:

None

put(key, value)[source]

Write one entry. False - and counted - when a REFUSE store is full.

Parameters:
  • key (K)

  • value (V)

Return type:

bool

dump()[source]

The contents as JSON-able data.

Return type:

object

check(data)[source]

Raise ValueError unless data is a dump this store can load whole. Separate from load() so a compartment’s restore is all or nothing.

Parameters:

data (object)

Return type:

None

load(data)[source]

Replace the contents with a checked dump. Not counted as inserts.

Parameters:

data (object)

Return type:

None

fleetmesh_node.compartment.stores.declared(obj)[source]

The stores a compartment declares, or () for one not yet converted.

Parameters:

obj (Any)

Return type:

tuple[Store, …]

fleetmesh_node.compartment.stores.every_store(compartments)[source]

Every declared store: what the node keeps, beside what it says (every_channel), measures (every_metric) and can be told (every_parameter).

Parameters:

compartments (Sequence[Any])

Return type:

list[StoreRecord]

fleetmesh_node.compartment.stores.shape_problem(shape, value)[source]

Why value is not one shape, or ‘’ when it is (or nothing is declared).

Shallow by design: a TypedDict’s keys, not its values’ types. The keys are where drift happens - a field renamed in one writer and not another - and checking them costs a set comparison per write.

Parameters:
Return type:

str

9.8. Sidecar Bridge

A sidecar, and the bridge compartment that is the node’s only way to reach it.

Three words, kept apart because the node had one word for two things (audit 2026-10-07-3, finding “two things called sidecar”):

compartment in-process. Built, wired, started, ticked, restarted and

retired by the Registry; its whole lifecycle is the node’s.

sidecar a separate process the node reaches but does not contain:

fips (Rust), libp2p (sixty-three packages, trio, will not install on 3.14), bacalhau, grasp, strfry. Kept out because its codebase, its dependencies, its runtime or its licence do not belong in fleetmesh_node/ - which is standard library plus cryptography, so that a second implementer never inherits any of it. The node never starts or supervises one (supervised is False, and stays False until code honours it).

bridge the ONE compartment that fronts one sidecar. Everything on the

node that needs a sidecar goes through its bridge - names it in requires/uses and calls bridge.call() or a method the bridge offers - and nothing else opens the sidecar’s socket. So the sidecar’s settings (PARAMS: endpoint, timeout), what it says (CHANNELS), what it measures (METRICS), what an operator can ask of it (COMMANDS) and how it fails (LIFECYCLE) are declared once, on the bridge, the way every other compartment declares them.

What a bridge gets from this base, so that every sidecar is reached the same way:

  • SIDECAR, a manifest: the protocol it speaks (family/major), what it wraps upstream, the command that runs it standalone, and the request that proves it is there.

  • a link state - unknown, up, down, incompatible - moved only by call(), said once each way on three declared channels and counted: <name>.sidecar.reachable|unreachable|incompatible.

  • the version gate (audit S1): every reply carries the protocol the sidecar speaks, and a different family or major is refused - a bridge that read a /2 reply as /1 would be wrong silently. On a link that is not up the manifest’s probe goes first as a handshake, so a sidecar that speaks another major is refused before it is sent anything that carries data.

  • two commands on the control socket: <name>.sidecar (the manifest and the link now) and <name>.probe (ask the sidecar now).

  • Lifecycle(restart=True): a bridge holds a link and nothing more, so a restart forgets the link and the next call finds out afresh. A wedged link that trips the breaker is restarted by its quarantine trial.

  • trouble when the sidecar is wanted and down or incompatible, naming what this node loses (CONSEQUENCE).

Two ways a sidecar runs, both described by the same manifest:

bridge mode the sidecar is already running - ours, or one on the market

(a strfry, a bacalhau) - and the bridge compartment in the node talks to it.

standalone SIDECAR.standalone is the command that runs it on its own,

beside the node or on another host; the bridge does not care who started it, only that its endpoint answers.

The transport is a unix socket carrying one JSON object per line, which is what announce, p2p and fips already speak. HTTP (the class-A manifests in fleetmesh_node/sidecars: grasp, ncontainer, magpie) arrives with the first bridge that needs it; TRANSPORTS says what is implemented and a manifest naming another is refused at import rather than at the first call.

Named sidecar_bridge because fleetmesh_node/bridge is the Universal Nostr Relay Bridge, a compartment called bridge that fronts relays rather than a sidecar. A package rather than a root module for the reason fleetmesh_node/lifecycle is one. Standard library only.

class fleetmesh_node.compartment.sidecar.Bridge[source]

Bases: Compartment

The compartment that fronts one sidecar. Subclass, declare SIDECAR, implement endpoint(), and reach the sidecar only through call().

Optional hooks: wanted() (False turns the link checks and trouble off, e.g. a sidecar the config has not enabled) and forget() (what the bridge must forget when its link is reset, at start and on every restart).

SIDECAR: Sidecar | None = None
CONSEQUENCE: str = 'what needs it waits'
LIFECYCLE: Lifecycle = Lifecycle(breaker=Breaker(failures=5, window=300, backoff=(30, 600)), restart=True, snapshot=0)
timeout: float = 5.0
__init__(node, clock=None)[source]
Parameters:
Return type:

None

property sidecar: Sidecar
endpoint()[source]
Return type:

str

wanted()[source]
Return type:

bool

forget()[source]

What a reset link must take with it. Nothing, by default.

Return type:

None

start()[source]

Everything that needs the rest of the node to exist already.

Return type:

None

stop()[source]

Anything that must be said before the node goes. Must not raise.

Return type:

Any

call(cmd, **args)[source]

The only way to the sidecar. Moves the link and says so once each way.

On a link that is not up, the manifest’s probe request goes first, as a handshake: the version gate must refuse BEFORE a request carrying data reaches a sidecar that would misread it, not after. One extra round trip per (re)connection, none while the link is up.

Raises SidecarError (SidecarIncompatible for a protocol this bridge does not speak); the caller decides what a missing sidecar costs it.

Parameters:
Return type:

Any

probe()[source]

Ask the sidecar now. Never raises: the answer says what happened.

Return type:

ProbeRecord

property available: bool

Whether a compartment that depends on this sidecar should try now.

bridge_state()[source]
Return type:

LinkRecord

sections()[source]

What a KIND of compartment adds to every report of its kind - a bridge, its link - so that a subclass’s own state() stays its own.

Return type:

Mapping[str, Any]

trouble()[source]

What an operator should be told without having to ask for it.

Everything here is WRONG: a watcher reds on it and a deploy fails on it. Something worth reading that is not a fault goes in notes(). May return a list of strings or typed Trouble instances.

Return type:

list[str]

abstract: ClassVar[bool] = True
class fleetmesh_node.compartment.sidecar.LinkRecord[source]

Bases: TypedDict

sidecar: SidecarRecord
endpoint: str
since: int
protocol: str
last_error: str
calls: int
failures: int
class fleetmesh_node.compartment.sidecar.ProbeRecord[source]

Bases: TypedDict

What <name>.probe answers: the link, and the status or the error.

protocol: str
status: object
error: str
class fleetmesh_node.compartment.sidecar.Sidecar[source]

Bases: object

What a bridge fronts. Declared on the bridge as SIDECAR.

name the sidecar’s name; also the bridge compartment’s protocol family/major this bridge speaks, e.g. ‘fleetmesh-announce/1’ upstream what the sidecar wraps, for a person: ‘py-libp2p gossipsub’ transport how it is reached; one of TRANSPORTS standalone the command that runs it on its own, for the docs and the

sidecar command; ‘’ when it has none

probe the request that proves it is there and returns its status supervised False: the node depends on it and never starts or restarts

it. Refused when True until the code that would honour it exists - a declared supervisor nothing runs is worse than none.

name: str
protocol: str
upstream: str
transport: str = 'unix'
standalone: str = ''
probe: str = 'status'
supervised: bool = False
property family: str
property major: str
compatible(said)[source]

Whether a sidecar that says it speaks said speaks this bridge’s protocol. Same family, same major; a minor (/1.3) is additive. An unstated protocol is accepted - the sidecars predate the field - and the link records that it was not stated.

Parameters:

said (str)

Return type:

bool

describe()[source]
Return type:

SidecarRecord

__init__(name, protocol, upstream, transport='unix', standalone='', probe='status', supervised=False)
Parameters:
Return type:

None

exception fleetmesh_node.compartment.sidecar.SidecarError[source]

Bases: Exception

No sidecar, a sidecar that will not answer, or one that says no.

exception fleetmesh_node.compartment.sidecar.SidecarIncompatible[source]

Bases: SidecarError

A sidecar that answered in a protocol this bridge does not speak.

class fleetmesh_node.compartment.sidecar.SidecarRecord[source]

Bases: TypedDict

name: str
protocol: str
upstream: str
transport: str
standalone: str
probe: str
supervised: bool
fleetmesh_node.compartment.sidecar.bridge_channels(name)[source]
Parameters:

name (str)

Return type:

tuple[Channel, …]

fleetmesh_node.compartment.sidecar.bridge_commands(sc)[source]
Parameters:

sc (Sidecar)

Return type:

tuple[Command, …]

fleetmesh_node.compartment.sidecar.bridge_metrics(name)[source]
Parameters:

name (str)

Return type:

tuple[Metric, …]

fleetmesh_node.compartment.sidecar.bridges(compartments)[source]

The bridges among a node’s compartments: every sidecar it reaches.

Parameters:

compartments (Any)

Return type:

list[Bridge]

fleetmesh_node.compartment.sidecar.jsonline_call(path, cmd, timeout=5.0, **args)[source]

One request, one reply, one connection, over a unix socket.

Returns (result, the protocol the reply said it speaks, or ‘’). Raises SidecarError for all of no sidecar, a sidecar that will not answer, and a sidecar that says no. The wire was announce’s; it is every unix sidecar’s.

Parameters:
Return type:

tuple[Any, str]

9.9. Wire Event Routing

WireProtocol: base class for compartments that speak a wire protocol.

A compartment that speaks one or more PIURIs declares what it handles (HANDLERS) and what it emits (OUTBOUND). The base class verifies the declarations at class definition time and binds a WireClient (self.wire) to manage outbound sends, requests, replies, and correlation.

class fleetmesh_node.compartment.wire.Outbound[source]

Bases: object

An outbound message kind declared by a WireProtocol.

States what message kind this compartment emits over the wire, what reply kinds it expects in return (if an RPC request), and what documentation explains its role.

__init__(kind, reply=None, reads=(), writes=(), doc='')[source]
Parameters:
Return type:

None

class fleetmesh_node.compartment.wire.WireClient[source]

Bases: object

The client adapter bound to self.wire on a WireProtocol compartment.

__init__(protocol)[source]
Parameters:

protocol (WireProtocol)

Return type:

None

property transport: Any
kind_of(message)[source]

Extract the message kind relative to this protocol’s declared PIURIs.

Parameters:

message (Mapping[str, Any])

Return type:

str | None

send(to_pubkey, message, *, anonymous=False, stored=False)[source]

Dispatch one message to to_pubkey over the transport ladder.

Parameters:
Return type:

Any

request(to_pubkey, message, *, timeout=30.0, anonymous=False)[source]

Dispatch a request message and await a correlated reply.

Parameters:
Return type:

Any | None

reply(inbound, message, *, sender=None, anonymous=False)[source]

Reply in-band to an inbound message, carrying forward its thread id.

Parameters:
  • inbound (Any)

  • message (Any)

  • sender (str | None)

  • anonymous (bool)

Return type:

Any

class fleetmesh_node.compartment.wire.WireProtocol[source]

Bases: Compartment

A compartment that speaks one or more DIDComm wire protocols (PIURIs).

piuris: tuple[str, ...] = ()
HANDLERS: tuple[Handler, ...] = ()
OUTBOUND: tuple[Outbound, ...] = ()
classmethod declaration_problems()[source]

Everything wrong with this class’s declarations, as sentences.

Collected rather than raised one at a time, like Metric.problems and config.Problems: whoever fixes one wants to see them all. Returns Problems (a list subclass) holding typed Problem instances.

Return type:

list[str]

__init__(node=None, clock=None, cfg=None, says=None, db=None, **kw)[source]
Parameters:
Return type:

None

abstract: ClassVar[bool] = True

9.10. Background Workers

WORKERS: background worker threads declared on a compartment.

class fleetmesh_node.compartment.worker.Worker[source]

Bases: object

A background worker thread declared on a compartment class.

The base Compartment starts declared workers during start() and signals them to stop and joins them during stop().

run

The method name on the compartment to run in a thread.

Type:

str

name

A unique name for the worker/thread (defaults to run).

Type:

str

timeout

How long in seconds to wait for the thread to join on stop().

Type:

float

daemon

Whether the thread is a daemon thread (defaults to True).

Type:

bool

when

Optional condition to run: attribute name (checked for truthiness) or callable receiving the compartment instance.

Type:

str | Callable[[Any], bool] | None

run: str
name: str = ''
timeout: float = 1.0
daemon: bool = True
when: str | Callable[[Any], bool] | None = None
should_run(instance)[source]

True if any when condition holds.

Parameters:

instance (Any)

Return type:

bool

problems(cls)[source]

Lint this declaration against the target class.

Parameters:

cls (type[Any])

Return type:

list[str]

__init__(run, name='', timeout=1.0, daemon=True, when=None)
Parameters:
Return type:

None

9.11. Periodic Handlers

EVERY: periodic work declared on a compartment.

class fleetmesh_node.compartment.every.Every[source]

Bases: object

A periodic job declared on a compartment class.

seconds

How often to run the job, in seconds. Can be an int, float, a callable receiving the compartment instance, or a Parameter. A callable that resolves to zero or less turns the job off (see is_off): that is how a setting like check_every: 0 says “only on command”.

Type:

int | float | Callable[[Any], int | float] | Any

run

The method name on the compartment to call when due.

Type:

str

name

A unique name for the job within the compartment (defaults to run).

Type:

str

report

Optional method name or callable to convert the method’s return value into a list of [(what, …)] tuples for the tick log.

Type:

str | Callable[[…], Any] | None

seconds: int | float | Callable[[Any], int | float] | Any
run: str
name: str = ''
report: str | Callable[[...], Any] | None = None
get_seconds(instance)[source]

Resolve the interval in seconds against a compartment instance.

Parameters:

instance (Any)

Return type:

float

is_off(instance)[source]

Whether the interval says this job does not run on a schedule.

Zero, a negative number, or anything not finite. Updates used to spell “off” as infinity, and report() died on int(inf) - which took the whole health report with it, every tick (audit 2026-10-15, B1). Off is now one rule, read here, and never a number anyone does arithmetic on.

Parameters:

instance (Any)

Return type:

bool

due(instance, now)[source]

True if this job has never run or if at least seconds have passed since last run. Never true for a job that is off, including on its first tick.

Parameters:
Return type:

bool

execute(instance, now)[source]

Call the target method on instance, passing now if accepted.

Parameters:
Return type:

Any

problems(cls)[source]

Lint this declaration against the target class.

Parameters:

cls (type[Any])

Return type:

list[str]

__init__(seconds, run, name='', report=None)
Parameters:
Return type:

None

HANDLERS: what a compartment can receive from the wire, declared where it is.

A wire compartment declares its message dispatch table as a tuple of typed Handler entries on the class attribute HANDLERS. Like COMMANDS, WORKERS, and CHANNELS, it is declared once, validated at class definition time by the base Compartment, and dispatched uniformly by the base handle(inbound).

class fleetmesh_node.compartment.handler.Handler[source]

Bases: object

One inbound wire protocol message handler.

kind: str
run: str
schema: Any | None = None
doc: str = ''
exact: bool = False
reads: tuple[str, ...] = ()
writes: tuple[str, ...] = ()
__init__(kind, run, *, schema=None, doc='', exact=False, reads=(), writes=())[source]
Parameters:
Return type:

None

matches(msg_type, piuris=())[source]

Check if this handler matches the given message type URI.

Parameters:
Return type:

bool

problems(cls)[source]

Validate this Handler against the declaring compartment class.

Parameters:

cls (type)

Return type:

list[str]

execute(instance, inbound, *args, **kw)[source]

Dispatch an inbound message to this handler on the compartment instance.

Parameters:
Return type:

Any

9.12. Schema Validation

SCHEMA: what a compartment persists in a relational database, declared where it is.

A compartment declares its database schema as a tuple of typed entries - Table and Index - on the class attribute SCHEMA. Like COMMANDS, WORKERS, and CHANNELS, it is declared once, validated at class definition time by the base Compartment, and instantiated into a database adapter module (sqlite, psql, etc.) when the compartment is initialized.

class fleetmesh_node.compartment.schema.Column[source]

Bases: object

One typed column of a database table.

name: str
type: str
nullable: bool = True
primary_key: bool = False
default: Any = None
unique: bool = False
__init__(name, type, *, nullable=True, not_null=False, primary_key=False, default=None, unique=False)[source]
Parameters:
Return type:

None

to_sql(dialect='sqlite')[source]

Render column specification in DDL.

Parameters:

dialect (str)

Return type:

str

problems(table_name='')[source]
Parameters:

table_name (str)

Return type:

list[str]

class fleetmesh_node.compartment.schema.Index[source]

Bases: object

An index over one or more columns in a table.

name: str
columns: tuple[str, ...]
table: str = ''
unique: bool = False
__init__(name, columns, *, table='', unique=False)[source]
Parameters:
Return type:

None

bind_table(table)[source]

Return a copy of this index bound to a table name if not set.

Parameters:

table (str)

Return type:

Index

to_sql(dialect='sqlite')[source]

Render CREATE INDEX statement.

Parameters:

dialect (str)

Return type:

str

problems(table=None)[source]
Parameters:

table (Table | None)

Return type:

list[str]

class fleetmesh_node.compartment.schema.Table[source]

Bases: object

A database table with typed columns, primary key, and optional indices.

name: str
columns: tuple[Column, ...]
primary_key: tuple[str, ...] = ()
indices: tuple[Index, ...] = ()
without_rowid: bool = False
__init__(name, columns, *, primary_key=(), indices=(), without_rowid=False)[source]
Parameters:
Return type:

None

column_names()[source]
Return type:

tuple[str, …]

pk_names()[source]
Return type:

tuple[str, …]

column(name)[source]
Parameters:

name (str)

Return type:

Column | None

to_sql(dialect='sqlite')[source]

Render CREATE TABLE statement.

Parameters:

dialect (str)

Return type:

str

secondary_sql(dialect='sqlite')[source]

Render all attached indices as DDL statements.

Parameters:

dialect (str)

Return type:

list[str]

problems()[source]
Return type:

list[str]

class fleetmesh_node.compartment.schema.Migration[source]

Bases: object

A versioned database migration.

version: int
up: tuple[str, ...]
down: tuple[str, ...] | None = None
name: str = ''
__init__(version, up, *, down=None, name='')[source]
Parameters:
Return type:

None

to_tuple()[source]

Convert to (version, sql) pair for BaseStore compatibility.

Return type:

tuple[int, str]

problems()[source]
Return type:

list[str]