summaryrefslogtreecommitdiff
path: root/modules/swarm/c++
diff options
context:
space:
mode:
Diffstat (limited to 'modules/swarm/c++')
-rw-r--r--modules/swarm/c++/SConscript27
-rw-r--r--modules/swarm/c++/capability.hpp199
-rw-r--r--modules/swarm/c++/capacity.hpp236
-rw-r--r--modules/swarm/c++/interpret.hpp113
-rw-r--r--modules/swarm/c++/message.hpp140
-rw-r--r--modules/swarm/c++/probe_search.hpp198
-rw-r--r--modules/swarm/c++/registry.hpp427
-rw-r--r--modules/swarm/c++/run.hpp193
-rw-r--r--modules/swarm/c++/signal.hpp52
-rw-r--r--modules/swarm/c++/swarm.hpp11
-rw-r--r--modules/swarm/c++/wire.hpp119
11 files changed, 1715 insertions, 0 deletions
diff --git a/modules/swarm/c++/SConscript b/modules/swarm/c++/SConscript
new file mode 100644
index 0000000..4071add
--- /dev/null
+++ b/modules/swarm/c++/SConscript
@@ -0,0 +1,27 @@
+#!/bin/false
+
+import os
+import os.path
+import glob
+
+
+Import('env')
+
+dir_path = Dir('.').abspath
+
+swarm_env = env.Clone();
+
+swarm_env.sources = sorted(glob.glob(dir_path + "/*.cpp"));
+swarm_env.headers = sorted(glob.glob(dir_path + "/*.hpp"));
+
+env.sources += swarm_env.sources;
+env.headers += swarm_env.headers;
+
+# Header only, like core. The StaticLibrary exists so dependents have something
+# to name; it is built from zero translation units.
+objects = []
+swarm_env.add_source_files(objects, swarm_env.sources, shared=False);
+env.library_static = swarm_env.StaticLibrary('#build/kel-lbm-swarm', [objects]);
+
+env.Install('$prefix/lib/', env.library_static);
+env.Install('$prefix/include/kel/lbm/swarm/', swarm_env.headers);
diff --git a/modules/swarm/c++/capability.hpp b/modules/swarm/c++/capability.hpp
new file mode 100644
index 0000000..8497969
--- /dev/null
+++ b/modules/swarm/c++/capability.hpp
@@ -0,0 +1,199 @@
+#pragma once
+
+#include <kel/lbm/abstract/schema.hpp>
+
+/**
+ * What a worker tells the orchestrator about itself.
+ *
+ * The envelope is deliberately backend agnostic: common fields, then one
+ * section named by "kind". Browsers running WebGL2 and native processes are
+ * both first class worker kinds, and the swarm is meant to take WebGPU runners
+ * later; a string tag survives version skew where a positional format does not.
+ *
+ * A worker of another kind carries its own section instead. Nothing has to
+ * carry a section it has no business describing, because each kind gets its own
+ * full capability type -- see CapabilityOf below and the hello variants in
+ * message.hpp.
+ */
+namespace kel {
+namespace lbm {
+namespace sch {
+
+/**
+ * Queryable WebGL2 limits, straight from glGetIntegerv.
+ *
+ * Worth knowing which of these actually bind. max_draw_buffers and
+ * max_color_attachments are guaranteed to be only 4, and since a D2Q9 lattice
+ * needs ceil(9/4) = 3 render targets they are the limits that decide whether a
+ * descriptor fits in a single pass at all. The rest are either generous in
+ * practice or bound by memory long before they bind by count.
+ */
+using GlLimits = Struct<
+ Member<UInt32, "max_texture_size">,
+ Member<UInt32, "max_3d_texture_size">,
+ Member<UInt32, "max_array_texture_layers">,
+ Member<UInt32, "max_draw_buffers">,
+ Member<UInt32, "max_color_attachments">,
+ Member<UInt32, "max_texture_image_units">,
+ Member<UInt32, "max_combined_texture_image_units">,
+ Member<UInt32, "max_renderbuffer_size">,
+ Member<UInt32, "max_fragment_uniform_vectors">,
+ Member<FixedArray<UInt32, 2u>, "max_viewport_dims">
+>;
+
+/**
+ * Extension and context properties.
+ *
+ * color_buffer_float is a hard gate: without EXT_color_buffer_float a float
+ * texture is not color renderable and there is no f32 solver on this device at
+ * all. The others are reported so the orchestrator can decide, not so the
+ * worker can.
+ */
+using GlFeatures = Struct<
+ Member<Bool, "webgl2">,
+ Member<Bool, "offscreen_canvas">,
+ Member<Bool, "color_buffer_float">,
+ Member<Bool, "color_buffer_half_float">,
+ Member<Bool, "texture_float_linear">,
+ Member<Bool, "float_blend">,
+ Member<Bool, "parallel_shader_compile">,
+ Member<Bool, "disjoint_timer_query">
+>;
+
+/**
+ * What the worker measured, as opposed to what it was told.
+ *
+ * There is no queryable "available VRAM" in WebGL2 -- navigator.deviceMemory is
+ * system RAM and unrelated -- and max_texture_size overstates capacity by
+ * roughly a hundredfold on a typical desktop. So these come from an actual
+ * allocation trial.
+ *
+ * probed_bytes_max is the largest allocation that survived; probed_bytes_safe
+ * applies safety_factor to leave room for the canvas, the compositor and other
+ * tabs. Both are reported so the orchestrator can apply its own policy rather
+ * than inheriting the worker's.
+ *
+ * probe_hit_texture_size_bound distinguishes "ran out of memory" from "ran into
+ * max_texture_size", which are very different signals about a device.
+ */
+using GlBudget = Struct<
+ Member<UInt64, "probed_bytes_max">,
+ Member<UInt64, "probed_bytes_safe">,
+ Member<UInt32, "probe_trials">,
+ Member<Bool, "context_lost_during_probe">,
+ Member<Bool, "probe_hit_texture_size_bound">,
+ Member<Float32, "safety_factor">
+>;
+
+/**
+ * One feasible way to lay a lattice out in textures on this device.
+ *
+ * This type has three jobs and keeping it as one type is what stops them
+ * drifting: it is an element of the capability report, it is the assignment
+ * message the orchestrator sends back, and it is the input to the shader
+ * preamble generator.
+ *
+ * The slot tables are the indirection that makes pixel stuffing expressible --
+ * slot_tex_of_q[i] / slot_cmp_of_q[i] say which texture and which channel
+ * direction i lives in, and the aux tables do the same for the non
+ * distribution fields packed into otherwise idle slots.
+ */
+using PackingPlan = Struct<
+ Member<String, "layout">,
+ Member<String, "aux_mode">,
+ Member<UInt8, "d">,
+ Member<UInt8, "q">,
+ Member<UInt8, "ghost">,
+ Member<UInt8, "storage_bits">,
+ Member<UInt8, "slots_per_texel">,
+ Member<UInt8, "textures_df">,
+ Member<UInt8, "textures_aux">,
+ Member<UInt8, "states">,
+ Member<UInt8, "passes">,
+ Member<UInt8, "idle_slots">,
+ Member<FixedArray<UInt32, 3u>, "domain">,
+ Member<FixedArray<UInt32, 2u>, "tiles">,
+ Member<Bool, "tiles_pow2">,
+ Member<FixedArray<UInt32, 2u>, "texture_size">,
+ Member<UInt64, "bytes_total">,
+ Member<UInt64, "bytes_useful">,
+ Member<Array<UInt8, 1u>, "slot_tex_of_q">,
+ Member<Array<UInt8, 1u>, "slot_cmp_of_q">,
+ Member<Array<UInt8, 1u>, "slot_tex_of_aux">,
+ Member<Array<UInt8, 1u>, "slot_cmp_of_aux">,
+ Member<Array<String, 1u>, "aux_names">
+>;
+
+using WebGl2Capability = Struct<
+ Member<GlLimits, "limits">,
+ Member<GlFeatures, "features">,
+ Member<GlBudget, "budget">,
+ Member<Array<PackingPlan, 1u>, "feasible">
+>;
+
+/**
+ * A worker that is a process rather than a browser tab.
+ *
+ * Native workers are not only a test fixture -- they are a worker kind in their
+ * own right, and the orchestrator should be able to hand them real work. What
+ * they report is correspondingly different: there is no texture budget to probe
+ * because there are no textures, so the interesting numbers are threads and
+ * addressable memory.
+ */
+using NativeCapability = Struct<
+ Member<UInt32, "threads">,
+ Member<UInt64, "memory_bytes">,
+ Member<String, "cpu">,
+ Member<Bool, "has_sycl">
+>;
+
+/**
+ * The part every worker reports, whatever it is.
+ *
+ * This is deliberately the *whole* type rather than a prefix of a larger one.
+ * Decoding runs strict, so a struct naming every backend section would oblige a
+ * browser to describe a CPU and a native process to describe a texture budget.
+ * Instead the common part stands alone and is enough to route on: decode this,
+ * read "kind", then decode again as the matching full type below. The backend
+ * section is skipped on the first pass because unknown keys always are.
+ */
+using WorkerCapability = Struct<
+ Member<String, "worker_id">,
+ Member<String, "kind">,
+ Member<String, "schema_version">,
+ Member<UInt64, "reported_at_ms">,
+ Member<String, "user_agent">
+>;
+
+/**
+ * The common part plus exactly one backend section. One alias per kind, so
+ * adding a kind never widens what the existing ones have to fill in.
+ */
+template <typename Section, string_literal Key>
+using CapabilityOf = Struct<
+ Member<String, "worker_id">,
+ Member<String, "kind">,
+ Member<String, "schema_version">,
+ Member<UInt64, "reported_at_ms">,
+ Member<String, "user_agent">,
+ Member<Section, Key>
+>;
+
+using WebGl2WorkerCapability = CapabilityOf<WebGl2Capability, "webgl2">;
+using NativeWorkerCapability = CapabilityOf<NativeCapability, "native">;
+
+/**
+ * The small, frequently resent part: enough to monitor a worker without
+ * re-sending its capability. Rides along on pong so a heartbeat doubles as a
+ * status update.
+ */
+using WorkerLive = Struct<
+ Member<String, "state">,
+ Member<UInt64, "uptime_ms">,
+ Member<UInt64, "steps_done">,
+ Member<String, "last_error">
+>;
+
+} // namespace sch
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/capacity.hpp b/modules/swarm/c++/capacity.hpp
new file mode 100644
index 0000000..4073405
--- /dev/null
+++ b/modules/swarm/c++/capacity.hpp
@@ -0,0 +1,236 @@
+#pragma once
+
+#include <cstdint>
+
+/**
+ * How much lattice fits on a worker.
+ *
+ * This is pure arithmetic over a descriptor's Q and a device's reported limits,
+ * with no GL and no schema, which is the point: the orchestrator needs it to
+ * size assignments, the worker needs it to drive its allocation trial, and
+ * neither reason is a good one to make it untestable without a browser.
+ *
+ * Everything is constexpr so the ceilings can be asserted at compile time
+ * against a descriptor rather than discovered on a device that happens to be
+ * minimum spec.
+ */
+namespace kel {
+namespace lbm {
+namespace swarm {
+
+/**
+ * A WebGL2 implementation is only *guaranteed* these. Real desktop values are
+ * far higher, but a plan that relies on more than this is a plan that works on
+ * the developer's machine.
+ */
+struct webgl2_guaranteed {
+ static constexpr uint32_t max_texture_size = 2048u;
+ static constexpr uint32_t max_3d_texture_size = 256u;
+ static constexpr uint32_t max_array_texture_layers = 256u;
+ static constexpr uint32_t max_draw_buffers = 4u;
+ static constexpr uint32_t max_color_attachments = 4u;
+ static constexpr uint32_t max_texture_image_units = 16u;
+};
+
+/**
+ * Packing a Q-direction lattice into RGBA textures.
+ *
+ * One texel holds four scalars, so a descriptor needs ceil(Q/4) textures and
+ * wastes whatever is left over. The leftovers are not merely waste: the aux
+ * fields (the per cell info flag, later the particle fields) can be stuffed
+ * into them, which is why idle_slots is reported rather than just computed.
+ */
+struct packing_math {
+ static constexpr uint64_t slots_per_texel = 4u;
+
+ static constexpr uint64_t planes(uint64_t q){
+ return (q + slots_per_texel - 1u) / slots_per_texel;
+ }
+
+ static constexpr uint64_t idle_slots(uint64_t q){
+ return planes(q) * slots_per_texel - q;
+ }
+
+ /**
+ * Aux planes needed once the idle slots have been used. Stuffing only
+ * works when the leftovers are big enough; D2Q9 has three idle slots, so
+ * a single info flag fits but the four fields a PSM run wants do not.
+ */
+ static constexpr uint64_t aux_planes(uint64_t q, uint64_t aux_scalars,
+ bool stuffed){
+ if(stuffed and aux_scalars <= idle_slots(q)){
+ return 0u;
+ }
+ return (aux_scalars + slots_per_texel - 1u) / slots_per_texel;
+ }
+
+ static constexpr uint64_t bytes_per_texel(uint64_t storage_bits){
+ return slots_per_texel * storage_bits / 8u;
+ }
+
+ /**
+ * Distributions are double buffered for the ping pong; aux fields are not,
+ * since nothing writes them during a step.
+ */
+ static constexpr uint64_t bytes_per_cell(uint64_t q, uint64_t states,
+ uint64_t aux_scalars, bool stuffed,
+ uint64_t storage_bits = 32u){
+ const uint64_t tex = states * planes(q) + aux_planes(q, aux_scalars, stuffed);
+ return tex * bytes_per_texel(storage_bits);
+ }
+
+ /**
+ * Render targets needed per pass, against what the device allows.
+ *
+ * This is the limit that actually decides whether a descriptor is usable.
+ * Collision couples every direction, so a multi-pass split has to re-read
+ * all planes and recompute rho and u in each pass -- roughly double the
+ * arithmetic for the same bandwidth. Worth detecting rather than
+ * stumbling into.
+ */
+ static constexpr uint64_t passes(uint64_t q, uint64_t mrt){
+ if(mrt == 0u){
+ return 0u;
+ }
+ return (planes(q) + mrt - 1u) / mrt;
+ }
+
+ static constexpr bool fits_single_pass(uint64_t q, uint64_t mrt){
+ return passes(q, mrt) == 1u;
+ }
+};
+
+/**
+ * Integer square root by bisection.
+ *
+ * std::sqrt is not constexpr before C++26 and this has to run at compile time
+ * for the ceiling assertions. Exactness also matters more than speed here: a
+ * domain edge that rounds up by one costs a whole row of cells against a
+ * budget that was measured, not guessed.
+ */
+constexpr uint64_t isqrt(uint64_t value){
+ if(value < 2u){
+ return value;
+ }
+
+ uint64_t low = 1u;
+ uint64_t high = (value / 2u) + 1u;
+
+ while(low < high){
+ const uint64_t mid = low + (high - low + 1u) / 2u;
+ if(mid <= value / mid){
+ low = mid;
+ } else {
+ high = mid - 1u;
+ }
+ }
+
+ return low;
+}
+
+/**
+ * A 2D domain and what it costs.
+ */
+struct domain_2d {
+ uint64_t nx;
+ uint64_t ny;
+
+ constexpr uint64_t cells() const { return nx * ny; }
+};
+
+struct capacity_math {
+ /**
+ * Cells the texture dimension allows, independent of memory.
+ *
+ * On a typical desktop this is around a hundred times looser than what
+ * memory actually permits, which is exactly why the worker measures
+ * instead of trusting it -- but it is still a hard ceiling and a worker
+ * that hits *this* one is telling you something different about itself
+ * than a worker that ran out of memory.
+ */
+ static constexpr uint64_t texture_bound_cells_2d(uint64_t max_texture_size,
+ uint64_t ghost){
+ const uint64_t pad = 2u * ghost;
+ if(max_texture_size <= pad){
+ return 0u;
+ }
+ const uint64_t edge = max_texture_size - pad;
+ return edge * edge;
+ }
+
+ static constexpr uint64_t cells_from_bytes(uint64_t bytes,
+ uint64_t bytes_per_cell){
+ if(bytes_per_cell == 0u){
+ return 0u;
+ }
+ return bytes / bytes_per_cell;
+ }
+
+ static constexpr uint64_t max_cells_2d(uint64_t budget_bytes,
+ uint64_t bytes_per_cell,
+ uint64_t max_texture_size,
+ uint64_t ghost){
+ const uint64_t by_memory = cells_from_bytes(budget_bytes, bytes_per_cell);
+ const uint64_t by_texture = texture_bound_cells_2d(max_texture_size, ghost);
+ return (by_memory < by_texture) ? by_memory : by_texture;
+ }
+
+ /**
+ * Largest domain of a given aspect ratio that fits in a cell count.
+ *
+ * Aspect arrives as a ratio of integers rather than a float so the result
+ * is reproducible across the orchestrator and the worker; they must agree
+ * exactly or an assignment will not fit the allocation the worker made.
+ *
+ * Rounds down on both axes, and clamps each edge to what the texture
+ * dimension allows, so the answer is always feasible rather than merely
+ * close.
+ */
+ static constexpr domain_2d fit_domain_2d(uint64_t cells,
+ uint64_t aspect_num,
+ uint64_t aspect_den,
+ uint64_t max_texture_size,
+ uint64_t ghost){
+ if(cells == 0u or aspect_num == 0u or aspect_den == 0u){
+ return domain_2d{0u, 0u};
+ }
+
+ // ny = sqrt(cells * den / num), nx = ny * num / den
+ uint64_t ny = isqrt((cells * aspect_den) / aspect_num);
+ if(ny == 0u){
+ ny = 1u;
+ }
+ uint64_t nx = (ny * aspect_num) / aspect_den;
+ if(nx == 0u){
+ nx = 1u;
+ }
+
+ const uint64_t pad = 2u * ghost;
+ const uint64_t edge = (max_texture_size > pad) ? (max_texture_size - pad) : 0u;
+ if(edge == 0u){
+ return domain_2d{0u, 0u};
+ }
+ if(nx > edge){
+ nx = edge;
+ }
+ if(ny > edge){
+ ny = edge;
+ }
+
+ // Rounding up through the aspect ratio can overshoot the budget by a
+ // row; give the row back rather than hand out a domain that does not
+ // fit the measurement.
+ while(nx * ny > cells and ny > 1u){
+ --ny;
+ }
+ while(nx * ny > cells and nx > 1u){
+ --nx;
+ }
+
+ return domain_2d{nx, ny};
+ }
+};
+
+} // namespace swarm
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/interpret.hpp b/modules/swarm/c++/interpret.hpp
new file mode 100644
index 0000000..1b2dcfa
--- /dev/null
+++ b/modules/swarm/c++/interpret.hpp
@@ -0,0 +1,113 @@
+#pragma once
+
+#include "capability.hpp"
+#include "capacity.hpp"
+
+#include <kel/lbm/abstract/data.hpp>
+
+#include <cstdint>
+#include <iomanip>
+#include <sstream>
+#include <string>
+
+/**
+ * Turning a reported capability into the one number the orchestrator needs:
+ * how much lattice this worker can hold.
+ *
+ * Quoted in D2Q9 cells so worker kinds are directly comparable. A browser's
+ * figure comes from its measured texture budget; a native worker's from
+ * addressable memory. Neither is a promise -- both ignore everything else
+ * happening on the machine -- but a planning figure that means the same thing
+ * across kinds is what makes a heterogeneous registry useful rather than
+ * decorative.
+ *
+ * Here rather than in the orchestrator because it is pure and therefore worth
+ * testing, and because the browser worker may eventually want to reason about
+ * its own capacity the same way the orchestrator does.
+ */
+namespace kel {
+namespace lbm {
+namespace swarm {
+
+/**
+ * The reference packing every capacity figure is quoted in: D2Q9, double
+ * buffered, the info flag stuffed into an idle slot. 96 bytes per cell.
+ */
+constexpr uint64_t reference_bytes_per_cell(){
+ return packing_math::bytes_per_cell(9u, 2u, 1u, true);
+}
+
+namespace impl {
+
+inline std::string human_bytes(uint64_t bytes){
+ std::ostringstream oss;
+ oss << std::fixed << std::setprecision(1);
+
+ if(bytes >= (1ull << 30)){
+ oss << (static_cast<double>(bytes) / static_cast<double>(1ull << 30))
+ << " GiB";
+ } else if(bytes >= (1ull << 20)){
+ oss << (static_cast<double>(bytes) / static_cast<double>(1ull << 20))
+ << " MiB";
+ } else {
+ oss << bytes << " B";
+ }
+
+ return oss.str();
+}
+
+} // namespace impl
+
+inline uint64_t webgl2_capacity_cells(const data<sch::WebGl2Capability> &cap){
+ const uint64_t budget = cap.get<"budget">().get<"probed_bytes_safe">().get();
+ const uint64_t max_tex = cap.get<"limits">().get<"max_texture_size">().get();
+
+ // Both bounds, tighter wins -- a worker can be limited by either, and
+ // which one it is says something different about the device.
+ return capacity_math::max_cells_2d(budget, reference_bytes_per_cell(),
+ max_tex, 0u);
+}
+
+inline uint64_t native_capacity_cells(const data<sch::NativeCapability> &cap){
+ const uint64_t memory = cap.get<"memory_bytes">().get();
+
+ // No texture dimension to bind against, so memory is the only limit. Take
+ // a quarter of it: the rest of the machine exists.
+ return capacity_math::cells_from_bytes(memory / 4u,
+ reference_bytes_per_cell());
+}
+
+inline std::string webgl2_summary(const data<sch::WebGl2Capability> &cap){
+ std::ostringstream oss;
+
+ oss << "tex " << cap.get<"limits">().get<"max_texture_size">().get()
+ << ", mrt " << cap.get<"limits">().get<"max_draw_buffers">().get()
+ << ", budget " << impl::human_bytes(
+ cap.get<"budget">().get<"probed_bytes_safe">().get());
+
+ if(not cap.get<"features">().get<"color_buffer_float">().get()){
+ // Without this there is no float render target and so no solver at
+ // all. Worth shouting about rather than leaving to be inferred.
+ oss << " [NO FLOAT RENDER]";
+ }
+
+ return oss.str();
+}
+
+inline std::string native_summary(const data<sch::NativeCapability> &cap){
+ std::ostringstream oss;
+
+ oss << cap.get<"threads">().get() << " threads, "
+ << impl::human_bytes(cap.get<"memory_bytes">().get())
+ << ", " << cap.get<"cpu">().stl_string();
+
+ if(cap.get<"has_sycl">().get()){
+ oss << ", sycl";
+ }
+
+ return oss.str();
+}
+
+} // namespace swarm
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/message.hpp b/modules/swarm/c++/message.hpp
new file mode 100644
index 0000000..aba5a9c
--- /dev/null
+++ b/modules/swarm/c++/message.hpp
@@ -0,0 +1,140 @@
+#pragma once
+
+#include "capability.hpp"
+
+#include <string_view>
+
+/**
+ * The worker/orchestrator control protocol.
+ *
+ * Every message is a JSON object carrying the same three leading members --
+ * "type", "worker_id", "seq" -- followed by whatever that type adds. Decoding
+ * happens in two stages (see wire.hpp): read MsgHeader to learn the type, then
+ * decode the full typed struct.
+ *
+ * The reason the protocol is shaped this way rather than as a tagged union is
+ * that sch::Union has no JSON codec. It turns out not to matter: the Struct
+ * decoder skips keys it does not recognise, so reading a header out of a full
+ * message is well defined and costs one extra parse of a short string.
+ *
+ * A versioning note that the strictness buys and charges for. Wire codecs run
+ * strict, so a *missing* member is an error while an *unknown* member is
+ * ignored. That means a newer sender talking to an older receiver is fine, but
+ * an older sender talking to a newer receiver fails as soon as the newer side
+ * adds a member. Adding a field to a message is therefore a breaking change in
+ * one direction, which is what schema_version in the hello/welcome exchange is
+ * for -- catch the mismatch deliberately instead of discovering it as a
+ * confusing decode error.
+ */
+namespace kel {
+namespace lbm {
+
+namespace sch {
+
+/**
+ * Prepends the common members so each message type only states what it adds.
+ */
+template <typename... Members>
+using Envelope = Struct<
+ Member<String, "type">,
+ Member<String, "worker_id">,
+ Member<UInt64, "seq">,
+ Members...
+>;
+
+/// Just the common members. Decoded first to learn which type follows.
+using MsgHeader = Envelope<>;
+
+/**
+ * worker -> orchestrator. First message on the channel.
+ *
+ * MsgHello carries only the common capability fields, which is enough to learn
+ * the worker kind. Decode it first, read capability.kind, then decode the same
+ * text again as the matching variant below -- the backend section is skipped on
+ * the first pass because unknown keys always are.
+ *
+ * The alternative, one hello naming every backend section, does not work: wire
+ * codecs run strict, so it would oblige a browser to describe a CPU.
+ */
+using MsgHello = Envelope<Member<WorkerCapability, "capability">>;
+
+using MsgHelloWebGl2 = Envelope<Member<WebGl2WorkerCapability, "capability">>;
+using MsgHelloNative = Envelope<Member<NativeWorkerCapability, "capability">>;
+
+/// orchestrator -> worker. Confirms registration and sets the heartbeat pace.
+using MsgWelcome = Envelope<
+ Member<UInt64, "heartbeat_ms">,
+ Member<String, "schema_version">
+>;
+
+/// orchestrator -> worker.
+using MsgPing = Envelope<Member<UInt64, "sent_at_ms">>;
+
+/**
+ * worker -> orchestrator. Echoes sent_at_ms so round trip time is measured
+ * against the orchestrator's own clock and the two machines never have to agree
+ * on what time it is.
+ */
+using MsgPong = Envelope<
+ Member<UInt64, "sent_at_ms">,
+ Member<UInt64, "worker_now_ms">,
+ Member<WorkerLive, "live">
+>;
+
+/// worker -> orchestrator. Initialised and idle.
+using MsgReady = Envelope<Member<WorkerLive, "live">>;
+
+/// worker -> orchestrator. Unsolicited: a state change or an error.
+using MsgStatus = Envelope<Member<WorkerLive, "live">>;
+
+} // namespace sch
+
+/**
+ * Wire values for the "type" member.
+ *
+ * Deliberately strings rather than an integer enum: the orchestrator and the
+ * worker are built from the same source today but will not always be, and a
+ * string tag misread is a routing failure you can see in a log, where an
+ * integer tag misread is a silently wrong payload.
+ */
+namespace msg {
+inline constexpr std::string_view hello = "hello";
+inline constexpr std::string_view welcome = "welcome";
+inline constexpr std::string_view ping = "ping";
+inline constexpr std::string_view pong = "pong";
+inline constexpr std::string_view ready = "ready";
+inline constexpr std::string_view status = "status";
+
+/// orchestrator -> everyone. A run begins or ends.
+inline constexpr std::string_view run_start = "run_start";
+inline constexpr std::string_view run_end = "run_end";
+} // namespace msg
+
+/**
+ * Values for WorkerLive's "state". The orchestrator owns stale and gone -- a
+ * worker never reports those about itself, they are conclusions drawn from
+ * missed heartbeats.
+ */
+namespace wstate {
+inline constexpr std::string_view registered = "registered";
+inline constexpr std::string_view ready = "ready";
+inline constexpr std::string_view busy = "busy";
+inline constexpr std::string_view error = "error";
+inline constexpr std::string_view stale = "stale";
+inline constexpr std::string_view gone = "gone";
+} // namespace wstate
+
+/**
+ * Bumped whenever a message or capability schema changes shape. Compared on
+ * hello/welcome so a mismatch is reported rather than hit as a decode failure.
+ */
+inline constexpr std::string_view schema_version = "1";
+
+/// Worker kinds, the tag selecting which capability section is populated.
+namespace wkind {
+inline constexpr std::string_view webgl2 = "webgl2";
+inline constexpr std::string_view native = "native";
+} // namespace wkind
+
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/probe_search.hpp b/modules/swarm/c++/probe_search.hpp
new file mode 100644
index 0000000..f678937
--- /dev/null
+++ b/modules/swarm/c++/probe_search.hpp
@@ -0,0 +1,198 @@
+#pragma once
+
+#include <cstdint>
+
+/**
+ * Finding out how much a device will actually give you.
+ *
+ * WebGL2 reports limits but not capacity. MAX_TEXTURE_SIZE on a typical desktop
+ * implies something like 25 GB of lattice, roughly a hundred times what the GPU
+ * will really hand over, and there is no query for the real figure --
+ * navigator.deviceMemory is system RAM and unrelated. So capacity is measured:
+ * try an allocation, see whether it survives, adjust.
+ *
+ * The strategy lives here rather than next to the GL calls because it is
+ * ordinary arithmetic and deserves to be tested as such. The caller owns the
+ * part that cannot be tested without a browser -- actually allocating -- and
+ * feeds the answers back in:
+ *
+ * allocation_search search{cfg};
+ * while(not search.done()){
+ * search.report(try_allocate(search.candidate()));
+ * }
+ * use(search.best_cells());
+ *
+ * Grow by doubling until something fails, then bisect. Doubling finds the right
+ * order of magnitude in a handful of steps even when devices differ by a factor
+ * of a thousand; bisecting then tightens it without the linear crawl a pure
+ * step search would need.
+ */
+namespace kel {
+namespace lbm {
+namespace swarm {
+
+class allocation_search {
+public:
+ struct config {
+ /**
+ * First attempt. Deliberately small: the opening trial should succeed
+ * on anything that can run at all, because a failure here means the
+ * device is unusable rather than merely modest.
+ */
+ uint64_t start_cells = 65536u;
+
+ /**
+ * Hard ceiling from the texture dimension, in cells. Zero means no
+ * ceiling. Reaching it is a different answer from running out of
+ * memory and is reported separately.
+ */
+ uint64_t ceiling_cells = 0u;
+
+ /// Bisection steps once a failure has bracketed the answer. Four gets
+ /// within about a sixteenth of the bracket, which is finer than the
+ /// figure deserves given it is a moving target anyway.
+ uint64_t bisect_steps = 4u;
+
+ /// Backstop so a device that answers inconsistently cannot spin.
+ uint64_t max_trials = 32u;
+ };
+
+ explicit allocation_search(config cfg) : cfg_{cfg} {
+ candidate_ = cfg_.start_cells;
+
+ if(cfg_.ceiling_cells > 0u and candidate_ > cfg_.ceiling_cells){
+ candidate_ = cfg_.ceiling_cells;
+ }
+
+ if(candidate_ == 0u){
+ phase_ = phase::finished;
+ }
+ }
+
+ bool done() const { return phase_ == phase::finished; }
+
+ /// The cell count to attempt next. Meaningless once done().
+ uint64_t candidate() const { return candidate_; }
+
+ /// Largest allocation that survived. Zero means nothing did.
+ uint64_t best_cells() const { return best_; }
+
+ uint64_t trials() const { return trials_; }
+
+ /**
+ * True when the search stopped because the texture dimension ran out
+ * rather than because memory did. Worth distinguishing: one says the
+ * device is small, the other says it is oddly shaped.
+ */
+ bool hit_ceiling() const { return hit_ceiling_; }
+
+ void report(bool ok){
+ if(phase_ == phase::finished){
+ return;
+ }
+
+ ++trials_;
+
+ if(phase_ == phase::grow){
+ report_grow(ok);
+ } else {
+ report_bisect(ok);
+ }
+
+ if(trials_ >= cfg_.max_trials){
+ phase_ = phase::finished;
+ }
+ }
+
+private:
+ enum class phase { grow, bisect, finished };
+
+ void report_grow(bool ok){
+ if(not ok){
+ failed_at_ = candidate_;
+
+ if(best_ == 0u){
+ // Even the opening attempt failed. There is nothing to
+ // bisect between, and the honest answer is zero.
+ phase_ = phase::finished;
+ return;
+ }
+
+ phase_ = phase::bisect;
+ advance_bisect();
+ return;
+ }
+
+ best_ = candidate_;
+
+ if(cfg_.ceiling_cells > 0u and candidate_ >= cfg_.ceiling_cells){
+ // The texture dimension, not memory, is what stopped us.
+ hit_ceiling_ = true;
+ phase_ = phase::finished;
+ return;
+ }
+
+ uint64_t next = candidate_ * 2u;
+ if(next < candidate_){
+ // Overflow. Nothing sane gets here, but silently wrapping to a
+ // tiny candidate would turn a huge device into a small one.
+ phase_ = phase::finished;
+ return;
+ }
+ if(cfg_.ceiling_cells > 0u and next > cfg_.ceiling_cells){
+ next = cfg_.ceiling_cells;
+ }
+ if(next == candidate_){
+ phase_ = phase::finished;
+ return;
+ }
+
+ candidate_ = next;
+ }
+
+ void report_bisect(bool ok){
+ if(ok){
+ best_ = candidate_;
+ } else {
+ failed_at_ = candidate_;
+ }
+ advance_bisect();
+ }
+
+ void advance_bisect(){
+ if(bisects_done_ >= cfg_.bisect_steps){
+ phase_ = phase::finished;
+ return;
+ }
+ if(failed_at_ <= best_ + 1u){
+ // Bracket closed; there is nothing left between them.
+ phase_ = phase::finished;
+ return;
+ }
+
+ const uint64_t mid = best_ + ((failed_at_ - best_) / 2u);
+ if(mid == best_ or mid == failed_at_){
+ phase_ = phase::finished;
+ return;
+ }
+
+ candidate_ = mid;
+ ++bisects_done_;
+ }
+
+ config cfg_;
+
+ phase phase_ = phase::grow;
+ uint64_t candidate_ = 0u;
+ /// Largest known good.
+ uint64_t best_ = 0u;
+ /// Smallest known bad.
+ uint64_t failed_at_ = 0u;
+ uint64_t trials_ = 0u;
+ uint64_t bisects_done_ = 0u;
+ bool hit_ceiling_ = false;
+};
+
+} // namespace swarm
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/registry.hpp b/modules/swarm/c++/registry.hpp
new file mode 100644
index 0000000..6159a72
--- /dev/null
+++ b/modules/swarm/c++/registry.hpp
@@ -0,0 +1,427 @@
+#pragma once
+
+#include "capability.hpp"
+
+#include <kel/lbm/abstract/data.hpp>
+
+#include <cstdint>
+#include <iomanip>
+#include <map>
+#include <mutex>
+#include <optional>
+#include <sstream>
+#include <string>
+#include <vector>
+
+/**
+ * Who is connected, how healthy they are, and how much they can hold.
+ *
+ * Deliberately free of any transport. The registry never sees a socket, a peer
+ * connection or a data channel -- it is given a session id and timestamps, and
+ * it answers with decisions. Two reasons:
+ *
+ * 1. modules/swarm is compiled by em++ as well as by the host compiler, and
+ * libdatachannel does not exist in a browser. Anything in here that
+ * touched it would make the worker unbuildable.
+ * 2. The liveness state machine is the part most worth testing and the part
+ * least convenient to test through a real connection. Every entry point
+ * takes `now_ms` explicitly rather than reading a clock, so a test can
+ * drive a worker from healthy to dropped in a few microseconds and assert
+ * each transition on the way.
+ *
+ * Resolving a session id back to something sendable is the caller's job.
+ */
+namespace kel {
+namespace lbm {
+namespace swarm {
+
+enum class worker_state {
+ /// Connected, peer connection up, but no hello yet.
+ signalling,
+ /// Hello received and accepted.
+ registered,
+ /// Worker says it is initialised and idle.
+ ready,
+ /// Missed enough heartbeats to be doubtful, not enough to give up.
+ stale,
+};
+
+inline const char *to_string(worker_state state){
+ switch(state){
+ case worker_state::signalling: return "signalling";
+ case worker_state::registered: return "registered";
+ case worker_state::ready: return "ready";
+ case worker_state::stale: return "stale";
+ }
+ return "?";
+}
+
+/**
+ * Liveness thresholds.
+ *
+ * At namespace scope rather than nested in registry so it is a complete type
+ * where the constructor default argument needs it.
+ */
+struct worker_thresholds {
+ /// Missed pings before a worker is called stale.
+ uint64_t stale_after = 3u;
+ /// Missed pings before it is dropped entirely.
+ uint64_t drop_after = 6u;
+};
+
+/**
+ * What the orchestrator knows about one worker.
+ *
+ * Note which id is which. session_id is assigned by the orchestrator and is
+ * unique by construction; worker_id is whatever the worker called itself and is
+ * neither unique nor trustworthy. The registry is keyed on the former and
+ * merely carries the latter, so two workers choosing the same name is a display
+ * annoyance rather than a collision.
+ */
+struct worker_record {
+ std::string session_id;
+ std::string worker_id;
+ std::string kind;
+
+ worker_state state = worker_state::signalling;
+
+ uint64_t connected_at_ms = 0u;
+ uint64_t registered_at_ms = 0u;
+ uint64_t last_seen_ms = 0u;
+
+ /// Sequence of the most recent ping, so a late pong can be told from a
+ /// current one rather than silently resetting the miss counter.
+ uint64_t ping_seq = 0u;
+ uint64_t outstanding_pings = 0u;
+ uint64_t pongs = 0u;
+
+ /// Exponentially weighted mean round trip, milliseconds. Negative until
+ /// the first pong lands.
+ double rtt_ewma_ms = -1.0;
+
+ /**
+ * Roughly how many lattice cells this worker could hold, derived from what
+ * it reported. The whole point of a capability is to answer this, so it is
+ * computed once on registration rather than recomputed per query.
+ */
+ uint64_t capacity_cells = 0u;
+
+ /// Short human readable form of the capability, for the monitor.
+ std::string summary;
+
+ /// Last live block the worker sent, on a pong or a status.
+ data<sch::WorkerLive> live;
+};
+
+/**
+ * The orchestrator's only shared mutable state.
+ *
+ * libdatachannel delivers callbacks on its own threads and the heartbeat runs
+ * on another, so everything here is behind one mutex. The interface is
+ * deliberately coarse -- whole operations rather than accessors -- so callers
+ * cannot hold a reference to a record past the lock, which is the usual way a
+ * design like this goes wrong.
+ */
+class registry {
+public:
+ using thresholds = worker_thresholds;
+
+ explicit registry(worker_thresholds limits = {}) : limits_{limits} {}
+
+ void add_session(const std::string &session_id, uint64_t now_ms){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ worker_record rec;
+ rec.session_id = session_id;
+ rec.state = worker_state::signalling;
+ rec.connected_at_ms = now_ms;
+ rec.last_seen_ms = now_ms;
+
+ records_[session_id] = std::move(rec);
+ }
+
+ /// Returns false if the session is gone.
+ bool mark_registered(const std::string &session_id,
+ const std::string &worker_id, const std::string &kind,
+ uint64_t capacity_cells, std::string summary,
+ uint64_t now_ms){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ auto iter = records_.find(session_id);
+ if(iter == records_.end()){
+ return false;
+ }
+
+ auto &rec = iter->second;
+ rec.worker_id = worker_id;
+ rec.kind = kind;
+ rec.capacity_cells = capacity_cells;
+ rec.summary = std::move(summary);
+ rec.state = worker_state::registered;
+ rec.registered_at_ms = now_ms;
+ rec.last_seen_ms = now_ms;
+
+ return true;
+ }
+
+ bool mark_ready(const std::string &session_id, data<sch::WorkerLive> live,
+ uint64_t now_ms){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ auto iter = records_.find(session_id);
+ if(iter == records_.end()){
+ return false;
+ }
+
+ iter->second.state = worker_state::ready;
+ iter->second.live = std::move(live);
+ iter->second.last_seen_ms = now_ms;
+
+ return true;
+ }
+
+ bool update_live(const std::string &session_id, data<sch::WorkerLive> live,
+ uint64_t now_ms){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ auto iter = records_.find(session_id);
+ if(iter == records_.end()){
+ return false;
+ }
+
+ iter->second.live = std::move(live);
+ iter->second.last_seen_ms = now_ms;
+
+ return true;
+ }
+
+ /**
+ * Records a pong. `echoed_sent_at_ms` is the orchestrator's own timestamp
+ * coming back, so round trip needs no agreement between the two clocks.
+ * Ignores the liveness effect of a pong whose sequence is not current.
+ */
+ bool record_pong(const std::string &session_id, uint64_t seq,
+ uint64_t echoed_sent_at_ms, data<sch::WorkerLive> live,
+ uint64_t now_ms){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ auto iter = records_.find(session_id);
+ if(iter == records_.end()){
+ return false;
+ }
+
+ auto &rec = iter->second;
+
+ if(seq != rec.ping_seq){
+ // A pong for a ping we have already given up on. Counting it would
+ // paper over a worker that is consistently one beat behind, so the
+ // liveness side is left alone; the message still proves the channel
+ // works, which is worth recording.
+ rec.last_seen_ms = now_ms;
+ return true;
+ }
+
+ rec.outstanding_pings = 0u;
+ ++rec.pongs;
+ rec.last_seen_ms = now_ms;
+ rec.live = std::move(live);
+
+ // Guard against a clock that went backwards rather than producing a
+ // negative round trip.
+ const double rtt = (now_ms > echoed_sent_at_ms)
+ ? static_cast<double>(now_ms - echoed_sent_at_ms)
+ : 0.0;
+
+ if(rec.rtt_ewma_ms < 0.0){
+ rec.rtt_ewma_ms = rtt;
+ } else {
+ // Smoothing factor chosen to react within a few beats without
+ // letting one slow sample dominate.
+ constexpr double alpha = 0.25;
+ rec.rtt_ewma_ms = (alpha * rtt) + ((1.0 - alpha) * rec.rtt_ewma_ms);
+ }
+
+ // A worker that answers again stops being doubtful. It goes back to
+ // registered rather than ready, because readiness is something only the
+ // worker can assert.
+ if(rec.state == worker_state::stale){
+ rec.state = worker_state::registered;
+ }
+
+ return true;
+ }
+
+ /// Removes a session. Returns the record if there was one.
+ std::optional<worker_record> remove(const std::string &session_id){
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ auto iter = records_.find(session_id);
+ if(iter == records_.end()){
+ return std::nullopt;
+ }
+
+ worker_record rec = std::move(iter->second);
+ records_.erase(iter);
+
+ return rec;
+ }
+
+ /**
+ * One heartbeat tick.
+ *
+ * Bumps the ping sequence and the miss counter for every session, applies
+ * the stale and drop thresholds, and returns what to do. Nothing is sent
+ * from here -- the registry has nothing to send on, and in the orchestrator
+ * sending runs callbacks, which while holding this lock is how it would
+ * deadlock.
+ */
+ struct tick_result {
+ struct ping_target {
+ std::string session_id;
+ uint64_t seq;
+ };
+
+ std::vector<ping_target> to_ping;
+ /// Sessions that passed drop_after; already removed from the registry.
+ std::vector<worker_record> dropped;
+ /// Sessions that just crossed into stale, for logging.
+ std::vector<std::string> newly_stale;
+ };
+
+ tick_result tick(uint64_t now_ms){
+ (void) now_ms;
+
+ tick_result out;
+
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ for(auto iter = records_.begin(); iter != records_.end(); ){
+ auto &rec = iter->second;
+
+ // A session still negotiating has no channel to ping on. It is not
+ // unhealthy, it is just not up yet, so the thresholds do not apply.
+ if(rec.state == worker_state::signalling){
+ ++iter;
+ continue;
+ }
+
+ if(rec.outstanding_pings >= limits_.drop_after){
+ out.dropped.push_back(rec);
+ iter = records_.erase(iter);
+ continue;
+ }
+
+ if(rec.outstanding_pings >= limits_.stale_after and
+ rec.state != worker_state::stale){
+ rec.state = worker_state::stale;
+ out.newly_stale.push_back(rec.session_id);
+ }
+
+ ++rec.ping_seq;
+ ++rec.outstanding_pings;
+
+ out.to_ping.push_back(
+ tick_result::ping_target{rec.session_id, rec.ping_seq});
+
+ ++iter;
+ }
+
+ return out;
+ }
+
+ std::size_t size() const {
+ std::lock_guard<std::mutex> lock{mutex_};
+ return records_.size();
+ }
+
+ /// Snapshot for display. Copies, so the caller holds no lock.
+ std::vector<worker_record> snapshot() const {
+ std::lock_guard<std::mutex> lock{mutex_};
+
+ std::vector<worker_record> out;
+ out.reserve(records_.size());
+ for(const auto &entry : records_){
+ out.push_back(entry.second);
+ }
+
+ return out;
+ }
+
+private:
+ mutable std::mutex mutex_;
+ std::map<std::string, worker_record> records_;
+ worker_thresholds limits_;
+};
+
+namespace impl {
+
+inline std::string human_cells(uint64_t cells){
+ std::ostringstream oss;
+ oss << std::fixed << std::setprecision(1);
+
+ if(cells >= 1000000000ull){
+ oss << (static_cast<double>(cells) / 1e9) << "G";
+ } else if(cells >= 1000000ull){
+ oss << (static_cast<double>(cells) / 1e6) << "M";
+ } else if(cells >= 1000ull){
+ oss << (static_cast<double>(cells) / 1e3) << "k";
+ } else {
+ oss << cells;
+ }
+
+ return oss.str();
+}
+
+} // namespace impl
+
+/// Renders a snapshot as a fixed width table.
+inline std::string render_table(const std::vector<worker_record> &records,
+ uint64_t now_ms){
+ std::ostringstream oss;
+
+ oss << " " << std::left
+ << std::setw(6) << "sess"
+ << std::setw(18) << "worker"
+ << std::setw(9) << "kind"
+ << std::setw(12) << "state"
+ << std::setw(9) << "rtt"
+ << std::setw(8) << "pongs"
+ << std::setw(8) << "seen"
+ << std::setw(8) << "cells"
+ << "detail" << "\n";
+
+ for(const auto &rec : records){
+ std::ostringstream rtt;
+ if(rec.rtt_ewma_ms < 0.0){
+ rtt << "-";
+ } else {
+ rtt << std::fixed << std::setprecision(1) << rec.rtt_ewma_ms << "ms";
+ }
+
+ std::ostringstream seen;
+ const uint64_t age = (now_ms > rec.last_seen_ms)
+ ? (now_ms - rec.last_seen_ms) : 0u;
+ seen << (age / 1000u) << "s";
+
+ oss << " " << std::left
+ << std::setw(6) << rec.session_id
+ << std::setw(18) << (rec.worker_id.empty() ? "-" : rec.worker_id)
+ << std::setw(9) << (rec.kind.empty() ? "-" : rec.kind)
+ << std::setw(12) << to_string(rec.state)
+ << std::setw(9) << rtt.str()
+ << std::setw(8) << rec.pongs
+ << std::setw(8) << seen.str()
+ << std::setw(8) << impl::human_cells(rec.capacity_cells)
+ << rec.summary << "\n";
+ }
+
+ if(records.empty()){
+ oss << " (no workers)\n";
+ }
+
+ return oss.str();
+}
+
+} // namespace swarm
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/run.hpp b/modules/swarm/c++/run.hpp
new file mode 100644
index 0000000..b11bdf5
--- /dev/null
+++ b/modules/swarm/c++/run.hpp
@@ -0,0 +1,193 @@
+#pragma once
+
+#include "message.hpp"
+
+#include <kel/lbm/abstract/data.hpp>
+
+#include <cstdint>
+#include <string>
+#include <string_view>
+#include <string_view>
+
+/**
+ * Run identity.
+ *
+ * There is none in the library today: outputs land in a directory named after
+ * the example, with `<field>_<step>.vtk` inside, so a rerun silently
+ * overwrites the one before it and nothing records what parameters produced
+ * what. A swarm makes that worse rather than better -- several workers write
+ * concurrently, and a result arriving for an unknown run has to be refusable.
+ *
+ * A run id is therefore the first thing the orchestrator mints and the thing
+ * every transfer names. It is sortable, unique, and safe as a directory name:
+ *
+ * 20261112T094501Z-a3f19c
+ *
+ * UTC so that two machines agree, second resolution because runs are not
+ * started faster than that by a human, and six hex digits of entropy so that
+ * two started in the same second by a script still differ.
+ */
+namespace kel {
+namespace lbm {
+namespace sch {
+
+using RunDescriptor = Struct<
+ Member<String, "run_id">,
+ Member<String, "name">,
+ Member<UInt64, "created_at_ms">,
+ Member<String, "schema_version">,
+ /**
+ * Whether halo exchange was on. False until milestone 3, and recorded
+ * rather than assumed: slices run with clamped edges until then, so the
+ * seams are wrong, and a stored result should say so rather than leave
+ * someone to mistake a seam artefact for a solver bug years later.
+ */
+ Member<Bool, "halo_exchange">,
+ /// Opaque to everything here: whatever the admin endpoint was handed.
+ Member<String, "params_json">
+>;
+
+} // namespace sch
+
+namespace swarm {
+
+namespace impl {
+
+/**
+ * Civil date from a day count since 1970-01-01, by Howard Hinnant's algorithm.
+ *
+ * Deliberately not gmtime_r: this is pure arithmetic, so it needs no locale,
+ * no timezone database and no thread safety caveat, and it can be exercised
+ * directly in a test rather than through whatever the host libc happens to
+ * believe. It is also the same on a browser as on the orchestrator, which
+ * matters when both ends format or parse an id.
+ */
+struct civil_date {
+ int64_t year;
+ uint32_t month; ///< 1-12
+ uint32_t day; ///< 1-31
+};
+
+constexpr civil_date civil_from_days(int64_t z){
+ z += 719468;
+ const int64_t era = (z >= 0 ? z : z - 146096) / 146097;
+ const uint64_t doe = static_cast<uint64_t>(z - era * 146097);
+ const uint64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
+ const int64_t y = static_cast<int64_t>(yoe) + era * 400;
+ const uint64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ const uint64_t mp = (5 * doy + 2) / 153;
+ const uint64_t d = doy - (153 * mp + 2) / 5 + 1;
+ const uint64_t m = mp + (mp < 10 ? 3 : -9);
+ return civil_date{y + (m <= 2 ? 1 : 0), static_cast<uint32_t>(m),
+ static_cast<uint32_t>(d)};
+}
+
+inline void append_padded(std::string &out, uint64_t value, uint32_t width){
+ char buffer[20];
+ uint32_t written = 0u;
+ do {
+ buffer[written++] = static_cast<char>('0' + (value % 10u));
+ value /= 10u;
+ } while(value > 0u and written < sizeof(buffer));
+
+ for(uint32_t i = written; i < width; ++i){
+ out.push_back('0');
+ }
+ for(uint32_t i = written; i > 0u; --i){
+ out.push_back(buffer[i - 1u]);
+ }
+}
+
+inline void append_hex(std::string &out, uint64_t value, uint32_t digits){
+ static constexpr char table[] = "0123456789abcdef";
+ for(uint32_t i = digits; i > 0u; --i){
+ out.push_back(table[(value >> ((i - 1u) * 4u)) & 0xfu]);
+ }
+}
+
+} // namespace impl
+
+/**
+ * Formats a run id.
+ *
+ * Takes the clock and the entropy rather than reading them, for the same
+ * reason the registry takes `now_ms`: a test can then pin both and assert the
+ * exact string, instead of matching a pattern and hoping.
+ *
+ * Only the low 24 bits of `entropy` are used.
+ */
+inline std::string make_run_id(uint64_t now_ms, uint64_t entropy){
+ const int64_t seconds = static_cast<int64_t>(now_ms / 1000u);
+ const int64_t days = (seconds >= 0) ? (seconds / 86400)
+ : ((seconds - 86399) / 86400);
+ const uint64_t secs_of_day = static_cast<uint64_t>(seconds - days * 86400);
+
+ const auto date = impl::civil_from_days(days);
+
+ std::string out;
+ out.reserve(24u);
+
+ impl::append_padded(out, static_cast<uint64_t>(date.year), 4u);
+ impl::append_padded(out, date.month, 2u);
+ impl::append_padded(out, date.day, 2u);
+ out.push_back('T');
+ impl::append_padded(out, secs_of_day / 3600u, 2u);
+ impl::append_padded(out, (secs_of_day / 60u) % 60u, 2u);
+ impl::append_padded(out, secs_of_day % 60u, 2u);
+ out.push_back('Z');
+ out.push_back('-');
+ impl::append_hex(out, entropy, 6u);
+
+ return out;
+}
+
+/**
+ * Whether a string could have come from make_run_id.
+ *
+ * The sink uses a run id as a directory name, so this is also the check that
+ * keeps a hostile id from escaping the storage root -- there is no '/', no
+ * '.', and nothing but a fixed shape of digits and hex.
+ */
+inline bool is_run_id(std::string_view id){
+ if(id.size() != 23u){
+ return false;
+ }
+
+ auto digit = [&](std::size_t i){ return id[i] >= '0' and id[i] <= '9'; };
+ auto hex = [&](std::size_t i){
+ return (id[i] >= '0' and id[i] <= '9') or (id[i] >= 'a' and id[i] <= 'f');
+ };
+
+ for(std::size_t i = 0u; i < 8u; ++i){
+ if(not digit(i)){ return false; }
+ }
+ if(id[8] != 'T'){ return false; }
+ for(std::size_t i = 9u; i < 15u; ++i){
+ if(not digit(i)){ return false; }
+ }
+ if(id[15] != 'Z'){ return false; }
+ if(id[16] != '-'){ return false; }
+ for(std::size_t i = 17u; i < 23u; ++i){
+ if(not hex(i)){ return false; }
+ }
+
+ return true;
+}
+
+} // namespace swarm
+
+namespace sch {
+
+using MsgRunStart = Envelope<Member<RunDescriptor, "run">>;
+using MsgRunEnd = Envelope<Member<String, "run_id">, Member<String, "outcome">>;
+
+} // namespace sch
+
+namespace run_outcome {
+inline constexpr std::string_view finished = "finished";
+inline constexpr std::string_view cancelled = "cancelled";
+inline constexpr std::string_view failed = "failed";
+} // namespace run_outcome
+
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/signal.hpp b/modules/swarm/c++/signal.hpp
new file mode 100644
index 0000000..e8d76bd
--- /dev/null
+++ b/modules/swarm/c++/signal.hpp
@@ -0,0 +1,52 @@
+#pragma once
+
+#include <kel/lbm/abstract/schema.hpp>
+
+#include <string_view>
+
+/**
+ * WebRTC signalling, carried over the WebSocket that precedes the data channel.
+ *
+ * This is a different protocol from the control messages in message.hpp and
+ * deliberately so: signalling exists only to get a peer connection established,
+ * after which everything moves to the data channel. It lives here rather than
+ * in the orchestrator because both the browser worker and the native test
+ * worker have to speak it, and one definition is the only way they cannot
+ * disagree.
+ *
+ * The shapes mirror what a browser hands you, with one deliberate difference:
+ * an ICE candidate arrives from JS as {candidate, sdpMid, sdpMLineIndex} and is
+ * sent on as {type:"candidate", candidate, mid}. Normalising at the JS boundary
+ * keeps the wire uniform -- every message here is a struct with a "type" -- at
+ * the cost of three lines in the worker's transport glue.
+ */
+namespace kel {
+namespace lbm {
+namespace sch {
+
+/// Stage one of the same two stage decode the control protocol uses.
+using SignalHeader = Struct<Member<String, "type">>;
+
+/// "offer" or "answer".
+using SignalDescription = Struct<
+ Member<String, "type">,
+ Member<String, "sdp">
+>;
+
+/// "candidate". mid may be empty; libdatachannel treats that as unhinted.
+using SignalCandidate = Struct<
+ Member<String, "type">,
+ Member<String, "candidate">,
+ Member<String, "mid">
+>;
+
+} // namespace sch
+
+namespace sig {
+inline constexpr std::string_view offer = "offer";
+inline constexpr std::string_view answer = "answer";
+inline constexpr std::string_view candidate = "candidate";
+} // namespace sig
+
+} // namespace lbm
+} // namespace kel
diff --git a/modules/swarm/c++/swarm.hpp b/modules/swarm/c++/swarm.hpp
new file mode 100644
index 0000000..a7c066f
--- /dev/null
+++ b/modules/swarm/c++/swarm.hpp
@@ -0,0 +1,11 @@
+#pragma once
+
+#include "capability.hpp"
+#include "capacity.hpp"
+#include "interpret.hpp"
+#include "message.hpp"
+#include "run.hpp"
+#include "probe_search.hpp"
+#include "registry.hpp"
+#include "signal.hpp"
+#include "wire.hpp"
diff --git a/modules/swarm/c++/wire.hpp b/modules/swarm/c++/wire.hpp
new file mode 100644
index 0000000..7c7c7d0
--- /dev/null
+++ b/modules/swarm/c++/wire.hpp
@@ -0,0 +1,119 @@
+#pragma once
+
+#include "message.hpp"
+
+#include <kel/lbm/abstract/data.hpp>
+#include <kel/lbm/abstract/json.hpp>
+
+#include <string>
+#include <string_view>
+
+/**
+ * Encoding and decoding control messages.
+ *
+ * Everything here runs the JSON codec in strict mode. That is not the codec's
+ * default, and the default is wrong for a wire: codec_config<enc::Json>::strict
+ * is false so that config files can state only their deviations, which means a
+ * worker sending "{}" would decode cleanly into a default constructed struct.
+ * A registration that silently becomes all zeroes is precisely the failure this
+ * protocol must not have, so strict is set explicitly on every wire codec.
+ *
+ * Strict only governs *missing* members. Unknown members are skipped by the
+ * Struct decoder, which is what makes the two stage decode below work and what
+ * lets a newer worker talk to an older orchestrator.
+ */
+namespace kel {
+namespace lbm {
+namespace swarm {
+
+namespace impl {
+template <typename Schema>
+codec<Schema, enc::Json> make_wire_codec(){
+ codec_config<enc::Json> cfg;
+ cfg.strict = true;
+ // Control messages nest at most capability -> webgl2 -> feasible -> plan,
+ // so the default guard against pathological input is already generous.
+ return codec<Schema, enc::Json>{cfg};
+}
+} // namespace impl
+
+/**
+ * Serialise a message to the text that goes on the data channel.
+ */
+template <typename Schema>
+error_or<std::string> encode_message(const data<Schema> &msg){
+ auto wire_codec = impl::make_wire_codec<Schema>();
+
+ data<Schema, enc::Json> out;
+ auto eov = wire_codec.encode(msg, out);
+ if(eov.is_error()){
+ return std::move(eov.get_error());
+ }
+
+ return out.stl_string();
+}
+
+/**
+ * Decode text into a known message type. Fails if any member is absent.
+ */
+template <typename Schema>
+error_or<data<Schema>> decode_message(std::string_view text){
+ auto wire_codec = impl::make_wire_codec<Schema>();
+
+ data<Schema, enc::Json> in{text};
+ data<Schema> out;
+ auto eov = wire_codec.decode(in, out);
+ if(eov.is_error()){
+ return std::move(eov.get_error());
+ }
+
+ return out;
+}
+
+/**
+ * Stage one: read just the common members so the caller learns which type to
+ * decode. The payload is skipped rather than parsed into anything, so this
+ * succeeds for every message type and fails only on genuinely malformed input
+ * or a message missing the common members.
+ */
+inline error_or<data<sch::MsgHeader>> peek_header(std::string_view text){
+ return decode_message<sch::MsgHeader>(text);
+}
+
+/**
+ * Fills in the members every message shares. Kept in one place so a message
+ * built by the orchestrator and one built by the worker cannot disagree about
+ * the shape of the envelope.
+ */
+template <typename Schema>
+void set_envelope(data<Schema> &msg, std::string_view type,
+ std::string_view worker_id, uint64_t seq){
+ msg.template get<"type">().set(std::string{type});
+ msg.template get<"worker_id">().set(std::string{worker_id});
+ msg.template get<"seq">().set(seq);
+}
+
+/**
+ * Convenience for the common shape: build a message, stamp the envelope.
+ */
+template <typename Schema>
+data<Schema> make_message(std::string_view type, std::string_view worker_id,
+ uint64_t seq){
+ data<Schema> msg;
+ set_envelope(msg, type, worker_id, seq);
+ return msg;
+}
+
+/// Reads the "type" of an already decoded header.
+inline std::string_view header_type(const data<sch::MsgHeader> &hdr){
+ return hdr.template get<"type">().stl_view();
+}
+
+/// Reads the "worker_id" of an already decoded header.
+inline std::string_view header_worker_id(const data<sch::MsgHeader> &hdr){
+ return hdr.template get<"worker_id">().stl_view();
+}
+
+} // namespace swarm
+} // namespace lbm
+} // namespace kel