Skip to content

Commit 6b37edc

Browse files
HoTT-stuffclaude
andcommitted
fix(glob, process_sub): structured refusal at start; keep a background job's FIFOs
CodeRabbit review on 8b7ff4f: - expand_glob_continuing returned a raw grade::Exceeded when a resumed usage was over a limit. word.rs passes on only GlobLimitExceeded, so the refusal was taken as "no match" and the literal word was used. Walker::new now returns GlobLimitExceeded (usage as given, at "."), still before any read. - A background job gets its process substitutions handed to a detached thread that waits for each one without releasing it, then removes the FIFO. The release from 9de7856 could end the writer or remove the FIFO before the job opened it. When no job starts, the normal cleanup runs. - A SIGPIPE end reported by sh as exit code 141 now counts as normal too. Tests: the glob refusal test asserts the structured error; a late reader gets a handed-off substitution's output (fails with the release); the SIGPIPE rule covers the sh exit code. cargo test 921 passed, 0 failed, 14 ignored; fmt, clippy -D warnings and the fuzz check pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0136P7Zk179dJt4BhyPzDhFN
1 parent 8b7ff4f commit 6b37edc

4 files changed

Lines changed: 116 additions & 21 deletions

File tree

‎impl/rust-cli/src/executable.rs‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -515,18 +515,21 @@ impl ExecutableCommand for Command {
515515
// Execute main command
516516
if *background {
517517
// Background execution
518-
let _job_id = external::execute_external_background(
518+
match external::execute_external_background(
519519
&expanded_program,
520520
expanded_args,
521521
redirects,
522522
state,
523-
)
524-
.unwrap_or_else(|e| {
525-
eprintln!("{}: {}", expanded_program, e);
526-
0 // No job created
527-
});
528-
529-
expansion.cleanup();
523+
) {
524+
// The job may open a FIFO later: do not release or
525+
// remove one that it has not read yet.
526+
Ok(_job_id) => expansion.cleanup_when_consumed(),
527+
// No job: nothing will open the FIFOs.
528+
Err(e) => {
529+
eprintln!("{}: {}", expanded_program, e);
530+
expansion.cleanup();
531+
}
532+
}
530533

531534
Ok(ExecutionResult::Success)
532535
} else {

‎impl/rust-cli/src/glob.rs‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,8 @@ pub fn expand_glob_continuing(
308308
) -> Result<Expansion> {
309309
let compiled =
310310
Compiled::new(pattern).with_context(|| format!("Invalid glob pattern: {}", pattern))?;
311-
let mut walker = Walker::new(pattern, base_dir, &compiled, limits, spent)?;
311+
let mut walker = Walker::new(pattern, base_dir, &compiled, limits, spent)
312+
.map_err(|stopped| anyhow::Error::new(*stopped))?;
312313
walker
313314
.run()
314315
.map_err(|stopped| anyhow::Error::new(*stopped))?;
@@ -427,20 +428,33 @@ impl<'a> Walker<'a> {
427428
compiled: &'a Compiled,
428429
limits: &GlobLimits,
429430
spent: GlobUsage,
430-
) -> Result<Self, crate::grade::Exceeded> {
431+
) -> Walk<Self> {
431432
// A usage already over a limit (a hand-built `GlobUsage`, for example)
432-
// is refused here, so every meter starts within its limit.
433+
// is refused here, before any read, so every meter starts within its
434+
// limit. The refusal is the same structured error as a limit met on
435+
// the walk, stopped at the base directory with the usage given.
436+
let refuse = |exceeded| {
437+
Box::new(GlobLimitExceeded {
438+
pattern: pattern.to_string(),
439+
exceeded,
440+
usage: spent,
441+
at: PathBuf::from("."),
442+
})
443+
};
433444
Ok(Walker {
434445
pattern,
435446
base,
436447
compiled,
437-
reads: Meter::starting_at("file-system reads", limits.max_reads, spent.reads)?,
438-
matches: Meter::starting_at("matches held", limits.max_matches, spent.matches)?,
448+
reads: Meter::starting_at("file-system reads", limits.max_reads, spent.reads)
449+
.map_err(refuse)?,
450+
matches: Meter::starting_at("matches held", limits.max_matches, spent.matches)
451+
.map_err(refuse)?,
439452
match_bytes: Meter::starting_at(
440453
"bytes of matches held",
441454
limits.max_match_bytes,
442455
spent.match_bytes,
443-
)?,
456+
)
457+
.map_err(refuse)?,
444458
max_listing_bytes: limits.max_listing_bytes,
445459
found: BTreeSet::new(),
446460
})
@@ -700,8 +714,21 @@ mod walk_tests {
700714
..GlobUsage::default()
701715
};
702716
let err = expand_glob_continuing("*", t.path(), &limits, spent).unwrap_err();
703-
let refused = err.downcast_ref::<Exceeded>().expect("an Exceeded refusal");
704-
assert_eq!((refused.limit, refused.level), (2, 5));
717+
// The structured glob error, so a caller that passes on only
718+
// `GlobLimitExceeded` does not take the refusal for "no match".
719+
let stopped = err
720+
.downcast_ref::<GlobLimitExceeded>()
721+
.expect("a GlobLimitExceeded refusal");
722+
assert_eq!(
723+
stopped.exceeded,
724+
Exceeded {
725+
axis: "file-system reads",
726+
limit: 2,
727+
level: 5
728+
}
729+
);
730+
assert_eq!(stopped.usage, spent);
731+
assert_eq!(stopped.at, PathBuf::from("."));
705732
}
706733

707734
#[test]

‎impl/rust-cli/src/process_sub.rs‎

Lines changed: 49 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,26 @@ impl ProcessSubstitution {
119119
/// its reader leave, and a `>(cmd)` reader sees end of file. A connected
120120
/// child is not cut short: the shell keeps waiting until it exits, so a
121121
/// `>(cmd)` reader still finishes the work it was given.
122-
pub fn cleanup(mut self) -> Result<()> {
123-
// Wait for background process to finish
122+
pub fn cleanup(self) -> Result<()> {
123+
self.finish(true)
124+
}
125+
126+
/// Wait for the substitution to end, then remove its FIFO, without
127+
/// releasing the child. For a background job, which may open the FIFO at
128+
/// any later time: a release could end the child or remove the FIFO first.
129+
pub fn cleanup_when_consumed(self) -> Result<()> {
130+
self.finish(false)
131+
}
132+
133+
fn finish(mut self, release: bool) -> Result<()> {
124134
if let Some(mut child) = self.child_process.take() {
125135
let status = loop {
126136
if let Some(status) = child.try_wait()? {
127137
break status;
128138
}
129-
self.release_waiting_child();
139+
if release {
140+
self.release_waiting_child();
141+
}
130142
std::thread::sleep(std::time::Duration::from_millis(10));
131143
};
132144
// A `<(cmd)` writer whose reader has gone ends on SIGPIPE. That is
@@ -173,11 +185,12 @@ impl ProcessSubstitution {
173185
fn release_waiting_child(&self) {}
174186
}
175187

176-
/// True when the process ended on SIGPIPE.
188+
/// True when the process ended on SIGPIPE, either itself or (through `sh`)
189+
/// as exit code 128 + SIGPIPE.
177190
#[cfg(unix)]
178191
fn ended_by_sigpipe(status: &std::process::ExitStatus) -> bool {
179192
use std::os::unix::process::ExitStatusExt;
180-
status.signal() == Some(libc::SIGPIPE)
193+
status.signal() == Some(libc::SIGPIPE) || status.code() == Some(128 + libc::SIGPIPE)
181194
}
182195

183196
#[cfg(not(unix))]
@@ -426,6 +439,37 @@ mod tests {
426439
assert!(finishes_within(10, move || sub.cleanup().unwrap()));
427440
}
428441

442+
#[cfg(unix)]
443+
#[test]
444+
fn a_sigpipe_end_counts_as_normal_also_through_sh() {
445+
// The substitution runs through `sh`, which reports a child killed by
446+
// SIGPIPE as exit code 128 + SIGPIPE, not as a signal.
447+
use std::os::unix::process::ExitStatusExt;
448+
use std::process::ExitStatus;
449+
assert!(ended_by_sigpipe(&ExitStatus::from_raw(libc::SIGPIPE)));
450+
assert!(ended_by_sigpipe(&ExitStatus::from_raw(
451+
(128 + libc::SIGPIPE) << 8
452+
)));
453+
assert!(!ended_by_sigpipe(&ExitStatus::from_raw(1 << 8)));
454+
}
455+
456+
#[test]
457+
fn a_handed_off_input_substitution_waits_for_a_late_reader() {
458+
// `cat <(cat FILE) &`: the shell hands the substitution off before the
459+
// background job opens the FIFO. The writer must not be released and
460+
// the FIFO must still exist when the job opens it.
461+
let src = TempDir::new().unwrap();
462+
let file = src.path().join("in.txt");
463+
std::fs::write(&file, "hi\n").unwrap();
464+
let (_dir, sub) = started(ProcessSubType::Input, &format!("cat {}", file.display()));
465+
let path = sub.fifo_path.clone();
466+
let handed_off = std::thread::spawn(move || sub.cleanup_when_consumed().unwrap());
467+
std::thread::sleep(std::time::Duration::from_millis(200));
468+
assert_eq!(std::fs::read_to_string(&path).unwrap(), "hi\n");
469+
assert!(finishes_within(10, move || handed_off.join().unwrap()));
470+
assert!(!path.exists());
471+
}
472+
429473
#[test]
430474
fn a_connected_output_substitution_finishes_its_work_before_cleanup_returns() {
431475
// `echo data > >(tee FILE)`: cleanup waits until tee has written FILE.

‎impl/rust-cli/src/word.rs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,27 @@ impl Expansion {
285285
}
286286
}
287287
}
288+
289+
/// Hand the process substitutions of a background job to a detached
290+
/// thread, which waits for each one to end and then removes its FIFO.
291+
/// The job may open a FIFO at any later time, so nothing is released and
292+
/// the shell does not wait.
293+
// snip: a substitution that the job never opens stays blocked until the
294+
// shell exits, and a FIFO is left in the temp directory when the shell
295+
// exits first (`vsh -c 'cmd <(x) &'`). Release and remove them once the
296+
// job table reaps background jobs.
297+
pub fn cleanup_when_consumed(self) {
298+
if self.process_subs.is_empty() {
299+
return;
300+
}
301+
std::thread::spawn(move || {
302+
for proc_sub in self.process_subs {
303+
if let Err(e) = proc_sub.cleanup_when_consumed() {
304+
eprintln!("Warning: Failed to cleanup process substitution: {}", e);
305+
}
306+
}
307+
});
308+
}
288309
}
289310

290311
/// Expand words relative to the current directory under the default limits.

0 commit comments

Comments
 (0)