summaryrefslogtreecommitdiff
path: root/src/host/control.zig
blob: 33b186b3afaaa8950199ff1152d8a6b45c694d2c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Local 9P controls, serviced on the frame thread: no SDL or state races.
const std = @import("std");
const c9 = @import("cloud9");
const c = @import("c");
const Host = @import("Host.zig");
const Presentation = @import("Presentation.zig");
const fs = c9.fs;
const transport = c9.transport;
const Backend = struct {
    pub const Req = fs.Req;
    pub const Reply = fs.Reply;
};
const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 });
const msize = 16384;
/// The files, a row each: what lookup, readdir and getattr answer. A
/// file's node is its number here.
const File = enum(u64) { @"/" = 1, ctl, status, log, @"screen.png", profile, @"profile-trace", @"timing-trace", @"presentation-trace" };
const files = std.enums.EnumArray(File, struct { mode: u16 = 0o400, doc: []const u8 }).init(.{
    .@"/" = .{ .mode = 0o700, .doc = "" },
    .ctl = .{ .mode = 0o600, .doc = "write console lines, a line each; screenshot captures the next frame, profile-reset clears profile" },
    .status = .{ .doc = "name, canvas size, playback mode, gpu, and the screenshot's state" },
    .log = .{ .doc = "the console's last five lines" },
    .@"screen.png" = .{ .doc = "the frame screenshot captured, as PNG; each open pins its own copy" },
    .profile = .{ .doc = "with --profile-gpu: label, count, mean, worst, p95 and p99 ms, tab-separated" },
    .@"profile-trace" = .{ .doc = "with --profile-gpu: label,sample,ns, the samples kept, as CSV" },
    .@"timing-trace" = .{ .doc = "index,frame_ns,work_ns,outside_work_ns, the frames kept, as CSV" },
    .@"presentation-trace" = .{ .doc = "on Wayland: presentation feedback per frame, as CSV" },
});

/// The verbs `ctl` takes beside the console's lines.
const Verb = enum { screenshot, @"profile-reset" };
const verbs = std.enums.EnumArray(Verb, []const u8).init(.{
    .screenshot = "captures the next frame for screen.png",
    .@"profile-reset" = "clears profile's counters and frame count, keeping its labels",
});

const Connection = struct {
    fd: c_int = -1,
    server: Server = undefined,
    input: [msize]u8 = undefined,
    output: [msize * 2]u8 = undefined,
    incoming: [msize]u8 = undefined,
    used: usize = 0,
    snapshots: [32]?[]u8 = @splat(null),

    fn close(self: *Connection, a: std.mem.Allocator) void {
        if (self.fd < 0) return;
        transport.close(self.fd);
        for (&self.snapshots) |*snapshot| if (snapshot.*) |bytes| {
            a.free(bytes);
            snapshot.* = null;
        };
        self.fd = -1;
    }
};

pub const Control = struct {
    allocator: std.mem.Allocator,
    path: [:0]u8,
    listener: c_int,
    connections: [4]Connection = @splat(.{}),
    png: []u8 = &.{},
    capture_pending: bool = false,
    generation: u64 = 0,
    capture_error: ?anyerror = null,

    pub fn init(a: std.mem.Allocator, path: []const u8) !*Control {
        const self = try a.create(Control);
        errdefer a.destroy(self);
        const z = try a.dupeSentinel(u8, path, 0);
        errdefer a.free(z);
        // Refuse an existing path; never unlink another process's socket.
        const fd = try transport.listenFd(.{ .unix = z }, 4);
        errdefer {
            transport.close(fd);
            _ = std.c.unlink(z);
        }
        if (std.c.chmod(z, 0o600) != 0) return error.SocketPermissions;
        self.* = .{ .allocator = a, .path = z, .listener = fd };
        return self;
    }

    pub fn deinit(self: *Control) void {
        for (&self.connections) |*conn| conn.close(self.allocator);
        transport.close(self.listener);
        _ = std.c.unlink(self.path);
        self.allocator.free(self.path);
        self.allocator.free(self.png);
        self.allocator.destroy(self);
    }

    pub fn poll(self: *Control, host: *Host) void {
        if (transport.acceptFd(self.listener, false) catch null) |fd| {
            var accepted = false;
            for (&self.connections) |*conn| if (conn.fd < 0) {
                conn.fd = fd;
                conn.used = 0;
                conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 });
                accepted = true;
                break;
            };
            if (!accepted) transport.close(fd);
        }
        for (&self.connections) |*conn| {
            if (conn.fd < 0) continue;
            self.service(host, conn) catch conn.close(self.allocator);
        }
    }

    fn service(self: *Control, host: *Host, conn: *Connection) !void {
        // Bound work per frame, including clients which continually write.
        for (0..32) |_| {
            var progressed = false;
            if (conn.used != 0) {
                const consumed = conn.server.push(conn.incoming[0..conn.used]);
                std.mem.copyForwards(u8, &conn.incoming, conn.incoming[consumed..conn.used]);
                conn.used -= consumed;
                progressed = consumed != 0;
            }
            while (conn.server.next()) |req| self.answer(host, conn, req);
            if (conn.server.protocol.dead) return error.Closed;
            if (conn.server.output().len > 0) {
                if (try transport.write(conn.fd, conn.server.output())) |n| {
                    if (n == 0) return error.Closed;
                    conn.server.wrote(n);
                    progressed = true;
                }
            }
            if (conn.used < conn.incoming.len) {
                if (try transport.read(conn.fd, conn.incoming[conn.used..])) |n| {
                    if (n == 0) return error.Closed;
                    conn.used += n;
                    progressed = true;
                }
            }
            if (!progressed) break;
        }
    }

    fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void {
        var reply: fs.Reply = .{ .tag = req.tag };
        var buffer: [msize]u8 = undefined;
        const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: {
            reply = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) };
            break :blk &.{};
        };
        conn.server.reply(&reply, bytes);
    }

    fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 {
        const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile;
        switch (req.op) {
            .lookup => {
                if (file != .@"/") return error.NotDirectory;
                const found = std.meta.stringToEnum(File, req.data) orelse return error.UnknownFile;
                if (found == .@"/") return error.UnknownFile;
                reply.attr = self.attr(@backingInt(found));
            },
            .getattr => reply.attr = self.attr(req.node),
            .open => {
                if (file == .@"screen.png" or file == .@"profile-trace" or file == .@"timing-trace" or file == .@"presentation-trace") {
                    if (file == .@"screen.png") {
                        if (self.capture_pending) return error.CapturePending;
                        if (self.capture_error) |err| return err;
                        if (self.png.len == 0) return error.CaptureScreenshotFirst;
                    }
                    for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
                        slot.* = switch (file) {
                            .@"screen.png" => try self.allocator.dupe(u8, self.png),
                            .@"profile-trace" => try self.trace(host),
                            .@"timing-trace" => try self.timingTrace(host),
                            else => try self.presentationTrace(host),
                        };
                        reply.handle = @intCast(handle);
                        return &.{};
                    };
                    return error.TooManySnapshots;
                }
            },
            .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) {
                const slot = &conn.snapshots[req.handle - 1];
                if (slot.*) |bytes| self.allocator.free(bytes);
                slot.* = null;
            },
            .readdir => {
                if (file != .@"/") return error.NotDirectory;
                var used: usize = 0;
                for (std.enums.values(File)[1..], 0..) |f, index| {
                    if (index < req.off) continue;
                    const name = @tagName(f);
                    std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little);
                    buffer[used + 8] = 0;
                    buffer[used + 9] = @intCast(name.len);
                    @memcpy(buffer[used + 10 ..][0..name.len], name);
                    used += 10 + name.len;
                }
                return buffer[0..used];
            },
            .read => {
                var writer: std.Io.Writer = .fixed(buffer);
                const bytes: []const u8 = switch (file) {
                    .ctl => "Write one console command per line. screenshot captures the next frame.\n",
                    .status => blk: {
                        try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" });
                        break :blk writer.buffered();
                    },
                    .log => blk: {
                        for (host.console.lines) |line| {
                            try writer.writeAll(line.bytes[0..line.len]);
                            try writer.writeByte('\n');
                        }
                        break :blk writer.buffered();
                    },
                    .@"screen.png", .@"profile-trace", .@"timing-trace", .@"presentation-trace" => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
                    .profile => blk: {
                        const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
                        const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
                        try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame});
                        var entries = profile.entries.iterator();
                        while (entries.next()) |entry| {
                            const value = entry.value_ptr;
                            const percentiles = value.percentiles();
                            const count: f64 = @floatFromInt(@max(value.count, 1));
                            try writer.print("{s}\t{d}\t{d:.6}\t{d:.6}\t{d:.6}\t{d:.6}\n", .{ entry.key_ptr.*, value.count, @as(f64, @floatFromInt(value.total)) / count / std.time.ns_per_ms, @as(f64, @floatFromInt(value.worst)) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[0])) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[1])) / std.time.ns_per_ms });
                        }
                        break :blk writer.buffered();
                    },
                    .@"/" => return error.NotFile,
                };
                return window(bytes, req.off, req.size);
            },
            .write => {
                if (file != .ctl) return error.ReadOnly;
                if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand;
                var lines = std.mem.tokenizeScalar(u8, req.data, '\n');
                while (lines.next()) |raw| {
                    const line = std.mem.trim(u8, raw, " \t\r");
                    const verb = std.meta.stringToEnum(Verb, line) orelse {
                        try host.runLine(line, c.SDL_GetTicksNS());
                        continue;
                    };
                    switch (verb) {
                        .screenshot => {
                            self.capture_pending = true;
                            self.capture_error = null;
                        },
                        .@"profile-reset" => {
                            const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
                            const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
                            for (profile.entries.values()) |*entry| entry.* = .{};
                            profile.start_frame = gpu.frame;
                        },
                    }
                }
                reply.written = @intCast(req.data.len);
            },
            .setattr => {
                if (file != .ctl or !req.truncate) return error.ReadOnly;
                reply.attr = self.attr(req.node);
            },
        }
        return &.{};
    }

    fn trace(self: *Control, host: *Host) ![]u8 {
        const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
        const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
        const buffer = try self.allocator.alloc(u8, 256 << 10);
        defer self.allocator.free(buffer);
        var writer: std.Io.Writer = .fixed(buffer);
        try writer.writeAll("label,sample,ns\n");
        var entries = profile.entries.iterator();
        while (entries.next()) |entry| {
            const value = entry.value_ptr;
            for (0..value.retained()) |i| {
                try writer.writeByte('"');
                for (entry.key_ptr.*) |ch| {
                    if (ch == '"') try writer.writeByte('"');
                    try writer.writeByte(ch);
                }
                try writer.print("\",{d},{d}\n", .{ value.count - value.retained() + i + 1, value.sample(i) });
            }
        }
        return self.allocator.dupe(u8, writer.buffered());
    }

    fn timingTrace(self: *Control, host: *const Host) ![]u8 {
        var csv: std.ArrayList(u8) = .empty;
        errdefer csv.deinit(self.allocator);
        try csv.appendSlice(self.allocator, "index,frame_ns,work_ns,outside_work_ns\n");
        for (0..host.timing.count) |i| {
            const sample = host.timing.sampleAt(i);
            try csv.print(self.allocator, "{d},{d},{d},{d}\n", .{ i, sample.frame, sample.work, sample.frame -| sample.work });
        }
        return csv.toOwnedSlice(self.allocator);
    }

    fn presentationTrace(self: *Control, host: *const Host) ![]u8 {
        var csv: std.Io.Writer.Allocating = .init(self.allocator);
        defer csv.deinit();
        try Presentation.csv(host.presentation, &csv.writer);
        if (csv.written().len > 2 << 20) return error.TraceTooLarge;
        return csv.toOwnedSlice();
    }

    fn attr(self: *Control, node: u64) fs.Attr {
        const file: File = @fromBackingInt(@intCast(node));
        return .{ .name = @tagName(file), .node = node, .dir = file == .@"/", .mode = files.get(file).mode, .size = if (file == .@"screen.png") self.png.len else 0, .version = if (file == .@"screen.png") @truncate(self.generation) else 0 };
    }

    pub fn capture(self: *Control, surface: *c.SDL_Surface) void {
        self.capture_pending = false;
        self.save(surface) catch |err| {
            self.capture_error = err;
        };
    }

    fn save(self: *Control, surface: *c.SDL_Surface) !void {
        const stream = c.SDL_IOFromDynamicMem() orelse return error.CaptureStream;
        defer _ = c.SDL_CloseIO(stream);
        if (!c.SDL_SavePNG_IO(surface, stream, false)) return error.EncodePng;
        const size = c.SDL_GetIOSize(stream);
        if (size <= 0) return error.EncodePng;
        const pointer = c.SDL_GetPointerProperty(c.SDL_GetIOProperties(stream), c.SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, null) orelse return error.EncodePng;
        const png = try self.allocator.dupe(u8, @as([*]const u8, @ptrCast(pointer))[0..@intCast(size)]);
        self.allocator.free(self.png);
        self.png = png;
        self.generation += 1;
    }
};

fn window(bytes: []const u8, offset: u64, count: u32) []const u8 {
    if (offset >= bytes.len) return &.{};
    const start: usize = @intCast(offset);
    return bytes[start..][0..@min(count, bytes.len - start)];
}

test "9P reads respect offsets, counts and EOF" {
    try std.testing.expectEqualStrings("cd", window("abcdef", 2, 2));
    try std.testing.expectEqualStrings("ef", window("abcdef", 4, 200));
    try std.testing.expectEqualStrings("", window("abcdef", std.math.maxInt(u64), 10));
}

test "control writes validate and screenshot opens pin an immutable snapshot" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined; // These backend operations do not access the host.
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [256]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .setattr, .node = 2, .truncate = true }, &reply, &buf);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 3, .data = "screenshot" }, &reply, &buf));
    try std.testing.expectError(error.InvalidCommand, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\x00" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\n" }, &reply, &buf);
    try std.testing.expect(control.capture_pending);
    try std.testing.expectError(error.CapturePending, control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf));
    control.capture_pending = false;
    control.png = try a.dupe(u8, "first image");
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf);
    const handle = reply.handle;
    a.free(control.png);
    control.png = try a.dupe(u8, "second image");
    defer a.free(control.png);
    const bytes = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 5, .handle = handle, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("first image", bytes);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 5, .handle = handle, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[handle - 1] == null);
}

test "control writes reset profiling counters while retaining labels" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.passes = null;
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [512]u8 = undefined;
    const reset: fs.Req = .{ .tag = 1, .op = .write, .node = 2, .data = "profile-reset\n" };
    try std.testing.expectError(error.ProfilingDisabled, control.respond(&host, &conn, reset, &reply, &buf));
    host.passes = @as(@import("gpu"), undefined);
    const gpu = &host.passes.?;
    gpu.profile = .init(a);
    defer gpu.profile.?.deinit();
    const profile = &gpu.profile.?;
    try profile.entries.put(profile.arena.allocator(), "scene", .{});
    profile.entries.values()[0].add(400_000);
    profile.entries.values()[0].add(600_000);
    gpu.frame = 420;
    const read: fs.Req = .{ .tag = 1, .op = .read, .node = 6, .size = buf.len };
    const before = try control.respond(&host, &conn, read, &reply, &buf);
    try std.testing.expect(std.mem.indexOf(u8, before, "scene\t2\t0.500000\t0.600000") != null);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 7 }, &reply, &buf);
    const trace_handle = reply.handle;
    _ = try control.respond(&host, &conn, reset, &reply, &buf);
    const trace = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 7, .handle = trace_handle, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("label,sample,ns\n\"scene\",1,400000\n\"scene\",2,600000\n", trace);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 7, .handle = trace_handle, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[trace_handle - 1] == null);
    try std.testing.expectEqual(@as(usize, 1), profile.entries.count());
    try std.testing.expectEqual(@as(u64, 0), profile.entries.values()[0].total);
    try std.testing.expectEqual(@as(u64, 420), profile.start_frame);
    const after = try control.respond(&host, &conn, read, &reply, &buf);
    try std.testing.expect(std.mem.indexOf(u8, after, "# frames 0") != null);
    try std.testing.expect(std.mem.indexOf(u8, after, "scene\t0\t0.000000\t0.000000") != null);
}

test "control writes profiling ring retains latest samples and nearest rank percentiles" {
    var entry: @import("gpu").Profile.Entry = .{};
    for (1..4100) |ns| entry.add(ns);
    try std.testing.expectEqual(@as(u64, 4099), entry.count);
    try std.testing.expectEqual(@as(usize, 2048), entry.retained());
    try std.testing.expectEqual(@as(u64, 2052), entry.sample(0));
    try std.testing.expectEqual(@as(u64, 4099), entry.sample(2047));
    try std.testing.expectEqual([2]u64{ 3997, 4079 }, entry.percentiles());
    entry = .{};
    try std.testing.expectEqual(@as(usize, 0), entry.retained());
    try std.testing.expectEqual([2]u64{ 0, 0 }, entry.percentiles());
    entry.add(20);
    try std.testing.expectEqual([2]u64{ 20, 20 }, entry.percentiles());
}

test "control writes reject timing trace mutations and opens pin chronological samples" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.timing = .{};
    for (0..@import("Timing.zig").capacity + 2) |i| host.timing.add(.{ .frame = i + 1, .work = i });
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [256]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "timing-trace" }, &reply, &buf);
    try std.testing.expectEqual(@as(u64, 8), reply.attr.node);
    try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 8, .data = "reset" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
    const first = reply.handle;
    host.timing = .{};
    host.timing.add(.{ .frame = 4, .work = 7 });
    const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = first, .size = 100 }, &reply, &buf);
    try std.testing.expect(std.mem.startsWith(u8, original, "index,frame_ns,work_ns,outside_work_ns\n0,3,2,1\n1,4,3,1\n"));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
    const second = reply.handle;
    const latest = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = second, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("index,frame_ns,work_ns,outside_work_ns\n0,4,7,0\n", latest);
    for ([_]u32{ first, second }) |handle| {
        _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 8, .handle = handle, .opened = true }, &reply, &buf);
        try std.testing.expect(conn.snapshots[handle - 1] == null);
    }
}

test "control writes reject presentation trace mutations and opens own independent snapshots" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.presentation = null;
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [512]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "presentation-trace" }, &reply, &buf);
    try std.testing.expectEqual(@as(u64, 9), reply.attr.node);
    try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 9, .data = "reset" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
    const first = reply.handle;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
    const second = reply.handle;
    try std.testing.expect(conn.snapshots[first - 1].?.ptr != conn.snapshots[second - 1].?.ptr);
    const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = first, .size = 4096 }, &reply, &buf);
    try std.testing.expect(std.mem.startsWith(u8, original, "# status "));
    try std.testing.expect(std.mem.indexOf(u8, original, "disabled_or_allocation_failed") != null);
    try std.testing.expect(std.mem.endsWith(u8, original, "frame_id,sample_ms,commit_ns,result,presented_ns,refresh_ns,sequence,flags\n"));
    try std.testing.expect(std.mem.indexOfScalar(u8, original, 0) == null);
    const expected = try a.dupe(u8, original);
    defer a.free(expected);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = first, .opened = true }, &reply, &buf);
    const retained = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = second, .size = 4096 }, &reply, &buf);
    try std.testing.expectEqualStrings(expected, retained);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = second, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[first - 1] == null and conn.snapshots[second - 1] == null);
}