Sub topic 15
Beyond Search: Rabin Fingerprints and Content-Defined Chunking
This chapter assumes you know the rolling hash update from earlier chapters: drop the outgoing character's term, multiply by the base, add the incoming character. It also assumes you are comfortable with modular arithmetic and bitwise operators (&, ^, <<, >>) in Python. The rolling hash is useful beyond pattern search. Backup tools, file synchronizers and deduplicating storage systems use it to cut byte streams into pieces that stay stable when the data is edited.
Rabin Fingerprints: The Same Idea Over Bits
Michael Rabin's 1981 paper "Fingerprinting by Random Polynomials" defines a hash close to the polynomial hash you already know, with one change: the arithmetic happens over GF(2), the field with only the values 0 and 1.
A bit string is read as a polynomial whose coefficients are its bits. For example, the bits 1011 are the polynomial x³ + x + 1. The fingerprint is the remainder when that polynomial is divided by a fixed irreducible polynomial P of degree k. A polynomial is irreducible when it cannot be factored into smaller polynomials over GF(2). Irreducible polynomials play the role that prime moduli play in integer hashing.
In GF(2), adding coefficients is XOR, so there are no carries. That changes the implementation:
| Operation | Integer polynomial hash | Rabin fingerprint over GF(2) |
|---|---|---|
| "Multiply by base" | `h * base` | shift left by one bit (multiply by x) |
| "Add next symbol" | `+ ord(ch)` | OR in the next bit |
| Reduce | `% mod` | XOR with P when bit k is set |
| Subtraction | needs `+ MOD` to avoid negatives | XOR, which is its own inverse |
| Overflow risk | yes, in fixed-width types | none, the value always fits in k bits |
The fingerprint is Horner's rule again, done one bit at a time. The toy version below uses the degree-8 irreducible polynomial x⁸ + x⁴ + x³ + x + 1 (0x11B, the polynomial AES uses). Real systems use degree 53 or 64.
def gf2_fingerprint(data, poly=0x11B, degree=8):
"""Remainder of the bit-polynomial of `data` modulo `poly`, over GF(2)."""
r = 0
for byte in data:
for bit in range(7, -1, -1):
r = (r << 1) | ((byte >> bit) & 1) # multiply by x, add the next bit
if (r >> degree) & 1: # degree reached k: reduce
r ^= poly
return r
a = b"hello"
b = b"world"
x = bytes(p ^ q for p, q in zip(a, b))
print(gf2_fingerprint(a), gf2_fingerprint(b))
# The fingerprint is linear: fp(a XOR b) == fp(a) XOR fp(b) for equal lengths
print(gf2_fingerprint(x) == gf2_fingerprint(a) ^ gf2_fingerprint(b)) # TrueRabin proved a collision bound for a randomly chosen irreducible P of degree k: two different strings of n bits get the same fingerprint with probability at most about n / 2ᵏ. With k = 64 and 8 KB inputs (n = 65,536 bits), that is about 2⁻⁴⁸. The bound holds for any pair of inputs, as long as the adversary does not know P. This is the same argument for randomized parameters you saw in the chapter on choosing the base and modulus.
Production code does not loop bit by bit. It precomputes two 256-entry tables. One reduces a whole byte at a time. The other gives the contribution of the byte leaving the window, which is XORed out. Each byte then costs a couple of table lookups and shifts.
The Problem Chunking Solves
Suppose a backup system stores files as chunks and keys each chunk by its hash. Identical chunks are stored once. This is deduplication. The design question is where to cut.
Fixed-size chunking cuts every 4 KB. It is simple, but inserting one byte near the start of a file moves every later byte by one position. Every later chunk changes, and nothing deduplicates against the previous version.
Content-defined chunking (CDC) decides cut points from the data itself. Slide a rolling hash over a small window, for example 48 bytes, and cut wherever the hash meets a condition, such as its low 13 bits all being 1. A cut point depends only on the 48 bytes before it. After an edit, once the window has moved past the changed bytes, the hash values match the old file's and the cuts fall in the same places relative to the content.
If the hash's low bits behave like random bits, a b-bit mask matches at each position with probability 2⁻ᵇ. Chunk lengths then follow roughly a geometric distribution with mean 2ᵇ bytes. A 13-bit mask gives chunks that average about 8 KB. That is the setup the Low-Bandwidth Network File System (LBFS, 2001) used, with Rabin fingerprints over a 48-byte window.
A Working Content-Defined Chunker
The chunker below reuses the integer rolling hash from earlier chapters, with the Mersenne prime 2⁶¹ − 1 as the modulus and 263 as the base. It adds the minimum and maximum chunk sizes that real systems enforce. The demo then compares CDC with fixed-size chunking after an 8-byte insertion.
import random
def cdc_cuts(data, window=48, mask_bits=10, min_size=256, max_size=4096,
base=263, mod=(1 << 61) - 1):
"""Return the end offset of every chunk in `data` (a bytes object)."""
mask = (1 << mask_bits) - 1
high = pow(base, window - 1, mod) # weight of the byte leaving the window
cuts, start, h = [], 0, 0
for i, b in enumerate(data):
if i >= window:
h = (h - data[i - window] * high) % mod # remove the outgoing byte
h = (h * base + b) % mod # add the incoming byte
size = i + 1 - start
if size >= min_size and ((h & mask) == mask or size >= max_size):
cuts.append(i + 1)
start = i + 1
if start < len(data):
cuts.append(len(data))
return cuts
def split(data, cuts):
pieces, start = [], 0
for c in cuts:
pieces.append(data[start:c])
start = c
return pieces
def fixed_split(data, size):
return [data[i:i + size] for i in range(0, len(data), size)]
def reused(old, new):
"""How many chunks of `new` already exist in `old`."""
known = set(old)
return sum(1 for c in new if c in known), len(new)
rng = random.Random(42)
data = bytes(rng.getrandbits(8) for _ in range(200_000))
edited = data[:100_000] + b"INSERTED" + data[100_000:]
cdc_old = split(data, cdc_cuts(data))
cdc_new = split(edited, cdc_cuts(edited))
fix_old = fixed_split(data, 1280)
fix_new = fixed_split(edited, 1280)
print("CDC reused %d of %d chunks" % reused(cdc_old, cdc_new))
print("Fixed reused %d of %d chunks" % reused(fix_old, fix_new))The average CDC chunk here is about min_size + 2**mask_bits ≈ 1,280 bytes, so the fixed chunker uses the same size for a fair comparison. When you run it, CDC reuses almost every chunk; usually only the one or two chunks around the insertion are new. Fixed-size chunking reuses roughly the first half and loses everything after offset 100,000.
Why the minimum size slightly delays resynchronization
The cut test checks both the hash and the chunk length. The chunk length depends on where the current chunk started, so it is not purely local. After an edit, a hash match that would have produced a cut in the old file can be skipped in the new one because the chunk is still shorter than min_size. That makes the next cut differ as well. Once one cut lands at the same content position in both versions, every later cut matches, because from that point both runs see identical bytes and identical chunk starts. In practice resynchronization takes one or two chunks.
Parameter trade-offs
| Parameter | Smaller value | Larger value |
|---|---|---|
| `mask_bits` (average size) | finer dedup, more chunks and more index metadata | less metadata, coarser dedup |
| `window` | cheaper; too small makes cut points depend on very little content | more context per decision, slightly more work per byte |
| `min_size` | allows tiny chunks that cost index space | skips more candidate cuts, slower resync |
| `max_size` | more forced cuts, which are not content-defined | allows long chunks in low-entropy data |
The max_size cap matters for repetitive input. A file of all zeros produces the same window hash at every position. If that hash fails the mask test, no cut ever appears, and the cap is the only thing that ends the chunk.
Rolling Hashes in Real Systems
Several families of rolling hash appear in practice. They make different choices about speed and theory.
| Hash | Update | Used by |
|---|---|---|
| Rabin fingerprint (GF(2)) | table lookups and XOR; provable collision bound | LBFS; restic, which picks a random irreducible polynomial per repository |
| Buzhash (cyclic polynomial) | rotate and XOR with a per-byte random table | Borg backup |
| Gear hash | `h = (h << 1) + table[byte]`; old bytes shift out with no subtraction | FastCDC |
| Adler-32-style weak checksum | running sums | rsync, to find matching blocks at any offset |
Gear hashing shows how far the idea can be simplified. Shifting left by one bit each step pushes a byte's influence out of a 64-bit word after 64 steps. The window is therefore implicit, and the update needs no subtraction.
rsync uses its rolling checksum differently. It does not choose cut points. The receiver sends weak and strong checksums of its fixed blocks. The sender slides the weak rolling checksum across its own file, one byte at a time, looking for those blocks at any offset. It confirms each candidate with the strong checksum. This is the same check-then-verify pattern as Rabin-Karp's explicit comparison after a hash match.
Exercise
In the CDC demo, an 8-byte insertion at offset 100,000 changes only one or two chunks. Explain why every cut after the first coinciding cut is identical in both versions, and why fixed-size chunking cannot recover.
Show answer
A CDC cut depends on the hash of the previous window bytes and on the current chunk's start. Once both versions place a cut at the same content position, they continue from identical chunk starts over identical bytes, so every later hash value and length check matches. Fixed-size cuts depend only on absolute offsets. The insertion shifts all later content by 8 bytes relative to the multiples of 1,280, so no chunk after the edit lines up with an old one.
Exercise
You want chunks averaging about 64 KB with the chunker above, keeping minsize at 256. Which maskbits should you choose? What happens to a 10 MB file of zero bytes?
Show answer
Use maskbits = 16, because 2^16 = 65,536 and the 256-byte minimum adds little. In a run of zeros, every full window has the same hash. If that hash's low 16 bits are not all 1, no content-defined cut ever happens, and the file is split purely by maxsize, here into 4,096-byte chunks. If the value does match, every chunk is cut at exactly min_size. Either way the boundaries are forced by the size limits, which shows why both limits are needed.
Exercise
Using gf2_fingerprint, explain why Rabin fingerprints over GF(2) need no "+ MOD" correction when the outgoing byte is removed, while the Java roll function from an earlier chapter does.
Show answer
In GF(2), subtraction is the same operation as addition: XOR. Removing the outgoing byte's contribution means XORing it out, and XOR of k-bit values always gives a k-bit value with no sign. Integer subtraction modulo a prime can produce a negative intermediate in fixed-width types, so Java adds MOD before reducing.