//! Comprehensive race condition tests for P2P library //! //! This test file verifies that all atomic operations and concurrent data structures //! work correctly under heavy concurrent load from multiple threads. const std = @import("std"); const testing = std.testing; const Thread = std.Thread; const Allocator = std.mem.Allocator; // Import from same directory const upload = @import("upload.zig"); const download = @import("download.zig"); const transfer = @import("transfer.zig"); const file_manager = @import("manager.zig"); const UploadState = upload.UploadState; const DownloadState = download.DownloadState; const RateLimiter = transfer.RateLimiter; const FileSharingManager = file_manager.FileSharingManager; const FileSharingConfig = file_manager.FileSharingConfig; /// Number of threads to use for concurrent tests const NUM_THREADS = 8; /// Number of operations per thread const OPS_PER_THREAD = 1000; // Test UploadState under concurrent updates from multiple threads test "UploadState: concurrent addUploadedBytes" { var state = UploadState.init(1024 * 1024 * 1024); // 1GB max // Create threads that will concurrently add bytes var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { state: *UploadState, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { ctx.state.addUploadedBytes(100); } } }; const ctx = ThreadContext{ .state = &state }; // Spawn threads for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } // Wait for all threads for (threads) |thread| { thread.join(); } // Verify total uploaded bytes const expected_total = NUM_THREADS * OPS_PER_THREAD * 100; const actual_total = state.total_uploaded.load(.monotonic); const actual_bandwidth = state.upload_bandwidth.load(.monotonic); try testing.expectEqual(@as(u64, expected_total), actual_total); try testing.expectEqual(@as(u64, expected_total), actual_bandwidth); } // Test UploadState: concurrent startUpload/completeUpload operations test "UploadState: concurrent upload lifecycle" { var state = UploadState.init(1024 * 1024 * 1024); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { state: *UploadState, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { ctx.state.startUpload(); // Simulate some work std.time.sleep(1); ctx.state.completeUpload(); } } }; const ctx = ThreadContext{ .state = &state }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // After all threads complete, active should be 0 and completed should equal total ops const active = state.active_uploads.load(.monotonic); const completed = state.completed_uploads.load(.monotonic); try testing.expectEqual(@as(u32, 0), active); try testing.expectEqual(@as(u32, NUM_THREADS * OPS_PER_THREAD), completed); } // Test DownloadState under concurrent updates test "DownloadState: concurrent addDownloadedBytes" { var state = DownloadState.init(1024 * 1024 * 1024, 1000); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { state: *DownloadState, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { ctx.state.addDownloadedBytes(50); ctx.state.addVerifiedBytes(50); } } }; const ctx = ThreadContext{ .state = &state }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } const expected = NUM_THREADS * OPS_PER_THREAD * 50; const downloaded = state.downloaded_bytes.load(.monotonic); const verified = state.verified_bytes.load(.monotonic); try testing.expectEqual(@as(u64, expected), downloaded); try testing.expectEqual(@as(u64, expected), verified); } // Test DownloadState: concurrent piece completion test "DownloadState: concurrent piece marking" { var state = DownloadState.init(1024 * 1024 * 1024, 10000); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { state: *DownloadState, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { ctx.state.markPieceCompleted(); } } }; const ctx = ThreadContext{ .state = &state }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } const completed = state.completed_pieces.load(.monotonic); try testing.expectEqual(@as(u32, NUM_THREADS * OPS_PER_THREAD), completed); } // Test RateLimiter under concurrent transfer start/complete operations test "RateLimiter: concurrent startTransfer/completeTransfer" { var limiter = RateLimiter.init(); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { limiter: *RateLimiter, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { // Start transfer ctx.limiter.startTransfer(1024); // Simulate transfer std.time.sleep(1); // Complete transfer ctx.limiter.completeTransfer(1024); } } }; const ctx = ThreadContext{ .limiter = &limiter }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // After all operations, active transfers should be 0 const active = limiter.active_transfers.load(.monotonic); try testing.expectEqual(@as(usize, 0), active); // Bandwidth should also be 0 (or very close due to race windows) const bandwidth = limiter.current_bandwidth.load(.monotonic); try testing.expect(bandwidth < 1024 * 10); // Allow small tolerance } // Test RateLimiter: concurrent bandwidth updates stress test test "RateLimiter: heavy concurrent bandwidth updates" { var limiter = RateLimiter.init(); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { limiter: *RateLimiter, thread_id: usize, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { // Use different sizes to create varied load const size = (ctx.thread_id + 1) * 512; ctx.limiter.startTransfer(size); // Small sleep to allow interleaving if (i % 10 == 0) { std.time.sleep(1); } ctx.limiter.completeTransfer(size); } } }; for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .limiter = &limiter, .thread_id = i }; thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // Verify consistency const active = limiter.active_transfers.load(.monotonic); const bandwidth = limiter.current_bandwidth.load(.monotonic); try testing.expectEqual(@as(usize, 0), active); // Bandwidth should be minimal (allow small tolerance for in-flight operations) try testing.expect(bandwidth < 1024 * 100); } // Test FileSharingManager: concurrent session cleanup test "FileSharingManager: concurrent session operations" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var mgr = try FileSharingManager.init(config, allocator); defer mgr.deinit(); // This test verifies that the two-phase cleanup approach in // cleanupCompletedSessions works correctly by calling it many times // concurrently. We can't easily create sessions from multiple threads, // but we can verify cleanup doesn't crash. var threads: [NUM_THREADS / 2]Thread = undefined; const ThreadContext = struct { manager: *FileSharingManager, fn worker(ctx: @This()) void { var i: usize = 0; while (i < 100) : (i += 1) { // Call processSessions which internally calls cleanupCompletedSessions ctx.manager.processSessions() catch {}; std.time.sleep(std.time.ns_per_ms); } } }; const ctx = ThreadContext{ .manager = &mgr }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // If we got here without crashing, the iterator-while-modifying fix works try testing.expect(true); } // Test mixed operations: Simulate realistic concurrent usage test "Mixed operations: realistic concurrent scenario" { const allocator = testing.allocator; var upload_state = UploadState.init(1024 * 1024 * 100); var download_state = DownloadState.init(1024 * 1024 * 100, 1000); var rate_limiter = RateLimiter.init(); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { upload_state: *UploadState, download_state: *DownloadState, rate_limiter: *RateLimiter, thread_id: usize, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD / 2) : (i += 1) { // Simulate upload if (ctx.thread_id % 2 == 0) { ctx.upload_state.startUpload(); ctx.upload_state.addUploadedBytes(512); std.time.sleep(1); ctx.upload_state.completeUpload(); } // Simulate download if (ctx.thread_id % 2 == 1) { ctx.download_state.addDownloadedBytes(256); ctx.download_state.addVerifiedBytes(256); if (i % 10 == 0) { ctx.download_state.markPieceCompleted(); } } // Rate limiting ctx.rate_limiter.startTransfer(1024); std.time.sleep(1); ctx.rate_limiter.completeTransfer(1024); } } }; for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .upload_state = &upload_state, .download_state = &download_state, .rate_limiter = &rate_limiter, .thread_id = i, }; thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // Verify final consistency const upload_active = upload_state.active_uploads.load(.monotonic); const limiter_active = rate_limiter.active_transfers.load(.monotonic); try testing.expectEqual(@as(u32, 0), upload_active); try testing.expectEqual(@as(usize, 0), limiter_active); // All operations completed without crashes - test passed _ = allocator; } // Test atomic fetchAdd operations maintain correct totals test "Atomic operations: fetchAdd accumulation correctness" { var state = UploadState.init(1024 * 1024 * 1024); var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { state: *UploadState, thread_id: usize, fn worker(ctx: @This()) void { // Each thread adds a unique value based on its ID const value_to_add = (ctx.thread_id + 1) * 100; var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { ctx.state.addUploadedBytes(value_to_add); } } }; for (&threads, 0..) |*thread, i| { const ctx = ThreadContext{ .state = &state, .thread_id = i }; thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // Calculate expected total: sum of (thread_id+1)*100*OPS_PER_THREAD for each thread var expected: u64 = 0; var tid: usize = 0; while (tid < NUM_THREADS) : (tid += 1) { expected += (tid + 1) * 100 * OPS_PER_THREAD; } const actual = state.total_uploaded.load(.monotonic); try testing.expectEqual(expected, actual); } // Test that CAS-based operations (like completeTransfer) handle contention correctly test "RateLimiter: CAS operation under high contention" { var limiter = RateLimiter.init(); // Pre-load some bandwidth limiter.startTransfer(1024 * 1024); // Start with 1MB var threads: [NUM_THREADS]Thread = undefined; const ThreadContext = struct { limiter: *RateLimiter, fn worker(ctx: @This()) void { var i: usize = 0; while (i < OPS_PER_THREAD) : (i += 1) { // Repeatedly try to complete transfers of varying sizes // This creates high contention on the CAS operation ctx.limiter.completeTransfer(1024); } } }; const ctx = ThreadContext{ .limiter = &limiter }; for (&threads) |*thread| { thread.* = Thread.spawn(.{}, ThreadContext.worker, .{ctx}) catch unreachable; } for (threads) |thread| { thread.join(); } // Bandwidth should have gone to zero (saturating subtraction) const bandwidth = limiter.current_bandwidth.load(.monotonic); try testing.expectEqual(@as(u64, 0), bandwidth); }