//! Tests for piece selection algorithms and tracking const std = @import("std"); const testing = std.testing; const PieceModule = @import("../src/files/piece.zig"); const { PieceAvailability, PieceSelector, SelectionStrategy, PiecePool, SelectionStats, PieceData } = PieceModule; test "piece availability creation and basic operations" { const availability = PieceAvailability.create(5, 3); try testing.expectEqual(@as(u32, 5), availability.piece_index); try testing.expectEqual(@as(u32, 3), availability.available_peers); try testing.expect(!availability.is_downloaded); try testing.expect(!availability.is_verified); try testing.expect(availability.isReady()); try testing.expectEqual(PieceAvailability.Priority.normal, availability.priority); } test "piece availability marking as downloaded" { var availability = PieceAvailability.create(0, 2); // Initially not downloaded try testing.expect(!availability.is_downloaded); try testing.expect(!availability.is_verified); try testing.expect(availability.isReady()); // Mark as downloaded availability.markDownloaded(); try testing.expect(availability.is_downloaded); try testing.expect(!availability.is_verified); try testing.expect(!availability.isReady()); // Should no longer be ready // Mark as verified availability.markVerified(); try testing.expect(availability.is_downloaded); try testing.expect(availability.is_verified); try testing.expect(!availability.isReady()); } test "piece availability priority settings" { var availability = PieceAvailability.create(0, 1); // Test different priority levels const priorities = .{ PieceAvailability.Priority.low, .normal, .high, .immediate }; for (priorities) |priority| { availability.setPriority(priority); try testing.expectEqual(priority, availability.priority); } } test "piece availability scoring" { // Test scoring with different availability and priorities const test_cases = .{ .{ @as(u32, 1), PieceAvailability.Priority.low, true, false }, .{ @as(u32, 5), PieceAvailability.Priority.normal, false, false }, .{ @as(u32, 2), PieceAvailability.Priority.high, false, false }, .{ @as(u32, 0), PieceAvailability.Priority.immediate, true, true }, }; for (test_cases) |test_case| { const available_peers = test_case[0]; const priority = test_case[1]; const is_downloaded = test_case[2]; const is_verified = test_case[3]; var availability = PieceAvailability.create(0, available_peers); availability.setPriority(priority); if (is_downloaded) { availability.markDownloaded(); } if (is_verified) { availability.markVerified(); } const score = availability.getScore(); // Priority should significantly impact score if (priority == .immediate) { try testing.expect(score > 2000); } else if (priority == .high) { try testing.expect(score > 1000); } // Downloaded pieces should have very low score if (is_downloaded) { try testing.expect(score < 0); } } } test "piece selector creation and initialization" { const allocator = testing.allocator; const seed: u64 = 12345; const strategy = SelectionStrategy.rarest_first; var selector = PieceSelector.init(strategy, seed, allocator); defer selector.deinit(); try testing.expectEqual(strategy, selector.strategy); try testing.expectEqual(@as(usize, 0), selector.availability_map.count()); try testing.expect(!selector.isComplete()); try testing.expectEqual(@as(f32, 0.0), selector.getProgress()); } test "piece selector adding and updating pieces" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces try selector.addPiece(0, 3); try selector.addPiece(1, 1); try selector.addPiece(2, 5); try testing.expectEqual(@as(usize, 3), selector.availability_map.count()); // Update availability try selector.updateAvailability(1, 2); // Piece 1 now has 2 peers try selector.updateAvailability(0, 0); // Piece 0 now has 0 peers (unavailable) // Check updates const piece0 = selector.availability_map.get(0).?; const piece1 = selector.availability_map.get(1).?; const piece2 = selector.availability_map.get(2).?; try testing.expectEqual(@as(u32, 0), piece0.available_peers); try testing.expectEqual(@as(u32, 2), piece1.available_peers); try testing.expectEqual(@as(u32, 5), piece2.available_peers); } test "piece selector rarest first selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces with different availability try selector.addPiece(0, 5); // Most common try selector.addPiece(1, 1); // Rarest try selector.addPiece(2, 3); // Medium try selector.addPiece(3, 2); // Medium-rare try selector.addPiece(4, 4); // Common const selected = try selector.selectNext(null); defer allocator.free(selected); // Should be sorted by availability (ascending) try testing.expectEqual(@as(u32, 1), selected[0]); // Rarest (1 peer) try testing.expectEqual(@as(u32, 3), selected[1]); // Medium-rare (2 peers) try testing.expectEqual(@as(u32, 2), selected[2]); // Medium (3 peers) try testing.expectEqual(@as(u32, 4), selected[3]); // Common (4 peers) try testing.expectEqual(@as(u32, 0), selected[4]); // Most common (5 peers) } test "piece selector random selection" { const allocator = testing.allocator; const seed: u64 = 98765; // Create two selectors with same seed var selector1 = PieceSelector.init(.random, seed, allocator); var selector2 = PieceSelector.init(.random, seed, allocator); defer selector1.deinit(); defer selector2.deinit(); // Add same pieces to both for (0..5) |i| { try selector1.addPiece(@as(u32, @intCast(i)), 3); try selector2.addPiece(@as(u32, @intCast(i)), 3); } const selected1 = try selector1.selectNext(null); const selected2 = try selector2.selectNext(null); defer allocator.free(selected1); defer allocator.free(selected2); // Should be in same order due to same seed try testing.expectEqualSlices(u32, selected1, selected2); // Test with different seed var selector3 = PieceSelector.init(.random, 11111, allocator); defer selector3.deinit(); for (0..5) |i| { try selector3.addPiece(@as(u32, @intCast(i)), 3); } const selected3 = try selector3.selectNext(null); defer allocator.free(selected3); // Should be in different order try testing.expect(!mem.eql(u32, selected1, selected3)); } test "piece selector sequential selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.sequential, 12345, allocator); defer selector.deinit(); // Add pieces in random order try selector.addPiece(3, 2); try selector.addPiece(1, 3); try selector.addPiece(4, 1); try selector.addPiece(0, 4); try selector.addPiece(2, 5); const selected = try selector.selectNext(null); defer allocator.free(selected); // Should be sorted by index for (selected, 0..) |piece_index, i| { try testing.expectEqual(@as(u32, @intCast(i)), piece_index); } } test "piece selector priority first selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.priority_first, 12345, allocator); defer selector.deinit(); // Add pieces with different priorities try selector.addPiece(0, 3); try selector.setPriority(0, .normal); try selector.addPiece(1, 3); try selector.setPriority(1, .high); try selector.addPiece(2, 3); try selector.setPriority(2, .low); try selector.addPiece(3, 3); try selector.setPriority(3, .immediate); try selector.addPiece(4, 3); try selector.setPriority(4, .normal); const selected = try selector.selectNext(null); defer allocator.free(selected); // Should be sorted by priority (high to low) try testing.expectEqual(@as(u32, 3), selected[0]); // immediate try testing.expectEqual(@as(u32, 1), selected[1]); // high try testing.expectEqual(@as(u32, 0), selected[2]); // normal try testing.expectEqual(@as(u32, 4), selected[3]); // normal (same priority, by index) try testing.expectEqual(@as(u32, 2), selected[4]); // low } test "piece selector balanced selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.balanced, 12345, allocator); defer selector.deinit(); // Add pieces with mixed priorities and availability try selector.addPiece(0, 1); // Rare, normal priority try selector.setPriority(0, .normal); try selector.addPiece(1, 5); // Common, high priority try selector.setPriority(1, .high); try selector.addPiece(2, 2); // Medium, low priority try selector.setPriority(2, .low); try selector.addPiece(3, 1); // Rare, immediate priority try selector.setPriority(3, .immediate); try selector.addPiece(4, 3); // Medium, normal priority try selector.setPriority(4, .normal); const selected = try selector.selectNext(null); defer allocator.free(selected); // High and immediate priority should come first (sorted by rarity within priority) try testing.expect(selected[0] == 3 or selected[0] == 1); // immediate or high priority try testing.expect(selected[1] == 3 or selected[1] == 1); // immediate or high priority // Normal priority should come next (sorted by rarity) const normal_pieces = &.{ selected[2], selected[3] }; try testing.expect(mem.sort(u32, normal_pieces, &selector, compareByAvailability) == void); } test "piece selector max pieces limit" { const allocator = testing.allocator; var selector = PieceSelector.init(.sequential, 12345, allocator); defer selector.deinit(); // Add many pieces for (0..20) |i| { try selector.addPiece(@as(u32, @intCast(i)), 1); } // Limit selection to 5 pieces const selected = try selector.selectNext(5); defer allocator.free(selected); try testing.expectEqual(@as(usize, 5), selected.len); // Should be the first 5 pieces in sequential order for (selected, 0..) |piece_index, i| { try testing.expectEqual(@as(u32, @intCast(i)), piece_index); } } test "piece selector with downloaded pieces" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces and mark some as downloaded try selector.addPiece(0, 1); try selector.addPiece(1, 3); try selector.addPiece(2, 2); try selector.markDownloaded(1); try selector.markDownloaded(2); // Only piece 0 should be available for selection const selected = try selector.selectNext(null); defer allocator.free(selected); try testing.expectEqual(@as(u32, 0), selected[0]); try testing.expectEqual(@as(usize, 1), selected.len); } test "piece selector verification marking" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces and mark some as verified try selector.addPiece(0, 1); try selector.addPiece(1, 2); try selector.addPiece(2, 3); try selector.markDownloaded(1); try selector.markVerified(1); try selector.markDownloaded(2); const selected = try selector.selectNext(null); defer allocator.free(selected); // Only piece 0 should be available (piece 1 is verified, piece 2 is downloaded but not verified) try testing.expectEqual(@as(u32, 0), selected[0]); try testing.expectEqual(@as(usize, 1), selected.len); } test "piece selector progress calculation" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Initially no progress try testing.expectEqual(@as(f32, 0.0), selector.getProgress()); try testing.expect(!selector.isComplete()); // Add pieces for (0..10) |i| { try selector.addPiece(@as(u32, @intCast(i)), 1); } // Still no progress try testing.expectEqual(@as(f32, 0.0), selector.getProgress()); // Mark some as verified for (0..5) |i| { try selector.markDownloaded(@as(u32, @intCast(i))); try selector.markVerified(@as(u32, @intCast(i))); } // 50% progress try testing.expectEqual(@as(f32, 0.5), selector.getProgress()); try testing.expect(!selector.isComplete()); // Mark all as verified for (5..10) |i| { try selector.markDownloaded(@as(u32, @intCast(i))); try selector.markVerified(@as(u32, @intCast(i))); } // 100% progress try testing.expectEqual(@as(f32, 1.0), selector.getProgress()); try testing.expect(selector.isComplete()); } test "piece selector statistics" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add various pieces try selector.addPiece(0, 2); // Normal try selector.addPiece(1, 0); // Unavailable try selector.addPiece(2, 5); // Common try selector.addPiece(3, 1); // Rare try selector.markDownloaded(2); try selector.markVerified(2); try selector.markDownloaded(3); // Not verified yet const stats = selector.getStats(); try testing.expectEqual(@as(usize, 3), stats.total_pieces); // 4 added, 1 unavailable doesn't count? try testing.expectEqual(@as(usize, 2), stats.downloaded_pieces); try testing.expectEqual(@as(usize, 1), stats.verified_pieces); try testing.expectEqual(@as(usize, 1), stats.unavailable_pieces); // Test completion percentage try testing.expectEqual(@as(f32, 33.33), @as(f32, @floatFromInt(stats.verified_pieces)) / @as(f32, @floatFromInt(stats.total_pieces)) * 100.0); // Test average availability const expected_avg = @as(f32, @floatFromInt(2 + 0 + 5 + 1)) / @as(f32, @floatFromInt(4)); try testing.expectEqual(expected_avg, stats.getAverageAvailability()); } test "piece pool operations" { const allocator = testing.allocator; var pool = PiecePool.init(allocator); defer pool.deinit(); // Initially empty try testing.expectEqual(@as(usize, 0), pool.count()); try testing.expect(!pool.hasPiece(0)); // Add piece data const test_data1 = "Piece 0 data content"; const test_data2 = "Piece 1 data content"; const hash1 = [_]u8{1} ** 32; const hash2 = [_]u8{2} ** 32; const piece1 = PieceData{ .index = 0, .data = test_data1, .hash = hash1 }; const piece2 = PieceData{ .index = 1, .data = test_data2, .hash = hash2 }; try pool.addPiece(piece1); try pool.addPiece(piece2); try testing.expectEqual(@as(usize, 2), pool.count()); try testing.expect(pool.hasPiece(0)); try testing.expect(pool.hasPiece(1)); try testing.expect(!pool.hasPiece(2)); // Retrieve pieces const retrieved1 = pool.getPiece(0).?; const retrieved2 = pool.getPiece(1).?; try testing.expectEqual(@as(u32, 0), retrieved1.index); try testing.expectEqualSlices(u8, test_data1, retrieved1.data); try testing.expect(mem.eql(u8, &hash1, &retrieved1.hash)); try testing.expectEqual(@as(u32, 1), retrieved2.index); try testing.expectEqualSlices(u8, test_data2, retrieved2.data); try testing.expect(mem.eql(u8, &hash2, &retrieved2.hash)); // Get piece indices const indices = pool.getPieceIndices(); defer allocator.free(indices); try testing.expectEqual(@as(usize, 2), indices.len); // Order might vary, so check both pieces are present var found_0 = false; var found_1 = false; for (indices) |idx| { if (idx == 0) found_0 = true; if (idx == 1) found_1 = true; } try testing.expect(found_0); try testing.expect(found_1); // Remove piece pool.removePiece(0); try testing.expectEqual(@as(usize, 1), pool.count()); try testing.expect(!pool.hasPiece(0)); try testing.expect(pool.hasPiece(1)); // Clear all pool.clear(); try testing.expectEqual(@as(usize, 0), pool.count()); try testing.expect(!pool.hasPiece(1)); } test "piece pool memory management" { const allocator = testing.allocator; var pool = PiecePool.init(allocator); defer pool.deinit(); // Add piece with allocated data const original_data = allocator.alloc(u8, 100) catch return; @memcpy(original_data, "Test data for memory management"); const hash = [_]u8{0} ** 32; const piece = PieceData{ .index = 0, .data = original_data, .hash = hash, }; try pool.addPiece(piece); // Original data can be freed (pool should have copied it) allocator.free(original_data); // Pool should still have the piece data const retrieved = pool.getPiece(0).?; try testing.expectEqual(@as(u32, 0), retrieved.index); // Clean up pool.removePiece(0); } test "compare functions" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Test compareByIndex try testing.expect(compareByIndex({}, 1, 2)); try testing.expect(!compareByIndex({}, 2, 1)); try testing.expect(!compareByIndex({}, 1, 1)); // Add pieces for other tests try selector.addPiece(0, 2); try selector.addPiece(1, 1); try selector.addPiece(2, 3); // Test compareByAvailability try testing.expect(compareByAvailability(&selector, 1, 0)); // Piece 1 has 1 peer, piece 0 has 2 try testing.expect(compareByAvailability(&selector, 1, 2)); // Piece 1 has 1 peer, piece 2 has 3 try testing.expect(!compareByAvailability(&selector, 0, 1)); // Piece 0 has 2 peers, piece 1 has 1 } test "piece selector with no ready pieces" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces but mark all as unavailable or downloaded try selector.addPiece(0, 0); // Unavailable try selector.addPiece(1, 1); try selector.markDownloaded(1); try selector.markVerified(1); // No pieces should be ready const selected = try selector.selectNext(null); defer allocator.free(selected); try testing.expectEqual(@as(usize, 0), selected.len); } test "piece selector error handling" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add a piece try selector.addPiece(0, 1); // Try to get a non-existent piece try testing.expect(selector.availability_map.get(999) == null); // Try to select from empty selector var empty_selector = PieceSelector.init(.sequential, 12345, allocator); defer empty_selector.deinit(); const empty_selected = try empty_selector.selectNext(null); defer allocator.free(empty_selected); try testing.expectEqual(@as(usize, 0), empty_selected.len); } test "rate limiting configuration" { const rate_limit = PieceModule.RateLimit{ .max_pieces_per_second = 5.0, .max_concurrent_downloads = 3, .bandwidth_limit_bps = 512 * 1024, // 512KB/s }; // Test delay calculation const delay_1mb = rate_limit.calculateDelay(1024 * 1024); try testing.expect(delay_1mb > 0); // With 5 pieces per second and 1MB pieces, should take 0.2 seconds per piece try testing.expect(@abs(delay_1mb - 0.2) < 0.01); } test "piece selector rate limiting" { const allocator = testing.allocator; var selector = PieceSelector.init(.rarest_first, 12345, allocator); defer selector.deinit(); // Add pieces try selector.addPiece(0, 1); try selector.addPiece(1, 2); try selector.addPiece(2, 3); // Should be able to start downloads try testing.expect(selector.canStartDownload(0)); try testing.expect(selector.canStartDownload(1)); // Start some downloads try selector.startDownload(0); try selector.startDownload(1); // Should now have 2 active downloads (under limit of 5) try testing.expect(selector.canStartDownload(2)); // Complete downloads selector.completeDownload(0); selector.completeDownload(1); // Should be able to start again try testing.expect(selector.canStartDownload(0)); } test "piece selector bandwidth optimized selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.bandwidth_optimized, 12345, allocator); defer selector.deinit(); // Add pieces with different availability try selector.addPiece(0, 1); // Rare try selector.addPiece(1, 5); // Common try selector.addPiece(2, 3); // Medium try selector.addPiece(3, 2); // Medium-rare // Set different priorities try selector.setPriority(0, .high); // Rare + high priority try selector.setPriority(1, .low); // Common + low priority try selector.setPriority(2, .normal); // Medium + normal try selector.setPriority(3, .immediate); // Medium-rare + immediate const selected = try selector.selectNext(null); defer allocator.free(selected); // Should prioritize high availability pieces with good priority // Piece 3 (immediate priority) should be first or second try testing.expect(selected[0] == 3 or selected[1] == 3); // Piece 0 (rare + high priority) should be in top positions const rare_index = for (selected, 0..) |piece, i| { if (piece == 0) break i; } else selected.len; try testing.expect(rare_index < 3); // Should be in top 3 } test "piece selector network aware selection" { const allocator = testing.allocator; var selector = PieceSelector.init(.network_aware, 12345, allocator); defer selector.deinit(); // Add pieces with different characteristics try selector.addPiece(0, 1); // Very rare try selector.addPiece(1, 10); // Very common try selector.addPiece(2, 3); // Medium try selector.addPiece(3, 2); // Medium-rare const selected = try selector.selectNext(null); defer allocator.free(selected); // Network-aware should balance rarity with availability // Very rare piece (0) should be prioritized for diversity // Medium-rare pieces should also be favored try testing.expect(selected[0] == 0 or selected[0] == 3); // Either rarest or most balanced }