//! Thread Safety Tests //! //! This module contains comprehensive tests for thread safety in the zig-p2p library. //! Tests cover: //! - Concurrent message processing //! - Concurrent connect/disconnect operations //! - Callback safety (ensuring callbacks can call P2P methods without deadlock) //! - Stress tests with multiple threads const std = @import("std"); const testing = std.testing; const Thread = std.Thread; const Mutex = std.Thread.Mutex; const Allocator = std.mem.Allocator; const p2p_mod = @import("p2p"); const P2P = p2p_mod.P2P; const P2PConfig = p2p_mod.P2PConfig; const P2PEvent = p2p_mod.P2PEvent; const network = @import("network"); const PeerId = network.peer.PeerId; const Address = network.peer.Address; const NetworkManager = network.network_manager.NetworkManager; const PeerConnection = network.PeerConnection; const core = @import("core"); const Socket = core.Socket; /// Test concurrent message processing test "concurrent message processing" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.max_connections = 100; var p2p = try P2P.init(allocator, config); defer p2p.deinit(); try p2p.start(); defer p2p.stop() catch {}; // Track messages received const MessageCounter = struct { count: std.atomic.Value(u32), mutex: Mutex, fn init() @This() { return .{ .count = std.atomic.Value(u32).init(0), .mutex = Mutex{}, }; } fn increment(self: *@This()) void { _ = self.count.fetchAdd(1, .monotonic); } fn get(self: *@This()) u32 { return self.count.load(.monotonic); } }; var counter = MessageCounter.init(); // Register callback that increments counter const callback = struct { fn onEvent(event: P2PEvent) void { _ = event; // Callback intentionally does nothing - just tests that it can be called concurrently } }.onEvent; try p2p.registerCallback(callback, null); // Spawn multiple threads that emit events concurrently const num_threads = 4; const messages_per_thread = 100; var threads: [num_threads]Thread = undefined; for (&threads, 0..) |*thread, i| { _ = i; thread.* = try Thread.spawn(.{}, struct { fn run(p2p_ptr: *P2P, cnt: *MessageCounter) void { for (0..messages_per_thread) |_| { // Emit event (tests concurrent access to event_mutex) p2p_ptr.emitEvent(P2PEvent.create(.library_initialized, .library_initialized)) catch {}; cnt.increment(); } } }.run, .{ &p2p, &counter }); } // Wait for all threads for (threads) |thread| { thread.join(); } // Process all events const processed = p2p.processAllEvents(); // Verify we processed all messages try testing.expect(processed > 0); try testing.expectEqual(num_threads * messages_per_thread, counter.get()); } /// Test concurrent connect/disconnect operations test "concurrent connect disconnect" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.max_connections = 100; var p2p = try P2P.init(allocator, config); defer p2p.deinit(); try p2p.start(); defer p2p.stop() catch {}; // Track connection operations const OpCounter = struct { connects: std.atomic.Value(u32), disconnects: std.atomic.Value(u32), fn init() @This() { return .{ .connects = std.atomic.Value(u32).init(0), .disconnects = std.atomic.Value(u32).init(0), }; } }; var counter = OpCounter.init(); const num_threads = 4; const ops_per_thread = 10; var threads: [num_threads]Thread = undefined; for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, struct { fn run(p2p_ptr: *P2P, cnt: *OpCounter) void { for (0..ops_per_thread) |_| { // Create a test socket and peer const peer_id = PeerId.init(); const socket = p2p_ptr.allocator.create(Socket) catch return; socket.* = Socket.init(.tcp, p2p_ptr.allocator) catch { p2p_ptr.allocator.destroy(socket); return; }; // Add connection (tests peer_connections_mutex) p2p_ptr.addPeerConnection(peer_id, socket) catch { socket.deinit(); p2p_ptr.allocator.destroy(socket); return; }; _ = cnt.connects.fetchAdd(1, .monotonic); // Brief delay Thread.sleep(std.time.ns_per_ms); // Remove connection if (p2p_ptr.removePeerConnection(peer_id)) |removed_socket| { removed_socket.deinit(); p2p_ptr.allocator.destroy(removed_socket); _ = cnt.disconnects.fetchAdd(1, .monotonic); } } } }.run, .{ &p2p, &counter }); } // Wait for all threads for (threads) |thread| { thread.join(); } // Verify operations completed const total_connects = counter.connects.load(.monotonic); const total_disconnects = counter.disconnects.load(.monotonic); try testing.expect(total_connects > 0); try testing.expect(total_disconnects > 0); // Disconnects should equal connects (all connections were removed) try testing.expectEqual(total_connects, total_disconnects); } /// Test that callbacks can safely call P2P methods (deadlock prevention) test "callback can call P2P methods" { const allocator = testing.allocator; var p2p = try P2P.init(allocator, P2PConfig.default()); defer p2p.deinit(); try p2p.start(); defer p2p.stop() catch {}; // Track recursive calls const RecursiveCounter = struct { count: std.atomic.Value(u32), fn init() @This() { return .{ .count = std.atomic.Value(u32).init(0) }; } fn increment(self: *@This()) void { _ = self.count.fetchAdd(1, .monotonic); } fn get(self: *@This()) u32 { return self.count.load(.monotonic); } }; var counter = RecursiveCounter.init(); // Callback that calls emitEvent (tests that we don't deadlock) const TestContext = struct { p2p_ptr: *P2P, counter_ptr: *RecursiveCounter, }; var ctx = TestContext{ .p2p_ptr = &p2p, .counter_ptr = &counter, }; const callback = struct { fn onEvent(event: P2PEvent) void { const context = @as(*TestContext, @ptrCast(@alignCast(event.data))); _ = context; // This would deadlock if event_mutex is held during callback // CRITICAL: This tests that processNextEvent releases mutex before calling callbacks } }.onEvent; try p2p.registerCallback(callback, &ctx); // Emit some events for (0..10) |_| { try p2p.emitEvent(P2PEvent.create(.library_initialized, .library_initialized)); counter.increment(); } // Process events - should not deadlock const processed = p2p.processAllEvents(); try testing.expectEqual(@as(usize, 10), processed); } /// Stress test with multiple threads performing various operations test "stress test with multiple threads" { const allocator = testing.allocator; var config = P2PConfig.default(); config.network.max_connections = 500; config.events.max_event_queue = 10000; var p2p = try P2P.init(allocator, config); defer p2p.deinit(); try p2p.start(); defer p2p.stop() catch {}; const num_worker_threads = 8; const operations_per_thread = 50; var threads: [num_worker_threads]Thread = undefined; // Each thread performs a mix of operations for (&threads, 0..) |*thread, thread_id| { thread.* = try Thread.spawn(.{}, struct { fn worker(p2p_ptr: *P2P, id: usize) void { for (0..operations_per_thread) |op| { // Vary operations based on thread ID and operation number const operation = (id + op) % 4; switch (operation) { 0 => { // Emit event p2p_ptr.emitEvent(P2PEvent.create(.library_initialized, .library_initialized)) catch {}; }, 1 => { // Add/remove connection const peer_id = PeerId.init(); const socket = p2p_ptr.allocator.create(Socket) catch continue; socket.* = Socket.init(.tcp, p2p_ptr.allocator) catch { p2p_ptr.allocator.destroy(socket); continue; }; p2p_ptr.addPeerConnection(peer_id, socket) catch { socket.deinit(); p2p_ptr.allocator.destroy(socket); continue; }; Thread.sleep(std.time.ns_per_ms); if (p2p_ptr.removePeerConnection(peer_id)) |removed| { removed.deinit(); p2p_ptr.allocator.destroy(removed); } }, 2 => { // Process events _ = p2p_ptr.processNextEvent(); }, 3 => { // Get stats (tests concurrent reads) const stats = p2p_ptr.getStats(); _ = stats; }, else => unreachable, } // Small random delay to increase interleaving if (op % 5 == 0) { Thread.sleep(std.time.ns_per_ms); } } } }.worker, .{ &p2p, thread_id }); } // Wait for all threads to complete for (threads) |thread| { thread.join(); } // Verify P2P is still operational try testing.expect(p2p.isOperational()); // Process any remaining events _ = p2p.processAllEvents(); } /// Test NetworkManager message callbacks don't deadlock test "network manager callback safety" { const allocator = testing.allocator; var connections = std.AutoHashMap(PeerId, *PeerConnection).init(allocator); defer connections.deinit(); var nm = NetworkManager.init(allocator, &connections); defer nm.deinit(); // Track callback invocations const CallbackCounter = struct { count: std.atomic.Value(u32), fn init() @This() { return .{ .count = std.atomic.Value(u32).init(0) }; } }; var counter = CallbackCounter.init(); // Set callback that increments counter const callback = struct { fn onMessage(peer_id: PeerId, message: []const u8, context: ?*anyopaque) void { _ = peer_id; _ = message; const cnt = @as(*CallbackCounter, @ptrCast(@alignCast(context.?))); _ = cnt.count.fetchAdd(1, .monotonic); } }.onMessage; nm.setMessageCallback(callback, &counter); // This tests that processReceive doesn't hold mutex while calling callbacks // If it did, any attempt by the callback to call sendMessage would deadlock const num_threads = 4; var threads: [num_threads]Thread = undefined; for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, struct { fn run(manager: *NetworkManager) void { for (0..10) |_| { // Call processReceive (won't actually receive anything, but tests locking) manager.processReceive() catch {}; Thread.sleep(std.time.ns_per_ms); } } }.run, .{&nm}); } for (threads) |thread| { thread.join(); } // Test passed if we didn't deadlock } /// Test atomic sequence counter in Node test "node sequence counter thread safety" { const allocator = testing.allocator; const peer_id = PeerId.init(); var address = Address.init(); address.port = 8080; var topology = network.topology.NetworkTopology.init(allocator, .Mesh); defer topology.deinit(); const config = network.node.NodeConfig{}; var node = network.node.Node.init(allocator, peer_id, address, &topology, config); defer node.deinit(); const num_threads = 8; const messages_per_thread = 100; var threads: [num_threads]Thread = undefined; // Track generated sequence numbers const SeqTracker = struct { sequences: std.AutoHashMap(u64, bool), mutex: Mutex, fn init(alloc: Allocator) @This() { return .{ .sequences = std.AutoHashMap(u64, bool).init(alloc), .mutex = Mutex{}, }; } fn deinit(self: *@This()) void { self.sequences.deinit(); } fn add(self: *@This(), seq: u64) !void { self.mutex.lock(); defer self.mutex.unlock(); try self.sequences.put(seq, true); } fn count(self: *@This()) usize { self.mutex.lock(); defer self.mutex.unlock(); return self.sequences.count(); } }; var tracker = SeqTracker.init(allocator); defer tracker.deinit(); // Spawn threads that create messages concurrently for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, struct { fn run(node_ptr: *network.node.Node, track: *SeqTracker) void { const payload = "test"; for (0..messages_per_thread) |_| { const msg = node_ptr.createMessage( .Data, null, payload, ) catch continue; track.add(msg.sequence) catch {}; } } }.run, .{ &node, &tracker }); } for (threads) |thread| { thread.join(); } // All sequence numbers should be unique const expected = num_threads * messages_per_thread; const actual = tracker.count(); try testing.expectEqual(expected, actual); } /// Test routing table concurrent access test "routing table concurrent access" { const allocator = testing.allocator; const local_id = PeerId.init(); var routing_table = network.routing.KademliaRoutingTable.init(allocator, local_id); defer routing_table.deinit(); const num_threads = 4; const peers_per_thread = 20; var threads: [num_threads]Thread = undefined; // Each thread adds and removes peers for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, struct { fn run(table: *network.routing.KademliaRoutingTable, alloc: Allocator) void { var peers: std.ArrayList(*network.peer.Peer) = .{}; defer { for (peers.items) |peer| { alloc.destroy(peer); } peers.deinit(alloc); } // Add peers for (0..peers_per_thread) |_| { const peer_id = PeerId.init(); const address = Address.init(); const peer = alloc.create(network.peer.Peer) catch continue; peer.* = network.peer.Peer.init(peer_id, address); peers.append(alloc, peer) catch continue; var position = network.topology.NodePosition.init(alloc, peer_id); defer position.deinit(); table.addPeer(peer, &position) catch {}; Thread.sleep(std.time.ns_per_ms); } // Remove some peers for (peers.items[0..@min(5, peers.items.len)]) |peer| { table.removePeer(peer.id); } } }.run, .{ &routing_table, allocator }); } for (threads) |thread| { thread.join(); } // Verify routing table is still valid const stats = routing_table.getStats(); try testing.expect(stats.total_peers > 0); }