From af9afefe271bd44958f15bd0a942940f15473ed8 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:10:20 +0300 Subject: [PATCH 1/4] Decode the mode-2 payloads of pool subgroups A mode-2 subgroup payload is an LZ token stream like a mode-2 block payload. It may start with a 13-byte pool header - a u32, the 0x47 marker at +4, the packed payload length at +5 (the length including the header) and the unpacked size at +9 - or with the file block's 9-byte stream header; without either, the tokens start at the first byte. The back-references reach into the pool stream: the reconstruction of every preceding pool of the document and of this pool before the record, each subgroup contributing its header and its decoded payload (the raw bytes when a payload does not fully decode, which keeps the distances of the following subgroups plausible). Reading a pool therefore decodes the pools before it in order. A distance is a u16, so the window keeps only its 64 KiB tail: the memory stays constant in the size of the file (a full reconstruction of a 777 MB sample exceeds 2 GiB). FindCompressedPools caches its list after the first scan so the pool objects stay identical between calls. Verified against saved files: every mode-2 subgroup of the corpus decodes, among them 14,446 in a 777 MB office sample and 5,254 in a stacked tower sample. --- CHANGELOG.md | 10 +++ docs/public-api.md | 15 +++-- src/PlaIO/Internal/PoolSubgroupReader.cs | 65 ++++++++++++++++++- src/PlaIO/Model/CompressedPool.cs | 7 +- src/PlaIO/PlaDocument.cs | 8 ++- tests/PlaIO.Tests/PoolSubgroupTests.cs | 82 +++++++++++++++++++++++- 6 files changed, 173 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f77afa..9554a50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,16 @@ API between minor releases. - `PlaStream.SkippedBlocks`: the indexed blocks that failed to decode to their declared size (false entries of the scan), in file order — the blocks behind `UnreliableFrom`. +- `CompressedPool.ReadSubgroups()` decodes mode-2 pool subgroups. A mode-2 payload is an LZ token stream like a + mode-2 block payload; it may start with a 13-byte pool header (a u32, the 0x47 marker, the packed payload length + and the unpacked size) or with the file block's 9-byte stream header. Its back-references reach into the pool + stream — the reconstruction of every preceding pool of the document and of this pool before the record — so + reading a pool decodes the pools before it in order and the cost of the call grows with the size of the file (the + window of the back-references keeps only its 64 KiB tail, so the memory stays constant in the size of the file). A + payload that does not decode is reported with empty data and `Partial`, as before. Verified against saved files: + every mode-2 subgroup of the corpus decodes (among them 14,446 in a 777 MB office sample). `FindCompressedPools` + now caches its list after the first scan, so the pool objects stay identical between calls. + ### Changed - The core library follows the IOExtend reference layout (RvtIO, NwcIO): the entry points (`PlaDocument`, diff --git a/docs/public-api.md b/docs/public-api.md index a332161..e506595 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -62,7 +62,7 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has | Member | Use | |---|---| -| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. Computed on each call. | +| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. The first call scans the file; later calls return the cached list, so the pool objects stay identical. | | `CompressedPool.Offset` and `End` | File offsets of the pool marker and of the end of the pool. | | `CompressedPool.TotalDecompressed` and `BlockCount` | Decoded byte count and number of frames in the pool. | | `CompressedPool.Decode()` | Decoded frame payloads in order. Throws `InvalidDataException` on invalid framing or data (a pool past `PlaReaderOptions.MaxDecodedPoolBytes` included) and `ObjectDisposedException` after disposing the document. | @@ -70,15 +70,20 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has ### Pool subgroups The subgroup header uses the FDB size field widths and may carry a GUID. It does not contain the file-level extra field. -Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte. +Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte. A mode-2 +payload is an LZ token stream like a mode-2 block payload: it may start with a 13-byte pool header (a u32, the 0x47 +marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header, and its +back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this +pool before the record — so reading a pool decodes the pools before it in order, and the cost of the call grows with +the size of the file (the window keeps only its 64 KiB tail, so the memory stays constant in the size of the file). | Member | Use | |---|---| -| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order. | +| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order, with mode-2 payloads decoded against the pool stream. | | `PoolSubgroup.Offset` | Start of the subgroup header in the decoded pool. | | `PoolSubgroup.Kind`, `Version`, `Flags` and `ObjectId` | Raw header metadata and the optional GUID. | -| `PoolSubgroup.Mode` and `Data` | Raw or zero-mask payload bytes. Mode 2 is reported with empty data. | -| `PoolSubgroup.Partial` | True for unavailable mode 2 data or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. | +| `PoolSubgroup.Mode` and `Data` | The payload bytes: raw as they are, zero-mask and mode-2 as their decoded output. A mode-2 payload that does not decode is reported with empty data and `Partial`. | +| `PoolSubgroup.Partial` | True for a mode-2 payload that does not decode (or produces less than declared) or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. | ## BIMx file (`.bimx`) diff --git a/src/PlaIO/Internal/PoolSubgroupReader.cs b/src/PlaIO/Internal/PoolSubgroupReader.cs index ee7e8b1..fbd0b14 100644 --- a/src/PlaIO/Internal/PoolSubgroupReader.cs +++ b/src/PlaIO/Internal/PoolSubgroupReader.cs @@ -1,10 +1,35 @@ +using System.Buffers.Binary; using PlaIO.Model; namespace PlaIO.Internal; +/// Reads the BL-tagged records of one decoded pool. A mode-2 payload is an LZ token stream like a mode-2 +/// block payload; its back-references reach into the pool stream — the reconstruction of every preceding pool of the +/// document (each subgroup's header, raw payloads as they are, zero-mask and mode-2 payloads as their full decodes, +/// concatenated in pool order), followed by the requested pool's own reconstruction so far. The pools are therefore +/// decoded in order until the requested one, and the cost of a read grows with the file. The window keeps only its +/// tail: a back-reference distance is a u16, so nothing reaches further back than +/// bytes and the memory stays constant in the size of the file. internal static class PoolSubgroupReader { - public static IReadOnlyList Read(byte[] pool) + /// The window tail kept for back-references: the largest distance the format can name. + private const int WindowTail = 1 << 16; + + public static IReadOnlyList Read(PlaDocument document, CompressedPool through) + { + var window = new List(); + foreach (var pool in document.FindCompressedPools()) + { + var subgroups = ReadPool(pool.Decode(), window); + if (ReferenceEquals(pool, through)) return subgroups; + } + throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(through)); + } + + /// Walks one decoded pool: parses each BL-tagged record, decodes its payload against + /// , and appends the record's reconstruction (header plus decoded payload) to the window + /// so the following subgroups can reference it. + private static IReadOnlyList ReadPool(byte[] pool, List window) { var subgroups = new List(); int pos = 0; @@ -20,6 +45,7 @@ public static IReadOnlyList Read(byte[] pool) } ReadOnlySpan payload = pool.AsSpan((int)header.PayloadOffset, (int)header.PackedSize); + ReadOnlySpan headerBytes = pool.AsSpan(pos, (int)header.PayloadOffset - pos); byte[] data; bool partial; switch (header.Mode) @@ -33,13 +59,46 @@ public static IReadOnlyList Read(byte[] pool) PayloadDecoder.DecodeZeroMask(payload, data, out _, out partial); break; default: - data = []; - partial = true; + (data, partial) = DecodeLz(payload, header, window); break; } subgroups.Add(new PoolSubgroup(header, data, partial)); + + // The window holds the reconstruction: the header bytes, then the decoded payload — except for a payload + // that does not fully decode (a truncated zero-mask literal, a mode-2 stream that fails), where the raw + // bytes keep the distances of the following subgroups plausible. Only the tail is kept; a distance + // cannot reach further back anyway. + window.AddRange(headerBytes); + window.AddRange(partial && data.Length != header.UnpackedSize ? payload.ToArray() : data); + if (window.Count > 4 * WindowTail) window.RemoveRange(0, window.Count - WindowTail); pos = (int)header.End; } return subgroups.AsReadOnly(); } + + /// Decodes one mode-2 subgroup payload. A 13-byte header — a u32, the marker 0x47 at +4, then the packed + /// payload length at +5 (the length including the header) and the unpacked size at +9 — precedes the token stream; + /// without it the payload starts with the file block's 9-byte stream header or with the tokens themselves. + /// Returns the declared unpacked buffer with a zero tail when the stream produces less than declared (partial), + /// or empty data with partial set when the stream does not decode at all. + private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, PlaBlock header, List window) + { + bool hasPoolHeader = payload.Length > 13 && payload[4] == 0x47 + && BinaryPrimitives.ReadUInt32LittleEndian(payload[5..]) == (uint)header.PackedSize + && BinaryPrimitives.ReadUInt32LittleEndian(payload[9..]) == (uint)header.UnpackedSize; + ReadOnlySpan body = hasPoolHeader ? payload[13..] : payload; + + var output = new byte[header.UnpackedSize]; + try + { + LzPayloadDecoder.Decode(body, output, window, header.Offset, out int produced); + return (output, produced < header.UnpackedSize); + } + catch (InvalidDataException) + { + // The stream does not decode; the caller keeps the raw payload in the window so the distances of the + // following subgroups stay plausible. + return ([], true); + } + } } diff --git a/src/PlaIO/Model/CompressedPool.cs b/src/PlaIO/Model/CompressedPool.cs index cf60aa1..b00881f 100644 --- a/src/PlaIO/Model/CompressedPool.cs +++ b/src/PlaIO/Model/CompressedPool.cs @@ -34,8 +34,11 @@ internal CompressedPool(PlaDocument document, PoolRange range) /// The owning document is disposed. public byte[] Decode() => _document.DecodePool(Offset); - /// Decodes the pool and reads BL-tagged records in pool order. + /// Decodes the pool and reads BL-tagged records in pool order. A mode-2 payload is an LZ token stream + /// whose back-references reach into the pool stream — the reconstruction of every preceding pool of the document + /// and of this pool before the record — so the pools are decoded in order until this one and the cost of the call + /// grows with the size of the file. /// The pool does not decode. /// The owning document is disposed. - public IReadOnlyList ReadSubgroups() => PoolSubgroupReader.Read(Decode()); + public IReadOnlyList ReadSubgroups() => PoolSubgroupReader.Read(_document, this); } diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 3f59e20..5e6523c 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -13,6 +13,7 @@ public sealed class PlaDocument : IDisposable private readonly bool _leaveOpen; private readonly List _blocks; private readonly PlaReaderOptions _options; + private IReadOnlyList? _pools; private bool _disposed; private PlaDocument(Stream stream, bool leaveOpen, long length, FdbHeader header, List blocks, PlaReaderOptions options) @@ -212,11 +213,14 @@ public IReadOnlyList FindDirectories() return found.AsReadOnly(); } - /// Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. + /// Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. The first + /// call scans the file; later calls return the cached list, so the pool objects stay identical. public IReadOnlyList FindCompressedPools() { ObjectDisposedException.ThrowIf(_disposed, this); - return PoolReader.Find(_stream, Length, Blocks).Select(range => new CompressedPool(this, range)).ToList().AsReadOnly(); + if (_pools is null) + _pools = PoolReader.Find(_stream, Length, Blocks).Select(range => new CompressedPool(this, range)).ToList().AsReadOnly(); + return _pools; } internal byte[] DecodePool(long offset) diff --git a/tests/PlaIO.Tests/PoolSubgroupTests.cs b/tests/PlaIO.Tests/PoolSubgroupTests.cs index c769ff5..0583f6c 100644 --- a/tests/PlaIO.Tests/PoolSubgroupTests.cs +++ b/tests/PlaIO.Tests/PoolSubgroupTests.cs @@ -49,6 +49,45 @@ public void LzSubgroupReportsPartialWithEmptyData() Assert.True(record.Partial); } + [Fact] + public void LzSubgroupDecodesAgainstAnEarlierPool() + { + // Pool 1: one raw subgroup "ABCDEFGH"; its reconstruction in the pool stream is the 13-byte + // header followed by the payload, so "ABCD" starts at offset 13 of the window. + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()); + // Pool 2: one mode-2 subgroup. Its payload starts with the pool header [u32][0x47][u32 packed][u32 unpacked] + // and the token stream emits the literals XY, then a match of length 4 at distance 10: the window ends two + // bytes past the 21-byte reconstruction of pool 1, and 23 - 13 = 10 reaches "ABCD". + byte[] tokens = [0x20, (byte)'X', (byte)'Y', 0x00, 0x0A, 0x04]; + byte[] payload = PoolLzPayload(tokens, unpacked: 6); + byte[] second = Synthetic.Block(PlaBlockMode.Lz, payload, unpacked: 6); + using var doc = OpenPools(first, second); + + var record = Assert.Single(doc.FindCompressedPools()[1].ReadSubgroups()); + Assert.Equal(PlaBlockMode.Lz, record.Mode); + Assert.Equal("XYABCD"u8.ToArray(), record.Data); + Assert.False(record.Partial); + } + + [Fact] + public void LzSubgroupWithTheBlockStreamHeaderDecodesWithoutAPoolHeader() + { + // A mode-2 payload may instead start with the file block's 9-byte stream header, which the LZ decoder + // recognises itself; here 6 literals stand alone, so nothing is referenced. + byte[] tokens = [0x60, (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F']; + byte[] payload = new byte[9 + tokens.Length]; + payload[0] = 0x47; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(1), (uint)payload.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(5), 6); + tokens.CopyTo(payload, 9); + byte[] subgroup = Synthetic.Block(PlaBlockMode.Lz, payload, unpacked: 6); + using var doc = OpenPool(subgroup); + + var record = Assert.Single(Assert.Single(doc.FindCompressedPools()).ReadSubgroups()); + Assert.Equal("ABCDEF"u8.ToArray(), record.Data); + Assert.False(record.Partial); + } + [Fact] public void ShortHeaderCandidateDoesNotHideLaterRecord() { @@ -88,6 +127,45 @@ public void ReadsSubgroupsFromSavedFiles() if (pools == 0) throw TestFiles.Missing("FDB fixture with nonempty QuickLZ pools"); } - private static PlaDocument OpenPool(byte[] data) => PlaDocument.Open(new MemoryStream(Synthetic.Fdb( - Synthetic.QuickLzPool(((uint)data.Length, Synthetic.QuickLzFrame(data, data.Length, flags: 0x46)))))); + [SkippableFact] + public void EveryLzSubgroupOfSavedFilesDecodes() + { + using var corpus = new SampleCorpus(); + long mode2 = 0, decoded = 0; + foreach (var sample in corpus.Fdb) + { + foreach (var pool in sample.Document.FindCompressedPools()) + { + foreach (var record in pool.ReadSubgroups()) + { + if (record.Mode != PlaBlockMode.Lz) continue; + mode2++; + if (!record.Partial && record.Data.Length > 0) decoded++; + } + } + } + if (mode2 == 0) throw TestFiles.Missing("FDB fixture with mode-2 pool subgroups"); + Assert.True(decoded >= 0.99 * mode2, $"{decoded} of {mode2} mode-2 subgroups decode"); + } + + private static PlaDocument OpenPool(byte[] data) => OpenPools(data); + + private static PlaDocument OpenPools(params byte[][] data) + { + byte[][] pools = data.Select(content => Synthetic.QuickLzPool( + ((uint)content.Length, Synthetic.QuickLzFrame(content, content.Length, flags: 0x46)))).ToArray(); + return PlaDocument.Open(new MemoryStream(Synthetic.Fdb(pools))); + } + + /// The 13-byte mode-2 pool header: a u32, the 0x47 marker, the packed payload length (including the + /// header) and the unpacked size, followed by the token stream. + private static byte[] PoolLzPayload(byte[] tokens, int unpacked) + { + byte[] payload = new byte[13 + tokens.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(5), (uint)payload.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(9), (uint)unpacked); + payload[4] = 0x47; + tokens.CopyTo(payload, 13); + return payload; + } } From 29725caa2916869c5bfa1f4172805b704125375c Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:21:10 +0300 Subject: [PATCH 2/4] Contribute each subgroup to the pool window exactly once Review fixes: - The LZ decoder already appends every produced byte to the window, so a decoded subgroup's payload entered the history twice: the header went in, then the decoder's contribution, then the same output again. Sizes still matched, so the corrupt results passed as complete. The header now joins the window before the stream decodes, the decoder makes the payload's contribution, the declared tail of a buffer block is zero-filled, and a stream that fails has its partial contribution rolled back before the raw bytes go in. A test matches a later LZ subgroup against the decoded output of an earlier one and asserts the exact bytes. - A truncated zero-mask literal contributed its zero-filled remainder to the window (the fallback branch was unreachable because the data buffer always has the declared length); the window now takes the raw payload bytes whenever a payload does not fully decode, and a test pins the distance arithmetic through such a subgroup. - Reading pools in file order advances one shared window on the document, so every pool decodes once instead of once per read (the saved-file corpus test over two large models went from minutes to seconds); a read naming an earlier pool rebuilds the window, and a preceding pool that does not decode is skipped instead of blocking later pools. Raw and zero-mask records never consult the window; only mode-2 payloads do. - The changelog no longer names sizes and counts of private samples. --- CHANGELOG.md | 13 ++-- docs/public-api.md | 6 +- src/PlaIO/Internal/PoolSubgroupReader.cs | 70 +++++++++++----------- src/PlaIO/Model/CompressedPool.cs | 6 +- src/PlaIO/PlaDocument.cs | 40 +++++++++++++ tests/PlaIO.Tests/PoolSubgroupTests.cs | 75 +++++++++++++++++++++++- 6 files changed, 161 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9554a50..24cbe81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,12 +51,13 @@ API between minor releases. - `CompressedPool.ReadSubgroups()` decodes mode-2 pool subgroups. A mode-2 payload is an LZ token stream like a mode-2 block payload; it may start with a 13-byte pool header (a u32, the 0x47 marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header. Its back-references reach into the pool - stream — the reconstruction of every preceding pool of the document and of this pool before the record — so - reading a pool decodes the pools before it in order and the cost of the call grows with the size of the file (the - window of the back-references keeps only its 64 KiB tail, so the memory stays constant in the size of the file). A - payload that does not decode is reported with empty data and `Partial`, as before. Verified against saved files: - every mode-2 subgroup of the corpus decodes (among them 14,446 in a 777 MB office sample). `FindCompressedPools` - now caches its list after the first scan, so the pool objects stay identical between calls. + stream — the reconstruction of every preceding pool of the document and of this pool before the record — so a read + decodes the pools before the named one; reading the pools in file order advances one shared window, so every pool + decodes once, and a preceding pool that does not decode is skipped. The window keeps only its 64 KiB tail (a + back-reference distance is a u16), so the memory stays constant in the size of the file. A payload that does not + decode is reported with empty data and `Partial`, as before. Verified against the saved-file corpus: every mode-2 + subgroup decodes. `FindCompressedPools` now caches its list after the first scan, so the pool objects stay + identical between calls. ### Changed diff --git a/docs/public-api.md b/docs/public-api.md index e506595..5b5045f 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -74,8 +74,10 @@ Offsets are relative to the decoded pool. The scanner retries an unmatched BL ca payload is an LZ token stream like a mode-2 block payload: it may start with a 13-byte pool header (a u32, the 0x47 marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header, and its back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this -pool before the record — so reading a pool decodes the pools before it in order, and the cost of the call grows with -the size of the file (the window keeps only its 64 KiB tail, so the memory stays constant in the size of the file). +pool before the record — so a read decodes the pools before the named one. Reading the pools in file order advances +one shared window, so every pool decodes once; a read that names an earlier pool rebuilds the window, and a +preceding pool that does not decode is skipped. The window keeps only its 64 KiB tail (a back-reference distance is +a u16), so the memory stays constant in the size of the file. | Member | Use | |---|---| diff --git a/src/PlaIO/Internal/PoolSubgroupReader.cs b/src/PlaIO/Internal/PoolSubgroupReader.cs index fbd0b14..d4124d7 100644 --- a/src/PlaIO/Internal/PoolSubgroupReader.cs +++ b/src/PlaIO/Internal/PoolSubgroupReader.cs @@ -6,30 +6,19 @@ namespace PlaIO.Internal; /// Reads the BL-tagged records of one decoded pool. A mode-2 payload is an LZ token stream like a mode-2 /// block payload; its back-references reach into the pool stream — the reconstruction of every preceding pool of the /// document (each subgroup's header, raw payloads as they are, zero-mask and mode-2 payloads as their full decodes, -/// concatenated in pool order), followed by the requested pool's own reconstruction so far. The pools are therefore -/// decoded in order until the requested one, and the cost of a read grows with the file. The window keeps only its -/// tail: a back-reference distance is a u16, so nothing reaches further back than -/// bytes and the memory stays constant in the size of the file. +/// concatenated in pool order), followed by this pool's own reconstruction so far. The window keeps only its tail: a +/// back-reference distance is a u16, so nothing reaches further back than bytes and the +/// memory stays constant in the size of the file. internal static class PoolSubgroupReader { /// The window tail kept for back-references: the largest distance the format can name. private const int WindowTail = 1 << 16; - public static IReadOnlyList Read(PlaDocument document, CompressedPool through) - { - var window = new List(); - foreach (var pool in document.FindCompressedPools()) - { - var subgroups = ReadPool(pool.Decode(), window); - if (ReferenceEquals(pool, through)) return subgroups; - } - throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(through)); - } - /// Walks one decoded pool: parses each BL-tagged record, decodes its payload against - /// , and appends the record's reconstruction (header plus decoded payload) to the window - /// so the following subgroups can reference it. - private static IReadOnlyList ReadPool(byte[] pool, List window) + /// , and appends the record's contribution to the window — its header bytes and its + /// payload exactly once — so the following subgroups can reference it. A record whose payload does not fully + /// decode contributes its raw bytes, which keeps the distances of the following subgroups plausible. + internal static IReadOnlyList ReadPool(byte[] pool, List window) { var subgroups = new List(); int pos = 0; @@ -48,28 +37,31 @@ private static IReadOnlyList ReadPool(byte[] pool, List wind ReadOnlySpan headerBytes = pool.AsSpan(pos, (int)header.PayloadOffset - pos); byte[] data; bool partial; - switch (header.Mode) + if (header.Mode == PlaBlockMode.Lz) + { + // The LZ decoder appends every produced byte to the window itself, so the header goes in first and + // the payload's contribution is made exactly once — inside DecodeLz. + window.AddRange(headerBytes); + (data, partial) = DecodeLz(payload, header, window); + } + else { - case PlaBlockMode.Raw: + if (header.Mode == PlaBlockMode.Raw) + { data = payload.ToArray(); partial = false; - break; - case PlaBlockMode.ZeroMask: + } + else + { data = new byte[header.UnpackedSize]; PayloadDecoder.DecodeZeroMask(payload, data, out _, out partial); - break; - default: - (data, partial) = DecodeLz(payload, header, window); - break; + } + window.AddRange(headerBytes); + // A truncated zero-mask literal leaves the rest of its buffer zero-filled; the window takes the raw + // bytes instead, because that is what the saved stream addresses. + window.AddRange(partial ? payload.ToArray() : data); } subgroups.Add(new PoolSubgroup(header, data, partial)); - - // The window holds the reconstruction: the header bytes, then the decoded payload — except for a payload - // that does not fully decode (a truncated zero-mask literal, a mode-2 stream that fails), where the raw - // bytes keep the distances of the following subgroups plausible. Only the tail is kept; a distance - // cannot reach further back anyway. - window.AddRange(headerBytes); - window.AddRange(partial && data.Length != header.UnpackedSize ? payload.ToArray() : data); if (window.Count > 4 * WindowTail) window.RemoveRange(0, window.Count - WindowTail); pos = (int)header.End; } @@ -80,7 +72,10 @@ private static IReadOnlyList ReadPool(byte[] pool, List wind /// payload length at +5 (the length including the header) and the unpacked size at +9 — precedes the token stream; /// without it the payload starts with the file block's 9-byte stream header or with the tokens themselves. /// Returns the declared unpacked buffer with a zero tail when the stream produces less than declared (partial), - /// or empty data with partial set when the stream does not decode at all. + /// or empty data with partial set when the stream does not decode at all. The window receives the payload's + /// contribution exactly once: the decoder appends the produced bytes, this method adds the declared tail of a + /// buffer block, and a stream that fails has its partial contribution rolled back before the raw bytes go + /// in. private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, PlaBlock header, List window) { bool hasPoolHeader = payload.Length > 13 && payload[4] == 0x47 @@ -92,12 +87,15 @@ private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, try { LzPayloadDecoder.Decode(body, output, window, header.Offset, out int produced); + if (produced < header.UnpackedSize) + window.AddRange(new byte[(int)(header.UnpackedSize - produced)]); // the buffer space stays addressed return (output, produced < header.UnpackedSize); } catch (InvalidDataException) { - // The stream does not decode; the caller keeps the raw payload in the window so the distances of the - // following subgroups stay plausible. + // The decoder rolled its partial contribution back; the raw bytes keep the distances of the following + // subgroups plausible. + window.AddRange(payload.ToArray()); return ([], true); } } diff --git a/src/PlaIO/Model/CompressedPool.cs b/src/PlaIO/Model/CompressedPool.cs index b00881f..7709d5a 100644 --- a/src/PlaIO/Model/CompressedPool.cs +++ b/src/PlaIO/Model/CompressedPool.cs @@ -37,8 +37,10 @@ internal CompressedPool(PlaDocument document, PoolRange range) /// Decodes the pool and reads BL-tagged records in pool order. A mode-2 payload is an LZ token stream /// whose back-references reach into the pool stream — the reconstruction of every preceding pool of the document /// and of this pool before the record — so the pools are decoded in order until this one and the cost of the call - /// grows with the size of the file. + /// grows with the size of the file. Reading the pools in file order advances one shared window, so every pool + /// decodes once; a read that names an earlier pool rebuilds the window. A preceding pool that does not decode is + /// skipped and reading continues with this one. /// The pool does not decode. /// The owning document is disposed. - public IReadOnlyList ReadSubgroups() => PoolSubgroupReader.Read(_document, this); + public IReadOnlyList ReadSubgroups() => _document.ReadPoolSubgroups(this); } diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 5e6523c..247db5e 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -229,6 +229,46 @@ internal byte[] DecodePool(long offset) return PoolReader.Decode(_stream, Length, offset, _options.MaxDecodedPoolBytes); } + /// The window that decoding builds while the pools are read in order: + /// the tail of the pool-stream reconstruction up to the pool with index (that + /// pool excluded). Reading the pools in file order advances the window, so every pool decodes once; a read that + /// names an earlier pool rebuilds the window from the start. + private List? _poolWindow; + private int _poolWindowThrough; + + /// Reads the subgroups of one pool of this document, decoding the pool stream up to it (see + /// ). A preceding pool that fails to decode is skipped: the + /// window continues without it, and the subgroups of the named pool are still read. + internal IReadOnlyList ReadPoolSubgroups(CompressedPool pool) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var pools = FindCompressedPools(); + int target = 0; + while (target < pools.Count && !ReferenceEquals(pools[target], pool)) target++; + if (target == pools.Count) + throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(pool)); + + if (_poolWindow is null || target < _poolWindowThrough) + { + _poolWindow = new List(); + _poolWindowThrough = 0; + } + for (int index = _poolWindowThrough; index < target; index++) + { + try + { + PoolSubgroupReader.ReadPool(pools[index].Decode(), _poolWindow); + } + catch (InvalidDataException) + { + // A pool that does not decode is skipped; the window continues without it. + } + } + var subgroups = PoolSubgroupReader.ReadPool(pools[target].Decode(), _poolWindow); + _poolWindowThrough = target + 1; + return subgroups; + } + /// Releases the stream unless the document was opened with leaveOpen. public void Dispose() { diff --git a/tests/PlaIO.Tests/PoolSubgroupTests.cs b/tests/PlaIO.Tests/PoolSubgroupTests.cs index 0583f6c..b0febc8 100644 --- a/tests/PlaIO.Tests/PoolSubgroupTests.cs +++ b/tests/PlaIO.Tests/PoolSubgroupTests.cs @@ -56,9 +56,10 @@ public void LzSubgroupDecodesAgainstAnEarlierPool() // header followed by the payload, so "ABCD" starts at offset 13 of the window. byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()); // Pool 2: one mode-2 subgroup. Its payload starts with the pool header [u32][0x47][u32 packed][u32 unpacked] - // and the token stream emits the literals XY, then a match of length 4 at distance 10: the window ends two - // bytes past the 21-byte reconstruction of pool 1, and 23 - 13 = 10 reaches "ABCD". - byte[] tokens = [0x20, (byte)'X', (byte)'Y', 0x00, 0x0A, 0x04]; + // and the token stream emits the literals XY, then a match of length 4. The subgroup's own 17-byte header is + // already part of the window when its stream decodes, so the window ends at 21 + 17 + 2 = 40 and the distance + // 40 - 13 = 27 reaches "ABCD" of pool 1. + byte[] tokens = [0x20, (byte)'X', (byte)'Y', 0x00, 0x1B, 0x04]; byte[] payload = PoolLzPayload(tokens, unpacked: 6); byte[] second = Synthetic.Block(PlaBlockMode.Lz, payload, unpacked: 6); using var doc = OpenPools(first, second); @@ -69,6 +70,74 @@ public void LzSubgroupDecodesAgainstAnEarlierPool() Assert.False(record.Partial); } + [Fact] + public void ALaterLzSubgroupMatchesTheDecodedOutputOfAnEarlierOneExactlyOnce() + { + // Pool 1: raw "ABCDEFGH" (13-byte header + 8 payload = 21 bytes of window). + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()); + // Pool 2, subgroup 1: mode 2 emitting the literals WXYZ. Its 17-byte header plus the 4 produced bytes end + // the window at 21 + 17 + 4 = 42, with WXYZ at 38..41. + byte[] firstTokens = [0x40, (byte)'W', (byte)'X', (byte)'Y', (byte)'Z']; + byte[] firstLz = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(firstTokens, unpacked: 4), unpacked: 4); + // Pool 2, subgroup 2: mode 2 matching length 4. The window at its match is 42 bytes of content plus the + // subgroup's own 17-byte header (the header joins the window before the stream decodes), so the distance + // 59 - 38 = 21 lands on WXYZ only when the output of subgroup 1 entered the window exactly once. A + // duplicated contribution shifts the distance onto other bytes, and the match returns wrong data while + // still reporting a complete decode. + byte[] secondTokens = [0x00, 0x00, 0x15, 0x04]; + byte[] secondLz = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(secondTokens, unpacked: 4), unpacked: 4); + using var doc = OpenPools(first, Synthetic.Concat(firstLz, secondLz)); + + var records = doc.FindCompressedPools()[1].ReadSubgroups(); + Assert.Equal(2, records.Count); + Assert.Equal("WXYZ"u8.ToArray(), records[0].Data); + Assert.Equal("WXYZ"u8.ToArray(), records[1].Data); + Assert.False(records[1].Partial); + } + + [Fact] + public void ATruncatedZeroMaskSubgroupContributesItsRawBytesToTheWindow() + { + // Pool 1: raw "ABCD" (13 + 4 = 17 bytes of window, "ABCD" at 13..16). + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray()); + // Pool 2, subgroup 1: a zero-mask subgroup whose single mask byte 0x80 starts a literal that the payload + // never delivers — the decode reports partial and the window takes the one raw payload byte, not the + // zero-filled remainder of the declared buffer. + byte[] truncated = Synthetic.Block(PlaBlockMode.ZeroMask, [0x80], unpacked: 8); + // Pool 2, subgroup 2: a match of length 4 at distance 52 - 13 = 39 (35 bytes of content plus the + // subgroup's own 17-byte header), which reaches "ABCD" of pool 1 only when the truncated subgroup + // contributed its 1 raw byte (17 + 17 + 1 = 35); a zero-filled contribution of 8 bytes shifts the + // distance onto zeros. + byte[] tokens = [0x00, 0x00, 0x27, 0x04]; + byte[] match = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(tokens, unpacked: 4), unpacked: 4); + using var doc = OpenPools(first, Synthetic.Concat(truncated, match)); + + var records = doc.FindCompressedPools()[1].ReadSubgroups(); + Assert.Equal(2, records.Count); + Assert.True(records[0].Partial); + Assert.Equal("ABCD"u8.ToArray(), records[1].Data); + Assert.False(records[1].Partial); + } + + [Fact] + public void APoolThatDoesNotDecodeDoesNotBlockLaterPools() + { + // Pool 1: structurally valid framing whose compressed frame fails inside the QuickLZ decode, so the pool is + // found but does not decode. Pool 2 is a plain raw pool and must still be readable. + byte[] brokenFrameBody = [0x01, 0x00, 0x00, 0x80, 0xF1, 0xFF]; // control word with a match at an unregistered slot + byte[] brokenPool = Synthetic.QuickLzPool((8, Synthetic.QuickLzFrame(brokenFrameBody, 8, flags: 0x45))); + byte[] goodContent = Synthetic.Block(PlaBlockMode.Raw, "sample"u8.ToArray()); + byte[] goodPool = Synthetic.QuickLzPool( + ((uint)goodContent.Length, Synthetic.QuickLzFrame(goodContent, goodContent.Length, flags: 0x46))); + using var doc = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(brokenPool, goodPool))); + + var pools = doc.FindCompressedPools(); + Assert.Equal(2, pools.Count); + Assert.Throws(() => pools[0].ReadSubgroups()); + var record = Assert.Single(pools[1].ReadSubgroups()); + Assert.Equal("sample"u8.ToArray(), record.Data); + } + [Fact] public void LzSubgroupWithTheBlockStreamHeaderDecodesWithoutAPoolHeader() { From 49a8a8ba27116df9f218855dc2518d0c4b780cec Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:28:28 +0300 Subject: [PATCH 3/4] Pin the single-pass pool walk with a counting-stream test Reading the pools in file order advances the shared window, so every pool decodes once. The new test opens a document over a stream that counts seeks to the pool markers - every pool decode starts by reading the pool header - and asserts that a full pass over eight pools reads each header exactly once (N decodes, not the N(N+1)/2 = 36 of a per-call rebuild). --- tests/PlaIO.Tests/PoolSubgroupTests.cs | 50 ++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/PlaIO.Tests/PoolSubgroupTests.cs b/tests/PlaIO.Tests/PoolSubgroupTests.cs index b0febc8..10fcb7b 100644 --- a/tests/PlaIO.Tests/PoolSubgroupTests.cs +++ b/tests/PlaIO.Tests/PoolSubgroupTests.cs @@ -138,6 +138,56 @@ public void APoolThatDoesNotDecodeDoesNotBlockLaterPools() Assert.Equal("sample"u8.ToArray(), record.Data); } + [Fact] + public void ReadingThePoolsInOrderDecodesEachPoolOnce() + { + // Eight raw pools; a full pass reads every pool's subgroups in file order. The counting stream counts how + // often each pool header is read (every decode of a pool starts by reading its 32-byte header), so the test + // pins the shared window: N pools decode N times, not N(N+1)/2 = 36 times as a per-call rebuild would. + const int count = 8; + byte[] file = Synthetic.Fdb(Enumerable.Range(0, count).Select(i => + { + byte[] content = Synthetic.Block(PlaBlockMode.Raw, [(byte)i]); + return Synthetic.QuickLzPool(((uint)content.Length, + Synthetic.QuickLzFrame(content, content.Length, flags: 0x46))); + }).ToArray()); + var counter = new CountingStream(file); + using var doc = PlaDocument.Open(counter); + + var pools = doc.FindCompressedPools(); + Assert.Equal(count, pools.Count); + counter.Watch(pools.Select(p => p.Offset)); // the find scan is over; count from here + + foreach (var pool in pools) pool.ReadSubgroups(); + + Assert.Equal(count, counter.Total); + Assert.All(pools, pool => Assert.Equal(1, counter.TimesRead(pool.Offset))); + } + + /// A stream that counts how often a seek lands on one of the watched offsets — every decode of a pool + /// seeks to the pool marker to read its header first. + private sealed class CountingStream(byte[] data) : MemoryStream(data) + { + private readonly HashSet _watch = []; + private readonly Dictionary _counts = []; + + public void Watch(IEnumerable offsets) + { + foreach (long offset in offsets) _watch.Add(offset); + } + + public int Total => _counts.Values.Sum(); + + public int TimesRead(long offset) => _counts.GetValueOrDefault(offset); + + public override long Seek(long offset, SeekOrigin origin) + { + if (origin == SeekOrigin.Begin && _watch.Contains(offset)) + _counts[offset] = _counts.GetValueOrDefault(offset) + 1; + return base.Seek(offset, origin); + } + } + [Fact] public void LzSubgroupWithTheBlockStreamHeaderDecodesWithoutAPoolHeader() { From 05102c37feb2a384e52b2bd61bac9a4f7384a55f Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:44:01 +0300 Subject: [PATCH 4/4] Preserve reliable subgroup history across failed pool reads --- CHANGELOG.md | 7 ++- docs/public-api.md | 7 +-- src/PlaIO/Internal/PoolSubgroupReader.cs | 11 ++--- src/PlaIO/Model/CompressedPool.cs | 9 ++-- src/PlaIO/Model/PoolSubgroup.cs | 2 +- src/PlaIO/PlaDocument.cs | 17 ++++--- tests/PlaIO.Tests/PoolSubgroupTests.cs | 60 ++++++++++++++++++++---- 7 files changed, 78 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24cbe81..403ee08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,10 +53,9 @@ API between minor releases. and the unpacked size) or with the file block's 9-byte stream header. Its back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this pool before the record — so a read decodes the pools before the named one; reading the pools in file order advances one shared window, so every pool - decodes once, and a preceding pool that does not decode is skipped. The window keeps only its 64 KiB tail (a - back-reference distance is a u16), so the memory stays constant in the size of the file. A payload that does not - decode is reported with empty data and `Partial`, as before. Verified against the saved-file corpus: every mode-2 - subgroup decodes. `FindCompressedPools` now caches its list after the first scan, so the pool objects stay + decodes once. A skipped pool or an undecodable mode-2 subgroup resets the history. A mode-2 payload that cannot + decode is reported with empty data and `Partial`. The decoder discards history beyond the maximum back-reference + distance between records. `FindCompressedPools` caches its list after the first scan, so the pool objects stay identical between calls. ### Changed diff --git a/docs/public-api.md b/docs/public-api.md index 5b5045f..072500d 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -75,9 +75,10 @@ payload is an LZ token stream like a mode-2 block payload: it may start with a 1 marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header, and its back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this pool before the record — so a read decodes the pools before the named one. Reading the pools in file order advances -one shared window, so every pool decodes once; a read that names an earlier pool rebuilds the window, and a -preceding pool that does not decode is skipped. The window keeps only its 64 KiB tail (a back-reference distance is -a u16), so the memory stays constant in the size of the file. +one shared window, so every pool decodes once. A read that names an earlier pool rebuilds the window. A skipped +pool or an undecodable mode-2 subgroup resets the history. A reference into missing history returns empty data +with `Partial` set. Subgroups can continue to reference bytes decoded after the gap. A back-reference distance is a +u16, so the decoder can discard older history between records. | Member | Use | |---|---| diff --git a/src/PlaIO/Internal/PoolSubgroupReader.cs b/src/PlaIO/Internal/PoolSubgroupReader.cs index d4124d7..ef6e914 100644 --- a/src/PlaIO/Internal/PoolSubgroupReader.cs +++ b/src/PlaIO/Internal/PoolSubgroupReader.cs @@ -16,8 +16,8 @@ internal static class PoolSubgroupReader /// Walks one decoded pool: parses each BL-tagged record, decodes its payload against /// , and appends the record's contribution to the window — its header bytes and its - /// payload exactly once — so the following subgroups can reference it. A record whose payload does not fully - /// decode contributes its raw bytes, which keeps the distances of the following subgroups plausible. + /// payload exactly once — so the following subgroups can reference it. A truncated zero-mask payload contributes + /// its stored bytes. An undecodable mode-2 payload resets the history. internal static IReadOnlyList ReadPool(byte[] pool, List window) { var subgroups = new List(); @@ -74,8 +74,7 @@ internal static IReadOnlyList ReadPool(byte[] pool, List win /// Returns the declared unpacked buffer with a zero tail when the stream produces less than declared (partial), /// or empty data with partial set when the stream does not decode at all. The window receives the payload's /// contribution exactly once: the decoder appends the produced bytes, this method adds the declared tail of a - /// buffer block, and a stream that fails has its partial contribution rolled back before the raw bytes go - /// in. + /// buffer block. A failed stream resets the history so later references cannot reach across the missing output. private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, PlaBlock header, List window) { bool hasPoolHeader = payload.Length > 13 && payload[4] == 0x47 @@ -93,9 +92,7 @@ private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, } catch (InvalidDataException) { - // The decoder rolled its partial contribution back; the raw bytes keep the distances of the following - // subgroups plausible. - window.AddRange(payload.ToArray()); + window.Clear(); return ([], true); } } diff --git a/src/PlaIO/Model/CompressedPool.cs b/src/PlaIO/Model/CompressedPool.cs index 7709d5a..0ee9494 100644 --- a/src/PlaIO/Model/CompressedPool.cs +++ b/src/PlaIO/Model/CompressedPool.cs @@ -8,15 +8,18 @@ public sealed class CompressedPool { private readonly PlaDocument _document; - internal CompressedPool(PlaDocument document, PoolRange range) + internal CompressedPool(PlaDocument document, PoolRange range, int index) { _document = document; + Index = index; Offset = range.Offset; End = range.End; TotalDecompressed = range.UnpackedSize; BlockCount = range.FrameCount; } + internal int Index { get; } + /// The file offset of the pool marker. public long Offset { get; } @@ -38,8 +41,8 @@ internal CompressedPool(PlaDocument document, PoolRange range) /// whose back-references reach into the pool stream — the reconstruction of every preceding pool of the document /// and of this pool before the record — so the pools are decoded in order until this one and the cost of the call /// grows with the size of the file. Reading the pools in file order advances one shared window, so every pool - /// decodes once; a read that names an earlier pool rebuilds the window. A preceding pool that does not decode is - /// skipped and reading continues with this one. + /// decodes once; a read that names an earlier pool rebuilds the window. An unreadable preceding pool resets + /// the history, and a subgroup that references missing bytes returns empty data with Partial set. /// The pool does not decode. /// The owning document is disposed. public IReadOnlyList ReadSubgroups() => _document.ReadPoolSubgroups(this); diff --git a/src/PlaIO/Model/PoolSubgroup.cs b/src/PlaIO/Model/PoolSubgroup.cs index a19ea7c..db9e4a9 100644 --- a/src/PlaIO/Model/PoolSubgroup.cs +++ b/src/PlaIO/Model/PoolSubgroup.cs @@ -33,7 +33,7 @@ internal PoolSubgroup(PlaBlock header, byte[] data, bool partial) /// The object GUID when present in the header. public Guid? ObjectId { get; } - /// The decoded payload. Mode 2 returns empty data pending a supported decoder. + /// The decoded payload. Mode 2 returns empty data when its stream cannot be decoded. public byte[] Data { get; } /// True when decoding is unavailable or the zero-mask stream ends inside a literal group. diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 247db5e..15abbc9 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -219,7 +219,7 @@ public IReadOnlyList FindCompressedPools() { ObjectDisposedException.ThrowIf(_disposed, this); if (_pools is null) - _pools = PoolReader.Find(_stream, Length, Blocks).Select(range => new CompressedPool(this, range)).ToList().AsReadOnly(); + _pools = PoolReader.Find(_stream, Length, Blocks).Select((range, index) => new CompressedPool(this, range, index)).ToList().AsReadOnly(); return _pools; } @@ -237,15 +237,14 @@ internal byte[] DecodePool(long offset) private int _poolWindowThrough; /// Reads the subgroups of one pool of this document, decoding the pool stream up to it (see - /// ). A preceding pool that fails to decode is skipped: the - /// window continues without it, and the subgroups of the named pool are still read. + /// ). A preceding pool that fails to decode resets the + /// history. Subgroups of the named pool can still use bytes decoded after that gap. internal IReadOnlyList ReadPoolSubgroups(CompressedPool pool) { ObjectDisposedException.ThrowIf(_disposed, this); var pools = FindCompressedPools(); - int target = 0; - while (target < pools.Count && !ReferenceEquals(pools[target], pool)) target++; - if (target == pools.Count) + int target = pool.Index; + if ((uint)target >= (uint)pools.Count || !ReferenceEquals(pools[target], pool)) throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(pool)); if (_poolWindow is null || target < _poolWindowThrough) @@ -253,15 +252,15 @@ internal IReadOnlyList ReadPoolSubgroups(CompressedPool pool) _poolWindow = new List(); _poolWindowThrough = 0; } - for (int index = _poolWindowThrough; index < target; index++) + for (; _poolWindowThrough < target; _poolWindowThrough++) { try { - PoolSubgroupReader.ReadPool(pools[index].Decode(), _poolWindow); + PoolSubgroupReader.ReadPool(pools[_poolWindowThrough].Decode(), _poolWindow); } catch (InvalidDataException) { - // A pool that does not decode is skipped; the window continues without it. + _poolWindow.Clear(); } } var subgroups = PoolSubgroupReader.ReadPool(pools[target].Decode(), _poolWindow); diff --git a/tests/PlaIO.Tests/PoolSubgroupTests.cs b/tests/PlaIO.Tests/PoolSubgroupTests.cs index 10fcb7b..a0f19a9 100644 --- a/tests/PlaIO.Tests/PoolSubgroupTests.cs +++ b/tests/PlaIO.Tests/PoolSubgroupTests.cs @@ -124,12 +124,8 @@ public void APoolThatDoesNotDecodeDoesNotBlockLaterPools() { // Pool 1: structurally valid framing whose compressed frame fails inside the QuickLZ decode, so the pool is // found but does not decode. Pool 2 is a plain raw pool and must still be readable. - byte[] brokenFrameBody = [0x01, 0x00, 0x00, 0x80, 0xF1, 0xFF]; // control word with a match at an unregistered slot - byte[] brokenPool = Synthetic.QuickLzPool((8, Synthetic.QuickLzFrame(brokenFrameBody, 8, flags: 0x45))); - byte[] goodContent = Synthetic.Block(PlaBlockMode.Raw, "sample"u8.ToArray()); - byte[] goodPool = Synthetic.QuickLzPool( - ((uint)goodContent.Length, Synthetic.QuickLzFrame(goodContent, goodContent.Length, flags: 0x46))); - using var doc = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(brokenPool, goodPool))); + byte[] goodPool = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "sample"u8.ToArray())); + using var doc = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(UnreadablePool(), goodPool))); var pools = doc.FindCompressedPools(); Assert.Equal(2, pools.Count); @@ -138,6 +134,49 @@ public void APoolThatDoesNotDecodeDoesNotBlockLaterPools() Assert.Equal("sample"u8.ToArray(), record.Data); } + [Fact] + public void APoolOverTheCapCannotSubstituteHistoryFromAnOlderPool() + { + byte[] first = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray())); + byte[] excluded = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "12345WXYZ"u8.ToArray())); + byte[] match = StoredPool(Synthetic.Block(PlaBlockMode.Lz, [0, 0, 21, 4], unpacked: 4)); + byte[] knownSuffix = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "EFGH"u8.ToArray())); + byte[] file = Synthetic.Fdb(first, excluded, match, match, knownSuffix, match); + using var unlimited = PlaDocument.Open(new MemoryStream(file)); + using var limited = PlaDocument.Open(new MemoryStream(file), leaveOpen: false, + options: new PlaReaderOptions { MaxDecodedPoolBytes = 21 }); + + Assert.Equal("WXYZ"u8.ToArray(), Assert.Single(unlimited.FindCompressedPools()[2].ReadSubgroups()).Data); + var pools = limited.FindCompressedPools(); + for (int index = 2; index <= 3; index++) + { + var record = Assert.Single(pools[index].ReadSubgroups()); + Assert.True(record.Partial); + Assert.Empty(record.Data); + } + var recovered = Assert.Single(pools[5].ReadSubgroups()); + Assert.False(recovered.Partial); + Assert.Equal("EFGH"u8.ToArray(), recovered.Data); + } + + [Fact] + public void FailedTargetReadDoesNotReplayPreviouslyDecodedPools() + { + byte[] first = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray())); + byte[] match = StoredPool(Synthetic.Block(PlaBlockMode.Lz, [0, 0, 38, 4], unpacked: 4)); + using var stream = new CountingStream(Synthetic.Fdb(first, UnreadablePool(), match)); + using var doc = PlaDocument.Open(stream); + + var pools = doc.FindCompressedPools(); + stream.Watch(pools.Select(pool => pool.Offset)); + Assert.Throws(() => pools[1].ReadSubgroups()); + + var record = Assert.Single(pools[2].ReadSubgroups()); + Assert.True(record.Partial); + Assert.Empty(record.Data); + Assert.Equal(1, stream.TimesRead(pools[0].Offset)); + } + [Fact] public void ReadingThePoolsInOrderDecodesEachPoolOnce() { @@ -271,11 +310,16 @@ public void EveryLzSubgroupOfSavedFilesDecodes() private static PlaDocument OpenPools(params byte[][] data) { - byte[][] pools = data.Select(content => Synthetic.QuickLzPool( - ((uint)content.Length, Synthetic.QuickLzFrame(content, content.Length, flags: 0x46)))).ToArray(); + byte[][] pools = data.Select(StoredPool).ToArray(); return PlaDocument.Open(new MemoryStream(Synthetic.Fdb(pools))); } + private static byte[] StoredPool(byte[] content) => Synthetic.QuickLzPool( + ((uint)content.Length, Synthetic.QuickLzFrame(content, content.Length, flags: 0x46))); + + private static byte[] UnreadablePool() => Synthetic.QuickLzPool( + (8, Synthetic.QuickLzFrame([1, 0, 0, 0x80, 0xF1, 0xFF], 8, flags: 0x45))); + /// The 13-byte mode-2 pool header: a u32, the 0x47 marker, the packed payload length (including the /// header) and the unpacked size, followed by the token stream. private static byte[] PoolLzPayload(byte[] tokens, int unpacked)