nmbrs_runtime/session.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Session: the root context for a workload run.
5//!
6//! A session has a human-readable ID, a directory for all diagnostic
7//! artifacts (metrics, logs, flamegraphs), and is the root of the
8//! component tree for metrics labeling.
9//!
10//! Session ID format: `{scenario}_{YYYYMMDD_HHmmss}`
11//! Session directory: `logs/{session_id}/`
12//!
13//! All files from a run live under the session directory:
14//! - `metrics.db` — SQLite metrics
15//! - `flamegraph.svg` — profiler output
16//! - `session.log` — diagnostic log (future)
17
18use std::path::{Path, PathBuf};
19use std::sync::{Arc, Mutex, RwLock};
20
21use nmbrs_metrics::component::{Component, ComponentState, attach};
22use nmbrs_metrics::labels::Labels;
23use nmbrs_metrics::metrics_query::MetricsQuery;
24
25/// SRD-77 — one invocation of `nmbrs <verb>` within a
26/// [`Session`]. The session is the persistent container;
27/// each execution is the unit of "what was attempted at
28/// this point in time, with what workload version, and how
29/// did it dispose?" Every per-phase / per-metric row carries
30/// the owning execution's [`Self::exec_id`] as a dimensional
31/// label so cross-execution queries can scope cleanly.
32///
33/// Until the SRD-77 `refine` verb lands the per-session
34/// monotonic registry, every session has exactly one
35/// execution with `exec_id = 1`. The shape exists now so the
36/// SRD-76 storage layer (`phase_outcomes` / `phase_errors`)
37/// and the component tree's root labels (`session`,
38/// `exec_id`) honour the eventual SRD-77 contract from day
39/// one — no later schema migration is required.
40#[derive(Clone)]
41pub struct Execution {
42 /// Monotonic per-session sequence (`1, 2, 3, ...`).
43 /// SRD-77's `refine` verb bumps it; SRD-88's concurrent
44 /// harness allocates a distinct id per in-flight execution.
45 pub exec_id: u64,
46 /// Which verb launched this execution: `"run"` /
47 /// `"resume"` / `"refine"`. Operator-visible via the SRD-77
48 /// `executions` table and replay header.
49 pub verb: &'static str,
50 /// Wall-clock nanos-since-epoch at execution start.
51 pub started_at_nanos: i64,
52 /// The workload's bare stem (the `workload=` dimensional
53 /// label and the `executions.workload` column for THIS
54 /// execution). Per SRD-88 this is execution-tier identity,
55 /// not session-tier: N executions sharing one session each
56 /// carry their own.
57 pub workload: String,
58 /// Scenario name for this execution (metadata, not a
59 /// dimensional label).
60 pub scenario: String,
61 /// This execution's component — a child of the session
62 /// component (SRD-88 §2). Carries the `exec_id` + `workload`
63 /// labels; phase/activity components attach under it so
64 /// every metric inherits this execution's identity. The
65 /// session component above it carries only `session=<id>`
66 /// and is shared by every concurrent execution.
67 pub component: Arc<RwLock<Component>>,
68}
69
70impl Execution {
71 /// Start an execution under `session`: derive its
72 /// [`Execution::component`] as a child of the session
73 /// component, labelled with this execution's `exec_id` +
74 /// `workload` stem (SRD-88 §2 — the session is the shared
75 /// common root, each execution derives from it). `exec_id`
76 /// is `1` for a fresh `run`/`resume`, the refine plan's
77 /// `next_exec_id` for `refine`, or a distinct allocated id
78 /// for a concurrent execution.
79 pub fn start(
80 session: &Session,
81 workload: &str,
82 scenario: &str,
83 verb: &'static str,
84 exec_id: u64,
85 ) -> Self {
86 let workload_stem = Path::new(workload)
87 .file_stem()
88 .and_then(|s| s.to_str())
89 .unwrap_or("workload");
90 // Execution-tier labels: `exec_id` + `workload`. The
91 // parent session component already carries `session`;
92 // `attach` composes the two so descendant metrics see
93 // the full `{session, exec_id, workload}` set, exactly
94 // as the pre-SRD-88 single-tier root did.
95 let component = Arc::new(RwLock::new(Component::new(
96 Labels::of("exec_id", exec_id.to_string()).with("workload", workload_stem),
97 std::collections::HashMap::new(),
98 )));
99 attach(&session.component, &component);
100 component
101 .write()
102 .unwrap_or_else(|e| e.into_inner())
103 .set_state(ComponentState::Running);
104 Self {
105 exec_id,
106 verb,
107 started_at_nanos: std::time::SystemTime::now()
108 .duration_since(std::time::UNIX_EPOCH)
109 .map(|d| d.as_nanos() as i64)
110 .unwrap_or(0),
111 workload: workload_stem.to_string(),
112 scenario: scenario.to_string(),
113 component,
114 }
115 }
116}
117
118impl std::fmt::Debug for Execution {
119 /// Identity fields only — the component is an `Arc<RwLock<…>>`
120 /// into the live tree and not meaningfully `Debug`-printable.
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 f.debug_struct("Execution")
123 .field("exec_id", &self.exec_id)
124 .field("verb", &self.verb)
125 .field("started_at_nanos", &self.started_at_nanos)
126 .field("workload", &self.workload)
127 .field("scenario", &self.scenario)
128 .finish_non_exhaustive()
129 }
130}
131
132/// A workload run session.
133///
134/// The session is the root of the component tree and — once the
135/// runner has installed one — holds the shared [`MetricsQuery`] that
136/// every in-process reader (TUI, summary, Polydat metric nodes) reads
137/// through. See SRD-42 §"MetricsQuery — the unified read interface".
138///
139/// Per SRD-77, the session is a persistent container; each
140/// [`Execution`] started under it is the unit
141/// of in-flight work. Both ride on the component tree as the
142/// `session` + `exec_id` dimensional labels so every metric
143/// the descendant components emit inherits them.
144pub struct Session {
145 /// Session identifier (the session-directory basename).
146 /// Surfaces as the `session` dimensional label on every
147 /// per-component metric via [`Self::component`].
148 pub id: String,
149 /// Output directory for diagnostic artifacts (metrics, logs, flamegraphs).
150 /// Located at `logs/{id}/`. Not the working directory.
151 pub output_dir: PathBuf,
152 /// Session root component — **one per process** (SRD-88 §2).
153 /// Owns the `session=<id>` dimensional label and nothing
154 /// else; per-execution identity (`exec_id`, `workload`)
155 /// lives on the [`Execution::component`] children that hang
156 /// under it. Each label name is owned by exactly one tier
157 /// and never redeclared below it.
158 pub component: Arc<RwLock<Component>>,
159 /// Shared `MetricsQuery` handle — installed by the runner once the
160 /// cadence reporter is built. `None` before the runner wires it.
161 pub metrics_query: Mutex<Option<Arc<MetricsQuery>>>,
162}
163
164/// The file in a session directory whose advisory lock says "a process is
165/// using this session". A process that creates or re-attaches a
166/// [`Session`] holds it shared until it exits ([`keep_session_live`]);
167/// [`purge_stale_sessions`] deletes a directory only when it can take it
168/// exclusively.
169const SESSION_LIVENESS_FILE: &str = "session.lock";
170
171/// Hold the liveness lock of the session at `dir` until this process exits.
172///
173/// Process lifetime, not [`Session`] lifetime: a run keeps using its session
174/// directory after the `Session` value is gone — the end-of-run report and
175/// summary open `metrics.db` once the executions have shut down — and a
176/// concurrent run's cleanup must not delete it in that window either.
177fn keep_session_live(dir: &Path) {
178 static HELD: Mutex<Vec<std::fs::File>> = Mutex::new(Vec::new());
179 if let Some(file) = hold_session_liveness(dir) {
180 HELD.lock().unwrap_or_else(|e| e.into_inner()).push(file);
181 }
182}
183
184/// Take the shared liveness lock on the session at `dir`, to be held for the
185/// life of the returned handle. Shared, so a second process attached to the
186/// same session (a resume racing the original, a reader) is not refused
187/// here — that conflict belongs to the checkpoint writer's exclusive lock.
188fn hold_session_liveness(dir: &Path) -> Option<std::fs::File> {
189 let path = dir.join(SESSION_LIVENESS_FILE);
190 let held = std::fs::OpenOptions::new()
191 .read(true)
192 .write(true)
193 .create(true)
194 .truncate(false)
195 .open(&path)
196 .and_then(|file| file.lock_shared().map(|()| file));
197 match held {
198 Ok(file) => Some(file),
199 Err(e) => {
200 crate::observer::log(
201 crate::observer::LogLevel::Warn,
202 &format!(
203 "warning: could not hold the session liveness lock {}: {e} \
204 (another run's session cleanup may delete this session while it runs)",
205 path.display(),
206 ),
207 );
208 None
209 }
210 }
211}
212
213/// Whether some process holds the liveness lock of the session at `dir`.
214/// A directory with no lock file is not live. One whose lock cannot be
215/// examined is reported live: the caller is deciding whether to delete it.
216fn session_is_live(dir: &Path) -> bool {
217 let file = match std::fs::File::open(dir.join(SESSION_LIVENESS_FILE)) {
218 Ok(file) => file,
219 Err(e) => return e.kind() != std::io::ErrorKind::NotFound,
220 };
221 // Taken and released at once: the lock goes with the handle.
222 file.try_lock().is_err()
223}
224
225/// Translate a CLI flag name (`--session-path`) into its
226/// canonical `NMBRS_`-prefixed env-var name (`NMBRS_SESSION_PATH`).
227/// Per SRD-04, every CLI flag automatically has an env-var
228/// equivalent following this convention.
229pub fn flag_env_name(flag: &str) -> String {
230 let stem = flag.trim_start_matches("--");
231 format!("NMBRS_{}", stem.replace('-', "_").to_ascii_uppercase())
232}
233
234/// Resolve a flag value from CLI args + its `NMBRS_`-prefixed
235/// env var. Returns `None` if neither is set. **Exits with
236/// status 2** if BOTH are set — configuration conflict; we
237/// refuse to silently disambiguate.
238///
239/// Per SRD-04 the env-var name is automatically derived from
240/// the flag name (`--foo-bar` → `NMBRS_FOO_BAR`).
241pub fn resolve_flag(args: &[String], flag: &str) -> Option<String> {
242 let cli = {
243 let eq_prefix = format!("{flag}=");
244 let mut iter = args.iter();
245 let mut found = None;
246 while let Some(arg) = iter.next() {
247 if let Some(rest) = arg.strip_prefix(&eq_prefix) {
248 found = Some(rest.to_string());
249 break;
250 }
251 if arg == flag {
252 found = iter.next().cloned();
253 break;
254 }
255 }
256 found
257 };
258 let env_name = flag_env_name(flag);
259 let env = std::env::var(&env_name)
260 .ok()
261 .filter(|v| !v.trim().is_empty());
262 match (cli, env) {
263 (Some(_), Some(_)) => {
264 eprintln!(
265 "error: configuration conflict — both `{flag}` (CLI) and \
266 `{env_name}` (env) are set. Pick one. Per SRD-04, every \
267 CLI flag has an env equivalent prefixed with `NMBRS_`; \
268 specifying both at once is a hard error so the operator \
269 sees their inputs are fighting."
270 );
271 std::process::exit(2);
272 }
273 (Some(v), None) | (None, Some(v)) => Some(v),
274 (None, None) => None,
275 }
276}
277
278/// Classify a session-path value: does it look like a
279/// `key=value` workload-param token (e.g. `scenario=foo`)
280/// rather than a real filesystem path? The umbrella
281/// `--session <kv>` parser splits only on `:`, so a
282/// `=`-shaped token slipping into the path slot would silently
283/// materialise directories like `<cwd>/scenario=foo/...`.
284///
285/// Heuristic: the head of `head=tail` matches the workload-
286/// param ABNF (alphanumeric / underscore / hyphen, no slash).
287/// A real path like `/var/tmp/k=v` keeps a leading slash in
288/// the head and passes through unchanged. Leading `./` or
289/// `../` likewise excludes the head from the param-shape
290/// check (the head contains a `/`).
291///
292/// Returns `Err(<error message>)` when the value should be
293/// rejected; `Ok(())` when it's safe to use as a session
294/// path.
295pub fn check_session_path(p: &str, source: &str) -> Result<(), String> {
296 if let Some((head, _)) = p.split_once('=') {
297 let head_looks_like_param = !head.is_empty()
298 && head
299 .chars()
300 .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
301 && !head.contains('/');
302 if head_looks_like_param {
303 return Err(format!(
304 "session path from {source} is '{p}' — that looks \
305 like a `key=value` workload param, not a path. The umbrella \
306 `--session <kv>` parser splits only on `:`, so this would \
307 silently create a `<cwd>/{p}/…` directory tree. \
308 Did you mean: `--session-path <path>` (with `{p}` as a \
309 separate workload arg), or `--session path:<path>` (umbrella \
310 form, `:` as the kv separator)?"
311 ));
312 }
313 }
314 Ok(())
315}
316
317/// Wrapper around [`check_session_path`] that prints to
318/// stderr and exits with code 2 on rejection. Used at every
319/// entry point that sets `session_path` from CLI / env input:
320/// [`parse_session_kv`] (bare-token branch and `path:`/`dir:`
321/// keys) and [`resolve_session_dir`] for `--session-path`
322/// (flag or `NMBRS_SESSION_PATH` env). Same exit-
323/// shape as the existing `--session` configuration-conflict
324/// error in [`resolve_flag`].
325pub(crate) fn validate_session_path_or_exit(p: &str, source: &str) {
326 if let Err(msg) = check_session_path(p, source) {
327 eprintln!("error: {msg}");
328 std::process::exit(2);
329 }
330}
331
332/// Token within a session-dir path that's replaced with the
333/// auto-generated session id at write time. Lets users template
334/// per-run directories without changing the path between runs:
335/// `--session-path /data/sessions/SESSION_run` →
336/// `/data/sessions/default_20260101_120000_run`.
337pub const SESSION_TOKEN: &str = "SESSION";
338
339/// Policy when a session about to be created lands on an
340/// existing, non-empty session directory.
341///
342/// Defaults to `Error` so accidental reuse can never silently
343/// destroy a prior session's artifacts.
344#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
345pub enum SessionReuse {
346 /// Refuse to start. Exit with a clear message naming the
347 /// existing path and the available reuse-mode flags.
348 /// Default when `--session-reuse` is not specified.
349 #[default]
350 Error,
351 /// Wipe the existing artifacts (`metrics.db`, `session.log`,
352 /// `checkpoint.jsonl`, `summary.md`, etc.) and start fresh.
353 /// The dir itself stays; only its contents are cleared.
354 Restart,
355 /// Continue with the existing session — equivalent to
356 /// `--resume <session>` against this directory. Surfaces a
357 /// hint if the operator probably wanted Restart.
358 Resume,
359}
360
361impl SessionReuse {
362 /// Parse from a string value (CLI flag or env var).
363 /// Accepts `error` / `restart` / `resume`, case-insensitive.
364 pub fn parse(s: &str) -> Result<Self, String> {
365 match s.trim().to_ascii_lowercase().as_str() {
366 "error" | "fail" | "abort" => Ok(Self::Error),
367 "restart" | "wipe" | "clean" => Ok(Self::Restart),
368 "resume" | "continue" => Ok(Self::Resume),
369 other => Err(format!(
370 "session-reuse: expected one of 'error' | 'restart' | 'resume', got '{other}'",
371 )),
372 }
373 }
374}
375
376/// Where the default session directory lives when the user hasn't
377/// passed `--session-path`. Three cases:
378///
379/// * **Normal invocation** (installed binary, user shell): the
380/// session lands at `<cwd>/logs/<id>`. This is the documented,
381/// long-standing user-facing behavior.
382///
383/// * **In-process tests that pre-sandboxed cwd** (e.g.
384/// `checkpoint_resume_staircase` `in_dir(tmp, runner::run)`):
385/// `<cwd>/logs/<id>` is already inside the test's tempdir
386/// sandbox, so leave it alone — the test reads back from
387/// `<cwd>/logs/latest` and would be broken by a redirect.
388///
389/// * **Cargo-spawned invocation where cwd lands inside the
390/// workspace** (`cargo test` integration tests that spawn
391/// `nmbrs` as a subprocess without `--session-path`, plus
392/// `cargo run --bin nmbrs` runs from the workspace root):
393/// the default would otherwise be the user-visible
394/// `<workspace>/logs/<id>`, and the `session-keep` rotation
395/// would evict real run sessions. Redirect into
396/// `$TMPDIR/nmbrs-sessions/<id>` — `.cargo/config.toml`
397/// already points `TMPDIR` at `<workspace>/target/test-tmp`,
398/// so cargo-spawned sessions live in `target/test-tmp/`
399/// alongside other test artifacts. See
400/// `feedback_tests_no_project_root`.
401///
402/// Tests that want to read back their session contents must
403/// still pass `--session-path` to a known path — this
404/// fallback is the blast-radius limiter, not a substitute for
405/// explicit sandboxing.
406pub fn default_session_dir(id: &str) -> PathBuf {
407 default_sessions_root().join(id)
408}
409
410/// Resolve the parent directory the runtime treats as the session
411/// root when `--session-path` is absent. See [`default_session_dir`]
412/// for the three-case logic.
413/// `<root>/latest` — the symlink the runtime maintains to point
414/// at the most recent session dir. Read-side commands
415/// (`nmbrs report`, `nmbrs report plot`, `nmbrs replay`, …) default to
416/// reading through this path so "show me my latest run" is the
417/// natural no-arg invocation.
418pub fn latest_session_dir() -> PathBuf {
419 default_sessions_root().join("latest")
420}
421
422/// `<root>/latest/metrics.db` — the sqlite db of the most recent
423/// session. Centralised here so every read-side command names
424/// the path one way.
425pub fn latest_metrics_db() -> PathBuf {
426 latest_session_dir().join("metrics.db")
427}
428
429/// `<root>/latest/session.log` — the diagnostic log of the most
430/// recent session. `nmbrs attach` / log tooling reads from here.
431pub fn latest_session_log() -> PathBuf {
432 latest_session_dir().join("session.log")
433}
434
435/// `<root>/latest/checkpoint.jsonl` — the SRD-44 event log of
436/// the most recent session. The resume planner reads from here.
437pub fn latest_checkpoint_jsonl() -> PathBuf {
438 latest_session_dir().join("checkpoint.jsonl")
439}
440
441/// `<root>/<name>` — a named session dir under the sessions root.
442/// Used by `--session=<name>` resolvers in read-side commands so
443/// the path doesn't get spelled out at every call site.
444pub fn session_dir_named(name: &str) -> PathBuf {
445 default_sessions_root().join(name)
446}
447
448/// Whether the CLI args request a dry-run (any `dryrun=<mode>` with a
449/// non-empty, non-false value). A dry-run is resume-INERT: it must NOT
450/// claim the `latest` symlink and must NOT write a checkpoint, so a
451/// later `--resume-latest` can never pick a dry-run up and resume from
452/// its (placeholder / short-circuited) phases (SRD-44). Detected from
453/// raw args so both `Session::new_with_args` (the `latest` claim) and
454/// `SessionHost::setup` (the checkpoint writer) gate on one signal.
455pub fn args_request_dryrun(args: &[String]) -> bool {
456 args.iter().any(|a| {
457 let a = a.strip_prefix("--").unwrap_or(a);
458 a.strip_prefix("dryrun=")
459 .map(|v| {
460 let v = v.trim();
461 !v.is_empty() && v != "false" && v != "0"
462 })
463 .unwrap_or(false)
464 })
465}
466
467/// Create a symlink at `link` pointing at `target` (which may be
468/// relative to `link`'s parent dir). On Unix this is plain
469/// `symlink`; Windows separates file and directory symlinks, so
470/// resolve the target and pick the matching flavor. Windows
471/// symlink creation needs Developer Mode (or admin) — callers
472/// treat failure as best-effort, same as on Unix.
473pub(crate) fn symlink_any(target: &Path, link: &Path) -> std::io::Result<()> {
474 #[cfg(unix)]
475 {
476 std::os::unix::fs::symlink(target, link)
477 }
478 #[cfg(windows)]
479 {
480 // Callers clear a previous link with `remove_file`, which
481 // on Windows cannot delete a DIRECTORY symlink or junction
482 // (those are directory entries) — clean up leftovers here
483 // so re-pointing works.
484 if let Ok(md) = std::fs::symlink_metadata(link)
485 && (md.file_type().is_symlink() || md.file_type().is_dir())
486 {
487 let _ = std::fs::remove_file(link);
488 let _ = std::fs::remove_dir(link);
489 }
490 let resolved = match link.parent() {
491 Some(p) => p.join(target),
492 None => target.to_path_buf(),
493 };
494 if resolved.is_dir() {
495 // Real symlinks need Developer Mode / admin; a
496 // directory junction needs no privilege and reads back
497 // through `fs::read_link` just the same (with an
498 // absolute target — consumers here already resolve
499 // both shapes). Junction targets must be absolute.
500 std::os::windows::fs::symlink_dir(target, link).or_else(|_| {
501 let abs = std::path::absolute(&resolved)?;
502 junction::create(&abs, link)
503 })
504 } else {
505 // File fallback: a same-volume hard link. Appends to
506 // the original show up through it (same file), and the
507 // artifact links are recreated at each session
508 // start / artifact production, which bounds staleness.
509 std::os::windows::fs::symlink_file(target, link)
510 .or_else(|_| std::fs::hard_link(&resolved, link))
511 }
512 }
513}
514
515/// Point `<sessions-root>/latest` at `session_dir`, but only when
516/// the dir lives under the sessions root — a path the user
517/// redirected elsewhere (`--session-path /tmp/x`) is left alone,
518/// same guard as the startup hook. Best-effort: symlink failures
519/// warn rather than abort.
520pub fn point_latest_at(session_dir: &Path) {
521 let root = default_sessions_root();
522 if !target_is_under(&root, session_dir) {
523 return;
524 }
525 if std::fs::create_dir_all(&root).is_err() {
526 return;
527 }
528 let latest = root.join("latest");
529 let relative_target = relative_symlink_target(&latest, session_dir);
530 let _ = std::fs::remove_file(&latest);
531 let _ = symlink_any(&relative_target, &latest);
532}
533
534/// Initialize a NEW, empty session: create its directory, the
535/// `metrics.db` schema, and the invariant `session` metadata — but
536/// record NO execution (nothing has run). Points `latest` at it.
537/// A later `run`/`refine` attaches the first execution.
538///
539/// `explicit_path` overrides the default `<sessions-root>/<id>`
540/// location. `reuse` governs an already-populated directory.
541pub fn init_empty_session(
542 id: &str,
543 explicit_path: Option<&Path>,
544 reuse: SessionReuse,
545) -> Result<PathBuf, String> {
546 let dir = match explicit_path {
547 Some(p) => p.to_path_buf(),
548 None => default_session_dir(id),
549 };
550 let metrics_db = dir.join("metrics.db");
551 if metrics_db.exists() {
552 match reuse {
553 SessionReuse::Error => {
554 return Err(format!(
555 "session '{id}' already exists at {} — pass session-reuse=restart to \
556 overwrite, session-reuse=resume to keep it, or choose another name",
557 dir.display(),
558 ));
559 }
560 SessionReuse::Restart => {
561 let _ = std::fs::remove_file(&metrics_db);
562 }
563 SessionReuse::Resume => return Ok(dir),
564 }
565 }
566 std::fs::create_dir_all(&dir)
567 .map_err(|e| format!("create session dir {}: {e}", dir.display()))?;
568 {
569 // `SqliteReporter::new` creates the schema; writing the
570 // invariant `session` key seeds session_metadata. Dropping
571 // the reporter flushes (writes auto-commit).
572 let mut reporter = nmbrs_metrics::reporters::sqlite::SqliteReporter::new(&metrics_db)
573 .map_err(|e| format!("create metrics.db at {}: {e}", metrics_db.display()))?;
574 reporter.set_metadata("session", id);
575 }
576 point_latest_at(&dir);
577 Ok(dir)
578}
579
580pub fn default_sessions_root() -> PathBuf {
581 if cwd_is_workspace_dir() {
582 // Cargo-spawned invocation, cwd is a cargo workspace
583 // dir (`Cargo.toml` present) — the cwd-relative default
584 // would write into the user-visible `<workspace>/sessions/`.
585 // Redirect to TMPDIR (per `.cargo/config.toml`, this is
586 // `<workspace>/target/test-tmp/`), under an
587 // `nmbrs-sessions/` infix so siblings tempfiles stay
588 // segregated.
589 std::env::temp_dir().join("nmbrs-sessions")
590 } else {
591 // SRD-77: `sessions/` is the per-cwd default. The
592 // directory holds session state (metrics.db,
593 // session.log, checkpoints, reports), not just logs.
594 // Pre-SRD-77 builds wrote to `logs/`; the migration is
595 // flag-day (no auto-rename — operators run a one-shot
596 // `mv logs sessions` if they care about retention).
597 PathBuf::from("sessions")
598 }
599}
600
601/// `true` when both (a) we're running under cargo
602/// (`CARGO_MANIFEST_DIR` env present, inherited from the cargo
603/// parent through `std::process::Command`'s default env-inherit)
604/// and (b) the current working directory has a `Cargo.toml` at
605/// its root (workspace member or workspace root). Tests that
606/// sandbox cwd into a tempdir won't satisfy (b) — the redirect
607/// stays off for those.
608fn cwd_is_workspace_dir() -> bool {
609 if std::env::var_os("CARGO_MANIFEST_DIR").is_none() {
610 return false;
611 }
612 std::env::current_dir()
613 .map(|cwd| cwd.join("Cargo.toml").is_file())
614 .unwrap_or(false)
615}
616
617/// Resolved session inputs from CLI / env. Built by
618/// [`resolve_session_dir`] from one of:
619///
620/// - The umbrella `--session <kv-list>` flag (a
621/// comma-separated list of `key:value` pairs and bare
622/// shortcuts).
623/// - Per-key long-form flags (`--session-name`,
624/// `--session-path`, `--session-reuse`, `--session-keep`,
625/// `--session-shelflife`).
626/// - The `NMBRS_`-prefixed env equivalent of each per-key flag
627/// (`NMBRS_SESSION_PATH`, …; SRD-04).
628///
629/// When both forms are present the long-form flag wins; the
630/// umbrella flag is shorthand. Within the umbrella value the
631/// last-wins rule applies if a key is repeated.
632#[derive(Debug, Clone, Default)]
633pub struct SessionDirSpec {
634 /// `name` — session id (basename of the session directory).
635 /// Used in metric labels and as the resolved value of the
636 /// `SESSION` token in `path`. When unset, defaults to the
637 /// auto-generated `<scenario>_<timestamp>` form.
638 pub session_name: Option<String>,
639 /// `path` — full directory path. Optional `SESSION` token
640 /// inside the path is replaced with `session_name` at write
641 /// time. When unset, the path is `logs/<session_name>/`.
642 pub session_path: Option<String>,
643 /// `reuse` — policy when the resolved directory already
644 /// contains prior session artifacts. Default `Error`.
645 pub reuse: SessionReuse,
646 /// `keep` — number of session directories retained under
647 /// the parent at startup. Default 10. `0` disables.
648 pub session_keep: usize,
649 /// `shelflife` — max age of a session directory before
650 /// purge at startup. Default 4 weeks. `0` disables.
651 pub session_shelflife: std::time::Duration,
652 /// SRD-106 — the umbrella bare token `new` (`--session new`):
653 /// force a fresh auto-named session. Its only consumer is the
654 /// `stick_session` resolution rung, which it defeats; with no
655 /// stick in play a fresh session is already the default, so
656 /// the token is a harmless no-op there.
657 pub force_new: bool,
658}
659
660impl SessionDirSpec {
661 /// `true` when no path/name flag is set — caller falls back
662 /// to the default `logs/<auto_id>/` behavior. (`reuse`,
663 /// `keep`, `shelflife` are always present at their defaults
664 /// and don't count toward "is this empty?".)
665 pub fn is_empty(&self) -> bool {
666 self.session_name.is_none() && self.session_path.is_none()
667 }
668
669 /// Resolve to a concrete `(output_dir, session_id)`.
670 ///
671 /// - `auto_id` is the fallback session name when
672 /// `session_name` is unset.
673 /// - The resolved id = `session_name.unwrap_or(auto_id)`.
674 /// - The resolved path = `session_path` (with `SESSION`
675 /// token replaced by the resolved id) if set, else
676 /// `logs/<id>/`.
677 ///
678 /// Returns `None` only when the spec is empty and the
679 /// caller should use defaults; otherwise `Some` with the
680 /// resolved values.
681 pub fn resolve(&self, auto_id: &str) -> Option<(PathBuf, String)> {
682 if self.is_empty() {
683 return None;
684 }
685 let id = self
686 .session_name
687 .clone()
688 .unwrap_or_else(|| auto_id.to_string());
689 let path = match &self.session_path {
690 Some(p) => PathBuf::from(p.replace(SESSION_TOKEN, &id)),
691 None => default_session_dir(&id),
692 };
693 // Re-derive id from basename so a path-only spec
694 // (`--session-path /tmp/foo`) still yields id="foo".
695 let id = path
696 .file_name()
697 .and_then(|s| s.to_str())
698 .map(String::from)
699 .unwrap_or(id);
700 Some((path, id))
701 }
702
703 /// `true` if the resolved path needs the auto-id (i.e.
704 /// neither `session_name` nor a fully-concrete
705 /// `session_path` is set). Used at startup to decide
706 /// whether `logs/latest` can be wired immediately or must
707 /// wait for session creation.
708 pub fn needs_auto_id(&self) -> bool {
709 if self.session_name.is_some() {
710 return false;
711 }
712 match self.session_path.as_deref() {
713 Some(p) => p.contains(SESSION_TOKEN),
714 None => true,
715 }
716 }
717}
718
719/// Parse the umbrella `--session <kv-list>` argument into a
720/// [`SessionDirSpec`]. The list is comma-separated; each item
721/// is either a bare shortcut (`restart`, `resume`, `error`)
722/// or a `key:value` pair.
723///
724/// Recognised keys (and their long-form flag equivalents):
725///
726/// | Key | Long-form flag |
727/// | -------------- | -------------------------- |
728/// | `name` | `--session-name` |
729/// | `path` / `dir` | `--session-path` |
730/// | `reuse` | `--session-reuse` |
731/// | `keep` | `--session-keep` |
732/// | `shelflife` | `--session-shelflife` |
733///
734/// Bare shortcuts:
735///
736/// | Token | Equivalent |
737/// | --------- | -------------- |
738/// | `restart` | `reuse:restart`|
739/// | `resume` | `reuse:resume` |
740/// | `error` | `reuse:error` |
741/// | `new` | force a fresh auto-named session (defeats `stick_session`) |
742///
743/// Whitespace around items + key/value separators is trimmed.
744/// Unknown keys produce a `Warn` log; the rest of the spec is
745/// kept (so a typo doesn't kill the run).
746pub fn parse_session_kv(s: &str) -> SessionDirSpec {
747 let mut spec = SessionDirSpec {
748 session_keep: DEFAULT_SESSIONS_MAX,
749 session_shelflife: DEFAULT_SESSIONS_SHELFLIFE,
750 ..SessionDirSpec::default()
751 };
752 for raw_item in s.split(',') {
753 let item = raw_item.trim();
754 if item.is_empty() {
755 continue;
756 }
757 // Bare shortcut?
758 match item {
759 "restart" => {
760 spec.reuse = SessionReuse::Restart;
761 continue;
762 }
763 "resume" => {
764 spec.reuse = SessionReuse::Resume;
765 continue;
766 }
767 "error" => {
768 spec.reuse = SessionReuse::Error;
769 continue;
770 }
771 // SRD-106 — `--session new`: force a fresh auto-named
772 // session, defeating a workload's `stick_session`.
773 // Intercepted here so the name heuristic below never
774 // reads it as `name:new`.
775 "new" => {
776 spec.force_new = true;
777 continue;
778 }
779 _ => {}
780 }
781 // A Windows drive-letter path (`C:\…` or `C:/…`) would
782 // split at its drive colon and read as unknown key "C" —
783 // recognize it as a bare path token before the key:value
784 // parse gets a look.
785 let drive_letter_path = item.len() >= 3
786 && item.as_bytes()[0].is_ascii_alphabetic()
787 && item.as_bytes()[1] == b':'
788 && matches!(item.as_bytes()[2], b'\\' | b'/');
789 // key:value pair takes precedence over the
790 // bare-token heuristics so `dir:/tmp/x` etc.
791 // disambiguate cleanly.
792 let kv = if drive_letter_path {
793 None
794 } else {
795 item.split_once(':')
796 };
797 let (key, value) = match kv {
798 Some((k, v)) => (k.trim(), v.trim()),
799 None => {
800 // Bare token without `:`. Two heuristics:
801 // - contains a path separator OR resolves to an
802 // existing directory → treat as `path:<value>`.
803 // Lets operators write
804 // `--session logs/fulltest_2026...` without
805 // remembering the `path:` prefix.
806 // - otherwise → session name (SRD-04
807 // most-specific-name rule).
808 if drive_letter_path
809 || item.contains('/')
810 || (cfg!(windows) && item.contains('\\'))
811 || std::path::Path::new(item).is_dir()
812 {
813 validate_session_path_or_exit(item, "umbrella `--session <bare-token>`");
814 spec.session_path = Some(item.to_string());
815 } else {
816 spec.session_name = Some(item.to_string());
817 }
818 continue;
819 }
820 };
821 match key {
822 "name" => spec.session_name = Some(value.to_string()),
823 "path" | "dir" => {
824 validate_session_path_or_exit(value, "umbrella `--session path:<v>`");
825 spec.session_path = Some(value.to_string());
826 }
827 "reuse" => match SessionReuse::parse(value) {
828 Ok(r) => spec.reuse = r,
829 Err(e) => crate::observer::log(
830 crate::observer::LogLevel::Warn,
831 &format!("--session: {e}"),
832 ),
833 },
834 "keep" => match value.parse::<usize>() {
835 Ok(n) => spec.session_keep = n,
836 Err(_) => crate::observer::log(
837 crate::observer::LogLevel::Warn,
838 &format!("--session: keep:{value:?} is not a non-negative integer"),
839 ),
840 },
841 "shelflife" => match parse_duration(value) {
842 Ok(d) => spec.session_shelflife = d,
843 Err(e) => crate::observer::log(
844 crate::observer::LogLevel::Warn,
845 &format!("--session: shelflife: {e}"),
846 ),
847 },
848 other => crate::observer::log(
849 crate::observer::LogLevel::Warn,
850 &format!(
851 "--session: unknown key {other:?} (recognised: name, path, dir, reuse, keep, shelflife)"
852 ),
853 ),
854 }
855 }
856 spec
857}
858
859/// The current flag for a retired `--session-*` spelling, for the
860/// unrecognized-flag error. The retired spellings are not accepted; this only
861/// lets the error name the flag the operator meant, which edit distance alone
862/// gets wrong (`--sessions-max` is closer to `--session-name` than to
863/// `--session-keep`).
864pub fn retired_flag_replacement(flag: &str) -> Option<&'static str> {
865 match flag {
866 "--sessions-max" => Some("--session-keep"),
867 "--sessions-shelflife" => Some("--session-shelflife"),
868 "--session-dir" => Some("--session-path"),
869 _ => None,
870 }
871}
872
873/// Reject a bare `session=<…>` argument. The session is named by
874/// `--session` alone, and a `session=` token would otherwise reach a command
875/// as an unrecognised parameter or positional, where a read-side command
876/// could report on the latest session while the operator named another.
877/// Checked once, at startup, for every command.
878pub fn reject_bare_session_param(args: &[String]) -> Result<(), String> {
879 match args.iter().find_map(|a| a.strip_prefix("session=")) {
880 Some(v) => Err(format!(
881 "`session={v}` is not a parameter; name the session with `--session={v}`"
882 )),
883 None => Ok(()),
884 }
885}
886
887/// Parse the umbrella `--session <kv>` flag + per-key
888/// long-form flags + env vars into a [`SessionDirSpec`].
889///
890/// **Umbrella form** — `--session <kv-list>` where `<kv-list>`
891/// is comma-separated `key:value` pairs and bare shortcuts.
892/// See [`parse_session_kv`] for the full key list.
893///
894/// **Long-form flags** — same keys, individually:
895/// `--session-name`, `--session-path`, `--session-reuse`,
896/// `--session-keep`, `--session-shelflife`. Both `=value` and
897/// space-separated `<flag> <value>` shapes are accepted.
898///
899/// **Env vars:**
900/// - `NMBRS_SESSION_PATH` → `--session-path`
901/// - `NMBRS_SESSION_KEEP` → `--session-keep`
902/// - `NMBRS_SESSION_SHELFLIFE` → `--session-shelflife`
903///
904/// (Setting a flag and its env var at once is a configuration
905/// conflict; see [`resolve_flag`].)
906///
907/// **Precedence** (highest first):
908/// 1. Long-form per-key flag.
909/// 2. Umbrella `--session` value (parsed left-to-right; later
910/// keys override earlier ones).
911/// 3. Env var equivalents.
912/// 4. Default.
913pub fn resolve_session_dir(args: &[String]) -> SessionDirSpec {
914 // Each flag goes through `resolve_flag` which checks both
915 // CLI and the auto-derived `NMBRS_<FLAG>` env var. Setting
916 // both is a hard error.
917
918 // Umbrella --session / NMBRS_SESSION first, so long-form
919 // and per-key env can override individual fields.
920 let mut spec = match resolve_flag(args, "--session") {
921 Some(kv) => parse_session_kv(&kv),
922 None => SessionDirSpec {
923 session_keep: DEFAULT_SESSIONS_MAX,
924 session_shelflife: DEFAULT_SESSIONS_SHELFLIFE,
925 ..SessionDirSpec::default()
926 },
927 };
928
929 // Long-form per-key flags (each with NMBRS_ env equivalent).
930 if let Some(v) = resolve_flag(args, "--session-name") {
931 spec.session_name = Some(v);
932 }
933 if let Some(v) = resolve_flag(args, "--session-path") {
934 validate_session_path_or_exit(&v, "`--session-path` flag (or NMBRS_SESSION_PATH env)");
935 spec.session_path = Some(v);
936 }
937 if let Some(v) = resolve_flag(args, "--session-reuse")
938 && let Ok(r) = SessionReuse::parse(&v)
939 {
940 spec.reuse = r;
941 }
942 // Retention: `--session-keep` / `--session-shelflife`, matching the rest of
943 // the `--session-*` family and the umbrella's `keep:` / `shelflife:` sub-keys.
944 if let Some(v) = resolve_flag(args, "--session-keep")
945 && let Ok(n) = v.trim().parse::<usize>()
946 {
947 spec.session_keep = n;
948 }
949 if let Some(v) = resolve_flag(args, "--session-shelflife")
950 && let Ok(d) = parse_duration(&v)
951 {
952 spec.session_shelflife = d;
953 }
954
955 spec
956}
957
958/// Resolve the `--session` / `--session-path` / `--session-name`
959/// arguments to a session directory path that `metrics.db`
960/// would live under. Used by every read-side tool (`nmbrs report plot`,
961/// `nmbrs report`, `nmbrs metrics ...`, completion) so the same
962/// flag means the same thing everywhere.
963///
964/// Returns `None` when no session flag is on the line — the
965/// caller falls back to its own default (typically
966/// `logs/latest`).
967///
968/// Never mutates the filesystem: no symlink rewrite, no purge. A pure path
969/// computation, because read-side tools must not have side effects on the active
970/// session symlink. This is now the ONLY way `--session` reaches a read command —
971/// the startup hook used to additionally repoint `sessions/latest` at the named
972/// session, which is exactly the side effect this doc warned against. See
973/// [`purge_stale_sessions_at_startup`].
974pub fn read_session_dir(args: &[String]) -> Option<PathBuf> {
975 let spec = resolve_session_dir(args);
976 if spec.is_empty() || spec.needs_auto_id() {
977 return None;
978 }
979 spec.resolve("").map(|(p, _)| p)
980}
981
982/// Active-session resolver consolidating the patterns used by
983/// `replay.rs` / `summary.rs` / `report_cmd.rs` /
984/// `metricsql_cmd.rs` / `plot_metrics.rs` / `completion.rs`.
985///
986/// Resolves to an existing session directory in this order:
987///
988/// 1. `--session` / `--session-path` / `--session-name` from
989/// `args` (via [`read_session_dir`]).
990/// 2. The `logs/latest` symlink, when it exists and points at a
991/// session directory with the expected artifacts
992/// (`metrics.db` or `session.log`).
993/// 3. `Err` with a remediation message naming the flags that
994/// would have worked.
995///
996/// Read-only — no filesystem mutation. Use this anywhere a
997/// post-run command needs to operate on an existing session.
998///
999/// **Why a separate function from [`read_session_dir`].**
1000/// `read_session_dir` returns `Option` (no opinion on what to do
1001/// when nothing's set); `resolve_active` makes that the call
1002/// site's failure mode, with a single canonical error message.
1003pub fn resolve_active(args: &[String]) -> Result<PathBuf, String> {
1004 if let Some(p) = read_session_dir(args) {
1005 if !p.exists() {
1006 return Err(format!(
1007 "session directory '{}' does not exist",
1008 p.display(),
1009 ));
1010 }
1011 return Ok(p);
1012 }
1013 let latest = latest_session_dir();
1014 if latest.exists() {
1015 // Resolve through the symlink so callers get a stable
1016 // path that won't change underneath them mid-run.
1017 let resolved = std::fs::canonicalize(&latest).unwrap_or(latest.clone());
1018 return Ok(resolved);
1019 }
1020 Err("no active session — run a workload first, or pass \
1021 `--session <name>` / `--session-path <dir>` to point \
1022 at an existing one"
1023 .to_string())
1024}
1025
1026/// Default for `--session-keep`: keep the
1027/// 10 most-recent sessions, purging older ones at the start of the
1028/// next session-creating command.
1029pub const DEFAULT_SESSIONS_MAX: usize = 10;
1030
1031/// Default for `--session-shelflife`:
1032/// 4 weeks. Sessions older than this are purged regardless of the
1033/// `--session-keep` cap.
1034pub const DEFAULT_SESSIONS_SHELFLIFE: std::time::Duration =
1035 std::time::Duration::from_secs(60 * 60 * 24 * 7 * 4);
1036
1037/// Parse a duration suffix-string. Accepts:
1038/// - `<n>s` — seconds
1039/// - `<n>m` — minutes
1040/// - `<n>h` — hours
1041/// - `<n>d` — days
1042/// - `<n>w` — weeks
1043/// - bare integer — seconds (back-compat with raw numeric input)
1044///
1045/// Whitespace is trimmed. `0` (any unit) disables the cap.
1046pub fn parse_duration(s: &str) -> Result<std::time::Duration, String> {
1047 let s = s.trim();
1048 if s.is_empty() {
1049 return Err("empty duration".into());
1050 }
1051 let (num_part, unit_seconds) = if let Some(n) = s.strip_suffix('w') {
1052 (n, 60 * 60 * 24 * 7)
1053 } else if let Some(n) = s.strip_suffix('d') {
1054 (n, 60 * 60 * 24)
1055 } else if let Some(n) = s.strip_suffix('h') {
1056 (n, 60 * 60)
1057 } else if let Some(n) = s.strip_suffix('m') {
1058 (n, 60)
1059 } else if let Some(n) = s.strip_suffix('s') {
1060 (n, 1)
1061 } else {
1062 (s, 1) // bare number = seconds
1063 };
1064 let n: u64 = num_part.trim().parse().map_err(|_| {
1065 format!("duration: '{s}' is not a valid number with optional s/m/h/d/w suffix",)
1066 })?;
1067 Ok(std::time::Duration::from_secs(n * unit_seconds))
1068}
1069
1070/// Return `true` when `dir` exists AND contains artifacts that
1071/// indicate a prior session's state (metrics db, session log,
1072/// or checkpoint). Used by [`Session::new_with_args`] to decide
1073/// whether the reuse-policy check applies.
1074pub fn session_dir_has_prior_artifacts(dir: &Path) -> bool {
1075 if !dir.exists() {
1076 return false;
1077 }
1078 for marker in ["metrics.db", "session.log", "checkpoint.jsonl"] {
1079 if dir.join(marker).exists() {
1080 return true;
1081 }
1082 }
1083 false
1084}
1085
1086/// Count directory entries under `parent` (excluding
1087/// symlinks, files, and the `latest` symlink target). Used
1088/// for end-of-run keep-cap forecasting.
1089pub fn count_session_dirs(parent: &Path) -> usize {
1090 let Ok(rd) = std::fs::read_dir(parent) else {
1091 return 0;
1092 };
1093 rd.filter_map(|e| e.ok())
1094 .filter(|e| {
1095 std::fs::symlink_metadata(e.path())
1096 .map(|m| !m.file_type().is_symlink() && m.file_type().is_dir())
1097 .unwrap_or(false)
1098 })
1099 .count()
1100}
1101
1102/// Forecast how many session directories the **next** new
1103/// session would auto-purge under `parent` given the current
1104/// keep cap. Returns `0` when no purge would happen (or when
1105/// `keep_cap == 0`, which disables the cap).
1106///
1107/// Logged at INFO level by the end-of-run notice guard so
1108/// operators see the imminent cleanup before it happens, with
1109/// instructions for disabling it.
1110pub fn forecast_keep_purge(parent: &Path, keep_cap: usize) -> usize {
1111 if keep_cap == 0 {
1112 return 0;
1113 }
1114 let current = count_session_dirs(parent);
1115 // After +1 new session, total would be current+1. Anything
1116 // past keep_cap gets purged.
1117 (current + 1).saturating_sub(keep_cap)
1118}
1119
1120/// `true` if `path` carries one of the signature artifacts an
1121/// nmbrs run writes — the gate the purge logic uses to avoid
1122/// destroying unrelated directories that happen to share a
1123/// parent with an explicit `--session-path`. Any one of
1124/// `metrics.db`, `session.log`, or `checkpoint.jsonl` is
1125/// enough; the runtime writes at least one of them per
1126/// session, so the test is robust across early-aborted runs.
1127fn looks_like_session_dir(path: &Path) -> bool {
1128 const SIGNATURES: &[&str] = &["metrics.db", "session.log", "checkpoint.jsonl"];
1129 SIGNATURES.iter().any(|s| path.join(s).exists())
1130}
1131
1132/// Purge stale session directories under `parent` according to
1133/// `max_sessions` (keep the latest N) and `shelflife` (drop
1134/// anything older than this).
1135///
1136/// Skipped: the `latest` symlink and whatever it points at, and
1137/// every session some process is still using
1138/// (it holds the directory's `session.lock`) — concurrent runs given sibling
1139/// `--session-path` directories each run this pass, and none may
1140/// delete another's session from under it. A live session does
1141/// not count toward `max_sessions`. Non-directory entries (loose
1142/// files like a stray `summary.md`) are left alone.
1143///
1144/// Errors during enumeration / removal are logged at Warn
1145/// (this is a best-effort housekeeping pass; failure shouldn't
1146/// abort startup).
1147pub fn purge_stale_sessions(parent: &Path, max_sessions: usize, shelflife: std::time::Duration) {
1148 if !parent.exists() {
1149 return;
1150 }
1151 // Resolve the latest-symlink's target so we never delete
1152 // the active session out from under a running operator.
1153 let latest_target: Option<PathBuf> = std::fs::read_link(parent.join("latest"))
1154 .ok()
1155 .map(|t| if t.is_absolute() { t } else { parent.join(t) });
1156
1157 // Collect (path, mtime) for every subdirectory.
1158 let mut entries: Vec<(PathBuf, std::time::SystemTime)> = match std::fs::read_dir(parent) {
1159 Ok(rd) => rd,
1160 Err(e) => {
1161 crate::observer::log(
1162 crate::observer::LogLevel::Warn,
1163 &format!(
1164 "warning: session cleanup: failed to read {}: {e}",
1165 parent.display(),
1166 ),
1167 );
1168 return;
1169 }
1170 }
1171 .filter_map(|entry| entry.ok())
1172 .filter_map(|entry| {
1173 let path = entry.path();
1174 // Skip symlinks (logs/latest) — only cleanup real
1175 // directories.
1176 let md = std::fs::symlink_metadata(&path).ok()?;
1177 if md.file_type().is_symlink() || !md.file_type().is_dir() {
1178 return None;
1179 }
1180 // Don't delete the active session.
1181 if let Some(target) = latest_target.as_ref()
1182 && path == *target
1183 {
1184 return None;
1185 }
1186 // Only consider directories that *look like* nmbrs
1187 // sessions — i.e. carry one of the signature
1188 // artifacts the runtime writes. Without this, an
1189 // explicit `--session-path /tmp/foo` would set
1190 // `cleanup_parent = /tmp` and drag arbitrary
1191 // unrelated dirs (snap.rootfs_*, systemd-private-*,
1192 // …) into the purge set.
1193 if !looks_like_session_dir(&path) {
1194 return None;
1195 }
1196 // Never delete a session a process is still running in.
1197 if session_is_live(&path) {
1198 return None;
1199 }
1200 let mtime = md.modified().ok()?;
1201 Some((path, mtime))
1202 })
1203 .collect();
1204
1205 if entries.is_empty() {
1206 return;
1207 }
1208
1209 // Sort newest-first for the max-cap pass.
1210 entries.sort_by_key(|e| std::cmp::Reverse(e.1));
1211
1212 let now = std::time::SystemTime::now();
1213 let mut to_purge: Vec<&PathBuf> = Vec::new();
1214
1215 // Cap by count: anything past the max is purged.
1216 if max_sessions > 0 && entries.len() > max_sessions {
1217 for (p, _) in &entries[max_sessions..] {
1218 to_purge.push(p);
1219 }
1220 }
1221
1222 // Cap by age: anything older than now - shelflife is purged.
1223 if !shelflife.is_zero() {
1224 for (p, mtime) in &entries[..entries.len().min(if max_sessions == 0 {
1225 usize::MAX
1226 } else {
1227 max_sessions
1228 })] {
1229 if let Ok(age) = now.duration_since(*mtime)
1230 && age > shelflife
1231 && !to_purge.contains(&p)
1232 {
1233 to_purge.push(p);
1234 }
1235 }
1236 }
1237
1238 for path in to_purge {
1239 if let Err(e) = std::fs::remove_dir_all(path) {
1240 crate::observer::log(
1241 crate::observer::LogLevel::Warn,
1242 &format!(
1243 "warning: session cleanup: failed to remove {}: {e}",
1244 path.display(),
1245 ),
1246 );
1247 }
1248 }
1249}
1250
1251/// Run session-lifecycle cleanup at binary startup, honouring
1252/// `--session-keep` / `--session-shelflife`.
1253///
1254/// # What this used to also do, and why it no longer does
1255///
1256/// It used to REPOINT the `sessions/latest` symlink at whatever `--session`
1257/// named, on the theory that read-side commands defaulting to
1258/// `sessions/latest/metrics.db` would then target the right session for free.
1259/// That made `--session` work by mutating shared state: a read-only
1260/// `nmbrs report table … --session=sessions/foo` left `latest` pointing at `foo`
1261/// afterwards, so a later bare `nmbrs report` — or a `--resume-latest` — silently
1262/// operated on `foo` instead of the newest real run. It also only worked for
1263/// sessions living under `sessions/`, so `--session=/tmp/x` behaved differently
1264/// from `--session=sessions/x` for no reason a caller could see.
1265///
1266/// Every command that legitimately OWNS `latest` claims it itself —
1267/// [`Session::new_with_args`] for a fresh run, [`Session::reattach`] for a
1268/// resume, [`init_empty_session`] for `session init` — so nothing was relying on
1269/// this to write the link. The read side now resolves `--session` locally
1270/// ([`read_session_dir`], and the per-command `resolve_db` helpers), which works
1271/// for any path and leaves `latest` alone.
1272///
1273/// A dry-run's deliberate refusal to claim `latest` is what made the cost of the
1274/// old behaviour concrete: see `args_request_dryrun` and SRD-44.
1275///
1276/// # Why this only runs for session-CREATING commands
1277///
1278/// The cleanup DELETES session directories (keeping the `--session-keep` most
1279/// recent, and dropping anything past `--session-shelflife`). It used to run on
1280/// every invocation, so a read-only `nmbrs report table …` could destroy old sessions —
1281/// the destructive counterpart of the symlink rewrite described above. Retiring
1282/// old sessions belongs where sessions are ADDED, which is the only moment the
1283/// count grows; observing a session must never delete one.
1284///
1285/// `creating_session` comes from the caller, which knows the subcommand. Passing
1286/// `false` for an unrecognised command fails safe: cleanup is skipped, and the
1287/// next writing command performs it.
1288///
1289/// Failures log Warn and return; cleanup is best-effort.
1290pub fn purge_stale_sessions_at_startup(args: &[String], creating_session: bool) {
1291 if !creating_session {
1292 return;
1293 }
1294 let spec = resolve_session_dir(args);
1295
1296 // Lifecycle cleanup runs unconditionally — it consults
1297 // `--session-keep` / `--session-shelflife` (with defaults).
1298 // Targets the parent dir: `--logs-dir` if specified, else
1299 // `logs/` under cwd. When `--session-path` is explicit, its
1300 // *parent* directory is the cleanup target.
1301 let cleanup_parent = if let Some(sd) = spec.session_path.as_ref() {
1302 let resolved = sd.replace(SESSION_TOKEN, "");
1303 PathBuf::from(resolved)
1304 .parent()
1305 .map(|p| p.to_path_buf())
1306 .unwrap_or_else(default_sessions_root)
1307 } else {
1308 default_sessions_root()
1309 };
1310 purge_stale_sessions(&cleanup_parent, spec.session_keep, spec.session_shelflife);
1311}
1312
1313/// True when `target`'s absolute path is `logs_dir`'s absolute
1314/// path or lies below it. Both paths are resolved against the
1315/// current cwd if relative; canonicalize is avoided so this works
1316/// for not-yet-created targets.
1317pub(crate) fn target_is_under(logs_dir: &Path, target: &Path) -> bool {
1318 let cwd = std::env::current_dir().ok();
1319 let abs = |p: &Path| -> Option<PathBuf> {
1320 if p.is_absolute() {
1321 Some(p.to_path_buf())
1322 } else {
1323 cwd.as_ref().map(|c| c.join(p))
1324 }
1325 };
1326 match (abs(logs_dir), abs(target)) {
1327 (Some(l), Some(t)) => t.starts_with(&l),
1328 _ => false,
1329 }
1330}
1331
1332/// Compute a target string for a symlink at `link_path` that
1333/// addresses `target` via a path relative to the link's parent
1334/// directory. Falls back to the absolute target when neither
1335/// path can be canonicalised (e.g. target doesn't exist yet,
1336/// which is normal for `logs/latest -> <id>` at session-create
1337/// time).
1338///
1339/// Examples:
1340/// `logs/latest`, `logs/foo_20260504/` → `foo_20260504`
1341/// `logs/latest`, `target/test-tmp/sandbox/` → `../target/test-tmp/sandbox`
1342/// `logs/latest`, `/tmp/explore/` → `/tmp/explore` (no common root)
1343pub(crate) fn relative_symlink_target(link_path: &Path, target: &Path) -> PathBuf {
1344 let link_parent = link_path.parent().unwrap_or_else(|| Path::new("."));
1345 // Resolve both sides to absolute paths to compute a relative
1346 // route. `canonicalize` would also follow symlinks; we want
1347 // logical absolutes so we use cwd-prefixing for the
1348 // not-yet-existing target case.
1349 let cwd = std::env::current_dir().ok();
1350 let abs = |p: &Path| -> Option<PathBuf> {
1351 if p.is_absolute() {
1352 Some(p.to_path_buf())
1353 } else {
1354 cwd.as_ref().map(|c| c.join(p))
1355 }
1356 };
1357 let (Some(link_abs), Some(tgt_abs)) = (abs(link_parent), abs(target)) else {
1358 return target.to_path_buf();
1359 };
1360 let link_comps: Vec<_> = link_abs.components().collect();
1361 let tgt_comps: Vec<_> = tgt_abs.components().collect();
1362 let common = link_comps
1363 .iter()
1364 .zip(tgt_comps.iter())
1365 .take_while(|(a, b)| a == b)
1366 .count();
1367 if common == 0 {
1368 // Different roots (e.g. `/home/...` vs `/tmp/...`) —
1369 // can't express as a relative path without more `..`s
1370 // than is sensible. Fall back to absolute.
1371 return tgt_abs;
1372 }
1373 let ups = link_comps.len() - common;
1374 let mut rel = PathBuf::new();
1375 for _ in 0..ups {
1376 rel.push("..");
1377 }
1378 for c in &tgt_comps[common..] {
1379 rel.push(c.as_os_str());
1380 }
1381 if rel.as_os_str().is_empty() {
1382 rel.push(".");
1383 }
1384 rel
1385}
1386
1387impl Session {
1388 /// Create a new session. Picks the output directory in this
1389 /// priority order:
1390 ///
1391 /// 1. `--session-path <path>` CLI flag (or the
1392 /// `NMBRS_SESSION_PATH` env var). `SESSION`
1393 /// token in the path is replaced with the auto-generated
1394 /// `{session_name}_{timestamp}` name. The basename becomes
1395 /// the session id.
1396 /// 2. `--logs-dir <parent>` and/or `--session <name>` CLI
1397 /// flags. Compose into `<parent>/<name>` (defaulting to
1398 /// `logs/<auto-id>` for any unspecified component).
1399 /// 3. Default — `logs/{session_name}_{timestamp}/`.
1400 ///
1401 /// `session_name` is the auto-id stem (the single-run caller
1402 /// passes the scenario name; a concurrent SRD-88 host passes
1403 /// a session-level name). `args` is the raw CLI args slice —
1404 /// pass an empty slice to get env-only resolution. The
1405 /// session carries only `session=<id>` identity; per-execution
1406 /// workload/scenario live on the [`Execution`] tier.
1407 pub fn new_with_args(session_name: &str, args: &[String]) -> Self {
1408 let timestamp = format_timestamp();
1409 let auto_id = format!("{session_name}_{timestamp}");
1410
1411 let spec = resolve_session_dir(args);
1412 let (output_dir, id) = spec
1413 .resolve(&auto_id)
1414 .unwrap_or_else(|| (default_session_dir(&auto_id), auto_id.clone()));
1415
1416 // Reuse-policy check. Only fires when the resolved
1417 // directory already holds prior session artifacts. The
1418 // resume path enters via `Session::resume`, not here, so
1419 // any pre-existing artifacts at this entry point are a
1420 // collision the operator must explicitly resolve.
1421 if session_dir_has_prior_artifacts(&output_dir) {
1422 match spec.reuse {
1423 SessionReuse::Error => {
1424 eprintln!(
1425 "error: session directory {} already contains artifacts \
1426 (metrics.db / session.log / checkpoint.jsonl).\n \
1427 Pick a reuse policy:\n \
1428 --session-reuse=restart (wipe artifacts, fresh run)\n \
1429 --session-reuse=resume (continue with the prior session — \
1430 equivalent to --resume <id>)\n \
1431 Or pick a different path via --session, --logs-dir, \
1432 --session-path, or NMBRS_SESSION_PATH env.",
1433 output_dir.display(),
1434 );
1435 std::process::exit(2);
1436 }
1437 SessionReuse::Restart => {
1438 for marker in [
1439 "metrics.db",
1440 "session.log",
1441 "checkpoint.jsonl",
1442 "checkpoint.lock",
1443 SESSION_LIVENESS_FILE,
1444 "summary.md",
1445 "summary.txt",
1446 "summary.json",
1447 "tui.dump",
1448 "flamegraph.svg",
1449 "flamegraph-perf.svg",
1450 "flamegraph-perf.md",
1451 ] {
1452 let _ = std::fs::remove_file(output_dir.join(marker));
1453 }
1454 crate::observer::log(
1455 crate::observer::LogLevel::Warn,
1456 &format!(
1457 "session-reuse=restart: wiped prior artifacts in {}",
1458 output_dir.display(),
1459 ),
1460 );
1461 }
1462 SessionReuse::Resume => {
1463 eprintln!(
1464 "error: --session-reuse=resume requires --resume to actually \
1465 continue the prior session. Add --resume (or --resume-latest) \
1466 to your command line. Path: {}",
1467 output_dir.display(),
1468 );
1469 std::process::exit(2);
1470 }
1471 }
1472 }
1473
1474 // Create the output directory (and any missing parents)
1475 if let Err(e) = std::fs::create_dir_all(&output_dir) {
1476 crate::observer::log(
1477 crate::observer::LogLevel::Warn,
1478 &format!(
1479 "warning: failed to create session output directory {}: {e}",
1480 output_dir.display()
1481 ),
1482 );
1483 }
1484
1485 keep_session_live(&output_dir);
1486
1487 // Refresh `logs/latest` → this session, then *clear* every
1488 // per-artifact convenience symlink from the previous
1489 // session. Optional artifacts (flamegraphs, summary,
1490 // tui.dump) get their convenience link only when their
1491 // writer actually produces the file — eager pre-creation
1492 // would leave a dangling link any time the run skips that
1493 // artifact (e.g. no `profiler=` on the CLI). The two
1494 // guaranteed-written artifacts (`session.log` / `metrics.db`)
1495 // are linked here so live tooling can `tail -f
1496 // logs/session.log` or open `logs/metrics.db` without
1497 // chasing the timestamped session id.
1498 let logs = default_sessions_root();
1499 // Only touch `logs/` when the session output dir is under
1500 // it. An explicit `--session-path /tmp/x` (or any redirect
1501 // outside `logs/`) is treated as opt-out:
1502 // - The mkdir below would otherwise stamp a stray
1503 // `<cwd>/logs/` directory in test sandboxes / CI
1504 // working trees that don't want it (the
1505 // `feedback_tests_no_project_root` rule), and
1506 // - `logs/latest` shouldn't get hijacked by test fixtures
1507 // or one-off `--session-path` runs.
1508 // A dry-run is resume-inert: it must not hijack `latest` (nor
1509 // the per-artifact convenience links). Leaving `latest` pointing
1510 // at the prior REAL run is exactly what lets a subsequent
1511 // `--resume-latest` resume that run instead of the throwaway
1512 // dry-run. See `args_request_dryrun` / SRD-44.
1513 if target_is_under(&logs, &output_dir) && !args_request_dryrun(args) {
1514 let _ = std::fs::create_dir_all(&logs);
1515 let latest = logs.join("latest");
1516 let _ = std::fs::remove_file(&latest);
1517 let _ = symlink_any(&latest_symlink_target(&output_dir, &logs, &id), &latest);
1518 for stale in [
1519 "summary.md",
1520 "flamegraph.svg",
1521 "flamegraph-perf.svg",
1522 "flamegraph-perf.md",
1523 "tui.dump",
1524 ] {
1525 let _ = std::fs::remove_file(logs.join(stale));
1526 }
1527 for artifact in ["session.log", "metrics.db"] {
1528 let link = logs.join(artifact);
1529 let _ = std::fs::remove_file(&link);
1530 // Relative target routes through the `latest`
1531 // symlink so swapping sessions updates every artifact
1532 // link in a single `latest` update.
1533 let target = PathBuf::from("latest").join(artifact);
1534 let _ = symlink_any(&target, &link);
1535 }
1536 }
1537
1538 // The session component owns exactly one dimensional
1539 // label: `session=<id>`. Per SRD-88 §2 this is the shared
1540 // common root — one per process — and per the label-
1541 // ownership invariant it never carries `exec_id` /
1542 // `workload`; those are declared once, on each
1543 // [`Execution::component`] child, and composed in by the
1544 // component tree. Descendant metrics still see the full
1545 // `{session, exec_id, workload}` set, but every name is
1546 // owned by exactly one tier.
1547 let component =
1548 Component::root(Labels::of("session", &id), std::collections::HashMap::new());
1549 // Install the session root as the resolver backing for
1550 // Polydat runtime-context nodes (`control(...)`, `rate()`,
1551 // `concurrency()`, etc.). See SRD 12 §"Runtime context
1552 // nodes" and polydat/src/nodes/runtime_context.rs.
1553 crate::polydat_nodes::runtime_context::set_session_root(component.clone());
1554
1555 Self {
1556 id,
1557 output_dir,
1558 component,
1559 metrics_query: Mutex::new(None),
1560 }
1561 }
1562
1563 /// Backward-compat shim for callers that don't have CLI
1564 /// args handy. Equivalent to
1565 /// `Session::new_with_args(session_name, &[])` — resolves
1566 /// the session directory from the environment only.
1567 pub fn new(session_name: &str) -> Self {
1568 Self::new_with_args(session_name, &[])
1569 }
1570
1571 /// Re-attach to a prior session — reuse its directory, id,
1572 /// and (consequently) its `metrics.db` so the attaching
1573 /// invocation appends to the same metrics history rather
1574 /// than starting fresh in a new dir. Per SRD-44 §"Wholesale
1575 /// metrics-purge", phases that re-run need their prior sample
1576 /// rows purged in-place; that requires writing to the same
1577 /// db, which requires reusing the same session dir. The id is
1578 /// read from the directory's basename, so it preserves the
1579 /// original timestamp suffix.
1580 ///
1581 /// Backs both `nmbrs resume` and `nmbrs refine`: the two differ
1582 /// only in the [`Execution`] the caller starts under this
1583 /// session (its `verb` and `exec_id`), which is now an
1584 /// execution-tier concern (SRD-88) — not a session-tier one.
1585 /// `session_name` is the fallback id stem used only when the
1586 /// directory basename can't be read.
1587 pub fn reattach(prior_session_dir: PathBuf, session_name: &str) -> Self {
1588 let id = prior_session_dir
1589 .file_name()
1590 .and_then(|s| s.to_str())
1591 .map(String::from)
1592 .unwrap_or_else(|| {
1593 // Fallback: synthesize a fresh id from the
1594 // session name + timestamp. Shouldn't fire in
1595 // practice (we resolved the dir to a real session
1596 // before calling here).
1597 format!("{session_name}_{}", format_timestamp())
1598 });
1599
1600 // Re-establish the convenience symlinks under `logs/` so
1601 // `tail -f logs/session.log` and `sqlite3 logs/metrics.db`
1602 // resolve to this session's artifacts. Same shape as
1603 // Session::new — a no-op when the symlinks already point
1604 // here from a prior run. Skipped when the session lives
1605 // outside `logs/` (see Session::new for rationale: one-off
1606 // external session dirs shouldn't hijack `logs/latest`).
1607 keep_session_live(&prior_session_dir);
1608
1609 let logs = default_sessions_root();
1610 if target_is_under(&logs, &prior_session_dir) {
1611 let latest = logs.join("latest");
1612 let _ = std::fs::remove_file(&latest);
1613 let _ = symlink_any(Path::new(&id), &latest);
1614 for artifact in ["session.log", "metrics.db"] {
1615 let link = logs.join(artifact);
1616 let _ = std::fs::remove_file(&link);
1617 let target = PathBuf::from("latest").join(artifact);
1618 let _ = symlink_any(&target, &link);
1619 }
1620 }
1621
1622 // Session component carries `session=<id>` only — the
1623 // re-attached execution(s) declare `exec_id` / `workload`
1624 // on their own [`Execution::component`] children, exactly
1625 // as a fresh session does (see `new_with_args`).
1626 let component =
1627 Component::root(Labels::of("session", &id), std::collections::HashMap::new());
1628 crate::polydat_nodes::runtime_context::set_session_root(component.clone());
1629
1630 Self {
1631 id,
1632 output_dir: prior_session_dir,
1633 component,
1634 metrics_query: Mutex::new(None),
1635 }
1636 }
1637
1638 /// Create a `logs/<artifact>` convenience symlink that points
1639 /// (through `logs/latest`) at the named artifact in the
1640 /// current session's output dir. Idempotent — replaces any
1641 /// existing link with the same name. Call from the writer
1642 /// at the moment the artifact has actually been produced, so
1643 /// the convenience link never dangles.
1644 pub fn link_artifact(name: &str) {
1645 let logs = default_sessions_root();
1646 let link = logs.join(name);
1647 let _ = std::fs::remove_file(&link);
1648 let target = PathBuf::from("latest").join(name);
1649 let _ = symlink_any(&target, &link);
1650 }
1651
1652 /// Install the shared [`MetricsQuery`] handle. Called once by the
1653 /// runner after it has planned the cadence tree and built the
1654 /// cadence reporter. Panics if called twice.
1655 pub fn set_metrics_query(&self, query: Arc<MetricsQuery>) {
1656 let mut slot = self.metrics_query.lock().unwrap_or_else(|e| e.into_inner());
1657 assert!(slot.is_none(), "session metrics_query already installed");
1658 *slot = Some(query);
1659 }
1660
1661 /// Borrow the installed [`MetricsQuery`]. Returns `None` before
1662 /// the runner wires it.
1663 pub fn metrics_query(&self) -> Option<Arc<MetricsQuery>> {
1664 self.metrics_query
1665 .lock()
1666 .unwrap_or_else(|e| e.into_inner())
1667 .clone()
1668 }
1669
1670 /// Path to the SQLite metrics file for this session.
1671 pub fn metrics_path(&self) -> PathBuf {
1672 self.output_dir.join("metrics.db")
1673 }
1674
1675 /// Path for a profiler output file.
1676 pub fn profiler_path(&self, suffix: &str) -> PathBuf {
1677 self.output_dir.join(format!("flamegraph{suffix}.svg"))
1678 }
1679
1680 /// Path for an arbitrary session artifact.
1681 pub fn artifact_path(&self, filename: &str) -> PathBuf {
1682 self.output_dir.join(filename)
1683 }
1684}
1685
1686/// Format the current time as `YYYYMMDD_HHmmss`.
1687/// Compute the symlink target string for `logs/latest`,
1688/// always relative. For sessions under `logs/<id>/` the link
1689/// resolves to a bare `{id}`; sessions outside `logs/` get an
1690/// `../...` route up to a common ancestor. Relative targets
1691/// keep the link portable across directory moves and readable
1692/// in `ls -la` output.
1693fn latest_symlink_target(output_dir: &Path, logs: &Path, id: &str) -> PathBuf {
1694 if output_dir.parent() == Some(logs) {
1695 return PathBuf::from(id);
1696 }
1697 let latest = logs.join("latest");
1698 relative_symlink_target(&latest, output_dir)
1699}
1700
1701/// UTC datetime components for session-name templating, derived
1702/// from the same manual Gregorian math as `format_timestamp` (no
1703/// chrono dependency). Returns `(year, month, day, hour, minute,
1704/// second, epoch_millis, epoch_seconds)`.
1705pub fn utc_datetime_fields() -> (u64, u64, u64, u64, u64, u64, u128, u64) {
1706 let now = std::time::SystemTime::now()
1707 .duration_since(std::time::UNIX_EPOCH)
1708 .unwrap_or_default();
1709 let secs = now.as_secs();
1710 let millis = now.as_millis();
1711 let day_count = secs / 86400;
1712 let t = secs % 86400;
1713 let (year, month, day) = days_to_ymd(day_count);
1714 (
1715 year,
1716 month,
1717 day,
1718 t / 3600,
1719 (t % 3600) / 60,
1720 t % 60,
1721 millis,
1722 secs,
1723 )
1724}
1725
1726fn format_timestamp() -> String {
1727 let secs = std::time::SystemTime::now()
1728 .duration_since(std::time::UNIX_EPOCH)
1729 .unwrap()
1730 .as_secs();
1731 // Convert epoch seconds to date/time components.
1732 // Simple implementation without chrono dependency.
1733 let days = secs / 86400;
1734 let time = secs % 86400;
1735 let hours = time / 3600;
1736 let minutes = (time % 3600) / 60;
1737 let seconds = time % 60;
1738
1739 // Days since epoch to Y/M/D (simplified Gregorian)
1740 let (year, month, day) = days_to_ymd(days);
1741
1742 format!("{year:04}{month:02}{day:02}_{hours:02}{minutes:02}{seconds:02}")
1743}
1744
1745/// Current wall-clock time as `YYYY-MM-DD HH:MM:SS.mmm` (UTC).
1746/// Used by the session log writer for human-readable line timestamps.
1747pub fn now_log_timestamp() -> String {
1748 format_log_timestamp(std::time::SystemTime::now())
1749}
1750
1751/// Format a specific `SystemTime` in the same shape as
1752/// [`now_log_timestamp`]. Used by the failure-dump path
1753/// in `nmbrs-tui::observer` to render per-LogEntry
1754/// timestamps captured at log-emit time.
1755pub fn format_log_timestamp(t: std::time::SystemTime) -> String {
1756 let dur = t.duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
1757 let secs = dur.as_secs();
1758 let millis = dur.subsec_millis();
1759 let days = secs / 86400;
1760 let time = secs % 86400;
1761 let hours = time / 3600;
1762 let minutes = (time % 3600) / 60;
1763 let seconds = time % 60;
1764 let (year, month, day) = days_to_ymd(days);
1765 format!("{year:04}-{month:02}-{day:02} {hours:02}:{minutes:02}:{seconds:02}.{millis:03}")
1766}
1767
1768/// Convert days since Unix epoch to (year, month, day).
1769/// Format Unix seconds as `MM-DD HH:MM:SS` (UTC).
1770///
1771/// Exposed because report tables now show WHEN a series started and last moved,
1772/// and the epoch value on its own is unreadable. Shares `days_to_ymd` with the
1773/// session-id formatter rather than restating the calendar arithmetic; the year
1774/// is omitted because these columns compare moments inside one run, where the
1775/// month and day are already the widest useful distinction.
1776pub fn format_utc_short(epoch_seconds: f64) -> String {
1777 if !epoch_seconds.is_finite() || epoch_seconds <= 0.0 {
1778 return "-".to_string();
1779 }
1780 let secs = epoch_seconds as u64;
1781 let (_, month, day) = days_to_ymd(secs / 86400);
1782 let t = secs % 86400;
1783 format!(
1784 "{month:02}-{day:02} {:02}:{:02}:{:02}",
1785 t / 3600,
1786 (t % 3600) / 60,
1787 t % 60
1788 )
1789}
1790
1791fn days_to_ymd(days: u64) -> (u64, u64, u64) {
1792 // Algorithm from Howard Hinnant's date library
1793 let z = days + 719468;
1794 let era = z / 146097;
1795 let doe = z - era * 146097;
1796 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
1797 let y = yoe + era * 400;
1798 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1799 let mp = (5 * doy + 2) / 153;
1800 let d = doy - (153 * mp + 2) / 5 + 1;
1801 let m = if mp < 10 { mp + 3 } else { mp - 9 };
1802 let y = if m <= 2 { y + 1 } else { y };
1803 (y, m, d)
1804}
1805
1806/// Resolve an operator-supplied relative path INSIDE `base`, refusing
1807/// anything that could name a location elsewhere: an absolute path, a
1808/// `..` component, an empty path, or a Windows drive/prefix. Output
1809/// paths that a workload file can set (`metrics-log`, `trace_log`)
1810/// route through here, so a shared workload can only ever write into
1811/// the session's own directory tree.
1812pub fn confine_to_dir(base: &Path, rel: &str) -> Result<PathBuf, String> {
1813 use std::path::Component;
1814 let rel_path = Path::new(rel.trim());
1815 if rel.trim().is_empty() {
1816 return Err("empty path".to_string());
1817 }
1818 for comp in rel_path.components() {
1819 match comp {
1820 Component::Normal(_) | Component::CurDir => {}
1821 Component::ParentDir => {
1822 return Err(format!(
1823 "'{rel}' escapes the session directory (`..` is not allowed)"
1824 ));
1825 }
1826 Component::RootDir | Component::Prefix(_) => {
1827 return Err(format!(
1828 "'{rel}' is absolute; only paths relative to the session directory are accepted here"
1829 ));
1830 }
1831 }
1832 }
1833 Ok(base.join(rel_path))
1834}
1835
1836#[cfg(test)]
1837mod tests {
1838 use super::*;
1839
1840 #[test]
1841 fn timestamp_format() {
1842 let ts = format_timestamp();
1843 // Should be 15 chars: YYYYMMDD_HHmmss
1844 assert_eq!(ts.len(), 15, "timestamp: {ts}");
1845 assert!(
1846 ts.contains('_'),
1847 "timestamp should contain underscore: {ts}"
1848 );
1849 }
1850
1851 /// Serialize all tests that mutate process-global state
1852 /// (`NMBRS_SESSION_*` env vars, cwd-relative `logs/` writes,
1853 /// etc.). Cargo runs tests in parallel by default; tests
1854 /// touching shared state must hold this lock for the
1855 /// duration of the operation.
1856 fn env_test_lock() -> std::sync::MutexGuard<'static, ()> {
1857 use std::sync::Mutex;
1858 static LOCK: Mutex<()> = Mutex::new(());
1859 LOCK.lock().unwrap_or_else(|e| e.into_inner())
1860 }
1861
1862 #[test]
1863 fn dryrun_detection_from_args() {
1864 let yes =
1865 |a: &[&str]| args_request_dryrun(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
1866 assert!(yes(&["run", "workload=w", "dryrun=op"]));
1867 assert!(yes(&["run", "dryrun=phase,wiring"]));
1868 assert!(yes(&["run", "--dryrun=structure"]));
1869 // A real run — no dryrun signal.
1870 assert!(!yes(&["run", "workload=w", "scenario=incremental"]));
1871 // Explicit falsey values are not a dry-run.
1872 assert!(!yes(&["run", "dryrun=false"]));
1873 assert!(!yes(&["run", "dryrun=0"]));
1874 assert!(!yes(&["run", "dryrun="]));
1875 }
1876
1877 #[test]
1878 fn session_id_format() {
1879 // Session construction installs the process-global session root as a
1880 // side effect (see `new_with_args`), racing every control-node test
1881 // that reads through it. Hold the same guard those tests hold.
1882 let _root_guard = crate::polydat_nodes::runtime_context::session_root_test_guard();
1883 let _g = env_test_lock();
1884 clear_session_env();
1885 let session = Session::new("fknn_rampup");
1886 assert!(session.id.starts_with("fknn_rampup_"), "id: {}", session.id);
1887 let expected_root = default_sessions_root();
1888 assert!(
1889 session.output_dir.starts_with(&expected_root),
1890 "output_dir {} should start with {}",
1891 session.output_dir.display(),
1892 expected_root.display()
1893 );
1894 }
1895
1896 #[test]
1897 fn session_paths() {
1898 // Session construction installs the process-global session root as a
1899 // side effect (see `new_with_args`), racing every control-node test
1900 // that reads through it. Hold the same guard those tests hold.
1901 let _root_guard = crate::polydat_nodes::runtime_context::session_root_test_guard();
1902 let _g = env_test_lock();
1903 clear_session_env();
1904 let session = Session::new("smoke");
1905 assert!(session.metrics_path().ends_with("metrics.db"));
1906 assert!(session.profiler_path("").ends_with("flamegraph.svg"));
1907 assert!(
1908 session
1909 .profiler_path("-perf")
1910 .ends_with("flamegraph-perf.svg")
1911 );
1912 }
1913
1914 /// Clear every env var that `resolve_session_dir` reads, so a
1915 /// `spec_*` test sees CLI-only inputs. Without this, a
1916 /// concurrent test that sets `NMBRS_SESSION_NAME` (or any
1917 /// peer var) collides with this test's CLI flag, hits the
1918 /// "configuration conflict" path in `resolve_flag`, and
1919 /// calls `process::exit(2)` — killing the entire test
1920 /// process and surfacing as an unrelated test failure.
1921 /// Must be called under [`env_test_lock`] so the cleanup
1922 /// holds for the duration of the spec resolution.
1923 fn clear_session_env() {
1924 // SAFETY: under env_test_lock, no other test thread is
1925 // touching these vars.
1926 unsafe {
1927 std::env::remove_var("NMBRS_SESSION");
1928 std::env::remove_var("NMBRS_SESSION_NAME");
1929 std::env::remove_var("NMBRS_SESSION_PATH");
1930 std::env::remove_var("NMBRS_SESSION_REUSE");
1931 std::env::remove_var("NMBRS_SESSION_KEEP");
1932 std::env::remove_var("NMBRS_SESSION_SHELFLIFE");
1933 }
1934 }
1935
1936 #[test]
1937 fn spec_session_path_flag_yields_basename_id() {
1938 let _g = env_test_lock();
1939 clear_session_env();
1940 let args = vec!["--session-path=/tmp/explicit".into()];
1941 let spec = resolve_session_dir(&args);
1942 let (path, id) = spec.resolve("auto-id").unwrap();
1943 assert_eq!(path.to_str(), Some("/tmp/explicit"));
1944 assert_eq!(id, "explicit");
1945 }
1946
1947 /// The `--session-*` family has one spelling per setting. The retired
1948 /// `--sessions-max` / `--sessions-shelflife` / `--session-dir` spellings set
1949 /// nothing here; the command-line walker rejects them as unknown flags (see
1950 /// the run spec's `retired_session_flag_spellings_are_rejected`).
1951 #[test]
1952 fn session_flags_have_one_spelling() {
1953 let _g = env_test_lock();
1954 clear_session_env();
1955
1956 let spec = resolve_session_dir(&["--session-keep=7".to_string()]);
1957 assert_eq!(spec.session_keep, 7);
1958 let spec = resolve_session_dir(&["--session-shelflife=2w".to_string()]);
1959 assert_eq!(
1960 spec.session_shelflife,
1961 std::time::Duration::from_secs(14 * 24 * 3600)
1962 );
1963
1964 let spec = resolve_session_dir(&[
1965 "--sessions-max=5".to_string(),
1966 "--sessions-shelflife=2w".to_string(),
1967 "--session-dir=/tmp/explicit".to_string(),
1968 ]);
1969 assert_eq!(spec.session_keep, DEFAULT_SESSIONS_MAX);
1970 assert_eq!(spec.session_shelflife, DEFAULT_SESSIONS_SHELFLIFE);
1971 assert!(spec.session_path.is_none());
1972 }
1973
1974 /// The session is named only by `--session` (or `NMBRS_SESSION`). A bare
1975 /// `session=<dir>` names nothing here; the command line rejects it before
1976 /// any command runs ([`reject_bare_session_param`]).
1977 #[test]
1978 fn bare_session_param_names_no_session() {
1979 let _g = env_test_lock();
1980 clear_session_env();
1981 let spec = resolve_session_dir(&["session=/tmp/explicit".to_string()]);
1982 assert!(spec.is_empty());
1983 assert!(reject_bare_session_param(&["session=/tmp/explicit".to_string()]).is_err());
1984 assert!(reject_bare_session_param(&["--session=/tmp/explicit".to_string()]).is_ok());
1985 }
1986
1987 #[test]
1988 fn spec_session_name_only_yields_default_logs_dir() {
1989 let _g = env_test_lock();
1990 clear_session_env();
1991 let args = vec!["--session-name=alpha".into()];
1992 let (path, id) = resolve_session_dir(&args).resolve("autogen").unwrap();
1993 assert_eq!(path, default_sessions_root().join("alpha"));
1994 assert_eq!(id, "alpha");
1995 }
1996
1997 #[test]
1998 fn spec_session_path_token_replaced_with_name() {
1999 let _g = env_test_lock();
2000 clear_session_env();
2001 let args = vec![
2002 "--session-path=/data/SESSION_run".into(),
2003 "--session-name=alpha".into(),
2004 ];
2005 let (path, id) = resolve_session_dir(&args).resolve("autogen").unwrap();
2006 assert_eq!(path.to_str(), Some("/data/alpha_run"));
2007 assert_eq!(id, "alpha_run");
2008 }
2009
2010 #[test]
2011 fn spec_session_path_token_falls_back_to_auto_id_when_no_name() {
2012 let _g = env_test_lock();
2013 clear_session_env();
2014 let args = vec!["--session-path=/data/SESSION_run".into()];
2015 let (path, id) = resolve_session_dir(&args).resolve("autogen").unwrap();
2016 assert_eq!(path.to_str(), Some("/data/autogen_run"));
2017 assert_eq!(id, "autogen_run");
2018 }
2019
2020 #[test]
2021 fn spec_space_form_session_path_flag() {
2022 let _g = env_test_lock();
2023 clear_session_env();
2024 let args = vec!["--session-path".into(), "/data/path".into()];
2025 let (path, _) = resolve_session_dir(&args).resolve("auto").unwrap();
2026 assert_eq!(path.to_str(), Some("/data/path"));
2027 }
2028
2029 #[test]
2030 fn spec_falls_back_to_env() {
2031 let _g = env_test_lock();
2032 clear_session_env();
2033 unsafe {
2034 std::env::set_var("NMBRS_SESSION_PATH", "/from/env");
2035 }
2036 let spec = resolve_session_dir(&[]);
2037 clear_session_env();
2038 let (path, _) = spec.resolve("auto").unwrap();
2039 assert_eq!(path.to_str(), Some("/from/env"));
2040 }
2041
2042 /// `SESSION_DIRECTORY` was the pre-SRD-04 spelling of
2043 /// `NMBRS_SESSION_PATH`. It is retired: nothing reads it.
2044 #[test]
2045 fn retired_session_directory_env_is_not_read() {
2046 let _g = env_test_lock();
2047 clear_session_env();
2048 let prior = std::env::var("SESSION_DIRECTORY").ok();
2049 unsafe {
2050 std::env::set_var("SESSION_DIRECTORY", "/from/env");
2051 }
2052 let spec = resolve_session_dir(&[]);
2053 unsafe {
2054 match prior {
2055 Some(v) => std::env::set_var("SESSION_DIRECTORY", v),
2056 None => std::env::remove_var("SESSION_DIRECTORY"),
2057 }
2058 }
2059 assert!(spec.session_path.is_none());
2060 }
2061
2062 #[test]
2063 fn spec_empty_returns_no_resolution() {
2064 let _g = env_test_lock();
2065 clear_session_env();
2066 let spec = resolve_session_dir(&[]);
2067 assert!(spec.is_empty());
2068 assert!(spec.resolve("auto").is_none());
2069 }
2070
2071 #[test]
2072 fn spec_needs_auto_id_when_token_present() {
2073 let _g = env_test_lock();
2074 clear_session_env();
2075 let args = vec!["--session-path=/data/SESSION_x".into()];
2076 assert!(resolve_session_dir(&args).needs_auto_id());
2077 }
2078
2079 #[test]
2080 fn spec_does_not_need_auto_id_when_path_is_concrete() {
2081 let _g = env_test_lock();
2082 clear_session_env();
2083 let args = vec!["--session-path=/data/specific".into()];
2084 assert!(!resolve_session_dir(&args).needs_auto_id());
2085 }
2086
2087 #[test]
2088 fn spec_does_not_need_auto_id_with_explicit_name() {
2089 let _g = env_test_lock();
2090 clear_session_env();
2091 let args = vec![
2092 "--session-path=/data/SESSION_x".into(),
2093 "--session-name=alpha".into(),
2094 ];
2095 assert!(!resolve_session_dir(&args).needs_auto_id());
2096 }
2097
2098 // -----------------------------------------------------------
2099 // Umbrella --session kv-list parsing
2100 // -----------------------------------------------------------
2101
2102 #[test]
2103 fn umbrella_dir_shortcut_sets_path() {
2104 let _g = env_test_lock();
2105 clear_session_env();
2106 let args = vec!["--session=dir:asldkfjsldfj".into()];
2107 let (path, id) = resolve_session_dir(&args).resolve("auto").unwrap();
2108 assert_eq!(path.to_str(), Some("asldkfjsldfj"));
2109 assert_eq!(id, "asldkfjsldfj", "session id is the basename of the path");
2110 }
2111
2112 #[test]
2113 fn umbrella_dir_with_subpath_yields_basename_id() {
2114 let _g = env_test_lock();
2115 clear_session_env();
2116 let args = vec!["--session=dir:l2k3j4/drr".into()];
2117 let (path, id) = resolve_session_dir(&args).resolve("auto").unwrap();
2118 assert_eq!(path.to_str(), Some("l2k3j4/drr"));
2119 assert_eq!(id, "drr");
2120 }
2121
2122 #[test]
2123 fn umbrella_full_kv_list() {
2124 let _g = env_test_lock();
2125 clear_session_env();
2126 let args =
2127 vec!["--session=keep:42,name:sessname42,path:sessions/dir/SESSION,reuse:resume".into()];
2128 let spec = resolve_session_dir(&args);
2129 assert_eq!(spec.session_name.as_deref(), Some("sessname42"));
2130 assert_eq!(spec.session_path.as_deref(), Some("sessions/dir/SESSION"));
2131 assert_eq!(spec.reuse, SessionReuse::Resume);
2132 assert_eq!(spec.session_keep, 42);
2133 let (path, id) = spec.resolve("autogen").unwrap();
2134 assert_eq!(path.to_str(), Some("sessions/dir/sessname42"));
2135 assert_eq!(id, "sessname42");
2136 }
2137
2138 #[test]
2139 fn umbrella_bare_restart_token_sets_reuse() {
2140 let _g = env_test_lock();
2141 clear_session_env();
2142 let args = vec!["--session=restart,dir:/tmp/x".into()];
2143 let spec = resolve_session_dir(&args);
2144 assert_eq!(spec.reuse, SessionReuse::Restart);
2145 assert_eq!(spec.session_path.as_deref(), Some("/tmp/x"));
2146 }
2147
2148 #[test]
2149 fn umbrella_bare_resume_token_sets_reuse() {
2150 let _g = env_test_lock();
2151 clear_session_env();
2152 let args = vec!["--session=resume,name:foo".into()];
2153 let spec = resolve_session_dir(&args);
2154 assert_eq!(spec.reuse, SessionReuse::Resume);
2155 assert_eq!(spec.session_name.as_deref(), Some("foo"));
2156 }
2157
2158 #[test]
2159 fn umbrella_long_form_overrides_umbrella() {
2160 let _g = env_test_lock();
2161 clear_session_env();
2162 let args = vec![
2163 "--session=name:from-umbrella".into(),
2164 "--session-name=from-longform".into(),
2165 ];
2166 let spec = resolve_session_dir(&args);
2167 assert_eq!(spec.session_name.as_deref(), Some("from-longform"));
2168 }
2169
2170 #[test]
2171 fn umbrella_unknown_key_logs_warn_but_keeps_rest() {
2172 let _g = env_test_lock();
2173 clear_session_env();
2174 let args = vec!["--session=name:foo,what:nope,reuse:restart".into()];
2175 let spec = resolve_session_dir(&args);
2176 // Unknown 'what:nope' was logged + skipped; recognized
2177 // entries still applied.
2178 assert_eq!(spec.session_name.as_deref(), Some("foo"));
2179 assert_eq!(spec.reuse, SessionReuse::Restart);
2180 }
2181
2182 // ── check_session_path: catch the `scenario=foo`-as-path footgun ──
2183
2184 #[test]
2185 fn check_session_path_rejects_workload_param_shape() {
2186 // The classic recurring footgun: `--session-path scenario=foo`
2187 // would silently create `<cwd>/scenario=foo/...` because the
2188 // umbrella parser splits only on `:`.
2189 for bad in &[
2190 "scenario=foo",
2191 "scenario=/tmp/foo",
2192 "scenario=target",
2193 "scenario=target/test-tmp/x",
2194 "k=v",
2195 "key_with_underscore=value",
2196 "kebab-case=value",
2197 ] {
2198 assert!(
2199 check_session_path(bad, "test").is_err(),
2200 "should reject '{bad}'"
2201 );
2202 }
2203 }
2204
2205 // ── SRD-77 session-path helpers ──────────────────────
2206 // Pin the structural composition: every helper builds on
2207 // `default_sessions_root()` so a future env-aware redirect
2208 // (cargo tmp, --session-path override, etc.) propagates
2209 // cleanly without each helper carrying its own literal.
2210
2211 #[test]
2212 fn latest_session_dir_is_under_default_sessions_root() {
2213 let root = default_sessions_root();
2214 let latest = latest_session_dir();
2215 assert!(
2216 latest.starts_with(&root),
2217 "latest_session_dir MUST live under default_sessions_root \
2218 so the env-aware redirect (cargo tmp, etc.) covers it; \
2219 root={root:?}, latest={latest:?}"
2220 );
2221 assert_eq!(latest.file_name().and_then(|s| s.to_str()), Some("latest"));
2222 }
2223
2224 #[test]
2225 fn latest_metrics_db_is_under_latest_session_dir() {
2226 let metrics = latest_metrics_db();
2227 let latest = latest_session_dir();
2228 assert!(
2229 metrics.starts_with(&latest),
2230 "latest_metrics_db MUST live under latest_session_dir; \
2231 metrics={metrics:?}, latest={latest:?}"
2232 );
2233 assert_eq!(
2234 metrics.file_name().and_then(|s| s.to_str()),
2235 Some("metrics.db")
2236 );
2237 }
2238
2239 #[test]
2240 fn latest_session_log_is_under_latest_session_dir() {
2241 let log = latest_session_log();
2242 let latest = latest_session_dir();
2243 assert!(log.starts_with(&latest));
2244 assert_eq!(
2245 log.file_name().and_then(|s| s.to_str()),
2246 Some("session.log")
2247 );
2248 }
2249
2250 #[test]
2251 fn latest_checkpoint_jsonl_is_under_latest_session_dir() {
2252 let ckpt = latest_checkpoint_jsonl();
2253 let latest = latest_session_dir();
2254 assert!(ckpt.starts_with(&latest));
2255 assert_eq!(
2256 ckpt.file_name().and_then(|s| s.to_str()),
2257 Some("checkpoint.jsonl")
2258 );
2259 }
2260
2261 #[test]
2262 fn session_dir_named_is_a_sibling_of_latest() {
2263 let root = default_sessions_root();
2264 let named = session_dir_named("default_20260601_120000");
2265 assert!(named.starts_with(&root));
2266 assert_eq!(
2267 named.file_name().and_then(|s| s.to_str()),
2268 Some("default_20260601_120000"),
2269 );
2270 }
2271
2272 #[test]
2273 fn check_session_path_accepts_real_paths() {
2274 for good in &[
2275 "/tmp/foo",
2276 "/tmp/foo/bar",
2277 "logs/session_2026",
2278 "./local/x",
2279 "../sibling/y",
2280 "relative/path",
2281 "/var/run/x=y", // `=` inside path, not at the head
2282 "C:/Windows/maybe", // exotic but harmless
2283 "logs/SESSION/x",
2284 ] {
2285 assert!(
2286 check_session_path(good, "test").is_ok(),
2287 "should accept '{good}'"
2288 );
2289 }
2290 }
2291
2292 #[test]
2293 fn check_session_path_message_names_remediation() {
2294 // The error must point the user at the right flag form,
2295 // not just say "bad path".
2296 let err = check_session_path("scenario=foo", "test").unwrap_err();
2297 assert!(err.contains("--session-path"), "missing flag hint: {err}");
2298 assert!(
2299 err.contains(":") && err.contains("kv separator"),
2300 "missing umbrella-form hint: {err}"
2301 );
2302 }
2303
2304 #[test]
2305 fn check_session_path_empty_head_passes() {
2306 // `=value` (empty head) is unusual but doesn't match the
2307 // param shape — let it through; downstream path APIs will
2308 // reject it on their own terms.
2309 assert!(check_session_path("=foo", "test").is_ok());
2310 }
2311
2312 #[test]
2313 fn flag_env_name_canonicalisation() {
2314 assert_eq!(flag_env_name("--session"), "NMBRS_SESSION");
2315 assert_eq!(flag_env_name("--session-name"), "NMBRS_SESSION_NAME");
2316 assert_eq!(flag_env_name("--session-path"), "NMBRS_SESSION_PATH");
2317 assert_eq!(flag_env_name("--multi-word-flag"), "NMBRS_MULTI_WORD_FLAG");
2318 }
2319
2320 #[test]
2321 fn resolve_flag_picks_cli_when_only_cli_set() {
2322 let _g = env_test_lock();
2323 unsafe {
2324 std::env::remove_var("NMBRS_SESSION_NAME");
2325 }
2326 let args = vec!["--session-name=foo".into()];
2327 assert_eq!(
2328 resolve_flag(&args, "--session-name").as_deref(),
2329 Some("foo")
2330 );
2331 }
2332
2333 #[test]
2334 fn resolve_flag_picks_env_when_only_env_set() {
2335 let _g = env_test_lock();
2336 unsafe {
2337 std::env::set_var("NMBRS_SESSION_NAME", "bar");
2338 }
2339 let v = resolve_flag(&[], "--session-name");
2340 unsafe {
2341 std::env::remove_var("NMBRS_SESSION_NAME");
2342 }
2343 assert_eq!(v.as_deref(), Some("bar"));
2344 }
2345
2346 #[test]
2347 fn forecast_keep_purge_counts_excess() {
2348 let parent =
2349 std::env::temp_dir().join(format!("nmbrs-forecast-{}", crate::scratch_suffix()));
2350 std::fs::create_dir_all(&parent).unwrap();
2351
2352 // 5 dirs present, keep=10 → next run wouldn't purge.
2353 for i in 0..5 {
2354 std::fs::create_dir(parent.join(format!("s{i}"))).unwrap();
2355 }
2356 assert_eq!(forecast_keep_purge(&parent, 10), 0);
2357
2358 // 5 dirs present, keep=5 → next run would purge 1.
2359 assert_eq!(forecast_keep_purge(&parent, 5), 1);
2360
2361 // 5 dirs present, keep=3 → next run would purge 3.
2362 assert_eq!(forecast_keep_purge(&parent, 3), 3);
2363
2364 // keep=0 disables.
2365 assert_eq!(forecast_keep_purge(&parent, 0), 0);
2366
2367 let _ = std::fs::remove_dir_all(&parent);
2368 }
2369
2370 #[test]
2371 fn resolve_flag_returns_none_when_neither_set() {
2372 let _g = env_test_lock();
2373 unsafe {
2374 std::env::remove_var("NMBRS_SESSION_NAME");
2375 }
2376 assert!(resolve_flag(&[], "--session-name").is_none());
2377 }
2378 // Note: the conflict-error path (both CLI and env set)
2379 // calls process::exit(2). Testing it requires spawning a
2380 // subprocess; left to the e2e level.
2381
2382 #[test]
2383 fn parse_duration_units() {
2384 use std::time::Duration;
2385 assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
2386 assert_eq!(parse_duration("5m").unwrap(), Duration::from_secs(300));
2387 assert_eq!(parse_duration("2h").unwrap(), Duration::from_secs(7200));
2388 assert_eq!(parse_duration("3d").unwrap(), Duration::from_secs(259200));
2389 assert_eq!(parse_duration("4w").unwrap(), Duration::from_secs(2419200));
2390 // Bare integer = seconds.
2391 assert_eq!(parse_duration("60").unwrap(), Duration::from_secs(60));
2392 }
2393
2394 #[test]
2395 fn parse_duration_rejects_garbage() {
2396 assert!(parse_duration("").is_err());
2397 assert!(parse_duration("not-a-number").is_err());
2398 assert!(parse_duration("abc4w").is_err());
2399 }
2400
2401 /// A session another run still holds is not deleted, however far past
2402 /// the keep cap it sits; once released, the same pass deletes it.
2403 #[test]
2404 fn purge_spares_a_live_session_until_it_is_released() {
2405 let parent =
2406 std::env::temp_dir().join(format!("nmbrs-purge-live-{}", crate::scratch_suffix()));
2407 let live = parent.join("live");
2408 std::fs::create_dir_all(&live).unwrap();
2409 std::fs::write(live.join("metrics.db"), "x").unwrap();
2410 let held = hold_session_liveness(&live).expect("hold the liveness lock");
2411 // Newer sessions, enough to push `live` past a cap of 1.
2412 for i in 0..3 {
2413 std::thread::sleep(std::time::Duration::from_millis(20));
2414 let d = parent.join(format!("later_{i}"));
2415 std::fs::create_dir(&d).unwrap();
2416 std::fs::write(d.join("metrics.db"), "x").unwrap();
2417 }
2418
2419 purge_stale_sessions(&parent, 1, std::time::Duration::ZERO);
2420 assert!(live.is_dir(), "a live session was purged");
2421 assert!(
2422 !parent.join("later_0").exists(),
2423 "an idle session past the cap survived"
2424 );
2425
2426 drop(held);
2427 purge_stale_sessions(&parent, 1, std::time::Duration::ZERO);
2428 assert!(!live.exists(), "a released session past the cap survived");
2429
2430 let _ = std::fs::remove_dir_all(&parent);
2431 }
2432
2433 #[test]
2434 fn purge_keeps_latest_n_sessions() {
2435 let parent =
2436 std::env::temp_dir().join(format!("nmbrs-purge-test-{}", crate::scratch_suffix()));
2437 std::fs::create_dir_all(&parent).unwrap();
2438
2439 // Create 5 dirs with staggered mtimes.
2440 for i in 0..5 {
2441 let d = parent.join(format!("sess_{i}"));
2442 std::fs::create_dir(&d).unwrap();
2443 let now = std::time::SystemTime::now() - std::time::Duration::from_secs(60 * (5 - i));
2444 // Touch via filetime-style: re-create a marker so mtime
2445 // reflects roughly the right ordering.
2446 std::fs::write(d.join("metrics.db"), "x").unwrap();
2447 // Set the dir's modified time via a fresh file write; OS
2448 // updates mtime as side effect. For test stability, sort
2449 // order will follow the creation order, which is
2450 // newest-last.
2451 let _ = now;
2452 }
2453
2454 // Newest 2 should survive after purge with max=2.
2455 purge_stale_sessions(&parent, 2, std::time::Duration::ZERO);
2456
2457 let surviving: Vec<_> = std::fs::read_dir(&parent)
2458 .unwrap()
2459 .filter_map(|e| e.ok())
2460 .map(|e| e.path())
2461 .filter(|p| p.is_dir())
2462 .collect();
2463 assert!(
2464 surviving.len() <= 2,
2465 "expected ≤2 survivors, got {}: {:?}",
2466 surviving.len(),
2467 surviving
2468 );
2469
2470 // Cleanup
2471 let _ = std::fs::remove_dir_all(&parent);
2472 }
2473
2474 #[test]
2475 fn purge_skips_logs_latest_symlink() {
2476 let parent =
2477 std::env::temp_dir().join(format!("nmbrs-purge-symlink-{}", crate::scratch_suffix()));
2478 std::fs::create_dir_all(&parent).unwrap();
2479 let active = parent.join("active_session");
2480 std::fs::create_dir(&active).unwrap();
2481 std::fs::write(active.join("metrics.db"), "x").unwrap();
2482 // Create logs/latest symlink → active. Windows only allows
2483 // symlink creation with Developer Mode / admin — skip the
2484 // test rather than fail when the link can't exist at all.
2485 if symlink_any(&active, &parent.join("latest")).is_err() {
2486 eprintln!("skipping: cannot create symlinks here");
2487 let _ = std::fs::remove_dir_all(&parent);
2488 return;
2489 }
2490
2491 // Purge with aggressive caps — `active` must not be deleted
2492 // because it's the symlink target.
2493 purge_stale_sessions(&parent, 0, std::time::Duration::from_secs(1));
2494
2495 assert!(
2496 active.exists(),
2497 "active session pointed-at by logs/latest must survive purge"
2498 );
2499 let _ = std::fs::remove_dir_all(&parent);
2500 }
2501}
2502
2503#[cfg(test)]
2504mod confine_tests {
2505 use super::confine_to_dir;
2506 use std::path::Path;
2507
2508 #[test]
2509 fn relative_paths_land_inside_the_base() {
2510 let base = Path::new("/sess");
2511 assert_eq!(
2512 confine_to_dir(base, "traces.jsonl").unwrap(),
2513 Path::new("/sess/traces.jsonl")
2514 );
2515 assert_eq!(
2516 confine_to_dir(base, "./sub/x.log").unwrap(),
2517 Path::new("/sess/./sub/x.log")
2518 );
2519 }
2520
2521 #[test]
2522 fn escapes_and_absolutes_are_refused() {
2523 let base = Path::new("/sess");
2524 assert!(confine_to_dir(base, "../x").unwrap_err().contains(".."));
2525 assert!(
2526 confine_to_dir(base, "a/../../x")
2527 .unwrap_err()
2528 .contains("..")
2529 );
2530 assert!(
2531 confine_to_dir(base, "/etc/passwd")
2532 .unwrap_err()
2533 .contains("absolute")
2534 );
2535 assert!(confine_to_dir(base, "").unwrap_err().contains("empty"));
2536 }
2537}