diff --git a/crates/argus-app/src/sampler.rs b/crates/argus-app/src/sampler.rs index 11554bc9..fc5a976a 100644 --- a/crates/argus-app/src/sampler.rs +++ b/crates/argus-app/src/sampler.rs @@ -9,6 +9,7 @@ use std::time::{Duration, Instant}; use crate::channel::Channel; use argus_core::history::{self, HistoryRecorder}; +use argus_core::watch::{WatchAction, WatchError, WatchRecorder, WatchView}; use argus_core::{Collector, Snapshot}; use argus_service::{DiskClient, NetworkClient, RuleRunner, SensorClient}; @@ -66,6 +67,11 @@ pub enum Control { /// Deletes the history in this folder; replies once the files are gone. /// Goes through this thread so no frame is being written meanwhile. ClearHistory(PathBuf, Sender>), + Watch( + PathBuf, + WatchAction, + Sender, WatchError>>, + ), } pub struct Sampler { @@ -204,6 +210,7 @@ impl Sampler { let mut subscriber: Option> = None; let mut window: Option = None; let mut history: Option = None; + let mut watch: Option = None; let mut interval = DEFAULT_INTERVAL; let mut minimized = BACKGROUND_INTERVAL; let mut tray = BACKGROUND_INTERVAL; @@ -255,11 +262,32 @@ impl Sampler { history = dir.map(HistoryRecorder::new); continue; } + Ok(Control::Watch(dir, action, reply)) => { + let result = if let Some(recorder) = &mut watch { + recorder.action(action) + } else if matches!(action, WatchAction::Delete) { + WatchRecorder::delete_saved(&dir).map(|()| None) + } else { + WatchRecorder::open(dir).and_then(|mut recorder| { + let result = recorder.action(action); + watch = Some(recorder); + result + }) + }; + let _ = reply.send(result); + continue; + } Ok(Control::ClearHistory(dir, reply)) => { - let result = match &mut history { - Some(recorder) => recorder.clear(), - None => history::clear(&dir), + let observed = match &mut watch { + Some(recorder) => recorder.action(WatchAction::Delete).map(|_| ()), + None => WatchRecorder::delete_saved(&dir), }; + let result = observed + .map_err(|_| io::Error::other("process observation cleanup failed")) + .and_then(|()| match &mut history { + Some(recorder) => recorder.clear(), + None => history::clear(&dir), + }); let _ = reply.send(result); continue; } @@ -296,6 +324,14 @@ impl Sampler { if let Some(recorder) = &mut history { recorder.record(&snapshot); } + if let Some(recorder) = &mut watch + && recorder.record(&snapshot).is_err() + { + argus_core::diagnostics::warn( + "process observation", + "recording interrupted", + ); + } // A paused view stays as it is, except right after an action. let send = publish_refresh(&mut owed, collector.process_sample_started()) || !paused; diff --git a/crates/argus-app/tests/process_watch.rs b/crates/argus-app/tests/process_watch.rs new file mode 100644 index 00000000..cde1267f --- /dev/null +++ b/crates/argus-app/tests/process_watch.rs @@ -0,0 +1,148 @@ +//! Real sampler integration; only observes this test process and writes its own temp folder. +use argus_app::{ + channel::Channel, + sampler::{Control, Sampler}, +}; +use argus_core::{ + Collector, MetaStore, + watch::{WatchAction, WatchError, WatchMode, WatchRecorder, WatchState, WatchView}, +}; +use std::sync::{Arc, mpsc}; +use std::time::Duration; + +fn request( + sampler: &Sampler, + dir: &std::path::Path, + action: WatchAction, +) -> Result, WatchError> { + let (tx, rx) = mpsc::channel(); + sampler.send(Control::Watch(dir.to_owned(), action, tx)); + rx.recv_timeout(Duration::from_secs(15)).unwrap() +} + +#[test] +#[ignore = "real Windows collector integration, run explicitly with --ignored"] +fn observes_and_deletes_through_the_real_sampler() { + let dir = std::env::temp_dir().join(format!("argus-sampler-watch-{}", std::process::id())); + let rules = Arc::new(argus_service::RuleRunner::spawn(false)); + // No rules are installed and no service operations or system settings are changed. + let sampler = Sampler::spawn(|| Collector::new(MetaStore::new()), rules); + let (tx, rx) = mpsc::channel(); + sampler.send(Control::Subscribe(Channel::new(move |snapshot| { + tx.send(snapshot)?; + Ok(()) + }))); + let snapshot = rx.recv_timeout(Duration::from_secs(30)).unwrap(); + let own = snapshot + .processes + .iter() + .find(|p| p.pid == std::process::id()) + .unwrap(); + let start = WatchAction::Start { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-test".into(), + }; + request(&sampler, &dir, start).unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + let _ = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let view = request(&sampler, &dir, WatchAction::Status) + .unwrap() + .unwrap(); + if view.points.iter().any(|point| point.memory.is_some()) { + break; + } + assert!( + std::time::Instant::now() < deadline, + "no valid observation through sampler" + ); + } + assert_eq!( + request(&sampler, &dir, WatchAction::Stop) + .unwrap() + .unwrap() + .state, + WatchState::Stopped + ); + assert!( + request(&sampler, &dir, WatchAction::Delete) + .unwrap() + .is_none() + ); + assert!(!dir.join("process-watch.jsonl").exists()); + request( + &sampler, + &dir, + WatchAction::Start { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-test".into(), + }, + ) + .unwrap(); + let (clear_tx, clear_rx) = mpsc::channel(); + sampler.send(Control::ClearHistory(dir.clone(), clear_tx)); + clear_rx + .recv_timeout(Duration::from_secs(15)) + .unwrap() + .unwrap(); + assert!( + request(&sampler, &dir, WatchAction::Status) + .unwrap() + .is_none() + ); + request( + &sampler, + &dir, + WatchAction::StartProgram { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-program".into(), + }, + ) + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(15); + loop { + let _ = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + let view = request(&sampler, &dir, WatchAction::Status) + .unwrap() + .unwrap(); + assert_eq!(view.mode, WatchMode::Program); + if view.points.iter().any(|point| point.memory.is_some()) { + break; + } + assert!(std::time::Instant::now() < deadline); + } + let stopped = request(&sampler, &dir, WatchAction::Stop).unwrap().unwrap(); + assert_eq!(stopped.state, WatchState::Stopped); + assert_eq!(stopped.live_runs, 0); + assert!(WatchRecorder::storage_bytes(&dir) > 0); + request(&sampler, &dir, WatchAction::Delete).unwrap(); + assert_eq!(WatchRecorder::storage_bytes(&dir), 0); + request( + &sampler, + &dir, + WatchAction::StartProgram { + pid: own.pid, + create_time: own.create_time, + name: "sampler-owned-program".into(), + }, + ) + .unwrap(); + let (clear_tx, clear_rx) = mpsc::channel(); + sampler.send(Control::ClearHistory(dir.clone(), clear_tx)); + clear_rx + .recv_timeout(Duration::from_secs(15)) + .unwrap() + .unwrap(); + assert!( + request(&sampler, &dir, WatchAction::Status) + .unwrap() + .is_none() + ); + assert_eq!(WatchRecorder::storage_bytes(&dir), 0); + drop(sampler); + drop(rx); + std::fs::remove_dir(dir).unwrap(); +} diff --git a/crates/argus-core/examples/process_watch.rs b/crates/argus-core/examples/process_watch.rs new file mode 100644 index 00000000..d349e508 --- /dev/null +++ b/crates/argus-core/examples/process_watch.rs @@ -0,0 +1,242 @@ +//! Controlled real-memory observation. Only owns helper processes and a temporary folder. +//! cargo run -p argus-core --example process_watch --release +use argus_core::{ + Collector, MetaStore, + history::{self, HistoryRecorder}, + watch::{WatchAction, WatchRecorder, WatchState}, +}; +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::os::windows::{io::AsRawHandle, process::CommandExt}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::time::{Duration, Instant}; +use windows::Win32::{ + Foundation::HANDLE, + System::{ + Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree}, + Threading::GetProcessTimes, + }, +}; + +fn helper(competitor: bool) { + let running = Arc::new(AtomicBool::new(true)); + let worker = competitor.then(|| { + let running = running.clone(); + std::thread::spawn(move || { + let mut value = 1u64; + while running.load(Ordering::Relaxed) { + for _ in 0..10_000 { + value = + std::hint::black_box(value.wrapping_mul(1664525).wrapping_add(1013904223)); + } + } + value + }) + }); + let mut allocation: *mut std::ffi::c_void = std::ptr::null_mut(); + println!("ready"); + for line in std::io::stdin().lock().lines() { + let line = line.unwrap(); + if !allocation.is_null() { + unsafe { VirtualFree(allocation, 0, MEM_RELEASE) }.unwrap(); + allocation = std::ptr::null_mut(); + } + if line == "exit" { + break; + } + let mib: usize = line.parse().unwrap(); + if mib > 0 { + let size = mib * 1024 * 1024; + allocation = + unsafe { VirtualAlloc(None, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!allocation.is_null()); + for offset in (0..size).step_by(4096) { + unsafe { std::ptr::write_volatile(allocation.cast::().add(offset), 1) }; + } + } + println!("allocated {mib}"); + } + if !allocation.is_null() { + unsafe { VirtualFree(allocation, 0, MEM_RELEASE) }.unwrap(); + } + running.store(false, Ordering::Relaxed); + if let Some(worker) = worker { + worker.join().unwrap(); + } +} + +struct Helper { + child: Child, + input: Option, + output: BufReader, +} +impl Helper { + fn spawn(mode: &str) -> Self { + let mut child = Command::new(std::env::current_exe().unwrap()) + .arg(mode) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let input = child.stdin.take(); + let output = BufReader::new(child.stdout.take().unwrap()); + let mut helper = Self { + child, + input, + output, + }; + let mut ready = String::new(); + helper.output.read_line(&mut ready).unwrap(); + assert_eq!(ready.trim(), "ready"); + helper + } + fn memory(&mut self, mib: usize) { + writeln!(self.input.as_mut().unwrap(), "{mib}").unwrap(); + let mut reply = String::new(); + self.output.read_line(&mut reply).unwrap(); + assert_eq!(reply.trim(), format!("allocated {mib}")); + } + fn creation(&self) -> i64 { + let (mut c, mut e, mut k, mut u) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(self.child.as_raw_handle()), + &mut c, + &mut e, + &mut k, + &mut u, + ) + } + .unwrap(); + let ticks = ((c.dwHighDateTime as u64) << 32) | c.dwLowDateTime as u64; + (ticks / 10000) as i64 - 11_644_473_600_000 + } + fn exit(&mut self) { + if let Some(mut input) = self.input.take() { + writeln!(input, "exit").unwrap(); + drop(input); + } + assert!(self.child.wait().unwrap().success()); + } +} +impl Drop for Helper { + fn drop(&mut self) { + self.input = None; + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if self.child.try_wait().ok().flatten().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn main() { + match std::env::args().nth(1).as_deref() { + Some("memory-helper") => return helper(false), + Some("competitor") => return helper(true), + _ => {} + } + let dir = std::env::temp_dir().join(format!("argus-watch-real-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + let mut target = Helper::spawn("memory-helper"); + let mut competitor = Helper::spawn("competitor"); + let pid = target.child.id(); + let competitor_pid = competitor.child.id(); + let created = target.creation(); + let mut collector = Collector::new(MetaStore::new()); + let mut history = HistoryRecorder::new(dir.clone()); + let mut recorder = WatchRecorder::open(dir.clone()).unwrap(); + recorder + .action(WatchAction::Start { + pid, + create_time: created, + name: "controlled-memory-helper".into(), + }) + .unwrap(); + let mut times = Vec::new(); + let mut ranges = Vec::new(); + for mib in [4, 12, 2] { + target.memory(mib); + println!("phase {mib} MiB: sampling real process for 7 seconds"); + let mut last = None; + for _ in 0..7 { + std::thread::sleep(Duration::from_secs(1)); + let snapshot = collector.sample(); + last = Some(snapshot.timestamp); + history.record(&snapshot); + let t = Instant::now(); + recorder.record(&snapshot).unwrap(); + times.push(t.elapsed().as_micros()); + } + let view = recorder.view().unwrap(); + let point = view + .points + .iter() + .rev() + .find(|p| p.memory.is_some()) + .unwrap(); + ranges.push((mib, point.memory.unwrap(), point.commit.unwrap())); + if mib == 12 { + println!("controlled sampling pause: 11 seconds (creates an explicit gap)"); + std::thread::sleep(Duration::from_secs(11)); + } + if mib == 2 { + let snapshot = collector.sample(); + history.record(&snapshot); + let moment = history::moment(&dir, last.unwrap() - 5000).unwrap(); + assert!( + !moment.processes.iter().any(|p| p.pid == pid), + "watched helper unexpectedly entered the overall top" + ); + assert!( + moment.processes.iter().any(|p| p.pid == competitor_pid), + "controlled CPU competitor missing from top" + ); + } + } + assert!(ranges[1].1 > ranges[0].1 + 4 * 1024 * 1024); + assert!(ranges[1].2 > ranges[0].2 + 4 * 1024 * 1024); + assert!(ranges[2].1 + 4 * 1024 * 1024 < ranges[1].1); + assert!(ranges[2].2 + 4 * 1024 * 1024 < ranges[1].2); + target.exit(); + std::thread::sleep(Duration::from_millis(100)); + recorder.record(&collector.sample()).unwrap(); + let view = recorder.view().unwrap(); + assert_eq!(view.state, WatchState::Exited); + if let Some(path) = std::env::args().nth(1) { + fs::write(path, serde_json::to_vec_pretty(&view).unwrap()).unwrap(); + } + assert!(view.points.iter().any(|p| p.state == WatchState::Gap)); + assert!( + recorder + .action(WatchAction::Start { + pid: competitor_pid, + create_time: competitor.creation(), + name: "other-run".into() + }) + .is_err() + ); + recorder.action(WatchAction::Stop).unwrap(); + recorder.action(WatchAction::Delete).unwrap(); + assert!(recorder.view().is_none()); + assert!(!dir.join("process-watch.jsonl").exists()); + competitor.exit(); + drop(history); + drop(recorder); + fs::remove_dir_all(&dir).unwrap(); + println!( + "PASS: private WS and commit grew/released; target below top; competitor in top; explicit gap; exact-instance exit; stop/delete; no replacement attached." + ); + println!("memory phases (MiB requested, private WS bytes, private commit bytes): {ranges:?}"); + times.sort(); + println!("watch record time us (dev/release per invocation): {times:?}"); +} diff --git a/crates/argus-core/src/lib.rs b/crates/argus-core/src/lib.rs index cfdc56ff..29c18988 100644 --- a/crates/argus-core/src/lib.rs +++ b/crates/argus-core/src/lib.rs @@ -35,6 +35,7 @@ pub mod startup; pub mod system; pub mod theme; mod util; +pub mod watch; mod webview; pub use collector::{Collector, Snapshot}; diff --git a/crates/argus-core/src/process.rs b/crates/argus-core/src/process.rs index 2402d2b2..414f5328 100644 --- a/crates/argus-core/src/process.rs +++ b/crates/argus-core/src/process.rs @@ -861,6 +861,13 @@ pub(crate) fn list_lineage() -> Vec<(u32, u32, i64)> { #[cfg(test)] mod tests { + #[test] + #[ignore = "owned child fixture for watch identity and launch regressions"] + fn liveness_child() { + use std::io::Read; + let _ = std::io::stdin().read(&mut [0u8]); + } + #[test] fn pending_queries_keep_recent_readings_but_expire_a_stuck_source() { let at = std::time::Instant::now(); diff --git a/crates/argus-core/src/watch.rs b/crates/argus-core/src/watch.rs new file mode 100644 index 00000000..f0b03239 --- /dev/null +++ b/crates/argus-core/src/watch.rs @@ -0,0 +1,750 @@ +//! Explicit, bounded observation of an instance or program, independent of top lists. +//! Local versioned storage. A closed observation is never resumed implicitly. +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use crate::{Snapshot, util::OwnedHandle}; +use serde::{Deserialize, Serialize}; +use windows::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows::Win32::System::Threading::WaitForSingleObject; +mod identity; +mod program; +mod store; +pub use identity::ProgramIdentity; +pub use store::{ + CAPACITY as PROGRAM_CAPACITY, MAX_BYTES as PROGRAM_MAX_BYTES, + RETENTION_MS as PROGRAM_RETENTION_MS, +}; + +pub const SAMPLE_MS: i64 = 5_000; +pub const MAX_POINTS: usize = 720; +pub const MAX_BYTES: u64 = 1 << 20; +const FILE_NAME: &str = "process-watch.jsonl"; + +#[derive(Clone, Debug, Deserialize)] +#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)] +pub enum WatchAction { + Start { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + name: String, + }, + StartProgram { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + name: String, + }, + SelectRun { + pid: u32, + #[serde(rename = "createTime")] + create_time: i64, + }, + Page { + before: Option, + }, + Runs { + offset: usize, + }, + Status, + Stop, + Delete, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WatchState { + Recording, + Gap, + Exited, + Stopped, + Interrupted, + Limit, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchPoint { + pub ts: i64, + pub memory: Option, + pub commit: Option, + pub state: WatchState, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum WatchMode { + #[default] + Instance, + Program, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchRun { + pub pid: u32, + pub create_time: i64, + pub first_ts: i64, + pub last_ts: i64, + pub points: usize, + pub state: WatchState, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WatchView { + pub version: u32, + pub pid: u32, + pub create_time: i64, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub program: Option, + #[serde(default)] + pub mode: WatchMode, + #[serde(default)] + pub runs: Vec, + #[serde(default)] + pub total_runs: usize, + #[serde(default)] + pub total_points: usize, + #[serde(default)] + pub damaged: bool, + #[serde(default)] + pub first_sequence: Option, + #[serde(default)] + pub has_earlier: bool, + #[serde(default)] + pub has_later: bool, + #[serde(default)] + pub run_offset: usize, + #[serde(default)] + pub live_runs: usize, + #[serde(default)] + pub unconfirmed: usize, + pub state: WatchState, + pub points: Vec, +} + +#[derive(Debug)] +pub enum WatchError { + Identity, + Access, + Existing, + Missing, + Storage, + Invalid, +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +enum Record { + Header { + version: u32, + pid: u32, + created: i64, + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + program: Option, + }, + Point(WatchPoint), +} + +pub struct WatchRecorder { + dir: PathBuf, + program_watch: Option, + view: Option, + handle: Option, + file: Option, + bytes: u64, + started: Option, + last: Option, +} + +impl WatchRecorder { + pub fn storage_bytes(dir: &std::path::Path) -> u64 { + [FILE_NAME, store::FILE_NAME] + .iter() + .map(|name| fs::metadata(dir.join(name)).map_or(0, |meta| meta.len())) + .sum() + } + pub fn delete_saved(dir: &std::path::Path) -> Result<(), WatchError> { + for name in [FILE_NAME, store::FILE_NAME] { + match fs::remove_file(dir.join(name)) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(WatchError::Storage), + } + } + Ok(()) + } + + pub fn open(dir: PathBuf) -> Result { + let mut recorder = Self { + dir, + program_watch: None, + view: None, + handle: None, + file: None, + bytes: 0, + started: None, + last: None, + }; + let path = recorder.dir.join(FILE_NAME); + if recorder + .dir + .join(store::FILE_NAME) + .try_exists() + .map_err(|_| WatchError::Storage)? + { + if path.try_exists().map_err(|_| WatchError::Storage)? { + return Err(WatchError::Existing); + } + recorder.program_watch = Some(program::ProgramWatch::open(&recorder.dir)?); + return Ok(recorder); + } + let bytes = match File::open(&path) { + Ok(file) => { + let mut bytes = Vec::new(); + file.take(MAX_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| WatchError::Storage)?; + if bytes.len() as u64 > MAX_BYTES { + return Err(WatchError::Invalid); + } + bytes + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(recorder), + Err(_) => return Err(WatchError::Storage), + }; + let mut lines = bytes.split(|b| *b == b'\n'); + let header: Record = serde_json::from_slice(lines.next().ok_or(WatchError::Invalid)?) + .map_err(|_| WatchError::Invalid)?; + let Record::Header { + version, + pid, + created, + name, + program, + } = header + else { + return Err(WatchError::Invalid); + }; + if !matches!(version, 1 | 2) || program.as_ref().is_some_and(|program| !program.valid()) { + return Err(WatchError::Invalid); + } + let mut view = WatchView { + version, + pid, + create_time: created, + name, + program, + mode: WatchMode::Instance, + runs: Vec::new(), + total_runs: 0, + total_points: 0, + damaged: false, + first_sequence: None, + has_earlier: false, + has_later: false, + run_offset: 0, + live_runs: 0, + unconfirmed: 0, + state: WatchState::Interrupted, + points: Vec::new(), + }; + let mut damaged = false; + for line in lines.filter(|line| !line.is_empty()) { + let Ok(Record::Point(point)) = serde_json::from_slice(line) else { + damaged = true; + break; + }; + if view.points.len() > MAX_POINTS { + return Err(WatchError::Invalid); + } + view.state = point.state; + view.points.push(point); + } + if damaged || matches!(view.state, WatchState::Recording | WatchState::Gap) { + view.state = WatchState::Interrupted; + } + recorder.bytes = bytes.len() as u64; + recorder.view = Some(view); + Ok(recorder) + } + + pub fn view(&self) -> Option { + self.program_watch + .as_ref() + .map(program::ProgramWatch::view) + .or_else(|| { + self.view.clone().map(|mut view| { + view.live_runs = usize::from(self.handle.is_some()); + view.total_runs = 1; + view.total_points = view.points.len(); + view + }) + }) + } + + pub fn action(&mut self, action: WatchAction) -> Result, WatchError> { + match action { + WatchAction::Status => {} + WatchAction::Start { + pid, + create_time, + name, + } => { + if self.view.is_some() || self.program_watch.is_some() { + return Err(WatchError::Existing); + } + if pid == 0 || create_time <= 0 || name.is_empty() || name.len() > 1024 { + return Err(WatchError::Identity); + } + let instance = identity::Instance::open(pid, create_time)?; + // Image identity is optional for a single-run observation. + let program = instance.program().ok(); + let handle = instance.into_handle(); + fs::create_dir_all(&self.dir).map_err(|_| WatchError::Storage)?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(self.dir.join(FILE_NAME)) + .map_err(|_| WatchError::Storage)?; + let mut header = serde_json::to_vec(&Record::Header { + version: 2, + pid, + created: create_time, + name: name.clone(), + program: program.clone(), + }) + .map_err(|_| WatchError::Storage)?; + header.push(b'\n'); + if file.write_all(&header).and_then(|()| file.flush()).is_err() { + drop(file); + let _ = fs::remove_file(self.dir.join(FILE_NAME)); + return Err(WatchError::Storage); + } + self.bytes = header.len() as u64; + self.file = Some(file); + self.handle = Some(handle); + self.started = Some(Instant::now()); + self.last = None; + self.view = Some(WatchView { + version: 2, + pid, + create_time, + name, + program, + mode: WatchMode::Instance, + runs: Vec::new(), + total_runs: 0, + total_points: 0, + damaged: false, + first_sequence: None, + has_earlier: false, + has_later: false, + run_offset: 0, + live_runs: 1, + unconfirmed: 0, + state: WatchState::Recording, + points: Vec::new(), + }); + } + WatchAction::StartProgram { + pid, + create_time, + name, + } => { + if self.view.is_some() || self.program_watch.is_some() { + return Err(WatchError::Existing); + } + if name.is_empty() || name.len() > 1024 { + return Err(WatchError::Identity); + } + self.program_watch = Some(program::ProgramWatch::start( + &self.dir, + pid, + create_time, + name, + )?); + } + WatchAction::SelectRun { pid, create_time } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .select(pid, create_time)?; + } + WatchAction::Page { before } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .page(before)?; + } + WatchAction::Runs { offset } => { + self.program_watch + .as_mut() + .ok_or(WatchError::Missing)? + .runs_page(offset); + } + WatchAction::Stop => { + if let Some(program) = &mut self.program_watch { + program.stop(WatchState::Stopped, now_ms())?; + return Ok(self.view()); + } + if self.view.is_none() { + return Err(WatchError::Missing); + } + if self.file.is_some() { + self.finish(WatchState::Stopped, now_ms())?; + } + } + WatchAction::Delete => { + self.program_watch = None; + self.file = None; + self.handle = None; + if Self::delete_saved(&self.dir).is_err() { + if let Some(view) = &mut self.view { + view.state = WatchState::Interrupted; + } + return Err(WatchError::Storage); + } + self.view = None; + self.started = None; + self.last = None; + self.bytes = 0; + } + } + Ok(self.view()) + } + + pub fn record(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if let Some(program) = &mut self.program_watch { + return program.record(snapshot); + } + let result = self.record_sample(snapshot); + if result.is_err() { + self.file = None; + self.handle = None; + if let Some(view) = &mut self.view { + view.state = WatchState::Interrupted; + } + } + result + } + + fn record_sample(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + let Some(handle) = &self.handle else { + return Ok(()); + }; + match unsafe { WaitForSingleObject(handle.0, 0) } { + WAIT_OBJECT_0 => return self.finish(WatchState::Exited, snapshot.timestamp), + WAIT_TIMEOUT => {} + _ => return self.finish(WatchState::Interrupted, snapshot.timestamp), + } + if self + .started + .is_some_and(|start| start.elapsed() >= Duration::from_secs(3600)) + || self + .view + .as_ref() + .is_some_and(|view| view.points.len() >= MAX_POINTS) + { + return self.finish(WatchState::Limit, snapshot.timestamp); + } + if self + .last + .is_some_and(|last| last.elapsed() < Duration::from_millis(SAMPLE_MS as u64)) + { + return Ok(()); + } + let view = self.view.as_ref().ok_or(WatchError::Missing)?; + if let Some(previous) = view.points.last() { + if snapshot.timestamp < previous.ts { + return self.finish(WatchState::Interrupted, previous.ts); + } + if snapshot.timestamp - previous.ts > SAMPLE_MS * 2 { + let missing = previous.ts + SAMPLE_MS; + self.push(WatchPoint { + ts: missing, + memory: None, + commit: None, + state: WatchState::Gap, + })?; + if self.handle.is_none() { + return Ok(()); + } + } + } + let view = self.view.as_ref().ok_or(WatchError::Missing)?; + let row = snapshot.processes.iter().find(|p| { + p.pid == view.pid + && p.create_time == view.create_time + && !p.stale + && !p.sample_reused + && !p.counters_pending + }); + let point = WatchPoint { + ts: snapshot.timestamp, + memory: row.map(|p| p.private_ws), + commit: row.map(|p| p.commit), + state: if row.is_some() { + WatchState::Recording + } else { + WatchState::Gap + }, + }; + self.push(point)?; + self.last = Some(Instant::now()); + Ok(()) + } + + fn push(&mut self, point: WatchPoint) -> Result<(), WatchError> { + if matches!(point.state, WatchState::Recording | WatchState::Gap) + && self + .view + .as_ref() + .is_some_and(|view| view.points.len() >= MAX_POINTS) + { + return self.finish(WatchState::Limit, point.ts); + } + let mut bytes = + serde_json::to_vec(&Record::Point(point.clone())).map_err(|_| WatchError::Storage)?; + bytes.push(b'\n'); + if self.bytes + bytes.len() as u64 > MAX_BYTES - 512 + && matches!(point.state, WatchState::Recording | WatchState::Gap) + { + return self.finish(WatchState::Limit, point.ts); + } + if self.bytes + bytes.len() as u64 > MAX_BYTES { + return Err(WatchError::Storage); + } + self.file + .as_mut() + .ok_or(WatchError::Storage)? + .write_all(&bytes) + .map_err(|_| WatchError::Storage)?; + self.bytes += bytes.len() as u64; + let view = self.view.as_mut().ok_or(WatchError::Missing)?; + view.state = point.state; + view.points.push(point); + Ok(()) + } + + fn finish(&mut self, state: WatchState, ts: i64) -> Result<(), WatchError> { + let result = self.push(WatchPoint { + ts, + memory: None, + commit: None, + state, + }); + self.file = None; + self.handle = None; + self.started = None; + if let Some(view) = &mut self.view { + view.state = if result.is_ok() { + state + } else { + WatchState::Interrupted + }; + } + result + } +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ProcessRow; + use crate::util::{filetime_ticks, ticks_to_unix_ms}; + use windows::Win32::System::Threading::{ + GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, + }; + + fn own_start() -> WatchAction { + let handle = OwnedHandle( + unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, std::process::id()) } + .unwrap(), + ); + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { GetProcessTimes(handle.0, &mut created, &mut exited, &mut kernel, &mut user) } + .unwrap(); + WatchAction::Start { + pid: std::process::id(), + create_time: ticks_to_unix_ms(filetime_ticks(created)), + name: "owned-helper.exe".into(), + } + } + + fn folder(tag: &str) -> PathBuf { + std::env::temp_dir().join(format!("argus-watch-{tag}-{}", std::process::id())) + } + fn sample(view: &WatchView) -> Snapshot { + Snapshot { + seq: 1, + timestamp: now_ms(), + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: vec![ProcessRow { + pid: view.pid, + create_time: view.create_time, + private_ws: 1024, + commit: 8192, + ..Default::default() + }], + } + } + + #[test] + fn legacy_observation_has_no_invented_program_identity_and_is_not_rewritten() { + let dir = folder("legacy-program"); + fs::create_dir(&dir).unwrap(); + let header = + b"{\"kind\":\"header\",\"version\":1,\"pid\":42,\"created\":1,\"name\":\"same.exe\"}\n"; + fs::write(dir.join(FILE_NAME), header).unwrap(); + let recorder = WatchRecorder::open(dir.clone()).unwrap(); + let view = recorder.view().unwrap(); + assert_eq!(view.version, 1); + assert!(view.program.is_none()); + assert_eq!(fs::read(dir.join(FILE_NAME)).unwrap(), header); + WatchRecorder::delete_saved(&dir).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn observes_below_top_and_never_attaches_to_a_replacement() { + let dir = folder("identity"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + assert!( + rec.view() + .unwrap() + .program + .as_ref() + .is_some_and(ProgramIdentity::valid) + ); + let mut snapshot = sample(&rec.view().unwrap()); + for pid in 100000..100100 { + snapshot.processes.push(ProcessRow { + pid, + private_ws: 1 << 30, + ..Default::default() + }); + } + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().points[0].memory, Some(1024)); + rec.last = None; + snapshot.processes[0].create_time += 1; + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().points[1].state, WatchState::Gap); + assert_eq!(rec.view().unwrap().points[1].memory, None); + rec.action(WatchAction::Stop).unwrap(); + let mut reopened = WatchRecorder::open(dir.clone()).unwrap(); + assert_eq!(reopened.view().unwrap().state, WatchState::Stopped); + assert!(matches!( + reopened.action(own_start()), + Err(WatchError::Existing) + )); + reopened.action(WatchAction::Delete).unwrap(); + assert!(!dir.join(FILE_NAME).exists()); + assert!(reopened.view().is_none()); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn restart_is_interrupted_and_storage_is_bounded() { + let dir = folder("bounded"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + let snapshot = sample(&rec.view().unwrap()); + rec.record(&snapshot).unwrap(); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Interrupted + ); + for _ in 1..=MAX_POINTS { + rec.last = None; + rec.record(&snapshot).unwrap(); + } + assert_eq!(rec.view().unwrap().state, WatchState::Limit); + assert!(fs::metadata(dir.join(FILE_NAME)).unwrap().len() <= MAX_BYTES); + assert!(rec.handle.is_none()); + rec.action(WatchAction::Delete).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn torn_or_oversized_records_are_bounded_and_can_be_deleted() { + let dir = folder("corrupt"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + rec.record(&sample(&rec.view().unwrap())).unwrap(); + rec.action(WatchAction::Stop).unwrap(); + OpenOptions::new() + .append(true) + .open(dir.join(FILE_NAME)) + .unwrap() + .write_all(b"{\"kind\":") + .unwrap(); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Interrupted + ); + WatchRecorder::delete_saved(&dir).unwrap(); + let file = File::create(dir.join(FILE_NAME)).unwrap(); + file.set_len(MAX_BYTES + 1).unwrap(); + drop(file); + assert!(matches!( + WatchRecorder::open(dir.clone()), + Err(WatchError::Invalid) + )); + WatchRecorder::delete_saved(&dir).unwrap(); + fs::remove_dir(dir).unwrap(); + } + + #[test] + fn gaps_at_the_quota_boundary_remain_readable() { + let dir = folder("gap-quota"); + let mut rec = WatchRecorder::open(dir.clone()).unwrap(); + rec.action(own_start()).unwrap(); + let mut snapshot = sample(&rec.view().unwrap()); + for _ in 0..MAX_POINTS - 1 { + rec.last = None; + rec.record(&snapshot).unwrap(); + } + snapshot.timestamp += 60_000; + rec.last = None; + rec.record(&snapshot).unwrap(); + assert_eq!(rec.view().unwrap().state, WatchState::Limit); + assert!(rec.view().unwrap().points.len() <= MAX_POINTS + 1); + assert_eq!( + WatchRecorder::open(dir.clone()) + .unwrap() + .view() + .unwrap() + .state, + WatchState::Limit + ); + rec.action(WatchAction::Delete).unwrap(); + fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/identity.rs b/crates/argus-core/src/watch/identity.rs new file mode 100644 index 00000000..da0ba9d7 --- /dev/null +++ b/crates/argus-core/src/watch/identity.rs @@ -0,0 +1,200 @@ +//! A watched program is identified from the validated process handle, never a UI label. +use super::WatchError; +use crate::util::{OwnedHandle, filetime_ticks, ticks_to_unix_ms}; +use serde::{Deserialize, Serialize}; +use windows::{ + Win32::{ + Foundation::{FILETIME, WAIT_TIMEOUT}, + System::Threading::{ + GetProcessTimes, OpenProcess, PROCESS_NAME_FORMAT, PROCESS_NAME_NATIVE, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, QueryFullProcessImageNameW, + WaitForSingleObject, + }, + }, + core::PWSTR, +}; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProgramIdentity { + /// The native image path avoids conflating two executables with the same basename. + pub native_path: String, + pub display_path: String, +} + +impl ProgramIdentity { + pub fn valid(&self) -> bool { + [&self.native_path, &self.display_path].iter().all(|path| { + !path.is_empty() && path.encode_utf16().count() < 32768 && !path.contains('\0') + }) + } + + /// Exact native identity is deliberately conservative around case-sensitive directories. + pub fn same_program(&self, other: &Self) -> bool { + self.native_path == other.native_path + } +} + +pub(super) struct Instance { + handle: OwnedHandle, +} + +fn error(error: windows::core::Error) -> WatchError { + match error.code().0 as u32 { + 0x80070005 => WatchError::Access, + _ => WatchError::Identity, + } +} + +impl Instance { + pub(super) fn open(pid: u32, created: i64) -> Result { + if pid == 0 || created <= 0 { + return Err(WatchError::Identity); + } + let handle = OwnedHandle( + unsafe { + OpenProcess( + PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE, + false, + pid, + ) + } + .map_err(error)?, + ); + let (mut birth, mut exited, mut kernel, mut user) = Default::default(); + unsafe { GetProcessTimes(handle.0, &mut birth, &mut exited, &mut kernel, &mut user) } + .map_err(error)?; + let birth: FILETIME = birth; + if ticks_to_unix_ms(filetime_ticks(birth)) != created + || unsafe { WaitForSingleObject(handle.0, 0) } != WAIT_TIMEOUT + { + return Err(WatchError::Identity); + } + Ok(Self { handle }) + } + + pub(super) fn program(&self) -> Result { + fn image(handle: &OwnedHandle, flags: PROCESS_NAME_FORMAT) -> Result { + let mut buffer = vec![0u16; 32768]; + let mut length = buffer.len() as u32; + unsafe { + QueryFullProcessImageNameW(handle.0, flags, PWSTR(buffer.as_mut_ptr()), &mut length) + } + .map_err(error)?; + String::from_utf16(&buffer[..length as usize]).map_err(|_| WatchError::Identity) + } + let identity = ProgramIdentity { + native_path: image(&self.handle, PROCESS_NAME_NATIVE)?, + display_path: image(&self.handle, PROCESS_NAME_FORMAT(0))?, + }; + if !identity.valid() || unsafe { WaitForSingleObject(self.handle.0, 0) } != WAIT_TIMEOUT { + return Err(WatchError::Identity); + } + Ok(identity) + } + + pub(super) fn into_handle(self) -> OwnedHandle { + self.handle + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn names_and_case_sensitive_paths_are_not_program_identity() { + let identity = |path: &str| ProgramIdentity { + native_path: path.into(), + display_path: String::new(), + }; + assert!( + !identity("\\Device\\disk\\one\\same.exe") + .same_program(&identity("\\Device\\disk\\two\\same.exe")) + ); + assert!( + !identity("\\Device\\disk\\Folder\\same.exe") + .same_program(&identity("\\Device\\disk\\folder\\same.exe")) + ); + assert!(Instance::open(std::process::id(), 0).is_err()); + } + + #[test] + #[ignore = "owned hidden child images in two temporary folders; run explicitly"] + fn two_copies_stay_distinct_and_restarting_the_same_copy_keeps_program_identity() { + use std::{ + os::windows::{io::AsRawHandle, process::CommandExt}, + process::{Child, Command, Stdio}, + }; + use windows::Win32::Foundation::HANDLE; + fn birth(child: &Child) -> i64 { + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(child.as_raw_handle()), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + } + .unwrap(); + ticks_to_unix_ms(filetime_ticks(created)) + } + fn start(path: &std::path::Path) -> Child { + Command::new(path) + .args(["--exact", "process::tests::liveness_child", "--ignored"]) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap() + } + fn exit(mut child: Child) { + drop(child.stdin.take()); + assert!(child.wait().unwrap().success()); + } + let suffix = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = std::env::temp_dir().join(format!( + "argus-program-identity-{}-{suffix}", + std::process::id() + )); + std::fs::create_dir(&dir).unwrap(); + for name in ["one", "two"] { + std::fs::create_dir(dir.join(name)).unwrap(); + std::fs::copy( + std::env::current_exe().unwrap(), + dir.join(name).join("same.exe"), + ) + .unwrap(); + } + let one = dir.join("one/same.exe"); + let two = dir.join("two/same.exe"); + let a = start(&one); + let b = start(&two); + let first = Instance::open(a.id(), birth(&a)).unwrap(); + let second = Instance::open(b.id(), birth(&b)).unwrap(); + let a_program = first.program().unwrap(); + assert!(!a_program.same_program(&second.program().unwrap())); + let first_pid = a.id(); + exit(a); + let again = start(&one); + assert_ne!(again.id(), first_pid); + let restarted = Instance::open(again.id(), birth(&again)).unwrap(); + assert!(a_program.same_program(&restarted.program().unwrap())); + assert!(Instance::open(again.id(), birth(&again) + 1000).is_err()); + exit(again); + exit(b); + drop((first, second, restarted)); + for path in [&one, &two] { + std::fs::remove_file(path).unwrap(); + } + for name in ["one", "two"] { + std::fs::remove_dir(dir.join(name)).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/program.rs b/crates/argus-core/src/watch/program.rs new file mode 100644 index 00000000..afb79cc4 --- /dev/null +++ b/crates/argus-core/src/watch/program.rs @@ -0,0 +1,764 @@ +//! Opt-in observation of future instances, with one validated handle per live instance. +use super::{ + SAMPLE_MS, WatchError, WatchMode, WatchPoint, WatchRun, WatchState, WatchView, + identity::Instance, + store::{self, Metadata, Store}, +}; +use crate::{Snapshot, util::OwnedHandle}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + path::Path, + time::{Duration, Instant}, +}; +use windows::Win32::{ + Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}, + System::Threading::WaitForSingleObject, +}; + +type Key = (u32, i64); +const MAX_ACTIVE: usize = 512; +const PREVIEW_POINTS: usize = 1000; +const PREVIEW_RUNS: usize = 256; + +pub(super) struct ProgramWatch { + store: Store, + handles: HashMap, + seen: HashSet, + unconfirmed: HashMap, + selected: Option, + before: Option, + run_offset: usize, + active: bool, + state: WatchState, + last: Option, + last_ts: Option, +} + +impl ProgramWatch { + pub fn start(dir: &Path, pid: u32, created: i64, name: String) -> Result { + let instance = Instance::open(pid, created)?; + let program = instance.program()?; + std::fs::create_dir_all(dir).map_err(|_| WatchError::Storage)?; + let store = Store::create(&dir.join(store::FILE_NAME), Metadata { program, name })?; + Ok(Self { + store, + handles: HashMap::from([((pid, created), instance.into_handle())]), + seen: HashSet::from([(pid, created)]), + unconfirmed: HashMap::new(), + selected: Some((pid, created)), + before: None, + run_offset: 0, + active: true, + state: WatchState::Recording, + last: None, + last_ts: None, + }) + } + + pub fn open(dir: &Path) -> Result { + let store = Store::open(&dir.join(store::FILE_NAME), super::now_ms())?; + // Restarting Argus never silently resumes an observation. + let state = match store.entries.back().map(|e| e.point.state) { + Some(WatchState::Stopped) => WatchState::Stopped, + Some(WatchState::Limit) => WatchState::Limit, + _ => WatchState::Interrupted, + }; + Ok(Self { + store, + handles: HashMap::new(), + seen: HashSet::new(), + unconfirmed: HashMap::new(), + selected: None, + before: None, + run_offset: 0, + active: false, + state, + last: None, + last_ts: None, + }) + } + + pub fn select(&mut self, pid: u32, created: i64) -> Result<(), WatchError> { + if !self.handles.contains_key(&(pid, created)) + && !self + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == (pid, created)) + { + return Err(WatchError::Missing); + } + self.selected = Some((pid, created)); + self.before = None; + Ok(()) + } + + pub fn page(&mut self, before: Option) -> Result<(), WatchError> { + if let Some(before) = before { + let view = self.view(); + if !self + .store + .entries + .iter() + .any(|e| e.seq < before && (e.pid, e.created) == (view.pid, view.create_time)) + { + return Err(WatchError::Missing); + } + } + self.before = before; + Ok(()) + } + + pub fn runs_page(&mut self, offset: usize) { + self.run_offset = offset.min(store::CAPACITY - 1); + } + + fn terminal(&mut self, key: Key, state: WatchState, ts: i64) -> Result<(), WatchError> { + self.store.push( + key.0, + key.1, + WatchPoint { + ts, + memory: None, + commit: None, + state, + }, + ) + } + + pub fn stop(&mut self, state: WatchState, ts: i64) -> Result<(), WatchError> { + self.active = false; + self.state = state; + let keys: Vec<_> = self.handles.keys().copied().collect(); + self.handles.clear(); + self.unconfirmed.clear(); + let ts = ts.max(self.last_ts.unwrap_or(ts)); + for key in keys { + self.terminal(key, state, ts)?; + } + // Preserve a durable stop marker even while waiting between launches. + if let Some(entry) = self.store.entries.back() + && entry.point.state != state + { + self.terminal((entry.pid, entry.created), state, ts)?; + } + self.store.flush() + } + + pub fn record(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if !self.active { + return self.store.prune(snapshot.timestamp); + } + let result = self.sample(snapshot); + if result.is_err() { + self.handles.clear(); + self.unconfirmed.clear(); + self.active = false; + self.state = WatchState::Interrupted; + } + result + } + + fn sample(&mut self, snapshot: &Snapshot) -> Result<(), WatchError> { + if self.last_ts.is_some_and(|ts| snapshot.timestamp < ts) { + return self.stop(WatchState::Interrupted, self.last_ts.unwrap()); + } + let present: HashSet<_> = snapshot + .processes + .iter() + .map(|row| (row.pid, row.create_time)) + .collect(); + self.seen + .retain(|key| present.contains(key) || self.handles.contains_key(key)); + self.unconfirmed.retain(|key, attempted| { + if !present.contains(key) { + return false; + } + if attempted.elapsed() >= Duration::from_secs(60) { + self.seen.remove(key); + return false; + } + true + }); + let basename = self + .store + .meta + .program + .display_path + .rsplit(['\\', '/']) + .next() + .unwrap_or(""); + for row in &snapshot.processes { + let key = (row.pid, row.create_time); + // The basename only reduces queries. Final identity always comes from the validated handle. + if row.create_time <= 0 + || !row.name.eq_ignore_ascii_case(basename) + || !self.seen.insert(key) + { + continue; + } + let Ok(instance) = Instance::open(row.pid, row.create_time) else { + self.unconfirmed.insert(key, Instant::now()); + continue; + }; + let Ok(identity) = instance.program() else { + self.unconfirmed.insert(key, Instant::now()); + continue; + }; + if !self.store.meta.program.same_program(&identity) { + continue; + } + if self.handles.len() == MAX_ACTIVE { + return self.stop(WatchState::Limit, snapshot.timestamp); + } + self.handles.insert(key, instance.into_handle()); + } + let terminal: Vec<_> = self + .handles + .iter() + .filter_map( + |(key, handle)| match unsafe { WaitForSingleObject(handle.0, 0) } { + WAIT_TIMEOUT => None, + WAIT_OBJECT_0 => Some((*key, WatchState::Exited)), + _ => Some((*key, WatchState::Interrupted)), + }, + ) + .collect(); + for (key, state) in terminal { + self.terminal(key, state, snapshot.timestamp)?; + self.handles.remove(&key); + } + if self + .last + .is_some_and(|last| last.elapsed() < Duration::from_millis(SAMPLE_MS as u64)) + { + return Ok(()); + } + if let Some(previous) = self.last_ts + && snapshot.timestamp.saturating_sub(previous) > SAMPLE_MS * 2 + { + // New launches start at their first sample; an earlier gap belongs to older runs. + let keys: Vec<_> = self + .handles + .keys() + .filter(|key| key.1 <= previous) + .copied() + .collect(); + // Terminal records may already have this snapshot's timestamp; keep sequence time monotonic. + let gap_ts = self.store.entries.back().map_or(previous + SAMPLE_MS, |e| { + e.point.ts.max(previous + SAMPLE_MS) + }); + for key in keys { + self.terminal(key, WatchState::Gap, gap_ts)?; + } + } + let rows: HashMap<_, _> = snapshot + .processes + .iter() + .map(|p| ((p.pid, p.create_time), p)) + .collect(); + for key in self.handles.keys() { + let row = rows + .get(key) + .filter(|p| !p.stale && !p.sample_reused && !p.counters_pending); + self.store.push( + key.0, + key.1, + WatchPoint { + ts: snapshot.timestamp, + memory: row.map(|p| p.private_ws), + commit: row.map(|p| p.commit), + state: if row.is_some() { + WatchState::Recording + } else { + WatchState::Gap + }, + }, + )?; + } + self.store.prune(snapshot.timestamp)?; + self.store.flush()?; + self.last = Some(Instant::now()); + self.last_ts = Some(snapshot.timestamp); + Ok(()) + } + + pub fn view(&self) -> WatchView { + let mut runs: BTreeMap = BTreeMap::new(); + for entry in &self.store.entries { + let run = runs.entry((entry.pid, entry.created)).or_insert(WatchRun { + pid: entry.pid, + create_time: entry.created, + first_ts: entry.point.ts, + last_ts: entry.point.ts, + points: 0, + state: WatchState::Interrupted, + }); + run.last_ts = entry.point.ts; + run.points += 1; + run.state = if !self.active + && matches!(entry.point.state, WatchState::Recording | WatchState::Gap) + { + WatchState::Interrupted + } else { + entry.point.state + }; + } + for key in self.handles.keys() { + runs.entry(*key).or_insert(WatchRun { + pid: key.0, + create_time: key.1, + first_ts: 0, + last_ts: 0, + points: 0, + state: WatchState::Recording, + }); + } + let key = self + .selected + .filter(|key| runs.contains_key(key) || self.handles.contains_key(key)) + .or_else(|| { + self.store + .entries + .back() + .map(|entry| (entry.pid, entry.created)) + }) + .or(self.selected) + .unwrap_or((0, 0)); + let mut entries: Vec<_> = self + .store + .entries + .iter() + .rev() + .filter(|entry| { + (entry.pid, entry.created) == key + && self.before.is_none_or(|before| entry.seq < before) + }) + .take(PREVIEW_POINTS) + .collect(); + entries.reverse(); + let first_sequence = entries.first().map(|entry| entry.seq); + let has_earlier = first_sequence.is_some_and(|seq| { + self.store + .entries + .iter() + .any(|e| e.seq < seq && (e.pid, e.created) == key) + }); + let mut points: Vec = Vec::new(); + for entry in entries { + if let Some(previous) = points.last() + && entry.point.ts.saturating_sub(previous.ts) > SAMPLE_MS * 2 + && previous.memory.is_some() + { + points.push(WatchPoint { + ts: previous.ts + SAMPLE_MS, + memory: None, + commit: None, + state: WatchState::Gap, + }); + } + points.push(entry.point.clone()); + } + let mut runs: Vec<_> = runs.into_values().collect(); + runs.sort_unstable_by_key(|run| (run.create_time, run.pid)); + let total_runs = runs.len(); + let selected_run = runs + .iter() + .find(|run| (run.pid, run.create_time) == key) + .cloned(); + let run_offset = self.run_offset.min(total_runs.saturating_sub(1)); + let end = total_runs - run_offset; + let start = end.saturating_sub(PREVIEW_RUNS); + let runs = runs[start..end].to_vec(); + WatchView { + version: 2, + pid: key.0, + create_time: key.1, + name: self.store.meta.name.clone(), + program: Some(self.store.meta.program.clone()), + mode: WatchMode::Program, + state: self.state, + points, + runs, + total_runs, + total_points: selected_run.map_or(0, |run| run.points), + damaged: self.store.damaged, + first_sequence, + has_earlier, + has_later: self.before.is_some(), + run_offset, + live_runs: self.handles.len(), + unconfirmed: self.unconfirmed.len(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Collector, + meta::MetaStore, + util::{filetime_ticks, ticks_to_unix_ms}, + }; + use std::{ + os::windows::{io::AsRawHandle, process::CommandExt}, + process::{Child, Command, Stdio}, + }; + use windows::Win32::{Foundation::HANDLE, System::Threading::GetProcessTimes}; + + #[test] + fn pages_keep_older_points_and_launches_accessible_and_clock_reversal_interrupts() { + let dir = std::env::temp_dir().join(format!("argus-watch-pages-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let mut store = Store::create( + &dir.join(store::FILE_NAME), + Metadata { + name: "same.exe".into(), + program: super::super::ProgramIdentity { + native_path: "\\Device\\disk\\same.exe".into(), + display_path: "C:\\same.exe".into(), + }, + }, + ) + .unwrap(); + let start = super::super::now_ms() - 10_000_000; + for i in 0..2001 { + store + .push( + 17, + 100, + WatchPoint { + ts: start + i * SAMPLE_MS, + memory: Some(i as u64), + commit: Some(0), + state: WatchState::Recording, + }, + ) + .unwrap(); + } + for pid in 1000..1300 { + store + .push( + pid, + i64::from(pid), + WatchPoint { + ts: start + 2000 * SAMPLE_MS, + memory: Some(0), + commit: Some(0), + state: WatchState::Recording, + }, + ) + .unwrap(); + } + store.flush().unwrap(); + drop(store); + let mut watch = ProgramWatch::open(&dir).unwrap(); + watch.select(17, 100).unwrap(); + let view = watch.view(); + assert_eq!(view.total_runs, 301); + assert_eq!(view.runs.len(), 256); + assert_eq!(view.total_points, 2001); + assert_eq!(view.points.first().unwrap().memory, Some(1001)); + assert!(view.has_earlier); + watch.page(view.first_sequence).unwrap(); + let view = watch.view(); + assert_eq!(view.points.first().unwrap().memory, Some(1)); + assert!(view.has_earlier && view.has_later); + watch.page(view.first_sequence).unwrap(); + assert_eq!(watch.view().points.first().unwrap().memory, Some(0)); + assert!(!watch.view().has_earlier); + watch.page(None).unwrap(); + assert!(!watch.view().has_later); + watch.runs_page(256); + assert_eq!(watch.view().runs.len(), 45); + assert_eq!(watch.view().runs[0].pid, 17); + watch.runs_page(usize::MAX); + assert_eq!(watch.view().runs.len(), 1); + watch.active = true; + watch.state = WatchState::Recording; + let unconfirmed = Snapshot { + seq: 1, + timestamp: start + 2000 * SAMPLE_MS, + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: vec![crate::ProcessRow { + pid: std::process::id(), + create_time: 1, + name: "same.exe".into(), + ..Default::default() + }], + }; + watch.record(&unconfirmed).unwrap(); + assert_eq!(watch.view().unconfirmed, 1); + assert!(watch.handles.is_empty()); + assert!(watch.view().points.iter().all(|p| p.memory.is_some())); + watch.last_ts = Some(start + 2000 * SAMPLE_MS); + let snapshot = Snapshot { + seq: 1, + timestamp: start, + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: Vec::new(), + }; + watch.record(&snapshot).unwrap(); + assert!(!watch.active); + assert_eq!(watch.state, WatchState::Interrupted); + drop(watch); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + std::fs::remove_dir(dir).unwrap(); + } + + struct Helper(Child); + + #[test] + fn a_new_launch_does_not_inherit_a_gap_before_its_creation() { + let dir = std::env::temp_dir().join(format!( + "argus-program-watch-birth-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let exe = std::env::current_exe().unwrap(); + let name = exe.file_name().unwrap().to_str().unwrap().to_owned(); + let first = Helper::spawn(&exe); + let first_key = first.key(); + let mut watch = ProgramWatch::start(&dir, first_key.0, first_key.1, name.clone()).unwrap(); + let snapshot = |keys: &[Key]| Snapshot { + seq: 1, + timestamp: super::super::now_ms(), + system: Default::default(), + hardware: Default::default(), + sessions: Vec::new(), + process_network: false, + processes: keys + .iter() + .map(|&(pid, created)| crate::ProcessRow { + pid, + create_time: created, + name: name.clone().into(), + ..Default::default() + }) + .collect(), + }; + watch.record(&snapshot(&[first_key])).unwrap(); + std::thread::sleep(Duration::from_millis((SAMPLE_MS * 2 + 1000) as u64)); + let later = Helper::spawn(&exe); + let later_key = later.key(); + watch.record(&snapshot(&[first_key, later_key])).unwrap(); + let before_birth = watch + .store + .entries + .iter() + .filter(|entry| (entry.pid, entry.created) == later_key && entry.point.ts < later_key.1) + .map(|entry| (entry.point.ts, entry.point.state)) + .collect::>(); + let existing_gap = watch.store.entries.iter().any(|entry| { + (entry.pid, entry.created) == first_key && entry.point.state == WatchState::Gap + }); + drop(watch); + drop(later); + drop(first); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + std::fs::remove_dir(dir).unwrap(); + assert!( + before_birth.is_empty(), + "records before creation: {before_birth:?}" + ); + assert!( + existing_gap, + "the existing run must retain the sampling gap" + ); + } + + impl Helper { + fn spawn(path: &Path) -> Self { + Self( + Command::new(path) + .args(["--exact", "process::tests::liveness_child", "--ignored"]) + .creation_flags(0x08000000) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap(), + ) + } + fn key(&self) -> Key { + let (mut created, mut exited, mut kernel, mut user) = Default::default(); + unsafe { + GetProcessTimes( + HANDLE(self.0.as_raw_handle()), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + } + .unwrap(); + (self.0.id(), ticks_to_unix_ms(filetime_ticks(created))) + } + } + impl Drop for Helper { + fn drop(&mut self) { + drop(self.0.stdin.take()); + let deadline = Instant::now() + Duration::from_secs(3); + while Instant::now() < deadline { + if self.0.try_wait().unwrap().is_some() { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + #[test] + #[ignore = "100 owned hidden idle helpers, real collector and two image folders; run explicitly"] + fn real_idle_instances_restart_and_same_name_other_folder_remain_separate() { + let dir = + std::env::temp_dir().join(format!("argus-program-watch-real-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + for folder in ["one", "two"] { + std::fs::create_dir(dir.join(folder)).unwrap(); + std::fs::copy( + std::env::current_exe().unwrap(), + dir.join(folder).join("same.exe"), + ) + .unwrap(); + } + let one = dir.join("one/same.exe"); + let two = dir.join("two/same.exe"); + let mut helpers: Vec<_> = (0..100).map(|_| Helper::spawn(&one)).collect(); + let other = Helper::spawn(&two); + let seed = helpers[0].key(); + let mut watch = + ProgramWatch::start(&dir, seed.0, seed.1, "UI label is not an identity".into()) + .unwrap(); + let mut collector = Collector::new(MetaStore::new()); + let deadline = Instant::now() + Duration::from_secs(15); + let mut max_record_us = 0; + let mut max_view_us = 0; + loop { + let snapshot = collector.sample(); + watch.last = None; + let started = Instant::now(); + watch.record(&snapshot).unwrap(); + max_record_us = max_record_us.max(started.elapsed().as_micros()); + let started = Instant::now(); + let view = watch.view(); + max_view_us = max_view_us.max(started.elapsed().as_micros()); + let measured = view + .runs + .iter() + .filter(|run| { + watch.store.entries.iter().any(|e| { + (e.pid, e.created) == (run.pid, run.create_time) && e.point.memory.is_some() + }) + }) + .count(); + if measured == 100 { + break; + } + assert!( + Instant::now() < deadline, + "not all 100 idle helpers received real measurements" + ); + std::thread::sleep(Duration::from_millis(150)); + } + assert_eq!(watch.handles.len(), 100); + assert!(!watch.handles.contains_key(&other.key())); + assert_eq!(watch.view().total_runs, 100); + // Removing one instance never reuses its curve for the next launch. + drop(helpers.remove(0)); + watch.record(&collector.sample()).unwrap(); + assert!( + watch + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == seed && e.point.state == WatchState::Exited) + ); + helpers.push(Helper::spawn(&one)); + let restarted = helpers.last().unwrap().key(); + assert_ne!(seed, restarted); + let deadline = Instant::now() + Duration::from_secs(10); + while !watch + .store + .entries + .iter() + .any(|e| (e.pid, e.created) == restarted && e.point.memory.is_some()) + { + watch.last = None; + watch.record(&collector.sample()).unwrap(); + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(150)); + } + assert_eq!(watch.view().total_runs, 101); + if let Some(path) = std::env::var_os("ARGUS_TEST_PROGRAM_WATCH_OUTPUT") { + std::fs::write(path, serde_json::to_vec_pretty(&watch.view()).unwrap()).unwrap(); + } + watch.select(seed.0, seed.1).unwrap(); + assert_eq!( + watch.view().points.last().unwrap().state, + WatchState::Exited + ); + watch.select(restarted.0, restarted.1).unwrap(); + assert!( + watch + .view() + .points + .iter() + .all(|p| p.state != WatchState::Exited) + ); + assert!(matches!( + watch.select(seed.0, seed.1 + 1), + Err(WatchError::Missing) + )); + // A delayed observation is explicitly broken; old readings are never filled forward. + let mut snapshot = collector.sample(); + snapshot.timestamp = watch.last_ts.unwrap() + 3 * SAMPLE_MS; + watch.last = None; + watch.record(&snapshot).unwrap(); + assert!( + watch + .view() + .points + .iter() + .any(|p| p.state == WatchState::Gap && p.memory.is_none()) + ); + watch.stop(WatchState::Stopped, snapshot.timestamp).unwrap(); + let saved = watch.view().points.len(); + watch.record(&snapshot).unwrap(); + assert_eq!(watch.view().points.len(), saved); + assert!(watch.handles.is_empty()); + println!( + "owned_idle=100 runs=101 other_folder_attached=0 max_record_us={max_record_us} max_view_us={max_view_us} bytes={}", + std::fs::metadata(dir.join(store::FILE_NAME)).unwrap().len() + ); + drop(watch); + let mut reopened = ProgramWatch::open(&dir).unwrap(); + assert!(!reopened.active); + assert_eq!(reopened.state, WatchState::Stopped); + reopened.select(seed.0, seed.1).unwrap(); + assert_eq!( + reopened.view().points.last().unwrap().state, + WatchState::Exited + ); + drop(reopened); + drop((helpers, other, collector)); + std::fs::remove_file(dir.join(store::FILE_NAME)).unwrap(); + for folder in ["one", "two"] { + std::fs::remove_file(dir.join(folder).join("same.exe")).unwrap(); + std::fs::remove_dir(dir.join(folder)).unwrap(); + } + std::fs::remove_dir(dir).unwrap(); + } +} diff --git a/crates/argus-core/src/watch/store.rs b/crates/argus-core/src/watch/store.rs new file mode 100644 index 00000000..520d3996 --- /dev/null +++ b/crates/argus-core/src/watch/store.rs @@ -0,0 +1,424 @@ +//! Fixed-size rolling records. Legacy single-run JSONL is never rewritten. +use super::{ProgramIdentity, WatchError, WatchPoint, WatchState}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::VecDeque, + fs::{File, OpenOptions}, + io::{Read, Seek, SeekFrom, Write}, + path::Path, +}; + +pub(super) const FILE_NAME: &str = "program-watch.v1.bin"; +const MAGIC: &[u8; 8] = b"ARGWCH01"; +const HEADER: u64 = 1 << 20; +const RECORD: u64 = 64; +pub const CAPACITY: usize = 131072; +pub const RETENTION_MS: i64 = 7 * 24 * 60 * 60 * 1000; +pub const MAX_BYTES: u64 = HEADER + CAPACITY as u64 * RECORD; + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Metadata { + pub program: ProgramIdentity, + pub name: String, +} + +#[derive(Clone, Debug)] +pub(super) struct Entry { + pub seq: u64, + pub pid: u32, + pub created: i64, + pub point: WatchPoint, +} + +pub(super) struct Store { + file: File, + pub meta: Metadata, + pub entries: VecDeque, + next: u64, + pub damaged: bool, +} + +// Integrity detection for torn records, not authentication of local files. +fn checksum(bytes: &[u8]) -> u32 { + bytes.iter().fold(2166136261, |h, b| { + (h ^ u32::from(*b)).wrapping_mul(16777619) + }) +} + +fn state_byte(state: WatchState) -> u8 { + match state { + WatchState::Recording => 1, + WatchState::Gap => 2, + WatchState::Exited => 3, + WatchState::Stopped => 4, + WatchState::Interrupted => 5, + WatchState::Limit => 6, + } +} + +impl Entry { + fn encode(&self) -> [u8; RECORD as usize] { + let mut bytes = [0; RECORD as usize]; + bytes[0..8].copy_from_slice(&self.seq.to_le_bytes()); + bytes[8..16].copy_from_slice(&self.point.ts.to_le_bytes()); + bytes[16..20].copy_from_slice(&self.pid.to_le_bytes()); + bytes[20..28].copy_from_slice(&self.created.to_le_bytes()); + bytes[28..36].copy_from_slice(&self.point.memory.unwrap_or_default().to_le_bytes()); + bytes[36..44].copy_from_slice(&self.point.commit.unwrap_or_default().to_le_bytes()); + bytes[44] = state_byte(self.point.state); + bytes[45] = + u8::from(self.point.memory.is_some()) | (u8::from(self.point.commit.is_some()) << 1); + let sum = checksum(&bytes[..52]); + bytes[52..56].copy_from_slice(&sum.to_le_bytes()); + bytes[56..64].copy_from_slice(&(!self.seq).to_le_bytes()); + bytes + } + + fn decode(bytes: &[u8; RECORD as usize], slot: usize) -> Option { + let seq = u64::from_le_bytes(bytes[0..8].try_into().ok()?); + let ts = i64::from_le_bytes(bytes[8..16].try_into().ok()?); + let pid = u32::from_le_bytes(bytes[16..20].try_into().ok()?); + let created = i64::from_le_bytes(bytes[20..28].try_into().ok()?); + if seq == 0 + || (seq - 1) % CAPACITY as u64 != slot as u64 + || !seq != u64::from_le_bytes(bytes[56..64].try_into().ok()?) + || checksum(&bytes[..52]) != u32::from_le_bytes(bytes[52..56].try_into().ok()?) + || pid == 0 + || created <= 0 + || ts <= 0 + || bytes[45] & !3 != 0 + || bytes[46..52] != [0; 6] + { + return None; + } + let state = match bytes[44] { + 1 => WatchState::Recording, + 2 => WatchState::Gap, + 3 => WatchState::Exited, + 4 => WatchState::Stopped, + 5 => WatchState::Interrupted, + 6 => WatchState::Limit, + _ => return None, + }; + if state != WatchState::Recording && bytes[45] != 0 { + return None; + } + Some(Self { + seq, + pid, + created, + point: WatchPoint { + ts, + state, + memory: (bytes[45] & 1 != 0) + .then(|| u64::from_le_bytes(bytes[28..36].try_into().unwrap())), + commit: (bytes[45] & 2 != 0) + .then(|| u64::from_le_bytes(bytes[36..44].try_into().unwrap())), + }, + }) + } +} + +impl Store { + pub fn create(path: &Path, meta: Metadata) -> Result { + let encoded = serde_json::to_vec(&meta).map_err(|_| WatchError::Invalid)?; + if !meta.program.valid() + || meta.name.is_empty() + || meta.name.len() > 1024 + || encoded.len() as u64 > HEADER - 16 + { + return Err(WatchError::Invalid); + } + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(path) + .map_err(|_| WatchError::Storage)?; + let result = (|| -> std::io::Result<()> { + file.write_all(MAGIC)?; + file.write_all(&(encoded.len() as u32).to_le_bytes())?; + file.write_all(&checksum(&encoded).to_le_bytes())?; + file.write_all(&encoded)?; + file.set_len(HEADER)?; + file.flush() + })(); + if result.is_err() { + drop(file); + let _ = std::fs::remove_file(path); + return Err(WatchError::Storage); + } + Ok(Self { + file, + meta, + entries: VecDeque::new(), + next: 1, + damaged: false, + }) + } + + pub fn open(path: &Path, now: i64) -> Result { + let mut file = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .map_err(|_| WatchError::Storage)?; + let size = file.metadata().map_err(|_| WatchError::Storage)?.len(); + if !(HEADER..=MAX_BYTES).contains(&size) { + return Err(WatchError::Invalid); + } + let mut header = [0u8; 16]; + file.read_exact(&mut header) + .map_err(|_| WatchError::Storage)?; + let len = u32::from_le_bytes(header[8..12].try_into().unwrap()) as usize; + if &header[..8] != MAGIC || len as u64 > HEADER - 16 { + return Err(WatchError::Invalid); + } + let mut data = vec![0; len]; + file.read_exact(&mut data) + .map_err(|_| WatchError::Storage)?; + if checksum(&data) != u32::from_le_bytes(header[12..16].try_into().unwrap()) { + return Err(WatchError::Invalid); + } + let meta: Metadata = serde_json::from_slice(&data).map_err(|_| WatchError::Invalid)?; + if !meta.program.valid() || meta.name.is_empty() || meta.name.len() > 1024 { + return Err(WatchError::Invalid); + } + file.seek(SeekFrom::Start(HEADER)) + .map_err(|_| WatchError::Storage)?; + let mut raw = Vec::new(); + file.read_to_end(&mut raw) + .map_err(|_| WatchError::Storage)?; + let mut entries = Vec::new(); + let mut damaged = raw.len() % RECORD as usize != 0; + let mut invalid_slots = Vec::new(); + for (slot, bytes) in raw.as_chunks::<{ RECORD as usize }>().0.iter().enumerate() { + if bytes.iter().all(|b| *b == 0) { + continue; + } + match Entry::decode(bytes, slot) { + Some(entry) => entries.push(entry), + None => { + damaged = true; + invalid_slots.push(slot); + } + } + } + entries.sort_unstable_by_key(|entry| entry.seq); + // Only the newest ring generation can survive a partial overwrite. + let next = entries + .last() + .map_or(Some(1), |entry| entry.seq.checked_add(1)) + .ok_or(WatchError::Invalid)?; + entries.retain(|entry| { + let keep = next - entry.seq <= CAPACITY as u64; + if !keep { + invalid_slots.push(((entry.seq - 1) % CAPACITY as u64) as usize); + } + keep + }); + if entries.windows(2).any(|p| p[0].point.ts > p[1].point.ts) { + return Err(WatchError::Invalid); + } + // Remove unreadable values as well: expiry must not leave damaged payloads indefinitely. + for slot in invalid_slots { + file.seek(SeekFrom::Start(HEADER + slot as u64 * RECORD)) + .and_then(|_| file.write_all(&[0; RECORD as usize])) + .map_err(|_| WatchError::Storage)?; + } + if raw.len() % RECORD as usize != 0 { + file.set_len(HEADER + (raw.len() as u64 / RECORD) * RECORD) + .map_err(|_| WatchError::Storage)?; + } + let mut store = Self { + file, + meta, + entries: entries.into(), + next, + damaged, + }; + store.prune(now)?; + Ok(store) + } + + fn offset(seq: u64) -> u64 { + HEADER + ((seq - 1) % CAPACITY as u64) * RECORD + } + + pub fn prune(&mut self, now: i64) -> Result<(), WatchError> { + let cutoff = now.saturating_sub(RETENTION_MS); + while self + .entries + .front() + .is_some_and(|entry| entry.point.ts < cutoff) + { + let entry = self.entries.front().unwrap(); + self.file + .seek(SeekFrom::Start(Self::offset(entry.seq))) + .and_then(|_| self.file.write_all(&[0; RECORD as usize])) + .map_err(|_| WatchError::Storage)?; + self.entries.pop_front(); + } + self.file.flush().map_err(|_| WatchError::Storage) + } + + pub fn push(&mut self, pid: u32, created: i64, point: WatchPoint) -> Result<(), WatchError> { + if pid == 0 + || created <= 0 + || point.ts <= 0 + || self + .entries + .back() + .is_some_and(|last| point.ts < last.point.ts) + || (point.state != WatchState::Recording + && (point.memory.is_some() || point.commit.is_some())) + { + return Err(WatchError::Invalid); + } + let next = self.next.checked_add(1).ok_or(WatchError::Invalid)?; + self.prune(point.ts)?; + let entry = Entry { + seq: self.next, + pid, + created, + point, + }; + self.file + .seek(SeekFrom::Start(Self::offset(entry.seq))) + .and_then(|_| self.file.write_all(&entry.encode())) + .map_err(|_| WatchError::Storage)?; + self.next = next; + while self + .entries + .front() + .is_some_and(|old| next - old.seq > CAPACITY as u64) + { + self.entries.pop_front(); + } + self.entries.push_back(entry); + Ok(()) + } + + pub fn flush(&mut self) -> Result<(), WatchError> { + self.file.flush().map_err(|_| WatchError::Storage) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn meta() -> Metadata { + Metadata { + name: "same.exe".into(), + program: ProgramIdentity { + native_path: "\\Device\\disk\\one\\same.exe".into(), + display_path: "C:\\one\\same.exe".into(), + }, + } + } + fn point(ts: i64, value: u64) -> WatchPoint { + WatchPoint { + ts, + memory: Some(value), + commit: Some(value + 1), + state: WatchState::Recording, + } + } + fn path(tag: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!( + "argus-watch-store-{}-{tag}.bin", + std::process::id() + )) + } + + #[test] + fn rolling_quota_and_runs_survive_reopen_without_splicing() { + let path = path("quota"); + let start = super::super::now_ms(); + let began = std::time::Instant::now(); + let mut store = Store::create(&path, meta()).unwrap(); + for i in 0..CAPACITY + 3 { + store + .push( + if i % 2 == 0 { 17 } else { 18 }, + 100 + (i % 2) as i64, + point(start + i as i64, i as u64), + ) + .unwrap(); + } + store.flush().unwrap(); + assert_eq!(store.entries.len(), CAPACITY); + assert_eq!(store.file.metadata().unwrap().len(), MAX_BYTES); + let writer_us = began.elapsed().as_micros(); + drop(store); + let began = std::time::Instant::now(); + let store = Store::open(&path, start + CAPACITY as i64).unwrap(); + println!( + "ring_records={} bytes={} writer_us={writer_us} reopen_us={}", + CAPACITY, + MAX_BYTES, + began.elapsed().as_micros() + ); + assert_eq!(store.entries.len(), CAPACITY); + assert_eq!(store.entries.front().unwrap().point.memory, Some(3)); + assert_eq!( + store.entries.back().unwrap().point.memory, + Some((CAPACITY + 2) as u64) + ); + assert_eq!(store.entries.front().unwrap().pid, 18); + assert!(!store.damaged); + drop(store); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn expiry_erases_values_and_torn_record_does_not_become_a_measurement() { + let path = path("expiry"); + let start = super::super::now_ms(); + let mut store = Store::create(&path, meta()).unwrap(); + store.push(17, 100, point(start, 12345)).unwrap(); + store + .push(17, 100, point(start + RETENTION_MS + 1, 23456)) + .unwrap(); + assert_eq!(store.entries.len(), 1); + let mut raw = std::fs::read(&path).unwrap(); + assert!( + raw[HEADER as usize..HEADER as usize + RECORD as usize] + .iter() + .all(|b| *b == 0) + ); + drop(store); + raw[HEADER as usize + RECORD as usize + 30] ^= 1; + std::fs::write(&path, raw).unwrap(); + let store = Store::open(&path, start + RETENTION_MS + 1).unwrap(); + assert!(store.entries.is_empty()); + assert!(store.damaged); + drop(store); + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn unknown_header_and_oversize_are_rejected_without_truncation() { + let path = path("invalid"); + let store = Store::create(&path, meta()).unwrap(); + drop(store); + let mut raw = std::fs::read(&path).unwrap(); + raw[0] ^= 1; + std::fs::write(&path, &raw).unwrap(); + assert!(matches!( + Store::open(&path, super::super::now_ms()), + Err(WatchError::Invalid) + )); + assert_eq!(std::fs::read(&path).unwrap(), raw); + let file = OpenOptions::new().write(true).open(&path).unwrap(); + file.set_len(MAX_BYTES + 1).unwrap(); + drop(file); + assert!(matches!( + Store::open(&path, super::super::now_ms()), + Err(WatchError::Invalid) + )); + assert_eq!(std::fs::metadata(&path).unwrap().len(), MAX_BYTES + 1); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/docs/guide/README.md b/docs/guide/README.md index 2ab5a6b8..90a8365a 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -202,6 +202,22 @@ Argus 运行时每 5 秒记录一帧:整机的 CPU(这 5 秒内各次采样 当前读取 v2 和 v3 历史。新建的 v3 文件保存进程创建时间;已有的当天 v2 文件继续按原格式追加,到下一天才创建 v3 文件,不覆盖旧记录。v2 记录的进程创建时间未知。旧版 Argus 无法读取 v3 文件,降级前需备份历史目录;旧版记录器可能重建格式不受支持的当天文件。更早的格式仍需用对应旧版读取备份。 +### 观察程序与运行实例 + +新的单实例观察文件使用 JSONL v2,在可查询时保存由同一已验证进程句柄取得的本机映像路径与显示路径,作为程序身份;界面传入的名称仅作标签。旧 v1 记录继续读取,程序路径保持未知,不从同名进程补全,也不重写旧文件。此元数据保存在本地观察文件中,单次运行的观察仍以 PID、创建时间及保留的句柄为准。 + +在进程列表中选中一个运行实例,在详细信息面板选择“观察此运行实例”或“观察后续运行”。记录在“历史”页顶部显示,即使该进程未进入系统历史的排行榜,也会记录其专用工作集与专用提交量。工作集表示当前驻留的私人内存;提交量表示程序获得的私人已提交内存,工作集增长本身不证明内存泄漏。 + +“观察此运行实例”仅限一个由 PID 与创建时间确认的实例,不跟随重启。每条记录最多 1 小时、720 个点及 1 MiB,达到任一上限后停止,保存在历史目录中的 `process-watch.jsonl`。 + +“观察后续运行”从所选实例的已验证句柄读取本机映像路径,记录当前及随后启动的同路径程序;界面名称只作标签,不用于认定程序身份。不同目录的同名 EXE 不合并,路径比较保持大小写敏感目录的区别,不承诺合并路径别名,也不以文件签名或哈希定义二进制版本。每个已确认的实例保留一个只读查询句柄,直到退出;各实例的曲线按 PID 与创建时间分开。新实例的身份暂时无法读取时,显示无法确认的同名实例数,每分钟重试,不拼接到旧实例的数据。程序全部退出后保持等待,直到后续运行、手动停止或达到同时观察 512 个实例的上限。 + +后续运行记录使用独立文件 `program-watch.v1.bin`,最多保留 7 天、131072 个记录点及 9 MiB;先到的上限触发最旧记录清理,时间过期的记录槽位会清零。停止后的数据也按此策略清理,Argus 关闭期间的过期记录在再次打开时清理。记录带序列与完整性校验,损坏记录不会当成读数。实例列表每页最多 256 项,曲线每页最多 1000 个已存点及空缺标记,可分别浏览较早实例、较早点或返回最新记录。 + +两种观察通常每 5 秒保留一个点;后台采样较慢、读数无效或采样中断时显示空缺,不补零。新启动的实例不继承其启动前的采样空缺。通过同一进程句柄确认退出。系统时钟倒退时中断观察,不把逆序时间拼接进曲线。观察文件与排行榜文件独立,关闭排行榜记录不停止显式选择的观察。 + +“停止记录”保留已有数据;“删除记录”停止观察并删除该条文件。开始另一条记录前需删除已有记录。退出或重启 Argus 不会自动继续旧观察,保留的未完成记录显示为中断。未知格式或损坏的记录也可删除。设置中的历史占用包含观察文件,“清除历史记录”同时停止并删除观察。 + ## 文件占用 在“更多”菜单中选择“查找占用文件的进程”,或者直接把文件、文件夹拖到窗口上,即可查询占用。结果合并两种来源:Restart Manager 查找文件引用和已加载的模块,句柄扫描补充打开的文件、目录及后代,包括把所选文件夹当作当前目录的命令行进程。文件 ID 可识别通过硬链接打开同一文件的情况。 diff --git a/locales/de-DE/history.json b/locales/de-DE/history.json index 74779809..c56a683f 100644 --- a/locales/de-DE/history.json +++ b/locales/de-DE/history.json @@ -45,6 +45,48 @@ "earliest": "Frühester Datensatz", "note": "Zeichnet alle 5 Sekunden die Prozesse mit der höchsten CPU-, Arbeitsspeicher-, I/O-, GPU- und Netzwerkauslastung auf. Bei längerem Intervall im minimierten Zustand oder im Infobereich gilt dieses Intervall. Die Daten bleiben 7 Tage erhalten.", "off": "Die Verlaufsaufzeichnung ist deaktiviert; neue Daten werden nicht aufgezeichnet. Einstellungen öffnen", + "watch": { + "title": "Prozessbeobachtung", + "empty": "In den Details eines einzelnen Prozesses „Diese Instanz beobachten“ wählen, um Speicher auch unterhalb der Spitzenliste aufzuzeichnen.", + "start": "Diese Instanz beobachten", + "target": "Beobachtung: {name} (PID {pid})", + "stop": "Aufzeichnung stoppen", + "delete": "Aufzeichnung löschen", + "note": "Nur diese Instanz; bis zu 1 Stunde, 720 Punkte und 1 MiB. Messungen meist alle 5 Sekunden; langsamere Hintergrundabfragen können Lücken lassen. Ein wachsender Arbeitssatz allein belegt kein Speicherleck. Stoppen behält Daten; Löschen stoppt und entfernt diese Aufzeichnung.", + "metric": { + "memory": "Privater Arbeitssatz", + "commit": "Privat zugesicherter Speicher" + }, + "state": { + "recording": "Aufzeichnung läuft", + "gap": "Keine gültige Messung", + "exited": "Diese Instanz wurde beendet", + "stopped": "Aufzeichnung gestoppt", + "interrupted": "Unterbrochen; nicht fortgesetzt", + "limit": "Aufzeichnungsgrenze erreicht" + }, + "error": { + "unavailable": "Der Sampler antwortete nicht rechtzeitig. Ergebnis unbekannt; vor einem erneuten Versuch den Status prüfen.", + "identity": "Die ausgewählte Instanz konnte nicht bestätigt werden. Aktualisieren und erneut versuchen.", + "access": "Die aktuellen Rechte reichen zum Lesen dieser Instanz nicht aus.", + "existing": "Eine Beobachtung existiert bereits. Vor einer neuen die bisherige stoppen und löschen.", + "missing": "Keine Beobachtung vorhanden.", + "storage": "Die Aufzeichnung konnte nicht gelesen oder geschrieben werden. Sie wurde gestoppt.", + "invalid": "Die Aufzeichnung ist beschädigt oder das Format wird nicht unterstützt. Sie kann gelöscht werden." + }, + "startProgram": "Weitere Starts beobachten", + "chooseRun": "Start auswählen", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} Starts angezeigt; {points} gespeicherte Punkte in diesem Start", + "earlier": "Frühere Punkte", + "latest": "Neueste Punkte", + "programNote": "Aktuelle und künftige Starts dieses Abbildpfads werden getrennt erfasst. Bis zu 7 Tage, 131072 Punkte und 9 MiB; beim ersten erreichten Limit werden die ältesten Daten entfernt. Bis zu 512 gleichzeitige Instanzen. Die Liste zeigt die letzten 256 Starts; jede Seite bis zu 1000 gespeicherte Punkte und Lückenmarkierungen. Frühere Punkte bleiben abrufbar. Meist 5 Sekunden Abstand; langsamere Abtastung lässt Lücken. Ein wachsender Arbeitssatz beweist kein Speicherleck. Stoppen behält Daten, Löschen entfernt sie. Ein Neustart von Argus setzt die Aufzeichnung nicht fort.", + "damaged": "Einige Datensätze haben die Integritätsprüfung nicht bestanden; fehlende Intervalle bleiben Lücken.", + "earlierRuns": "Frühere Starts", + "latestRuns": "Neueste Starts", + "waiting": "Warten auf einen weiteren Start", + "unconfirmed": "Identität von {count} gleichnamigen Instanzen nicht bestätigt; erneuter Versuch einmal pro Minute." + }, "instanceUnavailable": "Die aufgezeichnete Instanz von {name} (PID {pid}) wurde beendet oder ihre Identität kann nicht bestätigt werden.", "showCpuPeak": "CPU-Spitzenframe zeigen", "cpuSummary": "CPU-Mittel {average}%, Spitze {peak}%; Spitzenframe: {time}. Prozesswerte sind Frame-Mittelwerte und belegen nicht die Ursache einer kurzen Spitze." diff --git a/locales/en-US/history.json b/locales/en-US/history.json index 16edea77..ac6846c3 100644 --- a/locales/en-US/history.json +++ b/locales/en-US/history.json @@ -45,6 +45,48 @@ "earliest": "Earliest record", "note": "Records the top processes by CPU, memory, I/O, GPU and network every 5 seconds (or at the minimized or tray refresh rate when that is slower) and keeps them for 7 days.", "off": "History recording is off; no new data is being recorded. Open Settings", + "watch": { + "title": "Process observation", + "empty": "Choose “Watch this instance” in the details of a single process to record memory even below the top list.", + "start": "Watch this instance", + "target": "Watching {name} (PID {pid})", + "stop": "Stop recording", + "delete": "Delete recording", + "note": "This instance only; up to 1 hour, 720 points and 1 MiB. Samples are usually 5 seconds apart; slower background sampling may leave gaps. Working set growth alone does not prove a memory leak. Stop keeps data; Delete stops and removes this recording.", + "metric": { + "memory": "Private working set", + "commit": "Private commit" + }, + "state": { + "recording": "Recording", + "gap": "No valid sample", + "exited": "This instance exited", + "stopped": "Recording stopped", + "interrupted": "Recording interrupted; not resumed", + "limit": "Recording limit reached" + }, + "error": { + "unavailable": "The sampler did not reply in time. The outcome is unknown; check recording status before retrying.", + "identity": "The selected instance could not be confirmed. Refresh and try again.", + "access": "This instance cannot be read with current permissions.", + "existing": "An observation already exists. Stop and delete it before starting another.", + "missing": "No observation exists.", + "storage": "The recording could not be read or written. Recording has stopped.", + "invalid": "The recording is damaged or uses an unsupported format. It can be deleted." + }, + "startProgram": "Watch future launches", + "chooseRun": "Choose a launch", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Showing {shown}/{total} launches; {points} saved points in this launch", + "earlier": "Earlier points", + "latest": "Latest points", + "programNote": "Current and future launches at this image path are recorded separately. Up to 7 days, 131072 points and 9 MiB; the first limit reached removes oldest data. Up to 512 concurrent instances. The list shows the latest 256 launches; each page shows up to 1000 saved points plus gap markers. Earlier points remain browsable. Samples are usually 5 seconds apart; slower sampling leaves gaps. Working set growth does not prove a leak. Stop keeps data; Delete removes it. Restarting Argus does not resume recording.", + "damaged": "Some stored records failed integrity checks; missing intervals remain gaps.", + "earlierRuns": "Earlier launches", + "latestRuns": "Latest launches", + "waiting": "Waiting for another launch", + "unconfirmed": "Could not confirm {count} same-named instances; retrying once per minute." + }, "instanceUnavailable": "The recorded instance of {name} (PID {pid}) has exited or its identity cannot be confirmed.", "showCpuPeak": "Show CPU peak frame", "cpuSummary": "CPU average {average}%, peak {peak}%; peak frame: {time}. Process readings are frame averages and do not establish the cause of a brief peak." diff --git a/locales/es-ES/history.json b/locales/es-ES/history.json index 4d5d7d39..7431ce42 100644 --- a/locales/es-ES/history.json +++ b/locales/es-ES/history.json @@ -47,6 +47,48 @@ "earliest": "Registro más antiguo", "note": "Registra cada 5 segundos los procesos con mayor uso de CPU, memoria, I/O, GPU y red; si el intervalo al minimizar o permanecer en la bandeja es mayor, utiliza ese intervalo. Conserva los registros durante 7 días.", "off": "El registro del historial está desactivado; no se registran datos nuevos. Abrir Configuración", + "watch": { + "title": "Observación de proceso", + "empty": "Elija «Observar esta instancia» en los detalles de un solo proceso para registrar memoria fuera de la lista principal.", + "start": "Observar esta instancia", + "target": "Observando {name} (PID {pid})", + "stop": "Detener registro", + "delete": "Eliminar registro", + "note": "Solo esta instancia; hasta 1 hora, 720 puntos y 1 MiB. Muestras normalmente cada 5 segundos; un muestreo más lento puede dejar huecos. El crecimiento del conjunto de trabajo no prueba una fuga. Detener conserva datos; Eliminar detiene y borra este registro.", + "metric": { + "memory": "Conjunto de trabajo privado", + "commit": "Memoria privada comprometida" + }, + "state": { + "recording": "Registrando", + "gap": "Sin muestra válida", + "exited": "Esta instancia terminó", + "stopped": "Registro detenido", + "interrupted": "Registro interrumpido; no reanudado", + "limit": "Límite de registro alcanzado" + }, + "error": { + "unavailable": "El muestreador no respondió a tiempo. Resultado desconocido; compruebe el estado antes de reintentar.", + "identity": "No se pudo confirmar la instancia seleccionada. Actualice y reintente.", + "access": "Los permisos actuales no permiten leer esta instancia.", + "existing": "Ya existe una observación. Deténgala y elimínela antes de iniciar otra.", + "missing": "No existe ninguna observación.", + "storage": "No se pudo leer o escribir el registro. Se ha detenido.", + "invalid": "El registro está dañado o su formato no es compatible. Puede eliminarlo." + }, + "startProgram": "Observar próximos inicios", + "chooseRun": "Elegir un inicio", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Se muestran {shown}/{total} inicios; {points} puntos guardados en este inicio", + "earlier": "Puntos anteriores", + "latest": "Últimos puntos", + "programNote": "Los inicios actuales y futuros de esta ruta de imagen se registran por separado. Hasta 7 días, 131072 puntos y 9 MiB; el primer límite alcanzado elimina los datos más antiguos. Hasta 512 instancias simultáneas. La lista muestra los últimos 256 inicios; cada página hasta 1000 puntos guardados y marcas de huecos. Los puntos anteriores siguen disponibles. Normalmente cada 5 segundos; un muestreo más lento deja huecos. El crecimiento del conjunto de trabajo no demuestra una fuga. Detener conserva los datos; Eliminar los borra. Reiniciar Argus no reanuda la grabación.", + "damaged": "Algunos registros no superaron la comprobación de integridad; los intervalos ausentes siguen siendo huecos.", + "earlierRuns": "Inicios anteriores", + "latestRuns": "Últimos inicios", + "waiting": "Esperando otro inicio", + "unconfirmed": "No se pudieron confirmar {count} instancias con el mismo nombre; se reintenta una vez por minuto." + }, "instanceUnavailable": "La instancia registrada de {name} (PID {pid}) ha finalizado o no se puede confirmar su identidad.", "showCpuPeak": "Ver fotograma del pico CPU", "cpuSummary": "CPU: media {average}%, máximo {peak}%; fotograma del pico: {time}. Los valores de procesos son medias por fotograma y no prueban la causa de un pico breve." diff --git a/locales/fr-FR/history.json b/locales/fr-FR/history.json index b9a719be..d554b928 100644 --- a/locales/fr-FR/history.json +++ b/locales/fr-FR/history.json @@ -47,6 +47,48 @@ "earliest": "Premier enregistrement", "note": "Enregistre les processus utilisant le plus de CPU, mémoire, I/O, GPU et réseau toutes les 5 secondes, ou selon l’intervalle de la fenêtre réduite ou de la zone de notification s’il est plus long. Les données sont conservées 7 jours.", "off": "L’enregistrement de l’historique est désactivé ; aucune nouvelle donnée n’est enregistrée. Ouvrir les paramètres", + "watch": { + "title": "Observation du processus", + "empty": "Choisir «Observer cette instance» dans les détails d’un seul processus pour enregistrer la mémoire hors du classement.", + "start": "Observer cette instance", + "target": "Observation de {name} (PID {pid})", + "stop": "Arrêter l’enregistrement", + "delete": "Supprimer l’enregistrement", + "note": "Cette instance uniquement ; jusqu’à 1 heure, 720 points et 1 MiB. Mesures généralement toutes les 5 secondes ; un échantillonnage plus lent peut laisser des lacunes. La croissance du jeu de travail ne prouve pas une fuite. Arrêter conserve les données ; Supprimer arrête et efface cet enregistrement.", + "metric": { + "memory": "Jeu de travail privé", + "commit": "Mémoire privée engagée" + }, + "state": { + "recording": "Enregistrement en cours", + "gap": "Aucune mesure valide", + "exited": "Cette instance est terminée", + "stopped": "Enregistrement arrêté", + "interrupted": "Enregistrement interrompu ; non repris", + "limit": "Limite d’enregistrement atteinte" + }, + "error": { + "unavailable": "L’échantillonneur n’a pas répondu à temps. Résultat inconnu ; vérifier l’état avant de réessayer.", + "identity": "L’instance choisie n’a pas pu être confirmée. Actualiser et réessayer.", + "access": "Les autorisations actuelles ne permettent pas de lire cette instance.", + "existing": "Une observation existe déjà. L’arrêter et la supprimer avant d’en commencer une autre.", + "missing": "Aucune observation enregistrée.", + "storage": "Impossible de lire ou d’écrire l’enregistrement. Il est arrêté.", + "invalid": "L’enregistrement est endommagé ou son format n’est pas pris en charge. Il peut être supprimé." + }, + "startProgram": "Observer les prochains lancements", + "chooseRun": "Choisir un lancement", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} lancements affichés ; {points} points enregistrés pour ce lancement", + "earlier": "Points antérieurs", + "latest": "Derniers points", + "programNote": "Les lancements actuels et futurs de ce chemin sont enregistrés séparément. Jusqu’à 7 jours, 131072 points et 9 MiB ; la première limite atteinte supprime les données les plus anciennes. Jusqu’à 512 instances simultanées. La liste affiche les 256 derniers lancements ; chaque page jusqu’à 1000 points enregistrés et des repères de lacunes. Les points antérieurs restent consultables. En général toutes les 5 secondes ; un échantillonnage plus lent laisse des lacunes. La croissance du jeu de travail ne prouve pas une fuite. Arrêter conserve les données ; Supprimer les efface. Redémarrer Argus ne reprend pas l’enregistrement.", + "damaged": "Certains enregistrements ont échoué au contrôle d’intégrité ; les intervalles manquants restent des lacunes.", + "earlierRuns": "Lancements antérieurs", + "latestRuns": "Derniers lancements", + "waiting": "En attente d’un autre lancement", + "unconfirmed": "Identité non confirmée pour {count} instances du même nom ; nouvel essai chaque minute." + }, "instanceUnavailable": "L’instance enregistrée de {name} (PID {pid}) est terminée ou son identité ne peut pas être confirmée.", "showCpuPeak": "Voir la mesure du pic CPU", "cpuSummary": "CPU : moyenne {average}%, pic {peak}% ; mesure du pic : {time}. Les valeurs des processus sont des moyennes par mesure et ne prouvent pas la cause d’un bref pic." diff --git a/locales/ja-JP/history.json b/locales/ja-JP/history.json index 15d75851..7a5c6000 100644 --- a/locales/ja-JP/history.json +++ b/locales/ja-JP/history.json @@ -43,6 +43,48 @@ "earliest": "最も古い記録", "note": "CPU、メモリ、I/O、GPU、ネットワークの使用量が多いプロセスを 5 秒ごとに記録し、7 日間保存します。最小化中や通知領域への常駐中の更新間隔が長い場合は、その間隔で記録します。", "off": "履歴の記録はオフになっています。新しいデータは記録されません。設定を開く", + "watch": { + "title": "プロセスの観測", + "empty": "単一プロセスの詳細で「このインスタンスを観測」を選ぶと、上位リストにない場合もメモリを記録できます。", + "start": "このインスタンスを観測", + "target": "観測:{name}(PID {pid})", + "stop": "記録を停止", + "delete": "記録を削除", + "note": "このインスタンスのみ。最大 1 時間、720 点、1 MiB。通常は 5 秒ごとですが、バックグラウンドの間隔が長いと欠測が生じます。ワーキングセットの増加だけではリークを証明できません。停止はデータを保持し、削除は停止して記録を消去します。", + "metric": { + "memory": "プライベートワーキングセット", + "commit": "プライベートコミット" + }, + "state": { + "recording": "記録中", + "gap": "有効な測定なし", + "exited": "このインスタンスは終了", + "stopped": "記録停止", + "interrupted": "記録中断・自動再開なし", + "limit": "記録上限に到達" + }, + "error": { + "unavailable": "収集処理が時間内に応答しませんでした。結果は不明です。再試行前に記録状態を確認してください。", + "identity": "選択したインスタンスを確認できません。更新して再試行してください。", + "access": "現在の権限ではこのインスタンスを読み取れません。", + "existing": "観測が既に存在します。新しい観測の前に停止して削除してください。", + "missing": "観測記録がありません。", + "storage": "記録を読み書きできませんでした。記録は停止しています。", + "invalid": "記録が破損しているか、未対応の形式です。削除できます。" + }, + "startProgram": "以後の起動も監視", + "chooseRun": "起動を選択", + "run": "{started} · PID {pid} · {state}", + "runSummary": "{shown}/{total} 件の起動を表示・選択中の起動に {points} 点を保存", + "earlier": "以前のデータ", + "latest": "最新のデータ", + "programNote": "このイメージパスの現在および以後の起動を個別に記録します。上限は 7 日、131072 点、9 MiB で、先に達した制限に従い古いデータを削除します。同時監視は 512 インスタンスまで。一覧には最新 256 件の起動を表示し、1 ページに最大 1000 点と欠測マーカーを表示します。以前のデータも参照できます。通常は 5 秒間隔で、低速の取得では欠測を残します。ワーキングセットの増加だけではリークを証明できません。停止はデータを保持し、削除は消去します。Argus の再起動後は自動再開しません。", + "damaged": "一部の保存レコードが整合性チェックに失敗しました。不明な区間は欠測のまま表示します。", + "earlierRuns": "以前の起動", + "latestRuns": "最新の起動", + "waiting": "次の起動を待機中", + "unconfirmed": "同名の {count} インスタンスの識別を確認できませんでした。1 分ごとに再試行します。" + }, "instanceUnavailable": "記録された {name}(PID {pid})のインスタンスは終了したか、同一性を確認できません。", "showCpuPeak": "CPU ピークのフレームを表示", "cpuSummary": "CPU 平均 {average}%、最大 {peak}%。ピークのフレーム:{time}。プロセスの値はフレーム内の平均であり、短いピークの原因を証明するものではありません。" diff --git a/locales/ru-RU/history.json b/locales/ru-RU/history.json index 7311057f..1b0be006 100644 --- a/locales/ru-RU/history.json +++ b/locales/ru-RU/history.json @@ -49,6 +49,48 @@ "earliest": "Самая ранняя запись", "note": "Запись процессов с наибольшей нагрузкой на CPU, память, I/O, GPU и сеть каждые 5 секунд. Если интервал для свёрнутого окна или области уведомлений больше, используется он. Записи хранятся 7 дней.", "off": "Запись истории отключена; новые данные не записываются. Открыть параметры", + "watch": { + "title": "Наблюдение за процессом", + "empty": "Выберите «Наблюдать за этим запуском» в подробностях отдельного процесса, чтобы записывать память даже ниже порога топа.", + "start": "Наблюдать за этим запуском", + "target": "Наблюдение: {name} (PID {pid})", + "stop": "Остановить запись", + "delete": "Удалить запись", + "note": "Только этот запуск: до 1 часа, 720 точек и 1 MiB. Обычно выборки идут через 5 секунд; при более редком фоновом сборе возможны пропуски. Рост рабочего набора сам по себе не доказывает утечку. Остановка сохраняет данные; удаление останавливает и удаляет эту запись.", + "metric": { + "memory": "Частный рабочий набор", + "commit": "Частная выделенная память" + }, + "state": { + "recording": "Идёт запись", + "gap": "Нет достоверной выборки", + "exited": "Этот запуск завершён", + "stopped": "Запись остановлена", + "interrupted": "Запись прервана; автоматически не продолжена", + "limit": "Достигнут предел записи" + }, + "error": { + "unavailable": "Сборщик не ответил вовремя. Результат операции неизвестен; проверьте состояние записи перед повтором.", + "identity": "Выбранный запуск не подтверждён. Обновите данные и повторите попытку.", + "access": "Текущих прав недостаточно для чтения этого запуска.", + "existing": "Наблюдение уже существует. Перед новым остановите и удалите прежнюю запись.", + "missing": "Записи наблюдения нет.", + "storage": "Не удалось прочитать или записать наблюдение. Запись остановлена.", + "invalid": "Запись повреждена или имеет неподдерживаемый формат. Её можно удалить." + }, + "startProgram": "Наблюдать следующие запуски", + "chooseRun": "Выбрать запуск", + "run": "{started} · PID {pid} · {state}", + "runSummary": "Показано запусков: {shown}/{total}; в выбранном сохранено точек: {points}", + "earlier": "Более ранние точки", + "latest": "Последние точки", + "programNote": "Текущие и следующие запуски по этому пути записываются отдельно. До 7 дней, 131072 точек и 9 MiB; при достижении первого предела удаляются самые старые данные. До 512 одновременных экземпляров. В списке — последние 256 запусков; на странице — до 1000 сохранённых точек и отметки пропусков. Более ранние точки доступны для просмотра. Обычно шаг — 5 секунд; редкая выборка оставляет пропуски. Рост рабочего набора не доказывает утечку. Остановка сохраняет данные, удаление стирает их. После перезапуска Argus запись не возобновляется.", + "damaged": "Часть записей не прошла проверку целостности; отсутствующие интервалы остаются пропусками.", + "earlierRuns": "Более ранние запуски", + "latestRuns": "Последние запуски", + "waiting": "Ожидание следующего запуска", + "unconfirmed": "Не удалось проверить одноимённые экземпляры: {count}. Повторная проверка — раз в минуту." + }, "instanceUnavailable": "Записанный запуск {name} (PID {pid}) завершён или его идентичность не подтверждена.", "showCpuPeak": "Кадр пика CPU", "cpuSummary": "CPU: среднее {average}%, максимум {peak}%; кадр пика: {time}. Показатели процессов усреднены за кадр и не доказывают причину краткого пика." diff --git a/locales/zh-CN/history.json b/locales/zh-CN/history.json index ab601566..4908c4a2 100644 --- a/locales/zh-CN/history.json +++ b/locales/zh-CN/history.json @@ -39,6 +39,48 @@ "earliest": "最早的记录", "note": "每 5 秒记录 CPU、内存、I/O、GPU 和网络占用最高的进程(最小化或后台常驻时的刷新间隔更长时按该间隔),保留 7 天。", "off": "历史记录已关闭,不再记录新的数据。打开设置", + "watch": { + "title": "进程观察", + "empty": "在单个进程的详细信息中选择“观察此运行实例”,即可记录未进入排行榜的内存变化。", + "start": "观察此运行实例", + "target": "观察 {name}(PID {pid})", + "stop": "停止记录", + "delete": "删除记录", + "note": "仅观察此运行实例;最多 1 小时、720 个记录点、1 MiB。通常每 5 秒记录一次,较慢的后台采样可能产生空缺。工作集增长本身不证明内存泄漏。停止保留数据;删除会停止并移除本条记录。", + "metric": { + "memory": "专用工作集", + "commit": "专用提交量" + }, + "state": { + "recording": "正在记录", + "gap": "缺少有效采样", + "exited": "此运行实例已结束", + "stopped": "已停止记录", + "interrupted": "记录已中断,未自动继续", + "limit": "已达到记录上限" + }, + "error": { + "unavailable": "采样器未及时回复;操作结果未知,请先查看记录状态。", + "identity": "无法确认所选运行实例;请刷新后重试。", + "access": "无法以当前权限读取此运行实例。", + "existing": "已有观察记录;如需开始新记录,请先停止并删除旧记录。", + "missing": "没有观察记录。", + "storage": "无法读写观察记录;记录已停止。", + "invalid": "观察记录损坏或格式不受支持;可删除此记录。" + }, + "startProgram": "观察后续运行", + "chooseRun": "选择运行实例", + "run": "{started} · PID {pid} · {state}", + "runSummary": "显示 {shown}/{total} 个实例;所选实例共 {points} 个记录点", + "earlier": "更早的记录", + "latest": "最新记录", + "programNote": "同一映像路径的当前及后续实例分别记录。最多保存 7 天、131072 个点及 9 MiB,先到的上限触发旧记录清理;最多同时观察 512 个实例。列表显示最近 256 个实例,每页最多 1000 个已存点及空缺标记,可查看更早记录。通常每 5 秒记录;较慢采样保留空缺。工作集增长不证明内存泄漏。停止保留数据,删除移除记录;重启 Argus 不自动继续。", + "damaged": "部分存储记录未通过完整性检查;缺失区间保留为空缺。", + "earlierRuns": "更早的实例", + "latestRuns": "最新实例", + "waiting": "等待后续运行", + "unconfirmed": "有 {count} 个同名实例无法确认身份;每分钟重试一次。" + }, "instanceUnavailable": "进程 {name}(PID {pid})的记录实例已结束,或无法确认其身份。", "showCpuPeak": "查看 CPU 峰值帧", "cpuSummary": "区间 CPU 平均 {average}%,峰值 {peak}%;峰值记录帧:{time}。帧内进程读数为平均值,不能据此确定瞬时峰值的原因。" diff --git a/locales/zh-TW/history.json b/locales/zh-TW/history.json index 0a6ef828..8048c577 100644 --- a/locales/zh-TW/history.json +++ b/locales/zh-TW/history.json @@ -39,6 +39,48 @@ "earliest": "最早的記錄", "note": "每 5 秒記錄 CPU、記憶體、I/O、GPU 和網路佔用最高的處理程序(最小化或背景常駐時的重新整理間隔更長時依該間隔),保留 7 天。", "off": "歷程記錄已關閉,不再記錄新的資料。開啟設定", + "watch": { + "title": "處理程序觀察", + "empty": "在單一處理程序的詳細資料中選擇「觀察此執行個體」,即可記錄未進入排行榜的記憶體變化。", + "start": "觀察此執行個體", + "target": "觀察 {name}(PID {pid})", + "stop": "停止記錄", + "delete": "刪除記錄", + "note": "僅觀察此執行個體;最多 1 小時、720 個記錄點、1 MiB。通常每 5 秒記錄一次,較慢的背景取樣可能產生缺漏。工作集增長本身不證明記憶體洩漏。停止會保留資料;刪除會停止並移除此記錄。", + "metric": { + "memory": "私人工作集", + "commit": "私人認可用量" + }, + "state": { + "recording": "正在記錄", + "gap": "缺少有效取樣", + "exited": "此執行個體已結束", + "stopped": "已停止記錄", + "interrupted": "記錄已中斷,未自動繼續", + "limit": "已達記錄上限" + }, + "error": { + "unavailable": "取樣器未及時回覆;操作結果未知,請先檢視記錄狀態。", + "identity": "無法確認所選執行個體;請重新整理後重試。", + "access": "無法以目前權限讀取此執行個體。", + "existing": "已有觀察記錄;若要開始新記錄,請先停止並刪除舊記錄。", + "missing": "沒有觀察記錄。", + "storage": "無法讀寫觀察記錄;記錄已停止。", + "invalid": "觀察記錄損壞或格式不受支援;可刪除此記錄。" + }, + "startProgram": "觀察後續執行", + "chooseRun": "選擇執行個體", + "run": "{started} · PID {pid} · {state}", + "runSummary": "顯示 {shown}/{total} 個執行個體;所選個體共 {points} 個記錄點", + "earlier": "較早的記錄", + "latest": "最新記錄", + "programNote": "同一映像路徑的目前及後續執行個體分別記錄。最多保留 7 天、131072 個點及 9 MiB,先到的上限觸發舊記錄清理;最多同時觀察 512 個個體。清單顯示最近 256 個個體,每頁最多 1000 個已存點及空缺標記,可查看較早記錄。通常每 5 秒記錄;較慢取樣保留空缺。工作集成長不證明記憶體洩漏。停止保留資料,刪除移除記錄;重啟 Argus 不自動繼續。", + "damaged": "部分儲存記錄未通過完整性檢查;缺失區間保留為空缺。", + "earlierRuns": "較早的執行個體", + "latestRuns": "最新執行個體", + "waiting": "等待後續執行", + "unconfirmed": "有 {count} 個同名執行個體無法確認身分;每分鐘重試一次。" + }, "instanceUnavailable": "處理程序 {name}(PID {pid})的記錄執行個體已結束,或無法確認其身分。", "showCpuPeak": "檢視 CPU 峰值影格", "cpuSummary": "區間 CPU 平均 {average}%,峰值 {peak}%;峰值記錄影格:{time}。影格內處理程序讀數為平均值,無法據此確定瞬間峰值的原因。" diff --git a/src-gpui/src/commands.rs b/src-gpui/src/commands.rs index ef0f90e8..00cbf065 100644 --- a/src-gpui/src/commands.rs +++ b/src-gpui/src/commands.rs @@ -634,7 +634,37 @@ pub fn history_moment(dir: State<'_, HistoryDir>, ts: i64) -> Option) -> HistoryUsage { - history::usage(&dir.0) + let mut usage = history::usage(&dir.0); + usage.bytes = usage + .bytes + .saturating_add(argus_core::watch::WatchRecorder::storage_bytes(&dir.0)); + usage +} + +/// Explicit observation runs on the sampler, where its file and instance handle live. +pub fn watch_process( + state: State<'_, AppState>, + dir: State<'_, HistoryDir>, + action: argus_core::watch::WatchAction, +) -> Result, String> { + use argus_core::watch::WatchError; + let (tx, rx) = std::sync::mpsc::channel(); + state + .sampler + .send(Control::Watch(dir.0.clone(), action, tx)); + let result = rx + .recv_timeout(std::time::Duration::from_secs(5)) + .map_err(|_| tr!("history.watch.error.unavailable"))?; + result.map_err(|error| { + argus_core::i18n::text(match error { + WatchError::Identity => "history.watch.error.identity", + WatchError::Access => "history.watch.error.access", + WatchError::Existing => "history.watch.error.existing", + WatchError::Missing => "history.watch.error.missing", + WatchError::Storage => "history.watch.error.storage", + WatchError::Invalid => "history.watch.error.invalid", + }) + }) } /// Starts or stops recording; what is already recorded stays until it expires. diff --git a/src-gpui/src/dispatch.rs b/src-gpui/src/dispatch.rs index 2511d321..cc72e7f3 100644 --- a/src-gpui/src/dispatch.rs +++ b/src-gpui/src/dispatch.rs @@ -251,6 +251,13 @@ pub fn invoke(host: &Host, name: &str, args: Value) -> Result { serde_json::to_value(crate::commands::history_usage(host.state())) .expect("serializable command response"), ), + "watch_process" => crate::commands::watch_process( + host.state(), + host.state(), + argument::(&args, "action")?, + ) + .map(|value| serde_json::to_value(value).expect("serializable command response")) + .map_err(|error| serde_json::to_value(error).unwrap_or(serde_json::Value::Null)), "set_history_enabled" => crate::commands::set_history_enabled( host.clone(), host.state(), diff --git a/src-gpui/src/frontend/backend.rs b/src-gpui/src/frontend/backend.rs index bf68fa63..0739f255 100644 --- a/src-gpui/src/frontend/backend.rs +++ b/src-gpui/src/frontend/backend.rs @@ -92,6 +92,16 @@ impl Desktop { let Some(pending) = self.pending.remove(&id) else { return; }; + if pending.command == "watch_process" + && pending.args["generation"].as_u64().unwrap_or(0) + != self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + { + return; + } // An answer for another range or moment is dropped. One history query of each // kind is in flight at a time, so the one for what is shown now may have been // held back while this one was read: forget it was sent and ask again. @@ -147,9 +157,21 @@ impl Desktop { if let Some(key) = pending.cache { self.data.insert(key, value.clone()); } + if pending.command == "watch_process" { + self.data.remove("watchError"); + self.data.insert("processWatch".into(), value.clone()); + } if pending.command == "history_series" { self.history_answered(&pending.args, window, cx); } + if pending.command == "watch_process" + && matches!( + pending.args["action"]["op"].as_str(), + Some("start" | "startProgram") + ) + { + self.act(Action::Page("history".into()), window, cx); + } if pending.command.starts_with("set_") && value.get("closeToTray").is_some() { self.data.insert("settings".into(), value.clone()); } @@ -167,6 +189,11 @@ impl Desktop { .as_str() .map(str::to_owned) .unwrap_or_else(|| self.action_error(&pending.command, &pending.args, &error)); + if pending.command == "watch_process" && pending.args["action"]["op"] == "status" { + self.data.insert("watchError".into(), json!(message)); + cx.notify(); + return; + } self.command_failed(&pending.command, &pending.args, &error, message, window, cx); } } diff --git a/src-gpui/src/frontend/pages.rs b/src-gpui/src/frontend/pages.rs index 99b7c9e5..58690d7f 100644 --- a/src-gpui/src/frontend/pages.rs +++ b/src-gpui/src/frontend/pages.rs @@ -4,6 +4,7 @@ mod components; mod details; mod history; mod performance; +mod process_watch; mod settings; mod vitals; use super::*; @@ -521,6 +522,32 @@ impl Desktop { self.load_history(window, cx); } "historyMetric" => self.history_metric = value.as_str().unwrap_or("cpu").into(), + "watchProcess" => { + if self.pending.values().any(|pending| { + pending.command == "watch_process" && pending.args["action"]["op"] != "status" + }) { + return; + } + let generation = self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + + 1; + self.data + .insert("watchGeneration".into(), json!(generation)); + if self.options.fixture.is_some() { + self.data.insert("watchLastAction".into(), value.clone()); + } + self.request( + "watch_process", + json!({"action":value,"generation":generation}), + None, + window, + cx, + ); + return; + } "historyPeak" => { self.data.remove("historySelection"); if let Some(at) = value.as_i64() { diff --git a/src-gpui/src/frontend/pages/details.rs b/src-gpui/src/frontend/pages/details.rs index dee88a95..e67f29c3 100644 --- a/src-gpui/src/frontend/pages/details.rs +++ b/src-gpui/src/frontend/pages/details.rs @@ -1155,7 +1155,28 @@ impl Desktop { .hover(move |style| style.bg(control_hover)), ); } - row.into_any_element() + let mut actions = div().flex_none().flex().flex_col(); + if !picked.group && number(process, "createTime") > 0. { + actions = actions.child(div().px(px(16.)).pt(px(8.)).child( + self.btn_small("details-watch", label("history.watch.start"), None, widgets::Tone::Plain) + .child(self.watch_anchor("details-watch")) + .w_full() + .on_click(cx.listener({ + let target = json!({"op":"start","pid":process["pid"],"createTime":process["createTime"],"name":process["name"]}); + move |this, _, window, cx| this.preference("watchProcess",target.clone(),window,cx) + })) + )); + actions = actions.child(div().px(px(16.)).pt(px(8.)).child( + self.btn_small("details-watch-program", label("history.watch.startProgram"), None, widgets::Tone::Plain) + .child(self.watch_anchor("details-watch-program")) + .w_full() + .on_click(cx.listener({ + let target = json!({"op":"startProgram","pid":process["pid"],"createTime":process["createTime"],"name":process["name"]}); + move |this, _, window, cx| this.preference("watchProcess",target.clone(),window,cx) + })) + )); + } + actions.child(row).into_any_element() } fn details_exited(&self, cx: &mut Context) -> AnyElement { diff --git a/src-gpui/src/frontend/pages/history.rs b/src-gpui/src/frontend/pages/history.rs index 4c467def..b2030de4 100644 --- a/src-gpui/src/frontend/pages/history.rs +++ b/src-gpui/src/frontend/pages/history.rs @@ -403,6 +403,7 @@ impl Desktop { window: &mut Window, cx: &mut Context, ) { + self.load_watch(window, cx); let now = now_ms(); let span = self.history_span(); let buckets = ((span as f64 / FRAME).ceil() as i64) @@ -1206,6 +1207,11 @@ impl Desktop { .flex_col() .gap(px(10.)) .line_height(relative(1.4)) + .when( + self.data.get("processWatch").is_some_and(Value::is_object) + || self.data.contains_key("watchError"), + |d| d.child(self.watch_card(window, cx)), + ) .child(graphs) .child(moment_card) .child(scrollbar::scrollbar("history-scrollbar", &page, p.dark)) diff --git a/src-gpui/src/frontend/pages/process_watch.rs b/src-gpui/src/frontend/pages/process_watch.rs new file mode 100644 index 00000000..9511ee03 --- /dev/null +++ b/src-gpui/src/frontend/pages/process_watch.rs @@ -0,0 +1,427 @@ +//! Explicit instance or program observation, independent of historical top lists. +use super::*; +use widgets::Tone; + +impl Desktop { + pub(super) fn watch_anchor(&self, key: &'static str) -> AnyElement { + let anchors = self.ui.anchors.clone(); + canvas( + move |bounds, _, _| { + anchors.borrow_mut().insert(key.into(), bounds); + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0() + .into_any_element() + } + pub(super) fn load_watch(&mut self, window: &mut Window, cx: &mut Context) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64; + let active = !self.data.contains_key("processWatch") + || self.data.contains_key("watchError") + || self + .data + .get("processWatch") + .is_some_and(|watch| matches!(text(watch, "state"), "recording" | "gap")); + let last = self.data.get("watchQueryAt").and_then(Value::as_i64); + if last.is_none() + || (active && last.is_some_and(|at| now - at >= argus_core::watch::SAMPLE_MS)) + || last.is_some_and(|at| now < at || now - at >= 60_000) + { + self.data.insert("watchQueryAt".into(), json!(now)); + self.request( + "watch_process", + json!({"action":{"op":"status"},"generation":self.data.get("watchGeneration").and_then(Value::as_u64).unwrap_or(0)}), + Some("processWatch"), + window, + cx, + ); + } + } + + pub(super) fn watch_card(&self, window: &mut Window, cx: &mut Context) -> AnyElement { + let p = self.palette; + let watch = self.data.get("processWatch").unwrap_or(&Value::Null); + let mut card = div() + .flex_none() + .p(px(14.)) + .flex() + .flex_col() + .gap(px(8.)) + .border_1() + .border_color(p.stroke) + .rounded(px(8.)) + .bg(p.layer); + if !watch.is_object() { + if let Some(message) = self.data.get("watchError").and_then(Value::as_str) { + return card + .child(div().child(message.to_owned())) + .child( + self.btn_small( + "watch-delete-invalid", + label("history.watch.delete"), + None, + Tone::Plain, + ) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"delete"}), window, cx) + })), + ) + .into_any_element(); + } + return card + .child( + div() + .font_weight(theme::LABEL_WEIGHT) + .child(label("history.watch.title")), + ) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label("history.watch.empty")), + ) + .into_any_element(); + } + let state = text(watch, "state"); + let program_mode = text(watch, "mode") == "program"; + let points = values(&watch["points"]); + let start = points + .first() + .map(|point| number(point, "ts")) + .unwrap_or(0.); + let end = points + .last() + .map(|point| number(point, "ts")) + .unwrap_or(start) + + argus_core::watch::SAMPLE_MS as f64; + let latest = points.last(); + let names = [ + label("history.watch.metric.memory"), + label("history.watch.metric.commit"), + ]; + let key = charts::hash_of(( + watch["pid"].as_u64(), + watch["createTime"].as_i64(), + points.len(), + end.to_bits(), + latest.and_then(|point| point["memory"].as_u64()), + latest.and_then(|point| point["commit"].as_u64()), + p.dark, + &names, + )); + let cached = window.use_keyed_state("process-watch-series", cx, |_, _| { + None::<(u64, Arc>, f64)> + }); + let plot = cached + .read(cx) + .as_ref() + .filter(|(stored, _, _)| *stored == key) + .cloned(); + let (_, series, maximum) = plot.unwrap_or_else(|| { + let mut maximum = 1024. * 1024.; + let mut series = Vec::new(); + for ((field, color), name) in [("memory", p.memory), ("commit", p.cpu)] + .into_iter() + .zip(&names) + { + let data = points + .iter() + .map(|point| (number(point, "ts"), point[field].as_f64())) + .collect::>(); + maximum = data + .iter() + .filter_map(|(_, value)| *value) + .fold(maximum, f64::max); + series.push( + charts::Series::new(name.clone(), data, color, charts::MetricFormat::Gigabytes) + .source(charts::hash_of((key, field))), + ); + } + let plot = (key, Arc::new(series), maximum); + cached.update(cx, |cache, _| *cache = Some(plot.clone())); + plot + }); + let mut legend = div().flex().flex_wrap().gap_x_4().gap_y_1(); + for (field, color) in [("memory", p.memory), ("commit", p.cpu)] { + let value = latest + .and_then(|point| point[field].as_f64()) + .map(theme::memory) + .unwrap_or_else(|| label("format.missing")); + legend = legend.child(div().text_size(theme::font(12.)).text_color(color).child( + format!( + "{}: {value}", + label(&format!("history.watch.metric.{field}")) + ), + )); + } + let active = matches!(state, "recording" | "gap"); + let header = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(div().font_weight(theme::LABEL_WEIGHT).child(tr!( + "history.watch.target", + name = text(watch, "name"), + pid = watch["pid"] + ))) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label( + &if program_mode && active && watch["liveRuns"] == 0 { + "history.watch.waiting".into() + } else { + format!("history.watch.state.{state}") + }, + )), + ) + .child( + self.btn_small("watch-stop", label("history.watch.stop"), None, Tone::Plain) + .child(self.watch_anchor("watch-stop")) + .disabled(!active) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"stop"}), window, cx) + })), + ) + .child( + self.btn_small( + "watch-delete", + label("history.watch.delete"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-delete")) + .on_click(cx.listener(|this, _, window, cx| { + this.preference("watchProcess", json!({"op":"delete"}), window, cx) + })), + ); + card = card.child(header).child(legend); + if program_mode { + let runs = values(&watch["runs"]); + let options = runs + .iter() + .map(|run| { + tr!( + "history.watch.run", + started = date_time(number(run, "createTime")), + pid = run["pid"], + state = label(&format!("history.watch.state.{}", text(run, "state"))) + ) + }) + .collect(); + let selected = runs.iter().position(|run| { + run["pid"] == watch["pid"] && run["createTime"] == watch["createTime"] + }); + let keys: Vec<_> = runs + .iter() + .map( + |run| json!({"op":"selectRun","pid":run["pid"],"createTime":run["createTime"]}), + ) + .collect(); + card = card.child(self.select( + "watch-run", + label("history.watch.chooseRun"), + options, + selected, + keys.is_empty(), + move |this, index, window, cx| { + if let Some(action) = keys.get(index) { + this.preference("watchProcess", action.clone(), window, cx); + } + }, + cx, + )); + let offset = watch["runOffset"].as_u64().unwrap_or(0); + let total = watch["totalRuns"].as_u64().unwrap_or(0); + card = card.child( + div() + .flex() + .flex_wrap() + .gap(px(8.)) + .child( + self.btn_small( + "watch-older-runs", + label("history.watch.earlierRuns"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-older-runs")) + .disabled(offset + runs.len() as u64 >= total) + .on_click(cx.listener( + move |this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"runs","offset":offset+256}), + window, + cx, + ) + }, + )), + ) + .child( + self.btn_small( + "watch-latest-runs", + label("history.watch.latestRuns"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-latest-runs")) + .disabled(offset == 0) + .on_click(cx.listener(|this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"runs","offset":0}), + window, + cx, + ) + })), + ), + ); + card = card.child( + div() + .min_w_0() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(text(&watch["program"], "displayPath").to_owned()), + ); + card = card.child( + div() + .flex() + .flex_wrap() + .gap(px(8.)) + .child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(tr!( + "history.watch.runSummary", + shown = runs.len(), + total = watch["totalRuns"], + points = watch["totalPoints"] + )), + ) + .child( + self.btn_small( + "watch-earlier", + label("history.watch.earlier"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-earlier")) + .disabled(watch["hasEarlier"] != true) + .on_click(cx.listener({ + let before = watch["firstSequence"].clone(); + move |this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"page","before":before}), + window, + cx, + ) + } + })), + ) + .child( + self.btn_small( + "watch-latest", + label("history.watch.latest"), + None, + Tone::Plain, + ) + .child(self.watch_anchor("watch-latest")) + .disabled(watch["hasLater"] != true) + .on_click(cx.listener(|this, _, window, cx| { + this.preference( + "watchProcess", + json!({"op":"page","before":null}), + window, + cx, + ) + })), + ), + ); + if watch["damaged"] == true { + card = card.child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label("history.watch.damaged")), + ); + } + if number(watch, "unconfirmed") > 0. { + card = card.child(div().text_size(theme::font(12.)).text_color(p.muted).child( + tr!("history.watch.unconfirmed", count = watch["unconfirmed"]), + )); + } + } + if let Some(message) = self.data.get("watchError").and_then(Value::as_str) { + card = card.child(div().text_size(theme::font(12.)).child(message.to_owned())); + } + if !points.is_empty() { + card = card.child( + div() + .h(px(110.)) + .border_1() + .border_color(p.stroke) + .rounded(px(4.)) + .bg(p.chart_surface) + .child(charts::TimePlot { + id: "process-watch-memory".into(), + series, + start, + end, + max: maximum * 1.1, + min: 0., + interactive: true, + grid: true, + fill: false, + background_separate: false, + smooth: false, + ticks: None, + geometry_start: start, + measured_width: Rc::new(Cell::new(1.)), + live_clock: None, + image_surface: Default::default(), + dash_phases: Default::default(), + rescale: Default::default(), + readout: Default::default(), + captions: None, + }), + ); + } + card = card.child( + div() + .text_size(theme::font(12.)) + .text_color(p.muted) + .child(label(if program_mode { + "history.watch.programNote" + } else { + "history.watch.note" + })), + ); + for point in points + .iter() + .filter(|point| text(point, "state") != "recording") + .rev() + .take(6) + .collect::>() + .into_iter() + .rev() + { + card = card.child(div().text_size(theme::font(12.)).text_color(p.muted).child( + format!( + "{} — {}", + date_time(number(point, "ts")), + label(&format!("history.watch.state.{}", text(point, "state"))) + ), + )); + } + card.into_any_element() + } +} diff --git a/src-gpui/src/frontend/pages/settings.rs b/src-gpui/src/frontend/pages/settings.rs index a392c7b4..59170715 100644 --- a/src-gpui/src/frontend/pages/settings.rs +++ b/src-gpui/src/frontend/pages/settings.rs @@ -3918,6 +3918,16 @@ impl Desktop { } "clear_history" => { self.ui.busy.remove("clearHistory"); + let generation = self + .data + .get("watchGeneration") + .and_then(Value::as_u64) + .unwrap_or(0) + + 1; + self.data + .insert("watchGeneration".into(), json!(generation)); + self.data.insert("processWatch".into(), Value::Null); + self.data.remove("watchError"); self.notify_toast_for( ToastKind::Success, label("settings.data.history.cleared"), diff --git a/src-gpui/src/frontend/test_control.rs b/src-gpui/src/frontend/test_control.rs index 9ca8f15d..64e33814 100644 --- a/src-gpui/src/frontend/test_control.rs +++ b/src-gpui/src/frontend/test_control.rs @@ -623,9 +623,7 @@ impl Desktop { && (f32::from(viewport.height) - client.bottom as f32).abs() < 1. })) }); - println!( - "{}", - json!({"event":"ui-layout","label":label,"page":self.page,"device":self.device, + let mut layout = json!({"event":"ui-layout","label":label,"page":self.page,"device":self.device, "vitals":self.vitals_band_state(), "visibility":{"enabled":self.prefs.get::(visibility::preference(&self.page),false), "pids":self.rows.iter().filter(|row|row.section.is_none()).flat_map(|row| if row.members.is_empty(){std::slice::from_ref(&row.raw)}else{row.members.as_slice()}).filter_map(|p|p["pid"].as_u64()).collect::>()}, @@ -657,8 +655,10 @@ impl Desktop { "performanceCardHeight":self.perf_card_chrome.get().map(|chrome| f32::from(window.viewport_size().height - chrome)), "aboutScroll":{"max":about_max,"offset":about_offset,"canScroll":about_max > 0.5, "atEnd":about_max > 0.5 && (about_offset-about_max).abs() < 0.5}, - "settingsScrollY":f32::from(self.settings_scroll.max_offset().y),"settingsTop":self.settings_scroll.top_item()}) - ); + "settingsScrollY":f32::from(self.settings_scroll.max_offset().y),"settingsTop":self.settings_scroll.top_item()}); + layout["watch"] = json!(self.data.get("processWatch").map(|watch|json!({"pid":watch["pid"],"state":watch["state"],"mode":watch["mode"],"runs":values(&watch["runs"]).len(),"liveRuns":watch["liveRuns"],"points":values(&watch["points"]).len(),"missing":values(&watch["points"]).iter().filter(|point|point["memory"].is_null()).count()}))); + layout["watchAction"] = json!(self.data.get("watchLastAction")); + println!("{layout}"); } if self.options.fixture.is_some() && let Some(key) = control["clickHeader"].as_str() diff --git a/tools/window-probe/fixtures/process-watch.mjs b/tools/window-probe/fixtures/process-watch.mjs new file mode 100644 index 00000000..6a61c5b8 --- /dev/null +++ b/tools/window-probe/fixtures/process-watch.mjs @@ -0,0 +1,29 @@ +// Window test data; accepts a WatchView exported by the real process_watch example. +// Without an input path the trajectory is synthetic. No process commands run. +import {mkdirSync,readFileSync,writeFileSync} from 'node:fs'; +const base=Date.now()-40000; +const point=(offset,memory,state='recording')=>({ts:base+offset,memory,commit:memory===null?null:memory+1048576,state}); +const recorded=process.argv[2]?JSON.parse(readFileSync(process.argv[2],'utf8')):{version:1,pid:44101,createTime:base-1000,name:'controlled-memory-helper',state:'exited',points:[point(0,4<<20),point(5000,4<<20),point(10000,12<<20),point(15000,null,'gap'),point(30000,2<<20),point(35000,null,'exited')]}; +const fixture=JSON.parse(readFileSync(new URL('desktop.json',import.meta.url),'utf8')); +fixture.snapshot.processes=[{...fixture.snapshot.processes[0],pid:recorded.pid,ppid:0,createTime:recorded.createTime,instanceKey:undefined,name:recorded.name,description:recorded.name,appWindow:true}]; +fixture.snapshot.system.processCount=1; +fixture.processWatch=null; +mkdirSync('target',{recursive:true}); +writeFileSync('target/process-watch.json',JSON.stringify(fixture)); +const active={...recorded,state:'recording',points:recorded.points.filter(point=>point.state==='recording').slice(0,3)}; +const stopped={...active,state:'stopped',points:[...active.points,{ts:recorded.points.at(-1).ts,memory:null,commit:null,state:'stopped'}]}; +const resolve=(action,value,generation)=>({resolve:{command:'watch_process',args:{action:{op:action},generation},ok:true,value}}); +const steps=[ + {control:{page:'processes',view:'list',selectRow:0,pointerOutside:true},wait:700,inspect:'layout',label:'selected',expect:{'processTree.visibleRows':1},capture:'start-button'}, + {control:{clickAnchor:'details-watch'},wait:300,inspect:'layout',label:'start-action',expect:{'watchAction.op':'start','watchAction.pid':recorded.pid}}, + {control:resolve('start',active,1),wait:600,inspect:'layout',label:'recording',expect:{page:'history','watch.state':'recording','watch.points':active.points.length},capture:'recording'}, + {control:{clickAnchor:'watch-stop'},wait:300,inspect:'layout',label:'stop-action',expect:{'watchAction.op':'stop'}}, + {control:resolve('stop',stopped,2),wait:400,inspect:'layout',label:'stopped',expect:{'watch.state':'stopped'},capture:'stopped'}, + {control:resolve('status',recorded,2),wait:500,inspect:'layout',label:'real-exit-and-gap',expect:{'watch.state':'exited','watch.missing':recorded.points.filter(point=>point.memory===null).length},capture:'exit-and-gap'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:900,capture:'small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 800',wait:900}, + {control:{clickAnchor:'watch-delete'},wait:300,inspect:'layout',label:'delete-action',expect:{'watchAction.op':'delete'}}, + {control:resolve('delete',null,3),wait:400,inspect:'layout',label:'deleted',expect:{'watch.state':null,'watch.points':0},capture:'deleted'}, + {control:resolve('status',active,2),wait:300,inspect:'layout',label:'stale-status-rejected',expect:{'watch.state':null,'watch.points':0}}, +]; +writeFileSync('target/process-watch-steps.json',JSON.stringify({window:[1200,800],source:process.argv[2]??'synthetic',steps},null,2)); diff --git a/tools/window-probe/fixtures/program-watch.mjs b/tools/window-probe/fixtures/program-watch.mjs new file mode 100644 index 00000000..5fbde301 --- /dev/null +++ b/tools/window-probe/fixtures/program-watch.mjs @@ -0,0 +1,61 @@ +// Native-window fixture: commands are mocked; actual identity/collector is tested in Rust. +import {readFileSync,writeFileSync,mkdirSync} from 'node:fs'; +const fixture=JSON.parse(readFileSync(new URL('desktop.json',import.meta.url),'utf8')); +const base=Date.now()-60000; +const pid=44101,created=base-20000; +const point=(ts,memory,state='recording')=>({ts,memory,commit:memory===null?null:memory+1048576,state}); +const runs=[ + {pid,createTime:created,firstTs:base,lastTs:base+15000,points:1008,state:'exited'}, + {pid:44102,createTime:base+16000,firstTs:base+20000,lastTs:base+50000,points:7,state:'recording'} +]; +const view={version:2,pid,createTime:created,name:'same.exe',mode:'program',state:'recording',liveRuns:1, + program:{nativePath:'\\Device\\HarddiskVolume3\\Argus test\\one\\same.exe',displayPath:'C:\\Argus test\\one\\same.exe'}, + runs,totalRuns:2,totalPoints:1008,runOffset:0,damaged:false,unconfirmed:0, + firstSequence:101,hasEarlier:true,hasLater:false, + points:[point(base,4<<20),point(base+5000,12<<20),point(base+10000,null,'gap'),point(base+15000,null,'exited')] +}; +fixture.snapshot.processes=[{...fixture.snapshot.processes[0],pid,ppid:0,createTime:created,instanceKey:undefined,name:'same.exe',description:'same.exe',appWindow:true}]; +fixture.snapshot.system.processCount=1; +fixture.processWatch=null; +const second={...view,pid:44102,createTime:runs[1].createTime,totalPoints:7,firstSequence:1200,hasEarlier:false, + points:[point(base+20000,2<<20),point(base+25000,3<<20),point(base+30000,4<<20)]}; +const earlier={...view,firstSequence:1,hasEarlier:false,hasLater:true,points:[point(base-40000,1<<20),point(base-35000,2<<20)]}; +const waiting={...view,liveRuns:0,runs:runs.map(run=>({...run,state:'exited'}))}; +const stopped={...waiting,state:'stopped'}; +const answer=(op,value,generation)=>({resolve:{command:'watch_process',args:{action:{op},generation},ok:true,value}}); +const steps=[ + {control:{page:'processes',view:'list',selectRow:0,pointerOutside:true},wait:700,capture:'two-choices'}, + {control:{clickAnchor:'details-watch-program'},wait:250,inspect:'layout',label:'start-program-action',expect:{'watchAction.op':'startProgram','watchAction.pid':pid}}, + {control:answer('startProgram',view,1),wait:600,inspect:'layout',label:'program-history',expect:{page:'history','watch.mode':'program','watch.runs':2,'watch.pid':pid},capture:'first-launch'}, + {control:{clickAnchor:'watch-earlier'},wait:250,inspect:'layout',label:'earlier-action',expect:{'watchAction.op':'page','watchAction.before':101}}, + {control:answer('page',earlier,2),wait:350,capture:'earlier-points'}, + {control:{clickAnchor:'watch-latest'},wait:200,inspect:'layout',label:'latest-action',expect:{'watchAction.op':'page','watchAction.before':null}}, + {control:answer('page',view,3),wait:300}, + {control:{clickSelect:'watch-run'},wait:250,capture:'launch-menu'}, + {control:{keys:['down','enter']},wait:250,inspect:'layout',label:'choose-second',expect:{'watchAction.op':'selectRun','watchAction.pid':44102}}, + {control:answer('selectRun',second,4),wait:400,inspect:'layout',label:'second-curve',expect:{'watch.pid':44102,'watch.points':3},capture:'second-launch'}, + {control:answer('status',waiting,4),wait:350,inspect:'layout',label:'waiting',expect:{'watch.state':'recording','watch.liveRuns':0},capture:'waiting'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:800,capture:'small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 900',wait:600}, + {control:{clickAnchor:'watch-stop'},wait:200,inspect:'layout',label:'stop-action',expect:{'watchAction.op':'stop'}}, + {control:answer('stop',stopped,5),wait:350,inspect:'layout',label:'stopped',expect:{'watch.state':'stopped','watch.points':4},capture:'stopped'}, + {control:{clickAnchor:'watch-delete'},wait:200,inspect:'layout',label:'delete-action',expect:{'watchAction.op':'delete'}}, + {control:answer('delete',null,6),wait:300,inspect:'layout',label:'deleted',expect:{'watch.state':null}}, + {control:answer('status',view,5),wait:250,inspect:'layout',label:'stale-rejected',expect:{'watch.state':null}} +]; +mkdirSync('target',{recursive:true}); +writeFileSync('target/program-watch.json',JSON.stringify(fixture)); +writeFileSync('target/program-watch-steps.json',JSON.stringify({window:[1200,900],steps},null,2)); +if(process.argv[2]){ + const real=JSON.parse(readFileSync(process.argv[2],'utf8')); + const last=real.runs.at(-1); + const realSteps=[ + {control:{page:'history',pointerOutside:true},wait:400}, + {control:answer('status',real,0),wait:600,inspect:'layout',label:'real-runs',expect:{'watch.mode':'program','watch.runs':real.runs.length},capture:'real-recording'}, + {control:{contentZoom:1.5,theme:'light'},probe:'size 900 700',wait:700,capture:'real-small-150'}, + {control:{contentZoom:1,theme:'dark'},probe:'size 1200 900',wait:500}, + {control:{clickSelect:'watch-run'},wait:300,capture:'real-launch-list'}, + {control:{keys:[...Array(real.runs.length-1).fill('down'),'enter']},wait:300,inspect:'layout',label:'last-real-launch',expect:{'watchAction.op':'selectRun','watchAction.pid':last.pid}}, + ]; + writeFileSync('target/program-watch-real-steps.json',JSON.stringify({window:[1200,900],source:process.argv[2],steps:realSteps},null,2)); +}