//! linux_usb_test — exercises mgf-hrb-usb against REAL Linux hardware.
//!
//! These tests read this machine's actual `/sys/bus/usb/devices/`. They
//! prove the seam abstraction holds against genuine sysfs facts — the same
//! pattern `linux_test.zig` uses for the PCI backend. On a host with no USB
//! controller, the tests succeed with empty enumeration (per the contract:
//! a missing substrate is empty-not-error, never a lie).
//!
//! What this file does NOT do: exercise *successful* acquire end-to-end —
//! claiming a real USB interface detaches the device from its kernel driver
//! (uvcvideo, usbhid, ...), which is destructive for an automated test on
//! the developer's own machine. The U3a tests instead cover the URN parser,
//! the device-node resolver, and the honest-failure paths (NotFound on
//! bogus URNs, InvalidToken on unknown tokens, idempotent release). The
//! full conformance suite (acquire-then-crash, idempotent release, etc.)
//! runs against the fake backend; it would run UNCHANGED against this
//! backend on a host with a deliberately offered-up USB interface.

const std = @import("std");
const testing = std.testing;
const model = @import("mgf_hrb_model");
const kabi = @import("mgf_hrb_kabi");
const LinuxUsbBackend = @import("mgf_hrb_linux_usb").LinuxUsbBackend;

const Urn = model.Urn;
const Err = model.Err;

const Collector = struct {
    items: std.ArrayListUnmanaged(model.Resource) = .empty,
    alloc: std.mem.Allocator,
    fn push(ctx: *anyopaque, r: model.Resource) void {
        const self: *Collector = @ptrCast(@alignCast(ctx));
        self.items.append(self.alloc, r) catch {};
    }
    fn sink(self: *Collector) kabi.FactSink {
        return .{ .ctx = self, .push = push };
    }
};

test "linux-usb REAL: enumerate runs (live or empty, never an error)" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    const be = lb.backend();

    var col = Collector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();
    try be.enumerate("hw:/usb/**", &s, kabi.Deadline.none);

    std.debug.print("\n  [linux-usb] enumerated {d} interface(s)\n", .{col.items.items.len});
    for (col.items.items) |r| {
        try testing.expectEqual(model.Family.claimable, r.family);
        try testing.expectEqual(model.Kind.usb_interface, r.kind);
        // §2.2: every URN we emit starts with hw:/usb/bus
        try testing.expect(std.mem.startsWith(u8, r.urn.slice(), "hw:/usb/bus"));
        // G2: live (descriptor read) or unknown (sysfs raced) — never silently wrong
        try testing.expect(r.fidelity == .live or r.fidelity == .unknown);
    }
    if (col.items.items.len > 0) {
        const first = col.items.items[0];
        std.debug.print("  [linux-usb] first urn: {s} (fidelity: {s})\n", .{
            first.urn.slice(), @tagName(first.fidelity),
        });
    }
}

test "linux-usb REAL: URN grammar holds (§2.2 — ends with /dev/if<K>)" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    const be = lb.backend();
    var col = Collector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();
    try be.enumerate("hw:/usb/**", &s, kabi.Deadline.none);

    for (col.items.items) |r| {
        // Every URN we emit is an *interface*, not a device — so it must
        // contain the `/dev/if` separator the grammar mandates.
        try testing.expect(std.mem.indexOf(u8, r.urn.slice(), "/dev/if") != null);
    }
}

test "linux-usb REAL: scope filter narrows the result set" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    const be = lb.backend();

    // Ask for a scope that can't match any real device — must return empty.
    var col = Collector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();
    try be.enumerate("hw:/usb/bus999/**", &s, kabi.Deadline.none);
    try testing.expectEqual(@as(usize, 0), col.items.items.len);
}

test "linux-usb U3a: acquire on a nonexistent URN → NotFound (honest)" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    // Bus 99 doesn't exist on any sane host.
    const urn = Urn.from("hw:/usb/bus99/port-99/dev/if0");
    try testing.expectError(Err.NotFound, be.acquire(&urn, .exclusive, kabi.Deadline.none));
}

test "linux-usb U3a: acquire on a malformed URN → BadRequest" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    const urn = Urn.from("not-even-a-urn");
    try testing.expectError(Err.BadRequest, be.acquire(&urn, .exclusive, kabi.Deadline.none));
}

test "linux-usb U3a: release on an unknown token is a no-op (idempotent)" {
    // §6.3: release is TOTAL and IDEMPOTENT — even releasing a token we
    // never issued must succeed (or rather, must not raise).
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    be.release(.{ .id = 999999 }, kabi.Deadline.none);
    // If we got here, the no-op contract held.
}

test "linux-usb U3a: raw_channel on an unknown token → InvalidToken" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    try testing.expectError(
        Err.InvalidToken,
        be.rawChannel(.{ .id = 12345 }, kabi.Deadline.none),
    );
}

test "linux-usb U3a: reset on a nonexistent URN → NotFound" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    const urn = Urn.from("hw:/usb/bus99/port-99/dev/if0");
    try testing.expectError(
        Err.NotFound,
        be.reset(&urn, .function_level, kabi.Deadline.none),
    );
}

test "linux-usb REAL: watch opens a netlink uevent socket (U2b)" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.closeWatch();
    const be = lb.backend();

    const Es = struct {
        fn push(ctx: *anyopaque, ev: model.Event) void {
            _ = ctx;
            _ = ev;
        }
    };
    const es = kabi.EventSink{ .ctx = undefined, .push = Es.push };
    const handle = try be.watch("hw:/usb/**", &es, kabi.Deadline.none);
    // Handle.id is the fd cast to u64 — should be a valid (positive) fd.
    try testing.expect(handle.id > 0);
    try testing.expect(lb.uevent_fd >= 0);

    // pumpUevent should NOT block — the socket is non-blocking. Drain
    // whatever happens to be queued (likely nothing) and return cleanly.
    try lb.pumpUevent(&es, "hw:/usb/**");

    // closeWatch is idempotent.
    lb.closeWatch();
    lb.closeWatch();
    try testing.expect(lb.uevent_fd == -1);
}

const linux_usb = @import("mgf_hrb_linux_usb");

test "uevent parser: add event for a real USB interface" {
    // Synthetic uevent matching what the kernel sends when an interface
    // appears (NUL-separated, header line first).
    const msg =
        "add@/devices/pci0000:00/0000:00:14.0/usb3/3-9/3-9:1.0\x00" ++
        "ACTION=add\x00" ++
        "DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-9/3-9:1.0\x00" ++
        "SUBSYSTEM=usb\x00" ++
        "DEVTYPE=usb_interface\x00" ++
        "INTERFACE=14/0/0\x00";

    const p = linux_usb.parseUevent(msg);
    try testing.expectEqualStrings("add", p.action);
    try testing.expectEqualStrings("usb", p.subsystem);
    try testing.expectEqualStrings("usb_interface", p.devtype);
    try testing.expect(std.mem.endsWith(u8, p.devpath, "/3-9/3-9:1.0"));
}

test "uevent parser: skips the ACTION@DEVPATH header line" {
    // The first NUL-terminated record is the header (no `=`); parser
    // must skip it without confusing the KEY=VALUE extractor.
    const msg =
        "remove@/devices/.../3-9:1.0\x00" ++
        "ACTION=remove\x00" ++
        "DEVPATH=/devices/x/3-9:1.0\x00" ++
        "SUBSYSTEM=usb\x00" ++
        "DEVTYPE=usb_interface\x00";
    const p = linux_usb.parseUevent(msg);
    try testing.expectEqualStrings("remove", p.action);
}

test "uevent parser: missing fields default to empty" {
    const msg = "ACTION=add\x00SUBSYSTEM=usb\x00";
    const p = linux_usb.parseUevent(msg);
    try testing.expectEqualStrings("add", p.action);
    try testing.expectEqualStrings("usb", p.subsystem);
    try testing.expectEqualStrings("", p.devtype); // missing → empty
    try testing.expectEqualStrings("", p.devpath);
}

test "uevent → Event: add interface yields .added with the correct URN" {
    const p = linux_usb.ParsedUevent{
        .action = "add",
        .devpath = "/devices/pci0000:00/0000:00:14.0/usb3/3-9/3-9:1.0",
        .subsystem = "usb",
        .devtype = "usb_interface",
    };
    const ev = linux_usb.ueventToEvent(p) orelse return error.UnexpectedNull;
    switch (ev) {
        .added => |a| try testing.expectEqualStrings(
            "hw:/usb/bus3/port-9/dev/if0",
            a.urn.slice(),
        ),
        else => return error.WrongEventKind,
    }
}

test "uevent → Event: remove interface yields .removed with the correct URN" {
    const p = linux_usb.ParsedUevent{
        .action = "remove",
        .devpath = "/devices/.../3-9.4:1.2",
        .subsystem = "usb",
        .devtype = "usb_interface",
    };
    const ev = linux_usb.ueventToEvent(p) orelse return error.UnexpectedNull;
    switch (ev) {
        .removed => |r| try testing.expectEqualStrings(
            "hw:/usb/bus3/port-9.4/dev/if2",
            r.urn.slice(),
        ),
        else => return error.WrongEventKind,
    }
}

test "uevent → Event: non-USB subsystem is filtered out" {
    const p = linux_usb.ParsedUevent{
        .action = "add",
        .devpath = "/devices/.../something",
        .subsystem = "block",
        .devtype = "disk",
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);
}

test "uevent → Event: device-level events (usb_device) are filtered out" {
    // We emit one Resource per interface (§2.4); device-level events
    // would duplicate the per-interface ones. Filter them here so the
    // sink doesn't see redundant entries.
    const p = linux_usb.ParsedUevent{
        .action = "add",
        .devpath = "/devices/.../3-9",
        .subsystem = "usb",
        .devtype = "usb_device",
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);
}

test "uevent → Event: 'change'/'bind' actions return null (U3+ maps them)" {
    const p = linux_usb.ParsedUevent{
        .action = "change",
        .devpath = "/devices/.../3-9:1.0",
        .subsystem = "usb",
        .devtype = "usb_interface",
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);

    const p2 = linux_usb.ParsedUevent{
        .action = "bind",
        .devpath = "/devices/.../3-9:1.0",
        .subsystem = "usb",
        .devtype = "usb_interface",
    };
    try testing.expect(linux_usb.ueventToEvent(p2) == null);
}

test "uevent → Event: malformed DEVPATH (no slash, no entry) is filtered" {
    const p = linux_usb.ParsedUevent{
        .action = "add",
        .devpath = "garbage",
        .subsystem = "usb",
        .devtype = "usb_interface",
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);
}

// ----- Part 13 §5.4.1 — driver_bound / driver_unbound event kinds ----------

test "Part-13: uevent parser captures DRIVER field on bind" {
    // Real bind uevent shape: ACTION=bind carries the driver name in
    // the DRIVER= field. Parser must extract it alongside the existing
    // four fields.
    const msg =
        "bind@/devices/.../3-9:1.0\x00" ++
        "ACTION=bind\x00" ++
        "DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-9/3-9:1.0\x00" ++
        "SUBSYSTEM=usb\x00" ++
        "DEVTYPE=usb_interface\x00" ++
        "DRIVER=usbhid\x00";

    const p = linux_usb.parseUevent(msg);
    try testing.expectEqualStrings("bind", p.action);
    try testing.expectEqualStrings("usbhid", p.driver);
}

test "Part-13: uevent → Event: bind+DRIVER yields .driver_bound with the right URN + driver name" {
    const p = linux_usb.ParsedUevent{
        .action = "bind",
        .devpath = "/devices/pci0000:00/0000:00:14.0/usb3/3-9/3-9:1.0",
        .subsystem = "usb",
        .devtype = "usb_interface",
        .driver = "usbhid",
    };
    const ev = linux_usb.ueventToEvent(p) orelse return error.UnexpectedNull;
    switch (ev) {
        .driver_bound => |b| {
            try testing.expectEqualStrings(
                "hw:/usb/bus3/port-9/dev/if0",
                b.urn.slice(),
            );
            try testing.expectEqualStrings("usbhid", b.driver.slice());
        },
        else => return error.WrongEventKind,
    }
}

test "Part-13: uevent → Event: unbind+DRIVER yields .driver_unbound" {
    const p = linux_usb.ParsedUevent{
        .action = "unbind",
        .devpath = "/devices/.../3-9.4:1.2",
        .subsystem = "usb",
        .devtype = "usb_interface",
        .driver = "snd-usb-audio",
    };
    const ev = linux_usb.ueventToEvent(p) orelse return error.UnexpectedNull;
    switch (ev) {
        .driver_unbound => |u| {
            try testing.expectEqualStrings(
                "hw:/usb/bus3/port-9.4/dev/if2",
                u.urn.slice(),
            );
            try testing.expectEqualStrings("snd-usb-audio", u.driver.slice());
        },
        else => return error.WrongEventKind,
    }
}

test "Part-13: bind without DRIVER field is filtered (no fake driver name)" {
    // Some built-in drivers emit bind events without the DRIVER= field.
    // We honestly skip those rather than synthesising a fake name —
    // the consumer never sees `{"driver":""}` (G2 — never lie).
    const p = linux_usb.ParsedUevent{
        .action = "bind",
        .devpath = "/devices/.../3-9:1.0",
        .subsystem = "usb",
        .devtype = "usb_interface",
        .driver = "", // missing
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);
}

test "Part-13: bind on non-USB subsystem is filtered" {
    const p = linux_usb.ParsedUevent{
        .action = "bind",
        .devpath = "/devices/.../something",
        .subsystem = "block",
        .devtype = "disk",
        .driver = "nvme",
    };
    try testing.expect(linux_usb.ueventToEvent(p) == null);
}

// ----- U3a: URN reverse-parser ---------------------------------------------

test "U3a parseUsbUrn: a simple URN round-trips" {
    const p = linux_usb.parseUsbUrn("hw:/usb/bus3/port-9/dev/if0") orelse return error.UnexpectedNull;
    try testing.expectEqual(@as(u8, 3), p.bus);
    try testing.expectEqual(@as(u8, 1), p.port_depth);
    try testing.expectEqual(@as(u8, 9), p.port_chain[0]);
    try testing.expectEqual(@as(u8, 0), p.if_num);
}

test "U3a parseUsbUrn: deep port chain" {
    const p = linux_usb.parseUsbUrn("hw:/usb/bus1/port-2.3.1.4/dev/if7") orelse return error.UnexpectedNull;
    try testing.expectEqual(@as(u8, 1), p.bus);
    try testing.expectEqual(@as(u8, 4), p.port_depth);
    try testing.expectEqual(@as(u8, 2), p.port_chain[0]);
    try testing.expectEqual(@as(u8, 4), p.port_chain[3]);
    try testing.expectEqual(@as(u8, 7), p.if_num);
}

test "U3a parseUsbUrn: wrong prefix → null" {
    try testing.expect(linux_usb.parseUsbUrn("hw:/pci/0000:01:00.0/fn0") == null);
    try testing.expect(linux_usb.parseUsbUrn("not a urn") == null);
    try testing.expect(linux_usb.parseUsbUrn("") == null);
}

test "U3a parseUsbUrn: missing components → null" {
    try testing.expect(linux_usb.parseUsbUrn("hw:/usb/bus3/port-9/dev") == null); // no if
    try testing.expect(linux_usb.parseUsbUrn("hw:/usb/bus3/port-9") == null); // no dev/
    try testing.expect(linux_usb.parseUsbUrn("hw:/usb/bus3") == null); // no port-
    try testing.expect(linux_usb.parseUsbUrn("hw:/usb/busABC/port-9/dev/if0") == null); // bad bus
    try testing.expect(linux_usb.parseUsbUrn("hw:/usb/bus3/port-/dev/if0") == null); // empty chain
}

test "U3a parseUsbUrn ↔ urnForInterface round-trip" {
    // Build a URN forward, parse it back, confirm components match.
    const usb_helpers = @import("mgf_hrb_usb");
    var buf: [usb_helpers.MAX_USB_URN_BYTES]u8 = undefined;
    const urn = usb_helpers.urnForInterface(&buf, 7, &.{ 1, 2, 3 }, 5);
    const parts = linux_usb.parseUsbUrn(urn.slice()) orelse return error.UnexpectedNull;
    try testing.expectEqual(@as(u8, 7), parts.bus);
    try testing.expectEqual(@as(u8, 3), parts.port_depth);
    try testing.expectEqual(@as(u8, 1), parts.port_chain[0]);
    try testing.expectEqual(@as(u8, 2), parts.port_chain[1]);
    try testing.expectEqual(@as(u8, 3), parts.port_chain[2]);
    try testing.expectEqual(@as(u8, 5), parts.if_num);
}

// ----- U3a: device-node resolver -------------------------------------------

test "U3a resolveDevice: nonexistent bus → NotFound" {
    const parts = linux_usb.UsbUrnParts{
        .bus = 99,
        .port_chain = [_]u8{99} ++ [_]u8{0} ** 15,
        .port_depth = 1,
        .if_num = 0,
    };
    try testing.expectError(Err.NotFound, linux_usb.resolveDevice(&parts));
}

// ----- U4: S-conformance survivability properties ---------------------------

const EventCollector = struct {
    items: std.ArrayListUnmanaged(model.Event) = .empty,
    alloc: std.mem.Allocator,
    fn push(ctx: *anyopaque, ev: model.Event) void {
        const self: *EventCollector = @ptrCast(@alignCast(ctx));
        self.items.append(self.alloc, ev) catch {};
    }
    fn sink(self: *EventCollector) kabi.EventSink {
        return .{ .ctx = self, .push = push };
    }
};

test "U4: pushGap emits a typed Event.gap with the netlink source" {
    // Forcing ENOBUFS on a real netlink socket is impractical in a unit
    // test (would need to flood the kernel). Test the dispatch path
    // directly via the exposed helper — this is the path pumpUevent
    // hits on ENOBUFS, so coverage transfers.
    var col = EventCollector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();

    linux_usb.LinuxUsbBackend.pushGap(&s);

    try testing.expectEqual(@as(usize, 1), col.items.items.len);
    switch (col.items.items[0]) {
        .gap => |g| {
            try testing.expectEqual(model.GapSource.netlink_uevent, g.source);
            try testing.expect(g.since_ms > 0); // monotonic clock advanced
        },
        else => return error.WrongEventKind,
    }
}

test "U4: bus_level reset returns Unsupported (honest — no kernel ABI)" {
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    const urn = Urn.from("hw:/usb/bus3/port-9/dev/if0");
    // Even if the device exists, bus_level reset must return Unsupported
    // — USB has no Linux kernel ABI for it. §6.3: never lie about what
    // reset levels we can achieve.
    try testing.expectError(
        Err.Unsupported,
        be.reset(&urn, .bus_level, kabi.Deadline.none),
    );
}

test "U4: function_level reset on nonexistent URN → NotFound (verifies-after)" {
    // The post-reset verifier (§2.3) re-reads sysfs to confirm the device
    // came back. For a URN that doesn't exist, we never even get to the
    // ioctl — resolveDevice fails first. This pins that path.
    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    const urn = Urn.from("hw:/usb/bus99/port-99/dev/if0");
    try testing.expectError(
        Err.NotFound,
        be.reset(&urn, .function_level, kabi.Deadline.none),
    );
}

test "U3a resolveDevice: live device on this host (if any) resolves cleanly" {
    // Best-effort: walk /sys/bus/usb/devices, find the FIRST non-root-hub
    // entry, parse its name to get (bus, port_chain), and resolve. The
    // resulting device-node path must point at /dev/bus/usb/<bbb>/<ddd>.
    // On a host with no USB devices, the test is silently empty (the live
    // contract is honest emptiness; no failure).

    var lb = LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const be = lb.backend();
    var col = Collector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();
    try be.enumerate("hw:/usb/**", &s, kabi.Deadline.none);

    if (col.items.items.len == 0) return; // empty bus — honest

    // Pick the first enumerated URN, parse it back.
    const first = col.items.items[0];
    const parts = linux_usb.parseUsbUrn(first.urn.slice()) orelse return error.UnexpectedNull;
    const resolved = try linux_usb.resolveDevice(&parts);

    // The path must be /dev/bus/usb/<3-digit busnum>/<3-digit devnum>.
    const path = resolved.devNodePath();
    try testing.expect(std.mem.startsWith(u8, path, "/dev/bus/usb/"));
    try testing.expect(path.len >= "/dev/bus/usb/000/000".len);
    std.debug.print("\n  [linux-usb U3a] resolved {s} → {s}\n", .{ first.urn.slice(), path });
}

test "linux-usb: substitutability — plugs into the same KernelBackend seam (LSP)" {
    // Mirrors the PCI test in linux_test.zig: an end-to-end through the
    // abstract seam, proving the USB backend is substitutable for the fake
    // and for `mgf-hrb-youros` when it lands.
    var lb = LinuxUsbBackend.init(testing.allocator);
    const be: kabi.KernelBackend = lb.backend(); // same type as fake / PCI
    var col = Collector{ .alloc = testing.allocator };
    defer col.items.deinit(testing.allocator);
    const s = col.sink();
    try be.queryTopology(&s, kabi.Deadline.none);
    std.debug.print("  [linux-usb] queryTopology via the same seam → {d} interface(s)\n", .{col.items.items.len});
}

// ---------------------------------------------------------------------------
// Part 13 §5.1.1 — controlStateFor registry semantics.
//
// vControl's success path requires a writable sysfs file (root-only on this
// host) so we can't exercise it from CI. The state registry — the part
// sub-phase 4A actually adds — is testable in isolation: same backend, no
// sysfs involvement. These tests pin the lookup-or-allocate behavior:
//   * Different (urn, verb) pairs get different slots.
//   * Same (urn, verb) returns the SAME pointer across calls (so the
//     SpinMutex is shared across writers — that's the whole point).
//   * The registry caps at MAX_CONTROL_STATES; the next allocation
//     returns null (vControl surfaces it as Err.Overloaded).
// ---------------------------------------------------------------------------

test "control_state: distinct (urn, verb) pairs get distinct slots" {
    var lb = linux_usb.LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const urn_a = Urn.from("hw:/usb/bus3/port-9/dev/if0");
    const urn_b = Urn.from("hw:/usb/bus3/port-9/dev/if1");
    const s_a_auth = lb.controlStateFor(&urn_a, .set_authorized).?;
    const s_a_susp = lb.controlStateFor(&urn_a, .set_autosuspend).?;
    const s_b_auth = lb.controlStateFor(&urn_b, .set_authorized).?;
    // All three are distinct pointers — different states, different mutexes.
    try testing.expect(s_a_auth != s_a_susp);
    try testing.expect(s_a_auth != s_b_auth);
    try testing.expect(s_a_susp != s_b_auth);
}

test "control_state: same (urn, verb) returns same pointer" {
    var lb = linux_usb.LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const u = Urn.from("hw:/usb/bus3/port-9/dev/if0");
    const a = lb.controlStateFor(&u, .set_authorized).?;
    const b = lb.controlStateFor(&u, .set_authorized).?;
    // Pointer equality — the SpinMutex shared across writers.
    try testing.expect(a == b);
}

test "control_state: detect supersede via state.generation comparison" {
    // The real vControl path checks `post_gen > our_gen` after
    // unlock. We can model the same race here without sysfs: take
    // a state, simulate our write (gen=1), then simulate ANOTHER
    // writer landing (gen=2), and verify the comparison detects
    // the override.
    var lb = linux_usb.LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    const u = Urn.from("hw:/usb/bus3/port-9/dev/if0");
    const state = lb.controlStateFor(&u, .set_authorized).?;

    // Our write lands.
    state.generation = 1;
    state.last_writer_cap_id = 100;
    const our_gen = state.generation;

    // Simulate another writer landing between our unlock and the
    // re-snapshot.
    state.generation = 2;
    state.last_writer_cap_id = 200;
    state.last_ts_ms = 42;

    // The re-snapshot detects supersede.
    try testing.expect(state.generation > our_gen);
    try testing.expectEqual(@as(u64, 2), state.generation);
    try testing.expectEqual(@as(u64, 200), state.last_writer_cap_id);
}

test "control_state: registry caps at MAX_CONTROL_STATES" {
    var lb = linux_usb.LinuxUsbBackend.init(testing.allocator);
    defer lb.deinit();
    // Fill the registry with synthetic URNs.
    var i: usize = 0;
    while (i < linux_usb.MAX_CONTROL_STATES) : (i += 1) {
        var buf: [128]u8 = undefined;
        const slice = std.fmt.bufPrint(&buf, "hw:/test/dev{d}", .{i}) catch unreachable;
        const u = Urn.from(slice);
        try testing.expect(lb.controlStateFor(&u, .set_authorized) != null);
    }
    // One more → null (vControl surfaces this as Err.Overloaded).
    const overflow_urn = Urn.from("hw:/test/overflow");
    try testing.expect(lb.controlStateFor(&overflow_urn, .set_authorized) == null);
}
