From 418c0deee53ace52042873e2bc40e1c5ff0dc8f7 Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 21:25:48 -0600 Subject: [PATCH 1/7] Add design doc for core correctness and API ergonomics improvements Covers 5 phases: Process API surface, GenServer ergonomics (ServerRef, reply, stop), Supervisor completeness (terminate/delete/restart_child), Application fixes (remove unsafe, fix stop_all ordering), and documentation sync. --- ...-core-correctness-and-ergonomics-design.md | 226 ++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 docs/plans/2026-02-19-core-correctness-and-ergonomics-design.md diff --git a/docs/plans/2026-02-19-core-correctness-and-ergonomics-design.md b/docs/plans/2026-02-19-core-correctness-and-ergonomics-design.md new file mode 100644 index 0000000..3720da4 --- /dev/null +++ b/docs/plans/2026-02-19-core-correctness-and-ergonomics-design.md @@ -0,0 +1,226 @@ +# Core Correctness & API Ergonomics Design + +**Date**: 2026-02-19 +**Focus**: Core correctness + API ergonomics +**Approach**: Bottom-up (foundation first), cherry-picking best of spec and evolved code + +## Overview + +Fill in missing OTP-faithful APIs and improve developer ergonomics across all layers: Process, GenServer, Supervisor, and Application. Update documentation to match reality. + +## Phase 1: Process API Surface + +Expose existing `Context` methods as top-level `ambitious::` convenience functions. These already work internally; this phase is about wiring them into the public API. + +### New functions in `runtime/task_local.rs` + +```rust +pub fn link(pid: Pid) -> Result<(), SendError> +pub fn unlink(pid: Pid) +pub fn monitor(pid: Pid) -> Ref +pub fn demonitor(reference: Ref) +pub fn flag(flag: ProcessFlag, value: bool) -> bool +pub fn send_after(pid: Pid, msg: &impl Term, delay: Duration) -> TimerRef +``` + +### New type in `core/` + +```rust +pub enum ProcessFlag { + TrapExit, +} +``` + +### Re-exports + +Add to `lib.rs` public exports and `prelude` module: +```rust +pub use runtime::{link, unlink, monitor, demonitor, flag, send_after}; +pub use core::ProcessFlag; +``` + +### Implementation + +Each function delegates to `with_ctx()` which accesses the task-local `ProcessScope`: + +```rust +pub fn link(pid: Pid) -> Result<(), SendError> { + with_ctx(|ctx| ctx.link(pid)) +} +``` + +`send_after` delegates to `timer::send_after()` with the current process context. + +## Phase 2: GenServer Ergonomics + +### ServerRef + +Unified way to address a GenServer by Pid or registered name. + +```rust +pub enum ServerRef { + Pid(Pid), + Name(String), +} + +impl ServerRef { + pub fn resolve(&self) -> Option { + match self { + ServerRef::Pid(pid) => Some(*pid), + ServerRef::Name(name) => crate::whereis(name), + } + } +} + +impl From for ServerRef { ... } +impl From<&str> for ServerRef { ... } +impl From for ServerRef { ... } +``` + +### Updated call/cast signatures + +```rust +// Backwards-compatible: Pid still works via Into +pub async fn call( + server: impl Into, + msg: G::Call, + timeout: Duration, +) -> Result + +pub fn cast(server: impl Into, msg: G::Cast) +``` + +### Public reply() + +For deferred replies when `handle_call` returns `Reply::NoReply`: + +```rust +pub fn reply(from: From, value: T) +``` + +Extracts the existing reply encoding logic from the server loop into a public function. + +### Public stop() + +Graceful GenServer shutdown: + +```rust +pub async fn stop( + server: impl Into, + reason: ExitReason, +) -> Result<(), Error> +``` + +Resolves the ServerRef and sends an exit signal. + +## Phase 3: Supervisor Completeness + +### Architecture: SupervisorCommand + +Add command messages to the supervisor's message loop. Public functions send commands and await replies, keeping state mutation inside the supervisor process (OTP-faithful). + +```rust +enum SupervisorCommand { + TerminateChild { id: String, reply_to: Pid, reply_ref: Ref }, + DeleteChild { id: String, reply_to: Pid, reply_ref: Ref }, + RestartChild { id: String, reply_to: Pid, reply_ref: Ref }, +} +``` + +The supervisor loop decodes these from its mailbox alongside DOWN/EXIT messages. + +### terminate_child + +Stops a running child, keeps its spec. Replace current stub. + +1. Send `SupervisorCommand::TerminateChild` to supervisor +2. Supervisor looks up child, sends exit based on `ShutdownType` +3. Waits for termination (existing `wait_for_termination` helper) +4. Sets child pid to None, removes monitor +5. Updates `SUPERVISOR_STATES` query registry +6. Replies `Ok(())` + +Idempotent: if child already stopped, returns `Ok(())`. + +### delete_child + +Removes a stopped child's spec. Replace current stub. + +1. Send `SupervisorCommand::DeleteChild` to supervisor +2. Check child exists -> `DeleteError::NotFound` +3. Check child is stopped -> `DeleteError::Running` +4. Remove from `children` map and `child_order` vec +5. Update query registry +6. Reply `Ok(())` + +### restart_child + +Restart a terminated child using its existing spec. New function. + +```rust +pub async fn restart_child( + handle: &RuntimeHandle, + sup: Pid, + id: &str, +) -> Result +``` + +1. Send `SupervisorCommand::RestartChild` to supervisor +2. Check child exists -> `RestartError::NotFound` +3. Check child is stopped -> `RestartError::AlreadyRunning` +4. Call child's start function +5. Monitor new child, update state +6. Update query registry +7. Reply `Ok(new_pid)` + +## Phase 4: Application Fixes + +### Remove unsafe in AppController::start_with_config + +Change `StartFn` and `StopFn` type aliases from `Box` to `Arc`: + +```rust +type StartFn = Arc Result + Send + Sync>; +type StopFn = Arc) + Send + Sync>; +``` + +Then clone the Arc out of the lock scope and call safely. No unsafe needed. + +### Fix stop_all reverse dependency ordering + +Build the full dependency graph via `resolve_dependencies`, reverse it, and stop in that order. Dependents stop before their dependencies. + +## Phase 5: Documentation Sync + +### CLAUDE.md + +- Update crate structure diagram (consolidated single crate) +- Update GenServer trait to struct-is-state design with `&mut self` handlers +- Update return type names: `Reply`, `Status`, `Init` +- Add new Process functions (link, unlink, monitor, demonitor, flag, send_after) +- Add ServerRef, reply(), stop() to GenServer section +- Update Supervisor section with implemented terminate/delete/restart_child +- Update Message trait to actual encode_local/decode_local/encode_remote/decode_remote + +### README.md + +- Fix GenServer example to match current API +- Update crate structure diagram +- Add ServerRef usage example + +## Testing Strategy + +Each phase includes tests: + +- **Phase 1**: Test each new top-level function (link, unlink, monitor, demonitor, flag, send_after) exercises the underlying Context method +- **Phase 2**: Test ServerRef resolution (Pid, Name, not-found), call/cast with name, reply() deferred, stop() +- **Phase 3**: Test terminate_child (running child, already stopped, not found), delete_child (stopped, running, not found), restart_child (stopped, running, not found) +- **Phase 4**: Verify AppController start/stop works without unsafe, verify stop_all order with dependency chain + +## Non-Goals + +- Distribution layer changes +- New features (GenEvent, Registry via-tuples, etc.) +- Performance optimization +- Benchmarks +- Breaking API changes to existing working functions From f39463902300087066407734bb87b43e2ab043a0 Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 21:45:21 -0600 Subject: [PATCH 2/7] Add Process API surface: link, unlink, monitor, demonitor, flag, send_after Expose Erlang/OTP-style process primitives as top-level convenience functions that delegate to task-local context, matching the existing pattern used by current_pid(), send(), recv(), and exit(). - Add ProcessFlag enum (TrapExit variant) in core module - Add link/unlink for bidirectional failure propagation - Add monitor/demonitor for unidirectional process observation - Add flag() for setting process flags (returns previous value) - Add send_after() convenience wrapper with OTP argument order - Export all new functions from runtime, lib.rs, and prelude - Add integration test verifying all new functions work in process context --- crates/ambitious/src/core/mod.rs | 2 + crates/ambitious/src/core/process_flag.rs | 11 +++ crates/ambitious/src/lib.rs | 74 +++++++++++++++++-- crates/ambitious/src/runtime/mod.rs | 5 +- crates/ambitious/src/runtime/task_local.rs | 83 +++++++++++++++++++++- 5 files changed, 165 insertions(+), 10 deletions(-) create mode 100644 crates/ambitious/src/core/process_flag.rs diff --git a/crates/ambitious/src/core/mod.rs b/crates/ambitious/src/core/mod.rs index 58d7804..7a7cc6d 100644 --- a/crates/ambitious/src/core/mod.rs +++ b/crates/ambitious/src/core/mod.rs @@ -20,6 +20,7 @@ mod exit_reason; mod message; pub mod node; mod pid; +mod process_flag; mod reference; mod system_message; @@ -32,5 +33,6 @@ pub use exit_reason::ExitReason; pub use message::{DecodeError, Message, RawTerm, Term}; pub use node::{NodeId, NodeInfo, NodeName}; pub use pid::{Pid, current_creation, increment_creation}; +pub use process_flag::ProcessFlag; pub use reference::Ref; pub use system_message::SystemMessage; diff --git a/crates/ambitious/src/core/process_flag.rs b/crates/ambitious/src/core/process_flag.rs new file mode 100644 index 0000000..eb66ca2 --- /dev/null +++ b/crates/ambitious/src/core/process_flag.rs @@ -0,0 +1,11 @@ +//! Process flags for controlling process behavior. + +/// Flags that control process behavior. +/// +/// Used with `ambitious::flag()` to set process-level options. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProcessFlag { + /// When enabled, exit signals from linked processes are delivered + /// as messages instead of terminating this process. + TrapExit, +} diff --git a/crates/ambitious/src/lib.rs b/crates/ambitious/src/lib.rs index 2368788..0b4ac47 100644 --- a/crates/ambitious/src/lib.rs +++ b/crates/ambitious/src/lib.rs @@ -183,12 +183,12 @@ pub use process::global::{ // Re-export task-local functions for process operations without ctx pub use runtime::{ - current_pid, recv, recv_timeout, send, send_raw, try_current_pid, try_recv, with_ctx, - with_ctx_async, + current_pid, demonitor, exit, flag, link, monitor, recv, recv_timeout, send, send_after, + send_raw, try_current_pid, try_recv, unlink, with_ctx, with_ctx_async, }; // Re-export core types -pub use core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, RawTerm, Ref, Term}; +pub use core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, ProcessFlag, RawTerm, Ref, Term}; // Re-export runtime and process types pub use process::{Runtime, RuntimeHandle}; @@ -205,7 +205,9 @@ pub use ambitious_macros::{ChannelEvent, Message, main, self_pid, test}; /// ``` pub mod prelude { // Core types - pub use crate::core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, RawTerm, Ref, Term}; + pub use crate::core::{ + ExitReason, NodeId, NodeInfo, NodeName, Pid, ProcessFlag, RawTerm, Ref, Term, + }; // Runtime and process pub use crate::process::{Runtime, RuntimeHandle}; @@ -229,8 +231,8 @@ pub mod prelude { // Task-local functions for process operations without ctx pub use crate::runtime::{ - current_pid, recv, recv_timeout, send, send_raw, try_current_pid, try_recv, with_ctx, - with_ctx_async, + current_pid, demonitor, exit, flag, link, monitor, recv, recv_timeout, send, send_after, + send_raw, try_current_pid, try_recv, unlink, with_ctx, with_ctx_async, }; // Node API essentials @@ -417,4 +419,64 @@ mod tests { controller.stop("test_app").await.unwrap(); assert!(!controller.is_running("test_app")); } + + #[tokio::test] + async fn test_process_api_convenience_functions() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let link_ok = Arc::new(AtomicBool::new(false)); + let monitor_ok = Arc::new(AtomicBool::new(false)); + let flag_ok = Arc::new(AtomicBool::new(false)); + + let link_ok_c = link_ok.clone(); + let monitor_ok_c = monitor_ok.clone(); + let flag_ok_c = flag_ok.clone(); + + // Spawn a target process that stays alive + let target_pid = handle.spawn(|| async { + loop { + if crate::recv_timeout(std::time::Duration::from_secs(10)) + .await + .is_err() + { + break; + } + } + }); + + // Give target time to start + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + + handle.spawn(move || async move { + // Test link/unlink + assert!(crate::link(target_pid).is_ok()); + crate::unlink(target_pid); + link_ok_c.store(true, Ordering::SeqCst); + + // Test monitor/demonitor + let mon_ref = crate::monitor(target_pid).unwrap(); + crate::demonitor(mon_ref); + monitor_ok_c.store(true, Ordering::SeqCst); + + // Test flag + let prev = crate::flag(ProcessFlag::TrapExit, true); + assert!(!prev); // Was false before + let prev2 = crate::flag(ProcessFlag::TrapExit, false); + assert!(prev2); // Was true + flag_ok_c.store(true, Ordering::SeqCst); + }); + + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + assert!(link_ok.load(Ordering::SeqCst), "link/unlink should work"); + assert!( + monitor_ok.load(Ordering::SeqCst), + "monitor/demonitor should work" + ); + assert!(flag_ok.load(Ordering::SeqCst), "flag should work"); + } } diff --git a/crates/ambitious/src/runtime/mod.rs b/crates/ambitious/src/runtime/mod.rs index b6d14bf..19c4ac8 100644 --- a/crates/ambitious/src/runtime/mod.rs +++ b/crates/ambitious/src/runtime/mod.rs @@ -26,8 +26,9 @@ pub use mailbox::{Mailbox, MailboxSender}; pub use process_handle::{ProcessHandle, ProcessState}; pub use registry::{ProcessRegistry, RemoteSendHook, set_remote_send_hook}; pub use task_local::{ - ProcessScope, current_pid, exit, recv, recv_timeout, send, send_raw, set_exit_reason, - set_exit_reason_async, try_current_pid, try_recv, with_ctx, with_ctx_async, + ProcessScope, current_pid, demonitor, exit, flag, link, monitor, recv, recv_timeout, send, + send_after, send_raw, set_exit_reason, set_exit_reason_async, try_current_pid, try_recv, + unlink, with_ctx, with_ctx_async, }; // Re-export core types for convenience diff --git a/crates/ambitious/src/runtime/task_local.rs b/crates/ambitious/src/runtime/task_local.rs index 3faf331..b9e5ae8 100644 --- a/crates/ambitious/src/runtime/task_local.rs +++ b/crates/ambitious/src/runtime/task_local.rs @@ -4,8 +4,8 @@ //! allowing functions to access the current process's context without //! explicit parameter passing. -use super::{Context, Pid, SendError}; -use crate::core::ExitReason; +use super::{Context, Pid, Ref, SendError}; +use crate::core::{ExitReason, ProcessFlag}; use std::future::Future; use std::sync::Arc; use std::time::Duration; @@ -218,6 +218,85 @@ pub fn exit(target: Pid, reason: crate::core::ExitReason) { } } +/// Creates a bidirectional link with another process. +/// +/// If either process terminates abnormally, the other will receive +/// an exit signal. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn link(pid: Pid) -> Result<(), SendError> { + with_ctx(|ctx| ctx.link(pid)) +} + +/// Removes a link with another process. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn unlink(pid: Pid) { + with_ctx(|ctx| ctx.unlink(pid)) +} + +/// Creates a monitor on another process. +/// +/// Returns a reference that will be included in the `DOWN` message +/// when the monitored process terminates. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn monitor(pid: Pid) -> Result { + with_ctx(|ctx| ctx.monitor(pid)) +} + +/// Removes a monitor. +/// +/// The reference will no longer be valid and no `DOWN` message +/// will be sent for this monitor. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn demonitor(reference: Ref) { + with_ctx(|ctx| ctx.demonitor(reference)) +} + +/// Sets a process flag and returns the previous value. +/// +/// # Flags +/// +/// - `ProcessFlag::TrapExit` - When `true`, exit signals from linked +/// processes are delivered as messages instead of terminating the process. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn flag(flag: ProcessFlag, value: bool) -> bool { + match flag { + ProcessFlag::TrapExit => with_ctx(|ctx| ctx.set_trap_exit(value)), + } +} + +/// Sends a message to a process after a delay. +/// +/// Returns a [`TimerRef`] that can be used to cancel the timer. +/// +/// This is a convenience wrapper around `timer::send_after` that takes +/// arguments in OTP order: `(pid, msg, delay)`. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn send_after( + pid: Pid, + msg: &M, + delay: std::time::Duration, +) -> crate::timer::TimerResult { + crate::timer::send_after(delay, pid, msg) +} + /// Sets the exit reason for the current process. /// /// When the process function returns, this reason will be used instead of From 74c60585b5b8683b25b8bab7b2270a1379566f54 Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 21:51:52 -0600 Subject: [PATCH 3/7] Add GenServer ergonomics: ServerRef, reply, stop Phase 2 of the core correctness and API ergonomics plan: - Add ServerRef type for addressing GenServers by Pid or registered name - Update call() and cast() to accept impl Into instead of Pid - Add public reply() function for deferred reply pattern (NoReply + later reply) - Add public stop() function for graceful GenServer shutdown - Update lib.rs prelude re-exports to include ServerRef, reply, stop - Remove #[allow(dead_code)] from encode_stop (now used by stop()) - Add tests for ServerRef conversions, resolve, call with ServerRef, and stop --- crates/ambitious/src/gen_server/mod.rs | 97 ++++++++++++++++++- crates/ambitious/src/gen_server/protocol.rs | 1 - crates/ambitious/src/gen_server/server.rs | 61 +++++++++++- crates/ambitious/src/gen_server/server_ref.rs | 66 +++++++++++++ crates/ambitious/src/lib.rs | 3 +- 5 files changed, 221 insertions(+), 7 deletions(-) create mode 100644 crates/ambitious/src/gen_server/server_ref.rs diff --git a/crates/ambitious/src/gen_server/mod.rs b/crates/ambitious/src/gen_server/mod.rs index 883fa2b..6fbdf18 100644 --- a/crates/ambitious/src/gen_server/mod.rs +++ b/crates/ambitious/src/gen_server/mod.rs @@ -84,11 +84,13 @@ pub(crate) mod protocol; mod server; +mod server_ref; mod traits; mod types; // Primary exports -pub use server::{Error, call, cast, start, start_link}; +pub use server::{Error, call, cast, reply, start, start_link, stop}; +pub use server_ref::ServerRef; pub use traits::GenServer; pub use async_trait::async_trait; @@ -106,8 +108,8 @@ pub use crate::core::{ExitReason, Pid, Ref, Term}; /// ``` pub mod prelude { pub use super::{ - Error, ExitReason, From, GenServer, Init, Pid, Reply, Status, async_trait, call, cast, - start, start_link, + Error, ExitReason, From, GenServer, Init, Pid, Reply, ServerRef, Status, async_trait, call, + cast, reply, start, start_link, stop, }; } @@ -316,4 +318,93 @@ mod tests { tokio::time::sleep(Duration::from_millis(100)).await; assert_eq!(result.load(Ordering::SeqCst), 10); } + + // ========================================================================= + // Phase 2: ServerRef, reply, stop tests + // ========================================================================= + + #[test] + fn test_server_ref_from_pid() { + let pid = crate::core::Pid::new(); + let sr: ServerRef = pid.into(); + match sr { + ServerRef::Pid(p) => assert_eq!(p, pid), + _ => panic!("expected Pid variant"), + } + } + + #[test] + fn test_server_ref_from_str() { + let sr: ServerRef = "my_server".into(); + match sr { + ServerRef::Name(n) => assert_eq!(n, "my_server"), + _ => panic!("expected Name variant"), + } + } + + #[test] + fn test_server_ref_from_string() { + let sr: ServerRef = String::from("my_server").into(); + match sr { + ServerRef::Name(n) => assert_eq!(n, "my_server"), + _ => panic!("expected Name variant"), + } + } + + #[test] + fn test_server_ref_resolve_unregistered() { + crate::init(); + let sr = ServerRef::Name("nonexistent_server".to_string()); + assert!(sr.resolve().is_none()); + } + + #[tokio::test] + async fn test_call_with_server_ref_pid() { + crate::init(); + let handle = crate::handle(); + + let result = Arc::new(AtomicI64::new(-1)); + let result_clone = result.clone(); + + handle.spawn(move || async move { + let pid = start::(42).await.expect("failed to start counter"); + + // Call using Pid directly (backwards compatible) + let reply: CounterReply = + call::(pid, CounterCall::Get, Duration::from_secs(5)) + .await + .expect("call failed"); + + result_clone.store(reply.0, Ordering::SeqCst); + }); + + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(result.load(Ordering::SeqCst), 42); + } + + #[tokio::test] + async fn test_stop_gen_server() { + use crate::gen_server::stop; + + crate::init(); + let handle = crate::handle(); + + let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stopped_clone = stopped.clone(); + + handle.spawn(move || async move { + let pid = start::(0).await.expect("failed to start counter"); + assert!(crate::alive(pid)); + + stop(pid, crate::core::ExitReason::Normal).await.unwrap(); + + // Give it time to process + tokio::time::sleep(Duration::from_millis(50)).await; + + stopped_clone.store(!crate::alive(pid), Ordering::SeqCst); + }); + + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(stopped.load(Ordering::SeqCst), "Server should have stopped"); + } } diff --git a/crates/ambitious/src/gen_server/protocol.rs b/crates/ambitious/src/gen_server/protocol.rs index e149423..cb315e1 100644 --- a/crates/ambitious/src/gen_server/protocol.rs +++ b/crates/ambitious/src/gen_server/protocol.rs @@ -238,7 +238,6 @@ pub fn encode_reply(reference: Ref, payload: &[u8]) -> Vec { } /// Encode a stop request. -#[allow(dead_code)] pub fn encode_stop(reason: ExitReason, from: Option) -> Vec { Message::Stop { reason, from }.encode() } diff --git a/crates/ambitious/src/gen_server/server.rs b/crates/ambitious/src/gen_server/server.rs index 683af8f..96f55bf 100644 --- a/crates/ambitious/src/gen_server/server.rs +++ b/crates/ambitious/src/gen_server/server.rs @@ -350,14 +350,23 @@ fn schedule_continue(arg: &[u8]) { /// /// ```ignore /// let count: i64 = call::(pid, CounterCall::Get, Duration::from_secs(5)).await?; +/// +/// // Also accepts registered names: +/// let count: i64 = call::("my_counter", CounterCall::Get, Duration::from_secs(5)).await?; /// ``` -pub async fn call(pid: Pid, msg: G::Call, timeout: Duration) -> Result +pub async fn call( + server: impl Into, + msg: G::Call, + timeout: Duration, +) -> Result where G: GenServer, R: Message, { use tokio::time::timeout as tokio_timeout; + let pid = server.into().resolve().ok_or(Error::NotFound)?; + let reference = Ref::new(); let caller_pid = crate::current_pid(); @@ -417,12 +426,60 @@ async fn wait_for_reply(reference: Ref) -> Result { /// /// ```ignore /// cast::(pid, CounterCast::Increment); +/// +/// // Also accepts registered names: +/// cast::("my_counter", CounterCast::Increment); /// ``` -pub fn cast(pid: Pid, msg: G::Cast) +pub fn cast(server: impl Into, msg: G::Cast) where G: GenServer, { + let Some(pid) = server.into().resolve() else { + return; + }; // Wrap in $gen_cast envelope let envelope = encode_gen_cast_envelope(msg.encode_local()); let _ = crate::send_raw(pid, envelope); } + +/// Sends a reply to a caller outside of the normal handle_call return flow. +/// +/// This is useful when `handle_call` returns `Reply::NoReply` and the +/// reply needs to be sent later (deferred reply pattern). +/// +/// # Example +/// +/// ```ignore +/// async fn handle_call(&mut self, msg: MyCall, from: From) -> Reply { +/// // Store `from` and reply later +/// self.pending = Some(from); +/// Reply::NoReply +/// } +/// +/// // Later, in handle_cast or handle_info: +/// gen_server::reply(&self.pending.take().unwrap(), MyReply::Done); +/// ``` +pub fn reply(from: &From, value: T) { + send_reply(from, value.encode_local()); +} + +/// Gracefully stops a GenServer. +/// +/// Sends a stop protocol message to the server process. +/// The server's `terminate` callback will be called with the given reason. +/// +/// # Example +/// +/// ```ignore +/// gen_server::stop(pid, ExitReason::Normal).await?; +/// gen_server::stop("my_server", ExitReason::Shutdown).await?; +/// ``` +pub async fn stop(server: impl Into, reason: ExitReason) -> Result<(), Error> { + let pid = server.into().resolve().ok_or(Error::NotFound)?; + + // Send a Stop protocol message + let stop_msg = super::protocol::encode_stop(reason, None); + crate::send_raw(pid, stop_msg).map_err(|_| Error::NotFound)?; + + Ok(()) +} diff --git a/crates/ambitious/src/gen_server/server_ref.rs b/crates/ambitious/src/gen_server/server_ref.rs new file mode 100644 index 0000000..5877d56 --- /dev/null +++ b/crates/ambitious/src/gen_server/server_ref.rs @@ -0,0 +1,66 @@ +//! ServerRef - unified way to address a GenServer. + +use crate::core::Pid; + +/// A reference to a GenServer, either by PID or registered name. +/// +/// This allows GenServer client functions (`call`, `cast`, `stop`) to +/// accept either a `Pid` or a name string. +/// +/// # Examples +/// +/// ```ignore +/// use ambitious::gen_server::{call, ServerRef}; +/// +/// // By PID (most common) +/// let reply = call::(pid, msg, timeout).await?; +/// +/// // By registered name +/// let reply = call::("my_server", msg, timeout).await?; +/// ``` +#[derive(Debug, Clone)] +pub enum ServerRef { + /// Reference by process ID. + Pid(Pid), + /// Reference by registered name. + Name(String), +} + +impl ServerRef { + /// Resolves the ServerRef to a Pid. + /// + /// Returns `None` if the name is not registered. + pub fn resolve(&self) -> Option { + match self { + ServerRef::Pid(pid) => Some(*pid), + ServerRef::Name(name) => crate::whereis(name), + } + } +} + +impl From for ServerRef { + fn from(pid: Pid) -> Self { + ServerRef::Pid(pid) + } +} + +impl From<&str> for ServerRef { + fn from(name: &str) -> Self { + ServerRef::Name(name.to_string()) + } +} + +impl From for ServerRef { + fn from(name: String) -> Self { + ServerRef::Name(name) + } +} + +impl std::fmt::Display for ServerRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ServerRef::Pid(pid) => write!(f, "{:?}", pid), + ServerRef::Name(name) => write!(f, "{}", name), + } + } +} diff --git a/crates/ambitious/src/lib.rs b/crates/ambitious/src/lib.rs index 0b4ac47..1bb80d6 100644 --- a/crates/ambitious/src/lib.rs +++ b/crates/ambitious/src/lib.rs @@ -215,7 +215,8 @@ pub mod prelude { // GenServer essentials (enum-based pattern) pub use crate::gen_server::{ - Error, From, GenServer, Init, Reply, Status, call, cast, start, start_link, + Error, From, GenServer, Init, Reply, ServerRef, Status, call, cast, reply, start, + start_link, stop, }; // Supervisor essentials From 577f20cbed18104bc2e692f49c2ca97b233eecc5 Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 22:10:47 -0600 Subject: [PATCH 4/7] Implement supervisor child management commands (terminate, delete, restart) Replace stub implementations of terminate_child and delete_child with real message-passing command pattern using TaggedEnvelope protocol. Add new restart_child public API. Fix wait_for_termination to use task-local context instead of global runtime. --- crates/ambitious/src/supervisor/core.rs | 322 ++++++++++++++++++++++-- crates/ambitious/src/supervisor/mod.rs | 271 +++++++++++++++++++- 2 files changed, 574 insertions(+), 19 deletions(-) diff --git a/crates/ambitious/src/supervisor/core.rs b/crates/ambitious/src/supervisor/core.rs index 53e768d..09098a2 100644 --- a/crates/ambitious/src/supervisor/core.rs +++ b/crates/ambitious/src/supervisor/core.rs @@ -2,7 +2,7 @@ //! //! The supervisor manages child processes according to a supervision strategy. -use super::error::{DeleteError, StartError, TerminateError}; +use super::error::{DeleteError, RestartError, StartError, TerminateError}; use super::types::{ ChildCounts, ChildInfo, ChildSpec, ChildType, RestartType, ShutdownType, Strategy, SupervisorFlags, @@ -10,10 +10,110 @@ use super::types::{ use crate::core::{ExitReason, Pid, Ref, SystemMessage, Term}; use crate::process::RuntimeHandle; use dashmap::DashMap; +use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::OnceLock; use std::time::{Duration, Instant}; +// ============================================================================= +// Supervisor Command Protocol +// ============================================================================= + +/// Tag used for supervisor command envelopes. +const SUPERVISOR_COMMAND_TAG: &str = "$supervisor_cmd"; + +/// Internal command messages sent to a supervisor process. +/// +/// These commands are used by the public API functions (`terminate_child`, +/// `delete_child`, `restart_child`) to communicate with the supervisor loop. +#[derive(Debug, Clone, Serialize, Deserialize)] +enum SupervisorCommand { + /// Request to terminate a child process. + Terminate { + /// The child ID to terminate. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for matching the reply. + reply_ref: Ref, + }, + /// Request to delete a child specification (child must be stopped). + Delete { + /// The child ID to delete. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for matching the reply. + reply_ref: Ref, + }, + /// Request to restart a stopped child. + Restart { + /// The child ID to restart. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for matching the reply. + reply_ref: Ref, + }, +} + +/// Encodes a supervisor command into bytes using a tagged envelope. +fn encode_supervisor_command(cmd: &SupervisorCommand) -> Vec { + let payload = Term::encode(cmd); + let tagged = crate::gen_server::protocol::TaggedEnvelope::new(SUPERVISOR_COMMAND_TAG, payload); + tagged.encode() +} + +/// Tries to decode a supervisor command from bytes. +/// +/// Returns `None` if the bytes are not a valid supervisor command envelope. +fn decode_supervisor_command(data: &[u8]) -> Option { + let tagged = crate::gen_server::protocol::TaggedEnvelope::decode(data).ok()?; + if tagged.tag != SUPERVISOR_COMMAND_TAG { + return None; + } + Term::decode(&tagged.payload).ok() +} + +/// Waits for a reply to a supervisor command. +/// +/// Listens for a `Reply` protocol message with the matching reference. +/// Returns the raw payload bytes on success, or `Err(())` on timeout. +async fn wait_for_supervisor_reply(reference: Ref) -> Result, ()> { + use crate::gen_server::protocol::Message as ProtocolMessage; + + let timeout = std::time::Duration::from_secs(5); + let deadline = tokio::time::Instant::now() + timeout; + + loop { + let remaining = deadline - tokio::time::Instant::now(); + if remaining.is_zero() { + return Err(()); + } + + let raw_msg = match crate::runtime::recv_timeout(remaining).await { + Ok(Some(m)) => m, + Ok(None) => return Err(()), + Err(()) => return Err(()), + }; + + if let Ok(ProtocolMessage::Reply { + reference: ref r, + payload, + }) = ProtocolMessage::decode(&raw_msg) + && *r == reference + { + return Ok(payload); + } + + tracing::trace!("supervisor: ignoring non-reply message while waiting for command reply"); + } +} + +// ============================================================================= +// Supervisor State Registry +// ============================================================================= + /// Global registry of supervisor states for querying. /// This allows `which_children` and `count_children` to access supervisor state. static SUPERVISOR_STATES: OnceLock> = OnceLock::new(); @@ -382,6 +482,48 @@ impl SupervisorState { fn unregister_from_registry(&self) { get_supervisor_registry().remove(&self.self_pid); } + + /// Handles a `TerminateChild` command. + /// + /// Terminates the child if it exists (running or not). Returns an error + /// if the child ID is not found. + async fn handle_terminate_child_command(&mut self, id: &str) -> Result<(), String> { + if !self.children.contains_key(id) { + return Err(format!("child '{}' not found", id)); + } + self.terminate_child_by_id(id).await; + Ok(()) + } + + /// Handles a `DeleteChild` command. + /// + /// Removes the child specification. The child must not be running. + fn handle_delete_child_command(&mut self, id: &str) -> Result<(), String> { + let child = self + .children + .get(id) + .ok_or_else(|| format!("not_found:{}", id))?; + if child.pid.is_some() { + return Err(format!("running:{}", id)); + } + self.children.remove(id); + self.child_order.retain(|i| i != id); + Ok(()) + } + + /// Handles a `RestartChild` command. + /// + /// Restarts a stopped child. The child must exist and not be running. + async fn handle_restart_child_command(&mut self, id: &str) -> Result { + let child = self + .children + .get(id) + .ok_or_else(|| format!("not_found:{}", id))?; + if child.pid.is_some() { + return Err(format!("already_running:{}", id)); + } + self.start_child(id).await + } } /// The main supervisor process loop. @@ -437,6 +579,48 @@ async fn supervisor_loop(mut state: SupervisorState) { state.unregister_from_registry(); return; } + + // Check for supervisor commands + if let Some(cmd) = decode_supervisor_command(&msg) { + match cmd { + SupervisorCommand::Terminate { + id, + reply_to, + reply_ref, + } => { + let result = state.handle_terminate_child_command(&id).await; + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = + crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + SupervisorCommand::Delete { + id, + reply_to, + reply_ref, + } => { + let result = state.handle_delete_child_command(&id); + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = + crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + SupervisorCommand::Restart { + id, + reply_to, + reply_ref, + } => { + let result = state.handle_restart_child_command(&id).await; + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = + crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + } + } } } @@ -576,42 +760,146 @@ pub async fn count_children(_handle: &RuntimeHandle, sup: Pid) -> Result Result<(), TerminateError> { - // This would need a proper call mechanism - Err(TerminateError::NotFound("not implemented".to_string())) + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::Terminate { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| TerminateError::NotFound(id.to_string()))?; + + let reply = wait_for_supervisor_reply(reply_ref) + .await + .map_err(|_| TerminateError::Timeout)?; + + let result: Result<(), String> = + Term::decode(&reply).map_err(|_| TerminateError::NotFound(id.to_string()))?; + + result.map_err(TerminateError::NotFound) +} + +/// Deletes a child specification from the supervisor. +/// +/// Sends a `DeleteChild` command to the supervisor and waits for the reply. +/// The child must already be stopped (via [`terminate_child`]) before it can +/// be deleted. +/// +/// # Errors +/// +/// Returns [`DeleteError::Running`] if the child is still running, or +/// [`DeleteError::NotFound`] if the child ID does not exist. +pub async fn delete_child(_handle: &RuntimeHandle, sup: Pid, id: &str) -> Result<(), DeleteError> { + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::Delete { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| DeleteError::NotFound(id.to_string()))?; + + let reply = wait_for_supervisor_reply(reply_ref) + .await + .map_err(|_| DeleteError::NotFound(id.to_string()))?; + + let result: Result<(), String> = + Term::decode(&reply).map_err(|_| DeleteError::NotFound(id.to_string()))?; + + result.map_err(|e| { + if e.starts_with("running:") { + DeleteError::Running(e.strip_prefix("running:").unwrap_or(&e).to_string()) + } else { + DeleteError::NotFound(e.strip_prefix("not_found:").unwrap_or(&e).to_string()) + } + }) } -/// Deletes a child specification. +/// Restarts a stopped child process. /// -/// Note: This is a simplified implementation. -pub async fn delete_child( +/// Sends a `RestartChild` command to the supervisor and waits for the reply. +/// The child must be stopped (via [`terminate_child`] or having exited) before +/// it can be restarted. +/// +/// # Errors +/// +/// Returns [`RestartError::AlreadyRunning`] if the child is still running, +/// [`RestartError::NotFound`] if the child ID does not exist, or +/// [`RestartError::StartFailed`] if the child's start function fails. +pub async fn restart_child( _handle: &RuntimeHandle, - _sup: Pid, - _id: &str, -) -> Result<(), DeleteError> { - // This would need a proper call mechanism - Err(DeleteError::NotFound("not implemented".to_string())) + sup: Pid, + id: &str, +) -> Result { + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::Restart { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| RestartError::NotFound(id.to_string()))?; + + let reply = wait_for_supervisor_reply(reply_ref) + .await + .map_err(|_| RestartError::StartFailed("timeout waiting for reply".to_string()))?; + + let result: Result = + Term::decode(&reply).map_err(|_| RestartError::StartFailed("decode error".to_string()))?; + + result.map_err(|e| { + if e.starts_with("already_running:") { + RestartError::AlreadyRunning( + e.strip_prefix("already_running:").unwrap_or(&e).to_string(), + ) + } else if e.starts_with("not_found:") { + RestartError::NotFound(e.strip_prefix("not_found:").unwrap_or(&e).to_string()) + } else { + RestartError::StartFailed(e) + } + }) } /// Waits for a process to terminate. /// /// Returns `true` if the process terminated, `false` if the timeout expired. /// If `timeout` is `None`, waits indefinitely. +/// +/// Uses the task-local context's registry to check process liveness, so this +/// must be called from within a process context. async fn wait_for_termination(pid: Pid, timeout: Option) -> bool { const POLL_INTERVAL: Duration = Duration::from_millis(10); let deadline = timeout.map(|t| Instant::now() + t); loop { - // Check if process is dead - if !crate::alive(pid) { + // Check if process is dead using the task-local context's registry + let is_alive = crate::runtime::with_ctx(|ctx| ctx.is_alive(pid)); + if !is_alive { return true; } diff --git a/crates/ambitious/src/supervisor/mod.rs b/crates/ambitious/src/supervisor/mod.rs index 09851bf..d13d8ba 100644 --- a/crates/ambitious/src/supervisor/mod.rs +++ b/crates/ambitious/src/supervisor/mod.rs @@ -64,8 +64,8 @@ mod types; pub mod dynamic_supervisor; pub use core::{ - Supervisor, SupervisorInit, count_children, delete_child, start, start_link, terminate_child, - which_children, + Supervisor, SupervisorInit, count_children, delete_child, restart_child, start, start_link, + terminate_child, which_children, }; pub use error::{DeleteError, RestartError, StartError, TerminateError}; pub use types::{ @@ -699,4 +699,271 @@ mod tests { count ); } + + // ========================================================================= + // Child management command tests + // ========================================================================= + + /// Helper: creates a supervisor with a single long-lived worker child. + /// Returns the supervisor PID. Uses the provided handle for spawning. + async fn setup_supervisor_with_worker( + handle: &RuntimeHandle, + start_count: std::sync::Arc, + ) -> Pid { + use std::sync::atomic::Ordering; + struct WorkerSup; + + impl Supervisor for WorkerSup { + type InitArg = ( + RuntimeHandle, + std::sync::Arc, + ); + + fn init((handle, count): Self::InitArg) -> SupervisorInit { + let handle_clone = handle.clone(); + SupervisorInit::new( + SupervisorFlags::new(Strategy::OneForOne) + .max_restarts(10) + .max_seconds(60), + vec![ + ChildSpec::new("worker", move || { + let h = handle_clone.clone(); + let c = count.clone(); + async move { + let pid = h.spawn(move || async move { + c.fetch_add(1, Ordering::SeqCst); + // Long-lived worker that waits for messages + while let Ok(Some(_)) = + crate::runtime::recv_timeout(Duration::from_secs(60)).await + { + } + }); + Ok(pid) + } + }) + .restart(RestartType::Permanent) + .shutdown(ShutdownType::BrutalKill), + ], + ) + } + } + + start::(handle, (handle.clone(), start_count)) + .await + .unwrap() + } + + #[tokio::test] + async fn test_terminate_child() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let start_count = Arc::new(AtomicUsize::new(0)); + let test_passed = Arc::new(AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let start_count_clone = start_count.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let h = handle_clone; + let sup_pid = setup_supervisor_with_worker(&h, start_count_clone).await; + + // Give child time to start + sleep(Duration::from_millis(50)).await; + + // 1. Terminate running child - should succeed + let result = terminate_child(&h, sup_pid, "worker").await; + assert!( + result.is_ok(), + "terminate_child should succeed: {:?}", + result + ); + + // Give time for state to sync + sleep(Duration::from_millis(50)).await; + + // Verify child is stopped via count_children + let counts = count_children(&h, sup_pid).await.unwrap(); + assert_eq!(counts.active, 0, "child should be stopped after terminate"); + assert_eq!(counts.specs, 1, "spec should still exist"); + + // 2. Terminate already stopped child - should be idempotent (succeed) + let result2 = terminate_child(&h, sup_pid, "worker").await; + assert!( + result2.is_ok(), + "terminate_child on stopped child should succeed: {:?}", + result2 + ); + + // 3. Terminate nonexistent child - should error + let result3 = terminate_child(&h, sup_pid, "nonexistent").await; + assert!( + result3.is_err(), + "terminate_child on nonexistent should error" + ); + + test_passed_clone.store(true, Ordering::SeqCst); + }); + + sleep(Duration::from_millis(500)).await; + assert!( + test_passed.load(Ordering::SeqCst), + "test_terminate_child did not complete" + ); + } + + #[tokio::test] + async fn test_delete_child() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let start_count = Arc::new(AtomicUsize::new(0)); + let test_passed = Arc::new(AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let start_count_clone = start_count.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let h = handle_clone; + let sup_pid = setup_supervisor_with_worker(&h, start_count_clone).await; + + // Give child time to start + sleep(Duration::from_millis(50)).await; + + // 1. Delete running child - should error with Running + let result = delete_child(&h, sup_pid, "worker").await; + assert!( + result.is_err(), + "delete_child on running child should error" + ); + if let Err(ref e) = result { + assert!( + matches!(e, DeleteError::Running(_)), + "expected Running error, got: {:?}", + e + ); + } + + // 2. Terminate first, then delete - should succeed + let _ = terminate_child(&h, sup_pid, "worker").await; + sleep(Duration::from_millis(50)).await; + + let result2 = delete_child(&h, sup_pid, "worker").await; + assert!( + result2.is_ok(), + "delete_child after terminate should succeed: {:?}", + result2 + ); + + // Verify spec is gone + sleep(Duration::from_millis(50)).await; + let counts = count_children(&h, sup_pid).await.unwrap(); + assert_eq!(counts.specs, 0, "spec should be removed after delete"); + + // 3. Delete again - should error with NotFound + let result3 = delete_child(&h, sup_pid, "worker").await; + assert!( + result3.is_err(), + "delete_child on deleted child should error" + ); + if let Err(ref e) = result3 { + assert!( + matches!(e, DeleteError::NotFound(_)), + "expected NotFound error, got: {:?}", + e + ); + } + + test_passed_clone.store(true, Ordering::SeqCst); + }); + + sleep(Duration::from_millis(500)).await; + assert!( + test_passed.load(Ordering::SeqCst), + "test_delete_child did not complete" + ); + } + + #[tokio::test] + async fn test_restart_child() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let start_count = Arc::new(AtomicUsize::new(0)); + let test_passed = Arc::new(AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let start_count_clone = start_count.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let h = handle_clone; + let sup_pid = setup_supervisor_with_worker(&h, start_count_clone.clone()).await; + + // Give child time to start + sleep(Duration::from_millis(50)).await; + + // Initial start count should be 1 + let initial_count = start_count_clone.load(Ordering::SeqCst); + assert_eq!(initial_count, 1, "child should have started once initially"); + + // 1. Restart running child - should error with AlreadyRunning + let result = restart_child(&h, sup_pid, "worker").await; + assert!( + result.is_err(), + "restart_child on running child should error" + ); + if let Err(ref e) = result { + assert!( + matches!(e, RestartError::AlreadyRunning(_)), + "expected AlreadyRunning error, got: {:?}", + e + ); + } + + // 2. Terminate, then restart - should succeed + let _ = terminate_child(&h, sup_pid, "worker").await; + sleep(Duration::from_millis(50)).await; + + let result2 = restart_child(&h, sup_pid, "worker").await; + assert!( + result2.is_ok(), + "restart_child after terminate should succeed: {:?}", + result2 + ); + let new_pid = result2.unwrap(); + assert!(h.alive(new_pid), "restarted child should be alive"); + + // Give child time to increment counter + sleep(Duration::from_millis(50)).await; + + // 3. Verify start count incremented + let final_count = start_count_clone.load(Ordering::SeqCst); + assert_eq!( + final_count, 2, + "start count should be 2 after restart, got {}", + final_count + ); + + // Verify child is active via count_children + let counts = count_children(&h, sup_pid).await.unwrap(); + assert_eq!(counts.active, 1, "child should be active after restart"); + + test_passed_clone.store(true, Ordering::SeqCst); + }); + + sleep(Duration::from_millis(500)).await; + assert!( + test_passed.load(Ordering::SeqCst), + "test_restart_child did not complete" + ); + } } From 217adeff65142260bf70a7e1385d56ca0d0eb01f Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 22:17:32 -0600 Subject: [PATCH 5/7] Remove unsafe from AppController and fix stop_all ordering Replace raw pointer extraction with Arc::clone for safe access to application start functions across RwLock boundaries. The previous approach extracted a raw pointer from a Box behind a RwLock guard and used it after the guard was dropped via an unsafe block. Also fix stop_all to properly stop applications in reverse dependency order using visit_deps, rather than relying on arbitrary HashMap iteration order. --- crates/ambitious/src/application/core.rs | 60 +++++++++++++++--------- 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/crates/ambitious/src/application/core.rs b/crates/ambitious/src/application/core.rs index 02299d6..877bc48 100644 --- a/crates/ambitious/src/application/core.rs +++ b/crates/ambitious/src/application/core.rs @@ -8,10 +8,10 @@ use std::collections::{HashMap, HashSet}; use std::sync::{Arc, RwLock}; /// Type alias for the application start function. -type StartFn = Box Result + Send + Sync>; +type StartFn = Arc Result + Send + Sync>; /// Type alias for the application stop function. -type StopFn = Box) + Send + Sync>; +type StopFn = Arc) + Send + Sync>; /// The Application trait for implementing OTP-style applications. /// @@ -109,8 +109,8 @@ impl AppController { let app = RegisteredApp { spec, - start_fn: Box::new(|handle, config| A::start(handle, config)), - stop_fn: Box::new(|pid| A::stop(pid)), + start_fn: Arc::new(|handle, config| A::start(handle, config)), + stop_fn: Arc::new(|pid| A::stop(pid)), }; let mut registered = self.registered.write().unwrap(); @@ -145,15 +145,12 @@ impl AppController { } } - // Get the app - let (start_fn, _spec) = { + let start_fn = { let registered = self.registered.read().unwrap(); let app = registered .get(&app_name) .ok_or_else(|| StartError::NotFound(app_name.clone()))?; - - // Clone what we need - (app.start_fn.as_ref() as *const _, app.spec.clone()) + app.start_fn.clone() }; // Start it @@ -163,13 +160,7 @@ impl AppController { AppConfig::new() }; - // Safety: We're calling within the same function scope - let result = unsafe { - let start_fn: &( - dyn Fn(&RuntimeHandle, &AppConfig) -> Result + Send + Sync - ) = &*start_fn; - start_fn(&self.handle, &app_config) - }; + let result = start_fn(&self.handle, &app_config); let start_result = result.map_err(StartError::StartFailed)?; @@ -215,15 +206,42 @@ impl AppController { } /// Stops all running applications in reverse dependency order. + /// + /// Applications that depend on others are stopped first, then their + /// dependencies are stopped. pub async fn stop_all(&self) { - // Get all running app names - let names: Vec = { + // Collect all running app names and build dependency-aware stop order + let stop_order = { let running = self.running.read().unwrap(); - running.keys().cloned().collect() + let running_names: Vec = running.keys().cloned().collect(); + + if running_names.is_empty() { + return; + } + + // Build the full startup order for all running apps, then reverse it + let mut startup_order = Vec::new(); + let mut visited = std::collections::HashSet::new(); + let registered = self.registered.read().unwrap(); + + for name in &running_names { + let mut path = Vec::new(); + // Ignore errors - just best-effort ordering + let _ = Self::visit_deps( + name, + ®istered, + &mut startup_order, + &mut visited, + &mut path, + ); + } + + // Reverse the startup order for shutdown + startup_order.into_iter().rev().collect::>() }; - // Stop each (in reverse order would be better, but this is simpler) - for name in names.iter().rev() { + // Stop each in reverse dependency order + for name in &stop_order { let _ = self.stop(name).await; } } From 91b7eed1a350ccfe8c53489a316c6af57b4a14f7 Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 22:22:45 -0600 Subject: [PATCH 6/7] Update CLAUDE.md and README.md to match actual codebase Sync documentation with the real code after Phases 1-4 consolidated the project into a single crate with updated APIs: - Crate structure: single `crates/ambitious/` crate, not multi-crate - GenServer: self-as-state pattern with &mut self handlers, Init/Reply/Status return types - Supervisor: SupervisorInit with SupervisorFlags, RuntimeHandle-based client API - Term/Message: separate traits (Term for serialization, Message for tagged dispatch) - Process API: updated signatures (SendError, Result returns, current_pid) - Build commands: cargo test -p ambitious (not ambitious-process) --- AGENTS.md | 201 ++++++++++++++++++++++++++++-------------------------- README.md | 73 +++++++++++--------- 2 files changed, 147 insertions(+), 127 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a7419e9..90208e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,15 +44,19 @@ Ambitious aims to provide Erlang-style concurrency primitives in Rust: ## Crate Structure ``` -dream/ -├── dream/ # Main crate re-exporting all functionality -├── ambitious-core/ # Core types: Pid, Ref, ExitReason, Message trait -├── ambitious-runtime/ # Async runtime, scheduler, process registry -├── ambitious-process/ # Process spawning, mailboxes, links, monitors -├── ambitious-gen-server/ # GenServer trait and implementation -├── ambitious-supervisor/ # Supervisor trait and restart strategies -├── ambitious-application/ # Application lifecycle management -└── ambitious-macros/ # Procedural macros for ergonomic APIs +ambitious/ +├── crates/ +│ ├── ambitious/ # Main crate containing all functionality +│ │ └── src/ +│ │ ├── core/ # Core types: Pid, Ref, ExitReason, Atom, Term trait +│ │ ├── runtime/ # Async runtime, scheduler, process registry, task-locals +│ │ ├── process/ # Process spawning, mailboxes, links, monitors +│ │ ├── gen_server/ # GenServer trait and server loop +│ │ ├── supervisor/ # Supervisor trait and restart strategies +│ │ ├── application/ # Application lifecycle management +│ │ ├── timer/ # Timer management (send_after, cancel) +│ │ └── ... # Registry, channels, distribution, etc. +│ └── ambitious-macros/ # Procedural macros (#[derive(Message)], #[ambitious::main]) ``` ## Core Types @@ -90,16 +94,16 @@ fn spawn_link(f: F) -> Pid; fn spawn_monitor(f: F) -> (Pid, Ref); // Links (bidirectional) -fn link(pid: Pid) -> Result<(), ProcessError>; +fn link(pid: Pid) -> Result<(), SendError>; fn unlink(pid: Pid); // Monitors (unidirectional) -fn monitor(pid: Pid) -> Ref; +fn monitor(pid: Pid) -> Result; fn demonitor(reference: Ref); // Messaging -fn send(pid: Pid, msg: M); -fn send_after(pid: Pid, msg: M, delay: Duration) -> TimerRef; +fn send(pid: Pid, msg: &M) -> Result<(), SendError>; +fn send_after(pid: Pid, msg: &M, delay: Duration) -> TimerResult; // Process flags fn flag(flag: ProcessFlag, value: bool) -> bool; // trap_exit, etc. @@ -109,10 +113,10 @@ fn exit(pid: Pid, reason: ExitReason); // Info fn alive(pid: Pid) -> bool; -fn self_pid() -> Pid; +fn current_pid() -> Pid; // Registration -fn register(name: &str, pid: Pid) -> Result<(), RegistrationError>; +fn register(name: String, pid: Pid); fn whereis(name: &str) -> Option; fn unregister(name: &str); ``` @@ -121,85 +125,73 @@ fn unregister(name: &str); ### Trait Definition ```rust +#[async_trait] pub trait GenServer: Sized + Send + 'static { - type State: Send; - type InitArg: Send; - type Call: Message; // Request type - type Cast: Message; // Async message type - type Reply: Message; // Response type - type Info: Message; // Other messages (optional, default to bytes) - - // Callbacks - fn init(arg: Self::InitArg) -> InitResult; - - fn handle_call( - request: Self::Call, - from: From, - state: &mut Self::State, - ) -> CallResult; - - fn handle_cast( - msg: Self::Cast, - state: &mut Self::State, - ) -> CastResult; - - fn handle_info( - msg: Self::Info, // or raw bytes - state: &mut Self::State, - ) -> InfoResult; - - fn terminate(reason: ExitReason, state: &mut Self::State) {} + type Args: Send + 'static; + type Call: Message + Send + 'static; + type Cast: Message + Send + 'static; + type Info: Message + Send + 'static; + type Reply: Message + Send + 'static; + + async fn init(args: Self::Args) -> Init; + async fn handle_call(&mut self, msg: Self::Call, from: From) -> Reply; + async fn handle_cast(&mut self, msg: Self::Cast) -> Status; + async fn handle_info(&mut self, msg: Self::Info) -> Status; + async fn terminate(&mut self, _reason: ExitReason) {} + async fn handle_timeout(&mut self) -> Status { Status::Ok } + async fn handle_continue(&mut self, _arg: Vec) -> Status { Status::Ok } } ``` -### Return Types (matching Elixir) +Key design points: +- The struct IS the state (no separate `State` type) +- Handlers take `&mut self` +- `init` returns `Init` +- `handle_call` returns `Reply` +- `handle_cast`/`handle_info` return `Status` + +### Return Types ```rust -pub enum InitResult { +pub enum Init { Ok(S), - OkTimeout(S, Duration), - OkHibernate(S), - OkContinue(S, ContinueArg), + Continue(S, Vec), + Timeout(S, Duration), Ignore, Stop(ExitReason), } -pub enum CallResult { - Reply(R, S), - ReplyTimeout(R, S, Duration), - ReplyContinue(R, S, ContinueArg), - NoReply(S), - NoReplyTimeout(S, Duration), - NoReplyContinue(S, ContinueArg), - Stop(ExitReason, R, S), - StopNoReply(ExitReason, S), +pub enum Reply { + Ok(T), + Continue(T, Vec), + Timeout(T, Duration), + NoReply, + Stop(ExitReason, T), + StopNoReply(ExitReason), } -pub enum CastResult { - NoReply(S), - NoReplyTimeout(S, Duration), - NoReplyContinue(S, ContinueArg), - Stop(ExitReason, S), +pub enum Status { + Ok, + Continue(Vec), + Timeout(Duration), + Stop(ExitReason), } ``` ### Client Functions ```rust // Starting -async fn start(arg: G::InitArg) -> Result; -async fn start_link(arg: G::InitArg) -> Result; +async fn start(args: G::Args) -> Result; +async fn start_link(args: G::Args) -> Result; // Messaging -async fn call( - server: impl Into, - request: G::Call, - timeout: Duration, -) -> Result; - -fn cast(server: impl Into, msg: G::Cast); +async fn call(server: impl Into, msg: G::Call, timeout: Duration) -> Result; +fn cast(server: impl Into, msg: G::Cast); -fn reply(from: From, reply: impl Message); +// Deferred reply (for NoReply pattern) +fn reply(from: &From, value: T); -async fn stop(server: impl Into, reason: ExitReason) -> Result<(), StopError>; +// Graceful shutdown +async fn stop(server: impl Into, reason: ExitReason) -> Result<(), Error>; ``` ## Supervisor API (mirrors Elixir's Supervisor) @@ -239,45 +231,59 @@ pub enum ShutdownType { ### Supervisor Trait ```rust pub trait Supervisor: Sized + Send + 'static { - type InitArg: Send; + type InitArg: Send + 'static; fn init(arg: Self::InitArg) -> SupervisorInit; } pub struct SupervisorInit { - pub strategy: Strategy, - pub max_restarts: u32, // Default: 3 - pub max_seconds: u32, // Default: 5 + pub flags: SupervisorFlags, pub children: Vec, } ``` ### Client Functions ```rust -async fn start_link(arg: S::InitArg) -> Result; -async fn start_child(sup: Pid, spec: ChildSpec) -> Result; -async fn terminate_child(sup: Pid, id: &str) -> Result<(), TerminateError>; -async fn restart_child(sup: Pid, id: &str) -> Result; -async fn delete_child(sup: Pid, id: &str) -> Result<(), DeleteError>; -async fn which_children(sup: Pid) -> Vec; -async fn count_children(sup: Pid) -> ChildCounts; +async fn start_link(handle: &RuntimeHandle, parent: Pid, arg: S::InitArg) -> Result; +async fn start(handle: &RuntimeHandle, arg: S::InitArg) -> Result; +async fn terminate_child(handle: &RuntimeHandle, sup: Pid, id: &str) -> Result<(), TerminateError>; +async fn delete_child(handle: &RuntimeHandle, sup: Pid, id: &str) -> Result<(), DeleteError>; +async fn restart_child(handle: &RuntimeHandle, sup: Pid, id: &str) -> Result; +async fn which_children(handle: &RuntimeHandle, sup: Pid) -> Result, String>; +async fn count_children(handle: &RuntimeHandle, sup: Pid) -> Result; ``` -## Message Trait +## Term Trait + +The `Term` trait provides serialization for any type sent between processes: ```rust -pub trait Message: Serialize + DeserializeOwned + Send + 'static { +pub trait Term: Sized + Send + 'static { fn encode(&self) -> Vec; fn decode(bytes: &[u8]) -> Result; + fn try_encode(&self) -> Option>; } // Blanket implementation for all Serialize + DeserializeOwned types -impl Message for T -where - T: Serialize + DeserializeOwned + Send + 'static -{ ... } +impl Term for T { ... } ``` +## Message Trait + +The `Message` trait provides typed, self-describing messages with tag-based dispatch: + +```rust +pub trait Message: Sized + Send + 'static { + const TAG: &'static str; + fn encode_local(&self) -> Vec; + fn decode_local(bytes: &[u8]) -> Result; + fn encode_remote(&self) -> Vec; + fn decode_remote(bytes: &[u8]) -> Result; +} +``` + +Use `#[derive(Message)]` from `ambitious-macros` for automatic implementation. + ## Macros ### Process Macros @@ -294,12 +300,15 @@ spawn_link!(my_function); spawn_link!(MyModule::start, args); ``` -### GenServer Derive (future) +### Derive Macros ```rust -#[derive(GenServer)] -#[gen_server(call = MyCall, cast = MyCast, reply = MyReply)] -struct MyServer { - // state fields +#[derive(Message)] +struct Get; + +#[derive(Message)] +enum CounterCall { + Get, + Increment, } ``` @@ -314,7 +323,7 @@ struct MyServer { ## Testing -Each crate should have: +Each module should have: - Unit tests for core functionality - Integration tests for cross-process behavior - Doc tests for public APIs @@ -325,7 +334,7 @@ Each crate should have: ```bash cargo build # Build all crates cargo test # Run all tests -cargo test -p ambitious-process # Test specific crate +cargo test -p ambitious # Test the main crate cargo doc --open # Generate and view docs ``` diff --git a/README.md b/README.md index c68929f..cc1e342 100644 --- a/README.md +++ b/README.md @@ -50,10 +50,12 @@ async fn main() { ```rust use ambitious::prelude::*; -use ambitious::gen_server::{async_trait, GenServer, InitResult, CallResult, CastResult}; +use ambitious::gen_server::{self, async_trait, GenServer}; use serde::{Serialize, Deserialize}; -struct Counter; +struct Counter { + count: i64, +} #[derive(Debug, Serialize, Deserialize)] enum CounterCall { @@ -66,39 +68,46 @@ enum CounterCast { Reset, } +#[derive(Debug, Serialize, Deserialize)] +struct CounterReply(i64); + +// Message trait implementations omitted for brevity. +// Use #[derive(Message)] from ambitious-macros for automatic implementation. + #[async_trait] impl GenServer for Counter { - type State = i64; - type InitArg = i64; + type Args = i64; type Call = CounterCall; type Cast = CounterCast; - type Reply = i64; + type Info = (); + type Reply = CounterReply; - async fn init(initial: i64) -> InitResult { - InitResult::ok(initial) + async fn init(initial: i64) -> Init { + Init::Ok(Counter { count: initial }) } - async fn handle_call( - request: CounterCall, - _from: From, - state: &mut i64, - ) -> CallResult { - match request { - CounterCall::Get => CallResult::reply(*state, *state), + async fn handle_call(&mut self, msg: CounterCall, _from: From) -> Reply { + match msg { + CounterCall::Get => Reply::Ok(CounterReply(self.count)), CounterCall::Increment => { - *state += 1; - CallResult::reply(*state, *state) + self.count += 1; + Reply::Ok(CounterReply(self.count)) } } } - async fn handle_cast(msg: CounterCast, _state: &mut i64) -> CastResult { + async fn handle_cast(&mut self, msg: CounterCast) -> Status { match msg { - CounterCast::Reset => CastResult::noreply(0), + CounterCast::Reset => { + self.count = 0; + Status::Ok + } } } - // ... handle_info and handle_continue implementations + async fn handle_info(&mut self, _msg: ()) -> Status { + Status::Ok + } } ``` @@ -181,16 +190,18 @@ dynamic_supervisor::terminate_child(sup_pid, child_pid)?; ``` ambitious/ -├── ambitious/ # Main crate re-exporting all functionality -├── ambitious-core/ # Core types: Pid, Ref, ExitReason, Term trait -├── ambitious-runtime/ # Async runtime, scheduler, process registry -├── ambitious-process/ # Process spawning, mailboxes, links, monitors -├── ambitious-gen-server/ # GenServer trait and implementation -├── ambitious-supervisor/ # Supervisor trait and restart strategies -├── ambitious-application/ # Application lifecycle management -├── ambitious-macros/ # Procedural macros for ergonomic APIs -└── examples/ - └── chat/ # Distributed chat server example +├── crates/ +│ ├── ambitious/ # Main crate containing all functionality +│ │ └── src/ +│ │ ├── core/ # Core types: Pid, Ref, ExitReason, Atom, Term trait +│ │ ├── runtime/ # Async runtime, scheduler, process registry, task-locals +│ │ ├── process/ # Process spawning, mailboxes, links, monitors +│ │ ├── gen_server/ # GenServer trait and server loop +│ │ ├── supervisor/ # Supervisor trait and restart strategies +│ │ ├── application/ # Application lifecycle management +│ │ ├── timer/ # Timer management (send_after, cancel) +│ │ └── ... # Registry, channels, distribution, etc. +│ └── ambitious-macros/ # Procedural macros (#[derive(Message)], #[ambitious::main]) ``` ## Core Concepts @@ -270,8 +281,8 @@ cargo build # Run all tests cargo test -# Run a specific crate's tests -cargo test -p ambitious-gen-server +# Run the main crate's tests +cargo test -p ambitious # Run the chat example cargo run --example chat-server From f6141580469112bed3b4f2fb151c91f9d6ebf5ec Mon Sep 17 00:00:00 2001 From: Sonny Scroggin Date: Thu, 19 Feb 2026 22:37:48 -0600 Subject: [PATCH 7/7] Add implementation plan for core correctness and API ergonomics --- ...19-core-correctness-and-ergonomics-plan.md | 1992 +++++++++++++++++ 1 file changed, 1992 insertions(+) create mode 100644 docs/plans/2026-02-19-core-correctness-and-ergonomics-plan.md diff --git a/docs/plans/2026-02-19-core-correctness-and-ergonomics-plan.md b/docs/plans/2026-02-19-core-correctness-and-ergonomics-plan.md new file mode 100644 index 0000000..2abb2d1 --- /dev/null +++ b/docs/plans/2026-02-19-core-correctness-and-ergonomics-plan.md @@ -0,0 +1,1992 @@ +# Core Correctness & API Ergonomics Implementation Plan + +> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. + +**Goal:** Fill in missing OTP-faithful APIs and improve developer ergonomics across Process, GenServer, Supervisor, and Application layers. + +**Architecture:** Bottom-up approach. Phase 1 exposes existing Context methods as top-level convenience functions. Phase 2 adds ServerRef and GenServer client ergonomics. Phase 3 implements supervisor child management via message-passing commands. Phase 4 fixes application safety and ordering. Phase 5 syncs documentation. + +**Tech Stack:** Rust, tokio, dashmap, postcard, serde + +--- + +## Task 1: Add ProcessFlag enum + +**Files:** +- Create: `crates/ambitious/src/core/process_flag.rs` +- Modify: `crates/ambitious/src/core/mod.rs` + +**Step 1: Create the ProcessFlag enum** + +Create `crates/ambitious/src/core/process_flag.rs`: + +```rust +//! Process flags for controlling process behavior. + +/// Flags that control process behavior. +/// +/// Used with `ambitious::flag()` to set process-level options. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProcessFlag { + /// When enabled, exit signals from linked processes are delivered + /// as messages instead of terminating this process. + TrapExit, +} +``` + +**Step 2: Export ProcessFlag from core module** + +In `crates/ambitious/src/core/mod.rs`, add: +```rust +mod process_flag; +pub use process_flag::ProcessFlag; +``` + +Find the existing module declarations and add `mod process_flag;` alongside them, then add `ProcessFlag` to the `pub use` exports. + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors (ProcessFlag is defined but not yet used) + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/core/process_flag.rs crates/ambitious/src/core/mod.rs +git commit -m "feat: add ProcessFlag enum to core types" +``` + +--- + +## Task 2: Add link, unlink, monitor, demonitor to task_local.rs + +**Files:** +- Modify: `crates/ambitious/src/runtime/task_local.rs` + +**Step 1: Write the failing test** + +Add to the bottom of `crates/ambitious/src/runtime/task_local.rs` (inside a new `#[cfg(test)]` module if none exists, or at the file level for now since tests will be integration-level): + +Actually, these functions delegate to `with_ctx` which requires a task-local context. We'll test them in Task 7 as integration tests. For now, write the implementations. + +**Step 2: Add the four functions** + +Add after the `exit()` function (around line 219) and before `set_exit_reason()`: + +```rust +/// Creates a bidirectional link with another process. +/// +/// If either process terminates abnormally, the other will receive +/// an exit signal. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn link(pid: Pid) -> Result<(), SendError> { + with_ctx(|ctx| ctx.link(pid)) +} + +/// Removes a link with another process. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn unlink(pid: Pid) { + with_ctx(|ctx| ctx.unlink(pid)) +} + +/// Creates a monitor on another process. +/// +/// Returns a reference that will be included in the `DOWN` message +/// when the monitored process terminates. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn monitor(pid: Pid) -> Result { + with_ctx(|ctx| ctx.monitor(pid)) +} + +/// Removes a monitor. +/// +/// The reference will no longer be valid and no `DOWN` message +/// will be sent for this monitor. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn demonitor(reference: Ref) { + with_ctx(|ctx| ctx.demonitor(reference)) +} +``` + +**Step 3: Add Ref import** + +The `Ref` type is already available via `super::` imports. Check that `use super::{Context, Pid, SendError};` at line 7 covers what we need. `Ref` is not imported yet. Add it: + +Change line 7 from: +```rust +use super::{Context, Pid, SendError}; +``` +to: +```rust +use super::{Context, Pid, Ref, SendError}; +``` + +**Step 4: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 5: Commit** + +```bash +git add crates/ambitious/src/runtime/task_local.rs +git commit -m "feat: add link, unlink, monitor, demonitor to task-local API" +``` + +--- + +## Task 3: Add flag function to task_local.rs + +**Files:** +- Modify: `crates/ambitious/src/runtime/task_local.rs` + +**Step 1: Add the flag function** + +Add after the `demonitor()` function: + +```rust +/// Sets a process flag and returns the previous value. +/// +/// # Flags +/// +/// - `ProcessFlag::TrapExit` - When `true`, exit signals from linked +/// processes are delivered as messages instead of terminating the process. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn flag(flag: ProcessFlag, value: bool) -> bool { + match flag { + ProcessFlag::TrapExit => with_ctx(|ctx| ctx.set_trap_exit(value)), + } +} +``` + +**Step 2: Add ProcessFlag import** + +Add to the imports at the top of the file: +```rust +use crate::core::ProcessFlag; +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/runtime/task_local.rs +git commit -m "feat: add flag() function to task-local API" +``` + +--- + +## Task 4: Add send_after convenience function to task_local.rs + +**Files:** +- Modify: `crates/ambitious/src/runtime/task_local.rs` + +**Step 1: Add the send_after function** + +Add after the `flag()` function: + +```rust +/// Sends a message to a process after a delay. +/// +/// Returns a [`TimerRef`] that can be used to cancel the timer. +/// +/// This is a convenience wrapper around `timer::send_after` that takes +/// arguments in OTP order: `(pid, msg, delay)`. +/// +/// # Panics +/// +/// Panics if called outside of a Ambitious process context. +pub fn send_after( + pid: Pid, + msg: &M, + delay: std::time::Duration, +) -> crate::timer::TimerResult { + crate::timer::send_after(delay, pid, msg) +} +``` + +**Step 2: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/runtime/task_local.rs +git commit -m "feat: add send_after convenience function to task-local API" +``` + +--- + +## Task 5: Update runtime/mod.rs exports + +**Files:** +- Modify: `crates/ambitious/src/runtime/mod.rs` + +**Step 1: Add new function exports** + +In `crates/ambitious/src/runtime/mod.rs`, update the `pub use task_local::` block (lines 28-31) from: + +```rust +pub use task_local::{ + ProcessScope, current_pid, exit, recv, recv_timeout, send, send_raw, set_exit_reason, + set_exit_reason_async, try_current_pid, try_recv, with_ctx, with_ctx_async, +}; +``` + +to: + +```rust +pub use task_local::{ + ProcessScope, current_pid, demonitor, exit, flag, link, monitor, recv, recv_timeout, send, + send_after, send_raw, set_exit_reason, set_exit_reason_async, try_current_pid, try_recv, + unlink, with_ctx, with_ctx_async, +}; +``` + +**Step 2: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/runtime/mod.rs +git commit -m "feat: export new process functions from runtime module" +``` + +--- + +## Task 6: Update lib.rs re-exports and prelude + +**Files:** +- Modify: `crates/ambitious/src/lib.rs` + +**Step 1: Update top-level re-exports** + +In `crates/ambitious/src/lib.rs`, update the task-local re-exports block (lines 185-188) from: + +```rust +pub use runtime::{ + current_pid, recv, recv_timeout, send, send_raw, try_current_pid, try_recv, with_ctx, + with_ctx_async, +}; +``` + +to: + +```rust +pub use runtime::{ + current_pid, demonitor, flag, link, monitor, recv, recv_timeout, send, send_after, send_raw, + try_current_pid, try_recv, unlink, with_ctx, with_ctx_async, +}; +``` + +**Step 2: Add ProcessFlag to core re-exports** + +Update the core types re-export line (line 191) from: + +```rust +pub use core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, RawTerm, Ref, Term}; +``` + +to: + +```rust +pub use core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, ProcessFlag, RawTerm, Ref, Term}; +``` + +**Step 3: Update prelude** + +In the prelude module, update the task-local functions block (lines 231-234) from: + +```rust +pub use crate::runtime::{ + current_pid, recv, recv_timeout, send, send_raw, try_current_pid, try_recv, with_ctx, + with_ctx_async, +}; +``` + +to: + +```rust +pub use crate::runtime::{ + current_pid, demonitor, flag, link, monitor, recv, recv_timeout, send, send_after, + send_raw, try_current_pid, try_recv, unlink, with_ctx, with_ctx_async, +}; +``` + +Add `ProcessFlag` to the core types in prelude (line 208): + +```rust +pub use crate::core::{ExitReason, NodeId, NodeInfo, NodeName, Pid, ProcessFlag, RawTerm, Ref, Term}; +``` + +**Step 4: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 5: Commit** + +```bash +git add crates/ambitious/src/lib.rs +git commit -m "feat: re-export new process functions from lib.rs and prelude" +``` + +--- + +## Task 7: Write tests for Phase 1 process functions + +**Files:** +- Modify: `crates/ambitious/src/lib.rs` (add integration test at bottom of existing tests) + +**Step 1: Write the test** + +Add the following test to the `#[cfg(test)] mod tests` block in `crates/ambitious/src/lib.rs` (after the existing tests): + +```rust +#[tokio::test] +async fn test_process_api_convenience_functions() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let link_ok = Arc::new(AtomicBool::new(false)); + let monitor_ok = Arc::new(AtomicBool::new(false)); + let flag_ok = Arc::new(AtomicBool::new(false)); + + let link_ok_c = link_ok.clone(); + let monitor_ok_c = monitor_ok.clone(); + let flag_ok_c = flag_ok.clone(); + + // Spawn a target process that stays alive + let target_pid = handle.spawn(|| async { + loop { + if crate::recv_timeout(std::time::Duration::from_secs(10)).await.is_err() { + break; + } + } + }); + + // Give target time to start + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + + handle.spawn(move || async move { + // Test link/unlink + assert!(crate::link(target_pid).is_ok()); + crate::unlink(target_pid); + link_ok_c.store(true, Ordering::SeqCst); + + // Test monitor/demonitor + let mon_ref = crate::monitor(target_pid).unwrap(); + crate::demonitor(mon_ref); + monitor_ok_c.store(true, Ordering::SeqCst); + + // Test flag + let prev = crate::flag(ProcessFlag::TrapExit, true); + assert!(!prev); // Was false before + let prev2 = crate::flag(ProcessFlag::TrapExit, false); + assert!(prev2); // Was true + flag_ok_c.store(true, Ordering::SeqCst); + }); + + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + + assert!(link_ok.load(Ordering::SeqCst), "link/unlink should work"); + assert!(monitor_ok.load(Ordering::SeqCst), "monitor/demonitor should work"); + assert!(flag_ok.load(Ordering::SeqCst), "flag should work"); +} +``` + +**Step 2: Run the test** + +Run: `cargo test -p ambitious test_process_api_convenience_functions -- --nocapture` +Expected: PASS + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/lib.rs +git commit -m "test: add tests for new process API convenience functions" +``` + +--- + +## Task 8: Run full CI for Phase 1 + +**Step 1: Run CI** + +Run: `just ci` +Expected: All tests pass, no warnings + +**Step 2: Fix any issues and commit** + +If any issues, fix and commit with appropriate message. + +--- + +## Task 9: Add ServerRef type + +**Files:** +- Create: `crates/ambitious/src/gen_server/server_ref.rs` +- Modify: `crates/ambitious/src/gen_server/mod.rs` + +**Step 1: Create ServerRef module** + +Create `crates/ambitious/src/gen_server/server_ref.rs`: + +```rust +//! ServerRef - unified way to address a GenServer. + +use crate::core::Pid; + +/// A reference to a GenServer, either by PID or registered name. +/// +/// This allows GenServer client functions (`call`, `cast`, `stop`) to +/// accept either a `Pid` or a name string. +/// +/// # Examples +/// +/// ```ignore +/// use ambitious::gen_server::{call, ServerRef}; +/// +/// // By PID (most common) +/// let reply = call::(pid, msg, timeout).await?; +/// +/// // By registered name +/// let reply = call::("my_server", msg, timeout).await?; +/// ``` +#[derive(Debug, Clone)] +pub enum ServerRef { + /// Reference by process ID. + Pid(Pid), + /// Reference by registered name. + Name(String), +} + +impl ServerRef { + /// Resolves the ServerRef to a Pid. + /// + /// Returns `None` if the name is not registered. + pub fn resolve(&self) -> Option { + match self { + ServerRef::Pid(pid) => Some(*pid), + ServerRef::Name(name) => crate::whereis(name), + } + } +} + +impl From for ServerRef { + fn from(pid: Pid) -> Self { + ServerRef::Pid(pid) + } +} + +impl From<&str> for ServerRef { + fn from(name: &str) -> Self { + ServerRef::Name(name.to_string()) + } +} + +impl From for ServerRef { + fn from(name: String) -> Self { + ServerRef::Name(name) + } +} + +impl std::fmt::Display for ServerRef { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ServerRef::Pid(pid) => write!(f, "{:?}", pid), + ServerRef::Name(name) => write!(f, "{}", name), + } + } +} +``` + +**Step 2: Export from gen_server mod** + +In `crates/ambitious/src/gen_server/mod.rs`, add after `mod types;` (line 88): + +```rust +mod server_ref; +``` + +And update the exports at line 91 from: + +```rust +pub use server::{Error, call, cast, start, start_link}; +``` + +to: + +```rust +pub use server::{Error, call, cast, start, start_link}; +pub use server_ref::ServerRef; +``` + +Also update the gen_server prelude (line 108-111) to include `ServerRef`: + +```rust +pub use super::{ + Error, ExitReason, From, GenServer, Init, Pid, Reply, ServerRef, Status, async_trait, + call, cast, start, start_link, +}; +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/gen_server/server_ref.rs crates/ambitious/src/gen_server/mod.rs +git commit -m "feat: add ServerRef type for addressing GenServers by PID or name" +``` + +--- + +## Task 10: Update call and cast to accept ServerRef + +**Files:** +- Modify: `crates/ambitious/src/gen_server/server.rs` + +**Step 1: Update call signature** + +In `crates/ambitious/src/gen_server/server.rs`, change the `call` function (line 354) from: + +```rust +pub async fn call(pid: Pid, msg: G::Call, timeout: Duration) -> Result +where + G: GenServer, + R: Message, +{ + use tokio::time::timeout as tokio_timeout; + + let reference = Ref::new(); + let caller_pid = crate::current_pid(); +``` + +to: + +```rust +pub async fn call( + server: impl Into, + msg: G::Call, + timeout: Duration, +) -> Result +where + G: GenServer, + R: Message, +{ + use tokio::time::timeout as tokio_timeout; + + let pid = server.into().resolve().ok_or(Error::NotFound)?; + let reference = Ref::new(); + let caller_pid = crate::current_pid(); +``` + +**Step 2: Update cast signature** + +Change the `cast` function (line 421) from: + +```rust +pub fn cast(pid: Pid, msg: G::Cast) +where + G: GenServer, +{ + // Wrap in $gen_cast envelope + let envelope = encode_gen_cast_envelope(msg.encode_local()); + let _ = crate::send_raw(pid, envelope); +} +``` + +to: + +```rust +pub fn cast(server: impl Into, msg: G::Cast) +where + G: GenServer, +{ + let Some(pid) = server.into().resolve() else { + return; + }; + // Wrap in $gen_cast envelope + let envelope = encode_gen_cast_envelope(msg.encode_local()); + let _ = crate::send_raw(pid, envelope); +} +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors (existing callers pass `Pid` which implements `Into`) + +**Step 4: Run existing tests** + +Run: `cargo test -p ambitious gen_server` +Expected: All existing tests pass (backward compatible via `From`) + +**Step 5: Commit** + +```bash +git add crates/ambitious/src/gen_server/server.rs +git commit -m "feat: update call/cast to accept impl Into" +``` + +--- + +## Task 11: Add public reply() function + +**Files:** +- Modify: `crates/ambitious/src/gen_server/server.rs` +- Modify: `crates/ambitious/src/gen_server/mod.rs` + +**Step 1: Add the public reply function** + +In `crates/ambitious/src/gen_server/server.rs`, add after the `cast` function: + +```rust +/// Sends a reply to a caller outside of the normal handle_call return flow. +/// +/// This is useful when `handle_call` returns `Reply::NoReply` and the +/// reply needs to be sent later (deferred reply pattern). +/// +/// # Example +/// +/// ```ignore +/// async fn handle_call(&mut self, msg: MyCall, from: From) -> Reply { +/// // Store `from` and reply later +/// self.pending = Some(from); +/// Reply::NoReply +/// } +/// +/// // Later, in handle_cast or handle_info: +/// gen_server::reply(&self.pending.take().unwrap(), MyReply::Done); +/// ``` +pub fn reply(from: &From, value: T) { + send_reply(from, value.encode_local()); +} +``` + +Note: `send_reply` already exists as a private function at line 304. The new `reply` function just exposes it publicly with a typed interface. + +**Step 2: Export reply from gen_server mod** + +In `crates/ambitious/src/gen_server/mod.rs`, update line 91 from: + +```rust +pub use server::{Error, call, cast, start, start_link}; +``` + +to: + +```rust +pub use server::{Error, call, cast, reply, start, start_link}; +``` + +Update the prelude too (the `pub use super::` block): + +```rust +pub use super::{ + Error, ExitReason, From, GenServer, Init, Pid, Reply, ServerRef, Status, async_trait, + call, cast, reply, start, start_link, +}; +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/gen_server/server.rs crates/ambitious/src/gen_server/mod.rs +git commit -m "feat: add public reply() function for deferred GenServer replies" +``` + +--- + +## Task 12: Add public stop() function + +**Files:** +- Modify: `crates/ambitious/src/gen_server/server.rs` +- Modify: `crates/ambitious/src/gen_server/mod.rs` + +**Step 1: Add the stop function** + +In `crates/ambitious/src/gen_server/server.rs`, add after the `reply` function: + +```rust +/// Gracefully stops a GenServer. +/// +/// Sends a stop message to the server and waits for acknowledgment. +/// The server's `terminate` callback will be called with the given reason. +/// +/// # Example +/// +/// ```ignore +/// gen_server::stop(pid, ExitReason::Normal).await?; +/// gen_server::stop("my_server", ExitReason::Shutdown).await?; +/// ``` +pub async fn stop( + server: impl Into, + reason: ExitReason, +) -> Result<(), Error> { + let pid = server.into().resolve().ok_or(Error::NotFound)?; + + let reference = Ref::new(); + let caller_pid = crate::current_pid(); + + let from = From { + pid: caller_pid, + reference, + }; + + // Send a Stop protocol message with a from handle for reply + let stop_msg = super::protocol::encode_stop(reason, Some(from)); + let _ = crate::send_raw(pid, stop_msg); + + // Wait for acknowledgment with a reasonable timeout + let result = tokio::time::timeout( + Duration::from_secs(5), + wait_for_reply::<()>(reference), + ) + .await; + + match result { + Ok(Ok(())) => Ok(()), + Ok(Err(e)) => Err(e), + Err(_) => Err(Error::Timeout), + } +} +``` + +Note: The `()` type needs to implement `Message`. Check if it already does. Looking at the codebase, `()` should implement `Message` via the derive or blanket impl. If not, we may need to handle this differently. The existing server loop already handles `ProtocolMessage::Stop` at line 200-206 of `server.rs` and sends a reply using `send_reply(&f, Term::encode(&()))`. So the reply payload is `Term::encode(&())` which is the raw encoding. The `wait_for_reply` function decodes using `Message::decode_local`. We need `()` to implement `Message`. + +Let's check - if `()` doesn't implement `Message`, we can use a simpler approach: just send the exit signal and don't wait for reply. Actually, looking at the stop handler in `gen_server_loop`: + +```rust +ProtocolMessage::Stop { reason, from } => { + if let Some(f) = from { + send_reply(&f, Term::encode(&())); + } + server.terminate(reason).await; + return; +} +``` + +The reply is `Term::encode(&())` which is raw bytes, then `wait_for_reply::<()>` would try to decode it via `Message::decode_local`. The `()` type likely doesn't implement `Message`. Let's change the approach to just send an exit signal: + +```rust +/// Gracefully stops a GenServer. +/// +/// Sends an exit signal with the given reason to the server process. +/// The server's `terminate` callback will be called. +/// +/// # Example +/// +/// ```ignore +/// gen_server::stop(pid, ExitReason::Normal).await?; +/// gen_server::stop("my_server", ExitReason::Shutdown).await?; +/// ``` +pub async fn stop( + server: impl Into, + reason: ExitReason, +) -> Result<(), Error> { + let pid = server.into().resolve().ok_or(Error::NotFound)?; + + // Send a Stop protocol message + let stop_msg = super::protocol::encode_stop(reason, None); + crate::send_raw(pid, stop_msg).map_err(|_| Error::NotFound)?; + + Ok(()) +} +``` + +**Step 2: Export stop from gen_server mod** + +In `crates/ambitious/src/gen_server/mod.rs`, update the exports: + +```rust +pub use server::{Error, call, cast, reply, start, start_link, stop}; +``` + +Update the prelude: + +```rust +pub use super::{ + Error, ExitReason, From, GenServer, Init, Pid, Reply, ServerRef, Status, async_trait, + call, cast, reply, start, start_link, stop, +}; +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/gen_server/server.rs crates/ambitious/src/gen_server/mod.rs +git commit -m "feat: add public stop() function for graceful GenServer shutdown" +``` + +--- + +## Task 13: Update lib.rs for GenServer re-exports + +**Files:** +- Modify: `crates/ambitious/src/lib.rs` + +**Step 1: Add ServerRef to prelude** + +In `crates/ambitious/src/lib.rs`, update the prelude's GenServer section (lines 215-217) from: + +```rust +pub use crate::gen_server::{ + Error, From, GenServer, Init, Reply, Status, call, cast, start, start_link, +}; +``` + +to: + +```rust +pub use crate::gen_server::{ + Error, From, GenServer, Init, Reply, ServerRef, Status, call, cast, reply, start, + start_link, stop, +}; +``` + +**Step 2: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/lib.rs +git commit -m "feat: add ServerRef, reply, stop to lib.rs prelude" +``` + +--- + +## Task 14: Write tests for Phase 2 GenServer ergonomics + +**Files:** +- Modify: `crates/ambitious/src/gen_server/mod.rs` + +**Step 1: Add ServerRef and stop tests** + +Add to the existing `#[cfg(test)] mod tests` in `crates/ambitious/src/gen_server/mod.rs`: + +```rust +#[test] +fn test_server_ref_from_pid() { + let pid = crate::core::Pid::new(); + let sr: ServerRef = pid.into(); + match sr { + ServerRef::Pid(p) => assert_eq!(p, pid), + _ => panic!("expected Pid variant"), + } +} + +#[test] +fn test_server_ref_from_str() { + let sr: ServerRef = "my_server".into(); + match sr { + ServerRef::Name(n) => assert_eq!(n, "my_server"), + _ => panic!("expected Name variant"), + } +} + +#[test] +fn test_server_ref_from_string() { + let sr: ServerRef = String::from("my_server").into(); + match sr { + ServerRef::Name(n) => assert_eq!(n, "my_server"), + _ => panic!("expected Name variant"), + } +} + +#[test] +fn test_server_ref_resolve_unregistered() { + crate::init(); + let sr = ServerRef::Name("nonexistent_server".to_string()); + assert!(sr.resolve().is_none()); +} + +#[tokio::test] +async fn test_call_with_server_ref_pid() { + crate::init(); + let handle = crate::handle(); + + let result = Arc::new(AtomicI64::new(-1)); + let result_clone = result.clone(); + + handle.spawn(move || async move { + let pid = start::(42).await.expect("failed to start counter"); + + // Call using Pid directly (backwards compatible) + let reply: CounterReply = + call::(pid, CounterCall::Get, Duration::from_secs(5)) + .await + .expect("call failed"); + + result_clone.store(reply.0, Ordering::SeqCst); + }); + + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!(result.load(Ordering::SeqCst), 42); +} + +#[tokio::test] +async fn test_stop_gen_server() { + use crate::gen_server::stop; + + crate::init(); + let handle = crate::handle(); + + let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stopped_clone = stopped.clone(); + + handle.spawn(move || async move { + let pid = start::(0).await.expect("failed to start counter"); + assert!(crate::alive(pid)); + + stop(pid, crate::core::ExitReason::Normal).await.unwrap(); + + // Give it time to process + tokio::time::sleep(Duration::from_millis(50)).await; + + stopped_clone.store(!crate::alive(pid), Ordering::SeqCst); + }); + + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(stopped.load(Ordering::SeqCst), "Server should have stopped"); +} +``` + +**Step 2: Run the tests** + +Run: `cargo test -p ambitious gen_server` +Expected: All tests pass + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/gen_server/mod.rs +git commit -m "test: add tests for ServerRef, call with ServerRef, and stop" +``` + +--- + +## Task 15: Run full CI for Phase 2 + +**Step 1: Run CI** + +Run: `just ci` +Expected: All tests pass, no warnings + +**Step 2: Fix any issues and commit** + +--- + +## Task 16: Add SupervisorCommand enum and handler + +**Files:** +- Modify: `crates/ambitious/src/supervisor/core.rs` + +**Step 1: Define the SupervisorCommand enum** + +Add after the `SupervisorQueryState` impl block (around line 76), before the `Supervisor` trait: + +```rust +/// Commands sent to a supervisor process for child management. +/// +/// Public functions send these commands to the supervisor's mailbox and +/// await replies, keeping state mutation inside the supervisor process. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +enum SupervisorCommand { + /// Terminate a running child, keeping its spec. + TerminateChild { + /// The child ID to terminate. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for the reply. + reply_ref: Ref, + }, + /// Delete a stopped child's spec. + DeleteChild { + /// The child ID to delete. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for the reply. + reply_ref: Ref, + }, + /// Restart a stopped child using its existing spec. + RestartChild { + /// The child ID to restart. + id: String, + /// PID to send the reply to. + reply_to: Pid, + /// Reference for the reply. + reply_ref: Ref, + }, +} + +/// Tag for supervisor command messages. +const SUPERVISOR_COMMAND_TAG: &str = "$supervisor_cmd"; + +/// Encode a supervisor command as a tagged message. +fn encode_supervisor_command(cmd: &SupervisorCommand) -> Vec { + use crate::core::Term; + let payload = Term::encode(cmd); + let tagged = crate::gen_server::protocol::TaggedEnvelope::new(SUPERVISOR_COMMAND_TAG, payload); + tagged.encode() +} + +/// Try to decode a supervisor command from raw bytes. +fn decode_supervisor_command(data: &[u8]) -> Option { + use crate::core::Term; + let tagged = crate::gen_server::protocol::TaggedEnvelope::decode(data).ok()?; + if tagged.tag != SUPERVISOR_COMMAND_TAG { + return None; + } + Term::decode(&tagged.payload).ok() +} +``` + +**Step 2: Add `use crate::core::Ref` if not already imported** + +Check the imports at the top of `core.rs`. Line 10 already has: +```rust +use crate::core::{ExitReason, Pid, Ref, SystemMessage, Term}; +``` + +`Ref` is already imported. + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles (may have dead code warnings for the new functions, that's ok) + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/supervisor/core.rs +git commit -m "feat: add SupervisorCommand enum for supervisor child management" +``` + +--- + +## Task 17: Add command handling to supervisor_loop + +**Files:** +- Modify: `crates/ambitious/src/supervisor/core.rs` + +**Step 1: Add command handling in the supervisor loop** + +In the `supervisor_loop` function (line 388), add command handling after the EXIT signal check (after line 439) and before the closing `}` of the loop: + +```rust + // Check for supervisor commands + if let Some(cmd) = decode_supervisor_command(&msg) { + match cmd { + SupervisorCommand::TerminateChild { id, reply_to, reply_ref } => { + let result = state.handle_terminate_child_command(&id).await; + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + SupervisorCommand::DeleteChild { id, reply_to, reply_ref } => { + let result = state.handle_delete_child_command(&id); + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + SupervisorCommand::RestartChild { id, reply_to, reply_ref } => { + let result = state.handle_restart_child_command(&id).await; + state.sync_to_registry(); + let reply_bytes = Term::encode(&result); + let reply_msg = crate::gen_server::protocol::encode_reply(reply_ref, &reply_bytes); + let _ = crate::send_raw(reply_to, reply_msg); + } + } + } +``` + +**Step 2: Add the handler methods to SupervisorState** + +Add these methods to the `impl SupervisorState` block: + +```rust + /// Handles a terminate_child command. + /// Returns Ok(()) if child was terminated or already stopped. + /// Returns Err with message if child not found. + async fn handle_terminate_child_command(&mut self, id: &str) -> Result<(), String> { + if !self.children.contains_key(id) { + return Err(format!("child '{}' not found", id)); + } + + // Terminate the child (idempotent - ok if already stopped) + self.terminate_child_by_id(id).await; + Ok(()) + } + + /// Handles a delete_child command. + /// Returns Ok(()) if child spec was deleted. + /// Returns Err with message if child not found or still running. + fn handle_delete_child_command(&mut self, id: &str) -> Result<(), String> { + let child = self.children.get(id) + .ok_or_else(|| format!("not_found:{}", id))?; + + if child.pid.is_some() { + return Err(format!("running:{}", id)); + } + + // Remove from children map and child_order + self.children.remove(id); + self.child_order.retain(|i| i != id); + + Ok(()) + } + + /// Handles a restart_child command. + /// Returns Ok(pid) if child was restarted. + /// Returns Err with message if child not found, already running, or failed to start. + async fn handle_restart_child_command(&mut self, id: &str) -> Result { + let child = self.children.get(id) + .ok_or_else(|| format!("not_found:{}", id))?; + + if child.pid.is_some() { + return Err(format!("already_running:{}", id)); + } + + // Start the child using its existing spec + self.start_child(id).await + } +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/supervisor/core.rs +git commit -m "feat: add command handling to supervisor loop for child management" +``` + +--- + +## Task 18: Implement terminate_child via command + +**Files:** +- Modify: `crates/ambitious/src/supervisor/core.rs` + +**Step 1: Replace the terminate_child stub** + +Replace the existing `terminate_child` function (lines 582-589) with: + +```rust +/// Terminates a child process managed by the supervisor. +/// +/// The child's spec is kept, so it can be restarted later with `restart_child`. +/// If the child is already stopped, returns `Ok(())` (idempotent). +/// +/// This function sends a command to the supervisor process and waits for a reply. +pub async fn terminate_child( + _handle: &RuntimeHandle, + sup: Pid, + id: &str, +) -> Result<(), TerminateError> { + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::TerminateChild { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + // Send command to supervisor + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| TerminateError::NotFound(id.to_string()))?; + + // Wait for reply + let reply = wait_for_supervisor_reply(reply_ref).await + .map_err(|_| TerminateError::Timeout)?; + + // Decode result + let result: Result<(), String> = Term::decode(&reply) + .map_err(|_| TerminateError::NotFound(id.to_string()))?; + + result.map_err(|e| TerminateError::NotFound(e)) +} +``` + +**Step 2: Add the wait_for_supervisor_reply helper** + +Add this helper function near the bottom of the file, before the `wait_for_termination` function: + +```rust +/// Waits for a reply from the supervisor matching the given reference. +async fn wait_for_supervisor_reply(reference: Ref) -> Result, ()> { + use crate::gen_server::protocol::Message as ProtocolMessage; + + let timeout = std::time::Duration::from_secs(5); + let deadline = tokio::time::Instant::now() + timeout; + + loop { + let remaining = deadline - tokio::time::Instant::now(); + if remaining.is_zero() { + return Err(()); + } + + let raw_msg = match crate::runtime::recv_timeout(remaining).await { + Ok(Some(m)) => m, + Ok(None) => return Err(()), // Mailbox closed + Err(()) => return Err(()), // Timeout + }; + + // Check if this is our reply + if let Ok(ProtocolMessage::Reply { + reference: ref r, + payload, + }) = ProtocolMessage::decode(&raw_msg) + { + if *r == reference { + return Ok(payload); + } + } + + // Not our reply - put it back? No, just log and continue. + // In a production system we'd want selective receive, but for now + // supervisor commands are typically sent from dedicated callers. + tracing::trace!("supervisor: ignoring non-reply message while waiting for command reply"); + } +} +``` + +**Step 3: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 4: Commit** + +```bash +git add crates/ambitious/src/supervisor/core.rs +git commit -m "feat: implement terminate_child via supervisor command" +``` + +--- + +## Task 19: Implement delete_child via command + +**Files:** +- Modify: `crates/ambitious/src/supervisor/core.rs` + +**Step 1: Replace the delete_child stub** + +Replace the existing `delete_child` function (lines 594-601, now shifted) with: + +```rust +/// Deletes a stopped child's specification from the supervisor. +/// +/// The child must be stopped first (via `terminate_child`). +/// Returns an error if the child is still running or not found. +pub async fn delete_child( + _handle: &RuntimeHandle, + sup: Pid, + id: &str, +) -> Result<(), DeleteError> { + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::DeleteChild { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + // Send command to supervisor + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| DeleteError::NotFound(id.to_string()))?; + + // Wait for reply + let reply = wait_for_supervisor_reply(reply_ref).await + .map_err(|_| DeleteError::NotFound(id.to_string()))?; + + // Decode result + let result: Result<(), String> = Term::decode(&reply) + .map_err(|_| DeleteError::NotFound(id.to_string()))?; + + result.map_err(|e| { + if e.starts_with("running:") { + DeleteError::Running(e.strip_prefix("running:").unwrap_or(&e).to_string()) + } else { + DeleteError::NotFound(e.strip_prefix("not_found:").unwrap_or(&e).to_string()) + } + }) +} +``` + +**Step 2: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/supervisor/core.rs +git commit -m "feat: implement delete_child via supervisor command" +``` + +--- + +## Task 20: Add restart_child function + +**Files:** +- Modify: `crates/ambitious/src/supervisor/core.rs` +- Modify: `crates/ambitious/src/supervisor/mod.rs` + +**Step 1: Add the restart_child public function** + +Add after the `delete_child` function: + +```rust +/// Restarts a terminated child using its existing specification. +/// +/// The child must be stopped first. Returns the new PID of the restarted child. +pub async fn restart_child( + _handle: &RuntimeHandle, + sup: Pid, + id: &str, +) -> Result { + let reply_ref = Ref::new(); + let caller_pid = crate::runtime::current_pid(); + + let cmd = SupervisorCommand::RestartChild { + id: id.to_string(), + reply_to: caller_pid, + reply_ref, + }; + + // Send command to supervisor + crate::send_raw(sup, encode_supervisor_command(&cmd)) + .map_err(|_| RestartError::NotFound(id.to_string()))?; + + // Wait for reply + let reply = wait_for_supervisor_reply(reply_ref).await + .map_err(|_| RestartError::StartFailed("timeout waiting for reply".to_string()))?; + + // Decode result + let result: Result = Term::decode(&reply) + .map_err(|_| RestartError::StartFailed("decode error".to_string()))?; + + result.map_err(|e| { + if e.starts_with("already_running:") { + RestartError::AlreadyRunning( + e.strip_prefix("already_running:").unwrap_or(&e).to_string(), + ) + } else if e.starts_with("not_found:") { + RestartError::NotFound(e.strip_prefix("not_found:").unwrap_or(&e).to_string()) + } else { + RestartError::StartFailed(e) + } + }) +} +``` + +**Step 2: Add RestartError import** + +Check that `RestartError` is imported at the top of `core.rs`. Line 5 has: +```rust +use super::error::{DeleteError, StartError, TerminateError}; +``` + +Add `RestartError`: +```rust +use super::error::{DeleteError, RestartError, StartError, TerminateError}; +``` + +**Step 3: Export restart_child from supervisor/mod.rs** + +In `crates/ambitious/src/supervisor/mod.rs`, update line 66-69 from: + +```rust +pub use core::{ + Supervisor, SupervisorInit, count_children, delete_child, start, start_link, terminate_child, + which_children, +}; +``` + +to: + +```rust +pub use core::{ + Supervisor, SupervisorInit, count_children, delete_child, restart_child, start, start_link, + terminate_child, which_children, +}; +``` + +**Step 4: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors + +**Step 5: Commit** + +```bash +git add crates/ambitious/src/supervisor/core.rs crates/ambitious/src/supervisor/mod.rs +git commit -m "feat: add restart_child function for restarting terminated children" +``` + +--- + +## Task 21: Write tests for Phase 3 supervisor commands + +**Files:** +- Modify: `crates/ambitious/src/supervisor/mod.rs` + +**Step 1: Add terminate/delete/restart_child tests** + +Add to the existing test module in `crates/ambitious/src/supervisor/mod.rs`: + +```rust +#[tokio::test] +async fn test_terminate_child() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + let runtime = Runtime::new(); + let handle = runtime.handle(); + + let child_started = Arc::new(AtomicBool::new(false)); + let child_started_clone = child_started.clone(); + + struct TermTestSupervisor; + + impl Supervisor for TermTestSupervisor { + type InitArg = (RuntimeHandle, Arc); + + fn init((handle, started_flag): Self::InitArg) -> SupervisorInit { + let handle_clone = handle.clone(); + SupervisorInit::new( + SupervisorFlags::new(Strategy::OneForOne) + .max_restarts(0) + .max_seconds(5), + vec![ChildSpec::new("worker1", move || { + let h = handle_clone.clone(); + let sf = started_flag.clone(); + async move { + let pid = h.spawn(move || async move { + sf.store(true, Ordering::SeqCst); + while let Ok(Some(_)) = + crate::recv_timeout(Duration::from_secs(60)).await + { + } + }); + Ok(pid) + } + }) + .restart(RestartType::Temporary)], + ) + } + } + + // Need to spawn within a process context for terminate_child + let test_passed = Arc::new(AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let sup_pid = + start::(&handle_clone, (handle_clone.clone(), child_started_clone)) + .await + .unwrap(); + + sleep(Duration::from_millis(50)).await; + + // Terminate the child + let result = terminate_child(&handle_clone, sup_pid, "worker1").await; + assert!(result.is_ok(), "terminate_child should succeed: {:?}", result); + + // Terminating again should be idempotent + let result2 = terminate_child(&handle_clone, sup_pid, "worker1").await; + assert!(result2.is_ok(), "terminate_child should be idempotent"); + + // Not found + let result3 = terminate_child(&handle_clone, sup_pid, "nonexistent").await; + assert!(result3.is_err(), "terminate_child should error for nonexistent"); + + test_passed_clone.store(true, Ordering::SeqCst); + }); + + sleep(Duration::from_millis(500)).await; + assert!( + test_passed.load(Ordering::SeqCst), + "terminate_child test should pass" + ); +} + +#[tokio::test] +async fn test_delete_child() { + let runtime = Runtime::new(); + let handle = runtime.handle(); + + struct DeleteTestSupervisor; + + impl Supervisor for DeleteTestSupervisor { + type InitArg = RuntimeHandle; + + fn init(handle: Self::InitArg) -> SupervisorInit { + let handle_clone = handle.clone(); + SupervisorInit::new( + SupervisorFlags::new(Strategy::OneForOne) + .max_restarts(0) + .max_seconds(5), + vec![ChildSpec::new("worker1", move || { + let h = handle_clone.clone(); + async move { + let pid = h.spawn(|| async { + while let Ok(Some(_)) = + crate::recv_timeout(Duration::from_secs(60)).await + { + } + }); + Ok(pid) + } + }) + .restart(RestartType::Temporary)], + ) + } + } + + let test_passed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let sup_pid = start::(&handle_clone, handle_clone.clone()) + .await + .unwrap(); + + sleep(Duration::from_millis(50)).await; + + // Can't delete a running child + let result = delete_child(&handle_clone, sup_pid, "worker1").await; + assert!(result.is_err(), "delete_child should fail for running child"); + + // Terminate first, then delete + terminate_child(&handle_clone, sup_pid, "worker1") + .await + .unwrap(); + sleep(Duration::from_millis(50)).await; + + let result2 = delete_child(&handle_clone, sup_pid, "worker1").await; + assert!(result2.is_ok(), "delete_child should succeed after terminate: {:?}", result2); + + // Delete again should fail (not found) + let result3 = delete_child(&handle_clone, sup_pid, "worker1").await; + assert!(result3.is_err(), "delete_child should fail after already deleted"); + + test_passed_clone.store(true, std::sync::atomic::Ordering::SeqCst); + }); + + sleep(Duration::from_millis(500)).await; + assert!( + test_passed.load(std::sync::atomic::Ordering::SeqCst), + "delete_child test should pass" + ); +} + +#[tokio::test] +async fn test_restart_child() { + let runtime = Runtime::new(); + let handle = runtime.handle(); + + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let start_count = Arc::new(AtomicUsize::new(0)); + let start_count_clone = start_count.clone(); + + struct RestartTestSupervisor; + + impl Supervisor for RestartTestSupervisor { + type InitArg = (RuntimeHandle, Arc); + + fn init((handle, count): Self::InitArg) -> SupervisorInit { + let handle_clone = handle.clone(); + SupervisorInit::new( + SupervisorFlags::new(Strategy::OneForOne) + .max_restarts(0) + .max_seconds(5), + vec![ChildSpec::new("worker1", move || { + let h = handle_clone.clone(); + let c = count.clone(); + async move { + let pid = h.spawn(move || async move { + c.fetch_add(1, Ordering::SeqCst); + while let Ok(Some(_)) = + crate::recv_timeout(Duration::from_secs(60)).await + { + } + }); + Ok(pid) + } + }) + .restart(RestartType::Temporary)], + ) + } + } + + let test_passed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let test_passed_clone = test_passed.clone(); + let handle_clone = handle.clone(); + + handle.spawn(move || async move { + let sup_pid = start::( + &handle_clone, + (handle_clone.clone(), start_count_clone), + ) + .await + .unwrap(); + + sleep(Duration::from_millis(50)).await; + assert_eq!(start_count.load(Ordering::SeqCst), 1, "Should have started once"); + + // Can't restart a running child + let result = + crate::supervisor::restart_child(&handle_clone, sup_pid, "worker1").await; + assert!(result.is_err(), "restart_child should fail for running child"); + + // Terminate, then restart + terminate_child(&handle_clone, sup_pid, "worker1") + .await + .unwrap(); + sleep(Duration::from_millis(50)).await; + + let result2 = + crate::supervisor::restart_child(&handle_clone, sup_pid, "worker1").await; + assert!(result2.is_ok(), "restart_child should succeed: {:?}", result2); + + sleep(Duration::from_millis(50)).await; + assert_eq!( + start_count.load(Ordering::SeqCst), + 2, + "Should have started twice" + ); + + test_passed_clone.store(true, std::sync::atomic::Ordering::SeqCst); + }); + + sleep(Duration::from_millis(1000)).await; + assert!( + test_passed.load(std::sync::atomic::Ordering::SeqCst), + "restart_child test should pass" + ); +} +``` + +**Step 2: Run the tests** + +Run: `cargo test -p ambitious supervisor::tests::test_terminate_child -- --nocapture` +Run: `cargo test -p ambitious supervisor::tests::test_delete_child -- --nocapture` +Run: `cargo test -p ambitious supervisor::tests::test_restart_child -- --nocapture` +Expected: All pass + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/supervisor/mod.rs +git commit -m "test: add tests for terminate_child, delete_child, restart_child" +``` + +--- + +## Task 22: Run full CI for Phase 3 + +**Step 1: Run CI** + +Run: `just ci` +Expected: All tests pass, no warnings + +**Step 2: Fix any issues and commit** + +--- + +## Task 23: Remove unsafe from AppController + +**Files:** +- Modify: `crates/ambitious/src/application/core.rs` + +**Step 1: Change type aliases from Box to Arc** + +In `crates/ambitious/src/application/core.rs`, change lines 11-14 from: + +```rust +type StartFn = Box Result + Send + Sync>; + +/// Type alias for the application stop function. +type StopFn = Box) + Send + Sync>; +``` + +to: + +```rust +type StartFn = Arc Result + Send + Sync>; + +/// Type alias for the application stop function. +type StopFn = Arc) + Send + Sync>; +``` + +**Step 2: Update register to use Arc** + +In the `register` method (line 106), change the function creation from `Box::new` to `Arc::new`: + +```rust +let app = RegisteredApp { + spec, + start_fn: Arc::new(|handle, config| A::start(handle, config)), + stop_fn: Arc::new(|pid| A::stop(pid)), +}; +``` + +**Step 3: Replace unsafe block with safe Arc clone** + +Replace the block at lines 149-172 (the `let (start_fn, _spec)` block and the unsafe call) with: + +```rust + let start_fn = { + let registered = self.registered.read().unwrap(); + let app = registered + .get(&app_name) + .ok_or_else(|| StartError::NotFound(app_name.clone()))?; + app.start_fn.clone() + }; + + // Start it + let app_config = if app_name == name { + config.clone() + } else { + AppConfig::new() + }; + + let result = start_fn(&self.handle, &app_config); +``` + +**Step 4: Add Arc import** + +Check if `Arc` is already imported. Line 8 has: +```rust +use std::sync::{Arc, RwLock}; +``` + +Already imported. + +**Step 5: Run `cargo check`** + +Run: `cargo check -p ambitious` +Expected: Compiles with no errors, no unsafe blocks + +**Step 6: Run existing application tests** + +Run: `cargo test -p ambitious application` +Expected: All tests pass + +**Step 7: Commit** + +```bash +git add crates/ambitious/src/application/core.rs +git commit -m "fix: remove unsafe from AppController by using Arc instead of Box" +``` + +--- + +## Task 24: Fix stop_all reverse dependency ordering + +**Files:** +- Modify: `crates/ambitious/src/application/core.rs` + +**Step 1: Replace stop_all implementation** + +Replace the `stop_all` method (lines 218-229, now shifted) with: + +```rust + /// Stops all running applications in reverse dependency order. + /// + /// Applications that depend on others are stopped first, then their + /// dependencies are stopped. + pub async fn stop_all(&self) { + // Collect all running app names and build dependency-aware stop order + let stop_order = { + let running = self.running.read().unwrap(); + let running_names: Vec = running.keys().cloned().collect(); + + if running_names.is_empty() { + return; + } + + // Build the full startup order for all running apps, then reverse it + let mut startup_order = Vec::new(); + let mut visited = std::collections::HashSet::new(); + let registered = self.registered.read().unwrap(); + + for name in &running_names { + let mut path = Vec::new(); + // Ignore errors - just best-effort ordering + let _ = Self::visit_deps(name, ®istered, &mut startup_order, &mut visited, &mut path); + } + + // Reverse the startup order for shutdown + startup_order.into_iter().rev().collect::>() + }; + + // Stop each in reverse dependency order + for name in &stop_order { + let _ = self.stop(name).await; + } + } +``` + +**Step 2: Run tests** + +Run: `cargo test -p ambitious application` +Expected: All tests pass + +**Step 3: Commit** + +```bash +git add crates/ambitious/src/application/core.rs +git commit -m "fix: stop_all uses reverse dependency order" +``` + +--- + +## Task 25: Run full CI for Phase 4 + +**Step 1: Run CI** + +Run: `just ci` +Expected: All tests pass, no warnings + +**Step 2: Fix any issues and commit** + +--- + +## Task 26: Update CLAUDE.md documentation + +**Files:** +- Modify: `CLAUDE.md` + +**Step 1: Update relevant sections** + +Make the following updates to `CLAUDE.md`: + +1. **Crate structure**: Note that the project is a single crate (not the multi-crate structure shown) + +2. **Process API**: Add `link`, `unlink`, `monitor`, `demonitor`, `flag`, `send_after` to the process functions + +3. **GenServer API**: Update to show: + - `ServerRef` type and usage with `call`/`cast` + - `reply()` public function + - `stop()` public function + - Current trait signature with `&mut self` handlers and `Reply`/`Status` return types + +4. **Supervisor API**: Add `terminate_child`, `delete_child`, `restart_child` as implemented + +5. **Message trait**: Update to show `encode_local`/`decode_local`/`encode_remote`/`decode_remote` instead of `encode`/`decode` + +**Step 2: Commit** + +```bash +git add CLAUDE.md +git commit -m "docs: update CLAUDE.md to match current implementation" +``` + +--- + +## Task 27: Update README.md documentation + +**Files:** +- Modify: `README.md` + +**Step 1: Update GenServer example to match current API** + +Fix the GenServer example to use: +- `Reply` and `Status` return types +- `&mut self` handlers +- `ServerRef` usage example + +**Step 2: Commit** + +```bash +git add README.md +git commit -m "docs: update README.md examples to match current API" +``` + +--- + +## Task 28: Final CI run + +**Step 1: Run full CI** + +Run: `just ci` +Expected: All tests pass, no warnings, clean build + +**Step 2: Verify the changes** + +Run: `git log --oneline -20` +Verify all commits are present and well-described. + +--- + +## Summary of Changes + +| Phase | What | Files | +|-------|------|-------| +| 1 | Process convenience functions | `core/process_flag.rs`, `runtime/task_local.rs`, `runtime/mod.rs`, `lib.rs` | +| 2 | GenServer ServerRef + reply + stop | `gen_server/server_ref.rs`, `gen_server/server.rs`, `gen_server/mod.rs`, `lib.rs` | +| 3 | Supervisor commands | `supervisor/core.rs`, `supervisor/mod.rs` | +| 4 | Application safety + ordering | `application/core.rs` | +| 5 | Documentation sync | `CLAUDE.md`, `README.md` |