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:
TypedDictOne EVERY job as report() gives it. seconds and next_run are None for a job that is off (Every.is_off).
- fleetmesh_node.compartment.base.wall()[source]
The wall clock in whole seconds: every compartment’s default clock.
- Return type:
- class fleetmesh_node.compartment.base.CompartmentProtocol[source]
Bases:
ProtocolThe 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 commands: Mapping[str, CommandSpec]
- __init__(*args, **kwargs)
- class fleetmesh_node.compartment.base.Compartment[source]
Bases:
objectOne 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.
- commands: Mapping[str, CommandSpec] = {}
- LIFECYCLE: Lifecycle = Lifecycle(breaker=Breaker(failures=5, window=300, backoff=(30, 600)), restart=False, snapshot=0)
- 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.
- classmethod store_refs()[source]
(command, compartment, store) for every store of ANOTHER compartment this one’s commands read.
- 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.
- 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.
- 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:
- 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:
registry (Registry)
ctx (Any)
- Return type:
None
- state()[source]
What this compartment is, as plain data. Never raises. A compartment with a shape worth naming returns its TypedDict.
- trouble_with(message, *, code='fault', severity='trouble', since=None, hint=None, **metadata)[source]
Create a typed Trouble instance associated with this compartment.
- 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.
- note_with(message, *, topic='general', level='info', since=None, **metadata)[source]
Create a typed Note instance associated with this compartment.
- 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.
- 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).
- 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.
- 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.
- 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.
- 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).
- handle(inbound, *args, **kw)[source]
Answer an inbound wire protocol message according to HANDLERS declarations.
- 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.
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:
objectThe 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.
- 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.
- 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.
- 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:
- 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.
- 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.
- 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.
- 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.
- get(name)[source]
- Parameters:
name (str)
- Return type:
CompartmentProtocol | None
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.Breaker[source]
Bases:
objectWhen 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.
- class fleetmesh_node.compartment.lifecycle.Lifecycle[source]
Bases:
objectHow 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.
- class fleetmesh_node.compartment.lifecycle.LifecycleDecl[source]
Bases:
TypedDict- breaker: BreakerDecl
- class fleetmesh_node.compartment.lifecycle.LifecycleRecord[source]
Bases:
TypedDictOne compartment’s lifecycle as meshnode lifecycle and health read it.
- declared: LifecycleDecl
- class fleetmesh_node.compartment.lifecycle.SnapshotFile[source]
Bases:
TypedDict- compartments: dict[str, SnapshotEntry]
- class fleetmesh_node.compartment.lifecycle.Tracker[source]
Bases:
objectOne 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.
- move(to, at, why='')[source]
Go to to. Returns the transition, or None when already there.
- Parameters:
- Return type:
Transition | None
- 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
- class fleetmesh_node.compartment.lifecycle.Transition[source]
Bases:
NamedTupleTransition(compartment, was, now, at, why)
- fleetmesh_node.compartment.lifecycle.channel_for(t)[source]
Which declared channel a transition is said on.
- Parameters:
t (Transition)
- Return type:
- 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.
- 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.
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:
NamedTupleThe four durable stores a node keeps, as one argument.
- 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:
objectExplicit, 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.
- cfg: NodeConfigDict
- events: NodeEventBus
- stores: NodeStores
- descriptor()
- Return type:
NostrEvent | None
- public_descriptor()
- Return type:
NostrEvent | None
- persist_cfg()
- redescribe()
- regrant(**kw)
- propose(**kw)
- pull(**kw)
- amend(**kw)
- wire_request(**kw)
- build_descriptor()
- 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.
- 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
- 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.
- classmethod build(directory, ks, cfg, clock, events, stores, relays, transport=None, router=None, **more)[source]
- Parameters:
- Return type:
- __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:
dir (str)
ks (Any)
cfg (NodeConfigDict)
events (NodeEventBus)
stores (NodeStores)
transport (Any | None)
router (Any | None)
face (Any | None)
host (Any | None)
peers (Any | None)
policy (Any | None)
ledger (Any | None)
timeout (float)
stop (Event)
descriptor (Callable[[], NostrEvent | None])
public_descriptor (Callable[[], NostrEvent | None])
digest (str | None)
node (Any | None)
says (Any | None)
persist_cfg (Callable[[], None])
- Return type:
None
9.5. Dependency Needs
Declared dependencies a compartment takes from the node.
- class fleetmesh_node.compartment.need.Need[source]
Bases:
objectOne 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().
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:
NamedTupleRefusal(at, kind, subject, why, detail)
- class fleetmesh_node.compartment.refusals.RefusalsStateReport[source]
Bases:
TypedDict- recent: list[RefusalRecentSummary]
- class fleetmesh_node.compartment.refusals.Refusals[source]
Bases:
objectEvery ‘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.
- 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.
- fleetmesh_node.compartment.refusals.why_detail(e)[source]
- Parameters:
e (BaseException)
- Return type:
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:
TypedDictConcrete dictionary structure for a declaration problem.
- class fleetmesh_node.compartment.problem.Problem[source]
Bases:
strA 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.
- class fleetmesh_node.compartment.problem.DuplicateProblem[source]
Bases:
ProblemAn item was declared twice on the same surface.
- class fleetmesh_node.compartment.problem.InvalidIdentifierProblem[source]
Bases:
ProblemAn identifier name does not follow the required naming pattern.
- class fleetmesh_node.compartment.problem.ReferenceProblem[source]
Bases:
ProblemA declaration references an entity that is unknown or missing.
- class fleetmesh_node.compartment.problem.TypeMismatchProblem[source]
Bases:
ProblemA declaration entry has the wrong type or does not implement the expected class.
- class fleetmesh_node.compartment.problem.ShadowingProblem[source]
Bases:
ProblemA declared key would shadow a method or class attribute.
- class fleetmesh_node.compartment.problem.IncompatibleProblem[source]
Bases:
ProblemTwo declarations or declarations and method implementations are incompatible.
- class fleetmesh_node.compartment.problem.Problems[source]
-
A list of Problem instances providing query methods and surface filtering.
- class fleetmesh_node.compartment.problem.TroubleDict[source]
Bases:
TypedDictConcrete dictionary structure for runtime trouble.
- class fleetmesh_node.compartment.problem.Trouble[source]
Bases:
strWhat 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.
- static __new__(cls, message, *, code='fault', compartment='', severity='trouble', since=None, hint=None, **metadata)[source]
- class fleetmesh_node.compartment.problem.TroubleList[source]
-
A list of Trouble items offering filtering and serialization.
- class fleetmesh_node.compartment.problem.NoteDict[source]
Bases:
TypedDictConcrete dictionary structure for runtime notes.
- class fleetmesh_node.compartment.problem.Note[source]
Bases:
strWhat 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.
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:
_ContainerA fixed set of named integers - the fields of the store’s TypedDict.
- class fleetmesh_node.compartment.stores.Holdings[source]
Bases:
objectOne compartment’s containers, built from its STORES. Owned by the base.
- class fleetmesh_node.compartment.stores.Members[source]
Bases:
_Container,Generic[K]A bounded set. Evicts in the order members were added (or touched, LRU).
- add(member)[source]
Add one. False - and counted - when a REFUSE set is full.
- Parameters:
member (K)
- Return type:
- class fleetmesh_node.compartment.stores.Ring[source]
Bases:
_Container,Generic[V]A log: newest last, the oldest dropped at the bound.
- 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:
- class fleetmesh_node.compartment.stores.Store[source]
Bases:
objectOne collection a compartment keeps. See the module docstring.
- __init__(key, description, kind, shape=None, bound=0, evict='oldest', keyed_by='', persist='memory', sensitive=False, tags=())
- exception fleetmesh_node.compartment.stores.StoreFull[source]
Bases:
ExceptionA REFUSE store at its bound was asked to take a new entry.
- class fleetmesh_node.compartment.stores.StoreLive[source]
Bases:
TypedDictWhat a store is holding now, for a compartment’s report.
- class fleetmesh_node.compartment.stores.StoreRecord[source]
Bases:
TypedDictA store as the census, meshnode subsystems and the docs read it.
- 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.
- put(key, value)[source]
Write one entry. False - and counted - when a REFUSE store is full.
- Parameters:
key (K)
value (V)
- Return type:
- fleetmesh_node.compartment.stores.declared(obj)[source]
The stores a compartment declares, or () for one not yet converted.
- 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:
- Return type:
- 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.
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:
CompartmentThe 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).
- LIFECYCLE: Lifecycle = Lifecycle(breaker=Breaker(failures=5, window=300, backoff=(30, 600)), restart=True, snapshot=0)
- 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.
- 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.
- class fleetmesh_node.compartment.sidecar.LinkRecord[source]
Bases:
TypedDict- sidecar: SidecarRecord
- class fleetmesh_node.compartment.sidecar.ProbeRecord[source]
Bases:
TypedDictWhat <name>.probe answers: the link, and the status or the error.
- class fleetmesh_node.compartment.sidecar.Sidecar[source]
Bases:
objectWhat 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.
- 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.
- exception fleetmesh_node.compartment.sidecar.SidecarError[source]
Bases:
ExceptionNo sidecar, a sidecar that will not answer, or one that says no.
- exception fleetmesh_node.compartment.sidecar.SidecarIncompatible[source]
Bases:
SidecarErrorA sidecar that answered in a protocol this bridge does not speak.
- fleetmesh_node.compartment.sidecar.bridges(compartments)[source]
The bridges among a node’s compartments: every sidecar it reaches.
- 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.
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:
objectAn 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.
- class fleetmesh_node.compartment.wire.WireClient[source]
Bases:
objectThe client adapter bound to self.wire on a WireProtocol compartment.
- __init__(protocol)[source]
- Parameters:
protocol (WireProtocol)
- Return type:
None
- send(to_pubkey, message, *, anonymous=False, stored=False)[source]
Dispatch one message to to_pubkey over the transport ladder.
- class fleetmesh_node.compartment.wire.WireProtocol[source]
Bases:
CompartmentA compartment that speaks one or more DIDComm wire protocols (PIURIs).
- 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.
9.10. Background Workers
WORKERS: background worker threads declared on a compartment.
- class fleetmesh_node.compartment.worker.Worker[source]
Bases:
objectA 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().
- when
Optional condition to run: attribute name (checked for truthiness) or callable receiving the compartment instance.
9.11. Periodic Handlers
EVERY: periodic work declared on a compartment.
- class fleetmesh_node.compartment.every.Every[source]
Bases:
objectA 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”.
- 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
- 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.
- 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.
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:
objectOne inbound wire protocol message handler.
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:
objectOne typed column of a database table.
- __init__(name, type, *, nullable=True, not_null=False, primary_key=False, default=None, unique=False)[source]
- class fleetmesh_node.compartment.schema.Index[source]
Bases:
objectAn index over one or more columns in a table.
- class fleetmesh_node.compartment.schema.Table[source]
Bases:
objectA database table with typed columns, primary key, and optional indices.