feat(M7.4): make runtime polling configurable

Add validated profile runtime.poll_interval_ms settings with a 10 ms default and 1..=100 ms range. Apply the interval to both the server state-owner wait and Pulse notification/command loop, expose it in startup output, and document it in shipped profiles.

Tests: full workspace fmt/check/test/doc/clippy/release gates; default/no-default backend matrix; profile validation and Pulse owner-loop interval regression tests.
This commit is contained in:
Dandaedre 2026-10-15 03:54:10 +02:00
parent 3a75e24003
commit c812af52ee
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
9 changed files with 206 additions and 13 deletions

View File

@ -233,6 +233,9 @@ id = "desktop"
startup = "adopt"
new_stream = "adopt"
[runtime]
poll_interval_ms = 10
[audio]
adapter = "auto"
preference = ["pulse", "pipewire"]
@ -283,6 +286,14 @@ message = { kind = "note", channel = 1, number = 32 }
feedback = { kind = "note", channel = 1, number = 32, on = 127, off = 0 }
```
`runtime.poll_interval_ms` controls how long both the server state owner and the
native audio worker may wait between MIDI/IPC/command/notification polls. It
defaults to 10 ms when omitted and is validated within `1..=100`. Lower values
can reduce worst-case control latency at the cost of more wake-ups; higher
values reduce wake-ups but make physical control and external-state updates less
responsive. It does not change the bounded coalescing policy or cause every
intermediate fader sample to be written.
Reject unknown schema versions/fields, duplicate IDs/physical bindings, dangling references, invalid matchers/ranges, unsupported capability requirements, and unsafe profile paths. Use forward migrations with backups; never downgrade silently. Validate the whole candidate before changing live mappings or files.
Write same-directory temporary files, flush/fsync, rename atomically, then sync the directory. Debounce state writes (initial target: 500 ms after changes, maximum 2 s between dirty checkpoints), flush on orderly shutdown, and document the corresponding crash-loss window. Permission/disk-full errors leave the old file usable and show an unsaved state. Preserve user comments in profile edits with `toml_edit`. The server is the sole writer; TUI edits carry a base revision and conflict if stale. Detect out-of-process file edits before saving rather than overwriting them.

View File

@ -1,4 +1,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::{
collections::{BTreeMap, BTreeSet},
time::Duration,
};
use fader_core::{
ApplicationId, ApplicationMatcher, ApplicationSelector, FaderId, GroupId, MetadataField,
@ -8,6 +11,29 @@ use serde::{Deserialize, Serialize};
use crate::{ConfigError, SCHEMA_VERSION};
const DEFAULT_POLL_INTERVAL_MS: u64 = 10;
const MIN_POLL_INTERVAL_MS: u64 = 1;
const MAX_POLL_INTERVAL_MS: u64 = 100;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct RuntimeSettings {
#[serde(default = "default_poll_interval_ms")]
poll_interval_ms: u64,
}
impl Default for RuntimeSettings {
fn default() -> Self {
Self {
poll_interval_ms: DEFAULT_POLL_INTERVAL_MS,
}
}
}
const fn default_poll_interval_ms() -> u64 {
DEFAULT_POLL_INTERVAL_MS
}
/// Behavior when a profile becomes active.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
@ -209,6 +235,8 @@ struct RawProfile {
id: String,
startup: StartupPolicy,
new_stream: NewStreamPolicy,
#[serde(default)]
runtime: RuntimeSettings,
audio: Audio,
#[serde(default)]
applications: Vec<Application>,
@ -235,6 +263,7 @@ impl Profile {
let raw: RawProfile = toml::from_str(input)?;
validate_version(raw.schema_version)?;
let id = parse_id::<ProfileId>(&raw.id, "profile.id")?;
validate_runtime(&raw.runtime)?;
validate_audio(&raw.audio)?;
validate_profile_members(&raw)?;
Ok(Self { raw, id })
@ -288,6 +317,13 @@ impl Profile {
pub fn max_gain(&self) -> f64 {
self.raw.audio.max_gain
}
/// Interval used by the server and native audio worker while waiting for
/// MIDI, IPC, adapter commands, and subscription notifications.
#[must_use]
pub const fn poll_interval(&self) -> Duration {
Duration::from_millis(self.raw.runtime.poll_interval_ms)
}
}
impl Audio {
@ -498,6 +534,17 @@ fn validate_version(version: u16) -> Result<(), ConfigError> {
}
}
fn validate_runtime(runtime: &RuntimeSettings) -> Result<(), ConfigError> {
if (MIN_POLL_INTERVAL_MS..=MAX_POLL_INTERVAL_MS).contains(&runtime.poll_interval_ms) {
Ok(())
} else {
Err(ConfigError::validation(
"runtime.poll_interval_ms",
format!("must be within {MIN_POLL_INTERVAL_MS}..={MAX_POLL_INTERVAL_MS}"),
))
}
}
fn validate_audio(audio: &Audio) -> Result<(), ConfigError> {
if !audio.max_gain.is_finite() || audio.max_gain < 0.0 {
return Err(ConfigError::validation(

View File

@ -1,5 +1,6 @@
use fader_config::{DeviceProfile, PersistedState, Profile, StartupPolicy};
use fader_core::{StreamMetadata, VolumeMode};
use std::time::Duration;
const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml");
const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml");
@ -48,6 +49,31 @@ fn validated_profile_exposes_compiled_runtime_application_and_group_views() {
assert_eq!(media.volume_mode(), VolumeMode::Absolute);
}
#[test]
fn runtime_poll_interval_defaults_and_validates_safe_overrides() {
let without_runtime = EXAMPLE.replace("[runtime]\npoll_interval_ms = 10\n\n", "");
let default = Profile::parse(&without_runtime).expect("omitted runtime settings must validate");
assert_eq!(default.poll_interval(), Duration::from_millis(10));
let configured = EXAMPLE.replace("poll_interval_ms = 10", "poll_interval_ms = 4");
let configured = Profile::parse(&configured).expect("poll override must validate");
assert_eq!(configured.poll_interval(), Duration::from_millis(4));
assert_eq!(
Profile::parse(&configured.to_toml().unwrap())
.unwrap()
.poll_interval(),
Duration::from_millis(4)
);
for value in [0, 101] {
let invalid = EXAMPLE.replace(
"poll_interval_ms = 10",
&format!("poll_interval_ms = {value}"),
);
assert_error_contains(Profile::parse(&invalid), "runtime.poll_interval_ms");
}
}
#[test]
fn arch_pipewire_profile_matches_reported_qobuz_metadata() {
let profile = Profile::parse(ARCH_PIPEWIRE).expect("Arch profile must validate");

View File

@ -3,6 +3,9 @@ id = "arch-pipewire"
startup = "adopt"
new_stream = "adopt"
[runtime]
poll_interval_ms = 10
[audio]
adapter = "pulse"
max_gain = 1.0

View File

@ -3,6 +3,9 @@ id = "desktop"
startup = "adopt"
new_stream = "adopt"
[runtime]
poll_interval_ms = 10
[audio]
adapter = "auto"
preference = ["pulse", "pipewire"]

View File

@ -23,7 +23,6 @@ use crate::{
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
const SERVER_CLIENT_TIMEOUT: Duration = Duration::from_millis(20);
const SERVER_TICK: Duration = Duration::from_millis(10);
#[derive(Debug, Error)]
pub enum LocalError {
@ -176,6 +175,7 @@ pub struct LocalServer {
midi: crate::midi_runtime::MidiRuntime,
midi_sequence: u64,
dispatch: AdapterQueue,
poll_interval: Duration,
}
impl LocalServer {
@ -190,11 +190,17 @@ impl LocalServer {
listener: OwnedListener::bind(socket)?,
// One waiting native command keeps round-trip backpressure at the
// state-owner boundary, where unsent volume motion can coalesce.
worker: PulseWorker::spawn_with_capacities(BackendEpoch::new(1), 1, 256),
worker: PulseWorker::spawn_with_capacities_and_poll_interval(
BackendEpoch::new(1),
1,
256,
profile.poll_interval(),
),
mixer: LiveMixerState::new(write_ceiling, "pulse", profile)?,
midi,
midi_sequence: 1,
dispatch: AdapterQueue::new(256),
poll_interval: profile.poll_interval(),
})
}
@ -217,7 +223,7 @@ impl LocalServer {
}
self.mixer.set_devices(self.midi.snapshot());
self.flush_dispatch();
match self.worker.receive_timeout(SERVER_TICK) {
match self.worker.receive_timeout(self.poll_interval) {
Ok(event) => {
let commands = self.mixer.worker_event(event)?;
self.enqueue(commands)?;

View File

@ -76,9 +76,10 @@ fn serve(
}
};
println!(
"serving profile={} backend={} socket={}",
"serving profile={} backend={} poll={}ms socket={}",
profile.id(),
selected.backend,
profile.poll_interval().as_millis(),
socket.display()
);
LocalServer::pulse(socket, Gain::new(profile.max_gain())?, &profile)?.run()?;

View File

@ -307,9 +307,30 @@ impl PulseWorker {
command_capacity: usize,
event_capacity: usize,
) -> Self {
Self::spawn_connected_with_capacities(epoch, command_capacity, event_capacity, || {
PulseClient::connect()
})
Self::spawn_with_capacities_and_poll_interval(
epoch,
command_capacity,
event_capacity,
NOTIFICATION_POLL,
)
}
/// Starts a worker with independent lane capacities and a configured wait
/// between native command/notification polls.
#[must_use]
pub fn spawn_with_capacities_and_poll_interval(
epoch: BackendEpoch,
command_capacity: usize,
event_capacity: usize,
poll_interval: Duration,
) -> Self {
Self::spawn_connected_with_capacities_and_poll_interval(
epoch,
command_capacity,
event_capacity,
poll_interval,
PulseClient::connect,
)
}
/// Starts a worker against an explicit server, primarily for isolated fixtures.
@ -325,15 +346,42 @@ impl PulseWorker {
C: PulseConnection,
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
{
Self::spawn_connected_with_capacities(epoch, capacity, capacity, connect)
Self::spawn_connected_with_capacities_and_poll_interval(
epoch,
capacity,
capacity,
NOTIFICATION_POLL,
connect,
)
}
#[cfg(test)]
fn spawn_connected_with_capacities<C, F>(
epoch: BackendEpoch,
command_capacity: usize,
event_capacity: usize,
connect: F,
) -> Self
where
C: PulseConnection,
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
{
Self::spawn_connected_with_capacities_and_poll_interval(
epoch,
command_capacity,
event_capacity,
NOTIFICATION_POLL,
connect,
)
}
fn spawn_connected_with_capacities_and_poll_interval<C, F>(
epoch: BackendEpoch,
command_capacity: usize,
event_capacity: usize,
poll_interval: Duration,
connect: F,
) -> Self
where
C: PulseConnection,
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
@ -357,7 +405,13 @@ impl PulseWorker {
return;
}
};
if let Err(error) = run_connection(&mut connection, epoch, &command_receiver, &events) {
if let Err(error) = run_connection(
&mut connection,
epoch,
&command_receiver,
poll_interval,
&events,
) {
events.emit(WorkerEvent::Disconnected {
epoch,
message: error.to_string(),
@ -418,6 +472,7 @@ fn run_connection<C: PulseConnection>(
connection: &mut C,
epoch: BackendEpoch,
commands: &Receiver<AdapterCommand>,
notification_poll: Duration,
events: &EventLane,
) -> Result<(), PulseError> {
connection.subscribe()?;
@ -486,7 +541,7 @@ fn run_connection<C: PulseConnection>(
Err(TryRecvError::Disconnected) => return Ok(()),
Err(TryRecvError::Empty) => {}
}
if let Some(notification) = connection.poll_notification(NOTIFICATION_POLL)?
if let Some(notification) = connection.poll_notification(notification_poll)?
&& !process_notification(
notification,
&mut tracker,
@ -716,6 +771,7 @@ mod tests {
streams: Arc<Mutex<BTreeMap<u32, PulseStream>>>,
output: Arc<Mutex<Option<PulseOutput>>>,
reject_writes: Arc<AtomicBool>,
last_poll_timeout: Arc<Mutex<Option<Duration>>>,
}
impl FakeControl {
@ -768,6 +824,7 @@ mod tests {
streams: Arc::new(Mutex::new(streams)),
output: Arc::new(Mutex::new(None)),
reject_writes: Arc::new(AtomicBool::new(false)),
last_poll_timeout: Arc::new(Mutex::new(None)),
};
let owner_thread = Arc::new(Mutex::new(None));
(
@ -827,8 +884,13 @@ mod tests {
fn poll_notification(
&mut self,
_timeout: Duration,
timeout: Duration,
) -> Result<Option<PulseNotification>, PulseError> {
*self
.control
.last_poll_timeout
.lock()
.expect("fake poll timeout lock") = Some(timeout);
Ok(self
.control
.notifications
@ -986,6 +1048,38 @@ mod tests {
assert!(worker.shutdown());
}
#[test]
fn configured_notification_poll_interval_reaches_the_owner_loop() {
let (connection, control, _) = FakeConnection::new(Vec::new());
let expected = Duration::from_millis(3);
let mut worker = PulseWorker::spawn_connected_with_capacities_and_poll_interval(
BackendEpoch::new(4),
4,
32,
expected,
move || Ok(connection),
);
initial_snapshot(&worker);
let deadline = std::time::Instant::now() + Duration::from_secs(1);
loop {
if *control
.last_poll_timeout
.lock()
.expect("fake poll timeout lock")
== Some(expected)
{
break;
}
assert!(
std::time::Instant::now() < deadline,
"worker did not adopt the configured poll interval"
);
std::thread::yield_now();
}
assert!(worker.shutdown());
}
#[test]
fn notifications_cover_external_change_removal_and_backend_id_reuse() {
let (connection, control, _) = FakeConnection::new(Vec::new());

View File

@ -255,7 +255,9 @@ Dependencies: M3, M2; may proceed after the fake-adapter slice.
snapshot lane, and a batch event drain. Matching Pulse subscription echoes
retain the originating operation so confirmed writes do not repeatedly re-arm
pickup during continuous physical fader motion; genuinely different external
observations still re-arm it.
observations still re-arm it. Profiles may tune the shared server/native
polling interval from 1 through 100 ms (`10` by default) without changing
bounded latest-value coalescing.
## M8 — Live TUI