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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions bench/held/slow_sync.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,19 @@
// 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 <dlfcn.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>

Expand Down Expand Up @@ -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);
}
265 changes: 265 additions & 0 deletions bench/shell_streams.py
Original file line number Diff line number Diff line change
@@ -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()
68 changes: 68 additions & 0 deletions docs/DAEMON_MEASUREMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15215,3 +15215,71 @@ from its submit to its end):
against 264 ms with no shrink; fewer turns ended in that stretch (the
harness is one Python process, so turns per second here are not the
daemon's).

## 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.
Loading
Loading