From b093b26c12d2d056f49aaf3d2c66eab2f59f5c7c Mon Sep 17 00:00:00 2001 From: Mashrien Date: Thu, 26 Nov 2026 02:43:40 -0600 Subject: [PATCH 1/2] Read indexed archive chunks concurrently with up to four workers Batch consecutive physical chunks, validate each group independently, and deliver payloads in sequence to extraction, range readers, and continuous decompressors. Expose worker selection and asynchronous operations through the engine and client. Cover fragmented, encrypted, corrupt and compressed archives and build Windows NativeAOT in CI for the 1.4.0 release. --- .github/workflows/windows-native.yml | 25 +++++ BuildNumber.txt | 2 +- Directory.Build.props | 4 +- Directory.Build.targets | 2 +- MNX/Archive.cs | 117 +++++-------------- MNX/Archive/Chunks/ChunkReadWindow.cs | 137 +++++++++++++++++++++++ MNX/Archive/Chunks/Format.cs | 42 ++++--- MNX/Archive/Chunks/Reader.cs | 32 +----- MNX/Archive/Codecs/Compression.cs | 21 ++-- MNX/Archive/Codecs/Encryption.cs | 7 +- MNX/Archive/ReadOperationsAsync.cs | 17 +++ MNX/Archive/ReadOptions.cs | 24 ++++ MNX/Configuration.cs | 2 +- README.md | 23 +++- client/Archive.cs | 1 + client/MNXFile.Client.csproj | 2 + client/Models.cs | 2 +- interop/Protocol.cs | 1 + native/ClientProtocol.cs | 5 +- native/Exports.cs | 8 ++ native/include/mnxfile.h | 2 + tests/MNXFile.Client.Smoke/Program.cs | 7 +- tests/MNXFile.Smoke/ParallelReadSmoke.cs | 97 ++++++++++++++++ tests/MNXFile.Smoke/Program.cs | 5 + tests/native/smoke.c | 2 + 25 files changed, 425 insertions(+), 162 deletions(-) create mode 100644 .github/workflows/windows-native.yml create mode 100644 MNX/Archive/Chunks/ChunkReadWindow.cs create mode 100644 MNX/Archive/ReadOperationsAsync.cs create mode 100644 MNX/Archive/ReadOptions.cs create mode 100644 tests/MNXFile.Smoke/ParallelReadSmoke.cs diff --git a/.github/workflows/windows-native.yml b/.github/workflows/windows-native.yml new file mode 100644 index 0000000..e68bd9c --- /dev/null +++ b/.github/workflows/windows-native.yml @@ -0,0 +1,25 @@ +name: Windows native build +on: [pull_request, workflow_dispatch] +permissions: + contents: read + +jobs: + win-x64: + runs-on: windows-2022 + timeout-minutes: 40 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4 + with: + dotnet-version: '10.0.x' + - name: Build and test the managed engine, native DLL and clients + shell: pwsh + run: | + $env:MNXBuildNumber = (Get-Content BuildNumber.txt).Trim() + $env:MNXReleaseRoot = Join-Path $env:RUNNER_TEMP 'release' + ./build.ps1 -Runtime win-x64 -Test + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: mnxfile-win-x64 + path: ${{ runner.temp }}/release/win-x64/ + if-no-files-found: error diff --git a/BuildNumber.txt b/BuildNumber.txt index f599e28..b4de394 100644 --- a/BuildNumber.txt +++ b/BuildNumber.txt @@ -1 +1 @@ -10 +11 diff --git a/Directory.Build.props b/Directory.Build.props index b4990d4..120a464 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,11 +4,11 @@ git https://github.com/Mashrien/MNXFile GPL-3.0-only - 1.3.1 + 1.4.0 $(MSBuildThisFileDirectory)BuildNumber.txt true $([System.IO.File]::ReadAllText('$(MNXCounterFile)').Trim()) - $(MNXVersionPrefix)-alpha.$(MNXBuildNumber) + $(MNXVersionPrefix) $(Version) $(MNXVersionPrefix).$(MNXBuildNumber) $(AssemblyVersion) diff --git a/Directory.Build.targets b/Directory.Build.targets index 361405b..ee674f7 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -77,7 +77,7 @@ true - $(MNXVersionPrefix)-alpha.$(MNXBuildNumber) + $(MNXVersionPrefix) $(Version) $(MNXVersionPrefix).$(MNXBuildNumber) $(AssemblyVersion) diff --git a/MNX/Archive.cs b/MNX/Archive.cs index 8f0bc02..b118649 100644 --- a/MNX/Archive.cs +++ b/MNX/Archive.cs @@ -663,62 +663,17 @@ public byte[] ReadFileRange(Guid id, long offset, int count) { lock (_state.SyncRoot) { CheckOpen(); - VFile? file = RequireFile(id); - if (UsesStreamCompression) { - if ((ulong)offset >= file.SizeOriginal || count == 0) { - return Array.Empty(); - } - - int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset); - byte[] data = new byte[length]; - using ContinuousArchiveReadStream decoded = new ContinuousArchiveReadStream(this, file); - decoded.Seek(offset, SeekOrigin.Begin); - decoded.ReadExactly(data); - return data; - } - - using FileStream archive = DiskFile.OpenRead(_state.Path!); - return ReadFileRangeCore(archive, file, offset, count); - } - } - - private byte[] ReadFileRangeCore(Stream archive, VFile file, long offset, int count) { - if ((ulong)offset >= file.SizeOriginal || count == 0) { - return Array.Empty(); - } - - int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset); - byte[] output = new byte[length]; - int copied = 0; - long cursor = offset; - while (copied < length) { - uint sequence; - int within; - (sequence, within) = file.LocateByte((ulong)cursor); - uint index = file.PhysicalChunk(sequence); - byte[] payload = ChunkFormat.ReadChunk( - archive, - index, - out ChunkHeader slot, - _state.Codec, - LogicalChunkLength(file, sequence), - _state.ChunkSize - ); - if (slot.Id != file.FileID || slot.Sequence != sequence) { - throw new InvalidDataException("Chunk does not match the file index."); - } - - if (within >= payload.Length) { - throw new InvalidDataException("Chunk length does not cover the requested offset."); + VFile file = RequireFile(id); + if ((ulong)offset >= file.SizeOriginal || count == 0) { + return Array.Empty(); } - - int take = Math.Min(length - copied, payload.Length - within); - payload.AsSpan(within, take).CopyTo(output.AsSpan(copied)); - copied += take; - cursor += take; + int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset); + byte[] data = new byte[length]; + using Stream reader = CreateReadStream(file); + reader.Position = offset; + reader.ReadExactly(data); + return data; } - - return output; } /// Read a chunk payload; continuous compression returns a slice of the compressed file stream. @@ -726,21 +681,11 @@ public byte[] GetFileChunk(Guid id, uint sequence) { lock (_state.SyncRoot) { CheckOpen(); VFile? file = RequireFile(id); - uint index = file.PhysicalChunk(sequence); - using FileStream archive = DiskFile.OpenRead(_state.Path!); - byte[] payload = ChunkFormat.ReadChunk( - archive, - index, - out ChunkHeader slot, - _state.Codec, - LogicalChunkLength(file, sequence), - _state.ChunkSize - ); - if (slot.Id != id || slot.Sequence != sequence) { - throw new InvalidDataException("Chunk does not match the file index."); + if (sequence >= file.ChunkCount) { + throw new ArgumentOutOfRangeException(nameof(sequence)); } - - return payload; + using ChunkReadWindow reader = new ChunkReadWindow(this, file); + return reader.Read(sequence, 1); } } @@ -749,7 +694,7 @@ public ReturnCode VerifyArchive() { lock (_state.SyncRoot) { CheckOpen(); try { - using FileStream archive = DiskFile.OpenRead(_state.Path!); + using FileStream archive = ChunkReadWindow.OpenInput(this); ArchiveFormat.HeaderInfo? header = ArchiveFormat.ReadHeader(archive); if (header.version == 7) { archive.Position = _state.ChunkSize; @@ -791,22 +736,10 @@ public ReturnCode VerifyArchive() { occupiedChunks = checked(occupiedChunks + extent.Count); } ulong size = 0; + using ChunkReadWindow reader = new ChunkReadWindow(this, file, archive); for (uint sequence = 0; sequence < file.ChunkCount; sequence++) { - uint index = file.PhysicalChunk(sequence); - byte[] payload = ChunkFormat.ReadChunk( - archive, - index, - out ChunkHeader slot, - _state.Codec, - LogicalChunkLength(file, sequence), - _state.ChunkSize - ); - uint expectedNext = sequence + 1 < file.ChunkCount ? file.PhysicalChunk(sequence + 1) : 0; - if (payload.Length != LogicalChunkLength(file, sequence) || slot.Id != file.FileID || slot.Sequence != sequence || slot.Next != expectedNext || (sequence == 0 && slot.Type != (file.IsDirectory ? NodeType.Directory : NodeType.File)) || (sequence > 0 && slot.Type != NodeType.Continuation)) { - throw new InvalidDataException($"Chunk chain mismatch for {file.Name}."); - } - - size += (uint)LogicalChunkLength(file, sequence); + byte[] payload = reader.Read(sequence, file.ChunkCount - sequence); + size += (uint)payload.Length; checkedBytes += _state.ChunkSize; if (progressTimer.ElapsedMilliseconds >= Options.ProgressReportFrequency) { RaiseProgress("verify", checkedBytes, totalBytes); @@ -820,7 +753,7 @@ public ReturnCode VerifyArchive() { if (UsesStreamCompression && !file.IsDirectory) { using ContinuousArchiveReadStream decoded = new ContinuousArchiveReadStream(this, file); - byte[] buffer = new byte[64 * 1024]; + byte[] buffer = CreateTransferBuffer(file.SizeOriginal); long remaining = checked((long)file.SizeOriginal); while (remaining > 0) { int read = decoded.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining)); @@ -867,11 +800,14 @@ private void ValidateParentChain(VFile file) { public Stream OpenRead(Guid id) { lock (_state.SyncRoot) { CheckOpen(); - VFile? file = RequireFile(id); - return UsesStreamCompression ? new ContinuousArchiveReadStream(this, file) : new ArchiveReadStream(this, file); + return CreateReadStream(RequireFile(id)); } } + private Stream CreateReadStream(VFile file) { + return UsesStreamCompression ? new ContinuousArchiveReadStream(this, file) : new ArchiveReadStream(this, file); + } + /// Copy a file range through a fixed-size buffer without materializing the range. public long CopyFileRange(Guid id, Stream destination, long offset, long length, int bufferSize = 64 * 1024) { ArgumentNullException.ThrowIfNull(destination); @@ -931,7 +867,7 @@ public ReturnCode ExtractFile(Guid id, FileInfo destination, bool? overwrite = n FileMode mode = overwrite ?? Options.OverrideByDefault ? FileMode.Create : FileMode.CreateNew; using (FileStream output = new FileStream(destination.FullName, mode, FileAccess.Write, FileShare.None)) { outputOpened = true; - byte[] buffer = new byte[64 * 1024]; + byte[] buffer = CreateTransferBuffer(file.SizeOriginal); long completed = 0; while (true) { Options.CancellationToken.ThrowIfCancellationRequested(); @@ -1175,8 +1111,9 @@ private static Attribs MapAttributes(FileAttributes attributes) { return result; } - private int LogicalChunkLength(VFile file, uint sequence) { - return file.LogicalLength(sequence); + private byte[] CreateTransferBuffer(ulong fileSize) { + int capacity = Options.ReadWorkers == 1 ? 64 * 1024 : Options.ReadWorkers * ChunkReadWindow.BytesPerWorker; + return new byte[(int)Math.Clamp(fileSize, 1, (ulong)capacity)]; } private static VFile FromSource(Guid id, Guid parent, string name, FileSystemInfo source, bool directory, ulong size, uint first) => FromMetadata(id, parent, name, SourceMetadata(source), directory, size, first); diff --git a/MNX/Archive/Chunks/ChunkReadWindow.cs b/MNX/Archive/Chunks/ChunkReadWindow.cs new file mode 100644 index 0000000..80c8251 --- /dev/null +++ b/MNX/Archive/Chunks/ChunkReadWindow.cs @@ -0,0 +1,137 @@ +using System.Buffers; +using System.Security.Cryptography; +using Microsoft.Win32.SafeHandles; +using MNX.Codecs; + +namespace MNX.Storage; + +/// Reads adjacent disk chunks in batches and delivers validated payloads in file order. +internal sealed class ChunkReadWindow(Archive owner, VFile file, FileStream input) : IDisposable { + internal const int BytesPerWorker = 256 * 1024; + private readonly bool _ownsInput; + private byte[][] _payloads = []; + private uint _first; + private bool _singleChunkOnly; + + internal ChunkReadWindow(Archive owner, VFile file) + : this(owner, file, OpenInput(owner)) { + _ownsInput = true; + } + + internal static FileStream OpenInput(Archive owner) { + return new FileStream(owner.State.Path!, FileMode.Open, FileAccess.Read, FileShare.Read, + bufferSize: 1, FileOptions.Asynchronous | FileOptions.RandomAccess); + } + + // The coordinator holds the archive gate until every worker has completed. + // Workers use positional I/O and never acquire the gate or invoke a user callback. + internal byte[] Read(uint sequence, uint requestedChunks) { + CancellationToken cancellation = owner.Options.CancellationToken; + cancellation.ThrowIfCancellationRequested(); + if (sequence >= _first && sequence - _first < _payloads.Length) { + return _payloads[sequence - _first]; + } + + int workers = owner.Options.ReadWorkers; + int chunkSize = owner.State.ChunkSize; + int capacity = BytesPerWorker / chunkSize * workers; + uint available = file.ChunkCount - sequence; + int count = (int)Math.Min(Math.Min(requestedChunks, available), (uint)capacity); + _payloads = []; + _first = sequence; + if (workers > 1 && count > 1 && !_singleChunkOnly) { + try { + _payloads = FillWindowAsync(sequence, count, workers, chunkSize, cancellation).GetAwaiter().GetResult(); + return _payloads[0]; + } + catch (Exception error) when (error is IOException or InvalidDataException or CryptographicException) { + // A decoder can request bytes ahead of the caller. Deliver good earlier chunks + // and report damage when the caller actually reaches the affected sequence. + _singleChunkOnly = true; + } + } + + uint physical = file.PhysicalChunk(sequence); + byte[] payload = ChunkFormat.ReadChunk(input, physical, out ChunkHeader header, + owner.State.Codec, file.LogicalLength(sequence), chunkSize); + ValidateChain(sequence, header, payload.Length); + _payloads = [payload]; + return payload; + } + + private async Task FillWindowAsync(uint first, int count, int workers, int chunkSize, CancellationToken cancellation) { + int groups = Math.Min(workers, count); + byte[][] ordered = new byte[count][]; + Task[] pending = new Task[groups]; + SafeFileHandle handle = input.SafeFileHandle; + for (int worker = 0; worker < groups; worker++) { + int begin = count * worker / groups; + int end = count * (worker + 1) / groups; + pending[worker] = ReadGroupAsync(handle, first, begin, end, chunkSize, ordered, cancellation); + } + await Task.WhenAll(pending).ConfigureAwait(false); + return ordered; + } + + private async Task ReadGroupAsync(SafeFileHandle handle, uint first, int begin, int end, int chunkSize, + byte[][] ordered, CancellationToken cancellation) { + byte[] buffer = ArrayPool.Shared.Rent((end - begin) * chunkSize); + try { + ArchiveCodec? codec = owner.State.Codec; + using AesGcm? cipher = codec?.CreateReadCipher(); + int cursor = begin; + while (cursor < end) { + cancellation.ThrowIfCancellationRequested(); + uint physical = file.PhysicalChunk(first + (uint)cursor); + int run = 1; + while (cursor + run < end && (ulong)physical + (uint)run == file.PhysicalChunk(first + (uint)(cursor + run))) { + run++; + } + + long offset = (long)physical * chunkSize; + Memory remaining = buffer.AsMemory(0, run * chunkSize); + while (!remaining.IsEmpty) { + int read = await RandomAccess.ReadAsync(handle, remaining, offset, cancellation).ConfigureAwait(false); + if (read == 0) { + throw new EndOfStreamException("The archive ended inside a chunk."); + } + offset += read; + remaining = remaining.Slice(read); + } + + for (int slot = 0; slot < run; slot++) { + cancellation.ThrowIfCancellationRequested(); + uint sequence = first + (uint)cursor; + ordered[cursor] = ChunkFormat.DecodeChunk(buffer.AsSpan(slot * chunkSize, chunkSize), + physical + (uint)slot, out ChunkHeader header, codec, file.LogicalLength(sequence), cipher); + ValidateChain(sequence, header, ordered[cursor].Length); + cursor++; + } + } + } + finally { + ArrayPool.Shared.Return(buffer); + } + } + + private void ValidateChain(uint sequence, in ChunkHeader header, int payloadLength) { + if (payloadLength != file.LogicalLength(sequence)) { + throw new InvalidDataException($"Chunk length mismatch for {file.Name} at sequence {sequence}."); + } + NodeType expectedType = NodeType.Continuation; + if (sequence == 0) { + expectedType = file.IsDirectory ? NodeType.Directory : NodeType.File; + } + uint next = sequence + 1 < file.ChunkCount ? file.PhysicalChunk(sequence + 1) : 0; + if (header.Id != file.FileID || header.Sequence != sequence || header.Type != expectedType || header.Next != next) { + throw new InvalidDataException($"Chunk chain mismatch for {file.Name} at sequence {sequence}."); + } + } + + public void Dispose() { + _payloads = []; + if (_ownsInput) { + input.Dispose(); + } + } + } diff --git a/MNX/Archive/Chunks/Format.cs b/MNX/Archive/Chunks/Format.cs index 950a707..d93fd74 100644 --- a/MNX/Archive/Chunks/Format.cs +++ b/MNX/Archive/Chunks/Format.cs @@ -50,30 +50,36 @@ internal static byte[] ReadChunk( } stream.ReadExactly(chunkBytes); - if (!TryParseHeader(chunkBytes, index, chunkSize, out slot)) { - throw new InvalidDataException($"Chunk {index} is empty."); - } - int payloadStart = slot.Type == NodeType.Continuation ? NextHeaderSize : FirstHeaderSize; - ReadOnlySpan stored = buffer.AsSpan(payloadStart, checked((int)slot.DataLength)); - if (codec is not null) { - return codec.DecodeChunk( in slot, stored, expectedPlainLength); - } - - byte[] payload = stored.ToArray(); - Span payloadHash = stackalloc byte[32]; - SHA256.HashData(payload, payloadHash); - NodeFlags dataFlags = NodeFlags.Compressed | NodeFlags.Encrypted | NodeFlags.Streamed; - if ((slot.Flags & dataFlags) != NodeFlags.None || !slot.Hash.Matches(payloadHash)) { - throw new InvalidDataException($"Chunk {index} payload checksum does not match."); - } - - return payload; + return DecodeChunk(chunkBytes, index, out slot, codec, expectedPlainLength); } finally { ArrayPool.Shared.Return(buffer); } } + internal static byte[] DecodeChunk(ReadOnlySpan chunkBytes, uint index, out ChunkHeader slot, + ArchiveCodec? codec, int expectedPlainLength, AesGcm? readCipher = null) { + int chunkSize = chunkBytes.Length; + if (!TryParseHeader(chunkBytes, index, chunkSize, out slot)) { + throw new InvalidDataException($"Chunk {index} is empty."); + } + int payloadStart = slot.Type == NodeType.Continuation ? NextHeaderSize : FirstHeaderSize; + ReadOnlySpan stored = chunkBytes.Slice(payloadStart, checked((int)slot.DataLength)); + if (codec is not null) { + return codec.DecodeChunk(in slot, stored, expectedPlainLength, readCipher); + } + + byte[] payload = stored.ToArray(); + Span payloadHash = stackalloc byte[32]; + SHA256.HashData(payload, payloadHash); + NodeFlags dataFlags = NodeFlags.Compressed | NodeFlags.Encrypted | NodeFlags.Streamed; + if ((slot.Flags & dataFlags) != NodeFlags.None || !slot.Hash.Matches(payloadHash)) { + throw new InvalidDataException($"Chunk {index} payload checksum does not match."); + } + + return payload; + } + // Nullable adapter for standalone header inspection; the chunk loop uses an out value. private static ChunkHeader? ParseSlot(ReadOnlySpan buffer, uint index, int chunkSize) { return TryParseHeader(buffer, index, chunkSize, out ChunkHeader header) ? header : null; diff --git a/MNX/Archive/Chunks/Reader.cs b/MNX/Archive/Chunks/Reader.cs index 2d1435b..1d3b622 100644 --- a/MNX/Archive/Chunks/Reader.cs +++ b/MNX/Archive/Chunks/Reader.cs @@ -9,9 +9,7 @@ namespace MNX.Storage; internal sealed class ArchiveReadStream(Archive archive, VFile file) : Stream { private long _position; - private uint? _cachedSequence; - private byte[] _cachedPayload = Array.Empty(); - private readonly FileStream _input = DiskFile.OpenRead(archive.State.Path!); + private readonly ChunkReadWindow _chunks = new ChunkReadWindow(archive, file); public override bool CanRead => true; public override bool CanSeek => true; public override bool CanWrite => false; @@ -41,36 +39,18 @@ public override int Read(Span destination) { } int requested = (int)Math.Min(destination.Length, Length - _position); + (uint lastSequence, _) = file.LocateByte((ulong)(_position + requested - 1)); int copied = 0; while (copied < requested) { (uint sequence, int withinChunk) = file.LocateByte((ulong)_position); - if (_cachedSequence != sequence) { - uint physicalChunk = file.PhysicalChunk(sequence); - byte[] payload = ChunkFormat.ReadChunk( - _input, - physicalChunk, - out ChunkHeader header, - archive.State.Codec, - file.LogicalLength(sequence), - archive.State.ChunkSize - ); - uint expectedNext = sequence + 1 < file.ChunkCount ? file.PhysicalChunk(sequence + 1) : 0; - NodeType expectedType = sequence == 0 ? NodeType.File : NodeType.Continuation; - if (header.Id != file.FileID || header.Sequence != sequence || header.Type != expectedType || header.Next != expectedNext) { - throw new InvalidDataException("Chunk does not match the file index."); - } - - _cachedPayload = payload; - _cachedSequence = sequence; - } - - int available = _cachedPayload.Length - withinChunk; + byte[] payload = _chunks.Read(sequence, lastSequence - sequence + 1); + int available = payload.Length - withinChunk; if (available <= 0) { throw new InvalidDataException("Chunk length does not cover the requested offset."); } int take = Math.Min(requested - copied, available); - _cachedPayload.AsSpan(withinChunk, take).CopyTo(destination.Slice(copied, take)); + payload.AsSpan(withinChunk, take).CopyTo(destination.Slice(copied, take)); copied += take; _position += take; } @@ -94,7 +74,7 @@ public override void Flush() { protected override void Dispose(bool disposing) { if (disposing) { - _input.Dispose(); + _chunks.Dispose(); } base.Dispose(disposing); diff --git a/MNX/Archive/Codecs/Compression.cs b/MNX/Archive/Codecs/Compression.cs index b303542..a9f8c9b 100644 --- a/MNX/Archive/Codecs/Compression.cs +++ b/MNX/Archive/Codecs/Compression.cs @@ -238,7 +238,8 @@ public override void Flush() { } internal sealed class StoredPayloadStream(Archive owner, VFile file) : Stream { - private readonly FileStream _input = DiskFile.OpenRead(owner.State.Path!); + private readonly ChunkReadWindow _chunks = new ChunkReadWindow(owner, file); + internal uint RequestedChunks { get; set; } = 1; private uint _chunkSequence; private byte[] _payload = Array.Empty(); private int _offset; @@ -263,17 +264,8 @@ public override int Read(Span output) { return 0; } - uint physical = file.PhysicalChunk(_chunkSequence); - byte[] payload = ChunkFormat.ReadChunk( - _input, - physical, - out ChunkHeader slot, - owner.State.Codec, - file.LogicalLength(_chunkSequence), - owner.State.ChunkSize - ); - uint expectedNext = _chunkSequence + 1 < file.ChunkCount ? file.PhysicalChunk(_chunkSequence + 1) : 0; - if (slot.Id != file.FileID || slot.Sequence != _chunkSequence || slot.Next != expectedNext || slot.Type != (_chunkSequence == 0 ? NodeType.File : NodeType.Continuation) || payload.Length == 0) { + byte[] payload = _chunks.Read(_chunkSequence, RequestedChunks); + if (payload.Length == 0) { throw new InvalidDataException("Compressed file chunk chain is invalid."); } @@ -293,7 +285,7 @@ public override void Flush() { protected override void Dispose(bool disposing) { if (disposing) { - _input.Dispose(); + _chunks.Dispose(); } base.Dispose(disposing); @@ -340,6 +332,9 @@ public override int Read(Span output) { } int wanted = (int)Math.Min(output.Length, Length - _position); + // A large sequential read can feed the decoder from a bounded group + // of stored chunks. A tiny preview or range starts with just one. + _payload.RequestedChunks = (uint)Math.Max(1, (wanted + (long)_owner.ChunkSize - 1) / _owner.ChunkSize); int read = _decoder.Read(output[..wanted]); if (read == 0) { throw new InvalidDataException("Compressed file ended before its indexed length."); diff --git a/MNX/Archive/Codecs/Encryption.cs b/MNX/Archive/Codecs/Encryption.cs index 72fdc04..5ef2519 100644 --- a/MNX/Archive/Codecs/Encryption.cs +++ b/MNX/Archive/Codecs/Encryption.cs @@ -98,7 +98,10 @@ internal byte[] EncodeChunk( return ciphertext; } - internal byte[] DecodeChunk( in ChunkHeader slot, ReadOnlySpan stored, int expectedLength) { + // AesGcm instances have mutable native state. Each parallel reader owns its cipher. + internal AesGcm? CreateReadCipher() => _key is null ? null : new AesGcm(_key, TagLength); + + internal byte[] DecodeChunk(in ChunkHeader slot, ReadOnlySpan stored, int expectedLength, AesGcm? readCipher = null) { bool streamed = (slot.Flags & DiskNodeFlags.Streamed) != 0; bool expectedStream = _streamCompression && slot.Type != NodeType.Directory; if (streamed != expectedStream) { @@ -116,7 +119,7 @@ internal byte[] DecodeChunk( in ChunkHeader slot, ReadOnlySpan stored, int slot.Hash.CopyTo(authentication); Span associatedData = stackalloc byte[42]; WriteChunkAad(slot, associatedData); - _aes.Decrypt( + (readCipher ?? _aes).Decrypt( authentication.Slice(0, NonceLength), stored, authentication.Slice(NonceLength, TagLength), diff --git a/MNX/Archive/ReadOperationsAsync.cs b/MNX/Archive/ReadOperationsAsync.cs new file mode 100644 index 0000000..43f0a11 --- /dev/null +++ b/MNX/Archive/ReadOperationsAsync.cs @@ -0,0 +1,17 @@ +namespace MNX; + +public sealed partial class Archive { + // Keep the existing operation gate, progress callbacks and partial-output cleanup + // on one coordinator. The engine dispatches positional reads beneath that gate. + public Task ExtractFileAsync(Guid id, FileInfo destination, bool? overwrite = null) { + return Task.Run(() => ExtractFile(id, destination, overwrite), Options.CancellationToken); + } + + public Task VerifyArchiveAsync() { + return Task.Run(VerifyArchive, Options.CancellationToken); + } + + public Task ReadFileRangeAsync(Guid id, long offset, int count) { + return Task.Run(() => ReadFileRange(id, offset, count), Options.CancellationToken); + } + } diff --git a/MNX/Archive/ReadOptions.cs b/MNX/Archive/ReadOptions.cs new file mode 100644 index 0000000..cbb1fee --- /dev/null +++ b/MNX/Archive/ReadOptions.cs @@ -0,0 +1,24 @@ +namespace MNX; + +public sealed partial class Configuration { + public const int MaximumReadWorkers = 4; + private int _readWorkers = DefaultReadWorkers(); + + /// Maximum simultaneous chunk readers per archive operation. One uses synchronous I/O. + public int ReadWorkers { + get => _readWorkers; + set { + ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(value, MaximumReadWorkers); + _readWorkers = value; + } + } + + private static int DefaultReadWorkers() { + string? configured = Environment.GetEnvironmentVariable("MNX_READ_WORKERS"); + if (int.TryParse(configured, out int workers) && workers >= 1 && workers <= MaximumReadWorkers) { + return workers; + } + return 2; + } + } diff --git a/MNX/Configuration.cs b/MNX/Configuration.cs index a57b01f..e9f2d80 100644 --- a/MNX/Configuration.cs +++ b/MNX/Configuration.cs @@ -3,7 +3,7 @@ namespace MNX; /// Configuration for read and write operations. -public sealed class Configuration { +public sealed partial class Configuration { public int ProgressReportFrequency { get; set; } = 250; /// Cooperative cancellation for queue scans and adding files; completed entries remain valid. public CancellationToken CancellationToken { get; set; } diff --git a/README.md b/README.md index af565e3..2e33440 100644 --- a/README.md +++ b/README.md @@ -82,13 +82,13 @@ cd MNXFile ``` Each script reserves a build number automatically. The library/client version is -`1.3.1-alpha.N`. Use an explicitly reserved build number when preparing the local +`1.4.0`. Use an explicitly reserved build number when preparing the local dependency feed for a matching application build: ```sh -MNXBuildNumber=10 ./build.sh --test +MNXBuildNumber=11 ./build.sh --test # Managed NuGet packages only, without building the native library: -MNXBuildNumber=10 ./build.sh --packages-only +MNXBuildNumber=11 ./build.sh --packages-only ``` PowerShell equivalent: `$env:MNXBuildNumber='10'; .\build.ps1 -Test`. @@ -109,6 +109,23 @@ versions have not been published to NuGet.org. Linux arm64 selects the host architecture. Override `MNXBuildRoot`, `MNXReleaseRoot` or `MNXFinalRoot` to choose other destinations. Builds do not install the engine. +## Parallel archive reads + +The GUI, CLI and native callers use two chunk readers per archive operation by default. +Set `MNX_READ_WORKERS` to `1`, `2`, `3` or `4` before launching an application. +For example, `MNX_READ_WORKERS=4 mnx-gui` starts the archiver with four readers. +One selects the serial reader. This is a runtime setting for existing and new archives. + +C# callers can set `archive.Options.ReadWorkers` and await `ExtractFileAsync`, +`ReadFileRangeAsync` or `VerifyArchiveAsync`. Set `archive.Options.CancellationToken` +to cancel an operation. Native ABI callers can set the same limit with +`mnx_set_read_workers(handle, count)`. + +Readers combine neighboring physical chunks into bounded positional requests. Each +worker checks its chunks, with its own AES-GCM instance for encrypted data. Continuous +compression feeds one decoder in sequence. Small random reads fetch only the chunks +they need. Header and index reads retain their existing paging behavior. + ## Use the engine Choose **one** managed API provider in an application: diff --git a/client/Archive.cs b/client/Archive.cs index 7178ee3..533e7de 100644 --- a/client/Archive.cs +++ b/client/Archive.cs @@ -217,6 +217,7 @@ internal ClientResponse Call(ClientRequest request, Func + + diff --git a/client/Models.cs b/client/Models.cs index 2311379..bcb4f46 100644 --- a/client/Models.cs +++ b/client/Models.cs @@ -2,7 +2,7 @@ namespace MNX; -public sealed class Configuration { +public sealed partial class Configuration { public int ProgressReportFrequency { get; set; } = 250; public CancellationToken CancellationToken { get; set; } public bool OverrideByDefault { get; set; } = true; diff --git a/interop/Protocol.cs b/interop/Protocol.cs index cef2d53..480d3bb 100644 --- a/interop/Protocol.cs +++ b/interop/Protocol.cs @@ -17,6 +17,7 @@ internal sealed class ClientRequest { public int Level { get; set; } = 4; public int ChunkSize { get; set; } = 32768; public int Layout { get; set; } = 1; + public int? ReadWorkers { get; set; } public int Interval { get; set; } = 250; public bool Overwrite { get; set; } = true; public bool ExportKey { get; set; } diff --git a/native/ClientProtocol.cs b/native/ClientProtocol.cs index f75b22e..a9fb681 100644 --- a/native/ClientProtocol.cs +++ b/native/ClientProtocol.cs @@ -173,8 +173,11 @@ private static void DispatchClientRequest(ClientRequest input, ClientResponse ou context.Cancellation = new CancellationTokenSource(); return; } - context.Active = true; Archive target = context.Archive; + if (input.ReadWorkers.HasValue) { + target.Options.ReadWorkers = input.ReadWorkers.Value; + } + context.Active = true; target.Options.CancellationToken = context.Cancellation.Token; target.Options.OverrideByDefault = input.Overwrite; target.Options.ProgressReportFrequency = Math.Max(1, input.Interval); diff --git a/native/Exports.cs b/native/Exports.cs index 9e25966..98f267e 100644 --- a/native/Exports.cs +++ b/native/Exports.cs @@ -440,6 +440,14 @@ public static int ExtractDirectory(ulong handle, byte* id, byte* destination, in public static int Delete(ulong handle, byte* id) => Run(handle, context => Result(context.Archive.DeleteFileFromArchive(Id(id)))); [UnmanagedCallersOnly(EntryPoint = "mnx_compact", CallConvs = [typeof(CallConvCdecl)])] public static int Compact(ulong handle) => Run(handle, context => Result(context.Archive.CompactArchive())); + [UnmanagedCallersOnly(EntryPoint = "mnx_set_read_workers", CallConvs = [typeof(CallConvCdecl)])] + public static int SetReadWorkers(ulong handle, int workers) { + return Run(handle, context => { + context.Archive.Options.ReadWorkers = workers; + return 0; + }); + } + [UnmanagedCallersOnly(EntryPoint = "mnx_verify", CallConvs = [typeof(CallConvCdecl)])] public static int Verify(ulong handle) => Run(handle, context => Result(context.Archive.VerifyArchive(), true)); [UnmanagedCallersOnly(EntryPoint = "mnx_last_error", CallConvs = [typeof(CallConvCdecl)])] diff --git a/native/include/mnxfile.h b/native/include/mnxfile.h index 47968b4..28dff1b 100644 --- a/native/include/mnxfile.h +++ b/native/include/mnxfile.h @@ -117,6 +117,8 @@ MNX_API int32_t MNX_CALL mnx_extract_directory(mnx_handle archive, const char* i const char* destination, int32_t overwrite); MNX_API int32_t MNX_CALL mnx_delete(mnx_handle archive, const char* id); MNX_API int32_t MNX_CALL mnx_compact(mnx_handle archive); +/* Set the runtime chunk-read concurrency for this handle (1..4). */ +MNX_API int32_t MNX_CALL mnx_set_read_workers(mnx_handle archive, int32_t workers); MNX_API int32_t MNX_CALL mnx_verify(mnx_handle archive); /* Thread-local diagnostic from the last ordinary call. Queries preserve it. required is UTF-8 bytes including NUL. NULL + zero capacity queries size. */ diff --git a/tests/MNXFile.Client.Smoke/Program.cs b/tests/MNXFile.Client.Smoke/Program.cs index 505db5c..350a7da 100644 --- a/tests/MNXFile.Client.Smoke/Program.cs +++ b/tests/MNXFile.Client.Smoke/Program.cs @@ -18,7 +18,7 @@ } string engineVersion = LibraryInfo.Version; -Check(engineVersion.StartsWith("1.3.1-alpha.", StringComparison.Ordinal), "native engine reports its release version without opening an archive"); +Check(engineVersion == "1.4.0", "native engine reports its release version without opening an archive"); Check(LibraryInfo.FormatVersion == "0.1.8", "native engine reports the semantic storage format without opening an archive"); Check(Archive.MaximumArchiveBytes == 140_737_488_322_560UL, "client reports the exact physical archive capacity"); Console.WriteLine("PASS: installed MNXFile version " + engineVersion); @@ -89,7 +89,8 @@ Check(prefix.SequenceEqual(contents.AsSpan(17, 83).ToArray()), "stream backwards seek"); } string output = Path.Combine(root, compression + ".out"); - archive.ExtractFile(fileId, new FileInfo(output), false); + archive.Options.ReadWorkers = 4; + archive.ExtractFileAsync(fileId, new FileInfo(output), false).GetAwaiter().GetResult(); Check(File.ReadAllBytes(output).SequenceEqual(contents), "extract bytes"); archive.AddStreamNow(new MemoryStream([1, 2, 3, 4]), "stream.bin", 4); string later = Path.Combine(root, "later.txt"); @@ -111,7 +112,7 @@ archive.Close(); archive.Open(path, "ひみつのことば"); Check(archive.Compression == compression && archive.IsEncrypted && archive.Files.Single().Name == Path.GetFileName(source), "reopen metadata"); - Check(archive.VerifyArchive() == ReturnCode.Success, "reopen verify"); + Check(archive.VerifyArchiveAsync().GetAwaiter().GetResult() == ReturnCode.Success, "reopen verify"); Console.WriteLine("PASS: native client " + compression + " encryption/queue/callbacks/stream/range/extract/key/compact/reopen"); } diff --git a/tests/MNXFile.Smoke/ParallelReadSmoke.cs b/tests/MNXFile.Smoke/ParallelReadSmoke.cs new file mode 100644 index 0000000..fbc7a51 --- /dev/null +++ b/tests/MNXFile.Smoke/ParallelReadSmoke.cs @@ -0,0 +1,97 @@ +using MNX; + +internal static class ParallelReadSmoke { + internal static async Task Run(string directory) { + byte[] source = new byte[2 * 1024 * 1024 + 137]; + new Random(3741).NextBytes(source); + foreach (int chunkSize in new[] { 4096, 32768 }) { + foreach (ArchiveCompression compression in Enum.GetValues()) { + foreach (ArchiveCompressionLayout layout in Enum.GetValues()) { + if (compression == ArchiveCompression.LZ4 && layout == ArchiveCompressionLayout.IndependentChunks) { + continue; + } + string path = Path.Combine(directory, $"parallel-{chunkSize}-{compression}-{layout}.mnx"); + using Archive archive = new Archive(); + archive.Options.ChunkSize = chunkSize; + archive.Options.Compression = compression; + archive.Options.CompressionLayout = layout; + archive.Options.CompressionLevel = compression == ArchiveCompression.Brotli ? 1 : 0; + archive.Create(new FileInfo(path), layout == ArchiveCompressionLayout.Continuous ? "read-smoke" : null); + archive.AddStreamNow(new MemoryStream(source), "payload", source.Length); + VFile file = archive.Files.Single(); + for (int workers = 1; workers <= 4; workers++) { + archive.Options.ReadWorkers = workers; + const int offset = 32749; + byte[] range = await archive.ReadFileRangeAsync(file.FileID, offset, source.Length - offset); + if (!range.AsSpan().SequenceEqual(source.AsSpan(offset))) { + throw new InvalidDataException($"Worker count {workers} returned incorrect bytes."); + } + if (await archive.VerifyArchiveAsync() != Archive.ReturnCode.Success) { + throw new InvalidDataException("Parallel verification failed."); + } + } + string output = path + ".extracted"; + await archive.ExtractFileAsync(file.FileID, new FileInfo(output)); + if (!File.ReadAllBytes(output).AsSpan().SequenceEqual(source)) { + throw new InvalidDataException("Parallel extraction changed the entry."); + } + archive.Close(); + File.Delete(output); + File.Delete(path); + } + } + } + CheckLimits(); + await CheckFragmentedReads(directory, source); + Console.WriteLine("PASS: 1–4 readers, both chunk sizes and layouts, all codecs, encrypted reads, fragmented and damaged extents"); + } + + private static void CheckLimits() { + Configuration options = new Configuration(); + foreach (int invalid in new[] { -1, 0, 5 }) { + try { + options.ReadWorkers = invalid; + } + catch (ArgumentOutOfRangeException) { + continue; + } + throw new Exception("Invalid read worker count accepted."); + } + } + + private static async Task CheckFragmentedReads(string directory, byte[] source) { + string path = Path.Combine(directory, "parallel-fragmented.mnx"); + using Archive archive = new Archive(); + archive.Create(new FileInfo(path)); + archive.Options.ReadWorkers = 4; + archive.AddStreamNow(new MemoryStream(source, 0, 140000), "hole", 140000); + archive.AddStreamNow(new MemoryStream(source, 0, 90000), "separator", 90000); + archive.DeleteFileFromArchive(archive.Files.Single(node => node.Name == "hole").FileID); + archive.AddStreamNow(new MemoryStream(source), "fragmented", source.Length); + VFile entry = archive.Files.Single(node => node.Name == "fragmented"); + if (entry.ChunkExtents.Count < 2 || !(await archive.ReadFileRangeAsync(entry.FileID, 0, source.Length)).AsSpan().SequenceEqual(source)) { + throw new Exception("Fragmented file did not round-trip."); + } + long damagedOffset = (long)entry.PhysicalChunk(3) * archive.ChunkSize + 140; + using (FileStream output = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { + output.Position = damagedOffset; + int original = output.ReadByte(); + output.Position = damagedOffset; + output.WriteByte((byte)(original ^ 1)); + } + if (await archive.VerifyArchiveAsync() == Archive.ReturnCode.Success) { + throw new Exception("Verification accepted a damaged worker chunk."); + } + if (!(await archive.ReadFileRangeAsync(entry.FileID, 0, 128)).AsSpan().SequenceEqual(source.AsSpan(0, 128))) { + throw new Exception("Damage outside a requested range prevented reading an intact chunk."); + } + FileInfo partial = new FileInfo(path + ".out"); + try { + await archive.ExtractFileAsync(entry.FileID, partial); + } + catch (InvalidDataException) when (!File.Exists(partial.FullName)) { + return; + } + throw new Exception("Corruption did not fail extraction and remove partial output."); + } + } diff --git a/tests/MNXFile.Smoke/Program.cs b/tests/MNXFile.Smoke/Program.cs index 9e94676..60e4020 100644 --- a/tests/MNXFile.Smoke/Program.cs +++ b/tests/MNXFile.Smoke/Program.cs @@ -5,6 +5,10 @@ string work = Path.Combine(Path.GetTempPath(), "mnx-smoke-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(work); try { + if (args.Contains("--parallel-only")) { + await ParallelReadSmoke.Run(work); + return; + } CapacitySmoke.Run(); if (args.Contains("--capacity-only")) { return; @@ -23,6 +27,7 @@ return; } + await ParallelReadSmoke.Run(work); StorageLayoutSmoke.Run(); StreamWindowSmoke.Run(work); FilenameSmoke.Run(work); diff --git a/tests/native/smoke.c b/tests/native/smoke.c index 0849c1f..ae78dd6 100644 --- a/tests/native/smoke.c +++ b/tests/native/smoke.c @@ -130,6 +130,8 @@ int main(int argc, char **argv) { ok(mnx_extract_directory(archive, tree_id, extracted, 0), "extract directory tree"); snprintf(extracted, sizeof extracted, "%s/extracted-tree-%d/nested.bin", argv[1], codecs[c]); check_extracted(extracted, 123457, 43); + ok(mnx_set_read_workers(archive, 4), "select four read workers"); + if (mnx_set_read_workers(archive, 5) != MNX_INVALID_ARGUMENT) return 1; ok(mnx_verify(archive), "native verify"); mnx_archive_info before = {0}, after = {0}; before.struct_size = sizeof before; after.struct_size = sizeof after; From b76e3a3eebdc4ba5096b9fc4db411c5cb719f875 Mon Sep 17 00:00:00 2001 From: Mashrien Date: Thu, 26 Nov 2026 02:44:28 -0600 Subject: [PATCH 2/2] Use the ABI operation guard for the worker setter --- native/Exports.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/native/Exports.cs b/native/Exports.cs index 98f267e..da39b02 100644 --- a/native/Exports.cs +++ b/native/Exports.cs @@ -442,10 +442,7 @@ public static int ExtractDirectory(ulong handle, byte* id, byte* destination, in public static int Compact(ulong handle) => Run(handle, context => Result(context.Archive.CompactArchive())); [UnmanagedCallersOnly(EntryPoint = "mnx_set_read_workers", CallConvs = [typeof(CallConvCdecl)])] public static int SetReadWorkers(ulong handle, int workers) { - return Run(handle, context => { - context.Archive.Options.ReadWorkers = workers; - return 0; - }); + return Run(handle, context => context.Archive.Options.ReadWorkers = workers); } [UnmanagedCallersOnly(EntryPoint = "mnx_verify", CallConvs = [typeof(CallConvCdecl)])]