//! Terminal replies -> the capabilities a session reports (fixtures/terminal-replies.json), through the //! C ABI only: the host feeds the reply bytes as terminal input (ot_session_input_feed), forwards each REPLY //! event to the session (ot_session_control CAPABILITY_RESPONSE) and reads ot_session_get_capabilities, as the //! bindings do. Properties over the table's rows, run with model.zig, name the bug class each one catches. const std = @import("std"); const ot = @import("context_abi_c"); const model = @import("model.zig"); /// OT_CAP_* in bit order. const cap_names = [_][]const u8{ "kitty_keyboard", "kitty_graphics", "rgb", "ansi256", "sgr_pixels", "color_scheme_updates", "explicit_width", "scaled_text", "sixel", "focus_tracking", "sync", "bracketed_paste", "hyperlinks", "osc52", "notifications", "explicit_cursor_positioning", "remote", "program_status", }; const width_names = [_][]const u8{ "wcwidth", "unicode", "no_zwj", "unicode_wide" }; const multiplexer_names = [_][]const u8{ "none", "tmux", "zellij", "screen", "unknown" }; const osc52_names = [_][]const u8{ "unknown", "supported", "unsupported" }; comptime { std.debug.assert(ot.OT_CAP_KITTY_KEYBOARD == 1 and ot.OT_CAP_SIXEL == 1 << 8 and ot.OT_CAP_PROGRAM_STATUS == 1 << (cap_names.len - 1)); } /// Keys a user types between replies; none begins a reply. const keys = [_][]const u8{ "a", "Z", "5", " ", "\x1b[A", "\r" }; const Row = struct { name: []const u8, reads: []const []const u8, expected: []const []const u8, env: []const u8 = "", entries: u32 = 0, remote_mode: u32 = ot.OT_SESSION_REMOTE_REMOTE, alternate: bool = true, pixel: bool = false, /// The host decides whether its row-1 cursor reports are keys (context.keys "host"): only the /// capabilities are pinned. host_keys: bool = false, }; fn loadRows(arena: std.mem.Allocator) ![]Row { const file = try std.json.parseFromSliceLeaky(std.json.Value, arena, @embedFile("fixtures/terminal-replies.json"), .{}); const items = file.object.get("rows").?.array.items; const rows = try arena.alloc(Row, items.len); for (items, rows) |item, *row| { const fields = item.array.items; const reads = try arena.alloc([]const u8, fields[1].array.items.len); for (fields[1].array.items, reads) |read, *out| out.* = read.string; const expected = try arena.alloc([]const u8, fields[2].array.items.len); for (fields[2].array.items, expected) |token, *out| out.* = token.string; row.* = .{ .name = fields[0].string, .reads = reads, .expected = expected }; if (fields.len < 4) continue; const context = fields[3].object; if (context.get("env")) |env| { // The payload of ot_session_attach_renderer_with_env: u32 key and value lengths, then both. var payload: std.ArrayList(u8) = .empty; var entries = env.object.iterator(); while (entries.next()) |entry| { const key = entry.key_ptr.*; const value = entry.value_ptr.string; var lengths: [8]u8 = undefined; std.mem.writeInt(u32, lengths[0..4], @intCast(key.len), .little); std.mem.writeInt(u32, lengths[4..8], @intCast(value.len), .little); try payload.appendSlice(arena, &lengths); try payload.appendSlice(arena, key); try payload.appendSlice(arena, value); row.entries += 1; } row.env = payload.items; } if (context.get("mode")) |mode| { if (!std.mem.eql(u8, mode.string, "auto")) return error.UnknownMode; row.remote_mode = ot.OT_SESSION_REMOTE_AUTO; } if (context.get("screen")) |screen| { if (!std.mem.eql(u8, screen.string, "main")) return error.UnknownScreen; row.alternate = false; } if (context.get("keys")) |owner| { if (!std.mem.eql(u8, owner.string, "host")) return error.UnknownKeys; row.host_keys = true; } if (context.get("pending")) |pending| for (pending.array.items) |query| { if (!std.mem.eql(u8, query.string, "pixel")) return error.UnknownQuery; row.pixel = true; }; } return rows; } fn expectOk(status: ot.ot_status) !void { if (status != ot.OT_OK) { std.debug.print("native status {d}\n", .{status}); return error.NativeStatus; } } /// What the host saw: the capability record, the reply bytes in order, the bytes of typed keys, and /// how many other events (mouse, paste, focus) arrived. const Observation = struct { caps: ot.ot_session_capabilities, replies: []const u8, keys: []const u8, other: u32, }; /// One session that a host set up with the row's environment as the bindings do (alternate screen unless the /// row asks for the main screen, Kitty keyboard, the DA1 reply sentinel), then fed the replies. const Host = struct { context: *ot.ot_context, session: ot.ot_handle, arena: std.mem.Allocator, now: u64 = 1, expect: u32, /// The expectation once the sentinel's DA1 reply arrived or the host stopped waiting for it. after: u32, replies: std.ArrayList(u8) = .empty, keys: std.ArrayList(u8) = .empty, other: u32 = 0, records: [16]ot.ot_input_event = undefined, payload: [ot.OT_INPUT_PAYLOAD_BYTES_MIN]u8 = undefined, fn open(context: *ot.ot_context, arena: std.mem.Allocator, row: Row) !*Host { var session: ot.ot_handle = undefined; const session_options: ot.ot_session_options = .{ .struct_size = @sizeOf(ot.ot_session_options), .abi_version = ot.OT_CONTEXT_ABI_VERSION, .chunk_size = ot.OT_SESSION_CONTROL_PACKET_BYTES, .span_capacity = 8, .max_bytes = 8 * ot.OT_SESSION_CONTROL_PACKET_BYTES, .control_capacity = ot.OT_SESSION_CONTROL_PACKET_BYTES, .reserved = 0, }; try expectOk(ot.ot_session_create(context, &session_options, &session)); const host = try arena.create(Host); // Core keeps expecting replies while its pixel query waits (stdin-parser-native.ts expectationFlags). const after: u32 = if (row.pixel) ot.OT_INPUT_EXPECT_REPLIES else 0; host.* = .{ .context = context, .session = session, .arena = arena, .expect = ot.OT_INPUT_EXPECT_SENTINEL | ot.OT_INPUT_EXPECT_CURSOR_POSITION | after, .after = after }; errdefer host.close(); const renderer: ot.ot_session_renderer_env_options = .{ .struct_size = @sizeOf(ot.ot_session_renderer_env_options), .abi_version = ot.OT_CONTEXT_ABI_VERSION, .width = 20, .height = 4, .remote_mode = row.remote_mode, .entry_count = row.entries, .byte_count = @intCast(row.env.len), .reserved = 0, }; try expectOk(ot.ot_session_attach_renderer_with_env(context, &host.session, &renderer, if (row.env.len == 0) null else row.env.ptr)); const terminal: ot.ot_session_terminal_options = .{ .struct_size = @sizeOf(ot.ot_session_terminal_options), .abi_version = ot.OT_CONTEXT_ABI_VERSION, .flags = ot.OT_TERMINAL_REPLY_SENTINEL | if (row.alternate) ot.OT_TERMINAL_ALTERNATE_SCREEN else 0, .kitty_keyboard_flags = ot.OT_KITTY_KEYBOARD_DISAMBIGUATE, }; try expectOk(ot.ot_session_setup_terminal(context, &host.session, &terminal)); try host.pump(); var phase: u32 = 0; try expectOk(ot.ot_session_get_terminal_state(context, &host.session, &phase)); if (phase != ot.OT_TERMINAL_ACTIVE) return error.SetupNotActive; if (row.pixel) try host.control(ot.OT_CONTROL_QUERY_PIXEL_RESOLUTION, 0, ""); try expectOk(ot.ot_session_input_expect(context, &host.session, host.expect)); return host; } fn close(self: *Host) void { _ = ot.ot_session_cancel(self.context, &self.session); expectOk(ot.ot_session_destroy(self.context, &self.session)) catch unreachable; } /// Runs the session's work and delivers its output until it waits for nothing or only for time. fn pump(self: *Host) !void { var bytes: [ot.OT_SESSION_CONTROL_PACKET_BYTES]u8 = undefined; for (0..4096) |_| { var result = std.mem.zeroes(ot.ot_session_pump_result); result.struct_size = @sizeOf(ot.ot_session_pump_result); result.abi_version = ot.OT_CONTEXT_ABI_VERSION; try expectOk(ot.ot_session_pump(self.context, &self.session, self.now, 64, &result)); switch (result.status) { ot.OT_PUMP_IDLE, ot.OT_PUMP_WAIT_UNTIL, ot.OT_PUMP_CLOSED => return, ot.OT_PUMP_AGAIN => {}, ot.OT_PUMP_OUTPUT_PENDING => { var ticket: ot.ot_output_ticket = undefined; try expectOk(ot.ot_session_read_output(self.context, &self.session, &bytes, bytes.len, &ticket)); try expectOk(ot.ot_session_complete_output(self.context, &self.session, &ticket, 1)); }, else => return error.UnknownPump, } } return error.PumpBound; } fn control(self: *Host, kind: u32, argument: u32, bytes: []const u8) !void { const options: ot.ot_session_control_options = .{ .struct_size = @sizeOf(ot.ot_session_control_options), .abi_version = ot.OT_CONTEXT_ABI_VERSION, .kind = kind, .argument = argument, .reserved = 0, }; const status = ot.ot_session_control(self.context, &self.session, &options, if (bytes.len == 0) null else bytes.ptr, @intCast(bytes.len)); // The session validates capability replies; one it does not know (a color, a pixel size) is not one. if (!(kind == ot.OT_CONTROL_CAPABILITY_RESPONSE and status == ot.OT_INVALID_ARGUMENT)) try expectOk(status); try self.pump(); } /// One read of terminal input. fn feed(self: *Host, bytes: []const u8) !void { var offset: usize = 0; while (true) { var drain = std.mem.zeroes(ot.ot_input_drain); drain.struct_size = @sizeOf(ot.ot_input_drain); drain.abi_version = ot.OT_CONTEXT_ABI_VERSION; const rest = bytes[offset..]; try expectOk(ot.ot_session_input_feed(self.context, &self.session, if (rest.len == 0) null else rest.ptr, @intCast(rest.len), self.now, &self.records, self.records.len, &self.payload, self.payload.len, &drain)); // Copy the events out first: forwarding a reply calls into the session again. const events = try self.arena.dupe(ot.ot_input_event, self.records[0..drain.count]); const payload = try self.arena.dupe(u8, self.payload[0..drain.payload_len]); for (events) |record| try self.take(record, payload); offset += drain.consumed; if (offset == bytes.len or (drain.consumed == 0 and drain.count == 0)) break; } if (offset != bytes.len) return error.InputNotConsumed; } fn take(self: *Host, record: ot.ot_input_event, payload: []const u8) !void { const raw = payload[record.raw_offset..][0..record.raw_len]; switch (record.kind) { ot.OT_INPUT_REPLY => { try self.replies.appendSlice(self.arena, raw); try self.control(ot.OT_CONTROL_CAPABILITY_RESPONSE, 0, raw); // The sentinel's DA1 reply ends the startup replies. if (self.expect & ot.OT_INPUT_EXPECT_SENTINEL != 0 and replyKey(raw).kind == .da1) { self.expect = self.after; try expectOk(ot.ot_session_input_expect(self.context, &self.session, self.expect)); } }, ot.OT_INPUT_KEY => try self.keys.appendSlice(self.arena, raw), else => self.other += 1, } } /// The host stops waiting for the sentinel (its DA1 never came), and the input timeout passes. fn stopWaiting(self: *Host) !void { try self.control(ot.OT_CONTROL_END_REPLY_SENTINEL, 0, ""); self.expect = self.after; try expectOk(ot.ot_session_input_expect(self.context, &self.session, self.expect)); self.now += ot.OT_INPUT_TIMEOUT_NS; try self.feed(""); } /// Lets the timeout pass, so nothing the parser holds stays hidden, and reads the capabilities. fn observe(self: *Host) !Observation { self.now += ot.OT_INPUT_TIMEOUT_NS; try self.feed(""); var caps = std.mem.zeroes(ot.ot_session_capabilities); caps.struct_size = @sizeOf(ot.ot_session_capabilities); caps.abi_version = ot.OT_CONTEXT_ABI_VERSION; try expectOk(ot.ot_session_get_capabilities(self.context, &self.session, &caps)); return .{ .caps = caps, .replies = self.replies.items, .keys = self.keys.items, .other = self.other }; } }; const ReplyKind = enum { cpr, da1, decrpm, kitty_keyboard, csi, xtversion, xtgettcap, kitty_graphics, osc }; /// A complete reply's kind, with the parameter that tells two replies of one kind apart (a DEC mode, an /// XTGETTCAP name, an OSC number). const ReplyKey = struct { kind: ReplyKind, detail: []const u8 = "" }; fn replyKey(raw: []const u8) ReplyKey { if (std.mem.startsWith(u8, raw, "\x1b[")) { const final = raw[raw.len - 1]; if (raw.len > 3 and raw[2] == '?') { if (final == 'c') return .{ .kind = .da1 }; if (final == 'u') return .{ .kind = .kitty_keyboard }; if (final == 'y') return .{ .kind = .decrpm, .detail = raw[3 .. std.mem.findScalar(u8, raw, ';') orelse raw.len] }; } if (final == 'R') return .{ .kind = .cpr }; return .{ .kind = .csi, .detail = raw[raw.len - 1 ..] }; } if (std.mem.startsWith(u8, raw, "\x1bP>|")) return .{ .kind = .xtversion }; // The other DCS replies are XTGETTCAP's (n+r name=value); the APC replies, Kitty graphics'. if (std.mem.startsWith(u8, raw, "\x1bP")) { const body = raw[@min(raw.len - 2, 5) .. raw.len - 2]; return .{ .kind = .xtgettcap, .detail = body[0 .. std.mem.findScalar(u8, body, '=') orelse body.len] }; } if (std.mem.startsWith(u8, raw, "\x1b_")) return .{ .kind = .kitty_graphics }; return .{ .kind = .osc, .detail = raw[2 .. std.mem.findScalar(u8, raw, ';') orelse 2] }; } /// Whether two replies may arrive in either order with the same capabilities: replies of different kinds, except /// cursor reports and DA1, which the session reads in order (the sentinel's DA1 ends the startup reports). /// Replies of one kind keep their order: a later XTVERSION replaces the identity, a later report answers the /// next probe. fn independent(a: []const u8, b: []const u8) bool { const x = replyKey(a); const y = replyKey(b); if (x.kind == y.kind and std.ascii.eqlIgnoreCase(x.detail, y.detail)) return false; const ordered = [_]ReplyKind{ .cpr, .da1 }; return !(std.mem.findScalar(ReplyKind, &ordered, x.kind) != null and std.mem.findScalar(ReplyKind, &ordered, y.kind) != null); } /// The end of the first complete reply at the start of `bytes`. fn replyEnd(bytes: []const u8) usize { std.debug.assert(bytes.len >= 3 and bytes[0] == 0x1b); if (bytes[1] == '[') { var end: usize = 2; while (end < bytes.len and bytes[end] >= 0x20 and bytes[end] <= 0x3f) : (end += 1) {} return end + 1; } const bel = if (bytes[1] == ']') std.mem.findScalar(u8, bytes, 0x07) else null; const st = std.mem.find(u8, bytes, "\x1b\\"); if (bel != null and (st == null or bel.? < st.?)) return bel.? + 1; return st.? + 2; } /// The row's expected tokens against an observation; "unchanged" compares with a session that saw no reply. fn expectTokens(row: Row, caps: ot.ot_session_capabilities, baseline: ot.ot_session_capabilities) !void { for (row.expected) |token| { const ok = ok: { if (std.mem.eql(u8, token, "unchanged")) break :ok std.meta.eql(caps, baseline); if (token[0] == '+' or token[0] == '-') { const name = token[1..]; if (std.mem.eql(u8, name, "xtversion")) break :ok (caps.term_from_xtversion != 0) == (token[0] == '+'); const index = for (cap_names, 0..) |cap, index| { if (std.mem.eql(u8, cap, name)) break index; } else return error.UnknownCapability; break :ok (caps.flags & (@as(u32, 1) << @intCast(index)) != 0) == (token[0] == '+'); } const equals = std.mem.findScalar(u8, token, '=') orelse return error.UnknownToken; const key = token[0..equals]; const value = token[equals + 1 ..]; if (std.mem.eql(u8, key, "name")) break :ok std.mem.eql(u8, caps.term_name[0..caps.term_name_len], value); if (std.mem.eql(u8, key, "version")) break :ok std.mem.eql(u8, caps.term_version[0..caps.term_version_len], value); const names: []const []const u8, const field: u32 = if (std.mem.eql(u8, key, "width")) .{ &width_names, caps.width_method } else if (std.mem.eql(u8, key, "multiplexer")) .{ &multiplexer_names, caps.multiplexer } else if (std.mem.eql(u8, key, "osc52")) .{ &osc52_names, caps.osc52_support } else return error.UnknownToken; break :ok field < names.len and std.mem.eql(u8, names[field], value); }; if (!ok) { std.debug.print("terminal replies row \"{s}\": {s} does not hold; flags {b}, width {d}, multiplexer {d}, osc52 {d}, name \"{s}\", version \"{s}\"\n", .{ row.name, token, caps.flags, caps.width_method, caps.multiplexer, caps.osc52_support, caps.term_name[0..caps.term_name_len], caps.term_version[0..caps.term_version_len], }); return error.TestUnexpectedResult; } } } fn createContext() !*ot.ot_context { const options: ot.ot_context_options = .{ .struct_size = @sizeOf(ot.ot_context_options), .abi_version = ot.OT_CONTEXT_ABI_VERSION, .flags = 0, .object_capacity = 8, .render_cells_max = 256, .reserved = .{ 0, 0, 0 }, }; var context: ?*ot.ot_context = null; try expectOk(ot.ot_context_create(&options, &context)); return context.?; } /// One run of a row: `reads` arrive while the host waits for the replies, `late` after it stopped waiting. fn runRow(context: *ot.ot_context, arena: std.mem.Allocator, row: Row, reads: []const []const u8, late: []const []const u8) !Observation { const host = try Host.open(context, arena, row); defer host.close(); for (reads) |read| try host.feed(read); if (late.len > 0) { try host.stopWaiting(); for (late) |read| try host.feed(read); } return host.observe(); } test "terminal replies: each conformance row's replies give its capabilities through the C ABI" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const rows = try loadRows(arena); try std.testing.expect(rows.len > 0); const context = try createContext(); defer expectOk(ot.ot_context_destroy(context)) catch unreachable; var failures: usize = 0; for (rows) |row| checkRow(context, arena, row) catch { failures += 1; }; try std.testing.expectEqual(0, failures); } fn checkRow(context: *ot.ot_context, arena: std.mem.Allocator, row: Row) !void { const observed = try runRow(context, arena, row, row.reads, &.{}); // Every byte of a row is a reply: none is typed, and the parser drops none. const bytes = try std.mem.concat(arena, u8, row.reads); if (!row.host_keys and !std.mem.eql(u8, observed.replies, bytes) or observed.keys.len != 0 or observed.other != 0) { std.debug.print("terminal replies row \"{s}\": replies {f}, keys {f}, {d} other events\n", .{ row.name, std.ascii.hexEscape(observed.replies, .lower), std.ascii.hexEscape(observed.keys, .lower), observed.other }); return error.TestUnexpectedResult; } try expectTokens(row, observed.caps, (try runRow(context, arena, row, &.{}, &.{})).caps); } /// Each property changes one thing about how a row's replies arrive; its name is the bug class it catches. const Property = enum { /// A reply cut across reads is dropped, typed, or read as two replies. @"split reply", /// A key typed between replies is swallowed, or a reply comes out as a key. @"reply leaks as key", /// The capabilities depend on the arrival order of replies the contract treats as independent. @"order of independent replies", /// A reply that arrives whole after the host stopped waiting for the sentinel is dropped or typed. The /// contract: the session still applies it (Core and the Rust host forward every reply, also late ones). @"late reply", }; const Step = union(enum) { /// The table row the history replays; the first command of every history. row: u16, /// Cut the on-time stream at this offset (modulo its length) into another read. cut: u16, /// Type keys[key] before reply `at` (modulo the reply count plus one). key: struct { at: u16, key: u8 }, /// Swap reply `at` with the next one when they are independent. swap: u16, /// Replies from `at` on arrive after the host stopped waiting, each in one read. late: u16, }; const Model = struct { pub const Command = Step; context: *ot.ot_context, arena: std.mem.Allocator, rows: []const Row, property: Property, /// Per row: its replies (every byte of a row is one; replyEnd splits them, not the parser under test) and /// the capabilities they gave when they arrived as the row's reads. references: []?Reference, const Reference = struct { replies: []const []const u8, caps: ot.ot_session_capabilities, cpr: bool }; fn reference(self: *Model, index: usize) !Reference { if (self.references[index]) |cached| return cached; const row = self.rows[index]; const host = try Host.open(self.context, self.arena, row); defer host.close(); var replies: std.ArrayList([]const u8) = .empty; var cpr = false; for (row.reads) |read| try host.feed(read); const observed = try host.observe(); var rest = try std.mem.concat(self.arena, u8, row.reads); while (rest.len > 0) { const end = replyEnd(rest); try replies.append(self.arena, rest[0..end]); cpr = cpr or replyKey(rest[0..end]).kind == .cpr; rest = rest[end..]; } self.references[index] = .{ .replies = replies.items, .caps = observed.caps, .cpr = cpr }; return self.references[index].?; } pub fn generate(self: *Model, arena: std.mem.Allocator, random: std.Random, steps: usize) ![]Command { const commands = try arena.alloc(Command, steps); commands[0] = .{ .row = random.uintLessThan(u16, @intCast(self.rows.len)) }; for (commands[1..]) |*command| { const at = random.int(u16); const key: Command = .{ .key = .{ .at = at, .key = random.uintLessThan(u8, keys.len) } }; command.* = switch (self.property) { .@"split reply" => .{ .cut = at }, .@"reply leaks as key" => if (random.boolean()) .{ .cut = at } else key, .@"order of independent replies" => .{ .swap = at }, .@"late reply" => if (random.uintLessThan(u8, 4) == 0) .{ .late = at } else key, }; } return commands; } pub fn run(self: *Model, arena: std.mem.Allocator, commands: []const Command) !?model.Failure { // A shrunk history keeps its row: without one there is nothing to replay. if (commands.len == 0 or commands[0] != .row) return null; const index: usize = commands[0].row % self.rows.len; const ref = try self.reference(index); const replies = try arena.dupe([]const u8, ref.replies); // typed[i]: the keys before reply i; typed[replies.len]: after the last. const typed = try arena.alloc(std.ArrayList(u8), replies.len + 1); @memset(typed, .empty); var late = replies.len; var cuts: std.ArrayList(usize) = .empty; for (commands) |command| switch (command) { .row => {}, .swap => |at| if (replies.len > 1) { const i = at % (replies.len - 1); if (independent(replies[i], replies[i + 1])) { std.mem.swap([]const u8, &replies[i], &replies[i + 1]); model.count("swap"); } }, .key => |key| { try typed[key.at % typed.len].appendSlice(arena, keys[key.key]); model.count("key"); }, .cut => |at| try cuts.append(arena, at), // Cursor reports answer the setup's own probes, which a host that stopped waiting no longer reads. .late => |at| if (!ref.cpr and replies.len > 0) { late = @min(late, at % replies.len); }, }; if (late < replies.len) model.count("late"); var stream: std.ArrayList(u8) = .empty; var reply_ends: std.ArrayList([2]usize) = .empty; for (replies[0..late], typed[0..late]) |reply, key| { try stream.appendSlice(arena, key.items); try reply_ends.append(arena, .{ stream.items.len, stream.items.len + reply.len }); try stream.appendSlice(arena, reply); } if (late == replies.len) try stream.appendSlice(arena, typed[replies.len].items); var points: std.ArrayList(usize) = .empty; if (stream.items.len > 1) for (cuts.items) |at| try points.append(arena, 1 + at % (stream.items.len - 1)); std.mem.sort(usize, points.items, {}, std.sort.asc(usize)); var reads: std.ArrayList([]const u8) = .empty; var start: usize = 0; for (points.items) |point| { if (point == start) continue; for (reply_ends.items) |span| { if (point > span[0] and point < span[1]) model.count("cut inside a reply"); } try reads.append(arena, stream.items[start..point]); start = point; } try reads.append(arena, stream.items[start..]); var late_reads: std.ArrayList([]const u8) = .empty; for (replies[late..], typed[late..replies.len]) |reply, key| { if (key.items.len > 0) try late_reads.append(arena, key.items); try late_reads.append(arena, reply); } if (late < replies.len and typed[replies.len].items.len > 0) try late_reads.append(arena, typed[replies.len].items); const observed = try runRow(self.context, arena, self.rows[index], reads.items, late_reads.items); for (replies) |reply| model.count(@tagName(replyKey(reply).kind)); var expected_replies: std.ArrayList(u8) = .empty; var expected_keys: std.ArrayList(u8) = .empty; for (replies, typed[0..replies.len]) |reply, key| { try expected_keys.appendSlice(arena, key.items); try expected_replies.appendSlice(arena, reply); } try expected_keys.appendSlice(arena, typed[replies.len].items); const events_ok = self.rows[index].host_keys or (std.mem.eql(u8, observed.replies, expected_replies.items) and std.mem.eql(u8, observed.keys, expected_keys.items) and observed.other == 0); if (std.meta.eql(observed.caps, ref.caps) and events_ok) { model.count(@tagName(self.property)); return null; } return model.fail(@tagName(self.property), commands.len - 1); } pub fn simplify(_: *Model, arena: std.mem.Allocator, command: Command) ![]const Command { return switch (command) { .key => |key| if (key.key == 0) &.{} else arena.dupe(Command, &.{.{ .key = .{ .at = key.at, .key = 0 } }}), else => &.{}, }; } pub fn format(self: *Model, command: Command, writer: *std.Io.Writer) void { switch (command) { .row => |index| writer.print("row \"{s}\"", .{self.rows[index % self.rows.len].name}) catch {}, .cut => |at| writer.print("cut {d}", .{at}) catch {}, .key => |key| writer.print("key {f} before reply {d}", .{ std.ascii.hexEscape(keys[key.key], .lower), key.at }) catch {}, .swap => |at| writer.print("swap {d}", .{at}) catch {}, .late => |at| writer.print("late from reply {d}", .{at}) catch {}, } } }; test "terminal replies: splits, keys, order and late arrival keep each row's capabilities" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); const arena = arena_state.allocator(); const rows = try loadRows(arena); const context = try createContext(); defer expectOk(ot.ot_context_destroy(context)) catch unreachable; for (std.enums.values(Property)) |property| { var state: Model = .{ .context = context, .arena = arena, .rows = rows, .property = property, .references = try arena.alloc(?Model.Reference, rows.len) }; @memset(state.references, null); try model.check(Model, &state, .{ .seeds = 256, .steps = 12 }); } }