fix(runner): wait out a short-lived foreign orphan before refusing a lost runnerd's lineage proof (#23006)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Runner stops a lost (killed) local runnerd's provider and
tool processes from runnerd's durable process lineage journal
(`paperclip-runnerd reap-lineage`)
> - The reap refuses its proof (`unattributed_orphan`) while a live
orphan (parent PID 1) of this user exists that started after the dead
runnerd's last sample. Ownership of such a process cannot be proven, so
this rule is deliberate
> - The reap refused at the first sight of such an orphan, even when
another program left it and it exited a moment later. On a busy host,
short-lived orphans of the same user are common
> - When the reap refuses, closing the session fails with
`NativeSessionCloseUnrecoverableError: provider_transport_failed: runner
did not durably suspend before checkpoint`, so recovery of a lost
runnerd fails for a reason that has nothing to do with that runnerd
> - This is the intermittent failure of the Runner test "stops a lost
runnerd's provider and escaped tool job from its lineage journal
(journal=true)" in Cloud readiness, which blocks Docker publishing and
staging deploys
> - This pull request makes the reap wait out unattributed orphans until
its deadline, and refuse only if one still lives then
> - The benefit is that a lost runnerd's cleanup is proven on a busy
host, and master's Cloud readiness stops failing on this test

## Linked Issues or Issue Description

**What happened?**

`verify / Verify Paperclip Runner (protocol (3/4))` in the Cloud
readiness workflow failed intermittently on master (for example commits
64bef50be0 and 3f1632c7b7) in `src/live/runnerd-codex-transport.test.ts`
> "stops a lost runnerd's provider and escaped tool job from its lineage
journal (journal=true)". The error was
`NativeSessionCloseUnrecoverableError: provider_transport_failed: runner
did not durably suspend before checkpoint` from `finishClose` in
`runnerd-codex-transport.ts`, with `proofWindowEnd:
"suspend_not_completed"`. The test passed on other attempts and locally.

**Expected behavior**

When a local runnerd is killed, close proves its provider and escaped
tool job stopped from the lineage journal and ends the session as a
crash stop. A process that another program starts and that exits on its
own does not make the proof fail.

**Steps to reproduce**

1. Run the test while short-lived orphan processes of the same user
start on the host, for example `( sleep 0.2 & )` every 0.5 s, with 14
busy loops of CPU load.
2. The reap reports
`{"verified":false,"reason":"unattributed_orphan","signalled":2,"remaining":[...]}`.
The remaining PIDs are the foreign orphans. The test's own provider and
tool job were already stopped.
3. Close throws the same error as CI.

Root cause: `reap_journals` in
`packages/paperclip-runner/runner/crates/runner-core/src/process_lineage/journal.rs`
returned `unattributed_orphan` immediately when a live unattributed
orphan was in the first clean process table read. In CI, other test
files in the same shard leave short-lived orphans of the same user (for
example a fake provider whose runnerd was killed). This is a product
race, not only a test timing issue: on a real host with several agents,
any short-lived orphan of the same user that starts in that window makes
the lost runnerd's recovery fail.

## What Changed

- `reap_journals`: an unattributed orphan no longer refuses the proof at
once. The reap re-reads the process table every 10 ms and refuses with
`unattributed_orphan` only if such an orphan still lives at its
deadline. It still never signals an unattributed process.
- A table read is per process and not atomic, so a parent can exit
during a read and hide its re-parented child. Three rules close that:
- A process whose parent is not alive in the same read counts as an
orphan.
- The reap keeps every unattributed orphan and each process seen under
it (by parent, group or session; PID and start time; never signalled)
across reads, and waits until all of them are gone. It uses the existing
`LineageState` walk, seeded through a new `LineageState::track_roots`.
- Every proof needs `CLEAN_READS_REQUIRED_FOR_A_PROOF` (2) consecutive
clean reads (about 10 ms more).
- The reap reads the table through an injectable reader.
Controlled-table tests cover each rule, and each test fails when its
rule is removed:
`reaping_counts_a_process_whose_parent_exited_during_the_first_read`,
`reaping_keeps_an_orphans_descendants_across_reads`,
`reaping_needs_consecutive_clean_reads_before_a_proof`.
`reaping_follows_an_orphan_tree_through_successive_torn_reads` covers an
orphan A whose child B forks C and exits.
-
`reaping_keeps_a_process_in_an_orphans_group_or_session_after_the_orphan_exits`
fails without group and session membership.
- The `reap_journals` doc describes these rules. The journal tests moved
to `process_lineage/journal/tests.rs`.
- New Rust test
`reaping_waits_out_a_short_lived_orphan_it_cannot_attribute`: an orphan
that lives 0.5 s during the reap. The proof holds, and the orphan is not
signalled.
- `reaping_refuses_an_orphan_born_after_the_last_sample` uses a 1 s
deadline instead of 5 s, because the refusal now waits until the
deadline.
- `runnerd-codex-transport.test.ts`: the lost-runnerd test gets a
`foreignOrphan=true` case. After runnerd is killed (so its journal is
final), the test starts a 1.5 s orphan of the same user. This forces the
CI ordering deterministically. The test asserts the same things as
before: verified report, provider and tool job stopped, no queued
suspend. It also asserts that the orphan exited on its own before close
returned.
- No change to what the reap proves or signals, and no change to the
TypeScript close path.

## Verification

- Deterministic reproduction, before the fix (master `journal.rs`):
`foreignOrphan=true` fails with the CI signature
(`NativeSessionCloseUnrecoverableError ... runner did not durably
suspend before checkpoint`, reap reason `unattributed_orphan`). After
the fix: passes.
- Rust red/green: `cargo test --release -p paperclip-runner-core --lib
reaping_waits_out` fails on master's reap loop and passes with the fix.
All 16 `process_lineage` lib tests pass.
- Repeated runs on macOS (18 cores), 14 busy loops of CPU load plus a
short-lived foreign orphan every 0.5 s, `vitest run
src/live/runnerd-codex-transport.test.ts -t "lineage journal"`, 30 runs
each:
- Before the fix: 0/30 runs passed. The original `journal=true` case
failed in 8 of 30 runs with the CI signature.
- After the fix: 29/30 and 25/30 runs passed. Every remaining failure
ran to the 5 s deadline with only macOS launchd agents left (Spotlight
`mdworker_shared`, `CommCenter`, `IMTransferAgent`). Those are
long-lived processes with parent PID 1 that the reap cannot attribute,
so the refusal is correct. Linux CI hosts do not start such agents.
- `cargo fmt --check` passes.
`tests/runner-e2e/source-sdk-public-inputs.json` is unchanged (checked
with the sync script).

## Risks

- A close that must refuse because of a long-lived unattributed orphan
now takes until the reap deadline (about 4.5 s) instead of returning at
once. The outcome is the same fail-closed result.
- On macOS, launchd agents (for example Spotlight workers) have parent
PID 1 and can still make the reap refuse when one starts during the
proof window. That is the existing deliberate rule and is not changed
here.
- Low risk otherwise. The reap still never signals a process it cannot
attribute.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits) and extended reasoning.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Refs #20849

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 19:39:54 -06:00
1 parent 2f9dc4a4c6
commit 03d88e4216
4 files changed
+705 -359

No files matched your search

@@ -129,6 +129,13 @@ impl LineageState {
state
}
/// Adds processes as members, each with the identity this read reported.
pub(crate) fn track_roots(&mut self, roots: &[ProcessEntry]) {
for root in roots.iter().filter(|root| !root.zombie) {
self.members.insert(root.pid, root.started);
}
}
/// Updates membership from one table read and returns the live members.
/// Callers must apply reads in the order they were taken; an older read
/// would forget members that a newer one recorded.
@@ -593,6 +600,16 @@ mod tests {
}
}
pub(super) fn table_with_unreadable(
entries: Vec<(ProcessEntry, i32)>,
unreadable: Vec<i32>,
) -> FixedTable {
FixedTable {
unreadable,
..table(entries)
}
}
impl LineageState {
pub(super) fn observe_live(&mut self, table: &FixedTable) -> Vec<ProcessEntry> {
self.observe(table).live
@@ -25,9 +25,7 @@ use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use super::{
read_process_table, signal_member, LineageState, LiveProcessTable, ProcessEntry, ProcessTable,
};
use super::{read_process_table, signal_member, LineageState, ProcessEntry, ProcessTable};
impl LineageState {
fn journal_record(&self, writer: ProcessIdentity, sampled_through: u64) -> JournalRecord {
@@ -282,11 +280,36 @@ impl ReapReport {
/// directory are reaped too; a live writer's journals are never touched. Each
/// process is signalled only while its PID and start time still match a
/// recorded identity: TERM first, KILL after `grace`.
///
/// A live orphan of this user that started after the dead runnerd's last
/// sample cannot be attributed and is never signalled. A process whose parent
/// is not alive in the same table read counts as an orphan too, because a
/// table read is not atomic and its parent may have exited during the read.
/// The reap waits for such orphans to exit and refuses with
/// `unattributed_orphan` only if one still lives at `deadline`.
pub fn reap_journals(
state_dir: &Path,
runner_pid: i32,
grace: Duration,
deadline: Duration,
) -> ReapReport {
reap_journals_from(
state_dir,
runner_pid,
grace,
deadline,
read_process_table,
owned_by_this_user,
)
}
fn reap_journals_from<T: ProcessTable>(
state_dir: &Path,
runner_pid: i32,
grace: Duration,
deadline: Duration,
mut read_table: impl FnMut() -> Option<T>,
owned: impl Fn(i32) -> bool,
) -> ReapReport {
let directory = state_dir.join(JOURNAL_DIRECTORY_NAME);
let marker_path = directory.join(format!("writer-{runner_pid}.json"));
@@ -339,9 +362,12 @@ pub fn reap_journals(
let count = journals.len();
let started = Instant::now();
let mut signalled: HashSet<(i32, u64)> = HashSet::new();
let mut unattributed_tree = LineageState::default();
let mut consecutive_clean_reads = 0;
loop {
let elapsed = started.elapsed();
let Some(table) = read_process_table() else {
let Some(table) = read_table() else {
consecutive_clean_reads = 0;
if elapsed >= deadline {
return ReapReport {
journals: count,
@@ -367,14 +393,40 @@ pub fn reap_journals(
// cannot be proven either way, so it is never signalled, and the
// proof is refused.
if let Some(since) = unsampled_since {
let escaped = unattributed_orphans(&table, since, &journals);
if !escaped.is_empty() {
return ReapReport {
journals: count,
signalled: signalled.len(),
remaining: escaped,
..ReapReport::refused("unattributed_orphan")
};
let escaped = unattributed_orphans(&table, since, &journals, &owned);
let roots: Vec<ProcessEntry> = table
.entries()
.iter()
.filter(|entry| escaped.contains(&entry.pid))
.copied()
.collect();
unattributed_tree.track_roots(&roots);
let observation = unattributed_tree.observe(&table);
let mut remaining: Vec<i32> = observation
.live
.iter()
.map(|entry| entry.pid)
.chain(observation.unresolved)
.collect();
remaining.sort_unstable();
remaining.dedup();
if !remaining.is_empty() {
consecutive_clean_reads = 0;
if elapsed >= deadline {
return ReapReport {
journals: count,
signalled: signalled.len(),
remaining,
..ReapReport::refused("unattributed_orphan")
};
}
thread::sleep(Duration::from_millis(10));
continue;
}
consecutive_clean_reads += 1;
if consecutive_clean_reads < CLEAN_READS_REQUIRED_FOR_A_PROOF {
thread::sleep(Duration::from_millis(10));
continue;
}
}
for (path, _) in &journals {
@@ -390,6 +442,7 @@ pub fn reap_journals(
remaining: Vec::new(),
};
}
consecutive_clean_reads = 0;
if elapsed >= deadline {
let mut remaining: Vec<i32> = live
.iter()
@@ -417,25 +470,42 @@ pub fn reap_journals(
}
}
/// Live orphans (parent PID 1) of this user that started no earlier than
/// `since` and belong to no journal. An orphan of a subreaper other than init
/// is not seen here; such a host keeps the in-process teardown only.
const CLEAN_READS_REQUIRED_FOR_A_PROOF: usize = 2;
/// Live orphans (parent PID 1, or a parent not alive in this read) of this
/// user that started no earlier than `since` and belong to no journal. An
/// orphan of a subreaper other than init is not seen here; such a host keeps
/// the in-process teardown only.
fn unattributed_orphans(
table: &LiveProcessTable,
table: &dyn ProcessTable,
since: u64,
journals: &[(PathBuf, LineageState)],
owned: &dyn Fn(i32) -> bool,
) -> Vec<i32> {
let alive: HashMap<i32, u64> = table
.entries()
.iter()
.filter(|entry| !entry.zombie)
.map(|entry| (entry.pid, entry.started))
.collect();
let unreadable: HashSet<i32> = table.unreadable().iter().copied().collect();
let parent_alive = |entry: &ProcessEntry| {
unreadable.contains(&entry.ppid)
|| alive
.get(&entry.ppid)
.is_some_and(|started| *started <= entry.started)
};
let mut pids: Vec<i32> = table
.entries()
.iter()
.filter(|entry| {
!entry.zombie
&& entry.ppid == 1
&& (entry.ppid == 1 || !parent_alive(entry))
&& entry.started >= since
&& !journals
.iter()
.any(|(_, state)| state.members.get(&entry.pid) == Some(&entry.started))
&& owned_by_this_user(entry.pid)
&& owned(entry.pid)
})
.map(|entry| entry.pid)
.collect();
@@ -457,340 +527,4 @@ fn owned_by_this_user(_pid: i32) -> bool {
}
#[cfg(test)]
mod tests {
use super::super::tests::{entry, pids, table};
use super::super::SAMPLE_INTERVAL;
use super::*;
#[test]
fn a_journalled_record_restores_the_same_lineage() {
let mut state = LineageState::new(100);
state.observe(&table(vec![
(entry(100, 10, 100, 10), 1),
(entry(200, 100, 200, 20), 200),
(entry(201, 200, 200, 21), 200),
]));
let writer = ProcessIdentity {
pid: 10,
started: 5,
};
let record = state.journal_record(writer, 0);
let json = serde_json::to_string(&record).unwrap();
let restored: JournalRecord = serde_json::from_str(&json).unwrap();
assert_eq!(restored.writer, writer);
let mut restored = LineageState::from_journal_record(&restored);
// runnerd (10) is gone and the wrapper exited: provider 100 and job
// 201 are re-parented to init, and a later job 202 was started.
let after = table(vec![
(entry(1, 0, 1, 1), 1),
(entry(100, 1, 100, 10), 1),
(entry(201, 1, 200, 21), 200),
(entry(202, 201, 200, 30), 200),
(entry(300, 1, 300, 40), 300),
]);
assert_eq!(pids(&restored.observe_live(&after)), vec![100, 201, 202]);
}
#[test]
fn an_unknown_root_start_is_never_journalled_as_an_identity() {
let state = LineageState::new(100);
let record = state.journal_record(
ProcessIdentity {
pid: 10,
started: 5,
},
0,
);
assert_eq!(record.root, None);
}
fn temporary_directory(name: &str) -> PathBuf {
let directory = std::env::temp_dir().join(format!(
"paperclip-lineage-{name}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(directory.join(JOURNAL_DIRECTORY_NAME)).unwrap();
directory
}
fn write_marker(state_dir: &Path, writer: ProcessIdentity) {
let marker = WriterMarker {
schema: WRITER_SCHEMA.to_owned(),
writer,
};
fs::write(
state_dir
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid)),
serde_json::to_vec(&marker).unwrap(),
)
.unwrap();
}
/// A process that existed and has exited, so its identity is dead.
fn exited_writer() -> ProcessIdentity {
let mut child = std::process::Command::new("/bin/sleep")
.arg("5")
.spawn()
.unwrap();
let pid = i32::try_from(child.id()).unwrap();
let started = paperclip_process_table::read(pid).entry().unwrap().started;
child.kill().unwrap();
child.wait().unwrap();
ProcessIdentity { pid, started }
}
#[test]
fn reaping_refuses_without_a_marker_or_while_the_writer_lives() {
let directory = temporary_directory("refuse");
let report = reap_journals(&directory, 4242, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unavailable"));
assert!(!report.verified);
let alive = ProcessIdentity::current().unwrap();
write_marker(&directory, alive);
let report = reap_journals(&directory, alive.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("runner_alive"));
assert!(!report.verified);
let _ = fs::remove_dir_all(&directory);
}
#[test]
fn reaping_refuses_an_unreadable_journal() {
let directory = temporary_directory("unreadable");
let writer = exited_writer();
write_marker(&directory, writer);
fs::write(
directory
.join(JOURNAL_DIRECTORY_NAME)
.join("lineage-1-0.json"),
b"{",
)
.unwrap();
let report = reap_journals(&directory, writer.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unreadable"));
let _ = fs::remove_dir_all(&directory);
}
/// runnerd is SIGKILLed mid-tool: its provider and a tool job that left
/// the provider's session outlive it. The journal alone finds and stops
/// both, and proves them gone.
#[test]
fn reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job() {
use std::os::unix::process::CommandExt;
// The proof refuses while any orphan of this user started after the
// journal was written, including one that another test left.
let _no_foreign_orphans = super::super::host_orphans::no_foreign_orphans();
let directory = temporary_directory("reap");
let pid_file = directory.join("job.pid");
// The wrapper lives past several samples, as a real tool wrapper does.
let tool = r#"sleep 0.3; nohup /bin/sh -c 'while :; do sleep 1; done' >/dev/null 2>&1 & echo $! > "$0.tmp"; mv "$0.tmp" "$0"; exit 0"#;
let wrapper = format!(
"use POSIX (); POSIX::setsid() or die; exec '/bin/sh', '-c', q{{{tool}}}, $ARGV[0];"
);
let mut provider = std::process::Command::new("/bin/sh")
.args([
"-c",
r#"sleep 0.2; perl -e "$1" "$2"; while :; do sleep 1; done"#,
"provider",
&wrapper,
&pid_file.display().to_string(),
])
.process_group(0)
.spawn()
.unwrap();
let provider_pid = i32::try_from(provider.id()).unwrap();
let root = paperclip_process_table::read(provider_pid).entry().unwrap();
let mut state = LineageState::with_known_root(root);
let deadline = Instant::now() + Duration::from_secs(10);
let job = loop {
let live = state.observe(&read_process_table().unwrap()).live;
if let Some(pid) = fs::read_to_string(&pid_file)
.ok()
.and_then(|text| text.trim().parse::<i32>().ok())
{
if let Some(job) = live.iter().find(|entry| entry.pid == pid) {
break *job;
}
}
assert!(Instant::now() < deadline, "tool job was not recorded");
thread::sleep(SAMPLE_INTERVAL);
};
assert_ne!(job.pgid, provider_pid);
let writer = exited_writer();
write_marker(&directory, writer);
let journal = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid));
fs::write(
&journal,
serde_json::to_vec(&state.journal_record(writer, newest_start())).unwrap(),
)
.unwrap();
let report = reap_journals(
&directory,
writer.pid,
Duration::from_millis(500),
Duration::from_secs(10),
);
let _ = provider.wait();
let job_alive = paperclip_process_table::read(job.pid)
.entry()
.is_some_and(|current| current.started == job.started && !current.zombie);
if job_alive {
if let Some(group) = rustix::process::Pid::from_raw(job.pgid) {
let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
}
}
assert!(!job_alive, "tool job {} outlived the reap", job.pid);
assert!(report.verified, "{report:?}");
assert_eq!(report.journals, 1);
assert!(report.signalled >= 2, "{report:?}");
assert!(!journal.exists(), "a proven journal is retired");
assert!(!directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid))
.exists());
let _ = fs::remove_dir_all(&directory);
}
/// The newest start time a table read lists now, as the sampler records.
fn newest_start() -> u64 {
read_process_table()
.unwrap()
.entries()
.iter()
.map(|entry| entry.started)
.max()
.unwrap()
}
/// A tool forked and left its session after the dead runnerd's last
/// read, and its parents are gone: nothing recorded leads to it. The reap
/// must not claim proof, and must not signal a process it cannot
/// attribute.
#[test]
fn reaping_refuses_an_orphan_born_after_the_last_sample() {
let orphans = super::super::host_orphans::may_orphan();
let directory = temporary_directory("escape");
let writer = exited_writer();
write_marker(&directory, writer);
let provider = exited_writer();
let mut state = LineageState::default();
state.root = Some((provider.pid, provider.started));
let journal = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid));
fs::write(
&journal,
serde_json::to_vec(&state.journal_record(writer, newest_start())).unwrap(),
)
.unwrap();
// runnerd died right after the tool started, before any read saw it.
// The tool starts a new session, starts a job and exits, so the job
// is re-parented to init and leads neither its group nor its session.
let pid_file = directory.join("orphan.pid");
let status = std::process::Command::new("perl")
.args([
"-e",
"use POSIX (); exit 0 if fork(); POSIX::setsid() or die; exit 0 if fork(); sleep 1 while getppid() != 1; open(my $f, '>', \"$ARGV[0].tmp\") or die; print $f $$; close $f; rename(\"$ARGV[0].tmp\", $ARGV[0]) or die; open(STDIN, '<', '/dev/null'); open(STDOUT, '>', '/dev/null'); open(STDERR, '>', '/dev/null'); exec '/bin/sh', '-c', 'while :; do sleep 1; done'",
&pid_file.display().to_string(),
])
.status()
.unwrap();
assert!(status.success());
let deadline = Instant::now() + Duration::from_secs(10);
let orphan = loop {
if let Some(entry) = fs::read_to_string(&pid_file)
.ok()
.and_then(|text| text.trim().parse::<i32>().ok())
.and_then(|pid| paperclip_process_table::read(pid).entry())
.filter(|entry| entry.ppid == 1 && entry.pgid != entry.pid)
{
break entry;
}
assert!(Instant::now() < deadline, "orphan job did not start");
thread::sleep(Duration::from_millis(20));
};
let report = reap_journals(
&directory,
writer.pid,
Duration::ZERO,
Duration::from_secs(5),
);
let alive = ProcessIdentity {
pid: orphan.pid,
started: orphan.started,
}
.is_alive();
if let Some(group) = rustix::process::Pid::from_raw(orphan.pgid) {
let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
}
super::super::host_orphans::wait_until_group_gone(orphan.pgid);
drop(orphans);
let _ = fs::remove_dir_all(&directory);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert!(report.remaining.contains(&orphan.pid), "{report:?}");
assert!(alive, "an unattributed process is never signalled");
}
/// A record that could not be written may be missing a member. The
/// failure withdraws the writer marker, so no reap can verify.
#[test]
fn a_failed_journal_write_withdraws_the_writer_marker() {
let directory = temporary_directory("write-failure");
let writer = exited_writer();
write_marker(&directory, writer);
let marker = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid));
let journal = Journal {
path: directory.join("missing").join("lineage.json"),
marker: marker.clone(),
writer,
last: Mutex::new(JournalWrite::default()),
};
assert!(journal.write(&LineageState::new(100), 1).is_err());
assert!(!marker.exists());
let report = reap_journals(&directory, writer.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unavailable"));
let _ = fs::remove_dir_all(&directory);
}
#[test]
fn an_unchanged_record_is_rewritten_only_to_advance_sampled_through() {
let directory = temporary_directory("refresh");
let path = directory.join(JOURNAL_DIRECTORY_NAME).join("lineage.json");
let journal = Journal {
path: path.clone(),
marker: directory.join("marker"),
writer: ProcessIdentity {
pid: 10,
started: 5,
},
last: Mutex::new(JournalWrite::default()),
};
let state = LineageState::new(100);
let read = || {
serde_json::from_slice::<JournalRecord>(&fs::read(&path).unwrap())
.unwrap()
.sampled_through
};
journal.write(&state, 7).unwrap();
assert_eq!(read(), 7);
// Within the refresh interval an advance alone is not written.
journal.write(&state, 9).unwrap();
assert_eq!(read(), 7);
journal.last.lock().unwrap().at = Some(Instant::now() - SAMPLED_THROUGH_REFRESH);
journal.write(&state, 9).unwrap();
assert_eq!(read(), 9);
let _ = fs::remove_dir_all(&directory);
}
}
mod tests;
@@ -0,0 +1,583 @@
use super::super::tests::{entry, pids, table, FixedTable};
use super::super::SAMPLE_INTERVAL;
use super::*;
#[test]
fn a_journalled_record_restores_the_same_lineage() {
let mut state = LineageState::new(100);
state.observe(&table(vec![
(entry(100, 10, 100, 10), 1),
(entry(200, 100, 200, 20), 200),
(entry(201, 200, 200, 21), 200),
]));
let writer = ProcessIdentity {
pid: 10,
started: 5,
};
let record = state.journal_record(writer, 0);
let json = serde_json::to_string(&record).unwrap();
let restored: JournalRecord = serde_json::from_str(&json).unwrap();
assert_eq!(restored.writer, writer);
let mut restored = LineageState::from_journal_record(&restored);
// runnerd (10) is gone and the wrapper exited: provider 100 and job
// 201 are re-parented to init, and a later job 202 was started.
let after = table(vec![
(entry(1, 0, 1, 1), 1),
(entry(100, 1, 100, 10), 1),
(entry(201, 1, 200, 21), 200),
(entry(202, 201, 200, 30), 200),
(entry(300, 1, 300, 40), 300),
]);
assert_eq!(pids(&restored.observe_live(&after)), vec![100, 201, 202]);
}
#[test]
fn an_unknown_root_start_is_never_journalled_as_an_identity() {
let state = LineageState::new(100);
let record = state.journal_record(
ProcessIdentity {
pid: 10,
started: 5,
},
0,
);
assert_eq!(record.root, None);
}
fn temporary_directory(name: &str) -> PathBuf {
let directory = std::env::temp_dir().join(format!(
"paperclip-lineage-{name}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(directory.join(JOURNAL_DIRECTORY_NAME)).unwrap();
directory
}
fn write_marker(state_dir: &Path, writer: ProcessIdentity) {
let marker = WriterMarker {
schema: WRITER_SCHEMA.to_owned(),
writer,
};
fs::write(
state_dir
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid)),
serde_json::to_vec(&marker).unwrap(),
)
.unwrap();
}
/// A process that existed and has exited, so its identity is dead.
fn exited_writer() -> ProcessIdentity {
let mut child = std::process::Command::new("/bin/sleep")
.arg("5")
.spawn()
.unwrap();
let pid = i32::try_from(child.id()).unwrap();
let started = paperclip_process_table::read(pid).entry().unwrap().started;
child.kill().unwrap();
child.wait().unwrap();
ProcessIdentity { pid, started }
}
#[test]
fn reaping_refuses_without_a_marker_or_while_the_writer_lives() {
let directory = temporary_directory("refuse");
let report = reap_journals(&directory, 4242, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unavailable"));
assert!(!report.verified);
let alive = ProcessIdentity::current().unwrap();
write_marker(&directory, alive);
let report = reap_journals(&directory, alive.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("runner_alive"));
assert!(!report.verified);
let _ = fs::remove_dir_all(&directory);
}
#[test]
fn reaping_refuses_an_unreadable_journal() {
let directory = temporary_directory("unreadable");
let writer = exited_writer();
write_marker(&directory, writer);
fs::write(
directory
.join(JOURNAL_DIRECTORY_NAME)
.join("lineage-1-0.json"),
b"{",
)
.unwrap();
let report = reap_journals(&directory, writer.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unreadable"));
let _ = fs::remove_dir_all(&directory);
}
/// runnerd is SIGKILLed mid-tool: its provider and a tool job that left
/// the provider's session outlive it. The journal alone finds and stops
/// both, and proves them gone.
#[test]
fn reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job() {
use std::os::unix::process::CommandExt;
// The proof refuses while any orphan of this user started after the
// journal was written, including one that another test left.
let _no_foreign_orphans = super::super::host_orphans::no_foreign_orphans();
let directory = temporary_directory("reap");
let pid_file = directory.join("job.pid");
// The wrapper lives past several samples, as a real tool wrapper does.
let tool = r#"sleep 0.3; nohup /bin/sh -c 'while :; do sleep 1; done' >/dev/null 2>&1 & echo $! > "$0.tmp"; mv "$0.tmp" "$0"; exit 0"#;
let wrapper = format!(
"use POSIX (); POSIX::setsid() or die; exec '/bin/sh', '-c', q{{{tool}}}, $ARGV[0];"
);
let mut provider = std::process::Command::new("/bin/sh")
.args([
"-c",
r#"sleep 0.2; perl -e "$1" "$2"; while :; do sleep 1; done"#,
"provider",
&wrapper,
&pid_file.display().to_string(),
])
.process_group(0)
.spawn()
.unwrap();
let provider_pid = i32::try_from(provider.id()).unwrap();
let root = paperclip_process_table::read(provider_pid).entry().unwrap();
let mut state = LineageState::with_known_root(root);
let deadline = Instant::now() + Duration::from_secs(10);
let job = loop {
let live = state.observe(&read_process_table().unwrap()).live;
if let Some(pid) = fs::read_to_string(&pid_file)
.ok()
.and_then(|text| text.trim().parse::<i32>().ok())
{
if let Some(job) = live.iter().find(|entry| entry.pid == pid) {
break *job;
}
}
assert!(Instant::now() < deadline, "tool job was not recorded");
thread::sleep(SAMPLE_INTERVAL);
};
assert_ne!(job.pgid, provider_pid);
let writer = exited_writer();
write_marker(&directory, writer);
let journal = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid));
fs::write(
&journal,
serde_json::to_vec(&state.journal_record(writer, newest_start())).unwrap(),
)
.unwrap();
let report = reap_journals(
&directory,
writer.pid,
Duration::from_millis(500),
Duration::from_secs(10),
);
let _ = provider.wait();
let job_alive = paperclip_process_table::read(job.pid)
.entry()
.is_some_and(|current| current.started == job.started && !current.zombie);
if job_alive {
if let Some(group) = rustix::process::Pid::from_raw(job.pgid) {
let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
}
}
assert!(!job_alive, "tool job {} outlived the reap", job.pid);
assert!(report.verified, "{report:?}");
assert_eq!(report.journals, 1);
assert!(report.signalled >= 2, "{report:?}");
assert!(!journal.exists(), "a proven journal is retired");
assert!(!directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid))
.exists());
let _ = fs::remove_dir_all(&directory);
}
/// The newest start time a table read lists now, as the sampler records.
fn newest_start() -> u64 {
read_process_table()
.unwrap()
.entries()
.iter()
.map(|entry| entry.started)
.max()
.unwrap()
}
/// A tool forked and left its session after the dead runnerd's last
/// read, and its parents are gone: nothing recorded leads to it. The reap
/// must not claim proof, and must not signal a process it cannot
/// attribute.
#[test]
fn reaping_refuses_an_orphan_born_after_the_last_sample() {
let orphans = super::super::host_orphans::may_orphan();
let directory = temporary_directory("escape");
let writer = exited_writer();
write_marker(&directory, writer);
let provider = exited_writer();
let state = LineageState {
root: Some((provider.pid, provider.started)),
..LineageState::default()
};
let journal = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid));
fs::write(
&journal,
serde_json::to_vec(&state.journal_record(writer, newest_start())).unwrap(),
)
.unwrap();
// runnerd died right after the tool started, before any read saw it.
// The tool starts a new session, starts a job and exits, so the job
// is re-parented to init and leads neither its group nor its session.
let pid_file = directory.join("orphan.pid");
let status = std::process::Command::new("perl")
.args([
"-e",
"use POSIX (); exit 0 if fork(); POSIX::setsid() or die; exit 0 if fork(); sleep 1 while getppid() != 1; open(my $f, '>', \"$ARGV[0].tmp\") or die; print $f $$; close $f; rename(\"$ARGV[0].tmp\", $ARGV[0]) or die; open(STDIN, '<', '/dev/null'); open(STDOUT, '>', '/dev/null'); open(STDERR, '>', '/dev/null'); exec '/bin/sh', '-c', 'while :; do sleep 1; done'",
&pid_file.display().to_string(),
])
.status()
.unwrap();
assert!(status.success());
let deadline = Instant::now() + Duration::from_secs(10);
let orphan = loop {
if let Some(entry) = fs::read_to_string(&pid_file)
.ok()
.and_then(|text| text.trim().parse::<i32>().ok())
.and_then(|pid| paperclip_process_table::read(pid).entry())
.filter(|entry| entry.ppid == 1 && entry.pgid != entry.pid)
{
break entry;
}
assert!(Instant::now() < deadline, "orphan job did not start");
thread::sleep(Duration::from_millis(20));
};
let report = reap_journals(
&directory,
writer.pid,
Duration::ZERO,
Duration::from_secs(1),
);
let alive = ProcessIdentity {
pid: orphan.pid,
started: orphan.started,
}
.is_alive();
if let Some(group) = rustix::process::Pid::from_raw(orphan.pgid) {
let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
}
super::super::host_orphans::wait_until_group_gone(orphan.pgid);
drop(orphans);
let _ = fs::remove_dir_all(&directory);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert!(report.remaining.contains(&orphan.pid), "{report:?}");
assert!(alive, "an unattributed process is never signalled");
}
fn reap_torn_reads(
name: &str,
reads: Vec<FixedTable>,
settled: fn() -> FixedTable,
) -> (ReapReport, bool) {
reap_scripted_reads(name, reads.into_iter().map(Some).collect(), settled)
}
fn reap_scripted_reads(
name: &str,
reads: Vec<Option<FixedTable>>,
settled: fn() -> FixedTable,
) -> (ReapReport, bool) {
let directory = temporary_directory(name);
let writer = exited_writer();
write_marker(&directory, writer);
let provider = exited_writer();
let state = LineageState {
root: Some((provider.pid, provider.started)),
..LineageState::default()
};
let journal = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid));
fs::write(
&journal,
serde_json::to_vec(&state.journal_record(writer, 100)).unwrap(),
)
.unwrap();
let mut reads = std::collections::VecDeque::from(reads);
let report = reap_journals_from(
&directory,
writer.pid,
Duration::ZERO,
Duration::from_millis(200),
|| reads.pop_front().unwrap_or_else(|| Some(settled())),
|_| true,
);
let journal_kept = journal.exists();
let _ = fs::remove_dir_all(&directory);
(report, journal_kept)
}
const TORN_ORPHAN: i32 = 900_001;
const TORN_CHILD: i32 = 900_002;
const TORN_GRANDCHILD: i32 = 900_003;
const FOREIGN_PARENT: i32 = 900_010;
#[test]
fn reaping_counts_a_process_whose_parent_exited_during_the_first_read() {
let (report, journal_kept) = reap_torn_reads("torn-first-read", Vec::new(), || {
table(vec![(
entry(TORN_CHILD, TORN_ORPHAN, TORN_CHILD, 300),
TORN_CHILD,
)])
});
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert_eq!(report.remaining, vec![TORN_CHILD], "{report:?}");
assert_eq!(report.signalled, 0, "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_restarts_its_clean_reads_after_an_unreadable_table() {
let (report, journal_kept) = reap_scripted_reads(
"unreadable-between-clean-reads",
vec![Some(table(Vec::new())), None, Some(table(Vec::new()))],
|| table(vec![(entry(TORN_ORPHAN, 1, TORN_ORPHAN, 200), TORN_ORPHAN)]),
);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert_eq!(report.remaining, vec![TORN_ORPHAN], "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_needs_consecutive_clean_reads_before_a_proof() {
let (report, journal_kept) = reap_torn_reads("clean-reads", vec![table(Vec::new())], || {
table(vec![(entry(TORN_ORPHAN, 1, TORN_ORPHAN, 200), TORN_ORPHAN)])
});
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert_eq!(report.remaining, vec![TORN_ORPHAN], "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_keeps_a_process_in_an_orphans_group_or_session_after_the_orphan_exits() {
let (report, journal_kept) = reap_torn_reads(
"orphan-group",
vec![table(vec![
(entry(TORN_ORPHAN, 1, TORN_ORPHAN, 200), TORN_ORPHAN),
(entry(FOREIGN_PARENT, 1, FOREIGN_PARENT, 50), FOREIGN_PARENT),
(
entry(TORN_CHILD, FOREIGN_PARENT, TORN_ORPHAN, 300),
TORN_ORPHAN,
),
])],
|| {
table(vec![
(entry(FOREIGN_PARENT, 1, FOREIGN_PARENT, 50), FOREIGN_PARENT),
(
entry(TORN_CHILD, FOREIGN_PARENT, TORN_ORPHAN, 300),
TORN_ORPHAN,
),
])
},
);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert_eq!(report.remaining, vec![TORN_CHILD], "{report:?}");
assert_eq!(report.signalled, 0, "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_keeps_an_orphans_descendants_across_reads() {
let (report, journal_kept) = reap_torn_reads(
"orphan-tree",
vec![table(vec![
(entry(TORN_ORPHAN, 1, TORN_ORPHAN, 200), TORN_ORPHAN),
(
entry(TORN_CHILD, TORN_ORPHAN, TORN_ORPHAN, 300),
TORN_ORPHAN,
),
])],
|| {
super::super::tests::table_with_unreadable(
vec![(
entry(TORN_CHILD, TORN_ORPHAN, TORN_ORPHAN, 300),
TORN_ORPHAN,
)],
vec![TORN_ORPHAN],
)
},
);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert_eq!(
report.remaining,
vec![TORN_ORPHAN, TORN_CHILD],
"{report:?}"
);
assert_eq!(report.signalled, 0, "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_follows_an_orphan_tree_through_successive_torn_reads() {
let (report, journal_kept) = reap_torn_reads(
"torn-chain",
vec![
table(vec![
(entry(TORN_ORPHAN, 1, TORN_ORPHAN, 200), TORN_ORPHAN),
(
entry(TORN_CHILD, TORN_ORPHAN, TORN_ORPHAN, 300),
TORN_ORPHAN,
),
]),
table(vec![(
entry(TORN_CHILD, TORN_ORPHAN, TORN_ORPHAN, 300),
TORN_ORPHAN,
)]),
table(vec![(
entry(TORN_GRANDCHILD, TORN_CHILD, TORN_ORPHAN, 400),
TORN_ORPHAN,
)]),
],
|| {
table(vec![(
entry(TORN_GRANDCHILD, 1, TORN_ORPHAN, 400),
TORN_ORPHAN,
)])
},
);
assert_eq!(report.reason, Some("unattributed_orphan"), "{report:?}");
assert!(!report.verified);
assert_eq!(report.remaining, vec![TORN_GRANDCHILD], "{report:?}");
assert_eq!(report.signalled, 0, "{report:?}");
assert!(journal_kept, "a refused proof keeps the journal");
}
#[test]
fn reaping_waits_out_a_short_lived_orphan_it_cannot_attribute() {
let _no_foreign_orphans = super::super::host_orphans::no_foreign_orphans();
let directory = temporary_directory("short-orphan");
let writer = exited_writer();
write_marker(&directory, writer);
let provider = exited_writer();
let state = LineageState {
root: Some((provider.pid, provider.started)),
..LineageState::default()
};
fs::write(
directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("lineage-{}-0.json", writer.pid)),
serde_json::to_vec(&state.journal_record(writer, newest_start())).unwrap(),
)
.unwrap();
let pid_file = directory.join("orphan.pid");
let status = std::process::Command::new("perl")
.args([
"-e",
"use POSIX (); exit 0 if fork(); POSIX::setsid() or die; exit 0 if fork(); select(undef, undef, undef, 0.01) while getppid() != 1; open(STDIN, '<', '/dev/null'); open(STDOUT, '>', '/dev/null'); open(STDERR, '>', '/dev/null'); open(my $f, '>', \"$ARGV[0].tmp\") or die; print $f $$; close $f; rename(\"$ARGV[0].tmp\", $ARGV[0]) or die; select(undef, undef, undef, 0.5); exit 0",
&pid_file.display().to_string(),
])
.status()
.unwrap();
assert!(status.success());
let deadline = Instant::now() + Duration::from_secs(10);
let orphan = loop {
if let Some(entry) = fs::read_to_string(&pid_file)
.ok()
.and_then(|text| text.trim().parse::<i32>().ok())
.and_then(|pid| paperclip_process_table::read(pid).entry())
.filter(|entry| entry.ppid == 1 && !entry.zombie)
{
break entry;
}
assert!(Instant::now() < deadline, "orphan job did not start");
thread::sleep(Duration::from_millis(5));
};
let report = reap_journals(
&directory,
writer.pid,
Duration::ZERO,
Duration::from_secs(5),
);
let alive = ProcessIdentity {
pid: orphan.pid,
started: orphan.started,
}
.is_alive();
if alive {
if let Some(group) = rustix::process::Pid::from_raw(orphan.pgid) {
let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
}
super::super::host_orphans::wait_until_group_gone(orphan.pgid);
}
let _ = fs::remove_dir_all(&directory);
assert!(report.verified, "{report:?}");
assert_eq!(report.signalled, 0, "{report:?}");
assert!(!alive, "the reap returned while the orphan lived");
}
/// A record that could not be written may be missing a member. The
/// failure withdraws the writer marker, so no reap can verify.
#[test]
fn a_failed_journal_write_withdraws_the_writer_marker() {
let directory = temporary_directory("write-failure");
let writer = exited_writer();
write_marker(&directory, writer);
let marker = directory
.join(JOURNAL_DIRECTORY_NAME)
.join(format!("writer-{}.json", writer.pid));
let journal = Journal {
path: directory.join("missing").join("lineage.json"),
marker: marker.clone(),
writer,
last: Mutex::new(JournalWrite::default()),
};
assert!(journal.write(&LineageState::new(100), 1).is_err());
assert!(!marker.exists());
let report = reap_journals(&directory, writer.pid, Duration::ZERO, Duration::ZERO);
assert_eq!(report.reason, Some("journal_unavailable"));
let _ = fs::remove_dir_all(&directory);
}
#[test]
fn an_unchanged_record_is_rewritten_only_to_advance_sampled_through() {
let directory = temporary_directory("refresh");
let path = directory.join(JOURNAL_DIRECTORY_NAME).join("lineage.json");
let journal = Journal {
path: path.clone(),
marker: directory.join("marker"),
writer: ProcessIdentity {
pid: 10,
started: 5,
},
last: Mutex::new(JournalWrite::default()),
};
let state = LineageState::new(100);
let read = || {
serde_json::from_slice::<JournalRecord>(&fs::read(&path).unwrap())
.unwrap()
.sampled_through
};
journal.write(&state, 7).unwrap();
assert_eq!(read(), 7);
// Within the refresh interval an advance alone is not written.
journal.write(&state, 9).unwrap();
assert_eq!(read(), 7);
journal.last.lock().unwrap().at = Some(Instant::now() - SAMPLED_THROUGH_REFRESH);
journal.write(&state, 9).unwrap();
assert_eq!(read(), 9);
let _ = fs::remove_dir_all(&directory);
}
@@ -5672,11 +5672,12 @@ function processAlive(pid: number | null | undefined): boolean {
}
it.each([
{ journal: true },
{ journal: true, foreignOrphan: false },
{ journal: true, foreignOrphan: true },
// A runnerd that never journalled (an older build) proves nothing: the
// cleanup stays fail-closed, as before the journal existed.
{ journal: false },
])("stops a lost runnerd's provider and escaped tool job from its lineage journal (journal=$journal)", async ({ journal }) => {
{ journal: false, foreignOrphan: false },
])("stops a lost runnerd's provider and escaped tool job from its lineage journal (journal=$journal, foreignOrphan=$foreignOrphan)", async ({ journal, foreignOrphan }) => {
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-exit-stream-"));
const jobPidFile = join(stateDirectory, "escaped-tool-job.pid");
const diagnostics: string[] = [];
@@ -5694,6 +5695,7 @@ it.each([
}));
let jobPid: number | null = null;
let providerPid: number | null = null;
let orphanPid: number | null = null;
try {
await bundle.transport.request("initialize", {});
await bundle.transport.request("thread/start", {
@@ -5749,12 +5751,22 @@ it.each([
// The fake provider exits when runnerd's stdin pipe closes; the tool job
// that left its session is re-parented and keeps running.
expect(processAlive(jobPid)).toBe(true);
if (foreignOrphan) {
orphanPid = Number(execFileSync(process.execPath, ["-e", [
"const { spawn } = require('node:child_process');",
"const orphan = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 1500)'], { detached: true, stdio: 'ignore' });",
"orphan.unref();",
"process.stdout.write(String(orphan.pid));",
].join("\n")], { encoding: "utf8" }).trim());
expect(processAlive(orphanPid)).toBe(true);
}
const runnerState = () => readFile(join(stateDirectory, "runner", "runner-state.json"), "utf8")
.then((text) => JSON.parse(text));
if (journal) {
await bundle.transport.close();
expect(processAlive(providerPid)).toBe(false);
expect(processAlive(jobPid)).toBe(false);
if (foreignOrphan) expect(processAlive(orphanPid)).toBe(false);
const report = diagnostics.find((message) => message.startsWith("native_session_runner_loss_lineage "));
expect(JSON.parse(report!.slice("native_session_runner_loss_lineage ".length))).toMatchObject({
verified: true, journals: 1, remaining: [],
@@ -5783,7 +5795,7 @@ it.each([
expect(processAlive(jobPid)).toBe(true);
}
} finally {
for (const pid of [jobPid, providerPid]) {
for (const pid of [jobPid, providerPid, orphanPid]) {
if (pid && processAlive(pid)) try { process.kill(pid, "SIGKILL"); } catch { /* gone */ }
}
await rm(stateDirectory, { recursive: true, force: true });