feat(M2.3): checkpoint durable profile state
Rust CI fader_master failed CI.
MadGobblins/fader_master/pipeline/head There was a failure building this commit Details

Add a pure monotonic checkpoint coordinator with quiet-period debounce, bounded dirty latency, atomic state sinks, and shutdown flushing. Keep observations stale across restart, persist desired intent separately from assignments and UI preferences, and require explicit bounded restore before application-join writes.

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 01:43:54 +02:00
parent 7bb15ec039
commit 81241452fb
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
8 changed files with 621 additions and 22 deletions

View File

@ -1,10 +1,9 @@
# fader_master architecture
Status: design researched 2026-10-05; foundation, M1 domain contracts, and
M2.1–M2.2 schemas and safe file persistence are implemented. The executable
remains a Hello World scaffold and the TUI remains a basic Ratatui example.
Checkpoint scheduling, runtime workers, and native adapters below are planned,
not shipped.
Status: design researched 2026-10-05; foundation, M1 domain contracts, and the
M2 TOML/persistence milestone are implemented. The executable remains a Hello
World scaffold and the TUI remains a basic Ratatui example. Runtime workers and
native adapters below are planned, not shipped.
## Implemented boundary at M2 entry
@ -19,9 +18,12 @@ and feedback/output capabilities before returning a document. It serializes a
canonical semantic round trip. XDG resolution, private directory/file modes,
owner/symlink checks, same-directory atomic replacement with file and directory
sync, recoverable state loads, comment-preserving application-label edits, and
forward-migration backups are implemented. Checkpoint scheduling remains M2.3
work. MIDI/audio crates are adapter boundaries without native handles or
transport behavior yet.
forward-migration backups are implemented. A pure monotonic checkpoint
coordinator owns the 500 ms debounce, two-second maximum dirty interval, and
shutdown flush. Restart views force cached observations stale and retain desired
intent separately; adopt produces no audio write, while restore checks the
profile write ceiling before yielding application-join intent. MIDI/audio crates
are adapter boundaries without native handles or transport behavior yet.
Stable IDs contain 1–64 ASCII bytes, start with an alphanumeric character, and
otherwise allow alphanumerics, `_`, and `-`. Selector patterns contain 1–256
@ -253,8 +255,11 @@ directories are mode `0700`. Missing state and malformed readable state are
distinct recoverable load outcomes; malformed bytes are retained for diagnosis.
Profile migration accepts only versions below the current schema, validates the
replacement first, and durably backs up the original bytes before replacement.
M2.3 will add debouncing and shutdown coordination; revision conflict handling
belongs to the server/editor boundary in M9.3.
Checkpoint changes are written after 500 ms without another change and at least
every two seconds during sustained input, then flushed once more on orderly
shutdown. A process or machine crash can therefore lose up to the latest
unflushed interval; atomic replacement protects the preceding checkpoint.
Revision conflict handling belongs to the server/editor boundary in M9.3.
Profile switch: parse/validate candidate, prepare/probe required resources without writes, pause input briefly, drain old writes with a deadline, obtain fresh state, then commit a new config generation and publish bindings/feedback together. Abort on prepare failure and retain the old profile. If an old in-flight call cannot be safely drained, close/reconnect and reconcile before activation; generation tags alone do not cancel native writes. In-flight group membership is fixed at command acceptance. Re-arm pickup, invalidate stale queued commands, and adopt live volumes by default. Persist the active profile pointer only after successful activation; disk failure leaves the active runtime profile clearly marked unsaved. Durable crash-atomic multi-file transactions are not claimed.

124
config/src/checkpoint.rs Normal file
View File

@ -0,0 +1,124 @@
use std::{
path::PathBuf,
time::{Duration, Instant},
};
use crate::{AtomicFile, PersistedState, PersistenceError};
const DEBOUNCE: Duration = Duration::from_millis(500);
const MAX_DIRTY_AGE: Duration = Duration::from_secs(2);
/// Monotonic time source used by checkpoint scheduling.
pub trait Clock {
/// Elapsed monotonic time in an arbitrary clock-local epoch.
fn now(&self) -> Duration;
}
/// Production monotonic clock.
pub struct SystemClock {
origin: Instant,
}
impl Default for SystemClock {
fn default() -> Self {
Self {
origin: Instant::now(),
}
}
}
impl Clock for SystemClock {
fn now(&self) -> Duration {
self.origin.elapsed()
}
}
/// Destination for validated checkpoint snapshots.
pub trait CheckpointSink {
/// Durably writes one complete snapshot.
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError>;
}
/// Atomic state-file checkpoint destination.
pub struct StateFileSink {
path: PathBuf,
}
impl StateFileSink {
/// Creates a sink for an already initialized private state directory.
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into() }
}
}
impl CheckpointSink for StateFileSink {
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError> {
let document = state
.to_toml()
.map_err(|error| PersistenceError::serialization(&self.path, error.to_string()))?;
AtomicFile::write(&self.path, document.as_bytes())
}
}
/// Pure debounce/max-latency coordinator retaining the newest complete state.
pub struct CheckpointCoordinator<C, S> {
clock: C,
sink: S,
pending: Option<PersistedState>,
dirty_since: Option<Duration>,
last_change: Option<Duration>,
}
impl<C: Clock, S: CheckpointSink> CheckpointCoordinator<C, S> {
/// Starts clean with the documented 500ms debounce and 2s maximum delay.
pub fn new(clock: C, sink: S) -> Self {
Self {
clock,
sink,
pending: None,
dirty_since: None,
last_change: None,
}
}
/// Replaces any pending snapshot with the newest validated state.
pub fn mark_dirty(&mut self, state: PersistedState) {
let now = self.clock.now();
self.dirty_since.get_or_insert(now);
self.last_change = Some(now);
self.pending = Some(state);
}
/// Flushes after a quiet debounce or once continuous changes reach 2s.
pub fn poll(&mut self) -> Result<bool, PersistenceError> {
let now = self.clock.now();
let due = self
.last_change
.is_some_and(|last| now.saturating_sub(last) >= DEBOUNCE)
|| self
.dirty_since
.is_some_and(|first| now.saturating_sub(first) >= MAX_DIRTY_AGE);
if due { self.flush() } else { Ok(false) }
}
/// Flushes the final dirty snapshot during orderly shutdown.
pub fn shutdown(&mut self) -> Result<bool, PersistenceError> {
self.flush()
}
/// Exposes the sink for diagnostics and deterministic tests.
pub const fn sink(&self) -> &S {
&self.sink
}
fn flush(&mut self) -> Result<bool, PersistenceError> {
let Some(state) = self.pending.as_ref() else {
return Ok(false);
};
self.sink.write(state)?;
self.pending = None;
self.dirty_since = None;
self.last_change = None;
Ok(true)
}
}

View File

@ -47,6 +47,14 @@ impl PersistenceError {
source,
}
}
pub(crate) fn serialization(path: &Path, message: String) -> Self {
Self::io(
"serialize checkpoint",
path,
io::Error::new(io::ErrorKind::InvalidData, message),
)
}
}
/// Result of reading cache-like state; malformed data can be ignored by startup.

View File

@ -7,6 +7,7 @@
#![forbid(unsafe_code)]
mod checkpoint;
mod device;
mod document;
mod error;
@ -15,6 +16,7 @@ mod paths;
mod profile;
mod state;
pub use checkpoint::{CheckpointCoordinator, CheckpointSink, Clock, StateFileSink, SystemClock};
pub use device::{DeviceCapabilities, DeviceProfile};
pub use document::ProfileDocument;
pub use error::ConfigError;
@ -24,6 +26,8 @@ pub use profile::{
Adapter, Application, Audio, Binding, Fader, Group, NewStreamPolicy, Profile, StartupPolicy,
Surface,
};
pub use state::{PersistedState, ProfileState};
pub use state::{
CachedObservation, DesiredWrite, PersistedState, ProfileState, StartupState, UiView,
};
pub(crate) const SCHEMA_VERSION: u16 = 1;

View File

@ -258,6 +258,11 @@ impl Profile {
pub fn bindings(&self) -> &[Binding] {
&self.raw.bindings
}
/// Maximum configured gain for outbound writes and restored intents.
pub fn max_gain(&self) -> f64 {
self.raw.audio.max_gain
}
}
fn validate_version(version: u16) -> Result<(), ConfigError> {

View File

@ -32,12 +32,26 @@ struct Assignment {
output_port: Option<String>,
}
/// Last selected TUI view for a profile.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UiView {
/// Mixer overview.
Mixer,
/// MIDI surface assignment and status.
Devices,
/// Runtime diagnostics.
Status,
/// Configuration editor.
Editor,
}
/// Durable state for one stable profile; observed values are cache-only.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileState {
id: String,
last_view: String,
last_view: UiView,
#[serde(default)]
observed: Vec<ObservedObject>,
#[serde(default)]
@ -86,6 +100,267 @@ impl PersistedState {
pub fn profiles(&self) -> &[ProfileState] {
&self.raw.profiles
}
/// Records the latest durable object intent independently of observations.
pub fn set_desired(
&mut self,
profile_id: &str,
object_id: &str,
gain: Option<f64>,
muted: Option<bool>,
) -> Result<(), ConfigError> {
parse_id::<ApplicationId>(object_id, "desired.object")?;
if gain.is_none() && muted.is_none() {
return Err(ConfigError::validation(
"desired",
"at least one desired gain or mute value is required",
));
}
if let Some(value) = gain {
Gain::new(value)
.map_err(|error| ConfigError::validation("desired.gain", error.to_string()))?;
}
let profile = self
.raw
.profiles
.iter_mut()
.find(|profile| profile.id == profile_id)
.ok_or_else(|| {
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
})?;
if let Some(desired) = profile
.desired
.iter_mut()
.find(|desired| desired.object == object_id)
{
desired.gain = gain;
desired.muted = muted;
} else {
profile.desired.push(DesiredObject {
object: object_id.to_owned(),
gain,
muted,
});
}
Ok(())
}
/// Records a confirmed per-channel observation without a runtime handle.
pub fn set_observed(
&mut self,
profile_id: &str,
object_id: &str,
channels: &[f64],
muted: bool,
) -> Result<(), ConfigError> {
parse_id::<ApplicationId>(object_id, "observed.object")?;
let gains = channels
.iter()
.copied()
.map(Gain::new)
.collect::<Result<Vec<_>, _>>()
.map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?;
let validated = ChannelGains::new(gains)
.map_err(|error| ConfigError::validation("observed.gain", error.to_string()))?;
let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?;
let gain = validated.as_slice().iter().map(|gain| gain.get()).collect();
if let Some(observed) = profile
.observed
.iter_mut()
.find(|observed| observed.object == object_id)
{
observed.gain = gain;
observed.muted = muted;
} else {
profile.observed.push(ObservedObject {
object: object_id.to_owned(),
gain,
muted,
});
}
Ok(())
}
/// Remembers stable surface-to-port assignment hints for one profile.
pub fn set_surface_assignment(
&mut self,
profile_id: &str,
surface_id: &str,
input_port: &str,
output_port: Option<&str>,
) -> Result<(), ConfigError> {
parse_id::<SurfaceId>(surface_id, "assignment.surface")?;
if input_port.is_empty() || output_port.is_some_and(str::is_empty) {
return Err(ConfigError::validation(
"assignment.port",
"configured port names must not be empty",
));
}
let profile = find_profile_mut(&mut self.raw.profiles, profile_id)?;
let output_port = output_port.map(str::to_owned);
if let Some(assignment) = profile
.assignments
.iter_mut()
.find(|assignment| assignment.surface == surface_id)
{
assignment.input_port = input_port.to_owned();
assignment.output_port = output_port;
} else {
profile.assignments.push(Assignment {
surface: surface_id.to_owned(),
input_port: input_port.to_owned(),
output_port,
});
}
Ok(())
}
/// Updates the remembered UI view for one profile.
pub fn set_last_view(&mut self, profile_id: &str, view: UiView) -> Result<(), ConfigError> {
find_profile_mut(&mut self.raw.profiles, profile_id)?.last_view = view;
Ok(())
}
/// Creates restart state whose observations are always explicitly stale.
pub fn startup(
&self,
profile_id: &str,
policy: crate::StartupPolicy,
write_ceiling: f64,
) -> Result<StartupState, ConfigError> {
let write_ceiling = Gain::new(write_ceiling)
.map_err(|error| ConfigError::validation("write_ceiling", error.to_string()))?;
let profile = self
.raw
.profiles
.iter()
.find(|profile| profile.id == profile_id)
.ok_or_else(|| {
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
})?;
let cached_observations = profile
.observed
.iter()
.map(|observation| CachedObservation {
object: observation.object.clone(),
gain: observation.gain.clone(),
muted: observation.muted,
stale: true,
})
.collect();
let desired = profile
.desired
.iter()
.enumerate()
.map(|(index, intent)| {
if intent.gain.is_some_and(|gain| gain > write_ceiling.get()) {
return Err(ConfigError::validation(
format!("profiles.desired[{index}].gain"),
format!("exceeds write ceiling {}", write_ceiling.get()),
));
}
Ok(DesiredWrite {
object: intent.object.clone(),
gain: intent.gain,
muted: intent.muted,
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok(StartupState {
policy,
cached_observations,
desired,
})
}
}
/// A restart-only observation that cannot be mistaken for current backend data.
#[derive(Clone, Debug, PartialEq)]
pub struct CachedObservation {
object: String,
gain: Vec<f64>,
muted: bool,
stale: bool,
}
impl CachedObservation {
/// Stable virtual object identifier.
pub fn object(&self) -> &str {
&self.object
}
/// Cached per-channel gains retained for display only.
pub fn gain(&self) -> &[f64] {
&self.gain
}
/// Cached mute observation.
pub const fn muted(&self) -> bool {
self.muted
}
/// Cached observations are always stale until live discovery replaces them.
pub const fn is_stale(&self) -> bool {
self.stale
}
}
/// A validated desired object write, with absent properties left unchanged.
#[derive(Clone, Debug, PartialEq)]
pub struct DesiredWrite {
object: String,
gain: Option<f64>,
muted: Option<bool>,
}
impl DesiredWrite {
/// Stable virtual object identifier.
pub fn object(&self) -> &str {
&self.object
}
/// Desired scalar gain, when one was saved.
pub const fn gain(&self) -> Option<f64> {
self.gain
}
/// Desired mute state, when one was saved.
pub const fn muted(&self) -> Option<bool> {
self.muted
}
}
/// Validated restart data with an explicit adopt/restore policy.
#[derive(Clone, Debug, PartialEq)]
pub struct StartupState {
policy: crate::StartupPolicy,
cached_observations: Vec<CachedObservation>,
desired: Vec<DesiredWrite>,
}
impl StartupState {
/// Observations retained for display but never treated as fresh.
pub fn cached_observations(&self) -> &[CachedObservation] {
&self.cached_observations
}
/// Saved intents remain visible even when startup adopts live state.
pub fn desired_intents(&self) -> &[DesiredWrite] {
&self.desired
}
/// Returns the explicit write for a newly discovered application only when
/// the profile selected restore policy.
pub fn application_joined(&self, application_id: &str) -> Vec<DesiredWrite> {
if self.policy != crate::StartupPolicy::Restore {
return Vec::new();
}
self.desired
.iter()
.filter(|intent| intent.object == application_id)
.cloned()
.collect()
}
}
fn validate_profiles(profiles: &[ProfileState]) -> Result<(), ConfigError> {
@ -98,15 +373,6 @@ fn validate_profiles(profiles: &[ProfileState]) -> Result<(), ConfigError> {
"duplicate profile state",
));
}
if !matches!(
profile.last_view.as_str(),
"mixer" | "devices" | "status" | "editor"
) {
return Err(ConfigError::validation(
format!("profiles[{profile_index}].last_view"),
"must be mixer, devices, status, or editor",
));
}
validate_observed(profile_index, &profile.observed)?;
validate_desired(profile_index, &profile.desired)?;
validate_assignments(profile_index, &profile.assignments)?;
@ -181,6 +447,24 @@ fn validate_assignments(profile: usize, assignments: &[Assignment]) -> Result<()
"must not be empty",
));
}
if assignment.output_port.as_deref().is_some_and(str::is_empty) {
return Err(ConfigError::validation(
format!("{base}.output_port"),
"must not be empty when present",
));
}
}
Ok(())
}
fn find_profile_mut<'a>(
profiles: &'a mut [ProfileState],
profile_id: &str,
) -> Result<&'a mut ProfileState, ConfigError> {
profiles
.iter_mut()
.find(|profile| profile.id == profile_id)
.ok_or_else(|| {
ConfigError::validation("profile", format!("unknown profile {profile_id:?}"))
})
}

157
config/tests/checkpoints.rs Normal file
View File

@ -0,0 +1,157 @@
use std::{cell::Cell, rc::Rc, time::Duration};
use fader_config::{
CheckpointCoordinator, CheckpointSink, Clock, PersistedState, PersistenceError, StartupPolicy,
UiView,
};
#[test]
fn sustained_movement_has_bounded_writes_and_shutdown_persists_the_final_value() {
let clock = FakeClock::default();
let sink = RecordingSink::default();
let mut checkpoints = CheckpointCoordinator::new(clock.clone(), sink);
let mut state = state_with_observation();
for step in 0..50 {
state
.set_desired("desktop", "music", Some(f64::from(step) / 50.0), None)
.unwrap();
checkpoints.mark_dirty(state.clone());
checkpoints.poll().unwrap();
clock.advance(Duration::from_millis(100));
}
assert_eq!(
checkpoints.sink().documents.len(),
2,
"2s maximum bounds writes"
);
checkpoints.shutdown().unwrap();
assert_eq!(checkpoints.sink().documents.len(), 3);
let final_state = PersistedState::parse(checkpoints.sink().documents.last().unwrap()).unwrap();
let startup = final_state
.startup("desktop", StartupPolicy::Restore, 1.0)
.unwrap();
let writes = startup.application_joined("music");
assert_eq!(writes.len(), 1);
assert_eq!(writes[0].gain(), Some(0.98));
}
#[test]
fn a_quiet_period_flushes_after_debounce_not_before() {
let clock = FakeClock::default();
let mut checkpoints = CheckpointCoordinator::new(clock.clone(), RecordingSink::default());
checkpoints.mark_dirty(state_with_observation());
clock.advance(Duration::from_millis(499));
checkpoints.poll().unwrap();
assert!(checkpoints.sink().documents.is_empty());
clock.advance(Duration::from_millis(1));
checkpoints.poll().unwrap();
assert_eq!(checkpoints.sink().documents.len(), 1);
}
#[test]
fn restart_marks_cached_observations_stale_and_has_no_ephemeral_state() {
let state = state_with_observation();
let encoded = state.to_toml().unwrap();
assert!(!encoded.contains("backend_id"));
assert!(!encoded.contains("pending"));
assert!(!encoded.contains("operation"));
let restarted = PersistedState::parse(&encoded).unwrap();
let startup = restarted
.startup("desktop", StartupPolicy::Adopt, 1.0)
.unwrap();
assert_eq!(startup.cached_observations().len(), 1);
assert!(startup.cached_observations()[0].is_stale());
}
#[test]
fn offline_intent_survives_but_only_explicit_restore_emits_a_join_write() {
let mut state = state_with_observation();
state
.set_desired("desktop", "music", Some(0.7), Some(true))
.unwrap();
let restarted = PersistedState::parse(&state.to_toml().unwrap()).unwrap();
let adopt = restarted
.startup("desktop", StartupPolicy::Adopt, 1.0)
.unwrap();
assert!(adopt.application_joined("music").is_empty());
assert_eq!(adopt.desired_intents().len(), 1, "intent remains visible");
let restore = restarted
.startup("desktop", StartupPolicy::Restore, 1.0)
.unwrap();
let writes = restore.application_joined("music");
assert_eq!(writes.len(), 1);
assert_eq!(writes[0].gain(), Some(0.7));
assert_eq!(writes[0].muted(), Some(true));
}
#[test]
fn checkpoint_mutations_validate_observations_assignments_views_and_restore_bounds() {
let mut state = state_with_observation();
state
.set_observed("desktop", "music", &[0.8, 0.4], true)
.unwrap();
state
.set_surface_assignment("desktop", "desk-left", "input:1", Some("output:1"))
.unwrap();
state.set_last_view("desktop", UiView::Devices).unwrap();
state
.set_desired("desktop", "music", Some(1.5), None)
.unwrap();
let encoded = state.to_toml().unwrap();
assert!(encoded.contains("last_view = \"devices\""));
assert!(encoded.contains("surface = \"desk-left\""));
let error = state
.startup("desktop", StartupPolicy::Restore, 1.0)
.expect_err("restore must enforce the profile write ceiling");
assert!(error.to_string().contains("write ceiling"));
}
fn state_with_observation() -> PersistedState {
PersistedState::parse(
r#"
schema_version = 1
[[profiles]]
id = "desktop"
last_view = "mixer"
[[profiles.observed]]
object = "music"
gain = [0.5, 0.25]
muted = false
"#,
)
.unwrap()
}
#[derive(Clone, Default)]
struct FakeClock(Rc<Cell<Duration>>);
impl FakeClock {
fn advance(&self, duration: Duration) {
self.0.set(self.0.get() + duration);
}
}
impl Clock for FakeClock {
fn now(&self) -> Duration {
self.0.get()
}
}
#[derive(Default)]
struct RecordingSink {
documents: Vec<String>,
}
impl CheckpointSink for RecordingSink {
fn write(&mut self, state: &PersistedState) -> Result<(), PersistenceError> {
self.documents.push(state.to_toml().expect("valid state"));
Ok(())
}
}

14
task.md
View File

@ -58,7 +58,19 @@ Dependencies: M1 types; runtime activation follows in M10.
streaming atomic writes, directory sync, recoverable state loading,
comment-preserving validated edits, and backed-up forward migration are
covered by seven persistence integration tests.
- [ ] **M2.3 Checkpoints:** per-profile observed state and separate validated desired object volume/mute, surface assignments, UI preferences, debounce and shutdown flush. Tests with a fake clock: sustained movement causes bounded writes and final state persists; crash/restart treats cached observations as stale, never restores runtime IDs or pending requests; an offline command survives restart as saved intent but only explicit restore applies it when the application launches (adopt emits no write).
- [x] **M2.3 Checkpoints:** per-profile observed state and separate validated desired object volume/mute, surface assignments, UI preferences, debounce and shutdown flush. Tests with a fake clock: sustained movement causes bounded writes and final state persists; crash/restart treats cached observations as stale, never restores runtime IDs or pending requests; an offline command survives restart as saved intent but only explicit restore applies it when the application launches (adopt emits no write).
A runtime-independent monotonic coordinator now keeps only the newest complete
snapshot, flushes after 500 ms quiet or two seconds continuously dirty, retries
failed writes without discarding pending state, and flushes on shutdown. Five
fake-clock tests cover timing, final persistence, typed checkpoint mutations,
stale restart observations, absent ephemeral state, and bounded explicit
restore behavior.
M2 verification on 2026-10-14: 17 configuration integration tests pass alongside
the existing 30 core tests and compile-fail doctest. Locked formatting,
all-target/all-feature checks and tests, doctests, strict Clippy, release build,
and no-default-feature checks/tests pass on Rust 1.88.0. M0.2 still requires a
real Jenkins run.
## M3 — Server and fake-adapter vertical slice