diff options
| -rw-r--r-- | abi/wasm.zig | 146 | ||||
| -rw-r--r-- | abi/wire.zig | 5 | ||||
| -rw-r--r-- | build.zig | 102 | ||||
| -rw-r--r-- | build/core.zig | 24 | ||||
| -rw-r--r-- | core/Core.zig | 23 | ||||
| -rw-r--r-- | core/Query.zig | 65 | ||||
| -rw-r--r-- | core/Stream.zig | 29 | ||||
| -rw-r--r-- | core/Term.zig | 13 | ||||
| -rw-r--r-- | core/grammar_manifest.zig | 8 | ||||
| -rw-r--r-- | core/hunks.zig | 300 | ||||
| -rw-r--r-- | core/lib_syntax.zig | 17 | ||||
| -rw-r--r-- | core/normal.zig | 94 | ||||
| -rw-r--r-- | core/panes.zig | 18 | ||||
| -rw-r--r-- | core/replica.zig | 530 | ||||
| -rw-r--r-- | core/root.zig | 4 | ||||
| -rw-r--r-- | core/syntax.zig | 7 | ||||
| -rw-r--r-- | core/tape.zig | 16 | ||||
| -rw-r--r-- | core/term/terminal.zig | 31 | ||||
| -rw-r--r-- | core/views.zig | 43 | ||||
| -rw-r--r-- | docs/typ/building.typ | 111 | ||||
| -rw-r--r-- | runtime/client.zig | 7 | ||||
| -rw-r--r-- | test/consumer/build.zig | 77 | ||||
| -rw-r--r-- | test/consumer/lib.zig | 95 | ||||
| -rw-r--r-- | test/consumer/none.zig | 56 | ||||
| -rw-r--r-- | test/consumer/one.zig | 45 | ||||
| -rw-r--r-- | test/consumer/wasm.mjs | 113 | ||||
| -rw-r--r-- | test/daemon.py | 97 | ||||
| -rw-r--r-- | test/replicas.zig | 720 |
28 files changed, 2485 insertions, 311 deletions
diff --git a/abi/wasm.zig b/abi/wasm.zig new file mode 100644 index 00000000..d2b3889a --- /dev/null +++ b/abi/wasm.zig @@ -0,0 +1,146 @@ +//! A browser's module (build.zig `wasmModule`: wasm32-wasi, a reactor): the +//! functions a page calls, the same in every module. Every pointer and +//! length is a wasm32 address or count, an unsigned 32-bit integer; numbers +//! in memory are little-endian. docs/typ/building.typ has the layouts. +//! +//! - `reserve(len)`: `len` bytes (one at least, so a pointer even for 0) +//! for the page to write an argument into; `release(ptr, len)` gives them +//! back. +//! - `highlight(path, path_len, text, len)` (a module with a language): a +//! style byte for each byte of `text`, a `Syn` (0 none, 1 keyword, 2 +//! string, 3 number, 4 comment), as pardes colours the file `path` names +//! by its extension; all 0 for a file of another language. The module's +//! until the next `highlight`. +//! - `patch(text, len)`: the diff `text` stacked as pardes's patch view +//! shows it (`formatPatch`, with no file and no colours): a `Header`, its +//! rows' text, a style byte for each byte of it, and a `Record` a row. +//! The module's until the next `patch`. +//! +//! Each returns null (0) when its memory runs out. +const std = @import("std"); +const ps = @import("pardes-syntax"); +const options = @import("wasm_options"); + +const gpa = std.heap.wasm_allocator; + +/// A panic's message to stderr (fd 2) in one `fd_write`, then a trap: std's +/// own handler writes through std.Io, which imports 26 more of WASI's +/// functions a page would have to stub. +pub const panic = std.debug.FullPanic(struct { + fn write(message: []const u8, _: ?usize) noreturn { + var written: usize = 0; + _ = std.os.wasi.fd_write(2, &.{.{ .base = message.ptr, .len = message.len }}, 1, &written); + @trap(); + } +}.write); + +comptime { + // A module with no language has no highlighter, and so no tree-sitter. + if (options.highlight) @export(&highlight, .{ .name = "highlight" }); +} + +export fn reserve(len: usize) ?[*]u8 { + return (gpa.alloc(u8, @max(len, 1)) catch return null).ptr; +} + +export fn release(ptr: [*]u8, len: usize) void { + gpa.free(ptr[0..@max(len, 1)]); +} + +var started = false; +var styles: []u8 = &.{}; + +fn highlight(path: [*]const u8, path_len: usize, text: [*]const u8, len: usize) callconv(.c) ?[*]u8 { + if (!started) ps.start(gpa); + started = true; + gpa.free(styles); + styles = ps.highlightFileRange(gpa, path[0..path_len], text[0..len], 0, len) catch &.{}; + // A path in no language this module has, or an empty text: all plain. + if (styles.len == 0) { + styles = gpa.alloc(u8, @max(len, 1)) catch return null; + @memset(styles, 0); + } + return styles.ptr; +} + +/// What `patch` returns, 20 bytes. +pub const Header = extern struct { + /// The rows' text, a line a row, `text_len` bytes; the rows' paths + /// follow it in the same buffer. + text: u32, + text_len: u32, + /// A style byte for each byte of the text. + styles: u32, + /// `row_count` records of 36 bytes. + rows: u32, + row_count: u32, +}; + +/// A row, 36 bytes: nine u32. +pub const Record = extern struct { + /// 0 other, 1 meta, 2 hunk, 3 declaration, 4 context, 5 added, 6 removed + /// (`PatchRow.Kind`). + kind: u32, + /// Its numbers in the old and the new file, from 1; 0 where it has none. + old: u32, + new: u32, + /// Where its code starts, a byte of its text: after a label's + /// `path:line` and stars. + code_start: u32, + /// Its text, without its newline, and its section's path: offsets into + /// the header's `text`. + text_offset: u32, + text_len: u32, + path_offset: u32, + path_len: u32, + /// Bit 0: the diff has `\ No newline at end of file` after it. + flags: u32, +}; + +var arena_state: std.heap.ArenaAllocator = .init(gpa); + +export fn patch(text: [*]const u8, len: usize) ?*const Header { + _ = arena_state.reset(.retain_capacity); + return stack(arena_state.allocator(), text[0..len]) catch null; +} + +fn stack(arena: std.mem.Allocator, diff: []const u8) !*const Header { + const p = try ps.formatPatch(&.{ .arena = arena }, "", diff); + // The text, then each row's path where it changes from the row before. + var text: std.ArrayList(u8) = .empty; + try text.appendSlice(arena, p.text); + const marks = try arena.alloc(u8, p.text.len); + @memset(marks, 0); + const records = try arena.alloc(Record, p.rows.len); + var at: usize = 0; + var path: struct { []const u8, usize } = .{ "", 0 }; + for (p.rows, records) |row, *r| { + const line_len = std.mem.indexOfScalarPos(u8, p.text, at, '\n').? - at; + @memcpy(marks[at..][0..row.styles.len], row.styles); + if (!std.mem.eql(u8, row.path, path[0])) { + path = .{ row.path, text.items.len }; + try text.appendSlice(arena, row.path); + } + r.* = .{ + .kind = @backingInt(row.kind), + .old = @intCast(row.old orelse 0), + .new = @intCast(row.new orelse 0), + .code_start = @intCast(row.code_start), + .text_offset = @intCast(at), + .text_len = @intCast(line_len), + .path_offset = @intCast(path[1]), + .path_len = @intCast(row.path.len), + .flags = @intFromBool(row.no_newline), + }; + at += line_len + 1; + } + const header = try arena.create(Header); + header.* = .{ + .text = @intCast(@intFromPtr(text.items.ptr)), + .text_len = @intCast(p.text.len), + .styles = @intCast(@intFromPtr(marks.ptr)), + .rows = @intCast(@intFromPtr(records.ptr)), + .row_count = @intCast(records.len), + }; + return header; +} diff --git a/abi/wire.zig b/abi/wire.zig index cde9413e..88a82e52 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -12,8 +12,9 @@ const build_info = @import("build_info"); /// 27: a pair's first client makes its own core from the session's /// options and says its digest (`boot`) before its `far`: the session sends -/// no dump when its own at the join has the same (26 is the terminals' -/// line's); +/// no dump when its own at the join has the same; +/// 26: a view kept for its client's rejoin says when it went away +/// (View.away_ns), and is that client's for Views.away_kept_ns; /// 25: the 9P state a session's requests made (its open records, each /// pane's, the panes the last look or exec touched, a header's /// truncation) is in its join's dump and its digest (core/fs.zig Namespace); @@ -26,8 +26,21 @@ //! //! `.grammars`: the tree-sitter grammars compiled in: `none` (the runtime //! alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default). -//! `.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it -//! fetches uucode, mvzr and vaxis. +//! `.languages`: instead of `.grammars`, the languages compiled in by name +//! (`"rust"`, or `&.{ "rust", "go" }`), each with what it needs (markdown +//! its inline grammar); a name the manifest does not have fails the +//! configure. `.editor`: exports `pardes-editor` besides `pardes-syntax`, +//! and with it fetches uucode, mvzr and vaxis. +//! +//! The manifest, for a package's build script to read at configure time +//! (`@import("pardes").grammar_manifest.all`: each grammar's name, its +//! extensions and what it needs), is `grammar_manifest`. +//! +//! A browser's module, one call a language (`wasmModule`): +//! +//! const pardes = @import("pardes"); +//! b.installArtifact(pardes.wasmModule(b, .{ .language = "rust" })); +//! b.installArtifact(pardes.wasmModule(b, .{})); // the patch view alone //! //! Every dependency but tree-sitter's runtime is lazy in the manifest, so //! such a package fetches what it asked for and nothing else. @@ -72,13 +85,20 @@ pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, . pub const TreeSitterGrammars = enum { none, minimal, full }; +/// Every grammar pardes knows (the head comment). +pub const grammar_manifest = @import("core/grammar_manifest.zig"); + pub fn build(b: *std.Build) void { // What a package that depends on pardes may ask for (the head comment). // pardes's own build takes the mode and the grammars too, and its target // below, whose default -Dplatform says. const optimize = b.standardOptimizeOption(.{}); - const grammars = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)") orelse .full; - if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, grammars, b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false); + const grammars_option = b.option(TreeSitterGrammars, "grammars", "the tree-sitter grammars compiled in: none (the runtime alone), minimal (C, C++ and Zig) or full (all of them; the default)"); + const grammars = grammars_option orelse .full; + if (!b.isRoot()) return library(b, b.standardTargetOptions(.{}), optimize, librarySet( + grammars_option, + b.option([]const []const u8, "languages", "instead of grammars, the languages compiled in by name, each with what it needs"), + ), b.option(bool, "editor", "exports pardes-editor besides pardes-syntax, and with it fetches uucode, mvzr and vaxis") orelse false); // Everything below is pardes's own: the editor, its tests and tools. // This configure reads the environment (HOME, XDG_DATA_HOME, @@ -389,6 +409,46 @@ pub fn build(b: *std.Build) void { } } +/// A browser's module, one call a language (the head comment): wasm32-wasi +/// as a reactor (no `main`; `_initialize`, then any export), with +/// `language`'s grammar and what it needs, tree-sitter's runtime and +/// pardes's highlighter; or, with no language, the patch view alone, with +/// no tree-sitter in it. Its exports are abi/wasm.zig's (`memory`, +/// `_initialize`, `reserve`, `release`, `patch`, and with a language +/// `highlight`), the same in every module; docs/typ/building.typ has their +/// layouts and the WASI imports a page stubs. The package's dependency on +/// pardes is named "pardes". A name the manifest does not have fails the +/// configure, as `.languages` does. +pub fn wasmModule(b: *std.Build, options: struct { + language: ?[]const u8 = null, + optimize: std.lang.Optimize = .ReleaseSmall, +}) *std.Build.Step.Compile { + const target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .wasi }); + const pardes = if (options.language) |name| + b.dependency("pardes", .{ .target = target, .optimize = options.optimize, .languages = name }) + else + b.dependency("pardes", .{ .target = target, .optimize = options.optimize, .grammars = .none }); + const exports = b.addOptions(); + exports.addOption(bool, "highlight", options.language != null); + const module = b.addExecutable(.{ + .name = b.fmt("pardes-{s}", .{options.language orelse "patch"}), + .root_module = b.createModule(.{ + .target = target, + .optimize = options.optimize, + .root_source_file = pardes.path("abi/wasm.zig"), + .imports = &.{ + .{ .name = "pardes-syntax", .module = pardes.module("pardes-syntax") }, + .{ .name = "wasm_options", .module = exports.createModule() }, + }, + }), + }); + module.entry = .disabled; + module.wasi_exec_model = .reactor; + // Its own functions alone: tree-sitter's and libc's stay inside. + module.root_module.export_symbol_names = if (options.language != null) &.{ "reserve", "release", "patch", "highlight" } else &.{ "reserve", "release", "patch" }; + return module; +} + /// Installs `artifact` in the prefix and, given `home_bin`, copies it there /// too (`install` unlinks first, so a running binary is replaced). fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]const u8) void { @@ -401,13 +461,38 @@ fn installHome(b: *std.Build, artifact: *std.Build.Step.Compile, home_bin: ?[]co b.getInstallStep().dependOn(©.step); } +/// The grammars a dependent package asked for: the languages it named and +/// what each needs (the manifest's), or its tier's. A language the manifest +/// does not have, or a tier beside languages, ends the configure: Zig +/// reports an option it cannot read and builds on (exit code 0). +fn librarySet(grammars: ?TreeSitterGrammars, languages: ?[]const []const u8) core.GrammarSet { + const names = languages orelse return core.tierSet(grammars orelse .full); + if (grammars) |tier| fatal("pardes: `.languages` replaces `.grammars` (here .{t}): give one of them", .{tier}); + var set: core.GrammarSet = @splat(false); + for (names) |name| { + const i = grammar_manifest.byName(name) orelse fatal("pardes: no language \"{s}\" in its manifest (`.languages`); it has:{s}", .{ name, comptime known: { + var all: []const u8 = ""; + for (grammar_manifest.all) |g| all = all ++ " " ++ g.name; + break :known all; + } }); + set[i] = true; + for (grammar_manifest.all[i].needs) |need| set[grammar_manifest.byName(need).?] = true; + } + return set; +} + +fn fatal(comptime format: []const u8, args: anytype) noreturn { + std.log.err(format, args); + std.process.exit(1); +} + /// What a package that depends on pardes is given (the head comment): /// `pardes-syntax`, the grammars, highlighting and themes, over tree-sitter /// and the grammars of its set alone; and with `editor`, `pardes-editor`, /// whose uucode, mvzr and vaxis (with what its build names) are fetched /// then and only then. Of vaxis it takes the grapheme width, which uucode /// alone feeds. -fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, grammars: TreeSitterGrammars, editor: bool) void { +fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.Optimize, set: core.GrammarSet, editor: bool) void { var threaded: std.Io.Threaded = .init(b.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); @@ -417,10 +502,11 @@ fn library(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.lang.O .root_source_file = b.path("core/lib_syntax.zig"), .link_libc = true, }); - // A library's options: its grammars, nothing stamped, no window. - const cfg: core.ShellConfig = .{ .tree_sitter_grammars = grammars }; + // A library's options: nothing stamped, no window, and a tier only + // pardes's own tests read (syntax.zig knows the set by its queries). + const cfg: core.ShellConfig = .{ .tree_sitter_grammars = if (std.mem.eql(bool, &set, &core.tierSet(.full))) .full else if (std.mem.eql(bool, &set, &core.tierSet(.minimal))) .minimal else .none }; mod.addOptions("pardes_options", core.options(b, cfg, .{ .root = "core/lib_syntax.zig", .platform = .tui, .terminal = false }, false)); - const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, grammars); + const ts = core.treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, set); const themes = core.generatedThemes(b, io, target, optimize); mod.addImport("generated_themes", themes); ts.wire(mod); diff --git a/build/core.zig b/build/core.zig index b668211d..63b4a5e9 100644 --- a/build/core.zig +++ b/build/core.zig @@ -144,6 +144,16 @@ pub fn generatedThemes(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarg }); } +/// The grammars a build compiles in, a flag each in the manifest's order. +pub const GrammarSet = [grammar_manifest.all.len]bool; + +/// A tier's (`-Dgrammars`, a dependent package's `.grammars`). +pub fn tierSet(tier: TreeSitterGrammars) GrammarSet { + var set: GrammarSet = undefined; + for (grammar_manifest.all, &set) |g, *in| in.* = tier == .full or (tier == .minimal and g.tier == .minimal); + return set; +} + pub const TreeSitter = struct { mod: *std.Build.Module, queries: *std.Build.Step.Options, @@ -158,15 +168,15 @@ pub const TreeSitter = struct { }; /// tree-sitter's bindings, and for each grammar of the set its queries (the -/// `ts_queries` options syntax.zig reads) and its parser, a static library. -/// A grammar not fetched yet is asked for and left out: the configure runs -/// again once it is there. -pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, tree_sitter_grammars: TreeSitterGrammars) TreeSitter { +/// `ts_queries` options syntax.zig reads, and by which it knows the set) +/// and its parser, a static library. A grammar not fetched yet is asked for +/// and left out: the configure runs again once it is there. +pub fn treeSitter(b: *std.Build, io: std.Io, target: std.Build.ResolvedTarget, c_optimize: std.lang.Optimize, set: GrammarSet) TreeSitter { const tree_sitter_mod = b.dependency("tree_sitter", .{ .target = target, .optimize = c_optimize }).module("tree_sitter"); var ts_libs: std.ArrayList(*std.Build.Step.Compile) = .empty; const ts_queries = b.addOptions(); - inline for (grammar_manifest.all) |g| { - if (tree_sitter_grammars == .full or (tree_sitter_grammars == .minimal and g.tier == .minimal)) grammar: { + inline for (grammar_manifest.all, set) |g, in| { + if (in) grammar: { const dep = b.dependencyLazy(g.dep, .{}) catch break :grammar; const upstream = configureRead(b, io, dep.builder.root, g.query, 0x100000) catch @panic("read " ++ g.name ++ " highlights"); // the patterns that colour, filtered here once and not in @@ -433,7 +443,7 @@ pub fn assemble(b: *std.Build, c: struct { // nothing else. pardes takes these whatever it builds: the missing ones // are asked for here in one round, the grammars with them, where each // `b.dependency` below would end the configure to fetch its own alone. - const ts = treeSitter(b, io, target, c_optimize, c.shell_cfg.tree_sitter_grammars); + const ts = treeSitter(b, io, target, c_optimize, tierSet(c.shell_cfg.tree_sitter_grammars)); inline for (.{ "cloud9", "vaxis", "ghostty", "uucode", "zstbi", "mvzr", "zstd", "xitdb" }) |name| { // A dependency by path (none of these today) has no hash and is always there. const dep = @field(zon.dependencies, name); diff --git a/core/Core.zig b/core/Core.zig index 55b3682f..d2cfadfc 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -127,6 +127,9 @@ pub const View = struct { /// pane (util.c:467). Where the acme placement puts new panes /// (layout.placeNew). A Look click moves the keyboard but not this. active_column: u32 = 0, + /// When its client went away to join again for it (Views.away), on + /// the session's clock. + away_ns: u64 = 0, /// The live view's frontend (Event.frontend): a window, what it draws and /// the words it takes (builtins.zig `here`); it starts as /// `Options.windowed` says. @@ -1161,21 +1164,27 @@ pub inline fn view(p: anytype) if (@typeInfo(@TypeOf(p)).pointer.attrs.@"const") pub const openView = pardes.tape.taped(openViewInner); fn openViewInner(p: *Pardes) ?View.Id { // Every view taken: one kept for a client that has not come back - // for it (Views.away) goes first. ponytail: no timer lets one go; - // until its place is wanted it costs a parked slot, and a terminal - // it sized last keeps that size until another view types into it. - if (@popCount(p.views_open) == Views.max and p.views_away != 0) { - Views.close(p, @ctz(p.views_away)); + // for it in Views.away_kept_ns (Views.away) goes first; one kept + // since is its client's, and the join is refused. ponytail: no timer + // lets one go; until its place is wanted it costs a parked slot, and + // a terminal it sized last keeps that size until another view types + // into it. + if (@popCount(p.views_open) == Views.max) for (0..Views.max) |k| { + if (!Views.isAway(p, @intCast(k)) or p.clock.now_ns -| p.views[k].?.away_ns < Views.away_kept_ns) continue; + Views.close(p, @intCast(k)); p.sync(); - } + break; + }; // What was queued since the last pump (a leaving client's view // closed, a 9P request's step) done first, as every client of the // tape does it here: a join dumps the session next, and a core // loaded from a dump has no queue (Replica.initDump). p.settle(); + // A join refused (every view taken) reloads nothing. + const k = Views.open(p) orelse return null; pardes.panes.reloadTerminals(p); p.needs_frame = true; - return .at(Views.open(p) orelse return null); + return .at(k); } /// The client of view `k` gone: its view goes, the others stay. The diff --git a/core/Query.zig b/core/Query.zig index 3a5aa5f8..e2f59028 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -888,6 +888,7 @@ fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locatio if (gutter + code.len > buf.len) return; @memset(buf[address.len..gutter], ' '); @memcpy(buf[gutter..][0..code.len], code); + sh.file(p, path); try writeRow(p, out, rows, buf[0 .. gutter + code.len], .{ .kind = .match, .source_column = lead, @@ -895,16 +896,16 @@ fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locatio .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, .location_end = address.len, .code_start = gutter, - .colors = @constCast(if (shade.len >= lead + code.len) shade[lead..][0..code.len] else sh.of(p, path, line_no, code, lead)), + .colors = @constCast(if (shade.len >= lead + code.len) shade[lead..][0..code.len] else sh.of(line_no, code, lead)), }); } /// Rows' syntax colours from their file's whole (as Callstack's rows are), /// kept in the locations cache once a worker has painted it /// (Stream.paintRows): the line found going down the file a row at a time, -/// so a refill walks each file once. A file not painted, or whose line no -/// longer reads as the row does, is asked for (once a refill) and its rows -/// are plain till it lands (`recolor`). +/// so a refill walks each file once. Every file is asked for once its rows +/// are made (`file`, `done`; Stream.paintRows asks each once a Grep), and +/// a row it does not colour is plain till it lands (`recolor`). const Shades = struct { path: []const u8 = "", source: []const u8 = "", @@ -912,50 +913,54 @@ const Shades = struct { /// The line (1-based) that starts at `at` in `source`. line: usize = 1, at: usize = 0, - asked: bool = false, - /// The colours of `code`, which is line `line_no` of `path` from byte - /// `column` on, or none. - fn of(sh: *Shades, p: *Pardes, path: []const u8, line_no: usize, code: []const u8, column: usize) []const u8 { - if (path.len == 0 or line_no == 0 or code.len == 0) return &.{}; - if (!std.mem.eql(u8, path, sh.path)) { - // its own copy: a caller's path is often a buffer it reuses - sh.* = .{ .path = p.scratch.allocator().dupe(u8, path) catch return &.{} }; - if (p.locations_cache.peek(path)) |e| { - sh.source = e.source; - sh.colors = e.colors; - } + /// The rows of `path` follow (a caller's buffer: copied): the file + /// before them done. Called for every row, whatever colours it has, so + /// that every process asks paintRows at the same rows. + fn file(sh: *Shades, p: *Pardes, path: []const u8) void { + if (std.mem.eql(u8, path, sh.path)) return; + sh.done(p); + sh.* = .{ .path = p.scratch.allocator().dupe(u8, path) catch "" }; + if (p.locations_cache.peek(path)) |e| { + sh.source = e.source; + sh.colors = e.colors; } - if (sh.colors.len == 0 or sh.colors.len != sh.source.len) return sh.ask(p); + } + + /// The file's rows are made: its colours asked of a worker. + fn done(sh: *Shades, p: *Pardes) void { + if (sh.path.len > 0) Stream.paintRows(p, sh.path); + } + + /// The colours of `code`, which is line `line_no` of the file `file` + /// named from byte `column` on, or none. + fn of(sh: *Shades, line_no: usize, code: []const u8, column: usize) []const u8 { + if (sh.path.len == 0 or line_no == 0 or code.len == 0) return &.{}; + if (sh.colors.len == 0 or sh.colors.len != sh.source.len) return &.{}; if (line_no < sh.line) { sh.line = 1; sh.at = 0; } while (sh.line < line_no) : (sh.line += 1) { - sh.at = (std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse return sh.ask(p)) + 1; + sh.at = (std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse return &.{}) + 1; } const line = sh.source[sh.at .. std.mem.indexOfScalarPos(u8, sh.source, sh.at, '\n') orelse sh.source.len]; - if (column + code.len > line.len or !std.mem.eql(u8, line[column..][0..code.len], code)) return sh.ask(p); + if (column + code.len > line.len or !std.mem.eql(u8, line[column..][0..code.len], code)) return &.{}; return sh.colors[sh.at + column ..][0..code.len]; } - - fn ask(sh: *Shades, p: *Pardes) []const u8 { - if (!sh.asked) Stream.paintRows(p, sh.path); - sh.asked = true; - return &.{}; - } }; /// A file's colours arrived (Stream.paintRows): every query pane's hit /// rows still plain, live or frozen, coloured from what is painted now, in -/// place; the first row of a file not painted yet asks for it, so they are -/// painted one after another. +/// place; the next file not asked yet is asked for, so they are painted +/// one after another. pub fn recolor(p: *Pardes) void { for (p.panes) |slot| { const rp = slot orelse continue; if (rp.query == null) continue; const f = &rp.file.?; var sh: Shades = .{}; + defer sh.done(p); var lines = std.mem.splitScalar(u8, f.content, '\n'); // The rows are a blob (File.State): a digest keeps its word for // them and a rollback copy pins them, so they are made again, never @@ -967,9 +972,10 @@ pub fn recolor(p: *Pardes) void { for (f.location_rows, 0..) |row, i| { const text = lines.next() orelse break; if (row.kind != .match or row.location_end == 0 or row.at.line == 0 or row.colors.len == 0) continue; + sh.file(p, row.path); if (std.mem.indexOfNone(u8, row.colors, &.{0}) != null) continue; const code = text[@min(row.code_start, text.len)..]; - const got = sh.of(p, row.path, row.at.line, code[0..@min(code.len, row.colors.len)], row.source_column); + const got = sh.of(row.at.line, code[0..@min(code.len, row.colors.len)], row.source_column); if (got.len == 0) continue; const rows = fresh orelse locations.cloneRows(p.gpa, f.location_rows) catch break; fresh = rows; @@ -1027,6 +1033,7 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar const rel = lookPath(&relbuf, path, dir); const width = addressWidth(rel, index.len); var sh: Shades = .{}; + defer sh.done(p); const decls = ownerDecls(f) orelse &.{}; var decl_now: ?usize = null; var i: usize = @min(from, hits.len); @@ -1182,6 +1189,7 @@ fn makeGrepRows(p: *Pardes, id: usize, full: bool) !void { } var current: ?usize = null; var sh: Shades = .{}; + defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; for (q.found.items[lo..hi], lo..) |fd, i| { @@ -1342,6 +1350,7 @@ fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { var pathbuf: [4096 + 8]u8 = undefined; var n: usize = 0; var sh: Shades = .{}; + defer sh.done(p); var width: usize = 0; var relbuf: [4096]u8 = undefined; for (sorted.items, 0..) |ln, li| { diff --git a/core/Stream.zig b/core/Stream.zig index a04cad46..f65d0683 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -245,10 +245,10 @@ ahead_seen: struct { serial: u32 = 0, scroll: usize = 0, dir: i2 = 1 } = .{}, /// the next asked when it lands (Query.recolor); a worker per file if a /// Grep of hundreds of files colours too slowly. rows_paint: ?TextTask = null, -/// The files (a hash of path and revision) asked since the last Grep -/// began: each asked once, so a file whose colours never fit its rows -/// (changed on disk since) is not painted again and again. ponytail: a -/// ring of 256; the oldest forgotten. +/// The files (a hash of the path) asked since the last Grep began: each +/// asked once, so a file whose colours never fit its rows (changed on +/// disk since, an edit) is not painted again and again. ponytail: a ring +/// of 256; the oldest forgotten. rows_asked: [256]u64 = @splat(0), rows_asked_at: u8 = 0, /// Rows asked for their colours while a 9P write was served: asked again @@ -352,17 +352,13 @@ pub fn askAhead(p: *Pardes) void { /// from disk there. Kept in the locations cache when it lands, where the /// rows find them (Query.Shades). Not without workers (the rows stay /// plain), nor for a file bigger than `max_rows_paint_bytes`, nor twice for -/// one revision of a file. +/// a file between two Greps. Asked after every file's rows, whatever +/// colours they have here: those are this process's own (what its frames +/// painted of the text, what its locations cache kept: in no digest), and +/// what a step asks of a worker must not hang on them. pub fn paintRows(p: *Pardes, path: []const u8) void { const s = &p.stream; if (s.rows_paint != null or !p.tape.has(p, .search)) return; - // Asked while a 9P write is served (a script's Grep): not now, as no - // paint is (the write would wait for it to settle); the next step asks. - if (p.fs.serving) { - s.rows_later = true; - return; - } - if (!syntax.readyApart(path)) return; var content: ?[]const u8 = null; var revision: u32 = 0; for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output == null and std.mem.eql(u8, f.path, path)) { @@ -371,8 +367,15 @@ pub fn paintRows(p: *Pardes, path: []const u8) void { break; }; if (content) |c| if (c.len > max_rows_paint_bytes) return; - const key = std.hash.Wyhash.hash(revision, path) | 1; + const key = std.hash.Wyhash.hash(0, path) | 1; if (std.mem.indexOfScalar(u64, &s.rows_asked, key) != null) return; + if (!syntax.readyApart(path)) return; + // Asked while a 9P write is served (a script's Grep): not now, as no + // paint is (the write would wait for it to settle); the next step asks. + if (p.fs.serving) { + s.rows_later = true; + return; + } const job = TextJob.make(p.gpa, 0, revision, 0, path, content orelse "") orelse return; s.rows_asked[s.rows_asked_at] = key; s.rows_asked_at +%= 1; diff --git a/core/Term.zig b/core/Term.zig index aa05a68f..6ef9b0a5 100644 --- a/core/Term.zig +++ b/core/Term.zig @@ -65,6 +65,12 @@ fn the() *const iface.Ops { /// as it always has (`Parts` by name, then ghostty's snapshot). pub const State = struct { impl: *iface.State, + /// Written since its last reload (a feed, a reflow, a load: what cuts + /// its rows into pages), which a join reloads (panes.reloadTerminals, + /// the session's choice). One not holds the pages its last reload's + /// snapshot loads to, on every side, and so does a joiner loading the + /// same snapshot again from the dump. + written: bool = true, /// The emulator as its program has made it, for the replay digest. /// Under screen-state terminals the emulator is the authority's, and a @@ -167,7 +173,9 @@ pub fn reload(s: *State) !u64 { reloads.ns += dt; reloads.worst_ns = @max(reloads.worst_ns, dt); } - return the().reload(s.impl); + const hash = try the().reload(s.impl); + s.written = false; + return hash; } /// When its next kitty animation frame is due (ms on the core's clock), as @@ -180,6 +188,7 @@ pub fn due(s: *const State) ?u64 { /// history marked off from what the next shell prints. pub fn revive(s: *State) void { writes +%= 1; + s.written = true; the().revive(s.impl); } @@ -199,6 +208,7 @@ pub fn stop() void { /// went). pub fn feed(s: *State, bytes: []const u8, tracked: []const i32, rows: []i32, erased: []bool) Told { writes +%= 1; + s.written = true; return the().feed(s.impl, bytes, tracked, rows, erased); } @@ -229,6 +239,7 @@ pub fn follow(s: *State) void { /// Its grid reflowed, now or when `resizeDeferred` makes it. pub fn resize(s: *State, cols: u16, rows: u16, later: bool) void { writes +%= 1; + s.written = true; the().resize(s.impl, cols, rows, later); } diff --git a/core/grammar_manifest.zig b/core/grammar_manifest.zig index b4ff30b9..b0ce146c 100644 --- a/core/grammar_manifest.zig +++ b/core/grammar_manifest.zig @@ -17,6 +17,12 @@ pub const Grammar = struct { query: []const u8 = "queries/highlights.scm", /// Patterns appended to the highlights query before it is filtered. highlights_extra: []const u8 = "", + /// The grammars it cannot work without, compiled in with it when a + /// package names it alone (build.zig's `languages`). Only markdown has + /// one: its inline grammar. A fence's or a raw block's language + /// (markdown's, typst's) is coloured when it is in the build and left + /// plain when it is not. + needs: []const []const u8 = &.{}, }; pub const all = [_]Grammar{ @@ -38,7 +44,7 @@ pub const all = [_]Grammar{ .{ .name = "json", .dep = "ts_json", .exts = &.{".json"}, .tier = .full }, .{ .name = "kotlin", .dep = "ts_kotlin", .exts = &.{ ".kt", ".kts" }, .tier = .full, .scanner = true }, .{ .name = "ocaml", .dep = "ts_ocaml", .exts = &.{ ".ml", ".mli" }, .tier = .full, .src = "grammars/ocaml/src", .scanner = true }, - .{ .name = "markdown", .dep = "ts_markdown", .exts = &.{ ".md", ".markdown" }, .tier = .full, .src = "tree-sitter-markdown/src", .scanner = true, .query = "tree-sitter-markdown/queries/highlights.scm" }, + .{ .name = "markdown", .dep = "ts_markdown", .exts = &.{ ".md", ".markdown" }, .tier = .full, .src = "tree-sitter-markdown/src", .scanner = true, .query = "tree-sitter-markdown/queries/highlights.scm", .needs = &.{"markdown_inline"} }, // Second grammar off the SAME dep: the split_parser markdown repo ships a // block parser and an inline parser, and bold/italic/code-span live only in // the inline one. `.exts` is empty because no filename ever selects it — the diff --git a/core/hunks.zig b/core/hunks.zig index 837d2a52..98584980 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -5,6 +5,12 @@ //! green, coloured as their file, and the words a changed line changed on //! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` //! and `Alignment`). +//! +//! `format`, and what it takes and gives, names no pane and reads no file +//! but through its `Ctx`: `pardes-syntax` exports it (core/lib_syntax.zig) +//! for a program with no editor, a browser's reader, and with no colours +//! handed in it names no grammar either. The +Diff in the editor, the +//! file's second half, maps its rows onto a pane's (`paneResult`). const std = @import("std"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); @@ -15,45 +21,132 @@ const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Output = pardes.panes.Output; -const Row = locations.Row; - -/// What `format` takes of the editor it stacks for: its allocators, the -/// files a diff names read as the editor reads them (in pardes an open -/// pane's text, else the disk's, each read a site of the step's tape: -/// openDiff), their declarations, and one setting. +/// What `format` takes of the program it stacks for: an arena, the files a +/// diff names (in pardes an open pane's text, else the disk's, each read a +/// site of the step's tape: openDiff), their declarations, the diff's +/// colours, a text's width, one setting. A program with no files leaves +/// `source` to answer none: each hunk is numbered as the diff numbers it, +/// under git's own function line. pub const Ctx = struct { - /// The text and rows made, the caller's. - gpa: std.mem.Allocator, - /// All else, the call's. + /// What `format` makes and returns, the caller's to keep while it reads + /// the rows, and everything else of the call. arena: std.mem.Allocator, /// `path` as a look from `dir` finds it, its text the arena's (or the - /// editor's, good for the call); null when it is not there. - source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source, + /// caller's, good for the call); null when it is not there. + source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source = none, /// The declarations of `bytes`, the file at `path`, outermost first - /// (syntax.analyzeSource's), the arena's. - declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration, - /// The two above's own. - host: *anyopaque, + /// (`parsed`: syntax.analyzeSource's), the arena's; none by default. + declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration = noDeclarations, + /// A style byte for each byte of the diff, the arena's, its lines' + /// colours (`languages`: each hunk's as its file's language); null, the + /// grounds alone, and no grammar or tree-sitter in the program. + colors: ?*const fn (ctx: *const Ctx, content: []const u8) anyerror![]u8 = null, + /// The cells `text` takes, by which a removed and an added line are one + /// line changed or two (`max_line_distance`): its code points, or as + /// pardes's panes draw it. + width: *const fn (ctx: *const Ctx, text: []const u8) usize = codepoints, + /// The functions' own. + host: *anyopaque = undefined, /// A declaration above a hunk gets its `path:line` row too /// (LocationsConfig's tslocations). - tslocations: bool, - /// A tab's width in cells (the core's `settings.tab`). - tab: u16, + tslocations: bool = true, + + pub fn none(_: *const Ctx, _: []const u8, _: []const u8) ?Source { + return null; + } + + pub fn noDeclarations(_: *const Ctx, _: []const u8, _: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return &.{}; + } + + /// The file parsed by its path's grammar, each call. + pub fn parsed(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + } + + /// The diff coloured as the editor colours it (syntax.highlightDiff). + pub fn languages(ctx: *const Ctx, content: []const u8) anyerror![]u8 { + return syntax.highlightDiff(ctx.arena, content, 0, content.len); + } + + pub fn codepoints(_: *const Ctx, text: []const u8) usize { + var n: usize = 0; + for (text) |c| n += @intFromBool(c & 0xc0 != 0x80); + return n; + } }; /// A file's text, and its path as `dir` and the path named resolve. pub const Source = struct { path: []const u8, bytes: []const u8 }; -/// The rows `content`, a diff, stacks to, for a pane in `dir`, with each -/// row's metadata (Output.fillRows). Text and rows are `ctx.gpa`'s. -pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations.Result { +/// A diff stacked: its text, and a row for each of its lines (row i is +/// line i), the arena's; a row's path may be the diff's own bytes. +pub const Patch = struct { text: []const u8, rows: []const Row }; + +pub const Row = struct { + kind: Kind, + /// The file its section names, as `dir` finds it (the diff's name when + /// it is not found); "" for `other` and `meta`. + path: []const u8 = "", + /// The line of that file it points at, from 1 (0: none): where the file + /// has it now when `source` found it moved, else the diff's number. + line: usize = 0, + /// A hunk line's number in the old and in the new file, as the diff + /// numbers them; null on the side it is not on (an added line's old) + /// and on the rows that are not a hunk's lines. + old: ?usize = null, + new: ?usize = null, + /// Bytes into its text: where its `path:line` ends, and where what + /// follows the label starts (a hunk's stars). + location_end: usize = 0, + code_start: usize = 0, + /// A style byte for each byte of its text, or none: a `Syn` in the low + /// bits (`syntax.syn_bits`, with `colors`) and the grounds over it: + /// `ground_add` or `ground_del` on a changed line, `ground_line` on the + /// marker of one no other line changed, `ground_emph` on the words a + /// changed line changed. + styles: []const u8 = &.{}, + /// The diff's `\ No newline at end of file` follows this line: it has + /// no row of its own (delta shows it so, and the editor). + no_newline: bool = false, + + pub const Kind = enum { + /// What is said around the hunks: a mailed patch's headers, its + /// message and its diffstat, as written. + other, + /// A section's own words: a new file's mode, a rename, `Binary files + /// ... differ` (its `diff` and `index` lines say nothing the labels + /// do not, and its `---`/`+++` are the labels'). + meta, + /// A hunk's label, `path:line` where it changes something, a star + /// for each declaration it stands in. + hunk, + /// What the hunk stands in, above its label: a declaration's + /// `path:line` (`tslocations`) and its header's lines, from the file + /// `source` found and `declarations` read; or, without them, git's + /// own function line from the `@@`. + declaration, + /// A hunk's lines, behind their ` `, `+` or `-`. + context, + added, + removed, + }; +}; + +/// The rows `content`, a diff, stacks to, its files looked for from `dir`. +pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !Patch { const arena = ctx.arena; - const styles = try syntax.highlightDiff(arena, content, 0, content.len); - var out: Out = .{ .gpa = ctx.gpa, .text = .init(ctx.gpa) }; - errdefer out.deinit(); + const styles = if (ctx.colors) |colors| try colors(ctx, content) else plain: { + const none = try arena.alloc(u8, content.len); + @memset(none, 0); + break :plain none; + }; + var out: Out = .{ .text = .init(arena) }; var walk: diff.Walk = .{}; var hunk: Hunk = .{}; var source: SourceMemo = .{}; + // inferEdits' scratch, made once a call. + var scratch: []u8 = &.{}; var at: usize = 0; // The empty text after a last newline is no line. while (at < content.len) { @@ -73,9 +166,11 @@ pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations. }); }, // A `\ No newline` belongs to the line above, as delta shows it. - .no_newline => {}, + .no_newline => if (hunk.lines.items.len > 0) { + hunk.lines.items[hunk.lines.items.len - 1].no_newline = true; + }, else => { - try flush(ctx, &out, &hunk, &source, dir); + try flush(ctx, &out, &hunk, &source, &scratch, dir); switch (got.kind) { .hunk => hunk = .{ .path = walk.path(), @@ -86,22 +181,20 @@ pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations. }, // What is said around the hunks, a mailed patch's // headers, message and diffstat, as it was written. - .other => try out.row(line, "", .{ .kind = .context, .at = .{} }), + .other => try out.row(arena, line, .{ .kind = .other }), // A section's own words (a new file's mode, a rename, // `Binary files ... differ`), muted; its `diff` and // `index` lines say nothing the labels do not. .meta => if (!std.mem.startsWith(u8, line, "diff ") and !std.mem.startsWith(u8, line, "index ")) - try out.row(line, "", .{ .kind = .context, .declaration = true, .at = .{} }), + try out.row(arena, line, .{ .kind = .meta }), else => {}, } }, } at = nl + 1; } - try flush(ctx, &out, &hunk, &source, dir); - const rows = try out.rows.toOwnedSlice(ctx.gpa); - errdefer locations.freeRows(ctx.gpa, rows); - return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; + try flush(ctx, &out, &hunk, &source, &scratch, dir); + return .{ .text = out.text.written(), .rows = out.rows.items }; } const HunkLine = struct { @@ -115,6 +208,7 @@ const HunkLine = struct { /// Paired with a line it changed (inferEdits): its words show that; /// unpaired, the whole line was added or removed. paired: bool = false, + no_newline: bool = false, }; const Hunk = struct { @@ -134,37 +228,14 @@ fn gitContext(line: []const u8) []const u8 { } const Out = struct { - gpa: std.mem.Allocator, text: std.Io.Writer.Allocating, rows: std.ArrayList(Row) = .empty, - fn deinit(out: *Out) void { - out.text.deinit(); - locations.freeRowList(out.gpa, &out.rows); - } - - const Meta = struct { - kind: @FieldType(Row, "kind"), - declaration: bool = false, - at: @FieldType(Row, "at"), - location_end: usize = 0, - code_start: usize = 0, - colors: []const u8 = &.{}, - }; - - /// One row: its text, a newline, and its metadata. - fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { + /// One row: its text, a newline, and what it is. + fn row(out: *Out, arena: std.mem.Allocator, text: []const u8, r: Row) !void { try out.text.writer.writeAll(text); try out.text.writer.writeByte('\n'); - try locations.appendRow(out.gpa, &out.rows, .{ - .kind = meta.kind, - .declaration = meta.declaration, - .path = @constCast(path), - .at = meta.at, - .location_end = meta.location_end, - .code_start = meta.code_start, - .colors = @constCast(meta.colors), - }); + try out.rows.append(arena, r); } }; @@ -276,7 +347,7 @@ fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start return .{ .held = held, .of = @max(of, 1) }; } -fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { +fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, scratch: *[]u8, dir: []const u8) !void { defer hunk.* = .{}; if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; const arena = ctx.arena; @@ -310,13 +381,12 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons depth += 1; var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { - const at: @FieldType(Row, "at") = .{ .line = row + 1 }; if (row == declaration.start_line and ctx.tslocations) { const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); - try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); + try out.row(arena, label, .{ .kind = .declaration, .path = shown, .line = row + 1, .location_end = label.len, .code_start = label.len }); } // A blank where a hunk line has its marker: the code aligns. - try out.row(try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), shown, .{ .kind = .context, .declaration = true, .at = at }); + try out.row(arena, try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), .{ .kind = .declaration, .path = shown, .line = row + 1 }); } }; @@ -329,12 +399,12 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons try label.writer.writeByte(' '); try label.writer.splatByteAll('*', depth); } - try out.row(label.written(), shown, .{ .kind = .match, .at = .{ .line = line_no }, .location_end = location_end, .code_start = label.written().len }); + try out.row(arena, label.written(), .{ .kind = .hunk, .path = shown, .line = line_no, .location_end = location_end, .code_start = label.written().len }); // No file to read declarations from: git's own function line, muted // the same way. With one, git's guess (the last line before the hunk // that looked like a function) would only contradict it. if (side == .neither and hunk.header.len > 0) - try out.row(try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), shown, .{ .kind = .context, .declaration = true, .at = .{ .line = line_no } }); + try out.row(arena, try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), .{ .kind = .declaration, .path = shown, .line = line_no }); // Each run of removed lines and the added lines after it: the words // they changed. @@ -348,7 +418,7 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons while (i < lines.len and lines[i].kind == .removed) i += 1; const plus_start = i; while (i < lines.len and lines[i].kind == .added) i += 1; - try inferEdits(ctx.tab, arena, lines[minus_start..plus_start], lines[plus_start..i]); + try inferEdits(ctx, scratch, lines[minus_start..plus_start], lines[plus_start..i]); } // Each line behind its marker, `+`, `-` or a blank, as the diff @@ -368,7 +438,19 @@ fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []cons colors[0] = flag; @memcpy(colors[1..], line.styles); const on = moved(if (on_old) line.old else line.new, disk.shift); - try out.row(text, shown, .{ .kind = .preview, .at = .{ .line = @max(1, on) }, .colors = colors }); + try out.row(arena, text, .{ + .kind = switch (line.kind) { + .added => .added, + .removed => .removed, + else => .context, + }, + .path = shown, + .line = @max(1, on), + .old = if (line.kind == .added) null else line.old, + .new = if (line.kind == .removed) null else line.new, + .styles = colors, + .no_newline = line.no_newline, + }); } } @@ -385,18 +467,21 @@ const max_run = 256; const max_cells = 1 << 16; /// Pairs one hunk compares (each a table of up to `max_cells`): past it, the /// rest of its lines are shown unemphasised. And the scratch each pair is -/// aligned in, reused by the next: its table and the ranges it marks. +/// aligned in, reused by the next and by the next run's (one a `format`): +/// its table and the ranges it marks. const max_pairs = 4096; const pair_scratch_bytes = 8 << 20; /// Pair each removed line with the first added line after the last one /// paired that is near enough to it, in order, and emphasise in both the /// tokens one has and the other has not. -fn inferEdits(tab: u16, arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { +fn inferEdits(ctx: *const Ctx, scratch_bytes: *[]u8, minus: []HunkLine, plus: []HunkLine) !void { if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + const arena = ctx.arena; const plus_tokens = try arena.alloc([]const []const u8, plus.len); for (plus, plus_tokens) |line, *tokens| tokens.* = try tokenize(arena, line.code); - var scratch: std.heap.FixedBufferAllocator = .init(try @import("memory.zig").unfilled(arena, pair_scratch_bytes)); + if (scratch_bytes.len == 0) scratch_bytes.* = try @import("memory.zig").unfilled(arena, pair_scratch_bytes); + var scratch: std.heap.FixedBufferAllocator = .init(scratch_bytes.*); var pairs: usize = 0; var plus_index: usize = 0; for (minus) |*m| { @@ -410,7 +495,7 @@ fn inferEdits(tab: u16, arena: std.mem.Allocator, minus: []HunkLine, plus: []Hun scratch.reset(); const pair = scratch.allocator(); var alignment = Alignment.init(pair, m_tokens, p_tokens) catch continue; - const marks = annotate(tab, pair, &alignment, m.code, plus[j].code) catch continue; + const marks = annotate(ctx, pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { b.* |= syntax.ground_emph; @@ -536,7 +621,7 @@ const Marks = struct { /// what each deleted and inserted, and a run of blanks between two changes /// with them; the distance is the changed width over the whole width (a /// kept section counting on both lines). -fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { +fn annotate(ctx: *const Ctx, arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { var minus: std.ArrayList([2]usize) = .empty; var plus: std.ArrayList([2]usize) = .empty; var x_off: usize = 0; @@ -562,7 +647,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: switch (op) { .deletion => { const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); - const w = trimmedWidth(tab, minus_line[r[0]..r[1]]); + const w = trimmedWidth(ctx, minus_line[r[0]..r[1]]); numer += w; denom += w; try minus.append(arena, r); @@ -571,7 +656,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: .noop => { const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); const section = minus_line[r[0]..r[1]]; - denom += 2 * trimmedWidth(tab, section); + denom += 2 * trimmedWidth(ctx, section); const is_space = std.mem.trim(u8, section, " \t").len == 0; const coalesce = is_space and ((minus_prev == .deletion and plus_prev == .insertion and @@ -585,7 +670,7 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: }, .insertion => { const r = Take.section(a.y, &y_off, &p_byte, n, plus_line); - const w = trimmedWidth(tab, plus_line[r[0]..r[1]]); + const w = trimmedWidth(ctx, plus_line[r[0]..r[1]]); numer += w; denom += w; try plus.append(arena, r); @@ -597,8 +682,8 @@ fn annotate(tab: u16, arena: std.mem.Allocator, a: *const Alignment, minus_line: return .{ .minus = minus.items, .plus = plus.items, .distance = distance }; } -fn trimmedWidth(tab: u16, section: []const u8) usize { - return @import("File.zig").displayWidth(tab, std.mem.trim(u8, section, " \t")); +fn trimmedWidth(ctx: *const Ctx, section: []const u8) usize { + return ctx.width(ctx, std.mem.trim(u8, section, " \t")); } // ---- the +Diff in the editor ---- @@ -728,18 +813,22 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u // The cache's may go at its next use: kept for the call. return ctx.arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); } + fn width(ctx: *const Ctx, text: []const u8) usize { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + return pardes.panes.File.displayWidth(pp.settings.tab, text); + } }; const ctx: Ctx = .{ - .gpa = p.gpa, .arena = p.scratch.allocator(), .source = Read.source, .declarations = Read.declarations, + .colors = Ctx.languages, + .width = Read.width, .host = p, .tslocations = p.locations_config.tslocations, - .tab = p.settings.tab, }; const root = sourceRoot(&ctx, dir, content); - const result = try format(&ctx, root, content); + const result = try paneResult(p.gpa, try format(&ctx, root, content)); errdefer { p.gpa.free(result.content); locations.freeRows(p.gpa, result.rows); @@ -756,6 +845,31 @@ pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !u return Output.fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null); } +/// `patch`'s text and rows as a pane has them (Output.fillRows), `gpa`'s: a +/// hunk's label is a match n and N step to, what is around the hunks and +/// what they stand in is context (a section's words and a declaration +/// muted), a hunk's lines are previews of their file. +fn paneResult(gpa: std.mem.Allocator, patch: Patch) !locations.Result { + var rows: std.ArrayList(locations.Row) = .empty; + errdefer locations.freeRowList(gpa, &rows); + for (patch.rows) |r| try locations.appendRow(gpa, &rows, .{ + .kind = switch (r.kind) { + .hunk => .match, + .other, .meta, .declaration => .context, + .context, .added, .removed => .preview, + }, + .declaration = r.kind == .meta or r.kind == .declaration, + .path = @constCast(r.path), + .at = .{ .line = r.line }, + .location_end = r.location_end, + .code_start = r.code_start, + .colors = @constCast(r.styles), + }); + const content = try gpa.dupe(u8, patch.text); + errdefer gpa.free(content); + return .{ .content = content, .rows = try rows.toOwnedSlice(gpa), .anchor = null }; +} + /// Diff on a +Diff: the diff it stacks, as text. A pane holding it /// already (the newest: a +Pager folded under its +Diff unfolds) is /// shown; else the file is opened as text. @@ -796,7 +910,7 @@ const TestCtx = struct { fn init(t: *TestCtx) void { t.arena_state = .init(testing.allocator); - t.ctx = .{ .gpa = testing.allocator, .arena = t.arena_state.allocator(), .source = source, .declarations = declarations, .host = t, .tslocations = true, .tab = @import("config.zig").tab_width }; + t.ctx = .{ .arena = t.arena_state.allocator(), .source = source, .declarations = Ctx.parsed, .colors = Ctx.languages, .width = width }; syntax.start(testing.allocator); } @@ -811,8 +925,8 @@ const TestCtx = struct { return .{ .path = full, .bytes = bytes }; } - fn declarations(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { - return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + fn width(_: *const Ctx, text: []const u8) usize { + return pardes.panes.File.displayWidth(@import("config.zig").tab_width, text); } }; @@ -822,15 +936,17 @@ fn emphasised(line: HunkLine) ![]const u8 { return out.toOwnedSlice(testing.allocator); } -fn expectEmphasis(tab: u16, minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { +fn expectEmphasis(minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); + const ctx: Ctx = .{ .arena = arena, .width = TestCtx.width }; + var scratch: []u8 = &.{}; var m = [_]HunkLine{.{ .kind = .removed, .code = minus, .styles = try arena.alloc(u8, minus.len), .old = 1, .new = 1 }}; var p = [_]HunkLine{.{ .kind = .added, .code = plus, .styles = try arena.alloc(u8, plus.len), .old = 2, .new = 1 }}; @memset(m[0].styles, 0); @memset(p[0].styles, 0); - try inferEdits(tab, arena, &m, &p); + try inferEdits(&ctx, &scratch, &m, &p); const got_minus = try emphasised(m[0]); defer testing.allocator.free(got_minus); const got_plus = try emphasised(p[0]); @@ -840,16 +956,16 @@ fn expectEmphasis(tab: u16, minus: []const u8, plus: []const u8, want_minus: []c } test "delta's emphasis: the word a line changed, in both lines" { - try expectEmphasis(@import("config.zig").tab_width, " let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); - try expectEmphasis(@import("config.zig").tab_width, "a b c", "a x c", "..b..", "..x.."); + try expectEmphasis(" let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); + try expectEmphasis("a b c", "a x c", "..b..", "..x.."); } test "delta's emphasis: lines too far apart are no change of one another" { - try expectEmphasis(@import("config.zig").tab_width, "completely different text", "nothing alike here at all", ".........................", "........................."); + try expectEmphasis("completely different text", "nothing alike here at all", ".........................", "........................."); } test "delta's emphasis: a word added keeps the rest plain" { - try expectEmphasis(@import("config.zig").tab_width, "fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); + try expectEmphasis("fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); } test "delta's alignment: kitten to sitting, as align.rs has it" { @@ -880,7 +996,7 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st \\ tail \\ ; - const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); @@ -919,7 +1035,7 @@ test "a hunk the file has moved since is found where it went, inside its declara \\ b(); \\ ; - const result = try format(&t.ctx, dir, patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, dir, patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); @@ -947,7 +1063,7 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { \\+b \\ ; - const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, "/pardes-surely-missing-dir", patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); @@ -1038,7 +1154,7 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i \\ c \\ ; - const result = try format(&t.ctx, dir, patch); + const result = try paneResult(testing.allocator, try format(&t.ctx, dir, patch)); defer testing.allocator.free(result.content); defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); diff --git a/core/lib_syntax.zig b/core/lib_syntax.zig index f4f85820..0bb3f510 100644 --- a/core/lib_syntax.zig +++ b/core/lib_syntax.zig @@ -13,6 +13,7 @@ const syntax = @import("syntax.zig"); const colors = @import("colors.zig"); const modal = @import("modal.zig"); +const hunks = @import("hunks.zig"); /// Every grammar pardes knows (`all`), by name or alias (`byName`) and by /// path (`byPath`). The build's `grammars` option says which of them are @@ -70,6 +71,22 @@ pub const ground_emph = syntax.ground_emph; pub const ground_line = syntax.ground_line; pub const Grounds = colors.Grounds; +/// A unified diff stacked as pardes's patch view (its +Diff) shows it: +/// `formatPatch` gives a `Patch`, its text and a `PatchRow` a line: a +/// hunk's `path:line`, the declarations it stands in (or git's function +/// line), its lines with both their numbers, each byte's style (a `Syn` +/// when `colors` are given, the grounds, the words a changed line changed). +/// What it takes of the program is a `PatchCtx`: an arena, and optionally +/// the files the diff names (`source`, a `PatchSource`), their declarations +/// (`PatchCtx.parsed`), the colours (`PatchCtx.languages`, highlightDiff's) +/// and a text's width; with none of them it names no grammar and no +/// tree-sitter. +pub const formatPatch = hunks.format; +pub const PatchCtx = hunks.Ctx; +pub const PatchSource = hunks.Source; +pub const Patch = hunks.Patch; +pub const PatchRow = hunks.Row; + /// The tree-sitter bindings a tree is read through: `tree.rootNode()`, and /// a node's `kind()`, `startByte()`, `endByte()`, `child(i)`, `parent()`. pub const ts = syntax.ts; diff --git a/core/normal.zig b/core/normal.zig index ae6c2d18..982ab656 100644 --- a/core/normal.zig +++ b/core/normal.zig @@ -789,8 +789,12 @@ fn multiSelAction(tab: u16, t: *Text, text: []const u8, role: modal.Normal.Role, for (rs[0..n], 0..) |r, ri| { const is_pri = ri == got.pri; // head-exclusive: back the leading end off onto its own cell - const hp = modal.positionAt(text, if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head); - const ap = modal.positionAt(text, if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor)); + const h_off = if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head; + const a_off = if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor); + const hp = modal.positionAt(text, h_off); + const ap = modal.positionAt(text, a_off); + var al: LineWalk = .of(text, a_off, ap.row); + var hl: LineWalk = .of(text, h_off, hp.row); const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1; if (m >= Text.max_selections) break; if (is_pri) pri = m; @@ -803,12 +807,12 @@ fn multiSelAction(tab: u16, t: *Text, text: []const u8, role: modal.Normal.Role, const arow = if (below) ap.row + d else ap.row -| d; const hrow = if (below) hp.row + d else hp.row -| d; if (arow >= nlines or hrow >= nlines) break; - const a2 = modal.offsetAt(text, .{ .row = arow, .col = ap.col }); - const h2 = modal.offsetAt(text, .{ .row = hrow, .col = hp.col }); // a line too short to reach the column is skipped, not clamped - if (modal.positionAt(text, a2).col == ap.col and modal.positionAt(text, h2).col == hp.col) { + const a2 = al.cell(text, arow, ap.col); + const h2 = hl.cell(text, hrow, hp.col); + if (a2 != null and h2 != null) { if (is_pri) pri = m; - out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2, .head = a2 }, h2, true); + out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2.?, .head = a2.? }, h2.?, true); m += 1; made += 1; } @@ -818,6 +822,28 @@ fn multiSelAction(tab: u16, t: *Text, text: []const u8, role: modal.Normal.Role, t.setRanges(tab, text, out[0..m], &.{}, pri, expl); } +/// A line's start, walked on from the row C or Alt-C last tried: found +/// from the text's start, each try was a pass over all before it, and a +/// column no near line reaches hung the editor on a long text. +const LineWalk = struct { + row: usize, + start: usize, + + fn of(text: []const u8, off: usize, row: usize) LineWalk { + return .{ .row = row, .start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0 }; + } + + /// Column `col` of `row`, or null where the line ends before it or a + /// grapheme there spans it. + fn cell(w: *LineWalk, text: []const u8, row: usize, col: usize) ?usize { + while (w.row < row) : (w.row += 1) w.start = std.mem.indexOfScalarPos(u8, text, w.start, '\n').? + 1; + while (w.row > row) : (w.row -= 1) w.start = if (std.mem.lastIndexOfScalar(u8, text[0 .. w.start - 1], '\n')) |nl| nl + 1 else 0; + const e = std.mem.indexOfScalarPos(u8, text, w.start, '\n') orelse text.len; + const g = modal.graphemeStart(text[w.start..e], @min(col, e - w.start)); + return if (g == col) w.start + g else null; + } +}; + fn maxLine(text: []const u8) usize { const nl = modal.cursorLineCount(text); return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1; @@ -1547,6 +1573,62 @@ test "one cursor holds no room for other ranges; a second range makes it and one try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); } +test "C and Alt-C on a long text of short lines walk its lines once, not each try from its start" { + // Work, not time: the instructions this thread runs, as pardes-perf's + // gate counts them. Each try walking from the text's start made C here + // cost billions (the bytes soak's hang, at row 41,775 of a flood). + if (@import("builtin").os.tag != .linux) return error.SkipZigTest; + 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 opened = linux.perf_event_open(&attr, 0, -1, -1, linux.PERF.FLAG.FD_CLOEXEC); + if (linux.errno(opened) != .SUCCESS) return error.SkipZigTest; // no counter here (perf_event_paranoid 3) + const fd: linux.fd_t = @intCast(opened); + defer _ = linux.close(fd); + const Count = struct { + fn now(f: linux.fd_t) u64 { + var n: u64 = 0; + _ = linux.read(f, std.mem.asBytes(&n), @sizeOf(u64)); + return n; + } + }; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + // only the first line and the last reach column 3 + const lines = 50_000; + const text = try gpa.alloc(u8, 2 * 5 + (lines - 2) * 2); + defer gpa.free(text); + @memcpy(text[0..5], "abcd\n"); + for (0..lines - 2) |k| @memcpy(text[5 + 2 * k ..][0..2], "x\n"); + @memcpy(text[text.len - 5 ..], "abcd\n"); + const pane = try p.setTestFile(text); + const body = &pane.body; + // C walked once costs 194 million here in Debug, about 4,000 a line; + // walked from the start at every try it cost 306 billion + const bound = 10_000 * lines; + for ("lll") |cp| _ = handleNormal(p.editor(), body, .{ .cp = cp }); + var rs: [Text.max_selections]modal.Selection = undefined; + for ([_]Key{ .{ .cp = 'C' }, .{ .cp = 'C', .alt = true } }) |key| { + const t0 = Count.now(fd); + _ = handleNormal(p.editor(), body, key); + const cost = Count.now(fd) - t0; + const got = body.ranges(text, 0, &rs); + try std.testing.expectEqual(2, got.n); + try std.testing.expectEqual(3, @min(rs[0].anchor, rs[0].head)); + try std.testing.expectEqual(text.len - 2, @min(rs[1].anchor, rs[1].head)); + std.testing.expect(cost < bound) catch |err| { + std.debug.print("{u} (alt {}): {d} instructions, the bound {d}\n", .{ key.cp, key.alt, cost, bound }); + return err; + }; + // the new cursor alone, for the twin to walk back from + _ = handleNormal(p.editor(), body, .{ .cp = ',' }); + } +} + test "cursors that land on one place are one: a key typed there is typed once, as helix merges them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); diff --git a/core/panes.zig b/core/panes.zig index 3d6e8754..658de219 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -1125,16 +1125,20 @@ pub const Term = @import("Term.zig"); pub const positions_lost = "terminal edit position reset: out of memory"; /// At a join (Core's openView, rejoinView): under bytes, every live -/// terminal made again from its own snapshot, on every side alike, the -/// session included (Term.reload): an emulator loaded from a snapshot holds -/// its rows in other pages than one fed from its start, and ghostty prunes -/// its history a page at a time, so the joiner, loaded from the session's -/// dump made next, and the replicas there before it, would part. The +/// terminal written since its last reload made again from its own snapshot, +/// on every side alike, the session included (Term.reload): an emulator +/// loaded from a snapshot holds its rows in other pages than one fed from +/// its start, and ghostty prunes its history a page at a time, so the +/// joiner, loaded from the session's dump made next, and the replicas there +/// before it, would part. Which, the session says (`Term.State.written`, +/// taped): one written by nothing since holds the pages its last reload +/// made, on every side, and the joiner loads that snapshot again. The /// session's snapshot's hash is taped, and each replica's own compared /// with it: a check of the whole emulator at every join. pub fn reloadTerminals(p: *Pardes) void { if (tape.screenState()) return; for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| { + if (!tape.value(.reload, written, .{state})) continue; // Its cells' size in pixels as a feed sets it (`feedOutput`): a // frontend's draw sets its own view's between steps (ansi.zig), a // window's other than a terminal's, and the snapshot holds it. @@ -1149,6 +1153,10 @@ fn sameHash(h: ?u64) ?u64 { return h; } +fn written(s: *Term.State) bool { + return s.written; +} + /// The sizes steps gave terminals (`Pane.resizeGrid`), made: between /// units, on an authority with screen-state replicas (replica.Peers.unit). pub fn resizeDeferred(p: *Pardes) void { diff --git a/core/replica.zig b/core/replica.zig index 554ef327..56fc4a59 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -999,9 +999,10 @@ pub const Replica = struct { r.last_digest.clearRetainingCapacity(); if (ends) |d| r.last_digest.appendSlice(r.gpa, d) catch {}; } - // A terminal's output is never taken so (the one rule): what it - // writes outside the copy is applied once, at its place, and much - // of it no digest covers (a colour set, a mode). + // A terminal's output, or a join's reloads, never taken so (the one + // rule): what it writes outside the copy is applied once, at its + // place, and much of it no digest covers (a colour set, a mode, the + // pages a reload remakes). if (r.applied > 0 and u.origin != r.id and ends != null and std.mem.eql(u8, ends.?, r.last_digest.items) and (r.t.screen_state or !tape.feedsTerminal(u.tape))) { @@ -1724,8 +1725,11 @@ pub const Peer = struct { /// What it is sent, not written yet, and what the writer writes now. out: std.ArrayListUnmanaged(u8) = .empty, sending: std.ArrayListUnmanaged(u8) = .empty, - limit: usize = 64 << 20, + /// What may wait in `out` before it is cut off (a test's less). + limit: usize = lag_max, closing: bool = false, + /// Cut off (`send`): the words why are the last it is sent, and its + /// view is kept for it (views.away), as for a bye's `again`. cut: bool = false, /// Its writer has ended (what it was sent, written). done: std.atomic.Value(bool) = .init(false), @@ -1757,7 +1761,7 @@ pub const Peer = struct { if (!writeAll(peer.fd, peer.welcome[0..peer.welcome_len])) return false; const io = peer.peers.io; peer.lock.lockUncancelable(io); - while (peer.far == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); + while (peer.far == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const far = peer.far; const boot = peer.boot; peer.lock.unlock(io); @@ -1802,7 +1806,7 @@ pub const Peer = struct { if (peer.blobs.items.len > 0) { const io = peer.peers.io; peer.lock.lockUncancelable(io); - while (peer.want == null and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); + while (peer.want == null and !peer.closing) peer.cond.waitUncancelable(io, &peer.lock); const want = peer.want; peer.lock.unlock(io); const bits = want orelse return false; @@ -1817,12 +1821,13 @@ pub const Peer = struct { return peer.z != null; } - /// Whether it is being let go (or was cut off). + /// Whether it is being let go. One cut off is still sent its join + /// whole, then the words why (`send`): it joins again after them. fn letting(peer: *Peer) bool { const io = peer.peers.io; peer.lock.lockUncancelable(io); defer peer.lock.unlock(io); - return peer.closing or peer.cut; + return peer.closing; } /// One message into its stream's compressor. @@ -1873,8 +1878,9 @@ pub const Peer = struct { } /// `parts` queued for it, in order; never waits. A client whose queue - /// passes its limit is cut off: its link is shut down, and its reader - /// says it is gone. + /// passes its limit is cut off: what waits for it is let go and the + /// words why queued in its place, after which its writer ends its link + /// (`writeLoop`); it joins again from a dump, for its view (`leave`). fn send(peer: *Peer, parts: []const []const u8) void { const io = peer.peers.io; peer.lock.lockUncancelable(io); @@ -1894,7 +1900,13 @@ pub const Peer = struct { log.info("client {d} is {d} MB behind: cut off", .{ peer.id, n >> 20 }); peer.peers.cut += 1; peer.cut = true; - _ = libc.shutdown(peer.fd, 2); + peer.out.clearRetainingCapacity(); + var words: [48]u8 = undefined; + var msg: [64]u8 = undefined; + const word = wire.encodeServer(&msg, .{ .refused = std.fmt.bufPrint(&words, "{d} MB behind the session", .{n >> 20}) catch unreachable }) catch unreachable; + peer.out.appendSlice(peer.peers.gpa, word) catch { + _ = libc.shutdown(peer.fd, 2); + }; peer.cond.signal(io); return; } @@ -1955,17 +1967,17 @@ pub const Peer = struct { while (true) { peer.lock.lockUncancelable(io); while (peer.out.items.len == 0 and !peer.closing and !peer.cut) peer.cond.waitUncancelable(io, &peer.lock); - if (peer.out.items.len == 0 or peer.cut) { + if (peer.out.items.len == 0) { peer.lock.unlock(io); return; } std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &peer.sending); - // The limit was for the dump and what is queued behind it. - peer.limit = lag_max; + // Cut off: the words why came last, and its link ends after them. + const cut_off = peer.cut; peer.lock.unlock(io); const ok = if (peer.z != null) peer.zWrite(peer.sending.items, .flush) else writeAll(peer.fd, peer.sending.items); peer.sending.clearRetainingCapacity(); - if (!ok) { + if (!ok or cut_off) { _ = libc.shutdown(peer.fd, 2); return; } @@ -2370,7 +2382,7 @@ pub const Peers = struct { core.gpa.free(bytes); return daemon.refuseReplica(fd, "out of memory"); }; - peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .limit = lag_max, .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; + peer.* = .{ .peers = ps, .fd = fd, .id = ps.next_id, .view = .at(k), .dump = bytes, .blobs = blobs, .dump_gpa = core.gpa }; ps.next_id +%= 1; if (ps.next_id == 0) ps.next_id = 1; // The session's digest as dumped, for the joiner to check its load by @@ -2442,7 +2454,9 @@ pub const Peers = struct { ps.tellClients(); ps.screens.dropPeer(peer.sid); core.undrawn &= ~(@as(u8, 1) << @intCast(peer.view.index())); - ps.closeViewOf(core, peer, peer.again); + // Cut off, it joins again after the words why (`send`); its reader + // has ended and no other thread sets `cut` now. + ps.closeViewOf(core, peer, peer.again or peer.cut); if (ps.count() == 0) core.unattended = ps.detached; if (ps.count() == 0 and peer.close and daemon.sessionState() == .pair) ps.closed = true; ps.seq += 1; @@ -3272,6 +3286,10 @@ fn redial(gpa: Allocator, path: []const u8, session: []const u8, why: *[600]u8, } } +/// How far behind its session a client may fall before it lets its link go +/// and joins again from a dump (P32 (b)): near and far alike. +pub const behind_max_ms = 2_000; + /// A replica client's link to its session, the terminal's (tui.zig /// `runClient`) and the window's (gui.zig `runClient`): its replica, its socket, /// what the session said, and what it checks. Drawing is the frontend's. @@ -3337,6 +3355,17 @@ pub const Link = struct { /// moved on (its own motion), for PARDES_REPLICA_STATS. draws: u32 = 0, again: u32 = 0, + /// How far behind the session it is, ns: each unit's head carries the + /// session's monotonic clock as it was made; against this client's own, + /// less the smallest difference seen (the clocks' offset and the link's + /// quickest crossing). This machine's clock, the link's alone: no step + /// reads it and no digest holds it (`lags`). + behind: u64 = 0, + least: ?i64 = null, + /// No unit taken since it joined (`lags`). + fresh: bool = true, + /// How far behind it was as it let its link go (`rejoins` says so). + lagged: u64 = 0, /// A pair's first join, its own boot not confirmed yet: its inputs /// kept here, not sent (`release`; client.zig `confirm`). held: ?std.ArrayListUnmanaged(u8) = null, @@ -3371,6 +3400,8 @@ pub const Link = struct { c.asked = false; c.mispredicted = 0; c.put_off = false; + c.behind = 0; + c.fresh = true; if (r.core().views[r.view]) |v| { c.yanks = v.yanks; c.pastes = v.pastes; @@ -3418,6 +3449,7 @@ pub const Link = struct { switch (msg) { .unit => |bytes| { defer std.heap.c_allocator.free(bytes); + if (c.quit or c.lags(bytes)) return; c.r.confirm(bytes); if (c.test_diverge != 0 and c.r.stats.units >= c.test_diverge and c.r.quiet()) { c.test_diverge = 0; @@ -3477,6 +3509,25 @@ pub const Link = struct { }; } + /// The session's unit `bytes`, taken now: how far behind it is. Past + /// `behind_max_ms` it lets its link go (true), to join again from a dump. + /// The first unit after a join past it is taken as the link now (a + /// session's clock stood still while its machine slept; a dump that took + /// longer than the bound to come), never a let-go again at once. + fn lags(c: *Link, bytes: []const u8) bool { + const u = parseUnit(bytes) orelse return false; + const d = @as(i64, @intCast(c.time())) - u.mono_ns; + const max = behind_max_ms * std.time.ns_per_ms; + if (c.fresh and d - (c.least orelse d) > max) c.least = d; + c.fresh = false; + c.least = @min(c.least orelse d, d); + c.behind = @intCast(d - c.least.?); + if (c.behind <= max) return false; + c.lagged = c.behind; + c.quit = true; + return true; + } + /// A write to the session failed: it hung up (it cut this client off, /// lagging), as its reader will say. fn cut(c: *Link) void { @@ -3507,8 +3558,9 @@ pub const Link = struct { fn checked(c: *Link, theirs: u64) void { c.asked = false; // Not quiet now, the answer is let go: it covers nothing, and the - // next quiet asks again. - if (!c.r.quiet() or c.r.diverged != null) { + // next quiet asks again. Nor once its link is let go: a lag's let-go + // drops the units after it (`lags`), and the core is behind them. + if (c.quit or !c.r.quiet() or c.r.diverged != null) { c.changed = true; return; } @@ -3550,12 +3602,18 @@ pub const Link = struct { } /// The link ended: whether the client joins again, and why in its - /// notice (it diverged, or the session let it go to upgrade). + /// notice (it diverged, it fell too far behind, or the session let it + /// go: to upgrade, or cut off). pub fn rejoins(c: *Link) bool { if (c.r.diverged) |reason| { c.notify("joined again: this client diverged from the session ({s})", .{reason}); return true; } + if (c.lagged != 0) { + c.notify("joined again: {d}.{d} s behind", .{ c.lagged / std.time.ns_per_s, c.lagged / (std.time.ns_per_s / 10) % 10 }); + c.lagged = 0; + return true; + } if (c.refused) |words| { c.notify("joined again: {s}", .{words}); std.heap.c_allocator.free(words); @@ -4861,6 +4919,105 @@ fn firstOnPair(bytes: bool) !void { try std.testing.expectEqual(reloads + 2, pardes.Term.reloads.n); } +test "bytes: a join refused for want of a view reloads nothing on any side: a client with a key on top stays the session's" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + try b.output("a line of the program's\r\n"); + // Every view taken: the session's, then three clients'. + for (2..pardes.views.max + 1) |client| b.r.confirm((try b.a.openView(@intCast(client))).unit); + try b.output("and one since the last join\r\n"); + var sent: std.ArrayListUnmanaged([]u8) = .empty; + defer { + for (sent.items) |m| gpa.free(m); + sent.deinit(gpa); + } + // A key of its own on top; a fifth client refused, in the unit of the + // pump the others take next; the key confirmed; the program prints on. + try key(b.r, 'l', &sent); + try std.testing.expectEqual(@as(usize, 1), b.r.applied); + const before = pardes.Term.reloads.n; + try std.testing.expect(try b.a.join(pardes.views.max + 1, null) == null); + try std.testing.expectEqual(before, pardes.Term.reloads.n); + b.a.pump(); + b.r.confirm((try b.a.pending()).?); + b.r.confirm(try b.a.take(sent.items[0])); + b.r.settle(); + try b.output("and on\r\n"); + try std.testing.expectEqual(before, pardes.Term.reloads.n); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); +} + +test "bytes: a join reloads only the terminals written since their last reload: one idle since the last join is reloaded on no side, and through a prune of both every side holds the session's terminals, the joiner too" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + const b = try BytesPair.init(); + defer b.deinit(); + b.r.confirm(try b.a.local(.{ .command = "Term" })); + b.r.settle(); + const second: pardes.Pane.Id = for (b.a.core.panes, 0..) |slot, id| { + if (id != b.shell.index() and (slot orelse continue).terminal != null) break .at(id); + } else return error.NoTerminal; + const both = [_]pardes.Pane.Id{ b.shell, second }; + // Both written, and a join reloads both. + for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = "written\r\n" } }); + b.r.confirm((try b.a.pending()).?); + const first = (try b.a.join(2, null)).?; + gpa.free(first.dump); + b.r.confirm(first.unit); + // The shell alone written since: the next join reloads it alone, on + // every side; the joiner loads the other's snapshot as it was. + try b.output("the shell's\r\n"); + const before = pardes.Term.reloads.n; + const joined = (try b.a.join(3, null)).?; + defer gpa.free(joined.dump); + try std.testing.expectEqual(1, pardes.Term.reloads.n - before); + b.r.confirm(joined.unit); + try std.testing.expectEqual(2, pardes.Term.reloads.n - before); + const late = try Replica.initDump(gpa, 3, joined.view, joined.dump, .{ .cols = 80, .rows = 24 }); + defer late.deinit(); + late.t.screen_state = false; + late.core().echo = null; + try std.testing.expectEqual(joined.digest, late.digest()); + // Output into both until each has pruned its history (whole pages, by + // the history of its pages), a unit every few reads. + var read: std.ArrayListUnmanaged(u8) = .empty; + defer read.deinit(gpa); + const lines = 40_000; + var n: usize = 0; + while (n < lines) : (n += 100) { + read.clearRetainingCapacity(); + for (n..n + 100) |i| try read.print(gpa, "\x1b[3{d}m{d}\x1b[0m line\r\n", .{ i % 8, i }); + for (both) |id| b.a.output(.{ .output = .{ .pane = id, .bytes = read.items } }); + if (n % 2000 == 1900) { + const u = (try b.a.pending()).?; + b.r.confirm(u); + late.confirm(u); + } + } + if (try b.a.pending()) |u| { + b.r.confirm(u); + late.confirm(u); + } + for (both) |id| try std.testing.expect(pardes.Term.grid(b.a.core.panes[id.index()].?.terminal).total < lines); + try agrees(b.a, b.r); + try sameTerminals(b.a, b.r); + try agrees(b.a, late); + try sameTerminals(b.a, late); + // And a join after: both written, both reloaded, every hash compared. + const left = try b.a.leave(2, false); + b.r.confirm(left); + late.confirm(left); + const third = (try b.a.join(4, null)).?; + gpa.free(third.dump); + b.r.confirm(third.unit); + late.confirm(third.unit); + try agrees(b.a, b.r); + try agrees(b.a, late); +} + test "bytes: a session's output past a unit's bound is cut into units under it, between two reads" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -5446,6 +5603,212 @@ test "a client that diverged joins again for its view: kept for it meanwhile, it try agrees(a, back); } +test "a client cut off for what it left unread is told why and joins again for its view, kept for it meanwhile: it loads the session's dump and agrees" { + // A session's side of its clients' links in memory (`Peers.threads` + // false, the soak's): a connection handed to it and joined at its next + // boundary, the replica loaded from what its writer would write (the + // welcome, the dump with its blobs in place); and what it queued for one, + // down its link in order, the link's end after it if it was cut off. + const MemoryLinks = struct { + fn join(ps: *Peers, core: *Pardes, view: ?u8, fd: *c_int) !struct { r: *Replica, peer: *Peer } { + const gpa = std.testing.allocator; + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + fd.* = fds[1]; + ps.handed(fds[0], view); + ps.boundary(core); + const peer = for (ps.list) |slot| { + if (slot) |p| if (p.fd == fds[0]) break p; + } else return error.Refused; + const f = (try wire.framed(peer.welcome[0..peer.welcome_len])) orelse return error.BadWelcome; + const w = (try wire.decodeServer(f.tag, f.payload)).welcome; + var whole: std.ArrayListUnmanaged(u8) = .empty; + defer whole.deinit(gpa); + var pos: usize = 0; + for (peer.blobs.items) |b| { + try whole.appendSlice(gpa, peer.dump[pos..b.at]); + try whole.appendSlice(gpa, b.bytes); + pos = b.at; + } + try whole.appendSlice(gpa, peer.dump[pos..]); + var word: [16]u8 = undefined; + const far = try wire.encodeClient(&word, .{ .far = false }); + _ = peer.take(far[0], far[wire.header_len..]); + ps.post(.{ .joined = peer }); + const r = try Replica.initDump(gpa, w.client, w.view.index(), whole.items, .{ .cols = 80, .rows = 24 }); + if (!r.loaded(w.digest)) return error.LoadedAnother; + return .{ .r = r, .peer = peer }; + } + + fn down(peer: *Peer, link: *Link) !void { + var at: usize = 0; + while (try wire.framed(peer.out.items[at..])) |f| : (at += f.total) { + link.take(switch (std.enums.fromInt(wire.ServerTag, f.tag) orelse return error.BadFrame) { + .unit => .{ .unit = try std.heap.c_allocator.dupe(u8, f.payload) }, + .refused => .{ .refused = try std.heap.c_allocator.dupe(u8, (try wire.decodeServer(f.tag, f.payload)).refused) }, + else => return error.UnexpectedFrame, + }); + } + peer.out.clearRetainingCapacity(); + if (!peer.cut) return; + link.quit = true; + link.gone = true; + } + }; + const gpa = std.testing.allocator; + const core = try Pardes.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }); + defer core.deinit(); + core.host = TestHost.host(); + try core.pump(core.host); + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io, .threads = false }; + defer ps.deinit(); + defer ps.dropAll(core); + var fd: c_int = -1; + const first = try MemoryLinks.join(&ps, core, null, &fd); + defer _ = libc.close(fd); + var link: Link = .{ .r = first.r, .fd = fd }; + defer link.deinit(gpa); + const view = first.peer.view; + // The session's own input, taken by the client. + core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + try core.pump(core.host); + ps.boundary(core); + try MemoryLinks.down(first.peer, &link); + try std.testing.expect(!link.quit and first.r.diverged == null); + // Its link stalls; the session goes on, and what waits for it passes + // the bound: it is cut off. + first.peer.limit = 16 << 10; + const text: [6000]u8 = @splat('t'); + for (0..3) |_| { + core.update(.{ .paste = &text }); + try core.pump(core.host); + ps.boundary(core); + } + try std.testing.expect(first.peer.cut); + try std.testing.expectEqual(@as(u32, 1), ps.cut); + try MemoryLinks.down(first.peer, &link); + try std.testing.expect(link.quit); + // It was told why, and joins again (as a divergence's client does)... + try std.testing.expect(link.rejoins()); + try std.testing.expect(std.mem.indexOf(u8, link.notice(), "behind") != null); + // ...once its old link's end is heard: its view kept for it meanwhile. + ps.post(.{ .gone = first.peer }); + ps.boundary(core); + try std.testing.expect(pardes.views.isAway(core, view.index())); + first.r.deinit(); + _ = libc.close(fd); + const back = try MemoryLinks.join(&ps, core, view.index(), &fd); + defer back.r.deinit(); + try std.testing.expectEqual(view, back.peer.view); + link.reset(back.r, &.{ .fd = fd, .pid = 0, .client = back.r.id, .view = view.index(), .gmtoff = 0, .dump = &.{} }); + core.update(.{ .paste = "back" }); + try core.pump(core.host); + ps.boundary(core); + try MemoryLinks.down(back.peer, &link); + try std.testing.expect(!link.quit and back.r.diverged == null and back.r.quiet()); + try std.testing.expectEqual(tape.digestOf(core), back.r.digest()); +} + +test "a client whose session's units come more than two seconds later than its quickest lets its link go, says so once, and joins again; its first unit after a join learns the clocks again" { + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); + defer a.deinit(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), false); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer for (fds) |fd| { + _ = libc.close(fd); + }; + var link: Link = .{ .r = r, .fd = fds[1] }; + defer link.deinit(gpa); + const Late = struct { + // A unit the session made at `made` ms on its clock, taken at `at` + // ms on the client's. + fn take(l: *Link, from: *Authority, made: i64, at: u64) !void { + const u = try std.heap.c_allocator.dupe(u8, try from.local(.tick)); + std.mem.writeInt(i64, u[14..22], made * std.time.ns_per_ms, .little); + l.now = at * std.time.ns_per_ms; + l.take(.{ .unit = u }); + } + }; + // The client's clock 5 s on from the session's, the link 100 ms: the + // second unit 1.9 s later than the first, the third 2.1 s. + try Late.take(&link, a, 0, 5_100); + try Late.take(&link, a, 1_000, 8_000); + try std.testing.expect(!link.quit); + try Late.take(&link, a, 1_100, 8_300); + try std.testing.expect(link.quit); + // A check answered after it let go, behind the unit it let go of: its + // core is behind on purpose, no divergence. + link.take(.{ .checked = digestOf(a) +% 1 }); + try std.testing.expect(r.diverged == null); + try std.testing.expect(link.rejoins()); + try std.testing.expectEqualStrings("joined again: 2.1 s behind", link.notice()); + try std.testing.expect(!link.rejoins()); + r.deinit(); + // Joined again, its first unit 3 s later than any before (the session's + // clock stood still, its machine asleep; or the dump took that long): + // taken as the link now, not let go of again. + const back = try joinedNow(a, 1, 0); + defer back.deinit(); + link.reset(back, &.{ .fd = fds[1], .pid = 0, .client = 1, .view = 0, .gmtoff = 0, .dump = &.{} }); + try Late.take(&link, a, 2_000, 10_100); + try Late.take(&link, a, 2_100, 10_250); + try std.testing.expect(!link.quit and back.diverged == null); +} + +test "a client's writer, the client cut off while it waits on the socket, writes what it has in hand, then the words why, and ends the link" { + const gpa = std.testing.allocator; + var ps: Peers = .{ .gpa = gpa, .io = std.testing.io }; + defer ps.deinit(); + var fds: [2]c_int = undefined; + if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocket; + defer _ = libc.close(fds[1]); + const peer = try gpa.create(Peer); + peer.* = .{ .peers = &ps, .fd = fds[0], .id = 1, .view = .at(0), .dump_gpa = gpa, .far = false, .limit = 256 << 10 }; + peer.welcome_len = (try wire.encodeServer(&peer.welcome, .{ .welcome = .{ .pid = 1, .session = "t" } })).len; + peer.writer = try std.Thread.spawn(.{}, Peer.writeLoop, .{peer}); + defer ps.letGo(peer); + // Units its client does not read: the socket fills, the writer waits + // on it with a batch in hand, and the rest queues up to the bound. + const unit: [16 << 10]u8 = @splat('u'); + const head = wire.header(@backingInt(wire.ServerTag.unit), unit.len); + // The first taken in hand. + peer.send(&.{ &head, &unit }); + while (true) { + peer.lock.lockUncancelable(std.testing.io); + const taken = peer.out.items.len == 0; + peer.lock.unlock(std.testing.io); + if (taken) break; + std.Thread.yield() catch {}; + } + var sent: u32 = 1; + while (!peer.cut) : (sent += 1) peer.send(&.{ &head, &unit }); + const Heard = struct { + units: u32 = 0, + last: ?[]u8 = null, + fn post(h: *@This(), msg: Said) bool { + switch (msg) { + .unit => |b| { + std.heap.c_allocator.free(b); + h.units += 1; + }, + .refused => |words| h.last = words, + else => return false, + } + return true; + } + }; + var heard: Heard = .{}; + var rest: Framer = .{}; + defer rest.deinit(gpa); + readLink(gpa, fds[1], &rest, &heard, Heard.post); + const words = heard.last orelse return error.NotTold; + defer std.heap.c_allocator.free(words); + try std.testing.expectEqualStrings("0 MB behind the session", words); + try std.testing.expect(heard.units > 0 and heard.units < sent); +} + test "a client joined from a dump moves through another view's pane as the session does, its lines not wrapped" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, TestHost.host(), false); @@ -5500,6 +5863,70 @@ test "a client joined from a dump makes a `/` query's rows as the session does, } } +// A query row's colours come from what this process has (its frames' +// paint of the owner, File.highlights; a worker's paint kept in the +// locations cache): out of the rows' digest. Whether a step asks a +// worker to paint the rows' file (Stream.paintRows, an effect on the +// tape) must not come from them: a session whose host paints on workers +// (search), that has drawn its owner, and a client that has not. +test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has drawn its owner" { + const Paints = struct { + fn search(_: ?*anyopaque, _: u32) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + }; + const gpa = std.testing.allocator; + // A view as tall as the text: the frame paints every line of it. + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 500, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + defer a.deinit(); + { + const was = Stepping.begin(&a.t, null); + defer was.end(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + _ = try a.core.render(arena.allocator()); + } + _ = try a.openView(2); + const joiner = try joinedNow(a, 3, 1); + defer joiner.deinit(); + var buf: [256]u8 = undefined; + for ("/co", 1..) |c, seq| { + const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); + defer gpa.free(u); + joiner.confirm(u); + try agrees(a, joiner); + } +} + +// The same for the colours a worker painted earlier, kept in the session's +// locations cache (a Grep since has asked again of every file): a dump +// carries no cache, so a client joined since has none. +test "a client joined from a dump asks a worker for a `/` query's colours as the session does, though only the session has them from an earlier paint" { + const Paints = struct { + fn search(_: ?*anyopaque, _: u32) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .search = search }; + }; + const gpa = std.testing.allocator; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "build.zig" }, .{ .vtable = &Paints.vtable }, false); + defer a.deinit(); + { + const p = a.core; + const f = &p.panes[0].?.file.?; + const colors = try pardes.syntax.highlightFileRange(gpa, f.path, f.content, 0, f.content.len); + defer gpa.free(colors); + try p.locations_cache.put(p.tree_sitter_gpa, f.path, f.content, colors); + } + _ = try a.openView(2); + const joiner = try joinedNow(a, 3, 1); + defer joiner.deinit(); + var buf: [256]u8 = undefined; + for ("/co", 1..) |c, seq| { + const u = try gpa.dupe(u8, try a.take(try inputOf(&buf, 1, @intCast(seq), .{ .key = .{ .cp = c, .text = &.{c} } }))); + defer gpa.free(u); + joiner.confirm(u); + try agrees(a, joiner); + } +} + test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; @@ -6169,9 +6596,12 @@ const may_wait = [_]Wait{ .{ .what = "*", .on = .addon, .stop = "a kind's close", .why = "a kind's pane closed: its state let go on the session" }, .{ .what = "*", .on = .addon, .stop = "a kind's word", .why = "a word to a kind (a key it takes as one): its own state" }, .{ .what = "*", .on = .addon, .stop = "a kind's open", .why = "a kind's pane opened (`Life`): its state made on the session" }, -} ++ (if (pardes.platform == .gui) [_]Wait{ +} ++ (if (pardes.font_picker) [_]Wait{ // A window's view (the font words are a window's). .{ .what = "Font *", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, +} else [_]Wait{}) ++ (if (pardes.builtins.capabilities.font_picker) [_]Wait{ + // ...and Fonts a terminal's build has too, which a window client of its + // session runs (exec.zig's Font, a window build's alone, does not). .{ .what = "Fonts", .on = .any, .stop = "fonts", .why = "the session's machine's fonts, its disk" }, } else [_]Wait{}); @@ -6325,6 +6755,23 @@ const Walk = struct { return what.len >= pattern.len - 1 and std.mem.startsWith(u8, what, pattern[0..star]) and std.mem.endsWith(u8, what, pattern[star + 1 ..]); } + /// Every word, with a sample argument where one is required. + fn words(w: *Walk) !void { + var line: [128]u8 = undefined; + for (std.enums.values(pardes.builtins.registry.Builtin())) |b| { + const name = @tagName(b); + const arg: ?[]const u8 = for (walk_samples) |s| { + if (std.mem.eql(u8, s[0], name)) break s[1]; + } else null; + if (pardes.builtins.registry.requiresArg(b) and arg == null) { + std.debug.print("may_wait: `{s}` requires an argument: give it one in walk_samples\n", .{name}); + return error.NoSample; + } + const cmd = if (arg) |x| try std.fmt.bufPrint(&line, "{s} {s}", .{ name, x }) else name; + try w.try_(cmd, &.{.{ .command = cmd }}); + } + } + /// The name of what stopped the inputs, "" when none did. fn try_(w: *Walk, what: []const u8, evs: []const pardes.Event) !void { const r = w.r; @@ -6391,7 +6838,6 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' var hit: [may_wait.len]bool = @splat(false); var unlisted: u32 = 0; var tried: u32 = 0; - const Builtin = pardes.builtins.registry.Builtin(); const stands = [_]struct { On, ?usize }{ .{ .file, file }, .{ .kind, kind }, .{ .shell, shell }, .{ .shell_normal, shell } }; for (stands) |stand| { const on, const at = stand; @@ -6413,19 +6859,7 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' try std.testing.expectEqual(id, r.core().view().active); if (on == .shell) try std.testing.expect(pardes.Term.modes(r.core().panes[id].?.terminal).focus); var w: Walk = .{ .r = r, .on = on, .seen = &seen, .hit = &hit }; - // Every word, with a sample argument where one is required. - for (std.enums.values(Builtin)) |b| { - const name = @tagName(b); - const arg: ?[]const u8 = for (walk_samples) |s| { - if (std.mem.eql(u8, s[0], name)) break s[1]; - } else null; - if (pardes.builtins.registry.requiresArg(b) and arg == null) { - std.debug.print("may_wait: `{s}` requires an argument: give it one in walk_samples\n", .{name}); - return error.NoSample; - } - const cmd = if (arg) |x| try std.fmt.bufPrint(&line, "{s} {s}", .{ name, x }) else name; - try w.try_(cmd, &.{.{ .command = cmd }}); - } + try w.words(); // Every key, plain, with Ctrl and with Alt, and after each prefix. var name_buf: [64]u8 = undefined; for (walk_keys) |k| try w.try_(keyName(&name_buf, k), &.{.{ .key = k }}); @@ -6464,6 +6898,19 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' unlisted += w.unlisted; tried += w.tried; } + // A terminal's build has the window's words too, which a window's view + // runs (a window client of its session; builtins.capabilities): its + // words walked again in one. + if (comptime pardes.builtins.desktop and pardes.platform != .gui) { + a.core.view().active = file; + _ = try a.local(.{ .frontend = .{ .windowed = true } }); + const r = try joinedFresh(a); + defer r.deinit(); + var w: Walk = .{ .r = r, .on = .file, .seen = &seen, .hit = &hit }; + try w.words(); + unlisted += w.unlisted; + tried += w.tried; + } // A row is stale where every kind of pane was walked: with no terminal // compiled in (core-test), a shell's rows stop nothing. var stale: u32 = 0; @@ -6660,25 +7107,28 @@ test "an idle client's check answered covers the units that came while it was as _ = libc.close(fd); }; var c: Link = .{ .r = r, .fd = fds[0], .now = std.time.ns_per_s }; + // Each unit made as the client takes it, on its clock (Link.behind). const unit = struct { - fn of(au: *Authority) !Said { - return .{ .unit = try std.heap.c_allocator.dupe(u8, try au.local(.tick)) }; + fn of(au: *Authority, l: *const Link) !Said { + const u = try std.heap.c_allocator.dupe(u8, try au.local(.tick)); + std.mem.writeInt(i64, u[14..22], @intCast(l.now.?), .little); + return .{ .unit = u }; } }.of; // Something changed, 300 ms quiet since its last input: asked. - c.take(try unit(a)); + c.take(try unit(a, &c)); try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(c.asked); // The session's pump for it (a unit), then the answer: agreed, and // nothing to ask after it however long it stays quiet. - c.take(try unit(a)); + c.take(try unit(a, &c)); c.take(.{ .checked = digestOf(a) }); try std.testing.expect(!c.asked and c.r.diverged == null); c.now.? += 10 * std.time.ns_per_s; try std.testing.expectEqual(@as(?u32, null), c.quietCheck()); try std.testing.expect(!c.asked); // A unit after it is a change again. - c.take(try unit(a)); + c.take(try unit(a, &c)); c.now.? += std.time.ns_per_s; _ = c.quietCheck(); try std.testing.expect(c.asked); diff --git a/core/root.zig b/core/root.zig index 80495436..572204a1 100644 --- a/core/root.zig +++ b/core/root.zig @@ -737,7 +737,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Core.zig", "needs_frame", "whether to draw: steps set it, the loop reads it; no step's outcome reads it" }, .{ "Core.zig", "effects effects_head effects_len in_q in_head in_len opts dump_out dump_export tape", "this process's queues, options and tape, drained or set by its host" }, .{ "Core.zig", "shell_rows", "a terminal's rows as read here, swept at every update; a terminal is in no digest (Term.zig)" }, - .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest)" }, + .{ "Core.zig", "diff_output locations_cache tty_filter_palette body_chrome", "caches of pure functions of their key (a text, a theme): a step finds what it would make; a query row's colours from them are out of its digest (locations.Row.digest), and what a step asks a worker to paint is never decided by them (Stream.paintRows)" }, .{ "Core.zig", "retired_panes", "panes torn down this step, freed at its end" }, .{ "Core.zig", "distrusted frames tape", "Options: the client's own list, its runner's statistics, its tape" }, .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, @@ -746,7 +746,7 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, - .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest)" }, + .{ "File.zig", "highlights highlight_start syntax_dirty", "how a text looks, painted by frames: read by frames, and by a query's rows for colours only (out of their digest; what a step asks a worker to paint is never decided by them, Stream.paintRows)" }, .{ "File.zig", "allocator", "ContextCache's: what its declarations were made with, the parse's or a load's (a machine's handle, no state)" }, .{ "File.zig", "declarations", "ContextCache's: the text's at its revision (dumped, digested), parsed again from the text at a load" }, .{ "File.zig", "node_tree node_tree_revision node_tree_edits node_history", "the parse of the text at its revision, made by the first key that walks it" }, diff --git a/core/syntax.zig b/core/syntax.zig index 00ee497f..1bb8fb52 100644 --- a/core/syntax.zig +++ b/core/syntax.zig @@ -37,11 +37,10 @@ const Spec = struct { capture_styles: [256]u8 = undefined, }; +/// A grammar is in the build when the build gave its queries (build/core.zig +/// `treeSitter`): a tier's set, or the languages a package named. fn grammarSelected(comptime g: grammar_manifest.Grammar) bool { - return switch (g.tier) { - .minimal => minimal_grammars, - .full => full_grammars, - }; + return @hasDecl(ts_queries, g.name ++ "_highlights"); } fn specCount() comptime_int { diff --git a/core/tape.zig b/core/tape.zig index 09985d15..6af332a3 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -131,9 +131,9 @@ pub const Site = enum(u16) { /// What a call into a kind did (Kind.Outcome), and a kind's pane's /// tag prefix: the authority's, whose core alone runs the kind. addon, - /// The hash of a terminal's snapshot as the session reloaded it at a - /// join (panes.reloadTerminals), which every replica's own reload - /// compares. + /// Whether the session reloads a terminal at a join (written since its + /// last reload), then the hash of its snapshot as it did + /// (panes.reloadTerminals), which every replica's own reload compares. reload, /// A kitty image's medium as a terminal's emulator read it (a file, a /// temporary file, shared memory: Term.media), its bytes or its failure. @@ -1484,15 +1484,19 @@ pub fn endSpeculation(t: *Tape) bool { /// a message may be (replica.zig `lag_max`'s neighbour, wire's bound). pub const unit_max = 1 << 20; -/// Whether a unit feeds a terminal its program's output (a pty's read; an -/// input kept by hash is taken to): never taken as moving nothing (the -/// replica engine's one rule, core/replica.zig `confirm`). +/// Whether a unit writes a terminal's emulator: feeds one its program's +/// output (a pty's read; an input kept by hash is taken to), or reloads +/// every one at a join (`Site.reload`; a join refused too, which moves +/// nothing a digest covers): never taken as moving nothing (the replica +/// engine's one rule, core/replica.zig `confirm`). pub fn feedsTerminal(bytes: []const u8) bool { const Tag = std.meta.Tag(Input); const EventTag = std.meta.Tag(pardes.Event); + const reload: u16 = @as(u16, host_fns.len) + @backingInt(Site.reload); var r: walk.Reader = .{ .bytes = bytes }; while (nextRecord(&r)) |rec| switch (rec.kind) { .blob => if (rec.payload.len > 0 and rec.payload[0] == @backingInt(Kind.input)) return true, + .host => if (rec.payload.len >= 2 and std.mem.bytesToValue(u16, rec.payload[0..2]) == reload) return true, .input => { if (rec.payload.len < @sizeOf(Tag) + @sizeOf(EventTag)) continue; if (!std.mem.eql(u8, rec.payload[0..@sizeOf(Tag)], std.mem.asBytes(&@as(Tag, .update)))) continue; diff --git a/core/term/terminal.zig b/core/term/terminal.zig index e57193a6..1673a3d8 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -1792,3 +1792,34 @@ test "a join at a cut: every side reloaded from its own snapshot holds the same // another terminal once heavy colour has pruned pages cut otherwise. try std.testing.expectEqual(2, heavy_apart); } + +test "wide characters filling a scrollback past its limit, reflowed: its snapshot loads to the same snapshot and hash, and goes on as the same terminal through more bytes and reflows" { + // The soak's `cat` (test/replicas.zig): source lines, one in a few + // hundred with wide characters (CJK, box drawing, ambiguous symbols), + // a full scrollback pruned a page at a time, reflowed at odd widths + // where a wide character meets the right edge. + const gpa = std.testing.allocator; + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + const wide = " try writeText(notes, \"# Fallback faces and rules\\n\\n| name | glyphs |\\n|------|--------|\\n| cjk | \u{754C}\u{9762}\u{5B57} |\\n| sym | \u{222E} \u{2260} \u{2605} |\\n\\n\u{250C}\u{2500}\u{2500}\u{252C}\u{2500}\u{2500}\u{2510}\\n\u{2502} a\u{2502} b\u{2502}\\n\u{2514}\u{2500}\u{2500}\u{2534}\u{2500}\u{2500}\u{2518}\\n\");"; + for (0..30000) |i| { + if (i % 7 == 3) try out.writer.print("{s}\r\n", .{wide}) else try out.writer.print("{s} {d}\r\n", .{ " const line = std.fmt.bufPrint(&buf, \"{d}\", .{i}) catch continue;"[0 .. 8 + i % 60], i }); + } + const bytes = out.written(); + const stops: [2]usize = .{ bytes.len / 3, 2 * bytes.len / 3 }; + const first = try openKeeping(gpa, 121, 40, 1 << 20); + defer close(first); + feedReflowing(first, bytes, 0, bytes.len / 2, stops); + const snap = try snapshotOf(gpa, first); + defer gpa.free(snap); + const loaded = try load(gpa, snap, &parts(first)); + defer close(loaded); + const again = try snapshotOf(gpa, loaded); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, snap, again); + try std.testing.expectEqual(joinHash(snap), try reload(first)); + try expectSame(gpa, first, loaded); + feedReflowing(first, bytes, bytes.len / 2, bytes.len, stops); + feedReflowing(loaded, bytes, bytes.len / 2, bytes.len, stops); + try expectSame(gpa, first, loaded); +} diff --git a/core/views.zig b/core/views.zig index 89dcb454..2ddbb523 100644 --- a/core/views.zig +++ b/core/views.zig @@ -29,6 +29,13 @@ const MAX_PANES = pardes.MAX_PANES; /// Views at once: a window or terminal each. pub const max = 4; +/// How long a view kept for its client's rejoin (`away`) is that client's +/// alone: a join with no room is refused meanwhile, and takes it after +/// (Pardes.openView). A client that said it joins again dials at once, and +/// its join waits for its dump to cross: the soak's far link (1 Mbit/s, +/// 200 ms each way) has taken up to 18.3 s from one of its joins to the +/// next (a flood, joins for its lag). Past 30 s, it is taken as gone. +pub const away_kept_ns: u64 = 30 * std.time.ns_per_s; /// A pane's fields that are each view's own: where it is in the view's /// layout, which of its texts has the keyboard, how far it is scrolled, and @@ -324,7 +331,11 @@ pub fn gone(p: *Pardes, id: usize) void { fn park(p: *Pardes) void { for (p.panes) |s| if (s) |pane| { + // The slot owns the live text's selections now: known, so that + // the pane's end or the view's frees them (a pane made while one + // view was open had no view known). pane.pv[p.live] = extract(pane); + pane.pv_known |= bit(p.live); }; } @@ -466,6 +477,7 @@ pub fn away(p: *Pardes, k: u8) void { if (!isOpen(p, k)) return; if (k == p.live) if (looked(p, k) orelse open(p)) |other| to(p, other); p.views_away |= bit(k); + p.views[k].?.away_ns = p.clock.now_ns; } /// The session's end: what each view holds. @@ -601,6 +613,25 @@ test "each view has its own cursor and scroll, and an edit in one is in the othe try testing.expectEqual(Text.Mode.normal, pane.body.mode); } +// A pane made while one view is open is its share there alone; the +// ranges beside its primary that a key makes are the live text's, and +// the view's slot owns them once another view is live (park): freed with +// the pane, or with that view. +test "a text's ranges beside its primary, made while one view was open, are freed once another view has been live" { + const gpa = testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const text = try numbered(gpa, 20); + defer gpa.free(text); + const pane = try p.setTestFile(text); + // A second cursor below, and a key typed in insert mode at both. + typeKeys(p, "Cix"); + escape(p); + try testing.expect(pane.body.sels.len > 0); + try testing.expectEqual(@as(?View.Id, .at(1)), p.openView()); + p.toView(.at(1)); +} + test "each view has its own layout and focus over the same panes" { const gpa = testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); @@ -742,7 +773,7 @@ test "the last client's view going leaves the session its layout, which a rejoin try testing.expectEqual(@as(i32, 60), pane.body.cur_row); } -test "a client's view kept for its rejoin: through an Upgrade's dump, each client back in its own; a join with no room lets one go" { +test "a client's view kept for its rejoin: through an Upgrade's dump, each client back in its own; a join with no room lets one go only once it has been kept away_kept_ns" { const gpa = testing.allocator; const opts: pardes.Options = .{ .tty_only = true, .cols = 100, .rows = 30 }; const p = try Pardes.init(gpa, opts); @@ -775,9 +806,17 @@ test "a client's view kept for its rejoin: through an Upgrade's dump, each clien try testing.expect(layout.findPane(q, made[1 - i]) == null); } try testing.expect(!q.rejoinView(ks[0])); - // A client that never comes back: its view goes when a join has no room. + // A client that said it joins again is coming back (a far one's join + // for its lag waits seconds for its dump): a join with no room is + // refused, its view not let go, until `away_kept_ns` has passed. p.toView(.at(0)); try testing.expectEqual(@as(?View.Id, .at(3)), p.openView()); + try testing.expectEqual(@as(?View.Id, null), p.openView()); + p.advance(p.clock.now_ns + away_kept_ns - 1); + try testing.expectEqual(@as(?View.Id, null), p.openView()); + try testing.expect(isAway(p, ks[0].index()) and isAway(p, ks[1].index())); + // One that never comes back: its view goes once the bound has passed. + p.advance(p.clock.now_ns + 1); try testing.expectEqual(ks[0], p.openView()); try testing.expect(!isAway(p, ks[0].index()) and isAway(p, ks[1].index())); } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 94939452..f2b3289f 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -122,18 +122,38 @@ exe.root_module.addImport("pardes-editor", pardes.module("pardes-editor")); `.grammars`: the tree-sitter grammars compiled in: `none` (the runtime alone), `minimal` (C, C++ and Zig) or `full` (all of them; the default). -`.editor`: exports `pardes-editor` besides `pardes-syntax`, and with it -fetches uucode, mvzr and vaxis. +`.languages`: instead of `.grammars`, the languages compiled in by name +(`"rust"`, or `&.{ "rust", "go" }`), each with what it needs (markdown +its inline grammar); a name the manifest does not have fails the +configure. `.editor`: exports `pardes-editor` besides `pardes-syntax`, +and with it fetches uucode, mvzr and vaxis. + +The manifest, for a package's build script to read at configure time +(`@import("pardes").grammar_manifest.all`: each grammar's name, its +extensions and what it needs), is `grammar_manifest`. + +A browser's module, one call a language (`wasmModule`, below): + +``` +const pardes = @import("pardes"); +b.installArtifact(pardes.wasmModule(b, .{ .language = "rust" })); +b.installArtifact(pardes.wasmModule(b, .{})); // the patch view alone +``` Every dependency but tree-sitter's runtime is lazy in the manifest, so such a package fetches what it asked for and nothing else. `pardes-editor` has `pardes-syntax` in it as `.syntax`: a file belongs to one module, so a package imports one of the two. `test/consumer` is -such a package, with both shapes; `consumer-test`, which `unit-test` runs, +such a package, with every shape; `consumer-test`, which `unit-test` runs, builds and runs it. `build.zig.zon` names pardes by its path: `.pardes = .{ .path = "../pardes" }`. +Zig reports an option a dependency does not have, or a value it cannot +read, and builds on with the default (exit code 0): pardes ends the +configure itself (exit code 1, the manifest's names) for a language it +does not have, and for `.grammars` given beside `.languages`. + === The syntax It is the editor's own code under the names it has there. A language is @@ -146,6 +166,7 @@ for a language's name. [`theme`, `themes`, `page`, `ink`, `synInk`], [a theme by name and what it draws a page, its text and each class in], [`lineCount`, `lineStartOffset`, `lineSlice`], [a line's bytes from its number], [`grammars`, `supportsPath`, `pathFor`], [every grammar, and whether this build has a path's], + [`formatPatch`, `PatchCtx`, `Patch`, `PatchRow`, `PatchSource`], [a unified diff stacked as the patch view shows it (below)], [`start`, `stop`], [tree-sitter's allocator, and the end of the parsers kept per language], ) @@ -156,6 +177,85 @@ pardes's `zig-pkg` shares the one copy. What a pane measures stays out: a cell's width is vaxis's and uucode's, and a tab is `config.tab_width` cells wherever it stands. +=== The patch view + +`formatPatch` stacks a unified diff as pardes's +Diff shows it, with +nothing of the editor: each hunk under its `path:line`, what it stands in +above it, its lines behind their markers on their grounds, and the words a +changed line changed emphasised (delta's way). It returns a `Patch`, its +text and a `PatchRow` for each of its lines (row _i_ is line _i_), all in +the arena it is handed: + +#pairs( + [`kind`], [`other` (a mailed patch's headers, message, diffstat), `meta` (a section's own words: a mode, a rename, `Binary files ... differ`), `hunk` (its label, a star a declaration it stands in), `declaration` (what it stands in: a declaration's `path:line` and header lines from the file, or git's own words after the `@@`), `context`, `added`, `removed`], + [`path`, `line`], [the file its section names, and the line of it the row points at (0 for none)], + [`old`, `new`], [a hunk line's numbers in the old and the new file, null on the side it is not on], + [`location_end`, `code_start`], [where a label's `path:line` ends and what follows it starts], + [`styles`], [a byte a byte of its text: a `Syn` in `syn_bits` (with colours), `ground_add` or `ground_del` on a changed line, `ground_line` on the marker of one no other line changed, `ground_emph` on a changed word], + [`no_newline`], [the diff's `\ No newline at end of file` follows it], +) + +What it takes of the program is a `PatchCtx`: an `arena`, and, each with +a default, `source` (the file a section names, as a `PatchSource`: its +text and path; none by default, so each hunk is numbered by the diff and +stands under git's words), `declarations` (none; `PatchCtx.parsed` reads +them from the file's parse), `colors` (none; `PatchCtx.languages` colours +each hunk as its file's language), `width` (code points; it decides +whether two lines are one changed) and `tslocations`. With no `colors` +and no `declarations` it calls nothing of tree-sitter. A reader with a +commit's two blobs hands the new one in as `source` (or the old one, for a +file the commit deleted): the hunk is found in it on either side. + +=== In a browser + +`wasmModule(b, .{ .language = "rust" })`, called from a package's build +script after `@import("pardes")` (its dependency named `pardes`), gives +the compile step of one module for a browser: wasm32-wasi, a reactor (no +`main`: `_initialize`, then any export), with that language's grammar and +what it needs, tree-sitter's runtime and pardes's highlighter. With no +`.language` it is the patch view alone, with no tree-sitter in it and no +import at all. `.optimize` is `ReleaseSmall` unless given. A name the +manifest does not have fails the configure. The module is +`pardes-<language>.wasm`, or `pardes-patch.wasm`; its exports +(`core/lib_wasm.zig`) are the same in every module: + +#pairs( + [`memory`, `_initialize`], [its memory, and what a reactor runs once before any other call], + [`reserve(len)`, `release(ptr, len)`], [`len` bytes for the page to write an argument into (at least one, so `reserve(0)` is a pointer too), and their return], + [`highlight(path, path_len, text, len)`], [(a module with a language) a style byte for each byte of `text`: 0 none, 1 keyword, 2 string, 3 number, 4 comment, as pardes colours the file `path` names by its extension; all 0 for a path of another language. The module's until the next `highlight`], + [`patch(text, len)`], [the diff `text` stacked as the patch view shows it, with no file and no colours: a pointer to a header. The module's until the next `patch`], +) + +Each returns 0 when its memory runs out. Pointers and lengths are +wasm32's: unsigned 32-bit; in memory they are little-endian. `patch`'s +header is five u32, 20 bytes: + +#pairs( + [0 `text`, 4 `text_len`], [the rows' text, a line a row, each ending in a newline; the rows' paths follow it in the same buffer], + [8 `styles`], [a byte for each byte of the text: `ground_add` 0x80 or `ground_del` 0x40 on a changed line, `ground_line` 0x10 on the marker of one no other line changed, `ground_emph` 0x20 on the words a changed line changed], + [12 `rows`, 16 `row_count`], [the rows, a record of nine u32 (36 bytes) each], +) + +and a row's record: + +#pairs( + [0 `kind`], [0 other, 1 meta, 2 hunk, 3 declaration (git's words after the `@@`), 4 context, 5 added, 6 removed], + [4 `old`, 8 `new`], [its numbers in the old and the new file, from 1; 0 where it has none], + [12 `code_start`], [where its code starts in its text: after a hunk label's `path:line` and stars], + [16 `text_offset`, 20 `text_len`], [its text, without its newline, in the header's `text`], + [24 `path_offset`, 28 `path_len`], [its section's path, in the header's `text` too], + [32 `flags`], [bit 0: the diff has `\ No newline at end of file` after it], +) + +A module with a language imports three functions of +`wasi_snapshot_preview1`, `fd_write`, `fd_seek` and `fd_close` (libc's +streams, which tree-sitter's debug output names; `fd_write` is also how a +panic's message reaches stderr); a page stubs each (`fd_write` may write +to the console, the others answer `ENOSYS`, 52). The patch view's module +imports nothing. `test/consumer/wasm.mjs` is such a page, run by node: +`consumer-test` builds both shapes through `wasmModule` and runs them when +`node` is on PATH, and says so when it is not. + === The editor `pardes-editor` (`core/lib_editor.zig`) is the text pane as a library: @@ -198,8 +298,9 @@ zig build kitty-harness kitty graphics through a pane end to end (a fake kitt terminal outside on the tui, the GPU capture on the gui; kitten icat and chafa too when installed) zig build syntax deterministic per-byte highlighting snapshots -zig build consumer-test the library, from a package that depends on pardes (test/consumer); - unit-test runs it too +zig build consumer-test the library, from a package that depends on pardes (test/consumer): + its shapes, a language named alone, the browser's modules + under node; unit-test runs it too zig build hxlib helix's cases on the library's editor (-- --parity: against the file pane) zig build behaviour-test behaviour through the 9P tree, in process (test/behaviour/), and the T1 runner's short run of random 9P requests diff --git a/runtime/client.zig b/runtime/client.zig index 22e60fc1..d4b76a1b 100644 --- a/runtime/client.zig +++ b/runtime/client.zig @@ -185,8 +185,9 @@ pub fn Loop(comptime Frontend: type) type { l.link.take(msg); } - /// A join a pass: the first, and one after the replica diverged or - /// the session let it go to upgrade; the frontend stays as it is. + /// A join a pass: the first, and one after the replica diverged, fell + /// too far behind (replica.behind_max_ms) or the session let it go + /// (to upgrade, or cut off); the frontend stays as it is. pub fn run(l: *L, s: *Start) !Ended { const link = &l.link; // Its start path's file, for an Upgrade's question (`upgrade`). @@ -203,7 +204,7 @@ pub fn Loop(comptime Frontend: type) type { l.after(); } if (s.env.get("PARDES_REPLICA_STATS")) |file| link.writeStats(file); - if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null, .close = link.close }); + if (!link.gone) replica.bye(s.joined.fd, .{ .again = s.r.diverged != null or link.lagged != 0, .close = link.close }); // The link's reader ends with the link, posting as it goes: // what it posted is let go until it has (a terminal's queue // is bounded: a reader blocked on it would never end). diff --git a/test/consumer/build.zig b/test/consumer/build.zig index c643bfb3..45e1e2e5 100644 --- a/test/consumer/build.zig +++ b/test/consumer/build.zig @@ -1,33 +1,96 @@ //! A package that depends on pardes, as a program would (build.zig's head //! comment has its lines): pardes's `consumer-test`, which `unit-test` runs, //! runs `zig build test` here. `pardes-syntax` with the minimal grammars, -//! as a program that draws source text itself takes it; and -//! `pardes-editor` with no grammar of pardes's and one of its own, C's, -//! compiled here from the package pardes pins and handed in at run time, -//! as sketchbook's `examples/live` takes it. +//! as a program that draws source text itself takes it; with one language +//! named, for each language of pardes's manifest, read here at configure +//! time; `pardes-editor` with no grammar of pardes's and one of its own, +//! C's, compiled here from the package pardes pins and handed in at run +//! time, as sketchbook's `examples/live` takes it; and the browser's modules +//! pardes's build makes (`wasmModule`), run under node when it is there. const std = @import("std"); +const pardes = @import("pardes"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + // A name pardes's manifest does not have ends the configure: the step + // `bad-language` below runs this build with one. + if (b.option([]const u8, "language", "configure pardes with this one language named, and stop")) |name| { + _ = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = name }); + return; + } const syntax = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .minimal }); const editor = b.dependency("pardes", .{ .target = target, .optimize = optimize, .grammars = .none, .editor = true }); // The grammar of its own: C's, from the package pardes's manifest pins // (so `--pkg-dir` at pardes's zig-pkg has it), as that package builds it. const grammar = b.dependency("ts_c", .{ .target = target, .optimize = .ReleaseFast, .@"build-shared" = false }).artifact("tree-sitter-c"); - const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, and edit a text with its editor and a grammar of this package's"); + const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's syntax, build it with one language named, edit a text with its editor and a grammar of this package's, and run a browser's modules"); // A file belongs to one module: the syntax alone, and the editor (which // has it as `.syntax`), each a test of its own. - for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor } }) |t| { + // The patch view with no grammar at all: the editor's package has + // `pardes-syntax` too. + for ([_]struct { []const u8, []const u8, *std.Build.Dependency }{ .{ "lib.zig", "pardes-syntax", syntax }, .{ "editor.zig", "pardes-editor", editor }, .{ "none.zig", "pardes-syntax", editor } }) |t| { const mod = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path(t[0]), .imports = &.{.{ .name = t[1], .module = t[2].module(t[1]) }}, }); - if (t[2] == editor) mod.linkLibrary(grammar); + if (std.mem.eql(u8, t[1], "pardes-editor")) mod.linkLibrary(grammar); step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = mod })).step); } + + // Each language a file names, from pardes's manifest: `pardes-syntax` + // with it alone (and what it needs). `test` runs two: rust, alone, and + // markdown, which brings its inline grammar. + const each = b.step("each-language", "build and test pardes-syntax with each language of its manifest named alone"); + // A browser's module a language, and the patch view's: `sizes` + // installs every one; `test` runs the patch view's and rust's. + const sizes = b.step("sizes", "install a browser's module for each language, and the patch view's, into <prefix>/bin"); + const patch = pardes.wasmModule(b, .{}); + sizes.dependOn(&b.addInstallArtifact(patch, .{}).step); + var rust: ?*std.Build.Step.Compile = null; + for (pardes.grammar_manifest.all) |g| if (g.exts.len > 0) { + const module = pardes.wasmModule(b, .{ .language = g.name }); + sizes.dependOn(&b.addInstallArtifact(module, .{}).step); + if (std.mem.eql(u8, g.name, "rust")) rust = module; + const name = b.addOptions(); + name.addOption([]const u8, "name", g.name); + const one = b.addRunArtifact(b.addTest(.{ .name = b.fmt("one-{s}", .{g.name}), .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("one.zig"), + .imports = &.{ + .{ .name = "pardes-syntax", .module = b.dependency("pardes", .{ .target = target, .optimize = optimize, .languages = g.name }).module("pardes-syntax") }, + .{ .name = "language", .module = name.createModule() }, + }, + }) })); + each.dependOn(&one.step); + if (std.mem.eql(u8, g.name, "rust") or std.mem.eql(u8, g.name, "markdown")) step.dependOn(&one.step); + }; + // Each run as a page runs it, its WASI imports stubs. + if (b.findProgram(.{ .names = &.{"node"} })) |node| { + const run = b.addSystemCommand(&.{node}); + run.setName("node: the patch view's module and rust's"); + run.addFileArg(b.path("wasm.mjs")); + run.addArtifactArg(patch); + run.addArtifactArg(rust.?); + run.expectExitCode(0); + step.dependOn(&run.step); + } else { + std.debug.print("consumer-test: no node on PATH: the browser's modules are built, not run\n", .{}); + step.dependOn(&patch.step); + step.dependOn(&rust.?.step); + } + // ...and a name it does not have: the configure fails, saying so. + const bad = b.addSystemCommand(&.{ b.graph.zig_exe, "build", "-Dlanguage=klingon", "--pkg-dir", "../../zig-pkg" }); + bad.setName("a language pardes does not have fails the configure"); + bad.setCwd(b.path(".")); + bad.expectExitCode(1); + bad.addCheck(.{ .expect_stderr_match = "no language \"klingon\"" }); + bad.has_side_effects = true; + step.dependOn(&bad.step); + // What a key costs, a page count and a parse: `zig build bench -- <KiB> <keys>`. const bench = b.addExecutable(.{ .name = "bench", .root_module = b.createModule(.{ .target = target, diff --git a/test/consumer/lib.zig b/test/consumer/lib.zig index 7e297920..fa0f8aee 100644 --- a/test/consumer/lib.zig +++ b/test/consumer/lib.zig @@ -159,3 +159,98 @@ test "a diff is a language: its hunks coloured as their file's, its added and re test "every name the library has compiles outside pardes" { std.testing.refAllDecls(pardes); } + +// ---- the patch view (+Diff), without the editor ---- + +const patch_c = + \\diff --git a/main.c b/main.c + \\--- a/main.c + \\+++ b/main.c + \\@@ -2,4 +2,4 @@ int main(void) + \\ { + \\- int x = foo(1); + \\+ int x = bar(1); + \\ return x; + \\ } + \\\ No newline at end of file + \\ +; +/// main.c as the patch leaves it: what a reader hands in as its source. +const main_c = "int main(void)\n{\n int x = bar(1);\n return x;\n}"; + +/// Each byte of `text` that has `bit`, the rest as dots. +fn marked(buf: []u8, text: []const u8, styles: []const u8, bit: u8) []const u8 { + for (buf[0..text.len], text, styles) |*o, c, s| o.* = if (s & bit != 0) c else '.'; + return buf[0..text.len]; +} + +test "a diff stacked with no file to read: numbered by the diff, under git's function line, its changed words emphasised" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:3\n int main(void)\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + const Kind = pardes.PatchRow.Kind; + const want = [_]struct { Kind, ?usize, ?usize }{ + .{ .hunk, null, null }, + // the `@@`'s own words: the hunk's context + .{ .declaration, null, null }, + .{ .context, 2, 2 }, + .{ .removed, 3, null }, + .{ .added, null, 3 }, + .{ .context, 4, 4 }, + .{ .context, 5, 5 }, + }; + try std.testing.expectEqual(want.len, p.rows.len); + for (want, p.rows) |w, row| { + try std.testing.expectEqual(w[0], row.kind); + try std.testing.expectEqual(w[1], row.old); + try std.testing.expectEqual(w[2], row.new); + try std.testing.expectEqualStrings("main.c", row.path); + } + try std.testing.expectEqual(3, p.rows[0].line); + try std.testing.expectEqual("main.c:3".len, p.rows[0].location_end); + try std.testing.expect(p.rows[6].no_newline and !p.rows[5].no_newline); + var lines = std.mem.splitScalar(u8, p.text, '\n'); + var buf: [64]u8 = undefined; + for (p.rows) |row| { + const line = lines.next().?; + if (row.styles.len > 0) try std.testing.expectEqual(line.len, row.styles.len); + switch (row.kind) { + // the words a changed line changed, on both lines; each on its + // ground, its marker not on the line's own (it was paired) + .removed => try std.testing.expectEqualStrings(".............foo....", marked(&buf, line, row.styles, pardes.ground_emph)), + .added => try std.testing.expectEqualStrings(".............bar....", marked(&buf, line, row.styles, pardes.ground_emph)), + else => {}, + } + if (row.kind == .removed) try std.testing.expectEqual(pardes.ground_del, row.styles[0]); + if (row.kind == .added) try std.testing.expectEqual(pardes.ground_add, row.styles[0]); + } + // coloured as C: `return` a keyword + const ret = p.rows[5].styles[std.mem.indexOf(u8, " return x;", "return").?]; + try std.testing.expectEqual(pardes.Syn.keyword, @as(pardes.Syn, @fromBackingInt(ret & pardes.syn_bits))); +} + +test "a diff stacked with its file handed in: the declaration it stands in, from the file's own parse" { + const gpa = std.testing.allocator; + pardes.start(gpa); + defer pardes.stop(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const Given = struct { + fn source(_: *const pardes.PatchCtx, _: []const u8, path: []const u8) ?pardes.PatchSource { + return if (std.mem.eql(u8, path, "main.c")) .{ .path = path, .bytes = main_c } else null; + } + }; + const ctx: pardes.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = pardes.PatchCtx.parsed, .colors = pardes.PatchCtx.languages }; + const p = try pardes.formatPatch(&ctx, "", patch_c); + try std.testing.expectEqualStrings("main.c:1\n int main(void)\nmain.c:3 *\n {\n- int x = foo(1);\n+ int x = bar(1);\n return x;\n }\n", p.text); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[0].kind); + try std.testing.expectEqual(1, p.rows[0].line); + try std.testing.expectEqual(pardes.PatchRow.Kind.declaration, p.rows[1].kind); + try std.testing.expectEqual(pardes.PatchRow.Kind.hunk, p.rows[2].kind); + try std.testing.expectEqual("main.c:3".len, p.rows[2].location_end); +} diff --git a/test/consumer/none.zig b/test/consumer/none.zig new file mode 100644 index 00000000..a389d429 --- /dev/null +++ b/test/consumer/none.zig @@ -0,0 +1,56 @@ +//! The patch view in a build with no grammar at all (`.grammars = .none`): +//! a diff of a file in a language it does not have still gets its grounds, +//! its changed words and its rows, and the colours it is not given stay +//! out. +const std = @import("std"); +const ps = @import("pardes-syntax"); + +const patch_rs = + \\diff --git a/src/lib.rs b/src/lib.rs + \\--- a/src/lib.rs + \\+++ b/src/lib.rs + \\@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 { + \\ let mut sum = 0; + \\- for i in items { sum += i; } + \\+ for i in items { sum += *i; } + \\ sum + \\ +; + +test "a diff with no grammar in the build: rows, grounds and changed words, no colours" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + try std.testing.expect(!ps.supportsPath("lib.rs")); + const ctx: ps.PatchCtx = .{ .arena = arena.allocator() }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + try std.testing.expectEqualStrings("src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + try std.testing.expectEqual(ps.PatchRow.Kind.hunk, p.rows[0].kind); + try std.testing.expectEqual(ps.PatchRow.Kind.declaration, p.rows[1].kind); + const removed = p.rows[3]; + const added = p.rows[4]; + try std.testing.expectEqual(.{ 11, null }, .{ removed.old, removed.new }); + try std.testing.expectEqual(.{ null, 11 }, .{ added.old, added.new }); + try std.testing.expectEqual(ps.ground_del, removed.styles[0]); + try std.testing.expectEqual(ps.ground_add, added.styles[0]); + // `*` added: the one word emphasised; no byte has a colour of its own + const star = std.mem.indexOfScalar(u8, "+ for i in items { sum += *i; }", '*').?; + for (added.styles, 0..) |s, i| try std.testing.expectEqual(i == star, s & ps.ground_emph != 0); + for (p.rows) |row| for (row.styles) |s| try std.testing.expectEqual(0, s & ps.syn_bits); +} + +test "with no grammar, a file handed in still places the hunk, and no declaration is made up" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const Given = struct { + fn source(_: *const ps.PatchCtx, _: []const u8, path: []const u8) ?ps.PatchSource { + return .{ .path = path, .bytes = "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ "\n" ++ + "fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n for i in items { sum += *i; }\n sum\n}\n" }; + } + }; + const ctx: ps.PatchCtx = .{ .arena = arena.allocator(), .source = Given.source, .declarations = ps.PatchCtx.parsed }; + const p = try ps.formatPatch(&ctx, "", patch_rs); + // found (no `@@` words then: git's guess would only contradict the + // file's own), and no grammar to read a declaration from + try std.testing.expectEqualStrings("src/lib.rs:11\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n", p.text); + for (p.rows) |row| try std.testing.expect(row.kind != .declaration); +} diff --git a/test/consumer/one.zig b/test/consumer/one.zig new file mode 100644 index 00000000..4a113842 --- /dev/null +++ b/test/consumer/one.zig @@ -0,0 +1,45 @@ +//! `pardes-syntax` built with one language named (`.languages`, build.zig +//! here: the build's loop over pardes's manifest makes one of these a +//! language): that language and what it needs (the manifest's `needs`) are +//! compiled in, and no other. +const std = @import("std"); +const ps = @import("pardes-syntax"); +const language = @import("language").name; + +test "one language named: it and what it needs are in the build, no other grammar is linked" { + const gpa = std.testing.allocator; + ps.start(gpa); + defer ps.stop(); + const g = ps.grammars; + const named = comptime named: { + @setEvalBranchQuota(10_000); + break :named g.all[g.byName(language).?]; + }; + // This test program's own bytes (a Debug build keeps its symbols): a + // name is spelled whole only in its symbol table. + const self = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, "/proc/self/exe", gpa, .unlimited); + defer gpa.free(self); + var name: [64]u8 = undefined; + inline for (g.all) |other| { + const in = comptime std.mem.eql(u8, other.name, named.name) or for (named.needs) |n| { + if (std.mem.eql(u8, n, other.name)) break true; + } else false; + // the parser itself, by its symbol in this program's symbol table: + // linked, or not in it + const symbol = try std.fmt.bufPrint(&name, "\x00tree_sitter_{s}\x00", .{other.name}); + try std.testing.expectEqual(in, std.mem.indexOf(u8, self, symbol) != null); + if (other.exts.len > 0) try std.testing.expectEqual(in, ps.supportsPath(ps.pathFor(other.name).?)); + } + + // what two of them colour: rust alone, and markdown with the inline + // grammar it brings (its bold is markdown_inline's) + for ([_]struct { []const u8, []const u8, []const u8, ps.Syn }{ + .{ "rust", "fn main() { let x = 1; }\n", "fn", .keyword }, + .{ "markdown", "# Title\n\nsome **bold** text\n", "bold", .comment }, + }) |case| if (std.mem.eql(u8, case[0], named.name)) { + const styles = try ps.highlightFileRange(gpa, ps.pathFor(language).?, case[1], 0, case[1].len); + defer gpa.free(styles); + const at = std.mem.indexOf(u8, case[1], case[2]).?; + for (styles[at..][0..case[2].len]) |s| try std.testing.expectEqual(case[3], @as(ps.Syn, @fromBackingInt(s))); + }; +} diff --git a/test/consumer/wasm.mjs b/test/consumer/wasm.mjs new file mode 100644 index 00000000..9e76af0f --- /dev/null +++ b/test/consumer/wasm.mjs @@ -0,0 +1,113 @@ +// The browser's modules pardes builds (build.zig `wasmModule`), run as a +// page runs them: `node wasm.mjs PATCH.wasm LANGUAGE.wasm`. Every WASI +// import is a stub (fd_prestat_get says there is no directory, the rest +// that they are not there), and each module prints what it imports. +import { readFileSync } from "node:fs"; + +let failed = 0; +function expect(what, got, want) { + if (JSON.stringify(got) !== JSON.stringify(want)) { + console.error(`${what}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); + failed++; + } +} + +function load(file) { + const mod = new WebAssembly.Module(readFileSync(file)); + const imports = WebAssembly.Module.imports(mod); + console.log(`${file}: ${imports.length} imports: ${imports.map((i) => i.module + "." + i.name).join(" ")}`); + let memory; + const wasi = new Proxy({}, { + get: (_, name) => (...a) => { + if (name === "fd_prestat_get") return 8; // EBADF: no preopened directory + if (name === "proc_exit") throw Error(`exit ${a[0]}`); + if (name === "fd_write") { + const [, iovs, n, written] = a; + const v = new DataView(memory.buffer); + let sum = 0; + for (let i = 0; i < n; i++) { + const p = v.getUint32(iovs + 8 * i, true), l = v.getUint32(iovs + 8 * i + 4, true); + process.stderr.write(Buffer.from(memory.buffer, p, l)); + sum += l; + } + v.setUint32(written, sum, true); + return 0; + } + return 52; // ENOSYS + }, + }); + const inst = new WebAssembly.Instance(mod, { wasi_snapshot_preview1: wasi }); + memory = inst.exports.memory; + inst.exports._initialize(); + return { ex: inst.exports, mem: () => memory.buffer }; +} + +const enc = new TextEncoder(), dec = new TextDecoder(); +function put(m, text) { + const b = enc.encode(text); + const p = m.ex.reserve(b.length); + new Uint8Array(m.mem(), p, b.length).set(b); + return [p, b.length]; +} + +// patch: the diff stacked, read from the header and its 36-byte records +const kinds = ["other", "meta", "hunk", "declaration", "context", "added", "removed"]; +function patch(m, diff) { + const [p, n] = put(m, diff); + const h = m.ex.patch(p, n); + m.ex.release(p, n); + const v = new DataView(m.mem()); + const [text, textLen, styles, rows, count] = [0, 4, 8, 12, 16].map((o) => v.getUint32(h + o, true)); + const bytes = new Uint8Array(m.mem(), text); + const out = []; + for (let i = 0; i < count; i++) { + const [kind, old, nw, codeStart, off, len, pathOff, pathLen, flags] = [...Array(9)].map((_, f) => v.getUint32(rows + 36 * i + 4 * f, true)); + out.push({ + kind: kinds[kind], old, new: nw, codeStart, flags, + text: dec.decode(bytes.subarray(off, off + len)), + path: dec.decode(bytes.subarray(pathOff, pathOff + pathLen)), + styles: [...new Uint8Array(m.mem(), styles + off, len)], + }); + } + return { text: dec.decode(bytes.subarray(0, textLen)), rows: out }; +} + +const diff = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -10,3 +10,3 @@ fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n\\ No newline at end of file\n"; +for (const file of process.argv.slice(2)) { + const m = load(file); + // reserve(0) is a pointer still + const zero = m.ex.reserve(0); + expect(`${file} reserve(0)`, zero !== 0, true); + m.ex.release(zero, 0); + + const p = patch(m, diff); + expect(`${file} patch text`, p.text, "src/lib.rs:11\n fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n sum\n"); + expect(`${file} patch rows`, p.rows.map((r) => [r.kind, r.old, r.new, r.path, r.flags]), [ + ["hunk", 0, 0, "src/lib.rs", 0], + ["declaration", 0, 0, "src/lib.rs", 0], + ["context", 10, 10, "src/lib.rs", 0], + ["removed", 11, 0, "src/lib.rs", 0], + ["added", 0, 11, "src/lib.rs", 0], + ["context", 12, 12, "src/lib.rs", 1], + ]); + expect(`${file} hunk code start`, p.rows[0].codeStart, "src/lib.rs:11".length); + // the added line: its ground on the marker (0x80), and `*` its changed word (0x20) + const added = p.rows[4]; + expect(`${file} added styles`, added.styles.map((s, i) => (s & 0x20 ? added.text[i] : s & 0x80 ? "+" : ".")).join(""), [...added.text].map((c, i) => (i === 0 ? "+" : c === "*" ? "*" : ".")).join("")); + + if (m.ex.highlight) { + const src = 'fn main() { let s = "x"; }\n'; + const [pp, pn] = put(m, "main.rs"); + const [tp, tn] = put(m, src); + // (a call can grow the memory: its buffer is taken after it) + const at = m.ex.highlight(pp, pn, tp, tn); + const s = new Uint8Array(m.mem(), at, tn); + expect(`${file} highlight fn`, [s[0], s[1]], [1, 1]); + expect(`${file} highlight "x"`, s[src.indexOf('"')], 2); + const c = put(m, "main.c"); + const other = m.ex.highlight(c[0], c[1], tp, tn); + expect(`${file} highlight another language`, [...new Uint8Array(m.mem(), other, tn)].every((b) => b === 0), true); + } +} +if (failed) process.exit(1); +console.log("wasm: the modules run"); diff --git a/test/daemon.py b/test/daemon.py index 7a600048..2c86c04f 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -36,7 +36,8 @@ private HOME and runtime directory: the daemon killed: its sessions register again with the next; and one stopped: an Adopt waits for its answer to the hello python3 -B test/daemon.py --far <pardes> - the far clients and their blob cache alone, and a file by its hash + the far clients and their blob cache alone, one under `yes` across + a slow link, and a file by its hash python3 -B test/daemon.py --games <pardes> <lib> [seconds] the games in the clients that show them, from zig build addon-test's <prefix>/lib (libsnake, liblife, libliar) @@ -2010,6 +2011,81 @@ def far(binary): shutil.rmtree(root, ignore_errors=True) +def far_flood(binary): + """A far client (PARDES_REPLICA_FAR) across a slow link (delay_relay.py: + 200 ms each way, 20 KB/s) while the session's shell runs `yes`: once + `yes` ends it agrees with the session, and its keys after go in. It + pulls its terminal's screen (screen state), so the flood does not + queue for it: it keeps up without joining again (two runs, 2026-11-20), + and replica.behind_max_ms is not reached this way.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='fl-', dir=os.environ.get('TMPDIR') or 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_CACHE_HOME=str(root / 'cache'), TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', + PARDES_NOTIME='1') + (root / 'config' / 'pardes').mkdir(parents=True) + (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n') + notes = root / '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=files', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + started.append(sess.pid) + sock = root / 'pardes-replica.sock' + wait_for('the replica socket', sock.exists) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-files.sock').exists) + nine = Client(root / 'pardes-9p-files.sock') + pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text') + nine.write(f'/pane/{pane}/exec', b'Term\n') + shell = wait_for('a shell pane', lambda: next((int(row.split()[0]) for row in nine.read('/index').splitlines() + if row.split()[1] == b'term'), None)) + wait_for('the shell\'s prompt', lambda: b'$' in nine.read(f'/pane/{shell}/body') or b'#' in nine.read(f'/pane/{shell}/body')) + relay = subprocess.Popen([sys.executable, '-B', str(Path(__file__).parent / 'delay_relay.py'), + str(root / 'relay.sock'), str(sock), '--delay', '200', '--rate', '0.02'], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started.append(relay.pid) + wait_for('the relay', (root / 'relay.sock').exists) + check = root / 'f.check' + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, f'--attach={root / "relay.sock"}:files'], + dict(env, PARDES_REPLICA_FAR='1', PARDES_REPLICA_CHECK=str(check))) + started.append(c.pid) + wait_for('the far client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=60) + nine.write(f'/pane/{shell}/pty/data', b'timeout 20 yes; echo yes-done\r') + wait_for('yes ended', lambda: b'yes-done' in nine.read(f'/pane/{shell}/body').replace(b'\r', b''), timeout=60) + seen = len(checks(check)) + wait_for('the far client agrees once yes ended', lambda: agreed(check, seen), timeout=120) + os.write(t.master, b'echo from-far\r') + wait_for('the far client\'s keys in the shell', lambda: b'from-far' in nine.read(f'/pane/{shell}/body'), timeout=30) + seen = len(checks(check)) + wait_for('the far client agrees after its keys', lambda: agreed(check, seen), timeout=60) + # Its keys go to the shell: its terminal hangs up instead. + c.send_signal(signal.SIGHUP) + c.wait(timeout=10) + print(f'daemon: a far client across 20 KB/s and 200 ms each way under `yes` agreed once it ended ' + f'({len(checks(check))} checks) and its keys went in') + relay.kill() + relay.wait() + exit_session(nine, pane) + sess.wait(timeout=60) + nine.socket.close() + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=10) + 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 by_hash(binary): """A file over the wire's 16 MiB bound opened while clients are attached (its read was one unit, dropped: the client joined again, a @@ -3347,10 +3423,20 @@ def gui_upgrades(old, new): assert client.read(f'/pane/{text}/body') == b'one\ntwo\n' assert alive(shell_pid) and ppid(shell_pid) == proc.pid and alive(sleeper) wait_for('the window drawn again', lambda: frames[0].stat().st_mtime > mark) - # The second, a client of the old build: let go and told to upgrade too. - second.p.wait(timeout=30) - said = second.err.read_bytes() - assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] + if knows_exec(old): + # The second, a client of a build that execs: the same process, + # on the build at its start path (upgrade_clients checks its + # view; here that it is carried and not let go). + wait_for('the second window on the new build', lambda: exe_of(second.pid) == (str(binary), True), timeout=30) + assert second.p.poll() is None + second.p.terminate() + second.p.wait(timeout=30) + else: + # The second, a client of a build before the exec: let go and + # told to upgrade too. + second.p.wait(timeout=30) + said = second.err.read_bytes() + assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-400:] said = Replica(root / 'pardes-replica.sock').hello('win', semantics(new)) assert said == ('welcome', proc.pid, 'win'), said os.kill(sleeper, signal.SIGTERM) @@ -3411,6 +3497,7 @@ if __name__ == '__main__': games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10) elif sys.argv[1:2] == ['--far']: far(sys.argv[2]) + far_flood(sys.argv[2]) by_hash(sys.argv[2]) far_find(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: diff --git a/test/replicas.zig b/test/replicas.zig index d78e3e02..e5e719b3 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -13,8 +13,8 @@ //! are refused until one is let go. //! //! Terminals cross as screen state (core/term/screen_state.zig): the session's -//! shell pane runs a full-screen program and then a `yes` flood (`--flood` -//! MB of it) while the clients type, its output stepped by the authority +//! shell pane runs a full-screen program and then a flood (`--flood` MB of +//! `yes`, then as much of a `cat` of source text) while the clients type, its output stepped by the authority //! and sent to each replica as deltas, once a frame and before any input //! the authority steps, each replica acknowledging them over its link and //! asking for the rows it scrolls back into and does not hold. @@ -57,6 +57,9 @@ var trace = false; /// the pty's bytes its units carry into an emulator of its own, joined from /// a dump with every emulator whole (core/replica.zig `Peers.bytes`). var bytes_kind = false; +/// `--witness`: the witness judged at every run's end, not only after a +/// divergence (`Witness`). +var witness_always = false; /// The PDF the soak opens (`--pdf`), absolute. var pdf_path: ?[]const u8 = null; const frame_us = 16_667; @@ -178,6 +181,10 @@ const Kind = enum { /// session's down it. up, blob, + /// The session's words in a client's stream (a cut's: `Peer.send`). + word, + /// Room in the far link again: its Peer's writer goes on (`Soak.write`). + drain, }; const Msg = struct { @@ -201,6 +208,8 @@ const Msg = struct { const Link = struct { last: u64 = 0, + /// When what was sent down it before has crossed (`Net.cross`). + free: u64 = 0, /// When a message sent at `now` arrives: half the RTT, jitter on top, /// and never before the one sent ahead of it (a stream keeps order). fn arrive(l: *Link, random: std.Random, now: u64, one_way: u64, jitter: u64) u64 { @@ -272,6 +281,26 @@ const Totals = struct { detach_words: u64 = 0, /// Panes of each plain kind the session opened (image, life). kind_panes: [3]u64 = @splat(0), + /// The far client (`throttle_*`): its joins from a dump, the time between + /// two from the flood's start on, and from the flood's end to the first + /// frame of its final screen (us); the most the session's queue for it + /// held (bytes); the clients the session cut off. + far_joins: u64 = 0, + far_gaps: std.ArrayListUnmanaged(u64) = .empty, + far_final: std.ArrayListUnmanaged(u64) = .empty, + queue_max: u64 = 0, + cut: u64 = 0, + /// How far behind the session each fell at most (Link.behind, ns), and + /// how often it let its link go for it: the far client, and the others. + far_behind: u64 = 0, + far_lags: u64 = 0, + near_behind: u64 = 0, + near_lags: u64 = 0, + /// What a join costs the replicas already there, ns of this process's + /// clock: the session's join step (its reloads and its dump), and each + /// client's unit that reloaded its terminals. + join_session_ns: std.ArrayListUnmanaged(u64) = .empty, + join_client_ns: std.ArrayListUnmanaged(u64) = .empty, fn add(t: *Totals, s: *const replica.Stats) !void { t.inputs += s.inputs; @@ -307,7 +336,7 @@ const Totals = struct { /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its /// wheel; a yank to the system clipboard and a paste from it; now and /// then a client's Detach. -fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script) pardes.Event { +fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; if (script.at < script.n) { @@ -351,8 +380,9 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const 10 => "Tab 8", 11 => "Life", // Its link ended by the session (the session's own view's, - // its terminal's: none here). - 12 => if (random.uintLessThan(u8, 4) == 0) "Detach" else "Undo", + // its terminal's: none here). Not the far client's: the scene + // waits for its screen after the flood. + 12 => if (random.uintLessThan(u8, 4) == 0 and !far) "Detach" else "Undo", // The system clipboard, the client's own frontend's (client.zig // `asks`): a yank of the selection to it, a paste from it. 13 => "ClipYank", @@ -509,6 +539,17 @@ const Client = struct { distrusted: pardes.Addon.Distrusted = .{}, /// What stopped its inputs as last judged (`judgeStops`). stops: @FieldType(replica.Stats, "stops") = @splat(.{}), + /// Its Peer's writer's (`Soak.write`): the batch swapped out of the + /// session's queue for it (the Peers' allocator's), how much of it went + /// down the link, whether a cut's words end it, a wake asked for room; + /// how much of the queue carries the soak's clock (`Soak.stamp`). + sending: std.ArrayListUnmanaged(u8) = .empty, + at: usize = 0, + last: bool = false, + draining: bool = false, + marked: usize = 0, + /// The session's unit its last join's dump came after. + join_seq: u32 = 0, /// Where it is (`clients[c]`), the net its wakes go through, and the /// soak's time now. c: usize = 0, @@ -614,6 +655,17 @@ const Net = struct { jitter: u64, up: [8]Link = @splat(.{}), down: [8]Link = @splat(.{}), + /// The far client, whose link is `throttle_*`'s. + throttled: ?usize = null, + + /// When `bytes` sent at `now` down or up client `c`'s link `l` arrive: + /// the far one's cross at its rate as the far stream's zstd at `level` + /// makes them, after what was sent before them, then its delay. + fn cross(net: *Net, l: *Link, c: usize, now: u64, bytes: []const u8, level: c_int) u64 { + if (net.throttled != @as(?usize, c)) return l.arrive(net.random, now, net.one_way, net.jitter); + l.free = @max(now, l.free) + zstdLen(bytes, level) * std.time.us_per_s / throttle_rate; + return l.arrive(net.random, l.free, throttle_one_way, throttle_one_way / 20); + } fn send(net: *Net, m: Msg) !void { var mm = m; @@ -624,10 +676,32 @@ const Net = struct { /// Down client `c`'s link (the session's stream to it), `bytes` its. fn toClient(net: *Net, c: usize, now: u64, kind: Kind, gen: u32, bytes: []u8) !void { - try net.send(.{ .at = net.down[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); + try net.send(.{ .at = net.cross(&net.down[c], c, now, bytes, if (kind == .dump) 6 else 3), .n = 0, .kind = kind, .who = @intCast(c + 1), .bytes = bytes, .gen = gen }); } }; +/// P32's far case: a link of 1 Mbit/s and 200 ms each way, what it carries +/// counted as the far stream's zstd makes it (core/replica.zig `zstd`), the +/// third client's (it joins before the flood); at most `throttle_window` of it ahead of +/// what has crossed (its sockets' and the route's buffers), the rest in the +/// session's queue for it, as a writer blocked on its socket leaves it. +const throttle_rate: u64 = 125_000; +const throttle_one_way: u64 = 200_000; +const throttle_window: u64 = 64 << 10; + +extern fn ZSTD_compressBound(n: usize) usize; +extern fn ZSTD_compress(dst: [*]u8, cap: usize, src: [*]const u8, n: usize, level: c_int) usize; +extern fn ZSTD_isError(code: usize) c_uint; + +/// `bytes` through zstd at `level`, alone: the far stream's (3, and 6 for a +/// join's), which a message shares with those before it. +fn zstdLen(bytes: []const u8, level: c_int) u64 { + const room = gpa.alloc(u8, ZSTD_compressBound(bytes.len)) catch return bytes.len; + defer gpa.free(room); + const n = ZSTD_compress(room.ptr, room.len, bytes.ptr, bytes.len, level); + return if (ZSTD_isError(n) != 0) bytes.len else n; +} + /// What client `c` wrote to its socket since (its inputs and their stamps, /// its terminal messages, a check asked, its bye), read off the session's /// end, a frame a message up its link: the session's Peer takes each as it @@ -642,7 +716,7 @@ fn drain(cl: *Client, c: usize, net: *Net, now: u64) !void { } var at: usize = 0; while (try pardes.wire.framed(cl.got.items[at..])) |f| : (at += f.total) { - try net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); + try net.send(.{ .at = net.cross(&net.up[c], c, now, cl.got.items[at..][0..f.total], 3), .n = 0, .kind = .up, .who = @intCast(c + 1), .bytes = try gpa.dupe(u8, cl.got.items[at..][0..f.total]), .gen = cl.live }); } std.mem.copyForwards(u8, cl.got.items[0 .. cl.got.items.len - at], cl.got.items[at..]); cl.got.shrinkRetainingCapacity(cl.got.items.len - at); @@ -699,19 +773,23 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, const r = cl.r.?; const link = &cl.loop.link; // Its link ended by the session (a Detach), it says nothing more. - if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null }); + if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 }); try drain(cl, c, net, now); cl.live = 0; + if (link.lagged != 0) { + if (net.throttled == @as(?usize, c)) totals.far_lags += 1 else totals.near_lags += 1; + } if (r.diverged) |why| { if (link.put_off) totals.rejoined += 1 else { totals.divergences += 1; + Witness.failed(c, why); std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ run_.seed, run_.rtt_ms, c + 1, why }); } } if (link.rejoins()) { cl.back = r.view; cl.dialling = true; - return net.send(.{ .at = net.up[c].arrive(net.random, now, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); + return net.send(.{ .at = net.cross(&net.up[c], c, now, &.{}, 3), .n = 0, .kind = .dial, .who = @intCast(c + 1), .bytes = &.{} }); } try totals.add(&r.stats); r.deinit(); @@ -725,6 +803,289 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run, } } +/// The witness (a failure's report): the session's stream as its clients +/// were sent it (units and blobs, in its order, each kept once as the +/// first client's writer forwards it: no copy a client, no step: the +/// clients' pace is the run's) and every join's dump with where in that +/// stream its client began. At the run's end, only when a client diverged, +/// a replica that speculates nothing replays it from the first dump on, +/// every unit's digest compared: does the session's own tape bring a fresh +/// core to the session's digests? Where it does not, the session's step +/// read what its tape does not carry: the unit's records said, and the +/// fields named against the next dump (or the session at the end). +/// A loop inside one call that does not end (the soak's clock stands +/// still: `Soak.watch` never runs): a thread that sees no message taken for +/// `stuck_s` of the machine's clock says the last ones, has gdb print every +/// thread's stack (the soak lets any process of its own trace it: `main`'s +/// PR_SET_PTRACER), and ends the run. +const Watchdog = struct { + extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + const stuck_s = 240; + var taken: std.atomic.Value(u64) = .init(0); + var last: [8]struct { kind: Kind = .wake, who: u16 = 0, at: u64 = 0 } = @splat(.{}); + + fn took(m: Msg) void { + const n = taken.fetchAdd(1, .monotonic); + last[n % last.len] = .{ .kind = m.kind, .who = m.who, .at = m.at }; + } + + fn said() void { + const n = taken.load(.monotonic); + std.debug.print(" the last messages taken (of {d}):", .{n}); + for (0..@min(n, last.len)) |k| { + const e = last[(n - 1 - k) % last.len]; + std.debug.print(" {t} of {d} at {d} us;", .{ e.kind, e.who, e.at }); + } + std.debug.print("\n", .{}); + } + + fn run() void { + var was = taken.load(.monotonic); + var still: u32 = 0; + while (true) { + var ts: libc.timespec = .{ .sec = 10, .nsec = 0 }; + _ = libc.nanosleep(&ts, null); + const now = taken.load(.monotonic); + if (now != was) { + was = now; + still = 0; + continue; + } + still += 10; + if (still < stuck_s) continue; + std.debug.print("watchdog: no message taken for {d} s of the machine's clock: a loop inside one call\n", .{still}); + said(); + var pid_buf: [16]u8 = undefined; + const pid = std.fmt.bufPrintSentinel(&pid_buf, "{d}", .{libc.getpid()}, 0) catch unreachable; + const argv = [_:null]?[*:0]const u8{ "gdb", "-batch", "-p", pid, "-ex", "thread apply all bt 30", null }; + const child = libc.fork(); + if (child == 0) { + _ = libc.dup2(2, 1); + _ = execvp("gdb", &argv); + libc._exit(127); + } + if (child > 0) { + var status: c_int = 0; + _ = libc.waitpid(child, &status, 0); + } + libc._exit(3); + } + } +}; + +const Witness = struct { + const Sent = struct { blob: bool, bytes: []u8 }; + const Dump = struct { c: usize, id: u16, view: u8, cols: u16, rows: u16, join_seq: u32, bytes: []u8, start: ?usize = null }; + const Failure = struct { c: usize, why: []u8, at: usize }; + var sent: std.ArrayListUnmanaged(Sent) = .empty; + var dumps: std.ArrayListUnmanaged(Dump) = .empty; + var failures: std.ArrayListUnmanaged(Failure) = .empty; + /// Each client's place in `sent` (null: none yet since its join), and + /// its join's dump. + var at: [8]?usize = @splat(null); + var dump_of: [8]usize = @splat(0); + var broken: ?[]const u8 = null; + + fn joined(c: usize, cl: *const Client, bytes: []u8, join_seq: u32) void { + dump_of[c] = dumps.items.len; + at[c] = null; + dumps.append(gpa, .{ .c = c, .id = cl.id, .view = cl.view, .cols = cl.cols, .rows = cl.rows, .join_seq = join_seq, .bytes = bytes }) catch @panic("witness: out of memory"); + } + + /// A unit's origin and number. + fn head(bytes: []const u8) u48 { + return std.mem.readInt(u48, bytes[0..6], .little); + } + + fn same(s: Sent, blob: bool, bytes: []const u8) bool { + if (s.blob != blob or s.bytes.len != bytes.len) return false; + // A unit's clock words are each client's (`Soak.stamp`). + if (!blob) return head(s.bytes) == head(bytes) and std.mem.eql(u8, s.bytes[unit_head_len..], bytes[unit_head_len..]); + return std.mem.eql(u8, s.bytes, bytes); + } + const unit_head_len = 22; + + /// Client `c`'s writer forwarded `bytes` (a unit or a blob piece). + fn forwarded(c: usize, blob: bool, bytes: []const u8) void { + // Its join is not kept (the run's end judged it). + if (dump_of[c] >= dumps.items.len) return; + const i = at[c] orelse place: { + // Its first since its join: kept already (another's writer + // forwarded it first), else the next. + var i = sent.items.len; + while (i > 0 and sent.items.len - i < 1 << 14) { + i -= 1; + if (same(sent.items[i], blob, bytes)) break :place i; + } + break :place sent.items.len; + }; + if (at[c] == null) dumps.items[dump_of[c]].start = i; + if (i == sent.items.len) { + sent.append(gpa, .{ .blob = blob, .bytes = gpa.dupe(u8, bytes) catch @panic("witness: out of memory") }) catch @panic("witness: out of memory"); + } else if (broken == null and !same(sent.items[i], blob, bytes)) broken = "a client was sent another stream than the one kept"; + at[c] = i + 1; + } + + fn failed(c: usize, why: []const u8) void { + failures.append(gpa, .{ .c = c, .why = gpa.dupe(u8, why) catch return, .at = at[c] orelse 0 }) catch {}; + } + + fn reset() void { + for (sent.items) |m| gpa.free(m.bytes); + sent.clearRetainingCapacity(); + for (dumps.items) |d| gpa.free(d.bytes); + dumps.clearRetainingCapacity(); + for (failures.items) |f| gpa.free(f.why); + failures.clearRetainingCapacity(); + at = @splat(null); + broken = null; + } + + /// A replica of dump `d`, as the soak's clients make theirs. + /// The kinds the witness's replica distrusts: it keeps a pointer to + /// them for its life (a local here was a stack slot gone by its first + /// kind's call: an index of 0xAA..., the screen-state soak's panic). + var distrusted: pardes.Addon.Distrusted = .{}; + + fn load(d: *const Dump) !*replica.Replica { + distrusted = .{}; + // No client's id: every unit is another's. + const rp = try replica.Replica.initDump(gpa, std.math.maxInt(u16), d.view, d.bytes, .{ .cols = d.cols, .rows = d.rows, .distrusted = &distrusted }); + rp.guess = false; + if (bytes_kind) { + rp.t.screen_state = false; + rp.core().echo = null; + } + rp.t.local_files = true; + return rp; + } + + /// Each field of the core, its stream, its views and its panes whose + /// digest differs between `a` and `b`, named (tape.zig's digestParts', + /// by name), and each terminal's screen. + fn fieldsDiffer(a: *const pardes.Pardes, b: *const pardes.Pardes, w: *std.Io.Writer) void { + const walk = pardes.walk; + const Each = struct { + fn of(comptime T: type, x: *const T, y: *const T, prefix: []const u8, out: *std.Io.Writer) void { + const names = comptime walk.fieldNames(T); + var dx: [names.len]u64 = undefined; + var dy: [names.len]u64 = undefined; + _ = walk.fieldDigests(T, x, &dx); + _ = walk.fieldDigests(T, y, &dy); + for (names, dx, dy) |name, u, v| if (u != v) out.print("{s}{s} ", .{ prefix, name }) catch {}; + } + }; + Each.of(pardes.Pardes, a, b, "", w); + Each.of(pardes.Stream, &a.stream, &b.stream, "stream.", w); + for (&a.views, &b.views, 0..) |*x, *y, k| if (x.* != null and y.* != null) { + var buf: [24]u8 = undefined; + Each.of(pardes.Pardes.View, &x.*.?, &y.*.?, std.fmt.bufPrint(&buf, "views[{d}].", .{k}) catch "", w); + } else if ((x.* == null) != (y.* == null)) w.print("views[{d}] (one side only) ", .{k}) catch {}; + for (a.panes, b.panes, 0..) |x, y, id| { + if (x == null or y == null) { + if ((x == null) != (y == null)) w.print("pane {d} (one side only) ", .{id}) catch {}; + continue; + } + var buf: [24]u8 = undefined; + Each.of(pardes.Pane, x.?, y.?, std.fmt.bufPrint(&buf, "pane {d}.", .{id}) catch "", w); + if (x.?.terminal) |sx| if (y.?.terminal) |sy| { + const ex = &pardes.Term.emulatorOf(sx).vt; + const ey = &pardes.Term.emulatorOf(sy).vt; + w.print("[pane {d}'s screen {s}] ", .{ id, if (screenHash(ex) == screenHash(ey)) "equal" else "DIFFERS" }) catch {}; + }; + } + w.writeByte('\n') catch {}; + } + + /// At the run's end (the session's core still whole), when a client + /// diverged: the stream replayed from each dump on, as said above. + fn judge(s: *Soak) void { + if (failures.items.len == 0 and !witness_always) return; + const on = pardes.tape.on; + const trees = pardes.syntax.held_trees; + pardes.tape.on = null; + pardes.syntax.held_trees = null; + defer { + pardes.tape.on = on; + pardes.syntax.held_trees = trees; + } + var out_buf: [1 << 14]u8 = undefined; + // Streaming: a positional writer starts at offset 0, and over a log + // file each judgement wrote over the run's first lines. + var stderr = std.Io.File.stderr().writerStreaming(s.l.peers.io, &out_buf); + const w = &stderr.interface; + defer w.flush() catch {}; + const tag = .{ s.r.seed, s.r.rtt_ms }; + w.print("seed {d} rtt {d} ms: witness: {d} messages kept, {d} dumps{s}{s}\n", tag ++ .{ sent.items.len, dumps.items.len, if (broken != null) ": " else "", broken orelse "" }) catch {}; + for (failures.items) |f| { + const u: ?replica.Unit = if (f.at > 0 and !sent.items[f.at - 1].blob) replica.parseUnit(sent.items[f.at - 1].bytes) else null; + w.print("seed {d} rtt {d} ms: witness: client {d} failed at message {d} (unit {d}/{d}): {s}\n", tag ++ .{ f.c + 1, f.at -| 1, if (u) |x| x.origin else 0, if (u) |x| x.seq else 0, f.why }) catch {}; + } + var d: usize = 0; + while (d < dumps.items.len) { + const from = &dumps.items[d]; + const start = from.start orelse { + d += 1; + continue; + }; + const rp = load(from) catch |err| { + w.print("seed {d} rtt {d} ms: witness: dump {d} does not load: {t}\n", tag ++ .{ d, err }) catch {}; + d += 1; + continue; + }; + defer rp.deinit(); + var last0: u32 = from.join_seq; + var parted: ?usize = null; + var i = start; + const end = end: while (i < sent.items.len) : (i += 1) { + const m = sent.items[i]; + if (m.blob) { + rp.blobPiece(m.bytes); + continue; + } + const u = replica.parseUnit(m.bytes) orelse continue; + // A stretch no client was sent (none was joined): the stream + // has a gap here. + if (u.origin == 0 and u.seq != last0 + 1) break :end i; + if (u.origin == 0) last0 = u.seq; + rp.since_check = if (parted == null) 1 << 20 else 0; + rp.confirm(m.bytes); + if (rp.diverged) |why| { + if (parted == null) { + parted = i; + w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, after unit 0/{d}, message {d}) PARTS at message {d}, unit {d}/{d} ({d} bytes): {s}\n its records:\n", tag ++ .{ d, from.c + 1, from.join_seq, start, i, u.origin, u.seq, u.tape.len, why }) catch {}; + pardes.tape.describe(u.tape, w); + } + // On over it, to the next dump, unchecked. + gpa.free(rp.diverged.?); + rp.diverged = null; + rp.t.diverged = null; + } + // The next dump begins here: what differs then, by field. + if (parted != null) for (dumps.items[d + 1 ..], d + 1..) |*next, k| if (next.start == i + 1) { + const there = load(next) catch break; + defer there.deinit(); + w.print(" against dump {d} (after unit 0/{d}): ", .{ k, next.join_seq }) catch {}; + fieldsDiffer(rp.core(), there.core(), w); + break :end i + 1; + }; + } else i; + if (parted == null) { + w.print("seed {d} rtt {d} ms: witness from dump {d} (client {d}'s, message {d}): messages to {d} replayed to the session's every digest{s}", tag ++ .{ d, from.c + 1, start, end, if (end == sent.items.len) "; at the end against the session: " else " (a gap: no client was joined)\n" }) catch {}; + if (end == sent.items.len) fieldsDiffer(rp.core(), s.l.core, w); + } else if (end == sent.items.len) { + w.print(" at the end against the session: ", .{}) catch {}; + fieldsDiffer(rp.core(), s.l.core, w); + } + // Next: the first dump that begins at or after where this one ended. + const next = for (dumps.items[d + 1 ..], d + 1..) |x, k| { + if (x.start) |st| if (st >= end) break k; + } else dumps.items.len; + d = next; + } + } +}; + /// When the session's shell's program prints (`.output`): a full-screen /// program, a shell's session, then the flood. const tui_at: u64 = 400_000; @@ -756,7 +1117,9 @@ const Soak = struct { /// What the shell's program prints (`.output`). tui: []const u8, shell_session: []const u8, - yes: []const u8, + /// The flood: `yes`, then a `cat` (its first `yes_len` bytes `yes`). + flood: []const u8, + yes_len: usize, l: *SessionLoop = undefined, /// What failed inside the loop (its wait returns nothing): the run's. err: ?anyerror = null, @@ -805,9 +1168,17 @@ const Soak = struct { /// The temporary file and the shared memory object an image was shown /// by (`images`): gone once the session read them. media: *const Media = undefined, - /// A Peer's queue, swapped out as its writer swaps it (the Peers' - /// allocator's). - sending: std.ArrayListUnmanaged(u8) = .empty, + /// The session's unit with the flood's last bytes; the far client's + /// last join, and whether it has shown the final screen; a join's step + /// at worst. + flood_seq: u32 = 0, + far_joined: u64 = 0, + far_final: bool = false, + join_worst: u64 = 0, + /// The watchdog's (`watch`): what the steps and checks made came to, and + /// the soak's time it last moved. + moved: u64 = 0, + moved_at: u64 = 0, fn of(ctx: ?*anyopaque) *Soak { return @ptrCast(@alignCast(ctx.?)); @@ -914,13 +1285,13 @@ const Soak = struct { cl.loop.link.check = null; cl.loop.link.deinit(gpa); } + cl.sending.deinit(s.l.peers.gpa); } while (s.net.q.pop()) |m| if (m.bytes.len > 0) gpa.free(m.bytes); if (s.held) |m| if (m.bytes.len > 0) gpa.free(m.bytes); for (s.echo.items) |e| gpa.free(e.bytes); s.echo.deinit(gpa); s.versions.deinit(gpa); - s.sending.deinit(s.l.peers.gpa); } /// The tty's own boot (a raw shell, a text pane under it), then three @@ -1034,11 +1405,21 @@ const Soak = struct { cl.peer = peer; cl.shut = false; cl.read_done = false; + cl.join_seq = ps.seq; + cl.sending.clearRetainingCapacity(); + cl.at = 0; + cl.last = false; + cl.marked = 0; + // What the join cost the session's step (Peers.join's measure). + s.join_worst = @max(s.join_worst, ps.join_ns); + try s.totals.join_session_ns.append(gpa, ps.join_ns); + ps.join_ns = 0; cl.gen += 1; cl.id = welcome.client; cl.view = welcome.view.index(); cl.digest = welcome.digest; s.totals.joins += 1; + if (bytes_kind) Witness.joined(c, cl, try gpa.dupe(u8, whole.items), cl.join_seq); // never given the screen deltas, it checks no screen-state run try net.toClient(c, now, .dump, cl.gen, try whole.toOwnedSlice(gpa)); }; // A Detach typed in a client's view, or one cut off for its lag: its @@ -1048,49 +1429,19 @@ const Soak = struct { cl.shut = true; }; s.detach_view = null; - const flooding = now >= flood_at and s.flood_end == 0; + // The unit with the flood's last bytes: what the far client's final + // screen shows. + if (s.flood_end != 0 and s.flood_seq == 0) s.flood_seq = ps.seq; for (s.clients, 0..) |*cl, c| if (cl.peer) |peer| { - if (peer.cut) cl.shut = true; - const io = ps.io; - peer.lock.lockUncancelable(io); - std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &s.sending); - peer.lock.unlock(io); - defer s.sending.clearRetainingCapacity(); if (cl.shut) { - if (!cl.read_done) { - cl.read_done = true; - ps.post(.{ .gone = peer }); - try net.toClient(c, now, .gone, cl.gen, &.{}); - } + // What was queued for it is let go with its link. + peer.out.clearRetainingCapacity(); + try s.shut(cl, c); continue; } - var at: usize = 0; - while (try pardes.wire.framed(s.sending.items[at..])) |f| : (at += f.total) { - const tag = std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame; - switch (tag) { - .unit => { - s.totals.unit_bytes += f.payload.len; - if (flooding) s.totals.flood_unit_bytes += f.payload.len; - try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); - }, - .screen => { - if (f.payload[5] == 1) { - s.totals.deltas += 1; - s.totals.delta_bytes += f.payload.len; - if (flooding) s.totals.flood_delta_bytes += f.payload.len; - } else s.totals.filled_bytes += f.payload.len; - try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); - }, - .check => { - const d = try gpa.alloc(u8, 8); - std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); - try net.toClient(c, now, .checked, cl.gen, d); - }, - .blob => try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)), - else => return error.UnexpectedFrame, - } - } - if (at != s.sending.items.len) return error.TornFrame; + s.stamp(cl, peer); + if (net.throttled == @as(?usize, c)) s.totals.queue_max = @max(s.totals.queue_max, peer.out.items.len); + try s.write(cl, c); }; // The kinds' panes it has opened, each counted once. for (core.panes) |slot| if (slot) |pane| if (pane.addon) |k| if (pane.serial > s.kinds_seen) { @@ -1105,6 +1456,102 @@ const Soak = struct { } } + /// The units the session queued for client `cl` since, their heads + /// carrying the soak's clock, the session's here (its host's `now`): + /// what the client's lag is measured by. Its replica guesses no clock + /// from them (`joined`: in process, both read one). + fn stamp(s: *Soak, cl: *Client, peer: *replica.Peer) void { + const out = peer.out.items; + // A cut (Peer.send, past its limit) empties the queue for its words. + var at = @min(cl.marked, out.len); + while (pardes.wire.framed(out[at..]) catch null) |f| : (at += f.total) { + if (f.tag != @backingInt(pardes.wire.ServerTag.unit)) continue; + const head = at + f.total - f.payload.len; + std.mem.writeInt(i64, out[head + 14 ..][0..8], @intCast(s.now * std.time.ns_per_us), .little); + } + cl.marked = at; + } + + /// Client `c`'s Peer's writer (Peer.writeLoop's): the session's queue + /// for it swapped out a batch at a time and handed down its link, a + /// frame a message. The far link takes no more than `throttle_window` + /// ahead of what has crossed: the rest waits in the queue, as it does + /// for a writer blocked on its socket, until room comes (`.drain`). A + /// cut's words end a batch, and its link after them. + fn write(s: *Soak, cl: *Client, c: usize) !void { + const peer = cl.peer orelse return; + const net = s.net; + const window_us = throttle_window * std.time.us_per_s / throttle_rate; + while (true) { + if (cl.at == cl.sending.items.len) { + cl.sending.clearRetainingCapacity(); + cl.at = 0; + if (cl.last) return s.shut(cl, c); + const io = s.l.peers.io; + peer.lock.lockUncancelable(io); + std.mem.swap(std.ArrayListUnmanaged(u8), &peer.out, &cl.sending); + cl.last = peer.cut; + peer.lock.unlock(io); + cl.marked = 0; + if (cl.sending.items.len == 0) return; + } + if (net.throttled == @as(?usize, c) and net.down[c].free > s.now + window_us) { + if (!cl.draining) try net.send(.{ .at = net.down[c].free - window_us, .n = 0, .kind = .drain, .who = @intCast(c + 1), .bytes = &.{} }); + cl.draining = true; + return; + } + const f = (try pardes.wire.framed(cl.sending.items[cl.at..])) orelse return error.TornFrame; + cl.at += f.total; + try s.forward(cl, c, f); + } + } + + /// One frame of client `c`'s stream, down its link. + fn forward(s: *Soak, cl: *Client, c: usize, f: pardes.wire.Framed) !void { + const net = s.net; + const now = s.now; + const flooding = now >= flood_at and s.flood_end == 0; + switch (std.enums.fromInt(pardes.wire.ServerTag, f.tag) orelse return error.BadFrame) { + .unit => { + Witness.forwarded(c, false, f.payload); + s.totals.unit_bytes += f.payload.len; + if (flooding) s.totals.flood_unit_bytes += f.payload.len; + try net.toClient(c, now, .to_replica, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .screen => { + if (f.payload[5] == 1) { + s.totals.deltas += 1; + s.totals.delta_bytes += f.payload.len; + if (flooding) s.totals.flood_delta_bytes += f.payload.len; + } else s.totals.filled_bytes += f.payload.len; + try net.toClient(c, now, .screen_down, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .check => { + const d = try gpa.alloc(u8, 8); + std.mem.writeInt(u64, d[0..8], (try pardes.wire.decodeServer(f.tag, f.payload)).check, .little); + try net.toClient(c, now, .checked, cl.gen, d); + }, + .blob => { + Witness.forwarded(c, true, f.payload); + try net.toClient(c, now, .blob, cl.gen, try gpa.dupe(u8, f.payload)); + }, + .refused => try net.toClient(c, now, .word, cl.gen, try gpa.dupe(u8, (try pardes.wire.decodeServer(f.tag, f.payload)).refused)), + else => return error.UnexpectedFrame, + } + } + + /// Client `c`'s link ended at the session's side (a Detach typed in its + /// view, or the words of a cut sent): it hears its end and nothing after, + /// and its reader's end is said (the next boundary lets it go). + fn shut(s: *Soak, cl: *Client, c: usize) !void { + cl.shut = true; + cl.last = false; + if (cl.read_done) return; + cl.read_done = true; + s.l.peers.post(.{ .gone = cl.peer.? }); + try s.net.toClient(c, s.now, .gone, cl.gen, &.{}); + } + /// Each terminal at its version as the session's screen shows it now /// (after a flush: `Peers.flushed`). fn flushed(ctx: *anyopaque, core: *pardes.Pardes, screens: *replica.Screens) void { @@ -1144,6 +1591,7 @@ const Soak = struct { // What its boundary took is old news. _ = s.l.peers.urgent.swap(false, .acq_rel); while (true) { + try s.watch(); const next = net.q.peek() orelse return !took_output; // Every typist done, the flood over and its frames' two seconds // past: what is in flight is delivered and the run ends. The @@ -1162,6 +1610,7 @@ const Soak = struct { const m = net.q.pop().?; var kept = false; defer if (!kept and m.bytes.len > 0) gpa.free(m.bytes); + Watchdog.took(m); s.now = m.at; Draws.now = m.at; // A client's message, but an echo's and an output's `who` (a pane, @@ -1172,7 +1621,7 @@ const Soak = struct { // tape is stepped in it between its steps (tape.enter's check), // and no rollback epoch's trees are held. const in_client = switch (m.kind) { - .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => true, + .refused, .dump, .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => true, .draw => Draws.jobs.items.len > 0 and Draws.jobs.items[0].draw != null and Draws.jobs.items[0].draw != @as(?*const pardes.Pardes, core), else => false, }; @@ -1211,15 +1660,17 @@ const Soak = struct { if (s.program.at == s.program.bytes.len) { s.program = .{ .bytes = switch (m.who) { 0 => s.tui, - 1 => s.yes, + 1 => s.flood, else => s.shell_session, } }; } const k = @min(s.program.bytes.len - s.program.at, if (m.who == 1) @as(usize, 4096) else 700); const chunk = s.program.bytes[s.program.at..][0..k]; s.program.at += k; + // `yes` a read every 450 us, the `cat` a read every 4 ms + // (1 MB/s: the far link falls behind, many seconds long). if (s.program.at < s.program.bytes.len) - try net.send(.{ .at = m.at + if (m.who == 1) @as(u64, 450) else 3_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) + try net.send(.{ .at = m.at + if (m.who != 1) @as(u64, 3_000) else if (s.program.at < s.yes_len) @as(u64, 450) else 4_000, .n = 0, .kind = .output, .who = m.who, .bytes = &.{} }) else if (m.who == 1) s.flood_end = m.at; core.update(.{ .output = .{ .pane = .at(s.shell), .bytes = chunk } }); took_output = true; @@ -1240,6 +1691,12 @@ const Soak = struct { return false; } }, + // Room in the far link: its Peer's writer goes on. + .drain => { + cl.draining = false; + try s.write(cl, c); + if (s.l.peers.urgent.swap(false, .acq_rel)) return false; + }, // A client's connection, handed over by the daemon (tui.zig // `.replica`): joined at the session's next step boundary, // on a socket pair of its own. @@ -1322,7 +1779,12 @@ const Soak = struct { cl.r = null; } cl.tries += 1; - if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.up[c].arrive(s.random, m.at + 500_000, net.one_way, net.jitter), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { + // The far client refused before its screen after the + // flood (a join again for its lag finds its view taken: + // a join with no room lets an away one go): said, so + // that "it left" says why. + if (net.throttled == @as(?usize, c) and !s.far_final and cl.tries == 1) std.debug.print("seed {d} rtt {d} ms: the far client refused (every view taken), {d} keys left, try {d}\n", .{ s.r.seed, s.r.rtt_ms, cl.left, cl.tries }); + if (cl.left > 0 and cl.tries < 40) try net.send(.{ .at = net.cross(&net.up[c], c, m.at + 500_000, &.{}, 3), .n = 0, .kind = .dial, .who = m.who, .bytes = &.{} }) else { // Given up on: its keys are never typed. cl.dialling = false; if (cl.left > 0) s.typing -= 1; @@ -1330,7 +1792,7 @@ const Soak = struct { } }, .dump => try s.joined(cl, c, m), - .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone => { + .input, .to_replica, .screen_down, .checked, .blob, .wake, .quit, .gone, .word => { if (m.kind == .input and cl.left == 0) continue; const rp = cl.r orelse if (m.kind == .input and cl.dialling) { try net.send(.{ .at = m.at + 50_000, .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }); @@ -1349,7 +1811,7 @@ const Soak = struct { switch (m.kind) { .input => { var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script, net.throttled == @as(?usize, c)); cl.loop.input(ev); cl.left -= 1; if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { @@ -1358,7 +1820,21 @@ const Soak = struct { if (c == 0) try net.send(.{ .at = m.at + 300_000, .n = 0, .kind = .quit, .who = m.who, .bytes = &.{} }); } }, - .to_replica => cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }), + .to_replica => { + if (net.throttled == @as(?usize, c) and !s.far_final and s.flood_seq != 0) if (replica.parseUnit(m.bytes)) |u| if (u.origin == 0 and u.seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + }; + // A join's reloads on a replica there before it: + // what its unit cost, on this process's clock. + const reloads = pardes.Term.reloads.n; + const t0 = monoNs(); + cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }); + if (pardes.Term.reloads.n != reloads) try s.totals.join_client_ns.append(gpa, monoNs() - t0); + const behind = if (net.throttled == @as(?usize, c)) &s.totals.far_behind else &s.totals.near_behind; + behind.* = @max(behind.*, cl.loop.link.behind); + }, + .word => cl.loop.take(.{ .refused = try std.heap.c_allocator.dupe(u8, m.bytes) }), .blob => cl.loop.take(.{ .blob = try std.heap.c_allocator.dupe(u8, m.bytes) }), .screen_down => { const pane = m.bytes[0]; @@ -1401,13 +1877,48 @@ const Soak = struct { } } + /// No step of the session's and no unit or check of a client's for + /// `stuck_us` of the soak's own clock: a loop that does not end. Every + /// side's state said, and the run failed. + fn watch(s: *Soak) !void { + var moved: u64 = s.l.peers.seq; + for (s.clients) |*cl| if (cl.r) |rp| { + moved +%= rp.stats.units +% rp.stats.checks +% rp.pending.items.len; + }; + if (moved != s.moved) { + s.moved = moved; + s.moved_at = s.now; + return; + } + if (s.now - s.moved_at < stuck_us) return; + std.debug.print("seed {d} rtt {d} ms: watchdog: nothing stepped or checked for {d} s of the soak's clock (since {d} us)\n", .{ s.r.seed, s.r.rtt_ms, stuck_us / std.time.us_per_s, s.moved_at }); + s.report(); + return error.Hung; + } + const stuck_us = 60 * std.time.us_per_s; + + /// Every side's state, for a run that hangs: the session's and each + /// client's, what each waits on and holds, and the last messages taken. + fn report(s: *Soak) void { + const ps = &s.l.peers; + const core = s.l.core; + std.debug.print(" session: unit 0/{d}, needs_frame {any}, next wake {?d} (now {d} ns), quit {any}; the net {d} in flight, the next {s}; typing {d}, own left {d}, frames left {d}, flood at {d} of {d} (ended {d}), held {any}\n", .{ ps.seq, core.needs_frame, core.nextWake(), s.now_ns, core.quit, s.net.q.count(), if (s.net.q.peek()) |n| @tagName(n.kind) else "none", s.typing, s.own_left, s.frames_left, s.program.at, s.program.bytes.len, s.flood_end, s.held != null }); + for (s.clients, 1..) |*cl, id| { + std.debug.print(" client {d} ({t}): live {d} gen {d} dialling {any} left {d} wake_at {d}", .{ id, cl.kind, cl.live, cl.gen, cl.dialling, cl.left, cl.wake_at }); + if (cl.peer) |p| std.debug.print(", its queue at the session {d} B, sending {d}/{d}, shut {any} draining {any}", .{ p.out.items.len, cl.at, cl.sending.items.len, cl.shut, cl.draining }); + if (cl.r) |rp| std.debug.print(", replica: units {d} checks {d} pending {d} applied {d} blocked {?d} since {d} copy {any} diverged {any}, link quit {any} asked {any} behind {d} ms", .{ rp.stats.units, rp.stats.checks, rp.pending.items.len, rp.applied, rp.blocked, rp.since.items.len, rp.copy.held, rp.diverged != null, cl.loop.link.quit, cl.loop.link.asked, cl.loop.link.behind / std.time.ns_per_ms }); + std.debug.print("\n", .{}); + } + Watchdog.said(); + } + /// An input of its own frontend's, in the view it shows (the first: /// tui.zig `Shell.apply` goes into `s.own`). fn own(s: *Soak, m: Msg) !void { const core = s.l.core; s.clock(); var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script, false); core.toView(.at(0)); core.update(ev); s.own_left -= 1; @@ -1428,6 +1939,18 @@ const Soak = struct { } const rp = try replica.Replica.initDump(gpa, cl.id, cl.view, m.bytes, .{ .cols = cl.cols, .rows = cl.rows, .distrusted = &cl.distrusted }); cl.r = rp; + // In process: its clock reads are the session's machine's, and the + // units' heads carry the soak's clock (`stamp`). + rp.guess = false; + if (s.net.throttled == @as(?usize, c)) { + s.totals.far_joins += 1; + if (m.at >= flood_at and s.far_joined != 0) try s.totals.far_gaps.append(gpa, m.at - s.far_joined); + s.far_joined = m.at; + if (!s.far_final and s.flood_seq != 0 and cl.join_seq >= s.flood_seq) { + s.far_final = true; + try s.totals.far_final.append(gpa, m.at - s.flood_end); + } + } // Its terminals its own emulators, fed what the units carry. if (bytes_kind) { rp.t.screen_state = false; @@ -1470,7 +1993,9 @@ const Soak = struct { totals.flood_us += s.flood_end -| flood_at; for (s.flood_deltas[0..s.clients.len]) |d| totals.flood_deltas += d; const want = pardes.tape.digestOf(core); - if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.l.peers.join_ns / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + totals.cut += s.l.peers.cut; + if (bytes_kind) std.debug.print("seed {d} rtt {d} ms: a join's step at worst {d} us (the session's reloads and its dump), the last dump {d} KB ({d} KB of state)\n", .{ s.r.seed, s.r.rtt_ms, s.join_worst / 1000, s.l.peers.dump_bytes >> 10, s.l.peers.state_bytes >> 10 }); + if (s.net.throttled) |c| if (!s.far_final) std.debug.print("seed {d} rtt {d} ms: the far client never showed the screen after the flood ({s})\n", .{ s.r.seed, s.r.rtt_ms, if (s.clients[c].r == null) "it left" else "it is joined" }); if (bytes_kind) for (kitty_oks, s.kitty_answers) |ok, n| if (n != 1) { totals.unequal += 1; std.debug.print("seed {d} rtt {d} ms: the program's kitty {f} was answered {d} times on the session's pty\n", .{ s.r.seed, s.r.rtt_ms, std.ascii.hexEscape(ok, .lower), n }); @@ -1502,6 +2027,7 @@ const Soak = struct { if (cl.live == 0) continue; if (rp.diverged) |why| { totals.divergences += 1; + Witness.failed(id - 1, why); std.debug.print("seed {d} rtt {d} ms: client {d} diverged: {s}\n", .{ s.r.seed, s.r.rtt_ms, id, why }); } else if (!rp.quiet() or rp.digest() != want) { totals.unequal += 1; @@ -1539,11 +2065,14 @@ const Soak = struct { } } } + Witness.judge(s); } }; fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms }); + Witness.reset(); + defer Witness.reset(); var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var paths: [3][256:0]u8 = undefined; @@ -1579,7 +2108,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { nlooks += 1; }; - var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20 }; + var net: Net = .{ .random = random, .one_way = r.rtt_ms * 1000 / 2, .jitter = r.rtt_ms * 1000 / 20, .throttled = if (r.clients >= 3) 2 else null }; defer net.q.deinit(gpa); pardes.Kind.drawer = .{ .ctx = null, .go = Draws.go }; Draws.net = &net; @@ -1597,7 +2126,7 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // What the shell's program prints: a full-screen program, a shell's // session (prompts, titles, directories, a clear now and then), then a - // flood of `yes`, read 4 KB at a time as a pty gives it. + // flood of `yes` and of a `cat`, read 4 KB at a time as a pty gives it. const tui = try screen_state.tuiStream(gpa); defer gpa.free(tui); const session_only = try screen_state.shellStream(gpa); @@ -1617,6 +2146,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { defer gpa.free(yes_only); const yes = try std.mem.concat(gpa, u8, &.{ yes_only, shown }); defer gpa.free(yes); + const flood = try catAfter(yes, yes.len); + defer gpa.free(flood); var soak: Soak = .{ .r = r, @@ -1628,7 +2159,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { .with_pdf = with_pdf, .tui = tui, .shell_session = shell_session, - .yes = yes, + .flood = flood, + .yes_len = yes.len, .own_left = r.steps, .typing = r.clients + 1, .media = &media, @@ -1717,6 +2249,26 @@ fn images(dir: []const u8, seed: u64, media: *Media) ![]u8 { return out.toOwnedSlice(gpa); } +/// `before`, then `n` bytes of what a `cat` of source text prints through a +/// pty: this file's lines, CR LF after each, again and again. +fn catAfter(before: []const u8, n: usize) ![]u8 { + var out: std.ArrayListUnmanaged(u8) = .empty; + errdefer out.deinit(gpa); + try out.appendSlice(gpa, before); + while (out.items.len < before.len + n) { + var lines = std.mem.splitScalar(u8, @embedFile("replicas.zig"), '\n'); + while (lines.next()) |line| try out.print(gpa, "{s}\r\n", .{line}); + } + out.shrinkRetainingCapacity(before.len + n); + return out.toOwnedSlice(gpa); +} + +fn monoNs() u64 { + var ts: libc.timespec = undefined; + _ = libc.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * std.time.ns_per_s + @as(u64, @intCast(ts.nsec)); +} + /// A typist: keys 50-200 ms apart, a pause now and then. fn typistGap(random: std.Random) u64 { return if (random.uintLessThan(u8, 12) == 0) random.intRangeAtMost(u64, 300_000, 1_500_000) else random.intRangeAtMost(u64, 50_000, 200_000); @@ -2562,7 +3114,7 @@ fn runEcho(seed: u64, rtt_ms: u64, on: bool, et: *EchoTotals) !void { .screen_up => { if (try screens.take(a.core, peer, m.bytes)) |answer| try push(&queue, &n, .{ .at = down[0].arrive(random, m.at, one_way, jitter), .n = 0, .kind = .screen_down, .who = 1, .bytes = answer }); }, - .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob => {}, + .output, .own, .dial, .dump, .refused, .check_up, .checked, .bye_up, .wake, .quit, .gone, .draw, .up, .blob, .word, .drain => {}, } } const s = rp.echo.stats; @@ -2661,6 +3213,14 @@ fn echoMain(seeds: u64, first: u64, rtts: []const u64) !bool { } +fn secs(us: u64) f64 { + return @as(f64, @floatFromInt(us)) / std.time.us_per_s; +} + +fn msOf(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; +} + fn pct(samples: []u64, p: usize) u64 { if (samples.len == 0) return 0; std.mem.sort(u64, samples, {}, std.sort.asc(u64)); @@ -2837,6 +3397,10 @@ fn floods(io: std.Io, w: *std.Io.Writer) !void { pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); + // A loop that does not end names itself (`Watchdog`): its gdb, a child, + // may trace this process. + _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PTRACER), std.math.maxInt(usize), 0, 0, 0); + if (std.Thread.spawn(.{}, Watchdog.run, .{})) |th| th.detach() else |_| {} var seeds: u64 = 4; var first: u64 = 0; var steps: usize = 120; @@ -2859,6 +3423,10 @@ pub fn main(init: std.process.Init) !void { bytes_kind = true; continue; } + if (std.mem.eql(u8, name, "--witness")) { + witness_always = true; + continue; + } if (i + 1 >= args.len) return error.MissingValue; i += 1; const value = args[i]; @@ -2914,7 +3482,7 @@ pub fn main(init: std.process.Init) !void { // files (runtime/session.zig opens them), never the user's. var runtime_buf: [300]u8 = undefined; if (setenv("XDG_RUNTIME_DIR", try std.fmt.bufPrintSentinel(&runtime_buf, "{s}", .{dir}, 0), 1) != 0) return error.NoRuntimeDir; - std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); + std.debug.print("{d} seeds x {d} inputs from the session's own frontend and each of {d} clients (terminals and windows by turns, joined from a dump, at most {d} at once), a TUI then {d} MB of yes and as much of a cat in the shell; costs in us (frame {d})\n", .{ seeds, steps, clients, pardes.views.max - 1, flood_mb, frame_us }); std.debug.print(" rtt inputs at-once stopped units fast rollback(mis+foreign) rate rebase spec p50/p99 copy p50/p99 (KB) rollback p50/p99 diverged unequal\n", .{}); var term_lines: std.ArrayList(u8) = .empty; defer term_lines.deinit(gpa); @@ -2922,6 +3490,8 @@ pub fn main(init: std.process.Init) !void { defer join_lines.deinit(gpa); var stop_lines: std.ArrayList(u8) = .empty; defer stop_lines.deinit(gpa); + var far_lines: std.ArrayList(u8) = .empty; + defer far_lines.deinit(gpa); for (rtts) |rtt| { var t: Totals = .{}; pardes.Term.reloads = .{}; @@ -2958,6 +3528,20 @@ pub fn main(init: std.process.Init) !void { for (t.stops) |st| if (st.n > 0) try stop_lines.print(gpa, "{s}:{d} ", .{ st.name, st.n }); try stop_lines.append(gpa, '\n'); try join_lines.print(gpa, "{d:>4} {d:>5} {d:>7} {d:>8} {d:>8} {d:>6} {d:>5}/{d:<5} {d:>5}/{d:<6} {d:>7} {d:>5}/{d}/{d}\n", .{ rtt, t.joins, t.refused, t.rejoined, t.detached, t.detach_words, t.agree, t.differ, t.checks, t.units, t.resizes, t.kind_panes[0], t.kind_panes[1], t.kind_panes[2] }); + try far_lines.print(gpa, "{d:>4} {d:>5} {d:>4} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} {d:>8} {d:>3} {d:>6.1}/{d:<6.1} {d:>6.1}/{d:<6.1} ({d}) {d:>6.0}/{d:<6.0} {d}\n", .{ + rtt, t.far_joins, t.far_lags, + secs(pct(t.far_gaps.items, 50)), secs(pct(t.far_gaps.items, 100)), + secs(pct(t.far_final.items, 50)), secs(pct(t.far_final.items, 100)), + t.queue_max >> 10, t.cut, + msOf(pct(t.join_session_ns.items, 50)), msOf(pct(t.join_session_ns.items, 100)), + msOf(pct(t.join_client_ns.items, 50)), msOf(pct(t.join_client_ns.items, 100)), + t.join_client_ns.items.len, + msOf(t.far_behind), msOf(t.near_behind), + t.near_lags, + }); + // The far client shows the final screen in every run, and the near + // ones never fall behind with it. + if ((t.far_final.items.len < seeds and clients >= 3) or t.near_lags > 0) failed = true; if (t.divergences > 0 or t.unequal > 0 or t.screens_wrong > 0 or t.differ > 0 or t.unlisted > 0) failed = true; } std.debug.print("terminals: deltas a replica applied a second under the flood; a peer's bytes a second under the flood (deltas, units); encode a frame of the flood for every peer, apply a delta (us); rows fetched, KB of rows sent before the step that read them; resets; deltas checked/wrong\n", .{}); @@ -2966,6 +3550,8 @@ pub fn main(init: std.process.Init) !void { std.debug.print(" rtt joins refused rejoined detached detach agree/differ checks/units resizes kinds\n{s}", .{join_lines.items}); std.debug.print("stops: the wakes the clients' loops asked, the frames they drew, the yanks, pastes and links their frontends did (y/p/l), and what stopped their inputs (a stop counted again as its input is applied again), by name; those at a name replica.may_wait does not list fail the run\n", .{}); std.debug.print(" rtt unlisted wakes draws y/p/l stops\n{s}", .{stop_lines.items}); + std.debug.print("far: the third client's link 1 Mbit/s and 200 ms each way (zstd's bytes): its joins from a dump, of them for its lag (Link.behind past replica.behind_max_ms), s between two from the flood's start (p50/max), s from the flood's end to its final screen (p50/max: a run that never shows it fails), the session's queue for it at most, clients cut off; a join's cost to the replicas there before it, ms on this process's clock (p50/max): the session's step (reloads and dump), a client's unit (reloads), how many; ms behind the session at most (Link.behind), the far client and the others, and the others' joins for it (0, or the run fails)\n", .{}); + std.debug.print(" rtt joins lags refresh s final s queue KB cut session ms client ms behind far/near ms\n{s}", .{far_lines.items}); if (failed) std.process.exit(1); } |
