Author SHA1 Message Date
Muse 580728135a Baseline: full corruption matrix results + pass-2 analysis
200 trials/setting on slice1m (-6 -e 4, t=8, single block):
scattered bits <=8 recover 200/200, 9/16/32 recover 0/200;
bursts: 1B 200/200, 2B 117-135/200, >=4B 0/200; silent-bad 0/2800.
Pass 2 is wired in (entry_decode -> bch_decode_candidates) but
rescues nothing beyond t at this block size — the gap the
deep-repair work must close. Also: harness gains MATRIX_ONLY /
MATRIX_WORKDIR for concurrent runs; docs/BASELINE.md section 7
notes the blocked hot_chicago run.
2026-12-02 13:47:01 +00:00
Muse 9690691907 Baseline: codebase survey, bench harness, corruption matrix, docs/BASELINE.md (matrix table TBD)
Survey + reproducible yardstick for the parallel ECC/compression
experiments: bench/bench.sh (ratio/speed/RSS), bench/corrupt_matrix.py
(200 trials/setting, scattered bits + bursts), docs/BASELINE.md with
the full codebase map, format summary, test results and the
enwik8/Silesia corpus checksums.
2026-12-02 11:39:49 +00:00
21 changed files with 468 additions and 2487 deletions

No files matched your search

Executable
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
# Baseline ratio / speed / memory benchmark for lzply (experiments/baseline).
# Usage: bench.sh <lzply-binary> <corpus-dir> <work-dir>
# Corpus dir: enwik8 + silesia files (see docs/BASELINE.md for checksums).
# Each setting: encode once, decode once, timed with /usr/bin/time -v
# (max RSS), sizes from stat. Clean round-trips verified bit-identical
# with diff -r (any mismatch is reported in the roundtrip field).
set -u
LZPLY="$1"; CORPUS="$2"; WORK="$3"
mkdir -p "$WORK"
cd "$WORK" || exit 1
( cd "$CORPUS" && sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml > "$WORK/corpus.sha256" )
echo "corpus total bytes: $(du -sb "$CORPUS" | cut -f1)"
run_one() { # run_one <label> <input-path> <lzply -c flags...>
local label="$1" input="$2"; shift 2
local arc="$WORK/$label.lzply" out="$WORK/$label.out"
rm -rf "$arc" "$out"
/usr/bin/time -v "$LZPLY" -c "$@" "$input" "$arc" > "$WORK/$label.enc.log" 2> "$WORK/$label.enc.time"
local enc_rc=$?
local enc_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.enc.time" | awk '{print $NF}')
local enc_rss=$(grep "Maximum resident" "$WORK/$label.enc.time" | awk '{print $NF}')
local arc_size=$(stat -c%s "$arc" 2>/dev/null || echo 0)
/usr/bin/time -v "$LZPLY" -d -y "$arc" "$out" > "$WORK/$label.dec.log" 2> "$WORK/$label.dec.time"
local dec_rc=$?
local dec_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.dec.time" | awk '{print $NF}')
local dec_rss=$(grep "Maximum resident" "$WORK/$label.dec.time" | awk '{print $NF}')
local rt="?"
if [ $dec_rc -eq 0 ]; then
if diff -r -q "$input" "$out/$(basename "$input")" > /dev/null 2>&1; then rt="IDENTICAL"; else rt="MISMATCH"; fi
else rt="DECODE-FAILED"; fi
echo "$label enc_rc=$enc_rc enc_wall=$enc_wall enc_maxrss_kb=$enc_rss arc_bytes=$arc_size dec_rc=$dec_rc dec_wall=$dec_wall dec_maxrss_kb=$dec_rss roundtrip=$rt"
}
run_one enwik8-l1 "$CORPUS/enwik8" -1 -e 4
run_one enwik8-l6 "$CORPUS/enwik8" -6 -e 4
run_one enwik8-l9 "$CORPUS/enwik8" -9 -e 4
run_one corpus-l6e4 "$CORPUS" -6 -e 4
run_one corpus-l6e0 "$CORPUS" -6 -e 0
run_one corpus-l6e7 "$CORPUS" -6 -e 7
run_one mozilla-l6 "$CORPUS/mozilla" -6 -e 4
echo DONE
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Corruption-matrix harness for lzply baseline (experiments/baseline).
Builds a single-entry archive of a 1 MiB text slice (default -6 -e 4),
then for each setting runs N trials: copy the archive, corrupt ONLY the
stored-data region (headers untouched), run `lzply -t`, and on success
also extract + verify SHA-256 of the recovered file. Reports
recovered / failed-loud / silent-bad counts per setting.
Settings:
scattered N bits: N in {1,2,4,8,9,16,32} random distinct bit positions
burst L bytes: L in {1,2,4,8,16} consecutive bytes replaced with
random bytes at a random offset (up to 8*L bit errors)
Usage: corrupt_matrix.py <lzply> <archive> <trials> [seed]
Archive must have exactly one file entry; data offset is parsed from
the v4 headers (global 16 + entry 78 + path_len).
Env: MATRIX_WORKDIR (default /tmp/lzply-matrix), MATRIX_ONLY
(comma list of kinds to run, default "bits,burst") — used to run
the burst settings as a second concurrent process with its own
workdir and seed while the bits run continues.
"""
import hashlib
import os
import random
import shutil
import struct
import subprocess
import sys
LZPLY, ARCHIVE, TRIALS = sys.argv[1], sys.argv[2], int(sys.argv[3])
SEED = int(sys.argv[4]) if len(sys.argv) > 4 else 20261202
with open(ARCHIVE, "rb") as f:
raw = f.read()
assert raw[:4] == b"LZPL", "not an LZPL archive"
assert raw[4] == 4, "not v4"
path_len = struct.unpack_from("<H", raw, 16)[0]
data_off = 16 + 78 + path_len
# entry header (78 bytes from offset 16): path_len u16, level/rs_level/
# flags/reserved u8 x4, orig_size u64 @22, stored_size u64 @30,
# blob_size u64 @38, sha256[32] @46, mode u32, mtime u64, header_crc32 u32
orig_size, stored_size, blob_size = struct.unpack_from("<QQQ", raw, 22)
sha = raw[46:78].hex()
print("archive: %s data_off=%d stored=%d blob=%d orig=%d sha256=%s..."
% (ARCHIVE, data_off, stored_size, blob_size, orig_size, sha[:16]),
flush=True)
data_end = data_off + stored_size
assert data_end <= len(raw), "stored data overruns file"
work = os.environ.get("MATRIX_WORKDIR", "/tmp/lzply-matrix")
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
def trial(rng, kind, n):
p = os.path.join(work, "t.lzply")
buf = bytearray(raw)
if kind == "bits":
positions = rng.sample(range(data_off * 8, data_end * 8), n)
for pos in positions:
buf[pos // 8] ^= 1 << (pos % 8)
else: # burst: n consecutive bytes -> random bytes
start = rng.randrange(data_off, data_end - n + 1)
for i in range(n):
buf[start + i] = rng.randrange(256)
with open(p, "wb") as f:
f.write(buf)
r = subprocess.run([LZPLY, "-t", p], capture_output=True)
if r.returncode != 0:
return "failed-loud"
# -t passed: extract and verify content hash to catch silent damage
outdir = os.path.join(work, "out")
shutil.rmtree(outdir, ignore_errors=True)
r2 = subprocess.run([LZPLY, "-d", "-y", p, outdir],
capture_output=True)
if r2.returncode != 0:
return "failed-loud"
got = None
for root, _, files in os.walk(outdir):
for fn in files:
with open(os.path.join(root, fn), "rb") as f:
got = hashlib.sha256(f.read()).hexdigest()
return "recovered" if got == sha else "SILENT-BAD"
rng = random.Random(SEED)
results = {}
only = os.environ.get("MATRIX_ONLY", "bits,burst").split(",")
for kind, sizes in (("bits", [1, 2, 4, 8, 9, 16, 32]),
("burst", [1, 2, 4, 8, 16])):
if kind not in only:
continue
for n in sizes:
counts = {"recovered": 0, "failed-loud": 0, "SILENT-BAD": 0}
for _ in range(TRIALS):
counts[trial(rng, kind, n)] += 1
results[(kind, n)] = counts
print("%-5s n=%-3d: recovered %3d/%d failed-loud %3d silent-bad %d"
% (kind, n, counts["recovered"], TRIALS,
counts["failed-loud"], counts["SILENT-BAD"]), flush=True)
bad = sum(c["SILENT-BAD"] for c in results.values())
print("TOTAL silent-bad: %d (must be 0)" % bad)
sys.exit(1 if bad else 0)
+321
View File
@@ -0,0 +1,321 @@
# lzply baseline — experiments/baseline @ 8dbb8d03
Measured 2026-12-02 on hot_newyork (172.93.49.176, 8 cores, 30 GB RAM,
Ubuntu 26.04.1, gcc 15.2.0, liblz 1.16~rc1, libfuse3 3.18.2).
Base commit: `8dbb8d03` — "BCH: two-pass silent repair (hash-gated pass 2;
zero silent failures, loud failure otherwise)".
Branch: `experiments/baseline`. This file is the yardstick for the
parallel ECC / compression experiments: same corpus, same commands,
same harness (`bench/`).
## 1. Codebase map
Repo root `/opt/lzply-exp-base` (checked out from
`git@github.com:cnmcdee/lzply.git`, branch `experiments/baseline`).
~11,633 lines of C/Python, no legacy support: v4 (`LZPL`) is the only
format; v1/v2/v3 and old magics `LZRS`/`LZBC` are rejected outright.
| File | Lines | Role |
|---|---|---|
| `lzply.c` | 1926 | `lzply` CLI: `-c/-a/-d/-l/-t/-i/-tr`, date filters, selectors |
| `lzply_lib.c` / `lzply_lib.h` | 930 / 253 | shared core: v4 format, per-entry pipeline (lzip -> BCH), header I/O, archive scan, filters |
| `bch.c` / `bch.h` | 1007 / 109 | binary BCH codec + two-pass (pass-2 candidate) repair |
| `bch_polys.h` | 273 | 82 embedded generator polynomials (parents N = 2^m - 1, m = 7..22) |
| `gen_bch_polys.py` | 322 | regenerates `bch_polys.h` from rssearch data (checked in, not rebuilt by make) |
| `bch_test.c` | 415 | BCH unit tests (table remainder vs brute force, roundtrips, corruption, auto-pick, block splitting) |
| `sha256.c` / `sha256.h` | 124 / 26 | SHA-256 (per-entry integrity; load-bearing against BCH miscorrection) |
| `lzply_mount.c` | 1448 | FUSE filesystem (`lzply_mount`, `mount.lzply` helper) |
| `lzply_stat.c` | 293 | per-entry statistics (sizes, poly, t, parity bits, ECC overhead %) |
| `lzply_heal.c` | 618 | strip + re-apply BCH parity without touching the compressed blob |
| `lzply_check.c` | 564 | bit-error-rate measurement (`--json`, `--warn-ber`, `--fail-ber`) |
| `lzply_refresh.c` | 410 | in-place platter refresher (1-3 passes, SHA-256 verified) |
| `lzply_hyper.c` | 2264 | striped volume: 8 bit-plane data stripes + 1-3 XOR/GF parity, rebuilds up to 3 dead stripes (no compression) |
| `lzply_util.c` / `lzply_util.h` | 440 / 33 | shared helpers for stat/heal/check/refresh (mount resolution via /proc, human sizes) |
| `lzprobe.c` | 41 | tiny probe tool |
| `Makefile` | 137 | builds 7 binaries + `bch_test`; `make test` runs the full suite |
| `tests/run_tests.sh` | 1156 | 147 archive tests (see §3) |
| `tests/run_hyper_tests.sh` | 443 | 56 striped-volume tests |
| `tests/corrupt.c`, `tests/corrupt_bits.c` | 96 / 103 | whole-byte / single-bit corruption injectors used by the suite |
| `tests/make_testdata.sh` | 46 | generates `testdata/` (incl. a 50 MiB random file) on demand |
| `bench/bench.sh` | — | this baseline's ratio/speed/memory benchmark (see §5) |
| `bench/corrupt_matrix.py` | — | this baseline's corruption matrix (see §6) |
| `README.md`, `README-hyper.md`, `lzply_hyper-design.md` | — | user docs; format + CLI reference |
Build system: plain `make` (no configure/autotools). `make -j8` builds
`lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh
lzply_hyper` + `liblzply.a` (lzply_lib + bch + sha256). Deps:
`build-essential`, `liblz-dev` (lzip/LZMA), `libfuse3-dev` (mount only).
`CFLAGS = -O2 -Wall -Wextra`; the baseline build is warning-clean.
## 2. Format (v4) and pipeline
All integers little-endian. Global header (16 B): magic `"LZPL"`,
version u8 (=4), flags u8, entry_count u32, reserved u64. Each entry:
u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
u32 mode, u64 mtime, u32 header_crc32 (covers the 74 bytes before it),
path[path_len], data[stored_size]. End marker: u16 path_len == 0.
Per-entry pipeline: `compress (lzip) -> BCH encode` on write;
`BCH-decode -> decompress` on read. One entry = one independent byte
stream. `blob_size` is the compressed length before ECC parity.
CLI (see `README.md` for the full reference):
- Compression: lzip levels `-1`..`-9`, default `-6`. The compressed
stream inside an entry is byte-identical to `lzip -N`.
- Store mode (level 0): when the compressed blob would be no smaller
than the original (already-compressed / random / empty), the entry is
stored uncompressed; BCH still applies. `-0` forces store for all.
- Error correction: `-e <0..7>` maps to BCH t: 0 -> none, 1 -> 1,
2 -> 2, 3 -> 4, 4 -> 8, 5 -> 16, 6 -> 32, 7 -> 32. Default `-e 4`
(t=8). `poly=NN` (hex `poly=003a` or decimal `poly=58`) pins one
polynomial and overrides `-e`. With no pin, the most efficient poly
for the blob length is auto-picked (smallest parent whose codeword
covers the blob). A blob longer than one block's capacity is split
into blocks of that poly's max payload (m=22, t=32: 524,199 B/block);
the decoder rebuilds boundaries from blob_size + poly.
- Integrity: every entry carries SHA-256 of its original data. A
bounded-distance BCH decoder can miscorrect damage beyond t (e.g.
t=1, 2-bit errors miscorrect ~50% at codec level); SHA-256 catches
it, so miscorrection is reported as corruption, never silent damage.
- Two-pass repair (this base commit): when pass-1 decode fails (or the
hash fails after a pass-1 success), pass 2 enumerates up to 16
candidate decodings (residual-BM + bounded flip-and-redecode) and the
caller hash-verifies each; first SHA-256 match wins, otherwise loud
failure. Zero silent failures by construction.
- Timestamps: mtime (seconds, UTC) + file mode stored per entry;
ownership not stored. `-datestart` / `-dateend` / `-year` filter on
mtime; `-i` reads headers only (never decompresses); `-tr` prints a
tree; `-a` appends (incremental when no path collides); selectors
match exact paths or directory prefixes.
- Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.
- Limitations (v4): whole files buffered in memory (50 MiB fine,
multi-GB needs a streaming rewrite); symlinks/special files skipped;
BCH corrects scattered bit flips, not whole lost bytes — a burst
wiping many consecutive bits in one block can exceed t even when the
byte count is small; the BCH decoder builds GF(2^m) log/exp tables
(up to 32 MiB transient for m=22) the first time it must correct an
error in a block (no-error path needs no tables).
## 3. Test suite — results at this base
`make test` = `bch_test` + `tests/run_tests.sh` + `tests/run_hyper_tests.sh`.
| Suite | Result (hot_newyork) |
|---|---|
| `bch_test` phase 1+2 (remainder x-check + roundtrip, all 82 polys) | 5220 checks, 0 fails |
| `bch_test` phase 3 (corruption) | 7253 checks, 0 fails |
| `tests/run_tests.sh` | **147 passed, 0 failed** |
| `tests/run_hyper_tests.sh` | **56 passed, 0 failed** |
Coverage: roundtrips at every level `-1`..`-9`; byte-identical
cross-check vs system `lzip -6` (at `-e 0`); roundtrips at BCH levels
0..7; BCH corruption with pinned polys (t recovered, t+1 fails
cleanly); combined `-9 -e 5` with 16 corrupted bits; v1/v3 archives
and old magics rejected; overwrite flags; empty dir/file, 1-byte file,
spaces in names, truncated/non-archive inputs; 50 MiB multi-block file;
`poly=` pinning (hex/decimal), unknown-poly rejection; append (21
tests) + selective extract; inspect/tree/date filters (27 tests);
`lzply_stat` (4), `lzply_heal` (8), `lzply_check` (8),
`lzply_refresh` (9), mount write-back (3), store mode (16).
Environment caveat (NOT a code failure): run from `/opt/lzply-exp-base`
the suite reports **144 passed, 3 failed** — the 3 mount write-back
tests (`mount with relative archive path: writes persist in the real
archive`, `store mode: mount repack stores an incompressible file`,
`store mode: mount-repacked stored file extracts byte-identical`).
Root cause, verified: AppArmor's `fusermount3` profile (enforce mode,
`/etc/apparmor.d/fusermount3`) allows `umount` only under
`@{HOME}/**`, `/mnt/**`, `/run/user/@{uid}/**`, `/media/**`,
`/tmp/**`, `/cvmfs/**` — NOT under `/opt/**`. `fusermount3 -u`
fails with EPERM (audit: `apparmor="DENIED" operation="umount" ...
profile="fusermount3"`), the mount stays up, the repack never runs,
and the test reads the pre-mount archive. The lzply code is correct:
the same tests pass when the tree is copied under `/tmp`
(147/0 above), a manual relative-path mount under `/tmp` repacks
correctly, and plain `umount` (unconfined) unmounts the `/opt` mounts
fine and triggers the repack. To run the suite green, run it from a
copy under `/tmp` (or any AppArmor-allowed path):
`cp -a /opt/lzply-exp-base /tmp/lzply-tmproot && cd /tmp/lzply-tmproot && make test`.
Stale mounts left by the failing `/opt` runs were cleaned with
`umount` (the other coordinator's `/opt/lzply-exp-ecc` mounts were
left untouched).
## 4. Corpus (reproduction)
Standard corpora, downloaded 2026-12-02 to `/opt/lzply-bench/corpus/`:
- `enwik8` — first 100,000,000 bytes of English Wikipedia
(https://mattmahoney.net/dc/enwik8.zip), sha256
`2b49720ec4d78c3c9fabaee6e4179a5e997302b3a70029f30f2d582218c024a8`
- Silesia corpus (https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip),
all 12 files:
| file | bytes | sha256 |
|---|---|---|
| dickens | 10,192,446 | `b24c37886142e11d0ee687db6ab06f936207aa7f2ea1fd1d9a36763c7a507e6a` |
| mozilla | 51,220,480 | `657fc3764b0c75ac9de9623125705831ebbfbe08fed248df73bc2dc66e2a963b` |
| mr | 9,970,564 | `68637ed52e3e4860174ed2dc0840ac77d5f1a60abbcb13770d5754e3774d53e6` |
| nci | 33,553,445 | `fc63a31770947b8c2062d3b19ca94c00485a232bb91b502021948fee983e1635` |
| ooffice | 6,152,192 | `e7ee013880d34dd5208283d0d3d91b07f442e067454276095ded14f322a656eb` |
| osdb | 10,085,684 | `60f027179302ca3ad87c58ac90b6be72ec23588aaa7a3b7fe8ecc0f11def3fa3` |
| reymont | 6,627,202 | `0eac0114a3dfe6e2ee1f345a0f79d653cb26c3bc9f0ed79238af4933422b7578` |
| samba | 21,606,400 | `93ba07bc44d8267789c1d911992f40b089ffa2140b4a160fac11ccae9a40e7b2` |
| sao | 7,251,944 | `c2d0ea2cc59d4c21b7fe43a71499342a00cbe530a1d5548770e91ecd6214adcc` |
| webster | 41,458,703 | `6a68f69b26daf09f9dd84f7470368553194a0b294fcfa80f1604efb11143a383` |
| x-ray | 8,474,240 | `7de9fce1405dc44ae5e6813ed21cd5751e761bd4265655a005d39b9685d1c9ad` |
| xml | 5,345,280 | `0e82e54e695c1938e4193448022543845b33020c8be6bf3bf3ead2224903e08c` |
Data files total 311,489,800 bytes. The corpus directory also holds the
two source zips (`enwik8.zip` 36,445,475 B, `silesia.zip` 68,182,744 B);
whole-directory runs archive all 15 files (416,566,799 B total).
Corruption-matrix input: `slice1m.bin` = first 1,048,576 bytes of
`enwik8`, sha256
`4fb5efa9f35df431737731bf3c8f38a467b69731940ff82a4ee0e218aae58834`,
archived as `slice1m.lzply` at `-6 -e 4` (blob 296.9 KiB, poly `0050`,
t=8, single BCH block; 176 parity bits, 0.007% ECC overhead).
Reproduce the corpus download:
```sh
mkdir -p /opt/lzply-bench/corpus && cd /opt/lzply-bench/corpus
curl -sL -o enwik8.zip https://mattmahoney.net/dc/enwik8.zip
curl -sL -o silesia.zip https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip
python3 -c "import zipfile; zipfile.ZipFile('enwik8.zip').extractall()"
python3 -c "import zipfile; zipfile.ZipFile('silesia.zip').extractall()"
sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml
```
## 5. Baseline numbers — ratio, speed, memory
Command: `bench/bench.sh <lzply> <corpus-dir> <work-dir>` (needs
GNU `time`, `/usr/bin/time -v`, for wall clock + max RSS). Each run:
one encode, one decode, `diff -r` round-trip check. Machine shared
with other agents' builds during measurement — encode wall times are
noisy (see caveat); decode is stable. All round-trips bit-identical.
### 5.1 enwik8, single file, 100,000,000 bytes, default -e 4 (t=8)
| level | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|---|
| -1 | 29,126,665 | 29.13% | 1:43.82 | 0.96 | 156,404 KB | 0:06.57 | 15.2 | 157,560 KB |
| -6 | 26,519,665 | 26.52% | 3:06.14 | 0.54 | 215,800 KB | 0:06.19 | 16.2 | 159,668 KB |
| -9 | 25,397,987 | 25.40% | 4:10.43 | 0.40 | 485,112 KB | 0:06.24 | 16.0 | 181,880 KB |
### 5.2 whole corpus directory, 416,566,799 bytes (15 files), -6
| -e (t) | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|---|
| 4 (t=8, default) | 181,121,579 | 43.48% | 8:54.98 | 0.78 | 242,384 KB | 0:22.28 | 18.7 | 233,832 KB |
| 0 (no ECC) | 181,113,835 | 43.48% | 8:33.81 | 0.81 | 242,444 KB | 0:17.31 | 24.1 | 177,976 KB |
| 7 (t=32) | 181,144,811 | 43.49% | 8:56.79 | 0.78 | 242,568 KB | 0:38.93 | 10.7 | 233,844 KB |
ECC overhead on this corpus: default t=8 costs 7,744 bytes over no-ECC
(0.0043%); t=32 costs 30,976 bytes (0.017%). BCH parity is negligible
next to LZMA output at these sizes — the overhead story is per-block
parity bits, not a percentage of the archive. Decode slows with t
(17.3s -> 22.3s -> 38.9s) because larger t means larger GF tables on
the correction path and more blocks to check.
### 5.3 mozilla (binary-ish), 51,220,480 bytes, -6 -e 4
| archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|
| 13,580,691 | 26.51% | 0:49.45 | 1.04 | 155,768 KB | 0:02.89 | 17.7 | 86,776 KB |
### 5.4 Caveats
- Encode speed is dominated by single-threaded LZMA (`liblz`), not by
BCH: `-1` vs `-9` on enwik8 is 0.96 vs 0.40 MB/s for a 29.1% ->
25.4% ratio gain. Any compression-family experiment must beat
these ratio/speed points, not just the ratio.
- Wall times were measured while other agents were building on the
same 8-core server; expect encode times to vary run to run. Decode
times (I/O + LZMA decode, single-threaded) were stable across runs.
- Peak RSS is dominated by the whole-file buffering (input + blob +
stored copy in memory at once) plus, at `-9`, LZMA's dictionary
(485 MB for enwik8 -9 encode). Multi-GB files need the streaming
rewrite noted in §2.
## 6. Corruption matrix — correction power at default -e 4 (t=8)
Harness: `bench/corrupt_matrix.py <lzply> <archive> <trials> [seed]`.
Single-entry archive `slice1m.lzply` (see §4: 1 MiB text, blob
296.9 KiB, one BCH block, t=8). Each trial: copy the archive, corrupt
ONLY the stored-data region (headers untouched), run `lzply -t`, and
on success extract + SHA-256-verify the recovered file. 200 trials
per setting, seed 20261202 (Python `random.Random`, deterministic).
"recovered" = `-t` passed AND extracted bytes hash-identical;
"failed-loud" = `-t` (or extract) exited non-zero; "silent-bad" =
passed but content wrong (must be 0 — the SHA-256 gate).
### 6.1 Results (200 trials per setting)
Scattered bits (seed 20261202), single 304 KB block, t=8:
| scattered bits flipped | recovered | failed-loud | silent-bad |
|---|---|---|---|
| 1 | 200/200 | 0 | 0 |
| 2 | 200/200 | 0 | 0 |
| 4 | 200/200 | 0 | 0 |
| 8 (= t) | 200/200 | 0 | 0 |
| 9 (= t+1) | **0/200** | 200 | 0 |
| 16 | **0/200** | 200 | 0 |
| 32 | **0/200** | 200 | 0 |
Bursts — L consecutive bytes replaced with random bytes (up to 8L bit
errors); two independent seeds:
| burst length | recovered (seed 20261202) | recovered (seed 20261203) | failed-loud | silent-bad |
|---|---|---|---|---|
| 1 byte | 200/200 | 200/200 | 0 | 0 |
| 2 bytes | 135/200 | 117/200 | 65 / 83 | 0 |
| 4 bytes | 0/200 | 0/200 | 200 | 0 |
| 8 bytes | 0/200 | 0/200 | 200 | 0 |
| 16 bytes | 0/200 | 0/200 | 200 | 0 |
**Total silent-bad across all 2,800 trials: 0.** The SHA-256 gate
holds everywhere: damage beyond t is always a loud failure, never
wrong data.
### 6.2 Reading the numbers
- The cliff is exactly at t: everything at or below 8 scattered bit
errors recovers; everything above recovers nothing. Pass 1
(bounded-distance BCH) behaves exactly as theory says.
- **Pass 2 rescues nothing beyond t for random scattered errors at
this block size: 0/600 trials at n = 9, 16, 32.** Pass 2 IS wired
in (`entry_decode` in `lzply_lib.c` calls `bch_decode_candidates`,
up to 16 candidates, hash-gated) — the residual-BM +
flip-and-redecode candidates simply never land on the true codeword
for random t+1..t+4 patterns in a 304 KB (m=22) block. This is the
gap the deep-repair work (Chase flips, list decoding) exists to
close; any experiment claiming beyond-t recovery must beat 0/200
here, on this archive, with these seeds.
- The 2-byte burst split (117-135/200) is the binomial edge: two
random bytes differ in ~8 bits on average, so about half the trials
land at <= 8 bit errors (recovered) and half above (failed). A
1-byte burst is always <= 8 bit errors, hence 200/200.
- Pass 2 is expensive when it runs: trials at n <= 8 cost ~1 s each
(fresh `lzply -t` + `lzply -d` processes, GF(2^22) table build on
the correction path); trials beyond t cost ~4-5 s each (candidate
enumeration). A repair scheme's per-block time budget matters as
much as its recovery rate.
Reproduce: `python3 bench/corrupt_matrix.py /opt/lzply-exp-base/lzply
/opt/lzply-bench/slice1m.lzply 200 20261202` (bits + bursts, one
process) or with `MATRIX_ONLY=burst MATRIX_WORKDIR=/tmp/lzply-matrix-burst`
and seed 20261203 for the burst-only run. Logs:
`/opt/lzply-bench/matrix.log`, `/opt/lzply-bench/matrix-burst.log`.
## 7. What is NOT in this baseline
- hot_chicago build/test: blocked by the sshd outage (new sessions
hang at banner exchange; see report). The branch is pushed, so the
Chicago run is a clone + `make -j8` + `make test` + the same
`bench.sh` / `corrupt_matrix.py` once SSH recovers. Chicago needs
no package installs (lzip, liblz-dev, libfuse3-dev present).
- `lzply_hyper` (striped volume) numbers: the suite passes (56/0)
but no separate ratio/speed benchmark was run — it stores
uncompressed stripes, so its yardstick is rebuild time, not ratio.
-7
View File
@@ -1,7 +0,0 @@
bench
ldpc_diag
pass2_diag
uep_diag
*.o
corpora/
results/
-29
View File
@@ -1,29 +0,0 @@
# exp/Makefile - build the ECC experiments harness (bench).
# Links the real lzply BCH + SHA-256 from the repo root.
CC ?= gcc
CFLAGS ?= -O2 -Wall -Wextra -march=native
CPPFLAGS ?= -I. -I..
SRCS = bench.c bch_wrap.c interleave.c ldpc.c polar.c uep.c \
../bch.c ../sha256.c
OBJS = $(SRCS:.c=.o)
bench: $(OBJS)
$(CC) $(CFLAGS) -o $@ $(OBJS) -lm
ldpc_diag: ldpc_diag.c ldpc.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ ldpc_diag.c ldpc.c -lm
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
uep_diag: uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c -lm
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
clean:
rm -f bench ldpc_diag pass2_diag uep_diag $(OBJS)
.PHONY: clean
-201
View File
@@ -1,201 +0,0 @@
# lzply ECC experiments (branch `experiments/ecc`)
Open-ended error-correction research on top of lzply's BCH baseline.
Each family implements `ecc_iface.h` (whole-blob encode/decode) and is
measured by `bench.c` on the same corpora, same corruption matrix, same
success criterion (exact recovery, memcmp + SHA-256).
## How to run
```
./bench --codec bch-t32 --blob corpora/text.lz --size 65536 \
--trials 200 --ber 1e-3 --nopass2 --out results/x.csv
./bench --codec ldpc-r90 --blob corpora/text.lz --burst 256,1 --trials 200
./bench --codec bch-t32 --blob corpora/text.lz --speed
./ldpc_diag r90 40 50 # single-block error-count sweep
./uep_diag uep-c1024-h32-l8 corpora/text.lz 65536 50 --ber 1e-3
```
Modes: `--ber X` (independent bit flips), `--burst LEN,COUNT`
(COUNT randomized-byte bursts of LEN bytes), `--clean`, `--speed`.
`--nopass2` skips the (slow) second-chance recovery hook so the matrix
stays fast; `run_pass2.sh` measures rescue rates separately.
`run_matrix.sh <corpus> <size> <trials> <out.csv> <codec...>` runs the
full matrix (5 BERs + 5 burst settings + clean), parallel over cores.
Corpora (`mkcorpora.sh`, generated, not committed): `text.lz` /
`bin.lz` / `rand.lz` — lzip -9 of 4 MiB text, binaries, seeded random
bytes (the compressed blob is what lzply protects); `*.raw` — the
stored-entry case. Default window is 64 KiB.
## Families
| codec | what it is |
|---|---|
| `bch-t{2,4,8,16,32}` | Baseline: BCH exactly as lzply ships it (auto-pick poly for the whole blob; pass 2 via `recover_verified`). |
| `bch1k-t{8,16,32}` | Same BCH, forced m=13 blocks (971 data bytes/block) — the "spend real redundancy" point. |
| `intlv-d{D}-bch1k-t{T}` | Byte interleaver (depth D) over bch1k-t{T}. Zero extra parity; bursts spread across blocks. Groups merge the short tail (see below). |
| `ldpc-r{90,95}` | Regular LDPC, PEG construction, min-sum belief propagation. |
| `polar-r{90,95}[-d{2,3,4}]` | Polar code, SC decoding. `-dN` is the design crossover 1e-N (default d2 = 1e-2). The design point matters enormously (see below). |
| `uep-c{C}-h{H}-l{L}` | Unequal error protection: first C bytes at BCH t=H, rest at t=L (small blocks). |
## Results (text.lz, 64 KiB windows, 200 trials/setting, hot_newyork)
Recovery rate = fraction of trials exactly recovered. Overhead is
measured (stored/data - 1). Pass-2 rescue rates are in
results/pass2-text.csv (separate, 25 trials/setting).
### Baseline: what lzply ships is nearly unprotected
| codec | ovh | BER 1e-5 | 1e-4 | 1e-3 | 3e-3 | 1e-2 | burst 256 B |
|---|---|---|---|---|---|---|---|
| bch-t2 | 0.01% | 0.11 | 0 | 0 | 0 | 0 | 0 |
| bch-t8 | 0.03% | 0.88 | 0 | 0 | 0 | 0 | 0 |
| bch-t16 | 0.06% | 1.00 | 0 | 0 | 0 | 0 | 0 |
| bch-t32 | 0.12% | 1.00 | 0.01 | 0 | 0 | 0 | 0 |
One 64 KiB blob is a single BCH block (m=20, 80 parity bytes), so
t=32 corrects 32 bit errors per 64 KiB. At BER 1e-4 the blob already
carries ~52 errors: the cliff is between 1e-5 and 1e-4.
Pass 2 (hash-gated candidates) rescues nothing in practice:
the repo's own bch_test reports t+1 recovered 0/100 and t+2
recovered 0/100; this harness's pass2 matrix (35 rows, 875 trials,
all BCH codecs) shows rescued=0 in every setting, and a targeted
sweep (pass2_diag, m=13 t=16, k=t+1..t+8) rescues 0/50 at every k. Its mechanism (residual-BM)
addresses pass-1 miscorrection, which essentially never happens
for random errors (pass 1 fails rather than miscorrecting), and
the flip-and-redecode fallback does not reach the true codeword.
Its demonstrated value is the loud-failure guarantee: 0 silent
miscorrections in 7813 checks. The matrix numbers above are
therefore the true lzply numbers with or without pass 2.
### Spending redundancy: small-block BCH
| codec | ovh | BER 1e-4 | 1e-3 | 3e-3 |
|---|---|---|---|---|
| bch1k-t8 | 1.29% | 1.00 | 0 | 0 |
| bch1k-t16 | 2.62% | 1.00 | 0.73 | 0 |
| bch1k-t32 | 5.40% | 1.00 | 1.00 | 0.01 |
Same code, 1 KiB blocks: t=32 buys survival to BER 1e-3 at 5.4%
overhead. Bursts still kill it (256 B burst: 0.00 at every t).
### Interleaving: zero-overhead burst protection (WINNER)
Byte interleave over bch1k-t32, 5.40% overhead (unchanged):
| codec | burst 16 B | 64 B | 256 B | 1024 B | 4x64 B |
|---|---|---|---|---|---|
| bch1k-t32 (no intlv) | 0 | 0 | 0 | 0 | 0 |
| intlv-d16-t32 | 1.00 | 1.00 | 0 | 0 | 0.10 |
| intlv-d32-t32 | 1.00 | 1.00 | 0 | 0 | 0.80 |
| intlv-d64-t32 | 1.00 | 1.00 | 1.00 | 0 | 1.00 |
Random-error performance is unchanged by construction (same BCH
underneath). Even at 1.29% overhead, intlv-d64-bch1k-t8 survives
64 B bursts at 1.00. Gotcha fixed en route: a short tail group
(4 blocks of 68) was the weak point and measured 0.94 on 64 B
bursts; groups now merge the tail.
### LDPC: the random-error winner (WINNER at ~11% overhead)
| codec | ovh | BER 1e-3 | 3e-3 | 1e-2 | burst 16 B |
|---|---|---|---|---|---|
| ldpc-r90 | 10.94% | 1.00 | 0.97 | 0 | 0.24 |
| ldpc-r95 | 6.25% | 0.32 | 0 | 0 | 0 |
At BER 3e-3, ldpc-r90 recovers 0.97 where bch1k-t32 recovers 0.01
— the iterative decoder's cliff sits a decade higher in BER. But
bursts kill it (a 16 B burst is ~64 errors in one 1 KiB block),
and r95 is weak: the regular (3,64) code starts failing at 6
errors/block (ldpc_diag). Irregular LDPC would be the follow-up;
LDPC+interleave would fix bursts.
### Polar SC: dominated, rejected (honest negative)
Designing for p=1e-2 gives 0.00 at BER 1e-4; designing for the
operating point (d3/d4) gives 0.90/0.95 at 1e-4 — but every variant
is 0.00 at BER 1e-3. SC at N=4096/R=0.9 is far weaker than
bch1k-t32 (1.00 at 1e-3, half the overhead) and ldpc-r90 (1.00 at
1e-3, same overhead). Two real bugs were fixed en route (SC partial
sums overwrote the leaf decisions; see polar.c). SCL list decoding
is the follow-up that could rescue polar; SC as measured is a reject.
### UEP: graceful degradation, conditional
Exact recovery is dominated by the weak tier (uep-c1024-h32-l8 at
1e-3: 0.00, same as uniform bch1k-t8). The prefix tells another
story (uep_diag, 50 trials):
| codec | BER 1e-3 whole | BER 1e-3 prefix | burst 256 B prefix |
|---|---|---|---|
| uep-c1024-h32-l8 | 0.00 | 1.00 | 1.00 |
| uep-c4096-h32-l8 | 0.00 | 1.00 | 0.94 |
The first 1-4 KiB (lzip header + stream start) survives when the
file is lost. Only useful if lzply gains a salvage mode; today the
entry SHA gates all-or-nothing extraction.
## Speed and memory (isolated, sequential, 64 KiB blob, clean)
`--speed` mode, 5 reps each. RSS is the bench process peak (harness
+ buffers ~6.5 MB); the codec delta is what matters.
| codec | enc MB/s | dec MB/s | RSS KB | ovh |
|---|---|---|---|---|
| bch-t32 | 6.46 | 3.44 | 6564 | 0.12% |
| bch1k-t8 | 9.98 | 5.87 | 6560 | 1.29% |
| bch1k-t16 | 5.39 | 3.14 | 6492 | 2.62% |
| bch1k-t32 | 2.97 | 1.55 | 6652 | 5.40% |
| intlv-d64-t32 | 3.39 | 1.73 | 6720 | 5.40% |
| intlv-d64-t8 | 11.11 | 5.80 | 6572 | 1.29% |
| ldpc-r90 | 3.34 | 0.91 | 7776 | 10.94% |
| ldpc-r95 | 5.18 | 1.16 | 7652 | 6.25% |
| polar-r90-d4 | 4.82 | 0.58 | 7252 | 11.72% |
| uep-c1024-h32-l8 | 9.96 | 4.80 | 6612 | 1.43% |
Interleaving costs nothing measurable (same speed and memory as
the BCH underneath; it is a permutation). LDPC pays a one-time
~1.8 s init (PEG + Gauss-Jordan) and decodes ~4x slower than
bch1k-t32; polar decodes slowest of all (0.58 MB/s). Failed BCH
decodes are far slower than clean ones (pass 2 dominates; matrix
rows for failed whole-blob blocks read 0.02-0.10 MB/s).
## Generalization
Cross-corpus check (bin.lz, rand.lz, 100 trials/setting, headline
codecs, BER 1e-4/1e-3 + 256 B burst + clean) reproduces text.lz
exactly for every codec and setting: bch1k-t32 1.00/1.00/0.00,
intlv-d64-t32 1.00/1.00/1.00, ldpc-r90 1.00/1.00/0.00,
polar-r90-d4 0.94/0.00/0.00, uep-c1024 1.00/0.00/0.00. Clean
round-trips are bit-identical everywhere (all clean rows 1.00).
## Test totals
- BCH matrix (text.lz): 143 rows x 200 trials = 28,600 trials
- LDPC matrix: 22 rows x 200 = 4,400
- Polar matrix: 33 rows x 200 = 6,600
- UEP matrix: 33 rows x 200 = 6,600
- Pass-2 matrix: 35 rows x 25 = 875 (rescued 0)
- Cross-corpus: 48 rows x 100 = 4,800
- Diagnostics: ldpc_diag single-block sweeps, uep_diag prefix
survival (50 trials/setting), pass2_diag targeted sweep
(t+1..t+8, 50 trials each)
- Total matrix trials: 51,875 (+ diagnostics)
- hot_chicago verification: BLOCKED — the old-VPS tunnel's SSH
leg to 104.225.223.162 failed 4 times over ~1.5 h (banner-exchange
timeout on the last attempt). Snapshot zips are staged on the
old VPS (/tmp/lzply-*.zip) for a retry when the tunnel recovers.
## Rules of this branch
- Never touch `main` or the other coordinator's branches/checkouts.
- No Reed-Solomon (the other job's territory).
- No legacy support; the format may change freely.
- Do not break the existing `-r` levels.
- Honest negatives count: a family that loses on every axis is killed
early and its numbers recorded.
- After every push: zip snapshot to /root/git-backups/lzply/ on both
servers (newest 7 kept); use /root/scripts/git-push-snapshot.sh
when present, else temp-clone + zip + copy manually.
-158
View File
@@ -1,158 +0,0 @@
/* bch_wrap.c - BCH baseline codecs for the experiments harness.
*
* Two operating points of the same code, so the harness can show the
* overhead/correction tradeoff honestly:
*
* bch-t<N> - exactly what lzply ships: bch_poly_for_data(blob, t)
* picks the smallest parent covering the WHOLE blob, so a
* 64 KiB blob is a single huge block (m=20, t=32 -> 80
* parity bytes, 0.12% overhead, 32 correctable bits per
* 64 KiB). Pass 2 (hash-gated candidates) is wired to
* recover_verified, matching entry_decode().
* bch1k-t<N> - same code, forced small blocks: pinned m=13 poly, so a
* block holds 971 data bytes (t=32 -> 5.4% overhead).
* This is the "what if we spent real redundancy" point.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
typedef struct {
int t;
const bch_poly_t *pinned; /* NULL = auto-pick (as-shipped) */
} bch_priv_t;
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
static size_t bch_encode_fn(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(len, p->t);
if (!poly)
return 0;
size_t slen = bch_encoded_len(len, poly);
uint8_t *buf = (uint8_t *)malloc(slen ? slen : 1);
if (!buf)
return 0;
if (bch_encode(data, len, poly, buf) != slen) {
free(buf);
return 0;
}
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int bch_decode_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
int corr = 0;
int rc = bch_decode(stored, slen, orig_len, poly, out, &corr);
if (corrected)
*corrected = rc == 0 ? corr : -1;
return rc;
}
static int bch_recover_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * orig_len);
if (!cands)
return -1;
int nc = bch_decode_candidates(stored, slen, orig_len, poly, cands,
BCH_PASS2_MAX_CANDS);
int found = -1;
for (int i = 0; i < nc && found < 0; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * orig_len, orig_len, h);
if (memcmp(h, want_sha, 32) == 0)
found = i;
}
if (found >= 0)
memcpy(out, cands + (size_t)found * orig_len, orig_len);
free(cands);
return found >= 0 ? 0 : -1;
}
static void bch_destroy(ecc_codec_t *c)
{
free(c->priv);
free((void *)c->name);
free(c);
}
static ecc_codec_t *bch_new(int t, const bch_poly_t *pinned, const char *name)
{
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
bch_priv_t *p = (bch_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
return NULL;
}
p->t = t;
p->pinned = pinned;
c->name = name;
c->desc = pinned ? "BCH, forced 1 KiB blocks" : "BCH as shipped in lzply";
c->block_data = pinned ? bch_max_data(pinned) : 0;
c->encode = bch_encode_fn;
c->decode = bch_decode_fn;
c->recover_verified = bch_recover_fn;
c->destroy = bch_destroy;
c->priv = p;
return c;
}
/* As-shipped: auto-pick poly for the whole blob. */
ecc_codec_t *bch_ship_new(int t)
{
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch-t%d", t);
return bch_new(t, NULL, name);
}
/* Forced small blocks: pinned m=13 poly (971 data bytes/block at any t). */
ecc_codec_t *bch_1k_new(int t)
{
const bch_poly_t *poly = poly_by_mt(13, t);
if (!poly)
return NULL;
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch1k-t%d", t);
return bch_new(t, poly, name);
}
-10
View File
@@ -1,10 +0,0 @@
/* bch_wrap.h - constructors for the BCH baseline codecs (bch_wrap.c). */
#ifndef EXP_BCH_WRAP_H
#define EXP_BCH_WRAP_H
#include "ecc_iface.h"
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
#endif /* EXP_BCH_WRAP_H */
-349
View File
@@ -1,349 +0,0 @@
/* bench.c - corruption-matrix harness for the lzply ECC experiments.
*
* One invocation = one codec x one corruption setting x N trials.
* Each trial: take a window of the corpus blob, encode it, corrupt the
* stored bytes (random bit flips at a BER, or randomized byte bursts),
* decode, and check exact recovery (memcmp + SHA-256). On decode
* failure, the codec's recover_verified hook (if any) gets one shot
* with the expected SHA -- that is how BCH pass 2 is credited.
*
* Usage:
* bench --codec NAME --blob FILE [--size N] [--trials N] [--seed S]
* (--ber X | --burst LEN,COUNT | --clean | --speed)
* [--out results.csv]
*
* CSV (appended to --out, or stdout if omitted):
* codec,corpus,blob_size,trials,mode,param,success,rescued,rate,
* enc_MBps,dec_MBps,peak_rss_kb,overhead_pct
*
* Exit 0 on a completed run (even if recovery is 0 -- that is data),
* 2 on usage/codec errors.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
#include <libgen.h>
#include <sys/resource.h>
#include "ecc_iface.h"
#include "sha256.h"
/* ---- codec factory (one constructor per family file) ---- */
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
ecc_codec_t *interleave_new(int depth, int t);
ecc_codec_t *ldpc_new(int rate_pct);
ecc_codec_t *polar_new(int rate_pct, int design_exp);
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
static ecc_codec_t *make_codec(const char *name)
{
int v;
if (sscanf(name, "bch-t%d", &v) == 1)
return bch_ship_new(v);
if (sscanf(name, "bch1k-t%d", &v) == 1)
return bch_1k_new(v);
int d, t;
if (sscanf(name, "intlv-d%d-bch1k-t%d", &d, &t) == 2)
return interleave_new(d, t);
if (sscanf(name, "ldpc-r%d", &v) == 1)
return ldpc_new(v);
int dexp;
if (sscanf(name, "polar-r%d-d%d", &v, &dexp) == 2)
return polar_new(v, dexp);
if (sscanf(name, "polar-r%d", &v) == 1)
return polar_new(v, 2);
int cb, th, tl;
if (sscanf(name, "uep-c%d-h%d-l%d", &cb, &th, &tl) == 3)
return uep_new(cb, th, tl);
return NULL;
}
/* ---- xorshift64* RNG ---- */
static uint64_t rs = 0x12345678abcdefULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static uint8_t *read_file(const char *path, size_t *len_out)
{
FILE *f = fopen(path, "rb");
if (!f)
return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n <= 0) {
fclose(f);
return NULL;
}
uint8_t *buf = (uint8_t *)malloc((size_t)n);
if (!buf) {
fclose(f);
return NULL;
}
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
free(buf);
fclose(f);
return NULL;
}
fclose(f);
*len_out = (size_t)n;
return buf;
}
static void usage(void)
{
fprintf(stderr,
"usage: bench --codec NAME --blob FILE [--size N] [--trials N]\n"
" [--seed S] (--ber X | --burst LEN,COUNT | --clean | --speed)\n"
" [--out results.csv]\n"
" codecs: bch-t{2,4,8,16,32} bch1k-t{8,16,32}\n"
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n"
" polar-r{90,95} uep-c{1024,4096}-h{16,32}-l{2,4}\n");
}
int main(int argc, char **argv)
{
const char *codec_name = NULL, *blob_path = NULL, *out_path = NULL;
size_t win_size = 65536;
long trials = 200;
uint64_t seed = 0x12345678abcdefULL;
enum { M_BER, M_BURST, M_CLEAN, M_SPEED } mode = M_BER;
double ber = 1e-3;
long burst_len = 256, burst_count = 1;
int nopass2 = 0;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--codec") && i + 1 < argc)
codec_name = argv[++i];
else if (!strcmp(argv[i], "--blob") && i + 1 < argc)
blob_path = argv[++i];
else if (!strcmp(argv[i], "--out") && i + 1 < argc)
out_path = argv[++i];
else if (!strcmp(argv[i], "--size") && i + 1 < argc)
win_size = (size_t)strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--trials") && i + 1 < argc)
trials = strtol(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
seed = strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--ber") && i + 1 < argc) {
mode = M_BER;
ber = strtod(argv[++i], NULL);
} else if (!strcmp(argv[i], "--burst") && i + 1 < argc) {
mode = M_BURST;
char *a = argv[++i];
burst_len = strtol(a, NULL, 0);
char *comma = strchr(a, ',');
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
} else if (!strcmp(argv[i], "--nopass2")) {
nopass2 = 1;
} else if (!strcmp(argv[i], "--clean")) {
mode = M_CLEAN;
} else if (!strcmp(argv[i], "--speed")) {
mode = M_SPEED;
} else {
usage();
return 2;
}
}
if (!codec_name || !blob_path) {
usage();
return 2;
}
size_t file_len = 0;
uint8_t *file = read_file(blob_path, &file_len);
if (!file || file_len <= win_size) {
fprintf(stderr, "bench: cannot read blob %s (need > %zu bytes)\n",
blob_path, win_size);
return 2;
}
rs = seed ^ 0x9e3779b97f4a7c15ULL;
double t0 = now_s();
ecc_codec_t *c = make_codec(codec_name);
double init_s = now_s() - t0;
if (!c) {
fprintf(stderr, "bench: unknown codec %s\n", codec_name);
return 2;
}
const char *corpus = strrchr(blob_path, '/');
corpus = corpus ? corpus + 1 : blob_path;
uint8_t *win = (uint8_t *)malloc(win_size);
uint8_t *stored = NULL, *rx = NULL, *out = NULL;
uint8_t want_sha[32];
if (!win) return 2;
out = (uint8_t *)malloc(win_size);
if (!out) return 2;
long success = 0, rescued = 0;
double enc_s = 0, dec_s = 0;
double overhead = 0;
int have_overhead = 0;
if (mode == M_SPEED) {
/* encode/decode the whole file in windows, 5 passes */
long passes = 5;
size_t nw = file_len / win_size;
double te0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
free(stored);
stored = NULL;
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
if (!sl) {
fprintf(stderr, "bench: encode failed in speed mode\n");
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
}
double te1 = now_s();
double td0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
long corr = -1;
if (c->decode(c, stored, sl, win_size, out, &corr) != 0 ||
memcmp(out, file + w * win_size, win_size) != 0) {
fprintf(stderr, "bench: speed-mode roundtrip FAILED\n");
return 2;
}
}
double td1 = now_s();
double bytes = (double)passes * nw * win_size;
double enc_mb = bytes / (te1 - te0) / 1e6;
double dec_mb = bytes / (td1 - td0) / 1e6;
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
fprintf(stderr,
"SPEED %-28s corpus=%s win=%zu init=%.2fs enc=%.1f MB/s "
"dec=%.1f MB/s rss=%ld KiB overhead=%.2f%%\n",
codec_name, corpus, win_size, init_s, enc_mb, dec_mb,
ru.ru_maxrss, overhead * 100.0);
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,speed,init=%.2fs,0,0,1.000,"
"%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, passes, init_s, enc_mb,
dec_mb, ru.ru_maxrss, overhead * 100.0);
if (f != stdout)
fclose(f);
}
return 0;
}
/* corruption trials */
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
rx = (uint8_t *)malloc(1 << 20); /* grown below if needed */
for (long tr = 0; tr < trials; tr++) {
size_t off = (size_t)(xr() % (file_len - win_size + 1));
memcpy(win, file + off, win_size);
lzply_sha256(win, win_size, want_sha);
double te0 = now_s();
size_t slen = c->encode(c, win, win_size, &stored);
double te1 = now_s();
if (!slen) {
fprintf(stderr, "bench: encode failed trial %ld\n", tr);
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
if (tr == 0) {
free(rx);
rx = (uint8_t *)malloc(slen);
if (!rx)
return 2;
}
memcpy(rx, stored, slen);
/* corrupt the stored bytes */
if (mode == M_BER) {
for (size_t i = 0; i < slen; i++) {
uint8_t m = 0;
for (int b = 0; b < 8; b++)
if (xr() < ber_thr)
m |= (uint8_t)(1u << b);
rx[i] ^= m;
}
} else if (mode == M_BURST) {
for (long b = 0; b < burst_count; b++) {
if ((size_t)burst_len >= slen)
continue;
size_t start = (size_t)(xr() % (slen - (size_t)burst_len + 1));
for (long k = 0; k < burst_len; k++)
rx[start + k] = (uint8_t)(xr() & 0xff);
}
}
double td0 = now_s();
long corr = -1;
int rc = c->decode(c, rx, slen, win_size, out, &corr);
int ok = (rc == 0 && memcmp(out, win, win_size) == 0);
if (!ok && !nopass2 && c->recover_verified) {
if (c->recover_verified(c, rx, slen, win_size, want_sha, out) == 0) {
ok = 1;
rescued++;
}
}
double td1 = now_s();
enc_s += te1 - te0;
dec_s += td1 - td0;
if (ok)
success++;
free(stored);
stored = NULL;
}
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
double rate = trials ? (double)success / (double)trials : 0;
double enc_mb = enc_s > 0 ? (double)trials * win_size / enc_s / 1e6 : 0;
double dec_mb = dec_s > 0 ? (double)trials * win_size / dec_s / 1e6 : 0;
char param[64];
if (mode == M_BER)
snprintf(param, sizeof param, "ber=%g", ber);
else if (mode == M_BURST)
snprintf(param, sizeof param, "burst=%ldx%ld", burst_len, burst_count);
else
snprintf(param, sizeof param, "clean");
const char *mname =
mode == M_BER ? "ber" : mode == M_BURST ? "burst" : "clean";
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,%s,%s,%ld,%ld,%.4f,%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, trials, mname, param, success,
rescued, rate, enc_mb, dec_mb, ru.ru_maxrss,
overhead * 100.0);
if (f != stdout)
fclose(f);
}
fprintf(stderr, "%-28s %-12s %-14s %4ld trials rate=%.3f rescued=%ld "
"enc=%.0fMB/s dec=%.0fMB/s ovh=%.2f%% rss=%ldKiB\n",
codec_name, corpus, param, trials, rate, rescued, enc_mb, dec_mb,
overhead * 100.0, ru.ru_maxrss);
return 0;
}
-40
View File
@@ -1,40 +0,0 @@
/* ecc_iface.h - generic error-correction codec interface for the lzply
* experiments harness (exp/). Every family under test implements this
* interface so bench.c measures them all the same way: encode a blob,
* corrupt the stored bytes, decode, and check exact recovery (SHA-256).
*
* A codec is a whole-blob transform: encode(data) -> stored bytes,
* decode(stored) -> data or failure. Block structure inside is the
* codec's business; the harness only sees blob in / blob out.
*/
#ifndef EXP_ECC_IFACE_H
#define EXP_ECC_IFACE_H
#include <stddef.h>
#include <stdint.h>
typedef struct ecc_codec ecc_codec_t;
struct ecc_codec {
const char *name; /* short id, e.g. "bch-t32" (used in CSV output) */
const char *desc; /* human-readable description */
size_t block_data; /* nominal data bytes per code block (0 = whole blob) */
/* encode data[0..len) -> malloc'd *out; return stored length, 0 on error.
Sets c->overhead = stored/len - 1. */
size_t (*encode)(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out);
/* decode stored[0..slen) -> out[0..orig_len); 0 = exact recovery,
-1 = failure. *corrected = bits/symbols corrected if known, else -1. */
int (*decode)(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected);
/* Optional second-chance recovery: given the expected SHA-256 of the
original data, try harder (e.g. BCH pass-2 candidates) and use the
first candidate that verifies. 0 = rescued, -1 = not. May be NULL. */
int (*recover_verified)(ecc_codec_t *c, const uint8_t *stored,
size_t slen, size_t orig_len,
const uint8_t want_sha[32], uint8_t *out);
double overhead; /* from the last encode() call */
void (*destroy)(ecc_codec_t *c);
void *priv;
};
#endif /* EXP_ECC_IFACE_H */
-253
View File
@@ -1,253 +0,0 @@
/* interleave.c - byte interleaver over small-block BCH.
*
* The encoded stream (bch1k-t{T}: blocks of ~1 KiB data, t parity bits
* each) is permuted before it hits the channel: the stream is cut into
* groups of D consecutive blocks, each group written row-wise into a
* D-row matrix (row j = block j) and read out column-wise. A burst of
* L consecutive bytes in the channel then hits any one block at most
* ceil(L/D) bytes -- about 4*L/D bit errors, since a randomized byte
* flips ~4 bits -- instead of all L bytes landing in one block and
* killing it outright. Zero extra parity: the interleaver is a pure
* permutation, inverted on decode, so overhead is exactly the BCH
* overhead and random-error performance is unchanged. The win is
* purely burst tolerance, roughly a factor D in burst length.
*
* Groups are self-delimiting: block boundaries are recomputed from
* orig_len, so the decoder knows every group's shape. The final group
* may be short and the final block short; the column traversal simply
* skips missing cells, which keeps the permutation exact with no
* padding and no length change.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_wrap.h"
typedef struct {
ecc_codec_t *inner; /* bch1k-t{T} */
int depth; /* blocks per interleave group */
int t;
} intlv_priv_t;
/* Permute the encoded stream (forward = interleave).
* blocks[] holds the stored length of each block; nblocks total.
* out must hold the same total length.
*
* Groups: blocks are cut into groups of `depth`, EXCEPT the final
* partial group is merged into the previous one instead of standing
* alone. A tiny tail group is the weak point: a burst landing in a
* 4-block tail hits each of its blocks with L/4 bytes instead of
* L/64, which is exactly why the first measurement showed 0.94
* instead of 1.00 on 64-byte bursts (the 68-block blob ends in a
* 4-block tail). Merging makes every group >= depth (the last may
* exceed it); when nblocks <= depth there is a single group. */
static void permute(const uint8_t *in, uint8_t *out, const size_t *blocks,
size_t nblocks, int depth, int forward)
{
size_t *start = (size_t *)malloc((nblocks + 1) * sizeof(size_t));
if (!start)
return;
start[0] = 0;
for (size_t i = 0; i < nblocks; i++)
start[i + 1] = start[i] + blocks[i];
/* group boundaries: groups of `depth`, last partial group merged
into the previous one */
size_t g0 = 0;
while (g0 < nblocks) {
size_t remain = nblocks - g0;
size_t g = remain < (size_t)depth ? remain : (size_t)depth;
/* If this would leave a short tail after this group, extend
this group to absorb the tail. (Invariant: a short tail
never survives an iteration, so no group is ever < depth
except when the whole blob is.) */
if (remain > (size_t)depth && remain - (size_t)depth < (size_t)depth)
g = remain;
size_t maxlen = 0;
for (size_t j = 0; j < g; j++)
if (blocks[g0 + j] > maxlen)
maxlen = blocks[g0 + j];
size_t goff = start[g0];
size_t pos = 0;
for (size_t c = 0; c < maxlen; c++) {
for (size_t j = 0; j < g; j++) {
if (c >= blocks[g0 + j])
continue;
size_t src = start[g0 + j] + c;
size_t dst = goff + pos;
if (forward)
out[dst] = in[src];
else
out[src] = in[dst];
pos++;
}
}
g0 += g;
}
free(start);
}
static size_t intlv_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
uint8_t *enc = NULL;
size_t slen = p->inner->encode(p->inner, data, len, &enc);
if (!slen)
return 0;
/* block layout of the inner encoding */
size_t bd = p->inner->block_data;
size_t nblocks = (len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks) {
free(enc);
return 0;
}
/* stored length of block i: full blocks first, last may be short.
The inner codec is bch_encode with a pinned poly, so stored
length is a pure function of the block's data length. Recover
it by splitting slen: all full blocks share one length. */
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = len - i * bd < bd ? len - i * bd : bd;
/* stored bytes for dlen data bytes under the pinned poly:
ceil((8*dlen + r)/8); r = t*13 for m=13 */
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) { /* should not happen; bail out cleanly */
free(blocks);
free(enc);
return 0;
}
uint8_t *buf = (uint8_t *)malloc(slen);
if (!buf) {
free(blocks);
free(enc);
return 0;
}
permute(enc, buf, blocks, nblocks, p->depth, 1);
free(blocks);
free(enc);
c->overhead = p->inner->overhead;
*out = buf;
return slen;
}
static int intlv_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->decode(p->inner, deint, slen, orig_len, out,
corrected);
free(deint);
return rc;
}
static int intlv_recover(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->recover_verified
? p->inner->recover_verified(p->inner, deint, slen, orig_len,
want_sha, out)
: -1;
free(deint);
return rc;
}
static void intlv_destroy(ecc_codec_t *c)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
if (p->inner)
p->inner->destroy(p->inner);
free(p);
free((void *)c->name);
free(c);
}
ecc_codec_t *interleave_new(int depth, int t)
{
ecc_codec_t *inner = bch_1k_new(t);
if (!inner)
return NULL;
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
intlv_priv_t *p = (intlv_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
char *name = (char *)malloc(32);
if (!name) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
snprintf(name, 32, "intlv-d%d-bch1k-t%d", depth, t);
p->inner = inner;
p->depth = depth;
p->t = t;
c->name = name;
c->desc = "byte interleaver over small-block BCH";
c->block_data = inner->block_data;
c->encode = intlv_encode;
c->decode = intlv_decode;
c->recover_verified = intlv_recover;
c->destroy = intlv_destroy;
c->priv = p;
return c;
}
-565
View File
@@ -1,565 +0,0 @@
/* ldpc.c - regular LDPC codec for the experiments harness.
*
* Two operating points, both n=8192 bits, column weight 3:
* ldpc-r90: m=768 checks, row weight 32, k=7424 bits (928 B),
* rate 0.90625, overhead 10.34%.
* ldpc-r95: m=384 checks, row weight 64, k=7808 bits (976 B),
* rate 0.953125, overhead 4.92%.
*
* Construction: random regular parity-check matrix (configuration
* model with 4-cycle rejection), fixed seed, so the code is identical
* on every run and every server. Systematic encoding by Gauss-Jordan
* reduction of H to [I | P] (one-time, at codec creation); decoding
* is normalized min-sum belief propagation (factor 0.8), max 50
* iterations, early stop when the syndrome is zero. Channel LLR uses
* a fixed nominal crossover p0 = 1e-3 (the decoder does not know the
* true BER; this is the honest setting for a storage channel).
*
* A blob is split into blocks of k data bytes; the last block is
* zero-padded to k bytes (padding is discarded on decode). Stored
* length per block is exactly n/8 = 1024 bytes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ecc_iface.h"
#define LDPC_N 8192
#define LDPC_WC 3
#define LDPC_MAX_ITER 50
#define LDPC_MS_NORM 0.8f
#define LDPC_P0 1e-3
typedef struct {
int m; /* checks */
int wr; /* row weight */
int k; /* data bits */
int kbytes; /* data bytes per block */
int nedges;
int *chk_var; /* m * wr: vars of each check */
int *var_chk; /* n * wc: checks of each var */
int *chk_edge; /* m * wr: edge id (var*wc+w) of each check entry */
int *pivot_col; /* m: pivot column of each RREF row */
uint64_t *enc_rows; /* m * kwords: RREF rows over data positions */
int kwords;
int *col_of_dp; /* k: column holding data position i */
float *msg_vc; /* var->check, nedges */
float *msg_cv; /* check->var, nedges */
float *llr_ch; /* n */
uint8_t *hard; /* n */
} ldpc_t;
static void free_ldpc(ldpc_t *L)
{
if (!L)
return;
free(L->chk_var);
free(L->var_chk);
free(L->chk_edge);
free(L->pivot_col);
free(L->enc_rows);
free(L->col_of_dp);
free(L->msg_vc);
free(L->msg_cv);
free(L->llr_ch);
free(L->hard);
free(L);
}
static uint64_t lrs = 0x243f6a8885a308d3ULL;
static inline uint64_t lxr(void)
{
lrs ^= lrs << 13;
lrs ^= lrs >> 7;
lrs ^= lrs << 17;
return lrs;
}
/* ---- construction: progressive edge growth (PEG) ----
* Edge by edge, each new edge of variable node v connects to the
* check node farthest from v in the graph built so far (unreached
* checks count as infinitely far), tie-broken by lowest check degree.
* PEG never deadlocks (there is always a farthest check) and
* maximizes girth by construction -- unlike greedy 4-cycle
* rejection, which stalls in the endgame when the remaining stub
* rows all close short cycles. Fallback: if every farthest check is
* already full (cannot happen with balanced degrees, but be safe),
* take the lowest-degree check overall. */
static int build_H(ldpc_t *L, uint64_t seed)
{
int m = L->m, n = LDPC_N, wc = LDPC_WC, wr = L->wr;
int *chk_deg = (int *)calloc((size_t)m, sizeof(int));
int *var_deg = (int *)calloc((size_t)n, sizeof(int));
int *dist = (int *)malloc((size_t)(n + m) * sizeof(int));
int *queue = (int *)malloc((size_t)(n + m) * sizeof(int));
if (!chk_deg || !var_deg || !dist || !queue) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
lrs = seed;
(void)lxr; /* seed only matters for tie-breaking below */
for (int v = 0; v < n; v++) {
for (int e = 0; e < wc; e++) {
/* BFS from v over the graph built so far. Node ids:
0..n-1 variables, n..n+m-1 checks. */
for (int i = 0; i < n + m; i++)
dist[i] = -1;
int qh = 0, qt = 0;
dist[v] = 0;
queue[qt++] = v;
int found_checks = 0;
while (qh < qt && found_checks < m) {
int u = queue[qh++];
int d = dist[u];
if (u < n) {
for (int w = 0; w < var_deg[u]; w++) {
int nid = n + L->var_chk[u * wc + w];
if (dist[nid] < 0) {
dist[nid] = d + 1;
queue[qt++] = nid;
found_checks++;
}
}
} else {
int ch = u - n;
for (int k = 0; k < chk_deg[ch]; k++) {
int vv = L->chk_var[ch * wr + k];
if (dist[vv] < 0) {
dist[vv] = d + 1;
queue[qt++] = vv;
}
}
}
}
/* farthest distance among reached checks (-1 = unreached) */
int bestd = -2, have_unreached = 0;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
if (d < 0) {
have_unreached = 1;
} else if (d > bestd) {
bestd = d;
}
}
int best = -1, bestdeg = wr + 1;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
int far = have_unreached ? (d < 0) : (d == bestd);
if (!far)
continue;
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
/* fallback: lowest-degree check anywhere */
for (int ch = 0; ch < m; ch++)
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
L->var_chk[v * wc + var_deg[v]++] = best;
L->chk_var[best * wr + chk_deg[best]++] = v;
}
}
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return 0;
}
/* ---- Gauss-Jordan: H -> RREF, record pivot columns + enc rows ---- */
static int gauss_jordan(ldpc_t *L)
{
int m = L->m, n = LDPC_N;
int words = (n + 63) / 64;
uint64_t *H = (uint64_t *)calloc((size_t)m * words, sizeof(uint64_t));
if (!H)
return -1;
for (int r = 0; r < m; r++)
for (int k = 0; k < L->wr; k++) {
int c = L->chk_var[r * L->wr + k];
H[(size_t)r * words + c / 64] |= 1ULL << (c % 64);
}
int prow = 0;
for (int col = 0; col < n && prow < m; col++) {
int sel = -1;
for (int r = prow; r < m; r++)
if ((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL) {
sel = r;
break;
}
if (sel < 0)
continue;
if (sel != prow) {
for (int w = 0; w < words; w++) {
uint64_t t = H[(size_t)sel * words + w];
H[(size_t)sel * words + w] = H[(size_t)prow * words + w];
H[(size_t)prow * words + w] = t;
}
}
for (int r = 0; r < m; r++) {
if (r != prow &&
((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL)) {
for (int w = 0; w < words; w++)
H[(size_t)r * words + w] ^=
H[(size_t)prow * words + w];
}
}
L->pivot_col[prow++] = col;
}
if (prow != m) {
free(H);
return -1; /* H not full rank */
}
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot) {
free(H);
return -1;
}
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
L->col_of_dp = (int *)malloc((size_t)L->k * sizeof(int));
if (!L->col_of_dp) {
free(H);
free(is_pivot);
return -1;
}
int dp = 0;
for (int c = 0; c < n; c++)
if (!is_pivot[c])
L->col_of_dp[dp++] = c;
if (dp != L->k) {
free(H);
free(is_pivot);
return -1;
}
L->kwords = (L->k + 63) / 64;
L->enc_rows = (uint64_t *)calloc((size_t)m * L->kwords,
sizeof(uint64_t));
if (!L->enc_rows) {
free(H);
free(is_pivot);
return -1;
}
int *data_pos = (int *)malloc((size_t)n * sizeof(int));
if (!data_pos) {
free(H);
free(is_pivot);
return -1;
}
dp = 0;
for (int c = 0; c < n; c++)
data_pos[c] = is_pivot[c] ? -1 : dp++;
for (int i = 0; i < m; i++) {
for (int c = 0; c < n; c++) {
if (is_pivot[c])
continue;
if ((H[(size_t)i * words + c / 64] >> (c % 64)) & 1ULL) {
int p = data_pos[c];
L->enc_rows[(size_t)i * L->kwords + p / 64] |=
1ULL << (p % 64);
}
}
}
free(data_pos);
free(H);
free(is_pivot);
return 0;
}
/* bit helpers: MSB-first within each byte */
static inline int get_bit(const uint8_t *buf, int i)
{
return (buf[i / 8] >> (7 - (i % 8))) & 1;
}
static inline void set_bit(uint8_t *buf, int i, int v)
{
if (v)
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
else
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
}
static size_t ldpc_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
size_t slen = nblocks * (LDPC_N / 8);
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
if (!buf)
return 0;
uint8_t *dbytes = (uint8_t *)calloc((size_t)L->kbytes, 1);
uint64_t *dw = (uint64_t *)malloc((size_t)L->kwords * sizeof(uint64_t));
if (!dbytes || !dw) {
free(buf);
free(dbytes);
free(dw);
return 0;
}
for (size_t b = 0; b < nblocks; b++) {
size_t dlen = len - b * (size_t)L->kbytes < (size_t)L->kbytes
? len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memset(dbytes, 0, (size_t)L->kbytes);
memcpy(dbytes, data + b * (size_t)L->kbytes, dlen);
/* data as words, bit i of the block -> word i/64, bit i%64 */
memset(dw, 0, (size_t)L->kwords * sizeof(uint64_t));
for (int i = 0; i < L->k; i++)
if (get_bit(dbytes, i))
dw[i / 64] |= 1ULL << (i % 64);
uint8_t *cw = buf + b * (LDPC_N / 8);
for (int i = 0; i < L->k; i++)
set_bit(cw, L->col_of_dp[i], get_bit(dbytes, i));
for (int i = 0; i < L->m; i++) {
const uint64_t *row = L->enc_rows + (size_t)i * L->kwords;
int acc = 0;
for (int w = 0; w < L->kwords; w++)
acc ^= __builtin_parityll(row[w] & dw[w]);
set_bit(cw, L->pivot_col[i], acc);
}
}
free(dbytes);
free(dw);
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int ldpc_decode_block(ldpc_t *L, const uint8_t *cw_in,
uint8_t *data_out, long *corrected_out)
{
int n = LDPC_N, m = L->m, wc = LDPC_WC, wr = L->wr;
float L0 = (float)log((1.0 - LDPC_P0) / LDPC_P0);
for (int i = 0; i < n; i++) {
L->llr_ch[i] = get_bit(cw_in, i) ? -L0 : L0;
for (int w = 0; w < wc; w++)
L->msg_vc[i * wc + w] = L->llr_ch[i];
}
int converged = 0;
for (int it = 0; it < LDPC_MAX_ITER && !converged; it++) {
/* check update: two-minimum min-sum, via chk_edge ids */
for (int j = 0; j < m; j++) {
float min1 = 1e30f, min2 = 1e30f;
int argmin1 = -1, sign = 1;
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
float a = fabsf(x);
if (a < min1) {
min2 = min1;
min1 = a;
argmin1 = k;
} else if (a < min2) {
min2 = a;
}
if (x < 0)
sign = -sign;
}
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
int s = sign;
if (x < 0)
s = -s;
float mag = (k == argmin1 ? min2 : min1) * LDPC_MS_NORM;
L->msg_cv[e] = s > 0 ? mag : -mag;
}
}
/* hard decision + syndrome check */
converged = 1;
for (int i = 0; i < n; i++) {
float tot = L->llr_ch[i];
for (int w = 0; w < wc; w++)
tot += L->msg_cv[i * wc + w];
L->hard[i] = tot < 0 ? 1 : 0;
}
for (int j = 0; j < m; j++) {
int p = 0;
for (int k = 0; k < wr; k++)
p ^= L->hard[L->chk_var[j * wr + k]];
if (p) {
converged = 0;
break;
}
}
if (converged)
break;
/* var->check messages for the next iteration */
for (int i = 0; i < n; i++)
for (int w = 0; w < wc; w++) {
float tot = L->llr_ch[i];
for (int w2 = 0; w2 < wc; w2++)
if (w2 != w)
tot += L->msg_cv[i * wc + w2];
L->msg_vc[i * wc + w] = tot;
}
}
if (!converged)
return -1;
long corr = 0;
for (int i = 0; i < n; i++)
if (L->hard[i] != get_bit(cw_in, i))
corr++;
if (corrected_out)
*corrected_out = corr;
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot)
return -1;
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
int dp = 0;
memset(data_out, 0, (size_t)L->kbytes);
for (int col = 0; col < n; col++)
if (!is_pivot[col])
set_bit(data_out, dp++, L->hard[col]);
free(is_pivot);
return 0;
}
static int ldpc_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (orig_len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
if (slen != nblocks * (LDPC_N / 8))
return -1;
long corr = 0;
for (size_t b = 0; b < nblocks; b++) {
uint8_t *db = (uint8_t *)malloc((size_t)L->kbytes);
if (!db)
return -1;
long bc = 0;
int rc = ldpc_decode_block(L, stored + b * (LDPC_N / 8), db, &bc);
if (rc != 0) {
free(db);
if (corrected)
*corrected = -1;
return -1;
}
corr += bc;
size_t dlen = orig_len - b * (size_t)L->kbytes < (size_t)L->kbytes
? orig_len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memcpy(out + b * (size_t)L->kbytes, db, dlen);
free(db);
}
if (corrected)
*corrected = corr;
return 0;
}
static void ldpc_destroy(ecc_codec_t *c)
{
ldpc_t *L = (ldpc_t *)c->priv;
free_ldpc(L);
free((void *)c->name);
free(c);
}
ecc_codec_t *ldpc_new(int rate_pct)
{
int m, wr;
const char *tag;
if (rate_pct == 90) {
m = 768;
wr = 32;
tag = "ldpc-r90";
} else if (rate_pct == 95) {
m = 384;
wr = 64;
tag = "ldpc-r95";
} else {
return NULL;
}
ldpc_t *L = (ldpc_t *)calloc(1, sizeof(*L));
if (!L)
return NULL;
L->m = m;
L->wr = wr;
L->k = LDPC_N - m;
L->kbytes = L->k / 8;
L->nedges = LDPC_N * LDPC_WC;
L->chk_var = (int *)malloc((size_t)m * wr * sizeof(int));
L->var_chk = (int *)malloc((size_t)LDPC_N * LDPC_WC * sizeof(int));
L->chk_edge = (int *)malloc((size_t)m * wr * sizeof(int));
L->pivot_col = (int *)malloc((size_t)m * sizeof(int));
L->msg_vc = (float *)malloc((size_t)L->nedges * sizeof(float));
L->msg_cv = (float *)malloc((size_t)L->nedges * sizeof(float));
L->llr_ch = (float *)malloc((size_t)LDPC_N * sizeof(float));
L->hard = (uint8_t *)malloc((size_t)LDPC_N);
if (!L->chk_var || !L->var_chk || !L->chk_edge || !L->pivot_col ||
!L->msg_vc || !L->msg_cv || !L->llr_ch || !L->hard) {
free_ldpc(L);
return NULL;
}
int ok = -1;
int attempt_used = -1;
for (int attempt = 0; attempt < 10 && ok != 0; attempt++) {
ok = build_H(L, 0x9e3779b97f4a7c15ULL +
(uint64_t)attempt * 0x100000001b3ULL);
attempt_used = attempt;
}
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: build_H ok=%d attempts=%d\n", ok,
attempt_used + 1);
if (ok != 0) {
free_ldpc(L);
return NULL;
}
int gj = gauss_jordan(L);
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: gauss_jordan=%d\n", gj);
if (gj != 0) {
free_ldpc(L);
return NULL;
}
/* edge ids for the decoder: chk_edge[j*wr+k] = var*wc+w */
for (int j = 0; j < m; j++)
for (int k = 0; k < wr; k++) {
int v = L->chk_var[j * wr + k];
int e = -1;
for (int w = 0; w < LDPC_WC; w++)
if (L->var_chk[v * LDPC_WC + w] == j)
e = v * LDPC_WC + w;
L->chk_edge[j * wr + k] = e;
}
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
if (!c) {
free_ldpc(L);
return NULL;
}
char *name = (char *)malloc(16);
if (!name) {
free_ldpc(L);
free(c);
return NULL;
}
snprintf(name, 16, "%s", tag);
c->name = name;
c->desc = "regular LDPC, min-sum belief propagation";
c->block_data = (size_t)L->kbytes;
c->encode = ldpc_encode;
c->decode = ldpc_decode;
c->recover_verified = NULL;
c->destroy = ldpc_destroy;
c->priv = L;
return c;
}
-71
View File
@@ -1,71 +0,0 @@
/* ldpc_diag.c - diagnostic for the LDPC codec (NOT part of bench).
* Encodes one fixed block, flips exactly k bits (k = 0..KMAX), decodes,
* and reports the failure count per k. This separates "decoder bug"
* (fails even at k=1..3) from "code weakness" (fails only near the
* expected threshold). Usage: ldpc_diag <r90|r95> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ecc_iface.h"
ecc_codec_t *ldpc_new(int rate_pct);
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
int main(int argc, char **argv)
{
int rate = 90;
int kmax = 24, trials = 100;
if (argc > 1)
rate = atoi(argv[1] + 1); /* "r90" -> 90 */
if (argc > 2)
kmax = atoi(argv[2]);
if (argc > 3)
trials = atoi(argv[3]);
ecc_codec_t *c = ldpc_new(rate);
if (!c) {
fprintf(stderr, "ldpc_new failed\n");
return 2;
}
size_t dlen = c->block_data;
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *out = (uint8_t *)malloc(dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
uint8_t *stored = NULL;
size_t slen = c->encode(c, data, dlen, &stored);
if (!slen) {
fprintf(stderr, "encode failed\n");
return 2;
}
printf("rate=%d block_data=%zu stored=%zu overhead=%.2f%%\n", rate,
dlen, slen, c->overhead * 100.0);
uint8_t *rx = (uint8_t *)malloc(slen);
for (int k = 0; k <= kmax; k++) {
int fails = 0;
for (int t = 0; t < trials; t++) {
memcpy(rx, stored, slen);
/* flip k distinct random bits */
for (int f = 0; f < k; f++) {
size_t p = (size_t)(xr() % (slen * 8));
rx[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
}
long corr = -1;
int rc = c->decode(c, rx, slen, dlen, out, &corr);
if (rc != 0 || memcmp(out, data, dlen) != 0)
fails++;
}
printf("k=%2d fails=%d/%d\n", k, fails, trials);
fflush(stdout);
}
return 0;
}
-27
View File
@@ -1,27 +0,0 @@
#!/bin/bash
# mkcorpora.sh - build the experiment corpora in exp/corpora/.
# text.raw / text.lz : English-ish text (docs + sources)
# bin.raw / bin.lz : ELF binaries
# rand.raw / rand.lz : seeded pseudo-random bytes (incompressible)
# lz files are lzip -9 of the raw files: that is what lzply actually
# protects (the compressed blob), plus the raw files for stored entries.
set -e
cd "$(dirname "$0")/corpora"
# text: repo docs/sources + system docs
{ find /opt/lzply-exp-ecc -name "*.md" -o -name "*.c" -o -name "*.h" | sort | xargs cat
find /usr/share/doc -type f -size -200k 2>/dev/null | head -200 | sort | xargs cat 2>/dev/null
find /usr/include -name "*.h" 2>/dev/null | head -300 | sort | xargs cat 2>/dev/null
} > text.raw
head -c 4194304 text.raw > text4m.raw && mv text4m.raw text.raw
# binaries: ELF files from /bin and /usr/bin
{ for f in /bin/* /usr/bin/*; do
[ -f "$f" ] && head -c1 "$f" | grep -q . && file "$f" 2>/dev/null | grep -q ELF && cat "$f"
done
} > bin.raw 2>/dev/null
head -c 4194304 bin.raw > bin4m.raw && mv bin4m.raw bin.raw
# random: seeded python (reproducible on both servers)
python3 -c "import random; random.seed(1234); open(\"rand.raw\",\"wb\").write(bytes(random.getrandbits(8) for _ in range(4194304)))"
for f in text bin rand; do
lzip -9 -f -c "$f.raw" > "$f.lz" 2>/dev/null || lzip -9 -c "$f.raw" > "$f.lz"
done
ls -la
-89
View File
@@ -1,89 +0,0 @@
/* pass2_diag.c - targeted test of BCH pass-2 (hash-gated candidates).
* Encodes one bch1k block, flips exactly k bits (k around t), and
* reports: pass-1 success, and pass-2 rescue (candidate verifies
* against the SHA-256 of the original). This separates "pass 2 is
* weak" from "the harness wiring is broken".
* Usage: pass2_diag <t> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
int main(int argc, char **argv)
{
int t = argc > 1 ? atoi(argv[1]) : 16;
int kmax = argc > 2 ? atoi(argv[2]) : t + 8;
int trials = argc > 3 ? atoi(argv[3]) : 50;
const bch_poly_t *p = poly_by_mt(13, t);
if (!p) {
fprintf(stderr, "no poly m=13 t=%d\n", t);
return 2;
}
size_t dlen = bch_max_data(p);
size_t slen = bch_block_stored_len(dlen, p);
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *stored = (uint8_t *)malloc(slen);
uint8_t *rx = (uint8_t *)malloc(slen);
uint8_t *out = (uint8_t *)malloc(dlen);
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
if (bch_encode_block(data, dlen, p, stored) != 0) {
fprintf(stderr, "encode failed\n");
return 2;
}
uint8_t want[32];
lzply_sha256(data, dlen, want);
printf("t=%d block_data=%zu stored=%zu\n", t, dlen, slen);
for (int k = t - 2; k <= kmax; k++) {
int p1 = 0, rescued = 0;
for (int tr = 0; tr < trials; tr++) {
memcpy(rx, stored, slen);
for (int f = 0; f < k; f++) {
size_t pos = (size_t)(xr() % (slen * 8));
rx[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
}
int corr = -1;
if (bch_decode_block(rx, slen, dlen, p, out, &corr) == 0 &&
memcmp(out, data, dlen) == 0) {
p1++;
continue;
}
int nc = bch_decode_block_candidates(rx, slen, dlen, p, cands,
BCH_PASS2_MAX_CANDS);
for (int i = 0; i < nc; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * dlen, dlen, h);
if (memcmp(h, want, 32) == 0) {
rescued++;
break;
}
}
}
printf("k=%2d pass1=%d/%d rescued=%d/%d\n", k, p1, trials, rescued,
trials);
fflush(stdout);
}
return 0;
}
-333
View File
@@ -1,333 +0,0 @@
/* polar.c - polar code codec for the experiments harness.
*
* N=4096, successive-cancellation (SC) decoding with the min-sum
* f-function. Construction is Arikan's Bhattacharyya recursion for
* the binary erasure channel with erasure probability equal to the
* BSC's Bhattacharyya parameter Z = 2*sqrt(p(1-p)) at a design
* crossover p (see polar_new: the codec name selects it, e.g.
* polar-r90-d3 designs for p=1e-3; plain polar-r90 designs for
* p=1e-2). The design point matters: designing for a much worse
* channel than the operating point ranks the marginal channels
* wrong and SC pays for it.
*
* polar-r90: K=3680 info bits (460 B), rate 0.89844, overhead 11.30%.
* polar-r95: K=3888 info bits (486 B), rate 0.94922, overhead 5.35%.
*
* A blob is split into blocks of K data bytes; the last block is
* zero-padded. Stored length per block is exactly N/8 = 512 bytes.
*
* Note: SC decoding always returns a codeword, so decode() cannot
* detect failure by itself -- it returns 0 whenever decoding
* completes, and the caller (bench / lzply's SHA-256) is the oracle
* that decides whether the recovered data is correct. That matches
* lzply's architecture: the entry SHA is the miscorrection guard.
* Channel LLR uses a fixed nominal crossover p0 = 1e-3, same honest
* setting as the LDPC codec.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ecc_iface.h"
#define POLAR_N 4096
#define POLAR_LOGN 12
#define POLAR_P0 1e-3
typedef struct {
int k; /* info bits */
int kbytes; /* info bytes per block */
double p_design; /* design crossover for the BEC construction */
uint8_t frozen[POLAR_N]; /* 1 = frozen (0 bit) */
float *llr; /* N, decode workspace */
float *ws; /* N, SC scratch (bump-allocated down the tree) */
uint8_t *bits; /* N, decoded info vector (leaf decisions) */
uint8_t *psum; /* N, partial sums (re-encoded codeword) */
} polar_t;
static void polar_build_frozen(polar_t *P)
{
/* BEC Bhattacharyya recursion: Z starts at eps, then per level
the upper (bad) channel gets 2Z-Z^2 and the lower (good) one
gets Z^2. z[] holds the values in bit-reversed order matching
the standard construction; sorting by Z ascending gives the
reliability order. */
double eps = 2.0 * sqrt(P->p_design * (1.0 - P->p_design));
double z[POLAR_N];
for (int i = 0; i < POLAR_N; i++)
z[i] = eps;
for (int level = 0; level < POLAR_LOGN; level++) {
int step = 1 << (level + 1);
int half = 1 << level;
for (int base = 0; base < POLAR_N; base += step) {
for (int i = 0; i < half; i++) {
double a = z[base + i];
double b = z[base + half + i];
/* upper (first half) is the worse channel */
z[base + i] = 2 * a - a * a;
z[base + half + i] = b * b;
}
}
}
/* The recursion above indexes channels in natural order only if
the pairing is right; verify by construction: sort indices by
Z and take the K smallest as information positions. */
int idx[POLAR_N];
for (int i = 0; i < POLAR_N; i++)
idx[i] = i;
/* simple insertion-free sort: qsort with a comparator on z */
/* (z is captured via a file-scope pointer for the comparator) */
extern double *polar_sort_z;
polar_sort_z = z;
/* qsort needs a comparator; defined below */
extern int polar_cmp_idx(const void *, const void *);
qsort(idx, POLAR_N, sizeof(int), polar_cmp_idx);
memset(P->frozen, 1, POLAR_N);
for (int i = 0; i < P->k; i++)
P->frozen[idx[i]] = 0;
}
double *polar_sort_z = NULL;
int polar_cmp_idx(const void *a, const void *b)
{
int ia = *(const int *)a, ib = *(const int *)b;
if (polar_sort_z[ia] < polar_sort_z[ib])
return -1;
if (polar_sort_z[ia] > polar_sort_z[ib])
return 1;
return ia - ib;
}
/* polar transform: in-place butterfly, u ^= u shifted */
static void polar_transform(uint8_t *u, int n)
{
for (int len = 1; len < n; len <<= 1) {
for (int base = 0; base < n; base += 2 * len) {
for (int i = 0; i < len; i++) {
int a = base + i, b = base + len + i;
u[a] ^= u[b];
}
}
}
}
static inline int get_bit(const uint8_t *buf, int i)
{
return (buf[i / 8] >> (7 - (i % 8))) & 1;
}
static inline void set_bit(uint8_t *buf, int i, int v)
{
if (v)
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
else
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
}
static size_t polar_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
polar_t *P = (polar_t *)c->priv;
size_t nblocks = (len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
size_t slen = nblocks * (POLAR_N / 8);
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
if (!buf)
return 0;
uint8_t *u = (uint8_t *)malloc(POLAR_N);
if (!u) {
free(buf);
return 0;
}
for (size_t b = 0; b < nblocks; b++) {
size_t dlen = len - b * (size_t)P->kbytes < (size_t)P->kbytes
? len - b * (size_t)P->kbytes
: (size_t)P->kbytes;
memset(u, 0, POLAR_N);
int dp = 0;
for (int i = 0; i < POLAR_N; i++) {
if (P->frozen[i])
continue;
if (dp < (int)dlen * 8)
u[i] = (uint8_t)get_bit(data + b * (size_t)P->kbytes, dp);
dp++;
}
polar_transform(u, POLAR_N);
uint8_t *cw = buf + b * (POLAR_N / 8);
for (int i = 0; i < POLAR_N; i++)
set_bit(cw, i, u[i]);
}
free(u);
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static inline float polar_f(float a, float b)
{
float m = fabsf(a) < fabsf(b) ? fabsf(a) : fabsf(b);
int s = ((a < 0) ^ (b < 0)) ? -1 : 1;
return s * m;
}
static inline float polar_g(float a, float b, int u)
{
return b + (u ? -a : a);
}
static void sc_rec(polar_t *P, const float *llr, int off, int len,
float *ws)
{
if (len == 1) {
/* Leaf: the decision is the decoded info bit. The partial
sum at a leaf is the bit itself. The two arrays must stay
separate: the combine step below rewrites psum (it becomes
the re-encoded codeword) and must not touch bits. */
int b = 0;
if (!P->frozen[off])
b = llr[0] < 0 ? 1 : 0;
P->bits[off] = (uint8_t)b;
P->psum[off] = (uint8_t)b;
return;
}
int half = len / 2;
/* Scratch for this level lives in ws[0..half); children bump
past it. Total scratch along any path is N floats. */
float *tmp = ws;
for (int i = 0; i < half; i++)
tmp[i] = polar_f(llr[i], llr[half + i]);
sc_rec(P, tmp, off, half, ws + half);
for (int i = 0; i < half; i++)
tmp[i] = polar_g(llr[i], llr[half + i], P->psum[off + i]);
sc_rec(P, tmp, off + half, half, ws + half);
for (int i = 0; i < half; i++)
P->psum[off + i] ^= P->psum[off + half + i];
}
static int polar_decode_block(polar_t *P, const uint8_t *cw_in,
uint8_t *data_out, long *corrected_out)
{
float L0 = (float)log((1.0 - POLAR_P0) / POLAR_P0);
for (int i = 0; i < POLAR_N; i++)
P->llr[i] = get_bit(cw_in, i) ? -L0 : L0;
sc_rec(P, P->llr, 0, POLAR_N, P->ws);
/* psum now holds the decoded codeword; count corrected bits
against the received codeword. */
long corr = 0;
for (int i = 0; i < POLAR_N; i++)
if (P->psum[i] != get_bit(cw_in, i))
corr++;
if (corrected_out)
*corrected_out = corr;
/* data bits out: info positions in increasing index order */
int dp = 0;
memset(data_out, 0, (size_t)P->kbytes);
for (int i = 0; i < POLAR_N; i++) {
if (P->frozen[i])
continue;
set_bit(data_out, dp++, P->bits[i]);
}
return 0;
}
static int polar_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
polar_t *P = (polar_t *)c->priv;
size_t nblocks = (orig_len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
if (slen != nblocks * (POLAR_N / 8))
return -1;
long corr = 0;
for (size_t b = 0; b < nblocks; b++) {
uint8_t *db = (uint8_t *)malloc((size_t)P->kbytes);
if (!db)
return -1;
long bc = 0;
polar_decode_block(P, stored + b * (POLAR_N / 8), db, &bc);
corr += bc;
size_t dlen = orig_len - b * (size_t)P->kbytes < (size_t)P->kbytes
? orig_len - b * (size_t)P->kbytes
: (size_t)P->kbytes;
memcpy(out + b * (size_t)P->kbytes, db, dlen);
free(db);
}
if (corrected)
*corrected = corr;
return 0;
}
static void polar_destroy(ecc_codec_t *c)
{
polar_t *P = (polar_t *)c->priv;
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
free((void *)c->name);
free(c);
}
ecc_codec_t *polar_new(int rate_pct, int design_exp)
{
int k;
const char *tag;
if (rate_pct == 90) {
k = 3680;
tag = "polar-r90";
} else if (rate_pct == 95) {
k = 3888;
tag = "polar-r95";
} else {
return NULL;
}
polar_t *P = (polar_t *)calloc(1, sizeof(*P));
if (!P)
return NULL;
P->k = k;
P->kbytes = k / 8;
P->p_design = pow(10.0, -(double)design_exp);
P->llr = (float *)malloc((size_t)POLAR_N * sizeof(float));
P->ws = (float *)malloc((size_t)POLAR_N * sizeof(float));
P->bits = (uint8_t *)malloc((size_t)POLAR_N);
P->psum = (uint8_t *)malloc((size_t)POLAR_N);
if (!P->llr || !P->ws || !P->bits || !P->psum) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
return NULL;
}
polar_build_frozen(P);
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
if (!c) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
return NULL;
}
char *name = (char *)malloc(24);
if (!name) {
free(P->llr);
free(P->ws);
free(P->bits);
free(P->psum);
free(P);
free(c);
return NULL;
}
if (design_exp == 2)
snprintf(name, 24, "%s", tag);
else
snprintf(name, 24, "%s-d%d", tag, design_exp);
c->name = name;
c->desc = "polar code, successive-cancellation decoding";
c->block_data = (size_t)P->kbytes;
c->encode = polar_encode;
c->decode = polar_decode;
c->recover_verified = NULL;
c->destroy = polar_destroy;
c->priv = P;
return c;
}
-21
View File
@@ -1,21 +0,0 @@
#!/bin/bash
# run_matrix.sh - full corruption matrix for a list of codecs.
# Usage: run_matrix.sh <corpus> <blobsize> <trials> <outfile> <codec...>
# Each codec x setting is its own bench invocation; xargs -P spreads
# them over all cores. Pass 2 is OFF for the matrix (too slow at scale);
# rescue rates are measured separately by run_pass2.sh.
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-5 1e-4 1e-3 3e-3 1e-2; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --nopass2 --out $OUT"
done
for B in "16,1" "64,1" "256,1" "1024,1" "64,4"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --nopass2 --out $OUT"
done
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --clean --out $OUT"
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/matrix.log'
echo "matrix done: $OUT"
-18
View File
@@ -1,18 +0,0 @@
#!/bin/bash
# run_pass2.sh - BCH pass-2 rescue rates, small trial count (pass 2 is
# slow; 25 trials per setting is enough to see rescues).
# Usage: run_pass2.sh <corpus> <blobsize> <trials> <outfile> <codec...>
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-4 1e-3 3e-3; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --out $OUT"
done
for B in "64,1" "256,1"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --out $OUT"
done
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/pass2.log'
echo "pass2 done: $OUT"
-177
View File
@@ -1,177 +0,0 @@
/* uep.c - unequal error protection over small-block BCH.
*
* The blob is split into a critical prefix (the first C bytes -- the
* lzip header and the start of the LZMA stream, where an error costs
* the most) protected at BCH t_hi, and the remainder at t_lo, both
* with m=13 small blocks. Stored = prefix_stored + rest_stored; the
* split point is recomputed from C and orig_len, so no per-entry
* metadata is needed beyond the codec parameters.
*
* Two things to know before judging it:
* - Exact recovery is dominated by the WEAK tier: UEP cannot beat
* uniform BCH at the same total overhead on whole-blob recovery,
* because the weak tier fails first. The fair comparison is
* t_lo == the uniform baseline t, with t_hi > t_lo costing only
* a little extra overhead (the prefix is short).
* - The win, if any, is graceful degradation: the prefix survives
* when the rest does not. That only helps lzply if it gains a
* salvage mode (today the entry SHA gates all-or-nothing
* extraction), so prefix survival is reported separately by
* uep_diag.c, not by bench.c.
* Pass 2 is not wired: the recovery oracle is the whole-blob SHA,
* which cannot verify a prefix candidate on its own.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch_wrap.h"
#include "uep.h"
typedef struct {
ecc_codec_t *hi; /* bch1k-t{t_hi} */
ecc_codec_t *lo; /* bch1k-t{t_lo} */
int crit_bytes;
int t_hi, t_lo;
} uep_priv_t;
/* Max data bytes per block under small-block BCH at t (pinned m=13
poly, N=8191): floor((8191 - 13*t)/8). NOTE: this depends on t --
971 for t=32 but 1010 for t=8. An earlier version hardcoded 971
and broke every tier but t=32. */
static size_t bch1k_max_data(int t)
{
return (8191 - (size_t)13 * (size_t)t) / 8;
}
/* Stored length of dlen data bytes under small-block BCH at t:
blocks of bch1k_max_data(t) bytes, ceil((8*dlen + t*13)/8) stored
each. (Mirrors bch_block_stored_len for the pinned m=13 poly.) */
static size_t bch1k_stored_len(size_t dlen, int t)
{
size_t maxd = bch1k_max_data(t);
size_t total = 0;
size_t r = (size_t)t * 13;
while (dlen > 0) {
size_t b = dlen < maxd ? dlen : maxd;
total += (8 * b + r + 7) / 8;
dlen -= b;
}
return total;
}
static size_t uep_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
size_t clen = len < (size_t)p->crit_bytes ? len : (size_t)p->crit_bytes;
uint8_t *hi = NULL, *lo = NULL;
size_t hi_len = p->hi->encode(p->hi, data, clen, &hi);
size_t lo_len = 0;
if (hi_len)
lo_len = p->lo->encode(p->lo, data + clen, len - clen, &lo);
if (!hi_len || (len > clen && !lo_len)) {
free(hi);
free(lo);
return 0;
}
uint8_t *buf = (uint8_t *)malloc(hi_len + lo_len);
if (!buf) {
free(hi);
free(lo);
return 0;
}
memcpy(buf, hi, hi_len);
memcpy(buf + hi_len, lo, lo_len);
free(hi);
free(lo);
c->overhead = len ? (double)(hi_len + lo_len) / (double)len - 1.0 : 0.0;
*out = buf;
return hi_len + lo_len;
}
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
size_t clen = orig_len < (size_t)p->crit_bytes
? orig_len
: (size_t)p->crit_bytes;
size_t hi_len = bch1k_stored_len(clen, p->t_hi);
size_t lo_len = bch1k_stored_len(orig_len - clen, p->t_lo);
if (hi_len + lo_len != slen)
return 0;
int mask = 0;
long corr = -1;
if (p->hi->decode(p->hi, stored, hi_len, clen, out, &corr) == 0)
mask |= 1;
if (p->lo->decode(p->lo, stored + hi_len, lo_len, orig_len - clen,
out + clen, &corr) == 0)
mask |= 2;
return mask;
}
static int uep_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
(void)corrected;
return uep_decode_parts(c, stored, slen, orig_len, out) == 3 ? 0 : -1;
}
static void uep_destroy(ecc_codec_t *c)
{
uep_priv_t *p = (uep_priv_t *)c->priv;
if (p->hi)
p->hi->destroy(p->hi);
if (p->lo)
p->lo->destroy(p->lo);
free(p);
free((void *)c->name);
free(c);
}
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo)
{
ecc_codec_t *hi = bch_1k_new(t_hi);
ecc_codec_t *lo = bch_1k_new(t_lo);
if (!hi || !lo) {
if (hi)
hi->destroy(hi);
if (lo)
lo->destroy(lo);
return NULL;
}
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
uep_priv_t *p = (uep_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
hi->destroy(hi);
lo->destroy(lo);
return NULL;
}
char *name = (char *)malloc(32);
if (!name) {
free(c);
free(p);
hi->destroy(hi);
lo->destroy(lo);
return NULL;
}
snprintf(name, 32, "uep-c%d-h%d-l%d", crit_bytes, t_hi, t_lo);
p->hi = hi;
p->lo = lo;
p->crit_bytes = crit_bytes;
p->t_hi = t_hi;
p->t_lo = t_lo;
c->name = name;
c->desc = "unequal error protection over small-block BCH";
c->block_data = bch1k_max_data(t_lo); /* bulk tier's block size */
c->encode = uep_encode;
c->decode = uep_decode;
c->recover_verified = NULL;
c->destroy = uep_destroy;
c->priv = p;
return c;
}
-14
View File
@@ -1,14 +0,0 @@
/* uep.h - UEP codec plus the part-wise decode helper used by uep_diag. */
#ifndef EXP_UEP_H
#define EXP_UEP_H
#include "ecc_iface.h"
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
/* Decode and report per-part success: bit 1 = critical prefix decoded,
bit 2 = remainder decoded. Returns the bitmask (0..3). */
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out);
#endif /* EXP_UEP_H */
-125
View File
@@ -1,125 +0,0 @@
/* uep_diag.c - diagnostic for the UEP codec (NOT part of bench).
* Reports BOTH whole-blob exact recovery AND critical-prefix survival
* per corruption setting, so the graceful-degradation claim can be
* judged: a prefix that survives while the rest fails is only useful
* with a salvage mode, but it is the metric UEP exists for.
* Usage: uep_diag <codec> <blob> <size> <trials> (--ber X | --burst L,C)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ecc_iface.h"
#include "uep.h"
static uint64_t rs = 0x13579bdf2468aceULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
int main(int argc, char **argv)
{
if (argc < 6) {
fprintf(stderr,
"usage: uep_diag <codec> <blob> <size> <trials> "
"(--ber X | --burst L,C)\n");
return 2;
}
const char *codec_name = argv[1];
const char *blob_path = argv[2];
size_t win_size = (size_t)strtoull(argv[3], NULL, 0);
long trials = strtol(argv[4], NULL, 0);
double ber = 0;
long burst_len = 0, burst_count = 0;
int is_burst = 0;
if (!strcmp(argv[5], "--ber") && argc > 6)
ber = strtod(argv[6], NULL);
else if (!strcmp(argv[5], "--burst") && argc > 6) {
is_burst = 1;
burst_len = strtol(argv[6], NULL, 0);
char *comma = strchr(argv[6], ',');
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
} else {
fprintf(stderr, "uep_diag: need --ber X or --burst L,C\n");
return 2;
}
FILE *f = fopen(blob_path, "rb");
if (!f) {
fprintf(stderr, "uep_diag: cannot open %s\n", blob_path);
return 2;
}
fseek(f, 0, SEEK_END);
long file_len = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *file = (uint8_t *)malloc((size_t)file_len);
if (!file || fread(file, 1, (size_t)file_len, f) != (size_t)file_len)
return 2;
fclose(f);
ecc_codec_t *c = NULL;
/* parse the codec name the same way bench does */
int cb, th, tl;
if (sscanf(codec_name, "uep-c%d-h%d-l%d", &cb, &th, &tl) != 3) {
fprintf(stderr, "uep_diag: bad codec %s\n", codec_name);
return 2;
}
c = uep_new(cb, th, tl);
if (!c) {
fprintf(stderr, "uep_diag: uep_new failed\n");
return 2;
}
uint8_t *win = (uint8_t *)malloc(win_size);
uint8_t *out = (uint8_t *)malloc(win_size);
uint8_t *stored = NULL, *rx = NULL;
long whole = 0, prefix = 0;
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
for (long tr = 0; tr < trials; tr++) {
size_t off = (size_t)(xr() % ((size_t)file_len - win_size + 1));
memcpy(win, file + off, win_size);
size_t slen = c->encode(c, win, win_size, &stored);
if (!slen) {
fprintf(stderr, "uep_diag: encode failed\n");
return 2;
}
if (tr == 0) {
rx = (uint8_t *)malloc(slen);
if (!rx)
return 2;
}
memcpy(rx, stored, slen);
if (is_burst) {
for (long b = 0; b < burst_count; b++) {
if ((size_t)burst_len >= slen)
continue;
size_t start =
(size_t)(xr() % (slen - (size_t)burst_len + 1));
for (long k = 0; k < burst_len; k++)
rx[start + k] = (uint8_t)(xr() & 0xff);
}
} else {
for (size_t i = 0; i < slen; i++) {
uint8_t m = 0;
for (int b = 0; b < 8; b++)
if (xr() < ber_thr)
m |= (uint8_t)(1u << b);
rx[i] ^= m;
}
}
int mask = uep_decode_parts(c, rx, slen, win_size, out);
if (mask == 3 && memcmp(out, win, win_size) == 0)
whole++;
if (mask & 1)
prefix++;
free(stored);
stored = NULL;
}
printf("%s %s trials=%ld whole=%.4f prefix=%.4f overhead=%.2f%%\n",
codec_name, is_burst ? "burst" : "ber", trials,
(double)whole / (double)trials, (double)prefix / (double)trials,
c->overhead * 100.0);
return 0;
}