use std::io;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use fluxframe_core::{CONSUMER_EVENT_AGE_UNSET, EXTERNAL_OPENERS_UNSET, OUTPUT_STREAM_UNKNOWN};
use fluxframe_gst::{
ClientUsage, LoopbackState, ProbeFailure, classify_probe_error, probe_client_usage,
read_loopback_state,
};
use tracing::{debug, info, warn};
use super::detector::{
DetectorContext, DetectorState, UsageSource, WalkOutcome, apply_usage,
count_external_consumers, read_comm, shutdown_bounded_timeout_ms,
};
use super::state::ConsumerStatus;
pub(super) trait NodeProbe {
fn client_usage(&self) -> io::Result<ClientUsage>;
fn output_state(&self) -> LoopbackState;
}
pub(super) struct DeviceProbe {
device: PathBuf,
}
impl DeviceProbe {
pub(super) fn new(device: PathBuf) -> Self {
Self { device }
}
}
impl NodeProbe for DeviceProbe {
fn client_usage(&self) -> io::Result<ClientUsage> {
probe_client_usage(&self.device, shutdown_bounded_timeout_ms())
}
fn output_state(&self) -> LoopbackState {
read_loopback_state(&self.device)
}
}
#[derive(Debug, Clone, Copy)]
pub(super) enum ResyncSchedule {
Off,
Every(Duration),
#[cfg(test)]
EveryIterations(u32),
}
impl ResyncSchedule {
pub(super) fn every(interval: Duration) -> Self {
if interval.is_zero() {
Self::Off
} else {
Self::Every(interval)
}
}
fn interval(self) -> Duration {
match self {
Self::Every(d) => d,
Self::Off => Duration::ZERO,
#[cfg(test)]
Self::EveryIterations(_) => Duration::ZERO,
}
}
}
const RESYNC_BACKOFF_MAX: Duration = Duration::from_secs(300);
const RESYNC_BACKOFF_START: Duration = Duration::from_secs(1);
const RESYNC_ABSENT_CONFIRMATIONS: u8 = 2;
const EXTERNAL_CENSUS_INTERVAL: Duration = Duration::from_secs(300);
pub(super) struct ResyncState {
schedule: ResyncSchedule,
last_tick: Instant,
iterations: u32,
disabled: bool,
backoff_until: Option<Instant>,
backoff: Duration,
backoff_base: Duration,
absent_streak: u8,
probe_failing: bool,
output_down: Option<bool>,
external_holder: Option<bool>,
last_census: Option<Instant>,
last_external_event: Option<Instant>,
started_at: Instant,
stale_after: Duration,
stale_warned: bool,
}
impl ResyncState {
pub(super) fn new(schedule: ResyncSchedule, teardown_grace: Duration) -> Self {
let now = Instant::now();
let interval = schedule.interval();
Self {
schedule,
last_tick: now,
iterations: 0,
disabled: false,
backoff_until: None,
backoff: interval,
backoff_base: interval,
absent_streak: 0,
probe_failing: false,
output_down: None,
external_holder: None,
last_census: None,
last_external_event: None,
started_at: now,
stale_after: (interval * 3).max(teardown_grace),
stale_warned: false,
}
}
pub(super) fn announce(&self) {
if matches!(self.schedule, ResyncSchedule::Off) {
warn!(
target: "fluxframe::idle",
"consumer resync disabled by config — a lost kernel event will latch \
the verdict until the daemon restarts"
);
} else {
info!(
target: "fluxframe::idle",
resync_interval_secs = self.schedule.interval().as_secs(),
"consumer resync armed"
);
}
}
pub(super) fn note_external_event(&mut self) {
self.last_external_event = Some(Instant::now());
self.stale_warned = false;
self.absent_streak = 0;
}
pub(super) fn note_iteration(&mut self) {
self.iterations = self.iterations.saturating_add(1);
}
pub(super) fn due(&self) -> bool {
if self.disabled {
return false;
}
if self
.backoff_until
.is_some_and(|until| Instant::now() < until)
{
return false;
}
match self.schedule {
ResyncSchedule::Off => false,
ResyncSchedule::Every(interval) => self.last_tick.elapsed() >= interval,
#[cfg(test)]
ResyncSchedule::EveryIterations(n) => n > 0 && self.iterations % n == 0,
}
}
fn census_due(&self) -> bool {
match self.last_census {
None => true,
Some(_) if self.external_holder.is_none() => true,
Some(at) => at.elapsed() >= EXTERNAL_CENSUS_INTERVAL,
}
}
}
pub(super) fn resync_tick<S: UsageSource, P: NodeProbe>(
source: &mut S,
probe: &P,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
resync: &mut ResyncState,
) {
resync.last_tick = Instant::now();
ctx.counters.inc_consumer_resync();
let believed = *state.last_status;
match probe.client_usage() {
Ok(reading) => {
if resync.probe_failing {
info!(target: "fluxframe::idle", "consumer resync recovered");
resync.probe_failing = false;
}
resync.backoff_until = None;
resync.backoff = resync.backoff_base;
let echo_disagreed = drain_probe_echo(source, reading, ctx, state, resync);
if !echo_disagreed {
reconcile(reading, believed, ctx, state, resync);
}
if !ctx.stopped.load(Ordering::Acquire) {
check_external_holder(reading, ctx, resync);
}
}
Err(e) => on_probe_error(&e, ctx, resync),
}
check_output_stream(probe, ctx, resync);
if resync.disabled {
ctx.counters
.set_consumer_last_external_event_age_secs(CONSUMER_EVENT_AGE_UNSET);
} else {
report_event_silence(ctx, resync);
}
}
fn drain_probe_echo<S: UsageSource>(
source: &mut S,
reading: ClientUsage,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
resync: &mut ResyncState,
) -> bool {
let echo = match source.wait(0) {
Ok(Some(echo)) => echo,
Ok(None) => return false,
Err(e) => {
debug!(
target: "fluxframe::idle",
error = %e,
"echo drain failed; the subscription looks dead"
);
return false;
}
};
if echo == reading {
return false;
}
debug!(
target: "fluxframe::idle",
probed = reading.count,
observed = echo.count,
"client-usage changed while probing — taking the newer reading"
);
resync.note_external_event();
apply_usage(echo, ctx, state);
true
}
fn reconcile(
reading: ClientUsage,
believed: Option<ConsumerStatus>,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
resync: &mut ResyncState,
) {
let observed = if reading.attached() {
ConsumerStatus::Present
} else {
ConsumerStatus::Absent
};
if !matches!(
believed,
Some(ConsumerStatus::Present | ConsumerStatus::Absent)
) {
debug!(
target: "fluxframe::idle",
?believed,
?observed,
"consumer resync — initial synchronisation"
);
apply_usage(reading, ctx, state);
return;
}
if believed == Some(observed) {
debug!(target: "fluxframe::idle", ?observed, "consumer resync — verdict confirmed");
resync.absent_streak = 0;
return;
}
warn!(
target: "fluxframe::idle",
?believed,
?observed,
count = reading.count,
"consumer state drift — the kernel disagrees with the event-driven verdict"
);
if observed == ConsumerStatus::Present {
ctx.counters.inc_consumer_resync_corrections();
resync.absent_streak = 0;
apply_usage(reading, ctx, state);
return;
}
resync.absent_streak = resync.absent_streak.saturating_add(1);
if resync.absent_streak < RESYNC_ABSENT_CONFIRMATIONS {
debug!(
target: "fluxframe::idle",
confirmations = resync.absent_streak,
required = RESYNC_ABSENT_CONFIRMATIONS,
"holding the Present verdict until another re-read agrees"
);
return;
}
ctx.counters.inc_consumer_resync_corrections();
resync.absent_streak = 0;
apply_usage(reading, ctx, state);
}
fn on_probe_error(e: &io::Error, ctx: &DetectorContext<'_>, resync: &mut ResyncState) {
ctx.counters.inc_consumer_resync_failures();
let raw = e.raw_os_error();
match classify_probe_error(e) {
ProbeFailure::Permanent => {
warn!(
target: "fluxframe::idle",
error = %e,
errno = ?raw,
"consumer resync unavailable on this node — disabling it for this run"
);
resync.disabled = true;
ctx.counters
.set_consumer_last_external_event_age_secs(CONSUMER_EVENT_AGE_UNSET);
return;
}
ProbeFailure::Busy => {
let step = if resync.backoff.is_zero() {
RESYNC_BACKOFF_START
} else {
resync.backoff
};
let next = (step * 2).min(RESYNC_BACKOFF_MAX);
resync.backoff = next;
resync.backoff_until = Some(Instant::now() + next);
}
_ => {}
}
if !resync.probe_failing {
resync.probe_failing = true;
warn!(
target: "fluxframe::idle",
error = %e,
errno = ?raw,
backoff_secs = resync.backoff_until.map(|_| resync.backoff.as_secs()),
"consumer resync failed — the verdict is unverified until it recovers"
);
}
}
fn check_output_stream<P: NodeProbe>(
probe: &P,
ctx: &DetectorContext<'_>,
resync: &mut ResyncState,
) {
let (gauge, down) = match probe.output_state() {
LoopbackState::ProducerStreaming => (1, Some(false)),
LoopbackState::ProducerStopped => (0, Some(true)),
other => {
debug!(
target: "fluxframe::idle",
state = ?other,
"loopback OUTPUT state unavailable"
);
(OUTPUT_STREAM_UNKNOWN, None)
}
};
ctx.counters.set_output_stream_up(gauge);
let Some(down) = down else { return };
if resync.output_down == Some(down) {
return;
}
if down {
ctx.counters.inc_output_stream_down();
warn!(
target: "fluxframe::idle",
"loopback OUTPUT stream is not held — every capture client will get EIO \
until the output pipeline is rebuilt"
);
} else if resync.output_down == Some(true) {
info!(target: "fluxframe::idle", "loopback OUTPUT stream is held again");
}
resync.output_down = Some(down);
}
fn check_external_holder(
reading: ClientUsage,
ctx: &DetectorContext<'_>,
resync: &mut ResyncState,
) {
if reading.attached() {
ctx.counters.set_external_openers(EXTERNAL_OPENERS_UNSET);
resync.external_holder = None;
return;
}
if !resync.census_due() {
return;
}
resync.last_census = Some(Instant::now());
match count_external_consumers(ctx.proc_root, ctx.device_basename, ctx.my_pid) {
WalkOutcome::External { pid } => {
ctx.counters.set_external_openers(1);
if resync.external_holder != Some(true) {
let comm = read_comm(ctx.proc_root, pid)
.map(|c| c.escape_default().to_string())
.unwrap_or_default();
warn!(
target: "fluxframe::idle",
holder_pid = pid,
holder_comm = %comm,
"loopback is held open by a process that is not streaming — a client \
probably failed REQBUFS/STREAMON because the capture slot is taken"
);
}
resync.external_holder = Some(true);
}
WalkOutcome::CleanAbsent => {
ctx.counters.set_external_openers(0);
resync.external_holder = Some(false);
}
outcome => {
ctx.counters.set_external_openers(EXTERNAL_OPENERS_UNSET);
debug!(
target: "fluxframe::idle",
?outcome,
"cannot attribute the loopback's holders"
);
resync.external_holder = None;
}
}
}
fn report_event_silence(ctx: &DetectorContext<'_>, resync: &mut ResyncState) {
let age = if let Some(last) = resync.last_external_event {
let age = last.elapsed();
ctx.counters
.set_consumer_last_external_event_age_secs(age.as_secs());
age
} else {
ctx.counters
.set_consumer_last_external_event_age_secs(CONSUMER_EVENT_AGE_UNSET);
resync.started_at.elapsed()
};
if age >= resync.stale_after && !resync.stale_warned {
resync.stale_warned = true;
warn!(
target: "fluxframe::idle",
silent_secs = age.as_secs(),
threshold_secs = resync.stale_after.as_secs(),
"no client-usage events for longer than expected — if consumers are \
attaching, the subscription has gone deaf"
);
}
}
#[cfg(test)]
pub(super) mod fixtures {
use super::{ClientUsage, LoopbackState, NodeProbe, io};
pub(in crate::idle) struct FakeProbe {
usage: std::cell::RefCell<std::collections::VecDeque<io::Result<ClientUsage>>>,
last: std::cell::Cell<Option<u32>>,
pub(in crate::idle) output: std::cell::Cell<LoopbackState>,
pub(in crate::idle) calls: std::cell::Cell<u32>,
}
impl FakeProbe {
pub(in crate::idle) fn new(script: Vec<io::Result<ClientUsage>>) -> Self {
Self {
usage: std::cell::RefCell::new(script.into()),
last: std::cell::Cell::new(None),
output: std::cell::Cell::new(LoopbackState::ProducerStreaming),
calls: std::cell::Cell::new(0),
}
}
pub(in crate::idle) fn silent() -> Self {
Self::new(Vec::new())
}
}
impl NodeProbe for FakeProbe {
fn client_usage(&self) -> io::Result<ClientUsage> {
self.calls.set(self.calls.get() + 1);
match self.usage.borrow_mut().pop_front() {
Some(Ok(u)) => {
self.last.set(Some(u.count));
Ok(u)
}
Some(Err(e)) => Err(e),
None => match self.last.get() {
Some(count) => Ok(ClientUsage { count }),
None => Err(io::Error::from(io::ErrorKind::TimedOut)),
},
}
}
fn output_state(&self) -> LoopbackState {
self.output.get()
}
}
#[expect(
clippy::unnecessary_wraps,
reason = "the Result is the point: scripts mix successful readings with probe \
failures, mirroring `usage()` on the event side"
)]
pub(in crate::idle) fn probe_ok(count: u32) -> io::Result<ClientUsage> {
Ok(ClientUsage { count })
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use fluxframe_core::Counters;
use super::fixtures::FakeProbe;
use super::{
ClientUsage, Duration, LoopbackState, RESYNC_BACKOFF_MAX, ResyncSchedule, ResyncState,
check_external_holder, check_output_stream, io, on_probe_error, report_event_silence,
};
use crate::idle::detector::tests::{make_proc_entry, with_ctx};
#[test]
fn the_wall_clock_schedule_fires_only_after_its_interval() {
let never = ResyncState::new(
ResyncSchedule::every(Duration::from_secs(3600)),
Duration::from_secs(5),
);
assert!(!never.due(), "a fresh state must wait out its interval");
let now = ResyncState::new(
ResyncSchedule::every(Duration::from_millis(1)),
Duration::from_secs(5),
);
std::thread::sleep(Duration::from_millis(2));
assert!(now.due());
}
#[test]
fn a_zero_interval_is_not_a_schedule() {
let state = ResyncState::new(
ResyncSchedule::every(Duration::ZERO),
Duration::from_secs(5),
);
assert!(matches!(state.schedule, ResyncSchedule::Off));
assert!(!state.due());
}
#[test]
fn a_disabled_resync_never_fires_again() {
let mut state = ResyncState::new(
ResyncSchedule::every(Duration::from_millis(1)),
Duration::from_secs(5),
);
state.disabled = true;
std::thread::sleep(Duration::from_millis(2));
assert!(!state.due());
}
#[test]
fn busy_backs_off_and_recovers_to_the_configured_interval() {
const EBUSY: i32 = 16;
let counters = Counters::new();
let interval = Duration::from_secs(30);
let mut resync = ResyncState::new(ResyncSchedule::every(interval), Duration::from_secs(5));
let busy = io::Error::from_raw_os_error(EBUSY);
with_ctx(Path::new("/proc"), &counters, |ctx| {
on_probe_error(&busy, ctx, &mut resync);
let first = resync.backoff;
assert!(resync.backoff_until.is_some(), "EBUSY must back off");
assert!(!resync.due(), "the backoff deadline suppresses the tick");
on_probe_error(&busy, ctx, &mut resync);
assert!(
resync.backoff > first,
"consecutive EBUSY must escalate: {first:?} -> {:?}",
resync.backoff
);
assert!(resync.backoff <= RESYNC_BACKOFF_MAX);
});
resync.backoff_until = None;
resync.backoff = resync.backoff_base;
assert_eq!(resync.backoff, interval);
assert_eq!(counters.snapshot().consumer_resync_failures_total, 2);
}
#[test]
fn a_permanent_failure_is_not_retried_and_takes_the_gauge_with_it() {
const ENOTTY: i32 = 25;
let counters = Counters::new();
let mut resync = ResyncState::new(
ResyncSchedule::every(Duration::from_millis(1)),
Duration::from_secs(5),
);
with_ctx(Path::new("/proc"), &counters, |ctx| {
on_probe_error(&io::Error::from_raw_os_error(ENOTTY), ctx, &mut resync);
});
assert!(resync.disabled);
std::thread::sleep(Duration::from_millis(2));
assert!(!resync.due());
assert_eq!(
counters.snapshot().consumer_last_external_event_age_secs,
fluxframe_core::CONSUMER_EVENT_AGE_UNSET
);
}
#[test]
fn event_silence_is_measured_only_from_real_events() {
let counters = Counters::new();
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
resync.stale_after = Duration::ZERO;
with_ctx(Path::new("/proc"), &counters, |ctx| {
report_event_silence(ctx, &mut resync);
assert_eq!(
counters.snapshot().consumer_last_external_event_age_secs,
fluxframe_core::CONSUMER_EVENT_AGE_UNSET
);
assert!(resync.stale_warned);
resync.note_external_event();
assert!(!resync.stale_warned, "a real event re-arms the warning");
report_event_silence(ctx, &mut resync);
assert_ne!(
counters.snapshot().consumer_last_external_event_age_secs,
fluxframe_core::CONSUMER_EVENT_AGE_UNSET
);
});
}
#[test]
fn an_external_event_breaks_a_run_of_agreeing_reads() {
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
resync.absent_streak = 1;
resync.note_external_event();
assert_eq!(resync.absent_streak, 0);
}
#[test]
fn the_proc_census_is_throttled_between_state_changes() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 4321, 7, Path::new("/dev/video10"));
let counters = Counters::new();
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(dir.path(), &counters, |ctx| {
assert!(resync.census_due(), "the first Absent tick must census");
check_external_holder(ClientUsage { count: 0 }, ctx, &mut resync);
assert_eq!(counters.snapshot().external_openers, 1);
assert!(
!resync.census_due(),
"a second tick moments later must not walk /proc again"
);
check_external_holder(ClientUsage { count: 1 }, ctx, &mut resync);
assert!(resync.census_due(), "a state change forces a fresh census");
});
}
#[test]
fn output_stream_loss_is_counted_once_per_edge() {
let counters = Counters::new();
let probe = FakeProbe::silent();
probe.output.set(LoopbackState::ProducerStopped);
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(Path::new("/proc"), &counters, |ctx| {
check_output_stream(&probe, ctx, &mut resync);
check_output_stream(&probe, ctx, &mut resync);
assert_eq!(counters.snapshot().output_stream_up, 0);
assert_eq!(
counters.snapshot().output_stream_down_total,
1,
"a persistent fault is one edge, not one per tick"
);
probe.output.set(LoopbackState::ProducerStreaming);
check_output_stream(&probe, ctx, &mut resync);
assert_eq!(counters.snapshot().output_stream_up, 1);
assert_eq!(counters.snapshot().output_stream_down_total, 1);
});
}
#[test]
fn an_unreadable_output_state_is_unknown_not_down() {
let counters = Counters::new();
let probe = FakeProbe::silent();
probe
.output
.set(LoopbackState::Unreadable(io::ErrorKind::NotFound));
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(Path::new("/proc"), &counters, |ctx| {
check_output_stream(&probe, ctx, &mut resync);
});
assert_eq!(
counters.snapshot().output_stream_up,
fluxframe_core::OUTPUT_STREAM_UNKNOWN
);
assert_eq!(counters.snapshot().output_stream_down_total, 0);
}
#[test]
fn a_holder_that_is_not_streaming_is_surfaced() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 4321, 7, Path::new("/dev/video10"));
let counters = Counters::new();
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(dir.path(), &counters, |ctx| {
check_external_holder(ClientUsage { count: 0 }, ctx, &mut resync);
});
assert_eq!(counters.snapshot().external_openers, 1);
}
#[test]
fn nobody_holding_the_node_reads_as_zero_not_unknown() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 4321, 7, Path::new("/dev/video0"));
let counters = Counters::new();
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(dir.path(), &counters, |ctx| {
check_external_holder(ClientUsage { count: 0 }, ctx, &mut resync);
});
assert_eq!(counters.snapshot().external_openers, 0);
}
#[test]
fn holders_are_not_walked_while_somebody_is_streaming() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 4321, 7, Path::new("/dev/video10"));
let counters = Counters::new();
let mut resync = ResyncState::new(ResyncSchedule::Off, Duration::from_secs(5));
with_ctx(dir.path(), &counters, |ctx| {
check_external_holder(ClientUsage { count: 1 }, ctx, &mut resync);
});
assert_eq!(
counters.snapshot().external_openers,
fluxframe_core::EXTERNAL_OPENERS_UNSET
);
}
}