27 Commits
Author SHA1 Message Date
Muse 14a0ad3b85 README: add libfuse3-dev and fuse3 to build prerequisites (lzply_mount needs fuse3/fuse.h)
macOS build / macOS arm64 (macos-15) (push) Waiting to run
macOS build / macOS x86_64 (macos-15-intel) (push) Waiting to run
2026-12-05 22:13:48 +00:00
cnmcdee 4c06bdd39c README: add direct v0.1.1 download links
macOS build / macOS arm64 (macos-15) (push) Waiting to run
macOS build / macOS x86_64 (macos-15-intel) (push) Waiting to run
2026-12-04 22:19:27 -05:00
cnmcdee e8f61d7bb9 Add lzcsv: standalone high-speed CSV compressor (transpose + xz)
Column-wise transpose (COLT1, byte-compatible with the hot_qwen Cycle 1 Python prototype) + xz via liblzma. 14 corpus CSVs: 2,072,188 -> 1,784,880 bytes vs xz -6 (-13.9%), 13/14 win; vs xz -9e -14.0%. 18 held-out CSVs: -13.5% vs xz -6, 9/18 win (losses are tiny files and single-column). Byte-exact round-trips on all 32; oracle byte-identical to the prototype; clean rejections for embedded newlines, mixed endings, truncated/bad-magic input. CPU-only, conditional build on liblzma presence; own binary, no liblzply.a.
2026-12-04 22:09:01 -05:00
cnmcdee 88d1e3b183 Fix macOS link: stub the CUDA Chase entry points for CPU-only builds
deep_repair.c references chase_cuda_available/_scan1 (weak), but no CPU-only stub defined them, so the macOS link failed with undefined _chase_cuda_available/_chase_cuda_scan1 (run 7, both arches) -- the merge kept the BCH stub but the Chase symbols had none. Add chase_cuda_stub.c (available = 0, scan1 = -2) and wire it into CUDA_STUB_OBJ on the nvcc-absent path, so every tool that links deep_repair.o resolves. Verified both paths on hot_house: full make test green with real CUDA objects, and a no-nvcc build links and repairs (9-bit corruption recovered at L1 via the CPU Chase).
2026-12-04 08:02:12 -05:00
cnmcdee c6e06a0d48 Merge ci/macos-build: macOS CI (arm64 + x86_64) + CUDA stub for CPU-only builds 2026-12-04 07:31:43 -05:00
cnmcdee a2ecebb5e6 Merge experiments/chase-wired: CUDA Chase-1 in deep repair (L1) + lzply -r repair mode 2026-12-03 21:17:36 -05:00
cnmcdee 902d10d0e7 Wire CUDA Chase-1 into deep repair (L1) + lzply -r repair mode
L1 uses chase_cuda_scan1 when a device is present (weak symbols, CPU fallback otherwise); results identical (full-scan trial counts match CPU exactly). Deep repair is now built into the main CLI as lzply -r (same levels/options as lzply_deep_repair, which is unchanged in behaviour and shares the driver via repair_cmd.c). Docs cover the CUDA path + article link. Full make test green; 524 KiB-block repair 173.7s CPU -> 1.8s GPU end to end.
2026-12-03 21:08:15 -05:00
cnmcdee 5362ad35b0 README: cover CUDA BCH, CUDA Chase-1, phase-2 findings, four defences with lzply.com article links 2026-12-03 21:00:39 -05:00
cnmcdee fe512e6df2 Merge experiments/integration: four defences wired into build + tests
# Conflicts:
#	.gitignore
2026-12-03 20:51:34 -05:00
Muse c6a13f189c integration: record fresh benchmark numbers in docs/INTEGRATION.md
bench-integration.sh (best-of-3, mixed set + 1 MiB random) plus the
codec-name fix for the intlv speed run. Headline fresh numbers:
intlv-d64 enc 3.77 / dec 1.72 MB/s at 5.40% overhead; ldpc-r90 enc
4.08 / dec 1.07 at 10.94%; recovery 1.000 on the mixed blob for all
three ECC winners. Dict is +2.7% worse on the repo-sources-only code
corpus (branch -2.1% was header-heavy code) -- recorded honestly.
2026-12-02 15:47:38 +00:00
Muse fddd00c784 integration: fix codec name in smoke tests (intlv-d64-bch1k-t32)
The bench codec is intlv-d{D}-bch1k-t{T}; the bare intlv-d64-t32
name matched nothing, so the clean round-trip and speed checks
failed on unknown-codec (the burst check already used the right
name and passed 1.0000).
2026-12-02 15:38:54 +00:00
Muse 0f2cb105fc integration: build corpora from varied tree content, not repetition
Repeating the docs x12 still gave a 30 KiB lzip blob (LZMA eats
repeats). Use every text file in the tree for the text corpus and
every C file for the code corpus: ~1 MB raw -> 188 KiB blob (text),
~120 KiB blob (code). Same fix in bench-integration.sh.
2026-12-02 15:35:10 +00:00
Muse e53455bf07 integration: fix smoke-test corpus size + commit benchmark script
The docs corpus (86 KiB raw) compresses to 30 KiB under lzip -6,
below the 64 KiB bench window: repeat it x12 (~1 MB raw, ~90 KiB
blob) and the C sources x3. Also commits bench-integration.sh, the
best-of-3 benchmark harness used for the integration numbers.
2026-12-02 15:28:50 +00:00
Muse f60ca9fd73 integration: wire winners into the build + tests, document in docs/INTEGRATION.md
- make exp / make experiments build the integrated winners
  (exp/bench + diags; experiments/rans_tool + dict + bchcheck)
- make test runs tests/run_integration_tests.sh: clean round-trips
  for all three ECC codecs, intlv-d64 burst survival + uninterleaved
  control, bch1k BER survival + as-shipped control, LDPC BER survival,
  rANS round-trip, dict+lzip round-trip, bchcheck 8-flip recovery and
  32-flip expected failure, LZPL v5 archive round-trip
- docs/INTEGRATION.md: the four winners with measured numbers, the
  rejects with numbers, build/test instructions
- README.md: Integrated experiments section; branch READMEs carry a
  pointer to docs/INTEGRATION.md
Archive format unchanged (LZPL v5); wiring interleave/LDPC into
lzply -e levels would be a format change and is future work.
2026-12-02 14:42:57 +00:00
Muse bf8efab2b7 integration: drop rejected families (polar, UEP, lzrans, BWT, PPM)
The experiment branches measured these and rejected them; only their
numbers stay (in the READMEs and results/*.csv), the code does not
carry over to the integrated tree:
- polar SC: 0.00 at BER 1e-3 at every design point, dec 0.58 MB/s
- UEP: whole-file recovery dominated by the weak tier (0.00 at 1e-3);
  its prefix-survival property needs a salvage mode lzply lacks
- lzrans: ~75% relative ratio gap to lzip on text, static rANS
- BWT: 0.05 MB/s encode, loses to lzip everywhere
- PPM order-2: 32.84% on text vs lzip 3.56%, 6 MB/s encode
Winners kept: interleave d64 + bch1k, LDPC r90, dict transform,
rANS core.
2026-12-02 14:40:39 +00:00
Muse 1239bd9c64 experiments: BWT, PPM, dict transform, BCH corruption harness + results
BWT+MTF+rANS (cyclic-doubling SA; linear sort is NOT rotation
order, sentinel does not fix it), order-2 PPM + WNC arithmetic
coder, word-dictionary transform + lzip, bchcheck (BCH t=8
corruption harness), bench1 single-run harness. Results:
BWT text 6.35 / code 12.31 / bin 42.76 (encode ~3 min/8 MB);
PPM text 32.84 / code 30.82 / mixed 39.18; dict+lzip6 code
9.19 vs plain 9.38 (+2.1%, only code wins); BCH: dict+lzip
code blob survives 8 flips (8 corrected, bit-identical), fails
at 32 flips as expected. No family beats lzip on ratio; rANS
core kept as infrastructure, dict conditional on code. Full
tables + verdicts in experiments/README.md. BWT mixed/rand
still benching at commit time.
2026-12-02 14:40:06 +00:00
Muse 2932575441 experiments: rANS core + order-0 tool, LZ77+rANS (lazy/optimal), bench harness
rANS entropy coder (12-bit probs, 23-bit window) with byte and
general-alphabet layers; standalone order-0 tool (enc 30-38 MB/s)
and an LZ77+rANS prototype (hash chains, 1 MiB window, lazy and
optimal-parse modes). Bench harness + deterministic corpora builder
(text/code/bin/mixed 8 MiB, rand 4 MiB) and baseline numbers:
lzip -6 text 3.56% / code 9.38% / bin 32.61% / mixed 17.41%.
lzrans-lazy: text 6.26% / code 13.52% / bin 41.84%; optimal
parsing recovers only ~1-3% relative, so the gap is LZMA adaptive
entropy modelling, not parsing -- lzrans rejected as a lzip
replacement (see experiments/README.md). All round-trips sha256-verified.
2026-12-02 14:40:06 +00:00
Muse 4c32b542ba exp: gitignore the diag binaries 2026-12-02 14:39:53 +00:00
Muse c07d986cd9 exp: final README — pass-2 verdict (0/875), speeds, cross-corpus, totals
- Pass 2: 35 rows x 25 trials = 875, rescued 0. Repo's own test
  agrees (t+1 0/100, t+2 0/100).
- Isolated speed table (sequential): interleave costs nothing
  measurable; LDPC dec 0.91 MB/s; polar dec 0.58 MB/s.
- Cross-corpus (bin.lz, rand.lz) reproduces text.lz exactly.
- Test totals: 51,875 matrix trials + diagnostics.
- hot_chicago verification BLOCKED (tunnel down 4 attempts);
  snapshot zips staged on old VPS for a later retry.
2026-12-02 14:39:53 +00:00
Muse 0022cd76e0 exp: fix Makefile mangled by a sed (ldpc_diag/pass2_diag recipes)
The previous commit's sed ate the $(CC)/$(CFLAGS) variables and
moved the ldpc_diag recipe under pass2_diag. Rewrote the Makefile
cleanly; all four binaries build.
2026-12-02 14:39:53 +00:00
Muse 40d4d996d6 exp: results write-up + pass-2 diagnostic (pass 2 rescues nothing)
README now carries the measured tables for all four families.
pass2_diag.c: targeted sweep of BCH pass-2 recovery. Finding: the
repo's own bch_test reports t+1 recovered 0/100, t+2 0/100; this
harness's pass-2 matrix shows rescued=0 in every setting; the
targeted sweep (m=13 t=16, k=t+1..t+8) rescues 0/50 at every k.
Pass 2's demonstrated value is the loud-failure guarantee (0
silent miscorrections), not recovery -- its residual-BM mechanism
addresses pass-1 miscorrection, which essentially never happens
for random errors. Relevant to the sibling deep-repair job.
2026-12-02 14:39:53 +00:00
Muse acedd368df exp: interleave groups merge the short tail (no weak tail group)
A burst landing in the final partial group (4 blocks of a 68-block
blob) hit each of its blocks with L/4 bytes instead of L/64 -- that
is why 64 B bursts measured 0.94 instead of 1.00. Groups are now
formed so the last partial group is absorbed into the previous one
(every group >= depth). Re-measured, 50 trials: d16/d32/d64-t32 at
64 B bursts 1.00 (was 0.94); d64-t32 at 256 B and 64x4 bursts 1.00
(was 0.95 / 0.83).
2026-12-02 14:39:53 +00:00
Muse 8d268167f8 exp: regular LDPC codec, PEG construction + min-sum BP (family 2)
n=8192, column weight 3; r90 (m=768, rate 0.906) and r95 (m=384,
rate 0.953). PEG construction (the greedy 4-cycle-rejection builder
deadlocked in the endgame -- replaced, see comment). Systematic
encoding via Gauss-Jordan; normalized min-sum (0.8), 50 iters.
Single-block diagnostics (ldpc_diag): r90 clean to 37 errors/block,
first failures ~38-40; r95 starts failing at 6 errors/block -- the
high-rate regular (3,64) code is genuinely weak, an honest negative
for naive regular LDPC at rate 0.95. Clean round-trips bit-identical.
2026-12-02 14:39:53 +00:00
Muse 5c65f3cd89 exp: byte interleaver over small-block BCH (family 1)
Zero extra parity: groups of D blocks are read column-wise, so a
burst of L bytes hits any one block with at most ceil(L/D) bytes
instead of killing a block outright. Random-error performance is
unchanged by construction (same BCH underneath); burst tolerance
improves ~Dx. Smoke test on text.lz: d64-t32 survives 256 B bursts
at 0.95 (plain bch1k-t32: 0.00), clean round-trips bit-identical,
overhead identical to bch1k-t32 (5.40%).
2026-12-02 14:39:53 +00:00
Muse fe90ef37b2 exp: corruption-matrix harness + BCH baseline codecs
bench.c measures every ECC family the same way: encode a blob window,
corrupt the stored bytes (random bit flips at a BER, or randomized
byte bursts), decode, check exact recovery (memcmp + SHA-256).
bch_wrap.c wraps the shipped BCH two ways: as-shipped (auto-pick poly
for the whole blob) and forced 1 KiB blocks. Pass 2 is wired to
recover_verified; --nopass2 skips it for matrix speed.
Stubs for interleave/ldpc/polar/uep return NULL until implemented.
Corpora + results are generated, gitignored.
2026-12-02 14:39:53 +00:00
Muse 73e333f6f3 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 14:39:50 +00:00
Muse 911b3c998f 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 14:39:50 +00:00
60 changed files with 5936 additions and 365 deletions

No files matched your search

+9
View File
@@ -28,3 +28,12 @@ randfec/m2/fit1.log
randfec/m2/fit2.log
randfec/m2/fit2b.log
randfec/m2/p3-driver.log
# compression experiments (integrated winners only; lzrans/bwt/ppm rejected)
/experiments/corpora/
/experiments/rans_tool
/experiments/dict
/experiments/bchcheck
/testwork-int/
/testwork-bench/
/lzcsv
/testwork-lzcsv/
+111 -36
View File
@@ -3,41 +3,77 @@ CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local
# CUDA BCH remainder (optional): if nvcc is on PATH, bch_cuda.o is
# built and linked into liblzply.a and the tools; bch.c dispatches
# to it via weak symbols for large blobs. Without nvcc the build is
# unchanged (CPU-only) except that bch_cuda_stub.o (below) is linked
# instead, so the CUDA entry points always resolve -- see the stub
# comment. These definitions MUST stay above every rule
# that references $(CUDA_OBJ): make expands prerequisites when the
# rule is read, so a definition below the liblzply.a rule would
# silently leave bch_cuda.o out of the archive. NOTE: bch_cuda.o is
# still listed explicitly on each tool link line below, because the
# weak references from bch.o do not make the linker pull it out of
# the archive on their own. The stub is listed the same way.
# CUDA (optional): nvcc is found on PATH first; on hot_house it lives
# at /usr/local/cuda/bin/nvcc (not on PATH by default), so fall back
# to that path when it exists. Two CUDA objects share this NVCC:
# bch_cuda.o -- CUDA BCH remainder (bch.c dispatches via weak
# symbols for large blobs); linked into liblzply.a
# and every tool. Without nvcc the build is
# unchanged (CPU-only).
# chase_cuda.o -- CUDA Chase-1 scan for deep repair (t=8 only);
# linked into lzply and lzply_deep_repair, with a
# CPU fallback via weak references.
# Without nvcc, the *_cuda_stub.o objects are linked instead, so
# the CUDA entry points always resolve -- see the stub comment
# below. The stubs are required on macOS: ld64 does not resolve
# __attribute__((weak)) declarations to NULL the way GNU ld does,
# so a CPU-only build failed at link time with undefined
# _bch_cuda_available/_encode/_decode symbols (and, after the
# chase-wired merge, _chase_cuda_available/_scan1). A stub is
# never built alongside its CUDA object, so the symbols are
# defined exactly once.
# These definitions MUST stay above every rule that references
# $(CUDA_OBJ): make expands prerequisites when the rule is read, so
# a definition below the liblzply.a rule would silently leave
# bch_cuda.o out of the archive. NOTE: bch_cuda.o is still listed
# explicitly on each tool link line below, because the weak
# references from bch.o do not make the linker pull it out of the
# archive on their own. The stub is listed the same way.
NVCC ?= $(shell command -v nvcc 2>/dev/null)
ifeq ($(NVCC),)
NVCC := $(wildcard /usr/local/cuda/bin/nvcc)
endif
CUDA_ARCH ?= sm_86
NVCCFLAGS = -O3 -arch=$(CUDA_ARCH) -Xcompiler -O2
CUDA_OBJ =
CUDA_LIBS =
ifneq ($(NVCC),)
CUDA_OBJ = bch_cuda.o
CUDA_LIBS = -L$(dir $(NVCC))../lib64 -lcudart -lstdc++
endif
# CPU-only stub: when nvcc is absent, bch_cuda_stub.o defines the
# three CUDA entry points (available() = 0, encode = 0, decode = -2),
# so bch.c's references always resolve. This is required on macOS:
# ld64 does not resolve __attribute__((weak)) declarations to NULL
# the way GNU ld does, so a CPU-only build failed at link time with
# undefined _bch_cuda_available/_encode/_decode symbols. The stub
# is never built alongside bch_cuda.o, so the symbols are defined
# exactly once.
CUDA_STUB_OBJ =
ifeq ($(NVCC),)
CUDA_STUB_OBJ = bch_cuda_stub.o
CHASE_CUDA_OBJ =
ifneq ($(wildcard $(NVCC)),)
CHASE_CUDA_OBJ = chase_cuda.o
endif
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
# CPU-only stubs: when nvcc is absent, bch_cuda_stub.o defines the
# three BCH CUDA entry points (available() = 0, encode = 0,
# decode = -2) and chase_cuda_stub.o defines the two Chase CUDA
# entry points (available() = 0, scan1 = -2), so bch.c's and
# deep_repair.c's references always resolve. This is required on
# macOS: ld64 does not resolve __attribute__((weak)) declarations
# to NULL the way GNU ld does, so a CPU-only build failed at link
# time with undefined _bch_cuda_available/_encode/_decode symbols
# (and, after the chase-wired merge, _chase_cuda_available/_scan1).
# A stub is never built alongside its CUDA object, so the symbols
# are defined exactly once.
CUDA_STUB_OBJ =
ifeq ($(NVCC),)
CUDA_STUB_OBJ = bch_cuda_stub.o chase_cuda_stub.o
endif
# lzcsv: standalone high-speed CSV compressor (column transpose + xz).
# Completely separate from the lzply FEC core: own source (lzcsv-src/lzcsv.c),
# own binary, links only liblzma -- no liblzply.a, no liblz, no CUDA.
# Built only when lzma.h is present; skipped cleanly otherwise (e.g. a
# minimal CI image without liblzma-dev), so `make all` never fails for
# lack of it.
LZCSV =
ifneq ($(wildcard /usr/include/lzma.h),)
LZCSV = lzcsv
endif
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair $(LZCSV)
# Shared core: the v5 archive format, the per-entry pipeline
# (lzip -> BCH), header I/O, scan, and filters. The
@@ -59,6 +95,9 @@ bch.o: bch.c bch.h bch_polys.h
bch_cuda_stub.o: bch_cuda_stub.c bch_cuda.h bch.h
$(CC) $(CFLAGS) -c -o $@ bch_cuda_stub.c
chase_cuda_stub.o: chase_cuda_stub.c chase_cuda.h bch.h
$(CC) $(CFLAGS) -c -o $@ chase_cuda_stub.c
# CUDA BCH remainder rules (variables are defined at the top).
ifneq ($(NVCC),)
bch_cuda.o: bch_cuda.cu bch_cuda.h bch.h bch_polys.h
@@ -83,11 +122,15 @@ bch_bench: bch_bench.o bch.o $(CUDA_STUB_OBJ)
$(CC) $(CFLAGS) -o $@ bch_bench.o bch.o $(CUDA_STUB_OBJ)
endif
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h deep_repair.h repair_cmd.h
$(CC) $(CFLAGS) -c -o $@ lzply.c
lzply: lzply.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
$(CC) $(CFLAGS) -o $@ lzply.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
lzply: lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CHASE_CUDA_OBJ) $(CUDA_STUB_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
else
$(NVCC) -arch=$(CUDA_ARCH) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS) $(CUDA_LIBS)
endif
# FUSE filesystem. Needs libfuse3-dev; no pkg-config on the server, so
# the flags are explicit (-D_FILE_OFFSET_BITS=64 is required by FUSE).
@@ -151,8 +194,7 @@ bch_test: bch.c bch_test.c bch_cuda_stub.c bch.h bch_polys.h bch_cuda.h
# CUDA Chase-1 bench (experiments/cuda-chase): GPU port of the
# deep-repair Chase-1 scan (t=8 only). Needs CUDA 13.x; NVCC is
# /usr/local/cuda/bin/nvcc on hot_house (not on PATH by default).
NVCC ?= /usr/local/cuda/bin/nvcc
NVCCFLAGS = -O3 -arch=sm_86 -Xcompiler -O2
# NVCC / NVCCFLAGS are defined at the top of this file.
chase_bench_cpu: chase_bench.c bch.c bch_cuda_stub.c bch.h bch_polys.h bch_cuda.h
$(CC) $(CFLAGS) -o $@ chase_bench.c bch.c bch_cuda_stub.c
@@ -198,11 +240,15 @@ crc16_test: crc16_test.c liblzply.a $(CUDA_STUB_OBJ)
deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha256.h
$(CC) $(CFLAGS) -c -o $@ deep_repair.c
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h repair_cmd.h
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
lzply_deep_repair: lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CHASE_CUDA_OBJ) $(CUDA_STUB_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
else
$(NVCC) -arch=$(CUDA_ARCH) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS) $(CUDA_LIBS)
endif
# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
@@ -221,10 +267,17 @@ lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(CUDA
# testdata/ is generated (it includes a 50 MiB random file) and gitignored,
# so a fresh clone has none. Build it on demand so `make test` works
# straight from a clone.
# lzcsv: standalone CSV compressor. CPU-only, links liblzma.
lzcsv-src/lzcsv.o: lzcsv-src/lzcsv.c
$(CC) $(CFLAGS) -c -o $@ lzcsv-src/lzcsv.c
lzcsv: lzcsv-src/lzcsv.o
$(CC) $(CFLAGS) -o $@ lzcsv-src/lzcsv.o -llzma
testdata:
@if [ ! -d testdata/mixed ]; then ./tests/make_testdata.sh; fi
test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair $(LZCSV)
./bch_test
./rs_test
./crc16_test
@@ -248,6 +301,28 @@ test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_he
elif [ -x ../tests/run_hyper_tests.sh ]; then \
../tests/run_hyper_tests.sh ./lzply_hyper; \
else echo "run_hyper_tests.sh not found"; exit 1; fi
if [ -x ./tests/run_integration_tests.sh ]; then \
./tests/run_integration_tests.sh; \
elif [ -x ../tests/run_integration_tests.sh ]; then \
../tests/run_integration_tests.sh; \
else echo "run_integration_tests.sh not found"; exit 1; fi
if [ -x ./lzcsv ]; then \
if [ -x ./tests/run_lzcsv_tests.sh ]; then \
./tests/run_lzcsv_tests.sh ./lzcsv; \
elif [ -x ../tests/run_lzcsv_tests.sh ]; then \
../tests/run_lzcsv_tests.sh ./lzcsv; \
else echo "run_lzcsv_tests.sh not found"; exit 1; fi \
else echo "lzcsv: skipped (no liblzma)"; fi
# Integrated experiment winners (docs/INTEGRATION.md): the ECC harness
# (interleave d64, small-block BCH, LDPC r90) and the compression
# prototypes (rANS core, dict transform). Not part of `all`: the archive
# format is unchanged (LZPL v5); these are standalone tools.
exp:
$(MAKE) -C exp bench ldpc_diag pass2_diag
experiments:
$(MAKE) -C experiments
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
mkdir -p $(PREFIX)/bin
@@ -263,6 +338,6 @@ install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply
install -m 755 mount.lzply /sbin/mount.lzply
clean:
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test bch_cuda_test bch_bench chase_bench_cpu chase_bench_cuda *.o liblzply.a liblzrs.a
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair lzcsv lzcsv-src/lzcsv.o bch_test rs_test crc16_test bch_cuda_test bch_bench chase_bench_cpu chase_bench_cuda *.o liblzply.a liblzrs.a
.PHONY: all test install clean
.PHONY: all test install clean exp experiments
+106 -6
View File
@@ -53,6 +53,35 @@ BCH-decode -> decompress (on read)
and `-datestart` / `-dateend` / `-year` filter on it (see below).
File mode is preserved too; ownership is not.
## Download
Just want the executables? Grab the latest release, **v0.1.1**, for your
machine — no building needed:
| Platform | Download | Size | Needs |
| -------- | -------- | ---- | ----- |
| Linux x86_64, CPU-only | [lzply-v0.1.1-linux-x86_64-cpu.tar.gz](https://github.com/cnmcdee/lzply/releases/download/v0.1.1/lzply-v0.1.1-linux-x86_64-cpu.tar.gz) | 390,376 B | liblz.so.1 |
| Linux x86_64, CUDA | [lzply-v0.1.1-linux-x86_64-cuda.tar.gz](https://github.com/cnmcdee/lzply/releases/download/v0.1.1/lzply-v0.1.1-linux-x86_64-cuda.tar.gz) | 2,440,044 B | libcudart.so.13 + liblz.so.1 |
| Linux ARM64 (Raspberry Pi) | [lzply-v0.1.1-linux-aarch64-rpi.tar.gz](https://github.com/cnmcdee/lzply/releases/download/v0.1.1/lzply-v0.1.1-linux-aarch64-rpi.tar.gz) | 345,708 B | liblz.so.1 |
| macOS arm64 (Apple Silicon) | [lzply-v0.1.1-macos-arm64.tar.gz](https://github.com/cnmcdee/lzply/releases/download/v0.1.1/lzply-v0.1.1-macos-arm64.tar.gz) | 326,010 B | liblz.so.1 |
| macOS x86_64 (Intel) | [lzply-v0.1.1-macos-x86_64.tar.gz](https://github.com/cnmcdee/lzply/releases/download/v0.1.1/lzply-v0.1.1-macos-x86_64.tar.gz) | 343,953 B | liblz.so.1 |
Each archive holds `lzply`, `lz_rs`, `lzply_check`, `lzply_deep_repair`,
`lzply_heal`, `lzply_hyper`, `lzply_refresh`, `lzply_stat` — plus
`lzply_mount` on Linux x86_64 only — and a README. Unpack it and put the
binaries somewhere on your `PATH`. On Debian/Ubuntu install the `liblz1`
package if a binary complains about a missing `liblz.so.1`; on macOS run
`brew install lzlib`. The CUDA build additionally needs the CUDA runtime
(`libcudart.so.13`) installed just to start — with no CUDA device present
it falls back to the CPU path, byte-identical.
Full release page (all assets, checksums, and what's new):
https://github.com/cnmcdee/lzply/releases/tag/v0.1.1
Note: `lzcsv`, the standalone CSV compressor in `lzcsv-src/` (see its
README there), is built from source — there is no binary release for it
yet.
## The tools
Seven programs, one family. All are plain C, built by `make`
@@ -191,7 +220,8 @@ is the only LZRS format.
## Deep repair — past the BCH limit
`lzply_deep_repair` recovers entries whose bit errors exceed the
`lzply_deep_repair` -- also built into the main tool as `lzply -r` --
recovers entries whose bit errors exceed the
BCH correction limit t, in escalating levels, reporting per-level
timing ("time of arrival": how long each level took and at which
level the repair landed):
@@ -227,7 +257,9 @@ CRC-checked, 1,024 rejected by CRC, 0 false accepts.
Limits, measured honestly: Chase scans are O(nbits) trials at
~7,800 trials/s on m=22 blocks (a full scan of a 524 KiB block
takes ~9 minutes), so beyond-t repair of large blocks is bounded
takes ~9 minutes on the CPU; ~0.35 s on a CUDA build -- the L1
scan runs on the GPU when a device is present, with CPU fallback),
so beyond-t repair of large blocks is bounded
by the time budget (default 120 s per entry) and reports partial
coverage rather than pretending. Two bugs found by measurement
and fixed: the trial flip was not applied to the reconstructed
@@ -236,14 +268,41 @@ candidates before trying them, truncating the list before the
genuine candidate arrived (a 600 KiB file with 9 errors in one
block failed at a 60 s budget before the fix; it recovers after
it). Full design, bounds, and measured numbers:
`docs/deep-repair.md`. Tests: `tests/run_deep_repair_tests.sh`
`docs/deep-repair.md`. CUDA Chase write-up:
https://www.lzply.com/cuda-chase-500x-deep-repair/ . Tests:
`tests/run_deep_repair_tests.sh`
(round-trips, old-format rejection, corruption matrix,
false-accept measurement).
On NVIDIA GPUs the Chase-1 scan runs on CUDA instead — 453–512x
faster with bit-identical candidates; see "CUDA acceleration" below.
## CUDA acceleration
Optional: built only when `nvcc` is present (CUDA 13.x); without it
the CPU path is unchanged and nothing is lost.
* **CUDA BCH remainder** (`bch_cuda.cu`, `bch_cuda_test.c`): the
remainder computation that dominates `-e7` encode moves to the
GPU — t=32 runs 1,094 MB/s vs 22.8 MB/s on the CPU (48x), and a
full `-e7` encode drops from 2.439 s to 0.571 s (4.3x end to end).
Verified by `bch_cuda_test`: 612 checks, 0 fails.
* **CUDA Chase-1** (`chase_cuda.cu`, `CHASE_CUDA.md`): the
deep-repair Chase-1 scan (one CUDA thread per trial position,
Berlekamp-Massey + the lambda-splits test in-kernel) — 453–512x
vs the CPU scan (171.571 s -> 0.335–0.379 s on a 524 KiB block,
m=22, t=8) with bit-identical candidate sets (same hash, same
candidates, same order) across 5 patterns, and 453–562x across a
24-pattern sweep with 10/10 CPU/CUDA hash agreements. t=8 only;
Chase-2 is not ported. Benchmark with `chase_bench_cuda`
(vs `chase_bench_cpu`).
Write-ups: [171 seconds to a third of a second: deep-repair Chase on CUDA runs 500x faster](https://www.lzply.com/cuda-chase-500x-deep-repair/) and [GPU day: BCH, zseg, and the mixer that said no](https://www.lzply.com/gpu-day-bch-zseg-mixer-no/) (which also covers the segment-parallel zpaq driver, now in [lzpaq](https://github.com/cnmcdee/lzpaq), and the zpaq context-mixer GPU port — a negative: per-bit sequential dependencies, 32–64 MB of mutating tables).
## Building
```sh
apt install build-essential liblz-dev # Debian/Ubuntu
apt install build-essential liblz-dev libfuse3-dev fuse3 # Debian/Ubuntu
make # produces ./lzply, ./lz_rs, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh, ./lzply_deep_repair
make test # BCH + RS + CRC16 unit tests + full archive test suites (lzply + lz_rs + deep repair)
sudo make install # /usr/local/bin/lzply* (including lz_rs), /sbin/mount.lzply
@@ -438,6 +497,36 @@ Set `LZPLY_TEST_ROOT` to point the suite at a different tree root
(default: the parent of the `tests/` directory, so it works both
from the repo layout `~/workspace/lzply` and from `/opt/lzply/src`).
## Integrated experiments — interleaving, small-block BCH, LDPC, dict
The open-ended research branches (`experiments/baseline`,
`experiments/ecc`, `experiments/comp`) were merged onto current main
on `experiments/integration`. Four winners, measured numbers only,
full write-up in `docs/INTEGRATION.md`:
* **Byte interleaving d64 over small-block BCH** (`exp/`): zero extra
parity; a 256 B burst that kills uninterleaved BCH (0.00 recovery)
is recovered 1.00. Same 5.40% overhead as the BCH underneath.
* **Small-block BCH, 1 KiB blocks** (`exp/`): `bch1k-t32` survives
BER 1e-3 at 1.00 where as-shipped `bch-t32` scores 0.00, at 5.40%
overhead vs 0.12%.
* **Regular LDPC r90** (`exp/`): 1.00 at BER 1e-3, 0.97 at 3e-3
where `bch1k-t32` scores 0.01; 10.94% overhead, ~4x slower decode.
* **Dictionary transform, code-only** (`experiments/`): -2.1% vs
plain lzip -6 on code; worse everywhere else, so opt-in only.
The rANS core is kept as supporting infrastructure.
Rejected with numbers (code not carried over): polar SC (0.00 at
BER 1e-3), UEP (whole-file recovery dominated by the weak tier),
LZ77+rANS, BWT, and PPM order-2 — none beats lzip on ratio.
The archive format is unchanged (LZPL v5); the winners are
standalone tools, built with `make exp` / `make experiments` and
smoke-tested by `tests/run_integration_tests.sh` as part of
`make test`.
Write-up with the measured tables: [Four new defences, measured](https://www.lzply.com/four-new-defences-measured/).
## Limitations (v5)
* Whole files are buffered in memory (compress, BCH, and
@@ -729,5 +818,16 @@ nonlinear CRC hybrids), scored on d_min / burst length / cost
against CRC-16, shortened BCH, and RS. Full report:
`randfec/RANDFEC.md`. Headline: random CRC polynomials beat
shortened BCH at n<=32 and at n=64 when searched at the target
size; ROT/XOR, product, and nonlinear families do not. Research
only — nothing integrated into lzply core.
size; ROT/XOR, product, and nonlinear families do not.
Phase 2 (`randfec/PHASE2.md`, `PHASE3.md`, `PHASE4.md`) took three
further shots at a better lzply: **GRAND-MO** — noise guesses
ordered by a burst model fitted to real archive damage — beats
Berlekamp-Massey (e.g. 89.78 -> 97.48 repair rate on burst damage);
a **RaptorQ outer layer** ties Reed-Solomon everywhere (max gap
0.06 points over 350,300 trials) and wins nowhere; and the **CRC
polynomial swap** buys nothing under an ML decoder (within +/-0.35
points at n<=32, worse at (64,48,16)). Short LDPC was a dead end
too — no per-bit reliability signal exists in lzply's channel.
Write-up: [Three shots at a better lzply](https://www.lzply.com/three-shots-at-a-better-lzply/).
Research only — nothing integrated into lzply core.
+88
View File
@@ -0,0 +1,88 @@
#!/bin/sh
# Benchmarks for the integrated winners vs plain lzply at b27b345.
# Runs on hot_newyork in the integrated checkout. The lzply core is
# untouched by the integration (binaries md5-identical to pristine
# b27b345), so the lzply numbers below ARE the plain-b27b345 numbers.
# Each timed measurement is best-of-3; sizes are exact.
# Output: stdout + results file $OUT.
set -u
ROOT=$PWD
W=$ROOT/testwork-bench
OUT=$W/bench-results.txt
mkdir -p "$W"
: > "$OUT"
say() { printf '%s\n' "$*" | tee -a "$OUT"; }
# t3 <label> <cmd...>: best-of-3 wall seconds
t3() {
label=$1; shift
best=""
for i in 1 2 3; do
s=$(date +%s.%N)
"$@" >/dev/null 2>&1
e=$(date +%s.%N)
d=$(awk -v s="$s" -v e="$e" 'BEGIN{printf "%.3f", e-s}')
if [ -z "$best" ] || [ "$(awk -v a="$d" -v b="$best" 'BEGIN{print (a<b)?1:0}')" = 1 ]; then best=$d; fi
done
say "$label best-of-3: ${best}s"
echo "$best"
}
say "== benchmark run $(date -u +%Y-%m-%dT%H:%M:%SZ) hot_newyork $(nproc) cores load: $(uptime | sed 's/.*average: //')"
say "== data set =="
# mixed set: repo docs (text) + repo C sources (code) + system binaries
mkdir -p "$W/mixed"
# Varied content only: repetition compresses to ~nothing under lzip.
find "$ROOT" -type f \( -name "*.md" -o -name "*.c" -o -name "*.h" -o -name "*.sh" -o -name "*.py" -o -name "*.txt" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -not -path "$ROOT/testdata/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/text.txt"
find "$ROOT" -type f \( -name "*.c" -o -name "*.h" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/code.c"
cp /bin/ls /bin/cat /usr/bin/lzip "$W/mixed/" 2>/dev/null
head -c 1048576 /dev/urandom > "$W/rand1m.bin"
ls -l "$W/mixed" | tee -a "$OUT"
say "mixed dir bytes: $(du -sb "$W/mixed" | cut -f1); rand1m: 1048576"
lzip -6 -c "$W/mixed/text.txt" > "$W/text.lz"
lzip -6 -c "$W/mixed/code.c" > "$W/code.lz"
cat "$W/text.lz" "$W/code.lz" > "$W/mixed.lz"
say "lzip -6 blobs: text.lz $(stat -c%s "$W/text.lz"), code.lz $(stat -c%s "$W/code.lz"), mixed.lz $(stat -c%s "$W/mixed.lz")"
say ""
say "== plain lzply at b27b345 (integrated binary, md5 = pristine) =="
"$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" >/dev/null 2>&1
say "lzply -c -6 mixed: $(stat -c%s "$W/mixed.lzply") bytes"
t3 "lzply -c -6 mixed" "$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" > /dev/null
mkdir -p "$W/mixed-out"
t3 "lzply -d mixed" "$ROOT/lzply" -d -y "$W/mixed.lzply" "$W/mixed-out" > /dev/null
"$ROOT/lzply" -c -y -6 -e 0 "$W/mixed" "$W/mixed-e0.lzply" >/dev/null 2>&1
say "lzply -c -6 -e 0 mixed: $(stat -c%s "$W/mixed-e0.lzply") bytes (no BCH)"
"$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" >/dev/null 2>&1
say "lzply -c -6 rand1m: $(stat -c%s "$W/rand.lzply") bytes (stored, level 0 expected)"
t3 "lzply -c -6 rand1m" "$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" > /dev/null
t3 "lzply -d rand1m" "$ROOT/lzply" -d -y "$W/rand.lzply" "$W/rand-out" > /dev/null
say ""
say "== exp bench --speed, 64 KiB windows, mixed.lz blob =="
for c in bch-t32 bch1k-t32 intlv-d64-bch1k-t32 ldpc-r90; do
"$ROOT/exp/bench" --codec "$c" --blob "$W/mixed.lz" --size 65536 --speed --out "$W/speed-$c.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
done
say "CSV (codec,corpus,win,trials,mode,param,success,rescued,rate,enc_MBps,dec_MBps,rss_kb,ovh_pct):"
cat "$W"/speed-*.csv | tee -a "$OUT"
say ""
say "== exp bench: recovery on the mixed blob (20 trials) =="
"$ROOT/exp/bench" --codec intlv-d64-bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --burst 256,1 --out "$W/mixed-intlv-burst.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
"$ROOT/exp/bench" --codec bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --ber 1e-3 --out "$W/mixed-bch1k-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
"$ROOT/exp/bench" --codec ldpc-r90 --blob "$W/mixed.lz" --size 65536 --trials 10 --ber 1e-3 --out "$W/mixed-ldpc-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
say ""
say "== dict transform vs plain lzip -6 (sizes, bytes) =="
for f in text code; do
if [ "$f" = text ]; then SRC="$W/mixed/text.txt"; else SRC="$W/mixed/code.c"; fi
lzip -6 -c "$SRC" > "$W/$f.plain.lz"
"$ROOT/experiments/dict" c "$SRC" "$W/$f.dict" && lzip -6 -k -f "$W/$f.dict"
say "$f: plain lzip6 $(stat -c%s "$W/$f.plain.lz") vs dict+lzip6 $(stat -c%s "$W/$f.dict.lz")"
done
say ""
say "== rANS order-0 (infrastructure context) =="
"$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans"
say "text: plain $(stat -c%s "$W/mixed/text.txt") -> rANS order-0 $(stat -c%s "$W/text.rans")"
t3 "rans_tool c text" "$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans" > /dev/null
t3 "rans_tool d text" "$ROOT/experiments/rans_tool" d "$W/text.rans" "$W/text.rans.out" > /dev/null
say "== done =="
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)
+52
View File
@@ -0,0 +1,52 @@
/* chase_cuda_stub.c - CPU-only fallback for the CUDA Chase-1 entry points.
*
* Defines the two symbols deep_repair.c references (chase_cuda_available,
* chase_cuda_scan1) for builds without nvcc, so a CPU-only link always
* resolves. The stub reports "no GPU": the caller in deep_repair.c then
* takes the CPU Chase-1 path, exactly as it does when a CUDA build is
* present but no device is found.
*
* This exists for the same reason as bch_cuda_stub.c: the weak-symbol
* fallback it replaces does not work on macOS. deep_repair.c declares
* these functions __attribute__((weak)), expecting them to resolve to
* NULL when no CUDA object is linked. GNU ld does that; macOS ld64
* does not -- a weak declaration is a weak definition, not a weak
* import, so the link fails with undefined _chase_cuda_available /
* _chase_cuda_scan1 symbols (run 7 on main, both arm64 and x86_64).
* Defining the symbols outright removes all reliance on
* linker-specific weak-symbol behaviour, on every platform.
*
* The stub is built only when nvcc is absent (see the Makefile:
* CUDA_STUB_OBJ is empty whenever CHASE_CUDA_OBJ is set), so the
* symbols are defined exactly once in every build.
*/
#include <stddef.h>
#include <stdint.h>
#include "bch.h"
#include "chase_cuda.h"
int chase_cuda_available(void)
{
return 0;
}
int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out)
{
(void)in;
(void)in_len;
(void)data_len;
(void)p;
(void)cands;
(void)max_cands;
(void)suspects;
(void)nsuspects;
(void)trials_out;
(void)split_pass_out;
(void)codewords_out;
return -2;
}
+56 -3
View File
@@ -23,6 +23,16 @@
#include "rs.h"
#include "sha256.h"
/* CUDA Chase-1 (chase_cuda.cu), linked only when nvcc is available
* at build time; weak so a CPU-only build links and runs unchanged
* (same pattern as bch_cuda in bch.c on main). */
extern int chase_cuda_available(void) __attribute__((weak));
extern int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out) __attribute__((weak));
/* Decompress a blob and verify its SHA-256. Returns a malloc'd raw
* buffer (caller frees) or NULL on failure. Level 0 means stored
* uncompressed (the blob is the raw bytes). */
@@ -139,6 +149,42 @@ static void pool_free(block_pool_t *pool, size_t *pool_bytes)
pool->dlen = 0;
}
/* Chase-1 for one block: the CUDA scan when a device is present,
* the CPU scan otherwise. Same candidate contract as
* bch_chase1_block (suspects first, then ascending positions;
* candidates in scan order, so the L1 direct-try order is
* unchanged). *used_cuda is set to 1 when the GPU scan ran.
* The GPU scan has no deadline (it runs the full scan in ~0.35 s
* on a 524 KiB block); when the deadline is already past, the CPU
* scan runs instead and reports partial as usual. A -2 from the
* GPU scan (not t=8, or CUDA failed) also falls back to CPU. */
static int chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
bch_chase_stats_t *stats, double deadline,
int *used_cuda)
{
*used_cuda = 0;
if (chase_cuda_available && chase_cuda_available() &&
(deadline < 0 || bch_now() < deadline)) {
long trials = 0, split_pass = 0, codewords = 0;
int ncc = chase_cuda_scan1(in, in_len, data_len, p, cands,
max_cands, suspects, nsuspects,
&trials, &split_pass, &codewords);
if (ncc >= 0) {
stats->trials = trials;
stats->split_pass = split_pass;
stats->codewords = codewords;
stats->candidates = ncc;
stats->partial = 0;
*used_cuda = 1;
return ncc;
}
}
return bch_chase1_block(in, in_len, data_len, p, cands, max_cands,
suspects, nsuspects, stats, deadline);
}
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
int is_bch, uint16_t poly_id, int rs_level,
const uint8_t want_sha[32], size_t blob_size,
@@ -372,7 +418,8 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
free(bc);
}
added1 = pools[bi].n; /* pool size after pass-2 */
/* Chase-1 candidates (suspects first, then scan). */
/* Chase-1 candidates (suspects first, then scan) --
* GPU when a device is present, else CPU. */
{
size_t *susp = malloc(sizeof(size_t) *
BCH_CHASE_MAX_SUSPECTS);
@@ -389,10 +436,16 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
bslen[bi], bdlen[bi],
poly, susp,
BCH_CHASE_MAX_SUSPECTS);
ncc = bch_chase1_block(bch_stored + s_off,
{
int used_cuda = 0;
ncc = chase1_block(bch_stored + s_off,
bslen[bi], bdlen[bi], poly,
cc, BCH_CHASE_MAX_CANDS,
susp, ns, &cs, deadline);
susp, ns, &cs, deadline,
&used_cuda);
if (used_cuda)
stats->chase_cuda_used = 1;
}
stats->trials[1] += cs.trials;
stats->split_pass[1] += cs.split_pass;
stats->codewords[1] += cs.codewords;
+1
View File
@@ -67,6 +67,7 @@ typedef struct {
long blocks_total; /* BCH blocks in the blob */
long blocks_failed; /* blocks failing standard decode */
int partial; /* a level stopped early on its budget */
int chase_cuda_used; /* L1 ran on the GPU (CUDA Chase-1 scan) */
char fail_stage[24]; /* "ok", "rs", "len", "crc", "sha",
"budget", "noecc", "nocand" */
} deep_stats_t;
+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.
+203
View File
@@ -0,0 +1,203 @@
# Integration: experiment winners on current main (LZPL v5)
Merged onto `experiments/integration` at `b27b345` (LZPL v5 + lz_rs +
deep repair + CRC16). The three experiment branches were all based on
`8dbb8d03`; this integration re-bases their winners onto current main
instead. The archive format is unchanged (still LZPL v5): the winners
arrive as standalone tools in `exp/` and `experiments/`, built and
smoke-tested by `tests/run_integration_tests.sh` (hooked into
`make test`). Wiring interleave/LDPC into `lzply -e` levels would be
a format change (LZPL v6) and is explicitly future work, not done here.
## Sources
| branch | tip | carried over |
|---|---|---|
| `experiments/baseline` | `5807281` | `bench/`, `docs/BASELINE.md` (the comparison baseline) |
| `experiments/ecc` | `a34cd7d` | `exp/` harness + interleave + LDPC (see below) |
| `experiments/comp` | `fbce346` | `experiments/` rANS core + dict + bchcheck (see below) |
## Winners (integrated)
### 1. Byte interleaving, depth 64, over small-block BCH (`exp/`)
* What: the encoded stream (BCH, 1 KiB blocks) is permuted before it
hits the channel — groups of D consecutive blocks written row-wise
into a D-row matrix, read out column-wise. A burst of L bytes then
hits any one block at most ceil(L/D) bytes instead of all L bytes
landing in one block and killing it. Zero extra parity: a pure
permutation, inverted on decode, so overhead is exactly the BCH
overhead and random-error performance is unchanged.
* Gotcha fixed on the branch: groups merge the short tail (a 4-block
tail group measured 0.94 on 64 B bursts before the fix).
* Measured (text.lz, 64 KiB windows, 200 trials/setting):
`intlv-d64-bch1k-t32` recovers 1.00 at burst 16/64/256 B and 1.00 at
4x64 B bursts, where uninterleaved `bch1k-t32` recovers 0.00 at every
burst size. Random-error performance unchanged by construction
(1.00 at BER 1e-3, same as `bch1k-t32`). Overhead 5.40%.
Even at 1.29% overhead, `intlv-d64-bch1k-t8` survives 64 B bursts
at 1.00.
* Speed: interleaving costs nothing measurable (3.39 MB/s enc,
1.73 MB/s dec — same as the BCH underneath).
* Use:
```
cd exp && ./mkcorpora.sh # build corpora/text.lz etc.
./bench --codec intlv-d64-bch1k-t32 --blob corpora/text.lz \
--size 65536 --trials 200 --burst 256,1 --out results/x.csv
```
### 2. Small-block BCH, 1 KiB blocks (`exp/`)
* What: the same BCH lzply ships, but forced to m=13 blocks
(971 data bytes/block) instead of one huge block per blob.
This is the "spend real redundancy" point.
* Measured (text.lz, 64 KiB, 200 trials): `bch1k-t32` recovers 1.00
at BER 1e-4 and 1e-3, 0.01 at 3e-3, at 5.40% overhead — where
as-shipped `bch-t32` (one 64 KiB block, 0.12% overhead) recovers
1.00 at 1e-5, 0.01 at 1e-4, 0.00 at 1e-3. Bursts still kill it
without interleaving (256 B burst: 0.00 at every t).
* Speed: `bch1k-t32` 2.97 MB/s enc, 1.55 MB/s dec;
`bch1k-t8` 9.98 / 5.87 MB/s at 1.29% overhead.
* Use:
```
./bench --codec bch1k-t32 --blob corpora/text.lz \
--size 65536 --trials 200 --ber 1e-3
```
### 3. Regular LDPC, rate 0.90 (`exp/`)
* What: regular LDPC, PEG construction, min-sum belief propagation.
n=8192 bits, column weight 3, m=768 checks, row weight 32,
k=7424 bits (928 B). 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, ~1.8 s init).
* Measured (text.lz, 64 KiB, 200 trials): `ldpc-r90` recovers 1.00
at BER 1e-3 and 0.97 at 3e-3, where `bch1k-t32` recovers 0.01 at
3e-3 — the iterative decoder's cliff sits a decade higher in BER.
Overhead 10.94%. Bursts kill it (16 B burst: 0.24); LDPC+interleave
is the follow-up. `ldpc-r95` is weak (0.32 at 1e-3, fails at
6 errors/block); irregular LDPC is the follow-up.
* Speed: 3.34 MB/s enc, 0.91 MB/s dec — ~4x slower decode than
`bch1k-t32`.
* Use:
```
./bench --codec ldpc-r90 --blob corpora/text.lz \
--size 65536 --trials 200 --ber 1e-3
./ldpc_diag r90 40 50 # single-block error-count sweep
```
### 4. Dictionary transform, code-only opt-in (`experiments/`)
* What: per-file word dictionary (top 4096 words by saving,
transmitted in the header), words -> 3-byte codes, then lzip -6.
Format: magic `DICT`, u32 orig_len, u16 ndict, entries (u8 len,
bytes); 0xFF escape introduces a 2-byte code.
* Measured (8 MiB corpora, lzip -6): code 9.19% vs plain lzip6 9.38%
(-2.1% better — long repeated identifiers survive as codes better
than as LZ matches). Everywhere else the dictionary costs more
than it saves: text 3.58 vs 3.56 (+0.5% worse), bin 33.30 vs 32.61,
mixed 17.65 vs 17.41, rand worse. Not a default; a code-only
optional preprocessing stage at most.
* End-to-end BCH check (`bchcheck`): dict+lzip code blob (770,519 B)
BCH t=8, 8 flips -> 8 corrected, full pipeline recovers
bit-identical; 32 flips -> decode FAIL (beyond t=8, honest failure).
* Use (dict takes file paths, not stdin):
```
./dict c code.c code.dict && lzip -6 code.dict
lzip -dc code.dict.lz > code.dict2 && ./dict d code.dict2 code.c.out
```
### Supporting infrastructure: rANS core (`experiments/rans.[ch]`)
* What: the shared entropy stage for the prototypes — static
per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
RSS ~20 MB. Kept as reusable infrastructure, not as a standalone
compressor: order-0 rANS alone scores text 64.40%, code 67.62%
(no LZ stage), so it is a reject as a compressor and a keep as a
core. Two real bugs fixed on the branch (renormalisation threshold;
emitted stream can exceed n bytes, scratch is 2n+64).
* Use: `./rans_tool c in out` / `./rans_tool d in out`.
## Rejects (measured, not carried over)
Only their numbers stay (in `exp/README.md`, `experiments/README.md`,
`experiments/results/*.csv`); the code was removed in the integration
cleanup commit.
| family | verdict | numbers |
|---|---|---|
| Polar SC (`polar-r90`) | dominated, rejected | 0.00 at BER 1e-3 at every design point; designing for p=1e-2 gives 0.00 at 1e-4; best (d4) 0.95 at 1e-4. Dec 0.58 MB/s, slowest of all. SCL list decoding is the follow-up that could rescue it. |
| UEP (unequal error protection) | conditional, not integrated | Whole-file recovery dominated by the weak tier (0.00 at 1e-3). The 1-4 KiB prefix survives (1.00 at 1e-3, 1.00 at 256 B burst) — but only useful if lzply gains a salvage mode; today the entry SHA gates all-or-nothing extraction. |
| LZ77 + rANS (`lzrans`) | rejected as a lzip replacement | lazy: text 6.26, code 13.52, bin 41.84, mixed 23.15; optimal parsing recovers only ~1-3% relative — the gap is LZMA's adaptive context entropy model, not parsing. |
| BWT + MTF + rANS | rejected | text 6.35 (beats bzip2's 9.25), code 12.31, bin 42.76; loses to lzip everywhere; encode 0.05 MB/s (~3 min/8 MB), decode 5-6 MB/s, RSS ~200 MB. |
| PPM order-2 + arithmetic | rejected | text 32.84, code 30.82, mixed 39.18; ~6 MB/s enc, ~4 MB/s dec. Nowhere near PPMd-class. |
| rANS order-0 standalone | rejected as a compressor | text 64.40, code 67.62, bin 77.14 — no LZ stage. Core kept (above). |
## Baselines the winners were measured against
* As-shipped BCH (`bch-t32`): one 64 KiB blob = one BCH block
(m=20, 80 parity bytes, 0.12% overhead, 32 correctable bits per
64 KiB). Cliff between BER 1e-5 and 1e-4 (1.00 -> 0.01).
* Pass 2 (hash-gated candidates) rescues nothing in practice:
0/875 in the pass-2 matrix, 0/50 at every k in the targeted sweep.
Its demonstrated value is the loud-failure guarantee: 0 silent
miscorrections in 7813 checks. See `docs/BASELINE.md`.
* lzip (the current lzply stage): text 3.44-3.56%, code 9.05-9.38%,
bin 32.53-32.61%, mixed 17.17-17.41% at -9..-6. No prototype family
beats lzip on ratio. See `experiments/README.md`.
## Verification on the integrated tree
* `make -j8` then `make test` runs the full suites (bch_test,
rs_test, crc16_test, run_rs_tests.sh, run_tests.sh,
run_deep_repair_tests.sh, run_hyper_tests.sh) plus
`tests/run_integration_tests.sh`: clean round-trips for all three
ECC codecs, intlv-d64 burst survival + uninterleaved control,
bch1k BER survival + as-shipped control, LDPC BER survival,
rANS round-trip, dict+lzip round-trip, bchcheck 8-flip recovery
and 32-flip expected failure, LZPL v5 archive round-trip.
* Cross-corpus check on the branches reproduced text.lz exactly on
bin.lz and rand.lz for every codec and setting.
## Build
```
make -j8 # main tools + lz_rs + deep repair
make exp # exp/bench + ldpc_diag + pass2_diag
make experiments # experiments/rans_tool + dict + bchcheck
make test # full suites + integration smoke tests
```
## Fresh numbers on the integrated tree (hot_newyork, 2026-12-02)
Re-measured after the merge with `bench-integration.sh` (best-of-3
timings, load ~1.2-1.6). Data set: mixed dir 25,521,882 bytes (repo
text + repo C sources + /bin/ls, /bin/cat, /usr/bin/lzip) + 1 MiB
/dev/urandom. The lzply core is untouched by the integration, so the
plain-lzply numbers below are the b27b345 numbers.
Plain lzply at b27b345:
- `lzply -c -6` mixed: 7,060,165 bytes, 22.904 s compress / 1.594 s extract
- `lzply -c -6 -e 0` mixed: 7,059,797 bytes (BCH adds 368 bytes here)
- `lzply -c -6` rand1m: 1,048,750 bytes (stored, level 0), 0.577 s / 0.060 s
exp bench --speed, mixed.lz blob (308,207 bytes), 64 KiB windows:
- bch-t32: enc 8.59 MB/s, dec 4.28 MB/s, overhead 0.12%
- bch1k-t32: enc 3.72 MB/s, dec 1.93 MB/s, overhead 5.40%
- intlv-d64-bch1k-t32: enc 3.77 MB/s, dec 1.72 MB/s, overhead 5.40%
- ldpc-r90: enc 4.08 MB/s, dec 1.07 MB/s, overhead 10.94%, init 1.87 s
Recovery on the mixed blob (fresh, reproduces the branch matrices):
- intlv-d64-bch1k-t32, 256 B burst: 1.000 (20 trials)
- bch1k-t32, BER 1e-3: 1.000 (20 trials)
- ldpc-r90, BER 1e-3: 1.000 (10 trials)
Dictionary transform on this corpus (repo C sources only, 786,430
bytes): plain lzip6 120,409 vs dict+lzip6 123,662 (+2.7% worse) --
the branch -2.1% win was on header-heavy code (8 MiB of /usr/include
headers + repo sources). On text (1,004,068 bytes): plain 187,798 vs
dict 191,045 (+1.7% worse). The code-only conditional stands, and it
is corpus-dependent: headers win, plain C sources do not.
rANS order-0 on text (1,004,068 bytes): 614,658 bytes (61.2%),
enc ~31 MB/s, dec ~42 MB/s.
+56 -5
View File
@@ -1,11 +1,13 @@
# Deep repair — past the BCH limit t
`lzply_deep_repair` recovers archive entries whose bit errors exceed
Deep repair recovers archive entries whose bit errors exceed
the BCH correction limit t, in escalating levels, reporting
per-level timing ("time of arrival": how long each level took and
at which level the repair landed). The CRC16 is the oracle: every
beyond-t candidate is CRC-verified before acceptance, then
decompressed and SHA-256-checked.
at which level the repair landed). It is built into the main tool
(`lzply -r archive`, same levels and options as the standalone
`lzply_deep_repair` binary, which is still shipped). The CRC16
is the oracle: every beyond-t candidate is CRC-verified before
acceptance, then decompressed and SHA-256-checked.
## The levels
@@ -37,6 +39,43 @@ decompressed and SHA-256-checked.
holds its true data in the pool but neither single-block
variation passes the CRC.
## The CUDA Chase-1 scan (L1 on the GPU)
On a CUDA build (nvcc present at build time -- `make` links
`chase_cuda.o` into `lzply` and `lzply_deep_repair` automatically;
without nvcc the build is CPU-only and nothing changes), the L1
Chase-1 scan runs on the GPU when a CUDA device is present. The
dispatch is automatic: there is no flag. The scan is the same
algorithm as the CPU one (one thread per trial position:
Berlekamp-Massey + the lambda-splits test, Chien search in
parallel for survivors, host syndrome-zero verification), and
produces the same candidates in the same order -- verified
bit-identical across the 5-pattern validation and a 24-pattern
sweep (10/10 CPU/CUDA hash agreements, zero mismatches).
Measured on hot_house (RTX 3080 Ti), one 524 KiB block (m=22,
t=8, -e4), 4,194,296 trials: **171.571 s CPU -> 0.335-0.379 s
CUDA (453-512x on the timed scan, ~190x end to end)**; the
extended sweep runs 453-562x. A beyond-t repair of a 524 KiB
block that took ~8 minutes at L1 now lands in under a second.
`-v` marks the L1 line `(CUDA)` when the GPU scan ran.
Fallback: the CPU scan runs whenever the GPU scan cannot -- no
CUDA device, a CPU-only build, a non-t=8 poly (the kernel is
t=8 only), a CUDA failure, or a deadline already past when the
scan would start. The symbols are referenced weakly, so a
CPU-only build links and runs unchanged.
Limits: the kernel is t=8 only; Chase-2 is not ported (L2 stays
on the CPU). The GPU scan has no deadline -- it runs the full
scan, then truncates at `BCH_CHASE_MAX_CANDS` (the CPU scan
stops early at the cap when the budget hits); the candidate set
still matches. On small blocks the ~0.115 s CUDA first-touch
cost dominates -- a 512-byte block repairs in ~0.11 s on the GPU
vs ~0.04 s on the CPU -- so the win is on large blocks.
Full write-up: https://www.lzply.com/cuda-chase-500x-deep-repair/
## Why the suspect set does not help Chase-2 (much)
With hard-decision input there is no channel reliability, so
@@ -98,6 +137,16 @@ lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive
```
The same repair is built into the main tool:
```
lzply -r [--level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive [outdir]
```
`-r` takes the same levels, budget, and output options
(`--level` in place of `-l`, which is the list mode in `lzply`).
Per-entry output:
```
@@ -168,7 +217,9 @@ wrong-but-valid candidates per trial and the CRC rejects all
`bch_test` 7,975 checks still pass). A full Chase-1 scan of a
524 KiB block (4,194,296 trials) takes **471.9 s** (measured,
probe5: RECOVERED at L1 in 471.918 s, trials 4,194,296,
split 126, codewords 126). The tool scans fully before trying
split 126, codewords 126). On a CUDA build the same scan runs
on the GPU in ~0.35 s (see the CUDA section above); 471.9 s is
the CPU scan. The tool scans fully before trying
candidates (the chase layer has no oracle), so the landing time
is the full-scan time, not the time to the lowest true error.
At the default 120 s budget a beyond-t repair of a 524 KiB
+6
View File
@@ -0,0 +1,6 @@
bench
ldpc_diag
pass2_diag
*.o
corpora/
results/
+26
View File
@@ -0,0 +1,26 @@
# 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 \
../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
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
clean:
rm -f bench ldpc_diag pass2_diag $(OBJS)
.PHONY: clean
+206
View File
@@ -0,0 +1,206 @@
# lzply ECC experiments (branch `experiments/ecc`)
> Integrated onto current main (`experiments/integration`, LZPL v5):
> the winners here are interleaving d64, small-block BCH 1 KiB, and
> LDPC r90. Polar and UEP were measured, rejected, and their code was
> NOT carried over — see `docs/INTEGRATION.md`.
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
@@ -0,0 +1,158 @@
/* 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
@@ -0,0 +1,10 @@
/* 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 */
+338
View File
@@ -0,0 +1,338 @@
/* 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);
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);
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");
}
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
@@ -0,0 +1,40 @@
/* 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
@@ -0,0 +1,253 @@
/* 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
@@ -0,0 +1,565 @@
/* 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
@@ -0,0 +1,71 @@
/* 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
@@ -0,0 +1,27 @@
#!/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
@@ -0,0 +1,89 @@
/* 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;
}
+21
View File
@@ -0,0 +1,21 @@
#!/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
@@ -0,0 +1,18 @@
#!/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"
+32
View File
@@ -0,0 +1,32 @@
# experiments/Makefile - prototypes for the lzply compression research.
# Built with max cores via -j; each tool is standalone: `tool c in out`,
# `tool d in out`. Shared rANS core in rans.o.
CC = gcc
CFLAGS = -O3 -Wall -Wextra -march=native
LDLIBS = -llz -lm
TOOLS = rans_tool dict bchcheck
all: $(TOOLS)
rans.o: rans.c rans.h
$(CC) $(CFLAGS) -c -o $@ rans.c
rans_tool: rans_tool.o rans.o
$(CC) $(CFLAGS) -o $@ rans_tool.o rans.o
dict.o: dict.c
$(CC) $(CFLAGS) -c -o $@ dict.c
dict: dict.o
$(CC) $(CFLAGS) -o $@ dict.o
bchcheck.o: bchcheck.c ../bch.h
$(CC) $(CFLAGS) -I.. -c -o $@ bchcheck.c
bchcheck: bchcheck.o ../bch.o ../bch_polys.h
$(CC) $(CFLAGS) -o $@ bchcheck.o ../bch.o
clean:
rm -f $(TOOLS) *.o
.PHONY: all clean
+140
View File
@@ -0,0 +1,140 @@
# lzply compression experiments (branch experiments/comp)
> Integrated onto current main (`experiments/integration`, LZPL v5):
> the winners here are the dictionary transform (code-only) and the
> rANS core as infrastructure. lzrans, BWT, and PPM were measured,
> rejected, and their code was NOT carried over — see
> `docs/INTEGRATION.md`.
Prototypes for open-ended compression research. Each tool is standalone:
`tool c|o in out`, `tool d in out`. Shared rANS core in rans.[ch].
`bench.py <name> <enc> <dec> [corpora...]` times (best of 3), sizes,
and sha256-verifies round-trips; `bench1.py` is the single-run variant
(for slow tools); CSVs land in results/.
## Corpora (built by mkcorpora.py, deterministic per machine)
- text: 8 MiB UTF-8 docs from /usr/share/doc + common-licenses
- code: 8 MiB C headers (/usr/include) + this repo's sources
- bin: 8 MiB ELF binaries from /bin + /usr/bin
- mixed: 8 MiB round-robin 64 KiB chunks of text+code+bin
- rand: 4 MiB /dev/urandom (seed 1234), incompressible control
Corpora are NOT committed (regenerate with mkcorpora.py).
All ratios below are compressed/orig %; speeds are MB/s (orig bytes).
## Baseline: lzip (the current lzply stage; same liblz, same levels)
| tool | text | code | bin | mixed | rand | enc MB/s | dec MB/s |
|---|---|---|---|---|---|---|---|
| lzip -1 | 6.22 | 15.13 | 37.83 | 21.58 | 101.36 | 1.4-9.1 | 8.9-71.8 |
| lzip -6 | 3.56 | 9.38 | 32.61 | 17.41 | 101.36 | 0.9-2.3 | 7.9-71.4 |
| lzip -9 | 3.44 | 9.05 | 32.53 | 17.17 | 101.36 | 0.8-1.4 | 9.0-70.3 |
References: xz -6 ~= lzip -6 (text 3.51, code 9.20, bin 32.59,
mixed 17.30); zstd -19 text 3.63, code 9.48, bin 34.81, mixed 18.31;
gzip -9 text 23.48, code 16.40, bin 44.14, mixed 30.06;
bzip2 -9 text 9.25, code 12.55, bin 40.22, mixed 23.53,
dec only 5-9 MB/s.
## ANS: rANS order-0 (rans_tool) — REJECT as standalone, KEEP core
Static per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
RSS ~20 MB, but no LZ stage: text 64.40, code 67.62, bin 77.14,
mixed 78.11, rand 100.46. The core is the entropy stage for the BWT
and LZ prototypes below. (Two real bugs found and fixed in the core:
renormalisation threshold must be (L>>12)*f<<8 or the decoder
over-reads; the emitted stream can exceed n bytes, scratch is 2n+64.)
## LZ77 + rANS (lzrans) — REJECT as a lzip replacement
Hash-chain finder, 1 MiB window, lazy (`c`) and optimal-parse (`o`)
modes, deflate-style length codes, log2 distance codes, litlen/dist
rANS streams + raw extra bits.
| mode | text | code | bin | mixed | rand | enc | dec | RSS |
|---|---|---|---|---|---|---|---|---|
| lazy | 6.26 | 13.52 | 41.84 | 23.15 | 100.48 | 0.5-4.4 | 26-73 | 44 MB |
| optimal | 6.19 | 13.05 | — | — | — | 0.4-1.0 | 64-73 | 173 MB |
Optimal parsing recovers only ~1-3% relative, so the gap is not
parsing: it is LZMA's adaptive context entropy model plus deeper
match search and a larger dictionary. A static-table rANS cannot
close a ~75% relative gap on text.
## BWT + MTF + run tokens + rANS (bwt) — REJECT as a lzip replacement
Suffix array by cyclic doubling (see the linear-vs-rotation trap
below), MTF, runs >=4 tokenised as (value, 256, k), 257-symbol rANS.
| corpus | ratio | enc | dec |
|---|---|---|---|
| text | 6.35 | 177 s (0.05 MB/s) | 5.3 MB/s |
| code | 12.31 | 173 s | 6.3 MB/s |
| bin | 42.76 | 137 s | 5.9 MB/s |
| mixed | (bench running) | | |
| rand | (bench running) | | |
RSS ~200 MB. Beats bzip2 on text (6.35 vs 9.25), ~ties on code
(12.31 vs 12.55), loses on bin (42.76 vs 40.22); loses to lzip
everywhere by a wide margin. Encode is ~3 min/8 MB (doubling SA is
memory-latency-bound over 160 MB of rank arrays); decode is 5-6 MB/s
(LF-walk random access).
GOTCHA (real bug, fixed): a linear suffix sort is NOT rotation
order — "a" < "a bandana" linearly, but cyclically
"a bandanabanan" < "abanana bandan". A sentinel does not fix it
("a$" < "a bandana$" truncates the comparison). The SA must use
cyclic doubling (rank[(i+k) % n]).
## PPM order-2 + arithmetic coding (ppm) — REJECT
Order-2/1/0 contexts, escape mass = distinct-symbol count,
Witten-Neal-Cleary 32-bit arithmetic coder, counts updated in all
levels after every symbol. RSS ~80 MB.
| corpus | ratio | enc MB/s | dec MB/s |
|---|---|---|---|
| text | 32.84 | 6.3 | 3.9 |
| code | 30.82 | 6.3 | 4.1 |
| mixed | 39.18 | 4.8 | 3.2 |
Far behind lzip and slow: the bit-level coder plus 256-wide level
scans cost ~6 MB/s encode, ~4 MB/s decode. A simple order-2 PPM
with heavy escape mass is nowhere near PPMd-class.
## Dictionary transform + lzip (dict) — CONDITIONAL, code only
Per-file word dictionary (top 4096 words by saving, transmitted in
the header), words -> 3-byte codes, then lzip -6. RSS ~32 MB.
| corpus | dict+lzip6 | plain lzip6 | delta |
|---|---|---|---|
| text | 3.58 | 3.56 | +0.5% worse |
| code | 9.19 | 9.38 | -2.1% BETTER |
| bin | 33.30 | 32.61 | +2.1% worse |
| mixed | 17.65 | 17.41 | +1.4% worse |
| rand | 101.73 | 101.36 | worse |
Only code wins (+2.1%): long repeated identifiers survive as codes
better than as LZ matches. Everywhere else the dictionary costs
more than it saves (lzip already captures word repeats). Not a
default; a code-only optional preprocessing stage at most.
(Gotcha fixed during the build: words are sorted by count, so the
saving filter must `continue`, not `break`, or a short frequent
word like "the" discards the whole dictionary.)
## BCH end-to-end (bchcheck) — winners survive error correction
Blob -> BCH(t=8, lzply -e 4 level) -> flip N bits -> decode ->
decompress -> sha256 check.
- dict+lzip code blob (770,519 B): poly 0050, stored 770,563
(+44 B parity, 0.006%). 8 flips -> 8 corrected, full pipeline
recovers bit-identical. 32 flips -> decode FAIL (exceeds t=8 per
block; honest failure mode).
- plain lzip6 code blob (787,213 B): 8 flips -> 8 corrected,
recovered + decoded bit-identical.
## Verdicts (bottom line)
- No family beats lzip on ratio. lzip/LZMA's adaptive entropy
model + deep match search + large dictionary is very hard to beat
with a from-scratch prototype in this scope.
- KEEP: the rANS core (fast, correct, reusable as an entropy stage).
- CONDITIONAL: dict transform, code-only (+2.1% on code).
- REJECT: lzrans (lazy + optimal), BWT, PPM order-2, rANS order-0
standalone. Honest negatives, numbers above.
- Test totals: 334 timed bench invocations, all sha256-verified OK
(plus ~25 manual small-input round-trips and 3 BCH runs: 2 pass,
1 expected fail at 32 flips).
## Notes / environment
- hot_newyork (172.93.49.176), 8 cores, 30 GB RAM; server load was
10-17 during the runs (shared with other agents), so absolute
MB/s figures are load-dependent; ratios are exact.
- hot_chicago verification pending: its SSH stopped accepting new
sessions Dec 2 (sshd can't fork under load); a retry agent is
probing every 15 min. No Chicago numbers yet.
- The other lz_rs/deep-repair coordinator works in /opt/lzply/src
and /root/lzrs-verify/lzply; untouched by this work. No
Reed-Solomon was (re-)implemented here.
+88
View File
@@ -0,0 +1,88 @@
/* bchcheck.c - BCH end-to-end corruption test for experiment blobs.
* Takes a compressed blob, BCH-encodes it (t=8 by default, the lzply
* -e 4 level; largest t=8 poly if the blob exceeds one m=22 block),
* flips N random bits (seeded), decodes, and writes the recovered
* blob. Exit 0 if the recovered blob is byte-identical to the input,
* 1 if decode failed or the blob differs, 2 on usage/IO error.
* Usage: bchcheck blob nflips seed out [t]
* The caller then decompresses `out` with the prototype and checks
* the sha256 round-trip, proving the compressed stream survives BCH.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
/* Largest-capacity poly with the requested t (m=22 wins). */
static const bch_poly_t *largest_t_poly(int t) {
const bch_poly_t *best = NULL;
size_t bestcap = 0;
for (uint16_t id = 0x0001; id <= 0x0052; id++) {
const bch_poly_t *p = bch_poly_by_id(id);
if (!p || p->t != t) continue;
size_t cap = bch_max_data(p);
if (cap > bestcap) { bestcap = cap; best = p; }
}
return best;
}
int main(int argc, char **argv) {
if (argc < 5 || argc > 6) {
fprintf(stderr, "usage: %s blob nflips seed out [t]\n", argv[0]);
return 2;
}
int t = argc == 6 ? atoi(argv[5]) : 8;
long nflips = atol(argv[2]);
unsigned seed = (unsigned)atoi(argv[3]);
size_t n;
uint8_t *blob = slurp(argv[1], &n);
const bch_poly_t *poly = bch_poly_for_data(n, t);
if (!poly) poly = largest_t_poly(t);
if (!poly) { fprintf(stderr, "bchcheck: no poly for t=%d\n", t); return 2; }
size_t slen = bch_encoded_len(n, poly);
uint8_t *stored = malloc(slen ? slen : 1);
uint8_t *rec = malloc(n ? n : 1);
if (!stored || !rec) return 2;
if (bch_encode(blob, n, poly, stored) != slen) {
fprintf(stderr, "bchcheck: encode failed\n");
return 2;
}
/* xorshift64 PRNG for flip positions (seeded, deterministic) */
uint64_t xs = (uint64_t)seed * 0x9E3779B97F4A7C15ULL + 0x123456789ULL;
for (long k = 0; k < nflips; k++) {
xs ^= xs << 13; xs ^= xs >> 7; xs ^= xs << 17;
size_t bit = (size_t)(xs % (uint64_t)(slen * 8));
stored[bit / 8] ^= (uint8_t)(0x80u >> (bit % 8));
}
int corrected = 0;
int rc = bch_decode(stored, slen, n, poly, rec, &corrected);
fprintf(stderr, "bchcheck: poly=%04x blob=%zu stored=%zu overhead=%.1f%% "
"flips=%ld corrected=%d decode=%s\n",
poly->id, n, slen, 100.0 * (double)(slen - n) / (double)n,
nflips, corrected, rc == 0 ? "OK" : "FAIL");
if (rc != 0) return 1;
FILE *f = fopen(argv[4], "wb");
if (!f) { perror(argv[4]); return 2; }
if (n && fwrite(rec, 1, n, f) != n) return 2;
fclose(f);
if (memcmp(blob, rec, n) != 0) {
fprintf(stderr, "bchcheck: recovered blob DIFFERS\n");
return 1;
}
return 0;
}
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""bench.py <name> <enc-template> <dec-template> [corpus...]
Templates use {in} {out} {dec}; run via /bin/sh. Times encode/decode
(wall, best of 3 for encode, best of 3 for decode), records ratio,
MB/s, sha256 round-trip. Appends CSV rows to results/<name>.csv and
prints a table. Encode failure on a corpus records 'FAIL'.
"""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def bench_one(name, enc, dec, corpus):
src = os.path.join(CORP, corpus)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
best_enc = None
for _ in range(3):
rc, dt = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, None, None, None, "ENCFAIL")
best_enc = dt if best_enc is None else min(best_enc, dt)
csize = os.path.getsize(out)
best_dec = None
for _ in range(3):
if os.path.exists(decf):
os.unlink(decf)
rc, dt = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, csize, None, None, "DECFAIL")
best_dec = dt if best_dec is None else min(best_dec, dt)
ok = sha(decf) == want
return (corpus, n, csize, best_enc, best_dec, "OK" if ok else "MISMATCH")
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name}: enc=[{enc}] dec=[{dec}]")
print(f"{'corpus':8s} {'orig':>9s} {'comp':>9s} {'ratio%':>7s} {'encMB/s':>8s} {'decMB/s':>8s} status")
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
corpus, n, cs, es, ds, st = bench_one(name, enc, dec, c)
if cs is None:
print(f"{c:8s} {n:9d} {'-':>9s} {'-':>7s} {'-':>8s} {'-':>8s} {st}")
w.writerow([name, c, n, "", "", "", "", "", "", st])
continue
ratio = 100.0 * cs / n
emb = n / 1e6 / es if es else 0
dmb = n / 1e6 / ds if ds else 0
print(f"{c:8s} {n:9d} {cs:9d} {ratio:7.2f} {emb:8.1f} {dmb:8.1f} {st}")
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{emb:.1f}", f"{dmb:.1f}", st])
print("csv: " + csvp)
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""bench1.py: single-run variant of bench.py (for slow tools like bwt).
Usage: bench1.py <name> <enc-template> <dec-template> [corpus...]
Appends to results/<name>.csv and prints one line per corpus."""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=3600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name} (single run)", flush=True)
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
src = os.path.join(CORP, c)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
rc, es = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: ENCFAIL", flush=True)
w.writerow([name, c, n, "", "", "", "", "", "", "ENCFAIL"])
continue
cs = os.path.getsize(out)
if os.path.exists(decf):
os.unlink(decf)
rc, ds = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: DECFAIL", flush=True)
w.writerow([name, c, n, cs, "", "", "", "", "", "DECFAIL"])
continue
ok = sha(decf) == want
st = "OK" if ok else "MISMATCH"
ratio = 100.0 * cs / n
print(f"{c:8s} {n:9d} {cs:9d} {ratio:6.2f}% enc {es:7.1f}s "
f"({n/1e6/es:5.1f} MB/s) dec {ds:6.1f}s ({n/1e6/ds:5.1f} MB/s) {st}",
flush=True)
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{n/1e6/es:.1f}", f"{n/1e6/ds:.1f}", st])
print("csv: " + csvp, flush=True)
if __name__ == "__main__":
main()
+260
View File
@@ -0,0 +1,260 @@
/* dict.c - word-dictionary transform (preprocessing stage for lzip).
* Builds a per-file dictionary of the most frequent words (alnum runs
* of length >= 3), replaces them with 2-byte codes, then the caller
* pipes the output through lzip. The dictionary is transmitted in
* the header, so the cost is honest.
* Format: magic "DICT", u32 orig_len, u16 ndict, then ndict entries
* (u8 len, bytes), then the transformed stream: 0xFF escape byte
* introduces a 2-byte code (little-endian); a literal 0xFF in the
* data is escaped as 0xFF 0xFF 0xFF (escape + code 0xFFFF = literal
* 0xFF); other bytes pass through. Words are maximal [A-Za-z0-9_]
* runs; only words in the dictionary are replaced.
* Usage: dict c in out | dict d in out
* (then: lzip -6 transformed; decode: lzip -d | dict d)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define ESC 0xFF
#define MAX_DICT 4096
#define MIN_WORD 3
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
static int is_word(int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '_';
}
/* word table entry */
typedef struct { char *w; uint32_t count; } went_t;
static int cmp_count(const void *a, const void *b) {
uint32_t ca = ((const went_t *)a)->count, cb = ((const went_t *)b)->count;
return ca < cb ? 1 : ca > cb ? -1 : 0;
}
static uint32_t hash_str(const char *s, size_t n) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < n; i++) { h ^= (uint8_t)s[i]; h *= 16777619u; }
return h;
}
static int encode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
/* count words in a hash table (open addressing) */
size_t hcap = 1 << 20;
went_t *ht = calloc(hcap, sizeof *ht);
if (!ht) return 2;
size_t i = 0;
while (i < n) {
if (!is_word(in[i])) { i++; continue; }
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (hcap - 1);
while (ht[h].w) {
if (strlen(ht[h].w) == len &&
memcmp(ht[h].w, in + i, len) == 0) break;
h = (h + 1) & (hcap - 1);
}
if (!ht[h].w) {
ht[h].w = malloc(len + 1);
memcpy(ht[h].w, in + i, len);
ht[h].w[len] = 0;
}
ht[h].count++;
}
i = j;
}
/* collect, sort by count, keep the top MAX_DICT by SAVING:
* saving = count * (len - 3) - (len + 1) [dict cost]; keep > 0 */
went_t *all = malloc(hcap * sizeof *all);
size_t na = 0;
for (size_t k = 0; k < hcap; k++)
if (ht[k].w) all[na++] = ht[k];
qsort(all, na, sizeof *all, cmp_count);
went_t *dict = malloc(MAX_DICT * sizeof *dict);
size_t nd = 0;
for (size_t k = 0; k < na && nd < MAX_DICT; k++) {
size_t len = strlen(all[k].w);
/* code costs 3 bytes (ESC + 2), word costs len; saving per
* occurrence = len - 3; dict entry costs len + 1 bytes */
int64_t saving = (int64_t)all[k].count * ((int64_t)len - 3) -
(int64_t)(len + 1);
if (saving <= 0) continue; /* sorted by count, not saving */
dict[nd++] = all[k];
}
/* rebuild a lookup hash for the kept dictionary: code = index */
size_t lcap = 1 << 16;
int32_t *look = malloc(lcap * sizeof *look);
if (!look) return 2;
for (size_t k = 0; k < lcap; k++) look[k] = -1;
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
uint32_t h = hash_str(dict[k].w, len) & (lcap - 1);
while (look[h] >= 0) h = (h + 1) & (lcap - 1);
look[h] = (int32_t)k;
}
/* transform */
size_t cap = n + 1024;
uint8_t *out = malloc(cap);
if (!out) return 2;
size_t o = 0;
/* make room for the dictionary header */
{
size_t hdr = 10;
for (size_t k = 0; k < nd; k++) hdr += 1 + strlen(dict[k].w);
if (cap < hdr + 16) {
cap = hdr + 16;
out = realloc(out, cap);
if (!out) return 2;
}
}
/* header: magic, orig_len, ndict, entries */
memcpy(out, "DICT", 4); o += 4;
out[o++] = (uint8_t)(n & 0xff);
out[o++] = (uint8_t)((n >> 8) & 0xff);
out[o++] = (uint8_t)((n >> 16) & 0xff);
out[o++] = (uint8_t)((n >> 24) & 0xff);
out[o++] = (uint8_t)(nd & 0xff);
out[o++] = (uint8_t)((nd >> 8) & 0xff);
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
out[o++] = (uint8_t)len;
memcpy(out + o, dict[k].w, len);
o += len;
}
/* growable body: recompute with room (header already written) */
i = 0;
while (i < n) {
/* ensure room for the worst case (1 byte -> 3 bytes) + slack */
if (o + 8 > cap) {
cap *= 2;
out = realloc(out, cap);
if (!out) return 2;
}
if (is_word(in[i])) {
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
int code = -1;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (lcap - 1);
while (look[h] >= 0) {
int32_t k = look[h];
if (strlen(dict[k].w) == len &&
memcmp(dict[k].w, in + i, len) == 0) { code = k; break; }
h = (h + 1) & (lcap - 1);
}
}
if (code >= 0) {
out[o++] = ESC;
out[o++] = (uint8_t)(code & 0xff);
out[o++] = (uint8_t)((code >> 8) & 0xff);
} else {
memcpy(out + o, in + i, len);
o += len;
}
i = j;
} else {
uint8_t c = in[i++];
if (c == ESC) {
out[o++] = ESC;
out[o++] = 0xFF;
out[o++] = 0xFF;
} else {
out[o++] = c;
}
}
}
spit(outpath, out, o);
fprintf(stderr, "dict: %zu words kept (of %zu distinct)\n", nd, na);
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
if (n < 10 || memcmp(in, "DICT", 4) != 0) {
fprintf(stderr, "dict: bad magic/header\n");
return 3;
}
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint32_t nd = (uint32_t)in[8] | ((uint32_t)in[9] << 8);
size_t p = 10;
char **dict = malloc((nd ? nd : 1) * sizeof *dict);
if (!dict) return 2;
for (uint32_t k = 0; k < nd; k++) {
if (p >= n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
size_t len = in[p++];
if (p + len > n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
dict[k] = malloc(len + 1);
memcpy(dict[k], in + p, len);
dict[k][len] = 0;
p += len;
}
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
size_t o = 0;
while (p < n) {
uint8_t c = in[p++];
if (c == ESC) {
if (p + 1 >= n) { fprintf(stderr, "dict: truncated code\n"); return 3; }
uint32_t code = (uint32_t)in[p] | ((uint32_t)in[p + 1] << 8);
p += 2;
if (code == 0xFFFF) {
if (o >= orig) return 3;
out[o++] = ESC;
} else {
if (code >= nd) { fprintf(stderr, "dict: bad code\n"); return 3; }
size_t len = strlen(dict[code]);
if (o + len > orig) return 3;
memcpy(out + o, dict[code], len);
o += len;
}
} else {
if (o >= orig) return 3;
out[o++] = c;
}
}
if (o != orig) {
fprintf(stderr, "dict: short output %zu != %u\n", o, orig);
return 3;
}
spit(outpath, out, o);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
: decode(argv[2], argv[3]);
}
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Build deterministic benchmark corpora on the server. Sizes capped.
text: /usr/share/doc text files + common-licenses (English prose/docs)
code: /usr/include headers + this repo sources (C/Markdown)
bin: ELF binaries from /bin, /usr/bin (executables)
mixed: round-robin 64KiB chunks of text+code+bin
rand: /dev/urandom control (incompressible)
"""
import os, glob, hashlib, random
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corpora")
CAP = 8 * 1024 * 1024
def collect(patterns, cap, text_only=False):
buf = bytearray()
files = []
for p in patterns:
files += sorted(glob.glob(p, recursive=True))
for f in files:
try:
if not os.path.isfile(f):
continue
with open(f, "rb") as fh:
d = fh.read()
except OSError:
continue
if text_only:
try:
d.decode("utf-8")
except UnicodeDecodeError:
continue
buf += d
if len(buf) >= cap:
break
return bytes(buf[:cap])
def write(name, data):
p = os.path.join(OUT, name)
with open(p, "wb") as fh:
fh.write(data)
print(name + ": " + str(len(data)) + " bytes sha256=" + hashlib.sha256(data).hexdigest()[:16])
text = collect(["/usr/share/doc/**/*", "/usr/share/common-licenses/*"], CAP, text_only=True)
write("text", text)
code = collect(["/usr/include/**/*.h", "/opt/lzply-exp-comp/*.c",
"/opt/lzply-exp-comp/*.h", "/opt/lzply-exp-comp/*.md"], CAP)
write("code", code)
bins = []
for d in ("/bin", "/usr/bin"):
for f in sorted(glob.glob(d + "/*")):
try:
with open(f, "rb") as fh:
h = fh.read(4)
if h[:4] == b"\x7fELF":
bins.append(f)
except OSError:
pass
buf = bytearray()
for f in bins:
with open(f, "rb") as fh:
buf += fh.read()
if len(buf) >= CAP:
break
bindata = bytes(buf[:CAP])
write("bin", bindata)
parts = [text, code, bindata]
m = bytearray()
i = 0
while len(m) < CAP:
for part in parts:
off = (i * 65536) % max(1, len(part) - 65536)
m += part[off:off + 65536]
if len(m) >= CAP:
break
i += 1
write("mixed", bytes(m[:CAP]))
rnd = random.Random(1234).randbytes(4 * 1024 * 1024)
write("rand", rnd)
+221
View File
@@ -0,0 +1,221 @@
/* rans.c - rANS entropy coder (see rans.h). Standard rANS:
* encode backwards, x in [2^23, 2^32); decode forwards from the
* 4-byte final state stored at the end of the stream. */
#include "rans.h"
#include <stdlib.h>
#include <string.h>
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq) {
uint32_t cnt[256] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < 256; s++) {
/* scale counts to PROB_SCALE, present symbols keep >= 1 */
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
/* Fix the sum to exactly PROB_SCALE by adjusting the largest. */
int mx = 0;
for (int s = 1; s < 256; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
/* take from the largest symbol, never below 1 if present */
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
/* if still over (pathological), trim the next largest */
for (int s = 0; s < 256 && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out) {
uint32_t cum[256];
uint32_t c = 0;
for (int s = 0; s < 256; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
/* Encode backwards; emit bytes into a temp tail, then reverse.
* Simpler: write backwards from the end of a scratch area. We
* write into out[0..] backwards via a local reverse pass: emit
* into out in reverse order by filling from the end. Caller
* guarantees out holds n + 64 bytes, so use the tail. */
uint8_t *p = out + 2 * n + 64; /* one past the end of scratch */
/* reserve 4 bytes at the very start of the emitted stream for the
* final state; emit stream bytes before them. Work backwards: */
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint8_t s = in[i];
uint32_t f = freq[s];
/* xmax = (L>>12)*f<<8: keeps post-update state in [L, 2^31) so the
* decoder renormalisation consumes exactly the bytes emitted here. */
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
/* w..p holds the emitted bytes in order; final state x follows. */
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[256];
uint8_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < 256; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint8_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint8_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
uint16_t freq[256];
rans_freq(in, n, freq);
uint8_t *buf = malloc(520 + 2 * n + 64);
if (!buf) return -1;
memcpy(buf, "RANS", 4);
buf[4] = (uint8_t)(n & 0xff);
buf[5] = (uint8_t)((n >> 8) & 0xff);
buf[6] = (uint8_t)((n >> 16) & 0xff);
buf[7] = (uint8_t)((n >> 24) & 0xff);
for (int s = 0; s < 256; s++) {
buf[8 + 2 * s] = (uint8_t)(freq[s] & 0xff);
buf[8 + 2 * s + 1] = (uint8_t)((freq[s] >> 8) & 0xff);
}
size_t m = rans_encode_raw(in, n, freq, buf + 520);
*out = buf;
*out_len = 520 + m;
return 0;
}
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
if (n < 520 || memcmp(in, "RANS", 4) != 0) return -1;
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint16_t freq[256];
for (int s = 0; s < 256; s++)
freq[s] = (uint16_t)(in[8 + 2 * s] | (in[8 + 2 * s + 1] << 8));
uint8_t *buf = malloc(orig ? orig : 1);
if (!buf) return -1;
if (rans_decode_raw(in + 520, n - 520, freq, buf, orig) != 0) {
free(buf);
return -1;
}
*out = buf;
*out_len = orig;
return 0;
}
/* ---- general-alphabet layer (uint16_t symbols) ---- */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq) {
uint32_t cnt[1024] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < nsym; s++) {
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
int mx = 0;
for (int s = 1; s < nsym; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
for (int s = 0; s < nsym && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out) {
uint32_t cum[1024];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
uint8_t *p = out + 2 * n + 64;
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint16_t s = in[i];
uint32_t f = freq[s];
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[1024];
uint16_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint16_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint16_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
/* rans.h - rANS entropy coder shared by the lzply experiments.
* 12-bit probabilities (scale 4096), 23-bit renormalisation window.
* Two layers:
* - stream layer: rans_freq / rans_encode_raw / rans_decode_raw work
* on a raw byte stream with a caller-supplied freq table (for
* multi-stream coders, e.g. LZ token streams).
* - file layer: rans_encode / rans_decode wrap one stream with a
* header (magic "RANS", u32 orig_len, 256 x u16 freq table).
*/
#ifndef EXP_RANS_H
#define EXP_RANS_H
#include <stddef.h>
#include <stdint.h>
#define RANS_PROB_BITS 12
#define RANS_PROB_SCALE (1u << RANS_PROB_BITS)
#define RANS_L (1u << 23)
/* Count + normalise frequencies of `in` to sum RANS_PROB_SCALE.
* Symbols present get >= 1. */
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq /*[256]*/);
/* Encode `in` with `freq`; `out` must hold 2*n + 64 bytes. Returns
* bytes written. */
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out);
/* Decode `in_len` bytes into `out` (out_len bytes). Returns 0 ok, -1 bad. */
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len);
/* Whole-file wrap: mallocs *out. Returns 0 ok, -1 bad. */
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
#endif
/* General-alphabet layer (uint16_t symbols, nsym <= 1024): for token
* streams such as literal/length (286 symbols) and distance (21). */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq);
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out /* 2*n+64 */);
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len);
+46
View File
@@ -0,0 +1,46 @@
/* rans_tool.c - standalone rANS order-0 compressor: `rans_tool c in out`,
* `rans_tool d in out`. Used for the ANS-family measurements. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rans.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
size_t n;
uint8_t *in = slurp(argv[2], &n);
uint8_t *out = NULL;
size_t on = 0;
int rc = argv[1][0] == 'c' ? rans_encode(in, n, &out, &on)
: rans_decode(in, n, &out, &on);
if (rc != 0) {
fprintf(stderr, "%s: %s failed (bad input?)\n", argv[0], argv[1]);
return 3;
}
spit(argv[3], out, on);
return 0;
}
View File
Whitespace-only changes.
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
bzip2,text,8388608,776306,9.25,2.969,1.346,2.8,6.2,OK
bzip2,code,8388608,1053123,12.55,2.754,0.937,3.0,8.9,OK
bzip2,bin,8388608,3373815,40.22,1.866,1.575,4.5,5.3,OK
bzip2,mixed,8388608,1974225,23.53,2.081,0.875,4.0,9.6,OK
bzip2,rand,4194304,4213434,100.46,1.336,0.958,3.1,4.4,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 bzip2 text 8388608 776306 9.25 2.969 1.346 2.8 6.2 OK
3 bzip2 code 8388608 1053123 12.55 2.754 0.937 3.0 8.9 OK
4 bzip2 bin 8388608 3373815 40.22 1.866 1.575 4.5 5.3 OK
5 bzip2 mixed 8388608 1974225 23.53 2.081 0.875 4.0 9.6 OK
6 bzip2 rand 4194304 4213434 100.46 1.336 0.958 3.1 4.4 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
dict-lzip6,text,8388608,299963,3.58,2.541,0.166,3.3,50.4,OK
dict-lzip6,code,8388608,770519,9.19,4.144,0.218,2.0,38.5,OK
dict-lzip6,bin,8388608,2793130,33.30,9.522,0.467,0.9,18.0,OK
dict-lzip6,mixed,8388608,1480819,17.65,5.358,0.317,1.6,26.5,OK
dict-lzip6,rand,4194304,4266698,101.73,2.794,0.475,1.5,8.8,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 dict-lzip6 text 8388608 299963 3.58 2.541 0.166 3.3 50.4 OK
3 dict-lzip6 code 8388608 770519 9.19 4.144 0.218 2.0 38.5 OK
4 dict-lzip6 bin 8388608 2793130 33.30 9.522 0.467 0.9 18.0 OK
5 dict-lzip6 mixed 8388608 1480819 17.65 5.358 0.317 1.6 26.5 OK
6 dict-lzip6 rand 4194304 4266698 101.73 2.794 0.475 1.5 8.8 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
gzip9,text,8388608,1969901,23.48,0.830,0.117,10.1,71.6,OK
gzip9,code,8388608,1376091,16.40,0.980,0.066,8.6,127.7,OK
gzip9,bin,8388608,3702420,44.14,2.700,0.115,3.1,72.6,OK
gzip9,mixed,8388608,2521765,30.06,1.180,0.117,7.1,71.5,OK
gzip9,rand,4194304,4194967,100.02,0.428,0.059,9.8,71.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 gzip9 text 8388608 1969901 23.48 0.830 0.117 10.1 71.6 OK
3 gzip9 code 8388608 1376091 16.40 0.980 0.066 8.6 127.7 OK
4 gzip9 bin 8388608 3702420 44.14 2.700 0.115 3.1 72.6 OK
5 gzip9 mixed 8388608 2521765 30.06 1.180 0.117 7.1 71.5 OK
6 gzip9 rand 4194304 4194967 100.02 0.428 0.059 9.8 71.3 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip1,text,8388608,521474,6.22,0.923,0.117,9.1,71.8,OK
lzip1,code,8388608,1268850,15.13,1.127,0.216,7.4,38.8,OK
lzip1,bin,8388608,3173235,37.83,3.144,0.468,2.7,17.9,OK
lzip1,mixed,8388608,1809972,21.58,1.789,0.271,4.7,31.0,OK
lzip1,rand,4194304,4251394,101.36,3.104,0.474,1.4,8.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip1 text 8388608 521474 6.22 0.923 0.117 9.1 71.8 OK
3 lzip1 code 8388608 1268850 15.13 1.127 0.216 7.4 38.8 OK
4 lzip1 bin 8388608 3173235 37.83 3.144 0.468 2.7 17.9 OK
5 lzip1 mixed 8388608 1809972 21.58 1.789 0.271 4.7 31.0 OK
6 lzip1 rand 4194304 4251394 101.36 3.104 0.474 1.4 8.9 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip6,text,8388608,298558,3.56,3.655,0.117,2.3,71.4,OK
lzip6,code,8388608,787213,9.38,5.138,0.168,1.6,50.0,OK
lzip6,bin,8388608,2735269,32.61,9.676,0.416,0.9,20.2,OK
lzip6,mixed,8388608,1460156,17.41,5.519,0.267,1.5,31.4,OK
lzip6,rand,4194304,4251435,101.36,3.173,0.531,1.3,7.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip6 text 8388608 298558 3.56 3.655 0.117 2.3 71.4 OK
3 lzip6 code 8388608 787213 9.38 5.138 0.168 1.6 50.0 OK
4 lzip6 bin 8388608 2735269 32.61 9.676 0.416 0.9 20.2 OK
5 lzip6 mixed 8388608 1460156 17.41 5.519 0.267 1.5 31.4 OK
6 lzip6 rand 4194304 4251435 101.36 3.173 0.531 1.3 7.9 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip9,text,8388608,288746,3.44,6.658,0.119,1.3,70.3,OK
lzip9,code,8388608,758969,9.05,9.062,0.168,0.9,50.0,OK
lzip9,bin,8388608,2729180,32.53,10.747,0.479,0.8,17.5,OK
lzip9,mixed,8388608,1440405,17.17,8.603,0.272,1.0,30.8,OK
lzip9,rand,4194304,4251435,101.36,3.071,0.467,1.4,9.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip9 text 8388608 288746 3.44 6.658 0.119 1.3 70.3 OK
3 lzip9 code 8388608 758969 9.05 9.062 0.168 0.9 50.0 OK
4 lzip9 bin 8388608 2729180 32.53 10.747 0.479 0.8 17.5 OK
5 lzip9 mixed 8388608 1440405 17.17 8.603 0.272 1.0 30.8 OK
6 lzip9 rand 4194304 4251435 101.36 3.071 0.467 1.4 9.0 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-lazy,text,8388608,525357,6.26,1.888,0.119,4.4,70.6,OK
lzrans-lazy,code,8388608,1134159,13.52,3.264,0.116,2.6,72.5,OK
lzrans-lazy,bin,8388608,3510054,41.84,9.644,0.320,0.9,26.2,OK
lzrans-lazy,mixed,8388608,1942374,23.15,3.963,0.165,2.1,50.7,OK
lzrans-lazy,rand,4194304,4214292,100.48,9.295,0.115,0.5,36.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-lazy text 8388608 525357 6.26 1.888 0.119 4.4 70.6 OK
3 lzrans-lazy code 8388608 1134159 13.52 3.264 0.116 2.6 72.5 OK
4 lzrans-lazy bin 8388608 3510054 41.84 9.644 0.320 0.9 26.2 OK
5 lzrans-lazy mixed 8388608 1942374 23.15 3.963 0.165 2.1 50.7 OK
6 lzrans-lazy rand 4194304 4214292 100.48 9.295 0.115 0.5 36.3 OK
+3
View File
@@ -0,0 +1,3 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-opt,text,8388608,519352,6.19,18.714,0.132,0.4,63.5,OK
lzrans-opt,code,8388608,1094779,13.05,8.628,0.115,1.0,72.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-opt text 8388608 519352 6.19 18.714 0.132 0.4 63.5 OK
3 lzrans-opt code 8388608 1094779 13.05 8.628 0.115 1.0 72.9 OK
+4
View File
@@ -0,0 +1,4 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
ppm,text,8388608,2754814,32.84,1.327,2.176,6.3,3.9,OK
ppm,code,8388608,2585570,30.82,1.324,2.040,6.3,4.1,OK
ppm,mixed,8388608,3286801,39.18,1.732,2.635,4.8,3.2,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 ppm text 8388608 2754814 32.84 1.327 2.176 6.3 3.9 OK
3 ppm code 8388608 2585570 30.82 1.324 2.040 6.3 4.1 OK
4 ppm mixed 8388608 3286801 39.18 1.732 2.635 4.8 3.2 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
rans0,text,8388608,5401895,64.40,0.221,0.170,38.0,49.3,OK
rans0,code,8388608,5672388,67.62,0.277,0.171,30.3,49.1,OK
rans0,bin,8388608,6470778,77.14,0.217,0.179,38.6,46.9,OK
rans0,mixed,8388608,6552704,78.11,0.218,0.174,38.4,48.1,OK
rans0,rand,4194304,4213441,100.46,0.115,0.068,36.4,61.6,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 rans0 text 8388608 5401895 64.40 0.221 0.170 38.0 49.3 OK
3 rans0 code 8388608 5672388 67.62 0.277 0.171 30.3 49.1 OK
4 rans0 bin 8388608 6470778 77.14 0.217 0.179 38.6 46.9 OK
5 rans0 mixed 8388608 6552704 78.11 0.218 0.174 38.4 48.1 OK
6 rans0 rand 4194304 4213441 100.46 0.115 0.068 36.4 61.6 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
xz6,text,8388608,294056,3.51,4.257,0.076,2.0,110.1,OK
xz6,code,8388608,771984,9.20,7.147,0.200,1.2,42.0,OK
xz6,bin,8388608,2733616,32.59,12.330,0.367,0.7,22.8,OK
xz6,mixed,8388608,1450908,17.30,7.553,0.271,1.1,31.0,OK
xz6,rand,4194304,4194584,100.01,3.323,0.085,1.3,49.1,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 xz6 text 8388608 294056 3.51 4.257 0.076 2.0 110.1 OK
3 xz6 code 8388608 771984 9.20 7.147 0.200 1.2 42.0 OK
4 xz6 bin 8388608 2733616 32.59 12.330 0.367 0.7 22.8 OK
5 xz6 mixed 8388608 1450908 17.30 7.553 0.271 1.1 31.0 OK
6 xz6 rand 4194304 4194584 100.01 3.323 0.085 1.3 49.1 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
zstd19,text,8388608,304391,3.63,3.549,0.055,2.4,151.8,OK
zstd19,code,8388608,795239,9.48,11.348,0.071,0.7,117.7,OK
zstd19,bin,8388608,2919792,34.81,14.260,0.169,0.6,49.5,OK
zstd19,mixed,8388608,1535960,18.31,8.021,0.066,1.0,126.9,OK
zstd19,rand,4194304,4194413,100.00,3.020,0.037,1.4,112.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 zstd19 text 8388608 304391 3.63 3.549 0.055 2.4 151.8 OK
3 zstd19 code 8388608 795239 9.48 11.348 0.071 0.7 117.7 OK
4 zstd19 bin 8388608 2919792 34.81 14.260 0.169 0.6 49.5 OK
5 zstd19 mixed 8388608 1535960 18.31 8.021 0.066 1.0 126.9 OK
6 zstd19 rand 4194304 4194413 100.00 3.020 0.037 1.4 112.0 OK
+143
View File
@@ -0,0 +1,143 @@
# lzcsv — high-speed CSV compression
`lzcsv` compresses CSV files by transposing them column-wise and then
compressing with xz (liblzma). Same-field values become adjacent long
runs, which xz's matcher uses far better than alternating fields on
every row. It is a standalone tool in the lzply repo, completely
separate from the lzply FEC core: it links only liblzma, no
`liblzply.a`, no liblz, no CUDA.
The idea comes from hot_qwen Cycle 1 (Dec 2026): the coordinator
proposed grid-aware compression, hot_qwen tried to disprove it
(prior art, failure modes) and called it testable, and the test on
14 CSVs gave −13.9% vs `xz -6`, 13/14 files, all round-trips
byte-exact. This tool is that test turned into a real command.
## Format (LZCSV v1)
```
bytes 0..7 magic "LZCSV001"
bytes 8..15 uint64 LE original (CSV) size
bytes 16..23 uint64 LE transposed (COLT1) size
byte 24 xz preset (0-9)
byte 25 flags (bit 0 = extreme)
bytes 26.. xz stream (liblzma, preset, CRC64 check) holding COLT1
```
The transposed stream is COLT1, byte-compatible with the Cycle 1
Python prototype (`/root/hot-qwen/cycle1/transpose.py`):
```
line 1: COLT1 <nrows> <ncols> <crlf:0|1> <trailing_nl:0|1> <uniform:0|1>
if uniform=0: line "COUNTS <len>" then <len> bytes of comma-separated
per-row field counts (ragged rows; padding stripped on decode)
per column j: line "COL <len>" then exactly <len> bytes:
the column's raw field texts joined by "\n" (no trailing newline)
```
The compressed payload is the same liblzma preset-6 stream `xz -6`
produces on the same transposed bytes (within a few bytes: the
encoder's output varies slightly with how it is fed — 1500 vs 1504
bytes on tips.csv — same algorithm, same preset, not a different
compressor).
Integrity chain: liblzma verifies the CRC64 of the xz stream, the
COLT1 decoder is strict (magic, counts, column field counts, no
trailing data), and the container header's original size must match
the reconstructed output exactly.
## Build
```
make lzcsv # needs liblzma-dev; skipped cleanly without it
```
## Usage
```
lzcsv c [-p N] [-e] [-f] [-v] <in.csv> <out.lzcsv> compress (preset 6)
lzcsv d [-f] [-v] <in.lzcsv> <out.csv> decompress
lzcsv test <file.csv> ... in-memory round-trip check
lzcsv info <file.lzcsv> show container header
lzcsv raw-enc <in.csv> <out.colt> write COLT1 intermediate
lzcsv raw-dec <in.colt> <out.csv> decode COLT1 intermediate
lzcsv selftest built-in synthetic tests
```
## Measured results (hot_house, xz/liblzma 5.8.1)
14 corpus CSVs (12,096,190 bytes, `/root/fftdict-shared/corpus2`):
| file | xz -6 | xz -9e | lzcsv -6 | lzcsv -9e | lzcsv-6 vs xz-6 |
|---|---|---|---|---|---|
| covid-countries.csv | 646,112 | 654,748 | 464,786 | 464,446 | −28.1% |
| gen-log.csv | 38,060 | 38,100 | 29,346 | 29,626 | −22.9% |
| gen-numeric.csv | 171,016 | 171,256 | 136,142 | 137,990 | −20.4% |
| hydra-passwords.csv | 79,832 | 79,816 | 70,434 | 70,050 | −11.8% |
| gapminder.csv | 24,352 | 24,472 | 21,506 | 21,694 | −11.7% |
| diabetes.csv | 8,076 | 8,080 | 7,422 | 7,446 | −8.1% |
| default-passwords.csv | 25,900 | 25,892 | 23,898 | 23,906 | −7.7% |
| tips.csv | 1,636 | 1,640 | 1,526 | 1,502 | −6.7% |
| mam.csv | 192,364 | 192,496 | 179,690 | 179,906 | −6.6% |
| iab.csv | 128,396 | 128,392 | 120,114 | 120,342 | −6.5% |
| stocks.csv | 24,092 | 24,132 | 22,698 | 22,718 | −5.8% |
| oui.csv | 718,664 | 713,760 | 692,506 | 687,758 | −3.6% |
| iris.csv | 824 | 828 | 818 | 818 | −0.7% |
| pin-codes.csv | 12,864 | 12,844 | 13,994 | 14,066 | **+8.8%** |
| **aggregate** | **2,072,188 (0.1713)** | **2,076,456 (0.1717)** | **1,784,880 (0.1476)** | **1,782,268 (0.1473)** | **−13.9%** |
- lzcsv -6 wins on 13/14 files vs xz -6 and vs xz -9e. No file flips
at any preset. xz's best does not erase the win: direct xz -9e is
slightly *worse* than xz -6 on these CSVs (2,076,456 vs 2,072,188),
and lzcsv -6 beats direct xz -9e by −14.0%.
- Encode time (sums of per-file medians, 4 parallel workers,
approximate): xz -6 3.59 s, lzcsv -6 4.08 s. Decode: xz -6 0.14 s,
lzcsv -6 0.19 s. Roughly comparable; the transpose itself is
negligible next to xz.
18 held-out CSVs (4,431,565 bytes — 5 downloaded real-world files
plus 13 generated edge cases):
| aggregate | xz -6 | xz -9e | lzcsv -6 | lzcsv -9e | lzcsv-6 vs xz-6 |
|---|---|---|---|---|---|
| bytes | 844,752 (0.1906) | 842,764 (0.1902) | 730,756 (0.1649) | 726,864 (0.1640) | **−13.5%** |
- lzcsv -6 wins on 9/18. Best held-out wins: flights.csv −21.9%,
text.csv −21.4%, diamonds.csv −18.9%, taxis.csv −13.3%.
- All 9 losses are files under ~1 KB (or a single column): the fixed
overhead — COLT1 header + per-column headers + the 26-byte LZCSV
header + the xz stream itself — dominates on tiny files
(empty.csv: 0 → 98 bytes; tiny.csv: 24 → 134 bytes). Single-column
files gain nothing from transposition (there is only one column)
and xz -9e beats lzcsv there (single-col.csv: 1,152 vs 1,474).
- Honest scope: lzcsv wins on real-world CSVs above a few KB and
loses on tiny files. A size gate (transpose only above a
row/column threshold, pass small files through as plain xz) is the
obvious next step and is left for a later cycle.
## Limitations (documented, tested)
- Fields holding a raw newline (embedded newlines in quoted fields)
are rejected with a clear error — the COLT1 column join uses
`"\n"`, so such a field cannot be represented. Same as the
prototype. The test suite checks the rejection is clean.
- Files with mixed line endings (some rows CRLF, some LF) are
rejected: the single crlf flag cannot represent them, and the
prototype would silently mis-round-trip such a file.
- In-memory: the whole file is read into RAM (CSVs are small;
a 5.5 MB file uses tens of MB during the transpose).
- CSV only. Other file types gain nothing and are not the tool's job.
## Tests
```
./lzcsv selftest # built-in synthetic cases
bash tests/run_lzcsv_tests.sh ./lzcsv # full suite (also in `make test`)
python3 lzcsv-src/bench.py # benchmark (corpus + held-out)
```
The suite checks: selftest, `--help`, byte-exact round-trips on the
14 corpus CSVs and the 18 held-out CSVs, byte-identical COLT1 output
vs the Python prototype (oracle) plus cross-decoding both ways,
clean rejection of embedded-newline input, and clean failure on
truncated / bad-magic input.
+32
View File
@@ -0,0 +1,32 @@
covid-countries.csv 5512931 646112 654748 464786 464446 1.9201659050013404 1.9516634100000374 0.05220619498868473 0.07482820301083848
default-passwords.csv 90856 25900 25892 23898 23906 0.025861336005618796 0.021365027991123497 0.0034550470008980483 0.002496671979315579
diabetes.csv 23873 8076 8080 7422 7446 0.011048309010220692 0.009692073974292725 0.0023416100011672825 0.0014151250070426613
gapminder.csv 82079 24352 24472 21506 21694 0.021015542006352916 0.015395115013234317 0.003706499992404133 0.002185456018196419
gen-log.csv 373147 38060 38100 29346 29626 0.08884992098319344 0.0807244160096161 0.004460240976186469 0.004076949000591412
gen-numeric.csv 971501 171016 171256 136142 137990 0.2775053840014152 0.2098268090048805 0.012041809997754171 0.015114195994101465
hydra-passwords.csv 515376 79832 79816 70434 70050 0.10549499999615364 0.07998127699829638 0.006305735005298629 0.00882071300293319
iab.csv 381908 128396 128392 120114 120342 0.08515957900090143 0.08999008699902333 0.006552350998390466 0.007555139978649095
iris.csv 4601 824 828 818 818 0.00544012599857524 0.004784169985214248 0.0016728210030123591 0.0010296890104655176
mam.csv 608108 192364 192496 179690 179906 0.16979076401912607 0.1856548530049622 0.00886850300594233 0.010595135012408718
oui.csv 3372302 718664 713760 692506 687758 0.8365058559866156 1.3890049190085847 0.02745902701281011 0.05935608199797571
pin-codes.csv 83641 12864 12844 13994 14066 0.016631082020467147 0.016714841010980308 0.003020479023689404 0.0030090670043136925
stocks.csv 67924 24092 24132 22698 22718 0.01886416898923926 0.017659361008554697 0.003195147990481928 0.0021861470013391227
tips.csv 7943 1636 1640 1526 1502 0.007472163008060306 0.004107314976863563 0.0019683470018208027 0.0010860360052902251
crlf.csv 57 124 124 170 170 0.004888466995907947 0.007338372990489006 0.0019021829939447343 0.002908758004195988
diamonds.csv 2772143 445196 445344 361098 359134 2.396331233001547 1.2090837279974949 0.033903217990882695 0.041442929999902844
empty.csv 0 32 32 98 98 0.0018080949957948178 0.0020065490098204464 0.0013358870055526495 0.0006844690069556236
flights.csv 2350 648 648 506 506 0.005633962980937213 0.00863322100485675 0.0015973990084603429 0.0018542629841249436
header-only.csv 15 80 80 118 118 0.004120881989365444 0.006564754992723465 0.0027778010116890073 0.0021728830179199576
narrow.csv 78337 18748 19016 17790 17926 0.032430835999548435 0.029884938994655386 0.005319860007148236 0.0038035030011087656
no-trailing-nl.csv 11 76 76 122 122 0.0062791359960101545 0.0024431619967799634 0.003309124003862962 0.000765912001952529
numeric.csv 471030 213188 211892 203770 204030 0.33525239600567147 0.3318267239956185 0.015222632006043568 0.017531852994579822
one-row-no-nl.csv 5 72 72 114 114 0.002797479013679549 0.00583920898498036 0.0027009370096493512 0.0027930409996770322
penguins.csv 13478 2412 2428 2182 2166 0.010619982989737764 0.009998533001635224 0.003402178001124412 0.003114015009487048
quotes.csv 115 184 184 230 230 0.007522066996898502 0.0073039180133491755 0.003594912006519735 0.001310628023929894
ragged.csv 30 96 96 166 166 0.006454857997596264 0.007829547015717253 0.002639713027747348 0.002263063011923805
single-col.csv 31890 1448 1152 1474 1550 0.020343487994978204 0.019372289010789245 0.003808081994066015 0.0029039290093351156
taxis.csv 869349 114268 113392 99090 96730 0.3596663609787356 0.2504055729950778 0.01067515800241381 0.01706002399441786
text.csv 71105 13912 13960 10938 10974 0.0370593529951293 0.03674623399274424 0.004957627010298893 0.003607544000260532
tiny.csv 24 88 88 134 134 0.00707226200029254 0.004299127991544083 0.003431374003412202 0.0024710540019441396
titanic.csv 60302 18816 18808 17410 17374 0.03209059499204159 0.034872953983722255 0.0049819239939097315 0.004012949008028954
wide.csv 61324 15364 15372 15346 15322 0.026844223000807688 0.02351557300426066 0.003356151981279254 0.003094587998930365
1 covid-countries.csv 5512931 646112 654748 464786 464446 1.9201659050013404 1.9516634100000374 0.05220619498868473 0.07482820301083848
2 default-passwords.csv 90856 25900 25892 23898 23906 0.025861336005618796 0.021365027991123497 0.0034550470008980483 0.002496671979315579
3 diabetes.csv 23873 8076 8080 7422 7446 0.011048309010220692 0.009692073974292725 0.0023416100011672825 0.0014151250070426613
4 gapminder.csv 82079 24352 24472 21506 21694 0.021015542006352916 0.015395115013234317 0.003706499992404133 0.002185456018196419
5 gen-log.csv 373147 38060 38100 29346 29626 0.08884992098319344 0.0807244160096161 0.004460240976186469 0.004076949000591412
6 gen-numeric.csv 971501 171016 171256 136142 137990 0.2775053840014152 0.2098268090048805 0.012041809997754171 0.015114195994101465
7 hydra-passwords.csv 515376 79832 79816 70434 70050 0.10549499999615364 0.07998127699829638 0.006305735005298629 0.00882071300293319
8 iab.csv 381908 128396 128392 120114 120342 0.08515957900090143 0.08999008699902333 0.006552350998390466 0.007555139978649095
9 iris.csv 4601 824 828 818 818 0.00544012599857524 0.004784169985214248 0.0016728210030123591 0.0010296890104655176
10 mam.csv 608108 192364 192496 179690 179906 0.16979076401912607 0.1856548530049622 0.00886850300594233 0.010595135012408718
11 oui.csv 3372302 718664 713760 692506 687758 0.8365058559866156 1.3890049190085847 0.02745902701281011 0.05935608199797571
12 pin-codes.csv 83641 12864 12844 13994 14066 0.016631082020467147 0.016714841010980308 0.003020479023689404 0.0030090670043136925
13 stocks.csv 67924 24092 24132 22698 22718 0.01886416898923926 0.017659361008554697 0.003195147990481928 0.0021861470013391227
14 tips.csv 7943 1636 1640 1526 1502 0.007472163008060306 0.004107314976863563 0.0019683470018208027 0.0010860360052902251
15 crlf.csv 57 124 124 170 170 0.004888466995907947 0.007338372990489006 0.0019021829939447343 0.002908758004195988
16 diamonds.csv 2772143 445196 445344 361098 359134 2.396331233001547 1.2090837279974949 0.033903217990882695 0.041442929999902844
17 empty.csv 0 32 32 98 98 0.0018080949957948178 0.0020065490098204464 0.0013358870055526495 0.0006844690069556236
18 flights.csv 2350 648 648 506 506 0.005633962980937213 0.00863322100485675 0.0015973990084603429 0.0018542629841249436
19 header-only.csv 15 80 80 118 118 0.004120881989365444 0.006564754992723465 0.0027778010116890073 0.0021728830179199576
20 narrow.csv 78337 18748 19016 17790 17926 0.032430835999548435 0.029884938994655386 0.005319860007148236 0.0038035030011087656
21 no-trailing-nl.csv 11 76 76 122 122 0.0062791359960101545 0.0024431619967799634 0.003309124003862962 0.000765912001952529
22 numeric.csv 471030 213188 211892 203770 204030 0.33525239600567147 0.3318267239956185 0.015222632006043568 0.017531852994579822
23 one-row-no-nl.csv 5 72 72 114 114 0.002797479013679549 0.00583920898498036 0.0027009370096493512 0.0027930409996770322
24 penguins.csv 13478 2412 2428 2182 2166 0.010619982989737764 0.009998533001635224 0.003402178001124412 0.003114015009487048
25 quotes.csv 115 184 184 230 230 0.007522066996898502 0.0073039180133491755 0.003594912006519735 0.001310628023929894
26 ragged.csv 30 96 96 166 166 0.006454857997596264 0.007829547015717253 0.002639713027747348 0.002263063011923805
27 single-col.csv 31890 1448 1152 1474 1550 0.020343487994978204 0.019372289010789245 0.003808081994066015 0.0029039290093351156
28 taxis.csv 869349 114268 113392 99090 96730 0.3596663609787356 0.2504055729950778 0.01067515800241381 0.01706002399441786
29 text.csv 71105 13912 13960 10938 10974 0.0370593529951293 0.03674623399274424 0.004957627010298893 0.003607544000260532
30 tiny.csv 24 88 88 134 134 0.00707226200029254 0.004299127991544083 0.003431374003412202 0.0024710540019441396
31 titanic.csv 60302 18816 18808 17410 17374 0.03209059499204159 0.034872953983722255 0.0049819239939097315 0.004012949008028954
32 wide.csv 61324 15364 15372 15346 15322 0.026844223000807688 0.02351557300426066 0.003356151981279254 0.003094587998930365
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Benchmark lzcsv vs xz on the 14 corpus CSVs and the held-out set.
Methods per file: direct xz -6, direct xz -9e, lzcsv -6, lzcsv -9e.
Sizes are single-run (deterministic); times are median of 3.
Usage: python3 lzcsv-src/bench.py [--csv-only] [--heldout-only]
Writes lzcsv-src/bench-results.tsv and prints the tables.
"""
import concurrent.futures
import glob
import os
import statistics
import subprocess
import sys
import time
ROOT = "/root/lzply"
LZ = os.path.join(ROOT, "lzcsv")
CORPUS = "/root/fftdict-shared/corpus2"
HELD = "/root/hot-qwen/lzcsv-heldout"
WORK = "/tmp/lzcsv-bench"
os.makedirs(WORK, exist_ok=True)
def run_cmd(cmd):
t0 = time.perf_counter()
r = subprocess.run(cmd, capture_output=True)
dt = time.perf_counter() - t0
return r.returncode, dt
def xz_size_time(path, preset):
# encode: xz -preset -c path -> stdout (captured); time it
t0 = time.perf_counter()
r = subprocess.run(["xz", preset, "-c", path], capture_output=True, check=True)
dt = time.perf_counter() - t0
# decode time: xz -dc the compressed bytes
t0 = time.perf_counter()
subprocess.run(["xz", "-dc"], input=r.stdout, capture_output=True, check=True)
ddt = time.perf_counter() - t0
return len(r.stdout), dt, ddt
def lzcsv_size_time(path, preset_args, tag):
comp = os.path.join(WORK, tag + ".lzcsv")
dec = os.path.join(WORK, tag + ".csv")
enc_times, dec_times = [], []
size = None
for _ in range(3):
t0 = time.perf_counter()
r = subprocess.run([LZ, "c"] + preset_args + ["-f", path, comp], capture_output=True)
enc_times.append(time.perf_counter() - t0)
assert r.returncode == 0, f"lzcsv c failed on {path}: {r.stderr.decode()[:200]}"
size = os.path.getsize(comp)
t0 = time.perf_counter()
r = subprocess.run([LZ, "d", "-f", comp, dec], capture_output=True)
dec_times.append(time.perf_counter() - t0)
assert r.returncode == 0, f"lzcsv d failed on {path}: {r.stderr.decode()[:200]}"
return size, statistics.median(enc_times), statistics.median(dec_times)
def bench_one(path):
name = os.path.basename(path)
orig = os.path.getsize(path)
tag = name.replace(".csv", "")
row = {"file": name, "orig": orig}
# direct xz -6 / -9e (encode median of 3 for time; size from first run)
for preset, key in [("-6", "xz6"), ("-9e", "xz9e")]:
sizes, ets, dts = [], [], []
for _ in range(3):
s, et, dt = xz_size_time(path, preset)
sizes.append(s); ets.append(et); dts.append(dt)
row[key] = sizes[0]
row[key + "_enc"] = statistics.median(ets)
row[key + "_dec"] = statistics.median(dts)
# lzcsv -6 / -9e
for args, key in [([], "lz6"), (["-p", "9", "-e"], "lz9e")]:
s, et, dt = lzcsv_size_time(path, args, tag + "-" + key)
row[key] = s
row[key + "_enc"] = et
row[key + "_dec"] = dt
return row
def table(rows, title):
print(f"\n## {title}")
print("file\torig\txz-6\txz-9e\tlzcsv-6\tlzcsv-9e\tlz6-vs-xz6\tlz6-vs-xz9e\tenc-xz6\tenc-lz6\tdec-xz6\tdec-lz6")
t = {k: 0 for k in ("orig", "xz6", "xz9e", "lz6", "lz9e", "xz6_enc", "lz6_enc", "xz6_dec", "lz6_dec")}
for r in rows:
print(f"{r['file']}\t{r['orig']}\t{r['xz6']}\t{r['xz9e']}\t{r['lz6']}\t{r['lz9e']}"
f"\t{100.0*(r['lz6']-r['xz6'])/r['xz6']:+.1f}%\t{100.0*(r['lz6']-r['xz9e'])/r['xz9e']:+.1f}%"
f"\t{r['xz6_enc']:.3f}\t{r['lz6_enc']:.3f}\t{r['xz6_dec']:.3f}\t{r['lz6_dec']:.3f}")
for k in t:
t[k] += r[k]
n = len(rows)
print(f"AGGREGATE\t{t['orig']}\t{t['xz6']}\t{t['xz9e']}\t{t['lz6']}\t{t['lz9e']}"
f"\t{100.0*(t['lz6']-t['xz6'])/t['xz6']:+.1f}%\t{100.0*(t['lz6']-t['xz9e'])/t['xz9e']:+.1f}%"
f"\t{t['xz6_enc']:.2f}\t{t['lz6_enc']:.2f}\t{t['xz6_dec']:.2f}\t{t['lz6_dec']:.2f}")
print(f"ratios: xz-6 {t['xz6']/t['orig']:.4f} xz-9e {t['xz9e']/t['orig']:.4f} "
f"lzcsv-6 {t['lz6']/t['orig']:.4f} lzcsv-9e {t['lz9e']/t['orig']:.4f}")
wins6 = sum(1 for r in rows if r['lz6'] < r['xz6'])
wins9e = sum(1 for r in rows if r['lz6'] < r['xz9e'])
print(f"lzcsv-6 wins vs xz-6: {wins6}/{n}; vs xz-9e: {wins9e}/{n}")
return t
def main():
csv_only = "--heldout-only" not in sys.argv
held_only = "--csv-only" not in sys.argv
sets = []
if csv_only:
sets.append(("14 corpus CSVs", sorted(glob.glob(os.path.join(CORPUS, "*.csv")))))
if held_only:
held = sorted(f for f in glob.glob(os.path.join(HELD, "*.csv"))
if os.path.basename(f) != "embedded-nl.csv")
sets.append(("18 held-out CSVs", held))
all_rows = []
for title, files in sets:
print(f"benchmarking {len(files)} files ({title}) ...", flush=True)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
rows = list(ex.map(bench_one, files))
rows.sort(key=lambda r: r["file"])
table(rows, title)
all_rows.extend(rows)
with open(os.path.join(ROOT, "lzcsv-src", "bench-results.tsv"), "a") as f:
for r in rows:
f.write("\t".join(str(r[k]) for k in
("file", "orig", "xz6", "xz9e", "lz6", "lz9e",
"xz6_enc", "lz6_enc", "xz6_dec", "lz6_dec")) + "\n")
if __name__ == "__main__":
# fresh results file each run
p = os.path.join(ROOT, "lzcsv-src", "bench-results.tsv")
if os.path.exists(p):
os.remove(p)
main()
+756
View File
@@ -0,0 +1,756 @@
/* lzcsv - high-speed CSV compression: column transpose + xz (liblzma).
*
* A standalone tool in the lzply repo, completely separate from the
* lzply FEC core (it does not link liblzply.a). Idea from hot_qwen
* Cycle 1 (Dec 2026): transpose a CSV column-wise so same-field values
* become adjacent long runs, then compress with xz. On the 14 CSVs of
* the fftdict corpus2 the transposed stream compresses to 0.1475 with
* xz -6 vs 0.1713 direct (-13.9%), 13/14 files win, all round-trips
* byte-exact.
*
* Container (LZCSV v1):
* bytes 0..7 magic "LZCSV001"
* bytes 8..15 uint64 LE original (CSV) size
* bytes 16..23 uint64 LE transposed (COLT1) size
* byte 24 xz preset (0-9)
* byte 25 flags (bit 0 = extreme)
* bytes 26.. xz stream (liblzma, preset, CRC64 check) holding COLT1
*
* COLT1 (byte-compatible with /root/hot-qwen/cycle1/transpose.py):
* line 1: COLT1 <nrows> <ncols> <crlf:0|1> <trailing_nl:0|1> <uniform:0|1>
* if uniform=0: line "COUNTS <len>" then <len> bytes of comma-separated
* per-row field counts (ragged rows; padding fields stripped on decode)
* per column j: line "COL <len>" then exactly <len> bytes:
* the column's raw field texts joined by "\n" (no trailing newline).
* Fields containing a raw newline are rejected (same as the prototype).
* Mixed line endings (some rows CRLF, some LF) are rejected: the single
* crlf flag cannot represent them, and the prototype would silently
* mis-round-trip such a file. Consistent endings round-trip exactly.
*
* Build: make lzcsv (needs liblzma-dev; skipped cleanly without it)
* Usage: lzcsv c [-p N] [-e] [-f] [-v] <in.csv> <out.lzcsv>
* lzcsv d [-f] [-v] <in.lzcsv> <out.csv>
* lzcsv test <file.csv> ...
* lzcsv info <file.lzcsv>
* lzcsv raw-enc <in.csv> <out.colt>
* lzcsv raw-dec <in.colt> <out.csv>
* lzcsv selftest
* lzcsv --help
*/
#include <errno.h>
#include <inttypes.h>
#include <lzma.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define LZCSV_MAGIC "LZCSV001"
#define LZCSV_MAGIC_LEN 8
#define LZCSV_HEADER_LEN 26
#define LZCSV_VERSION "1.0"
static const char *prog = "lzcsv";
/* ------------------------------------------------------------------ */
/* small helpers */
/* ------------------------------------------------------------------ */
static void die(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s: ", prog);
vfprintf(stderr, fmt, ap);
fputc('\n', stderr);
va_end(ap);
exit(1);
}
static void *xmalloc(size_t n) {
void *p = malloc(n ? n : 1);
if (!p) die("out of memory");
return p;
}
static void *xrealloc(void *p, size_t n) {
void *q = realloc(p, n ? n : 1);
if (!q) die("out of memory");
return q;
}
/* Growable byte buffer. */
typedef struct {
uint8_t *v;
size_t n, cap;
} buf_t;
static void buf_init(buf_t *b) { b->v = NULL; b->n = 0; b->cap = 0; }
static void buf_reserve(buf_t *b, size_t extra) {
if (b->n + extra <= b->cap) return;
size_t nc = b->cap ? b->cap : 4096;
while (nc < b->n + extra) nc *= 2;
b->v = xrealloc(b->v, nc);
b->cap = nc;
}
static void buf_put(buf_t *b, const void *p, size_t n) {
buf_reserve(b, n);
memcpy(b->v + b->n, p, n);
b->n += n;
}
static void buf_putc(buf_t *b, uint8_t c) { buf_put(b, &c, 1); }
static void buf_printf(buf_t *b, const char *fmt, ...) {
char tmp[256];
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
va_end(ap);
if (n < 0) die("format error");
if ((size_t)n >= sizeof(tmp)) die("internal: formatted header too long");
buf_put(b, tmp, (size_t)n);
}
static void buf_free(buf_t *b) { free(b->v); b->v = NULL; b->n = b->cap = 0; }
static uint8_t *read_file(const char *path, size_t *len_out) {
FILE *f = fopen(path, "rb");
if (!f) die("cannot open %s: %s", path, strerror(errno));
struct stat st;
if (fstat(fileno(f), &st) != 0) die("cannot stat %s: %s", path, strerror(errno));
if (st.st_size < 0) die("%s: bad size", path);
size_t len = (size_t)st.st_size;
uint8_t *data = xmalloc(len);
if (len && fread(data, 1, len, f) != len) die("cannot read %s", path);
fclose(f);
*len_out = len;
return data;
}
static void write_file(const char *path, const uint8_t *data, size_t len, int force) {
if (!force) {
struct stat st;
if (stat(path, &st) == 0) die("%s already exists (use -f to overwrite)", path);
}
FILE *f = fopen(path, "wb");
if (!f) die("cannot open %s for writing: %s", path, strerror(errno));
if (len && fwrite(data, 1, len, f) != len) die("cannot write %s", path);
if (fclose(f) != 0) die("cannot close %s", path);
}
static uint64_t rd64le(const uint8_t *p) {
uint64_t v = 0;
for (int i = 7; i >= 0; i--) v = (v << 8) | p[i];
return v;
}
static void wr64le(uint8_t *p, uint64_t v) {
for (int i = 0; i < 8; i++) { p[i] = (uint8_t)(v & 0xff); v >>= 8; }
}
/* ------------------------------------------------------------------ */
/* CSV parsing (RFC 4180 quote rules, byte-identical to the COLT1 */
/* Python prototype's split_rows). Fields are slices into the input. */
/* ------------------------------------------------------------------ */
typedef struct { const uint8_t *p; size_t n; } slice_t;
typedef struct {
slice_t *fields; /* flat, row-major, unpadded */
size_t *row_start; /* index of each row's first field in fields[] */
size_t *row_count; /* field count per row (before padding) */
size_t nrows, ncols;
int crlf, trailing_nl, uniform;
} csv_t;
static void csv_free(csv_t *c) {
free(c->fields); free(c->row_start); free(c->row_count);
memset(c, 0, sizeof(*c));
}
/* Parse data into rows/fields. Returns 0 on success, -1 with *err set
* on a rejected file (embedded newline / mixed line endings). */
static int csv_parse(const uint8_t *data, size_t len, csv_t *csv, const char **err) {
memset(csv, 0, sizeof(*csv));
size_t fcap = 0, fn = 0;
size_t rcap = 0, rn = 0;
int in_q = 0;
int crlf = 0, trailing_nl = 0;
int crlf_rows = 0, lf_rows = 0;
size_t cur_start = 0; /* start of the current field */
size_t row_field_start = 0; /* fields[] index where the current row began */
size_t i = 0;
while (i < len) {
uint8_t b = data[i];
if (in_q) {
if (b == 0x22) { /* " */
if (i + 1 < len && data[i + 1] == 0x22) { i += 2; continue; }
in_q = 0;
}
i++;
continue;
}
if (b == 0x22 && i == cur_start) {
/* quote opens a quoted field only at field start (RFC 4180);
* a quote mid-field is a literal character */
in_q = 1;
i++;
} else if (b == 0x2c) { /* , */
if (fn == fcap) { fcap = fcap ? fcap * 2 : 256; csv->fields = xrealloc(csv->fields, fcap * sizeof(slice_t)); }
csv->fields[fn].p = data + cur_start;
csv->fields[fn].n = i - cur_start;
fn++;
cur_start = i + 1;
i++;
} else if (b == 0x0a) { /* \n: end of row */
size_t fend = i;
int this_crlf = 0;
if (i > cur_start && data[i - 1] == 0x0d) { fend = i - 1; this_crlf = 1; crlf = 1; }
if (this_crlf) crlf_rows++; else lf_rows++;
if (fn == fcap) { fcap = fcap ? fcap * 2 : 256; csv->fields = xrealloc(csv->fields, fcap * sizeof(slice_t)); }
csv->fields[fn].p = data + cur_start;
csv->fields[fn].n = fend - cur_start;
fn++;
if (rn == rcap) { rcap = rcap ? rcap * 2 : 64; csv->row_start = xrealloc(csv->row_start, rcap * sizeof(size_t)); csv->row_count = xrealloc(csv->row_count, rcap * sizeof(size_t)); }
csv->row_start[rn] = row_field_start;
csv->row_count[rn] = fn - row_field_start;
rn++;
row_field_start = fn;
cur_start = i + 1;
i++;
} else {
i++;
}
}
/* EOF: leftover field/row (mirrors the prototype exactly). */
if (cur_start < len || fn > row_field_start) {
if (fn == fcap) { fcap = fcap ? fcap * 2 : 256; csv->fields = xrealloc(csv->fields, fcap * sizeof(slice_t)); }
csv->fields[fn].p = data + cur_start;
csv->fields[fn].n = len - cur_start;
fn++;
if (rn == rcap) { rcap = rcap ? rcap * 2 : 64; csv->row_start = xrealloc(csv->row_start, rcap * sizeof(size_t)); csv->row_count = xrealloc(csv->row_count, rcap * sizeof(size_t)); }
csv->row_start[rn] = row_field_start;
csv->row_count[rn] = fn - row_field_start;
rn++;
trailing_nl = 0;
} else {
trailing_nl = 1; /* data ended exactly on a newline (or is empty) */
}
if (len == 0) trailing_nl = 0;
csv->nrows = rn;
csv->crlf = crlf;
csv->trailing_nl = trailing_nl;
size_t ncols = 0;
int uniform = 1;
for (size_t r = 0; r < rn; r++) {
if (csv->row_count[r] > ncols) ncols = csv->row_count[r];
if (r && csv->row_count[r] != csv->row_count[0]) uniform = 0;
}
csv->ncols = ncols;
csv->uniform = rn ? uniform : 1;
if (crlf_rows && lf_rows) {
*err = "mixed line endings (some rows CRLF, some LF); the single crlf flag cannot represent them";
return -1;
}
/* COLT1 joins column fields with "\n": a field holding a raw newline
* cannot be represented. Same rejection as the prototype. */
for (size_t k = 0; k < fn; k++) {
if (memchr(csv->fields[k].p, '\n', csv->fields[k].n)) {
*err = "field contains a raw newline (embedded newlines in quoted fields are not supported by the COLT1 transpose)";
return -1;
}
}
return 0;
}
/* field (row i, col j), honouring ragged-row padding with empty fields */
static slice_t csv_field(const csv_t *csv, size_t i, size_t j) {
static const uint8_t empty = 0;
if (j < csv->row_count[i]) return csv->fields[csv->row_start[i] + j];
slice_t s = { &empty, 0 };
return s;
}
/* ------------------------------------------------------------------ */
/* COLT1 transpose (byte-compatible with transpose.py) */
/* ------------------------------------------------------------------ */
static int colt_encode(const uint8_t *data, size_t len, buf_t *out, const char **err) {
csv_t csv;
if (csv_parse(data, len, &csv, err) != 0) return -1;
buf_printf(out, "COLT1 %zu %zu %d %d %d\n", csv.nrows, csv.ncols,
csv.crlf, csv.trailing_nl, csv.uniform);
if (!csv.uniform) {
buf_t cb;
buf_init(&cb);
for (size_t r = 0; r < csv.nrows; r++) {
if (r) buf_putc(&cb, ',');
buf_printf(&cb, "%zu", csv.row_count[r]);
}
buf_printf(out, "COUNTS %zu\n", cb.n);
buf_put(out, cb.v, cb.n);
buf_free(&cb);
}
for (size_t j = 0; j < csv.ncols; j++) {
size_t blen = 0;
for (size_t r = 0; r < csv.nrows; r++) blen += csv_field(&csv, r, j).n;
if (csv.nrows) blen += csv.nrows - 1; /* "\n" separators */
buf_printf(out, "COL %zu\n", blen);
for (size_t r = 0; r < csv.nrows; r++) {
if (r) buf_putc(out, '\n');
slice_t f = csv_field(&csv, r, j);
buf_put(out, f.p, f.n);
}
}
csv_free(&csv);
return 0;
}
/* Parse one "WORD <num>\n" header line at *pos. Advances *pos past it. */
static int colt_header(const uint8_t *data, size_t len, size_t *pos,
const char *word, size_t *num) {
size_t p = *pos;
size_t eol = p;
while (eol < len && data[eol] != '\n') eol++;
if (eol >= len) return -1;
size_t wlen = strlen(word);
if (eol - p < wlen + 2 || memcmp(data + p, word, wlen) != 0 || data[p + wlen] != ' ')
return -1;
char tmp[32];
size_t nlen = eol - (p + wlen + 1);
if (nlen == 0 || nlen >= sizeof(tmp)) return -1;
memcpy(tmp, data + p + wlen + 1, nlen);
tmp[nlen] = 0;
char *end = NULL;
unsigned long v = strtoul(tmp, &end, 10);
if (!end || *end) return -1;
*num = (size_t)v;
*pos = eol + 1;
return 0;
}
static int colt_decode(const uint8_t *data, size_t len, buf_t *out, const char **err) {
size_t pos = 0;
size_t eol = 0;
while (eol < len && data[eol] != '\n') eol++;
if (eol >= len) { *err = "COLT1: truncated header"; return -1; }
char hdr[128];
if (eol >= sizeof(hdr)) { *err = "COLT1: header line too long"; return -1; }
memcpy(hdr, data, eol);
hdr[eol] = 0;
long nrows, ncols, crlf, tnl, uniform;
if (sscanf(hdr, "COLT1 %ld %ld %ld %ld %ld", &nrows, &ncols, &crlf, &tnl, &uniform) != 5 ||
nrows < 0 || ncols < 0 || (crlf != 0 && crlf != 1) || (tnl != 0 && tnl != 1) ||
(uniform != 0 && uniform != 1)) {
*err = "COLT1: bad magic/header";
return -1;
}
if ((nrows == 0) != (ncols == 0)) {
*err = "COLT1: row/column counts inconsistent";
return -1;
}
pos = eol + 1;
size_t *counts = NULL;
if (nrows > 0) {
counts = xmalloc((size_t)nrows * sizeof(size_t));
for (long r = 0; r < nrows; r++) counts[r] = (size_t)ncols;
}
if (!uniform) {
size_t clen = 0;
if (colt_header(data, len, &pos, "COUNTS", &clen) != 0) { *err = "COLT1: bad COUNTS header"; free(counts); return -1; }
if (pos + clen > len) { *err = "COLT1: truncated COUNTS blob"; free(counts); return -1; }
/* parse comma-separated decimal counts */
size_t r = 0;
size_t p = pos;
size_t end = pos + clen;
while (p < end) {
if (r >= (size_t)nrows) { *err = "COLT1: too many counts"; free(counts); return -1; }
unsigned long v = 0;
int ndig = 0;
while (p < end && data[p] >= '0' && data[p] <= '9') { v = v * 10 + (data[p] - '0'); p++; ndig++; }
if (!ndig) { *err = "COLT1: bad COUNTS blob"; free(counts); return -1; }
counts[r++] = (size_t)v;
if (p < end && data[p] == ',') p++;
else if (p < end) { *err = "COLT1: bad COUNTS blob"; free(counts); return -1; }
}
if (r != (size_t)nrows) { *err = "COLT1: counts length mismatch"; free(counts); return -1; }
pos = end;
}
/* columns: split each COL blob on "\n" into nrows slices */
slice_t *cols = NULL; /* ncols x nrows, column-major */
if (ncols > 0 && nrows > 0) cols = xmalloc((size_t)ncols * (size_t)nrows * sizeof(slice_t));
for (long j = 0; j < ncols; j++) {
size_t blen = 0;
if (colt_header(data, len, &pos, "COL", &blen) != 0) { *err = "COLT1: bad COL header"; free(counts); free(cols); return -1; }
if (pos + blen > len) { *err = "COLT1: truncated COL blob"; free(counts); free(cols); return -1; }
const uint8_t *blob = data + pos;
pos += blen;
if (blen == 0) {
for (long r = 0; r < nrows; r++) { cols[(size_t)j * (size_t)nrows + r].p = blob; cols[(size_t)j * (size_t)nrows + r].n = 0; }
} else {
size_t start = 0;
long r = 0;
for (size_t k = 0; k <= blen; k++) {
if (k == blen || blob[k] == '\n') {
if (r >= nrows) { *err = "COLT1: column field count mismatch"; free(counts); free(cols); return -1; }
cols[(size_t)j * (size_t)nrows + r].p = blob + start;
cols[(size_t)j * (size_t)nrows + r].n = k - start;
r++;
start = k + 1;
}
}
if (r != nrows) { *err = "COLT1: column field count mismatch"; free(counts); free(cols); return -1; }
}
}
if (pos != len) { *err = "COLT1: trailing data after last column"; free(counts); free(cols); return -1; }
if (ncols == 0) { free(counts); free(cols); return 0; } /* empty input */
const uint8_t *eolb = crlf ? (const uint8_t *)"\r\n" : (const uint8_t *)"\n";
size_t eollen = crlf ? 2 : 1;
for (long i = 0; i < nrows; i++) {
for (size_t j = 0; j < counts[i]; j++) {
if (j) buf_putc(out, ',');
slice_t f = cols[j * (size_t)nrows + (size_t)i];
buf_put(out, f.p, f.n);
}
buf_put(out, eolb, eollen);
}
if (!tnl && out->n >= eollen) out->n -= eollen;
free(counts);
free(cols);
return 0;
}
/* ------------------------------------------------------------------ */
/* xz via liblzma (easy encoder, CRC64 check: same stream as xz -6) */
/* ------------------------------------------------------------------ */
static int xz_compress(const uint8_t *in, size_t in_len, uint32_t preset,
uint8_t *out, size_t out_cap, size_t *out_len) {
/* NOTE: out_pos is in/out and MUST start at 0 (it is the write offset,
* not the buffer size); passing the capacity here made the encoder
* think the buffer was already full -> LZMA_BUF_ERROR on every call. */
size_t out_pos = 0;
lzma_ret r = lzma_easy_buffer_encode(preset, LZMA_CHECK_CRC64, NULL,
in, in_len, out, &out_pos, out_cap);
if (r != LZMA_OK) return -1;
*out_len = out_pos;
return 0;
}
static int xz_decompress(const uint8_t *in, size_t in_len, uint8_t *out,
size_t *out_len) {
uint64_t memlimit = UINT64_MAX;
size_t in_pos = 0, out_pos = 0;
lzma_ret r = lzma_stream_buffer_decode(&memlimit, 0, NULL,
in, &in_pos, in_len,
out, &out_pos, *out_len);
if (r != LZMA_OK) return -1;
if (in_pos != in_len) return -1; /* trailing data */
*out_len = out_pos;
return 0;
}
/* ------------------------------------------------------------------ */
/* LZCSV container */
/* ------------------------------------------------------------------ */
static void put_header(uint8_t *h, uint64_t orig, uint64_t trans,
uint8_t preset, uint8_t flags) {
memcpy(h, LZCSV_MAGIC, LZCSV_MAGIC_LEN);
wr64le(h + 8, orig);
wr64le(h + 16, trans);
h[24] = preset;
h[25] = flags;
}
static int get_header(const uint8_t *h, size_t len, uint64_t *orig,
uint64_t *trans, uint8_t *preset, uint8_t *flags) {
if (len < LZCSV_HEADER_LEN) return -1;
if (memcmp(h, LZCSV_MAGIC, LZCSV_MAGIC_LEN) != 0) return -1;
*orig = rd64le(h + 8);
*trans = rd64le(h + 16);
*preset = h[24];
*flags = h[25];
if (*preset > 9 || (*flags & ~1u)) return -1;
return 0;
}
/* ------------------------------------------------------------------ */
/* commands */
/* ------------------------------------------------------------------ */
static void usage(FILE *f) {
fprintf(f,
"lzcsv %s - high-speed CSV compression (column transpose + xz)\n"
"usage: lzcsv <cmd> [options] <in> [out]\n"
" c [-p N] [-e] [-f] [-v] <in.csv> <out.lzcsv> compress (preset 6 default)\n"
" d [-f] [-v] <in.lzcsv> <out.csv> decompress\n"
" test <file.csv> ... in-memory round-trip check\n"
" info <file.lzcsv> show container header\n"
" raw-enc <in.csv> <out.colt> write COLT1 intermediate\n"
" raw-dec <in.colt> <out.csv> decode COLT1 intermediate\n"
" selftest built-in synthetic tests\n"
" --help this text\n"
"options: -p N xz preset 0-9 (default 6); -e extreme (-9e style);\n"
" -f overwrite output; -v print sizes\n"
"The COLT1 transpose is byte-compatible with the hot_qwen Cycle 1\n"
"Python prototype. Fields holding a raw newline and files with mixed\n"
"line endings are rejected (documented limitation).\n", LZCSV_VERSION);
}
static int do_compress(const char *in_path, const char *out_path,
int preset, int extreme, int force, int verbose) {
size_t in_len = 0;
uint8_t *in = read_file(in_path, &in_len);
buf_t trans;
buf_init(&trans);
const char *err = NULL;
if (colt_encode(in, in_len, &trans, &err) != 0) {
free(in);
die("%s: %s", in_path, err);
}
size_t bound = lzma_stream_buffer_bound(trans.n);
uint8_t *xz = xmalloc(bound);
size_t xz_len = 0;
uint32_t pr = (uint32_t)preset | (extreme ? LZMA_PRESET_EXTREME : 0);
if (xz_compress(trans.v, trans.n, pr, xz, bound, &xz_len) != 0) {
free(in); buf_free(&trans); free(xz);
die("%s: xz compression failed", in_path);
}
buf_t file;
buf_init(&file);
uint8_t hdr[LZCSV_HEADER_LEN];
put_header(hdr, (uint64_t)in_len, (uint64_t)trans.n, (uint8_t)preset, extreme ? 1 : 0);
buf_put(&file, hdr, LZCSV_HEADER_LEN);
buf_put(&file, xz, xz_len);
write_file(out_path, file.v, file.n, force);
if (verbose)
printf("%s -> %s: %zu -> %zu bytes (ratio %.4f, preset %d%s)\n",
in_path, out_path, in_len, file.n,
in_len ? (double)file.n / (double)in_len : 0.0,
preset, extreme ? "e" : "");
free(in); buf_free(&trans); free(xz); buf_free(&file);
return 0;
}
static int do_decompress(const char *in_path, const char *out_path,
int force, int verbose) {
size_t in_len = 0;
uint8_t *in = read_file(in_path, &in_len);
uint64_t orig = 0, trans = 0;
uint8_t preset = 0, flags = 0;
if (get_header(in, in_len, &orig, &trans, &preset, &flags) != 0) {
free(in);
die("%s: not an LZCSV file (bad magic/header)", in_path);
}
if (trans > (uint64_t)SIZE_MAX || orig > (uint64_t)SIZE_MAX) {
free(in);
die("%s: implausible sizes in header", in_path);
}
uint8_t *colt = xmalloc((size_t)trans ? (size_t)trans : 1);
size_t colt_len = (size_t)trans;
if (xz_decompress(in + LZCSV_HEADER_LEN, in_len - LZCSV_HEADER_LEN,
colt, &colt_len) != 0) {
free(in); free(colt);
die("%s: xz stream corrupt or truncated", in_path);
}
if (colt_len != (size_t)trans) {
free(in); free(colt);
die("%s: transposed size mismatch (header says %llu, got %zu)",
in_path, (unsigned long long)trans, colt_len);
}
buf_t out;
buf_init(&out);
const char *err = NULL;
if (colt_decode(colt, colt_len, &out, &err) != 0) {
free(in); free(colt); buf_free(&out);
die("%s: COLT1 decode failed: %s", in_path, err);
}
if (out.n != (size_t)orig) {
free(in); free(colt); buf_free(&out);
die("%s: output size mismatch (header says %llu, got %zu)",
in_path, (unsigned long long)orig, out.n);
}
write_file(out_path, out.v, out.n, force);
if (verbose)
printf("%s -> %s: %zu -> %zu bytes\n", in_path, out_path, in_len, out.n);
free(in); free(colt); buf_free(&out);
return 0;
}
static int do_raw_enc(const char *in_path, const char *out_path, int force) {
size_t in_len = 0;
uint8_t *in = read_file(in_path, &in_len);
buf_t trans;
buf_init(&trans);
const char *err = NULL;
if (colt_encode(in, in_len, &trans, &err) != 0) {
free(in);
die("%s: %s", in_path, err);
}
write_file(out_path, trans.v, trans.n, force);
free(in); buf_free(&trans);
return 0;
}
static int do_raw_dec(const char *in_path, const char *out_path, int force) {
size_t in_len = 0;
uint8_t *in = read_file(in_path, &in_len);
buf_t out;
buf_init(&out);
const char *err = NULL;
if (colt_decode(in, in_len, &out, &err) != 0) {
free(in); buf_free(&out);
die("%s: %s", in_path, err);
}
write_file(out_path, out.v, out.n, force);
free(in); buf_free(&out);
return 0;
}
static int do_info(const char *path) {
size_t len = 0;
uint8_t *in = read_file(path, &len);
uint64_t orig = 0, trans = 0;
uint8_t preset = 0, flags = 0;
if (get_header(in, len, &orig, &trans, &preset, &flags) != 0) {
free(in);
die("%s: not an LZCSV file (bad magic/header)", path);
}
printf("%s: LZCSV v1, original %llu bytes, transposed %llu bytes, "
"xz preset %d%s, container %zu bytes\n",
path, (unsigned long long)orig, (unsigned long long)trans,
preset, flags ? "e" : "", len);
free(in);
return 0;
}
/* In-memory round-trip of one file; returns 0 on success. */
static int roundtrip_mem(const uint8_t *data, size_t len, const char **err) {
buf_t trans;
buf_init(&trans);
if (colt_encode(data, len, &trans, err) != 0) { buf_free(&trans); return -1; }
buf_t out;
buf_init(&out);
if (colt_decode(trans.v, trans.n, &out, err) != 0) { buf_free(&trans); buf_free(&out); return -1; }
int ok = (out.n == len && (len == 0 || memcmp(out.v, data, len) == 0));
if (!ok) *err = "round-trip output differs from input";
buf_free(&trans); buf_free(&out);
return ok ? 0 : -1;
}
static int do_test(int nfiles, char **files) {
int fail = 0;
for (int i = 0; i < nfiles; i++) {
size_t len = 0;
uint8_t *data = read_file(files[i], &len);
const char *err = NULL;
if (roundtrip_mem(data, len, &err) == 0) {
printf("OK %s (%zu bytes)\n", files[i], len);
} else {
printf("FAIL %s: %s\n", files[i], err);
fail++;
}
free(data);
}
return fail ? 1 : 0;
}
static int selftest_one(const char *name, const uint8_t *data, size_t len) {
const char *err = NULL;
if (roundtrip_mem(data, len, &err) == 0) {
printf("PASS %s\n", name);
return 0;
}
printf("FAIL %s: %s\n", name, err);
return 1;
}
static int do_selftest(void) {
int fail = 0;
fail += selftest_one("empty", (const uint8_t *)"", 0);
fail += selftest_one("one-row-no-nl", (const uint8_t *)"a,b,c", 5);
fail += selftest_one("header-only", (const uint8_t *)"col1,col2,col3\n", 15);
fail += selftest_one("crlf", (const uint8_t *)"name,age\r\nann,34\r\nbob,29\r\n", 26);
fail += selftest_one("ragged", (const uint8_t *)"a,b,c\n1,2\n3,4,5,6,7\n8\n", 22);
fail += selftest_one("quotes", (const uint8_t *)"id,note\n1,\"hello, world\"\n2,\"say \"\"hi\"\"\"\n3,plain \"quoted\" text\n", 62);
fail += selftest_one("no-trailing-nl", (const uint8_t *)"x,y\n1,2\n3,4", 11);
fail += selftest_one("single-col", (const uint8_t *)"v\n1\n22\n333\n", 11);
fail += selftest_one("empty-fields", (const uint8_t *)"a,,c\n,,\n1,2,\n", 13);
fail += selftest_one("quoted-empty", (const uint8_t *)"a,b\n\"\",x\n", 9);
printf("selftest: %s\n", fail ? "FAIL" : "all pass");
return fail ? 1 : 0;
}
int main(int argc, char **argv) {
if (argc < 2) { usage(stderr); return 2; }
const char *cmd = argv[1];
if (!strcmp(cmd, "--help") || !strcmp(cmd, "-h") || !strcmp(cmd, "help")) {
usage(stdout);
return 0;
}
if (!strcmp(cmd, "selftest")) return do_selftest();
int preset = 6, extreme = 0, force = 0, verbose = 0;
int i = 2;
/* options come after the subcommand */
while (i < argc && argv[i][0] == '-' && argv[i][1] != 0) {
if (!strcmp(argv[i], "-p")) {
if (++i >= argc) { fprintf(stderr, "%s: -p needs a preset\n", prog); return 2; }
preset = atoi(argv[i]);
if (preset < 0 || preset > 9) { fprintf(stderr, "%s: preset must be 0-9\n", prog); return 2; }
} else if (!strcmp(argv[i], "-e")) {
extreme = 1;
} else if (!strcmp(argv[i], "-f")) {
force = 1;
} else if (!strcmp(argv[i], "-v")) {
verbose = 1;
} else {
fprintf(stderr, "%s: unknown option %s\n", prog, argv[i]);
return 2;
}
i++;
}
int npos = argc - i;
char **pos = argv + i;
if (!strcmp(cmd, "c")) {
if (npos != 2) { fprintf(stderr, "usage: lzcsv c [-p N] [-e] [-f] [-v] <in.csv> <out.lzcsv>\n"); return 2; }
return do_compress(pos[0], pos[1], preset, extreme, force, verbose);
}
if (!strcmp(cmd, "d")) {
if (npos != 2) { fprintf(stderr, "usage: lzcsv d [-f] [-v] <in.lzcsv> <out.csv>\n"); return 2; }
return do_decompress(pos[0], pos[1], force, verbose);
}
if (!strcmp(cmd, "test")) {
if (npos < 1) { fprintf(stderr, "usage: lzcsv test <file.csv> ...\n"); return 2; }
return do_test(npos, pos);
}
if (!strcmp(cmd, "info")) {
if (npos != 1) { fprintf(stderr, "usage: lzcsv info <file.lzcsv>\n"); return 2; }
return do_info(pos[0]);
}
if (!strcmp(cmd, "raw-enc")) {
if (npos != 2) { fprintf(stderr, "usage: lzcsv raw-enc <in.csv> <out.colt>\n"); return 2; }
return do_raw_enc(pos[0], pos[1], force);
}
if (!strcmp(cmd, "raw-dec")) {
if (npos != 2) { fprintf(stderr, "usage: lzcsv raw-dec <in.colt> <out.csv>\n"); return 2; }
return do_raw_dec(pos[0], pos[1], force);
}
fprintf(stderr, "%s: unknown command '%s'\n", prog, cmd);
usage(stderr);
return 2;
}
+95 -3
View File
@@ -105,7 +105,9 @@
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "repair_cmd.h"
@@ -1571,7 +1573,7 @@ static int cmd_tree(const char *archive, const char **selectors,
static void usage(FILE *out)
{
fprintf(out,
"Usage: %s -c|-d|-l|-t|-a|-i|-tr [options] <input> [output] [selectors...]\n"
"Usage: %s -c|-d|-l|-t|-a|-i|-tr|-r [options] <input> [output] [selectors...]\n"
"\n"
" -c compress a file or directory into one .lzply archive\n"
" -a append files/dirs to an archive (creates it if\n"
@@ -1594,6 +1596,15 @@ static void usage(FILE *out)
" -tr print an archive as a tree, like the Linux\n"
" `tree` command, with a directory/file count.\n"
" Selectors filter it.\n"
" -r repair an archive: recover entries whose bit\n"
" errors exceed the BCH limit t, in escalating\n"
" levels L0-L3 (standard decode, Chase-1,\n"
" Chase-2, cross-block). Recovered files go to\n"
" [output] dir (default ./repaired). --level N\n"
" caps the level (default 3), --time-budget S\n"
" the seconds per entry (default 120). On a\n"
" CUDA build the L1 Chase-1 scan runs on the\n"
" GPU when a device is present, else CPU.\n"
" -datestart <date> only entries with mtime on or after this date\n"
" -dateend <date> only entries with mtime on or before this date\n"
" Dates are YYYY-MM-DD (whole day, inclusive) or\n"
@@ -1648,16 +1659,18 @@ static void usage(FILE *out)
" %s -i backup.lzply -datestart 2024-01-01 -dateend 2024-06-30\n"
" inspect only Jan-Jun 2024 entries\n"
" %s -tr backup.lzply photos/ -year 2025 tree of 2025 photos only\n"
" %s -r backup.lzply repair into ./repaired\n"
" %s -r -o fixed/ backup.lzply repair into fixed/\n"
"\n"
"Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.\n",
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname);
lzply_progname, lzply_progname, lzply_progname);
}
enum { MODE_NONE, MODE_COMPRESS, MODE_DECOMPRESS, MODE_LIST, MODE_TEST,
MODE_APPEND, MODE_INSPECT, MODE_TREE };
MODE_APPEND, MODE_INSPECT, MODE_TREE, MODE_REPAIR };
/* Parse a poly=NN value: hex if it has a 0x prefix or any a-f/A-F
* letter, else decimal. Returns the poly, or NULL if it is not a
@@ -1696,6 +1709,11 @@ int main(int argc, char **argv)
int ecc_level = 4; /* default -e 4 -> BCH t=8 */
const bch_poly_t *pinned_poly = NULL;
int ow_mode = OW_ASK;
const char *repair_outdir = "./repaired";
int repair_verbose = 0;
int repair_max_level = DEEP_MAX_LEVEL;
double repair_budget = DEEP_DEFAULT_BUDGET_SEC;
const char *repair_only_entry = NULL;
date_filter_t dfilter;
const char **args = NULL; /* positional arguments after the options */
int nargs = 0;
@@ -1744,6 +1762,64 @@ int main(int argc, char **argv)
mode = MODE_INSPECT;
} else if (strcmp(a, "-tr") == 0 || strcmp(a, "--tree") == 0) {
mode = MODE_TREE;
} else if (strcmp(a, "-r") == 0 || strcmp(a, "--repair") == 0) {
mode = MODE_REPAIR;
} else if (strcmp(a, "-o") == 0 || strcmp(a, "--output") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: -o needs a directory\n",
lzply_progname);
return EXIT_USAGE;
}
repair_outdir = argv[++i];
} else if (strcmp(a, "-v") == 0 || strcmp(a, "--verbose") == 0) {
repair_verbose = 1;
} else if (strcmp(a, "--level") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --level needs 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
repair_max_level = atoi(argv[++i]);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--level=", 8) == 0) {
repair_max_level = atoi(a + 8);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--time-budget") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --time-budget needs seconds\n",
lzply_progname);
return EXIT_USAGE;
}
repair_budget = atof(argv[++i]);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--time-budget=", 14) == 0) {
repair_budget = atof(a + 14);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --entry needs a stored path\n",
lzply_progname);
return EXIT_USAGE;
}
repair_only_entry = argv[++i];
} else if (strncmp(a, "--entry=", 8) == 0) {
repair_only_entry = a + 8;
} else if (strcmp(a, "-datestart") == 0 ||
strcmp(a, "--datestart") == 0) {
if (i + 1 >= argc) {
@@ -1931,6 +2007,22 @@ int main(int argc, char **argv)
nargs >= 2 ? nargs - 1 : 0,
&dfilter);
break;
case MODE_REPAIR:
/* archive, optional outdir. */
if (nargs < 1 || nargs > 2) {
fprintf(stderr,
"%s: -r needs an archive and an optional output directory\n",
lzply_progname);
usage(stderr);
rc = EXIT_USAGE;
break;
}
if (nargs == 2)
repair_outdir = args[1];
rc = repair_archive(lzply_progname, args[0], repair_outdir,
repair_max_level, repair_budget,
repair_only_entry, repair_verbose);
break;
default:
rc = EXIT_USAGE;
break;
+6 -312
View File
@@ -18,27 +18,23 @@
* and how many bits were corrected. -v adds the per-level trial
* counts (BM trials, splitting-filter passes, valid codewords).
*
* The archive-walking driver lives in repair_cmd.c (shared with
* the lzply -r mode); this file is only the option parsing.
*
* Exit codes: 0 all entries recovered, 1 usage, 2 I/O error,
* 3 any entry unrecoverable (matching lzply's EXIT_CORRUPT).
*/
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "lzrs_lib.h"
#include "repair_cmd.h"
static const char *prog = "lzply_deep_repair";
@@ -57,56 +53,6 @@ static void usage(void)
prog, DEEP_DEFAULT_BUDGET_SEC);
}
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
static int mkdir_p(const char *path, mode_t mode)
{
char *tmp = xstrdup(path);
size_t n = strlen(tmp);
size_t i;
if (n == 0) {
free(tmp);
return 0;
}
while (n > 1 && tmp[n - 1] == '/')
tmp[--n] = '\0';
for (i = 1; i <= n; i++) {
if (tmp[i] == '/' || tmp[i] == '\0') {
char save = tmp[i];
struct stat st;
tmp[i] = '\0';
if (stat(tmp, &st) != 0) {
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
free(tmp);
return -1;
}
} else if (!S_ISDIR(st.st_mode)) {
free(tmp);
return -1;
}
tmp[i] = save;
}
}
free(tmp);
return 0;
}
static int write_out_file(const char *path, const uint8_t *data, size_t len,
uint32_t mode)
{
FILE *f = fopen(path, "wb");
if (!f)
return -1;
if (len > 0 && fwrite(data, 1, len, f) != len) {
fclose(f);
return -1;
}
if (fclose(f) != 0)
return -1;
if (mode)
chmod(path, (mode_t)(mode & 07777));
return 0;
}
int main(int argc, char **argv)
{
int max_level = DEEP_MAX_LEVEL;
@@ -115,9 +61,6 @@ int main(int argc, char **argv)
const char *outdir = "./repaired";
const char *only_entry = NULL;
const char *archive = NULL;
int is_lzrs = 0;
FILE *f = NULL;
uint8_t magic[4];
int opt;
static struct option long_opts[] = {
{ "time-budget", required_argument, NULL, 1000 },
@@ -167,255 +110,6 @@ int main(int argc, char **argv)
}
archive = argv[optind];
f = fopen(archive, "rb");
if (!f) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
strerror(errno));
return EXIT_IO;
}
if (fread(magic, 1, 4, f) != 4) {
fprintf(stderr, "%s: %s is too short to be an archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
if (memcmp(magic, "LZRS", 4) == 0)
is_lzrs = 1;
else if (memcmp(magic, "LZPL", 4) != 0) {
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
/* Validate the archive up front (version, headers, end marker),
* so a structurally broken archive fails before any repair is
* attempted. The scan also gives the clear v4 message for old
* LZPL archives. */
{
int version = 0;
uint32_t count = 0;
off_t size = 0, end_off = 0;
scan_list_t entries;
int s;
rewind(f);
if (is_lzrs)
s = lzrs_scan_archive(archive, &version, &count, &size,
&entries, &end_off);
else
s = scan_archive(archive, &version, &count, &size,
&entries, &end_off);
if (s != 0) {
fclose(f);
return EXIT_CORRUPT;
}
scan_list_free(&entries);
rewind(f);
}
if (mkdir_p(outdir, 0755) != 0) {
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
prog, outdir, strerror(errno));
fclose(f);
return EXIT_IO;
}
/* Skip the 16-byte global header; then walk the entries. */
if (fseeko(f, 16, SEEK_SET) != 0) {
fprintf(stderr, "%s: cannot seek in %s\n", prog, archive);
fclose(f);
return EXIT_IO;
}
{
int worst = 0;
long n_ok = 0, n_fail = 0, n_dir = 0;
long landed[4] = { 0, 0, 0, 0 };
double t_start = bch_now();
for (;;) {
char *path = NULL;
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
uint16_t poly_id = 0, want_crc16 = 0;
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
uint32_t mode = 0;
uint8_t sha[32];
uint8_t *stored = NULL;
int r;
if (is_lzrs) {
lzrs_ehdr_t h;
r = lzrs_read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = h.rs_level;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = h.bch_poly_id;
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
} else {
ehdr_t h;
r = read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = 0;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = (uint16_t)(h.rs_level |
((uint16_t)h.reserved << 8));
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
}
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
if (stored_size > 0 &&
fread(stored, 1, (size_t)stored_size, f) !=
(size_t)stored_size) {
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
free(stored);
free(path);
worst = EXIT_CORRUPT;
break;
}
if (only_entry && strcmp(path, only_entry) != 0) {
free(stored);
free(path);
continue;
}
if (is_dir) {
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
sprintf(dp, "%s/%s", outdir, path);
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
fprintf(stderr, "%s: cannot create directory %s: %s\n",
prog, dp, strerror(errno));
free(dp);
free(stored);
free(path);
n_dir++;
continue;
}
{
uint8_t *raw = NULL;
size_t raw_len = 0;
deep_stats_t st;
int drc = deep_repair_entry(stored, (size_t)stored_size,
level, is_bch, poly_id,
rs_level, sha,
(size_t)blob_size, want_crc16,
max_level, budget,
&raw, &raw_len, &st);
free(stored);
if (drc != 0) {
printf("%s: FAILED (stage %s) after %.3fs, "
"cands %ld crc-rejects %ld sha-rejects %ld\n",
path, st.fail_stage, st.t_total,
st.cands_tried, st.crc_rejects, st.sha_rejects);
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
free(path);
continue;
}
if (raw_len != orig_size) {
fprintf(stderr, "%s: %s: size mismatch after repair "
"(got %zu, expected %llu)\n", prog, path,
raw_len, (unsigned long long)orig_size);
free(raw);
free(path);
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
continue;
}
{
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
char *pd;
sprintf(dp, "%s/%s", outdir, path);
pd = parent_dir(dp);
if (mkdir_p(pd, 0755) != 0)
fprintf(stderr, "%s: cannot create %s: %s\n",
prog, pd, strerror(errno));
free(pd);
if (write_out_file(dp, raw, raw_len, mode) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n",
prog, dp, strerror(errno));
if (EXIT_IO > worst)
worst = EXIT_IO;
free(dp);
free(raw);
free(path);
continue;
}
free(dp);
}
{
char rssuf[48];
rssuf[0] = '\0';
if (st.rs_corrected > 0)
snprintf(rssuf, sizeof rssuf,
" (RS corrected %d symbols)",
st.rs_corrected);
printf("%s: RECOVERED at L%d in %.3fs "
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
"cands %ld crc-rejects %ld sha-rejects %ld "
"bch-corrected %d%s\n",
path, st.level_landed, st.t_total,
st.t_level[0], st.t_level[1], st.t_level[2],
st.t_level[3], st.cands_tried, st.crc_rejects,
st.sha_rejects, st.bch_corrected, rssuf);
}
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
landed[st.level_landed]++;
n_ok++;
free(raw);
free(path);
}
}
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
n_ok, landed[0], landed[1], landed[2], landed[3],
n_fail, n_dir, bch_now() - t_start);
fclose(f);
return worst;
}
return repair_archive(prog, archive, outdir, max_level, budget,
only_entry, verbose);
}
+354
View File
@@ -0,0 +1,354 @@
/* repair_cmd.c - shared archive repair driver for `lzply -r` and
* `lzply_deep_repair`.
*
* repair_archive() validates an LZPL v5 or LZRS v1 archive, then
* attempts the escalating deep-repair ladder (L0 standard decode
* to t, L1 Chase-1 flips, L2 Chase-2 flips, L3 cross-block list
* decoding) per entry, writing recovered files under outdir with
* their stored paths preserved. Nothing is ever written unless it
* passes both oracles (CRC16, then decompress + SHA-256).
*
* Per entry it reports the level the repair landed at and the
* per-level timing -- the "time of arrival": how long each level
* took, how many candidates were tried, how many the CRC rejected,
* and how many bits were corrected. -v adds the per-level trial
* counts (BM trials, splitting-filter passes, valid codewords);
* the L1 line carries a (CUDA) marker when the Chase-1 scan ran
* on the GPU.
*
* Returns the worst exit code: 0 all entries recovered, 2 I/O
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
*/
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "lzrs_lib.h"
#include "repair_cmd.h"
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
static int mkdir_p(const char *path, mode_t mode)
{
char *tmp = xstrdup(path);
size_t n = strlen(tmp);
size_t i;
if (n == 0) {
free(tmp);
return 0;
}
while (n > 1 && tmp[n - 1] == '/')
tmp[--n] = '\0';
for (i = 1; i <= n; i++) {
if (tmp[i] == '/' || tmp[i] == '\0') {
char save = tmp[i];
struct stat st;
tmp[i] = '\0';
if (stat(tmp, &st) != 0) {
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
free(tmp);
return -1;
}
} else if (!S_ISDIR(st.st_mode)) {
free(tmp);
return -1;
}
tmp[i] = save;
}
}
free(tmp);
return 0;
}
static int write_out_file(const char *path, const uint8_t *data, size_t len,
uint32_t mode)
{
FILE *f = fopen(path, "wb");
if (!f)
return -1;
if (len > 0 && fwrite(data, 1, len, f) != len) {
fclose(f);
return -1;
}
if (fclose(f) != 0)
return -1;
if (mode)
chmod(path, (mode_t)(mode & 07777));
return 0;
}
int repair_archive(const char *prog, const char *archive,
const char *outdir, int max_level, double budget,
const char *only_entry, int verbose)
{
int is_lzrs = 0;
FILE *f = NULL;
uint8_t magic[4];
lzply_set_progname(prog);
f = fopen(archive, "rb");
if (!f) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
strerror(errno));
return EXIT_IO;
}
if (fread(magic, 1, 4, f) != 4) {
fprintf(stderr, "%s: %s is too short to be an archive\n", prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
if (memcmp(magic, "LZRS", 4) == 0)
is_lzrs = 1;
else if (memcmp(magic, "LZPL", 4) != 0) {
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n", prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
/* Validate the archive up front (version, headers, end marker),
* so a structurally broken archive fails before any repair is
* attempted. The scan also gives the clear v4 message for old
* LZPL archives. */
{
int version = 0;
uint32_t count = 0;
off_t size = 0, end_off = 0;
scan_list_t entries;
int s;
rewind(f);
if (is_lzrs)
s = lzrs_scan_archive(archive, &version, &count, &size,
&entries, &end_off);
else
s = scan_archive(archive, &version, &count, &size,
&entries, &end_off);
if (s != 0) {
fclose(f);
return EXIT_CORRUPT;
}
scan_list_free(&entries);
rewind(f);
}
if (mkdir_p(outdir, 0755) != 0) {
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
prog, outdir, strerror(errno));
fclose(f);
return EXIT_IO;
}
/* Skip the 16-byte global header; then walk the entries. */
if (fseeko(f, 16, SEEK_SET) != 0) {
fprintf(stderr, "%s: cannot seek in %s: %s\n", prog, archive,
strerror(errno));
fclose(f);
return EXIT_IO;
}
{
int worst = 0;
long n_ok = 0, n_fail = 0, n_dir = 0;
long landed[4] = { 0, 0, 0, 0 };
double t_start = bch_now();
for (;;) {
char *path = NULL;
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
uint16_t poly_id = 0, want_crc16 = 0;
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
uint32_t mode = 0;
uint8_t sha[32];
uint8_t *stored = NULL;
int r;
if (is_lzrs) {
lzrs_ehdr_t h;
r = lzrs_read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = h.rs_level;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = h.bch_poly_id;
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
} else {
ehdr_t h;
r = read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = 0;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = (uint16_t)(h.rs_level |
((uint16_t)h.reserved << 8));
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
}
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
if (stored_size > 0 &&
fread(stored, 1, (size_t)stored_size, f) !=
(size_t)stored_size) {
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
free(stored);
free(path);
worst = EXIT_CORRUPT;
break;
}
if (only_entry && strcmp(path, only_entry) != 0) {
free(stored);
free(path);
continue;
}
if (is_dir) {
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
sprintf(dp, "%s/%s", outdir, path);
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
fprintf(stderr, "%s: cannot create directory %s: %s\n",
prog, dp, strerror(errno));
free(dp);
free(stored);
free(path);
n_dir++;
continue;
}
{
uint8_t *raw = NULL;
size_t raw_len = 0;
deep_stats_t st;
int drc = deep_repair_entry(stored, (size_t)stored_size,
level, is_bch, poly_id,
rs_level, sha,
(size_t)blob_size, want_crc16,
max_level, budget,
&raw, &raw_len, &st);
free(stored);
if (drc != 0) {
printf("%s: FAILED (stage %s) after %.3fs, "
"cands %ld crc-rejects %ld sha-rejects %ld\n",
path, st.fail_stage, st.t_total,
st.cands_tried, st.crc_rejects, st.sha_rejects);
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld%s\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv],
(lv == 1 && st.chase_cuda_used) ?
" (CUDA)" : "");
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
free(path);
continue;
}
if (raw_len != orig_size) {
fprintf(stderr, "%s: %s: size mismatch after repair "
"(got %zu, expected %llu)\n", prog, path,
raw_len, (unsigned long long)orig_size);
free(raw);
free(path);
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
continue;
}
{
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
char *pd;
sprintf(dp, "%s/%s", outdir, path);
pd = parent_dir(dp);
if (mkdir_p(pd, 0755) != 0)
fprintf(stderr, "%s: cannot create %s: %s\n",
prog, pd, strerror(errno));
free(pd);
if (write_out_file(dp, raw, raw_len, mode) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n",
prog, dp, strerror(errno));
if (EXIT_IO > worst)
worst = EXIT_IO;
free(dp);
free(raw);
free(path);
continue;
}
free(dp);
}
{
char rssuf[48];
rssuf[0] = '\0';
if (st.rs_corrected > 0)
snprintf(rssuf, sizeof rssuf,
" (RS corrected %d symbols)",
st.rs_corrected);
printf("%s: RECOVERED at L%d in %.3fs "
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
"cands %ld crc-rejects %ld sha-rejects %ld "
"bch-corrected %d%s\n",
path, st.level_landed, st.t_total,
st.t_level[0], st.t_level[1], st.t_level[2],
st.t_level[3], st.cands_tried, st.crc_rejects,
st.sha_rejects, st.bch_corrected, rssuf);
}
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld%s\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv],
(lv == 1 && st.chase_cuda_used) ?
" (CUDA)" : "");
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
landed[st.level_landed]++;
n_ok++;
free(raw);
free(path);
}
}
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
n_ok, landed[0], landed[1], landed[2], landed[3],
n_fail, n_dir, bch_now() - t_start);
fclose(f);
return worst;
}
}
+17
View File
@@ -0,0 +1,17 @@
/* repair_cmd.h - shared archive repair driver.
*
* repair_archive() is the archive-walking repair loop used by both
* the lzply -r mode and the lzply_deep_repair binary: it validates
* the archive, then attempts the escalating deep-repair ladder
* (L0-L3) per entry, writing recovered files under outdir.
* Returns the worst exit code: 0 all entries recovered, 2 I/O
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
*/
#ifndef LZPLY_REPAIR_CMD_H
#define LZPLY_REPAIR_CMD_H
int repair_archive(const char *prog, const char *archive,
const char *outdir, int max_level, double budget,
const char *only_entry, int verbose);
#endif /* LZPLY_REPAIR_CMD_H */
+13
View File
@@ -186,6 +186,19 @@ sys.exit(1 if fails else 0)
PYEOF
if [ $? -ne 0 ]; then FAIL=$((FAIL+1)); echo "FAIL: old-format rejection section (see above)"; else PASS=$((PASS+1)); echo "PASS: old-format rejection section"; fi
# --- 2b. lzply -r smoke test (repair built into the main CLI) -----------
"$LZPLY" -c -e 4 "$WORK/r512.bin" "$WORK/r-smoke.lzpl" >/dev/null
SMOKESZ=$(stat -c %s "$WORK/r-smoke.lzpl")
cp "$WORK/r-smoke.lzpl" "$WORK/r-smoke-corr.lzpl"
"$CORRUPT_BITS" "$WORK/r-smoke-corr.lzpl" 4242 9 104 $((SMOKESZ - 2)) >/dev/null
rm -rf "$WORK/r-smoke-out"
if "$LZPLY" -r -o "$WORK/r-smoke-out" "$WORK/r-smoke-corr.lzpl" >/dev/null 2>&1 \
&& cmp -s "$WORK/r512.bin" "$WORK/r-smoke-out/r512.bin"; then
ok "lzply -r repairs 9-bit corruption (L1)"
else
bad "lzply -r repairs 9-bit corruption (L1)"
fi
# --- 3. Corruption matrix -------------------------------------------------
# repair_trial ARCHIVE ORIG DATA_OFF BLOB_END SEED NERR MODE BUDGET TRIALNO
# MODE: scatter | burst1 | burst2 | conc1 (9 in block 1) | conc2 (9+9)
+139
View File
@@ -0,0 +1,139 @@
#!/bin/sh
# tests/run_integration_tests.sh - smoke tests for the integrated experiment
# winners on current main (LZPL v5). Fast by design: small trial counts,
# 64 KiB windows. The full matrices live in exp/run_matrix.sh and
# experiments/bench.py and are NOT re-run here.
#
# Assumes CWD is the repo root and the main binaries are already built
# (make test invokes this after building them). Exit nonzero on any
# failure. Work dir: ./testwork-int (git-ignored).
set -u
ROOT=$PWD
W=$ROOT/testwork-int
FAIL=0
say() { printf '%s\n' "int-test: $*"; }
pass() { say "PASS $1"; }
fail() { say "FAIL $1"; FAIL=1; }
# rate_of <csv> -> success rate, field 9 of the bench CSV
rate_of() { awk -F, 'NR==1{print $9}' "$1"; }
# rate_ok <csv> <min> <desc>: rate >= min
rate_ok() {
r=$(rate_of "$1")
ok=$(awk -v r="$r" -v m="$2" 'BEGIN{print (r+0 >= m+0) ? 1 : 0}')
if [ "$ok" = 1 ]; then pass "$3 (rate=$r)"; else fail "$3 (rate=$r, want >= $2)"; fi
}
rm -rf "$W"; mkdir -p "$W"
# ---- build the integrated winners (max cores) ----
say "building exp bench + experiments tools"
make -C "$ROOT/exp" -j8 bench ldpc_diag pass2_diag >/dev/null 2>"$W/build-exp.log" \
|| { fail "exp build (see $W/build-exp.log)"; cat "$W/build-exp.log"; exit 1; }
make -C "$ROOT" bch.o >/dev/null 2>&1
make -C "$ROOT/experiments" -j8 rans_tool dict bchcheck >/dev/null 2>"$W/build-experiments.log" \
|| { fail "experiments build (see $W/build-experiments.log)"; cat "$W/build-experiments.log"; exit 1; }
pass "exp + experiments build"
# ---- corpora: text + code, lzip -6 blobs (what lzply protects) ----
# Corpora must be genuinely varied: repetition compresses to ~nothing
# under lzip (docs x12 still gave a 30 KiB blob). Use every text file
# in the tree for text, every C file for code.
find "$ROOT" -type f \( -name "*.md" -o -name "*.c" -o -name "*.h" -o -name "*.sh" -o -name "*.py" -o -name "*.txt" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -not -path "$ROOT/testdata/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/text.txt"
find "$ROOT" -type f \( -name "*.c" -o -name "*.h" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/code.txt"
lzip -6 -c "$W/text.txt" > "$W/text.lz"
lzip -6 -c "$W/code.txt" > "$W/code.lz"
for b in text.lz code.lz; do
sz=$(stat -c%s "$W/$b")
[ "$sz" -gt 70000 ] || { fail "blob $b too small ($sz bytes)"; exit 1; }
done
pass "corpora built (text.lz + code.lz > 64 KiB)"
BENCH="$ROOT/exp/bench --blob $W/text.lz --size 65536 --seed 1234"
# ---- clean round-trips: every integrated ECC codec ----
for c in bch1k-t32 intlv-d64-bch1k-t32 ldpc-r90; do
$BENCH --codec "$c" --clean --trials 5 --out "$W/clean-$c.csv" 2>/dev/null
rate_ok "$W/clean-$c.csv" 1.0 "clean round-trip $c"
done
# ---- winner 1: interleaving d64 survives a 256-byte burst ----
$BENCH --codec intlv-d64-bch1k-t32 --burst 256,1 --trials 20 --out "$W/intlv-burst.csv" 2>/dev/null
rate_ok "$W/intlv-burst.csv" 0.95 "intlv-d64-bch1k-t32 burst 256 B"
# same burst kills uninterleaved small-block BCH (control: expect 0)
$BENCH --codec bch1k-t32 --burst 256,1 --trials 20 --out "$W/bch1k-burst.csv" 2>/dev/null
r=$(rate_of "$W/bch1k-burst.csv")
[ "$(awk -v r="$r" 'BEGIN{print (r+0 <= 0.05) ? 1 : 0}')" = 1 ] \
&& pass "control: bch1k-t32 burst 256 B rate=$r (expected ~0)" \
|| fail "control: bch1k-t32 burst 256 B rate=$r (expected ~0)"
# ---- winner 2: small-block BCH 1 KiB survives BER 1e-3 ----
$BENCH --codec bch1k-t32 --ber 1e-3 --trials 20 --out "$W/bch1k-ber.csv" 2>/dev/null
rate_ok "$W/bch1k-ber.csv" 0.95 "bch1k-t32 BER 1e-3"
# as-shipped BCH does not (control: expect ~0 at 1e-3)
$BENCH --codec bch-t32 --ber 1e-3 --trials 20 --out "$W/bch-ber.csv" 2>/dev/null
r=$(rate_of "$W/bch-ber.csv")
[ "$(awk -v r="$r" 'BEGIN{print (r+0 <= 0.05) ? 1 : 0}')" = 1 ] \
&& pass "control: bch-t32 BER 1e-3 rate=$r (expected ~0)" \
|| fail "control: bch-t32 BER 1e-3 rate=$r (expected ~0)"
# ---- winner 3: LDPC r90 survives BER 1e-3 (and 3e-3 at 10 trials) ----
$BENCH --codec ldpc-r90 --ber 1e-3 --trials 10 --out "$W/ldpc-ber.csv" 2>/dev/null
rate_ok "$W/ldpc-ber.csv" 0.9 "ldpc-r90 BER 1e-3"
# speed mode also proves the round-trip path for the two slow codecs
$BENCH --codec intlv-d64-bch1k-t32 --speed --out "$W/intlv-speed.csv" 2>/dev/null \
&& pass "intlv-d64-bch1k-t32 speed-mode round-trip" || fail "intlv-d64-bch1k-t32 speed mode"
$BENCH --codec ldpc-r90 --speed --out "$W/ldpc-speed.csv" 2>/dev/null \
&& pass "ldpc-r90 speed-mode round-trip" || fail "ldpc-r90 speed mode"
# ldpc_diag single-block sweep runs
"$ROOT/exp/ldpc_diag" r90 40 50 >/dev/null 2>&1 \
&& pass "ldpc_diag r90 sweep" || fail "ldpc_diag r90 sweep"
# ---- rANS core: order-0 round-trip ----
"$ROOT/experiments/rans_tool" c "$W/text.txt" "$W/text.rans" \
&& "$ROOT/experiments/rans_tool" d "$W/text.rans" "$W/text.out" \
&& cmp -s "$W/text.txt" "$W/text.out" \
&& pass "rANS order-0 round-trip" || fail "rANS order-0 round-trip"
# ---- winner 4: dictionary transform, code-only opt-in ----
"$ROOT/experiments/dict" c "$W/code.txt" "$W/code.dict" \
&& lzip -6 -k -f "$W/code.dict" \
&& lzip -dc "$W/code.dict.lz" > "$W/code.dict2" \
&& "$ROOT/experiments/dict" d "$W/code.dict2" "$W/code.out" \
&& cmp -s "$W/code.txt" "$W/code.out" \
&& pass "dict+lzip round-trip (code)" || fail "dict+lzip round-trip (code)"
lzip -6 -c "$W/code.txt" > "$W/code.plain.lz"
sz_d=$(stat -c%s "$W/code.dict.lz"); sz_p=$(stat -c%s "$W/code.plain.lz")
say "dict+lzip6 code: $sz_d bytes vs plain lzip6: $sz_p bytes"
# text must NOT win with dict (the measured result: +0.5% worse) -- record only
"$ROOT/experiments/dict" c "$W/text.txt" "$W/text.dict" \
&& lzip -6 -k -f "$W/text.dict" \
&& lzip -6 -c "$W/text.txt" > "$W/text.plain.lz"
say "dict+lzip6 text: $(stat -c%s "$W/text.dict.lz") bytes vs plain lzip6: $(stat -c%s "$W/text.plain.lz") bytes (dict expected worse on text)"
# ---- bchcheck: end-to-end BCH over a real lzip blob ----
"$ROOT/experiments/bchcheck" "$W/code.lz" 8 1234 "$W/code.rec" \
&& cmp -s "$W/code.lz" "$W/code.rec" \
&& pass "bchcheck 8 flips recovered" || fail "bchcheck 8 flips"
if "$ROOT/experiments/bchcheck" "$W/code.lz" 32 1234 "$W/code.rec32" 2>/dev/null; then
fail "bchcheck 32 flips unexpectedly recovered (t=8 must fail)"
else
pass "bchcheck 32 flips fails as expected (beyond t=8)"
fi
# ---- current main end-to-end: LZPL v5 archive round-trip ----
mkdir -p "$W/v5out"
(cd "$W" \
&& "$ROOT/lzply" -c text.txt v5.lzply >/dev/null 2>&1 \
&& "$ROOT/lzply" -a v5.lzply code.txt >/dev/null 2>&1 \
&& (cd v5out && "$ROOT/lzply" -d -y ../v5.lzply >/dev/null 2>&1) \
&& cmp -s text.txt v5out/text.txt \
&& cmp -s code.txt v5out/code.txt) \
&& pass "LZPL v5 archive round-trip (integrated tree)" \
|| fail "LZPL v5 archive round-trip"
if [ "$FAIL" != 0 ]; then say "INTEGRATION TESTS FAILED (work in $W)"; exit 1; fi
say "ALL INTEGRATION TESTS PASSED"
exit 0
+144
View File
@@ -0,0 +1,144 @@
#!/bin/bash
# run_lzcsv_tests.sh - test suite for lzcsv (standalone CSV compressor).
# Usage: run_lzcsv_tests.sh [path-to-lzcsv]
# Follows the repo's test conventions (PASS/FAIL counters, ok/bad).
# The corpus tests run only when the fftdict corpus is present
# (/root/fftdict-shared/corpus2); otherwise they are skipped, and the
# synthetic round-trips (generated here) still run. The oracle check
# runs only when the Python COLT1 prototype is present.
set -u
LZCSV="${1:-./lzcsv}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(dirname "$SCRIPT_DIR")"
WORK="$ROOT/testwork-lzcsv"
CORPUS="/root/fftdict-shared/corpus2"
HELD="/root/hot-qwen/lzcsv-heldout"
PY="/root/hot-qwen/cycle1/transpose.py"
PASS=0
FAIL=0
SKIP=0
ok() { PASS=$((PASS+1)); echo "PASS: $1"; }
bad() { FAIL=$((FAIL+1)); echo "FAIL: $1"; }
skip() { SKIP=$((SKIP+1)); echo "SKIP: $1"; }
rm -rf "$WORK"
mkdir -p "$WORK"
[ -x "$LZCSV" ] || { echo "lzcsv binary not found: $LZCSV"; exit 1; }
# --- 1. selftest + help ---------------------------------------------
if "$LZCSV" selftest > "$WORK/selftest.log" 2>&1; then ok "selftest"; else bad "selftest"; cat "$WORK/selftest.log"; fi
if "$LZCSV" --help > "$WORK/help.log" 2>&1; then ok "--help"; else bad "--help"; fi
# --- 2. synthetic round-trips (generated here, always run) -----------
printf 'a,b,c\n1,2,3\n4,5,6\n' > "$WORK/synth1.csv"
printf 'name,age,city\r\nann,34,oslo\r\nbob,29,bergen\r\n' > "$WORK/synth-crlf.csv"
printf 'a,b,c\n1,2\n3,4,5,6,7\n8\n' > "$WORK/synth-ragged.csv"
printf 'id,note\n1,"hello, world"\n2,"say ""hi"""\n3,plain "quoted" text\n' > "$WORK/synth-quotes.csv"
printf 'x,y\n1,2\n3,4' > "$WORK/synth-noeol.csv"
printf 'col1,col2,col3\n' > "$WORK/synth-header.csv"
: > "$WORK/synth-empty.csv"
for f in "$WORK"/synth*.csv; do
n="$(basename "$f")"
if "$LZCSV" c -f "$f" "$WORK/$n.lzcsv" > /dev/null 2>&1 && \
"$LZCSV" d -f "$WORK/$n.lzcsv" "$WORK/$n.rt.csv" > /dev/null 2>&1 && \
cmp -s "$f" "$WORK/$n.rt.csv"; then
ok "round-trip $n"
else
bad "round-trip $n"
fi
done
# in-memory test subcommand over the synthetic set
if "$LZCSV" test "$WORK"/synth*.csv > "$WORK/test.log" 2>&1; then ok "lzcsv test (synthetic)"; else bad "lzcsv test (synthetic)"; cat "$WORK/test.log"; fi
# --- 3. corpus round-trips (only where the corpus exists) ------------
if [ -d "$CORPUS" ]; then
n=0; ok_n=0
for f in "$CORPUS"/*.csv; do
n=$((n+1))
b="$(basename "$f")"
if "$LZCSV" c -f "$f" "$WORK/$b.lzcsv" > /dev/null 2>&1 && \
"$LZCSV" d -f "$WORK/$b.lzcsv" "$WORK/$b.rt.csv" > /dev/null 2>&1 && \
cmp -s "$f" "$WORK/$b.rt.csv"; then
ok_n=$((ok_n+1))
else
bad "corpus round-trip $b"
fi
done
[ "$ok_n" = "$n" ] && ok "corpus round-trips $ok_n/$n"
else
skip "corpus round-trips (no $CORPUS)"
fi
# --- 4. held-out round-trips (only where the set exists) --------------
if [ -d "$HELD" ]; then
n=0; ok_n=0
for f in "$HELD"/*.csv; do
b="$(basename "$f")"
[ "$b" = "embedded-nl.csv" ] && continue
n=$((n+1))
if "$LZCSV" c -f "$f" "$WORK/h-$b.lzcsv" > /dev/null 2>&1 && \
"$LZCSV" d -f "$WORK/h-$b.lzcsv" "$WORK/h-$b.rt.csv" > /dev/null 2>&1 && \
cmp -s "$f" "$WORK/h-$b.rt.csv"; then
ok_n=$((ok_n+1))
else
bad "held-out round-trip $b"
fi
done
[ "$ok_n" = "$n" ] && ok "held-out round-trips $ok_n/$n"
else
skip "held-out round-trips (no $HELD)"
fi
# --- 5. oracle: COLT1 output byte-identical to the Python prototype --
if [ -f "$PY" ] && [ -d "$CORPUS" ]; then
n=0; ok_n=0
for f in "$CORPUS"/*.csv; do
n=$((n+1))
b="$(basename "$f")"
python3 "$PY" enc "$f" "$WORK/$b.py.colt" 2>/dev/null
"$LZCSV" raw-enc -f "$f" "$WORK/$b.c.colt" 2>/dev/null
if cmp -s "$WORK/$b.py.colt" "$WORK/$b.c.colt"; then
ok_n=$((ok_n+1))
else
bad "oracle raw-enc $b"
fi
# cross-decode both ways
"$LZCSV" raw-dec -f "$WORK/$b.py.colt" "$WORK/$b.c-dec.csv" 2>/dev/null
python3 "$PY" dec "$WORK/$b.c.colt" "$WORK/$b.py-dec.csv" 2>/dev/null
cmp -s "$WORK/$b.c-dec.csv" "$f" || bad "C raw-dec of Python .colt $b"
cmp -s "$WORK/$b.py-dec.csv" "$f" || bad "Python dec of C .colt $b"
done
[ "$ok_n" = "$n" ] && ok "oracle raw-enc byte-identical $ok_n/$n"
else
skip "oracle check (no prototype or no corpus)"
fi
# --- 6. clean rejections ----------------------------------------------
printf 'id,note\n1,"first line\nsecond line"\n2,plain\n' > "$WORK/embedded.csv"
if "$LZCSV" c "$WORK/embedded.csv" "$WORK/embedded.lzcsv" > /dev/null 2>&1; then
bad "embedded-newline input must be rejected"
else
ok "embedded-newline input rejected cleanly"
fi
# truncated input
if [ -f "$WORK/synth1.csv.lzcsv" ]; then
head -c 20 "$WORK/synth1.csv.lzcsv" > "$WORK/trunc.lzcsv"
if "$LZCSV" d "$WORK/trunc.lzcsv" "$WORK/trunc.csv" > /dev/null 2>&1; then
bad "truncated input must fail"
else
ok "truncated input fails cleanly"
fi
printf 'NOTLZCSV' > "$WORK/badmagic.lzcsv"
cat "$WORK/synth1.csv.lzcsv" >> "$WORK/badmagic.lzcsv"
if "$LZCSV" d "$WORK/badmagic.lzcsv" "$WORK/bm.csv" > /dev/null 2>&1; then
bad "bad-magic input must fail"
else
ok "bad-magic input fails cleanly"
fi
fi
# info works
if "$LZCSV" info "$WORK/synth1.csv.lzcsv" > /dev/null 2>&1; then ok "info"; else bad "info"; fi
echo "lzcsv tests: $PASS passed, $FAIL failed, $SKIP skipped"
[ "$FAIL" = 0 ]