use std::ffi::{OsStr, OsString};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[cfg(test)]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use fluxframe_core::{Counters, IdlePresenceSource};
use fluxframe_gst::ClientUsage;
use fluxframe_gst::output::OutputSink;
use fluxframe_gst::v4l2_events::ConsumerWatch;
use tracing::{debug, info, warn};
use super::resync::{DeviceProbe, NodeProbe, ResyncSchedule, ResyncState, resync_tick};
use super::state::ConsumerStatus;
const EACCES_PID_SAMPLE: usize = 8;
const RESTAT_INTERVAL_POLLS: u32 = 60;
const SHUTDOWN_POLL_GRANULARITY: Duration = Duration::from_millis(50);
pub(super) fn shutdown_bounded_timeout_ms() -> i32 {
i32::try_from(SHUTDOWN_POLL_GRANULARITY.as_millis()).unwrap_or(i32::from(u8::MAX))
}
const INOTIFY_READ_ERROR_BUDGET: u32 = 16;
const INOTIFY_EVENT_BUFFER_BYTES: usize = 1024;
const CONSUMER_SOURCE_KERNEL: u64 = 0;
const CONSUMER_SOURCE_INOTIFY: u64 = 1;
const CONSUMER_SOURCE_POLL: u64 = 2;
const CONSUMER_SOURCE_DISABLED: u64 = 3;
pub(crate) trait UsageSource {
fn wait(&mut self, timeout_ms: i32) -> io::Result<Option<ClientUsage>>;
}
impl UsageSource for ConsumerWatch {
fn wait(&mut self, timeout_ms: i32) -> io::Result<Option<ClientUsage>> {
self.poll(timeout_ms)
}
}
enum DetectorExit {
WatchRemoved,
InitFailed(io::Error),
AddFailed(io::Error),
ReadFatal(io::Error),
}
impl std::fmt::Display for DetectorExit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::WatchRemoved => f.write_str("watch removed (IN_IGNORED)"),
Self::InitFailed(e) => write!(f, "inotify init failed: {e}"),
Self::AddFailed(e) => write!(f, "inotify watch add failed: {e}"),
Self::ReadFatal(e) => write!(f, "inotify read failed repeatedly: {e}"),
}
}
}
pub(super) struct DetectorContext<'a> {
pub(super) proc_root: &'a Path,
pub(super) my_pid: u32,
running: &'a AtomicBool,
status: &'a AtomicU8,
pub(super) stopped: &'a AtomicBool,
restat_interval_polls: u32,
pub(super) device_basename: &'a OsStr,
pub(super) counters: &'a Counters,
stale_balance_after: Duration,
teardown_grace: Duration,
#[cfg(test)]
inotify_activations: &'a AtomicU64,
}
pub(super) struct DetectorState<'a> {
log_once: &'a mut LogOnce,
pub(super) last_status: &'a mut Option<ConsumerStatus>,
presence: &'a mut ConsumerPresence,
}
#[must_use]
pub(crate) fn device_path(sink: &OutputSink) -> Option<PathBuf> {
let OutputSink::V4l2Loopback { device } = sink else {
return None;
};
Some(device.clone())
}
struct Gate(bool);
impl Gate {
const fn armed() -> Self {
Self(true)
}
fn fire(&mut self) -> bool {
std::mem::replace(&mut self.0, false)
}
fn rearm(&mut self) {
self.0 = true;
}
#[cfg(test)]
pub(super) fn is_armed(&self) -> bool {
self.0
}
}
struct LogOnce {
scan_failed: Gate,
eacces_storm: Gate,
}
impl LogOnce {
fn armed() -> Self {
Self {
scan_failed: Gate::armed(),
eacces_storm: Gate::armed(),
}
}
fn rearm(&mut self) {
self.scan_failed.rearm();
self.eacces_storm.rearm();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum WalkOutcome {
External { pid: u32 },
CleanAbsent,
UncertainAbsent { eacces_count: u32, pids: Vec<u32> },
Unreadable(io::ErrorKind),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PresenceReason {
External,
CleanAbsent,
UncertainAbsent,
UnattributableWake,
FailOpen,
}
#[derive(Default)]
struct ConsumerPresence {
open_balance: i32,
}
impl ConsumerPresence {
fn observe(
&mut self,
walk: &WalkOutcome,
net_opens: i32,
overflow: bool,
) -> (ConsumerStatus, PresenceReason) {
if overflow {
self.open_balance = 0;
} else {
self.open_balance = (self.open_balance + net_opens).max(0);
}
match walk {
WalkOutcome::Unreadable(_) => (ConsumerStatus::Unknown, PresenceReason::FailOpen),
WalkOutcome::External { .. } => {
self.open_balance = 1;
(ConsumerStatus::Present, PresenceReason::External)
}
WalkOutcome::CleanAbsent => {
self.open_balance = 0;
(ConsumerStatus::Absent, PresenceReason::CleanAbsent)
}
WalkOutcome::UncertainAbsent { .. } => {
if self.open_balance > 0 {
(ConsumerStatus::Present, PresenceReason::UnattributableWake)
} else {
(ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
}
}
}
}
fn is_stale(open_balance: i32, since_last_event: Duration, threshold: Duration) -> bool {
open_balance > 0 && since_last_event >= threshold
}
fn decay_if_stale(&mut self, since_last_event: Duration, threshold: Duration) -> bool {
if Self::is_stale(self.open_balance, since_last_event, threshold) {
self.open_balance = 0;
true
} else {
false
}
}
fn reset(&mut self) {
self.open_balance = 0;
}
}
pub(crate) struct ConsumerDetector {
handle: Option<JoinHandle<()>>,
status: Arc<AtomicU8>,
stopped: Arc<AtomicBool>,
#[cfg(test)]
inotify_activations: Arc<AtomicU64>,
}
pub(crate) struct DetectorParams {
pub(crate) device_path: PathBuf,
pub(crate) my_pid: u32,
pub(crate) poll_interval: Duration,
pub(crate) mode: IdlePresenceSource,
pub(crate) stale_balance_after: Duration,
pub(crate) teardown_grace: Duration,
pub(crate) resync_interval: Option<Duration>,
}
struct DetectorHandles {
running: Arc<AtomicBool>,
status: Arc<AtomicU8>,
stopped: Arc<AtomicBool>,
counters: Arc<Counters>,
}
pub(crate) struct DetectorTestKnobs {
proc_root: PathBuf,
restat_interval_polls: u32,
#[cfg(test)]
inotify_activations: Arc<AtomicU64>,
}
impl ConsumerDetector {
pub(crate) fn spawn(
params: DetectorParams,
running: Arc<AtomicBool>,
counters: Arc<Counters>,
watch: Option<ConsumerWatch>,
) -> Self {
Self::spawn_with_knobs(
params,
DetectorTestKnobs {
proc_root: PathBuf::from("/proc"),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
#[cfg(test)]
inotify_activations: Arc::new(AtomicU64::new(0)),
},
running,
counters,
watch,
)
}
pub(crate) fn spawn_with_knobs(
params: DetectorParams,
knobs: DetectorTestKnobs,
running: Arc<AtomicBool>,
counters: Arc<Counters>,
watch: Option<ConsumerWatch>,
) -> Self {
let status = Arc::new(AtomicU8::new(ConsumerStatus::Unknown.as_u8()));
let stopped = Arc::new(AtomicBool::new(false));
#[cfg(test)]
let inotify_activations = Arc::clone(&knobs.inotify_activations);
let handles = DetectorHandles {
running,
status: Arc::clone(&status),
stopped: Arc::clone(&stopped),
counters,
};
let handle = thread::Builder::new()
.name("fluxframe-detector".into())
.spawn(move || {
run_detector(params, handles, knobs, watch);
})
.expect("spawn detector thread");
Self {
handle: Some(handle),
status,
stopped,
#[cfg(test)]
inotify_activations,
}
}
pub(crate) fn status_handle(&self) -> Arc<AtomicU8> {
Arc::clone(&self.status)
}
#[cfg(test)]
pub(super) fn inotify_activations_handle(&self) -> Arc<AtomicU64> {
Arc::clone(&self.inotify_activations)
}
}
impl Drop for ConsumerDetector {
fn drop(&mut self) {
self.stopped.store(true, Ordering::Release);
if let Some(handle) = self.handle.take() {
if let Err(panic) = handle.join() {
warn!(
target: "fluxframe::idle",
panic = ?panic,
"consumer detector thread panicked during shutdown"
);
}
}
}
}
fn publish_if_changed(
new_status: ConsumerStatus,
status: &AtomicU8,
last_status: &mut Option<ConsumerStatus>,
counters: &Counters,
) {
if Some(new_status) == *last_status {
return;
}
status.store(new_status.as_u8(), Ordering::Release);
counters.set_consumer_status(new_status.as_u8());
if matches!(new_status, ConsumerStatus::Present | ConsumerStatus::Absent) {
info!(
target: "fluxframe::idle",
from = ?last_status,
to = ?new_status,
"consumer status changed"
);
} else {
debug!(
target: "fluxframe::idle",
from = ?last_status,
to = ?new_status,
"consumer status changed"
);
}
*last_status = Some(new_status);
}
fn run_detector(
params: DetectorParams,
handles: DetectorHandles,
knobs: DetectorTestKnobs,
watch: Option<ConsumerWatch>,
) {
let DetectorParams {
device_path,
my_pid,
poll_interval,
mode,
stale_balance_after,
teardown_grace,
resync_interval,
} = params;
let DetectorHandles {
running,
status,
stopped,
counters,
} = handles;
let DetectorTestKnobs {
proc_root,
restat_interval_polls,
#[cfg(test)]
inotify_activations,
} = knobs;
let Some(basename) = device_path.file_name() else {
warn!(
target: "fluxframe::idle",
path = %device_path.display(),
"device path has no basename — consumer detector disabled"
);
status.store(ConsumerStatus::Unknown.as_u8(), Ordering::Release);
return;
};
let device_basename: OsString = basename.to_os_string();
info!(
target: "fluxframe::idle",
device = %device_path.display(),
my_pid,
poll_ms = poll_interval.as_millis() as u64,
?mode,
subscription = watch.is_some(),
"consumer detector started"
);
let mut log_once = LogOnce::armed();
let mut last_status: Option<ConsumerStatus> = None;
let mut presence = ConsumerPresence::default();
let ctx = DetectorContext {
proc_root: &proc_root,
my_pid,
running: &running,
status: &status,
stopped: &stopped,
restat_interval_polls,
device_basename: &device_basename,
counters: &counters,
stale_balance_after,
teardown_grace,
#[cfg(test)]
inotify_activations: &inotify_activations,
};
let mut state = DetectorState {
log_once: &mut log_once,
last_status: &mut last_status,
presence: &mut presence,
};
let probe = DeviceProbe::new(device_path.clone());
let schedule = resync_interval.map_or(ResyncSchedule::Off, ResyncSchedule::every);
if run_presence_source(mode, watch, &probe, schedule, &ctx, &mut state) {
run_heuristic_detector(poll_interval, &device_path, &ctx, &mut state);
}
info!(target: "fluxframe::idle", "consumer detector exiting");
}
fn run_presence_source<P: NodeProbe>(
mode: IdlePresenceSource,
watch: Option<ConsumerWatch>,
probe: &P,
schedule: ResyncSchedule,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) -> bool {
match mode {
IdlePresenceSource::Disabled => {
run_detector_disabled(ctx, state);
false
}
IdlePresenceSource::Inotify => {
debug!(
target: "fluxframe::idle",
subscription = watch.is_some(),
"presence_source = inotify — using the heuristic path"
);
drop(watch);
true
}
IdlePresenceSource::Auto | IdlePresenceSource::KernelEvent => {
let strict = mode == IdlePresenceSource::KernelEvent;
let Some(mut watch) = watch else {
if strict {
warn!(
target: "fluxframe::idle",
"presence_source = kernel_event but the sink exposes no \
subscription — presence is UNKNOWN and idle will not engage"
);
park_until_stopped(ctx);
return false;
}
info!(
target: "fluxframe::idle",
"no kernel client-usage subscription available — using the \
inotify + /proc heuristic"
);
return true;
};
match run_detector_client_usage(&mut watch, probe, schedule, ctx, state) {
Ok(()) => false,
Err(e) if strict => {
warn!(
target: "fluxframe::idle",
error = %e,
"kernel client-usage subscription died and \
presence_source = kernel_event forbids falling back"
);
publish_if_changed(
ConsumerStatus::Unknown,
ctx.status,
state.last_status,
ctx.counters,
);
park_until_stopped(ctx);
false
}
Err(e) => {
warn!(
target: "fluxframe::idle",
error = %e,
"kernel client-usage subscription died — falling back to \
the inotify + /proc heuristic"
);
publish_if_changed(
ConsumerStatus::Unknown,
ctx.status,
state.last_status,
ctx.counters,
);
true
}
}
}
}
}
fn run_heuristic_detector(
poll_interval: Duration,
device_path: &Path,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) {
if let Err(exit) = run_detector_inotify(device_path, ctx, state) {
match &exit {
DetectorExit::WatchRemoved => warn!(
target: "fluxframe::idle",
"inotify watch removed — falling back to /proc polling"
),
DetectorExit::ReadFatal(e) => warn!(
target: "fluxframe::idle",
error = %e,
"inotify read repeatedly failed — falling back to /proc polling"
),
DetectorExit::InitFailed(_) | DetectorExit::AddFailed(_) => info!(
target: "fluxframe::idle",
reason = %exit,
"inotify path unavailable — falling back to /proc polling"
),
}
ctx.counters.set_consumer_source(CONSUMER_SOURCE_POLL);
run_detector_polling(poll_interval, ctx, state);
}
}
fn park_until_stopped(ctx: &DetectorContext<'_>) {
while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
thread::sleep(SHUTDOWN_POLL_GRANULARITY);
}
}
fn run_detector_client_usage<S: UsageSource, P: NodeProbe>(
source: &mut S,
probe: &P,
schedule: ResyncSchedule,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) -> io::Result<()> {
let timeout_ms = shutdown_bounded_timeout_ms();
ctx.counters.set_consumer_source(CONSUMER_SOURCE_KERNEL);
info!(
target: "fluxframe::idle",
"consumer detection using kernel client-usage events"
);
let mut resync = ResyncState::new(schedule, ctx.teardown_grace);
resync.announce();
while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
resync.note_iteration();
if let Some(usage) = source.wait(timeout_ms)? {
debug!(
target: "fluxframe::idle",
count = usage.count,
"client-usage event"
);
resync.note_external_event();
apply_usage(usage, ctx, state);
}
if !ctx.running.load(Ordering::Acquire) || ctx.stopped.load(Ordering::Acquire) {
break;
}
if resync.due() {
resync_tick(source, probe, ctx, state, &mut resync);
}
}
Ok(())
}
pub(super) fn apply_usage(
usage: ClientUsage,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) {
ctx.counters.set_consumer_clients(u64::from(usage.count));
let status = if usage.attached() {
ConsumerStatus::Present
} else {
ConsumerStatus::Absent
};
publish_if_changed(status, ctx.status, state.last_status, ctx.counters);
}
fn run_detector_disabled(ctx: &DetectorContext<'_>, state: &mut DetectorState<'_>) {
ctx.counters.set_consumer_source(CONSUMER_SOURCE_DISABLED);
info!(
target: "fluxframe::idle",
"consumer detection disabled by config — idle will never engage"
);
publish_if_changed(
ConsumerStatus::Present,
ctx.status,
state.last_status,
ctx.counters,
);
park_until_stopped(ctx);
}
#[derive(Default, Clone, Copy)]
struct EventSummary {
needs_rescan: bool,
net_opens: i32,
overflow: bool,
watch_removed: bool,
}
impl EventSummary {
fn observe(&mut self, mask: inotify::EventMask) {
if mask.contains(inotify::EventMask::Q_OVERFLOW) {
self.overflow = true;
}
if mask.contains(inotify::EventMask::OPEN) {
self.needs_rescan = true;
self.net_opens += 1;
}
if mask.intersects(inotify::EventMask::CLOSE_WRITE | inotify::EventMask::CLOSE_NOWRITE) {
self.needs_rescan = true;
self.net_opens -= 1;
}
if mask.contains(inotify::EventMask::IGNORED) {
self.watch_removed = true;
}
}
}
fn run_detector_inotify(
device_path: &Path,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) -> Result<(), DetectorExit> {
let mut inotify = inotify::Inotify::init().map_err(DetectorExit::InitFailed)?;
inotify
.watches()
.add(
device_path,
inotify::WatchMask::OPEN
| inotify::WatchMask::CLOSE_NOWRITE
| inotify::WatchMask::CLOSE_WRITE,
)
.map_err(DetectorExit::AddFailed)?;
#[cfg(test)]
ctx.inotify_activations.fetch_add(1, Ordering::Release);
ctx.counters.set_consumer_source(CONSUMER_SOURCE_INOTIFY);
walk_observe_publish(ctx, state, 0, false);
let mut buffer = [0u8; INOTIFY_EVENT_BUFFER_BYTES];
let mut walks_since_restat: u32 = 0;
let mut consecutive_read_errors: u32 = 0;
let mut last_event_at = Instant::now();
while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
let summary = read_event_batch(
&mut inotify,
&mut buffer,
ctx,
state,
&mut consecutive_read_errors,
)?;
if summary.needs_rescan || summary.net_opens != 0 || summary.overflow {
last_event_at = Instant::now();
}
apply_summary(summary, ctx, state, &mut walks_since_restat)?;
if state
.presence
.decay_if_stale(last_event_at.elapsed(), ctx.stale_balance_after)
{
warn!(
target: "fluxframe::idle",
quiet_secs = last_event_at.elapsed().as_secs(),
"discarding a stale unattributable open balance and re-checking; \
a close event was most likely missed"
);
last_event_at = Instant::now();
walk_observe_publish(ctx, state, 0, false);
}
}
Ok(())
}
fn read_event_batch(
inotify: &mut inotify::Inotify,
buffer: &mut [u8],
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
consecutive_read_errors: &mut u32,
) -> Result<EventSummary, DetectorExit> {
let mut summary = EventSummary::default();
match inotify.read_events(buffer) {
Ok(events) => {
*consecutive_read_errors = 0;
for ev in events {
summary.observe(ev.mask);
}
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
*consecutive_read_errors = 0;
thread::sleep(SHUTDOWN_POLL_GRANULARITY);
}
Err(e) => {
if *consecutive_read_errors == 0 {
publish_if_changed(
ConsumerStatus::Unknown,
ctx.status,
state.last_status,
ctx.counters,
);
}
*consecutive_read_errors = consecutive_read_errors.saturating_add(1);
let consecutive = *consecutive_read_errors;
if consecutive == 1 || consecutive >= INOTIFY_READ_ERROR_BUDGET - 1 {
warn!(
target: "fluxframe::idle",
error = %e,
consecutive,
"inotify read failed; retrying after shutdown poll window"
);
} else {
debug!(
target: "fluxframe::idle",
error = %e,
consecutive,
"inotify read failed; retrying after shutdown poll window"
);
}
if consecutive >= INOTIFY_READ_ERROR_BUDGET {
return Err(DetectorExit::ReadFatal(e));
}
thread::sleep(SHUTDOWN_POLL_GRANULARITY);
}
}
Ok(summary)
}
fn apply_summary(
summary: EventSummary,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
walks_since_restat: &mut u32,
) -> Result<(), DetectorExit> {
if summary.watch_removed {
publish_if_changed(
ConsumerStatus::Unknown,
ctx.status,
state.last_status,
ctx.counters,
);
return Err(DetectorExit::WatchRemoved);
}
if summary.overflow {
info!(
target: "fluxframe::idle",
"inotify queue overflow — resyncing via /proc walk"
);
}
if summary.needs_rescan || summary.overflow {
walk_observe_publish(ctx, state, summary.net_opens, summary.overflow);
tick_restat(
walks_since_restat,
ctx.restat_interval_polls,
state.log_once,
);
}
Ok(())
}
fn tick_restat(counter: &mut u32, interval: u32, log_once: &mut LogOnce) {
*counter = counter.wrapping_add(1);
if *counter >= interval {
log_once.rearm();
*counter = 0;
}
}
fn run_detector_polling(
poll_interval: Duration,
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
) {
let mut polls_since_restat: u32 = 0;
state.presence.reset();
while ctx.running.load(Ordering::Acquire) && !ctx.stopped.load(Ordering::Acquire) {
walk_observe_publish(ctx, state, 0, false);
tick_restat(
&mut polls_since_restat,
ctx.restat_interval_polls,
state.log_once,
);
let mut remaining = poll_interval;
while remaining > Duration::ZERO
&& ctx.running.load(Ordering::Acquire)
&& !ctx.stopped.load(Ordering::Acquire)
{
let chunk = remaining.min(SHUTDOWN_POLL_GRANULARITY);
thread::sleep(chunk);
remaining = remaining.saturating_sub(chunk);
}
}
}
fn walk_observe_publish(
ctx: &DetectorContext<'_>,
state: &mut DetectorState<'_>,
net_opens: i32,
overflow: bool,
) {
let walk = count_external_consumers(ctx.proc_root, ctx.device_basename, ctx.my_pid);
let prev = *state.last_status;
let (status, reason) = state.presence.observe(&walk, net_opens, overflow);
match &walk {
WalkOutcome::Unreadable(kind) => {
if state.log_once.scan_failed.fire() {
warn!(
target: "fluxframe::idle",
proc_root = %ctx.proc_root.display(),
error = ?kind,
"/proc scan failed — consumer detection disabled"
);
}
}
WalkOutcome::UncertainAbsent { eacces_count, pids } => {
if state.log_once.eacces_storm.fire() {
let comms = read_comms(ctx.proc_root, pids);
info!(
target: "fluxframe::idle",
eacces_count = *eacces_count,
net_opens,
open_balance = state.presence.open_balance,
decision = ?status,
reason = ?reason,
comms = ?comms,
"scanned /proc; candidate fd dirs returned EACCES — a sandboxed/privileged consumer may be present"
);
}
}
WalkOutcome::External { .. } | WalkOutcome::CleanAbsent => {}
}
if reason == PresenceReason::UnattributableWake && prev != Some(ConsumerStatus::Present) {
ctx.counters.inc_unattributable_wakes();
}
publish_if_changed(status, ctx.status, state.last_status, ctx.counters);
}
pub(super) fn read_comm(proc_root: &Path, pid: u32) -> Option<String> {
std::fs::read_to_string(proc_root.join(pid.to_string()).join("comm"))
.ok()
.map(|s| s.trim_end().to_string())
}
fn read_comms(proc_root: &Path, pids: &[u32]) -> Vec<String> {
pids.iter()
.filter_map(|&pid| read_comm(proc_root, pid))
.collect()
}
pub(super) fn count_external_consumers(
proc_root: &Path,
device_basename: &OsStr,
my_pid: u32,
) -> WalkOutcome {
let entries = match std::fs::read_dir(proc_root) {
Ok(it) => it,
Err(e) => return WalkOutcome::Unreadable(e.kind()),
};
let mut eacces_count: u32 = 0;
let mut eacces_pids: Vec<u32> = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
continue;
};
let Ok(pid) = name_str.parse::<u32>() else {
continue;
};
if pid == my_pid {
continue;
}
let fd_dir = entry.path().join("fd");
let fd_entries = match std::fs::read_dir(&fd_dir) {
Ok(it) => it,
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
eacces_count = eacces_count.saturating_add(1);
if eacces_pids.len() < EACCES_PID_SAMPLE {
eacces_pids.push(pid);
}
continue;
}
Err(_) => continue,
};
for fd in fd_entries.flatten() {
let Ok(link) = std::fs::read_link(fd.path()) else {
continue;
};
if link.file_name() == Some(device_basename) {
return WalkOutcome::External { pid };
}
}
}
if eacces_count > 0 {
WalkOutcome::UncertainAbsent {
eacces_count,
pids: eacces_pids,
}
} else {
WalkOutcome::CleanAbsent
}
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::{PermissionsExt, symlink};
use std::time::Instant;
use super::super::resync::fixtures::{FakeProbe, probe_ok};
struct FakeUsage<'a> {
script: std::collections::VecDeque<io::Result<Option<ClientUsage>>>,
stopped: &'a AtomicBool,
}
impl<'a> FakeUsage<'a> {
fn new(script: Vec<io::Result<Option<ClientUsage>>>, stopped: &'a AtomicBool) -> Self {
Self {
script: script.into(),
stopped,
}
}
}
impl UsageSource for FakeUsage<'_> {
fn wait(&mut self, _timeout_ms: i32) -> io::Result<Option<ClientUsage>> {
let Some(reading) = self.script.pop_front() else {
self.stopped.store(true, Ordering::Release);
return Ok(None);
};
reading
}
}
#[expect(
clippy::unnecessary_wraps,
reason = "the Result/Option wrapper is the point: scripts mix readings with \
Ok(None) timeouts and Err subscription deaths"
)]
fn usage(count: u32) -> io::Result<Option<ClientUsage>> {
Ok(Some(ClientUsage { count }))
}
struct ClientUsageRun {
last_status: Option<ConsumerStatus>,
result: io::Result<()>,
counters: fluxframe_core::CounterValues,
}
fn drive_client_usage(script: Vec<io::Result<Option<ClientUsage>>>) -> ClientUsageRun {
drive_client_usage_with(
script,
&FakeProbe::silent(),
ResyncSchedule::Off,
Path::new("/proc"),
)
}
fn drive_with_resync(
script: Vec<io::Result<Option<ClientUsage>>>,
probe: &FakeProbe,
) -> ClientUsageRun {
let empty_proc = tempfile::tempdir().expect("tempdir");
drive_client_usage_with(
script,
probe,
ResyncSchedule::EveryIterations(1),
empty_proc.path(),
)
}
fn drive_client_usage_with(
script: Vec<io::Result<Option<ClientUsage>>>,
probe: &FakeProbe,
schedule: ResyncSchedule,
proc_root: &Path,
) -> ClientUsageRun {
let running = AtomicBool::new(true);
let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
let stopped = AtomicBool::new(false);
let counters = Counters::new();
let device_basename = OsString::from("video10");
#[cfg(test)]
let activations = AtomicU64::new(0);
let ctx = DetectorContext {
proc_root,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
my_pid: 9999,
running: &running,
status: &status,
stopped: &stopped,
restat_interval_polls: RESTAT_INTERVAL_POLLS,
device_basename: &device_basename,
counters: &counters,
#[cfg(test)]
inotify_activations: &activations,
};
let mut log_once = LogOnce::armed();
let mut last_status: Option<ConsumerStatus> = None;
let mut presence = ConsumerPresence::default();
let mut state = DetectorState {
log_once: &mut log_once,
last_status: &mut last_status,
presence: &mut presence,
};
let mut source = FakeUsage::new(script, &stopped);
let result = run_detector_client_usage(&mut source, probe, schedule, &ctx, &mut state);
ClientUsageRun {
last_status,
result,
counters: counters.snapshot(),
}
}
#[test]
fn client_usage_zero_means_absent() {
let run = drive_client_usage(vec![usage(0)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Absent));
assert_eq!(run.counters.consumer_clients, 0);
}
#[test]
fn client_usage_nonzero_means_present() {
let run = drive_client_usage(vec![usage(1)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_clients, 1);
}
#[test]
fn client_usage_counts_above_one_still_mean_present() {
let run = drive_client_usage(vec![usage(3)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(
run.counters.consumer_clients, 3,
"the gauge carries the raw count, not the boolean"
);
}
#[test]
fn client_usage_tracks_transitions_in_order() {
let run = drive_client_usage(vec![usage(1), usage(1), usage(0), usage(1)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(
run.counters.consumer_transitions_total, 3,
"three actual changes; the repeated `1` must not be published twice"
);
assert_eq!(run.counters.consumer_clients, 1);
}
#[test]
fn client_usage_deduplicates_repeated_readings() {
let run = drive_client_usage(vec![usage(1), usage(1)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_transitions_total, 1);
}
#[test]
fn client_usage_timeout_does_not_change_the_verdict() {
let run = drive_client_usage(vec![usage(1), Ok(None), Ok(None)]);
assert!(run.result.is_ok());
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(
run.counters.consumer_transitions_total, 1,
"a timeout is not a transition"
);
}
#[test]
fn client_usage_stays_unknown_until_the_first_reading() {
let run = drive_client_usage(vec![Ok(None)]);
assert!(run.result.is_ok());
assert_eq!(
run.last_status, None,
"no verdict may be published without evidence"
);
assert_eq!(run.counters.consumer_transitions_total, 0);
}
#[test]
fn client_usage_surfaces_a_dead_subscription() {
const ENODEV: i32 = 19;
let run = drive_client_usage(vec![Err(io::Error::from_raw_os_error(ENODEV))]);
let err = run.result.expect_err("a dead subscription must surface");
assert_eq!(err.raw_os_error(), Some(ENODEV));
}
#[test]
fn resync_confirming_the_verdict_is_not_a_correction() {
let probe = FakeProbe::new(vec![probe_ok(1)]);
let run = drive_with_resync(vec![usage(1)], &probe);
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_resync_corrections_total, 0);
assert!(run.counters.consumer_resync_total > 0);
assert_eq!(run.counters.consumer_resync_failures_total, 0);
}
#[test]
fn resync_wakes_the_camera_as_soon_as_the_kernel_says_present() {
let probe = FakeProbe::new(vec![probe_ok(1)]);
let run = drive_with_resync(vec![usage(0)], &probe);
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_resync_corrections_total, 1);
assert_eq!(run.counters.consumer_clients, 1);
}
#[test]
fn resync_needs_two_agreeing_reads_before_letting_the_camera_go() {
let probe = FakeProbe::new(vec![probe_ok(0)]);
let one_tick = drive_with_resync(vec![usage(1), Ok(None)], &probe);
assert_eq!(
one_tick.last_status,
Some(ConsumerStatus::Present),
"a single disagreeing read must not release the camera"
);
assert_eq!(one_tick.counters.consumer_resync_corrections_total, 0);
let probe = FakeProbe::new(vec![probe_ok(0), probe_ok(0)]);
let two_ticks = drive_with_resync(vec![usage(1), Ok(None), Ok(None)], &probe);
assert_eq!(two_ticks.last_status, Some(ConsumerStatus::Absent));
assert_eq!(two_ticks.counters.consumer_resync_corrections_total, 1);
}
#[test]
fn resync_publishes_the_first_reading_without_calling_it_a_correction() {
let probe = FakeProbe::new(vec![probe_ok(1)]);
let run = drive_with_resync(vec![Ok(None)], &probe);
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_resync_corrections_total, 0);
}
#[test]
fn a_failed_resync_never_latches_the_verdict() {
let probe = FakeProbe::new(vec![Err(io::Error::from(io::ErrorKind::TimedOut))]);
let run = drive_with_resync(vec![usage(1)], &probe);
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert!(run.counters.consumer_resync_failures_total >= 1);
assert_eq!(run.counters.consumer_resync_corrections_total, 0);
}
#[test]
fn a_permanent_probe_failure_stops_the_resync_for_the_run() {
const ENOTTY: i32 = 25;
let probe = FakeProbe::new(vec![
Err(io::Error::from_raw_os_error(ENOTTY)),
probe_ok(1),
probe_ok(1),
]);
let run = drive_with_resync(vec![usage(0), Ok(None), Ok(None), Ok(None)], &probe);
assert_eq!(probe.calls.get(), 1, "the probe must not be called again");
assert_eq!(run.counters.consumer_resync_failures_total, 1);
assert_eq!(run.last_status, Some(ConsumerStatus::Absent));
}
#[test]
fn a_changed_reading_during_the_probe_wins_over_the_drift_check() {
let probe = FakeProbe::new(vec![probe_ok(0)]);
let run = drive_with_resync(vec![usage(0), usage(1)], &probe);
assert_eq!(run.last_status, Some(ConsumerStatus::Present));
assert_eq!(run.counters.consumer_resync_corrections_total, 0);
}
pub(in crate::idle) fn with_ctx<R>(
proc_root: &Path,
counters: &Counters,
f: impl FnOnce(&DetectorContext<'_>) -> R,
) -> R {
let running = AtomicBool::new(true);
let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
let stopped = AtomicBool::new(false);
let device_basename = OsString::from("video10");
#[cfg(test)]
let activations = AtomicU64::new(0);
let ctx = DetectorContext {
proc_root,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
my_pid: 9999,
running: &running,
status: &status,
stopped: &stopped,
restat_interval_polls: RESTAT_INTERVAL_POLLS,
device_basename: &device_basename,
counters,
#[cfg(test)]
inotify_activations: &activations,
};
f(&ctx)
}
#[test]
fn stale_balance_decays_only_after_the_quiet_period() {
let threshold = Duration::from_secs(5);
assert!(!ConsumerPresence::is_stale(
1,
Duration::from_secs(4),
threshold
));
assert!(ConsumerPresence::is_stale(
1,
Duration::from_secs(5),
threshold
));
assert!(!ConsumerPresence::is_stale(
0,
Duration::from_secs(600),
threshold
));
}
#[test]
fn decay_zeroes_the_balance_once() {
let mut presence = ConsumerPresence { open_balance: 4 };
assert!(presence.decay_if_stale(Duration::from_secs(10), Duration::from_secs(5)));
assert_eq!(presence.open_balance, 0);
assert!(!presence.decay_if_stale(Duration::from_secs(10), Duration::from_secs(5)));
}
#[test]
fn readable_walk_reanchors_the_balance_downwards() {
let mut presence = ConsumerPresence { open_balance: 9 };
let (status, reason) = presence.observe(&WalkOutcome::External { pid: 42 }, 0, false);
assert_eq!(status, ConsumerStatus::Present);
assert_eq!(reason, PresenceReason::External);
assert_eq!(presence.open_balance, 1);
let (status, _) = presence.observe(
&WalkOutcome::UncertainAbsent {
eacces_count: 400,
pids: vec![],
},
-1,
false,
);
assert_eq!(status, ConsumerStatus::Absent);
}
fn wait_for_status(
status: &Arc<AtomicU8>,
expected: ConsumerStatus,
timeout: Duration,
) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
let observed = ConsumerStatus::from_u8(status.load(Ordering::Acquire));
if observed == expected {
return true;
}
thread::sleep(Duration::from_millis(5));
}
false
}
pub(in crate::idle) fn make_proc_entry(proc_root: &Path, pid: u32, fd: u32, target: &Path) {
let fd_dir = proc_root.join(pid.to_string()).join("fd");
fs::create_dir_all(&fd_dir).unwrap();
symlink(target, fd_dir.join(fd.to_string())).unwrap();
}
#[test]
fn device_path_for_v4l2_loopback() {
let sink = OutputSink::V4l2Loopback {
device: PathBuf::from("/dev/video10"),
};
let path = device_path(&sink).expect("v4l2 sink yields a device path");
assert_eq!(path, PathBuf::from("/dev/video10"));
}
#[test]
fn device_path_none_for_non_v4l2_sinks() {
assert!(device_path(&OutputSink::Fake).is_none());
assert!(device_path(&OutputSink::Auto).is_none());
assert!(
device_path(&OutputSink::Pipewire {
node_name: Some("fluxframe".into())
})
.is_none()
);
}
#[test]
fn one_external_pid_with_matching_fd_is_external() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::External { pid: 1234 });
}
#[test]
fn multiple_fds_same_pid_is_external() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));
make_proc_entry(dir.path(), 1234, 4, Path::new("/dev/video10"));
make_proc_entry(dir.path(), 1234, 5, Path::new("/dev/video10"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::External { pid: 1234 });
}
#[test]
fn self_pid_only_is_clean_absent() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 9999, 3, Path::new("/dev/video10"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::CleanAbsent);
}
#[test]
fn no_matching_fds_is_clean_absent() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/null"));
make_proc_entry(dir.path(), 1234, 4, Path::new("/dev/video11"));
make_proc_entry(dir.path(), 5678, 3, Path::new("/dev/zero"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::CleanAbsent);
}
#[test]
fn permission_denied_pid_skipped_when_consumer_found() {
let dir = tempfile::tempdir().expect("tempdir");
let unreadable_fd_dir = dir.path().join("1234").join("fd");
fs::create_dir_all(&unreadable_fd_dir).unwrap();
let _restore = ScopeGuard::new({
let p = unreadable_fd_dir.clone();
move || {
let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
}
});
fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();
make_proc_entry(dir.path(), 5678, 3, Path::new("/dev/video10"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::External { pid: 5678 });
}
#[test]
fn all_eacces_no_match_is_uncertain_absent() {
let dir = tempfile::tempdir().expect("tempdir");
let unreadable_fd_dir = dir.path().join("1234").join("fd");
fs::create_dir_all(&unreadable_fd_dir).unwrap();
let _restore = ScopeGuard::new({
let p = unreadable_fd_dir.clone();
move || {
let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
}
});
fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert!(
matches!(
walk,
WalkOutcome::UncertainAbsent {
eacces_count: 1,
..
}
),
"expected UncertainAbsent with one EACCES, got {walk:?}"
);
}
#[test]
fn unreadable_proc_root_is_unreadable() {
let walk =
count_external_consumers(Path::new("/no/such/proc/path"), OsStr::new("video10"), 9999);
assert!(matches!(walk, WalkOutcome::Unreadable(_)), "got {walk:?}");
}
#[test]
fn mixed_self_plus_external_is_external() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 9999, 3, Path::new("/dev/video10"));
make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/video10"));
let walk = count_external_consumers(dir.path(), OsStr::new("video10"), 9999);
assert_eq!(walk, WalkOutcome::External { pid: 1234 });
}
fn uncertain(n: u32) -> WalkOutcome {
WalkOutcome::UncertainAbsent {
eacces_count: n,
pids: Vec::new(),
}
}
#[test]
fn observe_external_is_present_and_floors_balance() {
let mut p = ConsumerPresence::default();
let (s, r) = p.observe(&WalkOutcome::External { pid: 1 }, -5, false);
assert_eq!((s, r), (ConsumerStatus::Present, PresenceReason::External));
assert!(p.open_balance >= 1);
}
#[test]
fn observe_clean_absent_zeroes_balance() {
let mut p = ConsumerPresence { open_balance: 4 };
let (s, r) = p.observe(&WalkOutcome::CleanAbsent, 0, false);
assert_eq!(
(s, r),
(ConsumerStatus::Absent, PresenceReason::CleanAbsent)
);
assert_eq!(p.open_balance, 0);
}
#[test]
fn observe_unreadable_is_failopen_and_keeps_counting() {
let mut p = ConsumerPresence { open_balance: 1 };
let (s, r) = p.observe(&WalkOutcome::Unreadable(io::ErrorKind::NotFound), 1, false);
assert_eq!((s, r), (ConsumerStatus::Unknown, PresenceReason::FailOpen));
assert_eq!(p.open_balance, 2);
}
#[test]
fn observe_uncertain_wakes_on_positive_balance() {
let mut p = ConsumerPresence::default();
let (s, r) = p.observe(&uncertain(1), 1, false);
assert_eq!(
(s, r),
(ConsumerStatus::Present, PresenceReason::UnattributableWake)
);
}
#[test]
fn observe_uncertain_probe_open_then_close_stays_absent() {
let mut p = ConsumerPresence::default();
let (s, r) = p.observe(&uncertain(1), 0, false);
assert_eq!(
(s, r),
(ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
);
}
#[test]
fn observe_uncertain_aux_fd_close_keeps_present() {
let mut p = ConsumerPresence { open_balance: 2 };
let (s, r) = p.observe(&uncertain(1), -1, false);
assert_eq!(
(s, r),
(ConsumerStatus::Present, PresenceReason::UnattributableWake)
);
assert_eq!(p.open_balance, 1);
}
#[test]
fn observe_uncertain_steady_no_open_is_absent() {
let mut p = ConsumerPresence::default();
let (s, r) = p.observe(&uncertain(3), 0, false);
assert_eq!(
(s, r),
(ConsumerStatus::Absent, PresenceReason::UncertainAbsent)
);
}
#[test]
fn observe_overflow_resets_balance_before_deciding() {
let mut p = ConsumerPresence { open_balance: 5 };
let (s, _) = p.observe(&uncertain(1), 3, true);
assert_eq!(s, ConsumerStatus::Absent);
assert_eq!(p.open_balance, 0);
}
#[test]
fn observe_balance_clamps_at_zero() {
let mut p = ConsumerPresence::default();
let (_s, _r) = p.observe(&uncertain(1), -3, false);
assert_eq!(p.open_balance, 0);
}
#[test]
fn read_comms_reads_present_and_skips_missing() {
let dir = tempfile::tempdir().expect("tempdir");
let pid_dir = dir.path().join("1234");
fs::create_dir_all(&pid_dir).unwrap();
fs::write(pid_dir.join("comm"), "chrome\n").unwrap();
assert_eq!(
read_comms(dir.path(), &[1234, 5678]),
vec!["chrome".to_string()]
);
}
fn gates_after_one_walk(proc_root: &Path) -> (bool, bool) {
let running = AtomicBool::new(true);
let status = AtomicU8::new(ConsumerStatus::Unknown.as_u8());
let stopped = AtomicBool::new(false);
let counters = Counters::new();
let device_basename = OsString::from("video10");
let activations = AtomicU64::new(0);
let ctx = DetectorContext {
proc_root,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
my_pid: 9999,
running: &running,
status: &status,
stopped: &stopped,
restat_interval_polls: RESTAT_INTERVAL_POLLS,
device_basename: &device_basename,
counters: &counters,
inotify_activations: &activations,
};
let mut log_once = LogOnce::armed();
let mut last_status = None;
let mut presence = ConsumerPresence::default();
let mut state = DetectorState {
log_once: &mut log_once,
last_status: &mut last_status,
presence: &mut presence,
};
walk_observe_publish(&ctx, &mut state, 0, false);
(
log_once.scan_failed.is_armed(),
log_once.eacces_storm.is_armed(),
)
}
#[test]
fn walk_observe_publish_fires_scan_failed_on_unreadable() {
let (scan_armed, eacces_armed) = gates_after_one_walk(Path::new("/no/such/proc/path"));
assert!(!scan_armed, "Unreadable walk must consume scan_failed");
assert!(eacces_armed, "Unreadable walk must not touch eacces_storm");
}
#[test]
fn walk_observe_publish_fires_eacces_storm_on_uncertain() {
let dir = tempfile::tempdir().expect("tempdir");
let unreadable_fd_dir = dir.path().join("1234").join("fd");
fs::create_dir_all(&unreadable_fd_dir).unwrap();
let _restore = ScopeGuard::new({
let p = unreadable_fd_dir.clone();
move || {
let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
}
});
fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();
let (scan_armed, eacces_armed) = gates_after_one_walk(dir.path());
assert!(
scan_armed,
"UncertainAbsent walk must not touch scan_failed"
);
assert!(
!eacces_armed,
"UncertainAbsent walk must consume eacces_storm"
);
}
#[test]
fn walk_observe_publish_fires_no_gate_on_clean_absent() {
let dir = tempfile::tempdir().expect("tempdir");
make_proc_entry(dir.path(), 1234, 3, Path::new("/dev/null"));
let (scan_armed, eacces_armed) = gates_after_one_walk(dir.path());
assert!(
scan_armed && eacces_armed,
"CleanAbsent must not fire any gate"
);
}
#[test]
fn detector_cycles_through_states_via_fake_proc_polling_fallback() {
let dir = tempfile::tempdir().expect("tempdir");
let proc_root = dir.path().to_path_buf();
fs::write(proc_root.join("self"), "").unwrap();
let running = Arc::new(AtomicBool::new(true));
let activations = Arc::new(AtomicU64::new(0));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: PathBuf::from("/dev/this-device-does-not-exist"),
my_pid: 9999,
poll_interval: Duration::from_millis(20),
mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: proc_root.clone(),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
inotify_activations: Arc::clone(&activations),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
let status = detector.status_handle();
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"empty proc must surface as Absent"
);
make_proc_entry(
&proc_root,
1234,
3,
Path::new("/dev/this-device-does-not-exist"),
);
assert!(
wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
"external pid attaching must surface as Present"
);
fs::remove_dir_all(proc_root.join("1234")).unwrap();
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"external pid detaching must surface as Absent"
);
assert_eq!(
activations.load(Ordering::Acquire),
0,
"inotify path must not activate when add_watch fails"
);
running.store(false, Ordering::Release);
drop(detector);
}
#[test]
fn shutdown_completes_quickly_even_with_long_poll_interval() {
let dir = tempfile::tempdir().expect("tempdir");
let running = Arc::new(AtomicBool::new(true));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: PathBuf::from("/dev/video10"),
my_pid: 9999,
poll_interval: Duration::from_secs(2), mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: dir.path().to_path_buf(),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
inotify_activations: Arc::new(AtomicU64::new(0)),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
thread::sleep(Duration::from_millis(100));
let start = Instant::now();
running.store(false, Ordering::Release);
drop(detector); let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_millis(500),
"shutdown took {elapsed:?} — expected < 500 ms"
);
}
#[test]
fn log_once_gates_fire_once_and_rearm_in_lockstep() {
let mut log = LogOnce::armed();
assert!(log.scan_failed.is_armed());
assert!(log.eacces_storm.is_armed());
assert!(log.scan_failed.fire(), "first fire returns true");
assert!(!log.scan_failed.is_armed(), "gate consumed after fire");
assert!(!log.scan_failed.fire(), "second fire returns false");
assert!(log.eacces_storm.is_armed());
assert!(log.eacces_storm.fire());
assert!(!log.eacces_storm.is_armed());
log.rearm();
assert!(log.scan_failed.is_armed(), "rearm restores scan_failed");
assert!(log.eacces_storm.is_armed(), "rearm restores eacces_storm");
assert!(log.scan_failed.fire(), "re-armed gate is consumable again");
}
#[test]
fn run_detector_rearms_log_flag_at_restat_boundary() {
let running = Arc::new(AtomicBool::new(true));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: PathBuf::from("/dev/video10"),
my_pid: 9999,
poll_interval: Duration::from_millis(20),
mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: PathBuf::from("/no/such/proc/path"),
restat_interval_polls: 1, inotify_activations: Arc::new(AtomicU64::new(0)),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
let status = detector.status_handle();
assert!(
wait_for_status(&status, ConsumerStatus::Unknown, Duration::from_millis(300)),
"missing proc root must surface as Unknown"
);
thread::sleep(Duration::from_millis(200));
assert_eq!(
ConsumerStatus::from_u8(status.load(Ordering::Acquire)),
ConsumerStatus::Unknown,
"worker must keep publishing Unknown across rearm cycles"
);
running.store(false, Ordering::Release);
drop(detector);
}
#[test]
fn inotify_path_fires_on_external_open() {
let proc_dir = tempfile::tempdir().expect("proc tempdir");
let proc_root = proc_dir.path().to_path_buf();
fs::write(proc_root.join("self"), "").unwrap();
let device = tempfile::NamedTempFile::new().expect("device tempfile");
let device_path = device.path().to_path_buf();
make_proc_entry(&proc_root, 1234, 3, &device_path);
let running = Arc::new(AtomicBool::new(true));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: device_path.clone(),
my_pid: 9999,
poll_interval: Duration::from_millis(20),
mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: proc_root.clone(),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
inotify_activations: Arc::new(AtomicU64::new(0)),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
let status = detector.status_handle();
let activations = detector.inotify_activations_handle();
assert!(
wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
"baseline walk must surface synthesised consumer as Present"
);
assert!(
activations.load(Ordering::Acquire) > 0,
"inotify path must have activated (init + add_watch succeeded)"
);
fs::remove_dir_all(proc_root.join("1234")).unwrap();
{
let _f = std::fs::File::open(&device_path).expect("open device");
}
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"event-driven walk must observe the consumer disappearing"
);
make_proc_entry(&proc_root, 5678, 3, &device_path);
{
let _f = std::fs::File::open(&device_path).expect("open device again");
}
assert!(
wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
"event-driven walk must observe the consumer re-attaching"
);
running.store(false, Ordering::Release);
drop(detector);
}
#[test]
fn unattributable_held_open_wakes_via_net_count() {
let proc_dir = tempfile::tempdir().expect("proc tempdir");
let proc_root = proc_dir.path().to_path_buf();
let unreadable_fd_dir = proc_root.join("1234").join("fd");
fs::create_dir_all(&unreadable_fd_dir).unwrap();
let _restore = ScopeGuard::new({
let p = unreadable_fd_dir.clone();
move || {
let _ = fs::set_permissions(&p, fs::Permissions::from_mode(0o700));
}
});
fs::set_permissions(&unreadable_fd_dir, fs::Permissions::from_mode(0o000)).unwrap();
let device = tempfile::NamedTempFile::new().expect("device tempfile");
let device_path = device.path().to_path_buf();
let running = Arc::new(AtomicBool::new(true));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: device_path.clone(),
my_pid: 9999,
poll_interval: Duration::from_millis(20),
mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: proc_root.clone(),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
inotify_activations: Arc::new(AtomicU64::new(0)),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
let status = detector.status_handle();
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"uncertain-absent with zero balance must read Absent"
);
let held = std::fs::File::open(&device_path).expect("open device");
assert!(
wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
"held open on an unattributable consumer must wake to Present"
);
drop(held);
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"closing the held fd must return to Absent"
);
running.store(false, Ordering::Release);
drop(detector);
}
#[test]
fn inotify_watch_removed_falls_back_to_polling() {
let proc_dir = tempfile::tempdir().expect("proc tempdir");
let proc_root = proc_dir.path().to_path_buf();
fs::write(proc_root.join("self"), "").unwrap();
let device = tempfile::NamedTempFile::new().expect("device tempfile");
let device_path = device.path().to_path_buf();
make_proc_entry(&proc_root, 1234, 3, &device_path);
let running = Arc::new(AtomicBool::new(true));
let detector = ConsumerDetector::spawn_with_knobs(
DetectorParams {
device_path: device_path.clone(),
my_pid: 9999,
poll_interval: Duration::from_millis(20),
mode: IdlePresenceSource::Inotify,
stale_balance_after: Duration::from_secs(3600),
teardown_grace: Duration::from_secs(5),
resync_interval: None,
},
DetectorTestKnobs {
proc_root: proc_root.clone(),
restat_interval_polls: RESTAT_INTERVAL_POLLS,
inotify_activations: Arc::new(AtomicU64::new(0)),
},
Arc::clone(&running),
Arc::new(Counters::new()),
None,
);
let status = detector.status_handle();
assert!(
wait_for_status(&status, ConsumerStatus::Present, Duration::from_millis(500)),
"baseline walk must surface synthesised consumer as Present"
);
drop(device); thread::sleep(Duration::from_millis(100));
fs::remove_dir_all(proc_root.join("1234")).unwrap();
assert!(
wait_for_status(&status, ConsumerStatus::Absent, Duration::from_millis(500)),
"polling fallback must observe consumer detach after IN_IGNORED"
);
running.store(false, Ordering::Release);
drop(detector);
}
struct ScopeGuard<F: FnMut()> {
f: Option<F>,
}
impl<F: FnMut()> ScopeGuard<F> {
fn new(f: F) -> Self {
Self { f: Some(f) }
}
}
impl<F: FnMut()> Drop for ScopeGuard<F> {
fn drop(&mut self) {
if let Some(mut f) = self.f.take() {
f();
}
}
}
}