From 3e27e85d393a47168675802362154cc53e26d6fa Mon Sep 17 00:00:00 2001 From: Tom Main Date: Sat, 31 Oct 2026 17:02:06 -0400 Subject: [PATCH 1/2] Stabilize LZW decoding and 0.4 development metadata --- .github/workflows/ci.yml | 1 + CHANGELOG.md | 9 ++ benchmark/eval/README.md | 14 +++ benchmark/eval/lzw_early_change.py | 144 +++++++++++++++++++++++++++++ benchmark/eval/test_bounded_zig.py | 24 ++++- python/README.md | 5 + python/pyproject.toml | 12 +-- python/tests/wheel_smoke.py | 13 ++- python/zpdf/__init__.py | 2 +- src/decompress.zig | 119 +++++++++++++++++++++++- 10 files changed, 331 insertions(+), 12 deletions(-) create mode 100644 benchmark/eval/lzw_early_change.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 141959e..7a1acab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -141,6 +141,7 @@ jobs: python3 benchmark/eval/parser_improvements.py --output benchmark/eval/outputs/parser-020-ci/geometry-and-decoding python3 benchmark/eval/section_hierarchy.py --output benchmark/eval/outputs/parser-020-ci/sections python3 benchmark/eval/section_safety.py --output benchmark/eval/outputs/parser-020-ci/section-safety + python3 benchmark/eval/lzw_early_change.py --output benchmark/eval/outputs/parser-020-ci/lzw-early-change - name: Upload adaptive provenance evidence if: always() diff --git a/CHANGELOG.md b/CHANGELOG.md index 26d36b2..42ecc79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,15 @@ ### Fixed +- LZW decoding honors `EarlyChange` values 0 and 1, defaults to 1, and rejects + invalid explicit values. Regression controls cover code-width transitions, + dictionary reset, predictor/filter composition and decoded-output limits. +- The compiler-budget test records readiness before crossing its stop boundary, + avoiding a race between resource refusal and a subsequent diagnostic print. +- Python distribution and runtime metadata now use `0.4.0.dev0`, matching the + native `0.4.0-dev` build, with canonical repository links and installed-wheel + checks that compare package, native-library and manifest identities. + - Batch and streaming extraction share one bounded table-continuation policy. Partial headers, missing evidence, page gaps, and intervening tables abstain. - Native line grouping distinguishes opposite writing directions, including diff --git a/benchmark/eval/README.md b/benchmark/eval/README.md index cbf2fcc..4c50c49 100644 --- a/benchmark/eval/README.md +++ b/benchmark/eval/README.md @@ -21,6 +21,20 @@ must finish within its timeout and retain the page's body text. Run `node --test integrations/javascript/*.test.mjs` for strict batch/stream consumer validation and actual CLI adapter roundtrips. +LZW controls exercise omitted/default and explicit `EarlyChange`, every +9-to-12-bit width transition, clear-code resets and composed predictors through +native text and both public JSONL formats: + +```sh +python3 benchmark/eval/lzw_early_change.py --output benchmark/eval/outputs/lzw-run +``` + +The harness runs 24 CLI checks on eight generated inputs. Pass `--qpdf qpdf` +when that optional tool is installed to compare complete decoded stream bytes +independently. Zig unit checks also cover exact output caps, invalid parameter +values and allocation-failure cleanup. These controls do not establish general +PDF conformance. + The independent [table region development controls](table_regions/README.md) check separated regions, persistent columns, exact source ownership, and prose retention in both public JSONL formats. Their drawing truth is frozen before diff --git a/benchmark/eval/lzw_early_change.py b/benchmark/eval/lzw_early_change.py new file mode 100644 index 0000000..f1a82ff --- /dev/null +++ b/benchmark/eval/lzw_early_change.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Check LZW width transitions through native text and both public JSONL modes. + +Literal-only streams use fixed width windows rather than a copy of the decoder +dictionary. An optional qpdf comparison checks the complete decoded bytes. +Generated PDFs and raw results stay in a fresh evidence directory. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[2] + + +def literal_lzw(data, early_change, reset_at=None): + windows = (254, 766, 1790) if early_change else (255, 767, 1791) + bits = [] + + def emit(code, width): + bits.extend((code >> shift) & 1 for shift in range(width - 1, -1, -1)) + + def width(index): + return 9 + sum(index >= boundary for boundary in windows) + + emit(256, 9) + count = 0 + for index, byte in enumerate(data): + if index == reset_at: + emit(256, width(count)) + count = 0 + emit(byte, width(count)) + count += 1 + emit(257, width(count)) + bits.extend([0] * (-len(bits) % 8)) + return bytes(sum(bits[index + bit] << (7 - bit) for bit in range(8)) + for index in range(0, len(bits), 8)) + + +def make_pdf(payload, filters, params): + objects = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + f"<< /Length {len(payload)} /Filter {filters} {params} >>\nstream\n".encode() + payload + b"\nendstream", + ] + output, offsets = bytearray(b"%PDF-1.7\n"), [] + for index, obj in enumerate(objects, 1): + offsets.append(len(output)) + output.extend(f"{index} 0 obj\n".encode() + obj + b"\nendobj\n") + xref = len(output) + output.extend(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()) + for offset in offsets: + output.extend(f"{offset:010d} 00000 n \n".encode()) + output.extend(f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()) + return output + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cli", type=Path, default=ROOT / "zig-out/bin/pdf-parser") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--qpdf", help="optional independent decoded-byte oracle executable") + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=False) + report = {"cli_sha256": digest(args.cli), "harness_sha256": digest(Path(__file__)), + "decoder_sha256": digest(ROOT / "src/decompress.zig"), "runs": [], "oracles": []} + for name, early, chain, reset, entry in ( + ("default", 1, False, None, ""), + ("null-default", 1, False, None, "/EarlyChange null"), + ("early-one", 1, False, None, "/EarlyChange 1"), + ("early-zero", 0, False, None, "/EarlyChange 0"), + ("chain-predictor-one", 1, True, None, "/EarlyChange 1"), + ("chain-predictor-zero", 0, True, None, "/EarlyChange 0"), + ("reset-one", 1, False, 2100, "/EarlyChange 1"), + ("reset-zero", 0, False, 2100, "/EarlyChange 0"), + ): + expected = f"LZW {name} source retained" + content = b"%" + b"p" * 3200 + f"\nBT /F1 12 Tf 40 700 Td ({expected}) Tj ET\n".encode() + source = content + if chain: + source = bytes([content[0]] + [(byte - content[index - 1]) % 256 for index, byte in enumerate(content) if index]) + encoded = literal_lzw(source, early, reset) + filters = "/LZWDecode" + params = f"/DecodeParms << {entry} >>" + if chain: + encoded = encoded.hex().encode() + b">" + filters = "[/ASCIIHexDecode /LZWDecode]" + params = f"/DecodeParms [null << {entry} /Predictor 2 /Columns {len(content)} >>]" + path = args.output / f"{name}.pdf" + path.write_bytes(make_pdf(encoded, filters, params)) + if args.qpdf: + command = [args.qpdf, "--show-object=5", "--filtered-stream-data", str(path)] + result = subprocess.run(command, capture_output=True, timeout=15) + (args.output / f"{name}.qpdf.bin").write_bytes(result.stdout) + (args.output / f"{name}.qpdf.stderr").write_bytes(result.stderr) + report["oracles"].append({"command": command, "exit_code": result.returncode, + "passed": result.returncode == 0 and result.stdout == content}) + for fmt in ("native", "artifact-jsonl", "stream-jsonl"): + command = [str(args.cli.resolve()), "extract", "--fast", str(path)] if fmt == "native" else [ + str(args.cli.resolve()), "extract-adaptive", "--input", str(path), "--no-ocr", "--format", fmt] + result = subprocess.run(command, capture_output=True, text=True, timeout=15) + stem = args.output / f"{name}.{fmt}" + stem.with_suffix(stem.suffix + ".stdout").write_text(result.stdout) + stem.with_suffix(stem.suffix + ".stderr").write_text(result.stderr) + failures = [] + if result.returncode: + failures.append(f"exit {result.returncode}") + if fmt == "native": + if result.stdout.strip() != expected: + failures.append("native text mismatch") + else: + try: + records = [json.loads(line) for line in result.stdout.splitlines() if line.strip()] + spans = [r for r in records if r.get("record_type") == "span"] + if not records or records[0].get("record_type") != "document_manifest": + failures.append("missing manifest") + if " ".join(r.get("text", "") for r in spans) != expected or any(r.get("page_index") != 0 for r in spans): + failures.append("span text or page identity mismatch") + if any(r.get("errors") for r in records): + failures.append("artifact errors") + if fmt == "stream-jsonl" and (not records or records[-1].get("record_type") != "document_finished" or records[-1].get("status") != "completed"): + failures.append("missing completed stream") + except json.JSONDecodeError: + failures.append("invalid JSONL") + report["runs"].append({"case": name, "format": fmt, "command": command, + "input_sha256": digest(path), "exit_code": result.returncode, "failures": failures}) + report["passed"] = all(not r["failures"] for r in report["runs"]) and all(r["passed"] for r in report["oracles"]) + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"passed": report["passed"], "runs": len(report["runs"]), + "oracles": len(report["oracles"]), "failures": [r for r in report["runs"] if r["failures"]]})) + return 0 if report["passed"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmark/eval/test_bounded_zig.py b/benchmark/eval/test_bounded_zig.py index 387d5c8..f640874 100644 --- a/benchmark/eval/test_bounded_zig.py +++ b/benchmark/eval/test_bounded_zig.py @@ -77,10 +77,12 @@ def test_limit_stops_owned_parent_and_child_but_not_unrelated_process(self): f"subprocess.Popen([sys.executable,'-c',{sleeper!r}])\n" f"ready=pathlib.Path({str(child_ready)!r})\n" "while not ready.exists(): time.sleep(.01)\n" + # Once the write crosses the limit, the monitor may stop the group + # before the writer can print again. Log readiness before growing it. + "print('child group ready',flush=True)\n" "p=pathlib.Path(os.environ['ZIG_GLOBAL_CACHE_DIR'])/'large'\n" "with p.open('wb') as f:\n" " f.write(b'x'*(2*1024*1024)); f.flush(); os.fsync(f.fileno())\n" - "print('allocated over budget',flush=True)\n" "time.sleep(60)\n" ) unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True) @@ -94,11 +96,29 @@ def test_limit_stops_owned_parent_and_child_but_not_unrelated_process(self): self.assertEqual(child_stopped.read_text(), "terminated") self.assertIsNone(unrelated.poll(), "runner killed an unrelated process") self.assertTrue((self.cache / "global/large").exists()) - self.assertIn(b"allocated over budget", self.log.read_bytes()) + self.assertIn(b"child group ready", self.log.read_bytes()) finally: unrelated.terminate() unrelated.wait(timeout=5) + def test_budget_stop_does_not_require_output_after_allocation(self): + # Hold the writer after allocation so the monitor must stop it without + # relying on a later log line or successful command exit. + result = self.run_child( + "import os,pathlib,time\n" + "p=pathlib.Path(os.environ['ZIG_GLOBAL_CACHE_DIR'])/'large'\n" + "with p.open('wb') as f:\n" + " f.write(b'x'*(2*1024*1024)); f.flush(); os.fsync(f.fileno())\n" + "time.sleep(60)\n" + "print('must not reach this line',flush=True)\n" + ) + receipt = self.read_receipt() + self.assertEqual(result, 124) + self.assertEqual(receipt["status"], "allocation_budget_exceeded") + self.assertNotEqual(receipt["command_exit_code"], 0) + self.assertGreater(receipt["observed_budget_overshoot_bytes"], 0) + self.assertEqual(self.log.read_bytes(), b"") + def test_preexisting_cache_over_budget_never_starts_command(self): self.cache.mkdir() cached = self.cache / "preexisting" diff --git a/python/README.md b/python/README.md index 8582698..899a786 100644 --- a/python/README.md +++ b/python/README.md @@ -4,6 +4,11 @@ Python bindings for the Zig pdf-parser library. The package is named `pdf-parser`, while the import path remains `zpdf` for compatibility with the inherited API. +The current development package is `0.4.0.dev0`, the Python packaging spelling +of the native parser's `0.4.0-dev` build. Adaptive output uses schema `0.20.0`; +its version is independent of the package version. This is a capable pre-1.0 +parser; a development build is not a tagged release. + ## Install Published wheels are platform-specific. From a source checkout, build a wheel diff --git a/python/pyproject.toml b/python/pyproject.toml index 95e9c62..74c585d 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "pdf-parser" -version = "0.1.0" -description = "High-performance PDF text extraction powered by Zig" +version = "0.4.0.dev0" +description = "PDF text and artifact extraction powered by Zig" readme = "README.md" license = { text = "MIT" } requires-python = ">=3.8" @@ -13,7 +13,7 @@ dependencies = ["cffi>=1.15"] authors = [{name = "Thomas Main"}] keywords = ["pdf", "text-extraction", "parser", "zig"] classifiers = [ - "Development Status :: 3 - Alpha", + "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Topic :: Text Processing", "Programming Language :: Python :: 3", @@ -26,9 +26,9 @@ classifiers = [ ] [project.urls] -Homepage = "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/thomasmain/pdf-parser" -Repository = "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/thomasmain/pdf-parser" -Issues = "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/thomasmain/pdf-parser/issues" +Homepage = "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/Tom-R-Main/pdf-parser" +Repository = "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/Tom-R-Main/pdf-parser" +Issues = "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/Tom-R-Main/pdf-parser/issues" [project.optional-dependencies] dev = ["pytest>=7.0"] diff --git a/python/tests/wheel_smoke.py b/python/tests/wheel_smoke.py index 05c4c4e..f70cdc6 100644 --- a/python/tests/wheel_smoke.py +++ b/python/tests/wheel_smoke.py @@ -2,8 +2,10 @@ from __future__ import annotations +import json import sys import zipfile +from importlib import metadata from pathlib import Path import zpdf @@ -24,6 +26,13 @@ def main() -> None: assert selected_library.name == expected_library assert "-none-any.whl" not in wheel.name + distribution = metadata.distribution("pdf-parser") + native_version = _ffi.ffi.string(_ffi.lib.pdf_parser_version()).decode("ascii") + package_version = ( + native_version[:-4] + ".dev0" if native_version.endswith("-dev") else native_version + ) + assert distribution.version == zpdf.__version__ == package_version + with zipfile.ZipFile(wheel) as archive: native_members = [ name @@ -41,7 +50,9 @@ def main() -> None: source_id="wheel-smoke", format="artifact-jsonl", ) - assert '"record_type":"document_manifest"' in artifacts.splitlines()[0] + manifest = json.loads(artifacts.splitlines()[0]) + assert manifest["record_type"] == "document_manifest" + assert manifest["parser_version"] == native_version if __name__ == "__main__": diff --git a/python/zpdf/__init__.py b/python/zpdf/__init__.py index f13493f..23068fd 100644 --- a/python/zpdf/__init__.py +++ b/python/zpdf/__init__.py @@ -5,7 +5,7 @@ from ._ffi import ffi, lib from .exceptions import ZpdfError, InvalidPdfError, PageNotFoundError, ExtractionError -__version__ = "0.1.0" +__version__ = "0.4.0.dev0" __all__ = ["Document", "PageInfo", "TextSpan", "extract_adaptive", "ZpdfError", "InvalidPdfError", "PageNotFoundError", "ExtractionError"] diff --git a/src/decompress.zig b/src/decompress.zig index 2104e33..9443af7 100644 --- a/src/decompress.zig +++ b/src/decompress.zig @@ -589,7 +589,23 @@ fn decodeLZWWithLimit( params: ?Object, max_size: usize, ) ![]u8 { - _ = params; // TODO: EarlyChange parameter + // PDF defaults to changing one code early. A null dictionary value is + // equivalent to an absent entry; an explicit value must be integer 0 or 1. + var early_change: u16 = 1; + if (params) |p| { + if (p == .dict) { + if (p.dict.get("EarlyChange")) |value| { + switch (value) { + .null => {}, + .integer => |number| { + if (number != 0 and number != 1) return DecompressError.InvalidFilterParams; + early_change = @intCast(number); + }, + else => return DecompressError.InvalidFilterParams, + } + } + } + } var output: std.ArrayList(u8) = .empty; errdefer output.deinit(allocator); @@ -691,7 +707,7 @@ fn decodeLZWWithLimit( prev_code = code; // Increase code size when needed - if (table.size >= (@as(u16, 1) << code_size) and code_size < 12) { + if (code_size < 12 and table.size >= (@as(u16, 1) << code_size) - early_change) { code_size += 1; } } @@ -944,6 +960,105 @@ test "LZW dictionary entries are released after decoding" { try std.testing.expectEqualStrings("AB", decoded); } +// These streams deliberately use only literal codes. The width windows count +// decoded literals, independently of the decoder's dictionary implementation: +// the first literal adds no entry; subsequent literals add one each. +fn lzwTestWidth(literal_index: usize, early_change: u1) u4 { + const first: usize = if (early_change == 1) 254 else 255; + if (literal_index < first) return 9; + if (literal_index < first + 512) return 10; + if (literal_index < first + 512 + 1024) return 11; + return 12; +} + +fn appendLzwTestCode(allocator: std.mem.Allocator, encoded: *std.ArrayList(u8), bit_count: *usize, code: u16, width: u4) !void { + for (0..width) |index| { + if (bit_count.* % 8 == 0) try encoded.append(allocator, 0); + const code_shift: u4 = @intCast(@as(usize, width) - 1 - index); + const byte_shift: u3 = @intCast(7 - bit_count.* % 8); + encoded.items[encoded.items.len - 1] |= @as(u8, @intCast((code >> code_shift) & 1)) << byte_shift; + bit_count.* += 1; + } +} + +fn lzwLiteralTestStream(allocator: std.mem.Allocator, count: usize, early_change: u1, reset: bool) ![]u8 { + var encoded: std.ArrayList(u8) = .empty; + errdefer encoded.deinit(allocator); + var bits: usize = 0; + try appendLzwTestCode(allocator, &encoded, &bits, 256, 9); + for (0..count) |index| { + try appendLzwTestCode(allocator, &encoded, &bits, @intCast(index % 251), lzwTestWidth(index, early_change)); + } + if (reset) { + try appendLzwTestCode(allocator, &encoded, &bits, 256, lzwTestWidth(count, early_change)); + try appendLzwTestCode(allocator, &encoded, &bits, 'A', 9); + try appendLzwTestCode(allocator, &encoded, &bits, 258, 9); // KwKwK after reset: AAA. + try appendLzwTestCode(allocator, &encoded, &bits, 257, 9); + } else { + try appendLzwTestCode(allocator, &encoded, &bits, 257, lzwTestWidth(count, early_change)); + } + return encoded.toOwnedSlice(allocator); +} + +test "LZW EarlyChange selects every code-width boundary and resets at twelve bits" { + const allocator = std.testing.allocator; + for ([_]u1{ 0, 1 }) |early_change| { + var entries = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = .{ .integer = early_change } }}; + const params: Object = .{ .dict = .{ .entries = &entries } }; + // End codes immediately before/at/after each transition catch off-by-one + // errors. The long stream also exercises sustained twelve-bit codes. + for ([_]usize{ 253, 254, 255, 256, 765, 766, 767, 768, 1789, 1790, 1791, 1792, 3837 }) |count| { + const encoded = try lzwLiteralTestStream(allocator, count, early_change, false); + defer allocator.free(encoded); + const decoded = try decompressStreamWithOptions(allocator, encoded, .{ .name = "LZWDecode" }, params, .{ .max_output_bytes = count }); + defer allocator.free(decoded); + try std.testing.expectEqual(count, decoded.len); + for (decoded, 0..) |byte, index| try std.testing.expectEqual(@as(u8, @intCast(index % 251)), byte); + try std.testing.expectError(error.OutputTooLarge, decompressStreamWithOptions(allocator, encoded, .{ .name = "LZWDecode" }, params, .{ .max_output_bytes = count - 1 })); + if (early_change == 1) { + const default_decoded = try decodeLZW(allocator, encoded, null); + defer allocator.free(default_decoded); + try std.testing.expectEqualSlices(u8, decoded, default_decoded); + } + } + const encoded = try lzwLiteralTestStream(allocator, 1800, early_change, true); + defer allocator.free(encoded); + const decoded = try decodeLZW(allocator, encoded, params); + defer allocator.free(decoded); + try std.testing.expectEqual(@as(usize, 1803), decoded.len); + for (decoded[0..1800], 0..) |byte, index| try std.testing.expectEqual(@as(u8, @intCast(index % 251)), byte); + try std.testing.expectEqualStrings("AAA", decoded[1800..]); + } +} + +test "LZW EarlyChange rejects invalid values and treats null as the default" { + const allocator = std.testing.allocator; + const encoded = try lzwLiteralTestStream(allocator, 260, 1, false); + defer allocator.free(encoded); + for ([_]Object{ .{ .integer = -1 }, .{ .integer = 2 }, .{ .real = 1 }, .{ .boolean = true }, .{ .name = "1" } }) |value| { + var entries = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = value }}; + try std.testing.expectError(error.InvalidFilterParams, decodeLZW(allocator, encoded, .{ .dict = .{ .entries = &entries } })); + } + var entries = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = .null }}; + const decoded = try decodeLZW(allocator, encoded, .{ .dict = .{ .entries = &entries } }); + defer allocator.free(decoded); + try std.testing.expectEqual(@as(usize, 260), decoded.len); +} + +fn lzwEarlyChangeAllocationProbe(allocator: std.mem.Allocator, encoded: []const u8, early_change: u1) !void { + var entries = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = .{ .integer = early_change } }}; + const decoded = try decodeLZW(allocator, encoded, .{ .dict = .{ .entries = &entries } }); + defer allocator.free(decoded); +} + +test "LZW EarlyChange releases transition output and dictionary on allocation failure" { + for ([_]u1{ 0, 1 }) |early_change| { + const encoded = try lzwLiteralTestStream(std.testing.allocator, 260, early_change, false); + defer std.testing.allocator.free(encoded); + try std.testing.checkAllAllocationFailures(std.testing.allocator, lzwEarlyChangeAllocationProbe, .{ encoded, early_change }); + } +} + fn lzwAllocationProbe(allocator: std.mem.Allocator) !void { const encoded = [_]u8{ 128, 16, 72, 80, 16 }; const decoded = try decodeLZW(allocator, &encoded, null); From c0147dc2a083e0f2281b833fdd9ee0b2aa747ed2 Mon Sep 17 00:00:00 2001 From: Tom Main Date: Sat, 31 Oct 2026 17:45:25 -0400 Subject: [PATCH 2/2] Resolve indirect LZW decode parameters before caching streams --- CHANGELOG.md | 3 + benchmark/eval/README.md | 4 +- benchmark/eval/lzw_early_change.py | 60 +++++++++--- docs/output-schema.md | 7 ++ src/pagetree.zig | 149 ++++++++++++++++++++++++++++- 5 files changed, 204 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42ecc79..323b6c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,9 @@ - LZW decoding honors `EarlyChange` values 0 and 1, defaults to 1, and rejects invalid explicit values. Regression controls cover code-width transitions, dictionary reset, predictor/filter composition and decoded-output limits. +- LZW parameters resolve indirect dictionaries, array entries and `EarlyChange` + values at the document boundary, including Form and font streams. Bounded + resolution rejects cycles and preserves referenced object-stream byte limits. - The compiler-budget test records readiness before crossing its stop boundary, avoiding a race between resource refusal and a subsequent diagnostic print. - Python distribution and runtime metadata now use `0.4.0.dev0`, matching the diff --git a/benchmark/eval/README.md b/benchmark/eval/README.md index 4c50c49..0f90b46 100644 --- a/benchmark/eval/README.md +++ b/benchmark/eval/README.md @@ -29,7 +29,9 @@ native text and both public JSONL formats: python3 benchmark/eval/lzw_early_change.py --output benchmark/eval/outputs/lzw-run ``` -The harness runs 24 CLI checks on eight generated inputs. Pass `--qpdf qpdf` +The harness runs 45 CLI checks on fifteen generated inputs, including indirect +parameter values, dictionaries and filter-aligned arrays, plus a Form XObject. +Pass `--qpdf qpdf` when that optional tool is installed to compare complete decoded stream bytes independently. Zig unit checks also cover exact output caps, invalid parameter values and allocation-failure cleanup. These controls do not establish general diff --git a/benchmark/eval/lzw_early_change.py b/benchmark/eval/lzw_early_change.py index f1a82ff..fb5cc65 100644 --- a/benchmark/eval/lzw_early_change.py +++ b/benchmark/eval/lzw_early_change.py @@ -40,14 +40,22 @@ def width(index): for index in range(0, len(bits), 8)) -def make_pdf(payload, filters, params): +def make_pdf(payload, filters, params, extra_objects=(), form=False): + resources = b"/Font << /F1 4 0 R >>" + (b" /XObject << /Fm1 6 0 R >>" if form else b"") + stream = f"<< /Length {len(payload)} /Filter {filters} {params}".encode() + if form: + stream += b" /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >>" + stream += b" >>\nstream\n" + payload + b"\nendstream" objects = [ b"<< /Type /Catalog /Pages 2 0 R >>", b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", - b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << " + resources + b" >> /Contents 5 0 R >>", b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", - f"<< /Length {len(payload)} /Filter {filters} {params} >>\nstream\n".encode() + payload + b"\nendstream", + b"<< /Length 8 >>\nstream\n/Fm1 Do\n\nendstream" if form else stream, ] + if form: + objects.append(stream) + objects.extend(extra_objects) output, offsets = bytearray(b"%PDF-1.7\n"), [] for index, obj in enumerate(objects, 1): offsets.append(len(output)) @@ -72,16 +80,24 @@ def main(): args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=False) report = {"cli_sha256": digest(args.cli), "harness_sha256": digest(Path(__file__)), - "decoder_sha256": digest(ROOT / "src/decompress.zig"), "runs": [], "oracles": []} - for name, early, chain, reset, entry in ( - ("default", 1, False, None, ""), - ("null-default", 1, False, None, "/EarlyChange null"), - ("early-one", 1, False, None, "/EarlyChange 1"), - ("early-zero", 0, False, None, "/EarlyChange 0"), - ("chain-predictor-one", 1, True, None, "/EarlyChange 1"), - ("chain-predictor-zero", 0, True, None, "/EarlyChange 0"), - ("reset-one", 1, False, 2100, "/EarlyChange 1"), - ("reset-zero", 0, False, 2100, "/EarlyChange 0"), + "decoder_sha256": digest(ROOT / "src/decompress.zig"), + "resolver_sha256": digest(ROOT / "src/pagetree.zig"), "runs": [], "oracles": []} + for name, early, chain, reset, entry, style in ( + ("default", 1, False, None, "", "direct"), + ("null-default", 1, False, None, "/EarlyChange null", "direct"), + ("early-one", 1, False, None, "/EarlyChange 1", "direct"), + ("early-zero", 0, False, None, "/EarlyChange 0", "direct"), + ("chain-predictor-one", 1, True, None, "/EarlyChange 1", "direct"), + ("chain-predictor-zero", 0, True, None, "/EarlyChange 0", "direct"), + ("reset-one", 1, False, 2100, "/EarlyChange 1", "direct"), + ("reset-zero", 0, False, 2100, "/EarlyChange 0", "direct"), + ("indirect-one", 1, False, None, "/EarlyChange 6 0 R", "entry"), + ("indirect-zero", 0, False, None, "/EarlyChange 6 0 R", "entry"), + ("indirect-null", 1, False, None, "/EarlyChange 6 0 R", "null-entry"), + ("indirect-nested-zero", 0, False, None, "", "nested"), + ("indirect-params-zero", 0, False, None, "", "params"), + ("indirect-array-zero", 0, True, None, "", "array"), + ("indirect-form-zero", 0, False, None, "/EarlyChange 7 0 R", "form"), ): expected = f"LZW {name} source retained" content = b"%" + b"p" * 3200 + f"\nBT /F1 12 Tf 40 700 Td ({expected}) Tj ET\n".encode() @@ -95,10 +111,24 @@ def main(): encoded = encoded.hex().encode() + b">" filters = "[/ASCIIHexDecode /LZWDecode]" params = f"/DecodeParms [null << {entry} /Predictor 2 /Columns {len(content)} >>]" + extra = [] + if style in ("entry", "form"): + extra = [str(early).encode()] + elif style == "null-entry": + extra = [b"null"] + elif style == "nested": + params = "/DecodeParms 6 0 R" + extra = [b"<< /EarlyChange 7 0 R >>", b"0"] + elif style == "params": + params = "/DecodeParms 6 0 R" + extra = [b"<< /EarlyChange 0 >>"] + elif style == "array": + params = "/DecodeParms 6 0 R" + extra = [b"[null 7 0 R]", f"<< /EarlyChange 8 0 R /Predictor 2 /Columns {len(content)} >>".encode(), b"0"] path = args.output / f"{name}.pdf" - path.write_bytes(make_pdf(encoded, filters, params)) + path.write_bytes(make_pdf(encoded, filters, params, extra, style == "form")) if args.qpdf: - command = [args.qpdf, "--show-object=5", "--filtered-stream-data", str(path)] + command = [args.qpdf, "--show-object=6" if style == "form" else "--show-object=5", "--filtered-stream-data", str(path)] result = subprocess.run(command, capture_output=True, timeout=15) (args.output / f"{name}.qpdf.bin").write_bytes(result.stdout) (args.output / f"{name}.qpdf.stderr").write_bytes(result.stderr) diff --git a/docs/output-schema.md b/docs/output-schema.md index 7344620..5907fa5 100644 --- a/docs/output-schema.md +++ b/docs/output-schema.md @@ -731,6 +731,13 @@ allocator overhead, input mappings, or subprocess RSS. Intentional bounded Type3 scratch-buffer exhaustion remains best-effort; an explicit stream cap refusal propagates. +LZW decoding defaults to `EarlyChange=1` and accepts explicit integer 0 or 1. +For document streams, indirect decode-parameter dictionaries, aligned array +entries and `EarlyChange` values resolve before decoding. Reference chains and +nested object-stream parameter resolution have a 16-level bound; cyclic or +excessively deep resolution fails. Referenced object streams retain the same +decoded-byte cap. These controls change decoding behavior, not record fields. + ### `debug_asset` Reference to visual review and coordinate artifacts. Debug assets are always diff --git a/src/pagetree.zig b/src/pagetree.zig index 88143c9..56a8581 100644 --- a/src/pagetree.zig +++ b/src/pagetree.zig @@ -50,6 +50,8 @@ pub const BuildOptions = struct { diagnostic_allocator: ?std.mem.Allocator = null, recover: bool = true, decompress_options: decompress.Options = .{}, + /// Propagated through object-stream resolution to bound parameter cycles. + decode_param_depth: u8 = 0, }; /// Resolve object reference using XRef table @@ -143,8 +145,9 @@ pub fn resolveRefWithOptions( else indirect.obj; - try resolved_cache.put(ref.num, object); - return object; + const resolved = try resolveStreamDecodeParameters(allocator, data, xref, object, resolved_cache, options); + try resolved_cache.put(ref.num, resolved); + return resolved; }, .compressed => { // Object is inside an object stream @@ -153,6 +156,72 @@ pub fn resolveRefWithOptions( } } +fn isLzwFilter(filter: Object) bool { + return filter == .name and (std.mem.eql(u8, filter.name, "LZWDecode") or std.mem.eql(u8, filter.name, "LZW")); +} + +fn resolveDecodeParameter( + allocator: std.mem.Allocator, + data: []const u8, + xref: *const XRefTable, + cache: *std.AutoHashMap(u32, Object), + object: Object, + options: BuildOptions, + depth: *u8, +) anyerror!Object { + var value = object; + while (value == .reference) { + if (depth.* >= 16) return error.InvalidFilterParams; + depth.* += 1; + var nested = options; + nested.decode_param_depth = depth.*; + value = try resolveRefWithOptions(allocator, data, xref, value.reference, cache, nested); + } + return value; +} + +fn resolveEarlyChange(allocator: std.mem.Allocator, data: []const u8, xref: *const XRefTable, cache: *std.AutoHashMap(u32, Object), params: Object, options: BuildOptions, depth: *u8) anyerror!void { + if (params != .dict) return; + for (params.dict.entries) |*entry| { + if (std.mem.eql(u8, entry.key, "EarlyChange")) { + entry.value = try resolveDecodeParameter(allocator, data, xref, cache, entry.value, options, depth); + return; + } + } +} + +// Resolve LZW policy at the document boundary, where xref/security/cache state +// exists. Parsed metadata belongs to the parse allocator; normalized values +// retain that lifetime. Never cache a stream before normalization succeeds. +fn resolveStreamDecodeParameters(allocator: std.mem.Allocator, data: []const u8, xref: *const XRefTable, object: Object, cache: *std.AutoHashMap(u32, Object), options: BuildOptions) anyerror!Object { + if (object != .stream) return object; + const filter = object.stream.dict.get("Filter") orelse return object; + var has_lzw = isLzwFilter(filter); + if (filter == .array) { + for (filter.array[0..@min(filter.array.len, 16)]) |item| has_lzw = has_lzw or isLzwFilter(item); + } + if (!has_lzw) return object; + for (object.stream.dict.entries) |*entry| { + if (!std.mem.eql(u8, entry.key, "DecodeParms")) continue; + var depth = options.decode_param_depth; + const params = try resolveDecodeParameter(allocator, data, xref, cache, entry.value, options, &depth); + if (params == .array and filter == .array) { + for (filter.array[0..@min(filter.array.len, 16)], 0..) |item, index| { + if (!isLzwFilter(item) or index >= params.array.len) continue; + var item_depth = depth; + const value = try resolveDecodeParameter(allocator, data, xref, cache, params.array[index], options, &item_depth); + try resolveEarlyChange(allocator, data, xref, cache, value, options, &item_depth); + params.array[index] = value; + } + } else { + try resolveEarlyChange(allocator, data, xref, cache, params, options, &depth); + } + entry.value = params; + return object; + } + return object; +} + fn resolveCompressedObject( allocator: std.mem.Allocator, data: []const u8, @@ -192,13 +261,14 @@ fn resolveCompressedObject( return Object{ .null = {} }; }; - const objstm_obj = if (options.security) |handler| + const decrypted_objstm = if (options.security) |handler| handler.decryptObject(allocator, .{ .num = indirect.num, .gen = indirect.gen }, indirect.obj) catch |err| blk: { if (err == error.OutOfMemory) return err; break :blk Object{ .null = {} }; } else indirect.obj; + const objstm_obj = try resolveStreamDecodeParameters(allocator, data, xref, decrypted_objstm, resolved_cache, options); const stream = switch (objstm_obj) { .stream => |s| s, @@ -722,6 +792,79 @@ fn getStreamData( // TESTS // ============================================================================ +test "LZW decode parameters resolve indirect dictionaries arrays and integers" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var xref = XRefTable.init(std.testing.allocator); + defer xref.deinit(); + var cache = std.AutoHashMap(u32, Object).init(std.testing.allocator); + defer cache.deinit(); + var params_entries = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = .{ .reference = .{ .num = 7, .gen = 0 } } }}; + var params_array = [_]Object{ .null, .{ .reference = .{ .num = 6, .gen = 0 } } }; + try cache.put(6, .{ .dict = .{ .entries = ¶ms_entries } }); + try cache.put(7, .{ .integer = 0 }); + try cache.put(8, .{ .array = ¶ms_array }); + var filters = [_]Object{ .{ .name = "ASCIIHexDecode" }, .{ .name = "LZW" } }; + var entries = [_]Object.Dict.Entry{ + .{ .key = "Filter", .value = .{ .array = &filters } }, + .{ .key = "DecodeParms", .value = .{ .reference = .{ .num = 8, .gen = 0 } } }, + }; + const stream: Object = .{ .stream = .{ .dict = .{ .entries = &entries }, .data = "" } }; + const resolved = try resolveStreamDecodeParameters(arena.allocator(), "", &xref, stream, &cache, .{}); + const params = resolved.stream.dict.getArray("DecodeParms").?; + try std.testing.expect(params[0] == .null); + try std.testing.expectEqual(@as(?i64, 0), params[1].dict.getInt("EarlyChange")); +} + +test "LZW decode parameter cycles stop before publishing streams" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var xref = XRefTable.init(std.testing.allocator); + defer xref.deinit(); + var cache = std.AutoHashMap(u32, Object).init(std.testing.allocator); + defer cache.deinit(); + try cache.put(6, .{ .reference = .{ .num = 7, .gen = 0 } }); + try cache.put(7, .{ .reference = .{ .num = 6, .gen = 0 } }); + var entries = [_]Object.Dict.Entry{ + .{ .key = "Filter", .value = .{ .name = "LZWDecode" } }, + .{ .key = "DecodeParms", .value = .{ .reference = .{ .num = 6, .gen = 0 } } }, + }; + const stream: Object = .{ .stream = .{ .dict = .{ .entries = &entries }, .data = "" } }; + try std.testing.expectError(error.InvalidFilterParams, resolveStreamDecodeParameters(arena.allocator(), "", &xref, stream, &cache, .{})); + try std.testing.expect(entries[1].value == .reference); + + // The integer needed to decode ObjStm 2 is stored inside that same stream. + // Recursive object-stream resolution must inherit the parameter depth. + const data = "2 0 obj\n<< /Type /ObjStm /N 1 /First 4 /Filter /LZWDecode /DecodeParms << /EarlyChange 3 0 R >> /Length 6 >>\nstream\n3 0 0 \nendstream\nendobj\n"; + try xref.entries.put(2, .{ .offset = 0, .gen_or_index = 0, .entry_type = .in_use }); + try xref.entries.put(3, .{ .offset = 2, .gen_or_index = 0, .entry_type = .compressed }); + try std.testing.expectError(error.InvalidFilterParams, resolveRefWithOptions(arena.allocator(), data, &xref, .{ .num = 3, .gen = 0 }, &cache, .{})); + try std.testing.expect(!cache.contains(2)); + try std.testing.expect(!cache.contains(3)); +} + +test "LZW decode parameter resolution preserves compressed-object byte limits" { + const data = "2 0 obj\n<< /Type /ObjStm /N 1 /First 4 /Length 6 >>\nstream\n3 0 0 \nendstream\nendobj\n"; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var xref = XRefTable.init(std.testing.allocator); + defer xref.deinit(); + try xref.entries.put(2, .{ .offset = 0, .gen_or_index = 0, .entry_type = .in_use }); + try xref.entries.put(3, .{ .offset = 2, .gen_or_index = 0, .entry_type = .compressed }); + var cache = std.AutoHashMap(u32, Object).init(std.testing.allocator); + defer cache.deinit(); + var params = [_]Object.Dict.Entry{.{ .key = "EarlyChange", .value = .{ .reference = .{ .num = 3, .gen = 0 } } }}; + var entries = [_]Object.Dict.Entry{ + .{ .key = "Filter", .value = .{ .name = "LZWDecode" } }, + .{ .key = "DecodeParms", .value = .{ .dict = .{ .entries = ¶ms } } }, + }; + const stream: Object = .{ .stream = .{ .dict = .{ .entries = &entries }, .data = "" } }; + try std.testing.expectError(error.OutputTooLarge, resolveStreamDecodeParameters(arena.allocator(), data, &xref, stream, &cache, .{ .decompress_options = .{ .max_output_bytes = 5 } })); + try std.testing.expect(params[0].value == .reference); + const resolved = try resolveStreamDecodeParameters(arena.allocator(), data, &xref, stream, &cache, .{ .decompress_options = .{ .max_output_bytes = 6 } }); + try std.testing.expectEqual(@as(?i64, 0), resolved.stream.dict.getDict("DecodeParms").?.getInt("EarlyChange")); +} + test "content stream recovery preserves resource refusals and malformed fallback" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit();