feat(M3.4): complete the fake server lifecycle
Rust CI fader_master passed CI.
MadGobblins/fader_master/pipeline/head This commit looks good Details

Add adopt and ordered restore startup behavior, confirmed fake readback, unavailable and reconnect transitions, bounded exponential retry, disconnect invalidation, joined worker cancellation, and drain-before-checkpoint shutdown. Record the verified M3 hardware-free milestone.

Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features --locked; cargo test --workspace --all-targets --all-features --locked; cargo test --workspace --doc --all-features --locked; cargo clippy --workspace --all-targets --all-features --locked -- -D warnings; cargo build --workspace --release --all-features --locked; cargo check --workspace --all-targets --no-default-features --locked; cargo test --workspace --all-targets --no-default-features --locked (all pass)
This commit is contained in:
Dandaedre 2026-10-14 15:42:50 +02:00
parent 58e08f3741
commit 4f3eb4f279
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 433 additions and 10 deletions

View File

@ -1,9 +1,10 @@
# fader_master architecture
Status: design researched 2026-10-05; foundation, M1 domain contracts, and the
M2 TOML/persistence milestone are implemented. The executable launches an
interactive Ratatui mixer shell backed by explicitly labeled demo state. Runtime
workers, live TUI state, and native adapters below are planned, not shipped.
Status: design researched 2026-10-05; foundation and the M1–M3 hardware-free
domain, persistence, reducer, bounded dispatch, fake-adapter, and lifecycle
milestones are implemented. The executable launches an interactive Ratatui mixer
shell backed by explicitly labeled demo state. Native workers, live TUI state,
and native adapters below are planned, not shipped.
## Implemented boundary at M2 entry

View File

@ -81,6 +81,9 @@ pub enum AdapterEvent {
operation: OperationId,
message: String,
},
WriteSuperseded {
operation: OperationId,
},
StreamRemoved {
stream: StreamHandle,
},
@ -308,6 +311,10 @@ impl ServerReducer {
}
Ok(Transition::default())
}
AdapterEvent::WriteSuperseded { operation } => {
self.operations.remove(&operation);
Ok(Transition::default())
}
AdapterEvent::StreamRemoved { stream } => {
self.streams.remove(&stream);
self.operations

202
fader_master/src/lib.rs Normal file
View File

@ -0,0 +1,202 @@
//! Hardware-free server lifecycle used by the first vertical slice.
#![forbid(unsafe_code)]
use std::{collections::BTreeMap, error::Error, fmt};
use fader_core::{
AdapterEvent, ChannelGains, CommandOrigin, Gain, Mute, ReducerError, ServerCommand,
ServerReducer, StreamHandle, StreamView, Transition,
};
use volume_lib::{AdapterQueue, Enqueue, FakeAdapter};
/// Failure surfaced by the simulated server boundary.
#[derive(Debug)]
pub enum SliceError {
Reducer(ReducerError),
DispatchOverflow,
SnapshotInProgress,
}
/// Observable lifecycle state of the fake-backed server.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ServerStatus {
Ready,
Unavailable,
}
impl fmt::Display for SliceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Reducer(error) => error.fmt(formatter),
Self::DispatchOverflow => formatter.write_str("bounded adapter queue overflowed"),
Self::SnapshotInProgress => formatter.write_str("adapter snapshot is already active"),
}
}
}
impl Error for SliceError {}
impl From<ReducerError> for SliceError {
fn from(value: ReducerError) -> Self {
Self::Reducer(value)
}
}
/// In-process M3 server using the same effects as future native workers.
#[derive(Debug)]
pub struct VerticalSlice {
reducer: ServerReducer,
adapter: FakeAdapter,
dispatch: AdapterQueue,
confirmed: BTreeMap<StreamHandle, StreamView>,
status: ServerStatus,
}
impl VerticalSlice {
#[must_use]
pub fn new(adapter: FakeAdapter, queue_capacity: usize, write_ceiling: Gain) -> Self {
Self {
reducer: ServerReducer::new(write_ceiling),
adapter,
dispatch: AdapterQueue::new(queue_capacity),
confirmed: BTreeMap::new(),
status: ServerStatus::Ready,
}
}
#[must_use]
pub const fn status(&self) -> ServerStatus {
self.status
}
/// Returns the latest observation confirmed by adapter readback.
#[must_use]
pub fn confirmed(&self, stream: StreamHandle) -> Option<&StreamView> {
self.confirmed.get(&stream)
}
/// Adds a discovered stream by adopting its live state without a write.
pub fn adopt(
&mut self,
stream: StreamHandle,
channels: ChannelGains,
muted: Mute,
) -> Result<StreamView, SliceError> {
let event = self
.adapter
.upsert(stream, channels, muted)
.ok_or(SliceError::SnapshotInProgress)?;
self.reduce_event(event)?;
self.confirmed
.get(&stream)
.cloned()
.ok_or(SliceError::SnapshotInProgress)
}
/// Runs a simulated MIDI volume command through dispatch and readback.
pub fn midi_volume(
&mut self,
surface: impl Into<String>,
sequence: u64,
stream: StreamHandle,
target: Gain,
) -> Result<StreamView, SliceError> {
let transition = self.reducer.command(ServerCommand::SetVolume {
origin: CommandOrigin::Midi {
surface: surface.into(),
sequence,
},
expected_revision: self.reducer.revision(),
stream,
target,
})?;
self.enqueue(transition)?;
self.drain()?;
self.confirmed
.get(&stream)
.cloned()
.ok_or(SliceError::SnapshotInProgress)
}
/// Invalidates current handles and pending operations.
pub fn disconnect(&mut self) -> Result<(), SliceError> {
let streams = self.confirmed.keys().copied().collect::<Vec<_>>();
for stream in streams {
self.adapter.remove(stream);
self.reduce_event(AdapterEvent::StreamRemoved { stream })?;
self.confirmed.remove(&stream);
}
self.status = ServerStatus::Unavailable;
Ok(())
}
/// Replaces a disconnected worker and adopts its complete fresh snapshot.
pub fn reconnect(
&mut self,
adapter: FakeAdapter,
observations: Vec<(StreamHandle, ChannelGains, Mute)>,
) -> Result<(), SliceError> {
self.adapter = adapter;
self.status = ServerStatus::Ready;
for (stream, channels, muted) in observations {
self.adopt(stream, channels, muted)?;
}
Ok(())
}
/// Applies explicit restore entries in profile order; the last overlap wins.
pub fn restore_volumes(&mut self, entries: &[(StreamHandle, Gain)]) -> Result<(), SliceError> {
for (stream, target) in entries {
let transition = self.reducer.command(ServerCommand::SetVolume {
origin: CommandOrigin::Restore,
expected_revision: self.reducer.revision(),
stream: *stream,
target: *target,
})?;
self.enqueue(transition)?;
}
self.drain()
}
/// Drains accepted work and gives the final confirmed view to persistence.
pub fn shutdown(mut self, checkpoint: impl FnOnce(&[StreamView])) -> Result<(), SliceError> {
self.drain()?;
let views = self.confirmed.into_values().collect::<Vec<_>>();
checkpoint(&views);
Ok(())
}
fn reduce_event(&mut self, event: AdapterEvent) -> Result<(), SliceError> {
let transition = self.reducer.event(event)?;
self.enqueue(transition)
}
fn enqueue(&mut self, transition: Transition) -> Result<(), SliceError> {
for view in transition.confirmed {
self.confirmed.insert(view.stream, view);
}
for command in transition.adapter {
match self.dispatch.push(command) {
Enqueue::Queued => {}
Enqueue::Coalesced { superseded } => {
self.reducer.event(AdapterEvent::WriteSuperseded {
operation: superseded,
})?;
}
Enqueue::Overflow => return Err(SliceError::DispatchOverflow),
}
}
Ok(())
}
fn drain(&mut self) -> Result<(), SliceError> {
while let Some(command) = self.dispatch.pop() {
for event in self.adapter.execute(command) {
let transition = self.reducer.event(event)?;
self.enqueue(transition)?;
}
}
Ok(())
}
}

View File

@ -0,0 +1,88 @@
use std::{cell::RefCell, rc::Rc};
use fader_core::{BackendEpoch, ChannelGains, Gain, Mute, StreamHandle};
use fader_master::{ServerStatus, VerticalSlice};
use volume_lib::{FakeAdapter, RetrySchedule};
fn channels(left: f64, right: f64) -> ChannelGains {
ChannelGains::new(vec![Gain::new(left).unwrap(), Gain::new(right).unwrap()]).unwrap()
}
#[test]
fn reconnect_resnapshots_and_restore_overlap_uses_profile_order() {
let first_epoch = BackendEpoch::new(1);
let old = StreamHandle::new(first_epoch, 3, 1);
let mut server = VerticalSlice::new(FakeAdapter::new(first_epoch), 4, Gain::UNITY);
server
.adopt(old, channels(0.2, 0.4), Mute::Unmuted)
.unwrap();
server.disconnect().unwrap();
assert_eq!(server.status(), ServerStatus::Unavailable);
let next_epoch = BackendEpoch::new(2);
let current = StreamHandle::new(next_epoch, 3, 1);
server
.reconnect(
FakeAdapter::new(next_epoch),
vec![(current, channels(0.3, 0.6), Mute::Unmuted)],
)
.unwrap();
assert_eq!(server.status(), ServerStatus::Ready);
server
.restore_volumes(&[
(current, Gain::new(0.5).unwrap()),
(current, Gain::new(0.9).unwrap()),
])
.unwrap();
let feedback = server.confirmed(current).unwrap();
assert_eq!(feedback.channels.maximum(), Gain::new(0.9).unwrap());
}
#[test]
fn reconnect_backoff_is_bounded_and_resets_after_success() {
let mut retries = RetrySchedule::new(100, 800);
assert_eq!(
(0..5).map(|_| retries.next_delay_ms()).collect::<Vec<_>>(),
vec![100, 200, 400, 800, 800]
);
retries.reset();
assert_eq!(retries.next_delay_ms(), 100);
}
#[test]
fn startup_adopts_then_simulated_midi_converges_on_confirmed_feedback() {
let epoch = BackendEpoch::new(1);
let stream = StreamHandle::new(epoch, 8, 1);
let mut server = VerticalSlice::new(FakeAdapter::new(epoch), 8, Gain::UNITY);
let startup = server
.adopt(stream, channels(0.25, 0.5), Mute::Unmuted)
.unwrap();
assert_eq!(startup.channels, channels(0.25, 0.5));
assert!(!startup.pending);
assert_eq!(startup.desired_gain, None);
let feedback = server
.midi_volume("desk", 1, stream, Gain::new(0.8).unwrap())
.unwrap();
assert_eq!(feedback.channels, channels(0.4, 0.8));
assert_eq!(feedback.desired_gain, Some(Gain::new(0.8).unwrap()));
assert!(!feedback.pending);
}
#[test]
fn disconnect_expires_state_and_shutdown_checkpoints_after_drain() {
let epoch = BackendEpoch::new(4);
let stream = StreamHandle::new(epoch, 2, 1);
let mut server = VerticalSlice::new(FakeAdapter::new(epoch), 4, Gain::UNITY);
server
.adopt(stream, channels(0.3, 0.6), Mute::Muted)
.unwrap();
server.disconnect().unwrap();
let checkpointed = Rc::new(RefCell::new(None));
let output = Rc::clone(&checkpointed);
server
.shutdown(move |views| *output.borrow_mut() = Some(views.to_vec()))
.unwrap();
assert_eq!(checkpointed.borrow().as_deref(), Some([].as_slice()));
}

View File

@ -2,7 +2,11 @@
#![forbid(unsafe_code)]
use std::collections::{BTreeMap, VecDeque};
use std::{
collections::{BTreeMap, VecDeque},
sync::mpsc::{self, Receiver, SyncSender, TrySendError},
thread::{self, JoinHandle},
};
use fader_core::{AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, Mute, StreamHandle};
@ -57,6 +61,99 @@ pub struct AdapterQueue {
faulted: bool,
}
/// Bounded exponential reconnect timing, independent of a runtime clock.
#[derive(Clone, Copy, Debug)]
pub struct RetrySchedule {
initial_ms: u64,
maximum_ms: u64,
next_ms: u64,
}
struct WorkerRequest(AdapterCommand);
/// Joined owner thread for the fake adapter, using a bounded command channel.
#[derive(Debug)]
pub struct FakeWorker {
commands: Option<SyncSender<WorkerRequest>>,
events: Receiver<AdapterEvent>,
thread: Option<JoinHandle<()>>,
}
impl FakeWorker {
#[must_use]
pub fn spawn(mut adapter: FakeAdapter, capacity: usize) -> Self {
let (command_sender, command_receiver) = mpsc::sync_channel::<WorkerRequest>(capacity);
let (event_sender, event_receiver) = mpsc::channel();
let thread = thread::spawn(move || {
while let Ok(request) = command_receiver.recv() {
for event in adapter.execute(request.0) {
if event_sender.send(event).is_err() {
return;
}
}
}
});
Self {
commands: Some(command_sender),
events: event_receiver,
thread: Some(thread),
}
}
/// Nonblocking submission; a full lane is an explicit caller-visible fault.
pub fn try_submit(&self, command: AdapterCommand) -> Result<(), AdapterCommand> {
let Some(sender) = &self.commands else {
return Err(command);
};
match sender.try_send(WorkerRequest(command)) {
Ok(()) => Ok(()),
Err(TrySendError::Full(WorkerRequest(command)))
| Err(TrySendError::Disconnected(WorkerRequest(command))) => Err(command),
}
}
pub fn receive(&self) -> Result<AdapterEvent, mpsc::RecvError> {
self.events.recv()
}
/// Requests cancellation and does not return until the owner thread exits.
pub fn shutdown(&mut self) -> bool {
if let Some(sender) = self.commands.take() {
drop(sender);
}
self.thread
.take()
.is_none_or(|thread| thread.join().is_ok())
}
}
impl Drop for FakeWorker {
fn drop(&mut self) {
let _ = self.shutdown();
}
}
impl RetrySchedule {
#[must_use]
pub fn new(initial_ms: u64, maximum_ms: u64) -> Self {
Self {
initial_ms,
maximum_ms,
next_ms: initial_ms.min(maximum_ms),
}
}
pub fn next_delay_ms(&mut self) -> u64 {
let delay = self.next_ms;
self.next_ms = self.next_ms.saturating_mul(2).min(self.maximum_ms);
delay
}
pub fn reset(&mut self) {
self.next_ms = self.initial_ms.min(self.maximum_ms);
}
}
impl AdapterQueue {
#[must_use]
pub fn new(capacity: usize) -> Self {

View File

@ -2,7 +2,7 @@ use fader_core::{
AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, Gain, Mute, OperationId,
ServerReducer, StreamHandle,
};
use volume_lib::{FakeAdapter, WorkerEvent};
use volume_lib::{FakeAdapter, FakeWorker, WorkerEvent};
fn handle(epoch: u64, incarnation: u64) -> StreamHandle {
StreamHandle::new(BackendEpoch::new(epoch), 4, incarnation)
@ -70,3 +70,22 @@ fn reducer_ignores_old_epochs_and_reused_backend_incarnations() {
assert!(reducer.view(handle(1, 9)).is_none());
assert!(reducer.view(handle(2, 1)).is_none());
}
#[test]
fn cancellation_joins_the_bounded_worker() {
let mut adapter = FakeAdapter::new(BackendEpoch::new(1));
adapter.upsert(handle(1, 1), channels(0.3), Mute::Unmuted);
let mut worker = FakeWorker::spawn(adapter, 2);
worker
.try_submit(AdapterCommand::SetMute {
operation: OperationId::new(7),
stream: handle(1, 1),
muted: Mute::Muted,
})
.unwrap();
let AdapterEvent::WriteAccepted { operation } = worker.receive().unwrap() else {
panic!("write acceptance expected");
};
assert_eq!(operation, OperationId::new(7));
assert!(worker.shutdown());
}

17
task.md
View File

@ -76,13 +76,22 @@ real Jenkins run.
Dependencies: M1, M2. No real USB/audio device required.
- [ ] **M3.1 Reducer/effects:** one owner, command origins/revisions, desired/pending/observed state. Tests: accepted intent is recorded before adapter dispatch; success requires readback/observation; failure leaves actual state truthful; external changes update views without an outgoing audio command.
- [ ] **M3.2 Worker contract:** capabilities, snapshot barriers, readback, per-property ordered writes, operation results and fake backend. Tests: changes during snapshot are reconciled, old epoch/incarnation events are ignored, stream removal during write is handled, and newer pending intent survives an older completion.
- [ ] **M3.3 Load and ordering:** bounded channels, latest-volume coalescing, preserved mute ordering, overflow fault reporting. Tests: burst ends at latest value, toggles are not silently lost or guessed, memory stays bounded, and final readback resolves ambiguous acknowledgments.
- [ ] **M3.4 Lifecycle:** startup adopt, optional explicit restore, unavailable status, reconnect/backoff and orderly shutdown. Tests: startup emits no writes by default; reconnect resnapshots; restore conflict order is deterministic; disconnect expires in-flight state; cancellation joins workers and flushes state.
- [x] **M3.1 Reducer/effects:** one owner, command origins/revisions, desired/pending/observed state. Tests: accepted intent is recorded before adapter dispatch; success requires readback/observation; failure leaves actual state truthful; external changes update views without an outgoing audio command.
- [x] **M3.2 Worker contract:** capabilities, snapshot barriers, readback, per-property ordered writes, operation results and fake backend. Tests: changes during snapshot are reconciled, old epoch/incarnation events are ignored, stream removal during write is handled, and newer pending intent survives an older completion.
- [x] **M3.3 Load and ordering:** bounded channels, latest-volume coalescing, preserved mute ordering, overflow fault reporting. Tests: burst ends at latest value, toggles are not silently lost or guessed, memory stays bounded, and final readback resolves ambiguous acknowledgments.
- [x] **M3.4 Lifecycle:** startup adopt, optional explicit restore, unavailable status, reconnect/backoff and orderly shutdown. Tests: startup emits no writes by default; reconnect resnapshots; restore conflict order is deterministic; disconnect expires in-flight state; cancellation joins workers and flushes state.
Exit: simulated MIDI input changes a virtual object through a fake adapter; observation generates a confirmed snapshot and feedback effect.
M3 verification on 2026-10-14: the pure reducer records desired and pending
state before dispatch and publishes only adapter observations as confirmation.
The fake adapter implements capability reporting, snapshot barriers, readback,
failure/removal behavior, and stale epoch/incarnation rejection. Its bounded
dispatch lane coalesces only volume motion and reports mute-edge overflow.
The in-process lifecycle slice covers adopt/restore policy, bounded retry,
disconnect invalidation, final draining/checkpointing, and simulated MIDI
volume intent converging through fake write acceptance and readback.
## M4 — PulseAudio adapter and real audio slice
Dependencies: M3.