From 893e12345c2458e70b333faedaaaaf8fbffb6932 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 17:22:24 -0300 Subject: A 9P monkey drives random requests at a throwaway session and checks the documented rules test/monkey9p.py starts pardes --detach with its own HOME, XDG dirs and runtime dir, speaks raw 9P (test/ninep.py) with a timeout on every reply and Tflush for held reads, and after each seeded operation checks that pardes is alive, the one-failure rule over a marker-delimited log window (with and without a follower), /index against /pane, and chunked against whole reads. Every run writes a replayable ops log; a failure is saved with its seed and step, shrunk by delta debugging over replays, and the run goes on in a fresh session. Teardown makes the fuzzer a subreaper and kills every process carrying the session's token. zig build monkey-9p -- --seed N --steps M | --replay F | --shrink F; a 150-step fixed-seed smoke run is part of fs-test. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 1958 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1958 insertions(+) create mode 100644 test/monkey9p.py (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py new file mode 100644 index 00000000..4c1732e5 --- /dev/null +++ b/test/monkey9p.py @@ -0,0 +1,1958 @@ +#!/usr/bin/env python3 +"""pardes 9P monkey: random 9P operations against a throwaway detached session. + + zig build monkey-9p -Dplatform=tty --prefix -- [--seed N] [--steps M] + zig build monkey-9p -Dplatform=tty --prefix -- --replay FILE + zig build monkey-9p -Dplatform=tty --prefix -- --shrink FILE + python3 test/monkey9p.py [same flags] + +A run starts `pardes --detach` with its own HOME, XDG dirs and a short +runtime dir in /tmp, speaks raw 9P to it (test/ninep.py), and for each +step asks a GENERATOR for one concrete operation, runs it, then runs every +INVARIANT. Everything random comes from --seed; every operation it ran is +written to /runs/seed-N/ops.jsonl, concrete but for pane and column +references ({p3}: the 4th serial of /index, mod its length, when the op +runs, so a shrunk sequence still names live panes), and `--replay` runs +the same requests again without the generator. A failure writes a bug record +(seed, step, the replayable operations since that session began) to +/bugs/, shrinks it by delta debugging over replays unless +--no-shrink, and the run carries on in a fresh session. + +Plug-in points: a generator is a function `(ctx, rng) -> op dict` under +@generator(weight); an op kind is a function `(sess, op) -> Result` under +@op_kind(name); an invariant is a function `(ctx, res) -> str | None` +under @invariant, returning why it failed. + +Safety: the session never sees PARDES_*, NINE_MOUNT or NAMESPACE; every +payload that could reach a shell is drawn from an alphabet with no path +or shell metacharacters (shell_safe), Edit text from a grammar without +sam's w/e/r/f/b/B/D/n/!//| commands, and nothing is ever written, +created or removed under /os or /src (the host filesystem). This process +makes itself a child subreaper, so every shell the session starts is its +descendant even after pardes dies, and teardown kills them all. +""" +import argparse +import collections +import ctypes +import hashlib +import json +import os +import random +import re +import select +import shutil +import signal +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from ninep import Client, string # noqa: E402 + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +DEFAULT_OUT = os.path.join(os.path.dirname(REPO), '.scratch', 'monkey9p') + +# 9P message types. +TWALK, TOPEN, TCREATE, TREAD, TWRITE, TCLUNK, TREMOVE, TSTAT, TFLUSH = 110, 112, 114, 116, 118, 120, 122, 124, 108 +RERROR = 107 +OREAD, OWRITE, ORDWR, OTRUNC = 0, 1, 2, 16 +DMDIR = 0x80000000 + +TIMEOUT = 5.0 # every reply, unless the op is a documented slow one +SLOW_TIMEOUT = 30.0 # Grep, Find, Dump, Restore, Tty, huge writes +HELD_WAIT = 0.1 # how long a read of a held file is let wait before Tflush +MSIZE = 65536 + 24 + + +class Hang(Exception): + """A 9P reply did not come within its timeout.""" + + +class Dropped(Exception): + """The server closed the connection (or reset it).""" + + +class Ended(Exception): + """pardes quit cleanly: exit 0, no crash file. Closing the session's last + pane quits it (fs.md: 'Closing the session's last pane quits pardes'), + and a terminal whose shell exits closes its pane, so this can follow any + step; the run starts a fresh session and carries on.""" + + +# -------------------------------------------------------------------------- +# Wire: raw 9P with per-request timeouts and Tflush for held reads. + +class Wire(Client): + def __init__(self, address, msize=MSIZE): + super().__init__(address, timeout=TIMEOUT, msize=msize) + self.next_fid = 100 + + def newfid(self): + self.next_fid += 1 + return self.next_fid + + def _send(self, kind, payload): + self.tag = (self.tag + 1) % 65535 + packet = struct.pack(' self.msize: + raise ValueError(f'harness bug: a {len(packet)}-byte request exceeds msize {self.msize}') + try: + self.socket.sendall(packet) + except socket.timeout: + raise Hang('send did not drain within the timeout') + except OSError as why: + raise Dropped(f'send: {why}') + return self.tag + + def _recv(self, timeout): + self.socket.settimeout(timeout) + try: + size, kind, tag = struct.unpack(' fn(sess, op) -> Result +INVARIANTS = [] # fn(ctx, res) -> str | None + + +def generator(weight): + def wrap(fn): + GENERATORS.append((weight, fn)) + return fn + return wrap + + +def op_kind(name): + def wrap(fn): + OPS[name] = fn + return fn + return wrap + + +def invariant(fn): + INVARIANTS.append(fn) + return fn + + +def host_path(path): + """Guard: nothing mutating ever touches the served host tree.""" + parts = split(path) + return bool(parts) and parts[0] in (b'os', b'src') + + +def is_held(path): + return (path.rstrip('/') == '/log' or path.endswith('/event') or + path.endswith('/pty/data') or path.endswith('/pty/run')) + + +def slow(data): + return len(data) > 65536 or any(w in data for w in (b'Grep', b'Find', b'Dump', b'Restore', b'Tty', b'Edit')) + + +# -------------------------------------------------------------------------- +# Op kinds: each takes a concrete op (what the ops log holds) and runs it. + +def dec(s): + return s.encode('latin-1') + + +def enc(b): + return b.decode('latin-1') + + +@op_kind('write') +def op_write(sess, op): + """open(path, mode); write data in the given chunk sizes; clunk.""" + res = Result() + path, data, mode = op['path'], dec(op['data']), op.get('mode', OWRITE) + if host_path(path): + res.note = 'refused by guard: host tree' + return res + w = sess.wire + fid, err = w.walk_names(split(path)) + if fid is None: + res.add('walk', path, False, err) + return res + timeout = SLOW_TIMEOUT if slow(data) else TIMEOUT + ok, body = w.call(TOPEN, struct.pack(' 1: + n += 1 + else: + return + if n: + res.add('allow', path, True, n) + + +def open_kind(path, mode): + """An open the rule names: pane/new's (it makes a pane) and a truncation + ('every write or truncation the tree refused'); others are 'open'.""" + if path.rstrip('/') == '/pane/new' and not mode & 3: + return 'open-new' + if mode & OTRUNC and mode & 3: + return 'trunc' + return 'open' + + +def chunking(spec, n, cap): + if n == 0: + return [0] + if spec == 'bytes': + return [1] * n + if isinstance(spec, list): + out, total = [], 0 + for s in spec: + s = max(1, min(s, cap, n - total)) + out.append(s) + total += s + if total >= n: + return out + while total < n: + s = min(cap, n - total) + out.append(s) + total += s + return out + out, total = [], 0 + while total < n: + s = min(cap, n - total) + out.append(s) + total += s + return out + + +@op_kind('read') +def op_read(sess, op): + """open(path, OREAD); read from offset in chunks of count until EOF or cap.""" + res = Result() + path, count, offset = op['path'], op.get('count', 8192), op.get('offset', 0) + w = sess.wire + fid, err = w.walk_names(split(path)) + if fid is None: + res.add('walk', path, False, err) + return res + mode = op.get('mode', OREAD) + ok, body = w.call(TOPEN, struct.pack('.\\*?![]{}\'"') + + +def shell_safe(data): + """No path or shell metacharacters, whatever else it holds.""" + return bytes(b for b in data if b not in UNSAFE) + + +RUNES = ['é', 'é', '日本', '\U0001f600', 'Δ', ' ', '​', '\u0080', '\u009f'] +ODD = [b'', b'\n', b'\r\n', b'\0', b'\xff', b'\xfe\xff', b'\xe6\x97', b'\xc0\x80', b'\x1b[2J', b'\x7f', b'\t', + b'\n\n\n', b' ', b' \n'] +WORDS = [b'alpha', b'beta', b'foo', b'bar', b'x', b'hello', b'zz', b'0', b'1', b'-1', b'99999999999', + b'on', b'off', b'follow', b'follow new', b'lock', b'unlock', b'clean', b'dirty', b'show', + b'dot=addr', b'addr=dot', b'limit=addr', b'nomark', b'mark', b'get', b'put', b'del', b'delete', + b'name', b'cleartag', b'answer', b'answer -', b'size 80 24', b'size 20 6', b'size 5000 5000', + b'winsize 80 24', b'winsize 0 0', b'sig INT', b'sig TERM', b'sig HUP', b'sig KILL', b'sig BOGUS', + b'exec', b'Placement acme', b'Placement pardes', b'Wrap on', b'Wrap off'] +SHELL_LINES = [b'true', b'false', b'echo hi', b'echo m9p', b'sleep 1', b'ls', b'cat nonexist', + b'printf abc', b'exit 3', b'seq 1 2000', b'yes | head -n 3000', b'date', b'pwd', b'env | wc'] +DENY = {'Exit', 'Attach', 'Detach', 'Mount', 'Unmount', 'Tty9p', 'ClipYank', 'ClipYankMain', 'ClipPaste', + 'ClipPasteBefore', 'ClipReplace', 'Shell', 'ThemeFile', 'EffectCode', 'Help', 'Tutor', 'Changelog', + 'Rename', 'Hover', 'CodeAction', 'SelectRefs', 'Symbols', 'Diagnostics', 'WsDiagnostics', 'Callers', + 'Callees', 'Supertypes', 'Subtypes', 'WsSymbols', 'Lspinfo', 'Lspwhy', 'Restore'} +BUILTINS = ['Look', 'Exec', 'Kill', 'Dump', 'Msg', 'NextColor', 'Themes', 'DumpThemes', 'TreeContext', 'PdfFit', + 'PdfTint', 'PdfSections', 'Petscii', 'Palette', 'Ascii', 'Save', 'New', 'Newcol', 'Del', 'Filter', + 'Mode', 'Togglettymode', 'Edit', 'Undo', 'Redo', 'Collapse', 'Delcol', 'DelAbove', 'DelBelow', 'Tty', + 'Repl', 'Joincol', 'Config', 'LocationsConfig', 'Messages', 'Mini', 'Find', 'Grep', 'Left', 'Down', + 'Up', 'Right', 'Back', 'Forward', 'Last', 'Recent', 'Jumplist', 'Colors', 'Wrap', 'Tagbottom', 'Debug', + 'FocusTint', 'Verbose', 'Motion', 'InactiveDim', 'DumpDir', 'Theme', 'Placement', 'BootShell', + 'LookWord', 'Get', 'Put', 'Undo', 'Redo', 'Zerox', 'Snarf', 'Paste', 'Cut', 'Sort', 'Font', 'Local'] +PANE_FILES = ['name', 'body', 'tag', 'ctl', 'addr', 'dot', 'limit', 'data', 'xdata', 'sel', 'dirty', 'mark', + 'scroll', 'errors', 'event', 'look', 'exec', 'tagexec', 'pty', 'pty/run', 'pty/data', 'pty/ctl', + 'pty/status'] +ROOT_FILES = ['README', 'index', 'status', 'focus', 'ctl', 'commands', 'recent', 'look', 'exec', 'log', 'screen', + 'listeners', 'layout', 'tag', 'tagexec', 'pane', 'pane/new', 'col', ''] +COL_FILES = ['tag', 'ctl', 'exec'] +WRITABLE = ['ctl', 'exec', 'look', 'tag', 'tagexec', 'focus', 'body', 'data', 'xdata', 'addr', 'dot', 'limit', + 'name', 'sel', 'dirty', 'mark', 'scroll', 'errors', 'event', 'pty/run', 'pty/data', 'pty/ctl', 'log'] + + +class Ctx: + """What the generators and invariants see.""" + + def __init__(self, seed): + self.seed = seed + self.rng = random.Random(seed) + self.sess = None + self.step = 0 + self.serials = [] + self.cols = [] + self.gone = [] # serials seen and since closed (stale) + self.next_h = 0 + self.last_index = b'' + self.verbose = False + + +def pick_serial(ctx, rng): + """A live pane as a token, {pN}: the Nth serial of /index (mod its + length) when the op runs, so a shrunk replay still names a pane that + exists; or a stale or impossible serial, literally.""" + r = rng.random() + if ctx.serials and r < 0.85: + return '{p%d}' % rng.randrange(64) + if ctx.gone and r < 0.95: + return rng.choice(ctx.gone) + return rng.choice([0, 1, 999, 4294967295, 4294967296, -1]) + + +def pick_col(ctx, rng): + if ctx.cols and rng.random() < 0.85: + return '{c%d}' % rng.randrange(16) + return rng.choice([0, 99, 4294967295]) + + +def odd_bytes(rng, n): + out = bytearray() + while len(out) < n: + r = rng.random() + if r < 0.5: + out += rng.choice(WORDS) + elif r < 0.7: + out += rng.choice(RUNES).encode() + elif r < 0.9: + out += rng.choice(ODD) + else: + out.append(rng.randrange(256)) + if rng.random() < 0.5: + out += b' ' + return bytes(out[:n]) + + +def payload(rng, maxlen=64): + """Plain or odd bytes, sometimes huge, with or without a newline.""" + r = rng.random() + if r < 0.35: + data = rng.choice(WORDS) + elif r < 0.55: + data = odd_bytes(rng, rng.randrange(0, maxlen)) + elif r < 0.62: + data = rng.choice(ODD) + elif r < 0.66: + data = (rng.choice(WORDS) + b' ') * rng.randrange(100, 20000) # huge + elif r < 0.7: + data = b'x' * rng.choice([255, 256, 1023, 1024, 1025, 65535, 65536, 70000]) + else: + data = rng.choice(WORDS) + b' ' + odd_bytes(rng, rng.randrange(0, 12)) + if rng.random() < 0.6 and not data.endswith(b'\n'): + data += rng.choice([b'\n', b'\n', b'\r\n', b'\n\n']) + return shell_safe(data) + + +def weird_name(rng): + r = rng.random() + if r < 0.3: + return 'x' * rng.choice([255, 256, 300, 1000]) + if r < 0.5: + return rng.choice(['..', '.', '', ' ', 'new', 'NEW', '01', '1 ', '\n', 'a\0b']) + if r < 0.7: + return enc(rng.choice(RUNES).encode()) + return enc(bytes(rng.randrange(1, 256) for _ in range(rng.randrange(1, 20))).replace(b'/', b'_')) + + +def random_path(ctx, rng, writable=False): + r = rng.random() + if r < 0.6: + f = rng.choice(WRITABLE if writable else PANE_FILES) + return f'/pane/{pick_serial(ctx, rng)}/{f}' + if r < 0.75: + f = rng.choice(['ctl', 'exec', 'look', 'tag', 'tagexec', 'focus', 'log'] if writable else ROOT_FILES) + return '/' + f + if r < 0.85: + return f'/col/{pick_col(ctx, rng)}/{rng.choice(COL_FILES)}' + if r < 0.93: + return f'/pane/{pick_serial(ctx, rng)}/{weird_name(rng)}' + return '/' + '/'.join(weird_name(rng) for _ in range(rng.randrange(1, 4))) + + +def data_for(ctx, rng, path): + """Payload a file is likely to take, often mutated.""" + base = path.rsplit('/', 1)[-1] + r = rng.random() + if r < 0.25: + return payload(rng) + if base in ('addr', 'dot', 'limit', 'sel'): + return address(rng) + if base == 'ctl' and path.endswith('pty/ctl'): + return rng.choice([b'sig INT\n', b'sig TERM\n', b'sig HUP\n', b'sig QUIT\n', b'sig KILL\n', + b'winsize 80 24\n', b'winsize 1 1\n', b'winsize 99999 3\n', b'exec\n', b'sig\n']) + if base in ('ctl', 'exec', 'tagexec'): + return builtin_line(ctx, rng, path) + if base == 'run': + return shell_safe(rng.choice(SHELL_LINES)) + b'\n' + if base == 'data' and '/pty/' in path: + return shell_safe(rng.choice(SHELL_LINES)) + rng.choice([b'\r', b'\n', b'', b'\x03', b'\x04']) + if base == 'event': + return event_record(rng) + if base == 'focus': + return str(pick_serial(ctx, rng)).encode() + rng.choice([b'\n', b'']) + if base == 'look': + return shell_safe(rng.choice([b'alpha', b'alpha.txt', b'alpha.txt:2', b'utf8.txt:#3', b'nothere', + b'bad.txt', b'crlf.txt:1', b'gamma', b'beta'])) + b'\n' + if base in ('dirty', 'mark', 'scroll'): + return rng.choice([b'0', b'1', b'0\n', b'1\n', b'2\n', b'', b'yes\n']) + if base == 'log': + return rng.choice([b'follow\n', b'follow new\n', b'follow', b'nope\n']) + return payload(rng, 200) + + +def mutate(rng, data, rounds=None): + data = bytearray(data) + for _ in range(rounds or rng.randrange(1, 4)): + if not data: + data += rng.choice(WORDS) + continue + i = rng.randrange(len(data)) + r = rng.random() + if r < 0.3: + del data[i] + elif r < 0.55: + data[i:i] = shell_safe(rng.choice(ODD) or b'\0') + elif r < 0.75: + j = rng.randrange(i, len(data) + 1) + data[i:i] = data[i:j] + else: + data[i:i] = rng.choice(RUNES).encode() + return bytes(data) + + +def builtin_line(ctx, rng, path): + word = rng.choice(BUILTINS).encode() + r = rng.random() + if r < 0.4: + line = word + elif r < 0.7: + line = word + b' ' + rng.choice(WORDS) + elif r < 0.8: + line = b'Edit ' + edit_command(rng) + return line + b'\n' # Edit text keeps its / delimiters + else: + line = mutate(rng, word + b' ' + rng.choice(WORDS)) + if rng.random() < 0.1: + line = shell_safe(rng.choice(SHELL_LINES)) + if rng.random() < 0.8: + line += b'\n' + return shell_safe(line) + + +# sam's commands without the ones that reach files or shells. +EDIT_TEXT = b'abcdghijklmopqstuvxyz0123456789 ACEGHIJKLMNOPQRSTUVWXYZ_-' + + +def edit_text(rng): + s = bytes(rng.choice(EDIT_TEXT) for _ in range(rng.randrange(0, 8))) + if rng.random() < 0.3: + s += rng.choice(RUNES).encode() + return s + + +def regex(rng): + parts = [edit_text(rng) or b'a'] + for _ in range(rng.randrange(0, 4)): + parts.append(rng.choice([b'(a|b)', b'^', b'$', b'[a-z]', b'[^ ]', b'.*', b'\\n', + '[é日]'.encode(), b'x+', b'(', b'[', b'\\', b'a**', + b'(((a)))', b'[z-a]', (b'a|' * rng.randrange(1, 300)) + b'b'])) + parts.append(edit_text(rng)) + return b''.join(parts) + + +def address(rng): + """sam addresses: valid, near-valid and garbage.""" + simple = [b'0', b'$', b'.', b',', b';', b'#0', b'#3', b'#99999', b'1', b'2', b'3:2', b'1:1', b'0:0', + b'#1,#2', b'1,$', b'2,1', b'-', b'+', b'-1', b'+2', b'#-1', b'99999', b'1:99', b'?a?'] + r = rng.random() + if r < 0.4: + a = rng.choice(simple) + elif r < 0.7: + a = b'/' + regex(rng) + b'/' + elif r < 0.85: + a = rng.choice(simple) + rng.choice([b',', b';', b'+', b'-']) + rng.choice(simple + [b'/a/']) + else: + a = mutate(rng, rng.choice(simple) + b'/' + regex(rng) + b'/') + return a + rng.choice([b'', b'\n']) + + +def edit_command(rng): + t = lambda: edit_text(rng) # noqa: E731 + cmds = [lambda: b',x/' + regex(rng) + b'/c/' + t() + b'/', + lambda: b's/' + regex(rng) + b'/' + t() + b'/g', + lambda: b'a/' + t() + b'/', + lambda: b'i/' + t() + b'/', + lambda: b'c/' + t() + b'/', + lambda: b'd', + lambda: b',d', + lambda: b',y/' + regex(rng) + b'/d', + lambda: b',x/' + regex(rng) + b'/g/' + regex(rng) + b'/d', + lambda: b',x/' + regex(rng) + b'/v/' + regex(rng) + b'/c/' + t() + b'/', + lambda: b'1,2m$', + lambda: b'1t0', + lambda: b'k', + lambda: b'p', + lambda: b'=', + lambda: b'u', + lambda: b'{\na/' + t() + b'/\ni/' + t() + b'/\n}', + lambda: b',x/\\n/a/' + t() + b'/', + lambda: b'0,$s/' + regex(rng) + b'/&&/g'] + cmd = rng.choice(cmds)() + if rng.random() < 0.4: + cmd = address(rng).rstrip(b'\n') + cmd + if rng.random() < 0.2: + cmd = mutate(rng, cmd) + # Mutation never introduces a banned command letter or shell char. + cmd = bytes(b for b in cmd if b not in b'werfbBDn!<>|') + return cmd + + +def event_record(rng): + origin = rng.choice(b'EFKMZ') + action = rng.choice(b'xXlLiIdDZ') + q0, q1 = rng.choice([0, 1, 5, 10]), rng.choice([0, 2, 7, 1 << 40, -1]) + rec = bytes([origin, action]) + f'{q0} {q1} {rng.choice([0, 1, 2, 8])} '.encode() + text = shell_safe(edit_text(rng)) + rec += str(len(text)).encode() + b' ' + text + b'\n' + if rng.random() < 0.3: + rec = mutate(rng, rec) + return shell_safe(rec) + + +def new_handle(ctx): + ctx.next_h += 1 + return f'h{ctx.next_h}' + + +@generator(30) +def gen_write(ctx, rng): + path = random_path(ctx, rng, writable=True) + data = data_for(ctx, rng, path) + mode = rng.choice([OWRITE, OWRITE, ORDWR, OWRITE | OTRUNC, ORDWR | OTRUNC, OREAD]) + r = rng.random() + chunks = 'bytes' if r < 0.08 and len(data) <= 64 else ( + [rng.randrange(1, 16) for _ in range(4)] if r < 0.15 else 'whole') + op = {'op': 'write', 'path': path, 'data': enc(data), 'mode': mode, 'chunks': chunks} + if rng.random() < 0.05: + op['offset'] = rng.choice([1, 100, 1 << 40]) + return op + + +@generator(14) +def gen_read(ctx, rng): + path = random_path(ctx, rng) + return {'op': 'read', 'path': path, 'count': rng.choice([1, 2, 7, 64, 200, 8192, 1 << 20]), + 'offset': rng.choice([0, 0, 0, 1, 3, 100, 1 << 33]), 'reads': rng.choice([1, 2, 8])} + + +@generator(4) +def gen_stat(ctx, rng): + path = random_path(ctx, rng) + if rng.random() < 0.2: + path = '/os/' + rng.choice(['etc', 'etc/hosts', 'nonexistent', 'x' * 300]) + return {'op': 'stat', 'path': path} + + +@generator(5) +def gen_newpane(ctx, rng): + if rng.random() < 0.7: + return {'op': 'read', 'path': '/pane/new', 'count': 64, 'reads': 1} + return {'op': 'hold', 'h': new_handle(ctx), 'path': '/pane/new', 'mode': rng.choice([OREAD, ORDWR])} + + +@generator(2) +def gen_remove(ctx, rng): + r = rng.random() + if r < 0.6: + path = f'/pane/{pick_serial(ctx, rng)}' + elif r < 0.85: + path = f'/col/{pick_col(ctx, rng)}' + else: + path = random_path(ctx, rng) + return {'op': 'remove', 'path': path} + + +@generator(2) +def gen_create(ctx, rng): + where = rng.choice(['/col', '/pane', '/', f'/pane/{pick_serial(ctx, rng)}']) + return {'op': 'create', 'path': where, 'name': weird_name(rng) if rng.random() < 0.5 else 'new', + 'perm': rng.choice([0o666, DMDIR | 0o777]), 'mode': rng.choice([OREAD, OWRITE])} + + +@generator(2) +def gen_clear_window(ctx, rng): + """Down to the empty window (every pane closed), sometimes rebuilt.""" + keep = rng.choice(ctx.serials) if ctx.serials and rng.random() < 0.8 else None + ops = [{'op': 'remove', 'path': f'/pane/{s}'} for s in ctx.serials if s != keep] + if rng.random() < 0.5: + ops += [{'op': 'remove', 'path': f'/col/{c}'} for c in ctx.cols] + if rng.random() < 0.6: + ops.append({'op': 'read', 'path': '/pane/new', 'count': 64, 'reads': 1}) + return {'op': 'seq', 'ops': ops} + + +@generator(6) +def gen_hold(ctx, rng): + held = [h for h in (ctx.sess.handles if ctx.sess else {})] + r = rng.random() + if not held or r < 0.35: + path = random_path(ctx, rng) + if rng.random() < 0.3: + path = rng.choice(['/log', f'/pane/{pick_serial(ctx, rng)}/event', '/screen', '/index', + f'/pane/{pick_serial(ctx, rng)}/ctl']) + return {'op': 'hold', 'h': new_handle(ctx), 'path': path, 'mode': rng.choice([OREAD, ORDWR, OWRITE])} + h = rng.choice(held) + path = ctx.sess.handles[h][1] + if r < 0.6: + return {'op': 'hwrite', 'h': h, 'data': enc(data_for(ctx, rng, path))} + if r < 0.85: + return {'op': 'hread', 'h': h, 'count': rng.choice([1, 16, 8192]), + 'offset': rng.choice([None, None, 0, 5])} + return {'op': 'clunk', 'h': h} + + +@generator(6) +def gen_shell(ctx, rng): + s = pick_serial(ctx, rng) + line = shell_safe(rng.choice(SHELL_LINES)) + r = rng.random() + if r < 0.25: + return {'op': 'write', 'path': f'/pane/{s}/ctl', 'data': enc(b'Tty\n'), 'mode': OWRITE} + if r < 0.45: + return {'op': 'write', 'path': f'/pane/{s}/pty/run', 'data': enc(line + b'\n'), 'mode': ORDWR} + if r < 0.6: + return {'op': 'write', 'path': f'/pane/{s}/pty/data', 'data': enc(line + b'\r'), 'mode': OWRITE} + if r < 0.75: + return {'op': 'write', 'path': f'/pane/{s}/pty/ctl', + 'data': enc(rng.choice([b'sig INT\n', b'sig TERM\n', b'sig KILL\n', b'sig HUP\n'])), 'mode': OWRITE} + return {'op': 'write', 'path': rng.choice(['/exec', f'/pane/{s}/exec']), 'data': enc(line + b'\n'), + 'mode': OWRITE} + + +@generator(6) +def gen_edit(ctx, rng): + s = pick_serial(ctx, rng) + path = rng.choice([f'/pane/{s}/ctl', f'/pane/{s}/exec', '/exec']) + return {'op': 'write', 'path': path, 'data': enc(b'Edit ' + edit_command(rng) + b'\n'), 'mode': OWRITE} + + +@generator(8) +def gen_addr(ctx, rng): + s = pick_serial(ctx, rng) + ops = [{'op': 'write', 'path': f'/pane/{s}/addr', 'data': enc(address(rng)), 'mode': OWRITE}] + r = rng.random() + if r < 0.4: + ops.append({'op': 'read', 'path': f'/pane/{s}/{rng.choice(["xdata", "data", "addr", "dot"])}', + 'count': 8192, 'reads': 2}) + elif r < 0.7: + ops.append({'op': 'write', 'path': f'/pane/{s}/{rng.choice(["data", "xdata"])}', + 'data': enc(payload(rng, 20)), 'mode': rng.choice([OWRITE, OWRITE | OTRUNC])}) + return {'op': 'seq', 'ops': ops} + + +@generator(3) +def gen_tag(ctx, rng): + path = rng.choice([f'/pane/{pick_serial(ctx, rng)}/tag', '/tag', f'/col/{pick_col(ctx, rng)}/tag']) + return {'op': 'write', 'path': path, 'data': enc(payload(rng, 40)), + 'mode': rng.choice([OWRITE, OWRITE | OTRUNC])} + + +@generator(3) +def gen_event(ctx, rng): + s = pick_serial(ctx, rng) + return {'op': 'hold', 'h': new_handle(ctx), 'path': f'/pane/{s}/event', 'mode': ORDWR} + + +@generator(2) +def gen_dump_restore(ctx, rng): + r = rng.random() + if r < 0.5: + return {'op': 'write', 'path': '/ctl', 'data': enc(rng.choice([b'Dump\n', b'Dump', b'Dump m9pdump\n'])), + 'mode': OWRITE} + return {'op': 'restore', 'data': enc(rng.choice([b'Restore\n', b'Restore\n', b'Restore m9pdump\n', + b'Restore nothere\n']))} + + +@generator(3) +def gen_host(ctx, rng): + name = rng.choice(list(FIXTURES) + ['fresh.txt']) + if rng.random() < 0.5: + return {'op': 'host', 'action': 'rm', 'name': name} + return {'op': 'host', 'action': 'write', 'name': name, 'data': enc(payload(rng, 100))} + + +@generator(3) +def gen_look_fixture(ctx, rng): + name = rng.choice(list(FIXTURES) + ['fresh.txt']) + suffix = rng.choice([b'', b':2', b':#4', b':1:3', b':/beta/']) + return {'op': 'write', 'path': rng.choice(['/look', f'/pane/{pick_serial(ctx, rng)}/look']), + 'data': enc(name.encode() + suffix + b'\n'), 'mode': OWRITE} + + +# -------------------------------------------------------------------------- +# Log window: the records one step caused, between two unique markers. + +MARK = re.compile(r'unknown control message "(m9p-mark-\d+)"') + + +def write_marker(sess, step): + """An unknown ctl word logs `err - ctl: unknown control message ""`.""" + word = f'm9p-mark-{step}' + ok, why = sess.wire.write_path('/ctl', word.encode() + b'\n') + if ok: + return None, 'marker write was taken' + prev, sess.marker = sess.marker, word + if sess.follower is not None: + end = sess.follower.wait_for(f'"{word}"') + if end is None: + return None, 'marker record never reached the follower' + lines = sess.follower.lines[:end] + start = 0 + if prev is not None: + for i in range(len(lines) - 1, -1, -1): + if f'"{prev}"' in lines[i]: + start = i + 1 + break + else: + return None, None + window = lines[start:] + del sess.follower.lines[:end] + return window, None + lines = sess.wire.read_path('/log').decode(errors='replace').splitlines() + end = next((i for i in range(len(lines) - 1, -1, -1) if f'"{word}"' in lines[i]), None) + if end is None: + return None, 'marker record missing from /log' + if prev is None: + return None, None + start = next((i for i in range(end - 1, -1, -1) if f'"{prev}"' in lines[i]), None) + if start is None: + return None, None # the ring moved past it + return lines[start + 1:end], None + + +COUNT = re.compile(r'^(.*) \(x(\d+)\)$') + + +def occurrences(lines, kind): + """Records of `kind` (err|msg), counting `(xN)` repeats (fs.md: a record said + again is counted; a follower sees each count as a line of its own).""" + out, last_text, last_n = [], None, 0 + for line in lines: + if not line.startswith(kind + ' '): + last_text = None + continue + m = COUNT.match(line) + text, n = (m.group(1), int(m.group(2))) if m else (line, 1) + if text == last_text: + new = n - last_n + else: + new = n + out.extend([text] * max(new, 0)) + last_text, last_n = text, n + return out + + +# -------------------------------------------------------------------------- +# Invariants: small, cheap, each with its doc citation. + +@invariant +def alive(ctx, res): + """Never crashes or panics (src/crash.zig: a panic leaves its crash file).""" + if not ctx.sess.alive(): + return f'pardes died (exit {ctx.sess.proc.returncode})' + if ctx.sess.has_crash_file(): + return 'crash file written: ' + ctx.sess.crash_text()[-2000:] + return None + + +@invariant +def one_failure_rule(ctx, res): + """fs.md 'One rule for what fails': a write fails whenever what it asked + for fails ... and logs its reason exactly once, as `err : + `, with no `msg` for it. What is not a failure: a look that finds + nothing answers nothing and logs one `err`, the write succeeding.""" + if res.window is None or res.hung_up: + return None + writes = res.writes() + # A refused open with OTRUNC may be refused for the open, not the + # truncation (event's `file in use`): allowed an err or none, below. + failed = [w for w in writes if w[2] is False and w[0] != 'trunc'] + errs = occurrences(res.window, 'err') + msgs = occurrences(res.window, 'msg') + # Only for a write that succeeded: a failed one logs its one err. + failed_paths = {w[1] for w in failed} + allowed = sum(r[3] for r in res.requests if r[0] == 'allow' and r[1] not in failed_paths) + # fs.md 'A write of command lines ... what is left when it closes runs at + # the close ... and its failure is in the log alone'. + closes = [r for r in res.requests if r[0] == 'close-runs'] + # Refused opens (other than pane/new), removes and creates are not named + # by the rule: allow an err or none. + other = [r for r in res.requests if r[2] is False and ( + r[0] in ('remove', 'create', 'trunc') or r[0] == 'open' and r[1].rstrip('/') != '/pane/new')] + lo, hi = len(failed), len(failed) + allowed + len(closes) + len(other) + if not lo <= len(errs) <= hi: + return (f'{len(failed)} failed write(s) logged {len(errs)} err record(s) ' + f'(allowed {lo}..{hi}); failed={[(w[0], w[1], w[3]) for w in failed]} window={res.window}') + if failed and msgs: + return f'a failed write also logged msg: {msgs}; failed={[(w[1], w[3]) for w in failed]}' + return None + + +LINE_FILES = ('look', 'exec', 'tagexec', 'ctl') + + +@invariant +def close_runs_only_line_files(ctx, res): + """fs.md: 'A write of command lines -- to look, exec, tagexec, a ctl of the + root, a pane or a column, or a column's exec -- runs each line once it is + whole ... what is left when it closes runs at the close'. Another file + that fails only at its close breaks 'a write fails whenever what it asked + for fails' (or the list is short).""" + if res.window is None: + return None + closes = [r[1] for r in res.requests if r[0] == 'close-runs'] + failed_files = {w[1].rsplit('/', 1)[-1] for w in res.writes() if w[2] is False} + for line in occurrences(res.window, 'err'): + m = re.match(r'err \S+ ([^:]+):', line) + if not m: + continue + name = m.group(1).rsplit('/', 1)[-1] + if name in LINE_FILES or name in failed_files: + continue + for path in closes: + if path.rsplit('/', 1)[-1] == name: + return f'a write to {name} with no newline was answered, then failed at the close: {line}' + return None + + +@invariant +def index_matches_pane_dirs(ctx, res): + """fs.md /index: one line per pane; /pane// each pane's directory.""" + w = ctx.sess.wire + first = w.read_path('/index') + fid, err = w.walk_names([b'pane']) + if fid is None: + return f'walking /pane failed: {err}' + ok, _ = w.call(TOPEN, struct.pack(' {"ok" if r[2] else ("held" if r[2] is None else "Rerror")}' + f'{": " + str(r[3]) if r[3] else ""}') + for line in window or []: + print(f' log: {line}') + for check in INVARIANTS: + problem = check(ctx, res) + if problem: + raise Failure(check.__name__, problem, ctx.step) + # The column list, for the generators. + fid, err = sess.wire.walk_names([b'col']) + if fid is not None: + sess.wire.call(TOPEN, struct.pack(' deadline: + return False + budget[0] -= 1 + nonlocal sig + f = self.execute([{'op': 'fresh', 'follower': follower}] + candidate, run_dir) + if f is None: + return False + if sig is None: + if kind is not None and f.kind != kind: + return False + sig = f.signature() + return True + return f.signature() == sig + + if not fails(body): + # One more try with the other log mode, then give up. + follower = not follower + if not fails(body): + header['shrink'] = 'did not reproduce on replay' + write_ops(path, header, ops) + print(f' not reproduced on replay: {path}', flush=True) + return + small = ddmin(body, fails) + # Then shrink each op's payload. + small = shrink_payloads(small, fails) + header['shrink'] = f'{len(body)} -> {len(small)} ops' + out = path.replace('.jsonl', '.min.jsonl') + write_ops(out, header, [{'op': 'fresh', 'follower': follower}] + small) + print(f' shrunk {len(body)} -> {len(small)} ops: {out}', flush=True) + + +def ddmin(items, fails): + """Zeller's delta debugging: a 1-minimal failing subsequence.""" + n = 2 + # Trailing ops after the failure never matter; the failing op is last. + while len(items) >= 2: + size = max(1, len(items) // n) + chunks = [items[i:i + size] for i in range(0, len(items), size)] + reduced = False + for i in range(len(chunks)): + complement = [op for j, c in enumerate(chunks) if j != i for op in c] + if complement and fails(complement): + items, n, reduced = complement, max(n - 1, 2), True + break + if not reduced: + if n >= len(items): + break + n = min(len(items), n * 2) + return items + + +def shrink_payloads(ops, fails): + """Halve long data payloads while the failure stays.""" + ops = [dict(op) for op in ops] + for i, op in enumerate(ops): + while 'data' in op and len(op['data']) > 8: + half = dict(op, data=op['data'][:len(op['data']) // 2]) + trial = ops[:i] + [half] + ops[i + 1:] + if fails(trial): + ops[i] = op = half + else: + break + if op.get('chunks') not in (None, 'whole'): + whole = dict(op, chunks='whole') + if fails(ops[:i] + [whole] + ops[i + 1:]): + ops[i] = whole + return ops + + +def write_ops(path, header, ops): + with open(path, 'w') as f: + f.write(json.dumps(header) + '\n') + for op in ops: + f.write(json.dumps(op) + '\n') + + +def read_ops(path): + with open(path) as f: + lines = [json.loads(line) for line in f if line.strip()] + return lines[0], lines[1:] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) + ap.add_argument('binary') + ap.add_argument('--seed', type=int, action='append', help='seed (repeatable); default 1') + ap.add_argument('--steps', type=int, default=1000) + ap.add_argument('--replay', help='run an ops log (or bug record) exactly') + ap.add_argument('--shrink', help='shrink a bug record by delta debugging over replays') + ap.add_argument('--no-shrink', action='store_true', help='record failures without shrinking them') + ap.add_argument('--shrink-budget', type=int, default=300, help='replays a shrink may spend') + ap.add_argument('--shrink-seconds', type=float, default=600) + ap.add_argument('--smoke', action='store_true', help='fixed seed, few steps, fail on any failure') + ap.add_argument('--progress', type=int, default=500) + ap.add_argument('--verbose', '-v', action='store_true', help='replay: print each request and log record') + ap.add_argument('--out', default=DEFAULT_OUT) + args = ap.parse_args() + args.binary = os.path.abspath(args.binary) + for key in [k for k in os.environ if k.startswith('PARDES_') or k in ('NINE_MOUNT', 'NAMESPACE')]: + del os.environ[key] + become_subreaper() + signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) + runner = Runner(args) + try: + return run_main(runner, args) + finally: + sweep(f'{os.getpid()}-') + for d in RUNTIME_DIRS: + shutil.rmtree(d, ignore_errors=True) + + +def run_main(runner, args): + if args.replay: + header, ops = read_ops(args.replay) + run_dir = os.path.join(args.out, 'runs', f'replay-{os.getpid()}') + os.makedirs(run_dir, exist_ok=True) + f = runner.execute(ops, run_dir, verbose=args.verbose) + print(f'replay {args.replay}: ' + (f'FAIL at op {f.step}: {f.kind}: {f.why}' if f else 'passed')) + return 1 if f else 0 + if args.shrink: + runner.shrink(args.shrink) + return 0 + if args.smoke: + args.no_shrink = True + found = runner.fuzz(20260929, args.steps if args.steps != 1000 else 800) + return 1 if found else 0 + total = 0 + for seed in args.seed or [1]: + total += len(runner.fuzz(seed, args.steps)) + return 1 if total else 0 + + +if __name__ == '__main__': + sys.exit(main()) -- cgit v1.3 From 66500ac6e4f002a673e95e9788a4992178bf989a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 18:16:13 -0300 Subject: The 9P monkey counts the lines a write runs as the tree does: a short write's unended tail is a line of its own Since round 24 (uwzuqzxp), a write to a lines file shorter than a Twrite holds is whole, as acme takes each write, so a look line written a byte a Twrite is as many looks as bytes, each missing with its own err. one_failure_rule still split the data on newlines whole, allowed one err, and failed the fixed smoke seed (20260929 step 607, size 20 6 written in bytes to look: 7 errs). served_lines models the tree's write (tree.zig) and has a self-check run at start. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index 4c1732e5..6a8f27c1 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -640,12 +640,13 @@ def op_write(sess, op): timeout = SLOW_TIMEOUT if slow(data) else TIMEOUT ok, body = w.call(TOPEN, struct.pack(' Date: Tue, 29 Sep 2026 18:23:54 -0300 Subject: The 9P monkey's one-failure rule is a write's: a refused open, create or remove, or a write to pane/new, must log no err The coordinator's reading of fs.md, now documented (slnyzzps): only a write or truncation logs its reason; a refused open (pane/new's and an OTRUNC one included), create or remove is its Rerror alone, and so is a write to pane/new. The oracle allowed an err or none for those, and required one for a refused pane/new open. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index 6a8f27c1..c0e99fb8 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -1491,9 +1491,11 @@ def one_failure_rule(ctx, res): if res.window is None or res.hung_up: return None writes = res.writes() - # A refused open with OTRUNC may be refused for the open, not the - # truncation (event's `file in use`): allowed an err or none, below. - failed = [w for w in writes if w[2] is False and w[0] != 'trunc'] + # The rule is a write's: a refused open (pane/new's and an OTRUNC one + # too), create or remove logs no err, nor does a write to pane/new + # (`permission denied`: it is only read). + failed = [w for w in writes if w[2] is False and w[0] in ('write', 'clunk-write') + and w[1].rstrip('/') != '/pane/new'] errs = occurrences(res.window, 'err') msgs = occurrences(res.window, 'msg') # Only for a write that succeeded: a failed one logs its one err. @@ -1502,11 +1504,7 @@ def one_failure_rule(ctx, res): # fs.md 'A write of command lines ... what is left when it closes runs at # the close ... and its failure is in the log alone'. closes = [r for r in res.requests if r[0] == 'close-runs'] - # Refused opens (other than pane/new), removes and creates are not named - # by the rule: allow an err or none. - other = [r for r in res.requests if r[2] is False and ( - r[0] in ('remove', 'create', 'trunc') or r[0] == 'open' and r[1].rstrip('/') != '/pane/new')] - lo, hi = len(failed), len(failed) + allowed + len(closes) + len(other) + lo, hi = len(failed), len(failed) + allowed + len(closes) if not lo <= len(errs) <= hi: return (f'{len(failed)} failed write(s) logged {len(errs)} err record(s) ' f'(allowed {lo}..{hi}); failed={[(w[0], w[1], w[3]) for w in failed]} window={res.window}') -- cgit v1.3 From 290015c17de9348d10273cac1495950cc3e92d3a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 19:47:39 -0300 Subject: The 9P monkey allows a look's misses to each Twrite that succeeded, not to none when one failed A look line written a byte a Twrite is a look a byte, each its own write logging its own miss; when its last byte was a control character that one write failed, and the oracle dropped every miss allowance on the path, so seed 51 failed with 21 errs for 1 refused write. Allowances are now counted over the Twrites that succeeded (and an hwrite's only once it has). Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index c0e99fb8..ee0b0ebc 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -641,11 +641,11 @@ def op_write(sess, op): ok, body = w.call(TOPEN, struct.pack(' Date: Wed, 30 Sep 2026 10:13:10 -0300 Subject: The 9P monkey lets a failed write's op log a msg when another of its Twrites succeeded A ctl line cut across Twrites runs a piece a Twrite: in seed 109, "Save Pl" ran Save and said so, and the next piece, "acem", was refused. one_failure_rule took the msg as the failed write's. It now flags a msg only when no Twrite of the op succeeded. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index ee0b0ebc..7ab6cb0c 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -1514,7 +1514,11 @@ def one_failure_rule(ctx, res): if not lo <= len(errs) <= hi: return (f'{len(failed)} failed write(s) logged {len(errs)} err record(s) ' f'(allowed {lo}..{hi}); failed={[(w[0], w[1], w[3]) for w in failed]} window={res.window}') - if failed and msgs: + # A msg is a failed write's only when no Twrite of the op succeeded: a + # line cut across Twrites runs a piece a Twrite, and a piece that ran + # (a Save) says so while a later one is refused. + succeeded = [w for w in writes if w[2] is True and w[0] == 'write'] + if failed and msgs and not succeeded: return f'a failed write also logged msg: {msgs}; failed={[(w[1], w[3]) for w in failed]}' return None -- cgit v1.3 From ebcb870ac8ea962fd705068c7aaff935c5a5c15b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 12:56:58 -0300 Subject: The 9P monkey does not count a file watch's notice as a failed write's msg Seed 121 flagged a refused write to pane 2's dirty file because a `msg 3 deleted on disk (Save writes it again)` arrived in the same window. That notice was from an earlier host rm of pane 3's file, said whenever the watch noticed it. It did not reproduce on replay, since it depends on when the watch fires. The one-failure rule now leaves out the watch's deleted-on-disk and changed-on-disk notices. Any other msg with a failed write still fails the rule. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index 7ab6cb0c..4d190bbc 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -1518,6 +1518,9 @@ def one_failure_rule(ctx, res): # line cut across Twrites runs a piece a Twrite, and a piece that ran # (a Save) says so while a later one is refused. succeeded = [w for w in writes if w[2] is True and w[0] == 'write'] + # A file watch's notice (` deleted on disk ...`, `changed on + # disk`) is the host's news, said whenever it arrives: no write's. + msgs = [m for m in msgs if ' deleted on disk (' not in m and ' changed on disk (' not in m] if failed and msgs and not succeeded: return f'a failed write also logged msg: {msgs}; failed={[(w[1], w[3]) for w in failed]}' return None -- cgit v1.3 From 8598a5fbe6ffecad46891957356d47a37649e547 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 14:41:52 -0300 Subject: A write of a multiple of 4096 bytes holds the partial line it ends with, as one that fills its Twrite does: a burst through a mount no longer runs its cut lines as two commands selfmount's 1000-line burst reported 943 lines, on main too. The log ring was not losing records: a follower opened before the burst heard exactly 943 and no `lost`, and the burst itself exited 1 with `err 1 exec: wrong #args in control message "Msg"`. `seq ... > exec` through the mount arrives as stdio's 4096-byte writes, each shorter than a Twrite. The rule that such a write is whole ran each one's cut last line at once, so both halves of the line ran as commands (hence `exit 127` records). At 12288 bytes the cut left a bare `Msg`, which was refused and failed the write and the rest of the burst. A write of a multiple of 4096 bytes is where a writer's buffer (stdio, a page cache) filled, so it may go on: its unended tail now waits for the next write or the close, like one that fills its Twrite. `printf Save > exec` stays whole at once. fs.md says so, the 9P fuzzer's model of served lines follows it, and a unit test cuts a `Msg` at 4096 bytes. A follower does not lose records silently: a ring that outruns one already reads it `lost N` first (documented, tested). selfmount now follows the log from before the burst, so it checks every line heard once, in order, or a loss said, not a fresh open of a 64 KiB ring. It passed 3 in 3 and joins the gates with the new 9ns. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 ++++- src/ninep/tree.zig | 26 +++++++++++++++++++++++++- test/monkey9p.py | 7 ++++--- test/selfmount.py | 39 +++++++++++++++++++++++++++++++++++---- 4 files changed, 68 insertions(+), 9 deletions(-) (limited to 'test/monkey9p.py') diff --git a/docs/fs.md b/docs/fs.md index 146ff17b..34664343 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -156,7 +156,10 @@ effect, as acme's ctl does. Blank lines are skipped. A mount cuts a big write into pieces of at most one message (msize 64 KiB, 65536 negotiated, less the header), and each line runs once it is whole. A write that does not fill its message is -whole, so its last line runs even without a newline (`printf Save > exec`). An `Edit` whose `{` or +whole, so its last line runs even without a newline (`printf Save > exec`), +unless it is a multiple of 4096 bytes: that is where a writer's buffer (stdio, +a mount's page cache) filled and cut a line, so its tail waits for the next +write or the close. An `Edit` whose `{` or `a`/`c`/`i` text is still open waits for the next write on that open, and fails at the close if it never ends (``unmatched `{'``). A line held past 1 MiB is refused. diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 17941e10..322728da 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1169,7 +1169,12 @@ fn write(p: *Pardes, req: Req, target: Target) Reply { // and its failure is this write's, as acme takes each write whole. Held // only when it is not whole yet -- an open `{` block, an `a`/`c`/`i` // text awaiting its `.` -- or the write filled its Twrite and may go on. - const cut = p.fs.write_room != 0 and req.data.len >= p.fs.write_room; + // So may one cut where a writer's buffer filled: stdio flushes, and a + // mount's page cache writes back, in multiples of 4096 bytes. `seq ... + // > exec` through a mount arrived in 4096-byte writes, and the line cut + // at each end ran as two commands (the half `Msg` refused, failing the + // write and the rest of the burst). + const cut = (p.fs.write_room != 0 and req.data.len >= p.fs.write_room) or req.data.len % 4096 == 0; if (end < o.pending.items.len and !cut) { o.pending.append(p.gpa, '\n') catch return Reply.fail(req.tag, E.NOMEM); const whole = ctl.completeEnd(p, o.pending.items); @@ -1826,6 +1831,25 @@ test "look and exec read back what their own open's write touched; a fresh open for ([_]u32{ mine, theirs, fresh }) |hh| _ = call(p, .{ .tag = 10, .op = .release, .node = exec, .handle = hh, .opened = true }); } +test "a write cut where a writer's 4096-byte buffer filled holds its partial line for the next write" { + const p = try th.withFile(testing.allocator, "x\n"); + defer p.deinit(); + const exec_node = Node.of(serialOf(p), .exec); + const h = call(p, .{ .tag = 1, .op = .open, .node = exec_node, .omode = 1 }).reply.handle; + // 4096 bytes: whole `Msg first` lines, then a line cut after `Msg`. + var buf: [4096]u8 = undefined; + const line = "Msg first\n"; + var n: usize = 0; + while (n + line.len <= buf.len - 3) : (n += line.len) @memcpy(buf[n..][0..line.len], line); + @memset(buf[n..], ' '); + @memcpy(buf[buf.len - 3 ..], "Msg"); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = exec_node, .handle = h, .data = &buf }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = exec_node, .handle = h, .data = " last\n" }).reply.status); + _ = call(p, .{ .tag = 4, .op = .release, .node = exec_node, .handle = h, .opened = true }); + try testing.expect(th.logHas(p, "last")); + try testing.expect(!th.logHas(p, "wrong #args")); +} + test "no placement leaves a pane shorter than its tag and two rows; a full column refuses the next" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/test/monkey9p.py b/test/monkey9p.py index 4d190bbc..fd8c80fa 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -674,8 +674,9 @@ def served_lines(data, sizes, room): (fs.md, tree.zig write): each ended line, and the unended tail of a piece shorter than a Twrite holds (`room`, msize less 24), which is whole in itself, as acme takes each write; a piece that fills its Twrite may go - on, and its tail waits for the next. A line written a byte a Twrite is - so as many lines as bytes.""" + on, and its tail waits for the next, and so does one of a multiple of + 4096 bytes, where a writer's buffer filled. A line written a byte a + Twrite is so as many lines as bytes.""" lines, pending, at = [], b'', 0 for size in sizes: piece = data[at:at + size] @@ -683,7 +684,7 @@ def served_lines(data, sizes, room): pending += piece *done, pending = pending.split(b'\n') lines += done - if pending and len(piece) < room: + if pending and len(piece) < room and len(piece) % 4096 != 0: lines.append(pending) pending = b'' if pending: diff --git a/test/selfmount.py b/test/selfmount.py index 6534aa25..86c32fa8 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -20,6 +20,7 @@ import signal import struct import sys import termios +import threading import time sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -127,12 +128,42 @@ def run(binary): return exits[-1].split()[2] time.sleep(.1) return 'timeout' + # Followed from before the burst: a fresh open of the log reads + # only what its 64 KiB ring still holds, which a burst this size + # outgrows, and a follower the ring outruns reads `lost N`, so + # every line is either heard once, in order, or a loss is said. + heard = [] + + def follow(): + with Client(sock) as follower: + fid = follower.open('/log', 2) + start = len(follower.read_fid(fid)) + follower.rpc(118, struct.pack(' {mount}/exec\n".encode()) check(got == '0', f'a 1000-line burst written through the mount ({got!r})') - log = client.read('/log').decode() - said = [line.split(' ', 2)[2] for line in log.splitlines() if line.startswith('msg ') and 'mnt-' in line] - check(said == ['mnt-%04d' % i for i in range(1000)], f'each line of it ran once, whole ({len(said)} said)') - check('exit 127' not in log, 'no piece of a line ran as a command') + reader.join(60) + for r in heard: + if r.startswith(('err ', 'exit ')): + print(' heard: ' + r.rstrip()) + said = [r.rstrip('\n').split(' ', 2)[2] for r in heard if r.startswith('msg ') and 'mnt-' in r] + lost = [r for r in heard if r.startswith('lost ')] + numbers = [int(s[4:]) for s in said] + check(numbers == list(range(numbers[0] if numbers else 0, 1000)), + f'each line it heard ran once, whole, in order, through the last ({len(said)} heard)') + check(len(said) == 1000 or (lost and heard.index(lost[0]) < heard.index(next(r for r in heard if 'mnt-' in r))), + f'no line was lost unsaid ({len(said)} heard, {lost!r})') + check(not any('exit 127' in r for r in heard), 'no piece of a line ran as a command') scratch = int(client.read('/pane/new')) maker = "import sys; sys.stdout.write('Edit ,a\\n' + ''.join('line %05d of the block\\n' % i for i in range(2500)) + '.\\n')" check(run(f'python3 -c "{maker}" > {mount}/pane/{scratch}/ctl\n'.encode()) == '0', 'a 50 KB Edit block written through the mount') -- cgit v1.3 From 007ec29082fcd24764db0405c12f1cdf5638bdca Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 15:56:43 -0300 Subject: The 9P monkey's chunked read check allows a live file that changed between its two reads Seed 131 flagged a command pane's tag: the whole read said `running`, the chunked read on the same open said `exit 0`. A tag is live, not frozen at the open, and the command ended between the reads, so this was a false alarm that did not reproduce on replay. A mismatch now counts only when a third, whole read still differs from the chunks. Seeds 131, 133 and 134 at 3000 steps each run clean. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index fd8c80fa..87e386b3 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -1616,7 +1616,10 @@ def chunked_equals_whole(ctx, res): whole_n, chunk_n = dir_names(whole), dir_names(chunked) if whole_n != chunk_n: return f'{path}: whole {whole_n} != chunked({size}) {chunk_n}' - elif whole != chunked: + elif whole != chunked and w.read_all(fid) != chunked: + # A live file (a tag says `running`, then `exit 0`) may change + # between the two reads: only chunks that no whole read matches, + # read again, are a chunking fault. return f'{path}: whole {whole[:200]!r} != chunked({size}) {chunked[:200]!r}' finally: w.clunk(fid) -- cgit v1.3 From 79fb1b77b8c9993fb36c250daf36970807f767c9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 16:22:34 -0300 Subject: The 9P monkey does not count a file watch's reload notice as a failed write's msg Seed 144 flagged a refused addr write because a stamped `reloaded ` from the file watch arrived in the same window. The watch said the host had written a clean pane's file, which is the host's news, not the write's. The one-failure rule already left out the watch's deleted-on-disk and changed-on-disk notices; it now leaves out the `reloaded` ones too, for files and themes. Seed 144 reruns clean at 4000 steps. Co-Authored-By: Claude Opus 5.5 --- test/monkey9p.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'test/monkey9p.py') diff --git a/test/monkey9p.py b/test/monkey9p.py index 87e386b3..89751145 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -1520,8 +1520,9 @@ def one_failure_rule(ctx, res): # (a Save) says so while a later one is refused. succeeded = [w for w in writes if w[2] is True and w[0] == 'write'] # A file watch's notice (` deleted on disk ...`, `changed on - # disk`) is the host's news, said whenever it arrives: no write's. - msgs = [m for m in msgs if ' deleted on disk (' not in m and ' changed on disk (' not in m] + # disk`, a stamped `reloaded ` or `reloaded theme`) is the host's + # news, said whenever it arrives: no write's. + msgs = [m for m in msgs if ' deleted on disk (' not in m and ' changed on disk (' not in m and ' reloaded ' not in m] if failed and msgs and not succeeded: return f'a failed write also logged msg: {msgs}; failed={[(w[1], w[3]) for w in failed]}' return None -- cgit v1.3 From 6122159572f1cc950666df484e2074cf32f22eb5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 16:51:34 -0300 Subject: A 9P look keeps its leading blanks: an indented line, or blanks alone, is looked for as written Every line written to look or exec went through Messages.next, which trimmed blanks from both ends. A look of ` indented` then found the first bare `indented`, and a diff's blank context line ` ` looked at nothing. A look's line is now its text: only its `\r` and newline go. lookAt keeps the blanks for the word search too; it expands `~` only for a look that starts with one, and the path, address and command readings trim for themselves as before. runSearch keeps a pattern's blanks, since a builtin's argument comes trimmed already. An exec line is trimmed as before. fs.md says so. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 5 ++++- src/look.zig | 25 +++++++++++++++++-------- src/ninep/ctl.zig | 23 +++++++++++++++++++++++ test/monkey9p.py | 9 +++++++-- 4 files changed, 51 insertions(+), 11 deletions(-) (limited to 'test/monkey9p.py') diff --git a/docs/fs.md b/docs/fs.md index 985e36a1..020fce58 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -196,7 +196,10 @@ an edit land. Modes are 0644/0666, 0444 read-only, 0222 write-only. ## look and exec -A line written to `look` is a right click on it: +A line written to `look` is a right click on it, on the line as written: +its leading blanks are its own (` return x` finds that indented line, and +a diff's blank context line ` ` is a look too); only its newline and `\r` +go. An `exec` line's blanks at either end are trimmed. - a path opens the file (the pane already showing it, if any); `file:12` selects line 12, newline included; `file:12:5` puts the caret at line 12, diff --git a/src/look.zig b/src/look.zig index 76b58fbe..0f99722d 100644 --- a/src/look.zig +++ b/src/look.zig @@ -580,8 +580,10 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// `open_empty` false a text search that found nothing opens no buffer. pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; - const pat = std.mem.trim(u8, pat_raw, " \t\r\n"); - if (pat.len == 0) return 0; + // Blanks at either end are the pattern's (a look of an indented line); + // a builtin's argument comes trimmed already. + const pat = std.mem.trimEnd(u8, pat_raw, "\r\n"); + if (std.mem.trim(u8, pat, " \t").len == 0) return 0; const arena = p.scratch.allocator(); // where the pane lives: a file's directory, a shell's cwd — the walk // root, and the directory the results buffer is named in. From a @@ -1325,7 +1327,9 @@ fn addressed(tok: []const u8) ?struct { path: []const u8, expr: []const u8 } { /// A look at text that names nothing to open: a `./` name is a missing /// file, anything else a search for the text as written. -fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8) void { +/// `text` is what a word search looks for: the look as written, its blanks +/// kept; `trimmed` what a name is read from. +fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: []const u8) void { // A `./` or `../` name opened nothing: said, ENOENT, not searched // for as a word. What is missing is the pane's directory when // that is gone, else the file named. @@ -1340,8 +1344,9 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8) void // A raw terminal's clicks are its program's; a look written over // 9P is no keyboard input, and searches whatever the key mode. if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return; - if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, trimmed); - const rows = runSearch(p, id, trimmed, .text, .cursor, false) catch |err| { + if (text.len == 0) return; + if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); + const rows = runSearch(p, id, text, .text, .cursor, false) catch |err| { p.reportError(id, "search", err); return; }; @@ -1380,7 +1385,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { // A path that names nothing to open: the whole of what was written // is looked for, as `zzq:2` is, and a miss quotes it as written. if (!by_serial and resolveLookTarget(p, id, path, &realbuf) == .none) - return lookUnresolved(p, id, p.panes[id] orelse return, path.ptr[0 .. path.len + 1 + expr.len]); + return lookUnresolved(p, id, p.panes[id] orelse return, path.ptr[0 .. path.len + 1 + expr.len], path.ptr[0 .. path.len + 1 + expr.len]); const before = p.active; const failures = p.fs.failures; const was_missed = p.look_missed; @@ -1598,8 +1603,12 @@ fn diffFile(base: []const u8, path: []const u8, out: *[4096]u8) ?[]const u8 { pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const pane = p.panes[id] orelse return; // `~/x`, `~/x:12`, `~/x:/re/`: home, before anything reads the text. + // Anything else as written: a look of ` return x` is of those blanks + // too (the path, address and command readings below trim for + // themselves). var home_buf: [4096]u8 = undefined; - const operand = filesystem.expandHome(std.mem.trim(u8, operand_raw, " \t\r\n"), &home_buf); + const stripped = std.mem.trim(u8, operand_raw, " \t\r\n"); + const operand = if (stripped.len > 0 and stripped[0] == '~') filesystem.expandHome(stripped, &home_buf) else std.mem.trimEnd(u8, operand_raw, "\r\n"); // A +Recent row is a remembered place: reopened and clamped to the file // as it is now, never a miss for a line the file no longer has. if (isRecentList(pane)) { @@ -1665,7 +1674,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { pane.sel = @splat(.{}); } switch (found) { - .none => lookUnresolved(p, id, pane, trimmed), + .none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .pane => |t| { // `@p` names no open pane: a miss, said. if (t.id >= MAX_PANES or p.panes[t.id] == null) return missed(p, id, "no pane {s}", .{pl.path[0..@min(pl.path.len, 32)]}); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 549aa265..66fa22ab 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -110,6 +110,9 @@ const Messages = struct { p: *Pardes, data: []const u8, at: usize = 0, + /// A look's line is its text, leading blanks and all (` return x`, + /// a diff's context line ` ` alone): only its `\r` goes. + keep_blanks: bool = false, fn init(p: *Pardes, data: []const u8) Messages { return .{ .p = p, .data = data }; @@ -120,6 +123,7 @@ const Messages = struct { const start = m.at; var end = std.mem.indexOfScalarPos(u8, m.data, start, '\n') orelse m.data.len; m.at = end + 1; + if (m.keep_blanks) return std.mem.trimEnd(u8, m.data[start..end], "\r"); const first = std.mem.trim(u8, m.data[start..end], " \t\r"); const edit = "Edit"; if (!std.mem.startsWith(u8, first, edit) or (first.len > edit.len and first[edit.len] != ' ' and first[edit.len] != '\t')) @@ -186,6 +190,7 @@ pub fn command(p: *Pardes, req: Req, serial: ?u32, exec: bool, in_tag: bool) Rep for ([2]bool{ false, true }) |apply| { if (apply) p.fs.results_len = 0; var it = Messages.init(p, req.data); + it.keep_blanks = !exec; while (it.next()) |text| { if (text.len == 0) continue; // Only an Edit block holds newlines (Messages). @@ -2540,6 +2545,24 @@ test "a restored pane whose file is gone from disk comes back dirty, and Del ask try testing.expect(std.mem.indexOf(u8, r.reply.ename, "Modified") != null); } +test "a 9P look keeps its leading blanks, a blank-only look included, and exec still trims" { + const p = try withFile(testing.allocator, "a indented\nb\n indented\n \n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[p.paneBySerial(serial).?].?; + pane_files.setDot(pane, .{ .q0 = 0, .q1 = 0 }); + // The indented line, not the `indented` after `a `. + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .look), " indented\n").reply.status); + try testing.expectEqual(pane_files.State.Range{ .q0 = 13, .q1 = 25 }, pane_files.dotOf(pane)); + // Blanks alone are text to find too. + pane_files.setDot(pane, .{ .q0 = 26, .q1 = 26 }); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .look), " \n").reply.status); + try testing.expectEqual(pane_files.State.Range{ .q0 = 26, .q1 = 30 }, pane_files.dotOf(pane)); + // exec's line is still trimmed: ` Msg hi` runs Msg. + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .exec), " Msg blanks trimmed\n").reply.status); + try testing.expect(th.logHas(p, "blanks trimmed")); +} + test "a line starting with # runs as nothing at an exec or a ctl, silently" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/test/monkey9p.py b/test/monkey9p.py index 89751145..64b82832 100644 --- a/test/monkey9p.py +++ b/test/monkey9p.py @@ -698,8 +698,13 @@ def allowances(res, path, data, sizes, room): (acme's xfid.c:842) or run as the Look builtin; an Edit block whose text never ended runs, and fails, at the close.""" base = path.rsplit('/', 1)[-1] - lines = [line for line in served_lines(data, sizes, room) if line.strip()] - if base in ('look', 'event'): + served = served_lines(data, sizes, room) + lines = [line for line in served if line.strip()] + if base == 'look': + # A look's line is its text, blanks and all: one of blanks alone + # is a look too (fs.md); only an empty one (or a lone \r) is none. + n = len([line for line in served if line.rstrip(b'\r')]) + elif base == 'event': n = len(lines) elif base in ('exec', 'ctl', 'tagexec'): n = sum(1 for line in lines if line.split()[:1] == [b'Look']) -- cgit v1.3 From 5e72bfc34cc97d12be5185930135b55c2eb001b4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 23:04:26 -0300 Subject: The reference is fs.md's per-file semantics, errors and limits in Typst, with the settings table, and says what the pane ctl's Left, Right, Up and Down do Co-Authored-By: Claude Opus 5.5 --- docs/config.md | 202 ------------- docs/fs.md | 763 ------------------------------------------------- docs/macos.md | 4 +- docs/open-questions.md | 4 +- docs/typ/reference.typ | 721 ++++++++++++++++++++++++++++++++++++++++++++++ next-steps.txt | 2 +- src/builtins.zig | 2 +- src/ninep/ctl.zig | 4 +- test/monkey9p.py | 20 +- 9 files changed, 739 insertions(+), 983 deletions(-) delete mode 100644 docs/config.md delete mode 100644 docs/fs.md create mode 100644 docs/typ/reference.typ (limited to 'test/monkey9p.py') diff --git a/docs/config.md b/docs/config.md deleted file mode 100644 index 23355b06..00000000 --- a/docs/config.md +++ /dev/null @@ -1,202 +0,0 @@ -# Configuration - -## The startup file - -Native builds read one command file, `init`, from the per-user `pardes` -configuration directory: - -- Unix: `$XDG_CONFIG_HOME/pardes/init` (only an absolute `XDG_CONFIG_HOME` - counts), else `~/.config/pardes/init`. -- macOS: `$XDG_CONFIG_HOME/pardes/init` when set, else - `~/Library/Application Support/pardes/init`. -- Windows: `%LOCALAPPDATA%\pardes\init`, else - `%USERPROFILE%\AppData\Local\pardes\init`. - -The browser build has none. A file over 1 MiB or unreadable counts as absent. - -Each line is one builtin, spelled as it would be executed in pardes: - -```text -Theme orchard -Font DejaVuSansMono-Regular -TaglineSize 82 -Shell zsh -Wrap -``` - -A builtin that takes no argument matches only as the whole line (`Kill` runs, -`Kill something` does not); one that takes an argument takes the rest of the -line. Blank, unknown, malformed or failing lines are ignored silently and do -not stop later ones. Text that is no builtin is not run as a shell command -(`Exec ...` still is). Key bindings are compile-time choices in -`src/config.zig`; `init` does not remap them. - -`Config` (`SPC f c`) opens `init` itself in a pane, or goes to its pane when -it is open. With no file there yet, the pane is named for it, empty, and -Save writes it, making its directory first. `DumpConfig` opens a -`+DumpConfig` pane with every live setting, each line the word that sets -it and its value (`Shell /bin/bash`, `PanelSlide off`, `LocationsConfig …`) -and a `# Lift unsupported` comment for one the frontend cannot show. After a blank line -come what is in effect but set by no word, such as the last shell spawned -and the font in use, and the startup path (a right click opens it), each a -`#` line. A line starting with `#` is a comment wherever a line runs (the -init file, a ctl, an exec), so the report can be written back as is. The -root `ctl` file reads the settings back in the words a write takes -([fs.md](fs.md#the-root-ctl)). - -## Settings - -A setting that chooses among words (`on`/`off` switches, `Placement`, -`BootShell`, `Crt`, `Bloom`, `Vignette`, `Grain`, `Lift`, `Motion`, -`ShaderAnimation`) steps to its next value when given bare, as its word -clicked in a tag does; a value it does not take is refused, naming those it -does. `/commands` lists every builtin and its values. - -| setting | default | | -|---|---|---| -| `Theme ` | `orchard` | names as `Themes` (`SPC t t`) lists them ([themes.md](themes.md)); `NextColor` walks the ring | -| `ThemeFile ` | | a `.zon` theme, relative to the config directory; reloads live when saved | -| `FocusTint` | on | tint the focused pane's and column's tags | -| `SyntaxBold` | off | bold syntax keywords | -| `Verbose` | on | a builtin announces its name on the message row | -| `MessageAnimation` | on | messages ease in and dissolve | -| `MessageLinger`, `MessageFall`, `MessageDissolve` | 800, 180, 150 | milliseconds, at most 60000 | -| `Placement acme\|pardes` | `acme` | where new panes go ([tags.md](tags.md#where-new-panes-go)) | -| `BootShell keep\|replace` | `keep` | `replace` closes the untouched lone shell a dragged document lands beside | -| `LookWord search\|list` | `search` | a looked-at word selects its next place, or lists all in `+Search` | -| `Shell ` | `$SHELL`, else the login shell, else `/bin/sh` | the shell the next terminal runs; a bare name is looked for in the usual bin directories, not `$PATH`; bare `Shell` returns to the default | -| `DumpDir ` | `$XDG_DATA_HOME/pardes`, else `~/.local/share/pardes` | where `Dump` writes; `~/` is home; bare returns to the default | -| `TreeContext` | off | sticky declaration headers in a source pane (per pane, dumped) | -| `TreeContextTagStyle` | on | draw those headers in the tagline style | -| `LocationsConfig ...` | | Search, Grep and LSP result layout (below) | -| `Wrap`, `Colors`, `Tagbottom`, `Debug` | | toggles | -| `Font [:]`, `Fonts` | | SDL and macOS only; size 8-72 (pixels in SDL, points on macOS) | -| `TaglineSize <1-100>` | 82 | tagline face, percent; SDL and macOS | -| `WindowOpacity <0-100>` | 100 | SDL only: everything but text and the cursor | -| `Ligatures` | on | SDL only; macOS draws CoreText's own | -| `Pet cat\|frog\|off` | off | SDL only: a sprite in the workspace tag's blank space | - -`Tty9p` (`SPC n 9`) is described in [v9fs.md](v9fs.md); the -`PARDES_V9FS_HELPER` variable points development builds at the helper. - -### Terminals - -Ctrl-B switches a terminal between raw input and editor mode. Plain Escape -at a detected shell prompt hops back to the previous pane; other keys, -Ctrl-O, Ctrl-W and modified Escape included, go to the program. `Mode` in the -tag returns to editor mode in place. Ctrl-V types the yank register and -Ctrl-Shift-V the desktop clipboard, through bracketed paste when the program -asked for it; neither reaches the program as a keystroke. - -`Filter` in a terminal's tag maps its ANSI colours through the theme, -keeping each foreground at least `tty_filter_min_contrast` (WCAG 1.5, in -`src/config.zig`) against its background. - -### Location results - -`LocationsConfig` with no argument prints the current settings as a line -that can be run again; with fields it changes only those: - -```text -LocationsConfig context:5 tscontext:on tslocations:off layout:stacked -``` - -- `context` (0): source lines shown above and below each match. -- `tscontext` (off): include the enclosing tree-sitter declaration headers. -- `tslocations` (on): show a location on each declaration header. -- `layout` (`stacked`): the location on its own line; `inline` puts it - beside the source, padded in groups of eight matches. - -An invalid field rejects the whole line; a repeated field's last value wins. -The settings survive Dump and Restore. Source analysis is cached for 64 -files and 64 MiB. - -### Effects - -Panel transitions, one at a time; running the active one again turns it -off: `PanelSlide`, `PanelZoom`, `PanelDissolve`, `PanelAscii`, -`PanelVertical`, `PanelEdges`, `PanelFall`, `PanelWave`, `PanelCurtain`, -`PanelScramble`, `PanelType`. All start off; the web shell has none. - -Scene passes (SDL GUI, and a GUI attached to a detached session), each at a -level 0-3 (`on` is 2), all off by default: `Crt`, `Bloom`, `Vignette`, -`Grain`. `Shader ` adds a Shadertoy file written for ghostty to -the chain (`Shader off` removes it; it recompiles when saved); -`ShaderAnimation off|on|always` says when the chain animates by itself. - -The focused pane can stand off the page: `Lift shadow|rim|auto|off`, -`InactiveDim `, `Motion off|crisp|smooth|bouncy|playful` -(default `smooth`), `SelectionGlow`, `HoverGlow`, `Occlusion`, `Parallax`, -`JumpTrail`, `ChipShadow`, `ThumbFlash`, `CursorBlink`, `GripWidth <50-300>`. -Most are GUI-only; `InactiveDim` works everywhere, and `JumpTrail`, -`ChipShadow` and `ThumbFlash` are the terminal's. No effect may lower the -contrast of text, the selection or a focus indicator -([effects.md](effects.md)). - -`EffectCode ` lists that effect's sources under `/virtual` when the -build embeds them (`-Dembed-sources=true`). `zig build shaders` refreshes -the committed SPIR-V with its GLSL. - -### Look preview - -Resting the pointer on text for about 32 ms (`look_preview_delay_frames`, 2 -frames) tints what a right click would look at, with no other effect. Set -`look_preview_delay_frames` to `null` in `src/config.zig` to turn it off. - -## Themes from files - -`ThemeFile themes/mine.zon` loads a complete theme; a malformed save keeps -the last good one, and `Theme ` stops the watch. `DumpThemes` writes -every compiled theme to `/themes/builtin/.zon`: copy one, -change its `.name`, and edit. The format is `pardes.Theme` as -`std.zon.stringify` writes it; [themes.md](themes.md) describes each role. - -## Dumps - -`Dump` writes `pardes--