Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Changelog

- **Fixed** Running a nested `vp run` inside another cached `vp run` task (for example, through a wrapper script) now detects the active outer automatic file-access tracker and delegates tracking to it on Linux, macOS, and Windows, so the outer task records all nested file accesses and stays cacheable. The nested task reports that automatic tracking is already active in a parent task and can still be cached by configuring `input` and `output` manually ([#1034](https://github.com/voidzero-dev/vite-task/pull/1034)).
- **Changed** On Linux, automatic file-access tracking now uses an in-process ELF launcher and `SIGSYS` syscall tracker instead of `LD_PRELOAD` and `seccomp_unotify`, unifying tracking across glibc, musl, static binaries, and direct-syscall runtimes such as Bun. Tracked Linux processes run with `no_new_privs`, fall back from `io_uring` to standard filesystem syscalls, and require native ELF64 executables ([#1026](https://github.com/voidzero-dev/vite-task/pull/1026), [#1027](https://github.com/voidzero-dev/vite-task/pull/1027), [#1028](https://github.com/voidzero-dev/vite-task/pull/1028), [#1029](https://github.com/voidzero-dev/vite-task/pull/1029)).
- **Fixed** Remote cache operations now cap concurrent uploads to 4 per endpoint, use pooled HTTP/1.1 connections instead of multiplexing all reads and uploads over one HTTP/2 connection, retry transient `5xx`/`429`/`408` and network failures with jittered backoff, and back off briefly during sustained endpoint outages, preventing `503` upload bursts and Windows connection-reset drops ([#1016](https://github.com/voidzero-dev/vite-task/pull/1016)).
- **Fixed** Tasks that list `node_modules`, the workspace root, or `node_modules/.vite` no longer miss the cache when pnpm's `node_modules/.pnpm-workspace-state-*.json`, Vite's `node_modules/.vite-temp`, the workspace root's `.git`, or the task cache directory appear or disappear. Direct accesses to `node_modules/.vite-temp` and `.DS_Store` are now skipped as well, so they are neither tracked as inputs nor archived as outputs ([#1014](https://github.com/voidzero-dev/vite-task/pull/1014)).
Expand Down
4 changes: 2 additions & 2 deletions crates/fspy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ tempfile = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros", "net", "process", "io-util", "sync", "rt"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
vt_casefold = { workspace = true }
vt_materialized_artifact = { workspace = true }
which = { workspace = true, features = ["tracing"] }
Expand All @@ -35,7 +36,6 @@ fspy_shared_unix = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
linux-raw-sys = { workspace = true, features = ["general", "prctl", "ptrace"] }
syscalls = { workspace = true }
tracing = { workspace = true }

[target.'cfg(all(target_os = "linux", target_arch = "x86_64"))'.dependencies]
fspy_preload_linux = { path = "../fspy_preload_linux", artifact = "bin", target = "x86_64-unknown-none" }
Expand All @@ -51,7 +51,7 @@ ouroboros = { workspace = true }
fspy_detours_sys = { workspace = true }
fspy_preload_windows = { workspace = true }
ntapi = { workspace = true }
winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi"] }
winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleapi", "ntstatus"] }
winsafe = { workspace = true, features = ["kernel"] }

[dev-dependencies]
Expand Down
10 changes: 9 additions & 1 deletion crates/fspy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ installs a `SECCOMP_RET_TRAP` (`SIGSYS`) filter to record filesystem syscalls
into the shared-memory IPC channel (`fspy_shared::ipc::channel`) and chain child
`execve`/`execveat` calls. When `seccomp` is unavailable (such as in a
restricted sandbox), `fspy` falls back to running the command untracked and
reports `TrackingIncomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and
reports `UntrackedReason::Incomplete`. Because seccomp sets `PR_SET_NO_NEW_PRIVS` and
userland ELF mapping opens target binaries read-only, setuid/setgid and
file-capability escalations do not apply, and execute-only (`chmod 0111`)
binaries cannot be mapped and fail with `EACCES`.
Expand All @@ -28,6 +28,14 @@ coreutils for SIP-protected `/bin`/`/usr/bin` binaries.
Windows uses [Detours](https://github.com/microsoft/Detours) with
`fspy_preload_windows` (`src/windows`) to intercept Win32/NT file system calls.

## Nested tracking

When `fspy` runs inside a process already tracked by an outer `fspy` instance
on Linux, macOS, or Windows, it detects the active outer tracker by probing a
sentinel path under the OS null device (intercepted and short-circuited by the
outer preload without recording a file access), delegates tracking to the outer
tracker, and reports `UntrackedReason::Nested`.

## Unified interface

The unified interface of `Command` is in `src/command.rs`.
33 changes: 21 additions & 12 deletions crates/fspy/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,26 @@ pub enum SpawnError {
OsSpawn(std::io::Error),
}

/// A tracked process could not record a file access it went on to perform,
/// so the accesses collected for the run are a subset of what it really
/// touched.
/// Why complete file accesses could not be collected for a tracked child
/// process.
///
/// The tracking channel can be full, or a process can continue untracked
/// because the seccomp filter could not be installed.
///
/// The run itself is unaffected: recording must never stop the program
/// doing the work. What cannot be done is anything that needs every
/// access, caching above all, which has to treat the run as untracked
/// rather than as having touched only the paths that fit.
/// The run itself is unaffected: recording must never stop the program doing
/// the work. What cannot be done is anything that needs every access, caching
/// above all, which has to treat the run as untracked rather than as having
/// touched only a subset of paths.
#[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)]
#[error("automatic file tracking could not record every file access")]
pub struct TrackingIncomplete;
pub enum UntrackedReason {
/// A tracked process could not record a file access it went on to perform,
/// so the accesses collected for the run are a subset of what it really
/// touched (for example, the tracking channel filled up, or on Linux the
/// seccomp filter could not be installed or the launcher could not be
/// materialized).
#[error("automatic file tracking could not record every file access")]
Incomplete,

/// The current process is already running inside an outer `fspy` tracker,
/// so this child was spawned untracked and its accesses are captured by
/// the outer tracker instead.
#[error("automatic file tracking is already active in a parent process")]
Nested,
}
10 changes: 5 additions & 5 deletions crates/fspy/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use fspy_shared::ipc::{
channel::{FrameReader, Receiver},
};

use crate::error::TrackingIncomplete;
use crate::error::UntrackedReason;

/// Shared memory for one tracked run's file-access records.
///
Expand Down Expand Up @@ -39,7 +39,7 @@ pub struct ChannelAccesses {
}

impl TryFrom<Receiver<Global>> for ChannelAccesses {
type Error = TrackingIncomplete;
type Error = UntrackedReason;

/// Closes the channel and takes every record it collected.
///
Expand All @@ -50,11 +50,11 @@ impl TryFrom<Receiver<Global>> for ChannelAccesses {
///
/// # Errors
///
/// [`TrackingIncomplete`] when a tracked process could not record
/// [`UntrackedReason::Incomplete`] when a tracked process could not record
/// something it went on to do. What did arrive is then a subset of
/// what the run really touched, so none of it is handed back.
fn try_from(receiver: Receiver<Global>) -> Result<Self, TrackingIncomplete> {
Ok(Self { frames: receiver.close().map_err(|_| TrackingIncomplete)? })
fn try_from(receiver: Receiver<Global>) -> Result<Self, UntrackedReason> {
Ok(Self { frames: receiver.close().map_err(|_| UntrackedReason::Incomplete)? })
}
}

Expand Down
7 changes: 4 additions & 3 deletions crates/fspy/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod error;

mod ipc;
mod nested;

#[cfg(target_os = "linux")]
#[path = "./linux/mod.rs"]
Expand All @@ -21,7 +22,7 @@ mod command;
use std::{io, process::ExitStatus, sync::LazyLock};

pub use command::Command;
pub use error::TrackingIncomplete;
pub use error::UntrackedReason;
pub use fspy_shared::ipc::{IpcPath, PathAccess};
use futures_util::future::BoxFuture;
pub use os_impl::PathAccessIterable;
Expand All @@ -33,8 +34,8 @@ pub struct ChildTermination {
/// The exit status of the child process.
pub status: ExitStatus,
/// The path accesses captured from the child process, or the reason
/// they cannot be trusted to be all of them.
pub path_accesses: Result<PathAccessIterable, TrackingIncomplete>,
/// complete accesses were not collected.
pub path_accesses: Result<PathAccessIterable, UntrackedReason>,
}

pub struct TrackedChild {
Expand Down
89 changes: 54 additions & 35 deletions crates/fspy/src/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,26 @@ use tokio_util::sync::CancellationToken;
use vt_materialized_artifact::{Artifact, artifact};

use crate::{
ChildTermination, Command, TrackedChild, TrackingIncomplete, error::SpawnError,
ChildTermination, Command, TrackedChild, UntrackedReason, error::SpawnError,
ipc::ChannelAccesses,
};

const PRELOAD_LINUX: Artifact = artifact!("fspy_preload", "CARGO_BIN_FILE_FSPY_PRELOAD_LINUX");

#[derive(Debug)]
enum LinuxTracker {
/// Materialized executable path to `fspy_preload_linux`. Wrapped in
/// `RwLock` so a file reaped from the temp directory (e.g. by
/// `systemd-tmpfiles`) can be lazily re-materialized on `ENOENT`, or
/// cleared to `None` if re-materialization fails.
Active(RwLock<Option<Box<IpcStr>>>),
/// Untracked fallback with the exact reason (`Nested` or `Incomplete`).
Untracked(UntrackedReason),
}

#[derive(Debug)]
pub struct SpyImpl {
/// Materialized executable path to `fspy_preload_linux`, or `None` when
/// seccomp is unavailable or materialization failed (in which case `spawn`
/// falls back to untracked execution). Wrapped in `RwLock` so a file reaped
/// from the temp directory (e.g. by `systemd-tmpfiles`) can be lazily
/// re-materialized on `ENOENT`.
preload_path: RwLock<Option<Box<IpcStr>>>,
seccomp_available: bool,
tracker: LinuxTracker,
}

impl SpyImpl {
Expand All @@ -47,36 +52,42 @@ impl SpyImpl {
reason = "matches cross-platform SpyImpl::init() -> io::Result<Self> signature"
)]
pub fn init() -> io::Result<Self> {
let seccomp_available = probe_seccomp_available();
let preload_path = if seccomp_available {
let materialized = materialize_preload();
if materialized.is_none() {
tracing::warn!(
"failed to materialize the Linux task tracker binary, so Linux task \
tracking is off and caching is disabled"
);
}
materialized
} else {
None
if crate::nested::is_nested() {
tracing::debug!(
"nested inside an active fspy tracker; delegating tracking to outer tracker"
);
return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Nested) });
}
if !probe_seccomp_available() {
return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Incomplete) });
}
let Some(preload_path) = materialize_preload() else {
tracing::warn!(
"failed to materialize the Linux task tracker binary, so Linux task \
tracking is off and caching is disabled"
);
return Ok(Self { tracker: LinuxTracker::Untracked(UntrackedReason::Incomplete) });
};
Ok(Self { preload_path: RwLock::new(preload_path), seccomp_available })
Ok(Self { tracker: LinuxTracker::Active(RwLock::new(Some(preload_path))) })
}

fn preload_path(&self) -> Option<Box<IpcStr>> {
if !self.seccomp_available {
return None;
fn preload_path(&self) -> Result<Box<IpcStr>, UntrackedReason> {
match &self.tracker {
LinuxTracker::Untracked(reason) => Err(*reason),
LinuxTracker::Active(lock) => lock
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_deref()
.map(clone_ipc_str)
.ok_or(UntrackedReason::Incomplete),
}
self.preload_path
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_deref()
.map(clone_ipc_str)
}

fn rematerialize_preload(&self, failed_path: &IpcStr) -> Option<Box<IpcStr>> {
let mut guard =
self.preload_path.write().unwrap_or_else(std::sync::PoisonError::into_inner);
let LinuxTracker::Active(lock) = &self.tracker else {
return None;
};
let mut guard = lock.write().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(current) = guard.as_deref()
&& (current.as_bytes() != failed_path.as_bytes()
|| Path::new(current.as_os_str()).exists())
Expand All @@ -93,8 +104,9 @@ impl SpyImpl {
mut command: Command,
cancellation_token: CancellationToken,
) -> Result<TrackedChild, SpawnError> {
let Some(mut preload_path) = self.preload_path() else {
return spawn_untracked(command, cancellation_token);
let mut preload_path = match self.preload_path() {
Ok(path) => path,
Err(reason) => return spawn_untracked(command, cancellation_token, reason),
};
// If the cached launcher binary was removed mid-process (e.g. by
// `systemd-tmpfiles`), re-materialize before building `tokio_command`
Expand All @@ -103,7 +115,13 @@ impl SpyImpl {
if !Path::new(preload_path.as_os_str()).exists() {
match self.rematerialize_preload(&preload_path) {
Some(new_path) => preload_path = new_path,
None => return spawn_untracked(command, cancellation_token),
None => {
return spawn_untracked(
command,
cancellation_token,
UntrackedReason::Incomplete,
);
}
}
}

Expand Down Expand Up @@ -240,6 +258,7 @@ async fn await_startup_handshake(
fn spawn_untracked(
command: Command,
cancellation_token: CancellationToken,
reason: UntrackedReason,
) -> Result<TrackedChild, SpawnError> {
let mut tokio_command = command.into_tokio_command();
let mut child = tokio_command.spawn().map_err(SpawnError::OsSpawn)?;
Expand All @@ -255,7 +274,7 @@ fn spawn_untracked(
child.wait().await?
}
};
io::Result::Ok(ChildTermination { status, path_accesses: Err(TrackingIncomplete) })
io::Result::Ok(ChildTermination { status, path_accesses: Err(reason) })
})
.map(|f| f?)
.boxed(),
Expand Down
Loading
Loading