Data structureadvanced
Differential file
Also called Severance-Lohman differential files.
Keep changes in a separate file with a filter of changed keys and merge them into the main file later, which eases backup and recovery.
- Time
- Θ(k) worst
- Space
- Θ(m + n) extra
- Where
- N = the records of the main file; k = the hash functions of the filter; m = the length of the filter array; n = the entries in the differential file
- Model
- Word RAM
- Properties
- not concurrentexternalnot persistent
- Evidence
- Proof sketchCode in 1 languages
A differential file keeps a large file of records unchanged and writes every insert, change and delete to a second, small file, the differential file. A read checks the small file first, but only when an in-memory Bloom filter of the changed keys says that the key may be there. Now and then a reorganization merges the changes into a new copy of the main file. Severance and Lohman (1976) proposed it to make backup and recovery of large databases cheap: the main file changes only at a reorganization, so one dump of it stays valid until the next one. It differs from shadow paging, which keeps old and new versions of whole pages and switches a root pointer at commit; a differential file keeps changes at the level of records and merges them in a batch much later.
In plain words
Think of a large printed phone book and a short list of corrections next to it. You never write in the book. A new number, a changed number or a removed name goes on the list. To find a name, you look at the list first, and if the name is not on it, you look in the book.
Reading the list each time costs work. So you keep a small card of marks: each name on the list sets a few marks. If one of the marks of a name is missing, the name is surely not on the list, and you go straight to the book. Sometimes all the marks are there by chance, and you read the list for nothing.
Once a month you print a new book with all the corrections, keep a copy in a safe place, and start an empty list.
The abstract type
The structure stores a relation with a key: a set of records, at most one per key. The operations are:
- lookup(key): the record with this key, or absent;
- put(key, record): insert a record, or replace the record with this key;
- delete(key): remove the record with this key;
- scan(): all records in key order;
- reorganize(): no change to the relation; it only moves data between the parts of the structure.
The relation that the structure holds is the main file with the entries of the differential file applied over it, as defined under Correctness.
Representation
- The main file : the records at the last reorganization, sorted by key, for example a B+ tree or a sorted file on disk. It is read-only between reorganizations.
- The differential file : one entry per changed key, the newest one. An entry is a new record or a delete marker. A real system keeps as an append-only file with an index on its keys; the code keeps a dict.
- The filter : a Bloom filter of bits with hash functions over the keys in , in main memory.
- The archive: a dump of each generation of , made at the reorganization that writes it.
Operations
LOOKUP(key)- 1
if the bits h_1(key), ..., h_k(key) of F are all 1 then - 2
if D has an entry for key then return its record, or absent for a delete marker - 3
return the record of key in M, or absent PUT(key, entry) ▷ entry is a record or the delete marker- 4
D[key] ← entry - 5
set the bits h_1(key), ..., h_k(key) of F to 1 REORGANIZE()- 6
M' ← the merge of M and D in key order: an entry of D replaces the record of M, and a delete marker drops it - 7
dump M' to the archive; make M' the main file - 8
D ← empty; F ← all zeros
A lookup of an unchanged key whose filter bits are not all set reads only (line L3). A lookup whose bits are all set reads ; if has no entry, this was a false positive and the lookup goes on to . A put or a delete writes only and the filter. A scan merges and in key order, as line L6 does.
Backup and recovery. Between two reorganizations only changes. A backup is then a dump of only, and the dump of in the archive stays valid. If the disk that holds fails, copy from the archive. If is lost, restore its last dump and redo the changes logged since. The cost of a dump and of this redo grows with the size of , not with the size of the database. The analysis of how large may grow before a reorganization is in Aghili and Severance (1982).
Example
Main file : keys 1, 2 and 3 with records a, b and c. The filter has bits and hash functions; for the hand example take and (the code uses a cryptographic hash instead).
- put(2, B): , set bits 2 and 13.
- delete(3): gets a delete marker for 3, set bits 3 and 2.
- put(4, d): gets , set bits 4 and 7.
The filter now has bits 2, 3, 4, 7 and 13 set.
| lookup | bits | reads | answer |
|---|---|---|---|
| 1 | 1 and 8: bit 1 is 0 | a | |
| 2 | 2 and 13: both 1 | B | |
| 3 | 3 and 2: both 1 | absent (delete marker) | |
| 5 | 5 and 12: bit 5 is 0 | absent | |
| 18 | 2 and 13: both 1 | , then | absent (a false positive) |
reorganize() writes , dumps it, and clears and the filter.
Correctness
Define the relation that the structure holds as : the records of whose key has no entry in , plus the records of . A delete marker in removes its key.
Claim. If the structure holds = the relation of the abstract type before an operation, then after put or delete it holds the changed relation, lookup returns the record of the abstract type, and reorganize does not change .
Proof. A Bloom filter has no false negatives: line L5 sets every bit of each key in , and only line L8 clears bits, at the same time as it empties . So when has an entry for the key, line L1 is true and line L2 returns the entry; when has none, lookup reaches line L3 either directly or after a false positive, and returns the record of . That is the definition of . Line L4 keeps only the newest entry for a key, which is the effect of the newest put or delete. Line L6 computes itself, so after line L8, .
The filter affects only the cost of a lookup, never its answer. The proof states the invariants in full.
Proof: A differential file answers every lookup as the flat relation doesfull
Model. The structure is a main file (a map from keys to records), a differential file (a map from keys to records or a delete marker ), a filter of bits with hash functions , and an archive (a list of maps). The relation it represents is
The abstract relation starts as , put sets , and delete removes from .
Invariants. After every operation:
- (I1) .
- (I2) For every key , the bits of are 1.
- (I3) equals the last map in the archive.
Lemma 1. The invariants hold at the start and after each put, delete and reorganize.
Proof. At the start is empty, is all zeros, and the archive holds a copy of , so all three hold.
put sets (line L4). For the new gives , for every other key nothing changes, and changes the same way, so I1 holds. Line L5 sets the bits of and clears none, so I2 holds. and the archive do not change, so I3 holds. delete is the same with : the new has no record for , as .
reorganize sets (line L6), appends a copy of to the archive and makes it the main file (line L7), and then empties and clears (line L8). Now , which is I1. I2 holds because is empty, and I3 by line L7.
Lemma 2. lookup returns , or absent if .
Proof. If , then by I2 the test of line L1 is true, and line L2 returns , or absent when . That is . If , then line L2 does not return, whatever the filter says, and line L3 returns or absent, which again is . By I1 this is .
Lemma 3. scan returns the records of in key order, and between two reorganizations does not change.
Proof. scan computes in key order, which is by I1. Only line L7 assigns .
Recovery. If is lost between two reorganizations, a copy of the last map in the archive restores it, by I3, and I1 holds again with the same .
The filter enters only in Lemma 2, and only through I2. A false positive (line L1 true for a key not in ) changes the reads that a lookup makes, never its answer.
Complexity
Costs are in record reads of and and in in-memory bit probes.
- lookup: bit probes. For a key that has an entry in , one read of . For an unchanged key, one read of , plus one read of with the probability of a false positive.
- put and delete: one write to and bit sets. is not written.
- reorganize: one pass over and and one write of , records if is kept in key order, plus the dump of .
- Space: bits of memory for the filter, and entries in .
False positive rate (theorem, in an idealized model). If the hash values of each key are independent and uniform over the bits, the probability that a key not in passes the filter after entries is about , the standard Bloom filter bound. It is smallest near . With and , is under 1 percent, so unchanged keys almost never cost a read of . Real hash functions only approximate the model.
Variants
- Filter design. Severance and Lohman give the design of the filter in their Section 2.6, and Gremillion (1982) gives a method to choose its size and number of hash functions for a differential file.
- Several differential files. Two or more differential files over one read-only main file give two or more versions of the data, each seen through its own changes, for example a test version next to the live one.
- Log-structured merge trees. A log-structured merge tree also puts all changes in a small structure, keeps Bloom filters on its sorted runs, and merges in the background. It has many levels and merges continually, where a differential file has one level and reorganizes in a batch.
- Delta stores in column stores. A read-optimized main store with a small write-optimized delta store and a periodic merge follows the same plan.
When to use it
Use a differential file when the data is large, the rate of change is small, and backup or recovery of the whole data is costly. The main file stays read-only, so it can be dumped once and kept in compressed or read-optimized form. It does not help when most records change between two reorganizations: then grows as large as , and every lookup passes the filter. A buffer of changes with no filter costs a read of on every lookup; the filter is what makes reads of unchanged keys cheap.
Pitfalls
- Delete without a marker. If delete only removed the key from , a deleted record of would come back at the next lookup. A delete needs a marker in and filter bits.
- Clearing filter bits. A plain Bloom filter cannot remove a key, because a bit may belong to several keys. Clear the whole filter only when is emptied at a reorganization.
- A filter that is too small. As grows past the design size, tends to 1 and each lookup reads . Size for the largest before a reorganization, or reorganize earlier.
- Losing the old generation too early. Keep the old main file and its dump until the new main file is dumped. Otherwise a failure during the reorganization leaves no valid copy.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-file/. The authors are listed in prov/PBST4C.jsonl.
"""A differential file in the style of Severance and Lohman (1976).
The main file M is read-only between reorganizations. Every insert, change
and delete goes to the differential file D, newest entry per key, with a
delete marker for a delete. A Bloom filter F over the keys in D lets a lookup
of an unchanged key go to M without a read of D. A reorganization merges D
into a new generation of M and dumps it to the archive.
The counters count the simulated file reads, so a test can compare the reads
with the false positive rate of the filter.
"""
import hashlib
DELETED = object() # the delete marker in D
class DifferentialFile:
def __init__(self, main: dict, m: int = 256, k: int = 3):
self.main = dict(sorted(main.items())) # read-only generation of the main file
self.diff: dict = {} # key -> value or DELETED
self.m, self.k = m, k
self.bits = 0 # the filter F as an integer of m bits
self.archive = [dict(self.main)] # dumps of each generation of M
self.main_reads = self.diff_reads = self.false_positives = 0
def _positions(self, key) -> list[int]:
h = hashlib.blake2b(repr(key).encode(), digest_size=16).digest()
h1, h2 = int.from_bytes(h[:8], "big"), int.from_bytes(h[8:], "big") | 1
return [(h1 + i * h2) % self.m for i in range(self.k)]
def maybe_changed(self, key) -> bool:
return all(self.bits >> p & 1 for p in self._positions(key))
def lookup(self, key):
"""The value of key, or None if the key is absent."""
if self.maybe_changed(key): # @line L1
self.diff_reads += 1
if key in self.diff: # @line L2
v = self.diff[key] # @line L2
return None if v is DELETED else v # @line L2
self.false_positives += 1
self.main_reads += 1
return self.main.get(key) # @line L3
def put(self, key, value) -> None:
"""Insert or change a record."""
self.diff[key] = value # @line L4
for p in self._positions(key):
self.bits |= 1 << p # @line L5
def delete(self, key) -> None:
self.diff[key] = DELETED # @line L4
for p in self._positions(key):
self.bits |= 1 << p # @line L5
def scan(self) -> list:
"""All records in key order: the merge of M and D."""
out = dict(self.main)
for key, v in self.diff.items():
if v is DELETED:
out.pop(key, None)
else:
out[key] = v
return sorted(out.items())
def reorganize(self) -> None:
new_main = dict(self.scan()) # @line L6
self.archive.append(dict(new_main)) # @line L7
self.main = new_main # @line L7
self.diff, self.bits = {}, 0 # @line L8
def restore_main(self) -> None:
"""Recover from the loss of M: copy the dump of the current generation."""
self.main = dict(self.archive[-1])
test_differential_file.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-file/. The authors are listed in prov/PBST4C.jsonl.
"""The differential file against a flat dict that holds the same relation."""
import math
import random
from differential_file import DifferentialFile
def initial(rng: random.Random, n: int = 150) -> dict:
return {k: rng.randint(0, 9) for k in rng.sample(range(200), n)}
def test_random_operations_match_the_flat_relation() -> None:
for seed in range(5):
rng = random.Random(seed)
flat = initial(rng)
df = DifferentialFile(flat, m=128, k=3)
for step in range(600):
r = rng.random()
key = rng.randrange(220)
if r < 0.3:
v = rng.randint(0, 9)
df.put(key, v)
flat[key] = v
elif r < 0.4:
df.delete(key)
flat.pop(key, None)
elif r < 0.42:
generation = dict(df.main)
df.reorganize()
assert df.main == flat and not df.diff and df.bits == 0
assert generation == df.archive[-2]
else:
assert df.lookup(key) == flat.get(key)
if step % 50 == 0:
assert df.scan() == sorted(flat.items())
def test_main_file_is_read_only_between_reorganizations() -> None:
rng = random.Random(7)
flat = initial(rng)
df = DifferentialFile(flat)
before = dict(df.main)
for _ in range(100):
df.put(rng.randrange(200), rng.randint(0, 9))
df.delete(rng.randrange(200))
assert df.main == before == df.archive[-1]
def test_no_false_negatives() -> None:
rng = random.Random(3)
df = DifferentialFile({}, m=64, k=2)
for key in rng.sample(range(10_000), 60):
df.put(key, 1)
assert all(df.maybe_changed(key) for key in df.diff)
def test_false_positive_rate_near_the_formula() -> None:
rng = random.Random(11)
m, k, n = 1024, 4, 150
keys = rng.sample(range(100_000), n + 2000)
df = DifferentialFile({key: 0 for key in keys[n:]}, m=m, k=k)
for key in keys[:n]:
df.put(key, 1)
for key in keys[n:]:
assert df.lookup(key) == 0
rate = df.false_positives / 2000
expected = (1 - math.exp(-k * n / m)) ** k
assert abs(rate - expected) < 0.02
# each lookup of an unchanged key reads M once and D only on a false positive
assert df.main_reads == 2000 and df.diff_reads == df.false_positives
def test_restore_main_after_its_loss() -> None:
rng = random.Random(5)
flat = initial(rng)
df = DifferentialFile(flat)
for _ in range(40):
df.put(rng.randrange(200), rng.randint(0, 9))
df.reorganize()
for _ in range(40):
key = rng.randrange(200)
df.delete(key)
expect = df.scan()
df.main = {} # the disk that held M fails
df.restore_main()
assert df.scan() == expect
def test_hand_example() -> None:
df = DifferentialFile({1: "a", 2: "b", 3: "c"}, m=32, k=2)
df.put(2, "B")
df.delete(3)
df.put(4, "d")
assert [df.lookup(x) for x in (1, 2, 3, 4, 5)] == ["a", "B", None, "d", None]
assert df.scan() == [(1, "a"), (2, "B"), (4, "d")]
df.reorganize()
assert df.main == {1: "a", 2: "B", 4: "d"}
History
Severance and Lohman described differential files in ACM Transactions on Database Systems in 1976, with a search filter of the kind that Bloom had proposed in 1970 for hash coding with allowable errors. Gremillion (1982) studied the design of that filter, and Aghili and Severance (1982) gave a guide to the design of differential files for the recovery of on-line databases. The plan of a read-only main structure, a small structure of changes and a batch merge returns in log-structured merge trees and in the delta stores of column stores.
References
- Dennis G. Severance and Guy M. Lohman, Differential files, their application to the maintenance of large databases, ACM Transactions on Database Systems 1(3), 1976, pages 256 to 267, the differential file organization and its use for backup and recovery, the section on the search filter, and Section 2.6, Designing a Bloom filter
- Lee L. Gremillion, Designing a Bloom filter for differential file access, Communications of the ACM 25(9), 1982, pages 600 to 604, the choice of the filter size and the number of hash functions for a differential file, paper level
- Houtan Aghili and Dennis G. Severance, A practical guide to the design of differential files for recovery of on-line databases, ACM Transactions on Database Systems 7(4), 1982, pages 540 to 565, the design of differential files for recovery, paper level
- Burton H. Bloom, Space/time trade-offs in hash coding with allowable errors, Communications of the ACM 13(7), 1970, pages 422 to 426, the hash-coded filter with allowable errors, paper level
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PBST4C Edit this page History Report an error Markdown