#!/usr/bin/env python3 """Bounded synthetic CLI probe: decoder window limits are not output quotas.""" import argparse from datetime import datetime, timezone import hashlib import json import os from pathlib import Path import platform import shutil import subprocess MIB = 1024 * 1024 PAYLOAD = b"A" * (2 * MIB) CASES = { "small-window": (10, 1, 1, True), "large-window-rejected": (21, 1, 1, False), "large-window-accepted": (21, 1, 4, True), "two-small-window-frames": (10, 2, 1, True), } def require(condition, message): if not condition: raise ValueError(message) def digest(data): return hashlib.sha256(data).hexdigest() def run(args, payload): require(len(payload) <= 4 * MIB, "Synthetic input limit exceeded") env = {k: v for k, v in os.environ.items() if not k.startswith("ZSTD")} env["LC_ALL"] = "C" return subprocess.run(["zstd", *args], input=payload, capture_output=True, timeout=15, check=False, env=env) def fixture_header(frame, window_log): require(window_log in (10, 21), "Unsupported fixture window") # Check only our two generated headers, not arbitrary Zstandard input. # Descriptor 0x04: checksum present, no size, dictionary ID or single segment. expected = bytes.fromhex("28b52ffd04") + bytes([(window_log - 10) << 3]) require(frame.startswith(expected), "Unexpected synthetic frame header") def compress(window_log): args = ["-q", "-c", "-3", "--single-thread", "--check", "--no-content-size", "--zstd=wlog=" + str(window_log)] result = run(args, PAYLOAD) require(result.returncode == 0, result.stderr.decode("utf-8", "replace")) fixture_header(result.stdout, window_log) return result.stdout def validate(rows): require(len(rows) == len(CASES), "Unexpected case count") require({row["id"] for row in rows} == set(CASES), "Missing or duplicate cases") by_id = {row["id"]: row for row in rows} for row in rows: wlog, frames, limit, success = CASES[row["id"]] for key, value in { "windowLog": wlog, "windowBytes": 1 << wlog, "frameCount": frames, "decoderLimitBytes": limit * MIB, "expectedBytes": len(PAYLOAD) * frames, }.items(): require(type(row[key]) is int and row[key] == value, "Invalid " + key) require(type(row["exitCode"]) is int, "Invalid exit code") require(type(row["outputBytes"]) is int and 0 <= row["outputBytes"] <= 4 * MIB, "Invalid output size") require(type(row["compressedBytes"]) is int and row["compressedBytes"] > 0, "Invalid compressed size") require(row["frameContentSizePresent"] is False, "Unexpected size field") require(row["decodeArgs"] == ["-q", "-d", "-c", "--check", "-M" + str(limit) + "MiB"], "Changed decoder command") require(row["exitCode"] == (0 if success else 1), "Changed decoder outcome") if not success: require("Window size larger than maximum" in row["stderr"] and "2097152 > 1048576" in row["stderr"], "Failure was not the expected window-limit rejection") require(type(row["bytesMatch"]) is bool and row["bytesMatch"] == success, "Changed byte equality") expected_hash = digest(PAYLOAD * frames) require(row["expectedSha256"] == expected_hash, "Changed expected payload") require(row["bytesMatch"] == ( row["outputBytes"] == row["expectedBytes"] and row["outputSha256"] == expected_hash), "Inconsistent byte oracle") require(row["accepted"] is success, "Invalid acceptance") for key in ("compressedSha256", "outputSha256"): value = row[key] require(isinstance(value, str) and len(value) == 64 and all(c in "0123456789abcdef" for c in value), "Invalid hash") a, b = (by_id[key] for key in ("large-window-rejected", "large-window-accepted")) require(a["compressedSha256"] == b["compressedSha256"] and a["compressedBytes"] == b["compressedBytes"], "Limit comparison must use identical compressed input") small, pair = by_id["small-window"], by_id["two-small-window-frames"] require(pair["compressedBytes"] == 2 * small["compressedBytes"], "Concatenated input size mismatch") require(pair["outputBytes"] == 2 * small["outputBytes"], "Concatenated output size mismatch") def experiment(): require(shutil.which("zstd") is not None, "zstd CLI is required") frames = {w: compress(w) for w in (10, 21)} rows = [] for case_id, (wlog, count, limit, _) in CASES.items(): frame = frames[wlog] * count expected = PAYLOAD * count args = ["-q", "-d", "-c", "--check", "-M" + str(limit) + "MiB"] result = run(args, frame) match = result.stdout == expected rows.append({ "id": case_id, "windowLog": wlog, "windowBytes": 1 << wlog, "frameCount": count, "frameContentSizePresent": False, "decoderLimitBytes": limit * MIB, "decodeArgs": args, "compressedBytes": len(frame), "compressedSha256": digest(frame), "exitCode": result.returncode, "outputBytes": len(result.stdout), "outputSha256": digest(result.stdout), "expectedBytes": len(expected), "expectedSha256": digest(expected), "bytesMatch": match, "accepted": result.returncode == 0 and match, "stderr": result.stderr.decode("utf-8", "replace").strip(), }) validate(rows) return { "schemaVersion": 1, "generatedAt": datetime.now(timezone.utc).isoformat(), "sourceSha256": digest(Path(__file__).read_bytes()), "environment": {"zstd": run(["--version"], b"").stdout.decode().strip(), "python": platform.python_version(), "system": platform.system(), "machine": platform.machine()}, "method": { "type": "synthetic-decompression-resource-demonstration", "payload": "ASCII A repeated 2097152 times", "payloadBytes": len(PAYLOAD), "compressionArgs": ["-q", "-c", "-3", "--single-thread", "--check", "--no-content-size", "--zstd=wlog=10|21"], "maxExpectedDecodedBytes": 4 * MIB, "commandTimeoutSeconds": 15, "scope": "Four fixed cases on one CLI build; no RSS, CPU, throughput or hostile-input safety measurement.", "safety": "Only internally generated bounded inputs. capture_output is not an output limiter. Do not adapt this harness to accept untrusted archives.", }, "observations": rows, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) args = parser.parse_args() result = json.dumps(experiment(), indent=2) + "\n" if args.output: args.output.write_text(result, encoding="utf-8") else: print(result, end="") if __name__ == "__main__": main()