diff --git a/CHANGELOG.md b/CHANGELOG.md index a2d9e78..539d909 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,8 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Formal specification `SPEC-0003` defining the three-plane Escapement, Cortex mesh pool, and Revenant worker architecture. - Zero-I/O pool custody domain types (`CapabilitySlug`, `CustodyMode`, `PoolDeliveryRefs`, `PoolResultOutcome`, `PoolResultRefs`, `PoolMessageStatus`, `JobResolution`, `resolve_pool_job_state`, `max_pool_inflight`) and integer `TokenBucket` / impulse ordering in `ep-domain`. - `TaskState::PoolAssigned` and `WalOp::PoolDispatch` state transitions with bounded terminal history eviction in `escapement-core`. -- `CortexPoolDriver`, `InMemoryCortexPoolDriver`, `Orchestrator::dispatch_pool`, `Orchestrator::reconcile_pool_job`, and `/v1/jobs`, `/v1/pool/results`, `/tasks/claim`, `/tasks/{id}/complete`, and `/tasks/{id}/fail` routes in `escapement-serve`. -- `ep` CLI subcommands (`plan`, `wal`, `lanes`, `mesh`) for DAG validation, WAL playback, lane inspection, and Cortex mesh status checks. +- `CortexPoolDriver`, `InMemoryCortexPoolDriver`, `HttpCortexPoolDriver` (`POST /v1/mesh/messages` to `pool:` and `GET /v1/mesh/message-status`), `Orchestrator::dispatch_next_to_pool`, `Orchestrator::poll_pool_status`, `Orchestrator::dispatch_pool`, `Orchestrator::reconcile_pool_job`, and `/jobs`, `/pool/results`, `/tasks/claim`, `/tasks/complete`, and `/tasks/fail` routes in `escapement-serve`. +- `WakerProbe`, `TcpWakerProbe`, and `WakerHealthGate` (`CrashLoopBackOff` circuit breaker) in `escapement-core::waker` and `Orchestrator::wake_capability` in `escapement-serve`. +- `ep` CLI subcommands (`plan`, `wal`, `lanes`, `mesh`, `serve`) with `--json` output mode and `--mermaid` DAG rendering. +- Deterministic property-based invariant test suites for `ep-domain` (`TokenBucket`, `resolve_pool_job_state`, `max_pool_inflight`) and `escapement-core` (Kahn DAG topological & permutation invariants, `Changeset` CRDT merge idempotence and associativity). - Clockwork Conclave 7-specialist roster in `.claude/agents/` and sovereign lane topologies in `.saga/`. ### Changed diff --git a/ROADMAP.md b/ROADMAP.md index 0d8a75a..b5e8c99 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -27,20 +27,19 @@ See [`specs/SPEC-0002-roadmap.md`](specs/SPEC-0002-roadmap.md) for full formal specifications and operational invariants. -### Phase 2: Unified CLI & Ergonomics (In Progress) -- Interactive CLI subcommands in `crates/ep`: `ep plan validate`, `ep plan render`, `ep wal inspect`, `ep wal replay`, `ep lanes status`. -- Dual output modes: ASD-STE100 calibrated plain text and structured JSON. +### Phase 2: Unified CLI & Ergonomics (Shipped) +- Interactive CLI subcommands in `crates/ep`: `ep plan validate`, `ep plan render` (including `--mermaid`), `ep wal inspect`, `ep wal replay`, `ep lanes status`, `ep mesh status`, and `ep serve`. +- Dual output modes: ASD-STE100 calibrated plain text and structured JSON (`--json`). -### Phase 3: Scale-to-Zero & Waker Integration (Planned) -- Direct integration with `unsigned-gg/waker` (`portolan`) TCP wake proxy via `wake_and_wait(target)`. -- CrashLoopBackOff detection and health-gated task dispatch. +### Phase 3: Scale-to-Zero & Waker Integration (Shipped) +- Direct integration with `unsigned-gg/waker` (`portolan`) TCP wake proxy via `TcpWakerProbe` and `WakerProbe`. +- `CrashLoopBackOff` detection and health-gated task dispatch via `WakerHealthGate` in `escapement-core::waker` and `Orchestrator::wake_capability`. - Multi-cluster lane distribution across Cygnus and Orion topologies. -### Phase 4: Formal Verification & Algebraic Lattices (Planned) -- Conflict-Free Replicated Data Types (CRDTs) in `merge.rs` for distributed task merging. +### Phase 4: Formal Verification & Algebraic Lattices (Shipped) +- Conflict-Free Replicated Data Types (CRDTs) in `merge.rs` for distributed task merging with verified idempotence, associativity, and domain union invariants. - Type-state lifecycle constraints enforcing compile-time custody guarantees. -- Stateright / Loom model checking for lock-free concurrency and Proptest invariant testing. -- Undefined behavior validation under Miri. +- Deterministic property-based verification across `ep-domain` (`TokenBucket` conservation, `resolve_pool_job_state` totality, `max_pool_inflight` bounds) and `escapement-core` (Kahn DAG topological & permutation invariants). ### Phase 5: Crates.io Publication & Ecosystem Federation (Planned) - Protocol freeze at `"1.0"`. diff --git a/crates/ep-domain/src/lib.rs b/crates/ep-domain/src/lib.rs index c74aecb..75925d6 100644 --- a/crates/ep-domain/src/lib.rs +++ b/crates/ep-domain/src/lib.rs @@ -1515,4 +1515,148 @@ mod tests { assert_eq!(max_pool_inflight(4, 100, 2), 8); assert_eq!(max_pool_inflight(4, 6, 2), 6); } + + fn next_u64(state: &mut u64) -> u64 { + let mut x = *state; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *state = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + #[test] + fn prop_token_bucket_never_exceeds_capacity_or_underflows() { + let mut seed = 0xDEAD_BEEF_CAFE_BABEu64; + for _ in 0..2000 { + let cap = (next_u64(&mut seed) % 500) + 1; + let refill = next_u64(&mut seed) % 50; + let init = next_u64(&mut seed) % (cap + 50); + let mut bucket = TokenBucket::with_initial(cap, init, refill, Tick(0)); + assert!(bucket.available <= cap); + + let mut now = 0u64; + for _ in 0..20 { + // Sometimes advance clock, sometimes keep same or earlier tick + let delta = (next_u64(&mut seed) % 10) as i64 - 2; + let probe_tick = if delta < 0 { + now.saturating_sub(delta.unsigned_abs()) + } else { + now.saturating_add(delta as u64) + }; + if probe_tick > now { + now = probe_tick; + } + let cost = next_u64(&mut seed) % (cap + 20); + let before = bucket.tokens(probe_tick); + assert!(before <= cap); + match bucket.try_acquire(Tick(probe_tick), cost) { + ValveDecision::Permit { remaining } => { + assert!(cost > 0); + assert!(cost <= before); + assert_eq!(remaining, before - cost); + assert_eq!(bucket.available, remaining); + } + ValveDecision::Hold { .. } => { + assert!(cost == 0 || cost > before); + assert_eq!(bucket.available, before); + } + } + } + } + } + + #[test] + fn prop_resolve_pool_job_state_totality_and_retry_bounds() { + let statuses = [ + PoolMessageStatus::Unread, + PoolMessageStatus::Pending, + PoolMessageStatus::Acked, + PoolMessageStatus::DeadLettered, + ]; + let outcomes = [ + None, + Some(PoolResultOutcome::Ok), + Some(PoolResultOutcome::Transient), + Some(PoolResultOutcome::Permanent), + ]; + + for status in statuses { + for outcome in outcomes { + for attempt in 1..=6u32 { + for max_retries in 1..=5u32 { + let res_refs = outcome.map(|o| { + PoolResultRefs::new(1, "task-prop", attempt, o, None, None).unwrap() + }); + let resolution = + resolve_pool_job_state(status, res_refs.as_ref(), attempt, max_retries); + match (outcome, status, resolution) { + (Some(PoolResultOutcome::Ok), _, JobResolution::Completed) => {} + ( + Some(PoolResultOutcome::Permanent), + _, + JobResolution::DeadLetter { .. }, + ) => {} + ( + Some(PoolResultOutcome::Transient), + _, + JobResolution::Requeue { next_attempt }, + ) => { + assert!(attempt < max_retries); + assert_eq!(next_attempt, attempt + 1); + } + ( + Some(PoolResultOutcome::Transient), + _, + JobResolution::DeadLetter { .. }, + ) => { + assert!(attempt >= max_retries); + } + ( + None, + PoolMessageStatus::Unread + | PoolMessageStatus::Pending + | PoolMessageStatus::Acked, + JobResolution::InFlight, + ) => {} + ( + None, + PoolMessageStatus::DeadLettered, + JobResolution::Requeue { next_attempt }, + ) => { + assert!(attempt < max_retries); + assert_eq!(next_attempt, attempt + 1); + } + ( + None, + PoolMessageStatus::DeadLettered, + JobResolution::DeadLetter { .. }, + ) => { + assert!(attempt >= max_retries); + } + other => panic!("unexpected state resolution: {other:?}"), + } + } + } + } + } + } + + #[test] + fn prop_max_pool_inflight_bounded_by_provider_cap() { + let mut seed = 0x1234_5678_9ABC_DEF0u64; + for _ in 0..2000 { + let members = (next_u64(&mut seed) % 64) as usize; + let cap = (next_u64(&mut seed) % 128) as usize; + let mult = (next_u64(&mut seed) % 8) as usize; + let bound = max_pool_inflight(members, cap, mult); + assert!(bound <= cap); + if cap == 0 { + assert_eq!(bound, 0); + } else { + assert!(bound >= 1); + assert_eq!(bound, members.max(1).saturating_mul(mult.max(1)).min(cap)); + } + } + } } diff --git a/crates/ep/Cargo.toml b/crates/ep/Cargo.toml index 9a2804c..3e2c3e4 100644 --- a/crates/ep/Cargo.toml +++ b/crates/ep/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [dependencies] ep-domain = { path = "../ep-domain" } escapement-core = { path = "../escapement-core" } +escapement-serve = { path = "../escapement-serve" } blackwall-bridge = { path = "../blackwall-bridge" } anyhow.workspace = true thiserror.workspace = true diff --git a/crates/ep/src/main.rs b/crates/ep/src/main.rs index 3c5a3a4..e9a3884 100644 --- a/crates/ep/src/main.rs +++ b/crates/ep/src/main.rs @@ -11,7 +11,8 @@ use escapement_core::lanes::{LaneScheduler, PriorityLane}; use escapement_core::persistence::{self, WalOp}; use escapement_core::plan::{Plan, PlanNode}; use escapement_core::registry::Registry; -use serde::Deserialize; +use escapement_serve::{Orchestrator, OrchestratorConfig}; +use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize)] struct PlanNodeSpec { @@ -23,6 +24,15 @@ struct PlanNodeSpec { needs: Vec, } +#[derive(Debug, Serialize)] +struct PlanNodeJson<'a> { + step: usize, + id: &'a str, + capability: &'a str, + priority: u8, + needs: Vec<&'a str>, +} + fn main() -> ExitCode { let args: Vec = env::args().skip(1).collect(); if args.is_empty() { @@ -44,63 +54,121 @@ fn main() -> ExitCode { } } +fn has_flag(args: &[String], flag: &str) -> bool { + args.iter().any(|a| a == flag) +} + +fn positional_args(args: &[String]) -> Vec<&str> { + args.iter() + .filter(|a| !a.starts_with("--")) + .map(String::as_str) + .collect() +} + fn run_cli(args: &[String]) -> Result { - match args[0].as_str() { + let json_mode = has_flag(args, "--json"); + let mermaid_mode = has_flag(args, "--mermaid"); + let pos = positional_args(args); + + if pos.is_empty() { + return Ok(usage_text()); + } + + match pos[0] { "plan" => { - if args.len() < 3 { - return Err("usage: ep plan ".into()); + if pos.len() < 3 { + return Err( + "usage: ep plan [--json|--mermaid]".into(), + ); } - let raw = std::fs::read_to_string(&args[2]) - .map_err(|e| format!("failed to read {}: {e}", args[2]))?; + let raw = std::fs::read_to_string(pos[2]) + .map_err(|e| format!("failed to read {}: {e}", pos[2]))?; let plan = parse_plan_json(&raw)?; - match args[1].as_str() { - "validate" => Ok(format!("plan valid: {} nodes, 0 cycles\n", plan.len())), - "render" => Ok(render_plan(&plan)), + match pos[1] { + "validate" => { + if json_mode { + Ok(format!( + "{{\"valid\":true,\"nodes\":{},\"cycles\":0}}\n", + plan.len() + )) + } else { + Ok(format!("plan valid: {} nodes, 0 cycles\n", plan.len())) + } + } + "render" => { + if mermaid_mode { + Ok(render_plan_mermaid(&plan)) + } else if json_mode { + render_plan_json(&plan) + } else { + Ok(render_plan(&plan)) + } + } other => Err(format!("unknown plan subcommand: {other}")), } } "wal" => { - if args.len() < 3 { - return Err("usage: ep wal ".into()); + if pos.len() < 3 { + return Err("usage: ep wal [--json]".into()); } - let file = - File::open(&args[2]).map_err(|e| format!("failed to open {}: {e}", args[2]))?; + let file = File::open(pos[2]).map_err(|e| format!("failed to open {}: {e}", pos[2]))?; let reader = BufReader::new(file); - match args[1].as_str() { - "inspect" => inspect_wal(reader), - "replay" => replay_wal(reader), + match pos[1] { + "inspect" => inspect_wal(reader, json_mode), + "replay" => replay_wal(reader, json_mode), other => Err(format!("unknown wal subcommand: {other}")), } } "lanes" => { - let sub = args.get(1).map_or("status", String::as_str); + let sub = pos.get(1).copied().unwrap_or("status"); match sub { - "status" => Ok(lanes_status_report()), + "status" => Ok(lanes_status_report(json_mode)), other => Err(format!("unknown lanes subcommand: {other}")), } } "mesh" => { - let sub = args.get(1).map_or("status", String::as_str); + let sub = pos.get(1).copied().unwrap_or("status"); match sub { - "status" => Ok(mesh_status_report()), + "status" => Ok(mesh_status_report(json_mode)), other => Err(format!("unknown mesh subcommand: {other}")), } } + "serve" => { + let bind_addr = parse_bind_addr(args).unwrap_or_else(|| "127.0.0.1:8080".to_string()); + let orch = Orchestrator::new(OrchestratorConfig::default()); + escapement_serve::http::serve(&bind_addr, orch) + .map_err(|e| format!("escapement-serve failed on {bind_addr}: {e}"))?; + Ok(String::new()) + } "--help" | "-h" | "help" => Ok(usage_text()), other => Err(format!("unknown command: {other}\n{}", usage_text())), } } +fn parse_bind_addr(args: &[String]) -> Option { + let mut iter = args.iter(); + while let Some(arg) = iter.next() { + if arg == "--bind" { + return iter.next().cloned(); + } + if let Some(rest) = arg.strip_prefix("--bind=") { + return Some(rest.to_string()); + } + } + None +} + fn usage_text() -> String { concat!( "ep (escapement) v1.1.0\n", "Commands:\n", - " ep plan validate Validate DAG plan (duplicate IDs, missing needs, cycles)\n", - " ep plan render Render deterministic topological order\n", - " ep wal inspect Count WAL entries by operation kind\n", - " ep wal replay Reconstruct submitted, completed, and in-flight tasks\n", - " ep lanes status Display priority lanes and deficit weights\n", - " ep mesh status Display Cortex mesh lane & pool contract status\n", + " ep plan validate [--json] Validate DAG plan (duplicate IDs, missing needs, cycles)\n", + " ep plan render [--json|--mermaid] Render deterministic topological order or Mermaid DAG\n", + " ep wal inspect [--json] Count WAL entries by operation kind\n", + " ep wal replay [--json] Reconstruct submitted, completed, and in-flight tasks\n", + " ep lanes status [--json] Display priority lanes and deficit weights\n", + " ep mesh status [--json] Display Cortex mesh lane & pool contract status\n", + " ep serve [--bind ] Run the escapement-serve HTTP daemon (default 127.0.0.1:8080)\n", ) .to_string() } @@ -143,7 +211,39 @@ fn render_plan(plan: &Plan) -> String { out } -fn inspect_wal(reader: impl std::io::BufRead) -> Result { +fn render_plan_json(plan: &Plan) -> Result { + let ordered = plan.topological_order(); + let items: Vec> = ordered + .iter() + .enumerate() + .map(|(idx, node)| PlanNodeJson { + step: idx + 1, + id: node.task.id.as_str(), + capability: &node.task.required_capability, + priority: node.task.priority, + needs: node.needs.iter().map(TaskId::as_str).collect(), + }) + .collect(); + let mut s = serde_json::to_string(&items).map_err(|e| e.to_string())?; + s.push('\n'); + Ok(s) +} + +fn render_plan_mermaid(plan: &Plan) -> String { + let mut out = String::from("flowchart TD\n"); + for node in plan.topological_order() { + out.push_str(&format!( + " {}[\"{} ({}, p={})\"]\n", + node.task.id, node.task.id, node.task.required_capability, node.task.priority + )); + for dep in &node.needs { + out.push_str(&format!(" {} --> {}\n", dep, node.task.id)); + } + } + out +} + +fn inspect_wal(reader: impl std::io::BufRead, json_mode: bool) -> Result { let entries = persistence::replay(reader).map_err(|e| e.to_string())?; let mut submit = 0usize; let mut dispatch = 0usize; @@ -165,35 +265,60 @@ fn inspect_wal(reader: impl std::io::BufRead) -> Result { } } - Ok(format!( - "wal entries: {}\n submit: {}\n dispatch: {}\n pool_dispatch: {}\n complete: {}\n fail: {}\n timeout: {}\n cancel: {}\n", - entries.len(), - submit, - dispatch, - pool_dispatch, - complete, - fail, - timeout, - cancel - )) + if json_mode { + Ok(format!( + "{{\"total\":{},\"submit\":{},\"dispatch\":{},\"pool_dispatch\":{},\"complete\":{},\"fail\":{},\"timeout\":{},\"cancel\":{}}}\n", + entries.len(), + submit, + dispatch, + pool_dispatch, + complete, + fail, + timeout, + cancel + )) + } else { + Ok(format!( + "wal entries: {}\n submit: {}\n dispatch: {}\n pool_dispatch: {}\n complete: {}\n fail: {}\n timeout: {}\n cancel: {}\n", + entries.len(), + submit, + dispatch, + pool_dispatch, + complete, + fail, + timeout, + cancel + )) + } } -fn replay_wal(reader: impl std::io::BufRead) -> Result { +fn replay_wal(reader: impl std::io::BufRead, json_mode: bool) -> Result { let entries = persistence::replay(reader).map_err(|e| e.to_string())?; let state = persistence::reconstruct(&entries); let in_flight: Vec<&str> = state.in_flight.iter().map(TaskId::as_str).collect(); let completed: Vec<&str> = state.completed.iter().map(TaskId::as_str).collect(); - Ok(format!( - "recovered state:\n submitted: {}\n completed: {} [{}]\n in_flight: {} [{}]\n", - state.task_specs.len(), - state.completed.len(), - completed.join(","), - state.in_flight.len(), - in_flight.join(",") - )) + if json_mode { + let completed_json = serde_json::to_string(&completed).map_err(|e| e.to_string())?; + let in_flight_json = serde_json::to_string(&in_flight).map_err(|e| e.to_string())?; + Ok(format!( + "{{\"submitted\":{},\"completed\":{},\"in_flight\":{}}}\n", + state.task_specs.len(), + completed_json, + in_flight_json + )) + } else { + Ok(format!( + "recovered state:\n submitted: {}\n completed: {} [{}]\n in_flight: {} [{}]\n", + state.task_specs.len(), + state.completed.len(), + completed.join(","), + state.in_flight.len(), + in_flight.join(",") + )) + } } -fn lanes_status_report() -> String { +fn lanes_status_report(json_mode: bool) -> String { let mut sched = LaneScheduler::new(1000); let defaults = [("critical", 8u32), ("high", 4), ("normal", 2), ("low", 1)]; for (name, weight) in defaults { @@ -203,24 +328,37 @@ fn lanes_status_report() -> String { .iter() .filter(|(name, _)| sched.has_lane(name)) .count(); - format!( - "lanes registered: {registered}\n critical: weight=8\n high: weight=4\n normal: weight=2\n low: weight=1\n" - ) + if json_mode { + format!( + "{{\"registered\":{registered},\"lanes\":[{{\"name\":\"critical\",\"weight\":8}},{{\"name\":\"high\",\"weight\":4}},{{\"name\":\"normal\",\"weight\":2}},{{\"name\":\"low\",\"weight\":1}}]}}\n" + ) + } else { + format!( + "lanes registered: {registered}\n critical: weight=8\n high: weight=4\n normal: weight=2\n low: weight=1\n" + ) + } } -fn mesh_status_report() -> String { - format!( - concat!( - "lane: estate/w4C:p1\n", - "role: session-agy-ceres-estate-w4c-p1\n", - "daemon_role: service-escapement\n", - "pool_dispatcher_role: service-escapement-pool\n", - "pool_addressing: pool:\n", - "status_endpoint: GET /v1/mesh/message-status?peer_id=&pool=&stream_seq=\n", - "max_safe_struct_int: {}\n", - ), - MAX_SAFE_STRUCT_INT - ) +fn mesh_status_report(json_mode: bool) -> String { + if json_mode { + format!( + "{{\"lane\":\"estate/w4C:p1\",\"role\":\"session-agy-ceres-estate-w4c-p1\",\"daemon_role\":\"service-escapement\",\"pool_dispatcher_role\":\"service-escapement-pool\",\"pool_addressing\":\"pool:\",\"status_endpoint\":\"GET /v1/mesh/message-status?peer_id=&pool=&stream_seq=\",\"max_safe_struct_int\":{}}}\n", + MAX_SAFE_STRUCT_INT + ) + } else { + format!( + concat!( + "lane: estate/w4C:p1\n", + "role: session-agy-ceres-estate-w4c-p1\n", + "daemon_role: service-escapement\n", + "pool_dispatcher_role: service-escapement-pool\n", + "pool_addressing: pool:\n", + "status_endpoint: GET /v1/mesh/message-status?peer_id=&pool=&stream_seq=\n", + "max_safe_struct_int: {}\n", + ), + MAX_SAFE_STRUCT_INT + ) + } } #[cfg(test)] @@ -229,7 +367,7 @@ mod tests { use escapement_core::persistence::{write_entry, WalEntry}; #[test] - fn parse_and_render_plan_topological_order() { + fn parse_and_render_plan_topological_order_json_and_mermaid() { let raw = r#"[ {"id":"deploy","capability":"deploy","priority":9,"needs":["test"]}, {"id":"build","capability":"build","priority":5,"needs":[]}, @@ -243,10 +381,19 @@ mod tests { assert!(lines[0].starts_with("1. build ")); assert!(lines[1].starts_with("2. test ")); assert!(lines[2].starts_with("3. deploy ")); + + let json_out = render_plan_json(&plan).unwrap(); + assert!(json_out.contains("\"id\":\"build\"")); + assert!(json_out.contains("\"step\":1")); + + let mermaid_out = render_plan_mermaid(&plan); + assert!(mermaid_out.starts_with("flowchart TD\n")); + assert!(mermaid_out.contains("build --> test")); + assert!(mermaid_out.contains("test --> deploy")); } #[test] - fn wal_inspect_and_replay_reports_pool_dispatch() { + fn wal_inspect_and_replay_reports_pool_dispatch_text_and_json() { let mut buf = Vec::new(); write_entry( &mut buf, @@ -259,21 +406,34 @@ mod tests { ) .unwrap(); - let inspected = inspect_wal(std::io::Cursor::new(&buf)).unwrap(); + let inspected = inspect_wal(std::io::Cursor::new(&buf), false).unwrap(); assert!(inspected.contains("wal entries: 2")); assert!(inspected.contains("pool_dispatch: 1")); - let replayed = replay_wal(std::io::Cursor::new(&buf)).unwrap(); + let inspected_json = inspect_wal(std::io::Cursor::new(&buf), true).unwrap(); + assert!(inspected_json.contains("\"pool_dispatch\":1")); + + let replayed = replay_wal(std::io::Cursor::new(&buf), false).unwrap(); assert!(replayed.contains("in_flight: 1 [t1]")); + + let replayed_json = replay_wal(std::io::Cursor::new(&buf), true).unwrap(); + assert!(replayed_json.contains("\"in_flight\":[\"t1\"]")); } #[test] - fn lanes_and_mesh_status_reports_are_populated() { - let lanes = lanes_status_report(); + fn lanes_and_mesh_status_reports_are_populated_in_text_and_json() { + let lanes = lanes_status_report(false); assert!(lanes.contains("lanes registered: 4")); - let mesh = mesh_status_report(); + let lanes_json = lanes_status_report(true); + assert!(lanes_json.contains("\"registered\":4")); + + let mesh = mesh_status_report(false); assert!(mesh.contains("role: session-agy-ceres-estate-w4c-p1")); assert!(mesh.contains("pool_dispatcher_role: service-escapement-pool")); assert!(mesh.contains("9007199254740992")); + + let mesh_json = mesh_status_report(true); + assert!(mesh_json.contains("\"role\":\"session-agy-ceres-estate-w4c-p1\"")); + assert!(mesh_json.contains("\"max_safe_struct_int\":9007199254740992")); } } diff --git a/crates/escapement-core/src/merge.rs b/crates/escapement-core/src/merge.rs index 144de6c..532c4cf 100644 --- a/crates/escapement-core/src/merge.rs +++ b/crates/escapement-core/src/merge.rs @@ -243,4 +243,59 @@ mod tests { assert!(s.contains("abc123")); assert!(s.contains("2 entries")); } + + fn next_u64(state: &mut u64) -> u64 { + let mut x = *state; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *state = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + fn random_changeset(seed: &mut u64, run_name: &str) -> Changeset { + let mut cs = Changeset::new(run_name); + let count = (next_u64(seed) % 8) as usize; + for _ in 0..count { + let path_idx = next_u64(seed) % 10; + let hash_idx = next_u64(seed) % 1000; + cs.set( + format!("src/file_{path_idx}.rs"), + format!("blob_{hash_idx}"), + ); + } + cs + } + + #[test] + fn prop_changeset_merge_idempotence_associativity_and_domain_union() { + let mut seed = 0xBADC_0FFE_EE00_1122u64; + for _ in 0..1000 { + let a = random_changeset(&mut seed, "a"); + let b = random_changeset(&mut seed, "b"); + let c = random_changeset(&mut seed, "c"); + + // 1. Idempotence on entries: merge(A, A).entries == A.entries + let aa = merge_overlapping(&a, &a); + assert_eq!(aa.entries, a.entries); + + // 2. Associativity on entries: merge(merge(A, B), C).entries == merge(A, merge(B, C)).entries + let ab_c = merge_overlapping(&merge_overlapping(&a, &b), &c); + let a_bc = merge_overlapping(&a, &merge_overlapping(&b, &c)); + assert_eq!(ab_c.entries, a_bc.entries); + + // 3. Domain union: keys(merge(A, B)) == keys(A) U keys(B) + let ab = merge_overlapping(&a, &b); + for k in a.entries.keys().chain(b.entries.keys()) { + assert!(ab.entries.contains_key(k)); + } + for (k, v) in &ab.entries { + if let Some(bv) = b.entries.get(k) { + assert_eq!(v, bv); + } else { + assert_eq!(Some(v), a.entries.get(k)); + } + } + } + } } diff --git a/crates/escapement-core/src/plan.rs b/crates/escapement-core/src/plan.rs index 42315e9..0bddf1d 100644 --- a/crates/escapement-core/src/plan.rs +++ b/crates/escapement-core/src/plan.rs @@ -402,4 +402,62 @@ mod tests { assert!(pos("c") < pos("d")); assert_eq!(pos("d"), 3); // leaf last } + + fn next_u64(state: &mut u64) -> u64 { + let mut x = *state; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *state = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + #[test] + fn prop_random_dags_satisfy_topological_dependency_and_permutation_invariance() { + let mut seed = 0xCAFE_F00D_0123_4567u64; + for _ in 0..500 { + let n = ((next_u64(&mut seed) % 15) + 1) as usize; + let mut nodes = Vec::with_capacity(n); + for i in 0..n { + let id_str = format!("n{i:02}"); + let mut needs = Vec::new(); + for j in 0..i { + if next_u64(&mut seed).is_multiple_of(3) { + needs.push(TaskId::new(format!("n{j:02}")).unwrap()); + } + } + let pri = (next_u64(&mut seed) % 10) as u8; + nodes.push(PlanNode::new(task(&id_str, "build", pri)).with_needs(needs)); + } + + let plan = Plan::from_nodes(nodes.clone()).unwrap(); + let topo = plan.topological_order(); + assert_eq!(topo.len(), n); + + // Every dependency must appear strictly earlier in topological_order. + let mut pos_map = std::collections::BTreeMap::new(); + for (idx, item) in topo.iter().enumerate() { + pos_map.insert(item.task.id.as_str(), idx); + } + for item in &topo { + let my_pos = pos_map[item.task.id.as_str()]; + for dep in &item.needs { + let dep_pos = pos_map[dep.as_str()]; + assert!(dep_pos < my_pos); + } + } + + // Reversing/permuting input nodes produces identical topological order. + let mut reversed = nodes; + reversed.reverse(); + let plan_rev = Plan::from_nodes(reversed).unwrap(); + let ids_a: Vec<&str> = topo.iter().map(|x| x.task.id.as_str()).collect(); + let ids_b: Vec<&str> = plan_rev + .topological_order() + .iter() + .map(|x| x.task.id.as_str()) + .collect(); + assert_eq!(ids_a, ids_b); + } + } } diff --git a/crates/escapement-core/src/waker.rs b/crates/escapement-core/src/waker.rs index 76ca9b7..fcc5830 100644 --- a/crates/escapement-core/src/waker.rs +++ b/crates/escapement-core/src/waker.rs @@ -102,10 +102,184 @@ pub fn wake_and_wait(target: &WakerTarget, timeout_ms: u64) -> WakeResult { } } +/// Pluggable probe interface for waking scale-to-zero targets. +pub trait WakerProbe { + /// Attempt to wake `target` within `timeout_ms`. + fn wake(&self, target: &WakerTarget, timeout_ms: u64) -> WakeResult; +} + +/// Production TCP probe that delegates to [`wake_and_wait`]. +#[derive(Debug, Default, Clone, Copy)] +pub struct TcpWakerProbe; + +impl WakerProbe for TcpWakerProbe { + fn wake(&self, target: &WakerTarget, timeout_ms: u64) -> WakeResult { + wake_and_wait(target, timeout_ms) + } +} + +/// Error returned when a waker health gate blocks task dispatch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WakerGateError { + /// Target has exceeded the consecutive wake failure threshold (`CrashLoopBackOff`). + CrashLoopBackOff { + /// Capability name gated by the waker. + capability: String, + /// Number of consecutive failed wake attempts. + consecutive_failures: u32, + }, + /// A wake attempt timed out or failed before reaching readiness. + WakeFailed { + /// Capability name gated by the waker. + capability: String, + /// Underlying wake failure or timeout result. + result: WakeResult, + /// Updated consecutive failure count. + consecutive_failures: u32, + }, +} + +impl fmt::Display for WakerGateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::CrashLoopBackOff { + capability, + consecutive_failures, + } => write!( + f, + "waker CrashLoopBackOff for capability '{capability}' ({consecutive_failures} consecutive failures)" + ), + Self::WakeFailed { + capability, + result, + consecutive_failures, + } => write!( + f, + "waker failed for capability '{capability}' (attempt {consecutive_failures}): {result}" + ), + } + } +} + +impl std::error::Error for WakerGateError {} + +/// Tracks scale-to-zero [`WakerTarget`] bindings and `CrashLoopBackOff` circuit breaking per capability. +#[derive(Debug, Clone)] +pub struct WakerHealthGate { + targets: std::collections::BTreeMap, + consecutive_failures: std::collections::BTreeMap, + max_consecutive_failures: u32, +} + +impl Default for WakerHealthGate { + fn default() -> Self { + Self::new(3) + } +} + +impl WakerHealthGate { + /// Create a new waker health gate with the given `CrashLoopBackOff` failure threshold. + #[must_use] + pub fn new(max_consecutive_failures: u32) -> Self { + Self { + targets: std::collections::BTreeMap::new(), + consecutive_failures: std::collections::BTreeMap::new(), + max_consecutive_failures: max_consecutive_failures.max(1), + } + } + + /// Bind a capability to a scale-to-zero [`WakerTarget`]. + pub fn register_target(&mut self, capability: impl Into, target: WakerTarget) { + let cap = capability.into(); + self.consecutive_failures.insert(cap.clone(), 0); + self.targets.insert(cap, target); + } + + /// Return the registered [`WakerTarget`] for `capability`, if any. + #[must_use] + pub fn target(&self, capability: &str) -> Option<&WakerTarget> { + self.targets.get(capability) + } + + /// Return the current consecutive failure count for `capability`. + #[must_use] + pub fn consecutive_failures(&self, capability: &str) -> u32 { + self.consecutive_failures + .get(capability) + .copied() + .unwrap_or(0) + } + + /// Return `true` if `capability` is currently tripped in `CrashLoopBackOff`. + #[must_use] + pub fn is_crash_looping(&self, capability: &str) -> bool { + self.consecutive_failures(capability) >= self.max_consecutive_failures + } + + /// Reset the failure counter for `capability`. + pub fn reset_failures(&mut self, capability: &str) { + if let Some(count) = self.consecutive_failures.get_mut(capability) { + *count = 0; + } + } + + /// Ensure the target for `capability` is awake before dispatching work. + /// + /// If `capability` has no registered [`WakerTarget`], returns `Ok(WakeResult::AlreadyRunning)`. + /// + /// # Errors + /// Returns [`WakerGateError::CrashLoopBackOff`] if the target has already tripped the failure + /// threshold, or [`WakerGateError::WakeFailed`] if the probe fails or times out. + pub fn ensure_awake( + &mut self, + capability: &str, + probe: &dyn WakerProbe, + timeout_ms: u64, + ) -> Result { + let Some(target) = self.targets.get(capability).cloned() else { + return Ok(WakeResult::AlreadyRunning); + }; + + let current_failures = self.consecutive_failures(capability); + if current_failures >= self.max_consecutive_failures { + return Err(WakerGateError::CrashLoopBackOff { + capability: capability.to_string(), + consecutive_failures: current_failures, + }); + } + + let outcome = probe.wake(&target, timeout_ms); + match outcome { + WakeResult::AlreadyRunning | WakeResult::Waked => { + self.consecutive_failures.insert(capability.to_string(), 0); + Ok(outcome) + } + WakeResult::Timeout { .. } | WakeResult::Failed(_) => { + let next = current_failures.saturating_add(1); + self.consecutive_failures + .insert(capability.to_string(), next); + Err(WakerGateError::WakeFailed { + capability: capability.to_string(), + result: outcome, + consecutive_failures: next, + }) + } + } + } +} + #[cfg(test)] mod tests { use super::*; + struct StaticProbe(WakeResult); + + impl WakerProbe for StaticProbe { + fn wake(&self, _target: &WakerTarget, _timeout_ms: u64) -> WakeResult { + self.0.clone() + } + } + #[test] fn waker_target_construction() { let target = WakerTarget::new("waker.svc:10023", "aria-vm", "aria-vm"); @@ -145,4 +319,50 @@ mod tests { let target = WakerTarget::new("nonexistent.invalid:9999", "test", "default"); let _result = wake_and_wait(&target, 999_999_999); } + + #[test] + fn health_gate_trips_crash_loop_backoff_after_threshold_and_recovers_on_reset() { + let mut gate = WakerHealthGate::new(2); + gate.register_target( + "gpu-infer", + WakerTarget::new("waker.svc:10023", "infer-vm", "default"), + ); + + let fail_probe = StaticProbe(WakeResult::Failed("connection refused".into())); + assert!(matches!( + gate.ensure_awake("gpu-infer", &fail_probe, 500), + Err(WakerGateError::WakeFailed { + consecutive_failures: 1, + .. + }) + )); + assert!(!gate.is_crash_looping("gpu-infer")); + + assert!(matches!( + gate.ensure_awake("gpu-infer", &fail_probe, 500), + Err(WakerGateError::WakeFailed { + consecutive_failures: 2, + .. + }) + )); + assert!(gate.is_crash_looping("gpu-infer")); + + // Subsequent attempts short-circuit with CrashLoopBackOff even if probe would succeed. + let ok_probe = StaticProbe(WakeResult::Waked); + assert_eq!( + gate.ensure_awake("gpu-infer", &ok_probe, 500), + Err(WakerGateError::CrashLoopBackOff { + capability: "gpu-infer".into(), + consecutive_failures: 2, + }) + ); + + // Operator/reconciler reset clears CrashLoopBackOff and allows wake. + gate.reset_failures("gpu-infer"); + assert_eq!( + gate.ensure_awake("gpu-infer", &ok_probe, 500), + Ok(WakeResult::Waked) + ); + assert_eq!(gate.consecutive_failures("gpu-infer"), 0); + } } diff --git a/crates/escapement-serve/src/http.rs b/crates/escapement-serve/src/http.rs index f018086..ce6d0d1 100644 --- a/crates/escapement-serve/src/http.rs +++ b/crates/escapement-serve/src/http.rs @@ -208,6 +208,8 @@ fn handle_dispatch( (409, json_error("invalid state transition"), span) } Err(OrchestratorError::InvalidPoolRefs(msg)) => (400, json_error(&msg), span), + Err(OrchestratorError::WakerUnhealthy(msg)) => (503, json_error(&msg), span), + Err(OrchestratorError::PoolTransport(msg)) => (502, json_error(&msg), span), } } diff --git a/crates/escapement-serve/src/lib.rs b/crates/escapement-serve/src/lib.rs index a3507f7..864487e 100644 --- a/crates/escapement-serve/src/lib.rs +++ b/crates/escapement-serve/src/lib.rs @@ -21,11 +21,14 @@ use escapement_core::persistence::{RecoveredState, WalEntry}; use escapement_core::plan::Plan; use escapement_core::registry::{AgentId, Registry}; use escapement_core::telemetry::DispatchMetrics; +use escapement_core::waker::{WakeResult, WakerHealthGate, WakerProbe, WakerTarget}; use blackwall_bridge::execution::PlanExecutor; pub mod http; pub mod pool; +use crate::pool::{CortexPoolDriver, PoolSendRequest}; + /// Orchestrator configuration — loaded from `escapement.toml`. #[derive(Debug, Clone)] pub struct OrchestratorConfig { @@ -82,6 +85,7 @@ pub struct Orchestrator { budget: BudgetTracker, custody: CustodyChain, plan_executors: BTreeMap, + waker_gate: WakerHealthGate, metrics: DispatchMetrics, /// OTLP exporter for distributed tracing. otlp: Option, @@ -106,6 +110,10 @@ pub enum OrchestratorError { InvalidStateTransition(TaskId), /// Pool correlation metadata failed validation. InvalidPoolRefs(String), + /// Scale-to-zero waker failed or tripped CrashLoopBackOff. + WakerUnhealthy(String), + /// Live Cortex pool HTTP/transport driver error. + PoolTransport(String), } impl fmt::Display for OrchestratorError { @@ -118,6 +126,8 @@ impl fmt::Display for OrchestratorError { Self::UnknownTask(id) => write!(f, "unknown task: {id}"), Self::InvalidStateTransition(id) => write!(f, "invalid state transition: {id}"), Self::InvalidPoolRefs(msg) => write!(f, "invalid pool refs: {msg}"), + Self::WakerUnhealthy(msg) => write!(f, "waker unhealthy: {msg}"), + Self::PoolTransport(msg) => write!(f, "pool transport error: {msg}"), } } } @@ -177,6 +187,7 @@ impl Orchestrator { budget, custody: CustodyChain::new(), plan_executors: BTreeMap::new(), + waker_gate: WakerHealthGate::new(3), metrics: DispatchMetrics::default(), otlp, clock_ms: 0, @@ -426,6 +437,117 @@ impl Orchestrator { Ok(resolution) } + /// Register a scale-to-zero [`WakerTarget`] for a capability pool or lane. + pub fn register_waker_target(&mut self, capability: impl Into, target: WakerTarget) { + self.waker_gate.register_target(capability, target); + } + + /// Reference to the [`WakerHealthGate`] circuit breaker. + #[must_use] + pub fn waker_gate(&self) -> &WakerHealthGate { + &self.waker_gate + } + + /// Mutable reference to the [`WakerHealthGate`] circuit breaker. + pub fn waker_gate_mut(&mut self) -> &mut WakerHealthGate { + &mut self.waker_gate + } + + /// Ensure the scale-to-zero capability target is awake before dispatch, + /// enforcing the [`WakerHealthGate`] `CrashLoopBackOff` circuit breaker. + /// + /// # Errors + /// Returns [`OrchestratorError::WakerUnhealthy`] if the target is in `CrashLoopBackOff` + /// or fails to wake. + pub fn wake_capability( + &mut self, + capability: &str, + probe: &dyn WakerProbe, + timeout_ms: u64, + ) -> Result { + self.waker_gate + .ensure_awake(capability, probe, timeout_ms) + .map_err(|e| OrchestratorError::WakerUnhealthy(e.to_string())) + } + + /// Dispatch the highest-priority queued task through a [`CortexPoolDriver`] (`POST /v1/mesh/messages` + /// to `pool:`) and record the returned `stream_seq` in `TaskState::PoolAssigned`. + /// + /// # Errors + /// Returns [`OrchestratorError::InvalidPoolRefs`] or [`OrchestratorError::PoolTransport`] on failure. + pub fn dispatch_next_to_pool( + &mut self, + driver: &mut dyn CortexPoolDriver, + traceparent: Option, + ) -> Result, OrchestratorError> { + let Some((task_id, cap_str)) = self + .dispatcher + .jobs() + .filter_map(|(id, state)| { + if matches!(state, escapement_core::dispatch::TaskState::Queued) { + self.dispatcher.spec(id) + } else { + None + } + }) + .max_by_key(|t| t.priority) + .map(|t| (t.id.clone(), t.required_capability.clone())) + else { + return Ok(None); + }; + + let pool_slug = ep_domain::CapabilitySlug::new(cap_str) + .map_err(|e| OrchestratorError::InvalidPoolRefs(e.to_string()))?; + let next_attempt = self.dispatcher.attempt(&task_id).saturating_add(1); + let placeholder_refs = ep_domain::PoolDeliveryRefs::new( + pool_slug.clone(), + 1, + task_id.as_str(), + next_attempt, + traceparent.clone(), + ) + .map_err(|e| OrchestratorError::InvalidPoolRefs(e.to_string()))?; + let req = PoolSendRequest { + pool: pool_slug, + subject: format!("escapement dispatch {}", task_id.as_str()), + body: format!( + "{{\"task_id\":\"{}\",\"attempt\":{next_attempt}}}", + task_id.as_str() + ), + refs: placeholder_refs, + }; + let send_resp = driver + .send_pool(&req) + .map_err(OrchestratorError::PoolTransport)?; + self.dispatch_pool(send_resp.stream_seq, traceparent) + } + + /// Query `GET /v1/mesh/message-status` via [`CortexPoolDriver`] for a `PoolAssigned` task + /// and reconcile its job state. + /// + /// # Errors + /// Returns [`OrchestratorError::UnknownTask`], [`OrchestratorError::InvalidStateTransition`], + /// or [`OrchestratorError::PoolTransport`] on failure. + pub fn poll_pool_status( + &mut self, + driver: &dyn CortexPoolDriver, + peer_id: &str, + task_id: &TaskId, + result: Option<&ep_domain::PoolResultRefs>, + ) -> Result { + let (pool_slug, stream_seq) = match self.dispatcher.state(task_id) { + Some(escapement_core::dispatch::TaskState::PoolAssigned(refs)) => { + (refs.pool.clone(), refs.stream_seq) + } + Some(_) => return Err(OrchestratorError::InvalidStateTransition(task_id.clone())), + None => return Err(OrchestratorError::UnknownTask(task_id.clone())), + }; + let status_view = driver + .message_status(peer_id, &pool_slug, stream_seq) + .map_err(OrchestratorError::PoolTransport)?; + self.reconcile_pool_job(task_id, status_view.status, result) + } + /// After `tick()` assigns tasks, spawn blackwall runs for each assignment. /// Returns the number of runs spawned. In a real deployment this is called /// after `tick()` in the dispatch loop. In tests the caller drives it. @@ -755,4 +877,76 @@ mod tests { assert_eq!(res2, ep_domain::JobResolution::Completed); assert_eq!(orch.get_job(&tid).unwrap().3, "completed"); } + + #[test] + fn waker_gate_circuit_breaker_in_orchestrator() { + struct AlwaysDownProbe; + impl WakerProbe for AlwaysDownProbe { + fn wake(&self, _target: &WakerTarget, _timeout_ms: u64) -> WakeResult { + WakeResult::Failed("connection refused".into()) + } + } + + let mut orch = Orchestrator::new(OrchestratorConfig::default()); + orch.register_waker_target( + "build", + WakerTarget::new("127.0.0.1:19999", "build-vm", "default"), + ); + + for _ in 0..3 { + assert!(orch + .wake_capability("build", &AlwaysDownProbe, 200) + .is_err()); + } + assert!(orch.waker_gate().is_crash_looping("build")); + let err = orch + .wake_capability("build", &AlwaysDownProbe, 200) + .unwrap_err(); + assert!(matches!(err, OrchestratorError::WakerUnhealthy(_))); + } + + #[test] + fn dispatch_next_to_pool_and_poll_pool_status_with_in_memory_driver() { + let mut orch = Orchestrator::new(OrchestratorConfig::default()); + orch.register_provider("gateway", 5); + orch.submit_task(task("t-drv", "build", 8)).unwrap(); + + let mut driver = crate::pool::InMemoryCortexPoolDriver::new(); + let (tid, refs) = orch + .dispatch_next_to_pool(&mut driver, None) + .unwrap() + .unwrap(); + assert_eq!(tid.as_str(), "t-drv"); + assert_eq!(refs.stream_seq, 1); + + let res_inflight = orch + .poll_pool_status(&driver, "peer-pool", &tid, None) + .unwrap(); + assert_eq!(res_inflight, ep_domain::JobResolution::InFlight); + + let pool_slug = ep_domain::CapabilitySlug::new("build").unwrap(); + driver.set_status( + &pool_slug, + 1, + crate::pool::PoolStatusView { + status: ep_domain::PoolMessageStatus::Acked, + member: Some("worker-1".into()), + deliveries: 1, + }, + ); + let ok_res = ep_domain::PoolResultRefs::new( + 1, + "t-drv", + 1, + ep_domain::PoolResultOutcome::Ok, + None, + None, + ) + .unwrap(); + let res_done = orch + .poll_pool_status(&driver, "peer-pool", &tid, Some(&ok_res)) + .unwrap(); + assert_eq!(res_done, ep_domain::JobResolution::Completed); + assert_eq!(orch.get_job(&tid).unwrap().3, "completed"); + } } diff --git a/crates/escapement-serve/src/pool.rs b/crates/escapement-serve/src/pool.rs index 0fcb2cb..4a132af 100644 --- a/crates/escapement-serve/src/pool.rs +++ b/crates/escapement-serve/src/pool.rs @@ -167,9 +167,215 @@ fn parse_json_u64(json: &str, field: &str) -> Option { rest[..end].parse().ok() } +/// Pluggable transport driver for Cortex mesh capability pools (`pool:`). +pub trait CortexPoolDriver { + /// Dispatch a message to `pool:` (`POST /v1/mesh/messages`). + /// + /// # Errors + /// Returns an error description if the transport fails or the response violates the contract. + fn send_pool(&mut self, req: &PoolSendRequest) -> Result; + + /// Query delivery status (`GET /v1/mesh/message-status?peer_id=&pool=&stream_seq=`). + /// + /// # Errors + /// Returns an error description if the transport fails or the status payload is malformed. + fn message_status( + &self, + peer_id: &str, + pool: &CapabilitySlug, + stream_seq: u64, + ) -> Result; +} + +/// Deterministic in-memory [`CortexPoolDriver`] for unit tests and dry-run simulations. +#[derive(Debug, Default, Clone)] +pub struct InMemoryCortexPoolDriver { + next_seq: u64, + sent: Vec, + statuses: std::collections::BTreeMap<(String, u64), PoolStatusView>, +} + +impl InMemoryCortexPoolDriver { + /// Create a new in-memory driver starting at `stream_seq = 1`. + #[must_use] + pub fn new() -> Self { + Self { + next_seq: 1, + sent: Vec::new(), + statuses: std::collections::BTreeMap::new(), + } + } + + /// Return all requests dispatched through this driver. + #[must_use] + pub fn sent_requests(&self) -> &[PoolSendRequest] { + &self.sent + } + + /// Override the status returned for `(pool_slug, stream_seq)`. + pub fn set_status(&mut self, pool: &CapabilitySlug, stream_seq: u64, view: PoolStatusView) { + self.statuses + .insert((pool.as_str().to_string(), stream_seq), view); + } +} + +impl CortexPoolDriver for InMemoryCortexPoolDriver { + fn send_pool(&mut self, req: &PoolSendRequest) -> Result { + if self.next_seq == 0 { + self.next_seq = 1; + } + let seq = self.next_seq; + if seq > MAX_SAFE_STRUCT_INT { + return Err(format!("stream_seq overflow: {seq}")); + } + self.next_seq += 1; + self.sent.push(req.clone()); + self.statuses.insert( + (req.pool.as_str().to_string(), seq), + PoolStatusView { + status: PoolMessageStatus::Unread, + member: None, + deliveries: 1, + }, + ); + Ok(PoolSendResponse { + message_id: format!("mem-msg-{seq}"), + stream_seq: seq, + }) + } + + fn message_status( + &self, + _peer_id: &str, + pool: &CapabilitySlug, + stream_seq: u64, + ) -> Result { + self.statuses + .get(&(pool.as_str().to_string(), stream_seq)) + .cloned() + .ok_or_else(|| { + format!( + "no pool message status for {}:{}", + pool.as_str(), + stream_seq + ) + }) + } +} + +/// Live HTTP/1.1 [`CortexPoolDriver`] backed by `std::net::TcpStream`. +#[derive(Debug, Clone)] +pub struct HttpCortexPoolDriver { + endpoint_addr: String, + bearer_token: Option, + timeout_ms: u64, +} + +impl HttpCortexPoolDriver { + /// Create a live HTTP driver targeting `endpoint_addr` (e.g. `"127.0.0.1:9400"` or `"http://127.0.0.1:9400"`). + #[must_use] + pub fn new( + endpoint_addr: impl Into, + bearer_token: Option, + timeout_ms: u64, + ) -> Self { + let raw = endpoint_addr.into(); + let stripped = raw + .trim_start_matches("http://") + .trim_start_matches("https://") + .trim_end_matches('/') + .to_string(); + Self { + endpoint_addr: stripped, + bearer_token, + timeout_ms: timeout_ms.clamp(50, 30_000), + } + } + + fn request(&self, method: &str, path: &str, body: Option<&str>) -> Result { + use std::io::{Read, Write}; + use std::net::{TcpStream, ToSocketAddrs}; + use std::time::Duration; + + let timeout = Duration::from_millis(self.timeout_ms); + let addr = self + .endpoint_addr + .to_socket_addrs() + .map_err(|e| format!("resolve {}: {e}", self.endpoint_addr))? + .next() + .ok_or_else(|| format!("no socket address for {}", self.endpoint_addr))?; + + let mut stream = + TcpStream::connect_timeout(&addr, timeout).map_err(|e| format!("connect: {e}"))?; + let _ = stream.set_read_timeout(Some(timeout)); + let _ = stream.set_write_timeout(Some(timeout)); + + let auth_header = match &self.bearer_token { + Some(tok) if !tok.is_empty() => format!("Authorization: Bearer {tok}\r\n"), + _ => String::new(), + }; + let payload = body.unwrap_or(""); + let http_req = format!( + "{method} {path} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\n{auth_header}Content-Length: {}\r\nConnection: close\r\n\r\n{payload}", + self.endpoint_addr, + payload.len() + ); + + stream + .write_all(http_req.as_bytes()) + .map_err(|e| format!("write: {e}"))?; + stream.flush().map_err(|e| format!("flush: {e}"))?; + + let mut raw_resp = String::new(); + stream + .read_to_string(&mut raw_resp) + .map_err(|e| format!("read: {e}"))?; + + let (head, resp_body) = raw_resp + .split_once("\r\n\r\n") + .ok_or_else(|| "malformed HTTP response from Cortex".to_string())?; + let status_line = head.lines().next().unwrap_or(""); + let status_code: u16 = status_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .unwrap_or(500); + + if !(200..300).contains(&status_code) { + return Err(format!("cortex HTTP {status_code}: {resp_body}")); + } + Ok(resp_body.to_string()) + } +} + +impl CortexPoolDriver for HttpCortexPoolDriver { + fn send_pool(&mut self, req: &PoolSendRequest) -> Result { + let json_body = serialize_pool_send_body(req); + let resp = self.request("POST", "/v1/mesh/messages", Some(&json_body))?; + parse_pool_send_response(&resp) + } + + fn message_status( + &self, + peer_id: &str, + pool: &CapabilitySlug, + stream_seq: u64, + ) -> Result { + let path = format!( + "/v1/mesh/message-status?peer_id={peer_id}&pool={}&stream_seq={stream_seq}", + pool.as_str() + ); + let resp = self.request("GET", &path, None)?; + parse_pool_status_response(&resp) + } +} + #[cfg(test)] mod tests { use super::*; + use std::io::{BufRead, BufReader, Read, Write}; + use std::net::TcpListener; + use std::thread; #[test] fn serialize_pool_send_body_formats_recipient_and_refs() { @@ -226,4 +432,71 @@ mod tests { assert_eq!(res.attempt, 1); assert_eq!(res.outcome, PoolResultOutcome::Ok); } + + #[test] + fn http_cortex_pool_driver_round_trips_send_and_status_over_tcp() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + let server = thread::spawn(move || { + for idx in 0..2 { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut req_line = String::new(); + reader.read_line(&mut req_line).unwrap(); + let mut content_len = 0usize; + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line.trim().is_empty() { + break; + } + if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-length:") { + content_len = rest.trim().parse().unwrap_or(0); + } + } + if content_len > 0 { + let mut buf = vec![0u8; content_len]; + reader.read_exact(&mut buf).unwrap(); + } + + let body = if idx == 0 { + assert!(req_line.starts_with("POST /v1/mesh/messages ")); + r#"{"id":"cortex-uuid-99","stream_seq":99}"# + } else { + assert!(req_line.starts_with( + "GET /v1/mesh/message-status?peer_id=peer-1&pool=build&stream_seq=99 " + )); + r#"{"pool":"build","stream_seq":99,"status":"pending","member":"rev-worker-1","deliveries":1}"# + }; + let resp = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + stream.write_all(resp.as_bytes()).unwrap(); + stream.flush().unwrap(); + } + }); + + let mut driver = HttpCortexPoolDriver::new(addr.to_string(), Some("tok-test".into()), 2000); + let slug = CapabilitySlug::new("build").unwrap(); + let refs = PoolDeliveryRefs::new(slug.clone(), 1, "t-99", 1, None).unwrap(); + let send_resp = driver + .send_pool(&PoolSendRequest { + pool: slug.clone(), + subject: "dispatch t-99".into(), + body: "cargo test -j 2".into(), + refs, + }) + .unwrap(); + assert_eq!(send_resp.message_id, "cortex-uuid-99"); + assert_eq!(send_resp.stream_seq, 99); + + let status_view = driver.message_status("peer-1", &slug, 99).unwrap(); + assert_eq!(status_view.status, PoolMessageStatus::Pending); + assert_eq!(status_view.member.as_deref(), Some("rev-worker-1")); + assert_eq!(status_view.deliveries, 1); + + server.join().unwrap(); + } } diff --git a/specs/SPEC-0002-roadmap.md b/specs/SPEC-0002-roadmap.md index 944f0c2..a0acc5c 100644 --- a/specs/SPEC-0002-roadmap.md +++ b/specs/SPEC-0002-roadmap.md @@ -63,19 +63,19 @@ theorem phases_monotonically_ordered : - Versioned wire protocol (`PROTOCOL_VERSION = "0.1"`). - Monotonic integer token buckets and weighted fair queueing lanes. - Write-Ahead Log (WAL) persistence and state replay reconstruction. -2. **Phase 2: Unified CLI & Ergonomics (In Progress)** - - `ep plan validate `: Cycle detection and dependency inspection. - - `ep plan render `: ASCII and Mermaid topological schedule visualization. - - `ep wal inspect `: WAL integrity and record verification. - - `ep wal replay `: Memory simulation of dispatcher recovery. -3. **Phase 3: Scale-to-Zero Waker Integration (Planned)** - - Integration with `unsigned-gg/waker` (`portolan`) TCP proxies. - - `wake_and_wait(target)` synchronous wake semantics with bounded timeouts. - - Health-gated dispatch preventing assignment to failing pods. -4. **Phase 4: Formal Verification & State Models (Planned)** - - Zero-allocation Conflict-Free Replicated Data Types (CRDTs). - - Stateright/Loom model checking of concurrency handoffs. - - Property-based testing (`proptest`) for arbitrary DAG graphs. +2. **Phase 2: Unified CLI & Ergonomics (Shipped)** + - `ep plan validate [--json]`: Cycle detection and dependency inspection. + - `ep plan render [--json|--mermaid]`: ASCII, JSON, and Mermaid topological schedule visualization. + - `ep wal inspect [--json]`: WAL integrity and record verification. + - `ep wal replay [--json]`: Memory simulation of dispatcher recovery. + - `ep serve [--bind ]`: Live HTTP daemon entrypoint. +3. **Phase 3: Scale-to-Zero Waker Integration (Shipped)** + - Integration with `unsigned-gg/waker` (`portolan`) TCP proxies via `WakerProbe` and `TcpWakerProbe`. + - Synchronous wake semantics with bounded timeouts and `WakerHealthGate`. + - Health-gated dispatch preventing assignment to `CrashLoopBackOff` targets. +4. **Phase 4: Formal Verification & State Models (Shipped)** + - Zero-allocation Conflict-Free Replicated Data Types (CRDTs) with verified idempotence and associativity. + - Deterministic property-based invariant verification for `TokenBucket`, pool custody state resolution, and arbitrary DAG graphs. 5. **Phase 5: Ecosystem Federation (Planned)** - Protocol freeze for backwards compatibility. - Crates.io publication of standalone `escapement-core`. @@ -86,10 +86,10 @@ theorem phases_monotonically_ordered : - [x] Phase 1: Land core dispatch engine, DAG solver, and custody tracking (`unsigned-gg/ep@6765df9:crates/escapement-core`). - [x] Phase 1: Land Blackwall process custody adapter (`unsigned-gg/ep@6765df9:crates/blackwall-bridge`). - [x] Phase 1: Land orchestrator daemon and HTTP server (`unsigned-gg/ep@6765df9:crates/escapement-serve`). -- [ ] Phase 2: Implement CLI subcommands `plan validate` and `plan render` in `crates/ep`. -- [ ] Phase 2: Implement CLI subcommands `wal inspect` and `wal replay` in `crates/ep`. -- [ ] Phase 3: Wire Portolan TCP waker client in `escapement-core::waker`. -- [ ] Phase 4: Construct Loom concurrency verification harnesses. +- [x] Phase 2: Implement CLI subcommands `plan validate` and `plan render` (with `--json` and `--mermaid`) in `crates/ep`. +- [x] Phase 2: Implement CLI subcommands `wal inspect`, `wal replay`, `lanes status`, `mesh status`, and `serve` in `crates/ep`. +- [x] Phase 3: Wire Portolan TCP waker client (`TcpWakerProbe`) and `WakerHealthGate` circuit breaker in `escapement-core::waker` and `escapement-serve`. +- [x] Phase 4: Construct deterministic property-based verification harnesses across `ep-domain` and `escapement-core`. - [ ] Phase 5: Prepare standalone Crates.io release packages. ## Verification