refactor: consolidate crate functions #50
173 changed files with 1594 additions and 25774 deletions
2224
Cargo.lock
generated
2224
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
17
Cargo.toml
17
Cargo.toml
|
|
@ -1,23 +1,21 @@
|
|||
[workspace]
|
||||
members = [
|
||||
".",
|
||||
"crates/python",
|
||||
"crates/wasm/runtime",
|
||||
"crates/bin-runner",
|
||||
"crates/bindings/python",
|
||||
"crates/bindings/wasm-runtime",
|
||||
"crates/simulation",
|
||||
"crates/dashboard",
|
||||
"crates/distribution",
|
||||
"crates/std",
|
||||
"crates/process",
|
||||
"crates/datastore",
|
||||
"crates/shared-types",
|
||||
"crates/swactor-node",
|
||||
"crates/node",
|
||||
"crates/streams",
|
||||
"tests/docker",
|
||||
"crates/ci",
|
||||
"xtask",
|
||||
]
|
||||
exclude = ["tools/depgraph", "crates/wasm/crypto"]
|
||||
exclude = ["tools/depgraph", "crates/bindings/wasm-crypto"]
|
||||
|
||||
[package]
|
||||
name = "swactor"
|
||||
|
|
@ -33,7 +31,8 @@ strip = false
|
|||
crate-type = ["rlib"]
|
||||
|
||||
[features]
|
||||
default = ["getrandom"]
|
||||
default = ["getrandom", "std"]
|
||||
std = [] # OTP patterns: supervisors, registries, timers, routers
|
||||
getrandom = ["dep:getrandom"]
|
||||
serde = ["dep:serde"]
|
||||
tracing = ["dep:tracing"]
|
||||
|
|
@ -54,7 +53,6 @@ crossbeam-utils = "0.8.21"
|
|||
criterion = { version = "0.5", features = ["html_reports"] }
|
||||
proptest = "1"
|
||||
proptest-state-machine = "0.3"
|
||||
swactor-std = { path = "crates/std" }
|
||||
|
||||
[[bench]]
|
||||
name = "runtime_benchmarks"
|
||||
|
|
@ -68,6 +66,3 @@ harness = false
|
|||
name = "hasher_benchmarks"
|
||||
harness = false
|
||||
|
||||
[[example]]
|
||||
name = "tcp_ping_pong"
|
||||
required-features = ["transport"]
|
||||
|
|
|
|||
154
README.md
154
README.md
|
|
@ -1,152 +1,24 @@
|
|||
# swactor
|
||||
|
||||
Minimal actor runtime for Rust. Single-threaded or multi-threaded, with
|
||||
Python and WebAssembly bindings.
|
||||
Minimal actor runtime for Rust. One trait, one message type.
|
||||
Single-threaded (`tick()`) or multi-threaded (`run()`).
|
||||
|
||||
## Quick Start
|
||||
## Description
|
||||
|
||||
```rust
|
||||
use swactor::actor::{ActorAddress, ActorInterface};
|
||||
use swactor::runtime::{Ctx, Runtime, RuntimeConfig};
|
||||
Core runtime is `src/`. Actors implement `ActorInterface` (in `actor.rs`),
|
||||
interact through `Ctx` (in `runtime.rs`), and run on worker threads (`worker.rs`).
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Greet { name: String, reply_to: ActorAddress }
|
||||
`crates/` builds upward: `std` adds OTP patterns (supervision, monitoring, groups),
|
||||
`distribution` adds clustering, everything else composes from there.
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Greeting(String);
|
||||
## Dev commands
|
||||
|
||||
struct Greeter;
|
||||
`cargo xtask --help` for available test groups.
|
||||
|
||||
impl ActorInterface for Greeter {
|
||||
type Incoming = Greet;
|
||||
type Response = Greeting;
|
||||
## Testing
|
||||
|
||||
fn handle(&mut self, ctx: &Ctx, msg: Greet) {
|
||||
let _ = ctx.send(msg.reply_to, Greeting(format!("Hello, {}!", msg.name)));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let rt = Runtime::new(RuntimeConfig::default());
|
||||
let addr = rt.spawn(Greeter).unwrap();
|
||||
let inbox = rt.new_inbox::<Greeting>().unwrap();
|
||||
|
||||
rt.send_to(addr, Greet { name: "world".into(), reply_to: *inbox.addr() }).unwrap();
|
||||
rt.tick();
|
||||
rt.tick();
|
||||
|
||||
println!("{}", inbox.try_recv().unwrap().0); // "Hello, world!"
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### Actor Model
|
||||
|
||||
Actors implement one trait (`ActorInterface`), receive one message type, and
|
||||
hold mutable state. No lifecycle hooks, no supervision trees, no async.
|
||||
|
||||
Every actor gets a 32-byte globally unique `ActorAddress`. The same
|
||||
`ctx.send(addr, msg)` call works whether the target is on the same worker,
|
||||
a different worker thread, an external inbox, or a remote process.
|
||||
|
||||
Single-threaded mode (`rt.tick()`) gives deterministic frame-level control.
|
||||
Multi-threaded mode (`rt.run()`) spawns OS threads with adaptive backoff.
|
||||
|
||||
See [docs/runtime/actor-model.md](docs/runtime/actor-model.md) and
|
||||
[docs/runtime/runtime.md](docs/runtime/runtime.md) for the full model.
|
||||
|
||||
### Transport
|
||||
|
||||
Pluggable cross-process messaging. User-provided codecs handle serialization
|
||||
(gRPC/protobuf, bincode, hand-rolled — no serde bounds imposed) and
|
||||
user-provided transports handle delivery (TCP, in-memory, gRPC channel).
|
||||
|
||||
```bash
|
||||
cargo build --features transport
|
||||
cargo run --example tcp_ping_pong --features transport -- receiver # terminal 1
|
||||
cargo run --example tcp_ping_pong --features transport -- sender # terminal 2
|
||||
cargo check --workspace
|
||||
cargo xtask test <your-feature-crate>
|
||||
cargo xtask test essential
|
||||
```
|
||||
|
||||
See [docs/distribution/transport.md](docs/distribution/transport.md) for the routing chain, codec
|
||||
registry, and address resolution.
|
||||
|
||||
### Runtime Dashboard
|
||||
|
||||
Live web dashboard for monitoring actors, message throughput, and mailbox
|
||||
depths. Supports trace recording and replay at configurable speed.
|
||||
|
||||
Includes hand-authored SVG diagrams (actor lifecycle, message lifecycle,
|
||||
tick cycle, transport routing) and generated diagrams from DOT sources
|
||||
(architecture, dataflow, type erasure).
|
||||
|
||||
See [crates/runtime-dashboard/](crates/runtime-dashboard/README.md).
|
||||
|
||||
### Language Bindings
|
||||
|
||||
**Python** — PyO3 via Maturin. Spawn actors from Python callables, pass
|
||||
dicts as messages, single-threaded or multi-threaded.
|
||||
|
||||
```bash
|
||||
cd crates/swactor-python && maturin develop
|
||||
```
|
||||
|
||||
Examples in `examples/python/` (single-thread, async, Jupyter notebook).
|
||||
|
||||
**WASM** — wasm-bindgen. Runs single-threaded with deterministic addressing
|
||||
(`no_random` feature).
|
||||
|
||||
```bash
|
||||
cd crates/swactor-wasm && wasm-pack build --target nodejs
|
||||
```
|
||||
|
||||
### Connectome Analysis
|
||||
|
||||
Structural analysis of the internal dependency graph.
|
||||
|
||||
- **depgraph** (`tools/depgraph/`) — AST-based extraction of module
|
||||
dependencies, outputs GraphViz DOT
|
||||
- **spectral** (`tools/spectral/`) — Laplacian eigenvalue analysis,
|
||||
Connectome Complexity Index (CCI), coupling heatmaps, interactive HTML
|
||||
dashboard
|
||||
|
||||
```bash
|
||||
cargo run --manifest-path tools/depgraph/Cargo.toml -- --src-dir src/ --output deps
|
||||
python tools/spectral/spectral_analysis.py deps.dot
|
||||
```
|
||||
|
||||
See [docs/connectome/connectome.md](docs/connectome/connectome.md) for metric interpretation.
|
||||
|
||||
## Building & Testing
|
||||
|
||||
```bash
|
||||
cargo test # all tests
|
||||
cargo test --features transport # include transport tests
|
||||
cargo run --example hello # single actor example
|
||||
cargo run --example ring # 500-actor ring topology
|
||||
cargo bench # benchmarks (criterion)
|
||||
```
|
||||
|
||||
## Feature Flags
|
||||
|
||||
| Flag | Default | What it does |
|
||||
|------|---------|--------------|
|
||||
| `getrandom` | yes | System RNG for actor addresses |
|
||||
| `no_random` | no | Deterministic counter (WASM / reproducible tests) |
|
||||
| `transport` | no | Pluggable remote messaging (codec + transport) |
|
||||
| `tracing` | no | `tracing` instrumentation for runtime internals |
|
||||
| `serde` | no | Serde derives for stats types |
|
||||
| `python` | no | PyO3 bindings (cdylib wheel) |
|
||||
|
||||
## Documentation
|
||||
|
||||
| Document | Covers |
|
||||
|----------|--------|
|
||||
| [Actor Model](docs/runtime/actor-model.md) | Traits, type erasure, addresses |
|
||||
| [Runtime](docs/runtime/runtime.md) | Runtime, Ctx, Inbox, RuntimeHandle, stats |
|
||||
| [Worker Thread](docs/runtime/worker-thread.md) | Tick phases, backoff, routing, full system topology |
|
||||
| [Channels](docs/runtime/channels.md) | HybridChannel, AddressMap, Placement |
|
||||
| [Transport](docs/distribution/transport.md) | Codec, Transport, remote messaging, address resolution |
|
||||
| [Distribution](docs/distribution/distribution.md) | SWIM membership, Kademlia, NodeDriver |
|
||||
| [Connectome](docs/connectome/connectome.md) | CCI metrics, spectral analysis interpretation |
|
||||
| [Dashboard](crates/runtime-dashboard/README.md) | Live web UI, trace recording, diagram index |
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use swactor::{
|
|||
config::RuntimeConfig,
|
||||
runtime::{Ctx, Runtime},
|
||||
};
|
||||
use swactor_std::{RuntimeGroups, RuntimeNaming, StdExtension};
|
||||
use swactor::std::{RuntimeGroups, RuntimeNaming, StdExtension};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
[package]
|
||||
name = "swactor-bin-runner"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
swactor = { path = "../.." }
|
||||
wasmtime = "29"
|
||||
|
||||
[dev-dependencies]
|
||||
swactor = { path = "../..", features = ["getrandom"] }
|
||||
swactor-std = { path = "../std" }
|
||||
wat = "1"
|
||||
proptest = "1"
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let guests_dir = Path::new(manifest_dir).join("tests/guests");
|
||||
|
||||
for guest in &["echo", "double", "silent"] {
|
||||
let guest_dir = guests_dir.join(guest);
|
||||
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
guest_dir.join("src/lib.rs").display()
|
||||
);
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
guest_dir.join("Cargo.toml").display()
|
||||
);
|
||||
|
||||
let status = Command::new("cargo")
|
||||
.args(["build", "--target", "wasm32-unknown-unknown", "--release"])
|
||||
.current_dir(&guest_dir)
|
||||
.status()
|
||||
.unwrap_or_else(|e| panic!("failed to run cargo build for {guest} guest: {e}"));
|
||||
|
||||
assert!(status.success(), "failed to build {guest} guest");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
use swactor::actor::{ActorInterface, Ctx};
|
||||
use wasmtime::{Memory, Store, TypedFunc};
|
||||
|
||||
use crate::ByteMessage;
|
||||
|
||||
/// State accessible to host functions during guest execution.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostState {
|
||||
pub outbox: Vec<(swactor::actor::ActorAddress, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// An actor whose logic is defined by a WebAssembly guest module.
|
||||
///
|
||||
/// Messages arrive as [`ByteMessage`], are copied into Wasm linear memory,
|
||||
/// and processed by the guest's `handle` export. The guest can send messages
|
||||
/// back via the `swactor.send` host import.
|
||||
pub struct WasmActor {
|
||||
pub(crate) store: Store<HostState>,
|
||||
pub(crate) memory: Memory,
|
||||
pub(crate) alloc: TypedFunc<i32, i32>,
|
||||
pub(crate) handle: TypedFunc<(i32, i32), ()>,
|
||||
}
|
||||
|
||||
impl ActorInterface for WasmActor {
|
||||
type Incoming = ByteMessage;
|
||||
type Response = ();
|
||||
|
||||
fn handle(&mut self, ctx: &Ctx, msg: ByteMessage) {
|
||||
let bytes = &msg.0;
|
||||
let len: i32 = match i32::try_from(bytes.len()) {
|
||||
Ok(n) => n,
|
||||
Err(_) => return, // message too large for i32 ABI
|
||||
};
|
||||
|
||||
// 1. Allocate space in guest memory
|
||||
let ptr = match self.alloc.call(&mut self.store, len) {
|
||||
Ok(ptr) if ptr < 0 => return, // invalid pointer
|
||||
Ok(0) if len > 0 => return, // OOM — drop message
|
||||
Ok(ptr) => ptr,
|
||||
Err(_) => return, // alloc trapped — drop message
|
||||
};
|
||||
|
||||
// 2. Write message bytes into guest memory
|
||||
let mem = self.memory.data_mut(&mut self.store);
|
||||
let end = (ptr as usize).saturating_add(bytes.len());
|
||||
if end > mem.len() {
|
||||
return; // alloc returned OOB pointer — drop message
|
||||
}
|
||||
mem[ptr as usize..end].copy_from_slice(bytes);
|
||||
|
||||
// 3. Call guest handle
|
||||
if self.handle.call(&mut self.store, (ptr, len)).is_err() {
|
||||
self.store.data_mut().outbox.clear(); // discard sends from incomplete operation
|
||||
return; // handle trapped — drop message, keep actor alive
|
||||
}
|
||||
|
||||
// 4. Drain outbox → send via ctx
|
||||
let outbox: Vec<_> = self.store.data_mut().outbox.drain(..).collect();
|
||||
for (dest, payload) in outbox {
|
||||
let _ = ctx.send(dest, ByteMessage(payload));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,109 +0,0 @@
|
|||
use swactor::actor::ActorAddress;
|
||||
use wasmtime::{Linker, Module, Store, TypedFunc};
|
||||
|
||||
use crate::actor::{HostState, WasmActor};
|
||||
use crate::engine::SharedEngine;
|
||||
use crate::error::WasmActorError;
|
||||
|
||||
/// Compiles a Wasm module and produces a ready-to-use [`WasmActor`].
|
||||
pub struct WasmActorBuilder {
|
||||
engine: SharedEngine,
|
||||
wasm_bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl WasmActorBuilder {
|
||||
pub fn new(engine: SharedEngine, wasm_bytes: impl Into<Vec<u8>>) -> Self {
|
||||
Self {
|
||||
engine,
|
||||
wasm_bytes: wasm_bytes.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile the module, link host functions, and instantiate.
|
||||
pub fn build(self) -> Result<WasmActor, WasmActorError> {
|
||||
let engine = self.engine.inner();
|
||||
let module = Module::new(engine, &self.wasm_bytes)?;
|
||||
|
||||
let mut linker: Linker<HostState> = Linker::new(engine);
|
||||
Self::link_send(&mut linker)?;
|
||||
|
||||
let mut store = Store::new(engine, HostState::default());
|
||||
let instance = linker.instantiate(&mut store, &module)?;
|
||||
|
||||
// Extract required exports
|
||||
let memory = instance
|
||||
.get_memory(&mut store, "memory")
|
||||
.ok_or(WasmActorError::MissingExport("memory"))?;
|
||||
|
||||
let alloc: TypedFunc<i32, i32> = instance
|
||||
.get_typed_func(&mut store, "alloc")
|
||||
.map_err(|_| WasmActorError::MissingExport("alloc"))?;
|
||||
|
||||
let handle: TypedFunc<(i32, i32), ()> = instance
|
||||
.get_typed_func(&mut store, "handle")
|
||||
.map_err(|_| WasmActorError::MissingExport("handle"))?;
|
||||
|
||||
Ok(WasmActor {
|
||||
store,
|
||||
memory,
|
||||
alloc,
|
||||
handle,
|
||||
})
|
||||
}
|
||||
|
||||
/// Link the `swactor.send` host import.
|
||||
fn link_send(linker: &mut Linker<HostState>) -> Result<(), WasmActorError> {
|
||||
linker.func_wrap(
|
||||
"swactor",
|
||||
"send",
|
||||
|mut caller: wasmtime::Caller<'_, HostState>,
|
||||
dest_ptr: i32,
|
||||
payload_ptr: i32,
|
||||
payload_len: i32|
|
||||
-> Result<(), wasmtime::Error> {
|
||||
let mem = caller
|
||||
.get_export("memory")
|
||||
.and_then(|e| e.into_memory())
|
||||
.ok_or_else(|| wasmtime::Error::msg("guest must export memory"))?;
|
||||
let data = mem.data(&caller);
|
||||
let mem_len = data.len();
|
||||
|
||||
// Validate non-negative arguments
|
||||
if dest_ptr < 0 || payload_ptr < 0 || payload_len < 0 {
|
||||
return Err(wasmtime::Error::msg(
|
||||
"negative argument in swactor.send",
|
||||
));
|
||||
}
|
||||
|
||||
let dest_ptr = dest_ptr as usize;
|
||||
let payload_ptr = payload_ptr as usize;
|
||||
let payload_len = payload_len as usize;
|
||||
|
||||
// Bounds-check with overflow protection
|
||||
let dest_end = dest_ptr
|
||||
.checked_add(32)
|
||||
.ok_or_else(|| wasmtime::Error::msg("dest_ptr overflow"))?;
|
||||
let payload_end = payload_ptr
|
||||
.checked_add(payload_len)
|
||||
.ok_or_else(|| wasmtime::Error::msg("payload range overflow"))?;
|
||||
if dest_end > mem_len || payload_end > mem_len {
|
||||
return Err(wasmtime::Error::msg(
|
||||
"out-of-bounds memory access in swactor.send",
|
||||
));
|
||||
}
|
||||
|
||||
// Read 32-byte destination address
|
||||
let mut addr_bytes = [0u8; 32];
|
||||
addr_bytes.copy_from_slice(&data[dest_ptr..dest_end]);
|
||||
let dest = ActorAddress(addr_bytes);
|
||||
|
||||
// Read payload
|
||||
let payload = data[payload_ptr..payload_end].to_vec();
|
||||
|
||||
caller.data_mut().outbox.push((dest, payload));
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use wasmtime::Engine;
|
||||
|
||||
/// A shared, cheaply-cloneable Wasm engine.
|
||||
///
|
||||
/// Created once and reused across multiple [`WasmActor`](crate::WasmActor) instances.
|
||||
/// Configured with maximum sandboxing — no threads, no SIMD, no reference types.
|
||||
#[derive(Clone)]
|
||||
pub struct SharedEngine(Arc<Engine>);
|
||||
|
||||
impl std::fmt::Debug for SharedEngine {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("SharedEngine").field(&"<Engine>").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl SharedEngine {
|
||||
/// Create a new engine with sandboxed defaults.
|
||||
pub fn new() -> Result<Self, wasmtime::Error> {
|
||||
let mut config = wasmtime::Config::new();
|
||||
config.wasm_threads(false);
|
||||
config.wasm_simd(false);
|
||||
config.wasm_relaxed_simd(false);
|
||||
config.wasm_reference_types(false);
|
||||
config.wasm_multi_value(false);
|
||||
config.wasm_bulk_memory(true);
|
||||
let engine = Engine::new(&config)?;
|
||||
Ok(Self(Arc::new(engine)))
|
||||
}
|
||||
|
||||
pub(crate) fn inner(&self) -> &Engine {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
use std::fmt;
|
||||
|
||||
/// Errors that can occur when building or running a WasmActor.
|
||||
#[derive(Debug)]
|
||||
pub enum WasmActorError {
|
||||
/// A required export is missing from the Wasm module.
|
||||
MissingExport(&'static str),
|
||||
/// The Wasm module failed to compile or instantiate.
|
||||
Wasmtime(wasmtime::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for WasmActorError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingExport(name) => write!(f, "missing required export: `{name}`"),
|
||||
Self::Wasmtime(e) => write!(f, "wasmtime error: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WasmActorError {}
|
||||
|
||||
impl From<wasmtime::Error> for WasmActorError {
|
||||
fn from(e: wasmtime::Error) -> Self {
|
||||
Self::Wasmtime(e)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
mod actor;
|
||||
mod builder;
|
||||
mod engine;
|
||||
mod error;
|
||||
|
||||
pub use actor::WasmActor;
|
||||
pub use builder::WasmActorBuilder;
|
||||
pub use engine::SharedEngine;
|
||||
pub use error::WasmActorError;
|
||||
|
||||
/// A message carrying raw bytes, suitable for passing to/from Wasm guests.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ByteMessage(pub Vec<u8>);
|
||||
7
crates/bin-runner/tests/guests/double/Cargo.lock
generated
7
crates/bin-runner/tests/guests/double/Cargo.lock
generated
|
|
@ -1,7 +0,0 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "double-guest"
|
||||
version = "0.1.0"
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "double-guest"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
|
|
@ -1,63 +0,0 @@
|
|||
#![no_std]
|
||||
|
||||
use core::cell::UnsafeCell;
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
// --- bump allocator ---
|
||||
const HEAP_SIZE: usize = 65536;
|
||||
|
||||
struct BumpAlloc {
|
||||
heap: UnsafeCell<[u8; HEAP_SIZE]>,
|
||||
offset: UnsafeCell<usize>,
|
||||
}
|
||||
|
||||
unsafe impl Sync for BumpAlloc {}
|
||||
|
||||
static ALLOC: BumpAlloc = BumpAlloc {
|
||||
heap: UnsafeCell::new([0u8; HEAP_SIZE]),
|
||||
offset: UnsafeCell::new(0),
|
||||
};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn alloc(size: i32) -> i32 {
|
||||
unsafe {
|
||||
let offset = &mut *ALLOC.offset.get();
|
||||
let heap = &mut *ALLOC.heap.get();
|
||||
let align = 8;
|
||||
let start = (*offset + align - 1) & !(align - 1);
|
||||
let end = start + size as usize;
|
||||
if end > heap.len() {
|
||||
return 0; // OOM
|
||||
}
|
||||
*offset = end;
|
||||
heap.as_ptr().add(start) as i32
|
||||
}
|
||||
}
|
||||
|
||||
// --- host import ---
|
||||
#[link(wasm_import_module = "swactor")]
|
||||
unsafe extern "C" {
|
||||
#[link_name = "send"]
|
||||
fn host_send(dest_ptr: i32, payload_ptr: i32, payload_len: i32);
|
||||
}
|
||||
|
||||
/// Message format: first 32 bytes = destination address, rest = payload.
|
||||
/// Sends the payload back twice to demonstrate multi-send.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn handle(ptr: i32, len: i32) {
|
||||
if len < 32 {
|
||||
return;
|
||||
}
|
||||
let dest_ptr = ptr;
|
||||
let payload_ptr = ptr + 32;
|
||||
let payload_len = len - 32;
|
||||
unsafe {
|
||||
host_send(dest_ptr, payload_ptr, payload_len);
|
||||
host_send(dest_ptr, payload_ptr, payload_len);
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_info: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
7
crates/bin-runner/tests/guests/echo/Cargo.lock
generated
7
crates/bin-runner/tests/guests/echo/Cargo.lock
generated
|
|
@ -1,7 +0,0 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "echo-guest"
|
||||
version = "0.1.0"
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "echo-guest"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
#![no_std]
|
||||
|
||||
use core::cell::UnsafeCell;
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
// --- bump allocator ---
|
||||
const HEAP_SIZE: usize = 65536;
|
||||
|
||||
struct BumpAlloc {
|
||||
heap: UnsafeCell<[u8; HEAP_SIZE]>,
|
||||
offset: UnsafeCell<usize>,
|
||||
}
|
||||
|
||||
unsafe impl Sync for BumpAlloc {}
|
||||
|
||||
static ALLOC: BumpAlloc = BumpAlloc {
|
||||
heap: UnsafeCell::new([0u8; HEAP_SIZE]),
|
||||
offset: UnsafeCell::new(0),
|
||||
};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn alloc(size: i32) -> i32 {
|
||||
unsafe {
|
||||
let offset = &mut *ALLOC.offset.get();
|
||||
let heap = &mut *ALLOC.heap.get();
|
||||
let align = 8;
|
||||
let start = (*offset + align - 1) & !(align - 1);
|
||||
let end = start + size as usize;
|
||||
if end > heap.len() {
|
||||
return 0; // OOM
|
||||
}
|
||||
*offset = end;
|
||||
heap.as_ptr().add(start) as i32
|
||||
}
|
||||
}
|
||||
|
||||
// --- host import ---
|
||||
#[link(wasm_import_module = "swactor")]
|
||||
unsafe extern "C" {
|
||||
#[link_name = "send"]
|
||||
fn host_send(dest_ptr: i32, payload_ptr: i32, payload_len: i32);
|
||||
}
|
||||
|
||||
/// Message format: first 32 bytes = destination address, rest = payload.
|
||||
/// Echo sends the payload portion back to the specified destination.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn handle(ptr: i32, len: i32) {
|
||||
if len < 32 {
|
||||
return;
|
||||
}
|
||||
let dest_ptr = ptr;
|
||||
let payload_ptr = ptr + 32;
|
||||
let payload_len = len - 32;
|
||||
unsafe {
|
||||
host_send(dest_ptr, payload_ptr, payload_len);
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_info: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
7
crates/bin-runner/tests/guests/silent/Cargo.lock
generated
7
crates/bin-runner/tests/guests/silent/Cargo.lock
generated
|
|
@ -1,7 +0,0 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "silent-guest"
|
||||
version = "0.1.0"
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "silent-guest"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
#![no_std]
|
||||
|
||||
use core::cell::UnsafeCell;
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
// --- bump allocator ---
|
||||
const HEAP_SIZE: usize = 65536;
|
||||
|
||||
struct BumpAlloc {
|
||||
heap: UnsafeCell<[u8; HEAP_SIZE]>,
|
||||
offset: UnsafeCell<usize>,
|
||||
}
|
||||
|
||||
unsafe impl Sync for BumpAlloc {}
|
||||
|
||||
static ALLOC: BumpAlloc = BumpAlloc {
|
||||
heap: UnsafeCell::new([0u8; HEAP_SIZE]),
|
||||
offset: UnsafeCell::new(0),
|
||||
};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn alloc(size: i32) -> i32 {
|
||||
unsafe {
|
||||
let offset = &mut *ALLOC.offset.get();
|
||||
let heap = &mut *ALLOC.heap.get();
|
||||
let align = 8;
|
||||
let start = (*offset + align - 1) & !(align - 1);
|
||||
let end = start + size as usize;
|
||||
if end > heap.len() {
|
||||
return 0; // OOM
|
||||
}
|
||||
*offset = end;
|
||||
heap.as_ptr().add(start) as i32
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn handle(_ptr: i32, _len: i32) {
|
||||
// Silent: receive bytes, do nothing
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_info: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc f8674b306ba8187ad75bcc5a33c4a679e497a0053dc6fdb2234ccaeaae8f85b7 # shrinks to guest_idx = 0, n_msgs = 0, ticks_before = 1, ticks_after = 1
|
||||
cc db98a9c0726c0477ba56ec6098a1f21518faaff4551d90e915790ce3c890dd53 # shrinks to payload = []
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -8,5 +8,5 @@ name = "swactor"
|
|||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
swactor = { path = "../.." }
|
||||
swactor = { path = "../../.." }
|
||||
pyo3 = { version = "0.23", features = ["extension-module"] }
|
||||
|
|
@ -7,6 +7,5 @@ edition = "2024"
|
|||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
swactor = { path = "../../..", default-features = false, features = ["wasm"] }
|
||||
swactor-std = { path = "../../std", default-features = false, features = ["wasm"] }
|
||||
swactor = { path = "../../..", default-features = false, features = ["wasm", "std"] }
|
||||
wasm-bindgen = "0.2"
|
||||
|
|
@ -4,7 +4,7 @@ use wasm_bindgen::prelude::*;
|
|||
|
||||
use swactor::actor::{ActorAddress, ActorExited, ActorInterface};
|
||||
use swactor::runtime::{Ctx, Inbox, Runtime, RuntimeConfig};
|
||||
use swactor_std::{CtxGroups, CtxWatching, RuntimeNaming, RuntimeGroups, StdExtension};
|
||||
use swactor::std::{CtxGroups, CtxWatching, RuntimeNaming, RuntimeGroups, StdExtension};
|
||||
|
||||
// ─── Core JS-facing types ───────────────────────────────────────────────────
|
||||
|
||||
|
|
@ -270,7 +270,7 @@ pipelines:
|
|||
jobs:
|
||||
build:
|
||||
run: cargo build --release
|
||||
artifacts: ["target/release/swactor-node"]
|
||||
artifacts: ["target/release/swactor"]
|
||||
"#;
|
||||
let ci = parse_ci_yaml(yaml).unwrap();
|
||||
assert_eq!(ci.pipelines.len(), 3);
|
||||
|
|
|
|||
|
|
@ -9,13 +9,13 @@ to stdout (one object per line). Human-readable output goes to stderr.
|
|||
### Launching
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --example investigate_demo
|
||||
cargo run -p dashboard --example investigate_demo
|
||||
```
|
||||
|
||||
Or programmatically against any running runtime:
|
||||
|
||||
```rust
|
||||
use runtime_dashboard::investigate::run_investigate;
|
||||
use dashboard::investigate::run_investigate;
|
||||
run_investigate(runtime_arc, collector_arc)?; // blocks on stdin
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ edition = "2024"
|
|||
|
||||
[dependencies]
|
||||
swactor = { path = "../..", features = ["serde", "tracing"] }
|
||||
swactor-std = { path = "../std", default-features = false }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["registry"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
@ -35,6 +34,6 @@ path = "src/bin/tui.rs"
|
|||
required-features = ["tui"]
|
||||
|
||||
[[bin]]
|
||||
name = "swactor-node"
|
||||
name = "swactor-node-legacy"
|
||||
path = "src/bin/swactor-node.rs"
|
||||
required-features = ["node"]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
# runtime-dashboard
|
||||
# dashboard
|
||||
|
||||
Visual dashboard for the swactor runtime. Provides a live HTTP dashboard, a
|
||||
terminal UI (TUI), trace recording/replay, and an HTTP API for programmatic
|
||||
|
|
@ -16,7 +16,7 @@ runtime investigation.
|
|||
Start the dashboard demo and open it in a browser:
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --example dashboard_demo
|
||||
cargo run -p dashboard --example dashboard_demo
|
||||
```
|
||||
|
||||
Pages:
|
||||
|
|
@ -33,9 +33,9 @@ membership and actor registrations in the directory/cache.
|
|||
A standalone binary that connects to any running dashboard over SSE:
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --features tui --bin swactor-tui
|
||||
cargo run -p dashboard --features tui --bin swactor-tui
|
||||
# or point at a specific endpoint
|
||||
cargo run -p runtime-dashboard --features tui --bin swactor-tui -- http://localhost:9090
|
||||
cargo run -p dashboard --features tui --bin swactor-tui -- http://localhost:9090
|
||||
```
|
||||
|
||||
Views (cycle with Tab):
|
||||
|
|
@ -70,7 +70,7 @@ All examples are run from the workspace root.
|
|||
**HTTP dashboard** — live workload with distribution cluster, Ctrl+C to stop:
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --example dashboard_demo
|
||||
cargo run -p dashboard --example dashboard_demo
|
||||
# http://localhost:9090 — runtime overview
|
||||
# http://localhost:9090/distribution — cluster view
|
||||
```
|
||||
|
|
@ -78,14 +78,14 @@ cargo run -p runtime-dashboard --example dashboard_demo
|
|||
**Benchmarks** — four automated scenarios (~20 s total):
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --example bench_dashboard
|
||||
cargo run -p dashboard --example bench_dashboard
|
||||
# open http://localhost:9090
|
||||
```
|
||||
|
||||
**Record & replay** — records ~10 s of activity, then serves a replay:
|
||||
|
||||
```bash
|
||||
cargo run -p runtime-dashboard --example record_and_replay_demo
|
||||
cargo run -p dashboard --example record_and_replay_demo
|
||||
# live dashboard at http://localhost:9090 during recording
|
||||
# replay dashboard at http://localhost:9091 after recording finishes
|
||||
# Ctrl+C to stop
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ use dashboard::{start_dashboard, DashboardConfig};
|
|||
// ── CLI ──────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "swactor-node", about = "Swactor distributed node")]
|
||||
#[command(name = "swactor-node-legacy", about = "Swactor distributed node (legacy)")]
|
||||
struct Args {
|
||||
/// Transport to use: tcp or iroh
|
||||
#[arg(long, default_value = "tcp")]
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ pub fn enrich_names(stats: &mut RuntimeStats, runtime: &Runtime) {
|
|||
Some(ext) => ext,
|
||||
None => return,
|
||||
};
|
||||
let std_ext = match ext.as_any().downcast_ref::<swactor_std::StdExtension>() {
|
||||
let std_ext = match ext.as_any().downcast_ref::<swactor::std::StdExtension>() {
|
||||
Some(ext) => ext,
|
||||
None => return,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Built-in command handlers for runtime inspection and management.
|
||||
//!
|
||||
//! Extracted from `crates/runtime-dashboard/src/investigate.rs`.
|
||||
//! Extracted from `crates/dashboard/src/investigate.rs`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Datastore stats provider for the runtime dashboard.
|
||||
//!
|
||||
//! The trait returns a pre-serialized JSON string so that `runtime-dashboard`
|
||||
//! The trait returns a pre-serialized JSON string so that `dashboard`
|
||||
//! has no compile-time dependency on `swactor-datastore` (which would create a
|
||||
//! circular dependency since `swactor-datastore[node]` depends on us).
|
||||
//!
|
||||
|
|
|
|||
|
|
@ -13,12 +13,14 @@ shared-types = { path = "../shared-types" }
|
|||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
blake3 = "1"
|
||||
tokio = { version = "1", features = ["rt"] }
|
||||
swactor-streams = { path = "../streams" }
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
clap = { version = "4", features = ["derive"], optional = true }
|
||||
ureq = { version = "2", features = ["json"], optional = true }
|
||||
getrandom = { version = "0.2", optional = true }
|
||||
ctrlc = { version = "3", optional = true }
|
||||
runtime-dashboard = { path = "../runtime-dashboard", optional = true }
|
||||
dashboard = { path = "../dashboard" }
|
||||
toml = { version = "0.8", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
@ -28,14 +30,13 @@ proptest-state-machine = "0.3"
|
|||
tempfile = "3"
|
||||
distribution = { path = "../distribution" }
|
||||
swactor = { path = "../.." }
|
||||
swactor-std = { path = "../std" }
|
||||
ureq = { version = "2", features = ["json"] }
|
||||
tiny_http = "0.12"
|
||||
runtime-dashboard = { path = "../runtime-dashboard" }
|
||||
dashboard = { path = "../dashboard" }
|
||||
stateright = "0.31"
|
||||
|
||||
[features]
|
||||
node = ["dep:tiny_http", "dep:clap", "dep:ctrlc", "dep:runtime-dashboard", "dep:toml"]
|
||||
node = ["dep:tiny_http", "dep:clap", "dep:ctrlc", "dep:toml"]
|
||||
cli = ["dep:clap", "dep:ureq", "dep:getrandom"]
|
||||
|
||||
[[bin]]
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|||
|
||||
use swactor::actor::ActorAddress;
|
||||
use swactor::runtime::{Inbox, Runtime};
|
||||
use swactor_std::RuntimeNaming;
|
||||
use swactor::std::RuntimeNaming;
|
||||
|
||||
use distribution::types::NodeId;
|
||||
use dashboard::datastore_collector::{
|
||||
|
|
@ -521,7 +521,7 @@ impl DatastoreGroup {
|
|||
|
||||
// Spawn StreamListener
|
||||
use crate::actors::stream_listener::StreamListener;
|
||||
use swactor_std::RuntimeNaming;
|
||||
use swactor::std::RuntimeNaming;
|
||||
if let Ok(addr) = self.runtime.spawn(StreamListener::new(self.datastore_addr, stream_manager)) {
|
||||
let _ = self.runtime.register_name("StreamListener", addr);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ pub mod chunking;
|
|||
pub mod storage;
|
||||
pub mod actors;
|
||||
pub mod auth;
|
||||
pub mod blob_transfer;
|
||||
pub mod bridge;
|
||||
pub mod cli;
|
||||
pub mod metrics;
|
||||
#[cfg(feature = "node")]
|
||||
|
|
@ -18,3 +20,4 @@ pub use messages::{BlobStoreMsg, DatastoreNodeMsg, DatastoreResponse, MetadataMs
|
|||
pub use chunking::{chunk_blob, reassemble_blob, verify_integrity, ChunkingError};
|
||||
pub use storage::{StorageBackend, FilesystemBackend, InMemoryBackend};
|
||||
pub use actors::{BlobStoreActor, DatastoreNode, MetadataActor, TransferActor};
|
||||
pub use bridge::{DatastoreAuthConfig, DatastoreGroup, DatastoreGroupConfig, DatastoreNodeFactory};
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use std::sync::Arc;
|
|||
|
||||
use swactor::actor::{ActorAddress, Message};
|
||||
use swactor::runtime::{Inbox, Runtime, RuntimeConfig};
|
||||
use swactor_std::StdExtension;
|
||||
use swactor::std::StdExtension;
|
||||
|
||||
use swactor_datastore::chunking::chunk_blob;
|
||||
use swactor_datastore::messages::{BlobStoreMsg, DatastoreResponse, MetadataMsg};
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use swactor::config::RuntimeConfig;
|
|||
use swactor::runtime::Runtime;
|
||||
use swactor_datastore::bridge::{DatastoreGroup, DatastoreGroupConfig};
|
||||
use swactor_datastore::messages::{DatastoreNodeMsg, DatastoreResponse};
|
||||
use swactor_std::RuntimeNaming;
|
||||
use swactor::std::RuntimeNaming;
|
||||
|
||||
fn make_driver_with_streams() -> IrohDriver {
|
||||
IrohDriver::new(IrohDriverConfig {
|
||||
|
|
@ -31,7 +31,7 @@ fn make_runtime() -> Arc<Runtime> {
|
|||
channel_buffer_size: 2000,
|
||||
..Default::default()
|
||||
})
|
||||
.with_extension(Arc::new(swactor_std::StdExtension::new()));
|
||||
.with_extension(Arc::new(swactor::std::StdExtension::new()));
|
||||
|
||||
let handle = rt.run().expect("start runtime");
|
||||
handle.runtime
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Shared keypair persistence — load or generate an ed25519 keypair on disk.
|
||||
//!
|
||||
//! Reused by `swactor-node`, `store_node`, and xtask tooling.
|
||||
//! Reused by the `node` crate, `store_node`, and xtask tooling.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
//! Serializable snapshot of a `DistributedNode`'s state.
|
||||
//!
|
||||
//! Used by the runtime-dashboard to display distribution monitoring data
|
||||
//! Used by the dashboard to display distribution monitoring data
|
||||
//! for a single node without reaching out to other nodes.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
[package]
|
||||
name = "swactor-node"
|
||||
name = "node"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
swactor = { path = "../..", features = ["serde", "tracing", "transport"] }
|
||||
swactor-std = { path = "../std" }
|
||||
dashboard = { path = "../dashboard", features = ["distribution"] }
|
||||
swactor-datastore = { path = "../datastore" }
|
||||
distribution = { path = "../distribution" }
|
||||
99
crates/node/README.md
Normal file
99
crates/node/README.md
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
# node
|
||||
|
||||
The `node` crate produces the `swactor` binary — the batteries-included entry point for running a swactor node. It composes the actor runtime, SWIM-based cluster membership, content-addressed datastore, data streams, an HTTP dashboard, and an optional embedded relay server into a single process.
|
||||
|
||||
Run `swactor --help` for full CLI usage.
|
||||
|
||||
## What a Default Node Does
|
||||
|
||||
### Identity
|
||||
|
||||
Every node has a persistent Ed25519 keypair stored at `~/.swactor/identity/node.key.json`. This is the node's identity across restarts — deleting it makes the node appear as a new peer to the cluster. The keypair's public key doubles as the node ID (used in SWIM, peer auth, and invite codes). A deterministic human-readable name (e.g. `swift-falcon`) is derived from the key so you can tell nodes apart in logs and the dashboard.
|
||||
|
||||
### Networking
|
||||
|
||||
The default transport is **iroh** (QUIC over UDP). Nodes find each other via invite codes — base58-encoded public keys exchanged out-of-band. `swactor join <code>` adds a peer to the allow-list and sets it as the seed node for the next startup.
|
||||
|
||||
Once connected, **SWIM protocol** handles cluster membership: protocol probes every 500ms, 600ms probe timeout (tuned for relay round-trips), 2 indirect probes, 4s suspicion window. All intervals are in ticks where **1 tick = 100ms** (the main loop period).
|
||||
|
||||
**Peer auth** operates in two modes: open (no `peers_file`) or allow-list (`peers.json`). In allow-list mode, SWIM messages from unknown nodes are dropped at the transport layer. New peers can be added via `swactor join` or the dashboard UI, both of which hot-update the allow-list.
|
||||
|
||||
### Relay
|
||||
|
||||
Nodes with a public IP auto-promote to embedded relay servers (port 3340). Candidacy is evaluated at startup: the node checks its outbound IP is non-RFC1918 and the relay port is bindable. Relay URLs are announced via SWIM gossip so other nodes discover them automatically. Nodes behind NAT use relays for indirect connectivity — this is why the probe timeout is 600ms instead of the typical 300ms.
|
||||
|
||||
### Storage
|
||||
|
||||
The **datastore** is a content-addressed, chunked store. Default config persists to `~/.swactor/datastore/`. Auth is enabled by default (ACL files in `~/.swactor/auth/`). The datastore runs as a group of actors inside the runtime and is driven by the main tick loop — GC runs every 1000 ticks (~100s) and dissemination every 50 ticks (~5s). A `StreamManager` actor bridges iroh QUIC streams into the datastore for bulk data transfer between nodes.
|
||||
|
||||
Disable with `--no-datastore`. Use `--storage-path` to change location, or omit it from config for in-memory only.
|
||||
|
||||
### Observability
|
||||
|
||||
An HTTP dashboard serves on **port 9090**. It exposes runtime stats, cluster membership state, tracing output, and a peer management UI (add/remove peers). The dashboard receives a snapshot of the distribution layer every tick.
|
||||
|
||||
### State & Lifecycle
|
||||
|
||||
All persistent state lives under `~/.swactor/`. Deleting this directory fully resets the node (new identity, empty cluster, empty datastore). The node shuts down cleanly on SIGINT (Ctrl+C). `swactor install` copies the binary to `~/.swactor/bin/swactor` and registers it as a system service (systemd user unit, OpenRC/sysvinit init script, or `@reboot` crontab depending on the host).
|
||||
|
||||
## Exposed Ports
|
||||
|
||||
| Port | Service | Configurable via |
|
||||
|------|---------|-----------------|
|
||||
| 9090 | HTTP dashboard | `--dashboard-port` |
|
||||
| 3340 | Embedded relay (if eligible) | `--relay-port` |
|
||||
|
||||
## Data Directory (`~/.swactor/`)
|
||||
|
||||
```
|
||||
~/.swactor/
|
||||
├── node.toml # Node configuration
|
||||
├── peers.json # Peer allow-list
|
||||
├── identity/
|
||||
│ └── node.key.json # Persistent Ed25519 keypair
|
||||
├── datastore/ # Content-addressed chunk storage
|
||||
├── auth/ # ACL and owner key files
|
||||
└── bin/
|
||||
└── swactor # Installed binary (after `swactor install`)
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
CLI Args + TOML Config
|
||||
│
|
||||
▼
|
||||
Config Resolution (CLI > config > defaults)
|
||||
│
|
||||
▼
|
||||
Identity (Ed25519 Keypair) ──► Node Name
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Actor Runtime │
|
||||
│ (2 threads, StdExtension, stats hook) │
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────────────┐ │
|
||||
│ │ StreamManager │ │ Datastore Group │ │
|
||||
│ │ (actor) │◄─┤ (store, gateway, │ │
|
||||
│ │ │ │ bridge actors) │ │
|
||||
│ └──────────────┘ └──────────────────────┘ │
|
||||
└──────────────┬──────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────┐
|
||||
│ Distribution Driver (iroh) │
|
||||
│ SWIM probes, gossip, relay │
|
||||
└──────────────┬───────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────────┐
|
||||
│ HTTP Dashboard │
|
||||
│ :9090 — stats, tracing, peers │
|
||||
└──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
Main Tick Loop (100ms)
|
||||
recv → tick → streams → joins →
|
||||
heartbeats → snapshot → datastore
|
||||
```
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
//! TOML configuration file support for swactor-node.
|
||||
//! TOML configuration file support for the swactor node binary.
|
||||
//!
|
||||
//! CLI flags take precedence over config file values, which take
|
||||
//! precedence over compiled defaults.
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
//! swactor-node — unified distributed node with dashboard and datastore.
|
||||
//! Swactor node — unified distributed node with dashboard and datastore.
|
||||
//!
|
||||
//! Combines distribution, runtime dashboard, and content-addressed datastore
|
||||
//! into a single batteries-included binary. Datastore is on by default
|
||||
|
|
@ -495,7 +495,7 @@ fn main() {
|
|||
channel_buffer_size: 2000,
|
||||
..Default::default()
|
||||
})
|
||||
.with_extension(Arc::new(swactor_std::StdExtension::new()));
|
||||
.with_extension(Arc::new(swactor::std::StdExtension::new()));
|
||||
rt.set_stats_hook(collector.clone());
|
||||
|
||||
let handle = rt.run().expect("failed to start runtime");
|
||||
|
|
@ -713,7 +713,7 @@ fn run_iroh(
|
|||
) {
|
||||
use distribution::iroh_driver::{IrohDriver, IrohDriverConfig};
|
||||
use iroh::{RelayMode, SecretKey};
|
||||
use swactor_std::RuntimeNaming;
|
||||
use swactor::std::RuntimeNaming;
|
||||
|
||||
// Evaluate relay candidacy and determine embedded relay bind address
|
||||
#[cfg(feature = "relay")]
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
[package]
|
||||
name = "swactor-std"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[features]
|
||||
default = ["getrandom"]
|
||||
getrandom = ["dep:getrandom", "swactor/getrandom"]
|
||||
wasm = ["swactor/wasm"]
|
||||
|
||||
[dependencies]
|
||||
swactor = { path = "../..", default-features = false }
|
||||
getrandom = { version = "0.2", optional = true }
|
||||
|
|
@ -5,7 +5,6 @@ edition = "2024"
|
|||
|
||||
[dependencies]
|
||||
swactor = { path = "../..", features = ["serde"] }
|
||||
swactor-std = { path = "../std" }
|
||||
shared-types = { path = "../shared-types" }
|
||||
distribution = { path = "../distribution" }
|
||||
crossbeam-queue = "0.3.12"
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@
|
|||
|
||||
use swactor::actor::{ActorAddress, Ctx};
|
||||
use swactor::runtime::Runtime;
|
||||
use swactor_std::CtxNaming;
|
||||
use swactor_std::RuntimeNaming;
|
||||
use swactor::std::CtxNaming;
|
||||
use swactor::std::RuntimeNaming;
|
||||
|
||||
use crate::messages::StreamManagerMsg;
|
||||
use crate::types::{StreamConfig, StreamError, StreamId, StreamMode};
|
||||
|
|
|
|||
|
|
@ -1,76 +0,0 @@
|
|||
# Connectome Analysis
|
||||
|
||||
The connectome analysis applies spectral graph theory to the codebase's internal dependency DAG, producing quantitative coupling metrics and visual dashboards.
|
||||
|
||||
## What it measures
|
||||
|
||||
The tool parses `deps.dot` (a GraphViz DOT file describing struct/trait dependencies between modules) and computes:
|
||||
|
||||
- **Laplacian eigenvalue spectrum** -- encodes the graph's overall connectivity structure
|
||||
- **Fiedler vector** -- the optimal spectral bisection of the dependency graph, revealing natural module clusters
|
||||
- **Module coupling matrix** -- directed edge counts between every pair of modules
|
||||
- **Connectome Complexity Index (CCI)** -- a single 0-1 score combining five sub-metrics:
|
||||
|
||||
| Sub-metric | Weight | What it captures |
|
||||
|---|---|---|
|
||||
| Algebraic connectivity (lambda_2/n) | 25% | How tightly connected the graph is |
|
||||
| Spectral entropy (H/log2(k)) | 25% | How uniformly distributed coupling is across eigenvalues |
|
||||
| Edge density (\|E\|/n(n-1)) | 15% | Raw ratio of edges to possible edges |
|
||||
| Cross-module coupling ratio | 20% | Fraction of edges that cross module boundaries |
|
||||
| Spectral radius (rho/(n-1)) | 15% | Maximum hub concentration |
|
||||
|
||||
### Interpreting CCI
|
||||
|
||||
| CCI range | Label | Meaning |
|
||||
|---|---|---|
|
||||
| < 0.30 | LOW | Well-decomposed architecture |
|
||||
| 0.30 - 0.60 | MODERATE | Typical well-structured codebase |
|
||||
| > 0.60 | HIGH | Consider reviewing module boundaries |
|
||||
|
||||
## Running
|
||||
|
||||
From the project root:
|
||||
|
||||
```sh
|
||||
# Default: outputs to docs/connectome/
|
||||
python tools/spectral/spectral_analysis.py deps.dot
|
||||
|
||||
# Custom output directory
|
||||
python tools/spectral/spectral_analysis.py deps.dot -o path/to/output
|
||||
|
||||
# Also emit JSON metrics
|
||||
python tools/spectral/spectral_analysis.py deps.dot --json
|
||||
|
||||
# Text report only (skip matplotlib PNG)
|
||||
python tools/spectral/spectral_analysis.py deps.dot --no-plots
|
||||
```
|
||||
|
||||
### Prerequisites
|
||||
|
||||
The script requires numpy, scipy, and matplotlib (for the PNG dashboard). These are available in the project's `.venv`:
|
||||
|
||||
```sh
|
||||
source .venv/bin/activate
|
||||
python tools/spectral/spectral_analysis.py deps.dot
|
||||
```
|
||||
|
||||
## Output files
|
||||
|
||||
All output goes to `docs/connectome/` by default:
|
||||
|
||||
| File | Description |
|
||||
|---|---|
|
||||
| `connectome_report.txt` | Full text report with eigenvalues, Fiedler bisection, coupling matrix, and CCI breakdown |
|
||||
| `connectome_dashboard.html` | Interactive HTML dashboard with zoomable DAG, eigenvalue plot, Fiedler bar chart, and coupling heatmap |
|
||||
| `connectome_dashboard.png` | Static PNG snapshot of the spectral dashboard (dark theme, 16x12 @ 150 DPI) |
|
||||
| `connectome_metrics.json` | Machine-readable metrics (only with `--json` flag) |
|
||||
|
||||
## Regenerating deps.dot
|
||||
|
||||
The DOT file is the input to the spectral analysis. To regenerate it from source:
|
||||
|
||||
```sh
|
||||
cargo run --manifest-path tools/depgraph/Cargo.toml -- --src-dir src/ --output deps
|
||||
```
|
||||
|
||||
Then re-run the spectral analysis to update the connectome report.
|
||||
|
|
@ -1,743 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html><head>
|
||||
<meta charset="utf-8">
|
||||
<title>swactor — dependency analysis</title>
|
||||
<style>
|
||||
* { margin:0; padding:0; box-sizing:border-box; }
|
||||
body { background:#1a1a2e; color:#e0e0e0; font-family:system-ui,-apple-system,sans-serif; overflow:hidden; }
|
||||
|
||||
/* ─── Tab bar ───────────────────────────────────────────────────────────── */
|
||||
.tab-bar { display:flex; align-items:center; height:42px; background:#12122a;
|
||||
border-bottom:1px solid #2a2a5a; padding:0 16px; gap:8px; }
|
||||
.tab-bar .title { font-size:14px; font-weight:700; letter-spacing:0.5px; margin-right:18px;
|
||||
color:#8ab4f8; white-space:nowrap; }
|
||||
.tab { background:none; border:none; color:#888; font-size:13px; padding:8px 16px;
|
||||
cursor:pointer; border-bottom:2px solid transparent; transition:color 0.15s; }
|
||||
.tab:hover { color:#ccc; }
|
||||
.tab.active { color:#e0e0e0; border-bottom-color:#4fc3f7; }
|
||||
|
||||
/* ─── Tab content ───────────────────────────────────────────────────────── */
|
||||
.tab-content { display:none; }
|
||||
.tab-content.active { display:block; }
|
||||
|
||||
/* ─── DAG tab ───────────────────────────────────────────────────────────── */
|
||||
#tab-dag { height:calc(100vh - 42px); overflow:hidden; position:relative; }
|
||||
#dag-viewport { width:100%; height:100%; cursor:grab; }
|
||||
#dag-viewport:active { cursor:grabbing; }
|
||||
#dag-viewport svg { display:block; }
|
||||
#dag-controls { position:absolute; top:12px; left:12px; z-index:10;
|
||||
background:rgba(30,30,60,0.9); border-radius:8px; padding:10px 14px;
|
||||
color:#ccc; font-size:13px; backdrop-filter:blur(8px); }
|
||||
#dag-controls button { background:#333; color:#fff; border:1px solid #555;
|
||||
border-radius:4px; padding:4px 10px; cursor:pointer; margin:0 3px; }
|
||||
#dag-controls button:hover { background:#555; }
|
||||
#dag-loading { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);
|
||||
color:#ccc; font-size:18px; }
|
||||
|
||||
/* ─── Spectral tab ──────────────────────────────────────────────────────── */
|
||||
#tab-spectral { overflow-y:auto; max-height:calc(100vh - 42px); }
|
||||
|
||||
.grid { display:grid; grid-template-columns:1fr 1fr; grid-template-rows:auto auto;
|
||||
gap:16px; padding:16px 20px 20px; max-width:1600px; margin:0 auto; }
|
||||
|
||||
.panel { background:#16213e; border-radius:10px; border:1px solid #2a2a5a;
|
||||
padding:16px; position:relative; min-height:100px; }
|
||||
.panel h2 { font-size:14px; font-weight:600; margin-bottom:10px; color:#8ab4f8;
|
||||
display:flex; align-items:center; gap:8px; }
|
||||
.panel h2 .icon { font-size:16px; }
|
||||
.panel svg { width:100%; display:block; }
|
||||
|
||||
.tooltip { position:fixed; background:rgba(22,33,62,0.96); border:1px solid #4fc3f7;
|
||||
border-radius:6px; padding:8px 12px; font-size:12px; pointer-events:none;
|
||||
z-index:100; backdrop-filter:blur(8px); max-width:300px;
|
||||
box-shadow:0 4px 20px rgba(0,0,0,0.4); display:none; }
|
||||
.tooltip .tt-label { font-weight:600; color:#4fc3f7; }
|
||||
.tooltip .tt-val { color:#e0e0e0; }
|
||||
|
||||
svg text { user-select:none; }
|
||||
|
||||
/* Metrics panel */
|
||||
.metrics-grid { display:grid; grid-template-columns:1fr 1fr; gap:8px 20px; }
|
||||
.metric-item { display:flex; justify-content:space-between; font-size:12px;
|
||||
padding:4px 8px; border-radius:4px; }
|
||||
.metric-item:hover { background:rgba(79,195,247,0.08); }
|
||||
.metric-label { opacity:0.7; }
|
||||
.metric-value { font-weight:600; font-family:'SF Mono',monospace; }
|
||||
.cci-box { grid-column:1/-1; text-align:center; margin-top:10px; padding:14px;
|
||||
border-radius:8px; background:rgba(0,0,0,0.25); border:1px solid #333; }
|
||||
.cci-score { font-size:32px; font-weight:700; }
|
||||
.cci-label { font-size:14px; margin-top:2px; }
|
||||
.cci-desc { font-size:11px; opacity:0.6; margin-top:4px; }
|
||||
|
||||
.sub-header { font-size:11px; font-weight:600; text-transform:uppercase;
|
||||
letter-spacing:1px; opacity:0.4; margin:8px 0 4px; grid-column:1/-1; }
|
||||
|
||||
/* Heatmap */
|
||||
.hm-cell { cursor:pointer; transition:opacity 0.15s; }
|
||||
.hm-cell:hover { opacity:0.8; stroke:#4fc3f7; stroke-width:2; }
|
||||
|
||||
/* Cohesion / heatmap bars */
|
||||
.fi-bar { cursor:pointer; transition:opacity 0.15s; }
|
||||
.fi-bar:hover { opacity:0.85; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="tab-bar">
|
||||
<div class="title">swactor — dependency analysis</div>
|
||||
<button class="tab active" data-tab="spectral">Spectral Analysis</button>
|
||||
<button class="tab" data-tab="dag">Dependency DAG</button>
|
||||
</div>
|
||||
|
||||
<div class="tab-content" id="tab-dag">
|
||||
<div id="dag-controls">
|
||||
<button onclick="zoomIn()">+</button>
|
||||
<button onclick="zoomOut()">−</button>
|
||||
<button onclick="resetView()">fit</button>
|
||||
<span style="margin-left:8px;opacity:0.6">scroll to zoom · drag to pan · click node to focus</span>
|
||||
</div>
|
||||
<div id="dag-viewport"></div>
|
||||
<div id="dag-loading">Loading Graphviz…</div>
|
||||
</div>
|
||||
|
||||
<div class="tab-content active" id="tab-spectral">
|
||||
<div class="grid">
|
||||
<div class="panel" id="panel-structural">
|
||||
<h2><span class="icon">◉</span> Structural Properties</h2>
|
||||
<div id="structural-content"></div>
|
||||
</div>
|
||||
|
||||
<div class="panel" id="panel-cohesion">
|
||||
<h2><span class="icon">▨</span> Module Cohesion</h2>
|
||||
<svg id="svg-cohesion"></svg>
|
||||
</div>
|
||||
|
||||
<div class="panel" id="panel-heatmap">
|
||||
<h2><span class="icon">▦</span> Module Coupling (directed edge counts)</h2>
|
||||
<svg id="svg-heatmap"></svg>
|
||||
</div>
|
||||
|
||||
<div class="panel" id="panel-metrics">
|
||||
<h2><span class="icon">∑</span> Complexity Metrics</h2>
|
||||
<div id="metrics-content"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tooltip" id="tooltip"></div>
|
||||
|
||||
<!-- ─── Script 1: synchronous — data + tab switching + spectral panels ─── -->
|
||||
<script>
|
||||
// ─── Data ──────────────────────────────────────────────────────────────────
|
||||
const DATA = {"structural": {"avg_degree": 2.49, "max_fan_in": 16, "max_fan_in_node": "ActorAddress", "max_fan_out": 18, "max_fan_out_node": "Runtime", "dag_depth": 7, "clustering_coeff": 0.2668, "avg_module_cohesion": 0.302, "avg_module_size": 4.3}, "cohesion": [{"module": "actor", "cohesion": 0.214, "size": 7}, {"module": "worker", "cohesion": 0.167, "size": 4}, {"module": "channel", "cohesion": 0.5, "size": 3}, {"module": "config", "cohesion": 0.5, "size": 2}, {"module": "delivery", "cohesion": 0.167, "size": 7}, {"module": "stats", "cohesion": 0.25, "size": 5}, {"module": "runtime", "cohesion": 0.5, "size": 3}, {"module": "transport", "cohesion": 0.119, "size": 7}], "coupling": {"modules": ["actor", "worker", "channel", "error", "config", "delivery", "stats", "runtime", "transport"], "matrix": [[9.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0], [9.0, 2.0, 1.0, 1.0, 0.0, 5.0, 3.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0], [5.0, 0.0, 1.0, 2.0, 1.0, 7.0, 0.0, 0.0, 2.0], [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.0, 0.0, 0.0], [4.0, 1.0, 2.0, 1.0, 1.0, 5.0, 2.0, 3.0, 2.0], [3.0, 0.0, 2.0, 4.0, 0.0, 0.0, 0.0, 0.0, 5.0]]}, "metrics": {"n_nodes": 39, "n_edges": 97, "n_modules": 9, "connected_components": 2, "algebraic_connectivity": 0.0, "normalized_algebraic_connectivity": 0.0, "spectral_entropy": 4.7287, "normalized_spectral_entropy": 0.9077, "edge_density": 0.0655, "cross_module_ratio": 0.6392, "spectral_radius": 7.9636, "normalized_spectral_radius": 0.2096, "cci": 0.396, "cci_label": "MODERATE", "cci_color": "#ff9800", "cci_desc": "typical well-structured codebase"}, "module_colors": {"actor": "#1565c0", "worker": "#c62828", "channel": "#e65100", "error": "#7b1fa2", "config": "#2e7d32", "delivery": "#f9a825", "stats": "#00838f", "runtime": "#d84315", "transport": "#1565c0"}};
|
||||
const { structural, cohesion, coupling, metrics, module_colors } = DATA;
|
||||
|
||||
// ─── Tab switching ─────────────────────────────────────────────────────────
|
||||
document.querySelectorAll('.tab').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab').forEach(b => b.classList.remove('active'));
|
||||
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
|
||||
btn.classList.add('active');
|
||||
document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
|
||||
if (btn.dataset.tab === 'dag') {
|
||||
window.dispatchEvent(new Event('dag-visible'));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tooltip ───────────────────────────────────────────────────────────────
|
||||
const TT = document.getElementById('tooltip');
|
||||
function showTip(evt, html) {
|
||||
TT.innerHTML = html;
|
||||
TT.style.display = 'block';
|
||||
const x = evt.clientX + 14, y = evt.clientY - 10;
|
||||
TT.style.left = Math.min(x, window.innerWidth - TT.offsetWidth - 20) + 'px';
|
||||
TT.style.top = Math.min(y, window.innerHeight - TT.offsetHeight - 20) + 'px';
|
||||
}
|
||||
function hideTip() { TT.style.display = 'none'; }
|
||||
|
||||
function modColor(mod) { return module_colors[mod] || '#9e9e9e'; }
|
||||
|
||||
// ─── Structural Properties ────────────────────────────────────────────────
|
||||
(function() {
|
||||
const c = document.getElementById('structural-content');
|
||||
const s = structural;
|
||||
c.innerHTML = `
|
||||
<div class="metrics-grid">
|
||||
<div class="sub-header">Density & Depth</div>
|
||||
<div class="metric-item"><span class="metric-label">Edges/node (avg degree)</span><span class="metric-value">${s.avg_degree}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">DAG depth</span><span class="metric-value">${s.dag_depth}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Clustering coefficient</span><span class="metric-value">${s.clustering_coeff}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Avg module size</span><span class="metric-value">${s.avg_module_size}</span></div>
|
||||
|
||||
<div class="sub-header">Dependency Hotspots</div>
|
||||
<div class="metric-item"><span class="metric-label">Max fan-in</span><span class="metric-value">${s.max_fan_in} ← ${s.max_fan_in_node}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Max fan-out</span><span class="metric-value">${s.max_fan_out} → ${s.max_fan_out_node}</span></div>
|
||||
|
||||
<div class="sub-header">Cohesion</div>
|
||||
<div class="metric-item"><span class="metric-label">Avg module cohesion</span><span class="metric-value">${s.avg_module_cohesion}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Cross-module ratio</span><span class="metric-value">${(metrics.cross_module_ratio*100).toFixed(1)}%</span></div>
|
||||
</div>
|
||||
`;
|
||||
})();
|
||||
|
||||
// ─── Module Cohesion ──────────────────────────────────────────────────────
|
||||
(function() {
|
||||
const svg = document.getElementById('svg-cohesion');
|
||||
const n = cohesion.length;
|
||||
if (n === 0) return;
|
||||
const barH = Math.max(20, Math.min(36, 300/n));
|
||||
const W = 560, H = Math.max(200, n*barH + 60), M = {t:10,r:30,b:30,l:120};
|
||||
const w = W-M.l-M.r, h = H-M.t-M.b;
|
||||
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
|
||||
|
||||
const xScale = v => M.l + v * w;
|
||||
const yScale = i => M.t + (i/n) * h + barH/2;
|
||||
|
||||
// Background grid
|
||||
for (const tick of [0.25, 0.5, 0.75, 1.0]) {
|
||||
const x = xScale(tick);
|
||||
const line = document.createElementNS('http://www.w3.org/2000/svg','line');
|
||||
Object.entries({x1:x,x2:x,y1:M.t,y2:M.t+h,stroke:'#2a2a5a','stroke-width':0.5}).forEach(([k,v])=>line.setAttribute(k,v));
|
||||
svg.appendChild(line);
|
||||
const txt = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
txt.setAttribute('x', x); txt.setAttribute('y', H-8);
|
||||
txt.setAttribute('text-anchor','middle'); txt.setAttribute('fill','#666'); txt.setAttribute('font-size','10');
|
||||
txt.textContent = (tick*100).toFixed(0) + '%';
|
||||
svg.appendChild(txt);
|
||||
}
|
||||
|
||||
// Average line
|
||||
const avgX = xScale(structural.avg_module_cohesion);
|
||||
const avgLine = document.createElementNS('http://www.w3.org/2000/svg','line');
|
||||
Object.entries({x1:avgX,x2:avgX,y1:M.t,y2:M.t+h,stroke:'#ff4444','stroke-width':1.5,'stroke-dasharray':'5,3','stroke-opacity':0.7}).forEach(([k,v])=>avgLine.setAttribute(k,v));
|
||||
svg.appendChild(avgLine);
|
||||
const avgLbl = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
avgLbl.setAttribute('x', avgX+4); avgLbl.setAttribute('y', M.t+10);
|
||||
avgLbl.setAttribute('fill','#ff4444'); avgLbl.setAttribute('font-size','9'); avgLbl.setAttribute('opacity','0.8');
|
||||
avgLbl.textContent = 'avg';
|
||||
svg.appendChild(avgLbl);
|
||||
|
||||
cohesion.forEach((d, i) => {
|
||||
const barW = Math.max(d.cohesion * w, 2);
|
||||
const y = yScale(i) - barH*0.35;
|
||||
const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
|
||||
rect.setAttribute('x', M.l); rect.setAttribute('y', y);
|
||||
rect.setAttribute('width', barW); rect.setAttribute('height', barH*0.7);
|
||||
rect.setAttribute('rx', 3);
|
||||
rect.setAttribute('fill', modColor(d.module));
|
||||
rect.setAttribute('opacity', 0.85);
|
||||
rect.classList.add('fi-bar');
|
||||
rect.addEventListener('mousemove', e => showTip(e,
|
||||
`<span class="tt-label">${d.module}</span><br>` +
|
||||
`Types: <span class="tt-val">${d.size}</span><br>` +
|
||||
`Cohesion: <span class="tt-val">${(d.cohesion*100).toFixed(1)}%</span>`
|
||||
));
|
||||
rect.addEventListener('mouseleave', hideTip);
|
||||
svg.appendChild(rect);
|
||||
|
||||
// Value label on bar
|
||||
const valTxt = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
valTxt.setAttribute('x', M.l + barW + 6); valTxt.setAttribute('y', yScale(i)+4);
|
||||
valTxt.setAttribute('fill','#ccc'); valTxt.setAttribute('font-size','10'); valTxt.setAttribute('font-weight','600');
|
||||
valTxt.textContent = (d.cohesion*100).toFixed(0) + '%';
|
||||
svg.appendChild(valTxt);
|
||||
|
||||
// Module label
|
||||
const txt = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
txt.setAttribute('x', M.l-8); txt.setAttribute('y', yScale(i)+4);
|
||||
txt.setAttribute('text-anchor','end'); txt.setAttribute('fill', modColor(d.module));
|
||||
txt.setAttribute('font-size','11'); txt.setAttribute('font-weight','600');
|
||||
txt.textContent = `${d.module} (${d.size})`;
|
||||
svg.appendChild(txt);
|
||||
});
|
||||
})();
|
||||
|
||||
// ─── Module Coupling Heatmap ───────────────────────────────────────────────
|
||||
(function() {
|
||||
const mods = coupling.modules;
|
||||
const mat = coupling.matrix;
|
||||
const n = mods.length;
|
||||
const svg = document.getElementById('svg-heatmap');
|
||||
const cellSz = Math.min(55, 400/n);
|
||||
const M = {t:10,r:60,b:80,l:100};
|
||||
const W = M.l + n*cellSz + M.r, H = M.t + n*cellSz + M.b;
|
||||
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
|
||||
|
||||
const maxVal = Math.max(...mat.flat(), 1);
|
||||
|
||||
// Color scale: 0=transparent dark, max=deep red
|
||||
function heatColor(v) {
|
||||
if (v === 0) return '#1a1a2e';
|
||||
const t = v / maxVal;
|
||||
const r = Math.round(40 + 215*t);
|
||||
const g = Math.round(30 + 40*(1-t));
|
||||
const b = Math.round(50*(1-t));
|
||||
return `rgb(${r},${g},${b})`;
|
||||
}
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
// Row labels
|
||||
const rl = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
rl.setAttribute('x', M.l-8); rl.setAttribute('y', M.t + i*cellSz + cellSz/2 + 4);
|
||||
rl.setAttribute('text-anchor','end'); rl.setAttribute('fill', modColor(mods[i]));
|
||||
rl.setAttribute('font-size','11'); rl.setAttribute('font-weight','600');
|
||||
rl.textContent = mods[i];
|
||||
svg.appendChild(rl);
|
||||
|
||||
// Column labels
|
||||
const cl = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
cl.setAttribute('x', M.l + i*cellSz + cellSz/2);
|
||||
cl.setAttribute('y', M.t + n*cellSz + 16);
|
||||
cl.setAttribute('text-anchor','end'); cl.setAttribute('fill', modColor(mods[i]));
|
||||
cl.setAttribute('font-size','11'); cl.setAttribute('font-weight','600');
|
||||
cl.setAttribute('transform', `rotate(-45, ${M.l + i*cellSz + cellSz/2}, ${M.t + n*cellSz + 16})`);
|
||||
cl.textContent = mods[i];
|
||||
svg.appendChild(cl);
|
||||
|
||||
for (let j = 0; j < n; j++) {
|
||||
const v = mat[i][j];
|
||||
const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
|
||||
rect.setAttribute('x', M.l + j*cellSz + 1);
|
||||
rect.setAttribute('y', M.t + i*cellSz + 1);
|
||||
rect.setAttribute('width', cellSz-2); rect.setAttribute('height', cellSz-2);
|
||||
rect.setAttribute('rx', 3);
|
||||
rect.setAttribute('fill', heatColor(v));
|
||||
rect.classList.add('hm-cell');
|
||||
rect.addEventListener('mousemove', e => showTip(e,
|
||||
`<span class="tt-label">${mods[i]} → ${mods[j]}</span><br>` +
|
||||
`Edges: <span class="tt-val">${v}</span>` +
|
||||
(i !== j ? '<br><span style="opacity:0.6">cross-module</span>' : '<br><span style="opacity:0.6">intra-module</span>')
|
||||
));
|
||||
rect.addEventListener('mouseleave', hideTip);
|
||||
svg.appendChild(rect);
|
||||
|
||||
// Cell text
|
||||
if (v > 0) {
|
||||
const txt = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
txt.setAttribute('x', M.l + j*cellSz + cellSz/2);
|
||||
txt.setAttribute('y', M.t + i*cellSz + cellSz/2 + 4);
|
||||
txt.setAttribute('text-anchor','middle'); txt.setAttribute('font-size','11');
|
||||
txt.setAttribute('font-weight','700'); txt.setAttribute('pointer-events','none');
|
||||
txt.setAttribute('fill', v > maxVal*0.5 ? '#fff' : '#ccc');
|
||||
txt.textContent = v;
|
||||
svg.appendChild(txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Axis labels
|
||||
const srcL = document.createElementNS('http://www.w3.org/2000/svg','text');
|
||||
srcL.setAttribute('x', 10); srcL.setAttribute('y', M.t + n*cellSz/2);
|
||||
srcL.setAttribute('text-anchor','middle'); srcL.setAttribute('fill','#666');
|
||||
srcL.setAttribute('font-size','10');
|
||||
srcL.setAttribute('transform', `rotate(-90,10,${M.t + n*cellSz/2})`);
|
||||
srcL.textContent = 'source module';
|
||||
svg.appendChild(srcL);
|
||||
})();
|
||||
|
||||
// ─── Metrics Panel ─────────────────────────────────────────────────────────
|
||||
(function() {
|
||||
const c = document.getElementById('metrics-content');
|
||||
const mm = metrics;
|
||||
c.innerHTML = `
|
||||
<div class="metrics-grid">
|
||||
<div class="sub-header">Graph</div>
|
||||
<div class="metric-item"><span class="metric-label">Nodes</span><span class="metric-value">${mm.n_nodes}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Directed edges</span><span class="metric-value">${mm.n_edges}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Modules</span><span class="metric-value">${mm.n_modules}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Components</span><span class="metric-value">${mm.connected_components}</span></div>
|
||||
|
||||
<div class="sub-header">Spectral</div>
|
||||
<div class="metric-item"><span class="metric-label">λ<sub>2</sub> (alg. connectivity)</span><span class="metric-value">${mm.algebraic_connectivity}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">λ<sub>2</sub>/n (normalized)</span><span class="metric-value">${mm.normalized_algebraic_connectivity}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Spectral entropy</span><span class="metric-value">${mm.spectral_entropy}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Norm. entropy</span><span class="metric-value">${mm.normalized_spectral_entropy}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Spectral radius</span><span class="metric-value">${mm.spectral_radius}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Norm. radius</span><span class="metric-value">${mm.normalized_spectral_radius}</span></div>
|
||||
|
||||
<div class="sub-header">Coupling</div>
|
||||
<div class="metric-item"><span class="metric-label">Edge density</span><span class="metric-value">${mm.edge_density}</span></div>
|
||||
<div class="metric-item"><span class="metric-label">Cross-module ratio</span><span class="metric-value">${(mm.cross_module_ratio*100).toFixed(1)}%</span></div>
|
||||
|
||||
<div class="cci-box">
|
||||
<div class="cci-score" style="color:${mm.cci_color}">CCI = ${mm.cci}</div>
|
||||
<div class="cci-label" style="color:${mm.cci_color}">${mm.cci_label}</div>
|
||||
<div class="cci-desc">${mm.cci_desc}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
})();
|
||||
</script>
|
||||
|
||||
<!-- ─── Script 2: module — viz-js DAG rendering (async) ─────────────────── -->
|
||||
<script type="module">
|
||||
import { instance } from 'https://cdn.jsdelivr.net/npm/@viz-js/viz@3.11.0/lib/viz-standalone.mjs';
|
||||
|
||||
const DOT_SOURCE = `digraph swactor {
|
||||
rankdir=LR;
|
||||
fontname="Helvetica";
|
||||
fontsize=14;
|
||||
node [fontname="Helvetica", fontsize=11, style=filled, shape=record];
|
||||
edge [fontname="Helvetica", fontsize=9];
|
||||
label="swactor — internal dependency DAG";
|
||||
labelloc=t;
|
||||
compound=true;
|
||||
newrank=true;
|
||||
splines=ortho;
|
||||
|
||||
subgraph cluster_actor {
|
||||
label="actor";
|
||||
style="rounded,filled"; fillcolor="#e3f2fd"; color="#1565c0";
|
||||
Message [label="{«trait» Message}", fillcolor="#bbdefb"];
|
||||
ActorInterface [label="{«trait» ActorInterface|Incoming(Message)\\nResponse(Message)\\nhandle((&self, &Ctx, Self::Incoming))}", fillcolor="#bbdefb"];
|
||||
ActorAddress [label="{ActorAddress|0: [u8; ..]}", fillcolor="#bbdefb"];
|
||||
Actor [label="{Actor|0: A}", fillcolor="#bbdefb"];
|
||||
AnyActor [label="{«trait» AnyActor|handle_any((&self, &Ctx, Box\\<dyn Any + Send\\>))}", fillcolor="#bbdefb"];
|
||||
ContextInner [label="{«trait» ContextInner|send_any((&self, ActorAddress, Box\\<dyn Any + Send\\>) → Result\\<(), Error\\>)\\nspawn_any((&self, ActorAddress, Box\\<dyn AnyActor\\>) → Result\\<(), Error\\>)}", fillcolor="#bbdefb"];
|
||||
Ctx [label="{Ctx|inner: &'a dyn ContextInner\\nself_addr: ActorAddress}", fillcolor="#bbdefb"];
|
||||
}
|
||||
subgraph cluster_worker {
|
||||
label="worker";
|
||||
style="rounded,filled"; fillcolor="#fce4ec"; color="#c62828";
|
||||
Worker [label="{Worker|id: WorkerId\\npool: ActorPool\\ntransfer_rx: Receiver\\<Envelope\\>\\nspawn_rx: Receiver\\<(ActorAddress, Box\\<dyn AnyActor\\>)\\>\\nstats: Arc\\<WorkerStats\\>\\nmailbox_snapshot: Arc\\<std::sync::Mutex\\<Vec\\<(ActorAddress, usize)\\>\\>\\>}", fillcolor="#ffcdd2"];
|
||||
WorkerContext [label="{WorkerContext|worker_id: WorkerId\\ntc: &'a TickContext\\<'a\\>\\npending_local: &'a RefCell\\<Vec\\<(ActorAddress, Box\\<dyn Any + Send\\>)\\>\\>\\nstats: &'a WorkerStats}", fillcolor="#ffcdd2"];
|
||||
ActorSlot [label="{ActorSlot|mailbox: VecDeque\\<Box\\<dyn Any + Send\\>\\>\\nactor: Box\\<dyn AnyActor\\>}", fillcolor="#ffcdd2"];
|
||||
ActorPool [label="{ActorPool|actors: HashMap\\<ActorAddress, ActorSlot\\>}", fillcolor="#ffcdd2"];
|
||||
}
|
||||
subgraph cluster_channel {
|
||||
label="channel";
|
||||
style="rounded,filled"; fillcolor="#fff3e0"; color="#e65100";
|
||||
HybridChannel [label="{HybridChannel|ring: ArrayQueue\\<T\\>\\noverflow: SegQueue\\<T\\>}", fillcolor="#ffe0b2"];
|
||||
Receiver [label="{Receiver|queue: Arc\\<HybridChannel\\<T\\>\\>}", fillcolor="#ffe0b2"];
|
||||
Sender [label="{Sender|queue: Arc\\<HybridChannel\\<T\\>\\>}", fillcolor="#ffe0b2"];
|
||||
}
|
||||
subgraph cluster_error {
|
||||
label="error";
|
||||
style="rounded,filled"; fillcolor="#f3e5f5"; color="#7b1fa2";
|
||||
Error [label="{Error|0: Box\\<dyn std :: error :: Error + Send + Sync + 'static\\>}", fillcolor="#e1bee7"];
|
||||
}
|
||||
subgraph cluster_config {
|
||||
label="config";
|
||||
style="rounded,filled"; fillcolor="#e8f5e9"; color="#2e7d32";
|
||||
BackoffPolicy [label="{BackoffPolicy|spin_threshold: u32\\nyield_threshold: u32\\nsleep_increment_us: u64\\nsleep_max_us: u64}", fillcolor="#c8e6c9"];
|
||||
RuntimeConfig [label="{RuntimeConfig|max_actors: usize\\nactor_max_messages: usize\\nnum_threads: usize\\nbackoff_policy: BackoffPolicy}", fillcolor="#c8e6c9"];
|
||||
}
|
||||
subgraph cluster_delivery {
|
||||
label="delivery";
|
||||
style="rounded,filled"; fillcolor="#fff9c4"; color="#f9a825";
|
||||
WorkerId [label="{WorkerId|0: usize}", fillcolor="#fff59d"];
|
||||
AddressMap [label="{AddressMap|inner: RwLock\\<HashMap\\<ActorAddress, WorkerId\\>\\>}", fillcolor="#fff59d"];
|
||||
Placement [label="{Placement|next: AtomicUsize\\nnum_workers: usize}", fillcolor="#fff59d"];
|
||||
Envelope [label="{Envelope|dest: ActorAddress\\npayload: Box\\<dyn Any + Send\\>}", fillcolor="#fff59d"];
|
||||
SenderT [label="{«trait» SenderT|try_send_any((&self, Box\\<dyn Any + Send\\>))}", fillcolor="#fff59d"];
|
||||
InboxRegistry [label="{InboxRegistry|senders: RwLock\\<HashMap\\<ActorAddress, Arc\\<dyn SenderT\\>\\>\\>}", fillcolor="#fff59d"];
|
||||
TickContext [label="{TickContext|address_map: &'a AddressMap\\ntransfer_txs: &'a [Sender\\<Envelope\\>]\\nspawn_txs: &'a [Sender\\<(ActorAddress, Box\\<dyn AnyActor\\>)\\>]\\nplacement: &'a Placement\\ninbox_registry: &'a InboxRegistry\\nconfig: &'a RuntimeConfig\\ncodec_registry: Option\\<&'a crate::transport::CodecRegistry\\>\\ntransport_router: Option\\<&'a crate::transport::TransportRouter\\>}", fillcolor="#fff59d"];
|
||||
}
|
||||
subgraph cluster_stats {
|
||||
label="stats";
|
||||
style="rounded,filled"; fillcolor="#e0f7fa"; color="#00838f";
|
||||
TickTiming [label="{TickTiming|phase_us: [u64; ..]\\nmessages_processed: usize\\ndid_work: bool}", fillcolor="#b2ebf2"];
|
||||
WorkerStats [label="{WorkerStats|num_actors: AtomicUsize\\ntotal_mailbox_depth: AtomicUsize\\nmessages_processed: AtomicU64\\nlocal_sends: AtomicU64\\ncross_sends: AtomicU64\\ninbox_sends: AtomicU64\\ntype_mismatches: AtomicU64\\npanics: AtomicU64\\ntick_timings: std::sync::Mutex\\<VecDeque\\<TickTiming\\>\\>}", fillcolor="#b2ebf2"];
|
||||
WorkerInfo [label="{WorkerInfo|id: usize\\nnum_actors: usize\\nmailbox_depth: usize\\nmessages_processed: u64\\nlocal_sends: u64\\ncross_sends: u64\\ninbox_sends: u64\\ntype_mismatches: u64\\npanics: u64}", fillcolor="#b2ebf2"];
|
||||
ActorInfo [label="{ActorInfo|address: ActorAddress\\nworker_id: usize\\nmailbox_depth: usize}", fillcolor="#b2ebf2"];
|
||||
RuntimeStats [label="{RuntimeStats|num_workers: usize\\nactors: Vec\\<(ActorAddress, usize)\\>\\nworkers: Vec\\<WorkerInfo\\>\\nactor_details: Vec\\<ActorInfo\\>\\ntick_timings: Vec\\<Vec\\<TickTiming\\>\\>}", fillcolor="#b2ebf2"];
|
||||
}
|
||||
subgraph cluster_runtime {
|
||||
label="runtime";
|
||||
style="rounded,filled"; fillcolor="#fbe9e7"; color="#d84315";
|
||||
Inbox [label="{Inbox|addr: ActorAddress\\ninner: Receiver\\<M\\>}", fillcolor="#ffccbc"];
|
||||
RuntimeHandle [label="{RuntimeHandle|runtime: Arc\\<Runtime\\>\\nthreads: Vec\\<JoinHandle\\<()\\>\\>}", fillcolor="#ffccbc"];
|
||||
Runtime [label="{Runtime|config: RuntimeConfig\\naddress_map: Arc\\<AddressMap\\>\\ninbox_registry: Arc\\<InboxRegistry\\>\\ntransfer_txs: Vec\\<Sender\\<Envelope\\>\\>\\nspawn_txs: Vec\\<Sender\\<(ActorAddress, Box\\<dyn AnyActor\\>)\\>\\>\\nplacement: Placement\\nis_running: AtomicBool\\nworker_stats: Vec\\<Arc\\<WorkerStats\\>\\>\\nmailbox_snapshots: Vec\\<Arc\\<std::sync::Mutex\\<Vec\\<(ActorAddress, usize)\\>\\>\\>\\>\\ntick_workers: RefCell\\<Vec\\<Worker\\>\\>\\ncodec_registry: Option\\<Arc\\<crate::transport::CodecRegistry\\>\\>\\ntransport_router: Option\\<Arc\\<crate::transport::TransportRouter\\>\\>}", fillcolor="#ffccbc"];
|
||||
}
|
||||
subgraph cluster_transport {
|
||||
label="transport (feature-gated)";
|
||||
style="rounded,dashed,filled"; fillcolor="#e3f2fd"; color="#1565c0";
|
||||
Codec [label="{«trait» Codec|encode((&self, &M) → Result\\<Vec\\<u8\\>, Error\\>)\\ndecode((&self, &[u8]) → Result\\<M, Error\\>)}", fillcolor="#bbdefb"];
|
||||
NetworkMessage [label="{«trait» NetworkMessage|type_tag(() → &'static str)}", fillcolor="#bbdefb"];
|
||||
WireEnvelope [label="{WireEnvelope|dest: ActorAddress\\ntype_tag: String\\npayload: Vec\\<u8\\>}", fillcolor="#bbdefb"];
|
||||
Transport [label="{«trait» Transport|send((&self, WireEnvelope) → Result\\<(), Error\\>)}", fillcolor="#bbdefb"];
|
||||
CodecRegistry [label="{CodecRegistry|encoders: HashMap\\<TypeId, EncodeFn\\>\\ndecoders: HashMap\\<String, DecodeFn\\>}", fillcolor="#bbdefb"];
|
||||
TransportRouter [label="{TransportRouter|routes: RwLock\\<HashMap\\<ActorAddress, Arc\\<dyn Transport\\>\\>\\>}", fillcolor="#bbdefb"];
|
||||
InMemoryTransport [label="{InMemoryTransport|tx: std::sync::Mutex\\<std::sync::mpsc::Sender\\<WireEnvelope\\>\\>}", fillcolor="#bbdefb"];
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// INTRA-MODULE EDGES (within same cluster)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
ActorInterface -> Message [label="Incoming", style=dashed, color="#1565c0", penwidth=1];
|
||||
ActorInterface -> Ctx [label="handle", style=dashed, color="#1565c0", penwidth=1];
|
||||
AnyActor -> Ctx [label="handle_any", style=dashed, color="#1565c0", penwidth=1];
|
||||
ContextInner -> ActorAddress [label="send_any", style=dashed, color="#1565c0", penwidth=1];
|
||||
ContextInner -> AnyActor [label="spawn_any", style=dashed, color="#1565c0", penwidth=1];
|
||||
Ctx -> ContextInner [label="inner", style=dashed, color="#1565c0", penwidth=1];
|
||||
Ctx -> ActorAddress [label="self_addr", style=dashed, color="#1565c0", penwidth=1];
|
||||
Actor -> AnyActor [label="impl", style=dotted, color="#1565c0", penwidth=1];
|
||||
Actor -> Ctx [label="handle_any() param", style=dashed, color="#1565c0", penwidth=1];
|
||||
Worker -> ActorPool [label="pool", style=dashed, color="#c62828", penwidth=1];
|
||||
ActorPool -> ActorSlot [label="actors", style=dashed, color="#c62828", penwidth=1];
|
||||
Receiver -> HybridChannel [label="queue", style=dashed, color="#e65100", penwidth=1];
|
||||
Sender -> HybridChannel [label="queue", style=dashed, color="#e65100", penwidth=1];
|
||||
Receiver -> Sender [label="new_sender() param", style=dashed, color="#e65100", penwidth=1];
|
||||
RuntimeConfig -> BackoffPolicy [label="backoff_policy", style=dashed, color="#2e7d32", penwidth=1];
|
||||
AddressMap -> WorkerId [label="inner", style=dashed, color="#f9a825", penwidth=1];
|
||||
InboxRegistry -> SenderT [label="senders", style=dashed, color="#f9a825", penwidth=1];
|
||||
TickContext -> AddressMap [label="address_map", style=dashed, color="#f9a825", penwidth=1];
|
||||
TickContext -> Envelope [label="transfer_txs", style=dashed, color="#f9a825", penwidth=1];
|
||||
TickContext -> Placement [label="placement", style=dashed, color="#f9a825", penwidth=1];
|
||||
TickContext -> InboxRegistry [label="inbox_registry", style=dashed, color="#f9a825", penwidth=1];
|
||||
Placement -> WorkerId [label="next_worker() param", style=dashed, color="#f9a825", penwidth=1];
|
||||
WorkerStats -> TickTiming [label="tick_timings", style=dashed, color="#00838f", penwidth=1];
|
||||
RuntimeStats -> WorkerInfo [label="workers", style=dashed, color="#00838f", penwidth=1];
|
||||
RuntimeStats -> ActorInfo [label="actor_details", style=dashed, color="#00838f", penwidth=1];
|
||||
RuntimeStats -> TickTiming [label="tick_timings", style=dashed, color="#00838f", penwidth=1];
|
||||
WorkerStats -> WorkerInfo [label="snapshot() param", style=dashed, color="#00838f", penwidth=1];
|
||||
RuntimeHandle -> Runtime [label="runtime", style=dashed, color="#d84315", penwidth=1];
|
||||
Runtime -> Inbox [label="new_inbox() param", style=dashed, color="#d84315", penwidth=1];
|
||||
Runtime -> RuntimeHandle [label="run() param", style=dashed, color="#d84315", penwidth=1];
|
||||
Transport -> WireEnvelope [label="send", style=dashed, color="#1565c0", penwidth=1];
|
||||
TransportRouter -> Transport [label="routes", style=dashed, color="#1565c0", penwidth=1];
|
||||
InMemoryTransport -> WireEnvelope [label="tx", style=dashed, color="#1565c0", penwidth=1];
|
||||
CodecRegistry -> WireEnvelope [label="receive() param", style=dashed, color="#1565c0", penwidth=1];
|
||||
InMemoryTransport -> Transport [label="impl", style=dotted, color="#1565c0", penwidth=1];
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// CROSS-MODULE EDGES (the real dependency DAG)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
// --- actor depends on error ---
|
||||
ContextInner -> Error [label="send_any", style=solid, color="#1565c0", penwidth=1.5];
|
||||
Ctx -> Error [label="send() param", style=solid, color="#1565c0", penwidth=1.5];
|
||||
|
||||
// --- worker depends on actor ---
|
||||
Worker -> ActorAddress [label="spawn_rx", style=solid, color="#c62828", penwidth=1.5];
|
||||
Worker -> AnyActor [label="spawn_rx", style=solid, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> ActorAddress [label="pending_local", style=solid, color="#c62828", penwidth=1.5];
|
||||
ActorSlot -> AnyActor [label="actor", style=solid, color="#c62828", penwidth=1.5];
|
||||
ActorPool -> ActorAddress [label="actors", style=solid, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> ContextInner [label="impl", style=dotted, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> AnyActor [label="spawn_any() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
ActorPool -> AnyActor [label="insert() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
ActorPool -> ContextInner [label="tick_all() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
|
||||
// --- worker depends on channel ---
|
||||
Worker -> Receiver [label="transfer_rx", style=solid, color="#c62828", penwidth=1.5];
|
||||
|
||||
// --- worker depends on error ---
|
||||
WorkerContext -> Error [label="send_any() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
|
||||
// --- worker depends on delivery ---
|
||||
Worker -> WorkerId [label="id", style=solid, color="#c62828", penwidth=1.5];
|
||||
Worker -> Envelope [label="transfer_rx", style=solid, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> WorkerId [label="worker_id", style=solid, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> TickContext [label="tc", style=solid, color="#c62828", penwidth=1.5];
|
||||
Worker -> TickContext [label="tick_once() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
|
||||
// --- worker depends on stats ---
|
||||
Worker -> WorkerStats [label="stats", style=solid, color="#c62828", penwidth=1.5];
|
||||
WorkerContext -> WorkerStats [label="stats", style=solid, color="#c62828", penwidth=1.5];
|
||||
ActorPool -> WorkerStats [label="tick_all() param", style=solid, color="#c62828", penwidth=1.5];
|
||||
|
||||
// --- channel depends on delivery ---
|
||||
Sender -> SenderT [label="impl", style=dotted, color="#e65100", penwidth=1.5];
|
||||
|
||||
// --- delivery depends on actor ---
|
||||
AddressMap -> ActorAddress [label="inner", style=solid, color="#f9a825", penwidth=1.5];
|
||||
Envelope -> ActorAddress [label="dest", style=solid, color="#f9a825", penwidth=1.5];
|
||||
InboxRegistry -> ActorAddress [label="senders", style=solid, color="#f9a825", penwidth=1.5];
|
||||
TickContext -> ActorAddress [label="spawn_txs", style=solid, color="#f9a825", penwidth=1.5];
|
||||
TickContext -> AnyActor [label="spawn_txs", style=solid, color="#f9a825", penwidth=1.5];
|
||||
|
||||
// --- delivery depends on channel ---
|
||||
TickContext -> Sender [label="transfer_txs", style=solid, color="#f9a825", penwidth=1.5];
|
||||
|
||||
// --- delivery depends on error ---
|
||||
InboxRegistry -> Error [label="try_deliver() param", style=solid, color="#f9a825", penwidth=1.5];
|
||||
TickContext -> Error [label="route_nonlocal() param", style=solid, color="#f9a825", penwidth=1.5];
|
||||
|
||||
// --- delivery depends on config ---
|
||||
TickContext -> RuntimeConfig [label="config", style=solid, color="#f9a825", penwidth=1.5];
|
||||
|
||||
// --- delivery depends on transport ---
|
||||
TickContext -> CodecRegistry [label="codec_registry", style=solid, color="#f9a825", penwidth=1.5];
|
||||
TickContext -> TransportRouter [label="transport_router", style=solid, color="#f9a825", penwidth=1.5];
|
||||
|
||||
// --- stats depends on actor ---
|
||||
ActorInfo -> ActorAddress [label="address", style=solid, color="#00838f", penwidth=1.5];
|
||||
RuntimeStats -> ActorAddress [label="actors", style=solid, color="#00838f", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on actor ---
|
||||
Inbox -> ActorAddress [label="addr", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> ActorAddress [label="spawn_txs", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> AnyActor [label="spawn_txs", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> ContextInner [label="impl", style=dotted, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on worker ---
|
||||
Runtime -> Worker [label="tick_workers", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on channel ---
|
||||
Inbox -> Receiver [label="inner", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> Sender [label="transfer_txs", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on error ---
|
||||
Runtime -> Error [label="spawn() param", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on config ---
|
||||
Runtime -> RuntimeConfig [label="config", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on delivery ---
|
||||
Runtime -> AddressMap [label="address_map", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> InboxRegistry [label="inbox_registry", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> Envelope [label="transfer_txs", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> Placement [label="placement", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> TickContext [label="make_tick_context() param", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on stats ---
|
||||
Runtime -> WorkerStats [label="worker_stats", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> RuntimeStats [label="stats() param", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- runtime depends on transport ---
|
||||
Runtime -> CodecRegistry [label="codec_registry", style=solid, color="#d84315", penwidth=1.5];
|
||||
Runtime -> TransportRouter [label="transport_router", style=solid, color="#d84315", penwidth=1.5];
|
||||
|
||||
// --- transport depends on actor ---
|
||||
WireEnvelope -> ActorAddress [label="dest", style=solid, color="#1565c0", penwidth=1.5];
|
||||
TransportRouter -> ActorAddress [label="routes", style=solid, color="#1565c0", penwidth=1.5];
|
||||
CodecRegistry -> ActorAddress [label="receive() param", style=solid, color="#1565c0", penwidth=1.5];
|
||||
|
||||
// --- transport depends on channel ---
|
||||
InMemoryTransport -> Sender [label="tx", style=solid, color="#1565c0", penwidth=1.5];
|
||||
InMemoryTransport -> Receiver [label="pair() param", style=solid, color="#1565c0", penwidth=1.5];
|
||||
|
||||
// --- transport depends on error ---
|
||||
Codec -> Error [label="encode", style=solid, color="#1565c0", penwidth=1.5];
|
||||
Transport -> Error [label="send", style=solid, color="#1565c0", penwidth=1.5];
|
||||
CodecRegistry -> Error [label="encode() param", style=solid, color="#1565c0", penwidth=1.5];
|
||||
InMemoryTransport -> Error [label="send() param", style=solid, color="#1565c0", penwidth=1.5];
|
||||
}
|
||||
`;
|
||||
|
||||
const viz = await instance();
|
||||
const svg = viz.renderSVGElement(DOT_SOURCE);
|
||||
document.getElementById('dag-loading').remove();
|
||||
|
||||
const vp = document.getElementById('dag-viewport');
|
||||
vp.appendChild(svg);
|
||||
|
||||
// ─── Dark-mode SVG recoloring ──────────────────────────────────────────────
|
||||
svg.querySelectorAll('polygon[fill="white"]').forEach(el => el.setAttribute('fill','#1a1a2e'));
|
||||
svg.querySelectorAll('.graph > text').forEach(el => el.setAttribute('fill','#e0e0e0'));
|
||||
svg.querySelectorAll('.cluster > text').forEach(el => el.setAttribute('fill','#1a1a1a'));
|
||||
svg.querySelectorAll('.edge text').forEach(el => el.setAttribute('fill','#ffb74d'));
|
||||
svg.querySelectorAll('.node text').forEach(el => el.setAttribute('fill','#1a1a1a'));
|
||||
|
||||
// ─── Click-to-focus ────────────────────────────────────────────────────────
|
||||
const edges = svg.querySelectorAll('.edge');
|
||||
const nodes = svg.querySelectorAll('.node');
|
||||
const clusterChrome = [];
|
||||
svg.querySelectorAll('.cluster').forEach(c => {
|
||||
c.querySelectorAll(':scope > path, :scope > polygon, :scope > text').forEach(el => clusterChrome.push(el));
|
||||
});
|
||||
|
||||
const nodeByTitle = new Map();
|
||||
nodes.forEach(n => {
|
||||
const t = n.querySelector('title');
|
||||
if (t) nodeByTitle.set(t.textContent.trim(), n);
|
||||
});
|
||||
|
||||
const nodeToClusterEls = new Map();
|
||||
svg.querySelectorAll('.cluster').forEach(cluster => {
|
||||
const chrome = [...cluster.querySelectorAll(':scope > path, :scope > polygon, :scope > text')];
|
||||
cluster.querySelectorAll('.node title').forEach(t => {
|
||||
nodeToClusterEls.set(t.textContent.trim(), chrome);
|
||||
});
|
||||
});
|
||||
|
||||
const adj = new Map();
|
||||
edges.forEach(edge => {
|
||||
const t = edge.querySelector('title');
|
||||
if (!t) return;
|
||||
const parts = t.textContent.trim().split('->').map(s => s.trim());
|
||||
if (parts.length !== 2) return;
|
||||
const [src, dst] = parts;
|
||||
if (!adj.has(src)) adj.set(src, { edges: [], neighbors: new Set() });
|
||||
if (!adj.has(dst)) adj.set(dst, { edges: [], neighbors: new Set() });
|
||||
adj.get(src).edges.push(edge);
|
||||
adj.get(src).neighbors.add(dst);
|
||||
adj.get(dst).edges.push(edge);
|
||||
adj.get(dst).neighbors.add(src);
|
||||
});
|
||||
|
||||
const DIM = 0.08;
|
||||
let focused = null;
|
||||
|
||||
function clearFocus() {
|
||||
focused = null;
|
||||
nodes.forEach(n => n.style.opacity = '');
|
||||
edges.forEach(e => e.style.opacity = '');
|
||||
clusterChrome.forEach(el => el.style.opacity = '');
|
||||
}
|
||||
|
||||
function focusNode(title) {
|
||||
if (focused === title) { clearFocus(); return; }
|
||||
focused = title;
|
||||
const info = adj.get(title) || { edges: [], neighbors: new Set() };
|
||||
const connected = new Set([title, ...info.neighbors]);
|
||||
|
||||
nodes.forEach(n => n.style.opacity = DIM);
|
||||
edges.forEach(e => e.style.opacity = DIM);
|
||||
clusterChrome.forEach(el => el.style.opacity = DIM);
|
||||
|
||||
connected.forEach(name => {
|
||||
const el = nodeByTitle.get(name);
|
||||
if (el) el.style.opacity = 1;
|
||||
});
|
||||
|
||||
info.edges.forEach(e => e.style.opacity = 1);
|
||||
|
||||
const seen = new Set();
|
||||
connected.forEach(name => {
|
||||
const chrome = nodeToClusterEls.get(name);
|
||||
if (chrome) chrome.forEach(el => {
|
||||
if (!seen.has(el)) { seen.add(el); el.style.opacity = 1; }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
nodes.forEach(node => {
|
||||
node.style.cursor = 'pointer';
|
||||
node.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
const t = node.querySelector('title');
|
||||
if (t) focusNode(t.textContent.trim());
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Pan & zoom ────────────────────────────────────────────────────────────
|
||||
let scale = 1, tx = 0, ty = 0, dragging = false, didDrag = false, sx = 0, sy = 0;
|
||||
function applyTransform() { svg.style.transform = `translate(${tx}px,${ty}px) scale(${scale})`; svg.style.transformOrigin = '0 0'; }
|
||||
|
||||
window.resetView = function() {
|
||||
const vw = vp.clientWidth, vh = vp.clientHeight;
|
||||
const bb = svg.getBBox();
|
||||
scale = Math.min(vw / bb.width, vh / bb.height) * 0.92;
|
||||
tx = (vw - bb.width * scale) / 2;
|
||||
ty = (vh - bb.height * scale) / 2;
|
||||
applyTransform();
|
||||
};
|
||||
let dagFitted = false;
|
||||
window.addEventListener('dag-visible', () => {
|
||||
if (!dagFitted) { dagFitted = true; requestAnimationFrame(resetView); }
|
||||
});
|
||||
|
||||
window.zoomIn = function() { scale *= 1.3; applyTransform(); };
|
||||
window.zoomOut = function() { scale *= 0.7; applyTransform(); };
|
||||
|
||||
vp.addEventListener('wheel', e => { e.preventDefault(); const f = e.deltaY < 0 ? 1.12 : 0.89; const rect = vp.getBoundingClientRect(); const mx = e.clientX - rect.left; const my = e.clientY - rect.top; tx = mx - f * (mx - tx); ty = my - f * (my - ty); scale *= f; applyTransform(); }, { passive:false });
|
||||
vp.addEventListener('pointerdown', e => { dragging=true; didDrag=false; sx=e.clientX-tx; sy=e.clientY-ty; vp.setPointerCapture(e.pointerId); });
|
||||
vp.addEventListener('pointermove', e => { if(!dragging) return; didDrag=true; tx=e.clientX-sx; ty=e.clientY-sy; applyTransform(); });
|
||||
vp.addEventListener('pointerup', () => dragging=false);
|
||||
vp.addEventListener('click', e => { if (!didDrag && !e.target.closest('.node')) clearFocus(); });
|
||||
</script>
|
||||
</body></html>
|
||||
|
|
@ -1,169 +0,0 @@
|
|||
{
|
||||
"graph": {
|
||||
"n_nodes": 39,
|
||||
"n_edges": 97,
|
||||
"n_modules": 9,
|
||||
"connected_components": 2,
|
||||
"modules": [
|
||||
"actor",
|
||||
"worker",
|
||||
"channel",
|
||||
"error",
|
||||
"config",
|
||||
"delivery",
|
||||
"stats",
|
||||
"runtime",
|
||||
"transport"
|
||||
]
|
||||
},
|
||||
"structural": {
|
||||
"avg_degree": 2.4871794871794872,
|
||||
"max_fan_in": {
|
||||
"count": 16,
|
||||
"node": "ActorAddress"
|
||||
},
|
||||
"max_fan_out": {
|
||||
"count": 18,
|
||||
"node": "Runtime"
|
||||
},
|
||||
"dag_depth": 7,
|
||||
"clustering_coefficient": 0.26676384839650147,
|
||||
"avg_module_size": 4.333333333333333
|
||||
},
|
||||
"module_coupling": {
|
||||
"module_names": [
|
||||
"actor",
|
||||
"worker",
|
||||
"channel",
|
||||
"error",
|
||||
"config",
|
||||
"delivery",
|
||||
"stats",
|
||||
"runtime",
|
||||
"transport"
|
||||
],
|
||||
"coupling_matrix": [
|
||||
[
|
||||
9.0,
|
||||
0.0,
|
||||
0.0,
|
||||
2.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
9.0,
|
||||
2.0,
|
||||
1.0,
|
||||
1.0,
|
||||
0.0,
|
||||
5.0,
|
||||
3.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.0,
|
||||
0.0,
|
||||
3.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
5.0,
|
||||
0.0,
|
||||
1.0,
|
||||
2.0,
|
||||
1.0,
|
||||
7.0,
|
||||
0.0,
|
||||
0.0,
|
||||
2.0
|
||||
],
|
||||
[
|
||||
2.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
5.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
4.0,
|
||||
1.0,
|
||||
2.0,
|
||||
1.0,
|
||||
1.0,
|
||||
5.0,
|
||||
2.0,
|
||||
3.0,
|
||||
2.0
|
||||
],
|
||||
[
|
||||
3.0,
|
||||
0.0,
|
||||
2.0,
|
||||
4.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
5.0
|
||||
]
|
||||
],
|
||||
"cross_module_edges": 62,
|
||||
"total_edges": 97
|
||||
},
|
||||
"module_cohesion": {
|
||||
"actor": 0.21428571428571427,
|
||||
"worker": 0.16666666666666666,
|
||||
"channel": 0.5,
|
||||
"error": null,
|
||||
"config": 0.5,
|
||||
"delivery": 0.16666666666666666,
|
||||
"stats": 0.25,
|
||||
"runtime": 0.5,
|
||||
"transport": 0.11904761904761904
|
||||
},
|
||||
"metrics": {
|
||||
"algebraic_connectivity": 0.0,
|
||||
"spectral_entropy": 4.728701071955628,
|
||||
"edge_density": 0.06545209176788123,
|
||||
"cross_module_ratio": 0.6391752577319587,
|
||||
"spectral_radius": 7.96362061601628,
|
||||
"avg_module_cohesion": 0.3020833333333333,
|
||||
"cci": 0.39601706111504315
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
========================================================================
|
||||
SPECTRAL ANALYSIS REPORT — Dependency DAG
|
||||
========================================================================
|
||||
|
||||
GRAPH SUMMARY
|
||||
----------------------------------------
|
||||
Nodes: 39
|
||||
Directed edges: 97
|
||||
Modules: 9
|
||||
Connected components: 2
|
||||
Modules: actor, worker, channel, error, config, delivery, stats, runtime, transport
|
||||
|
||||
STRUCTURAL PROPERTIES
|
||||
----------------------------------------
|
||||
Edges/node (avg degree): 2.49
|
||||
Max fan-in: 16 (ActorAddress)
|
||||
Max fan-out: 18 (Runtime)
|
||||
DAG depth: 7
|
||||
Clustering coefficient: 0.2668
|
||||
|
||||
MODULE COHESION
|
||||
----------------------------------------
|
||||
Module Size Cohesion
|
||||
actor 7 0.214
|
||||
worker 4 0.167
|
||||
channel 3 0.500
|
||||
error 1 —
|
||||
config 2 0.500
|
||||
delivery 7 0.167
|
||||
stats 5 0.250
|
||||
runtime 3 0.500
|
||||
transport 7 0.119
|
||||
────────────────────────────────
|
||||
Average cohesion: 0.302
|
||||
Avg module size: 4.3
|
||||
|
||||
MODULE COUPLING MATRIX (directed edge counts)
|
||||
----------------------------------------
|
||||
actor worker channel error config delivery stats runtime transport
|
||||
actor 9 0 0 2 0 0 0 0 0
|
||||
worker 9 2 1 1 0 5 3 0 0
|
||||
channel 0 0 3 0 0 1 0 0 0
|
||||
error 0 0 0 0 0 0 0 0 0
|
||||
config 0 0 0 0 1 0 0 0 0
|
||||
delivery 5 0 1 2 1 7 0 0 2
|
||||
stats 2 0 0 0 0 0 5 0 0
|
||||
runtime 4 1 2 1 1 5 2 3 2
|
||||
transport 3 0 2 4 0 0 0 0 5
|
||||
|
||||
Cross-module edges: 62 / 97 (63.9%)
|
||||
|
||||
CONNECTOME COMPLEXITY INDEX (CCI)
|
||||
----------------------------------------
|
||||
Sub-metric Raw Normalized Weight Contrib
|
||||
──────────────────────────────────────── ────────── ────────── ──────── ────────
|
||||
Algebraic connectivity (lambda_2/n) 0.0000 0.0000 0.25 0.0000
|
||||
Spectral entropy (H/log2(k)) 4.7287 0.9077 0.25 0.2269
|
||||
Edge density (|E|/n(n-1)) 0.0655 0.0655 0.15 0.0098
|
||||
Cross-module coupling ratio 0.6392 0.6392 0.20 0.1278
|
||||
Spectral radius (rho/(n-1)) 7.9636 0.2096 0.15 0.0314
|
||||
──────────────────────────────────────── ────────── ────────── ──────── ────────
|
||||
CCI (weighted sum) 1.00 0.3960
|
||||
|
||||
Interpretation: MODERATE complexity — typical well-structured codebase
|
||||
|
||||
========================================================================
|
||||
|
|
@ -1,503 +0,0 @@
|
|||
# Swactor Datastore Auth Specification
|
||||
|
||||
**Version:** 0.2.0
|
||||
**Status:** Implemented (MVP)
|
||||
|
||||
## 1. Overview
|
||||
|
||||
This document specifies the authorization layer for the Swactor Datastore as implemented. It defines how access is controlled for external clients connecting to a datastore node.
|
||||
|
||||
### Principles
|
||||
|
||||
- **Cryptographic identity** — keys, not passwords. Every participant is identified by an ed25519 public key (`NodeId`).
|
||||
- **Binary access** — a client is either authorized or not. No permission tiers for MVP.
|
||||
- **Owner-only administration** — only the datastore owner can grant or revoke access.
|
||||
- **Two auth paths** — direct iroh connections (connection-level) and signed HTTP requests (browser/CLI). This spec covers the signed request path (Auth Path 2), which is fully implemented.
|
||||
|
||||
### Non-Goals (MVP)
|
||||
|
||||
- Per-path permission scoping.
|
||||
- Permission tiers (read-only, read-write, admin).
|
||||
- Capability tokens or time-limited delegated access.
|
||||
- Multi-level delegation chains.
|
||||
|
||||
## 2. Trust Boundaries
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Cluster (SWIM mesh) │
|
||||
│ │
|
||||
│ Node A ◄──────────────► Node B │
|
||||
│ implicitly trusted │
|
||||
│ (no auth checks) │
|
||||
└──────────────────┬──────────────────────────┘
|
||||
│
|
||||
│ auth boundary
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ External Clients │
|
||||
│ │
|
||||
│ CLI tool │
|
||||
│ Browser user │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
- **Cluster-internal** (node-to-node via SWIM): implicitly trusted. Nodes that are members of the SWIM cluster communicate freely — no per-request auth checks.
|
||||
- **External clients** (CLI, browser): must be authorized. Every external request is checked against the Access Control List before being dispatched to the actor system.
|
||||
|
||||
## 3. Identity Model
|
||||
|
||||
The auth layer reuses the existing ed25519 identity model from the distribution layer:
|
||||
|
||||
- Every client (CLI tool, browser user, node) has an ed25519 keypair.
|
||||
- Identity is the 32-byte public key, represented as `NodeId`.
|
||||
- The same `NodeId` type from `distribution::types` is used throughout.
|
||||
|
||||
There is no separate "user" concept — a keypair *is* an identity.
|
||||
|
||||
## 4. Access Control List
|
||||
|
||||
### 4.1 Structure
|
||||
|
||||
```rust
|
||||
AccessControlList {
|
||||
owner: NodeId, // The datastore owner's public key
|
||||
authorized_keys: HashSet<NodeId>, // Explicitly authorized client keys
|
||||
key_labels: HashMap<String, String>, // hex(public_key) → human-readable name
|
||||
}
|
||||
```
|
||||
|
||||
- The **owner** always has full access (implicit; never needs to be in `authorized_keys`).
|
||||
- An empty `authorized_keys` set means only the owner can access the datastore.
|
||||
- `key_labels` maps the hex-encoded public key to a human-readable name. Labels are set on grant (from the access request's `name` field or an explicit `--name`/`?name=` parameter) and removed on revoke. The `#[serde(default)]` annotation ensures backward compatibility with ACL files written before labels existed.
|
||||
|
||||
### 4.2 Persistence
|
||||
|
||||
The ACL is persisted as JSON in the **auth directory**, separate from the storage path:
|
||||
|
||||
```
|
||||
<auth-dir>/
|
||||
├── owner.key.json # Owner keypair
|
||||
└── acl.json # AccessControlList
|
||||
```
|
||||
|
||||
Default `auth-dir` is `./auth` (configurable via `--auth-dir`).
|
||||
|
||||
### 4.3 Mutations
|
||||
|
||||
| Operation | Signature | Who |
|
||||
|-----------|-----------|-----|
|
||||
| Grant access | `grant(requester, key, label)` | Owner only |
|
||||
| Revoke access | `revoke(requester, key)` | Owner only |
|
||||
|
||||
- `grant` adds a `NodeId` to `authorized_keys` and optionally sets a label in `key_labels`. If the key has a pending access request, the request's `name` is used as the label (unless an explicit label is provided). Idempotent.
|
||||
- `revoke` removes a `NodeId` from `authorized_keys` and removes its label from `key_labels`. Idempotent.
|
||||
- Revoking the owner is a no-op (the owner's implicit access cannot be removed).
|
||||
- Both operations persist the updated ACL to disk immediately via `persist_acl()`.
|
||||
|
||||
## 5. Auth Path 1 — Direct iroh Connection
|
||||
|
||||
For clients that connect directly to the datastore node over iroh (QUIC):
|
||||
|
||||
```
|
||||
Client (ed25519 keypair) Datastore Node
|
||||
│ │
|
||||
│──── iroh QUIC handshake ──────────>│
|
||||
│ (proves client's NodeId) │
|
||||
│ │
|
||||
│ check NodeId
|
||||
│ against ACL
|
||||
│ │
|
||||
│<─── accept / reject ──────────────│
|
||||
│ │
|
||||
│ (if accepted, all ops on │
|
||||
│ this connection are allowed) │
|
||||
```
|
||||
|
||||
1. The iroh QUIC handshake cryptographically proves the peer's `NodeId` (ed25519 public key).
|
||||
2. On connection establishment, the node checks the peer's `NodeId` against the ACL via `check_node()`.
|
||||
3. If authorized, connection accepted. All operations on that connection are allowed with no per-message overhead.
|
||||
4. If not authorized, connection rejected immediately.
|
||||
|
||||
## 6. Auth Path 2 — Signed Requests (HTTP API)
|
||||
|
||||
For browser users and CLI clients communicating over HTTP.
|
||||
|
||||
### 6.1 Threat Model
|
||||
|
||||
The HTTP transport is treated as an **untrusted relay**. Each request is self-authenticating via a signed envelope. The relay cannot forge, modify, or replay requests.
|
||||
|
||||
### 6.2 Signed Envelope
|
||||
|
||||
Each request carries a signed envelope in the `X-Signed-Request` HTTP header:
|
||||
|
||||
```rust
|
||||
SignedRequest {
|
||||
payload: SignedRequestPayload, // The request details
|
||||
public_key: NodeId, // Client's public key (as [u8; 32])
|
||||
signature: Signature, // ed25519 signature over serialized payload
|
||||
}
|
||||
|
||||
SignedRequestPayload {
|
||||
action: DatastoreAction, // What the client wants to do
|
||||
timestamp: u64, // Unix timestamp (seconds)
|
||||
nonce: [u8; 16], // 16 random bytes
|
||||
}
|
||||
|
||||
DatastoreAction = enum {
|
||||
Put { name, content_hash, size_bytes, tags },
|
||||
Get { content_hash },
|
||||
Delete { content_hash },
|
||||
List { name_filter },
|
||||
Access, // Identity proof (no content binding)
|
||||
}
|
||||
```
|
||||
|
||||
The header value is the JSON serialization of `SignedRequest`. The `public_key` and `signature` fields are serialized as arrays of integers (e.g., `[163, 45, ...]`), matching serde's default serialization for `[u8; 32]` and `[u8; 64]`.
|
||||
|
||||
### 6.3 DatastoreAction::Access
|
||||
|
||||
The `Access` variant is a lightweight identity proof that does not bind to a specific content operation. It is used by:
|
||||
|
||||
- **Browser** — all API calls use `Access` (the browser proves identity, and the HTTP layer gates the actual operation).
|
||||
- **CLI auth management** — `grant`, `revoke`, `requests`, `keys`, `deny` subcommands use `Access` since these admin operations don't correspond to content actions.
|
||||
|
||||
The CLI's data operations (`put`, `get`, `delete`, `list`) sign the corresponding specific action variants.
|
||||
|
||||
### 6.4 Verification Steps
|
||||
|
||||
The `AuthzEngine` verifies a signed request in strict order:
|
||||
|
||||
1. **Signature validity** — verify the ed25519 signature over the canonical JSON serialization of `SignedRequestPayload` using the provided `public_key`.
|
||||
2. **Timestamp freshness** — reject if `|now - payload.timestamp| > 300` seconds.
|
||||
3. **Nonce uniqueness** — reject if `payload.nonce` has been seen before within the time window.
|
||||
4. **ACL check** — reject if `public_key` is not in the ACL (not owner and not in `authorized_keys`).
|
||||
|
||||
If any step fails, the request is denied with the corresponding `DeniedReason`:
|
||||
- `InvalidSignature`
|
||||
- `RequestExpired`
|
||||
- `ReplayDetected`
|
||||
- `NotAuthorized`
|
||||
|
||||
### 6.5 Signature-Only Verification
|
||||
|
||||
A separate `check_signature_only()` path performs steps 1-3 (signature, timestamp, nonce) but **skips** step 4 (ACL check). This is used for the access request endpoint (`POST /api/auth/request`), where an unauthorized user needs to prove they own the key they're requesting access for.
|
||||
|
||||
### 6.6 Put Payload Note
|
||||
|
||||
`DatastoreAction::Put` references a `content_hash` rather than embedding raw file data. The bulk data is uploaded separately, and its integrity is guaranteed by blake3 content addressing. The signed envelope authorizes the *operation*, not the data transfer.
|
||||
|
||||
## 7. Replay Protection
|
||||
|
||||
### 7.1 Timestamp Window
|
||||
|
||||
- Requests must have a `timestamp` within ±300 seconds of the node's wall clock.
|
||||
- Requests outside this window are rejected with `DeniedReason::RequestExpired`.
|
||||
|
||||
### 7.2 Nonce
|
||||
|
||||
- Each request includes a 16-byte random nonce.
|
||||
- The node maintains a set of recently seen nonces in `seen_nonces: HashMap<[u8; 16], u64>`.
|
||||
- Duplicate nonces within the time window are rejected with `DeniedReason::ReplayDetected`.
|
||||
|
||||
### 7.3 Nonce Garbage Collection
|
||||
|
||||
- Nonces are stored alongside their timestamps.
|
||||
- When a nonce's timestamp falls outside the ±300 second window, it is eligible for GC.
|
||||
- `gc_nonces(now)` is called periodically via `GatewayMsg::NonceGcTick`, which piggybacks on the main loop's GC tick cadence.
|
||||
|
||||
## 8. Enforcement Point
|
||||
|
||||
Auth is enforced at the **edge** of the actor system via the `GatewayActor`:
|
||||
|
||||
```
|
||||
External Client
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ GatewayActor│◄── ACL check happens here
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────┐ ┌─────────────────┐ ┌────────────────┐
|
||||
│ MetadataActor│◄──►│ BlobStoreActor │ │ TransferActor │
|
||||
│ │ │ │ │ │
|
||||
│ (auth- │ │ (auth- │ │ (auth- │
|
||||
│ unaware) │ │ unaware) │ │ unaware) │
|
||||
└──────────────┘ └─────────────────┘ └────────────────┘
|
||||
```
|
||||
|
||||
### 8.1 HTTP API Route Table
|
||||
|
||||
| Method | Path | Auth Level | Description |
|
||||
|--------|------|------------|-------------|
|
||||
| `GET` | `/` | None | Browser UI page |
|
||||
| `GET` | `/admin` | None | Admin page |
|
||||
| `GET` | `/crypto.wasm` | None | WASM Ed25519 module |
|
||||
| `GET` | `/api/status` | None | Node identity |
|
||||
| `POST` | `/api/put` | Full (`check_auth`) | Store an object |
|
||||
| `GET` | `/api/get` | Full (`check_auth`) | Get object metadata |
|
||||
| `GET` | `/api/data` | Full (`check_auth`) | Download object data |
|
||||
| `POST` | `/api/delete` | Full (`check_auth`) | Delete an object |
|
||||
| `GET` | `/api/list` | Full (`check_auth`) | List objects |
|
||||
| `POST` | `/api/auth/grant` | Full (`check_auth_identity`) | Grant access to a key (owner-only) |
|
||||
| `POST` | `/api/auth/revoke` | Full (`check_auth_identity`) | Revoke access from a key (owner-only) |
|
||||
| `GET` | `/api/auth/requests` | Full (`check_auth_identity`) | List pending access requests (owner-only) |
|
||||
| `GET` | `/api/auth/keys` | Full (`check_auth_identity`) | List authorized keys (owner-only) |
|
||||
| `POST` | `/api/auth/deny` | Full (`check_auth_identity`) | Deny a pending request (owner-only) |
|
||||
| `POST` | `/api/auth/request` | Signature-only (`check_auth_signature_only`) | Submit an access request |
|
||||
|
||||
**Auth levels:**
|
||||
- **None** — no `X-Signed-Request` header required.
|
||||
- **Full** — `X-Signed-Request` header required; full 4-step verification (signature + timestamp + nonce + ACL).
|
||||
- **Signature-only** — `X-Signed-Request` header required; 3-step verification (signature + timestamp + nonce, no ACL check).
|
||||
|
||||
`check_auth_identity` is like `check_auth` but also returns the caller's `NodeId`, needed for grant/revoke/deny operations to identify the requester.
|
||||
|
||||
### 8.2 Internal Actors
|
||||
|
||||
`MetadataActor`, `BlobStoreActor`, and `TransferActor` remain **auth-unaware**. They process messages from any source within the actor system. The auth boundary is strictly external.
|
||||
|
||||
## 9. Browser Auth Flow
|
||||
|
||||
### 9.1 WASM Ed25519 Crypto
|
||||
|
||||
Browser clients use a WASM module (`/crypto.wasm`) compiled from `crates/crypto-wasm/` — a `no_std` Rust crate using `ed25519-dalek`. This replaces the earlier Web Crypto API approach, which has inconsistent Ed25519 support across browsers.
|
||||
|
||||
The WASM module exports three functions through a shared 8192-byte buffer:
|
||||
|
||||
| Function | Input | Output |
|
||||
|----------|-------|--------|
|
||||
| `buffer_ptr()` | — | Pointer to shared buffer |
|
||||
| `get_public_key()` | `BUF[0..32]` = seed | `BUF[32..64]` = public key |
|
||||
| `ed25519_sign(msg_len)` | `BUF[0..32]` = seed, `BUF[128..128+msg_len]` = message | `BUF[64..128]` = signature |
|
||||
|
||||
JavaScript wrapper functions:
|
||||
|
||||
```javascript
|
||||
async function initCrypto() {
|
||||
const { instance } = await WebAssembly.instantiate(
|
||||
await (await fetch('/crypto.wasm')).arrayBuffer()
|
||||
);
|
||||
wasmExports = instance.exports;
|
||||
bufPtr = wasmExports.buffer_ptr();
|
||||
}
|
||||
|
||||
function derivePublicKey(seed) { /* write seed → read pubkey */ }
|
||||
function signBytes(message, seed) { /* write seed+message → read signature */ }
|
||||
```
|
||||
|
||||
### 9.2 Device Key Management
|
||||
|
||||
On first visit (when auth is detected), the browser:
|
||||
|
||||
1. Generates a 32-byte random seed: `crypto.getRandomValues(new Uint8Array(32))`
|
||||
2. Stores it as hex in `localStorage.deviceKeySeed`
|
||||
3. Derives the public key via `derivePublicKey(seed)`
|
||||
|
||||
On subsequent visits, the seed is loaded from localStorage. A migration path handles legacy JWK keys (from an earlier Web Crypto implementation) by extracting the `d` parameter as the seed.
|
||||
|
||||
### 9.3 Auth Detection
|
||||
|
||||
On page load, the browser fetches `GET /api/list` without auth:
|
||||
- If the response is 401, auth is enabled → initialize WASM crypto, generate/load keys, show device key in header
|
||||
- If the response is 200, auth is disabled → proceed normally
|
||||
|
||||
### 9.4 Request Signing
|
||||
|
||||
All authenticated browser requests go through `authFetch()`:
|
||||
|
||||
```javascript
|
||||
async function authFetch(url, opts) {
|
||||
const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)));
|
||||
const payload = {
|
||||
action: "Access",
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
nonce: nonce
|
||||
};
|
||||
const payloadBytes = new TextEncoder().encode(JSON.stringify(payload));
|
||||
const sigBytes = signBytes(payloadBytes, deviceSeed);
|
||||
const header = JSON.stringify({
|
||||
payload: payload,
|
||||
public_key: Array.from(pubKeyBytes),
|
||||
signature: Array.from(sigBytes)
|
||||
});
|
||||
opts.headers['X-Signed-Request'] = header;
|
||||
return fetch(url, opts);
|
||||
}
|
||||
```
|
||||
|
||||
The browser always uses `DatastoreAction::Access` — it proves identity without binding to a specific content operation. The HTTP API layer handles the actual data operation gating.
|
||||
|
||||
### 9.5 Access Request Flow
|
||||
|
||||
When a browser user is not yet authorized:
|
||||
|
||||
1. **Auth banner appears** — shows a form with name (required, max 64 chars) and message (optional, max 256 chars) fields.
|
||||
2. **User submits** — `POST /api/auth/request` with JSON body `{ name, message }` and `X-Signed-Request` header (signature-only check).
|
||||
3. **Pending state** — banner switches to "waiting for operator approval" with localStorage persistence (`accessRequestPending`, `accessRequestName`).
|
||||
4. **Polling** — every 5 seconds, `authFetch('/api/list')` checks if the user has been granted access.
|
||||
5. **Granted** — when `/api/list` returns 200, polling stops, banner disappears, object list loads.
|
||||
6. **Re-submission on reload** — if the page is reloaded while pending, the request is re-submitted to handle node restarts.
|
||||
|
||||
## 10. Admin Page
|
||||
|
||||
The admin page (`/admin`) provides a browser interface for the datastore owner to manage access.
|
||||
|
||||
### 10.1 Authentication
|
||||
|
||||
The owner authenticates by uploading their `key.json` file:
|
||||
1. File is parsed for `secret_key` (hex) and `public_key` (hex).
|
||||
2. Public key is derived from the secret key via WASM and compared to the stored `public_key` for integrity.
|
||||
3. A test call to `GET /api/auth/requests` verifies this is actually the owner key (non-owners get 403).
|
||||
|
||||
### 10.2 Capabilities
|
||||
|
||||
- **Pending access requests** — table showing name, message, key (truncated), with grant/deny buttons per request.
|
||||
- **Authorized keys** — table showing label, key (truncated), with revoke button per key.
|
||||
- **Manual grant** — input fields for a 64-char hex public key + optional name, bypassing the access request flow.
|
||||
- **Name disambiguation** — when multiple entries share the same name, a key prefix `(abcd1234)` is appended for disambiguation.
|
||||
|
||||
### 10.3 Admin Request Signing
|
||||
|
||||
All admin API calls use `ownerAuthFetch()`, which signs with `DatastoreAction::Access` using the owner's seed.
|
||||
|
||||
## 11. CLI
|
||||
|
||||
### 11.1 Auth Signing
|
||||
|
||||
The CLI uses `--key <path>` to load a key.json file. Each command signs an `X-Signed-Request` header:
|
||||
|
||||
- **Data operations** (`put`, `get`, `delete`, `list`) sign with the corresponding `DatastoreAction` variant (e.g., `DatastoreAction::Put { name, content_hash, size_bytes, tags }`).
|
||||
- **Auth management** (`grant`, `revoke`, `requests`, `keys`, `deny`) sign with `DatastoreAction::Access`.
|
||||
- **`status`** — never signed (endpoint is always open).
|
||||
- Without `--key`, no header is sent (backward compatible with non-auth nodes).
|
||||
|
||||
### 11.2 Subcommands
|
||||
|
||||
```
|
||||
swactor-store --key <path> put <file> [--name <label>]
|
||||
Upload a file. Signs DatastoreAction::Put.
|
||||
|
||||
swactor-store --key <path> get <hash> [--output <path>]
|
||||
Retrieve metadata (or download with --output). Signs DatastoreAction::Get.
|
||||
|
||||
swactor-store --key <path> delete <hash>
|
||||
Delete an object. Signs DatastoreAction::Delete.
|
||||
|
||||
swactor-store --key <path> list [--name <filter>] [--all]
|
||||
List objects. Signs DatastoreAction::List.
|
||||
|
||||
swactor-store status
|
||||
Show node identity. No signing.
|
||||
|
||||
swactor-store --key <path> grant <key_or_name> [--name <label>]
|
||||
Authorize a public key. Owner-only. Accepts 64 hex chars or a name.
|
||||
|
||||
swactor-store --key <path> revoke <key_or_name>
|
||||
Revoke a public key. Owner-only. Accepts 64 hex chars or a name.
|
||||
|
||||
swactor-store --key <path> requests
|
||||
List pending access requests. Owner-only.
|
||||
|
||||
swactor-store --key <path> keys
|
||||
List authorized keys with labels. Owner-only.
|
||||
|
||||
swactor-store --key <path> deny <key_or_name>
|
||||
Deny a pending access request. Owner-only. Accepts 64 hex chars or a name.
|
||||
```
|
||||
|
||||
### 11.3 Name Resolution
|
||||
|
||||
`grant`, `revoke`, and `deny` accept either:
|
||||
- A **64-character hex public key** — used directly.
|
||||
- A **human-readable name** — resolved by fetching the pending requests (`/api/auth/requests`) or authorized keys (`/api/auth/keys`) list and matching by name.
|
||||
|
||||
If multiple entries match the same name, the CLI prints disambiguated names (e.g., `alice (c9d0e1f2)`) and asks the user to re-run with the disambiguated form. The `(prefix)` suffix uses the first 8 hex characters of the key.
|
||||
|
||||
## 12. Key Management
|
||||
|
||||
### 12.1 Key File Format
|
||||
|
||||
All keys use the same JSON format:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"secret_key": "...64 hex chars (32 bytes ed25519 seed)...",
|
||||
"public_key": "...64 hex chars (32 bytes ed25519 public key)...",
|
||||
"created_at": "2026-02-15T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
- Generated by the node on first `--auth` run at `<auth-dir>/owner.key.json`.
|
||||
- The CLI reads it via `--key`.
|
||||
- The admin page accepts it via file upload for authentication.
|
||||
|
||||
### 12.2 Node Key Generation
|
||||
|
||||
When `--auth` is enabled:
|
||||
1. If `<auth-dir>/owner.key.json` exists, load the keypair from it.
|
||||
2. Otherwise, generate a new `Keypair`, write the key file with ISO-8601 `created_at`.
|
||||
3. The keypair's `node_id()` becomes the node's `NodeId` (deterministic identity across restarts).
|
||||
4. Create/load `<auth-dir>/acl.json` with this `NodeId` as owner.
|
||||
|
||||
### 12.3 Browser Key Generation
|
||||
|
||||
Browser keys are simpler — 32 random bytes stored as hex in `localStorage.deviceKeySeed`. No key file is produced. The public key is derived on each page load via the WASM `get_public_key()` function.
|
||||
|
||||
### 12.4 Grant Flow
|
||||
|
||||
Two paths to granting access:
|
||||
|
||||
**Via access request (browser-initiated):**
|
||||
1. Browser user visits the page, generates device key, submits access request with name.
|
||||
2. Owner views pending requests on `/admin` or via `swactor-store requests`.
|
||||
3. Owner grants via admin page button or `swactor-store grant <name_or_key>`.
|
||||
4. Pending request is removed, name becomes key label, ACL is persisted.
|
||||
5. Browser's polling detects the grant and loads the object list.
|
||||
|
||||
**Via manual grant (out-of-band):**
|
||||
1. Client generates a keypair (or uses an existing one).
|
||||
2. Client shares their public key with the owner out-of-band.
|
||||
3. Owner runs: `swactor-store --key owner.key.json grant <pubkey> --name <label>`
|
||||
4. Or: uses the admin page's "Grant Key Manually" form.
|
||||
|
||||
### 12.5 Revocation
|
||||
|
||||
1. Owner runs: `swactor-store --key owner.key.json revoke <pubkey_or_name>`
|
||||
2. Or: clicks "revoke" on the admin page's authorized keys table.
|
||||
3. Client's access is immediately revoked for HTTP requests.
|
||||
4. Existing direct iroh connections from that client remain open until disconnected.
|
||||
|
||||
## 13. Protocol Integration
|
||||
|
||||
Each datastore operation has a clear auth integration point:
|
||||
|
||||
| Operation | CLI Signing | Browser Signing |
|
||||
|-----------|-------------|-----------------|
|
||||
| PUT | `DatastoreAction::Put { name, content_hash, size_bytes, tags }` | `DatastoreAction::Access` |
|
||||
| GET | `DatastoreAction::Get { content_hash }` | `DatastoreAction::Access` |
|
||||
| DELETE | `DatastoreAction::Delete { content_hash }` | `DatastoreAction::Access` |
|
||||
| LIST | `DatastoreAction::List { name_filter }` | `DatastoreAction::Access` |
|
||||
| Grant/Revoke/etc. | `DatastoreAction::Access` | `DatastoreAction::Access` |
|
||||
|
||||
The browser uses `Access` for all operations because:
|
||||
- Computing content hashes client-side would add complexity to the browser JS.
|
||||
- The HTTP API already gates the actual data operation — the signed request only needs to prove identity.
|
||||
- The `Access` action maps to `DatastoreNodeMsg::Status` in the gateway (a lightweight no-op that returns a valid response).
|
||||
|
||||
The CLI uses per-action signing for data operations because it has access to the `ContentHash` and can construct precise action payloads.
|
||||
|
||||
In all cases, auth is enforced *before* the request reaches the actor system. Internal inter-node communication (DHT replication, chunk transfers between cluster members) is not subject to auth checks.
|
||||
|
||||
## 14. Future Extensions
|
||||
|
||||
These are explicitly **out of scope** for MVP but inform the design:
|
||||
|
||||
- **Per-path permission scoping** — restrict a key to specific path prefixes.
|
||||
- **Permission tiers** — read-only, read-write, admin roles.
|
||||
- **Capability tokens** — time-limited, scope-limited bearer tokens for delegated access.
|
||||
- **Multi-level delegation** — allow authorized users to grant limited access to others.
|
||||
- **Connection tracking** — forcibly disconnect revoked keys from active iroh sessions.
|
||||
- **Persistent access requests** — currently in-memory only; lost on node restart (browser re-submits on reload as mitigation).
|
||||
|
|
@ -1,278 +0,0 @@
|
|||
# Datastore Actor Reference
|
||||
|
||||
## Overview
|
||||
|
||||
The datastore is built from four actors within the swactor runtime. `DatastoreNode` is the public facade — all external requests (HTTP API, network protocol) enter through it and are routed to two long-lived worker actors: `BlobStoreActor` (content-addressed chunk/manifest I/O) and `MetadataActor` (object index, DHT replication, GC). A fourth actor, `TransferActor`, is spawned ephemerally for each remote download and self-terminates on completion or failure.
|
||||
|
||||
```
|
||||
┌─────────────────────────┐
|
||||
│ store_node (main) │
|
||||
│ spawns all 3 long-lived │
|
||||
│ actors, drives ticks │
|
||||
└────┬──────┬──────┬───────┘
|
||||
│ │ │
|
||||
spawn │ │ │ spawn
|
||||
┌──────────────┘ │ └──────────────┐
|
||||
▼ │ spawn ▼
|
||||
┌───────────────────┐ │ ┌───────────────────┐
|
||||
│ BlobStoreActor │ │ │ MetadataActor │
|
||||
│ (chunks, manifests)│ │ │ (index, DHT, GC) │
|
||||
└─────────▲─────────┘ │ └──▲────────┬───────┘
|
||||
│ ▼ │ │
|
||||
│ ┌───────────────────┐ │ │
|
||||
│ │ DatastoreNode │────┘ │
|
||||
│ │ (facade/router) │─────────────┘
|
||||
└────────────│ │
|
||||
└────────┬──────────┘
|
||||
│ spawns (per download)
|
||||
▼
|
||||
┌───────────────────┐
|
||||
│ TransferActor │
|
||||
│ (ephemeral) │
|
||||
└───────────────────┘
|
||||
|
||||
Arrows: ──▶ sends messages to
|
||||
```
|
||||
|
||||
## Actors
|
||||
|
||||
### DatastoreNode
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Role** | Top-level coordinator/facade. Accepts user-facing commands and incoming network protocol messages, delegates all work to `BlobStoreActor` and `MetadataActor`. |
|
||||
| **Source** | `crates/datastore/src/actors/datastore_node.rs` |
|
||||
| **Spawned by** | `store_node` binary (`crates/datastore/src/bin/store_node.rs:188`) |
|
||||
| **Lifecycle** | Long-lived — runs for the lifetime of the process |
|
||||
|
||||
**Inbound messages** (`DatastoreNodeMsg` — 11 variants):
|
||||
|
||||
User-facing commands:
|
||||
- `Put { data, name, tags, reply_to }` — chunk a blob, write chunks + manifest to `BlobStoreActor`, register in `MetadataActor`
|
||||
- `Get { content_hash, reply_to }` — retrieve object metadata + manifest via `MetadataActor`
|
||||
- `Delete { content_hash, reply_to }` — remove object via `MetadataActor`
|
||||
- `List { name_filter, all, reply_to }` — list objects (local or swarm-wide) via `MetadataActor`
|
||||
- `Status { reply_to }` — return this node's `NodeId`
|
||||
- `ReadChunk { hash, reply_to }` — read a single chunk via `BlobStoreActor`
|
||||
|
||||
Protocol routing (incoming network messages):
|
||||
- `IncomingGetChunk` — forwards to `BlobStoreActor::ReadChunk`
|
||||
- `IncomingGetManifest` — forwards to `BlobStoreActor::ReadManifest`
|
||||
- `IncomingStoreObject` — forwards to `MetadataActor::HandleStoreObject`
|
||||
- `IncomingFindObject` — forwards to `MetadataActor::HandleFindObject`
|
||||
- `IncomingListObjects` — forwards to `MetadataActor::ListLocal`
|
||||
|
||||
**Key outbound messages:**
|
||||
- `BlobStoreMsg::WriteChunk`, `WriteManifest`, `ReadChunk`, `ReadManifest` — to `BlobStoreActor`
|
||||
- `MetadataMsg::PutObject`, `GetObject`, `DeleteObject`, `ListLocal`, `ListSwarm`, `HandleStoreObject`, `HandleFindObject` — to `MetadataActor`
|
||||
- `DatastoreResponse::NodeStatus` — directly to caller for `Status`
|
||||
|
||||
---
|
||||
|
||||
### BlobStoreActor
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Role** | Content-addressed storage for chunks and manifests. All I/O goes through a pluggable `StorageBackend` (filesystem or in-memory). |
|
||||
| **Source** | `crates/datastore/src/actors/blob_store.rs` |
|
||||
| **Spawned by** | `store_node` binary (`store_node.rs:178`) |
|
||||
| **Lifecycle** | Long-lived — runs for the lifetime of the process |
|
||||
|
||||
**Inbound messages** (`BlobStoreMsg` — 8 variants):
|
||||
|
||||
Chunk operations:
|
||||
- `WriteChunk { hash, data, reply_to }` — persist a chunk, reply `ChunkStored`
|
||||
- `ReadChunk { hash, reply_to }` — read a chunk, reply `ChunkOk` or `NotFound`
|
||||
- `DeleteChunk { hash }` — remove a chunk (fire-and-forget)
|
||||
- `HasChunk { hash, reply_to }` — existence check, reply `Bool`
|
||||
- `ListChunks { reply_to }` — list all chunk hashes, reply `ChunkList`
|
||||
- `GcUnreferenced { referenced }` — delete chunks not in the referenced set (fire-and-forget)
|
||||
|
||||
Manifest operations:
|
||||
- `WriteManifest { manifest, reply_to }` — persist a manifest, reply `ManifestStored`
|
||||
- `ReadManifest { hash, reply_to }` — read a manifest, reply `ManifestOk` or `NotFound`
|
||||
|
||||
**Key outbound messages:**
|
||||
- `DatastoreResponse` variants (`ChunkStored`, `ChunkOk`, `ManifestStored`, `ManifestOk`, `NotFound`, `Error`, `Bool`, `ChunkList`) — always back to the `reply_to` address
|
||||
|
||||
---
|
||||
|
||||
### MetadataActor
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Role** | Object metadata index. Maintains a `HashMap<ContentHash, ObjectEntry>` and a manifest cache. Handles DHT-style find/store operations, epidemic dissemination of entries to peers, and periodic garbage collection. |
|
||||
| **Source** | `crates/datastore/src/actors/metadata.rs` |
|
||||
| **Spawned by** | `store_node` binary (`store_node.rs:185`) |
|
||||
| **Lifecycle** | Long-lived — runs for the lifetime of the process |
|
||||
|
||||
**Inbound messages** (`MetadataMsg` — 11 variants):
|
||||
|
||||
Object operations:
|
||||
- `PutObject { entry, manifest, reply_to }` — store metadata + manifest locally, enqueue for dissemination, reply `PutOk`
|
||||
- `GetObject { content_hash, reply_to }` — local lookup, reply `GetOk` or `NotFound`
|
||||
- `DeleteObject { content_hash, reply_to }` — remove from local index, reply `DeleteOk` or `NotFound`
|
||||
- `ListLocal { name_filter, reply_to }` — list local entries with optional name filter, reply `ListOk`
|
||||
- `ListSwarm { name_filter, reply_to }` — swarm-wide list (currently delegates to `ListLocal`)
|
||||
|
||||
DHT protocol:
|
||||
- `HandleFindObject { from, content_hash, reply_to }` — answer an incoming FIND_VALUE from a peer
|
||||
- `HandleStoreObject { entry, manifest }` — accept an incoming STORE from a peer (fire-and-forget)
|
||||
|
||||
Peer management:
|
||||
- `SetPeers { peers }` — update the list of peer `MetadataActor` addresses for dissemination
|
||||
|
||||
Periodic ticks (driven by the `store_node` main loop):
|
||||
- `DisseminateTick` — send pending entries to all known peers
|
||||
- `GcTick` — collect referenced chunks from all manifests, send `BlobStoreMsg::GcUnreferenced` to `BlobStoreActor`
|
||||
|
||||
**Key outbound messages:**
|
||||
- `DatastoreResponse` variants (`PutOk`, `GetOk`, `DeleteOk`, `ListOk`, `NotFound`, `Error`) — to caller
|
||||
- `MetadataMsg::HandleStoreObject` — to peer `MetadataActor` addresses during dissemination
|
||||
- `BlobStoreMsg::GcUnreferenced` — to local `BlobStoreActor` during GC
|
||||
|
||||
---
|
||||
|
||||
### TransferActor
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Role** | Manages a single object download from a remote node. Tracks pending/received chunks, forwards received data to the local `BlobStoreActor`, and reports completion or failure to the original requester. |
|
||||
| **Source** | `crates/datastore/src/actors/transfer.rs` |
|
||||
| **Spawned by** | `DatastoreNode` (one per remote download) |
|
||||
| **Lifecycle** | Ephemeral — self-terminates via `ctx.stop_self()` on completion, failure, or cancel |
|
||||
|
||||
**Inbound messages** (`TransferMsg` — 4 variants):
|
||||
|
||||
- `StartDownload { manifest, source_node, reply_to }` — initialize the download with a manifest and source
|
||||
- `ChunkReceived { hash, data }` — a chunk arrived from the remote node
|
||||
- `ChunkFailed { hash, reason }` — a chunk fetch failed (retries up to `max_retries`, then fails the whole transfer)
|
||||
- `Cancel` — abort the transfer immediately
|
||||
|
||||
**Key outbound messages:**
|
||||
- `BlobStoreMsg::WriteChunk` — to local `BlobStoreActor` for each received chunk
|
||||
- `DatastoreResponse::TransferComplete` — to `reply_to` when all chunks received
|
||||
- `DatastoreResponse::TransferFailed` — to `reply_to` when retries are exhausted
|
||||
|
||||
---
|
||||
|
||||
## Message Reference
|
||||
|
||||
All message types are defined in `crates/datastore/src/messages.rs`.
|
||||
|
||||
### Intra-node actor messages
|
||||
|
||||
| Enum | Variants | Handled by |
|
||||
|------|----------|------------|
|
||||
| `DatastoreNodeMsg` | 11 (6 user-facing + 5 protocol routing) | `DatastoreNode` |
|
||||
| `BlobStoreMsg` | 8 (5 chunk ops + 1 GC + 2 manifest ops) | `BlobStoreActor` |
|
||||
| `MetadataMsg` | 11 (5 object ops + 2 DHT + 1 peer mgmt + 2 ticks) | `MetadataActor` |
|
||||
| `TransferMsg` | 4 (start + chunk received + chunk failed + cancel) | `TransferActor` |
|
||||
|
||||
### Shared response enum
|
||||
|
||||
`DatastoreResponse` — 15 variants used as the return type for all four actors:
|
||||
|
||||
| Variant | Meaning |
|
||||
|---------|---------|
|
||||
| `PutOk { content_hash }` | Object stored successfully |
|
||||
| `GetOk { entry, manifest }` | Object found |
|
||||
| `DeleteOk { content_hash }` | Object deleted |
|
||||
| `ListOk { entries }` | List result |
|
||||
| `ChunkOk { hash, data }` | Chunk data retrieved |
|
||||
| `ChunkStored { hash }` | Chunk written to storage |
|
||||
| `ManifestStored { hash }` | Manifest written to storage |
|
||||
| `ManifestOk { manifest }` | Manifest retrieved |
|
||||
| `TransferComplete { content_hash }` | All chunks downloaded |
|
||||
| `TransferFailed { reason }` | Transfer failed |
|
||||
| `NodeStatus { node_id }` | Node identity |
|
||||
| `NotFound` | Resource not found |
|
||||
| `Error { reason }` | Generic error |
|
||||
| `Bool(bool)` | Boolean result (e.g. `HasChunk`) |
|
||||
| `ChunkList { hashes }` | List of chunk hashes |
|
||||
|
||||
### Inter-node wire messages (NetworkMessage)
|
||||
|
||||
| Struct | Direction | Purpose |
|
||||
|--------|-----------|---------|
|
||||
| `GetChunkRequest` | requester → holder | Fetch a chunk by hash |
|
||||
| `GetChunkResponse` | holder → requester | Return chunk data (or `None`) |
|
||||
| `StoreObjectRequest` | origin → DHT peer | Kademlia STORE for object metadata |
|
||||
| `FindObjectRequest` | requester → DHT peer | Kademlia FIND_VALUE for object metadata |
|
||||
| `FindObjectResponse` | DHT peer → requester | Return `Found(entry)` or `Closer(nodes)` |
|
||||
| `GetManifestRequest` | requester → holder | Fetch a manifest by content hash |
|
||||
| `GetManifestResponse` | holder → requester | Return manifest (or `None`) |
|
||||
| `ListObjectsRequest` | requester → peer | List objects with optional name filter |
|
||||
| `ListObjectsResponse` | peer → requester | Return matching entries |
|
||||
|
||||
Wire messages are distinguished from intra-node messages by implementing the `NetworkMessage` trait with a stable `type_tag()` string. They are serialized with serde for transport over iroh/QUIC.
|
||||
|
||||
---
|
||||
|
||||
## Key Flows
|
||||
|
||||
### Put (store a blob)
|
||||
|
||||
```
|
||||
Client → DatastoreNode::Put
|
||||
→ chunk_blob() splits data into chunks
|
||||
→ BlobStoreActor::WriteChunk (for each chunk, fire-and-forget)
|
||||
→ BlobStoreActor::WriteManifest
|
||||
→ MetadataActor::PutObject
|
||||
→ stores entry + manifest locally
|
||||
→ enqueues for dissemination
|
||||
→ replies DatastoreResponse::PutOk
|
||||
```
|
||||
|
||||
### Get (retrieve metadata)
|
||||
|
||||
```
|
||||
Client → DatastoreNode::Get
|
||||
→ MetadataActor::GetObject
|
||||
→ local index lookup
|
||||
→ replies DatastoreResponse::GetOk (or NotFound)
|
||||
```
|
||||
|
||||
### Data (reassemble from chunks)
|
||||
|
||||
See [streaming.md](streaming.md) for the full transfer protocol. In summary:
|
||||
|
||||
```
|
||||
API server → DatastoreNode::Get → MetadataActor (local miss)
|
||||
→ iterate peers:
|
||||
→ FindObjectRequest (wire) → peer MetadataActor
|
||||
→ GetManifestRequest (wire) → peer BlobStoreActor
|
||||
→ GetChunkRequest (wire) → peer BlobStoreActor (per chunk)
|
||||
→ BlobStoreActor::WriteChunk (store locally)
|
||||
→ BlobStoreActor::WriteManifest
|
||||
→ MetadataActor::PutObject
|
||||
→ reassemble_blob() → verify blake3 → respond
|
||||
```
|
||||
|
||||
### Dissemination (epidemic replication)
|
||||
|
||||
```
|
||||
store_node main loop (every disseminate_interval ticks)
|
||||
→ MetadataActor::DisseminateTick
|
||||
→ take_pending() selects entries with remaining budget
|
||||
→ for each peer: MetadataActor::HandleStoreObject
|
||||
→ peer inserts if absent, re-enqueues for further dissemination
|
||||
```
|
||||
|
||||
Budget per entry = `Λ * ceil(log2(cluster_size))` (SWIM-style, Λ=3).
|
||||
|
||||
### GC (garbage collection)
|
||||
|
||||
```
|
||||
store_node main loop (every gc_interval ticks)
|
||||
→ MetadataActor::GcTick
|
||||
→ scans all manifests → builds referenced chunk set
|
||||
→ BlobStoreActor::GcUnreferenced { referenced }
|
||||
→ deletes any chunk not in the referenced set
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Related
|
||||
|
||||
- [streaming.md](streaming.md) — chunking, transfer protocol, reassembly, and progress tracking
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
# Datastore Streaming Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
"Streaming" in the swactor datastore refers to **progressive chunk-based transfer**, not byte-level streaming. When an object is stored, it is split into fixed-size chunks, each content-addressed with blake3. When retrieved from a remote peer, chunks are fetched individually and reassembled — enabling progress tracking and partial recovery.
|
||||
|
||||
This design trades a small amount of per-chunk overhead for:
|
||||
- **Progress visibility**: the dashboard shows `chunks_received / chunks_total` in real time
|
||||
- **Resumability**: a failed transfer can (in principle) restart from the last chunk
|
||||
- **Deduplication**: identical chunks across objects are stored once
|
||||
|
||||
## Content-Addressed Chunking
|
||||
|
||||
The `chunk_blob()` function (`chunking.rs`) splits raw bytes into fixed-size pieces:
|
||||
|
||||
1. Compute `ContentHash = blake3(entire_blob)` — this is the object's identity
|
||||
2. Split the blob into `ceil(total_size / chunk_size)` pieces (default chunk size: 1 MB)
|
||||
3. For each piece, compute `chunk_hash = blake3(piece_bytes)`
|
||||
4. Build a `ChunkRef { hash, offset, size }` for each piece
|
||||
5. Return an `ObjectManifest` containing the full list of `ChunkRef`s
|
||||
|
||||
```
|
||||
Blob (5.2 MB, chunk_size=1MB)
|
||||
├── Chunk 0: hash=abc1…, offset=0, size=1048576
|
||||
├── Chunk 1: hash=def2…, offset=1048576, size=1048576
|
||||
├── Chunk 2: hash=789a…, offset=2097152, size=1048576
|
||||
├── Chunk 3: hash=bcd3…, offset=3145728, size=1048576
|
||||
└── Chunk 4: hash=ef45…, offset=4194304, size=1048576 (last: 209920 bytes)
|
||||
```
|
||||
|
||||
The object's identity (`ContentHash`) is the hash of the *entire* blob, not of the manifest. This means the same data always produces the same hash regardless of chunk size.
|
||||
|
||||
## Transfer Protocol
|
||||
|
||||
When a client requests an object via `GET /api/data?hash=...`, the API server:
|
||||
|
||||
1. Sends a `DatastoreNodeMsg::Get` to the local `DatastoreNode` actor
|
||||
2. If found locally, reads all chunks from the local `BlobStore` and reassembles
|
||||
3. If **not found locally**, enters `try_remote_get()`:
|
||||
|
||||

|
||||
|
||||
### Remote GET step-by-step
|
||||
|
||||
1. **Iterate peers**: for each known peer node:
|
||||
2. **FindObject**: send `MetadataMsg::HandleFindObject` to the peer's `MetadataActor`
|
||||
3. **Read manifest**: send `BlobStoreMsg::ReadManifest` to the peer's `BlobStore`
|
||||
4. **Fetch chunks**: for each `ChunkRef` in the manifest:
|
||||
- Send `BlobStoreMsg::ReadChunk` to the peer
|
||||
- Receive `DatastoreResponse::ChunkOk { hash, data }`
|
||||
- Store locally via `BlobStoreMsg::WriteChunk`
|
||||
- Update `DatastoreMetrics::advance_transfer()` for dashboard progress
|
||||
5. **Store manifest locally**: `BlobStoreMsg::WriteManifest`
|
||||
6. **Store metadata locally**: `MetadataMsg::PutObject`
|
||||
7. **Reassemble and respond**: `reassemble_blob()` concatenates chunks and verifies integrity
|
||||
|
||||
If a peer doesn't have the object (or any step fails), the loop continues to the next peer.
|
||||
|
||||
## Reassembly
|
||||
|
||||
`reassemble_blob()` (`chunking.rs`) takes a manifest and a set of `(hash, data)` pairs:
|
||||
|
||||
1. For each `ChunkRef` in manifest order, find the matching `(hash, data)` pair
|
||||
2. Concatenate all chunk data into a single buffer
|
||||
3. Compute `blake3(result)` and verify it matches `manifest.content_hash`
|
||||
4. Return the reassembled blob (or a `ChunkingError` on mismatch)
|
||||
|
||||
This integrity check ensures that even if individual chunks are corrupted or swapped, the final result is always verified against the original content hash.
|
||||
|
||||
## Progress Tracking
|
||||
|
||||
The `DatastoreMetrics` struct provides thread-safe transfer tracking:
|
||||
|
||||
```
|
||||
begin_transfer(hash, chunks_total) // called when remote GET starts
|
||||
advance_transfer(hash) // called after each chunk is stored locally
|
||||
end_transfer(hash) // called on completion or failure
|
||||
```
|
||||
|
||||
The dashboard SSE stream includes a `datastore` event every ~200ms with a `DatastoreSnapshot` containing `active_transfers: Vec<TransferProgress>`. The web UI renders these as animated progress bars.
|
||||
|
||||
```
|
||||
TransferProgress {
|
||||
hash: "abc123...",
|
||||
chunks_received: 3,
|
||||
chunks_total: 5,
|
||||
}
|
||||
```
|
||||
|
||||
## GC Integration
|
||||
|
||||
When an object is deleted, its `ObjectEntry` and `ObjectManifest` are removed from the `MetadataActor`. However, the underlying chunks are **not immediately deleted** — they may be referenced by other manifests (deduplication).
|
||||
|
||||
Instead, garbage collection runs periodically:
|
||||
|
||||
1. `MetadataMsg::GcTick` triggers a scan
|
||||
2. The `MetadataActor` collects all chunk hashes referenced by any live manifest
|
||||
3. Sends `BlobStoreMsg::GcUnreferenced` with the referenced set
|
||||
4. The `BlobStore` deletes any chunks **not** in the referenced set
|
||||
|
||||
This two-phase approach prevents data loss when chunks are shared between objects.
|
||||
|
||||

|
||||
|
|
@ -1,542 +0,0 @@
|
|||
# Process Abstraction for Swactor — Development History
|
||||
|
||||
> Design and implementation record for the "process" abstraction layer built
|
||||
> on top of swactor's actor primitives. This work ran across items 1–9 and
|
||||
> added 9 extension traits, 3 registries, and ~70 scenario tests.
|
||||
|
||||
## Context
|
||||
|
||||
Swactor is a distributed actor runtime with local primitives (spawn, send, stop, monitor,
|
||||
supervise) and distributed primitives (SWIM membership, Kademlia directory, cluster-wide naming,
|
||||
content-addressed datastore). The goal was to design a "process" abstraction that sits on top of
|
||||
these primitives, making the experience of running code on a swactor network feel closer to what
|
||||
an OS process feels like -- with access to an API for requesting resources and querying system
|
||||
state.
|
||||
|
||||
---
|
||||
## Part 1: OS Process Mapping
|
||||
|
||||
### Already strong (direct OS equivalents exist)
|
||||
|
||||
OS Concept: PID
|
||||
Swactor Equivalent: ActorAddress (32-byte random)
|
||||
Where: src/actor.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: fork+exec
|
||||
Swactor Equivalent: ctx.spawn(), Runtime::spawn()
|
||||
Where: src/actor.rs, src/runtime.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: exit(0)
|
||||
Swactor Equivalent: ctx.stop_self()
|
||||
Where: src/actor.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: kill(pid, SIGTERM)
|
||||
Swactor Equivalent: ctx.stop_actor(addr)
|
||||
Where: src/actor.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: SIGCHLD / waitpid
|
||||
Swactor Equivalent: ctx.monitor() -> Down, ctx.watch() -> ActorExited
|
||||
Where: crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: IPC (message queues)
|
||||
Swactor Equivalent: Typed message passing (local + cross-worker + cross-runtime)
|
||||
Where: src/actor.rs, src/transport.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Service names
|
||||
Swactor Equivalent: NameRegistry (local), ClusterRegistry (cluster CRDT)
|
||||
Where: crates/std/src/name_registry.rs, crates/distribution/src/registry.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Process groups
|
||||
Swactor Equivalent: GroupRegistry (join/leave/publish/members)
|
||||
Where: crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: init/systemd
|
||||
Swactor Equivalent: Supervisor with restart strategies
|
||||
Where: crates/std/src/supervisor.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Scheduler
|
||||
Swactor Equivalent: Worker pool with load-aware placement + per-actor message budgets
|
||||
Where: src/worker.rs, src/delivery.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Machine identity
|
||||
Swactor Equivalent: NodeId (ed25519 public key)
|
||||
Where: crates/distribution/src/types.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Cluster membership
|
||||
Swactor Equivalent: SWIM protocol
|
||||
Where: crates/distribution/src/swim/
|
||||
────────────────────────────────────────
|
||||
OS Concept: /proc, top, ps
|
||||
Swactor Equivalent: RuntimeStats, StatsHook, Dashboard, Investigate protocol
|
||||
Where: src/stats.rs, crates/dashboard/
|
||||
|
||||
### Implemented during this work
|
||||
|
||||
OS Concept: System introspection from inside
|
||||
Swactor Equivalent: CtxSystem (worker_id, num_workers, total_actors, uptime_ms) + SystemInfo
|
||||
Where: src/actor.rs, crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Per-actor introspection
|
||||
Swactor Equivalent: CtxSelfStats (messages_processed, mailbox_depth, message_type_counts)
|
||||
Where: src/actor.rs, src/worker.rs, crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Process lineage (getppid)
|
||||
Swactor Equivalent: CtxLineage (ctx.parent(), ctx.supervisor())
|
||||
Where: src/actor.rs, src/worker.rs, crates/std/src/ctx_ext.rs, crates/std/src/supervisor_registry.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Process environment (environ/getenv)
|
||||
Swactor Equivalent: CtxEnvironment (ctx.env::<T>(), ctx.environment(), SpawnBuilder for overrides)
|
||||
Where: src/actor.rs, src/worker.rs, crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Well-known environment keys (spawn metadata)
|
||||
Swactor Equivalent: SpawnTimestamp(u64) injected by StdExtension on_spawn hook;
|
||||
LogicalName(String) injected by spawn_named (ctx and runtime level)
|
||||
Where: src/actor.rs, src/extension.rs, src/worker.rs, crates/std/src/extension.rs,
|
||||
crates/std/src/ctx_ext.rs, crates/std/src/runtime_ext.rs, src/runtime.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Service discovery
|
||||
Swactor Equivalent: ServiceRegistry + CtxResources (ctx.resource::<S>() -> Option<ActorAddress>)
|
||||
Where: src/actor.rs, crates/std/src/service_registry.rs, crates/std/src/ctx_ext.rs,
|
||||
crates/std/src/runtime_ext.rs, crates/std/src/extension.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Resource request API (typed handles)
|
||||
Swactor Equivalent: ResourceHandle trait + CtxHandles (ctx.handle::<H>() -> Option<H>)
|
||||
Where: crates/std/src/resource_handle.rs, crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Exit codes / rich exit values
|
||||
Swactor Equivalent: ExitValue(Arc<dyn Any + Send + Sync>), ctx.stop_with(value),
|
||||
StopReason::Completed, ExitReason::Completed. Exit values propagated via Down/ActorExited.
|
||||
Where: src/actor.rs, src/worker.rs, crates/std/src/extension.rs, crates/std/src/watch_registry.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Parent-child hierarchy + orphan handling
|
||||
Swactor Equivalent: ChildrenRegistry tracks parent->children. On parent death, unsupervised
|
||||
children are killed (StopSignal). Supervised children are left to their supervisor. Cascades
|
||||
naturally across generations via tick-based cleanup.
|
||||
Where: crates/std/src/children_registry.rs, crates/std/src/extension.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Suspend/resume (SIGSTOP/SIGCONT)
|
||||
Swactor Equivalent: ctx.suspend_self(), ctx.resume(target) with auth (self or supervisor only).
|
||||
Suspended actors queue messages but don't process them. ResumeSignal via transfer queue for
|
||||
cross-worker resume.
|
||||
Where: src/actor.rs, src/worker.rs, src/runtime.rs, crates/std/src/ctx_ext.rs
|
||||
────────────────────────────────────────
|
||||
OS Concept: Capability model / sandboxing
|
||||
Swactor Equivalent: CapabilitySet stored in actor's Environment. Enforced at Ctx level (send,
|
||||
spawn, stop_actor, monitor, resource). Opt-in: actors without a CapabilitySet are unrestricted.
|
||||
Where: src/actor.rs, crates/std/src/ctx_ext.rs
|
||||
|
||||
### Still partially there
|
||||
|
||||
OS Concept: Resource limits
|
||||
What Exists: Mailbox capacity + message budget
|
||||
What's Missing: No per-actor memory/CPU/fd limits
|
||||
────────────────────────────────────────
|
||||
OS Concept: Auth/permissions
|
||||
What Exists: Datastore ACL + node-level peer auth + actor-level CapabilitySet
|
||||
What's Missing: Cluster-level capability propagation (local-only today)
|
||||
|
||||
---
|
||||
## Part 2: Design Primitives
|
||||
|
||||
The design followed the existing extension pattern: new capabilities were added as extension traits
|
||||
on Ctx<'_>, backed by registries in the extension system. This preserved backwards compatibility
|
||||
and kept the core minimal.
|
||||
|
||||
### 2.1 System Queries (CtxSystem)
|
||||
|
||||
What it enables: An actor can ask about the system it's running in.
|
||||
|
||||
Implemented queries (available via ctx.system_info() or the CtxSystem extension trait):
|
||||
- ctx.worker_id() -> usize -- which worker thread am I on?
|
||||
- ctx.num_workers() -> usize -- how many worker threads exist?
|
||||
- ctx.total_actors() -> usize -- live actors across all workers
|
||||
- ctx.uptime_ms() -> u64 -- milliseconds since runtime creation
|
||||
|
||||
Implementation: SystemInfo struct in src/actor.rs. ContextInner::system_info() implemented on
|
||||
both Runtime (for spawn-time context) and WorkerContext (for handler context). Data flows through
|
||||
TickContext (worker_stats + created_at fields in src/delivery.rs). The CtxSystem extension trait
|
||||
in crates/std/src/ctx_ext.rs provides ergonomic per-field accessors.
|
||||
|
||||
Future cluster-level queries (not yet implemented):
|
||||
- What is my node's identity (NodeId)?
|
||||
- How many cluster nodes are alive?
|
||||
- Who are the cluster members?
|
||||
|
||||
These require the distribution crate's DistributedNode state to be exposed through the extension
|
||||
system. The CtxSystem trait can be extended with these when the distribution integration is ready.
|
||||
|
||||
### 2.2 Process Environment (CtxEnvironment)
|
||||
|
||||
What it enables: Typed configuration that flows from parent to child at spawn time.
|
||||
|
||||
Properties:
|
||||
- Inherited: When actor A spawns actor B via ctx.spawn(), B gets A's environment (Arc clone)
|
||||
- Overridable: ctx.spawn_builder(actor).env(Key(val)).finish() lazily clones the parent's map
|
||||
on first override (copy-on-write), leaving the common case (no overrides) allocation-free
|
||||
- Immutable after spawn: Set at creation, read-only thereafter. Mutable config goes through
|
||||
messages.
|
||||
- Typed values: TypeId-keyed (like http::Extensions), not string-to-string
|
||||
- Runtime-spawned actors start with an empty environment
|
||||
|
||||
Implementation: Environment is Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>> -- clone is an
|
||||
Arc bump (zero allocation). EnvironmentBuilder provides from_env() for copy-on-write overrides
|
||||
(cloning individual entries is cheap since values are also Arc-wrapped). The spawn channel was
|
||||
replaced with a SpawnRequest struct (addr, actor, parent, env) to avoid further tuple growth.
|
||||
ActorSlot stores env, and Ctx receives it at both construction sites (tick_all and cleanup_dead).
|
||||
SpawnBuilder provides the ergonomic override API. The CtxEnvironment extension trait in
|
||||
crates/std/src/ctx_ext.rs provides the import path, following the same pattern as CtxLineage
|
||||
(no StdExtension dependency required). Python crate spawns with Environment::new(). 6 scenario
|
||||
tests in tests/std_extension.rs cover: inheritance, empty for runtime-spawned, grandchild chain,
|
||||
override-one-inherit-others, readable in on_stop, and sibling independence.
|
||||
|
||||
Well-known keys:
|
||||
- SpawnTimestamp(u64): Injected by StdExtension's on_spawn hook. Milliseconds since runtime
|
||||
creation, same time base as SystemInfo::uptime_ms. Opt-in at runtime level (present when
|
||||
StdExtension is installed). Read via ctx.env::<SpawnTimestamp>().
|
||||
- LogicalName(String): Injected by spawn_named() at both ctx and Runtime levels. Inherited by
|
||||
children via normal environment inheritance. Read via ctx.env::<LogicalName>().
|
||||
- ServiceBinding<S>(ActorAddress): Injected by ServiceRegistry's inject_into() hook during
|
||||
on_spawn. Registered at runtime level via rt.register_service::<S>(addr). Read via
|
||||
ctx.resource::<S>() (CtxResources trait). Overridable per-subtree via spawn_builder.
|
||||
- CapabilitySet: Granted at spawn time (via environment or spawn_builder). Inherited by children.
|
||||
Enforced at Ctx level. See section 2.7.
|
||||
|
||||
Analogy: Unix environ -- inherited by default, augmented at fork/exec time, readable via getenv().
|
||||
|
||||
### 2.3 Service Discovery (CtxResources)
|
||||
|
||||
What it enables: Actors can discover system services by type, not by knowing raw addresses.
|
||||
|
||||
How it differs from NameRegistry: NameRegistry maps strings to addresses. CtxResources maps
|
||||
service marker types to addresses. Looking up "datastore" by name gives you a raw ActorAddress and
|
||||
you must know what messages it accepts. ctx.resource::<Datastore>() gives you the address of the
|
||||
service registered under that marker type.
|
||||
|
||||
Implementation: Three layers compose the feature:
|
||||
|
||||
1. Core type: ServiceBinding<S>(ActorAddress) in src/actor.rs -- a generic environment key
|
||||
parameterized by a zero-sized marker type. Any struct satisfying 'static + Send + Sync works
|
||||
as a marker (no special Service trait required, consistent with Environment's existing API).
|
||||
|
||||
2. Registry + injection: ServiceRegistry in crates/std/src/service_registry.rs stores registered
|
||||
bindings as RwLock<HashMap<TypeId, Arc<dyn Any + Send + Sync>>> (same thread-safety pattern
|
||||
as SupervisorRegistry). StdExtension's on_spawn hook calls inject_into() before adding
|
||||
SpawnTimestamp -- this merges all registered bindings into the actor's environment, skipping
|
||||
keys already present (preserves per-subtree overrides set via spawn_builder). Helper methods
|
||||
on Environment (contains_type_id) and EnvironmentBuilder (set_raw) support type-erased
|
||||
injection without knowing concrete types at compile time.
|
||||
|
||||
3. Read API: CtxResources trait in crates/std/src/ctx_ext.rs provides ctx.resource::<S>() ->
|
||||
Option<ActorAddress>, a thin wrapper around ctx.env::<ServiceBinding<S>>().map(|b| b.addr).
|
||||
Does NOT require StdExtension -- reads from core environment (same pattern as CtxEnvironment).
|
||||
When a CapabilitySet is present, resource() checks check_service::<S>() and returns None if
|
||||
denied. RuntimeResources trait in crates/std/src/runtime_ext.rs provides
|
||||
rt.register_service::<S>(addr) for startup-time registration.
|
||||
|
||||
Key design decisions:
|
||||
- No Service marker trait: S: 'static + Send + Sync is sufficient. Any zero-size struct works.
|
||||
- "Skip if present" injection: The registry doesn't overwrite env keys set by spawn_builder,
|
||||
enabling per-subtree service overrides (e.g., test doubles, staging vs production services).
|
||||
- No cleanup on service actor death: A dead service's binding stays in the registry (stale
|
||||
address). Sends to it will fail. Service lifecycle management is a higher-level concern.
|
||||
|
||||
6 scenario tests in tests/std_extension.rs cover: discovery by marker type, child inherits
|
||||
binding from parent, multiple services each accessible by marker, unregistered returns None,
|
||||
overridable via spawn_builder, accessible in on_start and on_stop lifecycle hooks.
|
||||
|
||||
Well-known services that could be registered (when swactor-node is updated):
|
||||
- Storage -- content-addressed datastore (currently wired manually in swactor-node)
|
||||
- Directory -- actor location resolution (currently locked inside DistributedNode)
|
||||
- Cluster -- membership/topology info (currently snapshot-only for dashboard)
|
||||
- Metrics -- runtime stats (currently StatsHook push-only)
|
||||
|
||||
### 2.4 Resource Handles (CtxHandles)
|
||||
|
||||
What it enables: Domain-specific typed proxies that wrap service addresses and provide ergonomic
|
||||
APIs.
|
||||
|
||||
The pattern: A handle wraps (service_address, self_address) and provides methods that construct
|
||||
and send the right messages, embedding self_addr as reply_to. Responses arrive as normal messages
|
||||
in the actor's handle().
|
||||
|
||||
Implementation: The ResourceHandle trait in crates/std/src/resource_handle.rs defines the contract:
|
||||
- type Service: 'static + Send + Sync -- the marker type used for service discovery
|
||||
- from_parts(service_addr, self_addr) -> Self -- construct from addresses
|
||||
- service_addr() -> ActorAddress -- the underlying service address
|
||||
- self_addr() -> ActorAddress -- the actor's own address (for reply_to)
|
||||
|
||||
The CtxHandles extension trait in crates/std/src/ctx_ext.rs provides ctx.handle::<H>() -> Option<H>,
|
||||
which looks up ServiceBinding<H::Service> from the actor's environment and constructs the handle.
|
||||
Returns None if the service is not registered (consistent with ctx.resource(), ctx.where_is()).
|
||||
|
||||
Handle methods take &self + &Ctx (not stored &Ctx -- avoids lifetime issues with &mut self in
|
||||
handlers). Example:
|
||||
impl MyHandle {
|
||||
pub fn do_work(&self, ctx: &Ctx, data: Vec<u8>) -> Result<(), Error> {
|
||||
ctx.send(self.service_addr(), MyMsg::DoWork { data, reply_to: self.self_addr() })
|
||||
}
|
||||
}
|
||||
|
||||
Key design tension: Handles can't block (no await in swactor). The response arrives asynchronously
|
||||
as a message. This is inherent to the actor model and not something to "fix" -- the handle just
|
||||
makes the send side ergonomic.
|
||||
|
||||
5 scenario tests: handle wraps service and sends ergonomically, returns None when service not
|
||||
registered, inherits service binding from parent, constructible in on_start, two actors with same
|
||||
handle type each get responses at their own address.
|
||||
|
||||
### 2.5 Process Lineage (CtxLineage)
|
||||
|
||||
What it enables: Actors know their ancestry.
|
||||
|
||||
Implemented queries:
|
||||
- ctx.parent() -> Option<ActorAddress> (who spawned me?)
|
||||
Returns Some(spawner_addr) for actor-spawned children, None for Runtime::spawn().
|
||||
Available in handle(), on_start(), and on_stop().
|
||||
- ctx.supervisor() -> Option<ActorAddress> (who supervises me, if anyone?)
|
||||
Returns Some(supervisor_addr) for supervised children, None for unsupervised actors.
|
||||
Gracefully returns None when StdExtension is absent (no panic).
|
||||
|
||||
Implementation (parent): The spawn channel uses a SpawnRequest struct (addr, actor, parent, env) --
|
||||
the original 3-tuple was replaced when CtxEnvironment was added. When Ctx::spawn is called, the
|
||||
spawning actor's self_addr is passed as Some(parent). Runtime::spawn passes None. The parent is
|
||||
stored in ActorSlot::parent_addr and threaded into Ctx::self_parent_addr at both construction sites
|
||||
(tick_all and cleanup_dead). 4 scenario tests cover: child knows parent, runtime-spawned has no
|
||||
parent, grandchild sees immediate parent (not grandparent), and parent is visible in on_stop.
|
||||
|
||||
Implementation (supervisor): SupervisorRegistry in crates/std/src/supervisor_registry.rs stores a
|
||||
child_addr -> supervisor_addr map (RwLock<AddrMap<ActorAddress>>). Supervisor::start_child calls
|
||||
register(self_addr, child_addr) after spawning and monitoring. cleanup() removes entries where the
|
||||
dead address is either child or supervisor (O(n) scan for supervisor death, acceptable since
|
||||
supervisor death is rare and the map is small). CtxLineage::supervisor() downcasts the extension
|
||||
gracefully (returns None if StdExtension is absent). 5 scenario tests cover: supervised child knows
|
||||
supervisor, unsupervised actor returns None, supervisor survives child restart, grandchild not
|
||||
supervised but parent is, OneForAll restart re-registers all children.
|
||||
|
||||
The CtxLineage extension trait in crates/std/src/ctx_ext.rs provides the ergonomic import path.
|
||||
|
||||
Orphan handling was implemented as part of item 8 (Lifecycle Enrichment) -- see section 2.8.
|
||||
|
||||
### 2.6 Self-Introspection (CtxSelfStats)
|
||||
|
||||
What it enables: Actors can see their own operational metrics.
|
||||
|
||||
Implemented queries (available directly on Ctx or via the CtxSelfStats extension trait):
|
||||
- ctx.messages_processed() -> u64 -- total successfully processed before current tick
|
||||
- ctx.mailbox_depth() -> usize -- messages queued at start of current tick (pre-dequeue)
|
||||
- ctx.message_type_counts() -> &[(&str, u64)] -- per-type counts, sorted descending
|
||||
|
||||
Implementation: Stats are snapshotted from ActorSlot fields into Ctx before each tick_all
|
||||
iteration (src/worker.rs). The snapshot captures the state before any messages are dequeued
|
||||
in the current tick, giving actors a consistent view. The same snapshot is provided during
|
||||
on_stop callbacks in cleanup_dead. The CtxSelfStats extension trait in crates/std/src/ctx_ext.rs
|
||||
provides the ergonomic import path.
|
||||
|
||||
The Vec allocation for type counts is bounded (max 32 entries from ActorSlot's msg_type_counts
|
||||
cap) and negligible relative to handle_any cost.
|
||||
|
||||
### 2.7 Capability Model (CapabilitySet + CtxCapabilities)
|
||||
|
||||
What it enables: Controlled access to system resources and other actors. Primarily important for
|
||||
sandboxing untrusted code (wasm actors in crates/bin-runner/).
|
||||
|
||||
Approach: A single CapabilitySet stored in the actor's Environment. When present, enforcement is
|
||||
active -- the actor can only perform operations granted by the set. When absent, the actor is
|
||||
unrestricted (backward compatible). Capabilities inherit from parent to child via normal
|
||||
environment inheritance.
|
||||
|
||||
Capability grants (all in CapabilitySet):
|
||||
- with_send(addr) -- send any message type to a specific address
|
||||
- with_send_typed::<M>(addr) -- send only messages of type M to a specific address
|
||||
- with_spawn() -- permission to spawn new actors
|
||||
- with_service::<S>() -- permission to access system service S via ctx.resource::<S>()
|
||||
- with_monitor(addr) -- permission to monitor a specific actor
|
||||
|
||||
Enforcement points (all in src/actor.rs Ctx methods or crates/std/src/ctx_ext.rs):
|
||||
- ctx.send::<M>(addr, msg) -- checks check_send::<M>(addr); self-send always allowed
|
||||
- ctx.spawn() / SpawnBuilder::finish() -- checks check_spawn()
|
||||
- ctx.stop_actor(addr) -- checks check_send_addr(addr) (stop is a send of StopSignal)
|
||||
- ctx.monitor(addr) -- checks check_monitor(addr); returns Result<MonitorRef, Error>
|
||||
- ctx.resource::<S>() -- checks check_service::<S>(); returns None if denied
|
||||
|
||||
Key design decisions:
|
||||
- Opt-in: No CapabilitySet in environment means unrestricted. Zero behavioral change for existing
|
||||
actors. The only cost is an Option check (env.get::<CapabilitySet>()) at each enforcement point.
|
||||
- Enforcement at Ctx level only: The core ContextInner::send_any is not gated. This means
|
||||
extension code (supervisors, timers, etc.) that calls send_any directly bypasses capability
|
||||
checks, which is intentional -- system infrastructure is trusted.
|
||||
- Dual send granularity: with_send(addr) grants all message types to an address.
|
||||
with_send_typed::<M>(addr) grants only type M. The check tries address-only first, then typed.
|
||||
This allows coarse grants for trusted peers and fine-grained grants for untrusted actors.
|
||||
- Self-send always allowed: A restricted actor can always send to its own address. This prevents
|
||||
capabilities from breaking actors that use self-messaging patterns (timers, state machines).
|
||||
- monitor() returns Result: Changed from -> MonitorRef to -> Result<MonitorRef, Error>. This was
|
||||
a breaking change to all callers (supervisor.rs, router.rs, test files), fixed mechanically by
|
||||
adding ? or .unwrap().
|
||||
|
||||
Builder API: Fluent (CapabilitySet::new().with_send(addr).with_spawn()) and mutable
|
||||
(caps.grant_send(addr)) variants. Mutable methods return &mut Self for chaining.
|
||||
|
||||
Introspection: CtxCapabilities extension trait in crates/std/src/ctx_ext.rs provides:
|
||||
- ctx.capabilities() -> Option<&CapabilitySet> -- access the raw set
|
||||
- ctx.is_restricted() -> bool -- quick check
|
||||
|
||||
Implementation locations:
|
||||
- src/actor.rs: CapabilitySet struct, builder methods, check methods, Ctx::capabilities() helper,
|
||||
enforcement in send/spawn/stop_actor/SpawnBuilder::finish
|
||||
- src/lib.rs: CapabilitySet re-export
|
||||
- crates/std/src/ctx_ext.rs: CtxCapabilities trait, monitor() enforcement, resource() enforcement
|
||||
- crates/std/src/lib.rs: CtxCapabilities re-export
|
||||
|
||||
11 scenario tests in tests/std_extension.rs cover: unrestricted actor sends freely (backward
|
||||
compat), restricted actor denied send, restricted actor allowed send, typed send grant (Ping
|
||||
allowed / Pong denied), spawn denied, spawn allowed, capability inheritance (child inherits
|
||||
parent's CapabilitySet), monitor denied, service access denied, self-send always allowed, stop
|
||||
requires send permission.
|
||||
|
||||
### 2.8 Lifecycle Enrichment
|
||||
|
||||
Rich exit values: ExitValue(Arc<dyn Any + Send + Sync>) is an opaque typed wrapper. Actors stop
|
||||
with ctx.stop_with(value) which stores the value and triggers StopReason::Completed. The value
|
||||
is propagated through Down (monitors) and ActorExited (watchers) via the exit_value: Option<ExitValue>
|
||||
field. Manual PartialEq/Eq on ExitValue (always false -- opaque blob), so Down/ActorExited compare
|
||||
by addr+reason only.
|
||||
|
||||
Implementation: StopWithSignal(ExitValue) is a sentinel message intercepted in tick_all (like
|
||||
StopSignal). ActorSlot gains exit_value: Option<ExitValue>. cleanup_dead returns
|
||||
Vec<(ActorAddress, StopReason, Option<ExitValue>)> with StopReason::Completed when exit_value is
|
||||
present. The on_actor_death extension hook receives and propagates exit values to monitors/watchers.
|
||||
|
||||
7 scenario tests: stop_with value received in Down, received in ActorExited, normal stop has None,
|
||||
panic has None, multiple monitors receive cloned value, stop_with from on_start, supervisor receives
|
||||
rich exit in handle_down (graceful handoff pattern).
|
||||
|
||||
Orphan handling: ChildrenRegistry tracks parent -> set of children. Populated in on_spawn when a
|
||||
parent is present. On parent death (on_actor_death), unsupervised children receive StopSignal.
|
||||
Supervised children are left to their supervisor. Cascades naturally: parent dies -> children killed
|
||||
next tick -> grandchildren killed the tick after that. StopSignal made pub (was pub(crate)) to
|
||||
enable this -- it's not Message (not Clone) so can't be sent via ctx.send().
|
||||
|
||||
4 scenario tests: unsupervised children killed on parent death, supervised children not killed,
|
||||
cascading cleanup across generations, runtime-spawned actors unaffected.
|
||||
|
||||
Suspend/resume: ActorSlot gains a suspended: bool flag. Suspended actors queue messages but don't
|
||||
process them (tick_all skips them). ctx.suspend_self() sets the flag via a suspend_requests buffer.
|
||||
ResumeSignal is intercepted in deliver() to clear the flag. StopSignal/StopWithSignal are also
|
||||
intercepted for suspended actors (so stop_actor works on them). Cross-worker resume sends
|
||||
ResumeSignal via the transfer queue.
|
||||
|
||||
Authorization: CtxLifecycle extension trait provides ctx.suspend_self() (always allowed) and
|
||||
ctx.resume(target) which checks: target == self (self-resume) OR caller is the target's supervisor
|
||||
via SupervisorRegistry. Returns Err if unauthorized.
|
||||
|
||||
5 scenario tests: suspended actor queues then resume processes, supervisor can resume, non-supervisor
|
||||
cannot resume, suspended actor can be stopped, cross-worker resume via runtime.
|
||||
|
||||
Graceful handoff: Built on rich exit values. An outgoing actor stops with its state via
|
||||
ctx.stop_with(state); the supervisor receives it in handle_down's Down message and can pass it
|
||||
to the replacement's constructor. Enables zero-downtime upgrades. No additional mechanism needed --
|
||||
the pattern composes from existing primitives.
|
||||
|
||||
---
|
||||
## Part 3: How These Compose
|
||||
|
||||
The primitives form a layered system:
|
||||
|
||||
Layer 3: Integration (swactor-node wires services at startup)
|
||||
Layer 2: Process (CapabilitySet, ProcessBuilder)
|
||||
Layer 1: Std (CtxSystem, CtxEnvironment, CtxLineage, CtxSelfStats, Well-known env keys,
|
||||
SupervisorRegistry, CtxResources, CtxHandles, CtxLifecycle, ChildrenRegistry,
|
||||
CtxCapabilities)
|
||||
Layer 0: Core (SystemInfo, Ctx self-stats, parent tracking, Environment + SpawnRequest,
|
||||
on_spawn hook, spawn_with_env, ServiceBinding, suspend flag, rich exit, orphan
|
||||
handling, CapabilitySet)
|
||||
|
||||
A "process" in swactor is an actor that has:
|
||||
1. An identity (ActorAddress) and a name (NameRegistry)
|
||||
2. A parent and supervisor it can query (CtxLineage)
|
||||
3. An environment inherited from its spawner, with well-known keys (CtxEnvironment)
|
||||
4. Access to system services through discovery (CtxResources)
|
||||
5. The ability to query the system it lives in (CtxSystem)
|
||||
6. Awareness of its own operational state (CtxSelfStats)
|
||||
7. Typed resource handles for ergonomic service interaction (CtxHandles)
|
||||
8. Rich lifecycle support including typed exit values, orphan handling, and suspend/resume
|
||||
9. Controlled permissions for what it can access (CapabilitySet)
|
||||
|
||||
What stayed the same: The core actor model (message passing, mailboxes, workers, tick-based
|
||||
execution) was unchanged. ActorInterface, Ctx, Runtime remained the foundation. The process
|
||||
abstraction was additive -- existing actors continued to work exactly as before.
|
||||
|
||||
---
|
||||
## Part 4: Implementation Sequence
|
||||
|
||||
Each item was implemented and merged in dependency order. Earlier items established the
|
||||
infrastructure (Environment, extension hooks) that later items built on.
|
||||
|
||||
1. **CtxSystem + CtxSelfStats** -- Exposed existing internal data to actors. SystemInfo struct,
|
||||
ContextInner::system_info(), Ctx self-stats snapshot fields. Extension traits CtxSystem and
|
||||
CtxSelfStats in swactor-std. Covered by 3 scenario tests.
|
||||
|
||||
2. **CtxLineage (parent tracking)** -- Option<ActorAddress> threaded through the spawn path.
|
||||
ContextInner::spawn_any gained a parent parameter. ActorSlot stores parent_addr. Ctx exposes
|
||||
parent(). CtxLineage extension trait in swactor-std. 4 scenario tests.
|
||||
Python crate updated to pass parent on spawn.
|
||||
|
||||
3. **CtxEnvironment (process environment)** -- Typed key-value map inherited from parent to
|
||||
child at spawn time. Environment is Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>> -- clone
|
||||
is an Arc bump. EnvironmentBuilder supports copy-on-write overrides via from_env(). The spawn
|
||||
channel 3-tuple was replaced with a SpawnRequest struct (addr, actor, parent, env) to stop
|
||||
tuple growth. ActorSlot stores env. Ctx gains env::<T>(), environment(), and spawn_builder().
|
||||
SpawnBuilder lazily clones the parent's map on first .env() call. CtxEnvironment extension trait
|
||||
in swactor-std (no StdExtension dependency). Python crate spawns with Environment::new().
|
||||
6 scenario tests: inheritance, empty for runtime-spawned, grandchild chain,
|
||||
override-one-inherit-others, readable in on_stop, sibling independence.
|
||||
|
||||
4. **Well-known environment keys** -- SpawnTimestamp(u64) and LogicalName(String) types in
|
||||
src/actor.rs, exported from src/lib.rs. SpawnTimestamp is opt-in at runtime level: injected by
|
||||
StdExtension's on_spawn hook (new RuntimeExtension::on_spawn hook with default no-op in
|
||||
src/extension.rs). Worker::drain_spawns now takes &TickContext and calls on_spawn for each
|
||||
spawn request, passing uptime_ms to avoid exposing the pub(crate) Instant type. LogicalName is
|
||||
injected by spawn_named at both ctx level (via spawn_builder + env override) and runtime level
|
||||
(via new Runtime::spawn_with_env method). LogicalName inherits to children automatically via
|
||||
normal environment inheritance. 7 scenario tests.
|
||||
|
||||
5. **Supervisor lineage (ctx.supervisor())** -- SupervisorRegistry in
|
||||
crates/std/src/supervisor_registry.rs stores child_addr -> supervisor_addr as
|
||||
RwLock<AddrMap<ActorAddress>>. Supervisor::start_child calls register() after spawning and
|
||||
monitoring. cleanup() removes entries for dead actors (both as child and as supervisor).
|
||||
CtxLineage::supervisor() gracefully returns None when StdExtension is absent (downcasts via
|
||||
as_any, no panic). Distinct from parent() because not every parent is a supervisor. get_ext
|
||||
made pub(crate) so supervisor.rs can access it. 5 scenario tests.
|
||||
|
||||
6. **Service Registry + CtxResources** -- Actors discover system services by type
|
||||
(ctx.resource::<Datastore>()) rather than by raw address. ServiceBinding<S>(ActorAddress)
|
||||
is a generic environment key parameterized by a marker type. ServiceRegistry in StdExtension
|
||||
stores bindings and injects them into every actor's environment via on_spawn (skipping keys
|
||||
already present to preserve spawn_builder overrides). CtxResources trait provides
|
||||
ctx.resource::<S>() sugar. RuntimeResources trait provides rt.register_service::<S>(addr).
|
||||
6 scenario tests.
|
||||
|
||||
7. **Resource Handles (CtxHandles)** -- ResourceHandle trait + CtxHandles extension trait.
|
||||
ctx.handle::<H>() -> Option<H> constructs typed proxies from ServiceBinding<H::Service> in the
|
||||
actor's environment. Handle methods take &self + &Ctx for ergonomic domain-specific APIs.
|
||||
5 scenario tests.
|
||||
|
||||
8. **Lifecycle enrichment** -- Three sub-features:
|
||||
a) Rich exit values: ExitValue(Arc<dyn Any + Send + Sync>), ctx.stop_with(value),
|
||||
StopReason::Completed, ExitReason::Completed. Propagated through Down/ActorExited.
|
||||
7 scenario tests.
|
||||
b) Orphan handling: ChildrenRegistry tracks parent->children. Unsupervised children killed
|
||||
on parent death. Supervised children left to their supervisor. Natural cascade.
|
||||
4 scenario tests.
|
||||
c) Suspend/resume: ActorSlot::suspended flag, ctx.suspend_self(), ctx.resume(target) with
|
||||
auth (self or supervisor only). ResumeSignal for cross-worker resume.
|
||||
5 scenario tests.
|
||||
|
||||
9. **Capability model (CapabilitySet)** -- Per-actor permission set stored in the Environment.
|
||||
Grants: with_send(addr), with_send_typed::<M>(addr), with_spawn(), with_service::<S>(),
|
||||
with_monitor(addr). Enforced at Ctx level in send, spawn, stop_actor, monitor, and resource.
|
||||
Opt-in: actors without a CapabilitySet are unrestricted (zero behavioral change). Self-send
|
||||
always allowed. monitor() changed from -> MonitorRef to -> Result<MonitorRef, Error> (breaking
|
||||
change, fixed mechanically in supervisor.rs, router.rs, and all test files). CtxCapabilities
|
||||
extension trait for introspection. 11 scenario tests.
|
||||
|
|
@ -1,434 +0,0 @@
|
|||
# Process Runner Design: Async Process Management in Swactor
|
||||
|
||||
## Context
|
||||
|
||||
Swactor is a synchronous, tick-based actor framework (Erlang-inspired). Actors must return quickly from `handle()` — blocking stalls the entire worker thread. There is no built-in async I/O.
|
||||
|
||||
The goal: let actors manage long-lived async "processes" — OS subprocesses and SSH shells — with full lifecycle control. Must support both interactive use (live shell, bidirectional real-time I/O) and automated execution (run commands, stream output, report exit).
|
||||
|
||||
Constraints from discussion:
|
||||
- Backends: SSH + local processes (two backends, not more)
|
||||
- Scale: Architecture should support thousands; first implementation handles tens
|
||||
- This is a standalone new feature — not related to or derived from the CI runner system
|
||||
|
||||
---
|
||||
|
||||
## Architecture: State Machine + Driver + Process-as-Actor
|
||||
|
||||
### Data Flow (full picture)
|
||||
|
||||
```
|
||||
OS process stdout/stderr
|
||||
│ (background thread reads pipe)
|
||||
▼
|
||||
EventQueue (Arc<SegQueue>) — shared lock-free buffer
|
||||
│ (background thread calls ProcessWaker → ExternalSender → PollTick)
|
||||
▼
|
||||
Actor handle(PollTick)
|
||||
│ calls driver.poll() which drains EventQueue
|
||||
▼
|
||||
Vec<ProcessEvent>
|
||||
│
|
||||
▼
|
||||
session.apply(event) → Vec<ProcessAction>
|
||||
│
|
||||
├─ Driver commands → driver.execute(action) → OS I/O
|
||||
├─ Notifications → ctx.send(subscriber, ProcessNotification)
|
||||
└─ SelfTerminate → ctx.stop_self()
|
||||
```
|
||||
|
||||
### The Layers
|
||||
|
||||
| Layer | Purpose | Status |
|
||||
|-------|---------|--------|
|
||||
| 1 — ProcessSession | Pure-logic state machine | **Implemented** |
|
||||
| 2 — ProcessDriver trait + MockDriver | Driver abstraction + test double | **Implemented** |
|
||||
| 3 — Process Actor + ExternalSender | Swactor integration, waker, event queue | **Implemented** |
|
||||
| 4 — LocalDriver | `std::process::Command` + pipe I/O + signal | **Implemented** |
|
||||
| 5 — SshDriver | SSH library + channel I/O | Not started |
|
||||
|
||||
---
|
||||
|
||||
## Implemented: Layers 1 + 2 (Pure Logic)
|
||||
|
||||
Crate: `crates/process/` (`swactor-process`)
|
||||
|
||||
### Layer 1 — ProcessSession (State Machine)
|
||||
|
||||
The core state machine. Pure logic, no I/O, fully deterministic.
|
||||
|
||||
**States:** `Starting` → `Running` → `Stopping` → `Exited`
|
||||
|
||||
State transitions are monotonic — the state never goes backward. `Exited` is terminal.
|
||||
|
||||
**Construction:**
|
||||
|
||||
```rust
|
||||
let (session, initial_actions) = ProcessSession::new(spec);
|
||||
// initial_actions == [SpawnProcess { spec }]
|
||||
// session.state() == Starting
|
||||
```
|
||||
|
||||
**Event loop:**
|
||||
|
||||
```rust
|
||||
let actions = session.apply(event);
|
||||
for action in actions {
|
||||
match action {
|
||||
ProcessAction::SpawnProcess { .. } |
|
||||
ProcessAction::WriteStdin { .. } |
|
||||
ProcessAction::SendSignal { .. } |
|
||||
ProcessAction::ResizePty { .. } |
|
||||
ProcessAction::CloseStdin |
|
||||
ProcessAction::ScheduleKillTimeout { .. } => driver.execute(action),
|
||||
|
||||
ProcessAction::NotifyStarted { subscribers } |
|
||||
ProcessAction::NotifyOutput { subscribers, .. } |
|
||||
ProcessAction::NotifyExited { subscribers, .. } |
|
||||
ProcessAction::NotifyError { subscribers, .. } => { /* send to subscribers */ }
|
||||
|
||||
ProcessAction::SelfTerminate => { /* actor stops itself */ }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Key invariants (all verified by property-based tests):**
|
||||
- Invalid events produce `NotifyError` actions — never panic
|
||||
- `SelfTerminate` is always the last action when entering `Exited`
|
||||
- State monotonicity: Starting ≤ Running ≤ Stopping ≤ Exited
|
||||
- Subscriber count always matches add/remove operations
|
||||
- No panics for arbitrary event sequences
|
||||
|
||||
**Event handling by state:**
|
||||
|
||||
| Event | Starting | Running | Stopping | Exited |
|
||||
|-------|----------|---------|----------|--------|
|
||||
| Started | → Running (+ NotifyStarted) | error | error | error |
|
||||
| SpawnFailed | → Exited (+ NotifyError + SelfTerminate) | error | error | error |
|
||||
| OutputReceived | error | NotifyOutput | NotifyOutput | error |
|
||||
| Exited | error | → Exited (+ NotifyExited + SelfTerminate) | → Exited (+ NotifyExited + SelfTerminate) | error |
|
||||
| ConnectionLost | error | → Exited (+ NotifyError + SelfTerminate) | → Exited (+ NotifyError + SelfTerminate) | error |
|
||||
| WriteStdin | error | WriteStdin (or buffer/error) | error | error |
|
||||
| SendSignal | error | SendSignal | SendSignal (escalation) | error |
|
||||
| ResizePty | error | ResizePty | error | error |
|
||||
| CloseStdin | error | CloseStdin (+ clear buffer) | CloseStdin (+ set flag) | error |
|
||||
| CloseRequested | set deferred flag | → Stopping (+ SendSignal Terminate [+ ScheduleKillTimeout]) | no-op | error |
|
||||
| KillTimeout | silent | silent | SendSignal Kill | silent |
|
||||
| Subscribe | add subscriber | add subscriber | add subscriber | add subscriber |
|
||||
| Unsubscribe | remove subscriber | remove subscriber | remove subscriber | remove subscriber |
|
||||
| StdinWritten | update flow | update flow + drain buffer | update flow | update flow |
|
||||
| SignalSent | silent | silent | silent | silent |
|
||||
| PtyResized | silent | silent | silent | silent |
|
||||
|
||||
**Special behaviors:**
|
||||
- **Close-before-start:** If `CloseRequested` arrives in `Starting`, a flag is set. When `Started` arrives, the session transitions through Running straight to Stopping and emits `SendSignal(Terminate)` (plus `ScheduleKillTimeout` if configured).
|
||||
- **Kill timeout:** When `spec.kill_timeout` is `Some(duration)`, entering `Stopping` emits `ScheduleKillTimeout { duration }` alongside `SendSignal(Terminate)`. If the process hasn't exited when the timeout fires, the `KillTimeout` event triggers `SendSignal(Kill)`. `KillTimeout` in non-Stopping states is silently consumed (harmless late arrival after the process already exited).
|
||||
- **Backpressure:** When `spec.stdin_buffer_limit` is `Some(limit)` and `pending_stdin_bytes >= limit`, `WriteStdin` events are buffered in a `VecDeque` instead of emitting actions. When `StdinWritten` acks reduce `pending_stdin_bytes` below the limit, buffered writes drain in FIFO order. The buffer is cleared on `CloseRequested`, `CloseStdin`, `ConnectionLost`, and `Exited`. When `stdin_buffer_limit` is `None`, all writes pass through immediately (original behavior).
|
||||
- **FlowControl:** `pending_stdin_bytes` is incremented on `WriteStdin` emission, decremented on `StdinWritten` receipt (saturating).
|
||||
- **Stdin closed:** Once `CloseStdin` is applied, further `WriteStdin` events produce `InvalidState` errors. Duplicate `CloseStdin` is a no-op. Closing stdin also clears any buffered writes.
|
||||
- **Late acks in Exited:** `StdinWritten`, `SignalSent`, `PtyResized`, and `KillTimeout` are silently consumed in all states (including Exited) — they never produce errors.
|
||||
|
||||
### Types
|
||||
|
||||
**ProcessSpec** — describes how to spawn a process:
|
||||
- `command: String`, `args: Vec<String>`, `env: HashMap<String, String>`
|
||||
- `working_dir: Option<String>`, `mode: ProcessMode`, `initial_pty_size: Option<PtySize>`
|
||||
- `kill_timeout: Option<Duration>` — escalate SIGTERM → SIGKILL after this duration (None = no escalation)
|
||||
- `stdin_buffer_limit: Option<usize>` — buffer stdin writes when pending bytes exceed limit (None = unlimited)
|
||||
|
||||
**ProcessMode** — `Interactive` | `Automated` (Copy)
|
||||
|
||||
**ExitStatus** — `Code(i32)` | `Signal(i32)` | `Unknown` (Copy)
|
||||
|
||||
**Signal** — `Terminate` | `Kill` | `Hangup` | `Interrupt` | `Other(i32)` (Copy)
|
||||
|
||||
**ProcessError** — `SpawnFailed { reason }` | `ConnectionLost { reason }` | `InvalidState { attempted, current_state }`
|
||||
|
||||
**OutputStream** — `Stdout` | `Stderr` (Copy)
|
||||
|
||||
**SubscriberSet** — deduplicated `Vec<ActorAddress>` with linear-scan dedup. Methods: `add()`, `remove()`, `snapshot()`, `count()`.
|
||||
|
||||
### Layer 2 — ProcessDriver Trait + MockDriver
|
||||
|
||||
```rust
|
||||
pub trait ProcessDriver: Send {
|
||||
fn execute(&mut self, action: ProcessAction);
|
||||
fn poll(&mut self) -> Vec<ProcessEvent>;
|
||||
}
|
||||
```
|
||||
|
||||
**MockDriver** — test-oriented implementation:
|
||||
- `inject(event)` / `inject_many(events)` — queue events for `poll()`
|
||||
- `executed_actions()` — view recorded actions
|
||||
- `take_executed_actions()` — take + clear recorded actions
|
||||
- `pending_event_count()` — number of queued events
|
||||
- `poll()` drains all pending events, `execute()` records actions
|
||||
|
||||
---
|
||||
|
||||
## Implemented: Layers 3 + 4 (Actor Integration + Local OS Processes)
|
||||
|
||||
### ExternalSender (swactor core primitive)
|
||||
|
||||
A `Clone + Send + Sync` handle for injecting messages into actor mailboxes from any thread. Lives in the `swactor` crate (because `Envelope` and `AddressMap` are `pub(crate)`).
|
||||
|
||||
```rust
|
||||
// Create from a runtime
|
||||
let sender = runtime.create_sender();
|
||||
|
||||
// Use from any thread (including I/O background threads)
|
||||
sender.send_to(actor_addr, MyMessage { ... })?;
|
||||
```
|
||||
|
||||
**Implementation:** Clones of the runtime's `Arc<AddressMap>`, per-worker `Sender<Envelope>` channels, and `Arc<Vec<OnceLock<Thread>>>` for worker thread unparking. The `send_to` method looks up the actor's worker, pushes an envelope, and unparks the worker thread.
|
||||
|
||||
**Changes to swactor core:**
|
||||
- `src/channel.rs` — Added `Clone` for `Sender<T>` (clones the inner `Arc`)
|
||||
- `src/runtime.rs` — Changed `worker_threads` from `Vec<OnceLock<Thread>>` to `Arc<Vec<OnceLock<Thread>>>`, added `ExternalSender` struct and `Runtime::create_sender()` factory
|
||||
|
||||
### Layer 3 — Process Actor
|
||||
|
||||
**`ProcessActor<D: ProcessDriver>`** — generic actor implementing `ActorInterface` with `Incoming = ProcessCommand`.
|
||||
|
||||
**Message types:**
|
||||
|
||||
```rust
|
||||
pub enum ProcessCommand {
|
||||
WriteStdin { data: Vec<u8> },
|
||||
SendSignal { signal: Signal },
|
||||
ResizePty { size: PtySize },
|
||||
CloseStdin,
|
||||
Close,
|
||||
Subscribe { address: ActorAddress },
|
||||
Unsubscribe { address: ActorAddress },
|
||||
PollTick, // internal: sent by waker from I/O threads
|
||||
}
|
||||
|
||||
pub enum ProcessNotification {
|
||||
Started { process: ActorAddress },
|
||||
Output { process: ActorAddress, data: Vec<u8>, stream: OutputStream },
|
||||
Exited { process: ActorAddress, status: ExitStatus },
|
||||
Error { process: ActorAddress, error: ProcessError },
|
||||
}
|
||||
```
|
||||
|
||||
**Handle ordering:** Commands are processed first, then I/O events are drained. This ensures `Subscribe` registers the subscriber before `Started` (or other buffered events) get dispatched. `PollTick` has no command effect — it just triggers the drain.
|
||||
|
||||
**Event queue (`EventQueue`):** Thin wrapper around `Arc<SegQueue<ProcessEvent>>`. I/O threads push events; `driver.poll()` drains them.
|
||||
|
||||
**Waker (`ProcessWaker`):** `Arc<dyn Fn() + Send + Sync>` — constructed with a closure that sends `PollTick` via `ExternalSender`. I/O threads call `waker.wake()` after pushing events.
|
||||
|
||||
**Factory functions:**
|
||||
|
||||
```rust
|
||||
// Spawn with real OS subprocess
|
||||
let addr = spawn_local_process(ctx, &sender, spec)?;
|
||||
|
||||
// Spawn with custom driver (for testing)
|
||||
let addr = spawn_process(ctx, &sender, spec, driver, waker_slot)?;
|
||||
```
|
||||
|
||||
The factory creates the driver, session, and actor, spawns it, then fills the waker slot with a closure that sends `PollTick` to the actor's address.
|
||||
|
||||
### Layer 4 — LocalDriver
|
||||
|
||||
Real OS process management via `std::process::Command` with piped I/O.
|
||||
|
||||
**Components:**
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `local/mod.rs` | `LocalDriver` struct, `ProcessDriver` impl, process spawning |
|
||||
| `local/pipes.rs` | Background thread reading stdout/stderr pipes (8KB buffer) |
|
||||
| `local/signal.rs` | `Signal` → libc constant mapping, `kill()` wrapper |
|
||||
| `local/wait.rs` | Background `waitpid()` thread with WIFEXITED/WIFSIGNALED decoding |
|
||||
|
||||
**Thread structure per process:**
|
||||
- 1 stdout reader thread
|
||||
- 1 stderr reader thread
|
||||
- 1 waitpid thread
|
||||
|
||||
Each thread pushes events to the shared `EventQueue` and calls `waker.wake()`.
|
||||
|
||||
**Drop behavior:** Closes stdin, kills the process, waits for exit.
|
||||
|
||||
**PTY support:** Not yet implemented — `ResizePty` is a no-op that returns a `PtyResized` ack. Pipe-based I/O only in this phase.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
swactor (root crate):
|
||||
src/
|
||||
channel.rs — + Clone for Sender<T>
|
||||
runtime.rs — + ExternalSender, create_sender(), Arc<worker_threads>
|
||||
|
||||
crates/process/ (swactor-process):
|
||||
Cargo.toml — + crossbeam-queue, libc deps
|
||||
src/
|
||||
lib.rs — module declarations + re-exports
|
||||
types.rs — ProcessSpec, ProcessMode, ExitStatus, Signal, PtySize, etc.
|
||||
event.rs — ProcessEvent enum
|
||||
action.rs — ProcessAction enum + OutputStream
|
||||
subscriber.rs — SubscriberSet
|
||||
session.rs — ProcessSession state machine
|
||||
driver.rs — ProcessDriver trait
|
||||
mock.rs — MockDriver
|
||||
queue.rs — EventQueue (Arc<SegQueue>)
|
||||
waker.rs — ProcessWaker (Arc<dyn Fn>)
|
||||
message.rs — ProcessCommand, ProcessNotification
|
||||
actor.rs — ProcessActor<D> impl ActorInterface
|
||||
spawn.rs — spawn_local_process(), spawn_process() factory functions
|
||||
local/
|
||||
mod.rs — LocalDriver struct + ProcessDriver impl
|
||||
pipes.rs — Pipe reader background threads
|
||||
signal.rs — OS signal delivery
|
||||
wait.rs — waitpid background thread
|
||||
tests/
|
||||
session_scenarios.rs — 26 session state machine scenario tests
|
||||
proptest_session.rs — 5 property-based session tests (KillTimeout included in arb_event)
|
||||
actor_scenarios.rs — 6 actor integration tests (TestDriver)
|
||||
local_driver.rs — 6 LocalDriver integration tests (real processes)
|
||||
e2e_process.rs — 2 end-to-end tests (Runtime + LocalDriver + real processes)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Test Coverage
|
||||
|
||||
### Layers 1 + 2 — Session + MockDriver (31 tests)
|
||||
|
||||
**Scenario tests** (26 tests in `tests/session_scenarios.rs`):
|
||||
1. Happy path automated: new → Started → OutputReceived×N → Exited(0)
|
||||
2. Interactive session with subscriber lifecycle (add/remove, verify notification membership)
|
||||
3. Spawn failure → error notification + SelfTerminate
|
||||
4. Connection loss mid-run → Exited with Unknown status
|
||||
5. Close before start → deferred SIGTERM on belated start
|
||||
6. Invalid event in Starting → NotifyError (no panic)
|
||||
7. Invalid event in Exited → NotifyError (no panic)
|
||||
8. Stdin closed then write → NotifyError
|
||||
9. MockDriver round-trip (driver + session in simulated tick loop)
|
||||
10. Signal escalation in Stopping (Kill after Terminate)
|
||||
11. Late acks in Exited silently consumed
|
||||
12. Flow control tracks pending stdin bytes (including saturating subtract)
|
||||
13. CloseStdin allowed in Stopping
|
||||
14. Connection loss in Stopping → Exited
|
||||
15. Duplicate CloseRequested in Stopping → no-op
|
||||
16. CloseRequested with kill_timeout emits both SendSignal{Terminate} and ScheduleKillTimeout
|
||||
17. Close-before-start with kill_timeout schedules timer on belated start
|
||||
18. KillTimeout in Stopping → SendSignal{Kill}, state stays Stopping
|
||||
19. KillTimeout silently consumed in Starting, Running, Exited
|
||||
20. CloseRequested without kill_timeout emits no ScheduleKillTimeout
|
||||
21. Full escalation flow: CloseRequested → KillTimeout → Exited{Signal(9)}
|
||||
22. Backpressure buffers writes when pending bytes exceed limit
|
||||
23. StdinWritten ack drains buffered chunks in FIFO order
|
||||
24. CloseRequested clears stdin buffer
|
||||
25. No backpressure when limit is None (all writes pass through)
|
||||
26. Exited clears stdin buffer
|
||||
|
||||
**Property-based tests** (5 tests in `tests/proptest_session.rs`):
|
||||
1. No panics for arbitrary event sequences (up to 50 events, including KillTimeout)
|
||||
2. Exited is terminal (state never leaves Exited)
|
||||
3. SelfTerminate always last action when entering Exited
|
||||
4. Subscriber count matches add/remove operations
|
||||
5. State monotonicity (state ordinal never decreases)
|
||||
|
||||
### Layer 3 — Actor Integration (6 tests)
|
||||
|
||||
Tests in `tests/actor_scenarios.rs` using a `TestDriver` (shared `EventQueue` + recorded actions):
|
||||
|
||||
1. **Happy path** — spawn → Started → Output → Exited → subscriber gets all notifications → actor stops
|
||||
2. **PollTick drains queued events** — three events buffered, single PollTick delivers all three notifications
|
||||
3. **Close triggers graceful shutdown** — Close command produces SIGTERM via driver
|
||||
4. **WriteStdin/SendSignal forwarded** — commands reach the driver as actions
|
||||
5. **Spawn failure** — error notification sent to subscriber, actor self-terminates
|
||||
6. **Subscribe/Unsubscribe routing** — two subscribers, unsubscribe one, only remaining gets subsequent notifications
|
||||
|
||||
### Layer 4 — LocalDriver Integration (6 tests)
|
||||
|
||||
Tests in `tests/local_driver.rs` using real OS processes, no actor layer:
|
||||
|
||||
1. **`echo hello`** — Started + OutputReceived("hello\n") + Exited(0)
|
||||
2. **`cat` stdin echo** — write "ping\n" → read "ping\n" back → close stdin → Exited(0)
|
||||
3. **`sleep 60` + SIGTERM** — Started → send Terminate → Exited(Signal)
|
||||
4. **Bad command** → SpawnFailed
|
||||
5. **`seq 1 10000`** — large output integrity (no data loss, correct start/end)
|
||||
6. **Kill timeout escalation** — spawn SIGTERM-ignoring process, ScheduleKillTimeout fires KillTimeout, SIGKILL terminates it
|
||||
|
||||
### End-to-End (2 tests)
|
||||
|
||||
Tests in `tests/e2e_process.rs` — full stack (Runtime + ExternalSender + ProcessActor + LocalDriver + real process):
|
||||
|
||||
1. **`echo hello` lifecycle** — spawn, subscribe, verify Started → Output("hello") → Exited(0) in order
|
||||
2. **Bad command** — spawn nonexistent binary, verify Error notification arrives
|
||||
|
||||
---
|
||||
|
||||
## Design Decisions Made
|
||||
|
||||
1. **ExternalSender over WorkerExtension:** The I/O → actor bridge is a general-purpose swactor core primitive, not process-specific. Any crate can use `ExternalSender` to inject messages from background threads.
|
||||
|
||||
2. **Handle ordering (command first, then drain):** Processing the incoming command before draining I/O events ensures that `Subscribe` registers the subscriber before buffered events (like `Started`) are dispatched. This avoids a race where early lifecycle events are sent to an empty subscriber list.
|
||||
|
||||
3. **ProcessActor is generic over `D: ProcessDriver`:** Enables testing with `TestDriver` while production uses `LocalDriver`. No trait object overhead.
|
||||
|
||||
4. **Thread-per-pipe model:** Each LocalDriver spawns 3 threads (stdout reader, stderr reader, waitpid). Simple, debuggable, correct for Phase 1 (tens of processes).
|
||||
|
||||
5. **EventQueue is lock-free:** Uses `crossbeam_queue::SegQueue` — no contention between I/O writer threads and the actor's poll draining.
|
||||
|
||||
6. **Waker uses OnceLock:** The waker slot (`Arc<OnceLock<ProcessWaker>>`) is filled after the actor address is known. I/O threads that call `waker.get()` before it's set simply skip the wake — events accumulate in the EventQueue and are drained on the next message.
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Near-term
|
||||
|
||||
1. **PTY support for Interactive mode** — The `LocalDriver` currently uses pipes only. Interactive mode needs PTY allocation (via raw libc: `openpty()` → `fork()` → `setsid()` + `ioctl(TIOCSCTTY)` + `dup2` + `execvp`), `SIGWINCH` for resize, and merged stdout/stderr on a single PTY master FD. The `ResizePty` action is already wired through as a no-op.
|
||||
|
||||
2. **Output buffering policies** — Subscribers currently receive every raw byte chunk. Add optional line-buffering or size-buffering in the session layer for consumers that want complete lines.
|
||||
|
||||
### Layer 5 — SshDriver
|
||||
|
||||
SSH-based process management. Same `ProcessDriver` trait, different backend.
|
||||
|
||||
**Open decisions:**
|
||||
- **SSH library:** `russh` (pure Rust, async — needs tokio bridge) vs. `ssh2` (libssh2 bindings, synchronous — fits the thread model naturally)
|
||||
- **Authentication:** Password, key file, agent forwarding, or pluggable credential provider
|
||||
- **Connection multiplexing:** One SSH connection per process actor, or connection pool with multiple channels
|
||||
- **Health monitoring:** Heartbeat/keepalive to detect connection drops → `ConnectionLost` events
|
||||
|
||||
### Scaling Path
|
||||
|
||||
The architecture isolates scaling concerns in the driver layer:
|
||||
|
||||
- **Phase 1 (tens):** Each driver spawns OS threads for I/O. Simple, debuggable. ← **current**
|
||||
- **Phase 2 (hundreds):** Shared thread pool for driver I/O. Replace per-process threads with a pool that multiplexes reads across processes.
|
||||
- **Phase 3 (thousands):** Async internals (tokio tasks for I/O). State machine and actor layers unchanged — only `ProcessDriver` implementations change.
|
||||
|
||||
---
|
||||
|
||||
## Alternative Approaches Considered
|
||||
|
||||
### WorkerExtension Approach
|
||||
|
||||
Managing processes as a per-worker extension (like TimerWheel). Rejected because:
|
||||
- Ties processes to specific workers, complicating supervision
|
||||
- Processes can't benefit from the actor model's naming, grouping, and monitoring
|
||||
- The API would be less intuitive than "send a message to the process"
|
||||
- Tick-bound latency is problematic for interactive use
|
||||
|
||||
### Pure Bridge Actor Approach
|
||||
|
||||
A single centralized bridge actor owning all processes (like IrohDriver). Rejected as the primary design because:
|
||||
- Doesn't give individual processes actor identity — can't supervise, name, or monitor them independently
|
||||
- Centralizes failure — the bridge dying kills all processes
|
||||
- However, this pattern does appear inside the recommended approach: the driver layer within each process actor is essentially a tiny bridge
|
||||
|
||||
### Pure Process-as-Actor (without state machine)
|
||||
|
||||
Just actors with embedded I/O logic, no state machine separation. Rejected because:
|
||||
- Untestable without real processes or SSH connections
|
||||
- Can't simulate
|
||||
- Backend-specific logic (SSH vs. local) interleaved with lifecycle logic
|
||||
|
|
@ -1,475 +0,0 @@
|
|||
Swactor Stream Primitive -- Architectural Design
|
||||
|
||||
Context
|
||||
|
||||
Swactor has a distributed actor runtime with SWIM membership, Kademlia routing, and a content-addressed datastore. The current datastore
|
||||
transfers blobs one chunk at a time via actor message round-trips -- extremely slow for large objects. Beyond the datastore, the system
|
||||
needs a general-purpose bulk data transfer primitive for ML workloads (training data, weight checkpoints, gradient exchange), real-time
|
||||
media (video/voice), and future game state replication.
|
||||
|
||||
The stream primitive is a high-performance data channel between nodes that actors negotiate and manage but do not sit on the data path of.
|
||||
It should achieve top-class throughput by leveraging QUIC's multiplexed streams directly, bypassing the actor mailbox system for data
|
||||
transfer.
|
||||
|
||||
Decisions made:
|
||||
- Data path: StreamHandle with try_read/try_write; actors receive lightweight notification messages but data bypasses mailboxes
|
||||
- Reliability: Reliable-only MVP; abstraction designed so unreliable (QUIC datagrams) can be added later
|
||||
- Locality: Cross-node only; same-node actors use regular messages
|
||||
- Crate: New crates/streams/ crate
|
||||
|
||||
---
|
||||
1. Core Concept: Control Plane vs Data Plane
|
||||
|
||||
The fundamental architecture separates stream management (control plane) from data transfer (data plane).
|
||||
|
||||
Control plane -- actor messages through normal mailboxes:
|
||||
- Stream negotiation (open, accept, reject)
|
||||
- Parameter configuration (buffer sizes, chunk sizes, parallelism)
|
||||
- Lifecycle events (established, closed, error)
|
||||
- Progress/health notifications
|
||||
|
||||
Data plane -- bypasses actors entirely:
|
||||
- Raw bytes flow through QUIC streams on the iroh transport
|
||||
- Managed by async tasks on the IrohDriver's tokio runtime
|
||||
- Actors interact via StreamHandle objects (try_read/try_write), not mailbox messages
|
||||
- QUIC's built-in flow control handles backpressure
|
||||
|
||||
CONTROL PLANE (actor messages, mailboxes, worker ticks)
|
||||
+--------+ StreamOpen +-----------+ StreamAccept +--------+
|
||||
| Actor | -----------> | Stream | <------------- | Actor |
|
||||
| (nodeA)| | Manager | |(nodeB) |
|
||||
+--------+ +-----------+ +--------+
|
||||
| | |
|
||||
| StreamReady(handle) | | StreamReady(handle)
|
||||
v v v
|
||||
DATA PLANE (tokio tasks, QUIC streams, pre-allocated buffers)
|
||||
+----------+ bytes +----------+ bytes +----------+
|
||||
| SendHalf | =========> | QUIC | =========> | RecvHalf |
|
||||
| (writer) | N parallel| streams | N parallel | (reader) |
|
||||
+----------+ stripes +----------+ stripes +----------+
|
||||
|
||||
---
|
||||
2. Stream Identity and Addressing
|
||||
|
||||
StreamId: A 16-byte random identifier, generated by the initiator during negotiation. Deliberately not an ActorAddress -- streams are not
|
||||
actors, are not placed on workers, and are not discoverable via Kademlia. Keeping them out of the AddressMap avoids polluting the actor
|
||||
routing hot path.
|
||||
|
||||
Full stream address: The tuple (NodeId, StreamId) is globally unique. A node can host many concurrent streams to many peers.
|
||||
|
||||
ALPN separation: Streams use a new protocol identifier swactor/stream/1, separate from the existing swactor/swim/1 used for membership.
|
||||
This means:
|
||||
- The iroh accept loop can distinguish stream connections from protocol messages immediately
|
||||
- Stream data never blocks or interferes with cluster heartbeats
|
||||
- Stream connections can have different tuning in the future
|
||||
|
||||
---
|
||||
3. QUIC Stream Utilization
|
||||
|
||||
Parallel Stripes for Blob Transfers
|
||||
|
||||
For a single large transfer, multiple QUIC streams are opened in parallel on the same QUIC connection. Each stream carries a disjoint
|
||||
range of the data. This is the stripe count, negotiated during handshake (default: 4).
|
||||
|
||||
Why multiple streams? A single QUIC stream can be limited by per-stream receive-window backpressure. Multiple streams allow the sender to
|
||||
push data into QUIC's send buffer more aggressively, keeping the congestion window filled. Measurements from quinn/s2n-quic show 2-8
|
||||
parallel streams can improve throughput 2-4x on high-bandwidth-delay-product links.
|
||||
|
||||
Stream layout per transfer:
|
||||
- Stream 0 (control stream): Bidirectional QUIC stream. Carries the handshake header and out-of-band signals (completion, cancel, errors,
|
||||
health). Stays open for the transfer's lifetime.
|
||||
- Streams 1..N (data stripes): Unidirectional QUIC streams, each carrying sequential chunks. Stripe assignment is round-robin by chunk
|
||||
index.
|
||||
|
||||
Connection Reuse
|
||||
|
||||
Multiple concurrent streams between the same two nodes share one QUIC connection (on the stream ALPN). QUIC multiplexing handles this
|
||||
natively. The streams crate maintains a connection cache separate from the SWIM connection cache.
|
||||
|
||||
---
|
||||
4. Wire Format
|
||||
|
||||
Two layers of wire format: the stream-level protocol (negotiation + data framing) and the blob transfer application protocol that rides on
|
||||
top of it.
|
||||
|
||||
Control Stream Header (stream-level)
|
||||
|
||||
[2B magic: 0x53 0x57] -- "SW"
|
||||
[1B version: 0x01]
|
||||
[16B StreamId]
|
||||
[1B mode] -- 0x01=BlobTransfer, 0x02=ContinuousStream (future)
|
||||
[1B stripe_count] -- parallel data stripes (1-255)
|
||||
[4B frame_size (BE u32)] -- maximum frame payload size in bytes
|
||||
[4B metadata_len (BE u32)]
|
||||
[N bytes metadata] -- negotiation payload (e.g., ContentHash for blob transfer)
|
||||
|
||||
Data Stripe Frame Format (stream-level)
|
||||
|
||||
[4B frame_len (BE u32)] -- 0 = end-of-stripe
|
||||
[N bytes payload] -- raw data bytes
|
||||
|
||||
Deliberately minimal. No per-frame type tags (QUIC provides ordered reliable delivery), no per-frame checksums on the wire (QUIC provides
|
||||
TLS integrity for transport), no per-frame metadata. Every byte of overhead on the hot path costs throughput.
|
||||
|
||||
BlobTransfer Application Protocol
|
||||
|
||||
For blob transfers, the `StreamConfig.metadata` carries the 32-byte `ContentHash` of the requested blob (so the serve side knows what to
|
||||
send). The actual blob data flows over the StreamHandle with this application-level framing:
|
||||
|
||||
[4B manifest_json_length (u32 BE)]
|
||||
[N bytes manifest JSON] -- serialized ObjectManifest
|
||||
[chunk_0 raw bytes] -- size from manifest.chunks[0].size
|
||||
[chunk_1 raw bytes] -- size from manifest.chunks[1].size
|
||||
...
|
||||
|
||||
The receiver knows each chunk's expected size and blake3 hash from the manifest. Each chunk is verified individually on arrival:
|
||||
blake3(chunk_data) == chunk_ref.hash. Corrupted chunks cause immediate transfer failure. This is implemented by the `send_blob` and
|
||||
`recv_blob` async functions in `crates/datastore/src/blob_transfer.rs`.
|
||||
|
||||
Note: the blob transfer protocol sends chunks sequentially through the StreamHandle, which distributes data frames across stripes via the
|
||||
data-plane layer's round-robin. Individual chunks are not split across stripes -- the stripe layer is transparent to the application
|
||||
protocol.
|
||||
|
||||
---
|
||||
5. Buffering Strategy
|
||||
|
||||
Pre-allocated Sliding Window (Zero Allocation on Hot Path)
|
||||
|
||||
The buffer pool is a sliding window, not a store. It never holds the entire blob in memory -- data flows through it like water through a
|
||||
pipe. A 1TB transfer uses the same ~4MB of buffer memory as a 1MB transfer; only the duration changes.
|
||||
|
||||
All buffers are allocated during stream setup, not per-frame.
|
||||
|
||||
Sender pipeline (per stripe, double-buffered):
|
||||
Source (disk/memory/computation)
|
||||
→ [Buffer A: being filled from source]
|
||||
→ [Buffer B: being written to QUIC]
|
||||
→ Buffer B recycled → becomes the next Buffer A
|
||||
→ repeat until source exhausted
|
||||
One buffer is being filled while the other is being sent. When QUIC accepts Buffer B's bytes, it's recycled and refilled from the source.
|
||||
The source can be disk I/O, a computation producing data, or anything that yields bytes.
|
||||
|
||||
Receiver pipeline (per stripe, double-buffered):
|
||||
QUIC recv stream
|
||||
→ [Buffer A: being filled from QUIC]
|
||||
→ [Buffer B: being written to disk/consumed]
|
||||
→ Buffer B recycled → becomes the next Buffer A
|
||||
→ repeat until stream ends
|
||||
The receiver reads from QUIC into one buffer while the previous buffer is being written to disk (for blob transfer) or consumed by the
|
||||
application. Buffers are recycled, never allocated mid-transfer.
|
||||
|
||||
Backpressure chain (end-to-end):
|
||||
Source read speed
|
||||
→ fills sender buffer pool (2 per stripe)
|
||||
→ QUIC congestion window
|
||||
→ network bandwidth
|
||||
→ QUIC receive window
|
||||
→ fills receiver buffer pool (2 per stripe)
|
||||
→ sink write speed (disk I/O, consumer processing)
|
||||
|
||||
If ANY link is slow, pressure propagates backward automatically.
|
||||
No custom flow control needed -- QUIC handles it.
|
||||
|
||||
Sizing:
|
||||
- Pool: stripe_count * 2 buffers per side = 8 buffers (at 4 stripes)
|
||||
- Frame size: 256KB per frame (separate from the datastore's 1MB storage chunk size)
|
||||
- Total memory per stream direction: 8 x 256KB = 2MB
|
||||
- Total for a bidirectional transfer: ~4MB, regardless of blob size
|
||||
- At ~1200 bytes per QUIC packet, 256KB = ~213 packets. Smaller blast radius on packet loss than 1MB, better interleaving across stripes,
|
||||
aligns with OS page sizes.
|
||||
|
||||
TB-Scale Considerations
|
||||
|
||||
For very large transfers (100GB+ ML weights, TB-scale training data), additional design considerations apply:
|
||||
|
||||
Manifest streaming: At 1MB datastore chunks, a 1TB blob has ~1M chunks. Each ChunkRef is ~40 bytes, so the manifest is ~40MB. This is too
|
||||
large for a single negotiation payload. The current implementation sends the manifest as a JSON preamble on the data stream itself (not in
|
||||
the negotiation metadata). For TB-scale, the manifest could be streamed progressively instead of loaded all at once.
|
||||
|
||||
Per-chunk verification on arrival: The receiver verifies each chunk individually as it arrives: blake3(chunk_data) == chunk_ref.hash.
|
||||
This is implemented in `recv_blob`. A corrupted chunk causes immediate transfer failure. This catches problems early rather than waiting
|
||||
for full reassembly.
|
||||
|
||||
Progressive resume tokens: Resume tokens are emitted periodically (e.g., every 1000 chunks or every 256MB, whichever comes first), not
|
||||
just on failure. The sender acknowledges receipt of resume tokens. On connection loss, the receiver persists the latest resume token, and
|
||||
a new stream can resume from that point. For a 1TB transfer, a resume token with a 1M-bit BitVec is ~125KB -- cheap to exchange.
|
||||
(Not yet implemented -- the ResumeToken type exists but nothing emits or consumes it.)
|
||||
|
||||
Disk I/O as the bottleneck: For TB-scale over fast networks (10Gbps+), disk I/O often becomes the bottleneck rather than the network. The
|
||||
buffering strategy handles this naturally: when disk writes slow down, the receiver's buffer pool fills, QUIC backpressure kicks in, and
|
||||
the sender slows to match. No special handling needed -- the pipeline self-regulates. For maximum disk throughput, the receiver can use
|
||||
O_DIRECT or memory-mapped writes, but this is an implementation optimization, not an architectural decision.
|
||||
|
||||
Stripe count scaling: For very high bandwidth links, the default 4 stripes may not be enough to saturate the connection. The stripe count
|
||||
should be configurable up to 16, negotiated during handshake based on the expected transfer size and link characteristics. A heuristic:
|
||||
min(16, max(4, total_chunks / 1000)) -- more stripes for larger transfers.
|
||||
|
||||
---
|
||||
6. StreamHandle -- The Actor-Facing API
|
||||
|
||||
The StreamHandle is a lightweight, Send (but not Clone) object that actors store in their state. It communicates with the data-plane tokio
|
||||
tasks via channels internally.
|
||||
|
||||
Writer interface:
|
||||
- try_write(data: &[u8]) -> Result<usize, StreamError> -- Non-blocking. Returns bytes accepted.
|
||||
- flush() -- Signal that buffered data should be sent.
|
||||
- close() -- Graceful close.
|
||||
|
||||
Reader interface:
|
||||
- try_read(buf: &mut [u8]) -> Result<usize, StreamError> -- Non-blocking. Returns bytes read, 0 if none available.
|
||||
- has_data() -> bool -- Check if data is available without consuming it.
|
||||
|
||||
BlobTransfer Async Functions
|
||||
|
||||
Rather than a wrapper object, blob transfer uses standalone async functions that run inside tokio tasks (spawned after StreamReady). These
|
||||
functions loop over try_write/try_read with tokio::task::yield_now() for cooperative scheduling:
|
||||
|
||||
- send_blob(send, manifest, read_chunk) -- Writes the manifest preamble, then calls read_chunk(hash) for each chunk on-demand and writes
|
||||
it. At most one chunk is in memory at a time on the sender side. The read_chunk callback allows any data source (BlobStore via Inbox,
|
||||
in-memory, etc).
|
||||
- recv_blob(recv) -- Reads the manifest, then reads and blake3-verifies each chunk. Returns ReceivedBlob { manifest, chunks }.
|
||||
- poll_inbox(inbox, timeout) -- Async version of the bridge.rs poll_response pattern. Yields instead of thread::sleep.
|
||||
|
||||
These live in crates/datastore/src/blob_transfer.rs. The key insight: since actors can't await futures, the pattern is for the actor to
|
||||
receive StreamReady, extract the StreamHandle via OneShot::take(), spawn a tokio task for the I/O loop, then stop itself. The tokio task
|
||||
sends results back to other actors via runtime.send_to().
|
||||
|
||||
Why non-blocking? Actor handlers are synchronous (fn handle(&mut self, ctx: &Ctx, msg)). They cannot await futures. The try_read/try_write
|
||||
pattern fits naturally. The tokio task bridge is the mechanism for async I/O.
|
||||
|
||||
---
|
||||
7. Actor Integration: Negotiation Protocol
|
||||
|
||||
Opening a Stream (Initiator)
|
||||
|
||||
1. Actor sends a StreamOpen control message (through normal actor mailbox routing) to a StreamManager system actor. Contains: target_node:
|
||||
NodeId, mode, metadata (e.g., ContentHash + manifest for blob transfer), reply_to: ActorAddress.
|
||||
2. StreamManager validates the request, allocates a StreamId, and posts an async task to the tokio runtime that:
|
||||
- Opens a QUIC connection to the target (stream ALPN)
|
||||
- Opens the control bidirectional stream
|
||||
- Sends the stream header
|
||||
- Waits for accept/reject
|
||||
3. On accept: StreamManager sends StreamReady { stream_id, handle: StreamHandle } back to the requesting actor.
|
||||
|
||||
Accepting a Stream (Receiver)
|
||||
|
||||
1. IrohDriver's accept loop receives connection on stream ALPN.
|
||||
2. Reads control stream header, extracts StreamId + mode + metadata.
|
||||
3. Sends StreamIncoming actor message to local StreamManager.
|
||||
4. StreamManager routes to registered stream acceptors (actors that called StreamListen).
|
||||
5. Matching actor receives StreamOffer { stream_id, mode, metadata } in its mailbox.
|
||||
6. Actor sends StreamAccept or StreamReject back to StreamManager.
|
||||
7. On accept: StreamManager allocates buffers, spawns data-plane tasks, sends StreamReady { handle } to the accepting actor.
|
||||
|
||||
Notification Model (Hybrid)
|
||||
|
||||
Stream data bypasses mailboxes, but actors need to know when data is available:
|
||||
|
||||
- The data-plane tasks inject lightweight StreamEvent sentinel messages into the owning actor's mailbox when state changes: DataReady,
|
||||
WriteReady, Closed, Error.
|
||||
- Coalescing: An atomic flag prevents duplicate notifications. Set when notification posted, cleared when actor handles it. A
|
||||
high-throughput stream generates at most one DataReady per actor tick, not one per frame.
|
||||
- The actor's handle_any dispatches StreamEvent via downcast (same mechanism as Down and ActorExited today -- no core trait changes
|
||||
needed).
|
||||
- Actors can also proactively call handle.try_read() from any handler, not just in response to DataReady.
|
||||
|
||||
---
|
||||
8. The StreamManager Actor
|
||||
|
||||
A system actor spawned alongside the IrohDriver, registered under a well-known name. It is the bridge between the actor world and the
|
||||
stream data plane.
|
||||
|
||||
Responsibilities:
|
||||
- Registry of active streams: StreamId -> StreamState
|
||||
- Handle StreamOpen / StreamAccept / StreamReject / StreamListen / StreamClose messages
|
||||
- Spawn and supervise data-plane tokio tasks
|
||||
- Monitor stream-holding actors; clean up streams when actors die
|
||||
- Expose stream metrics (active streams, throughput, errors) for the dashboard
|
||||
|
||||
Communication with tokio runtime: Uses tokio::sync::mpsc and tokio::sync::oneshot channels. Posts commands to async tasks, receives
|
||||
results as actor messages (via the Inbox pattern already used by DatastoreBridge).
|
||||
|
||||
---
|
||||
9. Flow Control and Backpressure
|
||||
|
||||
Three layers, all leveraging what QUIC already provides:
|
||||
|
||||
1. QUIC-level: Per-stream and per-connection flow control (receive window, congestion window). This is the primary mechanism. Not
|
||||
duplicated.
|
||||
2. Buffer pool saturation: When receiver's pre-allocated buffer pool is full, the recv-side tokio task stops reading from QUIC. QUIC's
|
||||
receive window closes, sender stops transmitting. Natural backpressure without custom protocol.
|
||||
3. StreamHandle backpressure: try_write() returns 0 bytes accepted when the send buffer is full. The actor knows to back off or buffer
|
||||
internally.
|
||||
|
||||
No custom flow control protocol. QUIC's congestion control (Cubic/BBR) is battle-tested. Adding application-level flow control would add
|
||||
complexity and latency without benefit.
|
||||
|
||||
Cancellation
|
||||
|
||||
- Cooperative: StreamCancel signal on the control stream
|
||||
- Abrupt: reset() on the QUIC streams
|
||||
- Nuclear: close the QUIC connection (node shutdown only)
|
||||
|
||||
---
|
||||
10. Error Handling and Recovery
|
||||
|
||||
Failure Modes
|
||||
|
||||
┌──────────────────┬──────────────────────┬────────────────────────────────────────────────┐
|
||||
│ Failure │ Detection │ Behavior │
|
||||
├──────────────────┼──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ Frame corruption │ QUIC TLS + checksums │ Automatic retransmit │
|
||||
├──────────────────┼──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ Stream reset │ QUIC RST_STREAM │ StreamEvent::Error to owning actor │
|
||||
├──────────────────┼──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ Connection loss │ QUIC timeout │ StreamEvent::Error on all streams to that node │
|
||||
├──────────────────┼──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ Node death │ SWIM declares Dead │ StreamEvent::Error on all streams to that node │
|
||||
├──────────────────┼──────────────────────┼────────────────────────────────────────────────┤
|
||||
│ Owner actor dies │ Worker cleanup phase │ Stream closed, remote side notified │
|
||||
└──────────────────┴──────────────────────┴────────────────────────────────────────────────┘
|
||||
|
||||
Resume Tokens for Blob Transfers (Not Yet Implemented)
|
||||
|
||||
For large transfers, the receiver periodically emits a ResumeToken on the control channel:
|
||||
|
||||
ResumeToken {
|
||||
stream_id: StreamId,
|
||||
manifest_hash: ContentHash,
|
||||
chunks_received: BitVec, -- which chunks confirmed stored
|
||||
}
|
||||
|
||||
On failure, the initiator can open a new stream with the ResumeToken. The sender skips confirmed chunks. This avoids retransmitting
|
||||
terabytes when a checkpoint transfer fails near completion. Leverages the existing ObjectManifest/ChunkRef model.
|
||||
|
||||
The ResumeToken type is defined in crates/streams/src/types.rs but emission/consumption logic is deferred to a future stage.
|
||||
|
||||
---
|
||||
11. Integration with Existing Datastore
|
||||
|
||||
The stream primitive adds a parallel transfer path to the datastore. The existing chunk-at-a-time TransferActor is preserved for
|
||||
compatibility; the new stream path is used when stream support is configured.
|
||||
|
||||
Architecture:
|
||||
|
||||
DOWNLOAD SIDE: SERVE SIDE:
|
||||
|
||||
DatastoreNode StreamListener
|
||||
│ DownloadViaStream (Incoming = StreamNotification)
|
||||
│ ctx.spawn(StreamDownloader) │ on StreamOffer → HandleStreamOffer
|
||||
▼ ▼
|
||||
StreamDownloader DatastoreNode
|
||||
(Incoming = StreamNotification) │ HandleStreamOffer
|
||||
│ on_start: Open → StreamManager │ ctx.spawn(StreamServer)
|
||||
│ StreamReady → tokio task: ▼
|
||||
│ recv_blob → verify → write chunks StreamServer
|
||||
│ send completion to DatastoreNode (Incoming = StreamNotification)
|
||||
▼ │ on_start: Accept → StreamManager
|
||||
DatastoreNode │ StreamReady → tokio task:
|
||||
│ StreamDownloadComplete │ read manifest from BlobStore (Inbox)
|
||||
│ persist metadata, reply to caller │ for each chunk: read from BlobStore,
|
||||
│ write to stream (one at a time)
|
||||
│ close stream
|
||||
|
||||
Design principles:
|
||||
- No bridge/shim actors. Stream-facing actors use Incoming = StreamNotification directly.
|
||||
- No preloading all chunks into memory. Chunks flow on-demand: storage → network.
|
||||
- DatastoreNode stays simple (fire-and-forget coordination). The stream actors own the full I/O lifecycle.
|
||||
- After receiving StreamReady, actors spawn tokio tasks for I/O. Tokio tasks communicate results back via runtime.send_to().
|
||||
- StreamServer reads chunks on-demand — at most one chunk in memory at a time.
|
||||
|
||||
Flow:
|
||||
1. DatastoreNode receives DownloadViaStream { content_hash, source_node, reply_to }.
|
||||
2. Spawns a StreamDownloader actor, which sends Open to StreamManager with metadata = content_hash.0 (32 bytes).
|
||||
3. Remote StreamListener receives StreamOffer, extracts ContentHash from metadata, sends HandleStreamOffer to DatastoreNode.
|
||||
4. Remote DatastoreNode spawns a StreamServer actor, which sends Accept to StreamManager.
|
||||
5. StreamServer receives StreamReady, spawns tokio task: reads manifest from BlobStore, then streams each chunk on-demand via send_blob.
|
||||
6. StreamDownloader receives StreamReady, spawns tokio task: calls recv_blob, writes chunks to BlobStore (fire-and-forget), notifies
|
||||
DatastoreNode of completion.
|
||||
7. DatastoreNode creates ObjectEntry and persists via MetadataActor, which sends PutOk to the original caller.
|
||||
|
||||
This eliminates the round-trip-per-chunk bottleneck. A 1GB object with 1MB chunks currently requires 1,024 sequential round-trips. With
|
||||
streams and 4 parallel stripes, the entire blob flows in a single burst limited only by network bandwidth.
|
||||
|
||||
---
|
||||
12. Growth Path
|
||||
|
||||
Phase 1 (MVP): Reliable Ordered Blob Transfer — IMPLEMENTED
|
||||
|
||||
- StreamConfig with BlobTransfer mode only
|
||||
- New ALPN swactor/stream/1 handler
|
||||
- StreamOpen/StreamAccept handshake
|
||||
- Parallel striped data transfer
|
||||
- StreamHandle with try_read/try_write
|
||||
- StreamManager actor
|
||||
- Datastore integration (StreamListener, StreamDownloader, StreamServer actors)
|
||||
- BlobTransfer application protocol (send_blob/recv_blob with per-chunk blake3 verification)
|
||||
|
||||
Remaining MVP work:
|
||||
- Two-node integration test (real QUIC, full download flow)
|
||||
- Resume tokens (ResumeToken type exists, emission/consumption not yet wired)
|
||||
|
||||
Phase 2: Continuous Streams
|
||||
|
||||
- ContinuousStream mode (no total size known)
|
||||
- Single bidirectional QUIC stream (no striping)
|
||||
- Variable-sized message frames
|
||||
- Bounded ring buffer backpressure
|
||||
- Enables: federated learning gradient streams, data pipelines
|
||||
|
||||
Phase 3: Unreliable Datagrams
|
||||
|
||||
- UnreliableSequenced reliability mode using QUIC datagrams
|
||||
- Sequence-based frame dropping (latest-wins)
|
||||
- Receiver-side jitter buffer
|
||||
- Advisory StreamThrottle on control channel
|
||||
- Enables: voice/video, game entity state replication
|
||||
|
||||
Phase 4: Priority and QoS
|
||||
|
||||
- priority: u8 in StreamConfig
|
||||
- Priority-aware write scheduler across concurrent streams
|
||||
- QUIC stream priority hints
|
||||
- Per-stream health reporting and dashboard integration
|
||||
- Enables: simultaneous video + checkpoint without starvation
|
||||
|
||||
Phase 5: Parallel Unordered Transfer
|
||||
|
||||
- ReliableUnordered mode: parallel QUIC streams per chunk, independent delivery
|
||||
- Configurable parallelism
|
||||
- Enables: gradient exchange for distributed ML (any chunk consumable independently)
|
||||
|
||||
---
|
||||
13. Key Design Decisions Summary
|
||||
|
||||
┌───────────────────┬───────────────────────────────────────────────┬────────────────────────────────────────────────────────────┐
|
||||
│ Decision │ Choice │ Rationale │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Data path │ StreamHandle bypass, tokio task bridge │ Max throughput; actors manage, don't bottleneck │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Stream identity │ 16-byte StreamId, not ActorAddress │ Streams are not actors; avoid polluting address space │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ ALPN │ Separate swactor/stream/1 │ Isolate from SWIM; no interference with heartbeats │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Parallel stripes │ 4 QUIC streams per blob transfer │ Saturate congestion window on high-BDP links │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Flow control │ QUIC built-in only │ Don't duplicate what the transport does well │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Wire format │ 4-byte length prefix, no type tags │ Minimal per-frame overhead │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Stream chunk size │ 256KB │ Better packet-loss resilience, page-aligned │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Buffering │ Pre-allocated slab per stream │ Zero allocation on hot path │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Blob protocol │ Async functions, not wrapper object │ Simpler; tokio tasks own the I/O loop after StreamReady │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Actor pattern │ Spawn actor → StreamReady → tokio task → stop │ Clean separation; actor negotiates, task does I/O │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Chunk I/O │ On-demand via Inbox polling (poll_inbox) │ At most 1 chunk in memory; no preloading │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Crate │ New crates/streams/ │ Optional, clean dependency graph │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ MVP scope │ Reliable ordered only │ Covers ML + datastore; unreliable added later │
|
||||
├───────────────────┼───────────────────────────────────────────────┼────────────────────────────────────────────────────────────┤
|
||||
│ Locality │ Cross-node only │ Focused scope; same-node uses regular messages │
|
||||
└───────────────────┴───────────────────────────────────────────────┴────────────────────────────────────────────────────────────┘
|
||||
|
|
@ -1,338 +0,0 @@
|
|||
# Swactor Streams -- Implementation Status
|
||||
|
||||
## What Was Built
|
||||
|
||||
Stages 1-4 are implemented. Stages 1-3 built the stream primitive in `crates/streams/` (the `swactor-streams` crate). Stage 4 connected streams to the datastore so blob transfers use QUIC streams instead of sequential actor-message round-trips. All 42 tests pass (37 streams + 5 blob_transfer).
|
||||
|
||||
### Stage 1: Types, Wire Format, and Buffer Pool
|
||||
|
||||
Pure Rust -- no tokio, no iroh, no network. Compiles and tests in isolation.
|
||||
|
||||
#### `src/types.rs`
|
||||
|
||||
Core domain types for the stream system.
|
||||
|
||||
- **`StreamId([u8; 16])`** -- 16-byte random identifier. `Copy`, `Hash`, `Eq`, `Serialize`/`Deserialize`. Custom `Debug` (4-byte hex prefix) and `Display` (8-byte hex prefix) following the codebase's ID conventions. Not an `ActorAddress` -- streams are not actors and don't pollute the address space.
|
||||
- **`StreamMode`** -- enum with `BlobTransfer` variant. Extensible for future modes (continuous streams, datagrams).
|
||||
- **`StreamConfig`** -- negotiation parameters: `stripe_count` (default 4), `frame_size` (default 256KB), `metadata` (opaque bytes for application-level negotiation payloads like ContentHash).
|
||||
- **`StreamError`** -- error enum covering `Closed`, `BrokenPipe`, `Disconnected`, `BufferExhausted`, `InvalidHeader`, and `ChunkVerificationFailed` (with expected/actual hashes for diagnostics).
|
||||
- **`ResumeToken`** -- checkpoint for resuming interrupted transfers, carrying stream identity and progress counters.
|
||||
|
||||
#### `src/wire.rs`
|
||||
|
||||
Binary wire format for stream headers and data frames. Pure functions, no I/O.
|
||||
|
||||
- **Constants**: `MAGIC: [0x53, 0x57]` ("SW"), `VERSION: 0x01`, `ALPN: b"swactor/stream/1"`.
|
||||
- **`StreamHeader`** -- the negotiation header sent at connection establishment. Wire layout: `[2B magic][1B version][16B stream_id][1B mode][1B stripe_count][4B frame_size][4B metadata_len][N metadata]`.
|
||||
- **`encode_header` / `decode_header`** -- round-trippable serialization with validation (magic, version, mode, truncation checks).
|
||||
- **Data frame format**: `[4B payload_len (big-endian)][payload]`. Deliberately minimal -- no per-frame type tags or checksums (QUIC provides TLS integrity). A zero-length payload signals end-of-stripe.
|
||||
- **`encode_data_frame` / `decode_data_frame` / `encode_end_of_stripe`** -- frame-level codec.
|
||||
|
||||
#### `src/buffer.rs`
|
||||
|
||||
Pre-allocated buffer pool for zero-allocation data transfer.
|
||||
|
||||
- **`FrameBuf`** -- a `Box<[u8]>` with read/write cursors. `write(&[u8]) -> usize` fills from the write cursor, `read(&mut [u8]) -> usize` drains from the read cursor. `reset()` zeroes only the cursors (not the data) for fast recycling. `load(&[u8])` replaces content directly.
|
||||
- **`BufferPool`** -- a fixed-size pool backed by `crossbeam::ArrayQueue<FrameBuf>` (lock-free MPMC). `checkout() -> Option<FrameBuf>` and `checkin(buf)` enable concurrent use between actor threads and tokio tasks without locks. `Clone` shares the underlying `Arc` so send/recv sides reference the same pool.
|
||||
|
||||
### Stage 2: StreamHandle, Channels, and Data Plane
|
||||
|
||||
Introduces tokio channels and async tasks but NOT iroh. Data-plane tasks are generic over `AsyncRead`/`AsyncWrite`, fully testable with `tokio::io::DuplexStream`.
|
||||
|
||||
#### `src/channel.rs`
|
||||
|
||||
Typed channel messages that move `FrameBuf`s by ownership (zero-copy handoff).
|
||||
|
||||
- **`SendCommand`** -- `Data(FrameBuf)`, `Flush`, `Close`. Actor -> send task.
|
||||
- **`SendEvent`** -- `WriteReady`, `Error(StreamError)`, `Closed`. Send task -> actor.
|
||||
- **`RecvCommand`** -- `Consumed(FrameBuf)`, `Close`. Actor -> recv task.
|
||||
- **`RecvEvent`** -- `Data(FrameBuf)`, `Error(StreamError)`, `Closed`. Recv task -> actor.
|
||||
|
||||
#### `src/notify.rs`
|
||||
|
||||
Notification coalescing to prevent flooding actor mailboxes.
|
||||
|
||||
- **`NotifyFlag`** -- `AtomicU8` bitflags (`DATA_READY`, `WRITE_READY`, `CLOSED`, `ERROR`). `set(kind) -> bool` returns true only if the bit was previously clear, signaling a new notification should be injected. `clear(kind)` is called by the actor after handling.
|
||||
- **`StreamEvent`** / **`StreamEventKind`** -- the lightweight sentinel message injected into actor mailboxes. Carries `stream_id` and `kind` (DataReady, WriteReady, Closed, Error).
|
||||
- **`NotifySink`** -- held by data-plane tasks. Combines the shared `NotifyFlag` with an inject closure. Convenience methods: `data_ready()`, `write_ready()`, `closed()`, `error()`.
|
||||
|
||||
#### `src/handle.rs`
|
||||
|
||||
The actor-facing API for reading and writing stream data.
|
||||
|
||||
- **`SendHalf`** -- owns `mpsc::Sender<SendCommand>`, `mpsc::Receiver<SendEvent>`, a `BufferPool` clone, and an active `FrameBuf`. `try_write(&[u8]) -> Result<usize>` fills the active buffer and sends full buffers via `try_send` (non-blocking). Returns 0 on backpressure. `flush()` sends partial buffers. `close()` flushes remaining data and sends the Close command.
|
||||
- **`RecvHalf`** -- owns `mpsc::Receiver<RecvEvent>`, `mpsc::Sender<RecvCommand>`, a `BufferPool` clone, and an active `FrameBuf`. `try_read(&mut [u8]) -> Result<usize>` drains the active buffer then pulls new buffers from the channel. Returns 0 when no data is available. `has_data()` peeks without consuming.
|
||||
- **`StreamHandle`** -- combines `SendHalf` and `RecvHalf`. `Send` but not `Clone` (the mpsc receivers are not cloneable).
|
||||
- **`create_stream_handle(stream_id, config, pool_size, channel_capacity)`** -- factory that returns `(StreamHandle, DataPlaneEndpoints)`. The handle goes to the actor; the endpoints go to the data-plane tasks.
|
||||
|
||||
#### `src/data_plane.rs`
|
||||
|
||||
Async tasks that bridge `StreamHandle` channels to actual byte streams.
|
||||
|
||||
- **`send_stripe_task<W: AsyncWrite>`** -- reads `SendCommand`s from the channel, wire-encodes them as data frames, writes to the transport, returns consumed buffers to the pool, and optionally notifies the actor via `NotifySink`.
|
||||
- **`recv_stripe_task<R: AsyncRead>`** -- reads wire-encoded frames from the transport, loads payloads into `FrameBuf`s from the pool, sends `RecvEvent::Data` to the actor channel. Handles end-of-stripe sentinel and connection closure.
|
||||
- **`spawn_send_stripes` / `spawn_recv_stripes`** -- spawn a set of stripe tasks from a writer/reader factory. The recv spawner merges all stripe outputs into a single `mpsc::Receiver<RecvEvent>`.
|
||||
|
||||
Generic over `AsyncRead + AsyncWrite + Send + Unpin + 'static`, so tests use `tokio::io::DuplexStream` with no network stack.
|
||||
|
||||
### Stage 3: QUIC Integration and StreamManager Actor
|
||||
|
||||
Connects the data-plane tasks to real QUIC streams via iroh. Introduces the `StreamManager` system actor with full open/accept/reject lifecycle. Modifies `IrohDriver` for generic ALPN routing and bootstraps the StreamManager in `swactor-node`.
|
||||
|
||||
#### `src/messages.rs`
|
||||
|
||||
Protocol types for the stream control plane.
|
||||
|
||||
- **`OneShot<T>`** -- Clone-friendly wrapper for non-Clone data (`StreamHandle`, `Connection`). Uses `Arc<Mutex<Option<T>>>` internally. First `.take()` extracts the value; subsequent calls (including from clones) return `None`. This allows non-Clone payloads inside Clone message enums required by the actor system's `Message` trait.
|
||||
- **`StreamManagerMsg`** -- 8-variant enum for messages sent TO the StreamManager actor:
|
||||
- `Open { target_node, mode, config, reply_to }` -- Request a new stream to a remote node.
|
||||
- `Accept { stream_id, reply_to }` -- Accept an offered incoming stream.
|
||||
- `Reject { stream_id }` -- Reject an offered incoming stream.
|
||||
- `Listen { mode, listener }` -- Register as a stream listener for a given mode.
|
||||
- `Close { stream_id }` -- Close a stream.
|
||||
- `IncomingConnection { node_id, stream_id, mode, config, conn }` -- Internal: from accept bridge to StreamManager.
|
||||
- `OpenCompleted { stream_id, reply_to, result }` -- Internal: async open task completed.
|
||||
- `AcceptCompleted { stream_id, reply_to, result }` -- Internal: async accept task completed.
|
||||
- **`StreamNotification`** -- 4-variant enum for notifications sent FROM StreamManager TO user actors:
|
||||
- `StreamReady { stream_id, handle }` -- Stream is ready for use (open or accept completed).
|
||||
- `StreamOffer { stream_id, mode, metadata, from_node }` -- A remote node is offering a stream.
|
||||
- `StreamClosed { stream_id, reason }` -- A stream was closed.
|
||||
- `StreamFailed { stream_id, error }` -- A stream open/accept failed.
|
||||
|
||||
#### `src/connection.rs`
|
||||
|
||||
Async connection cache for stream QUIC connections, separate from SWIM connections.
|
||||
|
||||
- **`StreamConnectionCache`** -- `HashMap<[u8; 32], Connection>` with health-check-on-access. `get_or_connect()` checks `conn.close_reason().is_none()` before reuse and falls back to connecting via `endpoint.connect(key, ALPN)`. `prune_closed()` for bulk cleanup. Uses the stream ALPN (`swactor/stream/1`).
|
||||
|
||||
#### `src/manager.rs`
|
||||
|
||||
The core StreamManager system actor.
|
||||
|
||||
- **`StreamManager`** -- implements `ActorInterface<Incoming = StreamManagerMsg>`. Manages active streams, pending incoming offers, listener registrations, and a connection cache. Holds an `Endpoint`, `tokio::runtime::Handle`, and `Arc<Runtime>` for spawning async tasks and sending messages back to itself.
|
||||
- **`STREAM_MANAGER_NAME`** -- well-known name `"StreamManager"` for the name registry.
|
||||
- **Open flow**: Generates `StreamId`, spawns a tokio task that connects, sends header on a control bi-stream, waits for a 1-byte accept/reject response, then creates `StreamHandle` + data-plane tasks, and sends `OpenCompleted` back to the StreamManager. StreamManager then delivers `StreamNotification::StreamReady` to the requesting actor.
|
||||
- **Incoming flow**: Accept bridge reads header, sends `IncomingConnection` to StreamManager. StreamManager stores as pending, notifies matching listeners with `StreamOffer`.
|
||||
- **Accept flow**: Takes pending connection, spawns tokio task that sends accept byte, creates `StreamHandle` + data-plane tasks, sends `AcceptCompleted` back. StreamManager delivers `StreamReady` to accepting actor.
|
||||
- **Reject flow**: Sends reject byte on a uni-stream, drops the connection.
|
||||
- **Close flow**: Removes stream state; data-plane tasks terminate when channels drop.
|
||||
- **`handle_down`**: Cleans up streams owned by dead actors and removes dead listeners.
|
||||
- **Data-plane spawning**: For each stream direction, a single tokio task opens N uni-streams and round-robins data frames across them. Recv tasks accept incoming uni-streams and dispatch each to a `recv_stripe_task`.
|
||||
|
||||
#### `src/accept.rs`
|
||||
|
||||
Bridge between incoming QUIC connections and the StreamManager actor.
|
||||
|
||||
- **`spawn_accept_bridge`** -- spawns a tokio task that reads from a channel of `(node_id, Connection)` pairs, accepting the control bi-stream, reading the stream header via `read_to_end` + `decode_header`, and forwarding `StreamManagerMsg::IncomingConnection` to the StreamManager via `runtime.send_to()`.
|
||||
- **`handle_incoming`** -- public async function for per-connection header processing. Can also be called directly from the main loop (used by `swactor-node`).
|
||||
|
||||
#### Modified: `crates/distribution/src/iroh_driver.rs`
|
||||
|
||||
Generic ALPN support to route stream connections separately from SWIM.
|
||||
|
||||
- **`IrohDriverConfig`**: Added `additional_alpns: Vec<Vec<u8>>` field. All existing call sites updated with `additional_alpns: vec![]`.
|
||||
- **Endpoint creation**: ALPNs now include both SWIM and any additional ALPNs (`vec![ALPN.to_vec()] + additional_alpns`).
|
||||
- **Accept loop**: After accepting a connection, checks `conn.alpn()`. SWIM ALPN routes to `accepted_conns` (existing behavior). All other ALPNs route to `other_accepted_conns` (new buffer).
|
||||
- **New field**: `other_accepted_conns: Arc<Mutex<Vec<(NodeId, Connection)>>>`.
|
||||
- **New methods**: `endpoint() -> &Endpoint` (for outbound stream connections), `drain_other_connections() -> Vec<(NodeId, Connection)>` (polled from main loop).
|
||||
|
||||
#### Modified: `crates/streams/src/types.rs`
|
||||
|
||||
- Added `Hash` derive to `StreamMode` (needed as `HashMap` key in listeners registry).
|
||||
|
||||
#### Modified: `crates/streams/src/lib.rs`
|
||||
|
||||
- Added module declarations and re-exports for `accept`, `connection`, `manager`, `messages`.
|
||||
- Re-exports: `StreamConnectionCache`, `StreamManager`, `STREAM_MANAGER_NAME`, `OneShot`, `StreamManagerMsg`, `StreamNotification`.
|
||||
|
||||
#### Modified: `crates/streams/Cargo.toml`
|
||||
|
||||
- Added `swactor-std` dependency (for `CtxMonitoring`, `RuntimeNaming`).
|
||||
- Added `io-util` feature to `tokio` (for `AsyncWriteExt::flush`).
|
||||
|
||||
#### Modified: `crates/swactor-node/src/main.rs`
|
||||
|
||||
Bootstrap integration in `run_iroh()`.
|
||||
|
||||
- Passes `swactor_streams::ALPN.to_vec()` in `IrohDriverConfig::additional_alpns`.
|
||||
- After driver creation, spawns `StreamManager::new(endpoint, tokio_handle, runtime)` as a named actor under `"StreamManager"`.
|
||||
- In the main loop, drains `driver.drain_other_connections()` and spawns `handle_incoming` tasks for each, forwarding to the StreamManager.
|
||||
|
||||
#### Modified: `crates/swactor-node/Cargo.toml`
|
||||
|
||||
- Added `swactor-streams` dependency.
|
||||
|
||||
#### Modified: `crates/distribution/tests/common/iroh.rs`, `crates/dashboard/src/bin/swactor-node.rs`
|
||||
|
||||
- Updated all `IrohDriverConfig` construction sites with `additional_alpns: vec![]`.
|
||||
|
||||
### Stage 4: Datastore Stream Integration
|
||||
|
||||
Connects the stream system to the datastore so blob transfers flow over QUIC streams instead of sequential per-chunk actor-message round-trips. A 1GB blob with 1MB chunks that previously required 1,024 round-trips now flows in a single burst.
|
||||
|
||||
#### `crates/datastore/src/blob_transfer.rs` (NEW)
|
||||
|
||||
Async functions for sending/receiving blobs over StreamHandle. Runs inside tokio tasks, NOT actor handlers.
|
||||
|
||||
- **`BlobTransferError`** -- enum: `IncompleteTransfer(String)`, `ChunkVerificationFailed { expected, actual }`, `InvalidManifest(String)`, `Storage(String)`.
|
||||
- **`ReceivedBlob`** -- `{ manifest: ObjectManifest, chunks: Vec<(ContentHash, Vec<u8>)> }`.
|
||||
- **`send_blob(send, manifest, read_chunk)`** -- generic over an async callback `F: Fn(ContentHash) -> Future<Output = Result<Vec<u8>>>`. Writes `[4B manifest_json_len][manifest JSON]` preamble, then for each chunk in the manifest calls `read_chunk(hash)` and writes the raw bytes. Chunks are NOT preloaded -- the callback reads one at a time.
|
||||
- **`recv_blob(recv)`** -- reads manifest preamble, deserializes JSON, then reads + blake3-verifies each chunk against the manifest's `ChunkRef` entries. Returns `ReceivedBlob`.
|
||||
- **`poll_inbox(inbox, timeout)`** -- async version of `bridge.rs:poll_response`. Yields (`tokio::task::yield_now`) instead of `thread::sleep`, polling the swactor `Inbox` until a message arrives or timeout.
|
||||
- **Internal helpers**: `write_all` (loops `try_write` + `yield_now`), `read_exact` (loops `try_read` + `yield_now`).
|
||||
|
||||
Wire format:
|
||||
```
|
||||
[4B manifest_json_length (u32 BE)]
|
||||
[N bytes manifest JSON]
|
||||
[chunk_0 raw bytes] <- size from manifest.chunks[0].size
|
||||
[chunk_1 raw bytes]
|
||||
...
|
||||
```
|
||||
|
||||
#### `crates/datastore/src/actors/stream_listener.rs` (NEW)
|
||||
|
||||
Listens for incoming BlobTransfer stream offers and routes them to DatastoreNode.
|
||||
|
||||
- **`StreamListener`** -- `Incoming = StreamNotification`. State: `datastore_node: ActorAddress`, `stream_manager: Option<ActorAddress>`.
|
||||
- `on_start`: looks up `"StreamManager"` via `ctx.where_is()`, sends `StreamManagerMsg::Listen { mode: BlobTransfer }`.
|
||||
- `handle(StreamOffer)`: extracts 32-byte ContentHash from `metadata`, sends `DatastoreNodeMsg::HandleStreamOffer` to DatastoreNode. Rejects if metadata != 32 bytes.
|
||||
|
||||
#### `crates/datastore/src/actors/stream_downloader.rs` (NEW)
|
||||
|
||||
Opens a stream to a remote node and downloads a blob.
|
||||
|
||||
- **`StreamDownloader`** -- `Incoming = StreamNotification`. Constructor takes: `content_hash`, `source_node`, `datastore_node`, `blob_store`, `reply_to`, `stream_manager`, `tokio_handle`, `runtime`.
|
||||
- `on_start`: sends `StreamManagerMsg::Open { target_node, mode: BlobTransfer, config.metadata: content_hash.0.to_vec() }`.
|
||||
- `handle(StreamReady)`: takes handle via `OneShot::take()`, spawns tokio task:
|
||||
- Calls `recv_blob(&mut recv_half)`.
|
||||
- Writes each chunk to BlobStore via `runtime.send_to(blob_store, WriteChunk)` (fire-and-forget).
|
||||
- Writes manifest via `runtime.send_to(blob_store, WriteManifest)` (fire-and-forget).
|
||||
- Sends `DatastoreNodeMsg::StreamDownloadComplete` to DatastoreNode.
|
||||
- On error: sends `DatastoreNodeMsg::StreamDownloadFailed`.
|
||||
- Actor calls `ctx.stop_self()` after spawning the task.
|
||||
- `handle(StreamFailed)`: sends `StreamDownloadFailed`, stops self.
|
||||
|
||||
#### `crates/datastore/src/actors/stream_server.rs` (NEW)
|
||||
|
||||
Serves a blob to a requesting node over a stream, reading chunks on-demand.
|
||||
|
||||
- **`StreamServer`** -- `Incoming = StreamNotification`. Constructor takes: `stream_id`, `content_hash`, `blob_store`, `stream_manager`, `tokio_handle`, `runtime`.
|
||||
- `on_start`: sends `StreamManagerMsg::Accept { stream_id }`.
|
||||
- `handle(StreamReady)`: takes handle, spawns tokio task:
|
||||
- Reads manifest from BlobStore via `runtime.new_inbox()` + `poll_inbox` (async Inbox polling).
|
||||
- Calls `send_blob(&mut send_half, &manifest, |chunk_hash| { ... })` with a callback that reads each chunk on-demand from BlobStore via a fresh Inbox.
|
||||
- At most one chunk is in memory at a time. Chunks flow directly from BlobStore to stream.
|
||||
- Actor calls `ctx.stop_self()`.
|
||||
- `handle(StreamFailed)`: stops self.
|
||||
|
||||
#### Modified: `crates/datastore/src/messages.rs`
|
||||
|
||||
Added 5 new variants to `DatastoreNodeMsg`:
|
||||
|
||||
- `DownloadViaStream { content_hash, source_node, reply_to }` -- triggers a stream download.
|
||||
- `HandleStreamOffer { stream_id, content_hash, from_node, stream_manager }` -- routes incoming stream offers.
|
||||
- `StreamDownloadComplete { content_hash, manifest, reply_to }` -- download succeeded; persist metadata.
|
||||
- `StreamDownloadFailed { content_hash, reason, reply_to }` -- download failed; notify caller.
|
||||
- `ConfigureStreams { stream_manager, tokio_handle, runtime }` -- late-binding stream support.
|
||||
|
||||
Changed from `#[derive(Debug, Clone)]` to `#[derive(Clone)]` with manual `Debug` impl (because `Arc<Runtime>` doesn't implement `Debug`).
|
||||
|
||||
#### Modified: `crates/datastore/src/actors/datastore_node.rs`
|
||||
|
||||
Added stream support fields and handlers to the coordinator actor.
|
||||
|
||||
- **New fields**: `runtime: Option<Arc<Runtime>>`, `tokio_handle: Option<tokio::runtime::Handle>`, `stream_manager: Option<ActorAddress>` -- all initialized to `None`.
|
||||
- **`handle_configure_streams`**: stores runtime/tokio_handle/stream_manager.
|
||||
- **`handle_download_via_stream`**: spawns `StreamDownloader`. Returns `TransferFailed` if streams not configured.
|
||||
- **`handle_stream_offer`**: spawns `StreamServer`.
|
||||
- **`handle_stream_download_complete`**: creates `ObjectEntry`, sends `MetadataMsg::PutObject` to metadata actor with the original `reply_to` for direct response routing.
|
||||
- **`handle_stream_download_failed`**: sends `DatastoreResponse::TransferFailed` to `reply_to`.
|
||||
|
||||
#### Modified: `crates/datastore/src/actors/mod.rs`
|
||||
|
||||
Added module declarations for `stream_downloader`, `stream_listener`, `stream_server`.
|
||||
|
||||
#### Modified: `crates/datastore/src/lib.rs`
|
||||
|
||||
Added `pub mod blob_transfer`.
|
||||
|
||||
#### Modified: `crates/datastore/src/bridge.rs`
|
||||
|
||||
- Added `datastore_addr: ActorAddress` field to `DatastoreGroup` (stored during `spawn()`).
|
||||
- Added `configure_streams(&self, stream_manager, tokio_handle)` method: sends `ConfigureStreams` to DatastoreNode, spawns and registers `StreamListener` under `"StreamListener"`.
|
||||
|
||||
#### Modified: `crates/datastore/Cargo.toml`
|
||||
|
||||
- Added `swactor-streams = { path = "../streams" }` and `tokio = { version = "1", features = ["sync", "rt", "time"] }` dependencies.
|
||||
- Added dev-dependencies for testing: `swactor-streams`, `tokio` with `rt-multi-thread`, `macros`, `io-util`.
|
||||
|
||||
#### Modified: `crates/swactor-node/src/main.rs`
|
||||
|
||||
After StreamManager registration, wires stream support into the datastore:
|
||||
```rust
|
||||
if let Some(group) = ds_group {
|
||||
group.configure_streams(stream_mgr_addr, driver.tokio_handle());
|
||||
}
|
||||
```
|
||||
|
||||
## Test Coverage
|
||||
|
||||
42 tests across all modules:
|
||||
|
||||
| Category | Tests | What they verify |
|
||||
|----------|-------|------------------|
|
||||
| `types` | 4 | StreamId uniqueness, Debug/Display formatting, StreamConfig defaults |
|
||||
| `wire` | 8 | Header round-trip (basic + property-based), bad magic/version/truncation rejection, data frame round-trip (basic + property-based), end-of-stripe sentinel |
|
||||
| `buffer` | 7 | FrameBuf write/read/reset/load, BufferPool checkout/checkin/exhaustion/recycling/sharing |
|
||||
| `notify` | 4 | Set returns true first time / false on duplicate, clear re-enables, independent flags, read shows all bits |
|
||||
| `data_plane` | 9 | Single-stripe end-to-end transfer, multi-chunk ordered delivery (20 chunks), 4-stripe round-robin (100 chunks), graceful close, notification coalescing, backpressure detection |
|
||||
| `messages` | 5 | OneShot take-once semantics, clone sharing, debug format, StreamManagerMsg is Message, StreamNotification is Message |
|
||||
| `blob_transfer` | 5 | Small blob round-trip (single chunk), multi-chunk round-trip (4MB / 256KB chunks / 16 chunks), corrupted chunk detection (blake3 verification), truncated stream detection, property-based arbitrary blob round-trips |
|
||||
|
||||
Property-based tests (via `proptest`) cover:
|
||||
- Arbitrary stream headers (random IDs, stripe counts 1-16, frame sizes 1KB-1MB, metadata 0-256 bytes)
|
||||
- Arbitrary data frame payloads (0-256KB)
|
||||
- Arbitrary blob transfers (random data 1-64KB, chunk sizes 256B-8KB)
|
||||
|
||||
## Dependency Footprint
|
||||
|
||||
### `swactor-streams` crate
|
||||
|
||||
- `swactor` (core actor types, with `serde` feature)
|
||||
- `swactor-std` (for `CtxMonitoring`, `RuntimeNaming`)
|
||||
- `shared-types` (ContentHash)
|
||||
- `distribution` (NodeId, iroh re-exports)
|
||||
- `crossbeam-queue` (lock-free buffer pool -- already a workspace dep)
|
||||
- `tokio` (mpsc channels, async I/O traits, io-util)
|
||||
- `iroh` (QUIC transport, connections, endpoints)
|
||||
- `blake3`, `serde`, `getrandom`
|
||||
|
||||
Dev dependencies: `proptest`, `tokio` (with rt-multi-thread, macros, test-util, io-util).
|
||||
|
||||
### `swactor-datastore` crate (Stage 4 additions)
|
||||
|
||||
- `swactor-streams` (stream primitives, messages, types)
|
||||
- `tokio` (sync, rt, time -- for spawning async blob transfer tasks and `poll_inbox`)
|
||||
|
||||
Dev dependencies: `swactor-streams`, `tokio` (with rt-multi-thread, macros, io-util).
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Remaining MVP Work
|
||||
|
||||
These items complete the minimum viable stream-based blob transfer:
|
||||
|
||||
1. **Two-node integration test** -- full open/accept/data-transfer/close cycle with real iroh endpoints and two `DatastoreGroup` instances. Verifies StreamListener receives offers, StreamServer serves blobs, StreamDownloader receives and persists them. This is the critical end-to-end validation that all the pieces work together over real QUIC.
|
||||
|
||||
2. **CtxStreams extension trait** (`crates/streams/src/ctx_ext.rs`) -- convenience methods on `Ctx`: `stream_open()`, `stream_listen()`, `stream_accept()`, `stream_reject()`, `stream_close()`. Looks up `"StreamManager"` via `where_is()` and wraps the message construction. Reduces boilerplate for any actor wanting to use streams.
|
||||
|
||||
3. **Resume tokens** -- checkpoint emission every N chunks or N bytes during `send_blob`/`recv_blob`. Stored in `ResumeToken` (already defined in `types.rs`). On reconnect, receiver sends its token in `StreamConfig.metadata` and sender seeks to the right chunk offset.
|
||||
|
||||
### Post-MVP Phases
|
||||
|
||||
- **Dashboard stream metrics** -- expose active streams, bytes transferred, and transfer rates through the existing dashboard infrastructure.
|
||||
- **Continuous Streams** -- `ContinuousStream` mode for unbounded data (ML gradient streams, data pipelines). Single bidirectional QUIC stream, variable-sized frames, ring buffer backpressure.
|
||||
- **Unreliable Datagrams** -- QUIC datagram-based mode for latency-sensitive data (voice/video, game state). Sequence-based dropping, jitter buffer.
|
||||
- **Priority and QoS** -- per-stream priority, write scheduling across concurrent streams, QUIC stream priority hints.
|
||||
- **Parallel Unordered Transfer** -- independent per-chunk QUIC streams for workloads where any chunk is consumable independently (distributed ML gradient exchange).
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
# Wasm Actor Crate — Development History
|
||||
|
||||
> Adds a new crate (`crates/bin-runner/`) that runs WebAssembly guest code
|
||||
> **inside** a swactor actor. The Wasm instance lives in the actor — not as a
|
||||
> separate OS process. Messages arrive as bytes, get written into Wasm linear
|
||||
> memory, and the guest's `handle` export is called.
|
||||
>
|
||||
> ~350 lines of Rust (host) · 3 guest modules · 7 tests
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Overview & Motivation](#1-overview--motivation)
|
||||
2. [What Was Built](#2-what-was-built)
|
||||
3. [Guest ↔ Host Contract](#3-guest--host-contract)
|
||||
4. [Handle Cycle (Hot Path)](#4-handle-cycle-hot-path)
|
||||
5. [Guest Modules](#5-guest-modules)
|
||||
6. [Design Decisions & Tradeoffs](#6-design-decisions--tradeoffs)
|
||||
7. [Known Gaps & Future Improvements](#7-known-gaps--future-improvements)
|
||||
8. [Test Coverage Summary](#8-test-coverage-summary)
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview & Motivation
|
||||
|
||||
Swactor already supported running *inside* a browser via `crates/wasm/`
|
||||
(wasm-bindgen). This crate flips the direction: run untrusted Wasm code
|
||||
*inside* an actor, sandboxed by wasmtime. Use cases include user-defined
|
||||
plugins, multi-language actors, and capability-restricted compute.
|
||||
|
||||
The main swactor crate has no wasmtime dependency — all Wasm machinery is
|
||||
isolated in `crates/bin-runner/`.
|
||||
|
||||
---
|
||||
|
||||
## 2. What Was Built
|
||||
|
||||
| Component | Location | Purpose |
|
||||
|-----------|----------|---------|
|
||||
| `swactor-bin-runner` crate | `crates/bin-runner/` | Host-side: engine, builder, actor impl |
|
||||
| 3 guest crates | `crates/bin-runner/tests/guests/{echo,double,silent}/` | `#![no_std]` Wasm modules for testing |
|
||||
| Integration tests | `crates/bin-runner/tests/wasm_actor.rs` | 7 behavioral tests |
|
||||
|
||||
### Crate modules
|
||||
|
||||
```
|
||||
crates/bin-runner/src/
|
||||
lib.rs — ByteMessage, re-exports
|
||||
engine.rs — SharedEngine (Arc<wasmtime::Engine>)
|
||||
builder.rs — WasmActorBuilder (compile + link + instantiate)
|
||||
actor.rs — WasmActor implementing ActorInterface
|
||||
error.rs — WasmActorError enum
|
||||
```
|
||||
|
||||
### Public types
|
||||
|
||||
- **`ByteMessage(pub Vec<u8>)`** — message type for Wasm actors. Satisfies
|
||||
`Message` bounds trivially.
|
||||
- **`SharedEngine`** — wraps `Arc<wasmtime::Engine>`. Created once, cloned
|
||||
cheaply across actors. Sandboxed config: no threads, no SIMD, no reference
|
||||
types.
|
||||
- **`WasmActorBuilder`** — takes an engine + raw `.wasm` bytes, compiles the
|
||||
module, links the `swactor.send` host import, extracts typed function handles,
|
||||
returns a `WasmActor`.
|
||||
- **`WasmActor`** — implements `ActorInterface<Incoming = ByteMessage, Response = ()>`.
|
||||
- **`WasmActorError`** — `MissingExport(&'static str)` or `Wasmtime(wasmtime::Error)`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Guest ↔ Host Contract
|
||||
|
||||
**Guest must export:**
|
||||
|
||||
| Export | Signature | Purpose |
|
||||
|--------|-----------|---------|
|
||||
| `memory` | WebAssembly linear memory | Host reads/writes message bytes here |
|
||||
| `alloc` | `(size: i32) -> i32` | Allocate `size` bytes, return pointer |
|
||||
| `handle` | `(ptr: i32, len: i32)` | Process message at `(ptr, len)` |
|
||||
|
||||
**Guest may import:**
|
||||
|
||||
| Import | Module | Signature | Purpose |
|
||||
|--------|--------|-----------|---------|
|
||||
| `send` | `swactor` | `(dest_ptr: i32, payload_ptr: i32, payload_len: i32)` | Send a message to another actor |
|
||||
|
||||
`dest_ptr` points to 32 bytes of `ActorAddress` in guest linear memory.
|
||||
`payload_ptr` + `payload_len` describe the message bytes.
|
||||
|
||||
---
|
||||
|
||||
## 4. Handle Cycle (Hot Path)
|
||||
|
||||
```
|
||||
ByteMessage arrives
|
||||
│
|
||||
v
|
||||
1. host calls guest alloc(msg.len) → ptr
|
||||
│
|
||||
v
|
||||
2. host writes msg bytes into guest memory at ptr
|
||||
│
|
||||
v
|
||||
3. host calls guest handle(ptr, len)
|
||||
│
|
||||
├── guest may call swactor.send() N times
|
||||
│ └── each appends (ActorAddress, Vec<u8>) to HostState.outbox
|
||||
│
|
||||
v
|
||||
4. host drains outbox → ctx.send(dest, ByteMessage(payload)) for each
|
||||
```
|
||||
|
||||
Traps during `alloc` or `handle` will panic. Swactor's existing
|
||||
`catch_unwind` in `tick_all` poisons the actor — consistent with the
|
||||
panic-safety model.
|
||||
|
||||
---
|
||||
|
||||
## 5. Guest Modules
|
||||
|
||||
Three `#![no_std]` Rust crates compiled to `wasm32-unknown-unknown`:
|
||||
|
||||
| Guest | Behavior | Tests it supports |
|
||||
|-------|----------|-------------------|
|
||||
| `echo` | Reads 32-byte dest + payload from message; sends payload back to dest | Echo roundtrip, binary preservation |
|
||||
| `double` | Same framing; sends payload back **twice** | Multi-send verification |
|
||||
| `silent` | Receives bytes; does nothing | No-output / no-error baseline |
|
||||
|
||||
Each guest uses a simple inline bump allocator (64 KiB heap, 8-byte aligned)
|
||||
and a `#[panic_handler]` that loops. No external dependencies.
|
||||
|
||||
Message framing convention: the first 32 bytes of the `ByteMessage` payload
|
||||
are the destination `ActorAddress`, followed by the actual message bytes.
|
||||
This allows guests to send replies without hardcoding addresses.
|
||||
|
||||
### Building guests
|
||||
|
||||
```bash
|
||||
rustup target add wasm32-unknown-unknown # one-time
|
||||
|
||||
cd crates/bin-runner/tests/guests/echo && cargo build --target wasm32-unknown-unknown --release
|
||||
cd crates/bin-runner/tests/guests/double && cargo build --target wasm32-unknown-unknown --release
|
||||
cd crates/bin-runner/tests/guests/silent && cargo build --target wasm32-unknown-unknown --release
|
||||
```
|
||||
|
||||
Each guest crate has its own `[workspace]` marker to stay independent of the
|
||||
root workspace.
|
||||
|
||||
---
|
||||
|
||||
## 6. Design Decisions & Tradeoffs
|
||||
|
||||
| # | Decision | Rationale |
|
||||
|---|----------|-----------|
|
||||
| 1 | **wasmtime, not wasmer/wasm3** | Best-maintained, fuel metering support, cranelift JIT |
|
||||
| 2 | **Raw bytes, not structured messages** | Keeps the boundary simple; framing/serialization is the guest's concern |
|
||||
| 3 | **Separate crate, not a feature flag** | wasmtime is ~30 crates; most users don't need it in their dependency tree |
|
||||
| 4 | **Bump allocator in guests** | Zero-dependency, predictable, sufficient for request/response patterns |
|
||||
| 5 | **Dest address in message payload** | Avoids hardcoded addresses; guests can send to any actor the host tells them about |
|
||||
| 6 | **Traps = panics (no Result)** | Matches swactor's existing panic-safety model; `catch_unwind` in `tick_all` poisons the actor |
|
||||
| 7 | **Engine sharing via Arc** | Module compilation is expensive; `SharedEngine` amortizes it across actors |
|
||||
| 8 | **Maximum sandboxing defaults** | Disabled: threads, SIMD, relaxed SIMD, reference types, multi-value. Enabled: bulk memory (required by most compilers) |
|
||||
|
||||
---
|
||||
|
||||
## 7. Known Gaps & Future Improvements
|
||||
|
||||
| # | Gap | Notes |
|
||||
|---|-----|-------|
|
||||
| 1 | **No fuel metering** | wasmtime supports fuel; maps naturally to per-tick actor budgets. Deferred to follow-up. |
|
||||
| 2 | **No WASI** | No filesystem, network, random, or clock access. Intentional for sandboxing, but limits guest capabilities. |
|
||||
| 3 | **No guest SDK crate** | The test guests serve as examples. A published `swactor-guest` crate with the alloc/handle/send glue would reduce boilerplate. |
|
||||
| 4 | **Bump allocator never frees** | Fine for short-lived handle calls, but long-running actors would need a real allocator. |
|
||||
| 5 | **No pre-compilation cache** | `Module::new()` recompiles every time. wasmtime supports serialized modules for faster cold starts. |
|
||||
| 6 | **`cargo test -p` doesn't resolve** | Must use `--manifest-path`. Workspace resolution quirk. |
|
||||
|
||||
---
|
||||
|
||||
## 8. Test Coverage Summary
|
||||
|
||||
7 behavioral tests in `crates/bin-runner/tests/wasm_actor.rs`:
|
||||
|
||||
| Test | Scenario |
|
||||
|------|----------|
|
||||
| `echo_returns_same_payload` | Send bytes → wasm echoes them back to inbox |
|
||||
| `echo_preserves_binary_payload` | All 256 byte values survive the roundtrip |
|
||||
| `silent_produces_no_output` | Guest does nothing; no error, no messages |
|
||||
| `double_sends_two_copies` | One message in → two messages out |
|
||||
| `missing_alloc_export_returns_error` | WAT module with no exports → `WasmActorError::MissingExport` |
|
||||
| `shared_engine_serves_multiple_actors` | Two actors from the same `SharedEngine` work independently |
|
||||
| `native_actor_communicates_with_wasm_actor` | Native Rust actor → WasmActor → inbox (two-tick delivery) |
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
# cfuzz Branch — Development History Overview
|
||||
|
||||
> 19 improvement cycles on the `cfuzz` branch.
|
||||
> Research-driven methodology: study competitors → identify gap → implement → test → benchmark.
|
||||
> Grew test suite from 42 → 148 passing tests.
|
||||
|
||||
---
|
||||
|
||||
## Methodology
|
||||
|
||||
Each cycle followed a consistent pattern:
|
||||
|
||||
1. **Research** — Study how competitors (Erlang/OTP, Tokio, Akka, Ractor, Actix, Kameo) handle the problem
|
||||
2. **Identify gap** — Find a specific deficiency in swactor
|
||||
3. **Implement** — Fix the gap with minimal, targeted changes
|
||||
4. **Test** — Write behavioral tests (Given/When/Then) from the consumer's perspective
|
||||
5. **Benchmark** — Measure impact where applicable
|
||||
|
||||
### Constraints
|
||||
|
||||
- `src/` structure is frozen — no new files or modules, only modify existing files in-place
|
||||
- No new dependencies on the root crate
|
||||
- Behavioral tests only — no white-box/structural tests
|
||||
- All `cargo test` must pass before each commit
|
||||
- Never delete tests for active code
|
||||
|
||||
---
|
||||
|
||||
## Baseline Benchmarks (Pre-Improvement)
|
||||
|
||||
| Benchmark | Time | Throughput |
|
||||
|-----------|------|-----------|
|
||||
| spawn | 1.28 µs | — |
|
||||
| message_roundtrip | 2.24 µs | — |
|
||||
| send_fire_and_forget | 1.50 µs | — |
|
||||
| single_actor/1000 | 57.5 µs | 17.4 Melem/s |
|
||||
| multi_actor/100x100 | 610.6 µs | 16.4 Melem/s |
|
||||
| ring/100 | 99.9 µs | 1.01 Melem/s |
|
||||
|
||||
---
|
||||
|
||||
## Cycle Summary
|
||||
|
||||
| Cycle | Commit | Topic | Tests Added | Cumulative Tests |
|
||||
|-------|--------|-------|-------------|-----------------|
|
||||
| 1 | `ef87f7e` | [Fairness (message budget)](CYCLE_01_FAIRNESS.md) | 3 | 45 |
|
||||
| 2 | `10cb078` | [Stress tests + benchmarks](CYCLE_02_STRESS_TESTS.md) | 6 | 51 |
|
||||
| 3 | `acacc1b` | [Thread parking](CYCLE_03_THREAD_PARKING.md) | 1 | 52 |
|
||||
| 4 | `cf61619` | [Shutdown fix + bug-inspired tests](CYCLE_04_SHUTDOWN_FIX.md) | 5 | 57 |
|
||||
| 5 | `7d00e65` | [Load-aware placement](CYCLE_05_LOAD_AWARE_PLACEMENT.md) | 3 | 60 |
|
||||
| 6 | `265992c` | [Mailbox backpressure](CYCLE_06_BACKPRESSURE.md) | 4 | 64 |
|
||||
| 7 | `1779ad6` | [Actor recovery](CYCLE_07_ACTOR_RECOVERY.md) | 4 | 68 |
|
||||
| 8 | `0213938` | [Dead actor cleanup](CYCLE_08_DEAD_ACTOR_CLEANUP.md) | 2 (+2 updated) | 70 |
|
||||
| 9 | `e28aca0` | [Lifecycle hooks + graceful stop](CYCLE_09_LIFECYCLE_HOOKS.md) | 12 | 82 |
|
||||
| 10 | `d58a999` | [Actor timers](CYCLE_10_TIMERS.md) | 6 | 88 |
|
||||
| 11 | `9b1518b` | [Property-based testing](CYCLE_11_PROPERTY_TESTING.md) | 7 | 95 |
|
||||
| 12 | `66a8523` | [Named actor registry](CYCLE_12_NAMED_REGISTRY.md) | 11 | 106 |
|
||||
| 13 | `8782638` | [Actor monitoring](CYCLE_13_MONITORING.md) | 7 | 113 |
|
||||
| 14 | `4d18874` | [Actor groups](CYCLE_14_GROUPS.md) | 9 | 122 |
|
||||
| 15 | `902471b` | [Ask pattern](CYCLE_15_ASK_PATTERN.md) | 5 | 127 |
|
||||
| 16 | `0ef6df9` | [Registry benchmarks](CYCLE_16_REGISTRY_BENCHMARKS.md) | 0 | 127 |
|
||||
| 17 | `a70bd86` | [Supervision trees](CYCLE_17_SUPERVISION.md) | 10 | 138 |
|
||||
| 18 | `771c38c` | [OneForAll + RestForOne](CYCLE_18_SUPERVISOR_STRATEGIES.md) | 3 | 141 |
|
||||
| 19 | `c688f0a` | [Router](CYCLE_19_ROUTER.md) | 7 | 148 |
|
||||
|
||||
---
|
||||
|
||||
## Thematic Groupings
|
||||
|
||||
### Scheduling & Performance (Cycles 1–5)
|
||||
Foundation work: fairness guarantees, stress testing, thread parking, shutdown reliability, and load-aware actor placement. Research thread: BEAM reductions → tokio coop budget → Kameo/Actix mailboxes → tokio parker → work stealing survey.
|
||||
|
||||
### Resilience & Lifecycle (Cycles 6–10)
|
||||
Production hardening: backpressure, crash recovery, memory leak fix, lifecycle hooks, and deterministic timers. Narrative arc: from "actors crash permanently" to "actors have a fully managed lifecycle."
|
||||
|
||||
### Testing & Service Discovery (Cycles 11–16)
|
||||
Property-based testing for invariant verification, plus four registry features (names, monitoring, groups, ask pattern) and benchmarks to validate them. Research shifted from scheduling to service discovery patterns.
|
||||
|
||||
### Supervision (Cycles 17–19)
|
||||
Capstone features built on everything preceding: supervision trees with configurable restart strategies, and routers for actor pool management. Directly modeled on Erlang/OTP supervision trees.
|
||||
|
||||
---
|
||||
|
||||
## Frameworks Studied
|
||||
|
||||
| Framework | Language | Key Lessons |
|
||||
|-----------|----------|-------------|
|
||||
| Erlang/OTP BEAM | Erlang | 4000-reduction budget, supervision trees, pg groups, gen_server:call |
|
||||
| Tokio | Rust | 128-op coop budget, work-stealing, parker state machine |
|
||||
| Akka | Scala/Java | SupervisorStrategy, Router actors, PoisonPill |
|
||||
| Ractor | Rust | String-based registry, SupervisionEvent, bug history |
|
||||
| Actix | Rust | Vyukov MPSC queue, 256-message guard, ctx.stop() |
|
||||
| Kameo | Rust | Dual mailbox (bounded/unbounded), on_panic hook, ActorPool |
|
||||
| Linux CFS/EEVDF | C | vruntime fairness, NO_HZ adaptive ticks |
|
||||
| libuv/Node.js | C | Phase-based event loop, round-robin handlers |
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
# Cycle 1: Per-Actor Message Budget for Tick Fairness — Development History
|
||||
|
||||
> Commit: `ef87f7e` · 8 files · Priority: P0 (critical bug fix)
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
The `tick_all` function in `worker.rs` drained the **entire mailbox** for each actor before moving to the next:
|
||||
|
||||
```rust
|
||||
while let Some(msg) = slot.mailbox.pop_front() {
|
||||
// processes ALL messages for actor A before moving to actor B
|
||||
}
|
||||
```
|
||||
|
||||
If actor A had 10,000 queued messages, all other actors on the same worker were completely starved until A finished. This is a critical fairness bug — every other runtime studied prevents this.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Runtime | Fairness Mechanism | Budget |
|
||||
|---------|-------------------|--------|
|
||||
| Erlang/OTP BEAM | Reduction counting, preemptive | 4,000 reductions |
|
||||
| Tokio | Cooperative budgeting | 128–256 operations |
|
||||
| libuv/Node.js | Round-robin across handlers | No single handler drains completely |
|
||||
| Linux CFS | vruntime-based fairness | Time slices enforced |
|
||||
| Ractor | N/A (1 task = 1 actor via tokio) | Inherited from tokio |
|
||||
| **Swactor (before)** | **None** | **Unlimited drain** |
|
||||
|
||||
The BEAM's reduction budget (4,000 per process before preemption) is the gold standard for actor fairness. Tokio's cooperative budget (128 ops) serves a similar purpose for async tasks. Actix has a 256-message assertion guard that validates the approach.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Added `actor_message_budget: usize` to `RuntimeConfig` (default: 64)
|
||||
- Modified `tick_all` in `worker.rs` to break after `budget` messages per actor per tick
|
||||
- `budget=0` means unlimited (100% backward compatible)
|
||||
- Updated `RuntimeConfig` struct literals across all crates (python, runtime-dashboard, mt_benchmarks)
|
||||
|
||||
**Key files modified:** `src/worker.rs`, `src/config.rs`, `benches/runtime_benchmarks.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Budget of 64 chosen** as default — between BEAM's 4,000 (too generous for swactor's coarser granularity) and tokio's 128 (per-op vs per-message). Benchmarks showed budget=32 was slightly faster for throughput, but 64 provides more fairness headroom.
|
||||
- **Per-runtime, not per-actor** — simpler configuration, matching the BEAM model where the reduction budget is global. Per-actor budgets could be added later as an extension.
|
||||
- **budget=0 means unlimited** — backward compatibility for users who want the old behavior.
|
||||
|
||||
## Tests Added
|
||||
|
||||
3 new behavioral tests (42 → 45 total):
|
||||
|
||||
- `hot_actor_does_not_starve_cold_actor` — hot actor with many messages doesn't prevent cold actor from processing
|
||||
- `unlimited_budget_drains_all` — budget=0 preserves old behavior
|
||||
- `budget_messages_drain_across_multiple_ticks` — excess messages carry over to next tick
|
||||
|
||||
**Benchmarks added:** `fairness/cold_latency_under_pressure`, `fairness/throughput_by_budget`
|
||||
|
||||
## Result
|
||||
|
||||
- 45 tests pass (42 original + 3 new)
|
||||
- All workspace crates compile
|
||||
- Baseline benchmarks established for future comparison
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
# Cycle 2: Stress Tests, Expanded Benchmarks, and Research Extension — Development History
|
||||
|
||||
> Commit: `10cb078` · 4 files · 517 insertions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
After fixing the fairness bug in Cycle 1, the runtime needed stress testing under adversarial conditions to find edge cases. Additionally, the competitor survey was extended to cover Kameo and Actix — two frameworks with distinct approaches to mailbox management and message dispatch.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
### Kameo (v0.19)
|
||||
- Fully async on tokio, one task per actor
|
||||
- Dual mailbox: bounded (default 64) or unbounded tokio mpsc channels
|
||||
- Typed signals via vtable dispatch (no `Box<dyn Any>` downcast)
|
||||
- Erlang-style links for supervision (`on_link_died`)
|
||||
- `on_panic` hook can restart actor (vs swactor's then-permanent poisoning)
|
||||
- Known bugs: deadlocks in link establishment, leaked ActorRef preventing stop
|
||||
|
||||
### Actix (v0.13)
|
||||
- Context-as-Future model — each actor is a single pollable Future on an Arbiter
|
||||
- **Custom Vyukov lock-free MPSC queue** (not tokio channels) — push is single atomic_swap
|
||||
- Default mailbox capacity: 16 (tiny)
|
||||
- `do_send()` bypasses capacity for internal notifications
|
||||
- **256-message assertion guard** — validates swactor's budget approach
|
||||
- vtable dispatch via `Box<dyn EnvelopeProxy<A>>` — no Any downcast
|
||||
- WHY FAST: custom MPSC queue, no async overhead, same-thread actors avoid cross-thread coordination
|
||||
|
||||
### Key Insight
|
||||
Both frameworks use vtable dispatch instead of `Box<dyn Any>` downcast. Actix's 256-message assertion guard independently validates the per-actor budget concept from Cycle 1.
|
||||
|
||||
## Implementation
|
||||
|
||||
### Stress Tests (6 new)
|
||||
- `message_ordering_preserved_under_budget` — FIFO order with budget=8
|
||||
- `mt_stress_many_senders_one_receiver` — 50 senders × 100 msgs on 4 threads
|
||||
- `mt_stress_concurrent_spawn_and_send` — 200 concurrent spawn+send on 4 threads
|
||||
- `mt_chain_spawning_under_load` — 50-level chain across 2 workers
|
||||
- `mt_panic_isolation_under_load` — 10 panicking + 10 healthy actors on 4 threads
|
||||
- `sustained_throughput_does_not_drop_messages` — 10 batches × 100 msgs
|
||||
|
||||
### Benchmarks (2 new groups)
|
||||
- `msg_size` group: throughput and send_latency by message size (8B, 64B, 256B, 1KB, 4KB)
|
||||
- `contention` group: fanin (1–100 senders to 1 sink), cross_worker (1–4 threads)
|
||||
|
||||
**Key files modified:** `tests/runtime_api.rs`, `benches/runtime_benchmarks.rs`, `CLAUDE/notes/research_synthesis.md`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Multi-threaded stress tests** included because single-threaded testing can't catch cross-worker races
|
||||
- **Panic isolation test** inspired by Actix's SyncArbiter model — ensures one panicking actor doesn't take down healthy actors on other workers
|
||||
- **Message ordering test** validates that the budget mechanism (Cycle 1) doesn't break FIFO guarantees
|
||||
- **Chain spawning** tests the spawn+send-in-same-handler pattern across worker boundaries
|
||||
|
||||
## Tests Added
|
||||
|
||||
6 new stress tests (45 → 51 total):
|
||||
|
||||
| Test | Pattern | Purpose |
|
||||
|------|---------|---------|
|
||||
| `message_ordering_preserved_under_budget` | FIFO verification | Budget doesn't break ordering |
|
||||
| `mt_stress_many_senders_one_receiver` | Fan-in | 50:1 contention on 4 threads |
|
||||
| `mt_stress_concurrent_spawn_and_send` | Concurrent spawn | Race condition hunting |
|
||||
| `mt_chain_spawning_under_load` | Cascading spawn | Cross-worker chain delivery |
|
||||
| `mt_panic_isolation_under_load` | Fault isolation | Panics don't spread |
|
||||
| `sustained_throughput_does_not_drop_messages` | Sustained load | No message loss over time |
|
||||
|
||||
## Result
|
||||
|
||||
- 51 tests pass (42 original + 3 fairness + 6 stress)
|
||||
- All workspace crates compile
|
||||
- No bugs found — the runtime handles adversarial conditions correctly
|
||||
- Benchmark data provides baselines for message size sensitivity and contention scaling
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
# Cycle 3: Thread Parking for Instant Worker Wakeup — Development History
|
||||
|
||||
> Commit: `acacc1b` · 4 files · 59 insertions, 10 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Before this change, idle workers used `thread::sleep` with a fixed timeout to wait for new work. This meant an idle worker wouldn't notice new messages until its sleep timer expired — up to 1ms of unnecessary latency on the idle-to-active transition. Under bursty workloads, this sleep-based backoff wastes both time and power.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Runtime | Idle Strategy | Wakeup Mechanism |
|
||||
|---------|--------------|-----------------|
|
||||
| Tokio | Parker state machine (notified/sleeping/empty) | `unpark()` via atomic CAS |
|
||||
| Linux | NO_HZ adaptive ticks (stop tick when idle) | Interrupt on new work |
|
||||
| Go | `notewakeup` / futex | OS-level wake |
|
||||
| BEAM | Scheduler sleep + signal | Thread signal |
|
||||
| **Swactor (before)** | **`thread::sleep(1ms)`** | **Timer expiry only** |
|
||||
|
||||
Tokio's parker uses a 3-state machine (notified → sleeping → empty) with atomic transitions. The key insight: `unpark()` is a **no-op** if the thread isn't parked, so callers pay zero cost on the hot path.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Replaced `thread::sleep` with `thread::park_timeout` in worker run loop
|
||||
- Workers register `thread::current()` via `OnceLock<Thread>` on startup
|
||||
- `send_to` and `spawn` call `Thread::unpark()` on target worker after enqueuing work
|
||||
- Cross-worker sends from `WorkerContext` also unpark the target
|
||||
- Zero new dependencies — uses only `std::sync::OnceLock` + `std::thread::park_timeout`
|
||||
|
||||
**Key files modified:** `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **`OnceLock<Thread>` for thread handle storage** — set-once semantics match the worker lifecycle (one thread per worker, never changes). Simpler than `Mutex<Option<Thread>>`.
|
||||
- **`park_timeout` instead of `park`** — timeout ensures workers periodically wake even without explicit unpark, preventing permanent sleep if an unpark is missed.
|
||||
- **Unpark on `send_to` and `spawn`** — these are the two operations that create work for a worker. The cost is a single atomic store (no-op if thread is already running).
|
||||
- **No condvar** — `thread::park/unpark` is simpler and avoids the spurious wakeup complexity of condition variables. Tokio's parker validates this approach.
|
||||
|
||||
## Tests Added
|
||||
|
||||
1 new test (51 → 52 total):
|
||||
|
||||
- `mt_parked_worker_wakes_on_send` — verifies that a parked worker processes a message immediately after send (not after timeout)
|
||||
|
||||
## Result
|
||||
|
||||
- 52 tests pass
|
||||
- All workspace crates compile
|
||||
- Idle-to-active latency reduced from up to 1ms to near-zero
|
||||
- No overhead on hot path — `unpark()` is a no-op when thread isn't parked
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
# Cycle 4: Shutdown Fix + Bug-Inspired Tests — Development History
|
||||
|
||||
> Commit: `cf61619` · 3 files · 161 insertions, 12 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Cycle 3 introduced thread parking, but created a new problem: `shutdown()` didn't unpark workers. Parked workers wouldn't notice the shutdown signal until their `park_timeout` expired, causing delayed shutdown. Additionally, studying bug reports from competitor projects (Ractor, Kameo, Actix) revealed specific failure modes worth testing in swactor.
|
||||
|
||||
## Competitor Bug Analysis
|
||||
|
||||
The 5 new tests were directly inspired by real bug reports from other actor frameworks:
|
||||
|
||||
| Test | Inspired By | Bug |
|
||||
|------|-------------|-----|
|
||||
| `stats_snapshot_is_read_only` | Ractor #310 | `get_children()` was destructive — moved children out of supervisor |
|
||||
| `stats_under_load_do_not_interfere_with_processing` | General | Stats collection shouldn't slow down message processing |
|
||||
| `shutdown_wakes_parked_workers_immediately` | Cycle 3 regression | Parked workers must notice shutdown promptly |
|
||||
| `mt_send_after_run_delivers_to_running_actors` | Kameo #185 | Messages sent after `run()` weren't delivered during startup race |
|
||||
| `budget_respected_even_with_self_sends` | Actix #515 | Self-sends bypassed mailbox capacity, defeating backpressure |
|
||||
|
||||
## Implementation
|
||||
|
||||
### Shutdown Fix
|
||||
- `shutdown()` now iterates all workers and calls `unpark()` on each thread handle
|
||||
- Parked workers wake immediately and check the shutdown flag
|
||||
- Workers that aren't parked are unaffected (unpark is a no-op)
|
||||
|
||||
### Bug-Inspired Tests
|
||||
Each test encodes a real bug class discovered in competitor frameworks, ensuring swactor doesn't have the same vulnerability.
|
||||
|
||||
**Key files modified:** `src/runtime.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Unpark-all on shutdown** rather than a dedicated shutdown condvar — simpler, reuses existing parking infrastructure from Cycle 3
|
||||
- **Bug-inspired testing methodology** — studying competitor bug trackers yields high-value test cases that target real failure modes, not theoretical ones
|
||||
|
||||
## Tests Added
|
||||
|
||||
5 new tests (52 → 57 total):
|
||||
|
||||
- `stats_snapshot_is_read_only` — reading stats doesn't mutate runtime state (from Ractor #310)
|
||||
- `stats_under_load_do_not_interfere_with_processing` — stats don't affect message processing throughput
|
||||
- `shutdown_wakes_parked_workers_immediately` — validates fast shutdown with thread parking
|
||||
- `mt_send_after_run_delivers_to_running_actors` — messages sent after run() are delivered (from Kameo #185)
|
||||
- `budget_respected_even_with_self_sends` — self-sends don't bypass budget (from Actix #515)
|
||||
|
||||
## Result
|
||||
|
||||
- 57 tests pass
|
||||
- All workspace crates compile
|
||||
- Shutdown latency with parked workers reduced from up to 1ms to near-zero
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
# Cycle 5: Load-Aware Actor Placement + Work Stealing Research — Development History
|
||||
|
||||
> Commit: `7d00e65` · 6 files · 184 insertions, 13 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
With fairness (Cycle 1), thread parking (Cycle 3), and shutdown (Cycle 4) resolved, the next bottleneck was actor placement. Swactor used blind round-robin to assign actors to workers — ignoring current load. If actors have unequal workloads, round-robin produces persistent imbalance. This cycle also included deep research into work stealing to decide whether full actor migration was worthwhile.
|
||||
|
||||
## Competitor Analysis: Work Stealing Deep Dive
|
||||
|
||||
| Aspect | Tokio | Go | BEAM | ForkJoinPool |
|
||||
|--------|-------|-----|------|-------------|
|
||||
| Queue | Fixed 256-slot ring | 256-slot ring + runnext | Per-priority linked | Growable array deque |
|
||||
| Steal granularity | Half victim's queue | Half victim's runq | Individual processes | One task at a time |
|
||||
| LIFO fast-path | Dedicated slot (3-use cap) | runnext (stealable 4th try) | None | Owner pops from top |
|
||||
| Global queue | Mutex intrusive list | Checked 1/61 ticks | Per-priority migration | Even-indexed queues |
|
||||
| Searcher limit | N/2 workers | GOMAXPROCS/2 | N/A (proactive migration) | Idle stack in ctl |
|
||||
| Balance strategy | Reactive steal | Reactive steal | **Proactive migration** + reactive | Reactive scan |
|
||||
|
||||
### Key Patterns Discovered
|
||||
|
||||
1. **LIFO slot** — every runtime has one; improves cache locality by running the recipient immediately after the sender. Tokio caps at 3 consecutive uses to prevent starvation.
|
||||
2. **Steal-half** — Tokio and Go both steal half the victim's queue, amortizing cross-thread coordination overhead.
|
||||
3. **N/2 searcher limit** — both Tokio and Go cap concurrent searchers to prevent thundering herd (O(N²) cache-line bouncing).
|
||||
4. **BEAM's migration** — unique dual approach: reactive stealing when idle + proactive migration via periodic `check_balance()`.
|
||||
|
||||
### Feasibility for Swactor
|
||||
|
||||
- **Full actor migration**: Mechanically possible (ActorSlot is `Send`), but has a 1-tick message loss window during migration and requires push-based donation (`ActorPool` is not `Sync` → no pull stealing)
|
||||
- **Message stealing without actors**: Impossible — the actor IS the state; messages without the actor are meaningless
|
||||
- **Decision: Load-aware placement over work stealing** — zero correctness risk, handles the primary imbalance source (uneven spawn distribution), full work stealing deferred
|
||||
|
||||
## Implementation
|
||||
|
||||
- `Placement::next_worker()` now reads per-worker stats (`num_actors` + `mailbox_depth`)
|
||||
- Selects the worker with lowest combined load
|
||||
- Scan starts from a rotating position → round-robin fallback when all stats are equal (initial burst, before first tick publishes stats)
|
||||
- O(N) relaxed atomic loads per spawn — trivial for N ≤ 8 workers
|
||||
|
||||
**Key files modified:** `src/delivery.rs`, `tests/runtime_api.rs`, `benches/runtime_benchmarks.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Load-aware placement instead of work stealing** — zero message loss risk, no ordering changes, trivial implementation cost. Handles the #1 source of imbalance: uneven spawn distribution.
|
||||
- **Combined metric (actors + depth)** — neither actor count alone nor mailbox depth alone captures load accurately. Combined metric approximates total pending work per worker.
|
||||
- **Relaxed atomics for stat reads** — stats are advisory (best-effort), so relaxed ordering is sufficient. No need for acquire/release which would add synchronization cost.
|
||||
- **Round-robin fallback** — before the first tick, all workers report zero stats. Falling back to round-robin ensures even initial distribution rather than always picking worker 0.
|
||||
- **Full work stealing deferred** — would require migration channels, address map coordination, forwarding tombstones, and a message loss window. Benefit uncertain for N ≤ 8 workers.
|
||||
|
||||
## Tests Added
|
||||
|
||||
3 new tests (57 → 60 total):
|
||||
|
||||
- `load_aware_placement_prefers_lighter_worker` — imbalanced load biases spawn toward the lighter worker
|
||||
- `load_aware_placement_single_worker_degrades_gracefully` — single-thread mode works correctly
|
||||
- `load_aware_placement_falls_back_to_round_robin_on_fresh_runtime` — even distribution before ticks produce stats
|
||||
|
||||
**Benchmark added:** `placement/spawn_under_load` (2-thread and 4-thread variants)
|
||||
|
||||
## Result
|
||||
|
||||
- 60 tests pass
|
||||
- All workspace crates compile
|
||||
- Comprehensive work-stealing research documented for future reference
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
# Cycle 6: Per-Actor Mailbox Backpressure — Development History
|
||||
|
||||
> Commit: `265992c` · 6 files · 163 insertions, 8 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Before this change, swactor mailboxes were unbounded — a fast producer could flood a slow consumer's mailbox without limit, eventually exhausting memory. Every production actor framework provides some form of backpressure. This was identified as a key weakness in the competitor analysis.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Default Capacity | Overflow Policy | Backpressure Model |
|
||||
|-----------|-----------------|----------------|-------------------|
|
||||
| Erlang/OTP | Unbounded | N/A (pobox for opt-in bounding) | Process isolation limits blast radius |
|
||||
| Actix | 16 | `do_send()` bypasses for internal msgs | Tiny default, force callers to handle |
|
||||
| Kameo | 64 | Bounded tokio mpsc (sender blocks) | Blocking backpressure |
|
||||
| Tokio mpsc | User-specified | Bounded (sender blocks or permit pattern) | Blocking or try_send |
|
||||
| Go channels | User-specified | Blocking send / non-blocking select | Blocking backpressure |
|
||||
| **Swactor (before)** | **Unbounded** | **None** | **None** |
|
||||
|
||||
Key observation: Actix's default capacity of 16 is aggressive — it forces callers to think about message flow. Kameo's 64 matches swactor's message budget. The consensus across frameworks: bounded by default, with configurable overflow policy.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Added `MailboxOverflow` enum: `DropNewest` (discard incoming when full) and `DropOldest` (evict oldest to make room)
|
||||
- Added `default_mailbox_capacity` and `mailbox_overflow` to `RuntimeConfig`
|
||||
- Default: `capacity=0` (unbounded) — 100% backward compatible
|
||||
- `ActorSlot` stores per-actor capacity and policy (initialized from runtime defaults at spawn time)
|
||||
- `deliver()` in worker enforces bounds; dropped messages tracked via `drops_this_tick` counter
|
||||
- `messages_dropped: AtomicU64` added to `WorkerStats` and `WorkerInfo`
|
||||
|
||||
**Key files modified:** `src/config.rs`, `src/worker.rs`, `src/runtime.rs`, `src/stats.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **DropNewest vs DropOldest (not blocking)** — swactor's synchronous tick model can't block the sender (it would deadlock the entire worker). Drop policies are the only viable option for a sync runtime.
|
||||
- **Default unbounded** — backward compatibility. Users opt into backpressure by setting capacity > 0.
|
||||
- **Per-runtime defaults, not per-actor** — simpler configuration. Per-actor overrides could be added later via a builder pattern on spawn.
|
||||
- **Drop counting** — critical for observability. Without it, users can't tell if their system is losing messages.
|
||||
- **No DropRandom** — the two policies cover the common cases. DropNewest protects against producer floods (newest messages are redundant). DropOldest keeps the freshest state (useful for sensor/status actors).
|
||||
|
||||
## Tests Added
|
||||
|
||||
4 new tests (60 → 64 total):
|
||||
|
||||
- `bounded_mailbox_drop_newest_caps_at_capacity` — 50 msgs sent, capacity 10 → only 10 delivered (oldest 10)
|
||||
- `bounded_mailbox_drop_oldest_keeps_newest` — 10 msgs sent, capacity 5 → newest 5 kept
|
||||
- `unbounded_mailbox_delivers_all_messages` — backward compatibility: capacity=0 delivers everything
|
||||
- `bounded_mailbox_refills_after_processing` — capacity 5, process batch, refill works correctly
|
||||
|
||||
## Result
|
||||
|
||||
- 64 tests pass
|
||||
- All workspace crates compile
|
||||
- Swactor weakness "no backpressure" resolved
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
# Cycle 7: Actor Recovery via Factory-Based Restart — Development History
|
||||
|
||||
> Commit: `1779ad6` · 6 files · 167 insertions, 10 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Before this change, a panicking actor was permanently poisoned — it could never process messages again. Its address remained in the address map but silently discarded all messages. In production, this means a single panic permanently degrades the system. Every mature actor framework provides some form of crash recovery.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Recovery Model | State After Restart | Mailbox After Restart |
|
||||
|-----------|---------------|--------------------|-----------------------|
|
||||
| Erlang/OTP | Factory (MFA tuple), fresh process | Fresh (new init/1) | Lost (new PID) |
|
||||
| Akka | Replace internals, keep ActorRef | Fresh (preRestart hook) | Preserved (docs say "usually wrong") |
|
||||
| Kameo | `on_panic(&mut self)` hook | Potentially corrupt | Preserved |
|
||||
| Actix | `Supervised` trait, re-create context | Fresh | Lost |
|
||||
| Ractor | `SupervisionEvent` callback | Up to supervisor | Up to supervisor |
|
||||
| **Swactor (before)** | **None — permanent poison** | **N/A** | **Silently discarded** |
|
||||
|
||||
### Key Insight
|
||||
Akka's approach of preserving state by replacing internals is documented as "usually wrong" — the state that caused the panic is likely corrupt. Kameo's `on_panic(&mut self)` is risky for the same reason. Erlang's factory-based restart (fresh process from MFA tuple) is the safest approach: guaranteed clean state.
|
||||
|
||||
## Implementation
|
||||
|
||||
- `Actor<A>` expanded from tuple struct to named fields: `inner`, `restart_factory`, `max_restarts`, `restart_count`
|
||||
- `AnyActor::try_restart(&self) -> Option<Box<dyn AnyActor>>` trait method (default `None`, backward compatible)
|
||||
- Factory stored as `Arc<dyn Fn() -> A + Send + Sync>` — called to produce fresh actor instance on restart
|
||||
- `spawn_restartable(actor, factory, max_restarts)` added to both `Runtime` and `Ctx`
|
||||
- `tick_all` panic handler: `try_restart()` before poisoning; on success, replace actor, clear mailbox, reset state
|
||||
- `restarts` counter added to `WorkerStats` and `WorkerInfo`
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `src/runtime.rs`, `src/worker.rs`, `src/stats.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Factory-based restart (Erlang model)** — safest approach, guaranteed clean state. Factory closure is `Arc<dyn Fn() -> A>`, cloned into fresh `Actor<A>` on each restart.
|
||||
- **max_restarts limit** — prevents infinite restart loops. When exceeded, actor is permanently poisoned. Mirrors Erlang's restart intensity.
|
||||
- **Mailbox cleared on restart** — messages that triggered the panic are discarded. Fresh actor starts with empty mailbox. (Erlang does this too — new PID means new mailbox.)
|
||||
- **Same address preserved** — unlike Erlang (new PID), the restarted actor keeps its `ActorAddress`. This is simpler for callers and matches Akka's model.
|
||||
- **Factory fields are "cold"** — `restart_factory` and `max_restarts` are never touched by `handle_any` (the hot path). After `catch_unwind`, these fields are guaranteed safe to read.
|
||||
- **Non-restartable actors unchanged** — `try_restart()` returns `None` by default, preserving the existing poison-on-panic behavior.
|
||||
|
||||
## Tests Added
|
||||
|
||||
4 new tests (64 → 68 total):
|
||||
|
||||
- `restartable_actor_recovers_after_panic` — basic restart works: panic, recover, process new messages
|
||||
- `restartable_actor_resets_state_on_restart` — fresh state confirmed post-restart (counter resets to zero)
|
||||
- `restartable_actor_respects_max_restarts` — 2 restarts allowed, 3rd panic → permanent poison
|
||||
- `non_restartable_actor_still_poisons_on_panic` — backward compatibility: default actors still poison
|
||||
|
||||
## Result
|
||||
|
||||
- 68 tests pass
|
||||
- All workspace crates compile
|
||||
- Swactor weakness "panicked actors permanently poisoned" resolved
|
||||
- Foundation laid for supervision trees (Cycle 17)
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
# Cycle 8: Dead Actor Cleanup (Memory Leak Fix) — Development History
|
||||
|
||||
> Commit: `0213938` · 4 files · 120 insertions, 14 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
After Cycles 7 (recovery) and the pre-existing poison-on-panic behavior, dead actors accumulated in both `ActorPool` and `AddressMap` forever. Their slots were never reclaimed, their addresses remained registered, and the system gradually leaked memory. This is a known bug class in actor frameworks.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Dead Actor Handling | Known Bugs |
|
||||
|-----------|-------------------|------------|
|
||||
| Akka | Automatic cleanup via DeathWatch | #22990 — ActorRef leak in certain paths |
|
||||
| CAF | Manual cleanup expected | #420 — actor leak in specific failure modes |
|
||||
| Erlang/OTP | Automatic — process exits free all resources | N/A (VM handles cleanup) |
|
||||
| Ractor | Supervisor-driven cleanup | Memory bloat per actor at scale |
|
||||
| **Swactor (before)** | **None — permanent leak** | **Both ActorPool and AddressMap leak** |
|
||||
|
||||
## Implementation
|
||||
|
||||
- Added `AddressMap::remove(addr)` to `delivery.rs` — O(1) removal from address map
|
||||
- Added `ActorPool::cleanup_dead()` to `worker.rs` — collects and removes poisoned actors, returns their addresses
|
||||
- Added Phase 7 to `tick_once`: `cleanup_dead` → remove from address_map → re-publish `num_actors` stat
|
||||
- Stats immediately reflect removal (no stale counts)
|
||||
|
||||
**Key files modified:** `src/delivery.rs`, `src/worker.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Automatic cleanup in tick_once** — no manual API needed. Dead actors are cleaned up every tick, preventing accumulation.
|
||||
- **Phase 7 (after all message processing)** — cleanup happens after `tick_all` and `pending_local`, so any final messages to dead actors correctly fail. No risk of cleaning up an actor that's about to receive a message.
|
||||
- **Re-publish `num_actors` after cleanup** — ensures stats are immediately consistent. Without this, stats would show stale actor counts until the next tick.
|
||||
|
||||
### Behavior Change
|
||||
- **Before**: Sending to a poisoned actor silently discarded the message (address still in map, delivery succeeded, but processing was skipped)
|
||||
- **After**: Sending to a cleaned-up actor returns `Err` (address removed from map, send fails)
|
||||
- This is **better** — callers learn the actor is gone instead of silently losing messages.
|
||||
|
||||
## Tests Added
|
||||
|
||||
2 new tests + 2 existing tests updated (68 → 70 total):
|
||||
|
||||
- `dead_actor_cleaned_up_from_stats_and_address_map` — good actor persists, bad actor's address is removed
|
||||
- `bulk_dead_actor_cleanup` — 20 panicked actors all cleaned up in one tick
|
||||
- Updated `send_to_poisoned_actor_is_a_silent_black_hole` → now asserts send returns `Err` (behavior change)
|
||||
- Updated `poisoned_actor_messages_not_counted_as_processed` → sends fail to cleaned-up actor
|
||||
|
||||
## Result
|
||||
|
||||
- 70 tests pass
|
||||
- All workspace crates compile
|
||||
- Memory leak closed: dead actors no longer accumulate in ActorPool or AddressMap
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
# Cycle 9: Lifecycle Hooks and Graceful Actor Stop — Development History
|
||||
|
||||
> Commit: `e28aca0` · 8 files · 427 insertions, 27 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Before this change, actors had no initialization or teardown callbacks and no way to stop gracefully. An actor started processing messages immediately (no setup phase) and could only die by panicking. Every mature actor framework provides lifecycle hooks for resource management and graceful shutdown.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | on_start | on_stop | on_panic | Self-stop | External stop |
|
||||
|-----------|----------|---------|----------|-----------|---------------|
|
||||
| Erlang | `init/1` | `terminate/2` (NOT on crash) | N/A | `{stop,Reason,State}` | `gen_server:stop` |
|
||||
| Akka | `preStart` | `postStop` (always) | `preRestart` | `context.stop(self)` | PoisonPill / stop |
|
||||
| Actix | `started` | `stopped` | N/A | `ctx.stop()` | `addr.do_send(Stop)` |
|
||||
| Kameo | `on_start` | `on_stop` | `on_panic` | `Context::stop()` | `stop_gracefully/kill` |
|
||||
| Ractor | `pre_start` | `post_stop` (NOT on kill/panic) | N/A | `stop()` | `Signal::Kill` |
|
||||
| **Swactor** | **`on_start`** | **`on_stop` (NOT on panic)** | N/A | **`ctx.stop_self()`** | **`runtime.stop_actor()`** |
|
||||
|
||||
### Key Findings
|
||||
- Most frameworks do NOT call `on_stop` on panic — state may be corrupt, running teardown on corrupt state is unsafe. Erlang and Ractor agree. Akka is the outlier (always calls `postStop`).
|
||||
- Self-stop should be immediate (after current message). External stop should be queued (PoisonPill semantics — process pending messages first).
|
||||
- Restarted actors should get `on_start` called again on the fresh instance.
|
||||
|
||||
## Implementation
|
||||
|
||||
### Lifecycle Hooks
|
||||
- `ActorInterface::on_start(&mut self, ctx: &Ctx)` — default no-op, called on first tick before any messages
|
||||
- `ActorInterface::on_stop(&mut self, ctx: &Ctx)` — default no-op, called during cleanup for gracefully-stopped actors
|
||||
- `AnyActor::on_start()`/`on_stop()` — forwarded from `Actor<A>` implementation
|
||||
- `ActorSlot` gains `started: bool` flag — tracks whether `on_start` has been called
|
||||
- `on_start` called in `tick_all` before first message; panic in `on_start` → immediate poison
|
||||
- `on_stop` called in `cleanup_dead` for stopping (not poisoned) actors, wrapped in `catch_unwind`
|
||||
- Restarted actors get `started=false` so `on_start` fires again on fresh instance
|
||||
|
||||
### Graceful Stop (Dual Mode)
|
||||
- `ctx.stop_self()` — **immediate** stop after current message via `request_stop` buffer
|
||||
- `runtime.stop_actor(addr)` — **external** stop via `StopSignal` message (PoisonPill semantics: queued after existing messages)
|
||||
- `ActorSlot` gains `stopping: bool` flag
|
||||
- Phase 7 `cleanup_dead` now handles both poisoned AND stopping actors
|
||||
|
||||
### Stats
|
||||
- `stops: AtomicU64` added to `WorkerStats` and `WorkerInfo` — tracks graceful stops separately from panics
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs`, `src/stats.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **`on_stop` NOT called on panic** — matches Erlang and Ractor. Corrupt state after panic makes teardown unsafe. If you need cleanup, use `spawn_restartable` (Cycle 7) to get a fresh instance.
|
||||
- **Dual stop modes** — `ctx.stop_self()` is immediate (actor decides "I'm done after this message"). `runtime.stop_actor()` is queued (external signal processed after pending messages). This matches Erlang's `{stop, Reason, State}` vs `gen_server:stop`.
|
||||
- **StopSignal as a message** — external stop uses the same delivery pipeline as regular messages. No special-case routing needed. The PoisonPill pattern (Akka) is well-proven.
|
||||
- **`on_start` panic → immediate poison** — initialization failure is fatal. No restart attempted because the factory might produce the same broken actor. Matches Erlang's `{stop, Reason}` from `init/1`.
|
||||
- **Default no-ops** — both hooks are optional. Existing actors don't need to change. 100% backward compatible.
|
||||
|
||||
## Tests Added
|
||||
|
||||
12 new tests (70 → 82 total):
|
||||
|
||||
- `on_start_called_before_first_message` — on_start fires on first tick, before messages
|
||||
- `on_start_called_per_actor` — 5 actors each get exactly one on_start call
|
||||
- `on_start_panic_poisons_actor` — panic in on_start → poisoned, no messages processed
|
||||
- `actor_can_stop_self` — 5 msgs sent, stops after 3, only 3 processed, on_stop called
|
||||
- `runtime_can_stop_actor` — external stop via runtime, on_stop called, actor removed
|
||||
- `send_to_stopped_actor_returns_error` — stopped actor gone from address map
|
||||
- `stop_vs_panic_tracked_separately_in_stats` — stops and panics counted independently
|
||||
- `on_stop_can_send_messages` — farewell message sent during on_stop is delivered
|
||||
- `on_start_called_again_after_restart` — restartable actor gets on_start on fresh instance
|
||||
- `external_stop_is_queued_after_pending_messages` — PoisonPill semantics verified
|
||||
- `external_stop_before_new_messages_prevents_processing` — stop before send blocks new msgs
|
||||
- `stop_nonexistent_actor_returns_error` — stop on bad address returns Err
|
||||
|
||||
## Result
|
||||
|
||||
- 82 tests pass
|
||||
- All workspace crates compile
|
||||
- Swactor weaknesses "no lifecycle hooks" and "no graceful stop" both resolved
|
||||
- Foundation for supervision (Cycle 17) — `on_stop` enables resource cleanup, `stop_actor` enables supervisor-controlled shutdown
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
# Cycle 10: Per-Worker Tick-Counting Timers — Development History
|
||||
|
||||
> Commit: `d58a999` · 5 files · 247 insertions, 5 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Actors often need to schedule delayed or periodic work (timeouts, heartbeats, polling intervals). Before this change, swactor had no timer mechanism — actors had to manually count ticks or rely on external scheduling. The synchronous tick model makes wall-clock timers inappropriate, but tick-counting timers are a natural fit and provide deterministic behavior.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Timer Model | Deterministic? |
|
||||
|-----------|------------|---------------|
|
||||
| Erlang | `timer:send_after`, `erlang:start_timer` (wall-clock ms) | No |
|
||||
| Akka | `scheduleOnce`, `scheduler` (wall-clock duration) | No |
|
||||
| Actix | `ctx.run_later`, `ctx.run_interval` (wall-clock) | No |
|
||||
| Kameo | `tokio::time::sleep` (wall-clock) | No |
|
||||
| Tokio | `tokio::time` (wall-clock, pausable for testing) | With `time::pause()` |
|
||||
| Go | `time.After`, `time.NewTicker` (wall-clock) | No |
|
||||
| **Swactor** | **Tick-counting** | **Yes — fully deterministic** |
|
||||
|
||||
### Key Insight
|
||||
Swactor's synchronous tick model makes tick-counting timers uniquely valuable: a timer scheduled for "5 ticks from now" fires at exactly tick N+5, regardless of wall-clock speed. This makes timer behavior reproducible in tests and simulations — something no other framework provides natively.
|
||||
|
||||
Also researched but **rejected**: priority messages (lifecycle hooks from Cycle 9 cover 95% of use cases) and SmallBox optimization (deferred: measure allocation cost first before adding unsafe code).
|
||||
|
||||
## Implementation
|
||||
|
||||
### Timer Types
|
||||
- `OnceTimer` — fire once at `fire_at` tick, consumed after firing
|
||||
- `IntervalTimer` — fire every `period` ticks, message cloned via `CloneMsg` trait
|
||||
|
||||
### Timer Infrastructure
|
||||
- `CloneMsg` trait — type-erased clone for interval timer messages (blanket impl for `Message + Clone`)
|
||||
- `TimerRequest` enum: `Once { dest, msg, ticks }` | `Interval { dest, msg, period }`
|
||||
- Per-worker `TimerWheel` — stores pending timers, checked each tick
|
||||
|
||||
### Integration into tick_once
|
||||
- **Phase 2.5**: Fire due timers, route through full delivery system (pool.deliver for local actors, transfer_txs for cross-worker, inbox_registry for inboxes)
|
||||
- **Phase 5.5**: Drain timer requests from handler buffer into TimerWheel
|
||||
- **After cleanup_dead**: GC interval timers for dead actors
|
||||
|
||||
### API
|
||||
- `ctx.send_after_ticks(addr, msg, ticks)` — one-shot timer
|
||||
- `ctx.send_interval_ticks(addr, msg, period)` — interval timer
|
||||
- `Runtime::schedule_timer()` — no-op with warning (timers are per-worker only, must be scheduled from within a handler)
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `src/worker.rs`, `src/runtime.rs`, `src/delivery.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Tick-counting, not wall-clock** — deterministic behavior is a core swactor advantage. Wall-clock timers would break test reproducibility and simulation fidelity.
|
||||
- **Per-worker timer wheel** — timers are local to the worker that owns the actor. No cross-worker synchronization needed. Timer routing uses the same delivery system as regular messages.
|
||||
- **CloneMsg trait** — interval timers need to clone the message for each firing. A blanket impl covers all `Message + Clone` types, so users don't need to implement anything extra.
|
||||
- **Timer GC for dead actors** — interval timers must be cleaned up when their target actor dies, otherwise they fire forever into the void.
|
||||
|
||||
### Bug Fixed
|
||||
`gc_dead_intervals` was initially over-aggressive — it removed timers for ANY address not in the local pool, including inboxes and cross-worker actors. Fixed to only GC timers for addresses in the `dead` set from `cleanup_dead`.
|
||||
|
||||
## Tests Added
|
||||
|
||||
6 new tests (82 → 88 total):
|
||||
|
||||
- `one_shot_timer_fires_after_n_ticks` — timer with delay=3 fires on tick 4
|
||||
- `handler_can_schedule_one_shot_timer` — timer scheduled from within a handler fires correctly
|
||||
- `one_shot_timer_fires_only_once` — consumed after firing, doesn't repeat
|
||||
- `interval_timer_fires_repeatedly` — period=2, fires every 2 ticks (3 firings verified)
|
||||
- `interval_timer_cleaned_up_when_actor_dies` — GC removes orphaned interval timers
|
||||
- `timer_with_zero_delay_fires_next_tick` — delay=0 fires on next tick (not same tick)
|
||||
|
||||
## Result
|
||||
|
||||
- 88 tests pass
|
||||
- All workspace crates compile
|
||||
- Bug found and fixed: over-aggressive timer GC for cross-worker addresses
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
# Cycle 11: Property-Based Testing and Extended Fuzz Targets — Development History
|
||||
|
||||
> Commit: `9b1518b` · 5 files · 534 insertions, 3 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
After 10 cycles of behavioral tests, the test suite relied entirely on manually-written scenarios. Property-based testing can explore state spaces that humans wouldn't think to test, automatically finding minimal failing cases. With swactor's deterministic tick model, property-based testing is an especially good fit — no concurrency noise to mask bugs.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework/Tool | Testing Approach | Fit for Swactor |
|
||||
|----------------|-----------------|-----------------|
|
||||
| Tokio + Loom | Model-checking for lock-free code | Poor fit — swactor isn't lock-free |
|
||||
| Erlang + PropEr/QuickCheck | Property-based with shrinking | Good model for swactor |
|
||||
| Shuttle | Concurrency permutation testing | Moderate — useful for MT tests |
|
||||
| proptest-state-machine | Stateful property testing for Rust | **Perfect fit** — deterministic ticks |
|
||||
| cargo-fuzz | Coverage-guided fuzzing | Already in use, extended here |
|
||||
|
||||
### Ranked Approaches
|
||||
1. **proptest-state-machine** — perfect fit for deterministic ticks, generates random operation sequences, automatic shrinking
|
||||
2. Extend cargo-fuzz with new action types
|
||||
3. Simple proptest (stateless properties)
|
||||
4. Shuttle (concurrency permutations)
|
||||
5. Loom (lock-free verification)
|
||||
|
||||
### Key Finding: Feature Gap Analysis
|
||||
While researching testing approaches, also surveyed remaining feature gaps: named actors/registry, actor monitoring/death watch, actor groups/pub-sub, and ask pattern. These became Cycles 12–15.
|
||||
|
||||
## Implementation
|
||||
|
||||
### Property-Based Tests (proptest)
|
||||
Added `proptest` and `proptest-state-machine` to dev-dependencies. New test file: `tests/proptest_runtime.rs` with 7 tests:
|
||||
|
||||
| Test | Property Verified |
|
||||
|------|-------------------|
|
||||
| `fifo_ordering_for_any_message_sequence` | FIFO preserved for 1–100 random messages |
|
||||
| `budget_limits_per_actor_processing` | Budget caps per-tick processing for 2–10 actors |
|
||||
| `one_shot_timer_fires_at_correct_tick` | Timer with delay 1–20 fires at exact right tick |
|
||||
| `interval_timer_fires_at_correct_period` | Period 1–10, verifies 3 consecutive firings |
|
||||
| `bounded_mailbox_never_exceeds_capacity` | Capacity 1–20, 1–200 messages, never exceeds |
|
||||
| `spawn_n_actors_all_tracked` | 1–50 actors, all unique, all in stats |
|
||||
| `swactor_state_machine` | Random Spawn/Send/Tick/Stop/CheckStats sequences |
|
||||
|
||||
### State Machine Test
|
||||
The `swactor_state_machine` test is the most sophisticated:
|
||||
- **Reference model**: `HashMap<id, alive>` tracking expected actor lifecycle
|
||||
- **Operations**: random Spawn, Send, Tick, Stop, CheckStats transitions (up to 40 per test, 128 cases)
|
||||
- **Invariants checked after every transition**: worker count, actor placement, mailbox safety
|
||||
- **Automatic shrinking**: finds minimal failing sequences when invariants break
|
||||
|
||||
### Extended Fuzz Targets
|
||||
Added 4 new `RawAction` variants to `fuzz/fuzz_targets/fuzz_runtime.rs`:
|
||||
- `StopActor` — graceful stop via `runtime.stop_actor`
|
||||
- `SpawnRestartable` — `spawn_restartable` with configurable `max_restarts`
|
||||
- `ScheduleTimer` — one-shot timer via TimerSchedulerActor
|
||||
- `ScheduleInterval` — interval timer via IntervalSchedulerActor
|
||||
|
||||
3 new actor types added to fuzz: `TimerSchedulerActor`, `IntervalSchedulerActor`, `RestartableEchoActor`
|
||||
|
||||
**Key files modified:** `Cargo.toml`, `tests/proptest_runtime.rs` (new), `fuzz/fuzz_targets/fuzz_runtime.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **proptest-state-machine over Loom** — Loom is designed for lock-free concurrent data structures. Swactor's primary correctness properties are sequential (within a tick). The state machine approach tests the actor lifecycle model, which is where bugs are most likely.
|
||||
- **Reference model pattern** — the state machine test maintains a separate `HashMap` as the "expected" state and compares it against the runtime's actual state after each operation. This catches any divergence between the mental model and reality.
|
||||
- **Extending existing fuzz targets** — rather than creating new fuzz targets, extended the existing `fuzz_runtime.rs` with new action variants. This means the fuzzer explores interactions between the new features (timers, restart, stop) and existing operations (spawn, send, tick).
|
||||
|
||||
### Bug Found
|
||||
The state machine test immediately caught an invariant mismatch: `address_map` tracks spawned actors immediately (on spawn), but per-worker `num_actors` lags until the first tick (when the spawn is drained). Fixed the invariant to use `<=` check instead of exact equality.
|
||||
|
||||
## Tests Added
|
||||
|
||||
7 new property tests (88 → 95 total):
|
||||
|
||||
- 6 stateless property tests covering FIFO, budget, timers, mailbox bounds, and spawn tracking
|
||||
- 1 stateful state machine test covering random operation sequences
|
||||
|
||||
## Result
|
||||
|
||||
- 95 tests pass (88 behavioral + 7 proptest)
|
||||
- Fuzz targets compile with new action variants
|
||||
- Bug found: stats lag vs address_map on spawn (invariant relaxed)
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
# Cycle 12: Named Actor Registry with Auto-Cleanup — Development History
|
||||
|
||||
> Commit: `66a8523` · 6 files · 267 insertions, 7 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Actors in swactor were only addressable by opaque `ActorAddress` values returned from spawn. There was no way to look up an actor by name — callers needed to pass addresses around manually. Named registration is one of the most fundamental actor runtime features, enabling service discovery within a runtime.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Key Type | Storage | Scope | Auto-Cleanup |
|
||||
|-----------|----------|---------|-------|-------------|
|
||||
| Erlang | Atom | ETS table | Per-node or global | Yes (on process exit) |
|
||||
| Actix | TypeId | SystemRegistry | Per-Arbiter | Yes (on actor stop) |
|
||||
| Bastion | Path | Hierarchy | Global | Yes (structural) |
|
||||
| Ractor | String | DashMap (global static) | Global | Yes (on actor death) |
|
||||
| xactor | TypeId | Singleton registry | Global | N/A (singletons) |
|
||||
| Akka | ServiceKey[T] | Receptionist | Cluster-wide | Yes (via DeathWatch) |
|
||||
| **Swactor** | **String** | **RwLock\<HashMap\>** | **Per-runtime** | **Yes (on death)** |
|
||||
|
||||
### Key Findings
|
||||
- **TypeId keys** (Actix, xactor) don't fit swactor's type-erased model — multiple actors of the same type can't share a TypeId key
|
||||
- **Global static** (Ractor) breaks multi-runtime scenarios (tests, embedding)
|
||||
- **Erlang's `register/whereis`** is the gold standard: atom keys, per-node scope, automatic cleanup on process exit
|
||||
|
||||
## Implementation
|
||||
|
||||
### NameRegistry
|
||||
- `NameRegistry` in `delivery.rs` with forward + reverse maps:
|
||||
- `names: RwLock<HashMap<String, ActorAddress>>` — name → address lookup
|
||||
- `addrs: RwLock<HashMap<ActorAddress, String>>` — address → name (for O(1) cleanup)
|
||||
- Added to `Runtime` as `Arc<NameRegistry>`, threaded through `TickContext`
|
||||
|
||||
### Runtime API
|
||||
- `spawn_named(name, actor)` — spawn and register atomically
|
||||
- `where_is(name)` — look up address by name
|
||||
- `unregister(name)` — manual unregistration (actor keeps running)
|
||||
- `registered_names()` — list all registered names
|
||||
|
||||
### Context API
|
||||
- `ctx.spawn_named(name, actor)` — register from within a handler
|
||||
- `ctx.where_is(name)` — look up from within a handler
|
||||
|
||||
### Auto-Cleanup
|
||||
- `cleanup_dead` phase calls `name_registry.unregister_by_addr()` for each dead actor
|
||||
- Name is freed immediately — can be reused for a replacement actor
|
||||
|
||||
### TOCTOU Prevention
|
||||
- Name reservation is immediate (before spawn queue push) — prevents race between checking name availability and registering it
|
||||
|
||||
**Key files modified:** `src/delivery.rs`, `src/runtime.rs`, `src/actor.rs`, `src/worker.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **String keys** — most flexible. Atoms (Erlang) aren't idiomatic in Rust. TypeId (Actix) is too restrictive. Strings allow any naming convention.
|
||||
- **Per-runtime scope** — matches swactor's architecture (one runtime per application). Global registries (Ractor) cause problems in tests and embedded scenarios.
|
||||
- **RwLock\<HashMap\>** — matches the existing `AddressMap` and `InboxRegistry` pattern. RwLock allows concurrent reads (lookups) with exclusive writes (registration).
|
||||
- **Collision returns error** — `spawn_named` returns `Err` if the name is already taken. The original binding is preserved. This is explicit and predictable, matching Erlang's behavior.
|
||||
- **Reverse map for O(1) cleanup** — without the reverse map, cleanup would require scanning all entries. The reverse map adds memory proportional to registered actors but makes cleanup constant-time.
|
||||
- **Immediate reservation** — name is reserved before the spawn is queued, preventing TOCTOU races where two `spawn_named` calls for the same name could both succeed.
|
||||
|
||||
## Tests Added
|
||||
|
||||
11 new tests (95 → 106 total):
|
||||
|
||||
- `named_actor_lookup_returns_spawn_address` — spawn_named → where_is roundtrip
|
||||
- `named_actor_receives_messages_via_lookup` — send to looked-up address works
|
||||
- `duplicate_name_returns_error` — collision error, original binding preserved
|
||||
- `where_is_returns_none_for_unknown_name` — nonexistent name → None
|
||||
- `name_auto_unregistered_on_actor_death` — stop_actor → name freed
|
||||
- `name_can_be_reused_after_actor_death` — death → respawn with same name succeeds
|
||||
- `name_auto_unregistered_on_panic` — panic → name freed
|
||||
- `registered_names_lists_all` — all registered names returned
|
||||
- `manual_unregister_frees_name_but_actor_lives` — unregister doesn't kill the actor
|
||||
- `ctx_where_is_resolves_inside_handler` — where_is works from handler context
|
||||
- `ctx_spawn_named_registers_from_handler` — spawn_named works from handler context
|
||||
|
||||
## Result
|
||||
|
||||
- 106 tests pass (99 behavioral + 7 proptest)
|
||||
- All workspace crates compile, zero warnings
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
# Cycle 13: Actor Monitoring with Down Message Notifications — Development History
|
||||
|
||||
> Commit: `8782638` · 6 files · 268 insertions, 10 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Actors had no way to know when other actors died. If actor A depended on actor B, and B panicked or was stopped, A would continue sending messages into the void with no notification. Monitoring (also called "death watch") is essential for building fault-tolerant systems — it's the foundation that supervision trees are built on.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Mechanism | Direction | Notification |
|
||||
|-----------|-----------|-----------|-------------|
|
||||
| Erlang | `monitor/2` | Unidirectional | `DOWN` message |
|
||||
| Akka | `watch` | Unidirectional | `Terminated` message |
|
||||
| Ractor | `link` | Bidirectional | `SupervisionEvent` |
|
||||
| Actix | None built-in | N/A | N/A |
|
||||
| Kameo | `link` | Bidirectional | `on_link_died` callback |
|
||||
| **Swactor** | **`ctx.monitor()`** | **Unidirectional** | **`Down` message** |
|
||||
|
||||
### Key Findings
|
||||
- **Erlang's unidirectional monitor + message delivery** is the best fit for swactor — it reuses the existing type-erased message handler, requires zero trait changes, and is composable
|
||||
- **Callbacks** (Ractor/Kameo style) rejected — would require adding a new method to `AnyActor`/`ActorInterface` traits, forcing all actors to implement it
|
||||
- **Bidirectional links** deferred — can be layered on top of monitors later
|
||||
- **Stacking** (Erlang) — multiple monitors of the same target produce independent notifications
|
||||
|
||||
## Implementation
|
||||
|
||||
### Types (in `actor.rs`)
|
||||
- `MonitorRef(u64)` — unique token from `AtomicU64` counter, used for demonitor
|
||||
- `Down { addr: ActorAddress, reason: StopReason }` — delivered as normal mailbox message
|
||||
- `StopReason` enum: `Normal` (graceful stop) | `Panicked` (panic, not restartable)
|
||||
|
||||
### MonitorRegistry (in `delivery.rs`)
|
||||
- `watchers: RwLock<HashMap<ActorAddress, Vec<(MonitorRef, ActorAddress)>>>` — watched → list of (ref, watcher)
|
||||
- `refs: RwLock<HashMap<MonitorRef, ActorAddress>>` — ref → watched (for O(1) demonitor)
|
||||
|
||||
### API
|
||||
- `ctx.monitor(target) → MonitorRef` — subscribe to death notifications
|
||||
- `ctx.demonitor(mref)` — cancel a subscription
|
||||
|
||||
### Integration with cleanup_dead
|
||||
- `cleanup_dead` now returns `Vec<(ActorAddress, StopReason)>` instead of `Vec<ActorAddress>`
|
||||
- After cleanup: iterate dead actors, take monitors from registry, route `Down` through normal delivery (pool.deliver for same-worker, transfer_txs for cross-worker, inbox_registry for inboxes)
|
||||
- Dead watcher cleanup: `remove_watcher()` strips monitor subscriptions for dead watchers (prevents ghost subscriptions)
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `src/delivery.rs`, `src/runtime.rs`, `src/worker.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Unidirectional monitors (Erlang model)** — simpler than bidirectional links, no cascading death. The watcher is notified but doesn't automatically die. This gives the watcher full control over how to react.
|
||||
- **Down as a regular message** — delivered through the same mailbox as other messages. Actors with `Incoming = Down` receive it via `handle()`. This reuses the entire existing delivery pipeline with zero special-case code.
|
||||
- **MonitorRef for demonitor** — each monitor subscription gets a unique ref. This supports stacking (multiple monitors of the same target) and precise cancellation.
|
||||
- **StopReason distinguishes Normal vs Panicked** — watchers can decide how to react based on whether the death was graceful or a crash. Matches Erlang's `DOWN` message which includes the exit reason.
|
||||
- **Dead watcher cleanup** — if the watcher dies before the watched actor, its monitor subscriptions are cleaned up. Without this, dead watchers would accumulate as ghost entries in the registry.
|
||||
|
||||
## Tests Added
|
||||
|
||||
7 new tests (106 → 113 total):
|
||||
|
||||
- `monitor_notifies_on_graceful_stop` — Down{reason: Normal} on graceful stop
|
||||
- `monitor_notifies_on_panic` — Down{reason: Panicked} on panic
|
||||
- `multiple_watchers_all_notified` — two watchers both receive Down
|
||||
- `demonitor_cancels_notification` — demonitor → no Down delivered
|
||||
- `dead_watcher_does_not_receive_down` — dead watcher's monitors cleaned up
|
||||
- `down_delivered_to_external_inbox` — Down forwarded through inbox
|
||||
- `stacked_monitors_produce_multiple_notifications` — two monitors on same target → two Downs
|
||||
|
||||
## Result
|
||||
|
||||
- 113 tests pass (106 behavioral + 7 proptest)
|
||||
- All workspace crates compile, zero warnings
|
||||
- Foundation for supervision trees (Cycle 17) — monitors provide the death detection mechanism
|
||||
|
|
@ -1,83 +0,0 @@
|
|||
# Cycle 14: Actor Groups with Pub-Sub Broadcast — Development History
|
||||
|
||||
> Commit: `4d18874` · 5 files · 307 insertions, 8 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Named registry (Cycle 12) provides one-to-one name→actor mapping. Many patterns require one-to-many: broadcasting events to subscribers, load distribution across a pool, or topic-based message routing. Actor groups provide this — a named collection of actors that can receive messages as a group.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Mechanism | Key Design | Auto-Cleanup |
|
||||
|-----------|-----------|------------|-------------|
|
||||
| Erlang `pg` | Scopes, join/leave/get_members | Flat groups, atom keys | Yes (on process exit) |
|
||||
| Akka | DistributedPubSub (mediator, topics) | Cluster-wide pub-sub | Yes (via DeathWatch) |
|
||||
| Ractor | `pg` module (join/leave/broadcast) | Erlang-style, global | Yes |
|
||||
| Bastion | Dispatcher | Hierarchy-based routing | Structural |
|
||||
| Redis pub/sub | Channels, patterns | External service | N/A |
|
||||
| **Swactor** | **GroupRegistry** | **Erlang pg-style, per-runtime** | **Yes (on death)** |
|
||||
|
||||
### Common Patterns Across Frameworks
|
||||
- Auto-cleanup on death (universal)
|
||||
- At-most-once delivery (no re-delivery guarantees)
|
||||
- String-based naming (flat, not hierarchical)
|
||||
- Lazy group creation/deletion (groups created on first join, deleted when empty)
|
||||
|
||||
## Implementation
|
||||
|
||||
### GroupRegistry (in `delivery.rs`)
|
||||
- Forward map: `groups: RwLock<HashMap<String, HashSet<ActorAddress>>>` — group → members
|
||||
- Reverse map: `memberships: RwLock<HashMap<ActorAddress, HashSet<String>>>` — actor → groups (for cleanup)
|
||||
- Groups auto-create on first join, auto-delete when empty
|
||||
|
||||
### Runtime API
|
||||
- `join_group(addr, name)` — add actor to group
|
||||
- `leave_group(addr, name)` — remove actor from group
|
||||
- `publish_to(group, msg)` — broadcast to all group members
|
||||
- `group_members(group)` — list members
|
||||
- `groups()` — list all groups
|
||||
|
||||
### Context API (from handler)
|
||||
- `ctx.join_group(name)` — join from inside handler
|
||||
- `ctx.leave_group(name)` — leave from inside handler
|
||||
- `ctx.publish(group, msg)` — broadcast from inside handler
|
||||
- `ctx.group_members(group)` — query from inside handler
|
||||
|
||||
### Message Delivery
|
||||
- `publish` clones message at the typed level (`Message: Clone`), sends to each member via normal routing
|
||||
- Uses the same delivery pipeline as regular messages (pool.deliver, transfer_txs, inbox_registry)
|
||||
|
||||
### Auto-Cleanup
|
||||
- `group_registry.cleanup(&addr)` called in `cleanup_dead` phase
|
||||
- Uses reverse map to find all groups the dead actor belonged to, removes from each
|
||||
|
||||
**Key files modified:** `src/delivery.rs`, `src/runtime.rs`, `src/actor.rs`, `src/worker.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Erlang `pg` model** — flat groups with string keys. Simpler than Akka's mediator/topic model, and sufficient for the common use cases (event broadcasting, worker pools).
|
||||
- **Clone-based broadcast** — message is cloned for each recipient. This is O(N) but straightforward and type-safe. Alternative (shared Arc) would complicate the message pipeline.
|
||||
- **Reverse map for cleanup** — without it, cleaning up a dead actor would require scanning all groups. O(1) per group membership vs O(groups) scan.
|
||||
- **Lazy lifecycle** — groups are created implicitly on first join and deleted when the last member leaves. No explicit create/delete API needed. Matches Erlang `pg`.
|
||||
- **publish requires `Message: Clone`** — enforced at the type level. If a message type isn't Clone, it can't be broadcast. This is a compile-time safety guarantee.
|
||||
|
||||
## Tests Added
|
||||
|
||||
9 new tests (113 → 122 total):
|
||||
|
||||
- `group_members_returns_joined_actors` — join + query returns members
|
||||
- `empty_group_returns_no_members` — nonexistent group → empty set
|
||||
- `publish_broadcasts_to_all_members` — 2 members, both receive the message
|
||||
- `leave_group_stops_receiving_publishes` — leave → excluded from future broadcasts
|
||||
- `dead_actor_auto_removed_from_group` — stop → removed from group
|
||||
- `actor_removed_from_all_groups_on_death` — multi-group membership cleanup
|
||||
- `empty_group_auto_deleted` — last member leaves → group removed from `groups()`
|
||||
- `ctx_join_group_from_handler` — join via on_start
|
||||
- `ctx_publish_broadcasts_from_handler` — publish via handler
|
||||
|
||||
## Result
|
||||
|
||||
- 122 tests pass (115 behavioral + 7 proptest)
|
||||
- All workspace crates compile, zero warnings
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
# Cycle 15: Ask Pattern for Typed Request-Response — Development History
|
||||
|
||||
> Commit: `902471b` · 3 files · 166 insertions, 1 deletion
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Request-response is one of the most common actor communication patterns: "send a question, wait for the answer." Before this change, implementing request-response in swactor required manual inbox creation, message construction with a reply-to address, sending, ticking, and polling — a verbose 5-step process. Every mature actor framework provides a convenience wrapper for this pattern.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Pattern | Mechanism | Synchronous? |
|
||||
|-----------|---------|-----------|-------------|
|
||||
| Erlang | `gen_server:call` | `From` + `gen_server:reply` | Blocks caller (with timeout) |
|
||||
| Akka | `ask` | Temporary actor + `Future` | Returns Future |
|
||||
| Ractor | `call` | `RpcReplyPort` (oneshot channel) | Returns JoinHandle |
|
||||
| Kameo | `ask` | Async + `Reply` trait | Returns Future |
|
||||
| xactor | `Handler::handle` | Return value auto-routed | Implicit |
|
||||
| **Swactor** | **`rt.ask()`** | **Inbox + closure** | **`recv_ticking` (tick-driven)** |
|
||||
|
||||
### Key Findings
|
||||
- Swactor's synchronous tick model requires explicit `reply_to` — there's no async runtime to suspend the caller
|
||||
- **Implicit auto-reply rejected** — would add magic to the message pipeline and complicate the actor interface
|
||||
- **Decision**: convenience wrapper over existing inbox pattern (not a new mechanism)
|
||||
|
||||
## Implementation
|
||||
|
||||
### Ask\<R\> Struct
|
||||
- Wraps an `Inbox<R>` with convenience methods
|
||||
- `try_recv()` — poll without ticking (works in both single and multi-threaded modes)
|
||||
- `recv_ticking(rt, max_ticks)` — tick the runtime until a response arrives or timeout (single-threaded only)
|
||||
- `reply_addr()` — access the inbox address for manual use
|
||||
|
||||
### Runtime::ask()
|
||||
- `rt.ask(addr, |reply_to| Msg { reply_to })` — one-line request-response
|
||||
- Creates inbox, builds message via closure (user provides the reply_to field), sends, returns `Ask<R>`
|
||||
- Purely sugar over the existing `new_inbox → send_to → tick → try_recv` pattern
|
||||
|
||||
### No Internal Changes
|
||||
- Zero changes to `ContextInner` or `ActorInterface`
|
||||
- No implicit auto-reply magic
|
||||
- Actors reply by explicitly sending to the `reply_to` address (same as before)
|
||||
|
||||
**Key files modified:** `src/runtime.rs`, `tests/runtime_api.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Closure-based message construction** — `rt.ask(addr, |reply_to| Msg { reply_to })` lets the user embed the reply address in any message shape. No trait requirements on the message type (beyond `Message`).
|
||||
- **`recv_ticking` for single-threaded** — in single-threaded mode, the runtime must be ticked for the target actor to process the request and reply. `recv_ticking` does this automatically. In multi-threaded mode, use `try_recv` with your own tick loop.
|
||||
- **No implicit reply** — frameworks like xactor auto-route the handler's return value as a reply. This is magical and doesn't fit swactor's explicit model. The ask pattern wraps existing mechanics without adding new ones.
|
||||
- **max_ticks timeout** — instead of wall-clock timeout, uses tick count for deterministic behavior (consistent with Cycle 10 timers).
|
||||
|
||||
## Tests Added
|
||||
|
||||
5 new tests (122 → 127 total):
|
||||
|
||||
- `ask_recv_ticking_returns_response` — basic PingPong ask roundtrip
|
||||
- `ask_multiple_times_tracks_state` — 3 sequential asks to CounterActor, state increments
|
||||
- `ask_timeout_when_no_response` — ask dead actor → timeout error
|
||||
- `ask_try_recv_returns_none_before_tick` — poll before tick → None, after tick → Some
|
||||
- `ask_reply_addr_is_accessible` — reply address is valid for manual use
|
||||
|
||||
## Result
|
||||
|
||||
- 127 tests pass (120 behavioral + 7 proptest)
|
||||
- All workspace crates compile, zero warnings
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
# Cycle 16: Registry Benchmarks for Named Actors, Groups, Monitors, and Ask — Development History
|
||||
|
||||
> Commit: `0ef6df9` · 2 files · 130 insertions, 1 deletion
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Cycles 12–15 added four new features (named registry, monitoring, groups, ask pattern) without performance measurement. Before building more features on top of these primitives, it was important to quantify their overhead and ensure they're efficient enough for production use.
|
||||
|
||||
## Benchmark Results
|
||||
|
||||
| Benchmark | Time | Analysis |
|
||||
|-----------|------|----------|
|
||||
| `named_spawn_lookup` | ~2.4 µs | vs bare spawn 1.9 µs → **+0.5 µs** overhead for name registration |
|
||||
| `where_is_100_names` | ~9.0 µs | Includes setup overhead; per-lookup cost is negligible |
|
||||
| `group_publish/10` | ~4.8 µs | O(N) message cloning |
|
||||
| `group_publish/50` | ~15.5 µs | Linear scaling confirmed |
|
||||
| `group_publish/100` | ~60 µs | Linear with O(N) clones |
|
||||
| `monitor_setup` | ~13.4 µs | monitor + stop + cleanup full cycle |
|
||||
| `ask_roundtrip` | ~4.5 µs | vs manual roundtrip 3.0 µs → **+1.5 µs** for inbox creation |
|
||||
|
||||
### Analysis
|
||||
|
||||
- **Named lookup**: +0.5 µs over bare spawn — the `RwLock<HashMap>` insert is fast. Acceptable for a feature used at spawn time, not on the hot path.
|
||||
- **Group publish**: scales linearly with group size, as expected for O(N) message cloning. No optimization needed — the bottleneck is inherent (must clone and deliver N messages).
|
||||
- **Monitor setup**: 13.4 µs covers the full lifecycle (monitor → stop → cleanup → Down delivery). The monitoring machinery adds minimal per-message overhead.
|
||||
- **Ask roundtrip**: +1.5 µs over manual inbox pattern (4.5 µs vs 3.0 µs). The overhead is inbox creation. Acceptable for a convenience pattern — users who need maximum throughput can use the manual pattern.
|
||||
|
||||
## Implementation
|
||||
|
||||
5 new criterion benchmark functions added to `benches/runtime_benchmarks.rs` in a `registry` group:
|
||||
|
||||
- `named_spawn_lookup` — spawn_named + where_is roundtrip
|
||||
- `where_is_100_names` — lookup in 100-name registry
|
||||
- `group_publish/{10,50,100}` — broadcast to N group members
|
||||
- `monitor_setup` — monitor + stop + Down delivery cycle
|
||||
- `ask_roundtrip` — ask + recv_ticking response
|
||||
|
||||
**Key files modified:** `benches/runtime_benchmarks.rs`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Full-cycle benchmarks** — each benchmark measures the complete operation (not just the fast path). For example, `monitor_setup` includes stop and cleanup, not just the monitor call, because that's the real-world cost.
|
||||
- **Parameterized group publish** — three group sizes (10, 50, 100) to verify linear scaling and catch any unexpected superlinear behavior.
|
||||
- **No optimization undertaken** — all operations are efficient enough. The benchmark results serve as baselines for future changes.
|
||||
|
||||
## Tests Added
|
||||
|
||||
No new tests (benchmarks only). Test count remains at 127.
|
||||
|
||||
## Result
|
||||
|
||||
- All benchmarks run cleanly
|
||||
- 127 tests pass, zero warnings
|
||||
- All registry operations confirmed efficient for production use
|
||||
- Named lookup: <1 µs overhead over bare spawn
|
||||
- Ask: ~50% overhead over manual inbox pattern (acceptable for convenience)
|
||||
- Group publish: linear O(N) as expected
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
# Cycle 17: Supervision Trees with handle_down and Supervisor Actor — Development History
|
||||
|
||||
> Commit: `a70bd86` · 4 files · 754 insertions, 7 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
With monitoring (Cycle 13), lifecycle hooks (Cycle 9), and factory-based restart (Cycle 7) in place, swactor had all the building blocks for supervision trees — the signature feature of Erlang/OTP. Supervision trees provide structured fault tolerance: a parent actor (supervisor) monitors children and restarts them according to configurable policies when they fail.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Supervisor Model | Strategies | Child Spec | Meltdown Protection |
|
||||
|-----------|-----------------|------------|------------|---------------------|
|
||||
| Erlang/OTP | Built-in `supervisor` behaviour | one_for_one, one_for_all, rest_for_one, simple_one_for_one | `{Id, MFA, Restart, Shutdown, Type}` | Intensity/period limits |
|
||||
| Akka | SupervisorStrategy | Resume, Restart, Stop, Escalate + BackoffSupervisor | N/A (inline) | MaxNrOfRetries/withinTimeRange |
|
||||
| Ractor | `ractor-supervisor` crate | External crate, event-based | SupervisionEvent callback | N/A |
|
||||
| Bastion | Built-in hierarchy | Redundancy groups | Structural (parent-child) | N/A |
|
||||
| CAF | No built-in supervisor | Monitor-based (manual) | N/A | N/A |
|
||||
| **Swactor** | **User-space `Supervisor` actor** | **OneForOne** (Cycle 17), **OneForAll/RestForOne** (Cycle 18) | **`ChildSpec`** | **max_restarts budget** |
|
||||
|
||||
### Key Findings
|
||||
- Swactor has all the building blocks: monitor (Cycle 13), `spawn_restartable` (Cycle 7), lifecycle hooks (Cycle 9), `Down` messages (Cycle 13)
|
||||
- **Decision**: Supervisor as a user-space actor built on existing primitives (like Ractor's `ractor-supervisor` crate), not a special runtime construct
|
||||
- **`handle_down` callback** enables any actor to react to monitored deaths without requiring `Incoming = Down` — this is the key API gap that needed filling
|
||||
|
||||
## Implementation
|
||||
|
||||
### 1. `handle_down` Callback on ActorInterface
|
||||
|
||||
The core API addition enabling supervision:
|
||||
|
||||
- `fn handle_down(&mut self, ctx: &Ctx, down: Down)` — default no-op, called when a monitored actor dies and the actor's `Incoming` type is NOT `Down`
|
||||
- Implemented via second downcast attempt in `handle_any`: if the message is `Down` and the actor's `Incoming` type doesn't match, call `handle_down` instead of `handle`
|
||||
- Fully backward-compatible: actors with `Incoming = Down` still receive via `handle()` as before
|
||||
- This decouples supervision logic from the actor's primary message type
|
||||
|
||||
### 2. `ctx.stop_actor(addr)` — Stop Another Actor
|
||||
|
||||
- Sends graceful stop to another actor from handler context
|
||||
- Uses `StopSignal` through normal message routing (PoisonPill semantics)
|
||||
- Enables supervisor-controlled shutdown of children
|
||||
|
||||
### 3. `Supervisor` Actor
|
||||
|
||||
A user-space actor managing child actors:
|
||||
|
||||
- **`SupervisorStrategy::OneForOne`** — only the failed child is restarted (Cycle 17)
|
||||
- **`RestartPolicy`**: `Permanent` (always restart), `Transient` (restart only on panic, not normal stop), `Temporary` (never restart)
|
||||
- **`ChildSpec`** — `{ id: String, restart: RestartPolicy, factory: Fn(&Ctx) -> Result<ActorAddress> }`
|
||||
- Children spawned in `on_start`, monitored via `ctx.monitor()`
|
||||
- Death detected via `handle_down`, restart policy consulted, factory invoked for replacement
|
||||
- **Meltdown detection**: stops itself when `total_restarts > max_restarts`
|
||||
- **Cascading shutdown**: `on_stop` sends stop signals to all living children
|
||||
|
||||
### ActiveChild Struct
|
||||
- Tracks `addr: ActorAddress` and `monitor_ref: MonitorRef` per child
|
||||
- Reused by Router (Cycle 19)
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **User-space actor (not runtime primitive)** — the Supervisor is just an actor that uses existing APIs (monitor, spawn, stop). No special runtime support needed. This validates the composability of the monitoring and lifecycle systems.
|
||||
- **`handle_down` as opt-in callback** — adding `handle_down` to `ActorInterface` with a default no-op means existing actors don't need to change. Actors that want to react to deaths override it. The alternative (requiring `Incoming = Down`) would force actors to handle `Down` as their primary message type.
|
||||
- **Factory takes `&Ctx`** — the factory closure receives the context so it can use `ctx.spawn`, `ctx.monitor`, etc. during child creation. This enables the supervisor to monitor new children immediately.
|
||||
- **Meltdown protection** — if children keep crashing faster than they can be restarted, the supervisor stops itself rather than looping forever. Matches Erlang's intensity/period limits.
|
||||
- **Cascading shutdown** — when the supervisor stops, all living children receive stop signals. This prevents orphaned actors.
|
||||
|
||||
## Tests Added
|
||||
|
||||
10 new tests (127 → 138 total, counting 130 behavioral + 7 proptest + 1 doctest):
|
||||
|
||||
- `handle_down_receives_death_notification` — handle_down callback fires on monitored death
|
||||
- `handle_down_skipped_when_incoming_is_down` — backward compat: Incoming=Down uses handle()
|
||||
- `ctx_stop_actor_stops_target` — one actor stops another via ctx.stop_actor()
|
||||
- `supervisor_restarts_permanent_child_on_panic` — panic → restart (OneForOne + Permanent)
|
||||
- `supervisor_does_not_restart_transient_child_on_normal_stop` — Normal stop → no restart
|
||||
- `supervisor_restarts_transient_child_on_panic` — Panicked → restart (Transient)
|
||||
- `supervisor_never_restarts_temporary_child` — Temporary → never restart
|
||||
- `supervisor_meltdown_after_max_restarts` — exceeding max_restarts stops supervisor
|
||||
- `supervisor_one_for_one_only_restarts_failed_child` — multi-child, only crashed child restarted
|
||||
- `supervisor_on_stop_kills_children` — supervisor shutdown cascades to children
|
||||
|
||||
## Result
|
||||
|
||||
- 138 tests pass (130 behavioral + 7 proptest + 1 doctest)
|
||||
- Zero warnings, full workspace compiles
|
||||
- Supervisor validates the composability of Cycles 7 (recovery), 9 (lifecycle), and 13 (monitoring)
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
# Cycle 18: OneForAll and RestForOne Supervisor Strategies — Development History
|
||||
|
||||
> Commit: `771c38c` · 4 files · 277 insertions, 2 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Cycle 17 introduced supervision with the `OneForOne` strategy (only the failed child is restarted). Erlang/OTP defines two additional coordinated restart strategies that handle interdependent children:
|
||||
|
||||
- **`one_for_all`** — when one child fails, ALL children are restarted (for tightly coupled children that share state assumptions)
|
||||
- **`rest_for_one`** — when one child fails, it and all children started AFTER it are restarted (for chains where later children depend on earlier ones)
|
||||
|
||||
These strategies require coordinated shutdown: the supervisor must stop living siblings, wait for all of them to die, then restart the affected set in the original spec order.
|
||||
|
||||
### Research Detour: SmallBox/InlineAny Optimization
|
||||
Before choosing this cycle's topic, investigated SmallBox optimization for message dispatch — a 44% queue throughput improvement was measured. However, it was deferred because:
|
||||
- Requires `unsafe` code in a core path
|
||||
- Would touch 32+ call sites across the codebase
|
||||
- Violates the "src/ structure frozen" constraint
|
||||
|
||||
Extended the Supervisor with coordinated strategies instead — higher value, zero risk.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | OneForAll | RestForOne | Coordinated Shutdown |
|
||||
|-----------|-----------|------------|---------------------|
|
||||
| Erlang/OTP | Yes | Yes | Built into supervisor behaviour |
|
||||
| Akka | No (different model: Resume/Restart/Stop/Escalate) | No | N/A |
|
||||
| Ractor | No | No | N/A |
|
||||
| Bastion | Implicit (redundancy groups) | No | Implicit |
|
||||
| **Swactor** | **Yes** | **Yes** | **Phase-based state machine** |
|
||||
|
||||
### Erlang's Coordinated Restart
|
||||
In Erlang, `one_for_all` and `rest_for_one` stop affected children in reverse start order, wait for all to terminate, then restart in start order. This guarantees initialization dependencies are respected.
|
||||
|
||||
## Implementation
|
||||
|
||||
### SupervisorPhase State Machine
|
||||
- `Normal` — steady state, processing handle_down events normally
|
||||
- `Stopping { awaiting: HashSet<ActorAddress>, restart_set: Vec<usize> }` — coordinated shutdown in progress
|
||||
|
||||
### SupervisorStrategy Extensions
|
||||
- `SupervisorStrategy::OneForAll` — all children restarted when one fails
|
||||
- `SupervisorStrategy::RestForOne` — failed child + all children after it (in spec order) restarted
|
||||
|
||||
### Coordinated Restart Flow
|
||||
1. Child dies → `handle_down` called
|
||||
2. Strategy determines affected indices (OneForAll: all, RestForOne: failed + later)
|
||||
3. `begin_coordinated_restart(ctx, indices)`:
|
||||
- Sends stop signals to living siblings in the restart set
|
||||
- Transitions to `Stopping` phase with `awaiting` set
|
||||
- Already-dead children handled: if all targets are already dead, skip to immediate restart
|
||||
4. Subsequent `handle_down` calls during `Stopping` phase:
|
||||
- Remove from `awaiting` set
|
||||
- When `awaiting` is empty → all stopped
|
||||
5. `finish_restart(ctx)`:
|
||||
- Restart all children in the restart set, in spec order
|
||||
- Transition back to `Normal` phase
|
||||
|
||||
### Refactoring
|
||||
- `check_intensity()` factored out of `handle_down` for restart budget checking — shared by all strategies
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Phase-based state machine** — the `Stopping` phase cleanly separates "waiting for siblings to die" from "normal operation." This prevents races where a new death arrives while a coordinated restart is in progress.
|
||||
- **Stop signals (not kill)** — affected siblings are stopped gracefully (PoisonPill semantics), giving them a chance to run `on_stop` for cleanup. This matches Erlang's `terminate/2` being called during supervised shutdown.
|
||||
- **Restart in spec order** — children are restarted in the order they appear in the ChildSpec list, regardless of which child triggered the restart. This preserves initialization dependencies.
|
||||
- **Already-dead optimization** — if all children in the restart set are already dead (e.g., cascading failures), skip the `Stopping` phase entirely and restart immediately. Without this, the supervisor would wait forever for Down messages that already arrived.
|
||||
- **Meltdown protection shared** — the same `max_restarts` budget applies across all strategies. OneForAll restarts count as one restart event (not N), matching Erlang's behavior.
|
||||
|
||||
## Tests Added
|
||||
|
||||
3 new tests (138 → 141 total):
|
||||
|
||||
- `supervisor_one_for_all_restarts_all_on_single_failure` — one child panics, all 3 get new addresses
|
||||
- `supervisor_rest_for_one_restarts_rest_after_failed` — child_b panics, child_a unchanged, child_b + child_c restarted
|
||||
- `supervisor_one_for_all_waits_for_all_downs_before_restart` — verifies coordinated shutdown completes before restart begins
|
||||
|
||||
## Result
|
||||
|
||||
- 141 tests pass (133 behavioral + 7 proptest + 1 doctest)
|
||||
- Zero warnings, full workspace compiles
|
||||
- All three Erlang-standard supervision strategies now available: OneForOne, OneForAll, RestForOne
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
# Cycle 19: Router Actor for Pooled Message Distribution — Development History
|
||||
|
||||
> Commit: `c688f0a` · 4 files · 528 insertions, 3 deletions
|
||||
|
||||
---
|
||||
|
||||
## Motivation
|
||||
|
||||
Many workloads benefit from distributing messages across a pool of identical worker actors. Before this change, users had to manually manage actor pools: spawn N workers, track their addresses, implement distribution logic, and handle worker replacement on failure. A Router actor encapsulates this pattern — it receives messages and transparently forwards them to pool members using a configurable strategy.
|
||||
|
||||
## Competitor Analysis
|
||||
|
||||
| Framework | Pool/Router Model | Strategies | Auto-Replace |
|
||||
|-----------|------------------|------------|-------------|
|
||||
| Erlang | `poolboy` (checkout/checkin), `wpool` (transparent forwarding, 6 strategies + custom) | RoundRobin, Random, BestWorker, Hash, Available, custom | Manual |
|
||||
| Akka | Router actors (Pool vs Group), Resizer for dynamic sizing | RoundRobin, Random, SmallestMailbox, Balancing, Broadcast, ScatterGather, TailChopping, ConsistentHashing | Pool auto-creates, Group manual |
|
||||
| Actix | SyncArbiter (shared queue, implicit work-stealing) | N/A (shared queue) | N/A |
|
||||
| Kameo | ActorPool (least-connections, auto-replace dead workers) | Least-connections | Yes |
|
||||
| Ractor | No built-in router (process groups only) | N/A | N/A |
|
||||
| **Swactor** | **`Router<M>` actor** | **RoundRobin, Random, Broadcast** | **Yes (via monitor + handle_down)** |
|
||||
|
||||
### Key Findings
|
||||
- **Router-as-actor** with transparent forwarding (wpool/Akka style) is the best fit — the router looks like a regular actor to callers
|
||||
- **User-space actor** like Supervisor (Cycle 17), reusing monitor + handle_down for worker replacement
|
||||
- **SmallestMailbox deferred** — requires runtime stats access not available in user-space
|
||||
- **ConsistentHashing deferred** — requires a hash function parameter, can be added later as a builder method
|
||||
|
||||
## Implementation
|
||||
|
||||
### Router\<M\> Actor
|
||||
- Generic over `M: Message` — same `Incoming` type as workers, enabling transparent forwarding
|
||||
- Workers spawned in `on_start`, monitored via `ctx.monitor()`, auto-replaced via `handle_down`
|
||||
- Reuses `ActiveChild` struct from Supervisor (addr + monitor_ref)
|
||||
|
||||
### Routing Strategies
|
||||
- `RoutingStrategy::RoundRobin` — sequential circular distribution via counter
|
||||
- `RoutingStrategy::Random` — random worker selection via `get_random()` helper
|
||||
- `RoutingStrategy::Broadcast` — clone message to all live workers (`M: Clone` required)
|
||||
|
||||
### Fault Tolerance
|
||||
- Dead worker detected via `handle_down` → factory invoked → new worker spawned and monitored
|
||||
- **Meltdown protection**: `total_restarts > max_restarts` → `ctx.stop_self()`
|
||||
- **Cascading shutdown**: `on_stop` sends stop signals to all workers
|
||||
|
||||
### Configuration
|
||||
- `Router::new(pool_size, strategy, factory, max_restarts)` — all-in-one constructor
|
||||
- Factory: `Arc<dyn Fn(&Ctx) -> Result<ActorAddress, Error> + Send + Sync>`
|
||||
|
||||
**Key files modified:** `src/actor.rs`, `tests/runtime_api.rs`, `docs/runtime.md`
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Router-as-actor (transparent forwarding)** — callers send messages to the router's address as if it were a regular actor. The router forwards to pool members. This is the cleanest API: no special send function, no pool handle, just an address.
|
||||
- **User-space actor (not runtime primitive)** — like Supervisor, Router is built entirely on existing APIs (spawn, monitor, handle_down, stop). This validates the actor system's composability.
|
||||
- **Generic over M** — `Router<M>` has `Incoming = M`, same as the workers. Messages are forwarded with zero transformation. Type safety is enforced at compile time.
|
||||
- **Broadcast requires Clone** — broadcasting clones the message for each worker. The Clone bound is only required when using the Broadcast strategy, enforced at the type level.
|
||||
- **SmallestMailbox deferred** — would require reading per-actor mailbox depth from runtime stats, which isn't available from within a handler. Could be added with a stats query API.
|
||||
- **ConsistentHashing deferred** — requires a hash function parameter (user must define which part of the message determines the routing key). Better to add as a builder method with a closure parameter.
|
||||
- **Reuses ActiveChild from Supervisor** — the pattern of "track address + monitor ref, replace on death" is identical. Code sharing confirms the design consistency between Supervisor and Router.
|
||||
|
||||
## Tests Added
|
||||
|
||||
7 new tests (141 → 148 total):
|
||||
|
||||
- `router_round_robin_distributes_across_workers` — 6 msgs to 3 workers, each gets 2
|
||||
- `router_broadcast_sends_to_all_workers` — 1 msg, all 3 workers receive
|
||||
- `router_random_delivers_to_some_worker` — 30 msgs across 3 workers, at least 2 workers used
|
||||
- `router_replaces_dead_worker` — panicked worker auto-replaced, pool size maintained
|
||||
- `router_meltdown_after_max_restarts` — 3 deaths with max_restarts=2 → router stops
|
||||
- `router_on_stop_kills_workers` — stopping router cascades to all workers
|
||||
- `router_broadcast_multiple_messages_all_received` — 5 msgs × 3 workers = 15 received
|
||||
|
||||
## Result
|
||||
|
||||
- 148 tests pass (140 behavioral + 7 proptest + 1 doctest)
|
||||
- Zero warnings, full workspace compiles
|
||||
- Router validates the composability of the entire cfuzz feature set: monitoring (Cycle 13), lifecycle hooks (Cycle 9), handle_down (Cycle 17), and the ActiveChild pattern (Cycle 17)
|
||||
- The cfuzz branch concludes with a comprehensive actor runtime featuring: fairness, backpressure, recovery, lifecycle management, timers, named registry, monitoring, groups, ask pattern, supervision trees, and routers
|
||||
|
|
@ -1,140 +0,0 @@
|
|||
# CI Pipeline Deployment — Development History
|
||||
|
||||
> Covers the first real deployment of the CI pipeline: Forgejo (VPS) → ci-relay
|
||||
> (iroh) → local-runner (Thinkpad). Verified end-to-end with a smoke-test
|
||||
> pipeline that reports status back to Forgejo.
|
||||
>
|
||||
> *Branch: `spot-instance`*
|
||||
|
||||
---
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Deployed Components
|
||||
|
||||
| Component | Machine | How |
|
||||
|-----------|---------|-----|
|
||||
| `.ci.yml` | Repo root | Smoke pipeline: `echo "CI is alive"` on push to `*` |
|
||||
| `ci-relay` | VPS | Release binary, systemd service |
|
||||
| `local-runner` | Runner host | Release binary, started via nohup |
|
||||
| Forgejo webhook | VPS (Docker) | Hook #1, fires on push to relay's HTTP listener |
|
||||
|
||||
### Deployment Steps
|
||||
|
||||
1. **Created `.ci.yml`** — minimal smoke pipeline (`echo "CI is alive"`)
|
||||
2. **Generated webhook secret** — `openssl rand -hex 32` → `~/.ssh/forgejo.ci-webhook-secret`
|
||||
3. **Built release binaries** — `cargo build --release -p ci-relay -p local-runner`
|
||||
4. **Distributed binaries** — `scp` to VPS (`docean:`) and Thinkpad (`thinkpad:`)
|
||||
5. **Deployed ci-relay as systemd service** on VPS:
|
||||
- Service file: `/etc/systemd/system/ci-relay.service`
|
||||
- Iroh Node ID: `<IROH_NODE_ID>`
|
||||
6. **Started local-runner on Thinkpad** — connects to relay via iroh, confirmed "Connected to relay!"
|
||||
7. **Configured Forgejo**:
|
||||
- Added `[webhook] ALLOWED_HOST_LIST = loopback,<DOCKER_BRIDGE_IP>` to `app.ini` (Forgejo blocks private IPs by default)
|
||||
- Restarted Forgejo container
|
||||
- Created webhook via API targeting `http://<DOCKER_BRIDGE_IP>:8787`
|
||||
- **Fixed UFW firewall** — Docker bridge traffic to port 8787 was blocked by default DROP policy; added a UFW rule allowing the Docker subnet
|
||||
8. **Verified end-to-end** — pushed commit, Forgejo shows green check:
|
||||
- `ci/hello`: success — "Job 'hello' completed"
|
||||
- `ci/smoke`: success — "Pipeline 'smoke' success"
|
||||
|
||||
### Issue Encountered: UFW Blocking Docker Bridge
|
||||
|
||||
The plan assumed Docker bridge traffic (`172.17.0.1`) would reach the host's port 8787 unimpeded. UFW's default INPUT policy is DROP, which blocks this. The fix was a single firewall rule allowing the Docker subnet.
|
||||
|
||||
### Credentials & Secrets
|
||||
|
||||
| File | Purpose | Location |
|
||||
|------|---------|----------|
|
||||
| Forgejo API token | CI status reporting | Spot instance + Thinkpad |
|
||||
| HMAC webhook secret | Webhook signature verification | Spot instance + Thinkpad |
|
||||
|
||||
Secrets are stored outside the repo. The webhook secret is embedded in the systemd service `ExecStart` line on the VPS. To rotate it: update the service file, restart ci-relay, update Forgejo webhook config.
|
||||
|
||||
### Connection Details
|
||||
|
||||
- **ci-relay** listens on HTTP (webhooks) + iroh (runner connection)
|
||||
- **local-runner** connects outbound to relay's iroh Node ID (NAT-friendly)
|
||||
- **Status reports** go directly from runner → Forgejo API over HTTPS (no relay)
|
||||
|
||||
---
|
||||
|
||||
## Next Step: Real CI Jobs
|
||||
|
||||
The smoke-test pipeline proves the plumbing works. The next step is replacing `echo "CI is alive"` with actual CI jobs in `.ci.yml`.
|
||||
|
||||
Candidates for the first real pipeline:
|
||||
|
||||
1. **`cargo check`** — fast compilation check, catches most errors
|
||||
2. **`cargo test`** — full test suite (simulation tests can be slow)
|
||||
3. **`cargo clippy`** — lint pass
|
||||
4. **Benchmark runs** — the whole reason for running CI on the Thinkpad (consistent hardware)
|
||||
|
||||
Things to consider:
|
||||
|
||||
- **Rust toolchain on Thinkpad**: `local-runner` shells out to run jobs, so the Thinkpad needs `rustup`/`cargo` installed and on PATH
|
||||
- **Build cache**: consecutive runs in separate `pipeline-N` dirs won't share a target directory. Consider a shared `CARGO_TARGET_DIR` or `sccache` for faster builds
|
||||
- **Job timeouts**: no timeout mechanism exists yet; a hung `cargo build` would block the single-threaded job queue forever
|
||||
- **Multiple jobs**: `.ci.yml` supports multiple jobs per pipeline, but they run sequentially. Could add `cargo check` as a fast gate before `cargo test`
|
||||
- **Branch filtering**: currently triggers on `*` — may want to restrict benchmarks to `master` only
|
||||
|
||||
### Suggested `.ci.yml` Evolution
|
||||
|
||||
```yaml
|
||||
pipelines:
|
||||
check:
|
||||
triggers:
|
||||
- event: push
|
||||
branches: ["*"]
|
||||
jobs:
|
||||
check:
|
||||
run: cargo check --workspace
|
||||
test:
|
||||
run: cargo test --workspace
|
||||
clippy:
|
||||
run: cargo clippy --workspace -- -D warnings
|
||||
|
||||
bench:
|
||||
triggers:
|
||||
- event: push
|
||||
branches: ["master"]
|
||||
jobs:
|
||||
bench:
|
||||
run: cargo bench --workspace
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operational Notes
|
||||
|
||||
### Restarting ci-relay (VPS)
|
||||
|
||||
```bash
|
||||
ssh <VPS_HOST>
|
||||
systemctl restart ci-relay
|
||||
journalctl -u ci-relay -f
|
||||
```
|
||||
|
||||
### Restarting local-runner (runner host)
|
||||
|
||||
```bash
|
||||
ssh <RUNNER_HOST>
|
||||
pkill local-runner
|
||||
nohup ~/local-runner \
|
||||
--relay-node-id <IROH_NODE_ID> \
|
||||
--forgejo-url https://zachery.lol/code \
|
||||
--forgejo-token "$(cat <TOKEN_FILE>)" \
|
||||
--yaml ~/.ci.yml \
|
||||
--work-dir ~/ci-work \
|
||||
--repo-url https://zachery.lol/code/zacheryasc/swactor.git \
|
||||
> ~/local-runner.log 2>&1 &
|
||||
```
|
||||
|
||||
### Checking webhook deliveries
|
||||
|
||||
```bash
|
||||
# Forgejo webhook UI: Settings → Webhooks → Hook #1 → Recent Deliveries
|
||||
# Or test delivery via API:
|
||||
curl -X POST "https://zachery.lol/code/api/v1/repos/zacheryasc/swactor/hooks/1/tests" \
|
||||
-H "Authorization: token <YOUR_TOKEN>"
|
||||
```
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
# CI Output Visible in Forgejo — Development History
|
||||
|
||||
> Added two mechanisms so CI results are visible directly in the Forgejo web
|
||||
> UI without SSH-ing into the runner: **enhanced commit status descriptions**
|
||||
> and **PR comments** with full job output.
|
||||
>
|
||||
> *Branch: `spot-instance`*
|
||||
|
||||
---
|
||||
|
||||
## Problem
|
||||
|
||||
The CI pipeline worked end-to-end but job output was only visible in the
|
||||
runner's stderr log on the Thinkpad. To see why clippy failed, you had to
|
||||
`ssh thinkpad 'tail ~/local-runner.log'`. Forgejo's commit status descriptions
|
||||
just said "Job 'clippy' completed" with no output.
|
||||
|
||||
Forgejo lacks GitHub's Checks API (no annotations, no log viewer), so we use
|
||||
two complementary approaches.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### 1. Enhanced Commit Status Descriptions
|
||||
|
||||
On job completion, the status description now includes:
|
||||
|
||||
- **On success**: `"Job 'check' passed"`
|
||||
- **On failure**: `"Job 'clippy' failed: command exited with code 101\n[stderr] error: you should consider..."` — last ~10 lines of output, capped at 250 characters.
|
||||
|
||||
This is visible directly on the PR page and commit page in Forgejo without
|
||||
clicking anything.
|
||||
|
||||
### 2. PR Comments with Full Output
|
||||
|
||||
When a pipeline reaches terminal state, the StatusReporter:
|
||||
|
||||
1. Queries `GET /repos/{owner}/{repo}/pulls?state=open` to find the PR for the branch
|
||||
2. Builds a markdown comment with `<details>` sections per job (up to 100 lines each)
|
||||
3. Posts it via `POST /repos/{owner}/{repo}/issues/{pr_number}/comments`
|
||||
4. Re-posts the pipeline commit status with `target_url` pointing to the comment
|
||||
|
||||
Example comment format:
|
||||
|
||||
```markdown
|
||||
## Pipeline `ci` — failure
|
||||
|
||||
Commit: `5b7ae7b`
|
||||
|
||||
<details>
|
||||
<summary>clippy — failed: command exited with code 101</summary>
|
||||
|
||||
_Showing last 100 of 523 lines_
|
||||
|
||||
\```
|
||||
error[E0599]: ...
|
||||
\```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>check — passed</summary>
|
||||
|
||||
\```
|
||||
$ cargo check --workspace
|
||||
Compiling ...
|
||||
\```
|
||||
|
||||
</details>
|
||||
```
|
||||
|
||||
### 3. `target_url` on Commit Statuses
|
||||
|
||||
Added `target_url: Option<String>` to `StatusUpdate`. When a PR comment is
|
||||
successfully posted, the pipeline's commit status badge links directly to that
|
||||
comment. Clicking the status badge on the PR page jumps to the output.
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `crates/ci/src/lib.rs` | Added `target_url: Option<String>` to `StatusUpdate` |
|
||||
| `crates/ci/src/status_reporter.rs` | Added `JobOutput`, `PostPipelineComment`, `find_pr_for_branch()`, `post_pr_comment()`, `build_pipeline_comment()`, `handle_pipeline_comment()` |
|
||||
| `crates/ci/src/local_coordinator.rs` | Enhanced `handle_job_complete()` descriptions; added `emit_pipeline_comment()`, called from `try_schedule_next()` |
|
||||
| `crates/ci/src/coordinator.rs` | Mechanical `target_url: None` at 4 sites |
|
||||
| `crates/simulation/src/ci/local_sim.rs` | Mechanical `target_url: None` at 3 sites |
|
||||
| `crates/simulation/src/ci/sim.rs` | Mechanical `target_url: None` at 2 sites |
|
||||
| `crates/ci/Cargo.toml` | Added `features = ["json"]` to `ureq` for `into_json()` |
|
||||
|
||||
## Deployment & Verification
|
||||
|
||||
Built and deployed updated `local-runner` to the Thinkpad, pushed to the
|
||||
`spot-instance` branch (which has PR #42 open), and observed:
|
||||
|
||||
**Working:**
|
||||
|
||||
- Commit statuses show descriptive output. The clippy failure status reads:
|
||||
`Job 'clippy' failed: command exited with code 101` followed by the tail of
|
||||
the clippy output, truncated at 250 chars.
|
||||
- Passed jobs show `"Job 'check' passed"` / `"Job 'test' passed"`.
|
||||
- Pipeline-level status correctly reports `ci/ci → failure`.
|
||||
|
||||
**Blocked on token scope:**
|
||||
|
||||
- PR comment posting returned HTTP 403. The Forgejo API token has
|
||||
`write:repository` scope (sufficient for commit statuses) but needs
|
||||
`write:issue` scope to post comments on PRs/issues.
|
||||
- The code degrades gracefully: logs the error, skips the comment, posts the
|
||||
pipeline status without `target_url`.
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] Regenerate Forgejo API token with `write:issue` scope to enable PR comments
|
||||
- [ ] After token update, re-deploy and verify the comment + `target_url` flow end-to-end
|
||||
|
||||
## Edge Cases Handled
|
||||
|
||||
| Case | Behavior |
|
||||
|------|----------|
|
||||
| No open PR for branch | Comment silently skipped, status posted without `target_url` |
|
||||
| API failures (403, network) | Logged via `eprintln!`, degrades gracefully |
|
||||
| Long output | Capped at last 100 lines per job in PR comment, with `_Showing last N of M lines_` note |
|
||||
| Long description | Capped at 250 chars for commit status description field |
|
||||
| All HTTP code | Gated behind `#[cfg(feature = "local")]` — simulation builds unaffected |
|
||||
|
||||
## Architecture Note
|
||||
|
||||
All new HTTP calls (PR listing, comment posting) happen in the StatusReporter
|
||||
actor, which is fire-and-forget. The LocalCoordinator never blocks on HTTP.
|
||||
The flow is:
|
||||
|
||||
```
|
||||
LocalCoordinator StatusReporter
|
||||
| |
|
||||
|-- emit_status(StatusUpdate) ----->|-- POST /statuses/{sha}
|
||||
| |
|
||||
|-- PostPipelineComment ----------->|-- GET /pulls?state=open
|
||||
| |-- POST /issues/{n}/comments
|
||||
| |-- POST /statuses/{sha} (with target_url)
|
||||
```
|
||||
|
|
@ -1,520 +0,0 @@
|
|||
# CI Webhook Relay via Iroh — Development History
|
||||
|
||||
> Covers the implementation of `ci-relay` and the iroh webhook receiver in
|
||||
> `local-runner`, enabling Forgejo webhooks to reach a NAT'd CI runner via
|
||||
> iroh's QUIC transport with automatic NAT traversal.
|
||||
>
|
||||
> ~3 files created · ~2 files modified · ~350 insertions
|
||||
>
|
||||
> *Branch: `spot-instance`*
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Problem & Motivation](#1-problem--motivation)
|
||||
2. [Architecture](#2-architecture)
|
||||
3. [What Was Built](#3-what-was-built)
|
||||
4. [ci-relay Binary](#4-ci-relay-binary)
|
||||
5. [local-runner Iroh Receiver](#5-local-runner-iroh-receiver)
|
||||
6. [Wire Protocol](#6-wire-protocol)
|
||||
7. [Connection Flow](#7-connection-flow)
|
||||
8. [Design Decisions & Tradeoffs](#8-design-decisions--tradeoffs)
|
||||
9. [Manual Testing Guide](#9-manual-testing-guide)
|
||||
10. [Known Gaps & Future Improvements](#10-known-gaps--future-improvements)
|
||||
|
||||
---
|
||||
|
||||
## 1. Problem & Motivation
|
||||
|
||||
The CI runner (`local-runner`) was designed for same-LAN usage: Forgejo sends
|
||||
webhooks over HTTP to the runner's listen port. In the real deployment:
|
||||
|
||||
- **Forgejo** runs on a VPS (`zachery.lol` / `139.59.195.69`)
|
||||
- **CI runner** runs on a Thinkpad at home (`192.168.1.102`), behind NAT
|
||||
|
||||
The VPS cannot reach the Thinkpad directly — no inbound port is open, no
|
||||
static IP, no UPnP. Traditional solutions (SSH reverse tunnel, VPN, port
|
||||
forwarding on router) all require ongoing configuration and are fragile.
|
||||
|
||||
iroh is already integrated in swactor's distribution layer (`iroh_driver.rs`)
|
||||
for SWIM protocol traffic. It provides QUIC connections with automatic NAT
|
||||
traversal via relay servers — exactly what's needed to bridge the webhook gap.
|
||||
|
||||
### Why Not Just SSH Tunnel?
|
||||
|
||||
An SSH tunnel (`ssh -R 8787:localhost:8787 zachery.lol`) would work, but:
|
||||
|
||||
- Tunnels drop on network changes (laptop suspend, WiFi roaming)
|
||||
- Requires autossh or systemd to keep alive
|
||||
- Another moving part to debug when CI stops working
|
||||
- Doesn't reuse any existing infrastructure
|
||||
|
||||
iroh handles reconnection, relay fallback, and NAT traversal automatically.
|
||||
The implementation reuses the same tagged-message-over-QUIC-stream pattern
|
||||
already proven in `iroh_driver.rs`.
|
||||
|
||||
---
|
||||
|
||||
## 2. Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────┐ ┌──────────────────────────────────┐
|
||||
│ VPS (zachery.lol) │ │ Thinkpad (192.168.1.102) │
|
||||
│ │ iroh │ │
|
||||
│ Forgejo ──webhook──► Relay ├───────►│ local-runner │
|
||||
│ :8787 │ QUIC │ (coordinator, runner, reporter) │
|
||||
│ │ │ │
|
||||
└─────────────────────────────┘ └──────────────────────────────────┘
|
||||
```
|
||||
|
||||
**VPS side** — `ci-relay` binary:
|
||||
- HTTP listener receives webhook POSTs from Forgejo (localhost only)
|
||||
- iroh endpoint accepts the runner's inbound connection
|
||||
- Forwards parsed `WebhookEvent` payloads over iroh uni streams
|
||||
|
||||
**Thinkpad side** — `local-runner` with `--relay-node-id`:
|
||||
- Connects to the VPS relay's iroh endpoint on startup
|
||||
- Receives `WebhookEvent` over iroh uni streams
|
||||
- Feeds events into `LocalCoordinator` via existing `Webhook` message
|
||||
- Status updates go directly Thinkpad → Forgejo API over HTTPS (no relay needed)
|
||||
|
||||
The relay is intentionally minimal — it's a bridge, not a CI component. All CI
|
||||
logic stays in `local-runner`.
|
||||
|
||||
---
|
||||
|
||||
## 3. What Was Built
|
||||
|
||||
| Component | Location | Nature |
|
||||
|-----------|----------|--------|
|
||||
| ci-relay binary | `crates/ci-relay/Cargo.toml`, `src/main.rs` | **New** — VPS webhook relay |
|
||||
| Iroh receiver | `crates/local-runner/src/main.rs` | **Modified** — iroh webhook source |
|
||||
| Dependencies | `crates/local-runner/Cargo.toml` | **Modified** — added iroh, tokio, serde_json |
|
||||
| Workspace | `Cargo.toml` | **Modified** — added ci-relay to members |
|
||||
|
||||
---
|
||||
|
||||
## 4. ci-relay Binary
|
||||
|
||||
### `crates/ci-relay/src/main.rs`
|
||||
|
||||
The relay runs two subsystems on a single process:
|
||||
|
||||
1. **iroh acceptor** (tokio task): accepts inbound connections from the runner,
|
||||
caches the most recent one in `Arc<TokioMutex<Option<Connection>>>`
|
||||
2. **HTTP listener** (main thread, blocking `tiny_http`): receives Forgejo
|
||||
webhook POSTs, verifies HMAC, parses event, forwards over iroh
|
||||
|
||||
### Webhook Handling
|
||||
|
||||
Reuses the same verification and parsing logic as `webhook_server.rs`:
|
||||
|
||||
- HMAC-SHA256 verification via `X-Forgejo-Signature` header (skippable with empty secret)
|
||||
- Event type from `X-Forgejo-Event` header: `push` → `Push`, `create` → `Tag`, `pull_request` → `Merge`
|
||||
- JSON parsing via `parse_webhook_json()` (re-exported from `swactor-ci`)
|
||||
|
||||
The relay uses `parse_webhook_json` directly rather than duplicating parsing
|
||||
logic. This keeps webhook interpretation consistent between HTTP and iroh paths.
|
||||
|
||||
### Forwarding
|
||||
|
||||
On webhook receipt, the relay:
|
||||
1. Serializes the `WebhookEvent` to JSON
|
||||
2. Opens a unidirectional QUIC stream on the cached connection
|
||||
3. Writes the tagged message (`ci::WebhookEvent` tag + JSON payload)
|
||||
4. Finishes the stream
|
||||
|
||||
If no runner is connected, the relay returns HTTP 502 to Forgejo. Forgejo will
|
||||
retry the webhook per its configured retry policy.
|
||||
|
||||
### CLI
|
||||
|
||||
```
|
||||
ci-relay [OPTIONS]
|
||||
|
||||
Options:
|
||||
--port <PORT> HTTP port for Forgejo webhooks [default: 8787]
|
||||
--secret <SECRET> HMAC-SHA256 secret [default: "" (no verification)]
|
||||
```
|
||||
|
||||
On startup, the relay prints its iroh Node ID — this is the value the runner
|
||||
needs for `--relay-node-id`.
|
||||
|
||||
---
|
||||
|
||||
## 5. local-runner Iroh Receiver
|
||||
|
||||
### New CLI Flag
|
||||
|
||||
```
|
||||
--relay-node-id <HEX> Iroh Node ID of the VPS ci-relay
|
||||
```
|
||||
|
||||
When `--relay-node-id` is provided:
|
||||
- The HTTP webhook listener is **not started** (no port conflict, no exposure)
|
||||
- An `iroh-receiver` thread starts instead
|
||||
|
||||
When omitted, behavior is unchanged — the HTTP listener starts on `--port`
|
||||
as before.
|
||||
|
||||
### `start_iroh_receiver()`
|
||||
|
||||
Spawns a dedicated thread (`iroh-receiver`) with its own single-threaded tokio
|
||||
runtime:
|
||||
|
||||
1. Creates an iroh `Endpoint` with ALPN `b"swactor/ci/1"`
|
||||
2. Connects to the relay's `PublicKey` (parsed from the hex flag)
|
||||
3. Enters a receive loop:
|
||||
- `conn.accept_uni()` with 1-second timeout
|
||||
- On stream: reads tagged message, deserializes `WebhookEvent`
|
||||
- Sends `LocalCoordinatorMsg::Webhook(event)` to the coordinator via the swactor runtime
|
||||
- On timeout: checks the `stop` flag (for graceful shutdown via Ctrl-C)
|
||||
- On connection error: breaks and exits
|
||||
|
||||
The thread respects the same `AtomicBool` stop flag as the main loop, so
|
||||
Ctrl-C cleanly shuts down both the swactor runtime and the iroh connection.
|
||||
|
||||
---
|
||||
|
||||
## 6. Wire Protocol
|
||||
|
||||
### ALPN
|
||||
|
||||
```rust
|
||||
const CI_ALPN: &[u8] = b"swactor/ci/1";
|
||||
```
|
||||
|
||||
Distinct from SWIM traffic (`b"swactor/swim/1"`). This allows both protocols
|
||||
to coexist on the same iroh endpoint in the future if needed.
|
||||
|
||||
### Frame Format
|
||||
|
||||
Same tagged-message format as `iroh_driver.rs`:
|
||||
|
||||
```
|
||||
[4 bytes: tag_len (big-endian u32)]
|
||||
[tag_len bytes: tag string]
|
||||
[remaining bytes: payload]
|
||||
```
|
||||
|
||||
For webhook events:
|
||||
- Tag: `"ci::WebhookEvent"` (17 bytes)
|
||||
- Payload: JSON-serialized `WebhookEvent`
|
||||
|
||||
### Transport
|
||||
|
||||
Each webhook is one unidirectional QUIC stream. The relay opens the stream,
|
||||
writes the tagged message, and finishes. The runner reads the message and the
|
||||
stream closes. No persistent framing or multiplexing needed — QUIC streams
|
||||
are lightweight.
|
||||
|
||||
---
|
||||
|
||||
## 7. Connection Flow
|
||||
|
||||
```
|
||||
1. VPS starts ci-relay
|
||||
→ iroh Endpoint binds
|
||||
→ prints Node ID (ed25519 public key, hex)
|
||||
→ HTTP listener starts on --port
|
||||
→ waits for runner connection
|
||||
|
||||
2. Thinkpad starts local-runner --relay-node-id <hex>
|
||||
→ iroh Endpoint binds
|
||||
→ connects to relay's PublicKey
|
||||
→ iroh handles NAT traversal (direct or via relay server)
|
||||
→ relay logs "Runner connected: <runner-node-id>"
|
||||
|
||||
3. Forgejo sends webhook POST to localhost:8787 on VPS
|
||||
→ relay verifies HMAC, parses event
|
||||
→ relay opens uni stream on cached connection
|
||||
→ writes tagged WebhookEvent
|
||||
→ runner receives, deserializes, dispatches to coordinator
|
||||
|
||||
4. Coordinator triggers pipeline
|
||||
→ StatusReporter posts status to Forgejo API directly
|
||||
(Thinkpad → zachery.lol over HTTPS, no relay involvement)
|
||||
```
|
||||
|
||||
The iroh connection is initiated by the runner (outbound from NAT), so no port
|
||||
forwarding is needed. iroh's relay servers handle the initial rendezvous, then
|
||||
attempt direct QUIC hole-punching for subsequent traffic.
|
||||
|
||||
---
|
||||
|
||||
## 8. Design Decisions & Tradeoffs
|
||||
|
||||
### 8.1 Separate Binary vs. Library Module
|
||||
|
||||
**Choice**: `ci-relay` is a standalone binary, not a module in `swactor-ci`.
|
||||
|
||||
**Why**: The relay runs on the VPS, which doesn't need swactor's runtime,
|
||||
actors, or any CI execution logic. A small binary with minimal dependencies
|
||||
deploys easily. It only depends on `swactor-ci` for `parse_webhook_json` and
|
||||
the `WebhookEvent`/`EventType` types.
|
||||
|
||||
**Tradeoff**: Two binaries to build and deploy instead of one. Acceptable
|
||||
given they run on different machines.
|
||||
|
||||
### 8.2 Runner Connects to Relay (Not Vice Versa)
|
||||
|
||||
**Choice**: The runner initiates the iroh connection to the relay.
|
||||
|
||||
**Why**: The runner is behind NAT. iroh can traverse NAT for established
|
||||
connections, but the initial rendezvous requires at least one side to be
|
||||
reachable. The VPS relay has a public IP and gets a stable relay URL from iroh's
|
||||
infrastructure. The runner connects outbound, which always works regardless of
|
||||
NAT type.
|
||||
|
||||
### 8.3 Single Cached Connection (Not Connection Pool)
|
||||
|
||||
**Choice**: The relay caches exactly one runner connection in
|
||||
`Arc<TokioMutex<Option<Connection>>>`.
|
||||
|
||||
**Why**: There's one runner. If a new connection arrives (e.g., runner
|
||||
restarts), it replaces the old one. No pool management needed.
|
||||
|
||||
**Tradeoff**: If multiple runners were needed, this would need a map. For
|
||||
single-runner use, the simplicity is worth it.
|
||||
|
||||
### 8.4 Own Tokio Runtime Per Thread
|
||||
|
||||
**Choice**: The iroh-receiver thread creates its own single-threaded tokio
|
||||
runtime rather than sharing the swactor runtime or the main thread's runtime.
|
||||
|
||||
**Why**: swactor's runtime is not tokio — it's a custom actor scheduler. The
|
||||
iroh receiver needs async for QUIC operations. A dedicated single-threaded
|
||||
runtime keeps the iroh I/O isolated from actor scheduling. Same pattern as
|
||||
`IrohDriver` in the distribution layer (which owns a multi-thread runtime).
|
||||
|
||||
### 8.5 HTTP 502 When No Runner Connected
|
||||
|
||||
**Choice**: If Forgejo sends a webhook but no runner is connected, the relay
|
||||
returns HTTP 502 (Bad Gateway).
|
||||
|
||||
**Why**: 502 tells Forgejo the upstream is unavailable. Forgejo will retry
|
||||
the webhook according to its retry policy. This is better than 200 (silently
|
||||
dropping) or 500 (suggesting a relay bug). When the runner reconnects, the
|
||||
next webhook will succeed.
|
||||
|
||||
---
|
||||
|
||||
## 9. Manual Testing Guide
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Build both binaries:
|
||||
|
||||
```bash
|
||||
cargo build -p ci-relay -p local-runner
|
||||
```
|
||||
|
||||
### 9.1 Local Smoke Test (Single Machine)
|
||||
|
||||
This tests the full relay path without needing two machines or Forgejo.
|
||||
|
||||
**Terminal 1 — Start the relay:**
|
||||
|
||||
```bash
|
||||
./target/debug/ci-relay --port 9787
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
ci-relay started
|
||||
Iroh Node ID: <NODE_ID_HEX>
|
||||
Webhook HTTP: http://0.0.0.0:9787
|
||||
|
||||
Waiting for runner to connect...
|
||||
Listening for webhooks...
|
||||
```
|
||||
|
||||
Copy the Node ID.
|
||||
|
||||
**Terminal 2 — Start the runner:**
|
||||
|
||||
You need a `.ci.yml` file. Create a minimal one:
|
||||
|
||||
```yaml
|
||||
# /tmp/test-ci.yml
|
||||
pipelines:
|
||||
test:
|
||||
triggers:
|
||||
- event: push
|
||||
branches: ["*"]
|
||||
jobs:
|
||||
hello:
|
||||
run: echo "hello from CI"
|
||||
```
|
||||
|
||||
Then start:
|
||||
|
||||
```bash
|
||||
./target/debug/local-runner \
|
||||
--relay-node-id <NODE_ID_HEX> \
|
||||
--yaml /tmp/test-ci.yml \
|
||||
--work-dir /tmp/ci-work-test
|
||||
```
|
||||
|
||||
You should see:
|
||||
```
|
||||
Iroh local ID: <RUNNER_ID>
|
||||
Connecting to relay <NODE_ID>...
|
||||
Connected to relay!
|
||||
Local CI runner started
|
||||
Webhook: via iroh relay
|
||||
```
|
||||
|
||||
And in Terminal 1:
|
||||
```
|
||||
Runner connected: <RUNNER_ID>
|
||||
```
|
||||
|
||||
**Terminal 3 — Send a fake webhook:**
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:9787 \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Forgejo-Event: push" \
|
||||
-d '{
|
||||
"ref": "refs/heads/main",
|
||||
"after": "abc123def456789012345678901234567890abcd",
|
||||
"repository": {
|
||||
"name": "test-repo",
|
||||
"owner": { "login": "testuser" }
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
Expected output:
|
||||
|
||||
- **curl** returns: `ok`
|
||||
- **Terminal 1** (relay):
|
||||
```
|
||||
webhook: abc123de main on testuser/test-repo
|
||||
→ forwarded to runner
|
||||
```
|
||||
- **Terminal 2** (runner):
|
||||
```
|
||||
iroh: received webhook abc123de on main
|
||||
```
|
||||
|
||||
The runner will also try to post status to Forgejo and log URL errors (since
|
||||
we didn't pass `--forgejo-url`) — that's expected and confirms the event
|
||||
reached the coordinator.
|
||||
|
||||
### 9.2 HMAC Verification Test
|
||||
|
||||
Start the relay with a secret:
|
||||
|
||||
```bash
|
||||
./target/debug/ci-relay --port 9787 --secret mysecret
|
||||
```
|
||||
|
||||
**Without signature — should be rejected (401):**
|
||||
|
||||
```bash
|
||||
curl -v -X POST http://localhost:9787 \
|
||||
-H "X-Forgejo-Event: push" \
|
||||
-d '{"ref":"refs/heads/main","after":"abc123","repository":{"name":"r","owner":{"login":"u"}}}'
|
||||
```
|
||||
|
||||
**With correct signature:**
|
||||
|
||||
```bash
|
||||
# Compute HMAC-SHA256
|
||||
BODY='{"ref":"refs/heads/main","after":"abc123","repository":{"name":"r","owner":{"login":"u"}}}'
|
||||
SIG=$(echo -n "$BODY" | openssl dgst -sha256 -hmac "mysecret" | awk '{print $2}')
|
||||
|
||||
curl -X POST http://localhost:9787 \
|
||||
-H "X-Forgejo-Event: push" \
|
||||
-H "X-Forgejo-Signature: $SIG" \
|
||||
-d "$BODY"
|
||||
```
|
||||
|
||||
Should return `ok` and forward to the runner.
|
||||
|
||||
### 9.3 Runner Reconnection Test
|
||||
|
||||
1. Start relay and runner as in 9.1
|
||||
2. Kill the runner (Ctrl-C in Terminal 2)
|
||||
3. Restart the runner with the same `--relay-node-id`
|
||||
4. The relay should log `Runner connected: <ID>` again
|
||||
5. Send another webhook — it should flow through
|
||||
|
||||
### 9.4 No Runner Connected Test
|
||||
|
||||
1. Start the relay only (no runner)
|
||||
2. Send a webhook via curl
|
||||
3. Should get HTTP 502 and relay logs: `forward failed: no runner connected`
|
||||
|
||||
### 9.5 Full End-to-End with Forgejo
|
||||
|
||||
For a real deployment:
|
||||
|
||||
**On VPS:**
|
||||
|
||||
```bash
|
||||
./ci-relay --port 8787 --secret <your-webhook-secret>
|
||||
```
|
||||
|
||||
**On Thinkpad:**
|
||||
|
||||
```bash
|
||||
./local-runner \
|
||||
--relay-node-id <NODE_ID_FROM_VPS> \
|
||||
--forgejo-url https://zachery.lol \
|
||||
--forgejo-token <your-forgejo-api-token> \
|
||||
--yaml .ci.yml \
|
||||
--work-dir ~/ci-work \
|
||||
--repo-url https://zachery.lol/<owner>/<repo>.git
|
||||
```
|
||||
|
||||
**In Forgejo (repo settings → Webhooks):**
|
||||
|
||||
- Target URL: `http://localhost:8787`
|
||||
- Secret: `<your-webhook-secret>`
|
||||
- Events: Push, Create (tags), Pull Request
|
||||
|
||||
Push a commit and watch:
|
||||
1. Relay logs the webhook and forwards it
|
||||
2. Runner logs the received event and starts a pipeline
|
||||
3. Forgejo shows commit status checks (pending → success/failure)
|
||||
|
||||
### 9.6 Inspecting Iroh Connectivity
|
||||
|
||||
Both binaries print their iroh Node ID on startup. To verify they're using
|
||||
relay servers (expected when both are behind NAT or on different networks),
|
||||
look for connection timing:
|
||||
|
||||
- **Fast connection (~1-3s)**: direct QUIC hole-punch succeeded
|
||||
- **Slower connection (~5-10s)**: using iroh relay server fallback
|
||||
|
||||
If connection hangs indefinitely, check that both machines have internet
|
||||
access and can reach iroh's relay servers (`https://relay.iroh.network`).
|
||||
|
||||
---
|
||||
|
||||
## 10. Known Gaps & Future Improvements
|
||||
|
||||
| Gap | Effort | Impact | Notes |
|
||||
|-----|--------|--------|-------|
|
||||
| Reconnection on runner side | Small | High | If the iroh connection drops mid-operation, the runner currently exits the receive loop. Should retry with backoff. |
|
||||
| Multiple runner support | Medium | Medium | Relay caches one connection. For running CI on multiple machines, need a connection map keyed by runner identity. |
|
||||
| Health check / heartbeat | Small | Medium | Neither side detects a silently dead connection until the next webhook. A periodic ping would surface stale connections faster. |
|
||||
| Relay authentication | Small | Medium | Any iroh endpoint can connect to the relay. Should verify the runner's public key against an allowlist. |
|
||||
| Binary size | Small | Low | ci-relay pulls in `swactor-ci` (which includes all CI types). A slimmer dependency with just `WebhookEvent` + `parse_webhook_json` would reduce the VPS binary. |
|
||||
| Logging | Small | Low | Both binaries use `eprintln!`. Structured logging (tracing) would help in production. |
|
||||
|
||||
---
|
||||
|
||||
## Files Created/Modified
|
||||
|
||||
| Action | File | Purpose |
|
||||
|--------|------|---------|
|
||||
| Created | `crates/ci-relay/Cargo.toml` | Relay binary manifest |
|
||||
| Created | `crates/ci-relay/src/main.rs` | Webhook relay: HTTP → iroh |
|
||||
| Modified | `crates/local-runner/Cargo.toml` | Added iroh, tokio, serde_json deps |
|
||||
| Modified | `crates/local-runner/src/main.rs` | Added `--relay-node-id` flag and iroh receiver |
|
||||
| Modified | `Cargo.toml` (workspace root) | Added ci-relay to workspace members |
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
# Dashboard Improvements — Research Phase
|
||||
|
||||
## Summary
|
||||
Researched 10 comparable monitoring/dashboard systems to inform swactor's dashboard improvement plan.
|
||||
|
||||
## Systems Analyzed
|
||||
- **Actor runtimes**: Erlang Observer (GUI/CLI/Web), Akka Insights, Ray Dashboard, Orleans Dashboard
|
||||
- **Async/runtime tools**: tokio-console, Lunatic
|
||||
- **Message/infrastructure**: RabbitMQ Management, Consul UI, Nomad UI
|
||||
- **Web frameworks**: Phoenix LiveDashboard
|
||||
|
||||
## Key Findings
|
||||
1. **Time-series history** is table-stakes — every system provides it
|
||||
2. **Actor detail drill-down** is universal (Observer has 6-tab process info, Orleans has grain state inspection)
|
||||
3. **Search/filter** exists in every system
|
||||
4. **Warning/anomaly detection** (tokio-console's lint system) is a high-value differentiator
|
||||
5. **Topology visualization** (Consul golden metrics, Observer supervision tree) is rare but powerful
|
||||
|
||||
## Implementation Plan
|
||||
8 feature stages defined (see `CLAUDE/notes/feature-stages/`):
|
||||
1. Time-Series History Infrastructure
|
||||
2. Actor Detail Drill-Down
|
||||
3. Search and Filter
|
||||
4. Per-Worker Utilization Visualization
|
||||
5. Warning/Anomaly Detection
|
||||
6. Actor-to-Actor Message Flow Topology
|
||||
7. Per-Actor Logging
|
||||
8. Per-Message-Type Breakdown
|
||||
|
|
@ -1,386 +0,0 @@
|
|||
# Datastore Auth: Development History
|
||||
|
||||
**Branch:** `swactor-auth`
|
||||
**Base commit:** `af15416` (pre-auth baseline)
|
||||
**5 commits + uncommitted working tree changes**
|
||||
|
||||
---
|
||||
|
||||
## What Was Built
|
||||
|
||||
A complete ed25519 authorization layer for the distributed datastore, spanning:
|
||||
|
||||
- **Auth engine** — `AuthzEngine` with ACL, signed request verification, replay protection, nonce GC
|
||||
- **GatewayActor** — actor-level enforcement point with grant/revoke, access requests, key listing
|
||||
- **Browser auth flow** — WASM Ed25519 crypto, device key generation, access request/grant/deny lifecycle
|
||||
- **Admin page** — owner key upload, pending request management, manual key grant, authorized key list
|
||||
- **Expanded CLI** — full CRUD + auth subcommands (`grant`, `revoke`, `requests`, `keys`, `deny`) with name resolution
|
||||
- **Storage persistence** — entry/manifest persistence to filesystem, startup bulk-load
|
||||
- **xtask** — `node`, `cli`, `wasm` subcommands with `config.toml` support
|
||||
- **WASM crypto crate** — `crates/crypto-wasm/`, a `no_std` cdylib exporting `ed25519_sign()`, `get_public_key()`, `buffer_ptr()`
|
||||
|
||||
The auth system enforces binary access control (authorized or not) at the HTTP API boundary. Internal actors remain auth-unaware. Two auth paths: connection-level (iroh QUIC handshake proves NodeId) and per-request signed envelopes (for browser/HTTP API). This branch implements Path 2 end-to-end, including the browser UX.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────┐
|
||||
│ HTTP API (api.rs) │
|
||||
│ │
|
||||
│ Ungated: │
|
||||
│ GET / → browser UI (access page) │
|
||||
│ GET /admin → admin page │
|
||||
│ GET /crypto.wasm → WASM Ed25519 module │
|
||||
│ GET /api/status → node identity │
|
||||
│ │
|
||||
│ Auth-gated (X-Signed-Request header): │
|
||||
│ POST /api/put → check_auth → handle_put │
|
||||
│ GET /api/get → check_auth → handle_get │
|
||||
│ GET /api/data → check_auth → handle_data │
|
||||
│ POST /api/delete → check_auth → handle_delete│
|
||||
│ GET /api/list → check_auth → handle_list │
|
||||
│ │
|
||||
│ Auth management (owner-only): │
|
||||
│ POST /api/auth/grant → check_auth_identity │
|
||||
│ POST /api/auth/revoke → check_auth_identity │
|
||||
│ GET /api/auth/requests→ check_auth_identity │
|
||||
│ GET /api/auth/keys → check_auth_identity │
|
||||
│ POST /api/auth/deny → check_auth_identity │
|
||||
│ │
|
||||
│ Signature-only (proves key, no ACL check): │
|
||||
│ POST /api/auth/request → check_auth_sig_only │
|
||||
└───────────────┬─────────────────────────────────────┘
|
||||
│
|
||||
GatewayMsg (various)
|
||||
│
|
||||
┌───────────────▼───────────────┐
|
||||
│ GatewayActor │
|
||||
│ │
|
||||
│ AuthzEngine: │
|
||||
│ 1. verify ed25519 signature │
|
||||
│ 2. check timestamp ±300s │
|
||||
│ 3. check nonce uniqueness │
|
||||
│ 4. check ACL │
|
||||
│ │
|
||||
│ Access request management: │
|
||||
│ pending_requests HashMap │
|
||||
│ grant resolves label from │
|
||||
│ pending request name │
|
||||
│ │
|
||||
│ ACL persistence: │
|
||||
│ persist_acl() on grant/ │
|
||||
│ revoke │
|
||||
└───────────────┬───────────────┘
|
||||
│
|
||||
┌───────────────▼───────────────┐
|
||||
│ DatastoreNode │
|
||||
│ │
|
||||
│ MetadataActor ◄──► BlobStore │
|
||||
│ (auth-unaware) │
|
||||
└───────────────────────────────┘
|
||||
|
||||
┌───────────────────────────────┐
|
||||
│ Browser (WASM Ed25519) │
|
||||
│ │
|
||||
│ /crypto.wasm → initCrypto() │
|
||||
│ deviceKeySeed in localStorage │
|
||||
│ signBytes() per request │
|
||||
│ Access action for all ops │
|
||||
│ → X-Signed-Request header │
|
||||
└───────────────────────────────┘
|
||||
|
||||
┌───────────────────────────────┐
|
||||
│ CLI (store_cli) │
|
||||
│ │
|
||||
│ --key owner.key.json │
|
||||
│ Per-action signing: │
|
||||
│ Put/Get/Delete/List/Access │
|
||||
│ Name resolution for │
|
||||
│ grant/revoke/deny │
|
||||
└───────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Commit-by-Commit
|
||||
|
||||
### `863185e` — feat: distributed datastore primitives protocol
|
||||
|
||||
Foundation commit establishing the distributed datastore protocol. Defined the protocol messages (`GetChunkRequest`, `FindObjectRequest`, `StoreObjectRequest`, `ListObjectsRequest` and their responses), all implementing `NetworkMessage` with stable `type_tag()` strings. This is the wire protocol for inter-node communication over iroh/QUIC.
|
||||
|
||||
**Key files:** `src/messages.rs` (inter-node message types)
|
||||
|
||||
### `84c4408` — fix: cli for datastore works
|
||||
|
||||
Brought up the `store_node` and `store_cli` binaries as `[[bin]]` targets with feature-gated dependencies (`node` and `cli` features). The node binary spawns the actor runtime, wires up BlobStoreActor/MetadataActor/DatastoreNode, and serves the HTTP API via `tiny_http`. The CLI binary talks to the node over HTTP with `ureq`. Added `clap` for arg parsing, `ctrlc` for graceful shutdown, and `runtime-dashboard` integration.
|
||||
|
||||
**Key files:** `Cargo.toml` (features `node`/`cli`), `src/bin/store_node.rs`, `src/bin/store_cli.rs`, `src/api.rs`
|
||||
|
||||
### `ebee109` — feat: mvp auth protocol
|
||||
|
||||
Core auth implementation:
|
||||
|
||||
- **`src/auth.rs`** — `DatastoreAction` enum, `SignedRequestPayload`, `SignedRequest` envelope, `AccessControlList` (with JSON persistence via `save()`/`load_or_create()`), `AuthzEngine` (4-step verification: signature, timestamp, nonce, ACL), `sign_request()`/`verify_signed_request()` helpers, `AuthzResult`/`DeniedReason` enums.
|
||||
- **`src/actors/gateway.rs`** — `GatewayActor` wrapping `AuthzEngine`. Handles `Authorize` (pure auth check), `HandleSignedRequest` (auth + dispatch via `action_to_node_msg()`), `CheckConnection` (Path 1), `Grant`/`Revoke` (owner-only ACL mutations), `NonceGcTick`.
|
||||
- **`src/messages.rs`** — `GatewayMsg` enum, `DatastoreResponse::Denied` variant.
|
||||
- **`crates/shared-types/`** — Extracted `ContentHash` into its own crate to break dependency cycles between `distribution` and `datastore`.
|
||||
|
||||
Tests added (18 total):
|
||||
- `auth_scenario_tests.rs` (10 tests) — owner access, stranger denial, grant/revoke lifecycle, signed request happy path, tampered signature, stale timestamp, replayed nonce, nonce GC, non-owner grant/revoke rejection.
|
||||
- `acl_persistence_tests.rs` (2 tests) — save/load round-trip, create-on-missing.
|
||||
- `gateway_tests.rs` (4 tests) — connection allow/deny, signed request flow-through, unauthorized signed request denial.
|
||||
|
||||
### `8ac45e5` — fix: adjust auth protocol to datastore protocol
|
||||
|
||||
Aligned the auth types with the content-hash-first datastore protocol:
|
||||
- `DatastoreAction::Put` carries `content_hash`, `size_bytes`, and `tags` (not raw data).
|
||||
- `DatastoreAction::Get`/`Delete` use `content_hash`.
|
||||
- `DatastoreAction::List` uses `name_filter`.
|
||||
- `GatewayActor::action_to_node_msg()` maps actions to `DatastoreNodeMsg` variants.
|
||||
- Wired `check_auth()` into the HTTP API handlers (put, get, data, delete, list) — reads `X-Signed-Request` header, sends `GatewayMsg::Authorize` to the gateway actor, denies with 401/403/504 on failure.
|
||||
- `handle_status` intentionally left ungated.
|
||||
|
||||
### `e549eef` — feat: auth MVP with integrated tests
|
||||
|
||||
Wired auth into both binaries:
|
||||
|
||||
**`store_node.rs`** — `--auth` and `--auth-dir <PATH>` flags:
|
||||
- Loads or generates owner keypair from `<auth-dir>/owner.key.json`.
|
||||
- Owner keypair's public key becomes the `NodeId` (deterministic identity across restarts).
|
||||
- Loads/creates `<auth-dir>/acl.json` with owner as sole authorized key.
|
||||
- Spawns `GatewayActor` and passes `Some(gateway_addr)` to `start_api_server`.
|
||||
- Sends `GatewayMsg::NonceGcTick` on the same cadence as the metadata GC tick.
|
||||
|
||||
**`store_cli.rs`** — `--key <PATH>` flag:
|
||||
- Each command builds the appropriate `DatastoreAction`, signs it, sends as `X-Signed-Request` header.
|
||||
- `status` never signs (always open by design).
|
||||
|
||||
**`http_auth_integration.rs`** — Full-stack integration test: spins up the actor runtime with GatewayActor, starts the HTTP server, proves owner is allowed (PUT/GET/LIST/DELETE), stranger gets 403, missing header gets 401.
|
||||
|
||||
---
|
||||
|
||||
## Uncommitted Working Tree Changes
|
||||
|
||||
The uncommitted changes represent the bulk of the user-facing work: browser UI, admin page, WASM crypto, expanded CLI, storage persistence, and xtask.
|
||||
|
||||
### Browser UI (`ui_html.rs` — `DATASTORE_UI_HTML`)
|
||||
|
||||
Complete browser access page served at `/`:
|
||||
|
||||
- **Upload panel** — file input + optional name, PUT via `authFetch()`
|
||||
- **Object table** — list all objects with hash, name, size; download and delete buttons
|
||||
- **Detail modal** — click a row to see full metadata, chunks, tags
|
||||
- **Auth detection** — on load, `detectAuth()` fetches `/api/list`; if 401, enables auth mode
|
||||
- **WASM crypto integration** — `initCrypto()` fetches `/crypto.wasm`, `initKeys()` generates or loads device seed from `localStorage`, derives public key via WASM
|
||||
- **Auth banner** — shown when user is not authorized, with access request form (name + optional message)
|
||||
- **Pending state** — after submitting request, shows "waiting for operator approval" with 5-second polling; auto-refreshes when granted
|
||||
- **Device key display** — shows truncated public key hex in header when auth is active
|
||||
- **JWK migration** — handles legacy `localStorage.deviceKey` (JWK format) by extracting the `d` parameter as seed
|
||||
|
||||
### Admin Page (`ui_html.rs` — `DATASTORE_ADMIN_HTML`)
|
||||
|
||||
Owner administration page served at `/admin`:
|
||||
|
||||
- **Owner key upload** — file input for `key.json`, loads secret/public key hex, derives via WASM to verify, test call to `/api/auth/requests` to confirm ownership
|
||||
- **Pending access requests table** — name, message, key (truncated), grant/deny buttons
|
||||
- **Authorized keys table** — name (label), key (truncated), revoke button
|
||||
- **Manual grant form** — input for 64-char hex public key + optional name
|
||||
- **Name disambiguation** — when multiple entries share the same name, appends `(key_prefix)` suffix
|
||||
- **`ownerAuthFetch()`** — signs all admin API calls with `DatastoreAction::Access`
|
||||
|
||||
### WASM Ed25519 Crypto (`crates/crypto-wasm/`)
|
||||
|
||||
New `no_std` Rust crate compiled to `wasm32-unknown-unknown`:
|
||||
|
||||
- **`Cargo.toml`** — `swactor-crypto-wasm`, `cdylib` crate type, depends on `ed25519-dalek` (no default features)
|
||||
- **`src/lib.rs`** — Three exported functions:
|
||||
- `buffer_ptr()` → pointer to 8192-byte shared buffer
|
||||
- `get_public_key()` — reads 32-byte seed from `BUF[0..32]`, writes public key to `BUF[32..64]`
|
||||
- `ed25519_sign(msg_len)` — reads seed from `BUF[0..32]`, message from `BUF[128..128+msg_len]`, writes 64-byte signature to `BUF[64..128]`
|
||||
- **`crypto_wasm.wasm`** — pre-built binary embedded in the datastore via `include_bytes!("crypto_wasm.wasm")`
|
||||
- Served at `/crypto.wasm` endpoint (ungated)
|
||||
- Replaces the earlier Web Crypto API approach — Web Crypto's Ed25519 support is inconsistent across browsers; WASM provides deterministic behavior using the same `ed25519-dalek` crate as the Rust backend
|
||||
|
||||
### Expanded GatewayActor (`actors/gateway.rs`)
|
||||
|
||||
New message handlers beyond the original `Authorize`/`HandleSignedRequest`/`CheckConnection`/`Grant`/`Revoke`:
|
||||
|
||||
- **`VerifySignature`** — calls `check_signature_only()` (no ACL check). Used for access request submissions where the caller needs to prove key ownership without being in the ACL.
|
||||
- **`SubmitAccessRequest`** — stores `AccessRequestInfo { key, name, message, requested_at }` in `pending_requests: HashMap<NodeId, AccessRequestInfo>`.
|
||||
- **`ListAccessRequests`** — owner-only; returns all pending requests.
|
||||
- **`DenyAccessRequest`** — owner-only; removes a pending request.
|
||||
- **`ListAuthorizedKeys`** — owner-only; returns `Vec<AuthorizedKeyInfo>` with labels.
|
||||
|
||||
Grant now resolves labels: when granting a key that has a pending request, the request's `name` field becomes the key's label (unless an explicit label is provided).
|
||||
|
||||
### Expanded Auth Types (`auth.rs`)
|
||||
|
||||
- **`AccessRequestInfo`** — `{ key: NodeId, name: String, message: String, requested_at: u64 }`
|
||||
- **`AuthorizedKeyInfo`** — `{ key: NodeId, label: String }`
|
||||
- **`DatastoreAction::Access`** — new variant for browser-originated requests that prove identity without binding to specific content. The browser uses `Access` for all operations (auth is at the HTTP layer).
|
||||
- **`key_labels: HashMap<String, String>`** added to `AccessControlList` — maps hex public key to human-readable name. Populated by `grant()`, removed by `revoke()`.
|
||||
- **`check_signature_only()`** on `AuthzEngine` — verifies signature, timestamp, and nonce but skips ACL check.
|
||||
- **`authorized_key_list()`** on `AuthzEngine` — returns all authorized keys with their labels.
|
||||
|
||||
### Storage Persistence (`storage/mod.rs`, `storage/in_memory.rs`)
|
||||
|
||||
Extended `StorageBackend` trait with entry persistence:
|
||||
|
||||
- **`write_entry()`** / **`read_entry()`** / **`delete_entry()`** / **`list_entries()`** — persist `ObjectEntry` JSON to disk
|
||||
- **`FilesystemBackend`** layout extended:
|
||||
```
|
||||
{root}/
|
||||
├── chunks/{hex[0..2]}/{hex[2..4]}/{full_hex_hash}
|
||||
├── manifests/{hex[0..2]}/{hex[2..4]}/{full_hex_hash}
|
||||
└── entries/{hex[0..2]}/{hex[2..4]}/{full_hex_hash}
|
||||
```
|
||||
- **`BlobStoreMsg::WriteEntry`** / **`DeleteEntry`** — fire-and-forget messages for entry persistence
|
||||
- **`BlobStoreMsg::LoadAll`** — startup bulk-load of all entries + their manifests
|
||||
- **`MetadataMsg::BulkLoad`** — injects loaded entries into MetadataActor's index
|
||||
- **`store_node.rs` startup sequence** — sends `LoadAll` to BlobStoreActor, polls for `LoadedAll` response, sends `BulkLoad` to MetadataActor
|
||||
|
||||
### Expanded CLI (`store_cli.rs`)
|
||||
|
||||
Full CRUD + auth management subcommands:
|
||||
|
||||
| Subcommand | Auth | Description |
|
||||
|------------|------|-------------|
|
||||
| `put <path> [--name]` | `--key` signs `DatastoreAction::Put` | Upload a file |
|
||||
| `get <hash> [--output]` | `--key` signs `DatastoreAction::Get` | Metadata or download |
|
||||
| `delete <hash>` | `--key` signs `DatastoreAction::Delete` | Delete an object |
|
||||
| `list [--name] [--all]` | `--key` signs `DatastoreAction::List` | List objects |
|
||||
| `status` | Never signed | Node identity |
|
||||
| `grant <key_or_name> [--name]` | `--key` signs `Access` | Authorize a key (owner-only) |
|
||||
| `revoke <key_or_name>` | `--key` signs `Access` | Revoke a key (owner-only) |
|
||||
| `requests` | `--key` signs `Access` | List pending access requests |
|
||||
| `keys` | `--key` signs `Access` | List authorized keys |
|
||||
| `deny <key_or_name>` | `--key` signs `Access` | Deny a pending request |
|
||||
|
||||
**Name resolution:** `grant`, `revoke`, and `deny` accept either a 64-char hex key or a human-readable name. When given a name, the CLI fetches the relevant list from the API and resolves the name to a key. Disambiguated names (`"alice (c9d0e1f2)"`) are supported.
|
||||
|
||||
### xtask (`xtask/src/main.rs`)
|
||||
|
||||
Development task runner with three new subcommands beyond the existing `test`:
|
||||
|
||||
- **`cargo xtask node`** — builds and runs `swactor-store-node`. Flags: `--port`, `--storage-path`, `--auth` (default: true), `--auth-dir`. Builds with `--features node` first, then runs the binary directly (not via `cargo run`) to avoid SIGINT issues. Ignores SIGINT in the xtask process so the child handles Ctrl-C.
|
||||
- **`cargo xtask cli`** — builds and runs `swactor-store`. Flags: `--url`, `--key`. Auto-detects `./auth/owner.key.json` if present. Passes extra args through.
|
||||
- **`cargo xtask wasm`** — builds `swactor-crypto-wasm` for `wasm32-unknown-unknown --release`, copies the output to `crates/datastore/src/crypto_wasm.wasm`, optionally runs `wasm-strip`.
|
||||
- **`config.toml` support** — reads `xtask/config.toml` for default values (node port, storage path, auth settings, CLI url/key).
|
||||
|
||||
**`xtask/Cargo.toml`** — added `toml`, `serde`, `libc` dependencies.
|
||||
|
||||
### HTTP API Expansion (`api.rs`)
|
||||
|
||||
New endpoints:
|
||||
|
||||
| Method | Path | Auth | Handler |
|
||||
|--------|------|------|---------|
|
||||
| `POST` | `/api/auth/grant?key=<hex>[&name=<label>]` | Owner (full check) | `handle_auth_grant` |
|
||||
| `POST` | `/api/auth/revoke?key=<hex>` | Owner (full check) | `handle_auth_revoke` |
|
||||
| `POST` | `/api/auth/request` | Signature-only | `handle_auth_request` |
|
||||
| `GET` | `/api/auth/requests` | Owner (full check) | `handle_auth_requests_list` |
|
||||
| `GET` | `/api/auth/keys` | Owner (full check) | `handle_auth_keys_list` |
|
||||
| `POST` | `/api/auth/deny?key=<hex>` | Owner (full check) | `handle_auth_deny` |
|
||||
| `GET` | `/` | None | Browser UI |
|
||||
| `GET` | `/admin` | None | Admin page |
|
||||
| `GET` | `/crypto.wasm` | None | WASM module |
|
||||
|
||||
New internal functions:
|
||||
- `check_auth_identity()` — like `check_auth()` but returns the caller's `NodeId` (needed for grant/revoke to identify the requester).
|
||||
- `check_auth_signature_only()` — verifies signature without ACL check (for access request submission).
|
||||
- `respond_wasm()`, `respond_admin_html()` — serve the new static assets.
|
||||
- `CRYPTO_WASM` constant — `include_bytes!("crypto_wasm.wasm")`.
|
||||
|
||||
### DatastoreResponse Expansion (`messages.rs`)
|
||||
|
||||
New response variants:
|
||||
- `AccessRequests { requests: Vec<AccessRequestInfo> }` — response to `ListAccessRequests`
|
||||
- `AuthorizedKeys { keys: Vec<AuthorizedKeyInfo> }` — response to `ListAuthorizedKeys`
|
||||
- `LoadedAll { entries: Vec<(ObjectEntry, ObjectManifest)> }` — response to `BlobStoreMsg::LoadAll`
|
||||
|
||||
---
|
||||
|
||||
## Key File Format
|
||||
|
||||
`owner.key.json` / any client `key.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"secret_key": "...64 hex chars (32 bytes)...",
|
||||
"public_key": "...64 hex chars (32 bytes)...",
|
||||
"created_at": "2026-02-15T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
Generated by the node on first `--auth` run. The CLI reads it via `--key`. The admin page uploads it for authentication. The browser generates a simpler device seed (32 random bytes stored as hex in `localStorage.deviceKeySeed`).
|
||||
|
||||
---
|
||||
|
||||
## Test Summary
|
||||
|
||||
| Test File | Count | What |
|
||||
|-----------|-------|------|
|
||||
| `auth_scenario_tests.rs` | 10 | AuthzEngine: signing, verification, timestamp, nonce, ACL, grant/revoke |
|
||||
| `acl_persistence_tests.rs` | 2 | ACL JSON round-trip, create-on-missing |
|
||||
| `gateway_tests.rs` | 4 | GatewayActor: connection check, signed request flow, denial |
|
||||
| `http_auth_integration.rs` | 1 | Full HTTP stack: owner PUT/GET/LIST/DELETE, stranger 403, no-header 401 |
|
||||
| **Auth total** | **17** | |
|
||||
|
||||
Pre-existing datastore tests (blob_store, metadata, datastore_node, chunking, gc, storage, transfer, multi_node, api_integration, dashboard_integration) continue to pass.
|
||||
|
||||
---
|
||||
|
||||
## Design Decisions
|
||||
|
||||
1. **WASM Ed25519 over Web Crypto** — Web Crypto's Ed25519 support varies by browser (Safari lacking, Firefox gated behind flags as of early 2026). A WASM module using `ed25519-dalek` with `no_std` gives deterministic, cross-browser behavior and byte-level compatibility with the Rust backend. The compiled module is ~27KB stripped.
|
||||
|
||||
2. **`DatastoreAction::Access` for browser ops** — The browser signs a lightweight `Access` action for every API call rather than constructing per-operation payloads. This simplifies the browser JS (no need to compute content hashes client-side) while still proving identity. The actual data operations are auth-gated at the HTTP layer.
|
||||
|
||||
3. **Signature-only check for access requests** — `POST /api/auth/request` uses `check_auth_signature_only()` which verifies the signature/timestamp/nonce but skips the ACL check. This allows an unauthorized user to prove key ownership when requesting access, without being in the ACL yet.
|
||||
|
||||
4. **Key labels in ACL** — `key_labels: HashMap<String, String>` maps hex public key to human-readable name. Labels are set on grant (from the access request's `name` field or an explicit `--name` flag) and removed on revoke. This enables the admin page and CLI to show meaningful names instead of raw hex keys.
|
||||
|
||||
5. **Access request flow** — Instead of requiring out-of-band key exchange, browser users can submit an access request with their name and a message. The request is stored in-memory in the GatewayActor's `pending_requests`. The owner can grant or deny from the admin page or CLI. On grant, the pending request is removed and its name becomes the key label.
|
||||
|
||||
6. **Entry persistence** — `StorageBackend` trait extended with `write_entry()`/`read_entry()`/`delete_entry()`/`list_entries()`. The `FilesystemBackend` stores entries as JSON files in a `entries/` directory with the same 2-level hex sharding as chunks. On startup, `BlobStoreMsg::LoadAll` reads all entries and their manifests, then `MetadataMsg::BulkLoad` injects them into the MetadataActor's index. This means stored objects survive node restarts.
|
||||
|
||||
7. **xtask builds then execs** — `cargo xtask node` and `cargo xtask cli` build the binary first, then exec it directly (not via `cargo run`). This avoids cargo sitting in the process chain and dying from SIGINT before the node finishes its shutdown sequence.
|
||||
|
||||
8. **Status endpoint stays open** — `/api/status`, `/`, `/admin`, and `/crypto.wasm` are never auth-gated. Status enables health checks; the UI/admin pages need to be loadable before authentication; the WASM module is needed to perform authentication.
|
||||
|
||||
9. **ACL persisted to auth-dir** — The ACL is stored at `<auth-dir>/acl.json` (default: `./auth/acl.json`), not inside the storage path. This separates auth config from data storage.
|
||||
|
||||
10. **CLI name resolution** — `grant`, `revoke`, and `deny` accept human-readable names in addition to hex keys. When given a name, the CLI fetches the pending requests or authorized keys list from the API and resolves the name. If multiple entries match, it prints disambiguated names (e.g., `"alice (c9d0e1f2)"`) and asks the user to re-run.
|
||||
|
||||
---
|
||||
|
||||
## File Inventory
|
||||
|
||||
| File | What |
|
||||
|------|------|
|
||||
| `crates/shared-types/` | `ContentHash` crate (breaks dependency cycles) |
|
||||
| `crates/crypto-wasm/Cargo.toml` | WASM crypto crate config |
|
||||
| `crates/crypto-wasm/src/lib.rs` | `no_std` Ed25519 sign/derive/buffer exports |
|
||||
| `crates/datastore/src/crypto_wasm.wasm` | Pre-built WASM binary (embedded via `include_bytes!`) |
|
||||
| `crates/datastore/Cargo.toml` | Feature flags (`node`/`cli`), dependencies |
|
||||
| `crates/datastore/src/auth.rs` | Auth engine, ACL, signing, verification, access request types |
|
||||
| `crates/datastore/src/actors/gateway.rs` | GatewayActor — auth enforcement + access request management |
|
||||
| `crates/datastore/src/actors/blob_store.rs` | BlobStoreActor — entry persistence, LoadAll |
|
||||
| `crates/datastore/src/actors/metadata.rs` | MetadataActor — entry persistence writes, BulkLoad |
|
||||
| `crates/datastore/src/messages.rs` | GatewayMsg, BlobStoreMsg (WriteEntry/DeleteEntry/LoadAll), DatastoreResponse extensions |
|
||||
| `crates/datastore/src/api.rs` | HTTP API — auth endpoints, WASM/admin serving, auth checking functions |
|
||||
| `crates/datastore/src/ui_html.rs` | Browser UI (access page) + Admin page HTML/CSS/JS |
|
||||
| `crates/datastore/src/storage/mod.rs` | StorageBackend trait (entry methods), FilesystemBackend |
|
||||
| `crates/datastore/src/storage/in_memory.rs` | InMemoryBackend (entry methods) |
|
||||
| `crates/datastore/src/bin/store_node.rs` | Node binary — `--auth`, `--auth-dir`, keypair mgmt, gateway spawn, bulk-load |
|
||||
| `crates/datastore/src/bin/store_cli.rs` | CLI binary — `--key`, all subcommands, name resolution |
|
||||
| `xtask/Cargo.toml` | xtask dependencies (toml, serde, libc) |
|
||||
| `xtask/src/main.rs` | `node`, `cli`, `wasm` subcommands, `config.toml` support |
|
||||
| `docs/datastore/DATASTORE_AUTH.md` | Auth specification document |
|
||||
| `tests/auth_scenario_tests.rs` | 10 AuthzEngine scenario tests |
|
||||
| `tests/acl_persistence_tests.rs` | 2 ACL persistence tests |
|
||||
| `tests/gateway_tests.rs` | 4 GatewayActor tests |
|
||||
| `tests/http_auth_integration.rs` | 1 full-stack HTTP auth integration test |
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
# Unified Swactor Node with Datastore Dashboard Management
|
||||
|
||||
This document summarizes the changes on the `datastore-dashboard` branch.
|
||||
|
||||
## Problem
|
||||
|
||||
The swactor ecosystem had two separate binaries with no overlap:
|
||||
|
||||
- **`swactor-node`** (in `runtime-dashboard`) — distribution + dashboard, no datastore
|
||||
- **`swactor-store-node`** (in `swactor-datastore`) — datastore + optional dashboard, no distribution
|
||||
|
||||
The dashboard's `/datastore` page was read-only (stats via SSE). The standalone datastore had its own management UI on a separate port. Neither binary gave you the full picture.
|
||||
|
||||
## Solution
|
||||
|
||||
A single batteries-included `swactor-node` crate that combines distribution, dashboard, and datastore. The dashboard now supports full datastore CRUD and lifecycle management. Old binaries remain as lightweight alternatives.
|
||||
|
||||
**Quick start:**
|
||||
|
||||
```
|
||||
cargo xtask dev-node
|
||||
```
|
||||
|
||||
Opens an iroh node with in-memory datastore on dashboard port 9090.
|
||||
|
||||
## What Changed
|
||||
|
||||
### New files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `crates/swactor-node/Cargo.toml` | Unified node crate — depends on `runtime-dashboard`, `swactor-datastore`, and `distribution` |
|
||||
| `crates/swactor-node/src/main.rs` | Combined binary with CLI: `--transport` (iroh default), `--storage-path`, `--no-datastore`, `--dashboard-port`, etc. Main loop merges distribution ticking with datastore GC/dissemination |
|
||||
| `crates/datastore/src/bridge.rs` | `DatastoreBridge` — implements the dashboard's provider trait by sending actor messages and polling responses. `DatastoreNodeFactory` — spawns a fresh set of datastore actors on demand (used by the start/stop UI) |
|
||||
|
||||
### Modified files
|
||||
|
||||
**`Cargo.toml` (workspace root)**
|
||||
- Added `"crates/swactor-node"` to workspace members.
|
||||
|
||||
**`crates/datastore/src/lib.rs`**
|
||||
- Added `pub mod bridge` behind `#[cfg(feature = "node")]`.
|
||||
|
||||
**`crates/runtime-dashboard/src/datastore_collector.rs`**
|
||||
- Expanded `DatastoreStatsProvider` trait with CRUD methods: `list_objects`, `get_object`, `get_data`, `put_data`, `delete_object`, `node_status`, `is_running`, `shutdown_datastore`. All have default impls returning `Err("not supported")` so existing `DatastoreMetrics` impl compiles unchanged.
|
||||
- Added `ListScope` enum (`Local` / `Swarm`).
|
||||
- Added `DatastoreFactory` trait for starting datastores from the dashboard.
|
||||
|
||||
**`crates/runtime-dashboard/src/lib.rs`**
|
||||
- Added `datastore_factory` field to `DashboardHandle`.
|
||||
- Added `set_datastore_factory()` and `datastore_provider()` methods.
|
||||
- Threads factory through to `spawn_http_server()`.
|
||||
|
||||
**`crates/runtime-dashboard/src/server.rs`**
|
||||
- Switched route matching from path-only to `(method, path)` tuples.
|
||||
- Added 8 new API routes under `/api/datastore/`:
|
||||
- `GET /api/datastore/list` — list objects (local or swarm scope)
|
||||
- `GET /api/datastore/get` — object metadata + manifest
|
||||
- `GET /api/datastore/data` — download raw bytes
|
||||
- `GET /api/datastore/status` — node identity
|
||||
- `POST /api/datastore/put` — upload data
|
||||
- `POST /api/datastore/delete` — delete object
|
||||
- `POST /api/datastore/start` — start datastore via factory
|
||||
- `POST /api/datastore/shutdown` — stop datastore
|
||||
- SSE `datastore` event now wraps the snapshot in an envelope: `{"is_running": bool, "snapshot": ...}`.
|
||||
|
||||
**`crates/runtime-dashboard/src/datastore_html.rs`**
|
||||
- Full rewrite merging the monitoring dashboard (SSE-driven stats, event timeline, transfers) with the management UI from `ui_html.rs`:
|
||||
- Upload panel (file input + optional name)
|
||||
- Objects table with Origin column (local/remote badges) and action buttons (download, delete)
|
||||
- Detail modal (hash, name, size, node, tags, chunk list)
|
||||
- Toast notifications
|
||||
- Lifecycle buttons: Start Datastore / Stop (shown based on `is_running` from SSE)
|
||||
|
||||
**`xtask/src/main.rs`**
|
||||
- Added `dev-node` subcommand: builds and runs the unified node with happy defaults (iroh transport, port 9090, 3 actors, in-memory datastore).
|
||||
- Options: `--port`, `--actors`, `--storage`, `--no-datastore`, `--tcp`, `--listen`, `--release`.
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Iroh is the default transport.** TCP is available via `--tcp` flag or `--transport tcp`.
|
||||
- **Datastore is on by default** (in-memory). Disable with `--no-datastore`.
|
||||
- **Dashboard-only API** — no separate datastore HTTP port. The dashboard serves all CRUD routes.
|
||||
- **Factory pattern** — even when started with `--no-datastore`, the dashboard can start/stop a datastore at runtime via `DatastoreNodeFactory`.
|
||||
- **No circular dependencies** — `swactor-node` sits atop the dependency graph: `swactor-node` -> `runtime-dashboard` + `swactor-datastore[node]`. The bridge trait lives in `runtime-dashboard` with default method impls.
|
||||
- **Old binaries kept** — `runtime-dashboard`'s `swactor-node` and `swactor-datastore`'s `swactor-store-node` still work as lightweight alternatives.
|
||||
|
||||
## Verification
|
||||
|
||||
```
|
||||
cargo build -p swactor-node -p runtime-dashboard -p swactor-datastore # clean, 0 warnings
|
||||
cargo test -p swactor -p distribution -p runtime-dashboard -p swactor-datastore -p swactor-node # 323 tests pass
|
||||
```
|
||||
|
|
@ -1,305 +0,0 @@
|
|||
# Swactor Datastore Auth Specification
|
||||
|
||||
**Version:** 0.1.0 (MVP)
|
||||
**Status:** Draft
|
||||
**Companion to:** `DATASTORE_PROTOCOL.md`
|
||||
|
||||
## 1. Overview
|
||||
|
||||
This document specifies the authorization layer for the Swactor Datastore. It defines how access is controlled for external clients connecting to a datastore node.
|
||||
|
||||
### Principles
|
||||
|
||||
- **Cryptographic identity** — keys, not passwords. Every participant is identified by an ed25519 public key (`NodeId`).
|
||||
- **Binary access** — a client is either authorized or not. No permission tiers for MVP.
|
||||
- **Owner-only administration** — only the datastore owner can grant or revoke access.
|
||||
- **Transport-layer authentication** — iroh's QUIC handshake cryptographically proves a peer's `NodeId`. This spec builds authorization on top of that.
|
||||
|
||||
### Non-Goals (MVP)
|
||||
|
||||
- Per-path permission scoping.
|
||||
- Permission tiers (read-only, read-write, admin).
|
||||
- Capability tokens or time-limited delegated access.
|
||||
- Multi-level delegation chains.
|
||||
|
||||
## 2. Trust Boundaries
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ Cluster (SWIM mesh) │
|
||||
│ │
|
||||
│ Node A ◄──────────────► Node B │
|
||||
│ implicitly trusted │
|
||||
│ (no auth checks) │
|
||||
└──────────────────┬──────────────────────────┘
|
||||
│
|
||||
│ auth boundary
|
||||
│
|
||||
┌──────────▼──────────┐
|
||||
│ External Clients │
|
||||
│ │
|
||||
│ CLI tool │
|
||||
│ Browser user │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
- **Cluster-internal** (node-to-node via SWIM): implicitly trusted. Nodes that are members of the SWIM cluster communicate freely — no per-request auth checks.
|
||||
- **External clients** (CLI, browser): must be authorized. Every external request is checked against the Access Control List before being dispatched to the actor system.
|
||||
|
||||
## 3. Identity Model
|
||||
|
||||
The auth layer reuses the existing ed25519 identity model from the distribution layer:
|
||||
|
||||
- Every client (CLI tool, browser user, node) has an ed25519 keypair.
|
||||
- Identity is the 32-byte public key, represented as `NodeId`.
|
||||
- The same `NodeId` type from `distribution::types` is used throughout.
|
||||
|
||||
There is no separate "user" concept — a keypair *is* an identity.
|
||||
|
||||
## 4. Access Control List
|
||||
|
||||
### 4.1 Structure
|
||||
|
||||
```
|
||||
AccessControlList {
|
||||
owner: NodeId, // The datastore owner's public key
|
||||
authorized_keys: Set<NodeId>, // Explicitly authorized client keys
|
||||
}
|
||||
```
|
||||
|
||||
- The **owner** always has full access (implicit; never needs to be in `authorized_keys`).
|
||||
- An empty `authorized_keys` set means only the owner can access the datastore.
|
||||
|
||||
### 4.2 Persistence
|
||||
|
||||
The ACL is persisted as a JSON file alongside the datastore's `storage_path`:
|
||||
|
||||
```
|
||||
{storage_path}/
|
||||
├── chunks/
|
||||
├── manifests/
|
||||
└── acl.json # AccessControlList
|
||||
```
|
||||
|
||||
### 4.3 Mutations
|
||||
|
||||
| Operation | Signature | Who |
|
||||
|-----------|-----------|-----|
|
||||
| Grant access | `grant(key: NodeId)` | Owner only |
|
||||
| Revoke access | `revoke(key: NodeId)` | Owner only |
|
||||
|
||||
- `grant` adds a `NodeId` to `authorized_keys`. Idempotent — granting an already-authorized key is a no-op.
|
||||
- `revoke` removes a `NodeId` from `authorized_keys`. Idempotent — revoking a non-existent key is a no-op.
|
||||
- Revoking the owner is a no-op (the owner's implicit access cannot be removed).
|
||||
- Both operations persist the updated ACL to disk immediately.
|
||||
|
||||
## 5. Auth Path 1 — Direct iroh Connection
|
||||
|
||||
For clients that connect directly to the datastore node over iroh (QUIC):
|
||||
|
||||
```
|
||||
Client (ed25519 keypair) Datastore Node
|
||||
│ │
|
||||
│──── iroh QUIC handshake ──────────>│
|
||||
│ (proves client's NodeId) │
|
||||
│ │
|
||||
│ check NodeId
|
||||
│ against ACL
|
||||
│ │
|
||||
│<─── accept / reject ──────────────│
|
||||
│ │
|
||||
│ (if accepted, all ops on │
|
||||
│ this connection are allowed) │
|
||||
```
|
||||
|
||||
1. The iroh QUIC handshake cryptographically proves the peer's `NodeId` (ed25519 public key).
|
||||
2. On connection establishment, the node checks the peer's `NodeId` against the ACL.
|
||||
3. If authorized → connection accepted. All operations on that connection are allowed with no per-message overhead.
|
||||
4. If not authorized → connection rejected immediately.
|
||||
|
||||
This is the preferred auth path — zero overhead after the initial handshake.
|
||||
|
||||
## 6. Auth Path 2 — Signed Requests (Browser Relay)
|
||||
|
||||
For browser users who cannot establish direct iroh connections (e.g., because the browser communicates via a website backend that relays requests):
|
||||
|
||||
### 6.1 Threat Model
|
||||
|
||||
The website backend acts as an **untrusted relay**. It forwards requests between the browser and the datastore node but never sees private keys. The relay cannot forge, modify, or replay requests.
|
||||
|
||||
### 6.2 Signed Envelope
|
||||
|
||||
Each request is wrapped in a signed envelope:
|
||||
|
||||
```
|
||||
SignedRequest {
|
||||
payload: SignedRequestPayload, // The request details
|
||||
public_key: NodeId, // Client's public key
|
||||
signature: Signature, // ed25519 signature over serialized payload
|
||||
}
|
||||
|
||||
SignedRequestPayload {
|
||||
action: DatastoreAction, // What the client wants to do
|
||||
timestamp: u64, // Unix timestamp (seconds)
|
||||
nonce: [u8; 16], // 16 random bytes
|
||||
}
|
||||
|
||||
DatastoreAction = enum {
|
||||
Put { name, content_hash, size_bytes, tags },
|
||||
Get { content_hash },
|
||||
Delete { content_hash },
|
||||
List { name_filter },
|
||||
}
|
||||
```
|
||||
|
||||
### 6.3 Verification Steps
|
||||
|
||||
The datastore node verifies a signed request in strict order:
|
||||
|
||||
1. **Signature validity** — verify the ed25519 signature over the canonical serialization of `SignedRequestPayload` using the provided `public_key`.
|
||||
2. **Timestamp freshness** — reject if `|now - payload.timestamp| > 300` seconds.
|
||||
3. **Nonce uniqueness** — reject if `payload.nonce` has been seen before within the time window.
|
||||
4. **ACL check** — reject if `public_key` is not in the ACL.
|
||||
|
||||
If any step fails, the request is denied with the corresponding `DeniedReason`.
|
||||
|
||||
### 6.4 Put Payload Note
|
||||
|
||||
`DatastoreAction::Put` references a `content_hash` rather than embedding raw file data. The bulk data is uploaded separately, and its integrity is guaranteed by blake3 content addressing. The signed envelope authorizes the *operation*, not the data transfer.
|
||||
|
||||
## 7. Replay Protection
|
||||
|
||||
### 7.1 Timestamp Window
|
||||
|
||||
- Requests must have a `timestamp` within ±300 seconds of the node's wall clock.
|
||||
- This bounds the maximum clock drift between client and server.
|
||||
- Requests outside this window are rejected with `DeniedReason::RequestExpired`.
|
||||
|
||||
### 7.2 Nonce
|
||||
|
||||
- Each request includes a 16-byte random nonce.
|
||||
- The node maintains a set of recently seen nonces.
|
||||
- Duplicate nonces within the time window are rejected with `DeniedReason::ReplayDetected`.
|
||||
|
||||
### 7.3 Nonce Garbage Collection
|
||||
|
||||
- Nonces are stored alongside their timestamps.
|
||||
- When a nonce's timestamp falls outside the ±300 second window, it is eligible for GC.
|
||||
- GC runs periodically (piggy-backed on request processing or a background sweep).
|
||||
|
||||
## 8. Enforcement Point
|
||||
|
||||
Auth is enforced at the **edge** of the actor system — between external clients and the internal actors:
|
||||
|
||||
```
|
||||
External Client
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ Auth Gate │◄── ACL check happens here
|
||||
└──────┬──────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────┐ ┌─────────────────┐ ┌────────────────┐
|
||||
│ MetadataActor│◄──►│ BlobStoreActor │ │ TransferActor │
|
||||
│ │ │ │ │ │
|
||||
│ (auth- │ │ (auth- │ │ (auth- │
|
||||
│ unaware) │ │ unaware) │ │ unaware) │
|
||||
└──────────────┘ └─────────────────┘ └────────────────┘
|
||||
```
|
||||
|
||||
### 8.1 Direct iroh Connections
|
||||
|
||||
- Auth check at connection acceptance time.
|
||||
- Once accepted, the connection is fully trusted for all operations.
|
||||
- No per-message overhead.
|
||||
|
||||
### 8.2 Signed Requests (Browser Relay)
|
||||
|
||||
- A `GatewayActor` receives signed request envelopes.
|
||||
- The GatewayActor verifies the envelope (signature, timestamp, nonce, ACL).
|
||||
- If valid, the GatewayActor dispatches the inner action to the `MetadataActor`.
|
||||
- If invalid, the GatewayActor returns the denial reason to the relay.
|
||||
|
||||
### 8.3 Internal Actors
|
||||
|
||||
`MetadataActor`, `BlobStoreActor`, and `TransferActor` remain **auth-unaware**. They process messages from any source within the actor system. The auth boundary is strictly external.
|
||||
|
||||
## 9. Key Management
|
||||
|
||||
### 9.1 Key Generation
|
||||
|
||||
- Uses `ed25519_dalek` keypairs (same as node identity).
|
||||
- CLI: `swactor-store auth keygen` generates a new keypair and prints both the secret key (for the client to store) and the public key (to share with the owner).
|
||||
- Browser: keypair generated client-side using WebCrypto Ed25519 or wasm-compiled ed25519. The private key never leaves the browser.
|
||||
|
||||
### 9.2 Grant Flow
|
||||
|
||||
```
|
||||
1. Client generates an ed25519 keypair.
|
||||
2. Client shares their public key with the datastore owner (out-of-band).
|
||||
3. Owner runs: swactor-store auth grant <pubkey>
|
||||
4. Client can now access the datastore.
|
||||
```
|
||||
|
||||
The out-of-band exchange is intentional — it keeps the trust model simple. The owner explicitly decides who gets access.
|
||||
|
||||
### 9.3 Revocation
|
||||
|
||||
```
|
||||
1. Owner runs: swactor-store auth revoke <pubkey>
|
||||
2. Client's access is immediately revoked.
|
||||
3. Existing direct iroh connections from that client remain open until disconnected.
|
||||
4. Signed requests from the revoked key are rejected immediately.
|
||||
```
|
||||
|
||||
Note: revoking a key does not forcibly disconnect an active iroh session. The revocation takes effect on the next connection attempt. For immediate disconnection, the owner should also restart the node or implement connection tracking (future extension).
|
||||
|
||||
## 10. CLI Extensions
|
||||
|
||||
The following subcommands are added under `swactor-store auth`:
|
||||
|
||||
```
|
||||
swactor-store auth keygen
|
||||
Generate a new ed25519 keypair.
|
||||
Prints the public key (hex) and secret key (hex) to stdout.
|
||||
|
||||
swactor-store auth grant <pubkey>
|
||||
Add a public key to the ACL's authorized_keys set.
|
||||
Requires running on the owner's node.
|
||||
|
||||
swactor-store auth revoke <pubkey>
|
||||
Remove a public key from the ACL's authorized_keys set.
|
||||
Requires running on the owner's node.
|
||||
|
||||
swactor-store auth list
|
||||
Show all authorized keys (including the owner).
|
||||
|
||||
swactor-store auth whoami
|
||||
Show this node's public key (NodeId).
|
||||
```
|
||||
|
||||
## 11. Integration with Datastore Protocol
|
||||
|
||||
Each protocol flow from `DATASTORE_PROTOCOL.md` §6 has a clear auth integration point:
|
||||
|
||||
| Protocol Flow | Auth Path 1 (Direct) | Auth Path 2 (Signed Request) |
|
||||
|---------------|----------------------|------------------------------|
|
||||
| §6.1 PUT | Connection-level ACL check | `SignedRequest { action: Put { name, content_hash, size_bytes, tags }, .. }` |
|
||||
| §6.2 GET (Local) | Connection-level ACL check | `SignedRequest { action: Get { content_hash }, .. }` |
|
||||
| §6.3 GET (Remote) | Connection-level ACL check | `SignedRequest { action: Get { content_hash }, .. }` → node handles remote fetch internally |
|
||||
| §6.4 DELETE | Connection-level ACL check | `SignedRequest { action: Delete { content_hash }, .. }` |
|
||||
| §6.5 LIST (Local) | Connection-level ACL check | `SignedRequest { action: List { name_filter }, .. }` |
|
||||
| §6.6 LIST (Swarm-Wide) | Connection-level ACL check | `SignedRequest { action: List { name_filter }, .. }` → node handles fan-out internally |
|
||||
|
||||
In all cases, auth is enforced *before* the request reaches the actor system. Internal inter-node communication (DHT replication, chunk transfers between cluster members) is not subject to auth checks.
|
||||
|
||||
## 12. Future Extensions
|
||||
|
||||
These are explicitly **out of scope** for MVP but inform the design:
|
||||
|
||||
- **Per-path permission scoping** — restrict a key to specific path prefixes (e.g., read-only access to `photos/`).
|
||||
- **Permission tiers** — read-only, read-write, admin roles.
|
||||
- **Capability tokens** — time-limited, scope-limited bearer tokens for delegated access without sharing long-lived keys.
|
||||
- **Multi-level delegation** — allow authorized users to grant limited access to others.
|
||||
- **Connection tracking** — forcibly disconnect revoked keys from active iroh sessions.
|
||||
|
|
@ -1,471 +0,0 @@
|
|||
# Swactor Datastore Protocol Specification
|
||||
|
||||
**Version:** 0.2.0 (MVP)
|
||||
**Status:** Draft
|
||||
|
||||
## 1. Overview
|
||||
|
||||
The Swactor Datastore is a distributed personal file/blob storage protocol for small trusted clusters (laptop, phone, browser). It provides content-hash-first addressing with immutable content-addressed objects, replicated via a Kademlia-based metadata DHT.
|
||||
|
||||
### Design Principles
|
||||
|
||||
- **Content-hash-first addressing** — every object is identified by `blake3(blob_bytes)`. This is the primary key for all operations.
|
||||
- **Immutable content-addressed objects** — content hashes are unique identifiers. There are no write conflicts by construction.
|
||||
- **Names are metadata** — optional flat strings attached to objects, not keys. Multiple objects can share a name; distinguished by content hash.
|
||||
- **Separation of data and metadata** — chunks are large opaque blobs; metadata is small, gossiped, and queryable.
|
||||
- **Crash-safe** — fsync before acknowledge on all writes.
|
||||
- **Actor-based** — three actor types coordinate via message passing within the swactor runtime.
|
||||
- **Transport-agnostic** — protocol messages defined as `NetworkMessage` types; MVP uses iroh (QUIC + NAT hole-punch + encryption).
|
||||
- **Pluggable storage** — `StorageBackend` trait abstracts I/O for filesystem (MVP), IndexedDB (browser), etc.
|
||||
|
||||
## 2. Terminology
|
||||
|
||||
| Term | Definition |
|
||||
|------|-----------|
|
||||
| **Object** | Content-addressed blob identified by `blake3(blob_bytes)`. May carry an optional human-readable name as metadata. |
|
||||
| **Blob** | The raw byte content of an object. |
|
||||
| **Chunk** | A fixed-size (1 MB default) slice of a blob, identified by its blake3 content hash. |
|
||||
| **Manifest** | An ordered list of `ChunkRef`s describing how to reassemble an object from chunks. Stored under the object's content hash. |
|
||||
| **ContentHash** | 32-byte blake3 digest. Primary identifier for blobs and DHT key. |
|
||||
| **ObjectEntry** | Metadata record: content hash, optional name, owner node, tags. |
|
||||
| **DHT overlay** | A Kademlia distributed hash table for object metadata, separate from the actor directory DHT. Keys are `blake3(blob_bytes)`. |
|
||||
| **StorageBackend** | Trait abstracting chunk and manifest I/O for pluggable backends (filesystem, IndexedDB, etc.). |
|
||||
| **Node** | A device running the swactor runtime with a datastore actor set (BlobStoreActor + MetadataActor). |
|
||||
|
||||
## 3. Data Model
|
||||
|
||||
### 3.1 ContentHash
|
||||
|
||||
```
|
||||
ContentHash = blake3(data)[0..32] // 32 bytes
|
||||
```
|
||||
|
||||
- **Hashing algorithm:** blake3 — 2-3x faster than sha256, tree-hashable (parallel hashing of large chunks), same 32-byte output. Supports streaming hashing for large blobs via `blake3::Hasher`.
|
||||
- **Display:** first 8 bytes as hex + ellipsis (e.g. `a1b2c3d4e5f6a7b8…`).
|
||||
- **XOR distance:** bitwise XOR of the 32-byte arrays, used for Kademlia routing in the metadata DHT.
|
||||
|
||||
### 3.2 ObjectEntry
|
||||
|
||||
```
|
||||
ObjectEntry {
|
||||
content_hash: ContentHash, // blake3(entire_blob) — primary identifier
|
||||
name: Option<String>, // Optional flat string, not a path
|
||||
node_id: NodeId, // Node that stores the object
|
||||
tags: BTreeMap<String, String>, // User-defined key-value tags
|
||||
size_bytes: u64, // Total object size
|
||||
created_at: u64, // Wall-clock creation time (informational)
|
||||
}
|
||||
```
|
||||
|
||||
No conflict resolution is needed — content hashes are unique identifiers. Storing the same blob twice is a no-op (same content hash). Different blobs always have different content hashes.
|
||||
|
||||
### 3.3 ObjectManifest
|
||||
|
||||
```
|
||||
ObjectManifest {
|
||||
content_hash: ContentHash, // blake3(entire_blob) — NOT the hash of this manifest
|
||||
chunks: Vec<ChunkRef>, // Ordered list of chunks
|
||||
total_size: u64, // Total object size in bytes
|
||||
chunk_size: u32, // Fixed chunk size used (e.g. 1MB)
|
||||
content_type: Option<String>, // MIME type
|
||||
}
|
||||
|
||||
ChunkRef {
|
||||
hash: ContentHash, // Content hash of chunk data
|
||||
offset: u64, // Byte offset in original object
|
||||
size: u32, // Actual size (last chunk may be smaller)
|
||||
}
|
||||
```
|
||||
|
||||
The `content_hash` field is `blake3(entire_blob)`, computed via a streaming hasher alongside chunking. The manifest is stored and looked up using this content hash as the key.
|
||||
|
||||
### 3.4 Storage Backend
|
||||
|
||||
The `StorageBackend` trait abstracts all chunk and manifest I/O:
|
||||
|
||||
```rust
|
||||
pub trait StorageBackend: Send {
|
||||
fn write_chunk(&mut self, hash: &ContentHash, data: &[u8]) -> Result<(), io::Error>;
|
||||
fn read_chunk(&self, hash: &ContentHash) -> Result<Option<Vec<u8>>, io::Error>;
|
||||
fn delete_chunk(&mut self, hash: &ContentHash) -> Result<(), io::Error>;
|
||||
fn has_chunk(&self, hash: &ContentHash) -> bool;
|
||||
fn list_chunks(&self) -> Vec<ContentHash>;
|
||||
fn write_manifest(&mut self, manifest: &ObjectManifest) -> Result<(), io::Error>;
|
||||
fn read_manifest(&self, content_hash: &ContentHash) -> Result<Option<ObjectManifest>, io::Error>;
|
||||
fn delete_manifest(&mut self, content_hash: &ContentHash) -> Result<(), io::Error>;
|
||||
}
|
||||
```
|
||||
|
||||
#### MVP: FilesystemBackend
|
||||
|
||||
Two-level directory sharding to avoid huge directories:
|
||||
|
||||
```
|
||||
{storage_path}/
|
||||
├── chunks/
|
||||
│ └── {hex[0..2]}/
|
||||
│ └── {hex[2..4]}/
|
||||
│ └── {full_hex_hash} # Raw chunk bytes
|
||||
└── manifests/
|
||||
└── {hex[0..2]}/
|
||||
└── {hex[2..4]}/
|
||||
└── {full_hex_hash} # JSON-serialized ObjectManifest
|
||||
```
|
||||
|
||||
Example: chunk with hash `abcdef12...` is stored at `chunks/ab/cd/abcdef12...`.
|
||||
|
||||
All writes are fsynced before acknowledging.
|
||||
|
||||
## 4. Content Addressing
|
||||
|
||||
### 4.1 Chunking Algorithm
|
||||
|
||||
Fixed-size chunking (MVP):
|
||||
|
||||
1. Read the input file in `chunk_size` byte blocks (default: 1,048,576 = 1 MB).
|
||||
2. For each block, compute `ContentHash::of(block)`.
|
||||
3. Store each chunk via the `StorageBackend`.
|
||||
4. Build a `Vec<ChunkRef>` with sequential offsets.
|
||||
5. Compute `content_hash = blake3(entire_blob)` using a streaming hasher fed alongside chunking.
|
||||
6. Create the `ObjectManifest` with this `content_hash` and store it via the `StorageBackend` keyed by `content_hash`.
|
||||
|
||||
The last chunk may be smaller than `chunk_size`.
|
||||
|
||||
### 4.2 Reassembly
|
||||
|
||||
1. Read the `ObjectManifest` (by its `content_hash`).
|
||||
2. For each `ChunkRef` in order, read the chunk by `hash`.
|
||||
3. Concatenate all chunk data to reconstruct the original blob.
|
||||
4. Verify: `blake3(reassembled) == content_hash` (optional integrity check).
|
||||
|
||||
## 5. Metadata DHT
|
||||
|
||||
> **Status:** Types and routing table logic exist in the `distribution` crate. `MetadataActor` has a dissemination queue (`enqueue`/`take_pending`) and peer-to-peer replication via `SetPeers` + `DisseminateTick`. Verified in local multi-node simulation. Full Kademlia iterative lookup (FIND_VALUE with α-parallel queries) is not yet implemented — dissemination is epidemic/gossip-style.
|
||||
|
||||
### 5.1 Overlay Design
|
||||
|
||||
The metadata DHT is a **separate Kademlia overlay** from the actor directory. It stores `ObjectEntry` records keyed by `blake3(blob_bytes)` — the content hash of the entire blob.
|
||||
|
||||
This separation ensures:
|
||||
- Object metadata routing doesn't interfere with actor discovery.
|
||||
- Different replication factors can be used (objects may be stored on fewer nodes).
|
||||
- The DHT can be independently tuned for the metadata workload.
|
||||
|
||||
### 5.2 Key Mapping
|
||||
|
||||
```
|
||||
DHT key = blake3(blob_bytes) = entry.content_hash
|
||||
```
|
||||
|
||||
### 5.3 Store Flow
|
||||
|
||||
When storing object metadata:
|
||||
1. Use `key = entry.content_hash`.
|
||||
2. Find the `k` closest nodes to `key` in the metadata DHT routing table.
|
||||
3. Send `StoreObjectRequest { entry }` to each of the `k` closest nodes.
|
||||
|
||||
### 5.4 Lookup Flow
|
||||
|
||||
When looking up object metadata:
|
||||
1. Send `FindObjectRequest { content_hash }` to the `α` closest known nodes.
|
||||
2. Each node responds with either `Found(ObjectEntry)` or `Closer(Vec<(NodeId, SocketAddr)>)`.
|
||||
3. Continue querying closer nodes until convergence.
|
||||
|
||||
No merge step is needed — content hashes are unique identifiers.
|
||||
|
||||
## 6. Protocol Flows
|
||||
|
||||
### 6.1 PUT — Store an Object
|
||||
|
||||
```
|
||||
User MetadataActor BlobStoreActor
|
||||
│ │ │
|
||||
│─── PutObject ────────────>│ │
|
||||
│ │ │
|
||||
│ │ (chunk the file, │
|
||||
│ │ stream blake3 hash) │
|
||||
│ │ │
|
||||
│ │─── WriteChunk ────────>│
|
||||
│ │<── ChunkStored ────────│ (repeat for each chunk)
|
||||
│ │ │
|
||||
│ │─── WriteManifest ─────>│
|
||||
│ │<── ManifestStored ─────│
|
||||
│ │ │
|
||||
│ │ (create ObjectEntry, │
|
||||
│ │ store in local index,│
|
||||
│ │ enqueue for DHT │
|
||||
│ │ dissemination) │
|
||||
│ │ │
|
||||
│<── PutOk {content_hash} ─│ │
|
||||
```
|
||||
|
||||
### 6.2 GET — Retrieve an Object (Local)
|
||||
|
||||
```
|
||||
User MetadataActor BlobStoreActor
|
||||
│ │ │
|
||||
│─── GetObject ────────────>│ │
|
||||
│ {content_hash} │ │
|
||||
│ │ (lookup content_hash │
|
||||
│ │ in local index) │
|
||||
│ │ │
|
||||
│<── GetOk { entry, │ │
|
||||
│ manifest } ──────│ │
|
||||
│ │
|
||||
│ (for each chunk in manifest) │
|
||||
│───────────── ReadChunk ───────────────────────────>│
|
||||
│<────────────── ChunkOk ───────────────────────────│
|
||||
│ │
|
||||
│ (reassemble chunks into original file) │
|
||||
```
|
||||
|
||||
### 6.3 GET — Retrieve an Object (Remote)
|
||||
|
||||
> **Status:** `TransferActor` state machine is functional and stores received chunks to the local `BlobStoreActor`. Chunks must be fed externally (via `ChunkReceived` messages). Automatic chunk pulling from remote nodes is not yet implemented — the test harness or a future network adapter plays the "pull" role. Verified in multi-node simulation.
|
||||
|
||||
```
|
||||
User MetadataActor TransferActor Remote BlobStore
|
||||
│ │ │ │
|
||||
│─ GetObject ──>│ │ │
|
||||
│ {content_hash}│ │ │
|
||||
│ │ (not in local │ │
|
||||
│ │ index; DHT │ │
|
||||
│ │ lookup) │ │
|
||||
│ │ │ │
|
||||
│ │─ StartDownload ───>│ │
|
||||
│ │ │ │
|
||||
│ │ │── GetChunkRequest ─>│
|
||||
│ │ │<─ GetChunkResponse ─│
|
||||
│ │ │ │
|
||||
│ │ │ (repeat for each │
|
||||
│ │ │ chunk) │
|
||||
│ │ │ │
|
||||
│ │<─ TransferComplete │ │
|
||||
│ │ │ │
|
||||
│<── GetOk ────│ │ (stops self) │
|
||||
```
|
||||
|
||||
### 6.4 DELETE — Remove an Object
|
||||
|
||||
```
|
||||
User MetadataActor
|
||||
│ │
|
||||
│─── DeleteObject ─────────>│
|
||||
│ {content_hash} │
|
||||
│ │
|
||||
│ │ (remove from local )
|
||||
│ │ (index, best-effort )
|
||||
│ │ (notify DHT peers )
|
||||
│ │
|
||||
│<── DeleteOk │
|
||||
│ {content_hash} ────────│
|
||||
```
|
||||
|
||||
Chunk data is **not** immediately deleted. Unreferenced chunks are cleaned up during GC sweeps (see Section 10).
|
||||
|
||||
### 6.5 LIST — List Objects (Local)
|
||||
|
||||
```
|
||||
User MetadataActor
|
||||
│ │
|
||||
│─── ListLocal ────────────>│
|
||||
│ {name_filter} │
|
||||
│ │
|
||||
│ │ (filter local index )
|
||||
│ │ (by name substring )
|
||||
│ │
|
||||
│<── ListOk { entries } ───│
|
||||
```
|
||||
|
||||
### 6.6 LIST — List Objects (Swarm-Wide)
|
||||
|
||||
> **Status:** `ListSwarm` currently delegates to `ListLocal` (returns local entries only). Fan-out to peer MetadataActors is not yet wired. Swarm-wide listing is verified in simulation by querying each node and merging results in the test harness.
|
||||
|
||||
```
|
||||
User MetadataActor Remote MetadataActors
|
||||
│ │ │
|
||||
│─ ListSwarm ──>│ │
|
||||
│ {name_filter} │ │
|
||||
│ │── ListObjectsRequest ─>│ (fan-out to all known
|
||||
│ │<─ ListObjectsResponse ─│ alive nodes)
|
||||
│ │ │
|
||||
│ │ (merge all results, │
|
||||
│ │ deduplicate by │
|
||||
│ │ content hash) │
|
||||
│ │ │
|
||||
│<── ListOk ───│ │
|
||||
```
|
||||
|
||||
## 7. Actor Architecture
|
||||
|
||||
> **Status:** All three actor types are fully implemented and tested. `DatastoreNode` coordinator routes commands to internal actors. 83+ tests across 8 test files verify single-node operations. Multi-node dissemination and cross-node transfers verified in simulation.
|
||||
|
||||
### 7.1 BlobStoreActor
|
||||
|
||||
**Responsibility:** Chunk and manifest I/O via `StorageBackend` trait.
|
||||
|
||||
- **State:** `Box<dyn StorageBackend>`
|
||||
- **Lifecycle:** Long-lived, one per node.
|
||||
- **Guarantees:** Delegates to backend; filesystem backend fsyncs before acknowledging.
|
||||
|
||||
**Message types:** `BlobStoreMsg` (see `messages.rs`)
|
||||
|
||||
### 7.2 MetadataActor
|
||||
|
||||
**Responsibility:** Object metadata index, DHT routing.
|
||||
|
||||
- **State:** Local object index (`HashMap<ContentHash, ObjectEntry>`), manifest cache, dissemination queue.
|
||||
- **Lifecycle:** Long-lived, one per node.
|
||||
- **Coordinates with:** BlobStoreActor (for manifest storage), remote MetadataActors (DHT operations).
|
||||
|
||||
**Message types:** `MetadataMsg` (see `messages.rs`)
|
||||
|
||||
### 7.3 TransferActor
|
||||
|
||||
**Responsibility:** Downloading an object (all its chunks) from a remote node.
|
||||
|
||||
- **State:** Manifest, pending/received chunk sets, retry counts.
|
||||
- **Lifecycle:** Ephemeral — spawned per download, self-terminates on completion/failure/cancel.
|
||||
- **Coordinates with:** Remote BlobStoreActor (chunk requests), local BlobStoreActor (chunk storage).
|
||||
|
||||
**Message types:** `TransferMsg` (see `messages.rs`)
|
||||
|
||||
## 8. Wire Protocol
|
||||
|
||||
> **Status:** All message types are defined with `NetworkMessage` implementations and stable type tags. Serialization is JSON (serde). No transport integration yet — messages are passed directly via actor addresses in simulation.
|
||||
|
||||
### 8.1 Message Types
|
||||
|
||||
All inter-node messages implement `NetworkMessage` with a stable `type_tag()`:
|
||||
|
||||
| Message | type_tag | Direction |
|
||||
|---------|----------|-----------|
|
||||
| `GetChunkRequest` | `swactor_datastore::GetChunkRequest` | requester → holder |
|
||||
| `GetChunkResponse` | `swactor_datastore::GetChunkResponse` | holder → requester |
|
||||
| `StoreObjectRequest` | `swactor_datastore::StoreObjectRequest` | writer → DHT nodes |
|
||||
| `FindObjectRequest` | `swactor_datastore::FindObjectRequest` | reader → DHT nodes |
|
||||
| `FindObjectResponse` | `swactor_datastore::FindObjectResponse` | DHT node → reader |
|
||||
| `GetManifestRequest` | `swactor_datastore::GetManifestRequest` | requester → holder |
|
||||
| `GetManifestResponse` | `swactor_datastore::GetManifestResponse` | holder → requester |
|
||||
| `ListObjectsRequest` | `swactor_datastore::ListObjectsRequest` | requester → remote node |
|
||||
| `ListObjectsResponse` | `swactor_datastore::ListObjectsResponse` | remote node → requester |
|
||||
|
||||
`FindObjectRequest` contains a `content_hash` field (the `blake3(blob_bytes)` key).
|
||||
|
||||
### 8.2 Serialization
|
||||
|
||||
MVP: serde JSON for all messages. Binary format (bincode or msgpack) planned for later to reduce overhead, especially for `GetChunkResponse` which carries large payloads.
|
||||
|
||||
### 8.3 Framing
|
||||
|
||||
Messages are framed over iroh QUIC streams:
|
||||
- Each request/response pair uses a single bidirectional stream.
|
||||
- Message format: `[4-byte length (big-endian)][JSON payload]`.
|
||||
|
||||
## 9. Naming
|
||||
|
||||
Names are **optional flat strings** — human-readable labels attached to objects as metadata.
|
||||
|
||||
- Names are not keys. The content hash is the only primary identifier.
|
||||
- Multiple objects can share the same name. They are distinguished by content hash.
|
||||
- Names are simple strings (e.g. `"vacation.jpg"`, `"backup-2024-01"`). No path hierarchy, no separators enforced.
|
||||
- No conflict resolution is needed — different content always produces different content hashes.
|
||||
|
||||
## 10. Garbage Collection
|
||||
|
||||
> **Status:** Fully implemented. `MetadataActor::gc_tick()` builds a referenced chunk set from all local manifests and sends `GcUnreferenced` to `BlobStoreActor`. Verified with 6 GC-specific tests including deduplication safety, interval gating, and empty-store edge case.
|
||||
|
||||
### 10.1 Entry Removal
|
||||
|
||||
Deleting an object:
|
||||
1. Remove the `ObjectEntry` from the local index.
|
||||
2. Best-effort notify DHT peers to remove their replicas.
|
||||
3. Remove the local manifest.
|
||||
|
||||
### 10.2 Chunk Reference Counting
|
||||
|
||||
Unreferenced chunk cleanup:
|
||||
|
||||
1. Build a referenced set: union of all chunk hashes from all local manifest entries.
|
||||
2. Send `BlobStoreMsg::GcUnreferenced { referenced }` to the BlobStoreActor.
|
||||
3. BlobStoreActor diffs its chunk list against the referenced set and deletes unreferenced chunks.
|
||||
|
||||
**Safety:** A chunk may be referenced by multiple objects (deduplication). Only delete when zero references remain.
|
||||
|
||||
### 10.3 GC Schedule
|
||||
|
||||
- `MetadataActor` runs `gc_tick()` every tick. Actual GC sweep happens every `gc_interval` ticks (default: 1000).
|
||||
- Chunk GC is triggered less frequently (order of minutes) to avoid overhead.
|
||||
|
||||
## 11. Failure Modes
|
||||
|
||||
### 11.1 Node Offline
|
||||
|
||||
- **Metadata persists** in the DHT (replicated to k-closest nodes). Lookups succeed as long as any replica is alive.
|
||||
- **Chunk fetches fail** if the only copy is on the offline node. The TransferActor retries once, then reports failure.
|
||||
- **Recovery:** When the node comes back, its metadata is re-disseminated (anti-entropy).
|
||||
|
||||
### 11.2 Transfer Interrupted
|
||||
|
||||
- **Partial state:** Some chunks may be written to the local BlobStoreActor before the transfer fails.
|
||||
- **Cleanup:** Partially downloaded chunks are not harmful — they're content-addressed and may be useful for future downloads. Unreferenced chunks are cleaned up by GC.
|
||||
- **Retry:** The user can retry the GET, and only missing chunks need to be fetched (future optimization).
|
||||
|
||||
### 11.3 DHT Inconsistency
|
||||
|
||||
- **Stale metadata:** A node may serve an outdated ObjectEntry. Anti-entropy dissemination ensures replicas converge.
|
||||
- Content addressing eliminates write conflicts — storing the same content hash twice is idempotent.
|
||||
|
||||
### 11.4 Disk Full
|
||||
|
||||
- `StorageBackend::write_chunk` fails with an I/O error, which is propagated back to the requester as `DatastoreResponse::Error`.
|
||||
- No partial writes — fsync ensures atomicity (filesystem backend).
|
||||
|
||||
## 12. CLI Interface
|
||||
|
||||
> **Status:** Command types defined in `src/cli.rs`. Parser, dispatcher, and `[[bin]]` target not yet implemented. Planned for a follow-up session.
|
||||
|
||||
```
|
||||
swactor-store put <local-path> [--name <label>] [--tag key=value...]
|
||||
Store a local file as a distributed object.
|
||||
Returns the content hash of the stored object.
|
||||
--name sets an optional human-readable label.
|
||||
|
||||
swactor-store get <content-hash>[@<node>] [--output <local-path>]
|
||||
Retrieve an object by content hash. Fetches from the specified node or discovers via DHT.
|
||||
--output defaults to the object's name (if set) in the current directory.
|
||||
|
||||
swactor-store delete <content-hash>
|
||||
Remove an object from the local index and notify DHT peers.
|
||||
|
||||
swactor-store list [--name <substring>] [--node <node-name>] [--all]
|
||||
List objects. --name filters by name substring. --all queries all nodes (swarm-wide). Default is local.
|
||||
|
||||
swactor-store status
|
||||
Show node info: identity, chunk count, storage usage.
|
||||
```
|
||||
|
||||
## 13. Browser API
|
||||
|
||||
> **Status:** Not started. Separate milestone.
|
||||
|
||||
WASM-exposed functions for browser integration:
|
||||
|
||||
```
|
||||
list_objects(name_filter: Option<String>) -> Vec<ObjectEntry>
|
||||
List objects visible to this node, optionally filtered by name.
|
||||
|
||||
get_object(content_hash: ContentHash) -> Result<Vec<u8>, Error>
|
||||
Download and reassemble an object by content hash.
|
||||
|
||||
put_object(data: Vec<u8>, name: Option<String>) -> Result<ContentHash, Error>
|
||||
Chunk, store, and register an object. Returns the content hash.
|
||||
|
||||
delete_object(content_hash: ContentHash) -> Result<(), Error>
|
||||
Remove an object from the local index.
|
||||
|
||||
get_node_status() -> NodeStatus
|
||||
Node identity, chunk count, connected peers.
|
||||
```
|
||||
|
||||
These map directly to the MetadataActor message types. The WASM runtime handles serialization across the JS/Rust boundary.
|
||||
|
|
@ -1,317 +0,0 @@
|
|||
# swactor-datastore: Development History & Status
|
||||
|
||||
## Overview
|
||||
|
||||
`swactor-datastore` is a distributed personal file/blob storage protocol for small trusted clusters (laptop, phone, browser). It provides content-hash-first addressing with immutable content-addressed objects, replicated via epidemic metadata dissemination across peers.
|
||||
|
||||
The implementation is organized as a single Rust crate (`crates/datastore/`) built on the `swactor` actor runtime. It was developed in 7 ordered modules (local single-node operations) followed by a multi-node simulation phase.
|
||||
|
||||
**Current state: 93 tests across 9 test files, all passing. Zero warnings.**
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ DatastoreNode │ Coordinator/facade
|
||||
│ (single entry point for callers) │
|
||||
├────────────────────┬────────────────────────────────┤
|
||||
│ MetadataActor │ BlobStoreActor │ Long-lived, one per node
|
||||
│ (object index, │ (chunk & manifest I/O │
|
||||
│ dissemination, │ via StorageBackend) │
|
||||
│ GC orchestration)│ │
|
||||
├────────────────────┴────────────────────────────────┤
|
||||
│ TransferActor (ephemeral) │ One per download
|
||||
│ (chunk tracking, retry, self-termination) │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ StorageBackend trait │ Pluggable I/O
|
||||
│ FilesystemBackend │ InMemoryBackend │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ Chunking Engine (pure functions) │ No I/O, deterministic
|
||||
│ chunk_blob · reassemble_blob · verify_integrity │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Core Design Principles
|
||||
|
||||
- **Content-hash-first addressing** -- every object identified by `blake3(blob_bytes)`.
|
||||
- **Immutable content-addressed objects** -- no write conflicts by construction.
|
||||
- **Names are metadata** -- optional flat strings, not keys.
|
||||
- **Separation of data and metadata** -- chunks are large opaque blobs; metadata is small and gossiped.
|
||||
- **Actor-based** -- three actor types coordinate via message passing.
|
||||
- **Transport-agnostic** -- protocol messages defined as `NetworkMessage` types.
|
||||
- **Pluggable storage** -- `StorageBackend` trait abstracts I/O.
|
||||
|
||||
---
|
||||
|
||||
## Module-by-Module Development History
|
||||
|
||||
### Module 1: Chunking Engine
|
||||
|
||||
**What:** Pure functions for content-addressed blob chunking and reassembly. `chunk_blob()`, `reassemble_blob()`, `verify_integrity()`, plus `ContentHash`, `ObjectManifest`, `ChunkRef` types.
|
||||
|
||||
**Key decisions:**
|
||||
- Fixed-size chunking over content-defined chunking (simpler, deterministic; CDC dedup unnecessary for small clusters)
|
||||
- BLAKE3 for all hashing (3-7 GB/s, 32-byte output matching `NodeId`)
|
||||
- Whole-blob hash as content hash rather than Merkle root of chunk hashes
|
||||
- Empty blob produces a valid zero-chunk manifest
|
||||
|
||||
**Tests:** 13 (10 scenario + 3 proptest). Round-trips, edge cases, integrity verification, determinism.
|
||||
|
||||
**Files:** `src/chunking.rs`, `src/types.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 2: Storage Backend
|
||||
|
||||
**What:** `StorageBackend` trait with two implementations: `FilesystemBackend` (2-level hex-sharded dirs, fsync-on-write) and `InMemoryBackend` (HashMap-based for tests/WASM).
|
||||
|
||||
**Key decisions:**
|
||||
- 2-level hex sharding (65,536 possible directories) to avoid hot directories
|
||||
- In-memory chunk index for O(1) `has_chunk` lookups, populated via scan-on-init
|
||||
- JSON manifest serialization for debuggability
|
||||
- `Send` but not `Sync` on the trait (single-actor ownership)
|
||||
- Idempotent writes and deletes
|
||||
|
||||
**Tests:** 12 (9 parameterized across both backends + 2 FS-only + 1 proptest).
|
||||
|
||||
**Files:** `src/storage/mod.rs`, `src/storage/in_memory.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 3: BlobStoreActor
|
||||
|
||||
**What:** Message-driven actor wrapping `Box<dyn StorageBackend>` for chunk/manifest CRUD plus garbage collection. Also introduced the shared test harness (`tests/common/mod.rs`).
|
||||
|
||||
**Key decisions:**
|
||||
- Thin delegation -- actor adds no logic beyond message dispatch
|
||||
- Explicit `reply_to` pattern (tell, not ask) for response routing
|
||||
- Fire-and-forget deletes and GC (no reply needed)
|
||||
- `Box<dyn StorageBackend>` for dynamic dispatch (one backend per instance)
|
||||
- Single-threaded tick-based testing for determinism
|
||||
|
||||
**Tests:** 7 scenario tests through the swactor runtime.
|
||||
|
||||
**Established patterns:** `reply_to` pattern, shared test harness with `test_runtime()`, `tick_n()`, `tick_until_recv()`, `DatastoreHarness`.
|
||||
|
||||
**Files:** `src/actors/blob_store.rs`, `tests/blob_store_tests.rs`, `tests/common/mod.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 4: MetadataActor
|
||||
|
||||
**What:** Object metadata index (`HashMap<ContentHash, ObjectEntry>`), manifest cache, SWIM-inspired gossip dissemination queue. Handles local CRUD, DHT protocol messages (`HandleFindObject`, `HandleStoreObject`), and GC tick orchestration.
|
||||
|
||||
**Key decisions:**
|
||||
- Node ID stamping on `PutObject` (prevents spoofing; remote entries retain original owner)
|
||||
- Idempotent DHT store (insert-if-absent semantics)
|
||||
- Synthetic empty manifest for `HandleFindObject` when manifest is missing
|
||||
- Separate `GetObject` (local, error on missing manifest) vs `HandleFindObject` (DHT, synthesizes empty manifest)
|
||||
- SWIM-style dissemination with budget `Lambda * ceil(log2(n))`, Lambda=3
|
||||
|
||||
**Tests:** 10 scenario tests covering CRUD, DHT operations, idempotency, lifecycle.
|
||||
|
||||
**Files:** `src/actors/metadata.rs`, `tests/metadata_tests.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 5: TransferActor
|
||||
|
||||
**What:** Ephemeral per-download actor. Tracks pending/received chunks, forwards received chunks to BlobStoreActor, implements per-chunk retry, self-terminates on completion/failure/cancel.
|
||||
|
||||
**Key decisions:**
|
||||
- Ephemeral actor pattern (one per download, isolates transfer state)
|
||||
- Passive design -- chunks driven externally via `ChunkReceived`/`ChunkFailed` (decoupled from networking)
|
||||
- Whole-transfer failure on any chunk exhausting retries
|
||||
- `max_retries` defaults to 1 (first failure allows retry, second aborts)
|
||||
- Fire-and-forget chunk persistence (ChunkStored reply silently dropped)
|
||||
|
||||
**Tests:** 10 scenario tests covering state machine transitions, retry logic, cancellation, data recovery.
|
||||
|
||||
**Files:** `src/actors/transfer.rs`, `tests/transfer_tests.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 6: DatastoreNode Coordinator
|
||||
|
||||
**What:** Facade actor encapsulating BlobStoreActor + MetadataActor behind a single address. Routes 6 user-facing commands and 5 network protocol variants.
|
||||
|
||||
**Key decisions:**
|
||||
- Pass-through `reply_to` pattern (responses go directly to caller, coordinator never intercepts)
|
||||
- Inline chunking in `handle_put` (synchronous, no async coordination)
|
||||
- Fire-and-forget chunk writes (same pattern as TransferActor)
|
||||
- Immutable state after construction
|
||||
- `Put` uses `data: Vec<u8>` not `PathBuf` (testable, WASM-compatible)
|
||||
|
||||
**Tests:** 12 scenario tests through `NodeHarness`.
|
||||
|
||||
**Files:** `src/actors/datastore_node.rs`, `tests/datastore_node_tests.rs`
|
||||
|
||||
---
|
||||
|
||||
### Module 7: Garbage Collection
|
||||
|
||||
**What:** Completed `MetadataActor::gc_tick()` to build a referenced chunk set from all manifests and send `GcUnreferenced` to BlobStoreActor for orphan cleanup.
|
||||
|
||||
**Key decisions:**
|
||||
- `blob_store_addr = None` guard for backward compatibility (GC no-ops when not wired)
|
||||
- Fire-and-forget `GcUnreferenced` (no reply needed)
|
||||
- `spawn_metadata_with_config()` helper to wire blob_store_addr before spawning
|
||||
- Mark-and-sweep: union of all chunk hashes from all manifests = referenced set
|
||||
|
||||
**Tests:** 6 scenario tests covering cleanup, preservation, deduplication safety, interval gating, empty-store edge case.
|
||||
|
||||
**Files:** `src/actors/metadata.rs` (delta), `tests/gc_tests.rs`, `tests/common/mod.rs` (GcHarness)
|
||||
|
||||
---
|
||||
|
||||
### Multi-Node Simulation (Phases 3-4)
|
||||
|
||||
**What:** Wired up MetadataActor for peer-to-peer metadata dissemination. Added `SetPeers` and `DisseminateTick` messages. Created `MultiNodeHarness` for simulating clusters on a single Runtime. Extended `HandleStoreObject` to carry manifests alongside entries for full metadata replication.
|
||||
|
||||
**Key decisions:**
|
||||
- Single Runtime for simulation -- all nodes' actors share one Runtime; actor addresses are globally unique so cross-node messaging "just works" via `ctx.send()`
|
||||
- MetadataActor owns peer relationships (simpler than routing through DatastoreNode)
|
||||
- Manifest dissemination alongside entry dissemination (peers receive both)
|
||||
- TransferActor stays passive -- tests feed chunks from remote BlobStoreActor (test harness plays the "network adapter" role)
|
||||
- No automatic remote GET orchestration yet -- DatastoreNode remains a stateless router
|
||||
|
||||
**New messages:**
|
||||
- `MetadataMsg::SetPeers { peers: Vec<ActorAddress> }`
|
||||
- `MetadataMsg::DisseminateTick`
|
||||
- `MetadataMsg::HandleStoreObject` extended with `manifest: Option<ObjectManifest>`
|
||||
|
||||
**Tests:** 10 new scenario tests in `tests/multi_node_tests.rs`:
|
||||
|
||||
| # | Test | Verifies |
|
||||
|---|------|----------|
|
||||
| 1 | `metadata_replicates_to_peer_after_dissemination` | Put on 0, disseminate, node 1 finds it |
|
||||
| 2 | `metadata_replicates_to_all_peers_in_3_node_cluster` | Full cluster replication |
|
||||
| 3 | `dissemination_budget_expires_after_enough_rounds` | Budget exhaustion, fresh entries still work |
|
||||
| 4 | `delete_on_origin_does_not_propagate_to_peers` | Delete is local only |
|
||||
| 5 | `duplicate_put_via_dissemination_is_idempotent` | No duplicate entries on peer |
|
||||
| 6 | `find_object_on_peer_after_dissemination` | HandleFindObject succeeds on peer |
|
||||
| 7 | `chunk_transfer_from_remote_blob_store` | TransferActor pulls chunks cross-node |
|
||||
| 8 | `full_remote_get_scenario` | End-to-end: put on 0, disseminate, transfer 0->1, reassemble matches |
|
||||
| 9 | `list_across_all_nodes_finds_objects_from_any_node` | Simulated ListSwarm fan-out |
|
||||
| 10 | `gc_on_one_node_does_not_affect_other_nodes` | GC isolation between nodes |
|
||||
|
||||
**Files:** `src/messages.rs`, `src/actors/metadata.rs`, `tests/common/mod.rs` (MultiNodeHarness), `tests/multi_node_tests.rs`
|
||||
|
||||
---
|
||||
|
||||
## Code Quality Pass
|
||||
|
||||
Alongside the multi-node work, a cleanup pass was performed:
|
||||
|
||||
- **PROTOCOL.md** -- Added honest `> Status:` annotations to sections 5 (Metadata DHT), 6.3 (Remote GET), 6.6 (ListSwarm), 7 (Actor Architecture), 8 (Wire Protocol), 10 (GC), 12 (CLI), and 13 (Browser API)
|
||||
- **metadata.rs** -- Updated stale `ListSwarm` "MVP" comment
|
||||
- **transfer.rs** -- Updated architecture comments describing simulation-ready passive design
|
||||
- **tests/common/mod.rs** -- Removed 3 unused imports (`ActorInterface`, `Ctx`, `DatastoreNodeMsg`)
|
||||
|
||||
---
|
||||
|
||||
## Test Summary
|
||||
|
||||
| Test File | Count | What |
|
||||
|-----------|-------|------|
|
||||
| `chunking_tests.rs` | 13 | Pure function round-trips, edge cases, proptests |
|
||||
| `storage_tests.rs` | 12 | Backend CRUD, parameterized across FS + InMemory, proptests |
|
||||
| `blob_store_tests.rs` | 7 | Actor-level chunk/manifest CRUD, GC |
|
||||
| `metadata_tests.rs` | 10 | Object index, DHT protocol, lifecycle |
|
||||
| `transfer_tests.rs` | 10 | Download state machine, retry, cancel |
|
||||
| `datastore_node_tests.rs` | 12 | Coordinator routing, network protocol |
|
||||
| `datastore_tests.rs` | 13 | Content-addressing properties, proptests |
|
||||
| `gc_tests.rs` | 6 | Mark-and-sweep GC, dedup safety |
|
||||
| `multi_node_tests.rs` | 10 | Dissemination, cross-node transfer, GC isolation |
|
||||
| **Total** | **93** | |
|
||||
|
||||
**Testing philosophy:** Scenario/story tests first, property-based tests for invariants, contract tests for serialization. No white-box/structural tests. Low coupling to internals -- tests should survive a refactor.
|
||||
|
||||
---
|
||||
|
||||
## Future Work
|
||||
|
||||
### Near-Term (Next Sessions)
|
||||
|
||||
**CLI Implementation (Phase 2)**
|
||||
- Parser and dispatcher using `clap`
|
||||
- `[[bin]]` target in Cargo.toml
|
||||
- `ContentHash::from_hex()` for CLI input
|
||||
- Commands: `put <path>`, `fetch <hash>` (metadata only), `get <hash> --output <path>` (full download), `delete <hash>`, `list`, `status`
|
||||
- Single-node only (no networking); spawns its own actor set
|
||||
- Follow `crates/node/src/main.rs` pattern
|
||||
|
||||
**ListSwarm Fan-Out**
|
||||
- Currently delegates to `ListLocal`. Wire MetadataActor to query all peers and merge/deduplicate results by content hash.
|
||||
|
||||
**Automatic Remote GET Orchestration**
|
||||
- Currently, remote GET requires manual orchestration (test harness or external driver reads chunks from remote BlobStore and feeds them to TransferActor).
|
||||
- DatastoreNode needs to become stateful: detect local miss, query peers via `HandleFindObject`, spawn TransferActor, coordinate chunk pulling from the remote BlobStoreActor.
|
||||
- This is the largest remaining architectural change for local functionality.
|
||||
|
||||
### Medium-Term
|
||||
|
||||
**Transport Integration (iroh/QUIC)**
|
||||
- Wire `NetworkMessage` types to actual network transport.
|
||||
- DatastoreNode gains peer management (`AddPeer`/`RemovePeer`) at the node level.
|
||||
- Replace simulation-only direct actor addressing with network-routed messages.
|
||||
- Framing: `[4-byte length (big-endian)][JSON payload]` over QUIC streams.
|
||||
|
||||
**Anti-Entropy / Repair**
|
||||
- When a node comes back online, re-disseminate its metadata to peers.
|
||||
- Periodic full-index comparison between peers to detect and repair drift.
|
||||
|
||||
**Active Chunk Pulling in TransferActor**
|
||||
- `StartDownload` sends `GetChunkRequest` to the source node for each chunk.
|
||||
- Currently passive (chunks fed externally); make it drive its own downloads.
|
||||
|
||||
**Parallel Chunk Fetching**
|
||||
- TransferActor currently fetches sequentially. Add configurable concurrency (`max_concurrent_transfers` in config already exists).
|
||||
|
||||
### Longer-Term
|
||||
|
||||
**Browser API (WASM)**
|
||||
- Expose `list_objects`, `get_object`, `put_object`, `delete_object`, `get_node_status` via WASM bindings.
|
||||
- Use `InMemoryBackend` (or IndexedDB backend) in the browser.
|
||||
- Coordinate with `crates/wasm/` for the in-browser swactor runtime.
|
||||
|
||||
**Binary Wire Format**
|
||||
- Replace JSON serialization with bincode or msgpack for `GetChunkResponse` and other payload-heavy messages.
|
||||
|
||||
**Content-Defined Chunking (CDC)**
|
||||
- Replace fixed-size chunking with FastCDC or similar for better cross-object deduplication.
|
||||
- Transparent to the rest of the system -- only `chunk_blob()` changes; manifest format is the same.
|
||||
|
||||
**Streaming / Large File Support**
|
||||
- Current `Put` takes `data: Vec<u8>` (entire blob in memory). For large files, add streaming chunking that reads from a `Read` source.
|
||||
|
||||
**Delete Propagation**
|
||||
- Currently, delete is local only (by design). Add optional "tombstone dissemination" to remove entries from peers.
|
||||
|
||||
**Replication Factor Control**
|
||||
- Currently, dissemination is epidemic (all peers get everything). Add configurable k-closest replication for the metadata DHT.
|
||||
|
||||
**IndexedDB Backend**
|
||||
- Implement `StorageBackend` for browser IndexedDB for persistent storage in web contexts.
|
||||
|
||||
---
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `src/types.rs` | Core types: `ContentHash`, `ObjectEntry`, `ObjectManifest`, `ChunkRef`, `DatastoreConfig` |
|
||||
| `src/messages.rs` | All inter-node and intra-node message types |
|
||||
| `src/chunking.rs` | Pure chunking/reassembly functions |
|
||||
| `src/storage/mod.rs` | `StorageBackend` trait + `FilesystemBackend` |
|
||||
| `src/storage/in_memory.rs` | `InMemoryBackend` |
|
||||
| `src/actors/blob_store.rs` | Chunk/manifest I/O actor |
|
||||
| `src/actors/metadata.rs` | Object index, dissemination, GC orchestration |
|
||||
| `src/actors/transfer.rs` | Ephemeral download actor |
|
||||
| `src/actors/datastore_node.rs` | Coordinator/facade |
|
||||
| `src/cli.rs` | CLI command type definitions (types only, no implementation) |
|
||||
| `PROTOCOL.md` | Protocol specification with status annotations |
|
||||
| `PROTOCOL_IMPLEMENTATION_PLAN.md` | Original 7-module implementation plan |
|
||||
| `tests/common/mod.rs` | Shared test harness: DatastoreHarness, GcHarness, MultiNodeHarness, NodeHarness |
|
||||
|
|
@ -1,418 +0,0 @@
|
|||
# Deploy Regression Tests — Development History
|
||||
|
||||
> Covers the addition of deployment topology simulation (NAT, relay, firewall),
|
||||
> 14 deploy scenario tests, 8 adversarial topology tests, and the supporting
|
||||
> simulation infrastructure. Motivated by two bugs discovered during a real
|
||||
> 3-node DigitalOcean deploy.
|
||||
>
|
||||
> ~1,230 insertions across 15 modified files + 3 new files
|
||||
>
|
||||
> *Branch: `datastore-dashboard`*
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Overview & Motivation](#1-overview--motivation)
|
||||
2. [The Deploy Bugs](#2-the-deploy-bugs)
|
||||
3. [What Was Built](#3-what-was-built)
|
||||
4. [Simulation Infrastructure](#4-simulation-infrastructure)
|
||||
5. [Deploy Scenario Tests](#5-deploy-scenario-tests)
|
||||
6. [Adversarial Topology Tests](#6-adversarial-topology-tests)
|
||||
7. [Bug-Class Regression Validation](#7-bug-class-regression-validation)
|
||||
8. [SWIM Protocol Enhancements](#8-swim-protocol-enhancements)
|
||||
9. [Deploy Tooling](#9-deploy-tooling)
|
||||
10. [Dashboard API](#10-dashboard-api)
|
||||
11. [Design Decisions](#11-design-decisions)
|
||||
12. [Known Gaps & Future Work](#12-known-gaps--future-work)
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview & Motivation
|
||||
|
||||
The simulation crate had 15 cluster scenario tests (from the SIMULATION_TESTING
|
||||
cycle) and 6 original distribution tests. All assumed flat network topologies —
|
||||
every node could directly reach every other node. No tests modeled NAT, relay
|
||||
dependencies, firewalled nodes, or the actual deployment sequence where a
|
||||
controller script orchestrates peer introductions.
|
||||
|
||||
During a real 3-node DigitalOcean deploy (1 public VPS + 2 home NAT machines),
|
||||
two bugs hit that the existing test suite could not have caught:
|
||||
|
||||
1. The deploy script sent `join_seed` to the seed node itself
|
||||
2. Port 3340 was blocked by firewall — all NAT nodes couldn't reach the relay
|
||||
|
||||
Both were fixed in production, but nothing prevented the same *class* of bug
|
||||
from recurring. This work adds simulation-level coverage for deployment
|
||||
topologies and the controller-driven introduction flow, plus concrete regression
|
||||
tests that replay the exact bugs.
|
||||
|
||||
---
|
||||
|
||||
## 2. The Deploy Bugs
|
||||
|
||||
### Bug 1: Self-Join ("Connecting to ourself")
|
||||
|
||||
**What happened**: The deploy script's peer-sync logic sent each node's own
|
||||
`node_id` as part of the join-seed list. When the seed node received a
|
||||
`join_seed` pointing to itself, iroh rejected the connection with "Connecting
|
||||
to ourself." The seed never learned about other nodes.
|
||||
|
||||
**Root cause**: The peer-sync endpoint didn't filter `own_id` from the peer
|
||||
list before initiating the SWIM join.
|
||||
|
||||
**Fix applied**: Filter `own_id` from new peers in `swactor-node/src/main.rs`
|
||||
before calling join.
|
||||
|
||||
**Simulation gap**: No test sent a `Join { node_idx: X, seed_idx: X }` (self-join)
|
||||
or `Introduce { node_a: X, node_b: X }` (self-introduction). Even if the
|
||||
protocol handled it gracefully (no crash), the *consequence* — a deploy that
|
||||
only sends self-joins and never makes real introductions — was untested.
|
||||
|
||||
### Bug 2: Firewall Blocks Relay Port
|
||||
|
||||
**What happened**: Port 3340 was blocked by the DigitalOcean firewall. All NAT
|
||||
nodes behind home routers couldn't reach the public relay node. The cluster was
|
||||
stuck at 0 peers — SWIM probes from NAT→relay were silently dropped.
|
||||
|
||||
**Root cause**: The deploy script didn't verify relay port reachability before
|
||||
proceeding with introductions. The failure was silent — no error, just 0 peers
|
||||
forever.
|
||||
|
||||
**Fix applied**: Added firewall rule for port 3340 to the deploy provisioning.
|
||||
|
||||
**Simulation gap**: No test modeled a topology where the relay was alive but
|
||||
unreachable by NAT nodes. Existing relay-death tests killed the relay entirely,
|
||||
which is a different failure mode (relay process crash vs. network-level block).
|
||||
|
||||
---
|
||||
|
||||
## 3. What Was Built
|
||||
|
||||
| Component | Location | Description |
|
||||
|-----------|----------|-------------|
|
||||
| Network topology model | `sim.rs` | `NodeLocation`, `NetworkTopology`, NAT/firewall reachability |
|
||||
| Per-link faults | `sim.rs` | `LinkFault`, `SetRelayPenalty` in `NetworkFault` |
|
||||
| Deferred join | `sim.rs` | Nodes that skip auto-join, require `SimAction::Join`/`Introduce` |
|
||||
| Controller actions | `sim.rs` | `SimAction::Join`, `SimAction::Introduce` |
|
||||
| 5 property checkers | `properties.rs` | Group convergence, stability, asymmetry, zero-convergence, staggered join |
|
||||
| 14 deploy scenario tests | `deploy_scenarios.rs` | NAT topology, relay failure, controller actions, compound faults |
|
||||
| 8 adversarial topology tests | `topology_adversarial.rs` | Per-link degradation, relay flapping, split-brain, hub saturation |
|
||||
| Indirect ack forwarding | `swim/node.rs` | `ForwardAck` action for relay-mediated probes |
|
||||
| `IndirectAck` wire message | `messages.rs` | New message type for forwarded acks |
|
||||
| Peer sync endpoint | `dashboard/server.rs` | `POST /api/peers/sync` for bulk introduction |
|
||||
| Native deploy pipeline | `xtask/deploy.rs` | 6-phase provisioning with convergence retry |
|
||||
|
||||
All 22 new simulation tests run in ~0.2s total. The full test suite
|
||||
(existing + new) passes.
|
||||
|
||||
---
|
||||
|
||||
## 4. Simulation Infrastructure
|
||||
|
||||
### Network Topology Model
|
||||
|
||||
Three new types model node placement:
|
||||
|
||||
```rust
|
||||
pub enum NodeLocation {
|
||||
Public, // Cloud VPS — accepts inbound from anyone
|
||||
Nat { group: String }, // Behind NAT — same-group LAN only, or via relay
|
||||
Firewalled, // No inbound or outbound
|
||||
}
|
||||
|
||||
pub struct NetworkTopology {
|
||||
pub locations: Vec<NodeLocation>, // Per-node, indexed by node_idx
|
||||
pub relay_nodes: Vec<usize>, // Indices of relay-capable nodes
|
||||
}
|
||||
```
|
||||
|
||||
Reachability rules in `NetworkState::directly_reachable()`:
|
||||
|
||||
| From \ To | Public | Nat(same) | Nat(diff) | Firewalled |
|
||||
|-----------|--------|-----------|-----------|------------|
|
||||
| **Public** | yes | no (can't initiate to NAT) | no | no |
|
||||
| **Nat(same)** | yes | yes (LAN) | no | no |
|
||||
| **Nat(diff)** | yes | no | no | no |
|
||||
| **Firewalled** | no | no | no | no |
|
||||
|
||||
Cross-NAT-group communication requires a relay path: both endpoints must be
|
||||
able to reach an alive relay node (in either direction, since connections are
|
||||
bidirectional once established).
|
||||
|
||||
### Per-Link Faults
|
||||
|
||||
Two new `NetworkFault` variants:
|
||||
|
||||
```rust
|
||||
NetworkFault::LinkFault { round, from, to, rate, bidirectional }
|
||||
NetworkFault::SetRelayPenalty { round, rate }
|
||||
```
|
||||
|
||||
`LinkFault` sets a drop rate on a specific (from, to) pair, enabling targeted
|
||||
degradation (e.g., "site-b gateway is lossy" without affecting site-a). The
|
||||
`bidirectional` flag optionally blocks both directions.
|
||||
|
||||
`SetRelayPenalty` adds extra drop probability for relay-routed messages. The
|
||||
composition formula ensures independent fault probabilities:
|
||||
|
||||
```
|
||||
effective_rate = 1 - (1 - base_rate) * (1 - relay_penalty)
|
||||
```
|
||||
|
||||
### Deferred Join & Controller Actions
|
||||
|
||||
`DistributionSimConfig` gained:
|
||||
|
||||
- `deferred_join: Vec<usize>` — nodes that skip the automatic seed-join during
|
||||
setup, modeling nodes that haven't been deployed yet
|
||||
- `SimAction::Join { node_idx, seed_idx }` — mid-simulation join via a seed
|
||||
- `SimAction::Introduce { node_a, node_b }` — bidirectional introduction
|
||||
modeling `POST /api/peers/sync`
|
||||
|
||||
`Introduce` is implemented as two back-to-back `handle_join_request` calls —
|
||||
A introduces itself to B, then B introduces itself to A — matching the real
|
||||
deploy flow.
|
||||
|
||||
### Property Checkers
|
||||
|
||||
Five new property functions in `properties.rs`:
|
||||
|
||||
| Function | Purpose |
|
||||
|----------|---------|
|
||||
| `check_group_convergence` | Subset of nodes converge (spread within tolerance) after a round |
|
||||
| `check_membership_stability` | Counts direction flips in member_count (detects suspect→dead cycling) |
|
||||
| `check_view_asymmetry` | Max spread of member_count across alive nodes |
|
||||
| `check_zero_convergence` | Detects all-nodes-stuck-at-zero failure mode |
|
||||
| `check_staggered_join` | Verifies deferred-join nodes reach quorum by deadline |
|
||||
|
||||
---
|
||||
|
||||
## 5. Deploy Scenario Tests
|
||||
|
||||
14 tests in `crates/simulation/tests/deploy_scenarios.rs`, organized by what
|
||||
they exercise:
|
||||
|
||||
### Baseline Topology (Tests 1–3)
|
||||
|
||||
| # | Test | Topology | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 1 | `home_cloud_topology_converges_via_relay` | 1 Public + 2 NAT("home") | 100% accuracy — the "happy path" home deploy |
|
||||
| 2 | `multi_site_nat_communicates_via_relay` | 1 Public + 2 NAT("home") + 2 NAT("office") | 100% accuracy — multi-site |
|
||||
| 3 | `relay_death_partitions_nat_groups` | Same as #2, kill relay at round 30 | Home/office groups maintain internal connectivity; cross-group lost |
|
||||
|
||||
### Deploy Lifecycle (Tests 4–6)
|
||||
|
||||
| # | Test | Scenario | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 4 | `rolling_redeploy_with_reintroduction` | Kill node 1 at round 20, revive at 40, re-join at 45 | Revived node sees >= 1 member |
|
||||
| 5 | `staggered_startup_seed_first` | 4 nodes, non-seed deferred, joined at rounds 10/20/30 | All 4 joined by round 100, >= 75% accuracy |
|
||||
| 6 | `firewalled_node_isolated_others_converge` | 4 normal + 1 firewalled (deferred, never joins) | 4 normal converge; firewalled sees 0 |
|
||||
|
||||
### Controller Actions (Tests 7–9)
|
||||
|
||||
| # | Test | Scenario | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 7 | `controller_driven_peer_introduction` | 4 Public nodes, all deferred, all 6 pairs introduced at round 10 | 100% accuracy via Introduce |
|
||||
| 8 | `deploy_auth_race_recovery_via_two_pass` | 100% drop at round 5 (auth race), clear at 10, re-introduce at 15 | Recovery via two-pass introduction |
|
||||
| 9 | `degenerate_controller_actions_do_not_degrade_convergence` | Self-joins + self-introductions + redundant re-introductions prepended to real introductions | Converges to 100%; speed gap <= 10 rounds vs. clean run |
|
||||
|
||||
### Relay & Fault Scenarios (Tests 10–12)
|
||||
|
||||
| # | Test | Scenario | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 10 | `relay_dependency_failure_prevents_cross_group_convergence` | All NAT↔relay links blocked (firewall) | LAN groups converge internally; full cluster < 100%; not zero |
|
||||
| 11 | `introduction_strategy_equivalence_under_nat_topology` | Star vs full-mesh vs chain introduction strategies | All >= 75% accuracy; spread <= 0.5 |
|
||||
| 12 | `mid_deploy_compound_fault_recovery` | 80% drops + seed kill + partition + revive + heal + re-introduce | >= 75% accuracy after recovery; all 5 alive; global convergence by round 60 |
|
||||
|
||||
### Bug Replays (Tests 13–14)
|
||||
|
||||
| # | Test | Real Bug | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 13 | `bug_replay_self_join_only_deploy_fails_to_converge` | Deploy sends only self-joins, never cross-node introductions | **Must fail**: zero-convergence, < 50% accuracy |
|
||||
| 14 | `bug_replay_firewall_blocks_relay_port_silent_isolation` | Firewall blocks all NAT↔relay traffic for entire simulation | **Must fail**: < 100% accuracy; relay isolated at 0 members; LAN peers still see each other |
|
||||
|
||||
---
|
||||
|
||||
## 6. Adversarial Topology Tests
|
||||
|
||||
8 tests in `crates/simulation/tests/topology_adversarial.rs`, focused on
|
||||
per-link degradation and relay-mediated failure modes:
|
||||
|
||||
| # | Test | Scenario | Assertion |
|
||||
|---|------|----------|-----------|
|
||||
| 1 | `per_link_degradation_causes_asymmetric_views` | Site-b at 40% link loss, site-a clean | Final spread reflects asymmetry |
|
||||
| 2 | `relay_penalty_causes_false_suspicions` | 50% relay penalty + tight SWIM timeouts | Not zero-convergence; some accuracy maintained |
|
||||
| 3 | `asymmetric_relay_links_create_view_divergence` | 60% one-direction loss on relay links | Bounded view divergence |
|
||||
| 4 | `relay_flapping_causes_membership_oscillation` | 3 relay kill/revive cycles | Membership eventually stabilizes |
|
||||
| 5 | `hub_saturation_degrades_spoke_connectivity` | Hub alive but 40% lossy to all spokes | Graceful degradation |
|
||||
| 6 | `correlated_nat_gateway_failure` | All NAT gateway links fail simultaneously | LAN groups survive; cross-group degraded |
|
||||
| 7 | `split_brain_with_dual_relays` | Kill relay-a, block group-a from relay-b | Detectable partition |
|
||||
| 8 | `relay_is_target_causes_isolation_on_death` | Relay killed; NAT group loses only relay path | NAT group isolated |
|
||||
|
||||
---
|
||||
|
||||
## 7. Bug-Class Regression Validation
|
||||
|
||||
The two bug-replay tests (13, 14) validate that the simulation framework
|
||||
*catches the bug class*, not just the specific instance. They model the exact
|
||||
failure scenario and assert that the buggy deploy **fails to converge** — the
|
||||
test passes by confirming the failure:
|
||||
|
||||
### Self-Join Regression (Test 13)
|
||||
|
||||
Models a deploy where the controller only sends self-joins (`Join{0,0}`,
|
||||
`Join{1,1}`, `Join{2,2}`) and never sends cross-node introductions. All nodes
|
||||
are deferred, so without correct introductions they never discover each other.
|
||||
|
||||
**Assertions (inverted — the test passes when the deploy fails):**
|
||||
- `check_zero_convergence` must **fail** (all nodes stuck at 0 members)
|
||||
- Membership accuracy < 0.5
|
||||
|
||||
This proves that test 9's assertions (convergence despite degenerate actions)
|
||||
would catch a deploy that accidentally sends only self-joins.
|
||||
|
||||
### Firewall Regression (Test 14)
|
||||
|
||||
Models a deploy where `LinkFault { rate: 1.0, bidirectional: true }` blocks all
|
||||
NAT↔relay traffic for the entire simulation. The deploy script introduces all
|
||||
pairs, but messages to/from the relay are dropped.
|
||||
|
||||
**Assertions (inverted — the test passes when the deploy is degraded):**
|
||||
- Membership accuracy < 1.0 (full convergence must NOT succeed)
|
||||
- Relay node isolated at 0 members
|
||||
- Same-group LAN peers still converge (the failure is cross-group, not total)
|
||||
|
||||
This proves that test 10's assertions (degraded accuracy under relay failure)
|
||||
would detect a silently firewalled relay.
|
||||
|
||||
---
|
||||
|
||||
## 8. SWIM Protocol Enhancements
|
||||
|
||||
### Indirect Ack Forwarding
|
||||
|
||||
SWIM's indirect probe path (Prober → Relay → Target) previously had no return
|
||||
path for the ack. When the relay forwarded a PingReq to the target and the
|
||||
target replied with an Ack, the ack went directly from target to relay — but
|
||||
relay didn't know to forward it back to the original prober.
|
||||
|
||||
**New flow:**
|
||||
|
||||
```
|
||||
Prober --PingReq--> Relay --Ping--> Target
|
||||
Relay <--Ack--- Target
|
||||
Prober <--ForwardAck-- Relay
|
||||
```
|
||||
|
||||
The relay tracks pending requests in `pending_relays: Vec<(requester, target, seq)>`.
|
||||
When an ack arrives matching a pending relay entry, the relay generates a
|
||||
`ForwardAck` action. The prober handles this via `handle_indirect_ack()`.
|
||||
|
||||
**Wire message**: New `IndirectAck` message type with tag `"swactor_dist::IndirectAck"`.
|
||||
|
||||
### SWIM Timeout Tuning
|
||||
|
||||
`swactor-node` SWIM config adjusted for relay-aware operation:
|
||||
- `probe_timeout`: 3 → 6 (allows relay RTT)
|
||||
- `suspicion_timeout`: 20 → 40 (allows refutation piggyback through relay path)
|
||||
|
||||
---
|
||||
|
||||
## 9. Deploy Tooling
|
||||
|
||||
### Native Deploy Pipeline (`xtask/src/deploy.rs`)
|
||||
|
||||
6-phase deployment replacing Docker-only approach:
|
||||
|
||||
1. **Build**: `cargo build --release -p swactor-node`
|
||||
2. **Deploy**: Transfer binary + generate `node.toml` + install systemd unit
|
||||
3. **Health**: Wait for all nodes' dashboard endpoints to respond
|
||||
4. **Introduce**: `POST /api/peers/sync` with all peers + seed designation
|
||||
5. **Convergence**: Poll member counts with multi-attempt retry + re-sync on failure
|
||||
6. **Report**: Final cluster state
|
||||
|
||||
Key functions:
|
||||
- `collect_node_info()` — Gather node IDs and relay URLs from all machines
|
||||
- `pick_seed()` — Select a relay node as cluster seed
|
||||
- `sync_peers()` — O(n) bulk peer sync replacing O(n^2) pairwise adds
|
||||
- `native_deploy_to_machine()` — Full provisioning with absolute path handling
|
||||
|
||||
### Peer Introduction Strategy Shift
|
||||
|
||||
**Old**: O(n^2) individual `POST /api/peers/add` calls, one per pair.
|
||||
**New**: Single O(n) `POST /api/peers/sync` per node, sending the full peer
|
||||
list + seed designation. Each node atomically adds all peers and initiates
|
||||
the SWIM join.
|
||||
|
||||
---
|
||||
|
||||
## 10. Dashboard API
|
||||
|
||||
### `POST /api/peers/sync` (`dashboard/server.rs`)
|
||||
|
||||
New endpoint for bulk peer introduction:
|
||||
|
||||
```json
|
||||
{
|
||||
"peers": [
|
||||
{ "node_id": "abc123...", "relay_url": "https://..." },
|
||||
...
|
||||
],
|
||||
"join_seed": "abc123..."
|
||||
}
|
||||
```
|
||||
|
||||
- Validates all peer node IDs before persisting
|
||||
- Atomically adds peers and triggers SWIM join to seed
|
||||
- Supports both hex and base58 node ID encodings
|
||||
- Returns JSON response with peer count
|
||||
|
||||
---
|
||||
|
||||
## 11. Design Decisions
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| LinkFault over RelayPenalty for firewall tests | RelayPenalty only affects relay-*routed* messages; SWIM gossip through the seed's direct NAT→Public connection still disseminates membership. LinkFault blocking all NAT↔relay traffic properly models the real firewall scenario. |
|
||||
| Bug replays assert failure, not success | Proving a bad deploy *fails to converge* is stronger than proving a good deploy converges. It verifies the property checkers would actually catch the bug. |
|
||||
| Deferred join as default for controller tests | Real deploys don't auto-join — the controller orchestrates introductions. Deferred join models this accurately. |
|
||||
| O(n) peer-sync over O(n^2) pairwise | Reduces deploy-time network calls. Single atomic operation per node prevents partial-introduction races. |
|
||||
| Relay pending_relays capped at 16 | FIFO eviction prevents memory growth from orphaned relay entries. 16 is generous — each probe cycle generates at most `indirect_probes` entries. |
|
||||
| Inverted assertions for regression tests | `assert!(!zero_check.passed, ...)` reads clearly: "the buggy deploy *should* produce zero-convergence." |
|
||||
|
||||
---
|
||||
|
||||
## 12. Known Gaps & Future Work
|
||||
|
||||
| Gap | Priority | Notes |
|
||||
|-----|----------|-------|
|
||||
| Relay penalty + gossip interaction | Medium | RelayPenalty doesn't prevent convergence through gossip — may need a "relay-only topology" mode where cross-group messages MUST go through relay |
|
||||
| Kademlia under NAT topology | Medium | Directory repair and lookup haven't been tested under NAT constraints |
|
||||
| Deploy rollback testing | Medium | What happens when a deploy partially succeeds and needs rollback |
|
||||
| Real DigitalOcean integration test | Low | Run the deploy pipeline against actual DO droplets in CI |
|
||||
| Chaos engineering mode | Low | Random fault injection during deploy (a la BUGGIFY) |
|
||||
|
||||
---
|
||||
|
||||
## Files Created/Modified
|
||||
|
||||
| Action | File | Purpose |
|
||||
|--------|------|---------|
|
||||
| Created | `crates/simulation/tests/deploy_scenarios.rs` | 14 deploy scenario tests |
|
||||
| Created | `crates/simulation/tests/topology_adversarial.rs` | 8 adversarial topology tests |
|
||||
| Modified | `crates/simulation/src/distribution/sim.rs` | Topology model, deferred join, link faults, controller actions |
|
||||
| Modified | `crates/simulation/src/distribution/properties.rs` | 5 new property checkers |
|
||||
| Modified | `crates/simulation/src/distribution/trace.rs` | New event kinds for introductions |
|
||||
| Modified | `crates/distribution/src/swim/node.rs` | ForwardAck, pending_relays, diagnostic logging |
|
||||
| Modified | `crates/distribution/src/messages.rs` | IndirectAck message type |
|
||||
| Modified | `crates/distribution/src/node.rs` | handle_indirect_ack, piggyback composition |
|
||||
| Modified | `crates/distribution/src/driver.rs` | Route IndirectAck messages |
|
||||
| Modified | `crates/distribution/src/iroh_driver.rs` | Relay URL caching |
|
||||
| Modified | `crates/distribution/tests/common/mod.rs` | Handle ForwardAck in test harness |
|
||||
| Modified | `crates/dashboard/src/server.rs` | POST /api/peers/sync endpoint |
|
||||
| Modified | `crates/dashboard/examples/dashboard_demo.rs` | Handle ForwardAck in demo |
|
||||
| Modified | `crates/swactor-node/src/main.rs` | SWIM timeout tuning, self-join filter |
|
||||
| Modified | `xtask/src/deploy.rs` | Native deploy pipeline |
|
||||
| Modified | `xtask/src/main.rs` | Config defaults, native deploy wiring |
|
||||
| Modified | `.gitignore` | Ignore .deploy/ except example config |
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue