Skip to content
HN On Hacker News ↗

Reverse-Engineering Kevin J. Lang's Lost OCaml Code in Apache DataSketches

▲ 46 points • 3 comments • by tison • 1w ago • HN discussion ↗

Pangram verdict · v3.3

We believe that this text is a mix of AI, AI-assisted, and human-written content.

77 %

AI likelihood · overall

Mixed
21% human-written 74% AI-generated
SEGMENTS · HUMAN 12 of 27
SEGMENTS · AI 7 of 27
WORD COUNT 1,421
PEAK AI % 100% · §2
Analyzed
Nov 19
backend: pangram/v3.3
Segments scanned
27 windows
avg 53 words each
Distribution
21 / 74%
human / AI fraction
Verdict
Mixed
Pangram v3.3

Article text · 1,421 words · 27 segments analyzed

Human AI-generated
§1 Mixed · 50%

It started with a routine feature in ScopeDB: implementing approx_count_distinct for approximate distinct counting. HyperLogLog (HLL) is the standard textbook choice. Early on, Rust’s HLL ecosystem was uneven, so I started with Cloudflare’s open-source cardinality-estimator.

§2 AI · 100%

That crate leaned heavily on unsafe code and manual bit-packing tricks, though, so to keep things auditable and under our control, I forked and maintained an internal copy inside ScopeDB.

§3 Mixed · 50%

While evaluating alternatives, I came across Apache DataSketches, which offered a battle-tested HllSketch alongside CpcSketch, an even more space-efficient design. At the time, Apache DataSketches only shipped Java and C++ implementations, whereas ScopeDB is written in Rust.

§4 Mixed · 50%

As it turned out, the Apache DataSketches community was interested in an official Rust port.

§5 Mixed · 50%

Starting late last year, I teamed up with a few other Rust developers well-versed in sketching algorithms to build and ship the initial releases of datasketches-rust, beginning with HllSketch. Soon after, I switched ScopeDB’s distinct counting over to our datasketches-rust implementation.

§6 Mixed · 51%

Apache DataSketches Rust Contributors Anyone who has implemented streaming distinct counting knows how HLL works: elements are hashed into KK buckets, and each bucket keeps only the maximum leading-zero count seen so far (typically 4 to 6 bits), while every other hit in that bucket goes unrecorded.

§7 Mixed · 51%

Once HLL enters dense mode, every bucket maintains a fixed-width register.

§8 Human · 0%

In his 2017 paper Back to the Future: an Even More Nearly Optimal Cardinality Estimation Algorithm, Yahoo!

§9 Human · 3%

Research scientist Kevin J.

§10 Mixed · 50%

Lang proposed going back to basics: instead of keeping only per-bucket maxima, retain the full K×64K \times 64 bit matrix of the classic FM85 coupon collector’s process.

§11 Mixed · 50%

Whenever row rr sees a hash with cc leading zeros, set bit (r,c)(r, c) to 11. Keeping the full two-dimensional hit matrix lets CPC pair a streaming HIP estimator with a mergeable ICON estimator for higher statistical efficiency than HLL.

§12 AI · 100%

On serialization, it adapts its layout to fill density: low cardinalities use a sparse PairTable of (row, column) pairs, while medium and high cardinalities combine a sliding 8-bit window, length-limited Huffman coding, and column permutations to pack the sketch near the information-theoretic entropy limit. According to the DataSketches documentation, serialized CPC shrinks storage by 30% to 40% compared with HLL at equal accuracy.

§13 Human · 0%

In late January, I ported CpcSketch to datasketches-rust (PR-75) and switched ScopeDB over to it. It has run smoothly in production for more than six months.

§14 Human · 0%

https://github.com/apache/datasketches-rust/pull/75 While porting CpcSketch from the upstream C++ and Java implementations, however, I noticed several hardcoded magic lookup tables in the source code: 23 static Huffman encoding tables 16 sliding-window column permutations 23 sets of degree-19 polynomial correction coefficients 4 empirical confidence-interval quantile tables These four sets of static tables live in compression_data.rs and estimator.rs. Here is a short excerpt: // datasketches/src/cpc/compression_data.rspub static LENGTH_LIMITED_UNARY_ENCODING_TABLE65: [u16; 65] = [ // entropy: 2.0 // avg_length: 2.0249023437500000000; max_length = 12; num_symbols = 65 0x1000, 0x2001, 0x3003, 0x4007, // ...];pub static COLUMN_PERMUTATIONS_FOR_ENCODING: [[u8; 56]; 16] = [ [0, 1, 2, 3, 5, 6, 7, 8, /* ... */ 54, 55, 34, 14, 4], // ...];pub static ENCODING_TABLES_FOR_HIGH_ENTROPY_BYTE: [[u16; 256]; 22] = [ // entropy: 4.4619200780464778333 // avg_length: 4.5415773046232610355; max_length = 12; num_symbols = 256 [0x9017, 0x5009, 0x7033, 0x3002, /* ... */], // ...];// datasketches/src/cpc/estimator.rsstatic ICON_POLYNOMIAL_COEFFICIENTS: [f64; ICON_TABLE_SIZE] = [ // log K = 4 0.9895027971889700513, 0.3319496644645180128, 0.1242818722715769986, // ...];static ICON_LOW_SIDE_DATA: [u16; 33] = [ //1, 2, 3, kappa 6037, 5720, 5328, // 4 1000000 // ...];static ICON_HIGH_SIDE_DATA: [u16; 33] = [ /* ... */ ];static HIP_LOW_SIDE_DATA: [u16; 33] = [ /* ... */ ];static HIP_HIGH_SIDE_DATA: [u16; 33] = [ /* ...

§15 Human · 0%

*/ ]; Whenever I port lookup tables, I prefer to derive the values from first principles in unit tests and check them element by element against the static array.

§16 Human · 0%

For kxp_byte_lookup, for example, I kept the derivation right inside the test suite: for byte in 0u8..=255 { // expected value let expected = KXP_BYTE_TABLE[byte as usize]; // computed value let mut computed = 0.0; for col in 0..8 { let bit = (byte >> col) & 1; if bit == 0 { // note the inverted logic computed += inv_pow2(col + 1); //note the "+1" } } assert_eq!(expected, computed);} For CompressionData and the ICON estimator tables, though, no generator source existed anywhere in the repositories, so I had no way to derive them on my own back then. Only two build commands remained in an upstream comment: ~/ocaml-4.03.0/bin/ocamlopt -o generateHuffmanCodes columnProbabilities.ml generateHuffmanCodes.ml./generateHuffmanCodes > raw-encoding-tables.c I searched every Apache DataSketches repository and came up empty on those .ml files.

§17 Human · 0%

So I opened ISSUE-720 on datasketches-java to ask where the generator sources lived.

§18 Human · 0%

Lee Rhodes replied: Kevin did most of his math simulations and modeling in OCaml. And his code was on his computer, which no longer exists. And his personal code died with him … even if they have a copy of his old computer it might be trying to find a needle in a haystack.

§19 Human · 0%

Kevin passed away in April 2019, and any code left on his personal machine is effectively lost to history.

§20 Human · 0%

I was saddened to hear that.

§21 Human · 0%

Kevin’s research in sketching algorithms underpins many of the core sketches in Apache DataSketches: A Framework for Estimating Stream Expression Cardinalities (Theta Sketch) Optimal Quantile Approximation in Streams (KLL Sketch, the “L” in KLL) A High-Performance Algorithm for Identifying Frequent Items in Data Streams (Frequent Items Sketch) Back to the Future: an Even More Nearly Optimal Cardinality Estimation Algorithm (CPC Sketch and HLL estimators) Still, with the runtime decoders and detailed header comments sitting right there in the source files, it seemed possible to reverse-engineer the offline generators from the artifacts alone. I asked Lee whether the CPC paper explained how the tables were derived, and he answered: You should definitely read the paper. But it won’t tell you any details on the Huffman codings. As I recall, in his paper he used a more standard compression scheme. He finished his work on the code after he had finished his paper — and in the process came up with the modified Huffman coding idea, which is quite a bit more efficient than what he discussed in the paper.

§22 AI · 100%

That placed the derivation well beyond what I could work out on my own in an afternoon. Since CpcSketch worked fine in datasketches-rust as long as the lookup arrays were copied faithfully, I left the mystery aside for the time being.

§23 Human · 0%

Then Gemini 4 Carbon came out just as I was preparing the next release of datasketches-rust.

§24 AI · 100%

Since the checked-in tables and 20-digit header comments already acted as a strict numerical oracle, any candidate generator could be tested immediately in code: either it reproduced every codeword, permutation entry, and floating-point diagnostic within IEEE-754 precision, or it was wrong. That made the problem well suited to an agentic workflow built around executable checks and adversarial review. Over several iterations, I steered three models against that oracle and against one another: Initial synthesis (Gemini 4 Carbon): Starting from the static arrays and source comments, it wrote executable probes and built the first constructive test harness, reproducing the Huffman codewords and column permutations bit-for-bit and fitting the ICON polynomials to matching accuracy. Mathematical falsification (Claude Opus 5.5): Tasked with breaking those initial claims, it ran controlled ablations that disproved an early “left-edge truncation” explanation, isolated an f64 cancellation trap, mapped out where the polynomial fits stop being identifiable, and re-ran the million-trial Monte Carlo statistics. Mutation and analytical audit (GPT 6 Astra): Auditing both the tests and the derivations, it used mutation testing to expose two tautological assertions, caught several mathematical overstatements in earlier drafts, and derived a closed-form expression matching the trailing digits of the asymptotic exponential constant. None of the models got everything right on the first try, and several plausible-looking explanations collapsed as soon as we tested perturbations in code.

§25 AI · 100%

What survived that filter became PR-355, which checks the reconstructed generators and derivations into datasketches-rust as unit tests, following the same approach we took for kxp_byte_lookup.

§26 AI · 100%

https://github.com/apache/datasketches-rust/pull/355 The rest of this post focuses on the mathematics and numerical forensics behind those four sets of tables: how each structure works, which wrong turns looked convincing until an ablation broke them, and where the surviving artifacts cannot tell two models apart. Formal derivations sit in the appendix at the end; if you spot an error, feel free to leave a comment or open a PR on datasketches-rust.

§27 AI · 100%

The Blind Spot of Discrete Codewords, and a 20-Digit Fingerprint We begin with the 23 Huffman coding tables in compression_data.rs. Why hardcode 23 static Huffman tables at all?