Test / ttt_codec_v14.py
Hfzune's picture
Upload 12 files
f02ef17 verified
Raw History Blame Contribute Delete
8.1 kB
"""TTT v1.4: versioned, lossless adaptive packet codec.
Wire format (13-byte header):
magic: 4 bytes, b'TTT4'
codec: 1 byte (0 raw, 1 gzip, 2 zstandard, 3 bzip2)
original_size: uint32 big-endian
crc32: uint32 big-endian, over the reconstructed original bytes
payload: raw/compressed bytes
The decoder enforces packet/original-size limits and validates length and CRC.
"""
from __future__ import annotations
import bz2
import gzip
import io
import struct
import zlib
from dataclasses import dataclass
from typing import Final
try:
import zstandard as zstd
except ImportError: # allow limited local tests without the optional package
zstd = None
MAGIC: Final[bytes] = b"TTT4"
VERSION: Final[str] = "1.4.0"
HEADER: Final[struct.Struct] = struct.Struct(">4sBII")
HEADER_BYTES: Final[int] = HEADER.size
MAX_ORIGINAL_BYTES: Final[int] = 16 * 1024 * 1024
MAX_PACKET_BYTES: Final[int] = 32 * 1024 * 1024
CODEC_NAMES: Final[dict[int, str]] = {0: "raw", 1: "gzip", 2: "zstd", 3: "bzip2"}
NAME_TO_CODEC: Final[dict[str, int]] = {v: k for k, v in CODEC_NAMES.items()}
class TTTError(ValueError):
"""Base exception for malformed or unsupported TTT packets."""
@dataclass(frozen=True)
class PacketInfo:
mode: str
original_size: int
payload_size: int
packet_size: int
savings_vs_raw_percent: float
def _compress(data: bytes, mode: str) -> bytes:
if mode == "raw":
return data
if mode == "gzip":
return gzip.compress(data, compresslevel=9, mtime=0)
if mode == "zstd":
if zstd is None:
raise TTTError("Zstandard is unavailable. Install requirements.txt.")
return zstd.ZstdCompressor(level=9, write_checksum=True, write_content_size=True).compress(data)
if mode == "bzip2":
return bz2.compress(data, compresslevel=9)
raise TTTError(f"Unknown mode: {mode}")
def encode_packet(data: bytes, mode: str = "auto") -> tuple[bytes, PacketInfo]:
"""Encode bytes into a TTT4 packet. In auto mode, choose smallest full packet."""
if not isinstance(data, bytes):
raise TypeError("data must be bytes")
if len(data) > MAX_ORIGINAL_BYTES:
raise TTTError(f"Input exceeds the {MAX_ORIGINAL_BYTES:,}-byte safety limit.")
mode = mode.lower().strip()
if mode == "auto":
modes = ["raw", "gzip", "zstd", "bzip2"]
elif mode in NAME_TO_CODEC:
modes = [mode]
else:
raise TTTError("Mode must be auto, raw, gzip, zstd, or bzip2.")
choices: list[tuple[int, bytes, str]] = []
errors: list[str] = []
for candidate_mode in modes:
try:
payload = _compress(data, candidate_mode)
packet_size = HEADER_BYTES + len(payload)
if packet_size <= MAX_PACKET_BYTES:
choices.append((packet_size, payload, candidate_mode))
except Exception as exc:
errors.append(f"{candidate_mode}: {exc}")
if not choices:
detail = "; ".join(errors) if errors else "No candidate produced a valid packet."
raise TTTError(detail)
packet_size, payload, chosen_mode = min(choices, key=lambda item: item[0])
crc = zlib.crc32(data) & 0xFFFFFFFF
packet = HEADER.pack(MAGIC, NAME_TO_CODEC[chosen_mode], len(data), crc) + payload
info = PacketInfo(
mode=chosen_mode,
original_size=len(data),
payload_size=len(payload),
packet_size=len(packet),
savings_vs_raw_percent=(100.0 * (len(data) - len(packet)) / len(data)) if data else 0.0,
)
return packet, info
def _decompress_payload(mode: str, payload: bytes, expected_size: int) -> bytes:
# Each path either caps output to expected_size+1 or explicitly checks output.
if mode == "raw":
result = payload
elif mode == "gzip":
decoder = zlib.decompressobj(wbits=16 + zlib.MAX_WBITS)
result = decoder.decompress(payload, expected_size + 1)
if len(result) <= expected_size and decoder.unconsumed_tail:
result += decoder.decompress(decoder.unconsumed_tail, expected_size + 1 - len(result))
if len(result) > expected_size:
raise TTTError("Decoded data exceeds the declared original size.")
if not decoder.eof:
raise TTTError("Incomplete GZIP stream.")
if decoder.unused_data:
raise TTTError("Unexpected trailing bytes inside GZIP payload.")
elif mode == "zstd":
if zstd is None:
raise TTTError("Zstandard is unavailable. Install requirements.txt.")
# Stream output in bounded chunks; cap the decoder window to limit hostile frames.
source = io.BytesIO(payload)
dctx = zstd.ZstdDecompressor(max_window_size=(MAX_ORIGINAL_BYTES + 1023) // 1024)
output = bytearray()
with dctx.stream_reader(source, read_size=8192, read_across_frames=False) as reader:
while len(output) <= expected_size:
remaining = expected_size + 1 - len(output)
chunk = reader.read(min(65536, remaining))
if not chunk:
break
output.extend(chunk)
result = bytes(output)
if len(result) > expected_size:
raise TTTError("Decoded data exceeds the declared original size.")
elif mode == "bzip2":
decoder = bz2.BZ2Decompressor()
result = decoder.decompress(payload, max_length=expected_size + 1)
if len(result) > expected_size:
raise TTTError("Decoded data exceeds the declared original size.")
if not decoder.eof:
raise TTTError("Incomplete BZIP2 stream or decoded-size limit reached.")
if decoder.unused_data:
raise TTTError("Unexpected trailing bytes inside BZIP2 payload.")
else:
raise TTTError(f"Unsupported codec: {mode}")
if len(result) != expected_size:
raise TTTError(f"Length mismatch: expected {expected_size} bytes, got {len(result)}.")
return result
def decode_packet(packet: bytes) -> tuple[bytes, PacketInfo]:
"""Validate and decode a TTT4 packet to the exact original bytes."""
if not isinstance(packet, bytes):
raise TypeError("packet must be bytes")
if len(packet) > MAX_PACKET_BYTES:
raise TTTError(f"Packet exceeds the {MAX_PACKET_BYTES:,}-byte safety limit.")
if len(packet) < HEADER_BYTES:
raise TTTError("Packet is shorter than the TTT4 header.")
magic, codec_id, expected_size, expected_crc = HEADER.unpack(packet[:HEADER_BYTES])
if magic != MAGIC:
raise TTTError("Not a TTT v1.4 packet (invalid magic).")
if codec_id not in CODEC_NAMES:
raise TTTError(f"Unknown codec ID: {codec_id}.")
if expected_size > MAX_ORIGINAL_BYTES:
raise TTTError(f"Declared output exceeds the {MAX_ORIGINAL_BYTES:,}-byte safety limit.")
payload = packet[HEADER_BYTES:]
mode = CODEC_NAMES[codec_id]
try:
data = _decompress_payload(mode, payload, expected_size)
except TTTError:
raise
except Exception as exc:
raise TTTError(f"Invalid or corrupted {mode} payload: {exc}") from exc
actual_crc = zlib.crc32(data) & 0xFFFFFFFF
if actual_crc != expected_crc:
raise TTTError("Checksum mismatch: packet may be damaged or modified.")
info = PacketInfo(
mode=mode,
original_size=len(data),
payload_size=len(payload),
packet_size=len(packet),
savings_vs_raw_percent=(100.0 * (len(data) - len(packet)) / len(data)) if data else 0.0,
)
return data, info
def health_info() -> dict[str, object]:
return {
"status": "ok",
"service": "TTT lossless adaptive transmitter",
"version": VERSION,
"packet_format": "TTT4",
"header_bytes": HEADER_BYTES,
"max_original_bytes": MAX_ORIGINAL_BYTES,
"max_packet_bytes": MAX_PACKET_BYTES,
"encodings": ["raw", "gzip"] + (["zstd"] if zstd is not None else []) + ["bzip2"],
"auto_selection": "smallest complete packet among available encoders",
"shared_tokenizer_vocabulary_required": False,
}