using System.Diagnostics;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class FileIndexPerformanceTests
{
[Test]
[Explicit]
public static async Task FileIndexSingleRootRemainsSearchableDuringScanAndCacheHydration()
{
using var tree = new LargeSearchTree();
var preparation = Stopwatch.StartNew();
const int folderCount = 256;
const int filesPerFolder = 128;
for (var folder = 0; folder < folderCount; folder++)
{
var directory = Directory.CreateDirectory(Path.Combine(tree.Root, $"project-{folder:D4}")).FullName;
for (var file = 0; file < filesPerFolder; file++)
using (File.Create(Path.Combine(directory, $"report-{folder:D4}-{file:D4}.txt"))) { }
}
Console.WriteLine($"Large-tree preparation: {preparation.Elapsed.TotalMilliseconds:N0} ms");
var watch = Stopwatch.StartNew();
await using (var service = new FileIndexService(tree.Options))
{
var rebuilding = service.RebuildAsync();
var maximumRead = TimeSpan.Zero;
var readCount = 0;
var firstResults = TimeSpan.Zero;
while (!rebuilding.IsCompleted)
{
var query = Stopwatch.StartNew();
var result = await Task.Run(() => service.Index.Search("report-0123", limit: 5));
if (query.Elapsed > maximumRead)
maximumRead = query.Elapsed;
if (firstResults == TimeSpan.Zero && service.Index.Count > 256)
firstResults = watch.Elapsed;
readCount++;
await Task.Delay(10);
}
await rebuilding;
Ensure(service.Index.Count == folderCount * (filesPerFolder + 1) + 1,
$"The single-root scan lost or duplicated entries: {service.Index.Count}.");
Ensure(service.Index.Search("report-0123").TotalMatches == filesPerFolder,
"Searching while the index was being populated corrupted postings.");
Ensure(readCount > 0, "Indexing should permit concurrent queries.");
Ensure(maximumRead < TimeSpan.FromSeconds(5), "A scan blocked a concurrent search for several seconds.");
Console.WriteLine($"Single-root files: {folderCount * filesPerFolder:N0}; scan/cache {watch.Elapsed.TotalMilliseconds:N0} ms; " +
$"first results {firstResults.TotalMilliseconds:N0} ms; concurrent reads {readCount}; longest read {maximumRead.TotalMilliseconds:N0} ms");
}
watch.Restart();
await using (var restarted = new FileIndexService(tree.Options))
{
var loading = restarted.StartAsync();
while (!loading.IsCompleted)
{
_ = restarted.Index.Count;
await Task.Delay(1);
}
await loading;
Ensure(restarted.Index.Search("report-0123").TotalMatches == filesPerFolder,
"A restored index must immediately provide the saved search results.");
Console.WriteLine($"Cache hydration: {watch.Elapsed.TotalMilliseconds:N0} ms");
restarted.RequestStop();
}
}
[Test]
public static async Task FileIndexOverlappingRootsDoNotDuplicateDirectoryTraversal()
{
using var tree = new LargeSearchTree();
var nested = Directory.CreateDirectory(Path.Combine(tree.Root, "priority")).FullName;
var deep = Directory.CreateDirectory(Path.Combine(nested, "deep")).FullName;
var file = Path.Combine(deep, "priority-document.txt");
File.WriteAllText(file, "priority");
await using var service = new FileIndexService(tree.Options with { Roots = [deep, nested, tree.Root] });
await service.RebuildAsync();
Ensure(service.Index.Count == 4 && service.Index.Search("priority-document").TotalMatches == 1,
"Prioritized nested roots must be visited once and remain searchable.");
}
[Test]
public static async Task FileIndexLargeCacheHydratesInSearchableBatches()
{
using var tree = new LargeSearchTree();
const int count = 100_000;
WriteSyntheticCache(tree, count, count);
await using var service = new FileIndexService(tree.Options);
var loading = service.StartAsync();
var sawSearchablePrefix = false;
while (!loading.IsCompleted)
{
var indexed = service.Index.Count;
if (indexed > 0 && indexed < count)
{
var result = await Task.Run(() => service.Index.Search("sample-000001", limit: 1));
sawSearchablePrefix |= result.TotalMatches == 1;
}
await Task.Delay(1);
}
await loading;
service.RequestStop();
Ensure(sawSearchablePrefix,
"Large cached indexes should provide searchable batches before the complete cache is decoded.");
}
[Test]
public static async Task FileIndexCorruptStreamingCacheDiscardsPublishedPrefix()
{
using var tree = new LargeSearchTree();
WriteSyntheticCache(tree, declaredCount: 1024, actualCount: 512);
await using var service = new FileIndexService(tree.Options);
await service.StartAsync();
Ensure(service.Index.Search("sample-").TotalMatches == 0,
"A truncated cache must discard even the batches that were published before corruption was detected.");
await service.RebuildAsync();
Ensure(service.Index.Count == 1, "A corrupt streamed snapshot must recover to the actual filesystem.");
}
private static void WriteSyntheticCache(LargeSearchTree tree, int declaredCount, int actualCount)
{
Directory.CreateDirectory(tree.Options.CacheDirectory);
using var file = File.Create(Path.Combine(tree.Options.CacheDirectory, "files.v1.gz"));
using var compressed = new GZipStream(file, CompressionLevel.Fastest);
using var writer = new BinaryWriter(compressed, Encoding.UTF8);
writer.Write(0x58464958);
writer.Write(1);
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(tree.Root));
WriteCacheString(writer, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
OperatingSystem.IsWindows() ? root.ToUpperInvariant() : root))));
writer.Write(declaredCount);
for (var index = 0; index < actualCount; index++)
{
WriteCacheString(writer, Path.Combine(tree.Root, $"sample-{index:D6}.txt"));
writer.Write((byte)0);
}
}
private static void WriteCacheString(BinaryWriter writer, string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
writer.Write(bytes.Length);
writer.Write(bytes);
}
private static void Ensure(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
private sealed class LargeSearchTree : IDisposable
{
public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-file-performance-" + Guid.NewGuid().ToString("N"));
public FileIndexOptions Options => new() { Roots = [Root], CacheDirectory = Path.Combine(Root, ".cache"), MaxParallelism = 2 };
public LargeSearchTree() => Directory.CreateDirectory(Root);
public void Dispose()
{
var target = Path.GetFullPath(Root);
var parent = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) + Path.DirectorySeparatorChar;
if (!target.StartsWith(parent, StringComparison.OrdinalIgnoreCase) ||
!Path.GetFileName(target).StartsWith("xfetoolbox-file-performance-", StringComparison.Ordinal))
throw new InvalidOperationException("Unexpected temporary tree cleanup path.");
Directory.Delete(target, recursive: true);
}
}
}
using System.Diagnostics;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class FileIndexPerformanceTests
{
[Test]
[Explicit]
public static async Task FileIndexSingleRootRemainsSearchableDuringScanAndCacheHydration()
{
using var tree = new LargeSearchTree();
var preparation = Stopwatch.StartNew();
const int folderCount = 256;
const int filesPerFolder = 128;
for (var folder = 0; folder < folderCount; folder++)
{
var directory = Directory.CreateDirectory(Path.Combine(tree.Root, $"project-{folder:D4}")).FullName;
for (var file = 0; file < filesPerFolder; file++)
using (File.Create(Path.Combine(directory, $"report-{folder:D4}-{file:D4}.txt"))) { }
}
Console.WriteLine($"Large-tree preparation: {preparation.Elapsed.TotalMilliseconds:N0} ms");
var watch = Stopwatch.StartNew();
await using (var service = new FileIndexService(tree.Options))
{
var rebuilding = service.RebuildAsync();
var maximumRead = TimeSpan.Zero;
var readCount = 0;
var firstResults = TimeSpan.Zero;
while (!rebuilding.IsCompleted)
{
var query = Stopwatch.StartNew();
var result = await Task.Run(() => service.Index.Search("report-0123", limit: 5));
if (query.Elapsed > maximumRead)
maximumRead = query.Elapsed;
if (firstResults == TimeSpan.Zero && service.Index.Count > 256)
firstResults = watch.Elapsed;
readCount++;
await Task.Delay(10);
}
await rebuilding;
Ensure(service.Index.Count == folderCount * (filesPerFolder + 1) + 1,
$"The single-root scan lost or duplicated entries: {service.Index.Count}.");
Ensure(service.Index.Search("report-0123").TotalMatches == filesPerFolder,
"Searching while the index was being populated corrupted postings.");
Ensure(readCount > 0, "Indexing should permit concurrent queries.");
Ensure(maximumRead < TimeSpan.FromSeconds(5), "A scan blocked a concurrent search for several seconds.");
Console.WriteLine($"Single-root files: {folderCount * filesPerFolder:N0}; scan/cache {watch.Elapsed.TotalMilliseconds:N0} ms; " +
$"first results {firstResults.TotalMilliseconds:N0} ms; concurrent reads {readCount}; longest read {maximumRead.TotalMilliseconds:N0} ms");
}
watch.Restart();
await using (var restarted = new FileIndexService(tree.Options))
{
var loading = restarted.StartAsync();
while (!loading.IsCompleted)
{
_ = restarted.Index.Count;
await Task.Delay(1);
}
await loading;
Ensure(restarted.Index.Search("report-0123").TotalMatches == filesPerFolder,
"A restored index must immediately provide the saved search results.");
Console.WriteLine($"Cache hydration: {watch.Elapsed.TotalMilliseconds:N0} ms");
restarted.RequestStop();
}
}
[Test]
public static async Task FileIndexOverlappingRootsDoNotDuplicateDirectoryTraversal()
{
using var tree = new LargeSearchTree();
var nested = Directory.CreateDirectory(Path.Combine(tree.Root, "priority")).FullName;
var deep = Directory.CreateDirectory(Path.Combine(nested, "deep")).FullName;
var file = Path.Combine(deep, "priority-document.txt");
File.WriteAllText(file, "priority");
await using var service = new FileIndexService(tree.Options with { Roots = [deep, nested, tree.Root] });
await service.RebuildAsync();
Ensure(service.Index.Count == 4 && service.Index.Search("priority-document").TotalMatches == 1,
"Prioritized nested roots must be visited once and remain searchable.");
}
[Test]
public static async Task FileIndexLargeCacheHydratesInSearchableBatches()
{
using var tree = new LargeSearchTree();
const int count = 100_000;
WriteSyntheticCache(tree, count, count);
await using var service = new FileIndexService(tree.Options);
var loading = service.StartAsync();
var sawSearchablePrefix = false;
while (!loading.IsCompleted)
{
var indexed = service.Index.Count;
if (indexed > 0 && indexed < count)
{
var result = await Task.Run(() => service.Index.Search("sample-000001", limit: 1));
sawSearchablePrefix |= result.TotalMatches == 1;
}
await Task.Delay(1);
}
await loading;
service.RequestStop();
Ensure(sawSearchablePrefix,
"Large cached indexes should provide searchable batches before the complete cache is decoded.");
}
[Test]
public static async Task FileIndexCorruptStreamingCacheDiscardsPublishedPrefix()
{
using var tree = new LargeSearchTree();
WriteSyntheticCache(tree, declaredCount: 1024, actualCount: 512);
await using var service = new FileIndexService(tree.Options);
await service.StartAsync();
Ensure(service.Index.Search("sample-").TotalMatches == 0,
"A truncated cache must discard even the batches that were published before corruption was detected.");
await service.RebuildAsync();
Ensure(service.Index.Count == 1, "A corrupt streamed snapshot must recover to the actual filesystem.");
}
private static void WriteSyntheticCache(LargeSearchTree tree, int declaredCount, int actualCount)
{
Directory.CreateDirectory(tree.Options.CacheDirectory);
using var file = File.Create(Path.Combine(tree.Options.CacheDirectory, "files.v1.gz"));
using var compressed = new GZipStream(file, CompressionLevel.Fastest);
using var writer = new BinaryWriter(compressed, Encoding.UTF8);
writer.Write(0x58464958);
writer.Write(1);
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(tree.Root));
WriteCacheString(writer, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
OperatingSystem.IsWindows() ? root.ToUpperInvariant() : root))));
writer.Write(declaredCount);
for (var index = 0; index < actualCount; index++)
{
WriteCacheString(writer, Path.Combine(tree.Root, $"sample-{index:D6}.txt"));
writer.Write((byte)0);
}
}
private static void WriteCacheString(BinaryWriter writer, string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
writer.Write(bytes.Length);
writer.Write(bytes);
}
private static void Ensure(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
private sealed class LargeSearchTree : IDisposable
{
public string Root { get; } = Path.Combine(Path.GetTempPath(), "xfetoolbox-file-performance-" + Guid.NewGuid().ToString("N"));
public FileIndexOptions Options => new() { Roots = [Root], CacheDirectory = Path.Combine(Root, ".cache"), MaxParallelism = 2 };
public LargeSearchTree() => Directory.CreateDirectory(Root);
public void Dispose()
{
var target = Path.GetFullPath(Root);
var parent = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.GetTempPath())) + Path.DirectorySeparatorChar;
if (!target.StartsWith(parent, StringComparison.OrdinalIgnoreCase) ||
!Path.GetFileName(target).StartsWith("xfetoolbox-file-performance-", StringComparison.Ordinal))
throw new InvalidOperationException("Unexpected temporary tree cleanup path.");
Directory.Delete(target, recursive: true);
}
}
}