Algorithm Search⌘K

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
Properties
not concurrentexternalnot persistent

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 MM: 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 DD: one entry per changed key, the newest one. An entry is a new record or a delete marker. A real system keeps DD as an append-only file with an index on its keys; the code keeps a dict.
  • The filter FF: a Bloom filter of mm bits with kk hash functions h1,…,hkh_1, \dots, h_k over the keys in DD, in main memory.
  • The archive: a dump of each generation of MM, made at the reorganization that writes it.

Operations

  1. LOOKUP(key)
  2. 1if the bits h_1(key), ..., h_k(key) of F are all 1 then
  3. 2if D has an entry for key then return its record, or absent for a delete marker
  4. 3return the record of key in M, or absent
  5. PUT(key, entry) ▷ entry is a record or the delete marker
  6. 4D[key] ← entry
  7. 5set the bits h_1(key), ..., h_k(key) of F to 1
  8. REORGANIZE()
  9. 6M' ← the merge of M and D in key order: an entry of D replaces the record of M, and a delete marker drops it
  10. 7dump M' to the archive; make M' the main file
  11. 8D ← empty; F ← all zeros

A lookup of an unchanged key whose filter bits are not all set reads only MM (line L3). A lookup whose bits are all set reads DD; if DD has no entry, this was a false positive and the lookup goes on to MM. A put or a delete writes only DD and the filter. A scan merges MM and DD in key order, as line L6 does.

Backup and recovery. Between two reorganizations only DD changes. A backup is then a dump of DD only, and the dump of MM in the archive stays valid. If the disk that holds MM fails, copy MM from the archive. If DD 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 DD, not with the size of the database. The analysis of how large DD may grow before a reorganization is in Aghili and Severance (1982).

Example

Main file MM: keys 1, 2 and 3 with records a, b and c. The filter has m=16m = 16 bits and k=2k = 2 hash functions; for the hand example take h1(x)=x mod 16h_1(x) = x \bmod 16 and h2(x)=(5x+3) mod 16h_2(x) = (5x + 3) \bmod 16 (the code uses a cryptographic hash instead).

  1. put(2, B): D={2↦B}D = \{2 \mapsto B\}, set bits 2 and 13.
  2. delete(3): DD gets a delete marker for 3, set bits 3 and 2.
  3. put(4, d): DD gets 4↦d4 \mapsto d, 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 MM a
2 2 and 13: both 1 DD B
3 3 and 2: both 1 DD absent (delete marker)
5 5 and 12: bit 5 is 0 MM absent
18 2 and 13: both 1 DD, then MM absent (a false positive)

reorganize() writes M′={1↦a,2↦B,4↦d}M' = \{1 \mapsto a, 2 \mapsto B, 4 \mapsto d\}, dumps it, and clears DD and the filter.

Correctness

Define the relation that the structure holds as R(M,D)R(M, D): the records of MM whose key has no entry in DD, plus the records of DD. A delete marker in DD removes its key.

Claim. If the structure holds R(M,D)R(M, D) = 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 RR.

Proof. A Bloom filter has no false negatives: line L5 sets every bit of each key in DD, and only line L8 clears bits, at the same time as it empties DD. So when DD has an entry for the key, line L1 is true and line L2 returns the entry; when DD has none, lookup reaches line L3 either directly or after a false positive, and returns the record of MM. That is the definition of R(M,D)R(M, D). Line L4 keeps only the newest entry for a key, which is the effect of the newest put or delete. Line L6 computes R(M,D)R(M, D) itself, so after line L8, R(M′,∅)=R(M,D)R(M', \emptyset) = R(M, D). □\square

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 MM (a map from keys to records), a differential file DD (a map from keys to records or a delete marker ⊥\bot), a filter FF of mm bits with hash functions h1,…,hkh_1, \dots, h_k, and an archive (a list of maps). The relation it represents is

R(M,D)={(x,r):D(x)=r≠⊥}∪{(x,r):M(x)=r, x∉dom(D)}.R(M, D) = \{(x, r) : D(x) = r \ne \bot\} \cup \{(x, r) : M(x) = r,\ x \notin \mathrm{dom}(D)\}.

The abstract relation SS starts as M0M_0, put(x,r)(x, r) sets S(x)=rS(x) = r, and delete(x)(x) removes xx from SS.

Invariants. After every operation:

  1. (I1) R(M,D)=SR(M, D) = S.
  2. (I2) For every key x∈dom(D)x \in \mathrm{dom}(D), the bits h1(x),…,hk(x)h_1(x), \dots, h_k(x) of FF are 1.
  3. (I3) MM 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 DD is empty, FF is all zeros, M=M0=SM = M_0 = S and the archive holds a copy of M0M_0, so all three hold.

put(x,r)(x, r) sets D(x)=rD(x) = r (line L4). For xx the new RR gives rr, for every other key nothing changes, and SS changes the same way, so I1 holds. Line L5 sets the bits of xx and clears none, so I2 holds. MM and the archive do not change, so I3 holds. delete(x)(x) is the same with D(x)=⊥D(x) = \bot: the new RR has no record for xx, as SS.

reorganize sets M′=R(M,D)M' = R(M, D) (line L6), appends a copy of M′M' to the archive and makes it the main file (line L7), and then empties DD and clears FF (line L8). Now R(M′,∅)=M′=R(M,D)=SR(M', \emptyset) = M' = R(M, D) = S, which is I1. I2 holds because DD is empty, and I3 by line L7. □\square

Lemma 2. lookup(x)(x) returns S(x)S(x), or absent if x∉dom(S)x \notin \mathrm{dom}(S).

Proof. If x∈dom(D)x \in \mathrm{dom}(D), then by I2 the test of line L1 is true, and line L2 returns D(x)D(x), or absent when D(x)=⊥D(x) = \bot. That is R(M,D)(x)R(M, D)(x). If x∉dom(D)x \notin \mathrm{dom}(D), then line L2 does not return, whatever the filter says, and line L3 returns M(x)M(x) or absent, which again is R(M,D)(x)R(M, D)(x). By I1 this is S(x)S(x). □\square

Lemma 3. scan returns the records of SS in key order, and between two reorganizations MM does not change.

Proof. scan computes R(M,D)R(M, D) in key order, which is SS by I1. Only line L7 assigns MM. □\square

Recovery. If MM 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 DD. □\square

The filter enters only in Lemma 2, and only through I2. A false positive (line L1 true for a key not in DD) changes the reads that a lookup makes, never its answer.

Complexity

Costs are in record reads of MM and DD and in in-memory bit probes.

  • lookup: kk bit probes. For a key that has an entry in DD, one read of DD. For an unchanged key, one read of MM, plus one read of DD with the probability pp of a false positive.
  • put and delete: one write to DD and kk bit sets. MM is not written.
  • reorganize: one pass over MM and DD and one write of M′M', O(N+n)O(N + n) records if DD is kept in key order, plus the dump of M′M'.
  • Space: mm bits of memory for the filter, and nn entries in DD.

False positive rate (theorem, in an idealized model). If the kk hash values of each key are independent and uniform over the mm bits, the probability that a key not in DD passes the filter after nn entries is about p≈(1−e−kn/m)kp \approx (1 - e^{-kn/m})^k, the standard Bloom filter bound. It is smallest near k=(m/n)ln⁡2k = (m/n) \ln 2. With m=10nm = 10 n and k=7k = 7, pp is under 1 percent, so unchanged keys almost never cost a read of DD. 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 DD grows as large as MM, and every lookup passes the filter. A buffer of changes with no filter costs a read of DD 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 DD, a deleted record of MM would come back at the next lookup. A delete needs a marker in DD 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 DD is emptied at a reorganization.
  • A filter that is too small. As nn grows past the design size, pp tends to 1 and each lookup reads DD. Size mm for the largest DD 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.

differential_file.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/PBST4C/text.yaml