From dc13bbaa3fcdae39b150cfe9eb7e5557f4884b50 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 05:14:47 +0000 Subject: [PATCH 1/2] Keep a running shell's output across a daemon stop or kill A shell with an outputs folder that runs past its first second writes its streams to their files as it runs, at most a second behind and without a sync, as Pi keeps a running call's output; one that ends sooner never touches the disk, and a file that ends within a preview is removed. A clean stop ends running commands with their output as daemon_shutdown, and a background command a killed daemon lost answers at the next start with what its files kept. Within 1 MiB the kept bytes are handed to the writer once a second without a copy per read or a wait on the disk; writes are one writev per batch on blocking workers, with no buffer kept per file. bench.shell_streams measures it against main; results in docs/DAEMON_MEASUREMENTS.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013jkdGFB8684xSdg7nKsRqk --- bench/held/slow_sync.c | 31 ++ bench/shell_streams.py | 265 ++++++++++++ docs/DAEMON_MEASUREMENTS.md | 68 +++ docs/RUST_PROTOTYPE.md | 12 +- src/server/mod.rs | 15 + src/server/turn.rs | 110 ++++- src/store.rs | 13 +- src/store/db.rs | 73 +++- src/tools.rs | 796 ++++++++++++++++++++++++++++++------ tests/test_wait.py | 96 ++++- 10 files changed, 1332 insertions(+), 147 deletions(-) create mode 100644 bench/shell_streams.py diff --git a/bench/held/slow_sync.c b/bench/held/slow_sync.c index 78366917f..b899d3915 100644 --- a/bench/held/slow_sync.c +++ b/bench/held/slow_sync.c @@ -9,6 +9,10 @@ // does while the disk's journal is held by another's sync: opening a file // to write or create it, a rename, an unlink, a mkdir. Linux only. // +// With SLOW_FILE_WRITES=1, every write(2) or writev(2) to a regular file +// waits too, as a disk whose queue is full holds a writer; writes to pipes +// and sockets do not, nor SQLite's, which uses pwrite(2). +// // cc -O2 -shared -fPIC -o slow_sync.so slow_sync.c -ldl #define _GNU_SOURCE #include @@ -16,6 +20,8 @@ #include #include #include +#include +#include #include #include @@ -126,3 +132,28 @@ int mkdir(const char *path, mode_t mode) { if (writes()) wait_out(); return real(path, mode); } + +static int file_writes(void) { + static int on = -1; + if (on < 0) { + const char *set = getenv("SLOW_FILE_WRITES"); + on = set && atoi(set) == 1; + } + return on; +} + +ssize_t write(int fd, const void *buffer, size_t count) { + static ssize_t (*real)(int, const void *, size_t); + if (!real) real = (ssize_t (*)(int, const void *, size_t))dlsym(RTLD_NEXT, "write"); + struct stat found; + if (file_writes() && fstat(fd, &found) == 0 && S_ISREG(found.st_mode)) wait_out(); + return real(fd, buffer, count); +} + +ssize_t writev(int fd, const struct iovec *slices, int count) { + static ssize_t (*real)(int, const struct iovec *, int); + if (!real) real = (ssize_t (*)(int, const struct iovec *, int))dlsym(RTLD_NEXT, "writev"); + struct stat found; + if (file_writes() && fstat(fd, &found) == 0 && S_ISREG(found.st_mode)) wait_out(); + return real(fd, slices, count); +} diff --git a/bench/shell_streams.py b/bench/shell_streams.py new file mode 100644 index 000000000..75a7f6c3e --- /dev/null +++ b/bench/shell_streams.py @@ -0,0 +1,265 @@ +"""Shells under load, measured from outside the daemon: many concurrent +commands that write fast, slowly or barely at all, and storms of short +ones, beside a fleet of stored agents. Built to compare two daemons on the +same workloads (a change against main), each case on a fresh copy of one +seed store, the two alternated. + +Per case it reports the daemon's CPU (user+system), what it wrote (wchar) +and in how many writes (syscw), the files left in the agents' outputs +folders, its peak RSS and final PSS, the run loop's answer to a small +request sent every 10 ms while the case runs (p50, p99, max), and each +command's turn from submit to its end (p50, p99). Synthetic model, no +spend; needs release builds of both. + + python3 -m bench.shell_streams --agent A --agent B [--fleet 5000] \\ + [--cases storm,trickle300] [--runs 3] [--out result.json] + +`--shim` (bench/held/slow_sync.c, built as bench.held_reads says) runs +each case on a slow disk once its agents are made: every sync, change to +the file system and write to a file takes `--slow-ms`. +""" +import argparse +import json +import os +import queue +import shutil +import statistics +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from bench.runtime_client import serve_args # noqa: E402 +from bench.synthetic_model import start # noqa: E402 +from bench.targets import clean_env # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +LINES = 'for i in $(seq 30); do echo "line $i of a command that writes slowly"; sleep .1; done' +MEDIUM = 'for i in $(seq 30); do head -c 10240 /dev/zero | tr "\\0" m; sleep .1; done' +FLOOD = 'head -c 64000000 /dev/zero | tr "\\0" f' +# name: (how many agents, prompt, whether each runs turns back to back +# for the case's time, or one turn) +CASES = { + 'storm': (30, 'shell:echo hi', True), + 'storm_quiet': (30, 'shell:true', True), + 'short_bg': (30, 'bgwait:echo hi; sleep .3', True), + 'trickle30': (30, 'bgwait:' + LINES, False), + 'trickle300': (300, 'bgwait:' + LINES, False), + 'trickle1000': (1000, 'bgwait:' + LINES, False), + 'medium30': (30, 'bgwait:' + MEDIUM, False), + 'medium300': (300, 'bgwait:' + MEDIUM, False), + 'flood30': (30, 'bgwait:' + FLOOD, False), + 'flood100': (100, 'bgwait:' + FLOOD, False), +} + + +def proc(pid): + stat = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split() + ticks = os.sysconf('SC_CLK_TCK') + cpu = (int(stat[11]) + int(stat[12])) / ticks + io = dict(line.split(': ') for line in Path(f'/proc/{pid}/io').read_text().splitlines()) + status = dict(line.split(':', 1) for line in Path(f'/proc/{pid}/status').read_text().splitlines()) + return {'cpu_s': cpu, 'wchar': int(io['wchar']), 'syscw': int(io['syscw']), + 'hwm_kib': int(status['VmHWM'].split()[0]), 'threads': int(status['Threads'])} + + +def pss(pid): + for line in Path(f'/proc/{pid}/smaps_rollup').read_text().splitlines(): + if line.startswith('Pss:'): + return int(line.split()[1]) + + +def pct(values, p): + values = sorted(values) + return round(values[min(len(values) - 1, int(len(values) * p / 100))], 2) if values else None + + +class Daemon: + """A daemon over stdio, shared by threads: answers go to whoever asked, + by id, and turn ends to one queue.""" + + def __init__(self, binary, store, url, extra=(), env=None): + self.log = Path(store).with_suffix('.log') + with self.log.open('w') as log: + self.process = subprocess.Popen( + [str(binary), *serve_args(store, url, extra=extra)], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=log, text=True, + env={**clean_env(), **(env or {})}, start_new_session=True) + self.lock, self.answers, self.ids = threading.Lock(), {}, 0 + self.ends, self.ready = queue.Queue(), threading.Event() + threading.Thread(target=self.read, daemon=True).start() + if not self.ready.wait(30): + raise RuntimeError(f'no ready ({self.process.poll()}): {self.log.read_text()[-2000:]}') + + def read(self): + for line in self.process.stdout: + message = json.loads(line) + if message.get('event') == 'ready': + self.ready.set() + elif message.get('event') == 'turn_finished': + self.ends.put((time.monotonic(), message)) + elif 'id' in message and 'event' not in message: + waiter = self.answers.pop(message['id'], None) + if waiter: + waiter.put(message) + + def request(self, op, timeout=60, **params): + answer = queue.Queue() + with self.lock: + self.ids += 1 + self.answers[self.ids] = answer + self.process.stdin.write(json.dumps({'id': self.ids, 'op': op, **params}) + '\n') + self.process.stdin.flush() + return answer.get(timeout=timeout) + + def create(self, bot, workspace, settings=None): + params = {'bot': bot, 'workspace': str(workspace), 'model': 'openai/synthetic-model', + 'instructions': 'Test agent.', 'tools': ['echo', 'shell', 'wait']} + if settings: + params['settings'] = settings + answer = self.request('create', **params) + assert 'result' in answer, answer + + def close(self): + if self.process.poll() is None: + self.process.stdin.close() + try: + self.process.wait(timeout=30) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + + +def seed(binary, url, fleet, work): + """A store with `fleet` stored agents, made once and copied per run.""" + path = work / f'seed-{fleet}.sqlite' + if path.exists(): + return path + daemon = Daemon(binary, path, url) + for n in range(fleet): + daemon.create(f'stored.{n}', work) + daemon.close() + return path + + +def run(binary, url, fleet, case, seconds, work, shim=None, slow_ms=0): + count, prompt, loop = CASES[case] + folder = Path(tempfile.mkdtemp(dir=work)) + store = folder / 'state.sqlite' + shutil.copy(seed(binary, url, fleet, work), store) + outputs = folder / 'outputs' + # A slow disk once the agents are made: each sync, each change to the + # file system and each write to a file waits `slow_ms`. + slow = folder / 'slow' + env = shim and {'LD_PRELOAD': str(Path(shim).resolve()), 'SLOW_SYNC_FILE': str(slow), + 'SLOW_WRITES': '1', 'SLOW_FILE_WRITES': '1'} + daemon = Daemon(binary, store, url, extra=['--max-processes', '0'], env=env) + try: + settings = {'outputs': str(outputs), 'quiet_background': True} + for n in range(count): + daemon.create(f'busy.{n}', folder, settings) + if shim: + slow.write_text(str(slow_ms)) + pid = daemon.process.pid + held, stop = [], threading.Event() + + def probing(): + while not stop.is_set(): + began = time.perf_counter() + daemon.request('tools') + held.append((time.perf_counter() - began) * 1000) + time.sleep(.01) + prober = threading.Thread(target=probing, daemon=True) + before = proc(pid) + began = time.monotonic() + prober.start() + latencies, turns, peak_files = [], 0, 0 + started = {} + + def submit(n, round_): + answer = daemon.request('submit', bot=f'busy.{n}', request_id=f'{n}-{round_}', + prompt=prompt, delivery='reject') + started[answer['result']['message'], n] = (time.monotonic(), round_) + for n in range(count): + submit(n, 0) + deadline = began + seconds + while started: + at, event = daemon.ends.get(timeout=120) + n = int(event['bot'].split('.')[1]) + entry = started.pop((event['turn'], n), None) + if entry is None: + continue + submitted, round_ = entry + assert event['data']['status'] == 'completed', event + latencies.append((at - submitted) * 1000) + turns += 1 + if outputs.exists() and turns % 10 == 0: + peak_files = max(peak_files, sum(1 for _ in outputs.iterdir())) + if loop and time.monotonic() < deadline: + submit(n, round_ + 1) + took = time.monotonic() - began + stop.set() + prober.join() + after = proc(pid) + slow.unlink(missing_ok=True) + files = sum(1 for _ in outputs.iterdir()) if outputs.exists() else 0 + return { + 'turns': turns, 'seconds': round(took, 2), 'turns_per_s': round(turns / took, 1), + 'cpu_ms': round((after['cpu_s'] - before['cpu_s']) * 1000), + 'cpu_ms_per_turn': round((after['cpu_s'] - before['cpu_s']) * 1000 / max(turns, 1), 3), + 'wchar_mib': round((after['wchar'] - before['wchar']) / 2 ** 20, 2), + 'writes': after['syscw'] - before['syscw'], + 'files_left': files, 'files_peak': peak_files, + 'hwm_mib': round(after['hwm_kib'] / 1024, 1), 'pss_mib': round(pss(pid) / 1024, 1), + 'threads': after['threads'], + 'probe_p50_ms': pct(held, 50), 'probe_p99_ms': pct(held, 99), + 'probe_max_ms': round(max(held), 2) if held else None, + 'turn_p50_ms': pct(latencies, 50), 'turn_p99_ms': pct(latencies, 99), + } + finally: + daemon.close() + shutil.rmtree(folder, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--agent', action='append', required=True, help='daemon binary; give two to compare') + parser.add_argument('--fleet', type=int, default=5000) + parser.add_argument('--cases', default=','.join(CASES)) + parser.add_argument('--runs', type=int, default=3) + parser.add_argument('--seconds', type=float, default=8) + parser.add_argument('--shim', help='bench/held/slow_sync.c built as a shared object') + parser.add_argument('--slow-ms', type=int, default=200) + parser.add_argument('--out') + args = parser.parse_args() + (ROOT / '.local').mkdir(exist_ok=True) + work = Path(tempfile.mkdtemp(dir=ROOT / '.local', prefix='shell-streams-')) + server, url = start() + results = {} + try: + for case in args.cases.split(','): + for n in range(args.runs): + # Alternated, so drift in the machine falls on both. + for binary in (args.agent if n % 2 == 0 else args.agent[::-1]): + row = run(binary, url, args.fleet, case, args.seconds, work, + args.shim, args.slow_ms) + results.setdefault(case, {}).setdefault(binary, []).append(row) + print(case, binary, json.dumps(row), flush=True) + summary = {case: {binary: {key: statistics.median(row[key] for row in rows) + for key in rows[0] if rows[0][key] is not None} + for binary, rows in by.items()} + for case, by in results.items()} + print(json.dumps(summary, indent=1)) + if args.out: + Path(args.out).write_text(json.dumps({'fleet': args.fleet, 'runs': results, + 'medians': summary}, indent=1)) + finally: + server.shutdown() + shutil.rmtree(work, ignore_errors=True) + + +if __name__ == '__main__': + main() diff --git a/docs/DAEMON_MEASUREMENTS.md b/docs/DAEMON_MEASUREMENTS.md index db914fac7..6f012f239 100644 --- a/docs/DAEMON_MEASUREMENTS.md +++ b/docs/DAEMON_MEASUREMENTS.md @@ -15051,3 +15051,71 @@ python -m bench.link_fanout --links 1 python -m bench.link_fanout --links 4 --bulk 1 python -m bench.link_fanout --links 4 --bulk 3 ``` + +## Shell output kept across a daemon stop or kill (Dec 2 feedback, item 23) + +2026-12-03, a 4-CPU cloud container, release builds of main (2f67e9b) and +this change built with the same `cargo build --release --locked --workspace +--bins`, glibc's allocator (the shipped Linux builds use jemalloc), synthetic +model. `bench.shell_streams` runs each case on a fresh copy of one seed store +with that many stored agents, the two daemons alternated, three runs each +(flood100 at 50 agents four), medians. The agents running commands are made +beside the fleet, each with an outputs folder. + +- storm, storm_quiet: 30 agents running `echo hi` (or `true`) in the + foreground back to back for 8 s, about 2,000 commands. Short commands, the + path that must not change. +- short_bg: 30 agents each running a 0.3 s background command and waiting + for it, back to back. +- trickle30, trickle300, trickle1000: that many concurrent 3 s background + commands writing a line every 0.1 s. +- medium30, medium300: 3 s commands writing 10 KiB every 0.1 s (300 KiB). +- flood30, flood100: 64 MB as fast as the pipe takes it. + +CPU is the daemon's own (user and system) per command; loop p99 is the +answer to a `tools` request sent every 10 ms while the case runs; command +p50 and p99 run from submit to the turn's end. + +{tables} + +The slow disk is `bench/held/slow_sync.c` with `SLOW_WRITES=1` and the new +`SLOW_FILE_WRITES=1`: once the agents are made, every sync, every file +created, renamed or removed, and every write(2) or writev(2) to a regular +file waits 200 ms. + +What it shows: + +- Commands that end within their first second, the storms and short_bg, are + unchanged at every fleet size: within 2% on CPU, RSS and latency, both ways + between runs. No timer is armed for a command until it has output and a + file to go to, and none is made for one without an outputs folder. +- A command that runs past its first second now writes its output to its + file: once at the mark, then at most once a second, or per 256 KiB. That is + real work main never did, and it costs 0.3 to 0.6 ms of daemon CPU per such + command (2 to 9%), about two trips to a blocking worker and an open, a + write or two and an unlink. Its latency, and the loop's, are unchanged. The + files it leaves are the same (none for the trickles, whose files end within + a preview and are removed; one per medium and flood stream, as on main). +- Past 1 MiB, writes are batched up to 256 KiB as main's buffered writer + did, without its 256 KiB buffer per stream: floods take 15% less CPU and + 18 to 85 MiB less memory. On a slow disk a batch takes everything already + waiting, up to 16 reads, so a flood finishes in half main's time there: + main makes the reader wait for 256 KiB writes that each take 200 ms. +- Within 1 MiB the reader never waits for the disk: what was read waits with + the stream's kept bytes, which hold it already, and goes when the writer has + room. A slow disk never holds a pipe longer than main does. +- medium300's peak RSS is 6.5 MiB higher: 300 streams reach their first + second together and each hands its first 100 KiB to its writer at once. + +A clean stop with 30 running background commands, each with a few hundred +bytes of output: 32 ms on main and with this change, three runs each. Main +records each as `process_lost` with no output; this change records each as +ended by the stop with its output (`daemon_shutdown`). + +Profile (`perf record` on trickle300, both daemons): the daemon's threads +take 2.6% more samples than main's, all of it opening, writing and removing +the files and waking the workers that do. An earlier cut of this change +copied each read for its writer and kept a 256 KiB buffer per file: medium300 +peaked 23 MiB above main and floods were 3 to 5% slower; writing from the +kept bytes, one writev per batch and taking the first write and the last +with the open and the close removed both. diff --git a/docs/RUST_PROTOTYPE.md b/docs/RUST_PROTOTYPE.md index a347735e5..9673602b4 100644 --- a/docs/RUST_PROTOTYPE.md +++ b/docs/RUST_PROTOTYPE.md @@ -293,8 +293,16 @@ Parked turns survive a daemon restart: they are re-registered at startup, peer handles resolve from durable state (a peer interrupted by the restart reports `interrupted`), and commands that were still running resolve to `process_lost`: their supervision ended with the daemon, whether or not the -OS process did. A daemon that stops cleanly does not wait for them: it kills -each one's process group and records `process_lost` itself. Interrupting a parked +OS process did. A command that runs past its first second has its output +written to its stream's file in the bot's outputs folder as it runs, at most a +second behind and without a sync, as Pi keeps a running call's output; one that +ends sooner never touches the disk, and a file that ends within a preview is +removed as the command ends. So a lost background command answers with what +its files kept: the text as a finished command's is shown, and the files where +they hold more. A daemon that stops cleanly asks each running command to end, +as a stop by its handle does, keeps reading it through the grace, and records +its end with its output as `daemon_shutdown`, waiting up to 5 s for those ends +to be recorded; only a row still running at the next start becomes lost. Interrupting a parked turn ends it as `interrupted`: the wait and any planned calls behind it get a `cancelled` tool result in the same transaction, so the conversation stays valid and the bot is not left uncertain. A bot whose turn is parked reports diff --git a/src/server/mod.rs b/src/server/mod.rs index acd161185..82ca3182f 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -54,6 +54,10 @@ use turn::Turn; /// idle one waits for no company. Anything else waits for those already /// queued, and they are answered in the order they arrived. const ADMISSION_WINDOW: usize = 32; +/// The longest the daemon's stop waits for the ends of the background +/// commands it ended to be recorded: each is asked to end, given its +/// grace, and its pipes read, so this bounds only a stuck disk. +const BACKGROUND_RECORDED: Duration = Duration::from_secs(5); /// A canonical workspace in JSON: the path limit, every byte escaped. const PATH_JSON: usize = 6 * 4096 + 2; /// A model reference in JSON, at the limits `split_model` enforces. @@ -3333,6 +3337,13 @@ pub async fn run(config: Configuration) -> Result<()> { .read("lifted_waiting", |db| db.lifted_waiting()) .await?; service.check_lifted(lifted); + // Background commands an earlier daemon lost while they ran answer + // with the output their files kept, before any wait reads them. + let lost = service + .store + .op("take_lost", |db| Ok(db.take_lost())) + .await?; + turn::lost_outputs(&service.store, &service.registry, lost).await?; // Detached commands an earlier daemon started run on: each is watched // again, and stopped by its handle, or its end is recorded now. let detached = service @@ -3990,6 +4001,10 @@ pub async fn run(config: Configuration) -> Result<()> { // Daemon steps still running end now that stopping is said, but for a // change to files already begun, which finishes; each end is recorded. service.steps_stopping().await; + // Each background command the stop ended has its end, with what it + // wrote, recorded before the store closes: a row left running would + // read as lost at the next start. + service.registry.recorded(BACKGROUND_RECORDED).await; // Every completion is committed. Allow publication to drain before // releasing waiters. Background result tasks may still own Store clones, // keeping the stream open even after the service is dropped. diff --git a/src/server/turn.rs b/src/server/turn.rs index 7be2a0847..ed43967f0 100644 --- a/src/server/turn.rs +++ b/src/server/turn.rs @@ -21,8 +21,8 @@ use agent_runtime::{ store::{ AfterTurn, Answer, ArtifactLines, Bot, CallAnswer, Charge, ContextPrefix, ContextUsage, Database, DetachedRow, ElisionPlan, Gated, Halt, Halted, Joined, Lifted, LiftedRun, Limit, - ProcessKind, Retained, Settings, Slot, Spend, Store, Strip, TURN_VIEW_ACCOUNTING, Waiting, - Window, listed_command, unserved, + LostRow, ProcessKind, Retained, Settings, Slot, Spend, Store, Strip, TURN_VIEW_ACCOUNTING, + Waiting, Window, listed_command, unserved, }, tools::{ Agents, Cord, Files, HISTORY_PAGE_BYTES, Outcome, POLL_YIELD_MS, Place, Prepared, @@ -8021,9 +8021,12 @@ impl Lifts { bot.to_owned(), ); // A detached command runs on past the daemon: its collector lets - // the store go as the daemon stops, recording no end. + // the store go as the daemon stops, recording no end. Any other's + // end the daemon's stop waits for, as the stop ends it. let stopping = outlives.then(|| self.registry.until_stopping()); + let recorded = (!outlives).then(|| self.registry.recording()); tokio::spawn(async move { + let _recorded = recorded; let received = match stopping { Some(stopping) => tokio::select! { received = receiver => received, @@ -8572,6 +8575,107 @@ impl Outputs { } } +/// Put in the result of each background command an earlier daemon lost +/// while it ran, `lost`, what its streams' files hold: the output it read +/// before it ended, shown as a finished command's is, and the files named +/// where they hold more. Only where its bot's commands may not write the +/// folder, as `keep` writes there: a file one put there is not read. +pub(super) async fn lost_outputs( + store: &Store, + registry: &Registry, + lost: Vec, +) -> Result<()> { + if lost.is_empty() { + return Ok(()); + } + let mut lost_by_bot: HashMap> = HashMap::new(); + for row in lost { + lost_by_bot.entry(row.bot.clone()).or_default().push(row); + } + let names: Vec = lost_by_bot.keys().cloned().collect(); + let bots: Vec = store + .read("lost_bots", move |db| { + Ok(names + .iter() + .filter_map(|name| db.inspect(name).ok()) + .collect()) + }) + .await?; + let daemon = registry.daemon().clone(); + let found = tokio::task::spawn_blocking(move || { + let (mut found, mut shown) = (Vec::new(), Vec::new()); + for bot in bots { + let Some(rows) = lost_by_bot.remove(&bot.name) else { + continue; + }; + let root = PathBuf::from(bot.workspace.clone().unwrap_or_default()); + let Some(outputs) = Outputs::of(&bot, root, &daemon) else { + continue; + }; + if outputs.exposed() { + continue; + } + for row in rows { + let name = format!("{}-{}", row.turn, file_name(&row.call_id)); + let streams = ["stdout", "stderr"].map(|stream| { + let kept = + agent_runtime::tools::retained_stream(&outputs.folder, &name, stream); + (stream, kept) + }); + if streams.iter().all(|(_, kept)| kept.is_none()) { + continue; + } + let mut result = json!({"error":"process_lost"}); + let mut files = Vec::new(); + for (stream, kept) in streams { + let Some((text, file)) = kept else { + result[stream] = json!(""); + continue; + }; + result[stream] = json!(text); + match file { + Some(file) => files.push((stream, file)), + // Shown whole, as a stream within a preview is: its + // file goes once the result holds it. + None => shown.push(outputs.folder.join(format!("{name}-{stream}"))), + } + } + // Named as `annotate` names a finished command's files. + if !files.is_empty() { + let refs: Vec = (files.iter()) + .map(|(stream, _)| format!("{}/{}/{stream}", row.turn, row.call_id)) + .collect(); + result["artifacts"] = json!(refs); + result["files"] = json!(files.iter().map(|(_, file)| file).collect::>()); + } + found.push((row.id, result, files)); + } + } + (found, shown) + }) + .await + .map_err(|_| Error::new("tool_outcome_failed"))?; + let (found, shown) = found; + if found.is_empty() { + return Ok(()); + } + store + .op("lost_output", move |db| { + for (id, result, files) in found { + db.lost_output(id, &result, &files)?; + } + Ok(()) + }) + .await?; + let _ = tokio::task::spawn_blocking(move || { + for path in shown { + let _ = std::fs::remove_file(path); + } + }) + .await; + Ok(()) +} + /// A call's id as part of a file's name: letters, digits, `_` and `-`. fn file_name(call_id: &str) -> String { call_id diff --git a/src/store.rs b/src/store.rs index 5e950c70d..84ef500d3 100644 --- a/src/store.rs +++ b/src/store.rs @@ -26,12 +26,13 @@ pub use db::{ CallAnswer, Capture, CatchUp, Charge, Closing, CompactionPlan, CompactionView, CopiedCall, Counts, DENIAL_WINDOW, Database, Decision, Delivery, DetachedRow, Durability, ENV_JSON, EVENT_PAGE_KINDS, ElisionPlan, FOLDERS_JSON, Fork, Gate, Gated, HOLD_MAX_MS, Halt, Halted, - Identity, Joined, Kept, Lapsed, Lifted, LiftedRun, Limit, MAX_GATES, Messages, NEVER_ASKS, - PROCESSES_PAGE, Pack, Packing, ParkedFallback, Plan, Planning, ProcessKind, ProcessesPage, - Publication, QuoteRef, RESTART_LIMIT, RULES_JSON, Reclaim, Replaced, Resumed, Room, SANDBOX, - SETTINGS, Served, Settings, Shared, Spend, Started, Step, StepAsk, StepOpened, Stepped, Strip, - Switch, TRAILER, TURN_VIEW_ACCOUNTING, Trailer, Translation, TurnBudget, TurnOptions, - UsageQuery, Waiting, Wake, Window, Work, cache_hit, glob, listed_command, share, unserved, + Identity, Joined, Kept, Lapsed, Lifted, LiftedRun, Limit, LostRow, MAX_GATES, Messages, + NEVER_ASKS, PROCESSES_PAGE, Pack, Packing, ParkedFallback, Plan, Planning, ProcessKind, + ProcessesPage, Publication, QuoteRef, RESTART_LIMIT, RULES_JSON, Reclaim, Replaced, Resumed, + Room, SANDBOX, SETTINGS, Served, Settings, Shared, Spend, Started, Step, StepAsk, StepOpened, + Stepped, Strip, Switch, TRAILER, TURN_VIEW_ACCOUNTING, Trailer, Translation, TurnBudget, + TurnOptions, UsageQuery, Waiting, Wake, Window, Work, cache_hit, glob, listed_command, share, + unserved, }; type ReadJob = Box; diff --git a/src/store/db.rs b/src/store/db.rs index d92a74953..53068ed0f 100644 --- a/src/store/db.rs +++ b/src/store/db.rs @@ -3197,6 +3197,9 @@ fn glob_in>(pattern: &[T], name: &[T]) -> bool { } pub struct Database { conn: Connection, + /// The background commands this open found lost, whose output the + /// daemon looks for in their files once (`take_lost`). + lost: Vec, /// Bounds on submissions waiting to start, turns and prompt bytes; zero /// is unbounded. Daemon configuration, set once after open. pending_limits: (usize, usize), @@ -4117,6 +4120,16 @@ impl ProcessKind { } } +/// A background command the daemon lost while it ran, found as the store +/// opened: its handle, bot, and the turn and call its files are named by. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LostRow { + pub id: i64, + pub bot: String, + pub turn: i64, + pub call_id: String, +} + /// A detached command an earlier daemon started, as its row keeps it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct DetachedRow { @@ -4195,6 +4208,7 @@ impl Database { ))?; Ok(Self { conn, + lost: Vec::new(), pending_limits: (0, 0), max_depth: None, pending: (0, 0), @@ -4672,27 +4686,39 @@ impl Database { // A call a message lifted that ran as one of these commands was cut // off with it: its row in the audit trail says so, in the same // commit, so a stop between them never leaves it unknown. + // A command's output went to its file as it ran: the daemon finds + // what is there once it knows where the bot's folder is + // (`take_lost`, `lost_output`). let tx = conn.unchecked_transaction()?; - let lost: Vec<(i64, String)> = tx + let rows: Vec<(LostRow, bool, bool)> = tx .prepare( "UPDATE processes SET status='lost',result=? WHERE status='running' AND detached IS NULL AND id NOT IN (SELECT process FROM approvals INDEXED BY approvals_lifted WHERE process IS NOT NULL) AND id NOT IN (SELECT process FROM answers INDEXED BY answers_lifted WHERE process IS NOT NULL) - RETURNING turn,call_id,call IS NOT NULL", + RETURNING id,bot,turn,call_id,kind='background',call IS NOT NULL", )? .query_map([json!({"error":"process_lost"}).to_string()], |r| { - Ok((r.get(0)?, r.get(1)?, r.get::<_, bool>(2)?)) + let bot: Option = r.get(1)?; + let shell = bot.is_some() && r.get::<_, Option>(4)? == Some(true); + let row = LostRow { + id: r.get(0)?, + bot: bot.unwrap_or_default(), + turn: r.get(2)?, + call_id: r.get(3)?, + }; + Ok((row, shell, r.get(5)?)) })? - .filter_map(|row| match row { - Ok((turn, call_id, true)) => Some(Ok((turn, call_id))), - Ok(_) => None, - Err(error) => Some(Err(error)), - }) .collect::>()?; - for (turn, call_id) in lost { - lifted_audit(&tx, turn, &call_id, End::Interrupted)?; + for (row, _, lifted) in &rows { + if *lifted { + lifted_audit(&tx, row.turn, &row.call_id, End::Interrupted)?; + } } tx.commit()?; + // A terminal's output went to no file. + let lost = (rows.into_iter()) + .filter_map(|(row, shell, _)| shell.then_some(row)) + .collect(); // A step lives only as long as the `approve_step` waiting on it, // which a restart ended: its call's time runs again. conn.execute( @@ -4734,6 +4760,7 @@ impl Database { files_gone: Vec::new(), calls_ended: Vec::new(), call_ends: None, + lost, }; // A switch a stop cut short is let go: what it wrote goes, and the // bot's turns go on in the family it is in. @@ -16634,6 +16661,32 @@ impl Database { next_after, }) } + /// The background commands this open found lost, once: their output, + /// if their files hold any, goes in with `lost_output`. + pub fn take_lost(&mut self) -> Vec { + std::mem::take(&mut self.lost) + } + /// Lost command `id`'s result, `result`, now with the output its files + /// held, and those files, `files`, as a finished command's are kept. + pub fn lost_output(&mut self, id: i64, result: &Value, files: &[(&str, String)]) -> Result<()> { + let tx = self.conn.savepoint()?; + let found: Option<(i64, String)> = tx + .prepare_cached( + "UPDATE processes SET result=? WHERE id=? AND status='lost' RETURNING turn,call_id", + )? + .query_row(params![result.to_string(), id], |r| { + Ok((r.get(0)?, r.get(1)?)) + }) + .optional()?; + let Some((turn, call_id)) = found else { + return Ok(()); + }; + for (stream, file) in files { + artifact::put_file(&tx, turn, &call_id, stream, file)?; + } + tx.commit()?; + Ok(()) + } /// The outcome and its overflow become visible in one transaction. /// `failed` is whoever ran it saying the call failed, never read back /// from the result's fields. diff --git a/src/tools.rs b/src/tools.rs index 54efd5967..50c114659 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -869,6 +869,9 @@ pub struct Registry { /// Set once as the daemon stops: background commands still running /// end then rather than outlive it. stopping: Arc>, + /// The ends of background commands being recorded, which the daemon's + /// stop waits for: see [`Registry::recording`]. + recording: Arc, /// Background commands running, by proc handle, each with what stops /// it when its agent kills it, and whose it is once it counts toward /// its bot's share. @@ -1062,6 +1065,18 @@ impl Decoding { text_of(std::mem::replace(&mut self.held, rest)) } + /// As `feed`, taking `bytes` to tell in place when nothing was held + /// before them, as is usual: no copy of them is made. + pub fn feed_owned(&mut self, mut bytes: Vec) -> String { + if !self.held.is_empty() { + return self.feed(&bytes); + } + let whole = bytes.len() - unfinished_char(&bytes); + self.held.extend_from_slice(&bytes[whole..]); + bytes.truncate(whole); + text_of(bytes) + } + /// Begin again after a gap in the stream: what was held no longer /// bears on what comes next. pub fn restart(&mut self) { @@ -1521,6 +1536,7 @@ impl Registry { #[cfg(unix)] terminals: Arc::default(), stopping: Arc::new(watch::Sender::new(false)), + recording: Arc::default(), stops: Arc::default(), pulls: Arc::new(watch::Sender::new(0)), credentials: Credentials::default(), @@ -2930,6 +2946,17 @@ impl Registry { "exit_code":null,"success":false,"timed_out":true,"wall_time_ms":elapsed_ms}), false, ), + // So is a command the daemon's stop ended: what it wrote, and + // why it ended, as a call the stop cut off says. + Exit::Stopped => { + let stopped = stopped_by_shutdown(); + ( + json!({"stdout":stdout,"stderr":stderr, + "exit_code":null,"success":false,"error":stopped.code, + "detail":stopped.detail,"wall_time_ms":elapsed_ms}), + false, + ) + } }; Outcome { output: output.to_string(), @@ -3084,9 +3111,16 @@ impl Registry { tokio::spawn(async move { let _listed = listed; let result = async { + // The daemon's stop before a slot came: it never starts. let slot = match queued.permit.take() { Some(permit) => Ok(permit), - None => registry.admitted_slot().await, + None => tokio::select! { + biased; + true = said(&mut stopping) => { + return Err(not_started_by_shutdown()); + } + slot = registry.admitted_slot() => slot, + }, }; drop(queued); // The slot and the sandbox's hold go once the command is @@ -3129,10 +3163,8 @@ impl Registry { Ok(()) = pulls.changed() => { let _ = done.send(Err(stopped_by_pause())); } - // A command still running as the daemon stops is dropped - // the same way; its handle then reports the process lost, - // as the next start would. - _ = stopping.wait_for(|stopping| *stopping) => {} + // A command still running as the daemon stops ends with + // what it wrote, its handle saying the stop ended it. result = result => { let _ = done.send(result); } @@ -3395,6 +3427,54 @@ impl Registry { pub fn end_background(&self) { self.stopping.send_replace(true); } + + /// Held while a background command's end is on its way to the store: + /// from before it can end until its end is recorded. + pub fn recording(&self) -> Recorded { + self.recording + .count + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Recorded(self.recording.clone()) + } + + /// Wait, up to `within`, until every background command's end is + /// recorded: as the daemon stops, once each was told to end. + pub async fn recorded(&self, within: Duration) { + let recording = &self.recording; + let _ = tokio::time::timeout(within, async { + loop { + let idle = recording.idle.notified(); + if recording.count.load(std::sync::atomic::Ordering::Relaxed) == 0 { + return; + } + idle.await; + } + }) + .await; + } +} + +/// Background commands whose ends are on their way to the store. +#[derive(Default)] +struct Recording { + count: std::sync::atomic::AtomicUsize, + idle: tokio::sync::Notify, +} + +/// One background command's end on its way to the store, until dropped. +pub struct Recorded(Arc); + +impl Drop for Recorded { + fn drop(&mut self) { + if self + .0 + .count + .fetch_sub(1, std::sync::atomic::Ordering::Relaxed) + == 1 + { + self.0.idle.notify_waiters(); + } + } } /// How a background command that was killed answers: by its agent, or @@ -4038,8 +4118,9 @@ impl Registry { /// What a stream wrote, bounded: all of it up to `ARTIFACT_BYTES`, past /// that its first and last `KEPT_END` bytes and a count of the rest. With -/// a [`Spill`], a stream that passes the bound is written whole to a file -/// as it is read, and these bytes are only what the model is shown. +/// a [`Spill`], a stream is written whole to a file as it is read once it +/// passes the bound, or once its command has run `STREAM_AFTER` still +/// writing, and these bytes are only what the model is shown. #[derive(Default)] struct Captured { head: Vec, @@ -4048,6 +4129,16 @@ struct Captured { /// Where the whole stream goes once it passes the bound, and the /// stream's name. spill: Option<(Spill, &'static str)>, + /// When its command has run `STREAM_AFTER`, for a stream with a + /// spill: from then it goes to its file as it is read, so a daemon + /// that stops or dies leaves what the command wrote. One that ends + /// sooner never touches the disk. + mark: Option, + /// Within the bound, how much of what was read its writer was handed: + /// the rest waits here, and goes by `due` or once a batch waits. + sent: usize, + /// When what waits here goes to the writer, within the bound. + due: Option, /// What writes it there, once it has passed. writer: Option, /// How many of a command's streams are waiting for their writer to @@ -4063,23 +4154,38 @@ struct Captured { /// invalid byte made at most three, as a stored copy's are. pub const FILE_RETAINED_BYTES: u64 = 3 * SPILL_BYTES; +/// How long a command runs before its streams go to their files as they +/// are read, as Pi persists a running call's output within a second. +const STREAM_AFTER: Duration = Duration::from_secs(1); + +/// The longest a stream's output waits in memory, once it goes to its +/// file, before it is written there: what a daemon killed outright can +/// lose of it. A stream that writes slowly costs one write a second. +const FLUSH_WITHIN: Duration = Duration::from_secs(1); + +/// A write's worth of a stream's output: once this much waits, it is +/// written without waiting out `FLUSH_WITHIN`. +const BATCH_BYTES: usize = 256 * 1024; + /// Where a command's streams go whole as it runs, once one passes -/// `ARTIFACT_BYTES`: a file each, `FOLDER/NAME-STREAM`, in the bot's -/// outputs folder. What a stream within the bound writes never reaches it. +/// `ARTIFACT_BYTES` or the command has run `STREAM_AFTER`: a file each, +/// `FOLDER/NAME-STREAM`, in the bot's outputs folder. What a command that +/// ends within that time writes within the bound never reaches it. #[derive(Clone)] pub struct Spill { pub folder: PathBuf, pub name: String, /// Whether the folder may hold them, asked on a blocking worker as a - /// stream first passes the bound: not while the bot's commands may - /// write there, since one could put a link there for the daemon. + /// stream first goes there: not while the bot's commands may write + /// there, since one could put a link there for the daemon. pub usable: Arc bool + Send + Sync>, } /// A stream's writer: what was read goes to it in pieces, written in /// batches on blocking workers, so the runtime's thread never waits on the -/// disk. A full line of pieces makes the reader wait, and the command with -/// it. +/// disk. Past the bound, a full line of pieces makes the reader wait, and +/// the command with it; within it, what was read waits with the rest of +/// the stream's kept bytes instead, and goes once there is room. struct Writer { /// Closed once the writer stops taking more: at its bound, or failed. pieces: Option>>, @@ -4135,9 +4241,11 @@ impl Captured { stream: &'static str, waiting: &Arc, peek: Option<&Peek>, + started: tokio::time::Instant, ) -> Self { Captured { spill: spill.map(|spill| (spill.clone(), stream)), + mark: spill.map(|_| started + STREAM_AFTER), waiting: waiting.clone(), peek: peek.cloned(), ..Captured::default() @@ -4145,41 +4253,158 @@ impl Captured { } /// Hand `bytes`, just read, to the writer, starting it with all read - /// before when they take the stream past the bound. + /// before when they take the stream past the bound or come past its + /// mark. Within the bound they are only kept, and go with the rest at + /// `flush`: the reader never waits for the disk, and nothing is copied + /// for each read. async fn spill(&mut self, bytes: &[u8]) { + let within = self.dropped == 0 && self.len() + bytes.len() <= ARTIFACT_BYTES; if self.writer.is_none() { - if self.len() + bytes.len() <= ARTIFACT_BYTES { + let marked = self + .mark + .is_some_and(|mark| tokio::time::Instant::now() >= mark); + if within && !marked { return; } - let Some((spill, stream)) = self.spill.take() else { - return; - }; - // Past the bound nothing was dropped yet: the head and tail are - // all of it so far. - let mut first = Vec::with_capacity(self.len()); - first.extend_from_slice(&self.head); - first.extend(self.tail.iter()); - let (pieces, received) = tokio::sync::mpsc::channel(SPILL_PIECES); - let done = tokio::spawn(spill_stream(spill, stream, first, received)); - self.writer = Some(Writer { - pieces: Some(pieces), - pending: None, - done, - }); + self.stream(within); } + if within { + if self.due.is_none() { + self.due = Some(tokio::time::Instant::now() + FLUSH_WITHIN); + } + return; + } + // Past the bound what was not handed yet goes first, before the + // tail drops any of it, and the reader waits for room. + let unsent = self.unsent(); + self.sent = self.len(); let Some(writer) = &mut self.writer else { return; }; - if writer.pieces.is_some() { - writer.pending = Some(bytes.to_vec()); - writer.hand(&self.waiting).await; + if writer.pieces.is_none() { + return; + } + let pending = writer.pending.get_or_insert_with(Vec::new); + if let Some(unsent) = unsent { + pending.extend_from_slice(&unsent); } + pending.extend_from_slice(bytes); + writer.hand(&self.waiting).await; + } + + /// What was read within the bound and not handed to the writer yet. + fn unsent(&self) -> Option> { + if self.dropped > 0 || self.sent >= self.len() { + return None; + } + let mut unsent = Vec::with_capacity(self.len() - self.sent); + match self.head.len().checked_sub(self.sent) { + Some(_) => { + unsent.extend_from_slice(&self.head[self.sent..]); + unsent.extend(self.tail.iter()); + } + None => unsent.extend(self.tail.range(self.sent - self.head.len()..)), + } + Some(unsent) + } + + /// Hand the writer what waits within the bound, once it is `due`, a + /// batch of it waits, or `now`: when it has room, else a second later. + fn flush(&mut self, now: bool) { + use tokio::sync::mpsc::error::TrySendError; + let waits = self.len().saturating_sub(self.sent); + if self.dropped > 0 || waits == 0 { + return; + } + let at = tokio::time::Instant::now(); + if !now && waits < BATCH_BYTES && self.due.is_some_and(|due| at < due) { + return; + } + let Some(pieces) = self + .writer + .as_ref() + .and_then(|writer| writer.pieces.as_ref()) + else { + return; + }; + let handed = match pieces.try_reserve() { + Ok(room) => { + room.send(self.unsent().unwrap_or_default()); + Ok(()) + } + Err(TrySendError::Full(())) => Err(false), + Err(TrySendError::Closed(())) => Err(true), + }; + match handed { + Ok(()) => { + self.sent = self.len(); + self.due = None; + } + Err(false) => self.due = Some(at + FLUSH_WITHIN), + Err(true) => { + if let Some(writer) = &mut self.writer { + writer.pieces = None; + } + } + } + } + + /// When the stream next has something to do without a read: go to + /// its file at its mark, or hand its writer what waits. + fn deadline(&self) -> Option { + if self.awaits_mark() { + return self.mark; + } + let writing = self + .writer + .as_ref() + .is_some_and(|writer| writer.pieces.is_some()); + (writing && self.dropped == 0 && self.sent < self.len()) + .then_some(self.due) + .flatten() + } + + /// Start the stream's writer with all read so far: `marked` when its + /// command's time, not the bound, sent it there. + fn stream(&mut self, marked: bool) { + let Some((spill, stream)) = self.spill.take() else { + return; + }; + self.mark = None; + // Short of the bound nothing was dropped yet: the head and tail + // are all of it so far. + let mut first = Vec::with_capacity(self.len()); + first.extend_from_slice(&self.head); + first.extend(self.tail.iter()); + self.sent = self.len(); + self.due = None; + let (pieces, received) = tokio::sync::mpsc::channel(SPILL_PIECES); + let done = tokio::spawn(spill_stream(spill, stream, first, received, marked)); + self.writer = Some(Writer { + pieces: Some(pieces), + pending: None, + done, + }); + } + + /// Whether it waits for its mark: it has a file to go to, and output + /// that is not there yet. + fn awaits_mark(&self) -> bool { + self.writer.is_none() && self.spill.is_some() && self.len() > 0 } /// Wait for the writer, when the stream had one, to take what it was /// still to be handed and finish its file. async fn settle(&mut self) { + let unsent = self.unsent(); + self.sent = self.len(); if let Some(mut writer) = self.writer.take() { + if let (Some(unsent), Some(_)) = (unsent, &writer.pieces) { + writer + .pending + .get_or_insert_with(Vec::new) + .extend_from_slice(&unsent); + } writer.hand(&self.waiting).await; drop(writer.pieces); self.spilled = writer.done.await.ok().flatten(); @@ -4189,6 +4414,18 @@ impl Captured { fn len(&self) -> usize { self.head.len() + self.tail.len() } + /// `bytes`, just read: the head takes them up to `KEPT_END`, the tail + /// the rest. + fn store(&mut self, bytes: &[u8]) { + let room = match self.tail.is_empty() { + true => KEPT_END.saturating_sub(self.head.len()).min(bytes.len()), + false => 0, + }; + self.head.extend_from_slice(&bytes[..room]); + if room < bytes.len() { + self.keep(&bytes[room..]); + } + } /// Output past the head. Once the whole would pass the bound, the tail /// keeps only its last `KEPT_END` bytes. fn keep(&mut self, bytes: &[u8]) { @@ -4236,43 +4473,79 @@ impl Captured { /// goes: `first`, then each piece as it comes, up to `SPILL_BYTES`. None /// when the folder may not hold it or a write fails, the file removed, and /// the stream's bounded copy is kept as before. The disk is used only on -/// blocking workers, a batch of pieces at a time: none is held while the -/// command writes nothing, so idle streams never fill the blocking pool. +/// blocking workers, a batch of pieces at a time, each batch written +/// through to the system so a daemon that dies leaves it: none is held +/// while the command writes nothing, so idle streams never fill the +/// blocking pool. A stream its command's time sent there, `marked`, that +/// ends within a preview's worth has its file removed: its answer shows it +/// whole, as one that ended sooner. async fn spill_stream( spill: Spill, stream: &'static str, first: Vec, mut pieces: tokio::sync::mpsc::Receiver>, + marked: bool, ) -> Option { let folder = spill.folder.clone(); - let mut file = tokio::task::spawn_blocking(move || SpillFile::open(&spill, stream)) - .await - .ok()??; - let mut batch = vec![first]; - loop { - let (back, full) = tokio::task::spawn_blocking(move || { - let full = file.write(&batch)?; - Some((file, full)) - }) - .await - .ok()??; - file = back; - if full { - break; - } + // Made and given what was read so far in one trip to a worker. + let (mut file, mut full) = tokio::task::spawn_blocking(move || { + let mut file = SpillFile::open(&spill, stream)?; + let full = file.write(vec![first])?; + Some((file, full)) + }) + .await + .ok()??; + // What came after the last write as the stream ended, written as + // the file is finished, in the same trip. + let mut last = Vec::new(); + while !full { + let written = tokio::time::Instant::now(); let Some(piece) = pieces.recv().await else { break; }; - batch = vec![piece]; - while batch.len() < SPILL_PIECES - && let Ok(piece) = pieces.try_recv() - { - batch.push(piece); + // What comes within `FLUSH_WITHIN` of the last write joins this + // piece, up to a batch, so a stream past the bound is written a + // batch at a time; one that comes later goes at once. + let mut bytes = piece.len(); + let mut batch = vec![piece]; + let due = written + FLUSH_WITHIN; + let mut closed = false; + while bytes < BATCH_BYTES { + match tokio::time::timeout_at(due, pieces.recv()).await { + Ok(Some(piece)) => { + bytes += piece.len(); + batch.push(piece); + } + Ok(None) => { + closed = true; + break; + } + Err(_) => break, + } + } + // And what is already waiting, as a disk slower than the stream + // leaves it: the next write takes all of it. + while !closed && batch.len() < SPILL_PIECES { + match pieces.try_recv() { + Ok(piece) => batch.push(piece), + Err(tokio::sync::mpsc::error::TryRecvError::Empty) => break, + Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => closed = true, + } + } + if closed { + last = batch; + break; } + (file, full) = tokio::task::spawn_blocking(move || { + let full = file.write(batch)?; + Some((file, full)) + }) + .await + .ok()??; } // Past the bound the reader stops sending once this end closes. pieces.close(); - let (path, saved) = tokio::task::spawn_blocking(move || file.close(&folder)) + let (path, saved) = tokio::task::spawn_blocking(move || file.close(&folder, marked, last)) .await .ok()??; Some(Spilled { @@ -4281,12 +4554,34 @@ async fn spill_stream( }) } +/// Write each of `texts`, in order, in as few writes as the system takes. +fn write_all_of(out: &mut std::fs::File, texts: &[String]) -> std::io::Result<()> { + use std::io::{IoSlice, Write}; + let mut slices: Vec = texts + .iter() + .filter(|text| !text.is_empty()) + .map(|text| IoSlice::new(text.as_bytes())) + .collect(); + let mut slices = &mut slices[..]; + while !slices.is_empty() { + match out.write_vectored(slices) { + Ok(0) => return Err(std::io::ErrorKind::WriteZero.into()), + Ok(written) => IoSlice::advance_slices(&mut slices, written), + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + Ok(()) +} + /// A stream's file while it is written, used on blocking workers only. struct SpillFile { path: PathBuf, - out: std::io::BufWriter, + out: std::fs::File, decoding: Decoding, saved: u64, + /// Bytes of text written for it. + told: usize, } impl SpillFile { @@ -4305,45 +4600,71 @@ impl SpillFile { .ok()?; Some(SpillFile { path, - out: std::io::BufWriter::with_capacity(256 << 10, file), + out: file, decoding: Decoding::default(), saved: 0, + told: 0, }) } - /// Write `batch`, as text, up to `SPILL_BYTES`: whether that bound - /// was reached, or None, the file removed, when a write failed. - fn write(&mut self, batch: &[Vec]) -> Option { - use std::io::Write; - for bytes in batch { + /// Write `batch`, as text, up to `SPILL_BYTES`, through to the system: + /// whether that bound was reached, or None, the file removed, when a + /// write failed. + fn write(&mut self, batch: Vec>) -> Option { + let (texts, full) = self.tell(batch); + if write_all_of(&mut self.out, &texts).is_err() { + let _ = std::fs::remove_file(&self.path); + return None; + } + Some(full) + } + + /// `batch` as text, up to `SPILL_BYTES`, counted as written: whether + /// that bound was reached. + fn tell(&mut self, batch: Vec>) -> (Vec, bool) { + let mut full = false; + // Each piece told as text in place, mostly, and the batch written + // at once: no buffer is kept or made for it. + let mut texts = Vec::with_capacity(batch.len()); + for mut bytes in batch { let fits = (bytes.len() as u64).min(SPILL_BYTES - self.saved) as usize; - let told = self.decoding.feed(&bytes[..fits]); - if self.out.write_all(told.as_bytes()).is_err() { - let _ = std::fs::remove_file(&self.path); - return None; - } + full = fits < bytes.len(); + bytes.truncate(fits); self.saved += fits as u64; - if fits < bytes.len() { - return Some(true); + let told = self.decoding.feed_owned(bytes); + self.told += told.len(); + texts.push(told); + if full { + break; } } - Some(false) + (texts, full) } /// Finish the file, on disk with its name in `folder` before the store /// records it: its path and how many bytes of the stream it holds. - fn close(self, folder: &Path) -> Option<(PathBuf, u64)> { - use std::io::Write; + /// `last` is written first. One `marked` that holds no more than a + /// preview is removed instead. + fn close(mut self, folder: &Path, marked: bool, last: Vec>) -> Option<(PathBuf, u64)> { + let (mut texts, _) = self.tell(last); let SpillFile { path, mut out, decoding, saved, + told, } = self; + texts.push(decoding.finish()); + let length = texts.last().map_or(0, String::len); + // Its answer shows it whole: what was not written yet never is. + if marked && told + length <= PREVIEW_BYTES { + drop(out); + let _ = std::fs::remove_file(&path); + return None; + } let written = (|| { - out.write_all(decoding.finish().as_bytes())?; - out.flush()?; - out.get_ref().sync_all()?; + write_all_of(&mut out, &texts)?; + out.sync_all()?; std::fs::File::open(folder)?.sync_all() })(); if written.is_err() { @@ -4354,49 +4675,114 @@ impl SpillFile { } } +/// What a stream of a command the daemon lost while it ran left in its +/// file, `FOLDER/NAME-STREAM` as [`Spill`] names it: the text a result +/// shows of it, its first and last halves of a preview past one, and the +/// file's path. None where there is no such file the daemon wrote. Read +/// on a blocking worker, never through a link, a page at most. +pub fn retained_stream( + folder: &Path, + name: &str, + stream: &str, +) -> Option<(String, Option)> { + use std::io::{Read, Seek, SeekFrom}; + use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; + let path = folder.join(format!("{name}-{stream}")); + let mut file = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(&path) + .ok()?; + let found = file.metadata().ok()?; + // SAFETY: geteuid takes nothing and cannot fail. + let daemon = unsafe { libc::geteuid() }; + // As the daemon made it: a file of its own with no other name. + if !found.is_file() || found.nlink() != 1 || found.uid() != daemon { + return None; + } + let length = found.len(); + let text = |bytes: Vec| text_of(bytes); + // Within a preview the text is all of it, as a stream within one is + // shown whole, and names no file. + if length <= PREVIEW_BYTES as u64 { + let mut whole = Vec::with_capacity(length as usize); + file.take(PREVIEW_BYTES as u64) + .read_to_end(&mut whole) + .ok()?; + return Some((text(whole), None)); + } + let half = PREVIEW_BYTES / 2; + let mut head = vec![0; half]; + file.read_exact(&mut head).ok()?; + let mut tail = vec![0; half]; + file.seek(SeekFrom::End(-(half as i64))).ok()?; + file.read_exact(&mut tail).ok()?; + // Cut on characters: a head's last unfinished one goes, as does what + // the tail begins inside one. + head.truncate(half - unfinished_char(&head)); + let inside = tail + .iter() + .take(3) + .take_while(|&&b| b & 0xC0 == 0x80) + .count(); + tail.drain(..inside); + let omitted = length - head.len() as u64 - tail.len() as u64; + let shown = format!( + "{}\n[... {omitted} bytes omitted; {LOST_RETAINED}: see this result's artifacts and read them with the read tool ...]\n{}", + text(head), + text(tail) + ); + Some((shown, Some(path.to_str()?.to_owned()))) +} + +/// What a lost command's file holds, as its result says. +const LOST_RETAINED: &str = "what the daemon read of it before it ended is retained"; + /// Append a pipe's output to `captured` until it closes. What arrived stays -/// there if the read is cancelled, as it is at a shell timeout. +/// there if the read is cancelled, as it is at a shell timeout. Output +/// read before the stream's mark goes to its file at the mark, should the +/// command write nothing more by then. async fn capture(pipe: &mut (impl AsyncRead + Unpin), captured: &mut Captured) -> Result<()> { - let room = KEPT_END.saturating_sub(captured.head.len()); - if room > 0 { - match &mut captured.peek { - // Read as it comes, so a client looking sees it at once. - Some(peek) => { - let mut chunk = vec![0; room.min(64 * 1024)]; - while captured.head.len() < KEPT_END { - let room = (KEPT_END - captured.head.len()).min(chunk.len()); - let read = pipe.read(&mut chunk[..room]).await?; - if read == 0 { - return Ok(()); - } - captured.head.extend_from_slice(&chunk[..read]); - peek.feed(&chunk[..read]); - } + let mut chunk = vec![0; 64 * 1024]; + // Armed only while the stream has a mark or output waiting to go to + // its file: none for a stream with no file to go to. + let mut timer = std::pin::pin!(tokio::time::sleep(Duration::ZERO)); + let mut armed = None; + loop { + let deadline = captured.deadline(); + if deadline != armed { + if let Some(deadline) = deadline { + timer.as_mut().reset(deadline); } - None => { - (&mut *pipe) - .take(room as u64) - .read_to_end(&mut captured.head) - .await?; - if captured.head.len() < KEPT_END { - return Ok(()); + armed = deadline; + } + let read = tokio::select! { + biased; + read = pipe.read(&mut chunk) => read?, + () = &mut timer, if armed.is_some() => { + armed = None; + match captured.awaits_mark() { + true => captured.stream(true), + false => captured.flush(true), } + continue; } - } - } - let mut chunk = vec![0; 64 * 1024]; - loop { - let read = pipe.read(&mut chunk).await?; + }; if read == 0 { return Ok(()); } + let bytes = &chunk[..read]; + // Read as it comes, so a client looking sees it at once. if let Some(peek) = &captured.peek { - peek.feed(&chunk[..read]); + peek.feed(bytes); } if captured.spill.is_some() || captured.writer.is_some() { - captured.spill(&chunk[..read]).await; + captured.spill(bytes).await; + } + captured.store(bytes); + if captured.writer.is_some() { + captured.flush(false); } - captured.keep(&chunk[..read]); // Past the bound nothing more is shown, so a runaway writer is // drained slowly: the daemon's one thread serves every bot, and the // writer waits on the full pipe instead of spending it. @@ -4410,10 +4796,26 @@ async fn capture(pipe: &mut (impl AsyncRead + Unpin), captured: &mut Captured) - /// which bounds its drain to about 64 MiB/s. const DRAIN_PAUSE: Duration = Duration::from_millis(1); -/// How a shell command ended: on its own, or killed at its timeout. +/// Resolves true once the daemon's stop is said on `stopping`; never, should +/// no stop be said. +async fn said(stopping: &mut watch::Receiver) -> bool { + stopping.wait_for(|stopping| *stopping).await.is_ok() +} + +/// How a shell command ended: on its own, killed at its timeout, or +/// ended by the daemon's stop. pub enum Exit { Status(std::process::ExitStatus), TimedOut, + Stopped, +} + +/// What ended a running command's wait on it. +#[cfg(unix)] +enum Ended { + Exited(std::process::ExitStatus), + TimedOut, + Stopped, } /// bash, as other harnesses run commands, where it is installed; else sh. @@ -5187,6 +5589,12 @@ async fn shell( if let Some(peek) = peek { peek.runs_in(workspace); } + // The daemon's stop ends it, its output kept, as its timeout would; a + // command the stop came before never starts. + let mut stopping = registry.stopping.subscribe(); + if *stopping.borrow_and_update() { + return Err(not_started_by_shutdown()); + } let (mut process, ended) = sh(command, workspace, registry, environment, sandbox, false)?; let child = process .stdin(Stdio::null()) @@ -5222,8 +5630,8 @@ async fn shell( .ok_or(Error::new("shell_spawn_failed"))?; let waiting = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let (mut out, mut err) = ( - Captured::spilling(spill, "stdout", &waiting, peek), - Captured::spilling(spill, "stderr", &waiting, peek), + Captured::spilling(spill, "stdout", &waiting, peek, started), + Captured::spilling(spill, "stderr", &waiting, peek, started), ); let status = { let reads = @@ -5247,8 +5655,26 @@ async fn shell( done?; read = true; } - status = child.wait() => break Some(status?), - () = &mut deadline => break None, + status = child.wait() => break Ended::Exited(status?), + () = &mut deadline => break Ended::TimedOut, + true = said(&mut stopping) => { + // Asked to end, as a stop by its handle asks, what it + // writes meanwhile still read; the rest goes below. + terminate(group, sandbox.is_some()).await; + let grace = tokio::time::sleep(STOP_GRACE); + tokio::pin!(grace); + loop { + tokio::select! { + done = &mut reads, if !read => { + done?; + read = true; + } + _ = child.wait() => break, + () = &mut grace => break, + } + } + break Ended::Stopped; + } } }; // Finish cleanup before returning: what the command left in its @@ -5277,7 +5703,11 @@ async fn shell( } status }; - let exit = status.map_or(Exit::TimedOut, Exit::Status); + let exit = match status { + Ended::Exited(status) => Exit::Status(status), + Ended::TimedOut => Exit::TimedOut, + Ended::Stopped => Exit::Stopped, + }; let elapsed = started.elapsed(); // A stream's file is finished by its caller, once the command's slot // is given back: see `Captured::settle`. @@ -6050,19 +6480,26 @@ mod tests { } /// Text cut anywhere reads as the whole: a character cut at a piece's - /// end is finished by the next, whatever invalid bytes came before. + /// end is finished by the next, whatever invalid bytes came before, + /// each piece told in place or copied. #[test] fn a_stream_cut_inside_a_character_reads_as_the_whole() { let text = b"before\xff after\xc3\xa9 end \xf0\x9f\x98\x80 \xe2\x82"; let whole = String::from_utf8_lossy(text).into_owned(); for size in 1..=text.len() { - let mut decoding = Decoding::default(); - let mut out = String::new(); - for piece in text.chunks(size) { - out.push_str(&decoding.feed(piece)); + // Told in place or copied, alternately or not at all. + for owned in [0, 1, 2] { + let mut decoding = Decoding::default(); + let mut out = String::new(); + for (n, piece) in text.chunks(size).enumerate() { + out.push_str(&match (n + owned) % 2 == 1 || owned == 2 { + true => decoding.feed_owned(piece.to_vec()), + false => decoding.feed(piece), + }); + } + out.push_str(&decoding.finish()); + assert_eq!(out, whole, "in pieces of {size}, {owned}"); } - out.push_str(&decoding.finish()); - assert_eq!(out, whole, "in pieces of {size}"); } } /// A piece handed to a stream's writer while it has no room stays @@ -6263,4 +6700,123 @@ mod tests { assert_eq!(std::fs::read_dir(dir.join("outputs")).unwrap().count(), 0); std::fs::remove_dir_all(dir).unwrap(); } + /// A command past its first second goes to its file as it runs, what + /// it wrote before then first, so a daemon that dies leaves it; one + /// that ends within a preview's worth answers as before, its file gone. + #[cfg(unix)] + #[tokio::test] + async fn a_running_command_goes_to_its_file_after_its_first_second() { + let dir = std::env::temp_dir().join(format!("agent-marked-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("outputs")).unwrap(); + let registry = Registry::new("shell").unwrap(); + let spill = Spill { + folder: dir.join("outputs"), + name: "8-call".into(), + usable: Arc::new(|| true), + }; + let run = tokio::spawn(registry.foreground( + "echo first; sleep 1.6; echo second".into(), + dir.clone(), + Some(60_000), + Vec::new(), + None, + registry.place(), + tokio::sync::oneshot::channel().0, + Some(spill), + )); + let file = dir.join("outputs/8-call-stdout"); + tokio::time::sleep(Duration::from_millis(1300)).await; + assert_eq!(std::fs::read_to_string(&file).unwrap(), "first\n"); + // Nothing was written to stderr: it has no file. + assert!(!dir.join("outputs/8-call-stderr").exists()); + let outcome = run.await.unwrap().unwrap(); + assert!(outcome.files.is_empty()); + let value: serde_json::Value = serde_json::from_str(&outcome.output).unwrap(); + assert_eq!(value["stdout"], "first\nsecond\n"); + assert!(!file.exists()); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// The daemon's stop ends a running command with what it wrote, and + /// says the stop ended it; one the stop came before never starts. + #[cfg(unix)] + #[tokio::test] + async fn the_daemons_stop_ends_a_command_with_its_output() { + let registry = Registry::new("shell").unwrap(); + let run = tokio::spawn(registry.foreground( + "echo before; sleep 30; echo after".into(), + std::env::temp_dir(), + Some(60_000), + Vec::new(), + None, + registry.place(), + tokio::sync::oneshot::channel().0, + None, + )); + tokio::time::sleep(Duration::from_millis(300)).await; + let began = std::time::Instant::now(); + registry.end_background(); + let outcome = run.await.unwrap().unwrap(); + assert!(began.elapsed() < Duration::from_secs(2)); + let value: serde_json::Value = serde_json::from_str(&outcome.output).unwrap(); + assert_eq!( + (&value["stdout"], &value["error"], &value["exit_code"]), + (&json!("before\n"), &json!("daemon_shutdown"), &json!(null)) + ); + assert!(outcome.failed); + let refused = registry + .foreground( + "echo never".into(), + std::env::temp_dir(), + Some(60_000), + Vec::new(), + None, + registry.place(), + tokio::sync::oneshot::channel().0, + None, + ) + .await + .unwrap_err(); + assert_eq!(refused.code, "daemon_shutdown"); + } + + /// A lost command's file is read as the daemon wrote it: its ends past + /// a preview, cut on characters; a file with another name, or a link, + /// is not read. + #[cfg(unix)] + #[test] + fn a_lost_commands_file_shows_its_ends() { + let dir = std::env::temp_dir().join(format!("agent-lost-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("9-call-stdout"), "short\n").unwrap(); + assert_eq!( + retained_stream(&dir, "9-call", "stdout"), + Some(("short\n".to_owned(), None)) + ); + assert_eq!(retained_stream(&dir, "9-call", "stderr"), None); + // Three-byte characters, so each half's edge falls inside one. + let long = "€".repeat(40_000); + std::fs::write(dir.join("10-call-stdout"), &long).unwrap(); + let (shown, file) = retained_stream(&dir, "10-call", "stdout").unwrap(); + assert_eq!(file.as_deref(), dir.join("10-call-stdout").to_str()); + let (head, rest) = shown.split_once("\n[... ").unwrap(); + let (marker, tail) = rest.split_once(" ...]\n").unwrap(); + assert!(head.chars().all(|c| c == '€') && tail.chars().all(|c| c == '€')); + assert_eq!((head.len(), tail.len()), (32_766, 32_766)); + let omitted = 120_000 - head.len() - tail.len(); + assert_eq!( + marker, + format!( + "{omitted} bytes omitted; {LOST_RETAINED}: see this result's artifacts and read them with the read tool" + ) + ); + // A second name, or a link to it, is no file the daemon wrote. + std::fs::hard_link(dir.join("9-call-stdout"), dir.join("11-call-stdout")).unwrap(); + assert_eq!(retained_stream(&dir, "11-call", "stdout"), None); + std::os::unix::fs::symlink(dir.join("10-call-stdout"), dir.join("12-call-stdout")).unwrap(); + assert_eq!(retained_stream(&dir, "12-call", "stdout"), None); + std::fs::remove_dir_all(dir).unwrap(); + } } diff --git a/tests/test_wait.py b/tests/test_wait.py index 685160adb..07434a7a3 100644 --- a/tests/test_wait.py +++ b/tests/test_wait.py @@ -8,6 +8,7 @@ import threading import time import unittest +from pathlib import Path from bench.runtime_client import Client, node_item, poll, serve_args from bench.socket_client import SocketClient @@ -108,23 +109,106 @@ def background(request, command): self.assertLess(process.memory_info().rss - baseline, 8 * 1024 * 1024, phase) self.assertEqual(client.request('wait', handles=[pending], timeout_ms=0)['result']['pending'], [pending]) - def test_a_clean_stop_ends_a_running_background_command_and_records_it_lost(self): + def test_a_clean_stop_ends_a_running_background_command_with_what_it_wrote(self): client = self.client('echo,shell,wait') - client.request('create', bot='Bob', workspace=str(self.path)) + outputs = self.path / 'outputs' + client.request('create', bot='Bob', workspace=str(self.path), settings={'outputs': str(outputs)}) turn = client.request('submit', bot='Bob', request_id='bg', - prompt='bg:while [ ! -f finish ]; do sleep .01; done')['result']['message'] + prompt='bg:for i in $(seq 20); do echo line $i; sleep .1; done')['result']['message'] self.assertEqual(client.finished(turn)['data']['status'], 'completed') handle = self.tool_output(client, 'Bob', 'bg-1')['handle'] - # The stop ends the command and records its end itself, instead of - # leaving the row running for the next start to find. + time.sleep(1.5) + # The stop ends the command and records its end itself, with what it + # wrote, instead of leaving the row running for the next start. client.close() with sqlite3.connect(self.path / 'state.sqlite') as db: rows = db.execute('SELECT status,result FROM processes').fetchall() self.assertEqual([(status, json.loads(result)['error']) for status, result in rows], - [('finished', 'process_lost')]) + [('finished', 'daemon_shutdown')]) + again = self.client('echo,shell,wait') + result = again.request('wait', handles=[handle])['result']['results'][handle] + self.assertEqual((result['error'], result['exit_code'], result['success']), ('daemon_shutdown', None, False)) + lines = result['stdout'].splitlines() + # About 1.5 s of a line each 0.1 s, the last a whole line. + self.assertGreaterEqual(len(lines), 10, result) + self.assertLess(len(lines), 20, result) + self.assertEqual(lines, [f'line {n}' for n in range(1, len(lines) + 1)]) + # Shown whole, as a stream within a preview is: no file is kept. + self.assertEqual((list(outputs.iterdir()), 'files' in result), ([], False)) + + def test_a_killed_daemon_leaves_what_a_running_background_command_wrote(self): + client = self.client('echo,shell,wait') + outputs = self.path / 'outputs' + client.request('create', bot='Bob', workspace=str(self.path), settings={'outputs': str(outputs)}) + # 100,000 bytes at once, then a line each 0.1 s. + command = 'head -c 100000 /dev/zero | tr "\\0" a; echo; for i in $(seq 30); do echo line $i; sleep .1; done' + turn = client.request('submit', bot='Bob', request_id='bg', prompt='bg:' + command)['result']['message'] + self.assertEqual(client.finished(turn)['data']['status'], 'completed') + handle = self.tool_output(client, 'Bob', 'bg-1')['handle'] + time.sleep(1.5) + client.close(kill=True) again = self.client('echo,shell,wait') result = again.request('wait', handles=[handle])['result']['results'][handle] self.assertEqual(result['error'], 'process_lost') + # What went to the file by the kill: at least the first second's, + # written at once when the command passed its first second. + [file] = result['files'] + written = Path(file).read_text() + self.assertTrue(written.startswith('a' * 100000 + '\nline 1\n'), written[100000:]) + lines = written[100001:].splitlines() + self.assertGreaterEqual(len(lines), 8, written[100000:]) + self.assertEqual(lines, [f'line {n}' for n in range(1, len(lines) + 1)]) + # Past a preview, its ends are shown and the file named, as a + # finished command's are. + self.assertTrue(result['stdout'].startswith('a' * 32768 + '\n[... '), result['stdout'][32760:33000]) + self.assertIn('what the daemon read of it before it ended is retained', result['stdout']) + self.assertTrue(result['stdout'].endswith(f'line {len(lines)}\n'), result['stdout'][-200:]) + self.assertEqual((result['stderr'], result['artifacts']), ('', [f'{turn}/bg-1/stdout'])) + self.assertEqual(Path(file).parent, outputs) + + def test_a_killed_daemon_shows_a_short_lost_output_whole(self): + client = self.client('echo,shell,wait') + outputs = self.path / 'outputs' + client.request('create', bot='Bob', workspace=str(self.path), settings={'outputs': str(outputs)}) + turn = client.request('submit', bot='Bob', request_id='bg', prompt='bg:echo first; sleep 10')['result']['message'] + self.assertEqual(client.finished(turn)['data']['status'], 'completed') + handle = self.tool_output(client, 'Bob', 'bg-1')['handle'] + time.sleep(1.5) + self.assertEqual((outputs / f'{turn}-bg-1-stdout').read_text(), 'first\n') + client.close(kill=True) + again = self.client('echo,shell,wait') + result = again.request('wait', handles=[handle])['result']['results'][handle] + # Within a preview it is shown whole and names no file, as a + # finished command's is, and its file is gone. + self.assertEqual((result['error'], result['stdout'], result['stderr']), ('process_lost', 'first\n', '')) + self.assertNotIn('files', result) + self.assertEqual(list(outputs.iterdir()), []) + + def test_a_command_ending_within_its_first_second_never_touches_the_disk(self): + client = self.client('echo,shell,wait') + outputs = self.path / 'outputs' + # Each read by a wait: none is told in a turn of its own. + client.request('create', bot='Bob', workspace=str(self.path), + settings={'outputs': str(outputs), 'quiet_background': True}) + def ran(request, command): + turn = client.request('submit', bot='Bob', request_id=request, prompt='bg:' + command)['result']['message'] + self.assertEqual(client.finished(turn)['data']['status'], 'completed') + handle = self.tool_output(client, 'Bob', 'bg-1')['handle'] + return turn, client.request('wait', handles=[handle])['result']['results'][handle] + _, quick = ran('quick', 'echo hi; sleep .2') + self.assertEqual((quick['stdout'], quick['exit_code']), ('hi\n', 0)) + self.assertFalse(outputs.exists() and list(outputs.iterdir())) + # Past its first second with a preview's worth or less: shown whole, + # its file gone once it ends. + _, slow = ran('slow', 'echo hi; sleep 1.3; echo there') + self.assertEqual((slow['stdout'], 'files' in slow), ('hi\nthere\n', False)) + self.assertEqual(list(outputs.iterdir()), []) + # More than a preview: its file is the one a finished command's + # output is kept in, whole. + turn, kept = ran('kept', 'sleep 1.2; head -c 100000 /dev/zero | tr "\\0" b') + self.assertEqual(kept['files'], [str(outputs / f'{turn}-bg-1-stdout')]) + self.assertEqual(Path(kept['files'][0]).read_text(), 'b' * 100000) + self.assertIn('the full output is retained', kept['stdout']) def test_old_turn_outcomes_use_indexed_event_lookups(self): client = self.client() From 0a923a629d0ce485eb8339f859eeb3761791c06c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 05:45:27 +0000 Subject: [PATCH 2/2] Read lost output before parked waits restore; never wait on a pipe A turn parked on a background command a killed daemon lost was restored, and its result read, before the start put the command's kept output in that result: the recovery now runs first. A lost command's file opens without waiting, so a pipe put in its place is rejected rather than holding the start. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013jkdGFB8684xSdg7nKsRqk --- src/server/mod.rs | 12 +++++------- src/tools.rs | 12 +++++++++--- tests/test_wait.py | 16 ++++++++++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/server/mod.rs b/src/server/mod.rs index f8fd5f5a6..8d16f79c4 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -3264,6 +3264,11 @@ pub async fn run(config: Configuration) -> Result<()> { handles.clone(), )); } + // Background commands an earlier daemon lost while they ran answer + // with the output their files kept, before any wait reads them: the + // parked waits below among them. + let lost = store.op("take_lost", |db| Ok(db.take_lost())).await?; + turn::lost_outputs(&store, ®istry, lost).await?; // Turns parked before a restart keep waiting; their processes are gone. // Those parked on a closed pool wait for their time, not for handles. let mut wakes = Wakes::default(); @@ -3415,13 +3420,6 @@ pub async fn run(config: Configuration) -> Result<()> { .read("lifted_waiting", |db| db.lifted_waiting()) .await?; service.check_lifted(lifted); - // Background commands an earlier daemon lost while they ran answer - // with the output their files kept, before any wait reads them. - let lost = service - .store - .op("take_lost", |db| Ok(db.take_lost())) - .await?; - turn::lost_outputs(&service.store, &service.registry, lost).await?; // Detached commands an earlier daemon started run on: each is watched // again, and stopped by its handle, or its end is recorded now. let detached = service diff --git a/src/tools.rs b/src/tools.rs index 50c114659..93407d258 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -4688,9 +4688,10 @@ pub fn retained_stream( use std::io::{Read, Seek, SeekFrom}; use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; let path = folder.join(format!("{name}-{stream}")); + // Never waiting on what is not a file: a pipe put there opens at once. let mut file = std::fs::OpenOptions::new() .read(true) - .custom_flags(libc::O_NOFOLLOW) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) .open(&path) .ok()?; let found = file.metadata().ok()?; @@ -6782,8 +6783,8 @@ mod tests { } /// A lost command's file is read as the daemon wrote it: its ends past - /// a preview, cut on characters; a file with another name, or a link, - /// is not read. + /// a preview, cut on characters; a file with another name, a link or a + /// pipe is not read. #[cfg(unix)] #[test] fn a_lost_commands_file_shows_its_ends() { @@ -6817,6 +6818,11 @@ mod tests { assert_eq!(retained_stream(&dir, "11-call", "stdout"), None); std::os::unix::fs::symlink(dir.join("10-call-stdout"), dir.join("12-call-stdout")).unwrap(); assert_eq!(retained_stream(&dir, "12-call", "stdout"), None); + // Nor is a pipe, which is not waited on for a writer. + let fifo = std::ffi::CString::new(dir.join("13-call-stdout").to_str().unwrap()).unwrap(); + // SAFETY: a valid C string names the pipe to make. + assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0); + assert_eq!(retained_stream(&dir, "13-call", "stdout"), None); std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/tests/test_wait.py b/tests/test_wait.py index 07434a7a3..7fedeeee8 100644 --- a/tests/test_wait.py +++ b/tests/test_wait.py @@ -184,6 +184,22 @@ def test_a_killed_daemon_shows_a_short_lost_output_whole(self): self.assertNotIn('files', result) self.assertEqual(list(outputs.iterdir()), []) + def test_a_turn_parked_on_a_lost_command_gets_what_it_wrote(self): + client = self.client('echo,shell,wait') + outputs = self.path / 'outputs' + client.request('create', bot='Dave', workspace=str(self.path), settings={'outputs': str(outputs)}) + dave = client.request('submit', bot='Dave', request_id='d', + prompt='bgwait:echo early; sleep 10')['result']['message'] + client.receive(lambda m: m.get('event') == 'turn_waiting' and m.get('turn') == dave) + time.sleep(1.5) + client.close(kill=True) + client = self.client('echo,shell,wait') + # The wait restored at start reads the result with the output its + # file kept, not the bare loss. + self.assertEqual(client.finished(dave, timeout=15)['data']['status'], 'completed') + [result] = self.tool_output(client, 'Dave', 'wait-1')['results'].values() + self.assertEqual((result['error'], result['stdout']), ('process_lost', 'early\n')) + def test_a_command_ending_within_its_first_second_never_touches_the_disk(self): client = self.client('echo,shell,wait') outputs = self.path / 'outputs'