An e-Discovery platform rests on three verifiable promises
When a lawsuit involves millions of emails and files, the party that has to produce the documents cannot read them all, but must be able to show three things: that nothing was altered after collection, that duplicates were handled consistently, and that the automatic selection did not leave out too much of what was relevant. The rest of a platform (message queues, storage, search engine) exists to make these three promises measurable. This article shows how, with three listings that were actually run.
A caveat before starting. Discovery is an institution of civil procedure in common-law countries, especially the United States: the rules I cite (the Federal Rules of Civil Procedure and of Evidence) are American. Italian procedure has different instruments, and a system built for Italy starts from those, not from these rules. The technical parts (integrity, deduplication, recall estimation) hold anywhere electronic documents must be produced in a defensible way, and what you read here is not legal advice.
The architecture in six steps, and what each must guarantee
The scheme below is a teaching simplification, not the official EDRM model: the cycle of a discovery is usually described in more phases, and the real order depends on the case. What stays constant is that every step transforms the documents and must leave a trace.
- Collection: copy of the file from the source, with a SHA-256 fingerprint computed immediately.
- Preservation: archive of the original files, append-only, separate from the derivatives.
- Processing: extraction of text and metadata, and deduplication.
- Review: lawyers classify; a model ranks the documents by priority.
- Control: you estimate how much of what is relevant was left out.
- Production: numbering and delivery in the format agreed with the other side.
The criterion that holds the list together is reversibility: the original is never touched, every derivative (text, thumbnail, redacted version) is regenerated from it, and every step writes an event in the custody register. If you swap collection and processing, you compute fingerprints on files that have already been converted and can no longer show that they are those of the source. On the technical side it is usually built with a message queue between the steps, an object storage for the originals, a relational database for metadata and custody, and a full-text search engine; the choice of products matters less than the guarantees, and the size of the case decides whether you need a queue or a database is enough.
Promise 1: the chain of custody cannot be rewritten without it showing
An "immutable" register must be built on two levels. The first prevents modification: here with two triggers
that reject UPDATE and DELETE. The second makes it visible when the first is bypassed:
every event contains the hash of the previous event, so changing a row breaks the chain from that point on. The
listing uses SQLite (Python standard library) so that it can be run; the principle carries over to PostgreSQL
with a BEFORE UPDATE OR DELETE trigger that raises an exception, as the
PL/pgSQL trigger examples show.
I did not run the PostgreSQL version.
import hashlib
import json
import sqlite3
from datetime import datetime, timezone
def sha256_file(percorso: str) -> str:
h = hashlib.sha256()
with open(percorso, "rb") as f:
for blocco in iter(lambda: f.read(65536), b""):
h.update(blocco)
return h.hexdigest()
def crea_registro() -> sqlite3.Connection:
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE custodia (
n INTEGER PRIMARY KEY AUTOINCREMENT,
doc_id TEXT NOT NULL, evento TEXT NOT NULL, quando TEXT NOT NULL,
sha256 TEXT NOT NULL, hash_precedente TEXT NOT NULL, hash_evento TEXT NOT NULL);
CREATE TRIGGER custodia_no_update BEFORE UPDATE ON custodia
BEGIN SELECT RAISE(ABORT, 'custody register: modification forbidden'); END;
CREATE TRIGGER custodia_no_delete BEFORE DELETE ON custodia
BEGIN SELECT RAISE(ABORT, 'custody register: deletion forbidden'); END;
""")
return db
def registra(db, doc_id: str, evento: str, sha256: str, quando: str) -> None:
ultimo = db.execute("SELECT hash_evento FROM custodia ORDER BY n DESC LIMIT 1").fetchone()
precedente = ultimo[0] if ultimo else "0" * 64
corpo = json.dumps([doc_id, evento, quando, sha256, precedente])
hash_evento = hashlib.sha256(corpo.encode()).hexdigest()
db.execute("INSERT INTO custodia (doc_id, evento, quando, sha256, hash_precedente, hash_evento)"
" VALUES (?,?,?,?,?,?)", (doc_id, evento, quando, sha256, precedente, hash_evento))
def verifica(db) -> int | None:
"""Returns the number of the first inconsistent event, or None if the chain holds."""
precedente = "0" * 64
for n, doc_id, evento, quando, sha, prec, h in db.execute("SELECT * FROM custodia ORDER BY n"):
atteso = hashlib.sha256(json.dumps([doc_id, evento, quando, sha, precedente]).encode()).hexdigest()
if prec != precedente or h != atteso:
return n
precedente = h
return None
if __name__ == "__main__":
db = crea_registro()
ora = datetime(2026, 11, 12, 9, 0, tzinfo=timezone.utc).isoformat()
sha = hashlib.sha256(b"document content").hexdigest()
for evento in ("COLLECTION", "PROCESSING", "REVIEW"):
registra(db, "doc-001", evento, sha, ora)
print("chain intact:", verifica(db) is None)
try:
db.execute("UPDATE custodia SET evento = 'DELETED' WHERE n = 2")
except sqlite3.DatabaseError as errore:
print("UPDATE rejected:", errore)
# whoever has access to the database file can still bypass the triggers: the hash chain reveals it
db.execute("DROP TRIGGER custodia_no_update")
db.execute("UPDATE custodia SET evento = 'DELETED' WHERE n = 2")
print("first inconsistent event:", verifica(db))
# Output (run):
# chain intact: True
# UPDATE rejected: custody register: modification forbidden
# first inconsistent event: 2
In the output the first UPDATE is rejected by the trigger. Then the listing does what someone with
access to the database file would do: it removes the trigger and modifies event 2. The register no longer
prevents it, but verify (the verifica function) discovers it, because the hash of
event 2 no longer matches its content. The honest limit: whoever can rewrite all the following events,
recomputing the hashes, produces a consistent chain. To close the gap you periodically publish the last hash
outside the system (a timestamp, a copy held by a third party) and the check compares against it. The original
file is verified separately, by comparing sha256_file with the fingerprint recorded at collection.
Promise 2: deduplicating consistently, knowing where it goes wrong
Exact duplicates are recognised by the SHA-256 fingerprint: same content, same fingerprint. Near-duplicates (the same email with an extra signature, the draft and the final version) require a similarity measure. You get it with shingles, sequences of three consecutive words, and the Jaccard index between the two sets: common elements divided by total elements. Computing it on millions of pairs is too expensive, so you use MinHash, which summarises each set in a signature of 128 numbers and estimates the Jaccard from the fraction of equal positions; libraries such as datasketch add the LSH index to search without comparing everything with everything. The listing implements MinHash with the standard library alone, to show the numbers. The sample emails are in Italian (an order confirmation, the same email with a signature added, and an unrelated message): the texts are data of the experiment and the numbers do not depend on the language.
import hashlib
import re
def shingles(testo: str, k: int = 3) -> set[str]:
parole = re.findall(r"\w+", testo.lower())
return {" ".join(parole[i:i + k]) for i in range(len(parole) - k + 1)}
def jaccard(a: set, b: set) -> float:
return len(a & b) / len(a | b)
def minhash(insieme: set[str], n_perm: int = 128) -> list[int]:
"""For each 'permutation' (a different seed) keeps the minimum hash value."""
firma = []
for seme in range(n_perm):
firma.append(min(
int.from_bytes(hashlib.blake2b(s.encode(), digest_size=8, salt=seme.to_bytes(8, "big")).digest(), "big")
for s in insieme))
return firma
def stima_jaccard(f1: list[int], f2: list[int]) -> float:
return sum(x == y for x, y in zip(f1, f2)) / len(f1)
if __name__ == "__main__":
originale = ("Si conferma che la consegna dei prodotti avverrà entro il quindici marzo presso il magazzino "
"del cliente di Lecce. Restano valide le condizioni concordate nella riunione del dieci febbraio "
"e il pagamento sarà effettuato a trenta giorni dalla fattura. Cordiali saluti.")
con_firma = originale + " Mario Rossi - Responsabile acquisti - Via Roma 1 - tel. 0832 000000"
altra = "Allego il verbale della riunione di ieri con l'elenco delle azioni da completare entro fine mese."
print("SHA-256 equal (original, with signature):",
hashlib.sha256(originale.encode()).digest() == hashlib.sha256(con_firma.encode()).digest())
for nome, testo in (("with signature", con_firma), ("other email", altra)):
a, b = shingles(originale), shingles(testo)
esatto = jaccard(a, b)
stima = stima_jaccard(minhash(a), minhash(b))
print(f"{nome:<14} exact Jaccard = {esatto:.3f} MinHash estimate (128 permutations) = {stima:.3f}")
# Output (run):
# SHA-256 equal (original, with signature): False
# with signature exact Jaccard = 0.796 MinHash estimate (128 permutations) = 0.828
# other email exact Jaccard = 0.000 MinHash estimate (128 permutations) = 0.000
The result contains the lesson. The email with an added signature has a SHA-256 fingerprint different from the original, so for exact deduplication it is a new document. Its exact Jaccard is 0.796 and the MinHash estimate 0.828: the estimate is close but not identical, because with 128 permutations the error is of the order of a few hundredths. And above all, with a threshold of 0.85 this pair would not be flagged: a one-line signature on a short message is enough to fall below it. The threshold is chosen by looking at real pairs from your own corpus, and you also decide what to do with the grey zone (send it to a reviewer, not discard it). The Jaccard of 0.000 with the other email shows the opposite case: not a single three-word sequence in common.
The text extraction that precedes this step is usually done with
Apache Tika, which extracts text
and metadata from over a thousand file types with a single interface; in server mode you send the file with a
PUT request (to the /tika endpoint for the text, /meta for the metadata),
as described in the TikaServer page.
I did not run the code that calls Tika: it requires the server to be running. One thing not to forget: if the
extracted text is empty, the document is probably a scan and goes to the OCR described in the
previous article.
Promise 3: estimating how much was left out, with the uncertainty
Assisted review ranks documents by probability of relevance, and you stop when new relevant documents become rare. At that point you need an estimate of recall: the fraction of relevant documents you actually found. A direct way is the elusion test: you draw a random sample from the discarded documents, review it by hand and estimate how many relevant ones were left in. The listing simulates a case where the true value is known (1,700 found out of 2,000 relevant, recall 0.85) and repeats the experiment 1,000 times for three sample sizes.
import random
def stima_richiamo(trovati: int, scartati: int, campione_scartati: list[bool]) -> tuple[float, float]:
"""Elusion test: a random sample of the DISCARDED documents is reviewed and used to
estimate how many relevant ones are left in. Returns (recall, estimated missing relevant)."""
tasso = sum(campione_scartati) / len(campione_scartati)
mancanti = tasso * scartati
return trovati / (trovati + mancanti), mancanti
if __name__ == "__main__":
rng = random.Random(7)
# Simulated collection: 100,000 documents, 2,000 relevant. Review found 1,700
# out of 12,000 reviewed; 300 relevant ones stayed among the 88,000 discarded.
totale, rilevanti, trovati, mancanti_veri = 100_000, 2_000, 1_700, 300
scartati = totale - 12_000
p = mancanti_veri / scartati
print(f"true value: recall = {trovati / rilevanti:.2f}")
for dimensione in (400, 1_500, 5_000):
stime = []
for _ in range(1_000): # 1,000 repetitions of the same experiment
campione = [rng.random() < p for _ in range(dimensione)]
stime.append(stima_richiamo(trovati, scartati, campione)[0])
stime.sort()
print(f"sample of {dimensione:>5}: estimated recall between {stime[50]:.2f} and {stime[950]:.2f} "
f"(5%-95% over 1,000 repetitions)")
# Output (run):
# true value: recall = 0.85
# sample of 400: estimated recall between 0.66 and 1.00 (5%-95% over 1,000 repetitions)
# sample of 1500: estimated recall between 0.76 and 0.94 (5%-95% over 1,000 repetitions)
# sample of 5000: estimated recall between 0.80 and 0.90 (5%-95% over 1,000 repetitions)
The output says that a sample of 400 documents produces an estimate ranging from 0.66 to 1.00, that is, almost unusable: the relevant documents left over are only 0.34% of the discarded ones, so in 400 you see very few of them and the estimate swings. With 5,000 the interval narrows to 0.80-0.90. The practical rule is that the sample for an elusion test is sized on the rarity of what you are looking for, not on the number of documents, and that recall must always be reported with its interval. The figures are simulations that can be reproduced from the listing (seed fixed at 7): they do not measure any real case or any platform.
A note on using a model for the ranking: a classifier trained on the reviewers' decisions (for example with sentence embeddings and logistic regression) is a reasonable choice, but I did not run it because it requires libraries that are not present here. The point to defend before a judge is not the model, it is the protocol: how the sample was chosen, how many documents were reviewed, what recall was estimated and with what interval.
What not to delegate to the system
Some points remain with people, even with the best platform. The preservation of data once a proceeding is foreseeable: the American rule on failure to preserve electronically stored information (FRCP 37(e)) provides that the judge may take measures if information that should have been preserved was lost for lack of reasonable steps and cannot be recovered. The inadvertent production of privileged documents: Federal Rule of Evidence 502(d) allows a federal court to order that disclosure does not amount to a waiver of the privilege. And the transfer of personal data from the EU to the United States, for which the European Commission adopted in July 2023 an adequacy decision for companies that adhere to the Data Privacy Framework: if the receiving company does not adhere, other legal bases apply.
- Deciding when the duty to preserve begins, and ordering the hold on the data.
- Establishing what is covered by professional privilege and must be removed from the production.
- Assessing the legal basis for the cross-border transfer of personal data.
- Approving and documenting the assisted-review protocol.
These are four legal decisions that software can support but not take: the platform must record who took them, when and on what grounds. The processing of personal data in systems of this kind is taken up again in the article on GDPR and privacy by design, while the automatic checking of regulatory rules is the subject of compliance automation.
What you can do now
You can build a custody register that rejects modifications and reveals the ones that bypass it, you know why a one-line signature can let a near-duplicate slip past a 0.85 threshold, and you can estimate recall with a sample sized on rarity, reporting the interval instead of a single number. You also know which decisions stay human. For searching the corpus built here, continue with the search engine with embeddings.
Frequently asked questions
What is e-Discovery?
It is the process by which the parties to a proceeding identify, preserve, process, review and produce electronic documents as evidence. It is an institution of common-law systems, especially the United States; the Italian legal system has instruments of its own.
Why is the SHA-256 hash not enough to find duplicates?
Because it identifies only files that are identical byte for byte: a signature added to an email changes the fingerprint. For near-duplicates you use a similarity measure such as the Jaccard index on shingles, estimated with MinHash, with a threshold chosen on real pairs.
How do you estimate the recall of assisted review?
By reviewing by hand a random sample of the discarded documents and estimating how many relevant ones were left in. When relevant documents are rare a large sample is needed, and the result must be reported with an interval, not as a single number.
Sources
- Federal Rules of Civil Procedure, Rule 37 (Legal Information Institute, Cornell) - the text of subdivision (e) on failure to preserve electronically stored information, consulted on 2026-11-12
- Federal Rules of Evidence, Rule 502 (Legal Information Institute, Cornell) - subdivision (d) on the court order that excludes waiver of privilege, consulted on 2026-11-12
- European Commission: EU-US data transfers - the adequacy decision on the Data Privacy Framework of July 2023, consulted on 2026-11-12
- Apache Tika - extraction of text and metadata from over a thousand file types, consulted on 2026-11-12
- Apache Tika wiki: TikaServer - the
/tikaand/metaendpoints with a PUT request, consulted on 2026-11-12 - datasketch: MinHash LSH - the role of the LSH index in searching by Jaccard threshold, consulted on 2026-11-12
- PostgreSQL 16: Trigger Functions - a trigger that raises an exception to prevent an operation, consulted on 2026-11-12
- SQLite: CREATE TRIGGER - the RAISE function used by the custody register that was run, consulted on 2026-11-12
The three listings were run with Python 3 and the standard library only: the outputs are the real ones and the third is a simulation with a fixed seed. The edrm.net site was not reachable from the machine used for writing, so the cycle of phases described here is declared a simplification and not a citation of the EDRM model. The American rules are cited from the text published by the Legal Information Institute of Cornell Law School, not from the site of a federal authority. Nothing here is legal advice.
Commenti
Caricamento commenti...
Sign in to comment