//! Thread safety tests for Core module //! //! This test suite verifies that the thread-safe implementations of //! BufferPool, ConnectionPool, and SocketManager correctly handle //! concurrent access without data corruption or race conditions. const std = @import("std"); const testing = std.testing; const Thread = std.Thread; const time = std.time; const core = @import("core"); const Buffer = core.buffer; const Connection = core.connection; const Socket = core.socket; const Address = core.Address; const Error = core.Error; /// Test configuration const TestConfig = struct { num_threads: usize = 8, operations_per_thread: usize = 100, buffer_size: usize = 1024, }; /// Thread context for buffer pool tests const BufferPoolThreadContext = struct { pool: *Buffer.BufferPool, thread_id: usize, operations: usize, allocator: std.mem.Allocator, errors: std.atomic.Value(u32), success_count: std.atomic.Value(u32), }; /// Thread context for connection pool tests const ConnectionPoolThreadContext = struct { pool: *Connection.ConnectionPool, thread_id: usize, operations: usize, allocator: std.mem.Allocator, errors: std.atomic.Value(u32), success_count: std.atomic.Value(u32), }; /// Thread context for socket manager tests const SocketManagerThreadContext = struct { manager: *Socket.SocketManager, thread_id: usize, operations: usize, allocator: std.mem.Allocator, errors: std.atomic.Value(u32), success_count: std.atomic.Value(u32), }; /// Worker function for concurrent buffer pool operations fn bufferPoolWorker(context: *BufferPoolThreadContext) void { var i: usize = 0; while (i < context.operations) : (i += 1) { // Acquire buffer const buffer = context.pool.acquire(context.thread_id * 100 + 64) catch { _ = context.errors.fetchAdd(1, .monotonic); continue; }; // Simulate work with the buffer @memset(buffer, @as(u8, @truncate(context.thread_id))); // Small delay to increase chance of race conditions Thread.sleep(1 * time.ns_per_ms); // Verify buffer contents for (buffer) |byte| { if (byte != @as(u8, @truncate(context.thread_id))) { _ = context.errors.fetchAdd(1, .monotonic); break; } } // Release buffer context.pool.release(buffer); _ = context.success_count.fetchAdd(1, .monotonic); } } /// Worker function for concurrent connection pool operations fn connectionPoolWorker(context: *ConnectionPoolThreadContext) void { var connections = std.ArrayList(*Connection.Connection){}; defer { // Clean up connections created by this thread for (connections.items) |conn| { context.pool.removeConnection(conn); } connections.deinit(context.allocator); } var i: usize = 0; while (i < context.operations) : (i += 1) { // Create connection const conn_type: Connection.ConnectionType = if (i % 2 == 0) .tcp else .udp; const conn = context.pool.createConnection(conn_type) catch { _ = context.errors.fetchAdd(1, .monotonic); continue; }; connections.append(context.allocator, conn) catch { _ = context.errors.fetchAdd(1, .monotonic); continue; }; // Verify connection state if (conn.getState() != .disconnected) { _ = context.errors.fetchAdd(1, .monotonic); } // Small delay to increase chance of race conditions Thread.sleep(1 * time.ns_per_ms); _ = context.success_count.fetchAdd(1, .monotonic); } // Test finding connections const addr = Address.parse("127.0.0.1:8080") catch { _ = context.errors.fetchAdd(1, .monotonic); return; }; _ = context.pool.findConnectionByAddress(addr); // Test getting active connections var active = context.pool.getActiveConnections() catch { _ = context.errors.fetchAdd(1, .monotonic); return; }; active.deinit(context.allocator); } /// Worker function for concurrent socket manager operations fn socketManagerWorker(context: *SocketManagerThreadContext) void { // Store fds instead of pointers to avoid invalidation when ArrayList grows var socket_fds = std.ArrayList(std.posix.fd_t){}; defer { // Clean up sockets created by this thread using fd-based removal for (socket_fds.items) |fd| { context.manager.removeSocketByFd(fd); } socket_fds.deinit(context.allocator); } var i: usize = 0; while (i < context.operations) : (i += 1) { // Create socket (alternate between TCP and UDP) const sock = if (i % 2 == 0) context.manager.createTcpSocket() catch { _ = context.errors.fetchAdd(1, .monotonic); continue; } else context.manager.createUdpSocket() catch { _ = context.errors.fetchAdd(1, .monotonic); continue; }; // Store the fd immediately (before pointer might become invalid due to ArrayList growth) // Note: After storing, the sock pointer may become invalid if another thread // causes the SocketManager's ArrayList to reallocate const fd = sock.fd; socket_fds.append(context.allocator, fd) catch { _ = context.errors.fetchAdd(1, .monotonic); continue; }; // Small delay to increase chance of race conditions Thread.sleep(1 * time.ns_per_ms); _ = context.success_count.fetchAdd(1, .monotonic); } } test "BufferPool: concurrent acquire and release" { const config = Buffer.PoolConfig{ .min_chunk_size = 256, .max_chunk_size = 4096, .initial_chunks = 8, .max_chunks = 64, }; var pool = try Buffer.BufferPool.init(config, testing.allocator); defer pool.deinit(); const test_config = TestConfig{ .num_threads = 4, .operations_per_thread = 20, }; var threads: [4]Thread = undefined; var contexts: [4]BufferPoolThreadContext = undefined; // Initialize contexts for (&contexts, 0..) |*ctx, i| { ctx.* = .{ .pool = &pool, .thread_id = i, .operations = test_config.operations_per_thread, .allocator = testing.allocator, .errors = std.atomic.Value(u32).init(0), .success_count = std.atomic.Value(u32).init(0), }; } // Spawn threads for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, bufferPoolWorker, .{&contexts[i]}); } // Wait for all threads to complete for (&threads) |*thread| { thread.join(); } // Verify results var total_errors: u32 = 0; var total_success: u32 = 0; for (&contexts) |*ctx| { total_errors += ctx.errors.load(.monotonic); total_success += ctx.success_count.load(.monotonic); } std.debug.print("\n[BufferPool] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors }); // Check pool statistics const stats = pool.stats(); std.debug.print("[BufferPool] Pool stats - Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks }); // All buffers should be released try testing.expectEqual(@as(usize, 0), stats.used_chunks); // Should have no errors from data corruption try testing.expectEqual(@as(u32, 0), total_errors); } test "BufferPool: stress test with rapid allocation/deallocation" { const config = Buffer.PoolConfig{ .min_chunk_size = 128, .max_chunk_size = 2048, .initial_chunks = 2, .max_chunks = 64, }; var pool = try Buffer.BufferPool.init(config, testing.allocator); defer pool.deinit(); const test_config = TestConfig{ .num_threads = 16, .operations_per_thread = 25, }; var threads: [16]Thread = undefined; var contexts: [16]BufferPoolThreadContext = undefined; // Initialize contexts for (&contexts, 0..) |*ctx, i| { ctx.* = .{ .pool = &pool, .thread_id = i, .operations = test_config.operations_per_thread, .allocator = testing.allocator, .errors = std.atomic.Value(u32).init(0), .success_count = std.atomic.Value(u32).init(0), }; } // Spawn threads for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, bufferPoolWorker, .{&contexts[i]}); } // Wait for all threads for (&threads) |*thread| { thread.join(); } // Verify all buffers released const stats = pool.stats(); std.debug.print("[BufferPool Stress] Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks }); try testing.expectEqual(@as(usize, 0), stats.used_chunks); } test "ConnectionPool: concurrent create and remove operations" { const conn_config = Connection.ConnectionConfig{ .connection_type = .tcp, .buffer_size = 1024, }; var pool = Connection.ConnectionPool.init(conn_config, testing.allocator); defer pool.deinit(); const test_config = TestConfig{ .num_threads = 6, .operations_per_thread = 20, }; var threads: [6]Thread = undefined; var contexts: [6]ConnectionPoolThreadContext = undefined; // Initialize contexts for (&contexts, 0..) |*ctx, i| { ctx.* = .{ .pool = &pool, .thread_id = i, .operations = test_config.operations_per_thread, .allocator = testing.allocator, .errors = std.atomic.Value(u32).init(0), .success_count = std.atomic.Value(u32).init(0), }; } // Spawn threads for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, connectionPoolWorker, .{&contexts[i]}); } // Wait for all threads for (&threads) |*thread| { thread.join(); } // Verify results var total_errors: u32 = 0; var total_success: u32 = 0; for (&contexts) |*ctx| { total_errors += ctx.errors.load(.monotonic); total_success += ctx.success_count.load(.monotonic); } std.debug.print("\n[ConnectionPool] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors }); // Get pool statistics const stats = pool.getPoolStats(); std.debug.print("[ConnectionPool] Total connections: {}, Active: {}, Disconnected: {}\n", .{ stats.total_connections, stats.active_connections, stats.disconnected_connections }); // All connections should be removed by workers try testing.expectEqual(@as(usize, 0), stats.total_connections); } test "ConnectionPool: concurrent findConnectionByAddress" { const conn_config = Connection.ConnectionConfig{ .connection_type = .tcp, }; var pool = Connection.ConnectionPool.init(conn_config, testing.allocator); defer pool.deinit(); // Pre-create some connections const conn1 = try pool.createConnection(.tcp); const conn2 = try pool.createConnection(.udp); const conn3 = try pool.createConnection(.tcp); _ = conn1; _ = conn2; _ = conn3; _ = TestConfig{ .num_threads = 8, .operations_per_thread = 100, }; const ReadWorker = struct { fn run(p: *Connection.ConnectionPool) void { var i: usize = 0; while (i < 100) : (i += 1) { const addr = Address.parse("127.0.0.1:9999") catch unreachable; _ = p.findConnectionByAddress(addr); Thread.sleep(500 * time.ns_per_us); // 0.5ms } } }; var threads: [8]Thread = undefined; for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, ReadWorker.run, .{&pool}); } for (&threads) |*thread| { thread.join(); } // Verify pool is still intact const stats = pool.getPoolStats(); try testing.expectEqual(@as(usize, 3), stats.total_connections); } test "SocketManager: concurrent socket creation and removal" { var manager = Socket.SocketManager.init(testing.allocator); defer manager.deinit(); const test_config = TestConfig{ .num_threads = 6, .operations_per_thread = 20, }; var threads: [6]Thread = undefined; var contexts: [6]SocketManagerThreadContext = undefined; // Initialize contexts for (&contexts, 0..) |*ctx, i| { ctx.* = .{ .manager = &manager, .thread_id = i, .operations = test_config.operations_per_thread, .allocator = testing.allocator, .errors = std.atomic.Value(u32).init(0), .success_count = std.atomic.Value(u32).init(0), }; } // Spawn threads for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, socketManagerWorker, .{&contexts[i]}); } // Wait for all threads for (&threads) |*thread| { thread.join(); } // Verify results var total_errors: u32 = 0; var total_success: u32 = 0; for (&contexts) |*ctx| { total_errors += ctx.errors.load(.monotonic); total_success += ctx.success_count.load(.monotonic); } std.debug.print("\n[SocketManager] Successful operations: {}, Errors: {}\n", .{ total_success, total_errors }); // All sockets should be removed by workers try testing.expectEqual(@as(usize, 0), manager.sockets.items.len); } test "SocketManager: concurrent getActiveSockets" { var manager = Socket.SocketManager.init(testing.allocator); defer manager.deinit(); // Pre-create some sockets const sock1 = try manager.createTcpSocket(); const sock2 = try manager.createUdpSocket(); const sock3 = try manager.createTcpSocket(); _ = sock1; _ = sock2; _ = sock3; const ReadWorker = struct { fn run(mgr: *Socket.SocketManager, alloc: std.mem.Allocator) void { var i: usize = 0; while (i < 50) : (i += 1) { const active = mgr.getActiveSockets() catch return; alloc.free(active); Thread.sleep(1 * time.ns_per_ms); } } }; var threads: [8]Thread = undefined; for (&threads) |*thread| { thread.* = try Thread.spawn(.{}, ReadWorker.run, .{ &manager, testing.allocator }); } for (&threads) |*thread| { thread.join(); } // Verify manager is still intact try testing.expectEqual(@as(usize, 3), manager.sockets.items.len); } test "BufferPool: verify no memory leaks under concurrent load" { const config = Buffer.PoolConfig{ .min_chunk_size = 512, .max_chunk_size = 8192, .initial_chunks = 4, .max_chunks = 32, }; var pool = try Buffer.BufferPool.init(config, testing.allocator); defer pool.deinit(); const Worker = struct { fn run(p: *Buffer.BufferPool, thread_id: usize) void { var buffers: [10][]u8 = undefined; var acquired: usize = 0; // Acquire multiple buffers while (acquired < 10) : (acquired += 1) { buffers[acquired] = p.acquire(512 + thread_id * 64) catch break; } // Release all acquired buffers (important: release what we got, even if we didn't get all) var i: usize = 0; while (i < acquired) : (i += 1) { p.release(buffers[i]); } } }; var threads: [10]Thread = undefined; for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, Worker.run, .{ &pool, i }); } for (&threads) |*thread| { thread.join(); } const stats = pool.stats(); std.debug.print("[Memory Leak Test] Total chunks: {}, Used: {}, Free: {}\n", .{ stats.total_chunks, stats.used_chunks, stats.free_chunks }); // All buffers must be released try testing.expectEqual(@as(usize, 0), stats.used_chunks); } test "Mixed operations: ConnectionPool + BufferPool concurrency" { // Test interaction between connection pool and buffer pool under load const conn_config = Connection.ConnectionConfig{ .connection_type = .tcp, .buffer_size = 2048, }; var conn_pool = Connection.ConnectionPool.init(conn_config, testing.allocator); defer conn_pool.deinit(); const MixedWorker = struct { fn run(pool: *Connection.ConnectionPool, _: usize) void { var i: usize = 0; while (i < 30) : (i += 1) { const conn = pool.createConnection(.tcp) catch return; // Create buffers through the connection var send_buf = conn.createSendBuffer() catch { pool.removeConnection(conn); return; }; var recv_buf = conn.createReceiveBuffer() catch { send_buf.release(); pool.removeConnection(conn); return; }; // Simulate some work const test_data = "Thread data"; send_buf.write(test_data) catch {}; Thread.sleep(1 * time.ns_per_ms); // Release buffers BEFORE removing the connection recv_buf.release(); send_buf.release(); pool.removeConnection(conn); } } }; var threads: [6]Thread = undefined; for (&threads, 0..) |*thread, i| { thread.* = try Thread.spawn(.{}, MixedWorker.run, .{ &conn_pool, i }); } for (&threads) |*thread| { thread.join(); } const stats = conn_pool.getPoolStats(); std.debug.print("[Mixed Test] Connections remaining: {}\n", .{stats.total_connections}); try testing.expectEqual(@as(usize, 0), stats.total_connections); }