#!/usr/bin/env python3 """Bounded, synthetic gzip read-coverage observations; no external input.""" import argparse from datetime import datetime, timezone import gzip import hashlib import io import json from pathlib import Path import platform import sys import zlib METHODS = ("prefix-close", "exact-length-close", "read-to-eof", "gzip-decompress", "zlib-one-member", "zlib-object-flush") SOURCES = [ "https://www.rfc-editor.org/rfc/rfc1952.html", "https://docs.python.org/3.12/library/gzip.html", "https://docs.python.org/3.12/library/zlib.html", "https://raw.githubusercontent.com/python/cpython/v3.12.3/Lib/gzip.py", "https://www.zlib.net/manual.html", ] def digest(raw): return hashlib.sha256(raw).hexdigest() def require(condition, message): if not condition: raise RuntimeError(message) def payloads(): return (hashlib.shake_256(b"hesela-gzip-A-v1").digest(65536), hashlib.shake_256(b"hesela-gzip-B-v1").digest(32768)) def member(raw): target = io.BytesIO() with gzip.GzipFile(filename="", mode="wb", fileobj=target, compresslevel=6, mtime=0) as stream: stream.write(raw) return target.getvalue() def fixtures(): a, b = payloads() first, second = member(a), member(b) clean = first + second bad_first = bytearray(first) bad_first[-8] ^= 1 bad_second = bytearray(clean) bad_second[-8] ^= 1 return [ ("single-clean", first, a, first, None), ("single-crc-bit", bytes(bad_first), a, first, len(first) - 8), ("single-trailer-truncated", first[:-1], a, first, len(first) - 1), ("two-clean", clean, a + b, clean, None), ("second-crc-bit", bytes(bad_second), a + b, clean, len(clean) - 8), ("second-member-removed", first, a + b, clean, len(first)), ("trailing-garbage", clean + b"NOT-GZIP", a + b, clean, len(clean)), ] def describe_error(error): return {"type": type(error).__name__, "message": str(error)} def read_case(raw, expected, method): output = b"" read_error = close_error = None eof_before = eof_after = unused = unconsumed = None if method in ("prefix-close", "exact-length-close", "read-to-eof"): stream = gzip.GzipFile(fileobj=io.BytesIO(raw), mode="rb") try: if method == "prefix-close": output = stream.read(16) elif method == "exact-length-close": output = stream.read(len(expected)) else: chunks = [] try: while True: chunk = stream.read(4096) if not chunk: break chunks.append(chunk) finally: output = b"".join(chunks) except (OSError, EOFError, zlib.error) as error: read_error = describe_error(error) finally: try: stream.close() except (OSError, EOFError, zlib.error) as error: close_error = describe_error(error) else: try: if method == "gzip-decompress": output = gzip.decompress(raw) elif method == "zlib-one-member": output = zlib.decompress(raw, wbits=31) elif method == "zlib-object-flush": decoder = zlib.decompressobj(wbits=31) output = decoder.decompress(raw) eof_before = decoder.eof output += decoder.flush() eof_after = decoder.eof unused = len(decoder.unused_data) unconsumed = len(decoder.unconsumed_tail) else: raise ValueError(method) except (OSError, EOFError, zlib.error) as error: read_error = describe_error(error) return { "method": method, "apiCompleted": read_error is None and close_error is None, "readError": read_error, "closeError": close_error, "returnedBytes": len(output), "returnedSha256": digest(output), "matchesExpectedPayload": output == expected, "matchesExpectedPrefix": output == expected[:len(output)], "streamEofBeforeFlush": eof_before, "streamEofAfterFlush": eof_after, "unusedInputBytes": unused, "unconsumedTailBytes": unconsumed, } def observe(): cases = [] for name, raw, expected, trusted, offset in fixtures(): cases.append({ "id": name, "inputBytes": len(raw), "inputSha256": digest(raw), "trustedObjectBytes": len(trusted), "trustedObjectSha256": digest(trusted), "matchesTrustedObject": raw == trusted, "expectedBytes": len(expected), "expectedSha256": digest(expected), "mutationOffset": offset, "observations": [read_case(raw, expected, method) for method in METHODS], }) return { "schemaVersion": 1, "kind": "designed-software-observation", "generatedAt": datetime.now(timezone.utc).isoformat(), "scriptSha256": digest(Path(__file__).read_bytes()), "environment": { "python": platform.python_version(), "implementation": platform.python_implementation(), "platform": platform.platform(), "zlibBuild": zlib.ZLIB_VERSION, "zlibRuntime": zlib.ZLIB_RUNTIME_VERSION, "gzipModuleSha256": digest(Path(gzip.__file__).read_bytes()), "zlibModuleSha256": digest(Path(zlib.__file__).read_bytes()) if hasattr(zlib, "__file__") else None, "zlibModuleKind": "extension" if hasattr(zlib, "__file__") else "built-in", "pythonExecutableSha256": digest(Path(sys.executable).read_bytes()), }, "design": { "payloadGenerator": "SHAKE-256 of ASCII hesela-gzip-A-v1 / hesela-gzip-B-v1", "payloadBytes": [65536, 32768], "compressionLevel": 6, "mtime": 0, "prefixReadBytes": 16, "eofReadChunkBytes": 4096, "expectedPayload": "A for single-*; A+B for all other fixtures, fixed before encoding", "trailerMutation": "XOR 1 at first CRC32 byte; compressed payload unchanged", "truncation": "Remove final ISIZE byte, retaining complete DEFLATE payload", "returnedBytesMeaning": "Only bytes returned to the caller, not internally decoded bytes", "scope": "Seven generated fixtures and six API operations each; in-memory, no disk crash or field incidence", }, "sources": SOURCES, "cases": cases, } def validate(result): require(result["schemaVersion"] == 1, "schema") require(result["kind"] == "designed-software-observation", "kind") require(len(result["cases"]) == 7, "case count") expected_cases = fixtures() for case, (name, raw, expected, trusted, offset) in zip(result["cases"], expected_cases): require(case["id"] == name, "case identity") for key, value in { "inputBytes": len(raw), "inputSha256": digest(raw), "trustedObjectBytes": len(trusted), "trustedObjectSha256": digest(trusted), "expectedBytes": len(expected), "expectedSha256": digest(expected), "mutationOffset": offset, "matchesTrustedObject": raw == trusted, }.items(): require(type(case[key]) is type(value) and case[key] == value, key) require(len(case["observations"]) == len(METHODS), "method count") for row, method in zip(case["observations"], METHODS): require(json.dumps(row, sort_keys=True) == json.dumps(read_case(raw, expected, method), sort_keys=True), "observation drift: " + name + "/" + method) require(result["sources"] == SOURCES, "sources") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) args = parser.parse_args() require(not args.output.exists(), "Refusing existing output") result = observe() validate(result) with args.output.open("x", encoding="utf-8") as handle: json.dump(result, handle, indent=2) handle.write("\n") print("Recorded 42 operations; runtime observations rechecked before output.") if __name__ == "__main__": main()