Squeeze: the Information Theory CapstoneSqueeze
0 / 0

Workbench / Squeeze: the Information Theory Capstone

S8 · B1·08

Detecting Damage

Stage 8 of Squeeze, after chapter 8: every Squeeze file gets two CRC-32 checks, a frame check over the stored bytes that's verified before any decoding, and a content check over the original data that's verified after it; one flipped bit, which went unnoticed in every unprotected trial and garbled a median of 36,000 to 46,000 bytes in the arithmetic coders' files, is now caught every time, for 8 bytes per file.

6 topics · ~10 min read
Updated Suggest a correction

Stage 8: detecting damage

The brief

What you'll build. A new squeeze.py that seals every file: after the method's output it appends a CRC-32 of the original data (the content check), then a CRC-32 of everything before it (the frame check). unpack verifies the frame check first, before any decoder sees the bytes, then decodes, then verifies the content check against the result. A failure raises Damaged and the command line exits with a clear message. And damage.py, which flips one bit in each method's file and measures what happens with and without the checks.

Why a compressor needs this. Chapter 8 showed that compressed data has no redundancy left: one flipped bit in a deflate stream went unreported every time and garbled up to 600,000 bytes. Squeeze's arithmetic coders have no block boundaries at all, so the damage can run to the end of the file. A compressor that can't say "this file is damaged" will one day hand someone wrong data without a word.

Why now. The chapter supplies the binomial count (long files will meet errors), CRCs and what they catch, and the rule: compress, then add a check.

What you'll have at the end. The sealed format, damage.py's table for every method, and a command line that refuses damaged files.

Theory to own

  1. Why check twice? What does the frame check catch that the content check doesn't, and the other way round? (Chapter: "Detecting isn't correcting"; the companion's drill D4.)
  2. Why check before decoding? What can a decoder do with damaged input besides produce wrong data? (Chapter: "Damage in compressed data".)
  3. What 8 bytes buy. What's the chance that a random corruption of a sealed file goes unnoticed? (Chapter: "Checksums and CRCs".)
  4. Why not correct? When would a compressor want a correcting code instead of a check? (Chapter: "Detecting isn't correcting"; exercises T6.)

Build it

Step 1: seal and check. The methods are unchanged; squeeze.py wraps them.

Python
"""Squeeze, stage 8: try every method, keep the smallest, and protect the result with two CRC-32 checks.
Usage: python3 squeeze.py pack|unpack IN OUT"""
import sys, zlib
from pathlib import Path
import fixed, huffman, arith, adaptive

def store(data):
    return b"SQZ\x00" + len(data).to_bytes(4, "big") + data

METHODS = {0: ("store", store, lambda b: b[8:]), 1: ("fixed", fixed.pack, fixed.unpack),
           2: ("huffman", huffman.pack, huffman.unpack), 3: ("arithmetic", arith.pack, arith.unpack), 4: ("order-1", adaptive.pack, adaptive.unpack)}

class Damaged(ValueError):
    """The file failed a check: it was changed after it was packed."""

def seal(body, data):
    """Append a CRC-32 of the original data (the content check), then one of everything before it (the frame check)."""
    body += zlib.crc32(data).to_bytes(4, "big")
    return body + zlib.crc32(body).to_bytes(4, "big")

def pack_with(method, data):
    return seal(METHODS[method][1](data), data)

def pack(data):
    results = []
    for m, (name, enc, _) in METHODS.items():
        try:
            results.append((len(blob := enc(data)), m, blob))
        except ValueError:
            pass                                           # a method that can't handle this input is skipped
    return seal(min(results)[2], data)

def unpack(blob):
    if len(blob) < 16 or zlib.crc32(blob[:-4]) != int.from_bytes(blob[-4:], "big"):
        raise Damaged("frame check failed: the file was damaged after packing")
    body, content = blob[:-8], int.from_bytes(blob[-8:-4], "big")
    if body[:3] != b"SQZ" or body[3] not in METHODS:
        raise ValueError("not a Squeeze file, or an unknown method")
    data = METHODS[body[3]][2](body)
    if zlib.crc32(data) != content:
        raise Damaged("content check failed: the decoder produced the wrong data")
    return data

if __name__ == "__main__":
    if len(sys.argv) != 4 or sys.argv[1] not in ("pack", "unpack"):
        sys.exit(__doc__)
    try:
        out = (pack if sys.argv[1] == "pack" else unpack)(Path(sys.argv[2]).read_bytes())
    except Damaged as e:
        sys.exit(f"squeeze: {sys.argv[2]}: {e}")
    Path(sys.argv[3]).write_bytes(out)

Step 2: measure the damage. One random bit flipped in each method's file, 20 times, decoded first without the checks (straight to the method's own unpack, with a time limit in case a decoder never finishes), then with them.

Python
"""Flip one bit in each method's file, 20 times, and see what the decoder does with and without the checks."""
import random, signal
from pathlib import Path
import squeeze

class Hung(Exception):
    pass
def alarm(*_):
    raise Hung
signal.signal(signal.SIGALRM, alarm)

rng = random.Random(8)
data = Path("shakespeare.txt").read_bytes()[:100_000]
print(f"{len(data):,} bytes of the plays; one random bit flipped, 20 trials per method\n")
print(f"{'method':<12}{'bytes':>8}  {'no check: error / wrong / right':>32}  {'median wrong':>12}  {'checks caught':>13}")
for m, (name, enc, dec) in squeeze.METHODS.items():
    body = enc(data)
    sealed = squeeze.pack_with(m, data)
    outcomes, wrongs, caught = {"error": 0, "wrong": 0, "right": 0}, [], 0
    for _ in range(20):
        bit = rng.randrange(len(body) * 8)
        bad = bytearray(body); bad[bit // 8] ^= 1 << (bit % 8)
        signal.alarm(5)
        try:
            out = dec(bytes(bad))
            w = sum(a != b for a, b in zip(out, data)) + abs(len(out) - len(data))
            outcomes["wrong" if w else "right"] += 1
            if w:
                wrongs.append(w)
        except (Exception, Hung):
            outcomes["error"] += 1
        finally:
            signal.alarm(0)
        bad = bytearray(sealed); bad[bit // 8] ^= 1 << (bit % 8)      # the same bit, in the sealed file
        try:
            squeeze.unpack(bytes(bad))
        except squeeze.Damaged:
            caught += 1
    med = sorted(wrongs)[len(wrongs) // 2] if wrongs else 0
    print(f"{name:<12}{len(body):>8,}  {outcomes['error']:>14} / {outcomes['wrong']:>5} / {outcomes['right']:>5}  {med:>12,}  {caught:>10} of 20")
Text
100,000 bytes of the plays; one random bit flipped, 20 trials per method

method         bytes   no check: error / wrong / right  median wrong  checks caught
store        100,008               0 /    20 /     0             1          20 of 20
fixed         75,071               0 /    20 /     0             1          20 of 20
huffman       60,066               2 /    18 /     0             1          20 of 20
arithmetic    59,600               0 /    20 /     0        36,368          20 of 20
order-1       43,851               0 /    20 /     0        45,549          20 of 20

Step 3: run the round trips again, and try the command line on a damaged file.

Python
import subprocess, zlib
from pathlib import Path
import squeeze

print(f"{'file':<16}{'stage 7':>9}{'stage 8':>9}  chosen, round trip")
for name in ("shakespeare.txt", "zeros.bin", "random.bin", "squares.csv", "server.log"):
    data = Path(name).read_bytes()
    blob = squeeze.pack(data)
    ok = squeeze.unpack(blob) == data
    print(f"{name:<16}{len(blob) - 8:>9,}{len(blob):>9,}  {squeeze.METHODS[blob[3]][0]}, {'exact' if ok else 'FAILED'}")
for edge in (b"", b"x", b"ab" * 3, bytes(range(256)), bytes(range(256)) * 300):
    assert squeeze.unpack(squeeze.pack(edge)) == edge
print("edge cases: exact")

subprocess.run(["python3", "squeeze.py", "pack", "server.log", "log.sqz"], check=True)
blob = bytearray(Path("log.sqz").read_bytes()); blob[len(blob) // 2] ^= 0x10
Path("log.sqz").write_bytes(blob)
r = subprocess.run(["python3", "squeeze.py", "unpack", "log.sqz", "log.out"], capture_output=True, text=True)
print("one bit flipped in log.sqz:", r.stderr.strip(), f"(exit status {r.returncode})")
Text
file              stage 7  stage 8  chosen, round trip
shakespeare.txt   492,328  492,336  order-1, exact
zeros.bin              11       19  fixed, exact
random.bin        200,008  200,016  store, exact
squares.csv        80,809   80,817  order-1, exact
server.log         41,760   41,768  order-1, exact
edge cases: exact
one bit flipped in log.sqz: squeeze: log.sqz: frame check failed: the file was damaged after packing (exit status 1)

Step 4: read the tables.

  • Without checks, almost nothing complains. Of 100 damaged files, only 2 (Huffman's) made a decoder fail; the other 98 decoded "successfully".
  • How much goes wrong depends on the method. Store and the fixed-length code lose exactly one byte: each byte is coded on its own. Huffman usually loses one byte too: a flipped bit inside a canonical code often produces another valid code of the same length, and when it doesn't, the decoder soon falls back into step. The arithmetic coders lose a median of 36,368 and 45,549 bytes of 100,000: every later symbol depends on the state the damaged bit changed, so the rest of the file is garbage. The better the compression, the worse the damage.
  • With checks, all 100 were caught, by the frame check, before decoding started. The cost is 8 bytes per file, 0.002 % of Shakespeare's.
  • The command line refuses the damaged log with a message and a non-zero exit status, so scripts notice too.

Senior and architect lens

  • Check before you decode. A decoder fed damaged input can do worse than produce wrong data: a damaged length field can make it allocate gigabytes or loop for minutes (the time limit in damage.py exists for this reason), and in languages without bounds checks, damaged input is how decoders get exploited. Verifying the frame check first means decoders only ever see bytes that are exactly what the encoder wrote.
  • Two checks, two jobs. The frame check covers storage and transmission. The content check covers the code: an encoder or decoder bug, or a decoder from a different version, produces wrong data from perfect bytes, and only a check of the original data catches that. For this reason gzip and zip store a CRC-32 of the uncompressed data, zlib streams (inside every PNG) an Adler-32, and zstd an optional checksum of its own.
  • Detection is not protection. A damaged Squeeze file is now reported, not repaired. If the file is the only copy, the data is still lost; that's a job for redundancy (chapter 9's codes, or a second copy), and for storing archives where scrubbing can find damage while a good copy exists.
  • CRCs stop accidents, not people. Anyone who can change the file can recompute both checks. If files cross a trust boundary, add a cryptographic hash or signature from a trusted source (the companion's point 2).

Evidence

  • The new squeeze.py, damage.py with your table, and run.py, every file "exact".
  • The message and exit status from unpacking a damaged file.
  • A paragraph explaining why the arithmetic coders' files lose tens of thousands of bytes from one bit while Huffman's usually lose one.

Carry forward

Stage 9, after chapter 9, goes from detecting damage to surviving it: you'll add a correcting code to Squeeze's files, measure how much redundancy it costs against the channel's capacity, and see how close a simple code gets to the limit.