Sub topic 15
Beyond Search: Rabin Fingerprints and Content-Defined Chunking
This chapter assumes you know the rolling hash update from earlier chapters. You should also be comfortable with Python bytes objects and bitwise AND. Rabin-Karp uses a rolling hash to answer "does this window match the pattern?" The same constant-time window hash can answer another question: "is this a good place to cut the data?" Backup tools, deduplicating storage, and file-sync programs such as rsync-style systems and LBFS rely on this idea.
Rabin Fingerprints
Michael Rabin's original fingerprint treats a bit string as a polynomial over GF(2), the field with two elements, and reduces it modulo a random irreducible polynomial. You can compute it with XOR and shifts, and it rolls the same way our hash does: remove the outgoing contribution, shift, add the incoming one. Its collision probability can be bounded for any fixed pair of inputs because the polynomial is chosen at random. That is the same reason we randomize the base in Rabin-Karp.
For this chapter, the integer polynomial hash modulo a prime plays the same role. The algorithms below only need a window hash that is cheap to roll and roughly uniform.
The Problem with Fixed-Size Chunks
Suppose you split a file into 4 KiB blocks, hash each block, and store only blocks you have not seen before. If someone inserts one byte at the start of the file, every block boundary shifts by one. Every block now looks new, so deduplication fails.
Content-defined chunking fixes this by choosing boundaries from the content itself. You slide a window of w bytes over the data and declare a boundary wherever the window hash meets a condition, such as hash & mask == 0. A boundary depends only on the w bytes just before it. An edit can therefore only move boundaries near the edit. After that, the chunker hits the same boundaries as before.
With a uniform hash, hash & mask == 0 holds with probability 1 / (mask + 1). A mask of 0x3F therefore gives boundaries about every 64 bytes. Production systems use masks like 0x1FFF for chunks of about 8 KiB. Minimum and maximum sizes stop chunks from getting tiny or huge.
A Working Chunker
import random
def chunk(data, window=16, mask=0x3F, base=257, mod=(1 << 61) - 1,
min_size=32, max_size=256):
high = pow(base, window - 1, mod)
chunks, start, h = [], 0, 0
for i, b in enumerate(data):
if i >= window:
h = (h - data[i - window] * high) % mod # drop outgoing byte
h = (h * base + b) % mod # add incoming byte
size = i + 1 - start
if (size >= min_size and (h & mask) == 0) or size >= max_size:
chunks.append(data[start:i + 1])
start = i + 1
if start < len(data):
chunks.append(data[start:])
return chunks
def fixed(data, size=64):
return [data[i:i + size] for i in range(0, len(data), size)]
random.seed(1)
data = bytes(random.randrange(256) for _ in range(20000))
edited = b"XYZ" + data # insert 3 bytes at the front
for name, f in [("content-defined", chunk), ("fixed-size", fixed)]:
a, b = f(data), f(edited)
shared = len(set(a) & set(b))
print(f"{name}: {shared} of {len(set(a))} chunks reused")When you run it, almost every content-defined chunk survives the edit, and almost no fixed-size chunk does. The window hash here covers the last w bytes of the whole stream and ignores chunk starts, so the boundary test does not depend on where the previous chunk began. The minimum-size rule adds a small dependency on the previous boundary, but the chunker falls back into step within a chunk or two.
Exercise
You want an average chunk size of about 8 KiB using the test h & mask == 0. What mask do you use, and why does inserting bytes in the middle of a file change only one or two chunks?
Show answer
Use mask = 0x1FFF (8192 - 1). A uniform hash then satisfies the test with probability 1/8192. Each boundary depends only on the last w bytes before it. Boundaries far from the edit see the same windows and stay where they were, so only the chunks that overlap the edit, plus at most a nearby one affected by the minimum-size rule, change.
Exercise
Why is it acceptable for the boundary hash to have occasional collisions, when Rabin-Karp must verify every hash match?
Show answer
A collision in the boundary test only produces an extra or missing cut point. That changes chunk sizes but never gives a wrong answer. Correctness comes from the strong per-chunk hash used for deduplication, not from the rolling hash.