diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 04:51:01 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 06:44:43 -0300 |
| commit | 89f4b611e4e6e1732595d070184daf167b53bfb3 (patch) | |
| tree | 3a37b8eca99c41efbc32ded89483172ee79a013c | |
| parent | 5b7124d10f9b2db8d1c5e99eacb9b6d2fffff0cc (diff) | |
| download | pardes-89f4b611e4e6e1732595d070184daf167b53bfb3.tar.gz pardes-89f4b611e4e6e1732595d070184daf167b53bfb3.zip | |
tape: the budget is a count, step 7 (reports/pardes-handle-69-design.md section 2, P33's lean 3): Names.rescore stops after 3,000,000 of the scorer's cells (a key's bytes times the query's and one, what `match` can visit of a candidate, so a long query's slice is no longer than a short one's) and a tick's Places.fill after 512 KiB read, the places an insert above the view moves charged as read (with many places below it, the moving was what only the clock bounded), so no clock is read in a step: Tape.over, the free over, overNow, the budget site and the two clock reads are deleted, and a far client's guess of a key into a big name query is the session's step by construction (test/daemon.py --far's new scene, a Find over 40,000 names typed into: mispredicted 1, 1, 1 and 4 in four runs of the base, 0 in four of this); the constants measured by pardes-perf's new --search (ReleaseFast, this machine at a load of 12 to 24, every call's instructions counted): a tick's fill on the 18 MB text at most 23-24M instructions where the clock's 4 ms ticks took 47-75M, a rescore's scan on a long query at most 31.5M where the clock's took 32.6M; the longest rescore is not the scan but its sort of every hit at each call (about 125-145M instructions, 16-22 ms, with the clock and with the count alike: not bounded by either, left); the semantics word moves (the site's number goes: 7a610621b2f37456 -> df1f0502317ed362), so cross_replay across this change diverges at the first site after it, as it must; tui core-test 857/1008 (151 skipped), shell-test 1048/1051, pane-test 183/184, term-test 17/17, kitty-test 45/45, behaviour-test 275/275 and --replay 275/275, process-test 0 of 144 failed, both soaks diverged 0 unequal 0 corpus 22 of 22 no leak (bytes: the base's one unlisted `now` stop at 30 ms), daemon.py plain, --far, --games (alone, at load 24), --window-clients, --upgrade both ways against merge31 (new->old alone after the Adopt race); gui unit-test 1645/1649 (the perf check's BaselineHarnessMismatch); frames 77/77, perfab +0.055%, the 121 counts within 0.1% against tree2 (key-down on medium 10,039,595, render on medium 11,454,507; the base 10,039,283 and 11,454,252)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | core/Names.zig | 20 | ||||
| -rw-r--r-- | core/Places.zig | 21 | ||||
| -rw-r--r-- | core/replica.zig | 3 | ||||
| -rw-r--r-- | core/tape.zig | 15 | ||||
| -rw-r--r-- | docs/next-daemon.md | 7 | ||||
| -rw-r--r-- | test/daemon.py | 71 | ||||
| -rw-r--r-- | test/perf.zig | 138 |
7 files changed, 233 insertions, 42 deletions
diff --git a/core/Names.zig b/core/Names.zig index fff2c84f..2fbbec37 100644 --- a/core/Names.zig +++ b/core/Names.zig @@ -2,7 +2,7 @@ //! directory (listed by the disk engine, Stream.zig), the recent files, the open panes, //! a file's declarations. Each keystroke scores them again with a small //! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses -//! at the starts of words and path segments), a frame's budget at a time, +//! at the starts of words and path segments), a frame's count at a time, //! the best kept first. Lifted from the pick prototype (Pick.zig), whose //! scorer took ~1 ms for 20k paths in a release build. Embedded in a //! Query; the rows it shows are the Query's to make. @@ -56,8 +56,12 @@ pub const max_query = 64; /// A candidate is scored over its first this many bytes. const max_text = 512; const max_cands = 200_000; -/// A keystroke's scoring, and a frame's: what is left waits a frame. -const score_budget_ns = 4 * std.time.ns_per_ms; +/// A keystroke's scoring, and a frame's: at most this many of the +/// scorer's cells (a key's bytes times the query's and one: what `match` +/// can visit of a candidate); what is left waits a frame. A count, not the +/// clock: a client's guess of a key scores as far as the session's step +/// (P27, P30). About 4 ms in a release build (`pardes-perf --search`). +const score_cells = 3_000_000; pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { n.bytes.deinit(gpa); @@ -136,12 +140,12 @@ pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { } /// Scores the pending candidates, then `cands[scored..]`, into `hits`, and -/// sorts them: at most `score_budget_ns` of it a call, the rest on the -/// next frames while the best so far is shown. +/// sorts them: at most `score_cells` of it a call, the rest on the next +/// frames while the best so far is shown. pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { const q = n.queryText(); const empty = std.mem.trim(u8, q, " ").len == 0; - const started = pardes.FrameStats.nowNs(); + var left: usize = score_cells; const had = n.hits.items.len; const was_scored = n.scored; var count: usize = 0; @@ -157,8 +161,8 @@ pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null); if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break; - // The clock every 256 candidates: reading it is not free either. - if (!empty and count % 256 == 255 and pardes.tape.over(started, score_budget_ns)) break; + left -|= @as(usize, @min(c.key_len, max_text)) * (q.len + 1); + if (!empty and left == 0) break; } // An empty query keeps the source's order (the walk's, recency): no // row moves as the walk goes on, it only grows at the foot. diff --git a/core/Places.zig b/core/Places.zig index 9ffbff88..35b79805 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -46,13 +46,14 @@ pub const Provenance = enum { typed, search, list }; /// Places past this many are not kept. ponytail: 16 bytes a place, 16 MB /// at the cap; a sparse count past it if a million is ever too few. pub const max_hits = 1 << 20; -/// What one frame spends finding places: about 4 ms on the clock, checked -/// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms -/// of them, so this is about 5 ms), which bound one slow piece; and bytes -/// read, the bound where there is no clock. -pub const frame_ns: u64 = 4 * std.time.ns_per_ms; +/// What one frame spends finding places: bytes of the text read (and the +/// places an insert above the view moves, as many bytes), about 4 ms in a +/// release build (`pardes-perf --search`); and mvzr's steps (Regex.budget +/// is about 300 ms of them, so this is about 5 ms), which bound one slow +/// piece. Counts, not the clock: a replica finds as many places a frame as +/// its session (P27, P30). pub const frame_steps: u64 = regexp.Regex.budget / 64; -pub const frame_bytes: usize = 8 << 20; +pub const frame_bytes: usize = 512 << 10; /// The text is searched in pieces of about this much, each ending at a /// line's end, so that a budget runs out between pieces, not inside one. /// A folding set lowers its copy of the text a piece at a time too. @@ -405,7 +406,6 @@ fn restart(set: *Places, p: *Pardes, f: *File.State) void { /// been searched, make it current. Run after every step (with no budget: /// the view only) and every tick (a frame's). pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) void { - const started_ns = pardes.FrameStats.nowNs(); if (!set.started) return; set.derive(p.gpa); const f = if (pane.file) |*file| file else return set.clear(p.gpa); @@ -490,17 +490,14 @@ pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) voi } if (forward) set.hi = at else { set.hits.insertSlice(gpa, set.nhead, head.items) catch return; + // With many places below, moving them is most of the work. + left -|= (set.hits.items.len - set.nhead - head.items.len) * @sizeOf(Hit); if (set.current) |*c| c.* += head.items.len; set.nhead += head.items.len; set.head_to = at; } left -|= at - from; if (short) break; - // A frame's time spent (a whole search's for n and N, whose steps - // are mvzr's whole budget). - // The clock's verdict is the session's (core/tape.zig): a replica - // finds as many places a frame as this did. - if (started_ns != 0 and bytes != std.math.maxInt(usize) and pardes.tape.over(started_ns, frame_ns)) break; } if (set.hits.items.len != found_before) { set.gen +%= 1; diff --git a/core/replica.zig b/core/replica.zig index 67a29df3..31e16f46 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6604,9 +6604,6 @@ test "a client joined from a dump lands a click on a rail's tick as the session r.confirm(try a.take(m)); r.settle(); } - // (The key may be mispredicted: a step's places are a frame's time's - // worth, `tape.over`, the session's verdict, and its drawn caches let - // it find more in that time than the client's speculation did.) try agrees(a, r); try std.testing.expectEqual(a.core.panes[owner].?.places.current, r.core().panes[owner].?.places.current); } diff --git a/core/tape.zig b/core/tape.zig index f9303d67..934bc499 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -114,7 +114,6 @@ pub const Site = enum(u16) { fonts, // Read in place (`value`). clock, - budget, wake, env, interpreter, @@ -768,12 +767,6 @@ pub const Tape = struct { return t.value(.authority, f, args); } - /// A budget of `budget_ns` from `since_ns` on the monotonic clock is spent: - /// what the clock said is taped, so a replica stops its work where this did. - pub fn over(t: *Tape, since_ns: u64, budget_ns: u64) bool { - return t.value(.budget, overNow, .{ since_ns, budget_ns }); - } - /// A body whose first parameter is an `std.Io` its caller does not pass /// is handed the tape's (`args` are the rest): the only way core/ comes /// to hold one. @@ -1324,14 +1317,6 @@ pub fn resync(t: *Tape) void { t.real = .{}; } -pub fn over(since_ns: u64, budget_ns: u64) bool { - return (on orelse &none).over(since_ns, budget_ns); -} - -fn overNow(since_ns: u64, budget_ns: u64) bool { - return pardes.FrameStats.nowNs() -| since_ns > budget_ns; -} - /// One host call, `f(args)`, made out of the turn (pardes.turn). pub fn out(comptime f: anytype, args: anytype) @typeInfo(@TypeOf(f)).@"fn".return_type.? { pardes.turn.yield(); diff --git a/docs/next-daemon.md b/docs/next-daemon.md index 37ba0241..538729e6 100644 --- a/docs/next-daemon.md +++ b/docs/next-daemon.md @@ -710,9 +710,10 @@ Decisions taken at the forks, with the ponytail lens: - **Clock.** `advance`'s wakes are the recording session's (`tape.value(.wake, nextWake)`): a picture decoding or a fade asks a frame, and a replica that draws none must still take the session's - ticks. The budgets of Places, Names and Tables are taped verdicts - (`tape.over`), as are a message's time of day (TZ included), File.mtime - and the pump's clock read (made whether or not it waits). A message's + ticks. The budgets of Places and Names are counts (bytes read, the + scorer's cells), the same on every side, never the clock's verdict + (P27, P30). A message's time of day (TZ included), File.mtime + and the pump's clock read (made whether or not it waits) are taped. A message's stamp and an unattended session's expiry of it read the clock through the tape too, not the session clock: that is the last pump's, and stamped by it a message written over 9P after an idle spell was as old diff --git a/test/daemon.py b/test/daemon.py index d134732b..887e6d0d 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -1425,6 +1425,74 @@ def games(binary, libs, secs=10): shutil.rmtree(root, ignore_errors=True) +def far_find(binary): + """A far client types a query into a Find over 40,000 names: each key + scores the names again a slice at a time (core/Names.zig `rescore`), + the client's guess of the key first. The slice is a count, the same on + both sides, so no guess is wrong (a slice the clock ended was the + client's clock's verdict, which the session's own contradicted).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch)) + env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k} + env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'), + TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + tree = root / 'tree' + for d in range(200): + (tree / f'module_{d}').mkdir(parents=True) + for f in range(200): + (tree / f'module_{d}' / f'replica_{f}.zig').touch() + notes = tree / 'notes.txt' + notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300))) + started, terms = [], [] + try: + sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + wait_for('the replica socket', (root / 'pardes-replica.sock').exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists) + nine = Client(root / 'pardes-9p-find.sock') + text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'], + dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats'))) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30) + time.sleep(.3) + # SPC f f: the Find, typed into, its names walked on the session's worker. + os.write(t.master, b' ff') + time.sleep(3) + wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60) + query = b'module_19/replica_3' + for ch in query: + os.write(t.master, bytes([ch])) + time.sleep(.15) + seen = len(checks(root / 'q.check')) + wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60) + c.send_signal(signal.SIGHUP) + c.wait(timeout=20) + line = (root / 'q.stats').read_text().split() + got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)} + print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs ' + f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once') + assert got['mispredicted'] == '0', got + exit_session(nine, text) + sess.wait(timeout=60) + nine.socket.close() + finally: + for term in terms: + term.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def far_joins(sock, session, binary, n): """`n` far joins of one session in a row, each read whole (its blobs asked for by none, its zstd frames unpacked) and answering a ping, then @@ -2238,6 +2306,9 @@ if __name__ == '__main__': elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) by_hash(sys.argv[2]) + far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--far-find']: + far_find(sys.argv[2]) elif sys.argv[1:2] == ['--window-clients']: window_clients(sys.argv[2], sys.argv[3]) pdf_window(sys.argv[2], sys.argv[3]) diff --git a/test/perf.zig b/test/perf.zig index 7920dedf..8c88ef01 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -391,6 +391,8 @@ const Options = struct { creation: bool = false, startup: bool = false, mini: bool = false, + /// The scans a frame's slice bounds, a call at a time (`measureSearch`). + search: bool = false, terminal_mib: ?usize = null, /// The real binary's keystroke-to-present, `yes` stream and big open /// (a tty pardes), or its keystrokes alone (a pardes-gui). @@ -407,13 +409,14 @@ const Options = struct { while (i < args.len) : (i += 1) { const arg = args[i]; if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption; - const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse + const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse return error.UnknownOption; switch (option) { .json => opts.json = true, .creation => opts.creation = true, .startup => opts.startup = true, .mini => opts.mini = true, + .search => opts.search = true, .@"self-test" => opts.self_test = true, else => { i += 1; @@ -475,6 +478,7 @@ pub fn main(init: std.process.Init) !void { if (opts.creation) return measureCreation(init.io, reps, opts.json); if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json); if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json); + if (opts.search) return measureSearch(init.io); if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json); if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json); // The image-frame cells load the image addon by the path the build baked @@ -1742,6 +1746,138 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool) } } +/// `--search`: the two scans a frame's slice bounds, each call timed and +/// its instructions counted (user space, this thread): a find's names +/// scored again as a query is typed into it over 200,000 paths +/// (core/Names.zig `rescore`, Names' cap), and a search's places found a +/// tick at a time over the large fixture, the view in its middle +/// (core/Places.zig `settle` on a tick). The longest call of each is the +/// slice a key or a frame can take. +fn measureSearch(io: std.Io) !void { + var random: [12]u8 = undefined; + io.random(&random); + const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-perf-{x}", .{random}); + defer gpa.free(dir); + try std.Io.Dir.createDirAbsolute(io, dir, .default_dir); + defer std.Io.Dir.cwd().deleteTree(io, dir) catch {}; + var counter: Instructions = try .open(); + defer counter.close(); + + const Names = @FieldType(pardes.panes.Query, "names"); + var names: Names = .{}; + defer names.deinit(gpa); + const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" }; + const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" }; + var row: [160]u8 = undefined; + for (0..200_000) |i| { + const path = try std.fmt.bufPrint(&row, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i }); + try names.add(gpa, path, 0, path.len, Names.baseOf(path), 0); + } + // Typed a key at a time, as into a find: each key's call, then the + // calls of the frames after it while it is busy. + for ([_][]const u8{ "m", "tape", "places zig", "core/module_9/replica_1", "zig-pkg/ghostty/src/terminal/module_99/kitty" }) |query| { + var slow: Slowest = .{}; + names.typed(gpa, ""); + for (1..query.len + 1) |n| { + var calls: usize = 0; + while (true) : (calls += 1) { + const was = counter.read(); + const t0 = nowNs(); + if (calls == 0) names.typed(gpa, query[0..n]) else names.rescore(gpa); + slow.add(nowNs() -| t0, counter.read() -| was, names.hits.items.len); + if (!names.busy()) break; + } + } + slow.report("rescore", query, names.hits.items.len); + } + + const fx = fixtures[2]; + const path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, fx.name }); + defer gpa.free(path); + const text = try generate(fx); + try writeFile(path, text); + gpa.free(text); + for ([_][]const u8{ "e", "lorem.*amet", "helper_[0-9]+", "qqq" }) |pattern| { + const core = try boot(); + defer core.deinit(); + pardes.look.lookAt(core, 0, path); + pump(core); + const id = filePane(core) orelse return error.OpenDidNotOpenFile; + const pane = core.panes[id].?; + seek(pane, fx, 0); + pane.file.?.scroll = fx.lines / 2; + pane.body.cur_row = @intCast(fx.lines / 2); + _ = try frame(core); + const set = &pane.places; + set.search(core, pane, .typed, pane.serial, pattern, false, null, false); + var slow: Slowest = .{}; + while (set.busy(pane) and slow.calls < 100_000) { + const was = counter.read(); + const t0 = nowNs(); + set.settle(core, pane, true); + slow.add(nowNs() -| t0, counter.read() -| was, 0); + } + slow.report("fill", pattern, set.hits.items.len); + } +} + +/// The longest of a scan's calls. +const Slowest = struct { + calls: usize = 0, + total_ns: u64 = 0, + ns: u64 = 0, + /// The instructions of the longest call (by time), and the most of any. + ins: u64 = 0, + most_ins: u64 = 0, + /// The same of the calls that left under 1,000 hits to sort: the scan + /// alone, nearly (`Names.rescore` sorts every hit at each call). + few_ns: u64 = 0, + few_ins: u64 = 0, + + fn add(s: *Slowest, ns: u64, ins: u64, hits: usize) void { + s.calls += 1; + if (hits < 1000 and ns > s.few_ns) { + s.few_ns = ns; + s.few_ins = ins; + } + s.total_ns += ns; + if (ns > s.ns) { + s.ns = ns; + s.ins = ins; + } + s.most_ins = @max(s.most_ins, ins); + } + + fn report(s: *const Slowest, what: []const u8, of: []const u8, hits: usize) void { + std.debug.print("{s} \"{s}\": {d} calls, {d} hits, {d:.2} ms in all; longest {d} us ({d} instructions); most instructions {d}; longest with under 1,000 hits {d} us ({d} instructions)\n", .{ + what, of, s.calls, hits, @as(f64, @floatFromInt(s.total_ns)) / 1e6, s.ns / 1000, s.ins, s.most_ins, s.few_ns / 1000, s.few_ins, + }); + } +}; + +/// This thread's instructions in user space (perf_event_open). +const Instructions = struct { + fd: std.posix.fd_t, + + fn open() !Instructions { + const linux = std.os.linux; + var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } }; + const rc = linux.perf_event_open(&attr, 0, -1, -1, 0); + if (linux.errno(rc) != .SUCCESS) return error.NoInstructionCounter; + return .{ .fd = @intCast(rc) }; + } + + fn read(c: Instructions) u64 { + var n: u64 = 0; + _ = std.os.linux.read(c.fd, std.mem.asBytes(&n), 8); + return n; + } + + fn close(c: Instructions) void { + _ = std.os.linux.close(c.fd); + } +}; + fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void { const f = &pane.file.?; const span = @max(1, fx.lines * 8 / 10); |
