#!/usr/bin/env python3 """CC0: bounded native LZ4 dictionary experiment, not a production decoder.""" import argparse import ctypes as C import datetime import importlib.util import json import pathlib import platform import sys BASE = pathlib.Path(__file__).parent SPEC = importlib.util.spec_from_file_location("frame_contract", BASE / "lz4-frame-contract.py") FRAME = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(FRAME) lib, checked, sha = FRAME.lib, FRAME.checked, FRAME.sha for name, args, result in [ ("LZ4F_createCompressionContext", [C.POINTER(C.c_void_p), C.c_uint], C.c_size_t), ("LZ4F_freeCompressionContext", [C.c_void_p], C.c_size_t), ("LZ4F_createCDict", [C.c_void_p, C.c_size_t], C.c_void_p), ("LZ4F_freeCDict", [C.c_void_p], None), ("LZ4F_compressFrame_usingCDict", [C.c_void_p, C.c_void_p, C.c_size_t, C.c_void_p, C.c_size_t, C.c_void_p, C.POINTER(FRAME.Preferences)], C.c_size_t), ("LZ4F_getFrameInfo", [C.c_void_p, C.POINTER(FRAME.FrameInfo), C.c_void_p, C.POINTER(C.c_size_t)], C.c_size_t), ("LZ4F_decompress_usingDict", [C.c_void_p, C.c_void_p, C.POINTER(C.c_size_t), C.c_void_p, C.POINTER(C.c_size_t), C.c_void_p, C.c_size_t, C.c_void_p], C.c_size_t), ]: fn = getattr(lib, name) fn.argtypes, fn.restype = args, result DICTIONARY = b"".join(FRAME.hashlib.sha256(i.to_bytes(4, "little")).digest() for i in range(1024)) WRONG = bytes(value ^ 255 for value in DICTIONARY) PAYLOAD = DICTIONARY[8192:16384] EXPECTED_ID = 424242 def require(condition, message): if not condition: raise ValueError(message) def compress(dict_id, content_checksum): prefs = FRAME.Preferences() prefs.frameInfo.blockSizeID = 4 prefs.frameInfo.blockMode = 1 prefs.frameInfo.blockChecksumFlag = 1 prefs.frameInfo.contentChecksumFlag = int(content_checksum) prefs.frameInfo.dictID = dict_id context = C.c_void_p() checked(lib.LZ4F_createCompressionContext(C.byref(context), 100)) dictionary = lib.LZ4F_createCDict(DICTIONARY, len(DICTIONARY)) if not dictionary: checked(lib.LZ4F_freeCompressionContext(context)) raise MemoryError("LZ4F_createCDict failed") try: capacity = checked(lib.LZ4F_compressFrameBound(len(PAYLOAD), C.byref(prefs))) output = C.create_string_buffer(capacity) size = checked(lib.LZ4F_compressFrame_usingCDict( context, output, capacity, PAYLOAD, len(PAYLOAD), dictionary, C.byref(prefs))) return output.raw[:size] finally: lib.LZ4F_freeCDict(dictionary) checked(lib.LZ4F_freeCompressionContext(context)) def decode(data, dictionary, output_capacity=1024): require(isinstance(output_capacity, int) and output_capacity > 0, "output capacity must be a positive integer") context = C.c_void_p() checked(lib.LZ4F_createDecompressionContext(C.byref(context), 100)) # Keep the original dictionary allocation alive for the full frame. dictionary_buffer = C.create_string_buffer(dictionary) if dictionary is not None else None source = C.create_string_buffer(data) info = FRAME.FrameInfo() header_size = C.c_size_t(len(data)) chunks, error, hint, offset = [], None, 1, 0 try: checked(lib.LZ4F_getFrameInfo(context, C.byref(info), source, C.byref(header_size))) offset = header_size.value for _ in range(20000): incoming = C.create_string_buffer(data[offset:]) incoming_size = C.c_size_t(len(data) - offset) outgoing = C.create_string_buffer(output_capacity) outgoing_size = C.c_size_t(output_capacity) hint = lib.LZ4F_decompress_usingDict(context, outgoing, C.byref(outgoing_size), incoming, C.byref(incoming_size), dictionary_buffer, len(dictionary) if dictionary is not None else 0, None) if lib.LZ4F_isError(hint): error = lib.LZ4F_getErrorName(hint).decode() break offset += incoming_size.value chunks.append(outgoing.raw[:outgoing_size.value]) if hint == 0 or (incoming_size.value == 0 and outgoing_size.value == 0): break else: raise RuntimeError("bounded decoder call budget exhausted") finally: checked(lib.LZ4F_freeDecompressionContext(context)) output = b"".join(chunks) complete = error is None and hint == 0 exact = output == PAYLOAD digest_matches = dictionary is not None and sha(dictionary) == sha(DICTIONARY) id_matches = info.dictID == EXPECTED_ID transport_complete = complete and offset == len(data) return { "headerDictID": info.dictID, "headerBytes": header_size.value, "bodySha256": sha(data[header_size.value:]), "error": error, "frameComplete": complete, "inputFullyConsumed": offset == len(data), "successfulCallOutputBytes": len(output), "outputSha256": sha(output), "exactPayload": exact, "dictionarySha256": sha(dictionary) if dictionary is not None else None, "dictionaryDigestMatches": digest_matches, "idMatchesExpected": id_matches, "codecComplete": transport_complete, "namedIdPolicyAccepted": transport_complete and id_matches, "verifiedNamedRestore": transport_complete and id_matches and digest_matches and exact, "verifiedOutOfBandRestore": transport_complete and digest_matches and exact, } def validate(rows): expected = {f"{checksum}/{label}/{dictionary}" for checksum in ("block-only", "block-and-content") for label in ("expected-id", "different-id", "omitted-id") for dictionary in ("correct", "wrong", "missing")} require(len(rows) == len(expected), "expected exactly 18 observations") require({row["id"] for row in rows} == expected, "missing or duplicate case identities") for row in rows: require(row["id"] == f'{row["policy"]}/{row["idPolicy"]}/{row["dictionary"]}', "inconsistent case identity") require(row["codecComplete"] == (row["frameComplete"] and row["inputFullyConsumed"] and row["error"] is None), "inconsistent completion fields") correct = row["dictionary"] == "correct" wrong = row["dictionary"] == "wrong" expected_id = row["idPolicy"] == "expected-id" require(row["headerDictID"] == {"expected-id": EXPECTED_ID, "different-id": EXPECTED_ID + 1, "omitted-id": 0}[row["idPolicy"]], "wrong parsed ID") require(row["dictionaryDigestMatches"] == correct, "wrong dictionary digest classification") require(row["idMatchesExpected"] == expected_id, "wrong caller ID classification") require(row["verifiedNamedRestore"] == (correct and expected_id), "wrong named restore outcome") require(row["verifiedOutOfBandRestore"] == correct, "wrong out-of-band restore outcome") require(row["codecComplete"] == (correct or (wrong and row["policy"] == "block-only")), "unexpected native completion outcome") require(row["exactPayload"] == correct, "unexpected output identity") if wrong and row["policy"] == "block-and-content": require(row["error"] == "ERROR_contentChecksum_invalid", "expected content checksum error") if row["dictionary"] == "missing": require(row["error"] == "ERROR_decompressionFailed", "expected missing dependency failure") require(row["namedIdPolicyAccepted"] == (row["codecComplete"] and expected_id), "wrong named ID policy") for policy in ("block-only", "block-and-content"): subset = [row for row in rows if row["policy"] == policy] require(len({row["bodySha256"] for row in subset}) == 1, "ID variants must retain identical compressed blocks and footer") def run(): rows = [] for policy, checksum in (("block-only", False), ("block-and-content", True)): for label, dict_id in (("expected-id", EXPECTED_ID), ("different-id", EXPECTED_ID + 1), ("omitted-id", 0)): data = compress(dict_id, checksum) for dictionary_name, dictionary in (("correct", DICTIONARY), ("wrong", WRONG), ("missing", None)): rows.append({"id": f"{policy}/{label}/{dictionary_name}", "policy": policy, "idPolicy": label, "dictionary": dictionary_name, "frameSha256": sha(data), "frameBytes": len(data), **decode(data, dictionary)}) validate(rows) return {"schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "classification": "Deterministic synthetic native API experiment, not a field rate or security test.", "environment": {"python": platform.python_version(), "liblz4": lib.LZ4_versionString().decode(), "platform": platform.platform()}, "method": { "expectedDictID": EXPECTED_ID, "dictionaryBytes": len(DICTIONARY), "dictionarySha256": sha(DICTIONARY), "wrongDictionarySha256": sha(WRONG), "payloadBytes": len(PAYLOAD), "payloadSha256": sha(PAYLOAD), "recipe": "Concatenate SHA-256 of little-endian uint32 0..1023; payload is dictionary[8192:16384]; wrong dictionary XORs every byte with 255.", "framePolicy": "Independent blocks; block checksums always enabled; content checksum toggled; native compressor regenerates every valid header.", "decodePolicy": "LZ4F_getFrameInfo then LZ4F_decompress_usingDict; NULL options verify checksums; 1024-byte output buffer; error-call bytes excluded.", "callerPolicies": "namedIdPolicyAccepted requires codec completion and expected numeric ID only; verifiedNamedRestore additionally requires exact dictionary and payload; verifiedOutOfBandRestore deliberately ignores the header ID but requires both exact identities.", "harnessSha256": sha(pathlib.Path(__file__).read_bytes()), "baseHarnessSha256": sha((BASE / "lz4-frame-contract.py").read_bytes())}, "observations": rows} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=pathlib.Path) parser.add_argument("--verify", type=pathlib.Path) args = parser.parse_args() result = run() if args.verify: previous = json.loads(args.verify.read_text()) require(previous["method"] == result["method"], "method or harness changed") require(previous["environment"]["liblz4"] == result["environment"]["liblz4"], "library version changed") require(previous["observations"] == result["observations"], "native observations changed") print("Exact replay: 18 dictionary observations") elif args.output: args.output.write_text(json.dumps(result, indent=2) + "\n") print("Recorded 18 dictionary observations") else: json.dump(result, sys.stdout, indent=2) print() if __name__ == "__main__": main()