diff --git a/src/p2p/lifecycle.zig b/src/p2p/lifecycle.zig index 6339869..756067a 100644 --- a/src/p2p/lifecycle.zig +++ b/src/p2p/lifecycle.zig @@ -484,11 +484,14 @@ pub fn shutdownImpl(p2p: *P2P) void { p2p.state_mutex.unlock(); // Clear event queue - p2p.event_mutex.lock(); - defer p2p.event_mutex.unlock(); - p2p.event_queue.clearRetainingCapacity(); + { + p2p.event_mutex.lock(); + defer p2p.event_mutex.unlock(); + p2p.event_queue.clearRetainingCapacity(); + } // Emit final event (ignore errors during shutdown) + // Must be outside event_mutex scope — emitEvent takes the lock internally p2p.emitEvent(P2PEvent.create(.library_stopped, .library_stopped)) catch |err| { std.log.warn("Failed to emit shutdown event: {}", .{err}); }; diff --git a/src/p2p/p2p.zig b/src/p2p/p2p.zig index 9252067..1be8a08 100644 --- a/src/p2p/p2p.zig +++ b/src/p2p/p2p.zig @@ -1043,23 +1043,28 @@ pub const P2P = struct { pub fn addMappedPeersToRoutingTable(p2p: *P2P) !usize { var added: usize = 0; - // Collect node IDs and their connection peer IDs - p2p.dht_node_to_peer_mutex.lock(); - defer p2p.dht_node_to_peer_mutex.unlock(); + // Snapshot node mappings under lock, then release before calling other locked functions + const Mapping = struct { node_id: [32]u8, peer_id: PeerId }; + var mappings: [64]Mapping = undefined; + var count: usize = 0; - var iter = p2p.dht_node_to_peer.iterator(); - while (iter.next()) |entry| { - const node_id = entry.key_ptr.*; - const connection_peer_id = entry.value_ptr.*; + { + p2p.dht_node_to_peer_mutex.lock(); + defer p2p.dht_node_to_peer_mutex.unlock(); - // Get the socket for this connection peer - const socket = p2p.getPeerSocket(connection_peer_id) orelse continue; + var iter = p2p.dht_node_to_peer.iterator(); + while (iter.next()) |entry| { + if (count >= mappings.len) break; + mappings[count] = .{ .node_id = entry.key_ptr.*, .peer_id = entry.value_ptr.* }; + count += 1; + } + } - // Get the peer's address from the socket (already in our Address type) + // Process mappings without holding dht_node_to_peer_mutex + for (mappings[0..count]) |mapping| { + const socket = p2p.getPeerSocket(mapping.peer_id) orelse continue; const address = socket.getPeerAddress() catch continue; - - // Add to routing table - p2p.dhtAddPeer(node_id, address) catch continue; + p2p.dhtAddPeer(mapping.node_id, address) catch continue; added += 1; } @@ -1124,8 +1129,16 @@ pub const P2P = struct { // Add new observed address (limit to 10 entries to prevent unbounded growth) if (p2p.observed_addresses.items.len >= 10) { - // Remove oldest entry - _ = p2p.observed_addresses.orderedRemove(0); + // Remove the entry with the oldest timestamp (least recently observed) + var oldest_idx: usize = 0; + var oldest_ts: i64 = p2p.observed_addresses.items[0].timestamp; + for (p2p.observed_addresses.items[1..], 1..) |item, i| { + if (item.timestamp < oldest_ts) { + oldest_ts = item.timestamp; + oldest_idx = i; + } + } + _ = p2p.observed_addresses.orderedRemove(oldest_idx); } p2p.observed_addresses.append(p2p.allocator, observed) catch return; diff --git a/tests/test_p2p_high_impact.zig b/tests/test_p2p_high_impact.zig index 25fcb71..215d9ad 100644 --- a/tests/test_p2p_high_impact.zig +++ b/tests/test_p2p_high_impact.zig @@ -372,9 +372,27 @@ test "lifecycle: error state and recovery" { // This is expected behavior - recovery resets to clean state } -// Note: shutdown test disabled due to deadlock in event emission during shutdown -// This is a known limitation - shutdown should be called only when not holding locks -// test "lifecycle: shutdown force terminates" { ... } +test "lifecycle: shutdown completes cleanly" { + const allocator = testing.allocator; + + var instance = try P2P.init(allocator, createTestConfig()); + defer instance.deinit(); + + try instance.start(); + + // Process a few update cycles to let the system settle + var i: usize = 0; + while (i < 5) : (i += 1) { + try instance.update(); + std.Thread.sleep(10 * std.time.ns_per_ms); + } + + // Shutdown should complete without deadlock (H2 fix: event_mutex scoped in shutdownImpl) + try instance.stop(); + + // Verify state is stopped + try testing.expectEqual(P2PState.Initialized, instance.getState()); +} // ============================================================================ // TIER 1: Event System