diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-20 12:36:59 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-20 13:09:56 -0300 |
| commit | 9c50dd0b64ecaa8cbcfd4f76868dc83e5b9636e3 (patch) | |
| tree | 1fd44d101a680ed4ff601c8760d2f6bd4139edc0 | |
| parent | 1374e668fe568ad4f7f70c06156c1ecdbb8840b9 (diff) | |
| parent | c8ac386d8f2404417b6d09af1635e1104bcc66ae (diff) | |
| download | pardes-9c50dd0b64ecaa8cbcfd4f76868dc83e5b9636e3.tar.gz pardes-9c50dd0b64ecaa8cbcfd4f76868dc83e5b9636e3.zip | |
integration: the addons' workers and the daemon's notes once, on the five faults a busy machine showed: pardes-services-3 (jobs, draws, pipes and a search through the session's one queue, their workers the queue's; the daemon's notes the loop's own: eight frontend calls; an Adopt's shells kept room in a full queue; a command's exit told after its reads are applied; the tty harness's end of a case) and pardes-merge36 (pardes-faults-5); two conflicts, both where the daemon's reader starts: the faults made daemon.watch() argument-free with daemon.notesTo, the services gave the loop its own note: daemon.notesTo(&l, note) and daemon.watch(); the terminal frontend's quit arm starts no reader (kept does), and Shell.session, whose one reader that line was, is deleted; tui core-test 861/1016 (155 skipped), shell-test 1058/1061, term-test 17/17, both soaks diverged 0, unequal 0, unlisted 0, the window builds; the coordinator's gate in the ledger (reorg/merge37)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | dev/Inbox.zig | 75 | ||||
| -rw-r--r-- | dev/Ptys.zig | 34 | ||||
| -rw-r--r-- | dev/gui/gui.zig | 79 | ||||
| -rw-r--r-- | dev/host_io.zig | 55 | ||||
| -rw-r--r-- | dev/tui/tui.zig | 140 | ||||
| -rw-r--r-- | runtime/session.zig | 35 | ||||
| -rw-r--r-- | test/e2e_harness.zig | 18 | ||||
| -rw-r--r-- | test/replicas.zig | 1 |
8 files changed, 229 insertions, 208 deletions
diff --git a/dev/Inbox.zig b/dev/Inbox.zig index aac1f7a1..d733b971 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, @@ -63,6 +67,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, @@ -77,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, @@ -101,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(); @@ -114,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); } @@ -189,7 +212,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; @@ -262,9 +285,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); } @@ -291,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 } }); } @@ -311,9 +339,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 +353,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 +392,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/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/gui/gui.zig b/dev/gui/gui.zig index 59e70935..201c23df 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; } @@ -1079,12 +1071,7 @@ 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 { - 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 +1402,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 +1412,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 +1420,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); @@ -2357,8 +2341,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, @@ -2567,10 +2549,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; @@ -2586,33 +2565,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); } @@ -3119,21 +3075,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); } @@ -3184,7 +3125,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); } @@ -3192,13 +3133,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); } @@ -5982,7 +5923,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, @@ -6014,11 +5954,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); } } @@ -7682,9 +7622,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..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 } }); @@ -2265,11 +2267,62 @@ 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()); } +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 "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 e699745a..e5e28f6e 100644 --- a/dev/tui/tui.zig +++ b/dev/tui/tui.zig @@ -97,15 +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 pane's output, a -/// worker's answer, a wake. +/// 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). @@ -120,14 +119,7 @@ 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, /// A replica's reader posted: the step boundary takes it in. replica_mail, /// A replica client's: what the session streamed (replica.Link). @@ -369,8 +361,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 +750,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 +773,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; @@ -1001,19 +993,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 => {}, }; o.screen.art.deinit(gpa); @@ -1049,14 +1030,9 @@ 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; - sh.pipe_tasks.cancelAll(io); // One view, the terminal's (host_io.restoreCore). const live = o.screen; stopInput(io, &live.thread); @@ -1085,24 +1061,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 { @@ -1140,8 +1098,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, @@ -1511,11 +1467,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(); } @@ -1593,11 +1547,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; }, @@ -1653,27 +1602,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; } @@ -1882,7 +1810,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. @@ -1910,8 +1839,14 @@ 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; + }, + .adopted => |a| s.ptys.adoptions.adoptShell(s.core, a.pid, a.fd), + .fs_ready => {}, + else => s.ptys.queue.land(s.core, m), } } } @@ -1966,50 +1901,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); } }; @@ -2758,7 +2672,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 93b72deb..e4eb0300 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). @@ -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). @@ -90,6 +88,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); @@ -100,7 +100,7 @@ pub fn Loop(comptime Frontend: type) type { l.host = try fe.open(&l); defer fe.close(&l); - daemon.notesTo(l.fe, note); + daemon.notesTo(&l, note); defer l.peers.deinit(); // Before the core goes: each client sees its link end. defer l.peers.dropAll(l.core); @@ -155,7 +155,7 @@ 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 { @@ -163,9 +163,20 @@ pub fn Loop(comptime Frontend: type) type { daemon.watch(); } + /// 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 @@ -174,7 +185,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; 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); 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 {} |
