From 8d9f4c88072089b53c77ab7e66b01c461fbbee74 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 04:17:12 -0300 Subject: dev, runtime: the addons' jobs and draws, the pipes and a search answer through the session's one queue in both frontends, and their workers are the queue's: the terminal's own posts to vaxis's queue are deleted (its pipe_done, search_rows and kind_job messages and their arms in apply and in Own.close's drain, deliverSearch, deliverPipe, the two inline deliver functions), its pipe, search, job and draw post with Inbox.pushPipe, pushSearch and pushJob as the window's did and takeQueue lands them; Inbox.land (landLsp grown to every worker's answer: a pipe's, a search's rows, a job's or a draw's, a handover's end) replaces the two frontends' copies of those arms; pipe_tasks and job_tasks leave both Shells and the window's Own for the Inbox beside lsp_task, ended in Inbox.deinit (and so a client's draws in both clients, which the terminal's client never canceled), the pipes canceled by the session loop's Restore and the search's worker by the loop's end, not by each frontend's close and restoring; a terminal client's queue wakes its loop (wakeForQueue) now that its draws come through it; the test first: on the base a search worker's post into vaxis's full queue waited for the loop to take one and a cancel did end it (vaxis's Queue.push waits on a cancelable condition), so no worker could have hung, but the terminal's keys waited behind up to 512 queued batches of rows in that one queue (the input thread's post waits in it too); now rows wait in the session's queue and keys never behind them, pinned by host_io's test of pushSearch into a full queue (a take lets it in, a cancel ends the wait and frees the rows); tui core-test 857/1008 (151 skipped), shell-test 1048/1051, term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed (wheeldrift and exec failed once in the run, passed on their retries), soak --clients 5 diverged 0, unequal 0, checked/wrong 1874/0 1937/0 1831/0, quiet checks 597/0 673/0 779/0, unlisted 0, corpus 22 of 22, no leak; --bytes --clients 5 diverged 0, unequal 0, quiet checks 693/0 586/0 802/0, corpus 22 of 22, no leak, one unlisted stop at `now` at 30 ms (the base's, known); gui unit-test 1645/1649 with only the perf check's BaselineHarnessMismatch; daemon.py plain, --far, --games, --window-clients, --upgrade both ways pass (upgrade-back failed once at its Adopt into the old build's fresh session, then passed 3 of 3) (load 11-22) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Inbox.zig | 44 ++++++++++++++++++++---- dev/gui/gui.zig | 60 +++++--------------------------- dev/host_io.zig | 32 +++++++++++++++++ dev/tui/tui.zig | 99 +++++++++++++---------------------------------------- runtime/session.zig | 14 +++++--- 5 files changed, 111 insertions(+), 138 deletions(-) diff --git a/dev/Inbox.zig b/dev/Inbox.zig index aac1f7a1..234d89eb 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -63,6 +63,11 @@ gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator, /// The query in flight; the UI thread's alone (spawnLsp, teardown). lsp_task: ?Lsp.Task = null, +/// The `|` pipes' and the addons' jobs' and draws' workers in flight, each +/// posting its answer here (`pushPipe`, `pushJob`); the loop's thread's +/// alone: joined as their answers land (`land`), canceled at the end. +pipe_tasks: selection_pipe.Tasks = .{}, +job_tasks: selection_pipe.Tasks = .{}, /// Wakes the host's loop after a push from another thread: an SDL /// event, a macOS runtime callback. Null: nobody to wake (tests). wake_fn: ?*const fn (?*anyopaque) void = null, @@ -262,9 +267,11 @@ pub fn close(q: *Inbox) void { } pub fn deinit(q: *Inbox) void { - // The query in flight ends first: what it still delivers is dropped. + // The workers in flight end first: what they still deliver is dropped. if (q.lsp_task) |*t| t.future.cancel(q.io); q.lsp_task = null; + q.pipe_tasks.cancelAll(q.io); + q.job_tasks.cancelAll(q.io); q.close(); std.debug.assert(q.waiting == 0); } @@ -311,9 +318,10 @@ pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void { Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows); } -/// A language server's answer or status line taken off the queue, to the -/// core (whichever frontend took it). -pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void { +/// A worker's answer taken off the queue, to the core (whichever frontend +/// took it), its worker joined: a language server's answer or status line, +/// a pipe's, a search's rows, an addon's job or draw, a handover's end. +pub fn land(q: *Inbox, core: *pardes.Pardes, m: Msg) void { switch (m) { .lsp => |l| { core.update(.{ .lsp_resp = .{ .id = l.id, .rows = l.rows } }); @@ -324,7 +332,30 @@ pub fn landLsp(q: *Inbox, core: *pardes.Pardes, m: Msg) void { core.setStatus(.at(core.view().active), pardes.Messages.Message.stamp(&mbuf, "lsp", text)); q.lsp_allocator.free(text); }, - else => unreachable, + .pipe => |response_value| { + var response = response_value; + core.update(.{ .pipe_resp = .{ + .id = response.id, + .success = response.success, + .outputs = response.outputs, + .failure = response.failure, + } }); + response.deinit(q.gpa); + q.pipe_tasks.finish(q.io, response_value.id); + }, + .search => |b| { + core.update(.{ .search = b }); + b.deinit(q.gpa); + }, + .kind_job => |j| { + q.job_tasks.finish(q.io, j.id); + j.land(core); + }, + .handed => |h| { + core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); + q.gpa.free(h.words); + }, + .output, .eof, .files_changed, .fs_ready, .adopted => unreachable, } } @@ -340,12 +371,13 @@ pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { q.push(.{ .lsp_status = copy }); } -/// A `|` job's answer (selection_pipe.start's sink). +/// An addon's job or draw done (KindJob.go's sink). pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void { const q: *Inbox = @ptrCast(@alignCast(ctx.?)); q.push(.{ .kind_job = j }); } +/// A `|` pipe's answer (selection_pipe.start's sink). pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { const q: *Inbox = @ptrCast(@alignCast(ctx.?)); q.push(.{ .pipe = response }); diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index ab33abe9..fa480665 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -379,7 +379,6 @@ fn sdlWake(_: ?*anyopaque) void { sev.type = c.SDL_EVENT_USER; _ = c.SDL_PushEvent(&sev); } -const PipeTasks = selection_pipe.Tasks; const output_capacity = Queue.output_capacity; const Gui = struct { @@ -991,7 +990,6 @@ const Own = struct { g: *Gui, test_mode: bool, detached: bool, - pipe_tasks: PipeTasks = .{}, shell: Shell = undefined, const Session = session_loop.Loop(Own); @@ -1024,7 +1022,6 @@ const Own = struct { .lsp_allocator = l.allocs.lsp, .ptys = &l.ptys, .queue = &l.inbox, - .pipe_tasks = &o.pipe_tasks, .watches = &l.watches, .fs = l.fs, .test_mode = o.test_mode, @@ -1044,15 +1041,10 @@ const Own = struct { return host; } - pub fn close(o: *Own, l: *Session) void { - const io = l.io; + pub fn close(o: *Own, _: *Session) void { o.shell.fs = null; host_io.setExitWake(null, null); pardes.Kind.drawer = null; - o.shell.job_tasks.cancelAll(io); - o.pipe_tasks.cancelAll(io); - // Its worker may be waiting on the queue for room. - l.core.stream.cancelTask(); o.g.hit_core = null; } @@ -1084,7 +1076,6 @@ const Own = struct { } pub fn restoring(o: *Own, nc: *pardes.Pardes) void { - o.pipe_tasks.cancelAll(o.shell.io); // One view, the window's (host_io.restoreCore). o.shell.gview = 0; o.g.cells.clearImages(); @@ -1415,7 +1406,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ var queue: Queue = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp, .wake_fn = sdlWake }; defer queue.deinit(); var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = undefined }; - var pipe_tasks: PipeTasks = .{}; var no_watches: file_watch.Watches = .{ .io = io, .gpa = gpa, .queue = &queue }; var no_peers: replica.Peers = .{}; var shell: Shell = .{ @@ -1426,7 +1416,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ .lsp_allocator = start.allocs.lsp, .ptys = &ptys, .queue = &queue, - .pipe_tasks = &pipe_tasks, .watches = &no_watches, .test_mode = test_mode, .client = &window, @@ -1435,7 +1424,6 @@ fn clientSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ window.shell = &shell; pardes.Kind.drawer = .{ .ctx = &shell, .go = kindDraw }; defer pardes.Kind.drawer = null; - defer shell.job_tasks.cancelAll(io); g.no_blink = test_mode; defer g.hit_core = null; _ = c.SDL_StartTextInput(g.window); @@ -2351,8 +2339,6 @@ const Shell = struct { queue: *Queue, /// What drainQueue takes each wakeup, kept rather than rebuilt. batch: Queue.Batch = .{}, - pipe_tasks: *PipeTasks, - job_tasks: PipeTasks = .{}, /// The session's file watches (runtime/session.zig's); a client's, /// none. watches: *file_watch.Watches, @@ -2561,10 +2547,7 @@ const Shell = struct { fn takeDraws(s: *Shell) bool { s.queue.takeInto(&s.batch); for (s.batch.slice()) |m| switch (m) { - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, + .kind_job => s.queue.land(s.core, m), else => m.deinit(s.gpa, s.lsp_allocator), }; return s.batch.slice().len > 0; @@ -2580,33 +2563,10 @@ const Shell = struct { for (msgs.slice()) |m| switch (m) { .output => |o| s.ptys.output(s.core, o), .eof => |e| s.ptys.eof(s.core, e), - .lsp, .lsp_status => s.queue.landLsp(s.core, m), - .pipe => |response_value| { - var response = response_value; - s.core.update(.{ .pipe_resp = .{ - .id = response.id, - .success = response.success, - .outputs = response.outputs, - .failure = response.failure, - } }); - response.deinit(s.gpa); - s.pipe_tasks.finish(s.io, response_value.id); - }, - .search => |b| { - s.core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - .handed => |h| { - s.core.update(.{ .handed = .{ .seq = h.seq, .to = if (h.ok) h.words else "", .failure = if (h.ok) null else h.words } }); - s.gpa.free(h.words); - }, - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(s.core); - }, .files_changed => check_files = true, .fs_ready => {}, .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), + else => s.queue.land(s.core, m), }; if (check_files) s.watches.reload(s.core); } @@ -3178,7 +3138,7 @@ fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { fn pipe(ctx: ?*anyopaque, id: u32) void { const s = shellOf(ctx); - if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, s.pipe_tasks, id, s.queue, Queue.pushPipe); + if (s.threads_ok) return selection_pipe.start(s.io, s.gpa, s.core, &s.queue.pipe_tasks, id, s.queue, Queue.pushPipe); s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable); } @@ -3186,13 +3146,13 @@ fn pipe(ctx: ?*anyopaque, id: u32) void { /// A draw (api.draw) on a worker, as a job is. fn kindDraw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { const s = shellOf(ctx); - return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s.queue, Queue.pushJob); + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.queue.job_tasks, j, s.queue, Queue.pushJob); } fn kindJob(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void { const pane = id.index(); const s = shellOf(ctx); - if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s.queue, Queue.pushJob); + if (s.threads_ok) return host_io.KindJob.start(s.io, s.core, &s.queue.job_tasks, pane, serial, token, s.queue, Queue.pushJob); host_io.KindJob.runHere(s.core, pane, serial, token); } @@ -5976,7 +5936,6 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { .lsp_allocator = failing.allocator(), }; defer queue.deinit(); - var tasks: PipeTasks = .{}; core.lspRequest(core.view().active, .status, ""); const req: host_io.Lsp.Request = .{ .id = core.lsp_ask.wait.?.id, @@ -6008,11 +5967,11 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); const pipe_id = core.pipe.wait.?.id; - selection_pipe.start(failing_io, failing.allocator(), core, &tasks, pipe_id, &queue, Queue.pushPipe); + selection_pipe.start(failing_io, failing.allocator(), core, &queue.pipe_tasks, pipe_id, &queue, Queue.pushPipe); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); try std.testing.expect(queue.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), tasks.len); + try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len); try std.testing.expectEqual(@as(usize, 0), queue.len); } } @@ -7676,9 +7635,8 @@ test "a detached GUI authority follows terminal directory changes with no window const rcs: host_io.Shell.PromptFiles = .{}; var ptys: host_io.Ptys = .{ .queue = &queue, .prompt_rcs = &rcs, .gens = @splat(1) }; defer ptys.deinit(); - var pipes: PipeTasks = .{}; var no_peers: replica.Peers = .{}; - var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .pipe_tasks = &pipes, .watches = undefined, .peers = &no_peers }; + var shell: Shell = .{ .core = core, .io = io, .gpa = gpa, .lsp_allocator = gpa, .ptys = &ptys, .queue = &queue, .watches = undefined, .peers = &no_peers }; const child = try host_io.forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); ptys.slots[0] = .{ .fd = child.file.handle, .pid = child.pid }; try std.testing.expect(host_io.writeFd(child.file.handle, "cd child\n")); diff --git a/dev/host_io.zig b/dev/host_io.zig index 5465fc7a..1c4fe332 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -2270,6 +2270,38 @@ test "PTY EOF reserve cannot evict terminal output" { for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane.index()); } +test "a search's rows posted into a full queue wait for room: a take lets them in, a cancel ends the wait and frees them" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var queue: Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(.at(0), 1); + const Post = struct { + fn run(q: *Inbox, posted: *?bool) void { + const rows = std.testing.allocator.dupe(u8, "a.txt:1:1-2 hit\n") catch return; + posted.* = Inbox.pushSearch(q, .{ .gen = 1, .rows = rows }); + } + }; + for ([_]bool{ false, true }) |cancel| { + // The loop busy: its queue full of output. + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "busy") } }); + var posted: ?bool = null; + var worker = try io.concurrent(Post.run, .{ &queue, &posted }); + try PtyTests.waitBlocked(&queue); + if (cancel) worker.cancel(io) else { + var batch = queue.take(); + for (batch.slice()) |msg| msg.deinit(gpa, gpa); + worker.await(io); + } + try std.testing.expectEqual(!cancel, posted.?); + var rest = queue.take(); + defer for (rest.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, if (cancel) Inbox.output_capacity else 1), rest.len); + if (!cancel) try std.testing.expectEqualStrings("a.txt:1:1-2 hit\n", rest.items[0].search.rows); + try std.testing.expectEqual(@as(usize, 0), queue.waiting); + } +} + test "completions retain their arrival order across LSP and pipes" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 }; diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 543be3aa..1b00d1b9 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -97,8 +97,9 @@ fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { w.flush() catch {}; } -/// What the loop's queue carries: a terminal's input, a pane's output, a -/// worker's answer, a wake. +/// What the loop's queue carries: a terminal's input, a wake, what the +/// daemon and a replica's reader hand over. A pane's output and a worker's +/// answer are the session's queue's (Inbox, `takeQueue`). const Msg = union(enum) { nop, /// The terminal's input ended: its end of file, a hangup. A session @@ -120,11 +121,6 @@ const Msg = union(enum) { paste: []const u8, paste_start, paste_end, - pipe_done: selection_pipe.Response, - /// A streaming search's rows (pardes.Stream). - search_rows: pardes.Stream.Batch, - /// A kind's job done on a worker (host_io.KindJob). - kind_job: *host_io.KindJob, fs_ready, /// A replica's connection, handed over by the daemon (Peers). replica: daemon.Joining, @@ -369,8 +365,6 @@ const TestReader = struct { } }; -const PipeTasks = selection_pipe.Tasks; - /// A watched child exited: wake the loop, which takes it (`takeExits`). fn wakeForExit(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); @@ -760,7 +754,7 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, var c = try Client.init(&tty, &start); defer c.link.deinit(gpa); // A client has no clients of its own, and spawns nothing: its pty - // table an empty one over an empty queue. + // table an empty one over a queue that carries its draws alone. var no_peers: replica.Peers = .{}; var no_inbox: host_io.Inbox = .{ .io = io, .gpa = gpa, .lsp_allocator = start.allocs.lsp }; defer no_inbox.deinit(); @@ -783,6 +777,8 @@ pub fn runClient(init: std.process.Init, opts: pardes.Options, path: []const u8, .ptys = &no_ptys, }; tty = .{ .sh = &sh, .screen = &screen, .loop = &loop, .joins = &start }; + no_inbox.wake_fn = Shell.wakeForQueue; + no_inbox.wake_ctx = &sh; pardes.Kind.drawer = .{ .ctx = &sh, .go = Shell.draw }; defer pardes.Kind.drawer = null; @@ -985,18 +981,8 @@ const Own = struct { stopInput(io, &o.screen.thread); pardes.Kind.drawer = null; host_io.setExitWake(null, null); - sh.pipe_tasks.cancelAll(io); - sh.job_tasks.cancelAll(io); - // Its worker may be waiting on the loop's queue for room. - sh.core.stream.cancelTask(); while (loop.tryEvent() catch null) |ev| switch (ev) { .paste => |b| gpa.free(@constCast(b)), - .pipe_done => |response_value| { - var response = response_value; - response.deinit(gpa); - }, - .search_rows => |b| b.deinit(gpa), - .kind_job => |j| j.drop(), .adopted => |a| _ = libc.close(a.fd), else => {}, }; @@ -1040,7 +1026,6 @@ const Own = struct { pub fn restoring(o: *Own, nc: *pardes.Pardes) void { const sh = &o.sh; const io = sh.io; - sh.pipe_tasks.cancelAll(io); // One view, the terminal's (host_io.restoreCore). const live = o.screen; stopInput(io, &live.thread); @@ -1124,8 +1109,6 @@ const Shell = struct { batch: host_io.Inbox.Batch = .{}, batch_at: usize = 0, queue_woken: std.atomic.Value(bool) = .init(false), - pipe_tasks: PipeTasks = .{}, - job_tasks: PipeTasks = .{}, threads_ok: bool = false, check_files: bool = false, in_paste: bool = false, @@ -1648,27 +1631,6 @@ const Shell = struct { s.paste_buf.clearRetainingCapacity(); }, .fs_ready => {}, - .pipe_done => |response_value| { - var response = response_value; - core.update(.{ .pipe_resp = .{ - .id = response.id, - .success = response.success, - .outputs = response.outputs, - .failure = response.failure, - } }); - response.deinit(s.gpa); - s.pipe_tasks.finish(s.io, response_value.id); - }, - .search_rows => |b| { - core.update(.{ .search = b }); - b.deinit(s.gpa); - }, - .kind_job => |j| { - s.job_tasks.finish(s.io, j.id); - j.land(core); - // A client's draw done: its frame is its own to draw again. - if (s.client) |cl| cl.link.dirty = true; - }, } return false; } @@ -1877,7 +1839,8 @@ const Shell = struct { } /// What the session's queue holds: its ptys' output (`waitInput` - /// paces it; the focused pane's is its echo) and their ends of file. + /// paces it; the focused pane's is its echo), their ends of file and + /// the workers' answers. /// A read a step, as the terminal's own queue gave them: the frame /// after one shows it before what came after it (a command's last line /// before its exit scrolls it away), the rest kept for the next wait. @@ -1905,8 +1868,13 @@ const Shell = struct { }, .eof => |e| s.ptys.eof(s.core, e), .files_changed => s.check_files = true, - .lsp, .lsp_status => s.ptys.queue.landLsp(s.core, m), - else => m.deinit(s.gpa, s.lsp_gpa), + .kind_job => { + s.ptys.queue.land(s.core, m); + // A client's draw done: its frame is its own to draw again. + if (s.client) |cl| cl.link.dirty = true; + }, + .fs_ready, .adopted => m.deinit(s.gpa, s.lsp_gpa), + else => s.ptys.queue.land(s.core, m), } } } @@ -1961,50 +1929,29 @@ const Shell = struct { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return s.core.reportError(.at(s.core.view().active), "pipe", error.WorkersUnavailable); } - selection_pipe.start(s.io, s.gpa, s.core, &s.pipe_tasks, id, s, deliverPipe); + const q = s.ptys.queue; + selection_pipe.start(s.io, s.gpa, s.core, &q.pipe_tasks, id, q, host_io.Inbox.pushPipe); } fn search(ctx: ?*anyopaque, gen: u32) void { const s = of(ctx); - if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s, deliverSearch); + if (s.threads_ok) return pardes.Stream.start(s.io, s.gpa, s.core, gen, s.ptys.queue, host_io.Inbox.pushSearch); pardes.Stream.runHere(s.core, gen, true); } /// A draw (api.draw) on a worker, as a job is. fn draw(ctx: ?*anyopaque, j: *host_io.KindJob) bool { const s = of(ctx); - return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &s.job_tasks, j, s, struct { - fn deliver(c: ?*anyopaque, k: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = k }) catch k.drop(); - } - }.deliver); + const q = s.ptys.queue; + return (s.threads_ok or s.client != null) and host_io.KindJob.go(s.io, &q.job_tasks, j, q, host_io.Inbox.pushJob); } fn job(ctx: ?*anyopaque, id: pardes.Pane.Id, serial: u32, token: u32) void { const pane = id.index(); const s = of(ctx); if (!s.threads_ok) return host_io.KindJob.runHere(s.core, pane, serial, token); - host_io.KindJob.start(s.io, s.core, &s.job_tasks, pane, serial, token, s, struct { - fn deliver(c: ?*anyopaque, j: *host_io.KindJob) void { - of(c).loop.postEvent(.{ .kind_job = j }) catch j.drop(); - } - }.deliver); - } - - /// The loop's queue waits for room (a wait the worker's cancel ends). - fn deliverSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool { - const s = of(ctx); - s.loop.postEvent(.{ .search_rows = batch }) catch { - batch.deinit(s.gpa); - return false; - }; - return true; - } - - fn deliverPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void { - const s = of(ctx); - var owned = response; - s.loop.postEvent(.{ .pipe_done = owned }) catch owned.deinit(s.gpa); + const q = s.ptys.queue; + host_io.KindJob.start(s.io, s.core, &q.job_tasks, pane, serial, token, q, host_io.Inbox.pushJob); } }; @@ -2737,7 +2684,7 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); try std.testing.expect(queue.lsp_task == null); - try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); + try std.testing.expectEqual(@as(usize, 0), queue.pipe_tasks.len); } } diff --git a/runtime/session.zig b/runtime/session.zig index fdd72c2b..e425fa3f 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -6,10 +6,10 @@ //! posts, `Inbox`), its ptys (`Ptys`) and the files it watches //! (`file_watch.Watches`): a step, its unit to the clients and theirs //! taken in, an Upgrade or a Restore between steps; and the order its -//! parts end in. Its other devices (the LSP's and the pipes' and addons' -//! jobs, the session's own input) are still its frontend's (each `Shell`); -//! the language servers' answers come through its queue (`Inbox.startLsp`). -//! What a frontend does is: +//! parts end in. Its workers (a language server's query, the pipes, the +//! addons' jobs and draws, a search) answer through its queue, which holds +//! their tasks and ends them (`Inbox.land`, `Inbox.deinit`); the session's +//! own input is its frontend's (each `Shell`). What a frontend does is: //! //! - `options(o)`: before the core: what it gives the core it starts (a //! window's size, for a dump's layout). @@ -90,6 +90,8 @@ pub fn Loop(comptime Frontend: type) type { l.peers = .{ .gpa = l.gpa, .io = l.io, .name = daemon.name() }; l.inbox = .{ .io = l.io, .gpa = l.gpa, .lsp_allocator = l.allocs.lsp }; defer l.inbox.deinit(); + // A search's worker may be waiting on the queue for room. + defer l.core.stream.cancelTask(); // The language servers' status lines, from the first effects on. pardes.lsp.setStatusSink(&l.inbox, host_io.Inbox.lspStatus); defer pardes.lsp.setStatusSink(null, null); @@ -162,7 +164,9 @@ pub fn Loop(comptime Frontend: type) type { fn restore(l: *L, path: []const u8) void { const nc = host_io.restoreCore(l.gpa, l.core, path, &l.peers, l.watches.fd, &l.watches.table) orelse return; l.fe.restoring(nc); - // An answer to the old core's query is turned away. + // The old core's pipes end, and an answer to its query is + // turned away. + l.inbox.pipe_tasks.cancelAll(l.io); l.inbox.discardCompletions(); l.ptys.stop(); nc.host = l.host; -- cgit v1.3 From 26d0581168ac4b582025ecb01b36968850344811 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 06:07:10 -0300 Subject: runtime, dev: the daemon's notes are the session loop's own, so `note` leaves the frontend calls (nine to eight: options, open, close, start, sent, upgradeAsked, restoring, restored): the loop's note puts an adopted shell on its queue (both frontends take it in their wait), hands a client's connection to Peers (joined at the next step boundary, its post the wake, as the window did) and wakes the queue for a new daemon's hello; the terminal's deliverNote, its adopted and replica messages and arms (in apply and in Own.close's drain) and the window's deliverNote and both Own.note are deleted, the terminal's Shell names its session loop (`session`) so that a quit before the first frame starts the daemon's reader through the loop's watch; and the test first: an Adopt's shells arriving while output fills the queue were dropped by Inbox.push, their masters closed and the shells lost with them (448 outputs in, the shell and the end of the list pushed, 448 taken), in the window today, and in the terminal once its notes came through this queue (vaxis's queue had made the daemon's thread wait); the queue now keeps room for one Adopt's shells beyond the output's (adopt_capacity, the ring 64 + 1 longer, the output's bound unchanged) and each pane's end of file beyond those; a user could have hit it: Adopt in a window while another pane floods; tui core-test 858/1009 (151 skipped), shell-test 1049/1052, term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed (msg, pagercolor and exec-bigdrag failed once in the run, passed on their retries), soak --clients 5 diverged 0, unequal 0, checked/wrong 1874/0 1937/0 1831/0, quiet checks 597/0 673/0 779/0, unlisted 0, corpus 22 of 22, no leak; --bytes --clients 5 diverged 0, unequal 0, quiet checks 693/0 586/0 802/0, corpus 22 of 22, no leak, its one unlisted stop at `now` the base's; gui unit-test 1646/1650 with only BaselineHarnessMismatch; daemon.py plain, --far, --games (keys stopped 0 and 0), --window-clients, --upgrade both ways pass (load 8-22) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Inbox.zig | 10 +++++++--- dev/gui/gui.zig | 19 ------------------- dev/host_io.zig | 21 ++++++++++++++++++++- dev/tui/tui.zig | 47 ++++++++++------------------------------------- runtime/session.zig | 21 +++++++++++++++------ test/replicas.zig | 1 - 6 files changed, 52 insertions(+), 67 deletions(-) diff --git a/dev/Inbox.zig b/dev/Inbox.zig index 234d89eb..347ad278 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -47,8 +47,12 @@ pub const Msg = union(enum) { } }; -pub const capacity = 512; -pub const output_capacity = capacity - pardes.MAX_PANES; +/// The ring's room: output up to `output_capacity` (a reader waits for +/// more), an Adopt's shells beyond it (one note's: never lost to a flood), +/// and each pane's end of file beyond those (lost to neither). +pub const output_capacity = 512 - pardes.MAX_PANES; +const adopt_capacity = output_capacity + pardes.MAX_PANES + 1; +pub const capacity = adopt_capacity + pardes.MAX_PANES; pub const Batch = struct { items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined, @@ -194,7 +198,7 @@ pub fn push(q: *Inbox, m: Msg) void { return; } std.debug.assert(q.len < q.items.len); - } else if (q.len >= output_capacity) { + } else if (q.len >= @as(usize, if (m == .adopted) adopt_capacity else output_capacity)) { q.unlock(); m.deinit(q.gpa, q.lsp_allocator); return; diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index fa480665..72ad1eed 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -1071,10 +1071,6 @@ const Own = struct { if (o.shell.upgrade_asked) |pane| o.shell.upgradeNow(pane); } - pub fn note(o: *Own, n: daemon.Note) void { - deliverNote(&o.shell, n); - } - pub fn restoring(o: *Own, nc: *pardes.Pardes) void { // One view, the window's (host_io.restoreCore). o.shell.gview = 0; @@ -3073,21 +3069,6 @@ fn guiNow(ctx: ?*anyopaque) u64 { return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); } -/// The daemon's thread: what it says, onto the queue (drainQueue). -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const s: *Shell = @ptrCast(@alignCast(ctx)); - const q = s.queue; - switch (note) { - .relinked => q.wake(), - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| q.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); - q.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); - }, - // Joined at the next step boundary (Peers, any thread). - .replica => |j| s.peers.handed(j.fd, j.view), - } -} - fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { host_io.writeDump(shellOf(ctx).core, bytes); } diff --git a/dev/host_io.zig b/dev/host_io.zig index 1c4fe332..0efb37fd 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -2265,7 +2265,7 @@ test "PTY EOF reserve cannot evict terminal output" { for (0..pardes.MAX_PANES) |pane| queue.push(.{ .eof = .{ .pane = .at(pane), .gen = 1 } }); var batch = queue.take(); defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); - try std.testing.expectEqual(Inbox.capacity, batch.len); + try std.testing.expectEqual(Inbox.output_capacity + pardes.MAX_PANES, batch.len); for (batch.items[0..Inbox.output_capacity]) |msg| try std.testing.expectEqualStrings("before", msg.output.bytes); for (batch.items[Inbox.output_capacity..batch.len], 0..) |msg, pane| try std.testing.expectEqual(pane, msg.eof.pane.index()); } @@ -2302,6 +2302,25 @@ test "a search's rows posted into a full queue wait for room: a take lets them i } } +test "an Adopt's shells are taken in whatever output fills the queue" { + const gpa = std.testing.allocator; + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + queue.acceptReader(.at(0), 1); + for (0..Inbox.output_capacity) |_| queue.push(.{ .output = .{ .pane = .at(0), .gen = 1, .bytes = try gpa.dupe(u8, "flood") } }); + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + defer _ = libc.close(fds[1]); + queue.push(.{ .adopted = .{ .pid = 42, .fd = fds[0] } }); + queue.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); + var batch = queue.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(Inbox.output_capacity + 2, batch.len); + try std.testing.expectEqual(@as(libc.pid_t, 42), batch.items[Inbox.output_capacity].adopted.pid); + try std.testing.expectEqual(fds[0], batch.items[Inbox.output_capacity].adopted.fd); + try std.testing.expectEqual(@as(libc.pid_t, 0), batch.items[Inbox.output_capacity + 1].adopted.pid); +} + test "completions retain their arrival order across LSP and pipes" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 2 }; diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index 1b00d1b9..ecc52df0 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -97,16 +97,14 @@ fn kittyShmProbe(w: *std.Io.Writer, feed: *Feed) void { w.flush() catch {}; } -/// What the loop's queue carries: a terminal's input, a wake, what the -/// daemon and a replica's reader hand over. A pane's output and a worker's -/// answer are the session's queue's (Inbox, `takeQueue`). +/// What the loop's queue carries: a terminal's input, a wake, what a +/// replica client's reader hands over. A pane's output, a worker's answer +/// and the daemon's notes are the session's queue's (Inbox, `takeQueue`). const Msg = union(enum) { nop, /// The terminal's input ended: its end of file, a hangup. A session /// a daemon keeps carries on detached; any other ends. quit, - /// A shell a dead session left, its pty's master (daemon.Note.adopted). - adopted: struct { pid: posix.pid_t, fd: posix.fd_t }, /// A timed wait ran out: the core's next wake has come. wake, /// A SIGWINCH: a terminal changed size (Shell.winched). @@ -122,8 +120,6 @@ const Msg = union(enum) { paste_start, paste_end, fs_ready, - /// A replica's connection, handed over by the daemon (Peers). - replica: daemon.Joining, /// A replica's reader posted: the step boundary takes it in. replica_mail, /// A replica client's: what the session streamed (replica.Link). @@ -953,6 +949,7 @@ const Own = struct { .test_clock = host_io.testClock(), .peers = &l.peers, .ptys = &l.ptys, + .session = l, }; const sh = &o.sh; sh.screen = o.screen; @@ -983,7 +980,6 @@ const Own = struct { host_io.setExitWake(null, null); while (loop.tryEvent() catch null) |ev| switch (ev) { .paste => |b| gpa.free(@constCast(b)), - .adopted => |a| _ = libc.close(a.fd), else => {}, }; o.screen.art.deinit(gpa); @@ -1019,10 +1015,6 @@ const Own = struct { if (o.sh.upgrade_asked) |pane| o.sh.upgradeNow(pane); } - pub fn note(o: *Own, n: daemon.Note) void { - deliverNote(o.loop, n); - } - pub fn restoring(o: *Own, nc: *pardes.Pardes) void { const sh = &o.sh; const io = sh.io; @@ -1054,24 +1046,6 @@ fn clearNativeImages( kitty_handles.clearRetainingCapacity(); } -/// The daemon's thread: what it says, onto the loop's queue. -fn deliverNote(ctx: *anyopaque, note: daemon.Note) void { - const loop: *Loop = @ptrCast(@alignCast(ctx)); - switch (note) { - // A full queue wakes it anyway. - .relinked => _ = loop.tryPostEvent(.nop) catch false, - .adopted => |a| { - for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| loop.postEvent(.{ .adopted = .{ .pid = pid, .fd = fd } }) catch { - _ = libc.close(fd); - }; - loop.postEvent(.{ .adopted = .{ .pid = 0, .fd = -1 } }) catch {}; - }, - .replica => |j| loop.postEvent(.{ .replica = j }) catch { - _ = libc.close(j.fd); - }, - } -} - /// A replica reader's post: the session's wait ends, and its step /// boundary takes the post in. fn wakeForReplica(ctx: ?*anyopaque) void { @@ -1103,6 +1077,9 @@ const Shell = struct { /// The session's ptys (runtime/session.zig's); a client's, an empty /// table over an empty queue. ptys: *host_io.Ptys, + /// The session's loop (its `watch`, the daemon's notes); a client's + /// and a test's, none. + session: ?*Own.Session = null, /// What `takeQueue` takes off the ptys' queue, and whether the loop /// was woken for it since it last did (one wake, not one a read ahead /// of the terminal's keys in the loop's queue). @@ -1563,7 +1540,7 @@ const Shell = struct { // without it, to be attached again. Gone before the first // frame, the reader that takes the daemon's `ok` (kept // waits on it) is not started yet: started here. - daemon.watch(s.loop, deliverNote); + if (s.session) |l| l.watch(); if (daemon.kept()) { if (!s.detached()) s.leaveTerminal(); return true; @@ -1571,11 +1548,6 @@ const Shell = struct { core.quit = true; return true; }, - .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), - .replica => |j| { - s.peers.handed(j.fd, j.view); - s.input_seen = true; - }, .replica_mail => if (s.peers.urgent.swap(false, .acq_rel)) { s.input_seen = true; }, @@ -1873,7 +1845,8 @@ const Shell = struct { // A client's draw done: its frame is its own to draw again. if (s.client) |cl| cl.link.dirty = true; }, - .fs_ready, .adopted => m.deinit(s.gpa, s.lsp_gpa), + .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), + .fs_ready => {}, else => s.ptys.queue.land(s.core, m), } } diff --git a/runtime/session.zig b/runtime/session.zig index e425fa3f..64846319 100644 --- a/runtime/session.zig +++ b/runtime/session.zig @@ -25,8 +25,6 @@ //! session's first wait (`l.watch`). //! - `sent()`: after each step's unit went to the clients. //! - `upgradeAsked()`: an Upgrade asked in the step, done (it execs). -//! - `note(n)`: what the daemon says (an adopted shell, a client's -//! connection, a new daemon's hello taken), onto its queue. //! - `restoring(nc)`, `restored(l)`: a Restore's new core, before it //! replaces the old one (its devices let go, what it is told of the //! frontend) and after (its own view of it again). @@ -145,17 +143,28 @@ pub fn Loop(comptime Frontend: type) type { while (l.core.nextEffect()) |e| l.core.perform(e); } - /// What the daemon says, onto the frontend's queue (once: its + /// What the daemon says, onto the session's queue (once: its /// reader is started by the first call); and a daemon started /// since the last one died told the shells' masters it held. pub fn watch(l: *L) void { if (daemon.relinked()) l.ptys.tellDaemon(); - daemon.watch(l.fe, note); + daemon.watch(l, note); } + /// The daemon's thread: an adopted shell onto the queue (taken + /// in the frontend's wait), a client's connection to `Peers` + /// (joined at the next step boundary), a new daemon's hello taken + /// a wake (`watch` tells it the rest). fn note(ctx: *anyopaque, n: daemon.Note) void { - const fe: *Frontend = @ptrCast(@alignCast(ctx)); - fe.note(n); + const l: *L = @ptrCast(@alignCast(ctx)); + switch (n) { + .relinked => l.inbox.wake(), + .adopted => |a| { + for (a.pids[0..a.n], a.fds[0..a.n]) |pid, fd| l.inbox.push(.{ .adopted = .{ .pid = pid, .fd = fd } }); + l.inbox.push(.{ .adopted = .{ .pid = 0, .fd = -1 } }); + }, + .replica => |j| l.peers.handed(j.fd, j.view), + } } /// A Restore: the core its dump makes replaces this one, its clients diff --git a/test/replicas.zig b/test/replicas.zig index 7bf79055..7610ad8c 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -1120,7 +1120,6 @@ const Soak = struct { } pub fn upgradeAsked(_: *Soak) void {} - pub fn note(_: *Soak, _: anytype) void {} pub fn restoring(_: *Soak, _: *pardes.Pardes) void {} pub fn restored(_: *Soak, _: *SessionLoop) void {} -- cgit v1.3 From d48f044458756cdf807e34842444a7fd1b01498d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 06:17:22 -0300 Subject: dev: a command's exit is told only once every read its reader took out of the pty is applied: the queue counts each pane's reads read and not yet applied (Inbox.unapplied, raised by the reader the moment a read returns, lowered by Ptys.output once applied, by the reader when its dupe or push fails and by cancelReader for each read it drops), and host_io.takeExits passes over a command whose pty has not ended while its host has such a read (Ptys.unapplied); with it the terminal's guard (takeExits only once the reads taken off the queue were all applied) is deleted, the count holding those too; the test first: Ptys's "a command's exit is told after its output a reader read, however long that waits in the queue" (a reaped command, its pty held open, its last output read and queued) failed on the base, the exit told at once (CommandWatch.due polls the kernel, where the read output no longer is); the run first: process-test's cmdexit alone, 300 times under 16 busy loops, all niced 15 (load 25-33): 3 of 300 drew `exit 0` above BGSTARTED before, 1 of 300 after: what is left is the few instructions between the read's return and the count's raise (a reader preempted on its way back from the syscall), which std.Io gives no way to close (a readiness wait before the read would, and 0.17's Io has none: a raw poll is no cancel point); the exit cannot instead be ordered after the pty's end of file: in the one case that races, what the command left running holds the pty open and the end of file comes only when that ends (cmdexit's `sleep 30`); a user could have hit it: a command that ends leaving a background job on its terminal, its last line drawn below its exit; tui core-test 858/1009 (151 skipped), shell-test 1050/1053, term 17/17, pane 183/184, kitty 45/45; behaviour-test and --replay 275/275 (in the gate, at load 37-50, two addon-test scripts failed and the monkey replay hung a step: both re-run 275/275 and 275/275 at load 25, the two scripts pass alone; addon_test runs no line of this change); process-test whole 1 of 144 failed (pagercolor, on the known list; load 25), in a rerun 2 (pty/run and a control byte through pty/data, both pass alone); soak --clients 5 diverged 0, unequal 0, checked/wrong 1874/0 1937/0 1831/0, quiet checks 597/0 673/0 779/0, unlisted 0, corpus 22 of 22, no leak; --bytes --clients 5 diverged 0, unequal 0, quiet checks 693/0 586/0 802/0, corpus 22 of 22, no leak, its unlisted stop at `now` the base's; gui unit-test 1647/1651 with only BaselineHarnessMismatch; daemon.py plain, --far, --games, --window-clients, --upgrade both ways pass (upgrade failed once at its last Adopt as upgrade-back did in change 1's gate, then 3 of 3) (load 20-50) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Inbox.zig | 21 +++++++++++++++++++-- dev/Ptys.zig | 34 ++++++++++++++++++++++++++++++++++ dev/host_io.zig | 2 ++ dev/tui/tui.zig | 8 +++----- 4 files changed, 58 insertions(+), 7 deletions(-) diff --git a/dev/Inbox.zig b/dev/Inbox.zig index 347ad278..d733b971 100644 --- a/dev/Inbox.zig +++ b/dev/Inbox.zig @@ -86,6 +86,11 @@ len: usize = 0, closed: bool = false, files_changed: bool = false, readers: [pardes.MAX_PANES]?u32 = @splat(null), +/// Each pane's reads read out of its pty and not yet applied (`applied`): +/// a command's exit is told only once none is (Ptys.unapplied), since +/// the poll that asks whether its output is in (CommandWatch.due) cannot +/// see a read the reader holds or the queue does. +unapplied: [pardes.MAX_PANES]std.atomic.Value(u32) = @splat(.init(0)), waiting: usize = 0, lsp_id: ?u32 = null, completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined, @@ -110,6 +115,12 @@ pub fn acceptReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void { q.readers[pane.index()] = gen; } +/// One of `pane`'s reads applied, or dropped unapplied. +pub fn applied(q: *Inbox, pane: pardes.Pane.Id) void { + const n = &q.unapplied[pane.index()]; + if (n.load(.acquire) > 0) _ = n.fetchSub(1, .acq_rel); +} + pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void { q.lock(); defer q.unlock(); @@ -123,7 +134,10 @@ pub fn cancelReader(q: *Inbox, pane: pardes.Pane.Id, gen: u32) void { .eof => |e| e.pane == pane and e.gen == gen, else => false, }; - if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; + if (matches) { + if (msg == .output) q.applied(pane); + q.removeAt(i).deinit(q.gpa, q.lsp_allocator); + } else i += 1; } q.space.broadcast(q.io); } @@ -302,11 +316,14 @@ fn readPty(q: *Inbox, pty: std.Io.File, pane: pardes.Pane.Id, gen: u32) void { }, }; if (n == 0) continue; + // Counted at once: out of the pty, the poll no longer sees it. + _ = q.unapplied[pane.index()].fetchAdd(1, .acq_rel); const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| { + q.applied(pane); failure = err; break; }; - if (!q.pushOutput(pane, gen, bytes)) return; + if (!q.pushOutput(pane, gen, bytes)) return q.applied(pane); } q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } }); } diff --git a/dev/Ptys.zig b/dev/Ptys.zig index 16a31939..583e3c38 100644 --- a/dev/Ptys.zig +++ b/dev/Ptys.zig @@ -180,6 +180,7 @@ pub fn close(p: *Ptys, id: pardes.Pane.Id) void { /// A reader's read, off the queue (freed here). pub fn output(p: *Ptys, core: *pardes.Pardes, o: @FieldType(Inbox.Msg, "output")) void { defer p.queue.gpa.free(o.bytes); + defer p.queue.applied(o.pane); if (p.gens[o.pane.index()] == o.gen) core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); } @@ -213,6 +214,11 @@ pub fn takeExits(p: *Ptys, core: *pardes.Pardes) void { host_io.takeExits(core, &p.slots, p, closeWatched); } +/// Whether pane `id` has reads not yet applied (host_io.takeExits). +pub fn unapplied(p: *const Ptys, id: usize) bool { + return p.queue.unapplied[id].load(.acquire) > 0; +} + fn closeWatched(p: *Ptys, id: usize) void { p.close(.at(id)); } @@ -401,3 +407,31 @@ test "a post of an older generation is passed over" { try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); } + +test "a command's exit is told after its output a reader read, however long that waits in the queue" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; + defer queue.deinit(); + var p = testing(&queue); + defer p.deinit(); + // A command done (reaped), its pty held open by what it left running + // (the pipe's write end): no end of file, and no output in the kernel + // once the reader has read it. + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return error.PipeFailed; + defer _ = libc.close(fds[1]); + p.slots[0] = .{ .fd = fds[0], .pid = 0, .cmd = .{ .watched = true, .fd = fds[0], .exited = true, .status = 0 } }; + p.slots[0].?.reader = try queue.startReader(.{ .handle = fds[0], .flags = .{ .nonblocking = false } }, .at(0), p.gens[0]); + try std.testing.expect(host_io.writeFd(fds[1], "LAST")); + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (queue.len == 0 and std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) try std.testing.io.sleep(.fromMilliseconds(1), .awake); + try std.testing.expectEqual(@as(usize, 1), queue.len); + p.takeExits(core); + try std.testing.expect(!p.slots[0].?.cmd.told); + var batch = queue.take(); + for (batch.slice()) |msg| p.output(core, msg.output); + p.takeExits(core); + try std.testing.expect(p.slots[0].?.cmd.told); +} diff --git a/dev/host_io.zig b/dev/host_io.zig index 0efb37fd..a22bf5ce 100644 --- a/dev/host_io.zig +++ b/dev/host_io.zig @@ -1105,6 +1105,8 @@ pub fn takeExits(core: *pardes.Pardes, ptys: anytype, ctx: anytype, comptime clo for (ptys, 0..) |*slot, id| { const pt = slotPty(slot) orelse continue; if (!pt.cmd.watched or !pt.cmd.due()) continue; + // Its output read and not yet applied (a host whose reader counts). + if (comptime @hasDecl(@TypeOf(ctx.*), "unapplied")) if (!pt.cmd.eof and ctx.unapplied(id)) continue; pt.cmd.told = true; const eof = pt.cmd.eof; core.update(.{ .exited = .{ .pane = .at(id), .status = pt.cmd.status } }); diff --git a/dev/tui/tui.zig b/dev/tui/tui.zig index ecc52df0..86956eb5 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -1463,11 +1463,9 @@ const Shell = struct { // is held for the next wait: `split`). s.takeQueue(); // An exit's wake (a .nop) or output an exit waited behind: told - // here, inside the step, so the frame after it shows it; not while - // reads taken off the queue wait their steps (`takeQueue`): one of - // them may be the command's own last output, which its exit would - // be drawn above (CommandWatch.due cannot see it). - if (s.batch_at == s.batch.len) s.takeExits(); + // here, inside the step, so the frame after it shows it (a read + // still to be applied holds it back: Ptys.unapplied). + s.takeExits(); s.reloadWatched(); } -- cgit v1.3 From c8ac386d8f2404417b6d09af1635e1104bcc66ae Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 20 Nov 2026 10:50:39 -0300 Subject: test: the tty harness ends a case as closing its terminal ends it: Harness.deinit closes the master first, waits on the app for up to 5 s and SIGKILLs and reaps it only after (it SIGKILLed at once and never reaped); the whole process-test on the run's own binaries under a subreaper, before and after: wall 82.7 s (load 8) against 84.7 s (load 9) and 87.4 s (load 15), the processes left 5 s after its end 1 and 1 (cmdexit's own `sleep 30`), 0 of 144 failed each time: nothing measurable, since every tty case runs without a daemon and a hangup is Killed.handle's (the terminal put back, then the signal's own death by raise), which runs no exit hook either, so a language server's group is not killed (lsp_client's killAllAtExit, an atexit) whichever way the case ends; the final tree, this change on the three before it: tui core-test 858/1009 (151 skipped), shell-test 1050/1053, term 17/17, pane 183/184, kitty 45/45, behaviour-test and --replay 275/275, process-test 0 of 144 failed, soak --clients 5 diverged 0, unequal 0, checked/wrong 1874/0 1937/0 1831/0, quiet checks 597/0 673/0 779/0, unlisted 0, corpus 22 of 22, no leak, --bytes --clients 5 diverged 0, unequal 0, corpus 22 of 22, no leak, its one unlisted stop at `now` the base's; gui unit-test 1647/1651 with only BaselineHarnessMismatch; daemon.py plain, --far, --games (keys stopped 0 and 0), --window-clients, --upgrade both ways pass; the macOS library (Linux, aarch64-macos) and FreeBSD tui build; the frame and perf gate against tree2 PASS (77 of 77 frames byte-identical, perfab corpus2x -0.039% with noise 0.080%, perfops 121 counts within 0.1%, the largest +0.0056%) (load 4-17) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/e2e_harness.zig | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig index f7d65b03..26e942e7 100644 --- a/test/e2e_harness.zig +++ b/test/e2e_harness.zig @@ -149,9 +149,25 @@ pub const Harness = struct { return true; } + /// The app ended as closing its terminal ends it: the master closed (its + /// hangup), the app given `end_ms` to end, SIGKILLed only after, and + /// reaped: what it ends at its own end (its shells, its language servers' + /// groups) does not outlive the case. pub fn deinit(self: *Harness) void { - posix.kill(self.pid, posix.SIG.KILL) catch {}; _ = libc.close(self.master); + const end_ms = 5000; + const until = nowMs() + end_ms; + var status: c_int = 0; + var none: [0]posix.pollfd = .{}; + while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) { + if (nowMs() < until) { + _ = posix.poll(&none, 5) catch 0; + continue; + } + posix.kill(self.pid, posix.SIG.KILL) catch {}; + _ = libc.waitpid(self.pid, &status, 0); + break; + } self.stream.deinit(); self.gpa.destroy(self.raw); self.term.deinit(self.gpa); -- cgit v1.3