const std = @import("std"); const testing = std.testing; const Queue = @import("mpsc.zig").Queue; const Pool = @import("mpsc.zig").Pool; /// Node in the graph, represents an object that can have parent/child relations const Node = struct { id: u64, next: ?*Node = null, // Used by Pool, otherwise stores next_sibling parent: ?*Node = null, first_child: ?*Node = null, /// Returns true if this node has the given node as a child fn hasChild(n: *Node, child_id: u64) bool { var current = n.first_child; while (current) |child| : (current = child.next) { if (child.id == child_id) return true; } return false; } /// Adds a child to this node's children list fn addChild(n: *Node, child: *Node) void { var last_child: ?*Node = null; var current = n.first_child; while (current) |curr| : (current = curr.next) { last_child = curr; } child.parent = n; if (last_child) |last| last.next = child else n.first_child = child; } /// Removes a child from this node's children list fn removeChild(n: *Node, child_id: u64) void { if (n.first_child) |first| { if (first.id == child_id) { n.first_child = first.next; if (first.parent == n) { first.parent = null; first.next = null; // Clear the next pointer } return; } var prev = first; var current = first.next; while (current) |curr| { if (curr.id == child_id) { prev.next = curr.next; if (curr.parent == n) { curr.parent = null; curr.next = null; // Clear the next pointer } break; } prev = curr; current = curr.next; } } } }; /// Error set for graph operations pub const Error = error{ OutOfMemory, }; /// Read/write/mutate operations to perform on the graph. const Op = union(enum) { /// Add a child to a parent. no-op if already a child. add_child: struct { parent_id: u64, child_id: u64 }, /// Remove a child from a parent. no-op if not a child. remove_child: struct { parent_id: u64, child_id: u64 }, /// Set the parent of a child node. no-op if already has this parent. set_parent: struct { child_id: u64, parent_id: u64 }, /// Remove the parent of a child node. no-op if no parent. remove_parent: struct { child_id: u64 }, /// Query the children of the given node get_children: struct { node_id: u64, result: *std.ArrayListUnmanaged(u64), err: *?Error, done: *std.atomic.Value(bool), }, /// Query the parent of a node get_parent: struct { node_id: u64, result: *?u64, done: *std.atomic.Value(bool), }, }; /// A graph of objects with parent/child/etc relations. /// /// Reads/writes/mutations to the graph can be performed by any thread in parallel. This is possible /// without a global mutex locking the entire graph because we represent all interactions with the /// graph as /operations/ enqueued to a lock-free Multi Producer, Single Consumer (MPSC) FIFO queue. /// /// When an operation is desired (adding a parent to a child, querying the children or parent of a /// node, etc.) it is enqueued. Then, a background thread processes all pending operations. Atomics /// are used to wait for reads to complete, and parallel writes are lock-free. /// /// The graph uses lock-free pools to manage all nodes internally, eliminating runtime allocations /// during operation processing. pub const Graph = struct { /// Queue of read/write/mutation operations to the graph. queue: Queue(Op), /// Pool of nodes for allocation and recycling. nodes: Pool(Node), /// Maps node IDs to their struct, protected by a read-write lock id_to_node: struct { map: std.AutoHashMapUnmanaged(u64, *Node) = .{}, lock: std.Thread.RwLock = .{}, } = .{}, /// Pool of ArrayLists for query results result_lists: struct { available: std.ArrayListUnmanaged(*std.ArrayListUnmanaged(u64)) = .{}, lock: std.Thread.RwLock = .{}, } = .{}, preallocate_result_list_size: u32, /// Thread that processes operations from the queue thread: ?std.Thread = null, /// Flag to signal the processing thread to stop should_stop: std.atomic.Value(bool) = .init(false), /// Initialize the graph with the given pre-allocated space for nodes and operations. /// /// Spawns a backgroound thread for processing operations to the graph. pub fn init( graph: *Graph, allocator: std.mem.Allocator, preallocate: struct { queue_size: u32, nodes_size: u32, num_result_lists: u32, result_list_size: u32, }, ) !void { graph.* = .{ .queue = undefined, .nodes = undefined, .preallocate_result_list_size = preallocate.result_list_size, }; try graph.queue.init(allocator, preallocate.queue_size); errdefer graph.queue.deinit(allocator); try graph.id_to_node.map.ensureTotalCapacity(allocator, preallocate.nodes_size); errdefer graph.id_to_node.map.deinit(allocator); graph.nodes = try Pool(Node).init(allocator, preallocate.nodes_size); errdefer graph.nodes.deinit(allocator); // Pre-allocate result lists try graph.result_lists.available.ensureTotalCapacity(allocator, preallocate.num_result_lists); errdefer { for (graph.result_lists.available.items) |list| { list.deinit(allocator); allocator.destroy(list); } graph.result_lists.available.deinit(allocator); } for (0..preallocate.num_result_lists) |_| { var list = try allocator.create(std.ArrayListUnmanaged(u64)); errdefer allocator.destroy(list); list.* = .{}; try list.ensureTotalCapacity(allocator, preallocate.result_list_size); try graph.result_lists.available.append(allocator, list); } graph.thread = try std.Thread.spawn(.{ .allocator = allocator }, processThread, .{ graph, allocator }); } pub fn deinit(graph: *Graph, allocator: std.mem.Allocator) void { graph.should_stop.store(true, .release); graph.thread.?.join(); for (graph.result_lists.available.items) |list| { list.deinit(allocator); allocator.destroy(list); } graph.result_lists.available.deinit(allocator); graph.id_to_node.map.deinit(allocator); graph.nodes.deinit(allocator); graph.queue.deinit(allocator); } /// Get an existing Node for the given ID, or null if not found fn getNode(graph: *Graph, id: u64) ?*Node { graph.id_to_node.lock.lockShared(); defer graph.id_to_node.lock.unlockShared(); return graph.id_to_node.map.get(id); } /// The thread that runs continuously in the background to process queue submissions. fn processThread(graph: *Graph, allocator: std.mem.Allocator) void { while (!graph.should_stop.load(.acquire)) { // Process the entire queue while (graph.queue.pop()) |op| graph.processOp(allocator, op); std.Thread.yield() catch {}; } } /// Checks if a node has any relationships and if not, removes it from the graph inline fn cleanupIsolatedNode(graph: *Graph, node: *Node) void { if (node.parent != null or node.first_child != null) return; graph.id_to_node.lock.lock(); defer graph.id_to_node.lock.unlock(); _ = graph.id_to_node.map.remove(node.id); graph.nodes.release(node); } /// Process a single operation to the graph. inline fn processOp(graph: *Graph, allocator: std.mem.Allocator, op: Op) void { switch (op) { .add_child => |data| { const parent = graph.getNode(data.parent_id) orelse return; const new_child = graph.getNode(data.child_id) orelse return; if (!parent.hasChild(new_child.id)) parent.addChild(new_child); }, .remove_child => |data| { const parent = graph.getNode(data.parent_id) orelse return; const child = graph.getNode(data.child_id) orelse return; parent.removeChild(data.child_id); graph.cleanupIsolatedNode(parent); graph.cleanupIsolatedNode(child); }, .set_parent => |data| { const child = graph.getNode(data.child_id) orelse return; const new_parent = graph.getNode(data.parent_id) orelse return; if (child.parent) |old_parent| { if (old_parent == new_parent) return; old_parent.removeChild(child.id); graph.cleanupIsolatedNode(old_parent); } new_parent.addChild(child); }, .remove_parent => |data| { const child = graph.getNode(data.child_id) orelse return; if (child.parent) |parent| { parent.removeChild(child.id); graph.cleanupIsolatedNode(parent); graph.cleanupIsolatedNode(child); } }, .get_children => |query| { const node = graph.getNode(query.node_id) orelse { // Instead of just storing done, we return an empty result query.done.store(true, .release); return; }; var current = node.first_child; while (current) |child| : (current = child.next) { query.result.append(allocator, child.id) catch |err| { query.err.* = err; break; }; } query.done.store(true, .release); }, .get_parent => |query| { const node = graph.getNode(query.node_id) orelse { query.result.* = null; query.done.store(true, .release); return; }; query.result.* = if (node.parent) |parent| parent.id else null; query.done.store(true, .release); }, } } /// preallocateNodes2 ensures graph.id_to_node contains an entry for the two given IDs. fn preallocateNodes2(graph: *Graph, allocator: std.mem.Allocator, id1: u64, id2: u64) !void { graph.id_to_node.lock.lock(); defer graph.id_to_node.lock.unlock(); // Preallocate first node const result1 = try graph.id_to_node.map.getOrPut(allocator, id1); if (!result1.found_existing) { const node = try graph.nodes.acquire(allocator); node.* = .{ .id = id1 }; result1.value_ptr.* = node; } // Preallocate second node const result2 = try graph.id_to_node.map.getOrPut(allocator, id2); if (!result2.found_existing) { const node = try graph.nodes.acquire(allocator); node.* = .{ .id = id2 }; result2.value_ptr.* = node; } } pub fn addChild(graph: *Graph, allocator: std.mem.Allocator, parent_id: u64, child_id: u64) Error!void { try graph.preallocateNodes2(allocator, parent_id, child_id); try graph.queue.push(allocator, .{ .add_child = .{ .parent_id = parent_id, .child_id = child_id, } }); } pub fn removeChild(graph: *Graph, allocator: std.mem.Allocator, parent_id: u64, child_id: u64) Error!void { try graph.preallocateNodes2(allocator, parent_id, child_id); try graph.queue.push(allocator, .{ .remove_child = .{ .parent_id = parent_id, .child_id = child_id, } }); } pub fn setParent(graph: *Graph, allocator: std.mem.Allocator, child_id: u64, parent_id: u64) Error!void { try graph.preallocateNodes2(allocator, child_id, parent_id); try graph.queue.push(allocator, .{ .set_parent = .{ .child_id = child_id, .parent_id = parent_id, } }); } pub fn removeParent(graph: *Graph, allocator: std.mem.Allocator, child_id: u64) Error!void { try graph.queue.push(allocator, .{ .remove_parent = .{ .child_id = child_id, } }); } pub const Results = struct { // The actual result items. Read-only. items: []const u64, // Internal / private fields. internal_list: *std.ArrayListUnmanaged(u64), internal_graph: *Graph, // Deinit returns the allocation back to the Graph memory pool for reuse in the future. pub fn deinit(r: Results) void { r.internal_graph.releaseResultList(r.internal_list); } }; pub fn getChildren(graph: *Graph, allocator: std.mem.Allocator, id: u64) Error!Results { const results = try graph.acquireResultList(allocator, graph.preallocate_result_list_size); errdefer graph.releaseResultList(results); var done = std.atomic.Value(bool).init(false); var err: ?Error = null; try graph.queue.push(allocator, .{ .get_children = .{ .node_id = id, .result = results, .err = &err, .done = &done, } }); while (!done.load(.acquire)) { std.Thread.yield() catch {}; } if (err) |e| return e; return Results{ .items = results.items, .internal_list = results, .internal_graph = graph, }; } fn acquireResultList(graph: *Graph, allocator: std.mem.Allocator, min_capacity: usize) !*std.ArrayListUnmanaged(u64) { // Try to get an existing list first graph.result_lists.lock.lock(); const list = graph.result_lists.available.popOrNull(); graph.result_lists.lock.unlock(); if (list) |l| { errdefer { graph.result_lists.lock.lock(); defer graph.result_lists.lock.unlock(); graph.result_lists.available.appendAssumeCapacity(l); } try l.ensureTotalCapacity(allocator, min_capacity); return l; } // Create new result list if needed var new_list = try allocator.create(std.ArrayListUnmanaged(u64)); errdefer allocator.destroy(new_list); new_list.* = .{}; try new_list.ensureTotalCapacity(allocator, graph.preallocate_result_list_size); return new_list; } fn releaseResultList(graph: *Graph, list: *std.ArrayListUnmanaged(u64)) void { list.clearRetainingCapacity(); graph.result_lists.lock.lock(); defer graph.result_lists.lock.unlock(); graph.result_lists.available.appendAssumeCapacity(list); } pub fn getParent(graph: *Graph, allocator: std.mem.Allocator, id: u64) Error!?u64 { var result: ?u64 = null; var done = std.atomic.Value(bool).init(false); try graph.queue.push(allocator, .{ .get_parent = .{ .node_id = id, .result = &result, .done = &done, } }); while (!done.load(.acquire)) { std.Thread.yield() catch {}; } return result; } };