Skip to content

Commit 59be27f

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
fix(desktop): check PGID in orphan sweep and signal correct process groups (#1359)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent c65989a commit 59be27f

3 files changed

Lines changed: 206 additions & 8 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ const overrides = new Map([
7272
// path here. Load-bearing feature growth; queued to split in the resolver
7373
// unify refactor followup. +26 for resolve_effective_prompt_model_provider
7474
// re-introduced after 826d735fe removal (config-bridge caller still needs it).
75-
["src-tauri/src/managed_agents/runtime.rs", 2036],
75+
// PGID resolution helper + PID-recycling safety guard added for orphan sweep.
76+
["src-tauri/src/managed_agents/runtime.rs", 2150],
7677
// Phase-2 inbound reconcile + review-fix cycle: reconcile_inbound_persona_event
7778
// dispatches 30175/30176/30177 inbound plus kind:5 tombstone consume
7879
// (reconcile_inbound_tombstone), the two apply_inbound_* fns, the

‎desktop/src-tauri/src/managed_agents/runtime.rs‎

Lines changed: 110 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -355,9 +355,71 @@ fn sigterm_then_sigkill(pids: &[i32]) {
355355
}
356356
}
357357

358+
/// Resolve orphan candidate PIDs to their actual process group IDs, dedupe,
359+
/// and signal the groups. An orphaned grandchild (e.g. `goose` or `buzz-dev-mcp`)
360+
/// whose harness has exited retains the harness's PGID — signaling that PGID
361+
/// kills the entire orphaned subtree. Falls back to the candidate PID itself
362+
/// when PGID resolution fails (process may have exited between detection and
363+
/// kill).
364+
#[cfg(target_os = "macos")]
365+
fn resolve_pgids_and_kill(candidate_pids: &[i32]) {
366+
let candidate_set: std::collections::HashSet<i32> = candidate_pids.iter().copied().collect();
367+
let mut pgids = std::collections::HashSet::new();
368+
for &pid in candidate_pids {
369+
let pgid = unsafe { libc::getpgid(pid) };
370+
if pgid > 0 {
371+
pgids.insert(pgid);
372+
} else {
373+
// Process may have exited; try signaling it directly as a group.
374+
pgids.insert(pid);
375+
}
376+
}
377+
// PID-recycling guard: if a resolved PGID is alive but isn't one of our
378+
// orphan candidates, the old harness PID was recycled by a new process
379+
// that called setsid() — skip it to avoid killing an unrelated group.
380+
pgids.retain(|&pgid| {
381+
if candidate_set.contains(&pgid) {
382+
return true;
383+
}
384+
let alive = unsafe { libc::kill(pgid, 0) } == 0;
385+
!alive
386+
});
387+
let unique: Vec<i32> = pgids.into_iter().collect();
388+
sigterm_then_sigkill(&unique);
389+
}
390+
391+
/// Resolve orphan candidate PIDs to their actual process group IDs, dedupe,
392+
/// and signal the groups. Linux variant reads PGID from /proc/<pid>/stat.
393+
#[cfg(all(unix, not(target_os = "macos")))]
394+
fn resolve_pgids_and_kill(candidate_pids: &[i32]) {
395+
let candidate_set: std::collections::HashSet<i32> = candidate_pids.iter().copied().collect();
396+
let mut pgids = std::collections::HashSet::new();
397+
for &pid in candidate_pids {
398+
if let Some(pgid) = read_pgid_linux(pid as u32) {
399+
pgids.insert(pgid as i32);
400+
} else {
401+
// Process may have exited; try signaling it directly as a group.
402+
pgids.insert(pid);
403+
}
404+
}
405+
// PID-recycling guard: if a resolved PGID is alive but isn't one of our
406+
// orphan candidates, the old harness PID was recycled by a new process
407+
// that called setsid() — skip it to avoid killing an unrelated group.
408+
pgids.retain(|&pgid| {
409+
if candidate_set.contains(&pgid) {
410+
return true;
411+
}
412+
let alive = unsafe { libc::kill(pgid, 0) } == 0;
413+
!alive
414+
});
415+
let unique: Vec<i32> = pgids.into_iter().collect();
416+
sigterm_then_sigkill(&unique);
417+
}
418+
358419
/// Kill orphaned agent processes using PID file receipts. Reads all files from
359420
/// `agent-pids/`, verifies each PID still belongs to a known agent binary,
360-
/// then kills the process group. Deletes the PID file after killing.
421+
/// then resolves each candidate's actual PGID and signals the process group.
422+
/// Deletes the PID file after killing.
361423
///
362424
/// `skip_pids` are PIDs already handled by the tracked-agent path.
363425
#[cfg(unix)]
@@ -379,7 +441,7 @@ pub(crate) fn sweep_orphaned_agent_processes(app: &AppHandle, skip_pids: &[u32])
379441
.collect();
380442

381443
if !targets.is_empty() {
382-
sigterm_then_sigkill(&targets);
444+
resolve_pgids_and_kill(&targets);
383445
}
384446

385447
// Clean up PID files for processes we just killed or that are already gone.
@@ -503,6 +565,13 @@ pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32])
503565
if skip_pids.contains(&info.pbi_ppid) {
504566
continue;
505567
}
568+
// Grandchild check: the harness is spawned with process_group(0), so
569+
// all descendants share its PGID. If this process's PGID matches a
570+
// tracked harness PID, it's a live descendant — not an orphan.
571+
let pgid = unsafe { libc::getpgid(pid) };
572+
if pgid > 0 && skip_pids.contains(&(pgid as u32)) {
573+
continue;
574+
}
506575
if !process_has_buzz_marker(upid, instance_id) {
507576
continue;
508577
}
@@ -514,7 +583,7 @@ pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32])
514583
"buzz-desktop: system sweep found {} orphaned agent process(es), cleaning up",
515584
orphans.len()
516585
);
517-
sigterm_then_sigkill(&orphans);
586+
resolve_pgids_and_kill(&orphans);
518587
}
519588
}
520589

@@ -530,6 +599,17 @@ fn read_ppid_linux(pid: u32) -> Option<u32> {
530599
ppid_str.parse::<u32>().ok()
531600
}
532601

602+
/// Read the process group ID from /proc/<pid>/stat. Same parsing strategy as
603+
/// `read_ppid_linux` — field 3 after the closing ')' is the PGID.
604+
#[cfg(all(unix, not(target_os = "macos")))]
605+
fn read_pgid_linux(pid: u32) -> Option<u32> {
606+
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
607+
let after_comm = stat.rsplit_once(')')?.1;
608+
// Fields after ')': " S ppid pgid ..."
609+
let pgid_str = after_comm.split_whitespace().nth(2)?;
610+
pgid_str.parse::<u32>().ok()
611+
}
612+
533613
#[cfg(all(unix, not(target_os = "macos")))]
534614
pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32]) {
535615
let my_uid = unsafe { libc::getuid() };
@@ -575,6 +655,14 @@ pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32])
575655
continue;
576656
}
577657
}
658+
// Grandchild check: the harness is spawned with process_group(0), so
659+
// all descendants share its PGID. If this process's PGID matches a
660+
// tracked harness PID, it's a live descendant — not an orphan.
661+
if let Some(pgid) = read_pgid_linux(upid) {
662+
if skip_pids.contains(&pgid) {
663+
continue;
664+
}
665+
}
578666
orphans.push(pid);
579667
}
580668

@@ -583,7 +671,7 @@ pub(crate) fn sweep_system_agent_processes(instance_id: &str, skip_pids: &[u32])
583671
"buzz-desktop: system sweep found {} orphaned agent process(es), cleaning up",
584672
orphans.len()
585673
);
586-
sigterm_then_sigkill(&orphans);
674+
resolve_pgids_and_kill(&orphans);
587675
}
588676
}
589677

@@ -613,7 +701,7 @@ pub(crate) fn sweep_system_agent_processes_with_grace(
613701
"buzz-desktop: periodic sweep confirmed {} orphaned agent process(es), cleaning up",
614702
confirmed.len()
615703
);
616-
sigterm_then_sigkill(&confirmed);
704+
resolve_pgids_and_kill(&confirmed);
617705
}
618706
current
619707
}
@@ -694,6 +782,13 @@ pub(crate) fn collect_same_instance_orphans(
694782
if skip_pids.contains(&info.pbi_ppid) {
695783
continue;
696784
}
785+
// Grandchild check: the harness is spawned with process_group(0), so
786+
// all descendants share its PGID. If this process's PGID matches a
787+
// tracked harness PID, it's a live descendant — not an orphan.
788+
let pgid = unsafe { libc::getpgid(pid) };
789+
if pgid > 0 && skip_pids.contains(&(pgid as u32)) {
790+
continue;
791+
}
697792
if process_has_buzz_marker(upid, instance_id) {
698793
orphans.insert(upid);
699794
}
@@ -747,6 +842,14 @@ pub(crate) fn collect_same_instance_orphans(
747842
continue;
748843
}
749844
}
845+
// Grandchild check: the harness is spawned with process_group(0), so
846+
// all descendants share its PGID. If this process's PGID matches a
847+
// tracked harness PID, it's a live descendant — not an orphan.
848+
if let Some(pgid) = read_pgid_linux(upid) {
849+
if skip_pids.contains(&pgid) {
850+
continue;
851+
}
852+
}
750853
orphans.insert(upid);
751854
}
752855
orphans
@@ -1141,7 +1244,7 @@ pub(crate) fn reap_dead_instance_agents(our_instance_id: &str, skip_pids: &[u32]
11411244
"buzz-desktop: reaping {} orphaned agent(s) from dead instance '{instance_id}'",
11421245
agent_pids.len()
11431246
);
1144-
sigterm_then_sigkill(agent_pids);
1247+
resolve_pgids_and_kill(agent_pids);
11451248
}
11461249
}
11471250

@@ -1199,7 +1302,7 @@ pub(crate) fn reap_dead_instance_agents(our_instance_id: &str, skip_pids: &[u32]
11991302
"buzz-desktop: reaping {} orphaned agent(s) from dead instance '{instance_id}'",
12001303
agent_pids.len()
12011304
);
1202-
sigterm_then_sigkill(agent_pids);
1305+
resolve_pgids_and_kill(agent_pids);
12031306
}
12041307
}
12051308

‎desktop/src-tauri/src/managed_agents/runtime/tests.rs‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,3 +512,97 @@ fn name_matches_interpreter_rejects_node_prefix() {
512512
assert!(!super::name_matches_interpreter("nodejs"));
513513
assert!(!super::name_matches_interpreter("node-gyp"));
514514
}
515+
516+
// ── PGID-based orphan sweep tests ───────────────────────────────────────
517+
518+
/// Validates the kernel invariant that the orphan sweep PGID fix relies on:
519+
/// a grandchild process inherits the PGID of the process group leader (the
520+
/// harness), so checking PGID membership in `skip_pids` correctly identifies
521+
/// live descendants even when their ppid is an intermediate process (e.g.
522+
/// goose) rather than the harness itself.
523+
#[cfg(unix)]
524+
#[test]
525+
fn grandchild_inherits_pgid_of_process_group_leader() {
526+
use std::os::unix::process::CommandExt;
527+
use std::process::Command;
528+
529+
// Spawn a "harness" process in its own process group (mirrors
530+
// `command.process_group(0)` in the real spawn path). The harness
531+
// spawns an intermediate child which in turn spawns a grandchild.
532+
// This mirrors the real tree: buzz-acp → goose → buzz-dev-mcp.
533+
//
534+
// The intermediate `sh` uses exec to replace itself with another sh
535+
// that backgrounds the grandchild, so the grandchild's ppid is the
536+
// intermediate (not the harness).
537+
let mut harness = {
538+
let mut cmd = Command::new("sh");
539+
cmd.args(["-c", "sh -c 'sleep 10 & echo $!' & wait $!"])
540+
.stdout(std::process::Stdio::piped())
541+
.process_group(0);
542+
cmd.spawn().expect("spawn harness")
543+
};
544+
545+
// Read the grandchild PID from stdout.
546+
use std::io::BufRead;
547+
let stdout = harness.stdout.take().unwrap();
548+
let reader = std::io::BufReader::new(stdout);
549+
let grandchild_pid: i32 = reader
550+
.lines()
551+
.next()
552+
.expect("should get a line")
553+
.expect("should read line")
554+
.trim()
555+
.parse()
556+
.expect("should parse grandchild PID");
557+
558+
let harness_pid = harness.id() as i32;
559+
560+
// The harness is the process group leader (PGID == its own PID).
561+
let harness_pgid = unsafe { libc::getpgid(harness_pid) };
562+
assert_eq!(
563+
harness_pgid, harness_pid,
564+
"harness should be its own process group leader"
565+
);
566+
567+
// The grandchild's PGID should equal the harness PID — this is the
568+
// invariant our orphan sweep fix relies on.
569+
let grandchild_pgid = unsafe { libc::getpgid(grandchild_pid) };
570+
assert_eq!(
571+
grandchild_pgid, harness_pid,
572+
"grandchild PGID should match harness PID (process group leader)"
573+
);
574+
575+
// The grandchild's ppid is NOT the harness — it's the intermediate sh.
576+
// This proves the ppid-only check would miss it (the regression path).
577+
#[cfg(target_os = "macos")]
578+
{
579+
let mut info = std::mem::MaybeUninit::<super::BSDInfo>::zeroed();
580+
let ret = unsafe {
581+
super::proc_pidinfo(
582+
grandchild_pid,
583+
super::PROC_PIDTBSDINFO,
584+
0,
585+
info.as_mut_ptr() as *mut libc::c_void,
586+
std::mem::size_of::<super::BSDInfo>() as libc::c_int,
587+
)
588+
};
589+
assert!(ret > 0, "proc_pidinfo should succeed for grandchild");
590+
let info = unsafe { info.assume_init() };
591+
assert_ne!(
592+
info.pbi_ppid as i32, harness_pid,
593+
"grandchild ppid must NOT be the harness (it's the intermediate sh)"
594+
);
595+
}
596+
597+
// With skip_pids containing the harness PID, the grandchild's PGID
598+
// is in skip_pids — so it would NOT be flagged as an orphan.
599+
let skip_pids: Vec<u32> = vec![harness_pid as u32];
600+
assert!(
601+
skip_pids.contains(&(grandchild_pgid as u32)),
602+
"grandchild's PGID should be found in skip_pids"
603+
);
604+
605+
// Cleanup: kill the process group.
606+
unsafe { libc::kill(-harness_pid, libc::SIGTERM) };
607+
let _ = harness.wait();
608+
}

0 commit comments

Comments
 (0)