Content-Identical File Grouping with Staged I/O
Hard · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Given an inventory files where each item is a dictionary {"path": str, "content": str}, identify every set of two or more paths whose files contain the exact same sequence of UTF-8 bytes.
Return all duplicate groups as a List[List[str]] subject to these rules:
- Include a group only when at least two distinct paths share identical byte contents; omit any file whose byte sequence is unique.
- Two or more
0-byte ("") files are byte-identical to one another and form a valid duplicate group. - Sort the paths inside every group in ascending lexicographical order, and sort the outer list of groups in ascending lexicographical order as well.
- Treat the file collection as read-only — never mutate or delete entries.
Although the test harness passes files in memory, structure your implementation around bounded, staged filesystem I/O suitable for multi-gigabyte files on disk:
- Use cheap metadata (byte length) and small leading-byte reads first to eliminate files that cannot match without reading their full contents.
- Process large surviving candidates via fixed-size chunked streaming rather than loading whole files into RAM as dictionary keys.
- Separate probabilistic filtering (such as a streaming cryptographic digest) from exact chunk-by-chunk byte verification so hash collisions can never produce false duplicates.
Implement find_duplicate_files(files: List[Dict[str, str]]) -> List[List[str]].
Examples
Example 1
Input:
files = [
{"path": "logs/app.log", "content": " timeout\n"},
{"path": "backup/app.log", "content": " timeout\n"},
{"path": "logs/auth.log", "content": "denied!!\n"},
]
Output: [["backup/app.log", "logs/app.log"]]
All three files are 9 bytes long, so byte length alone keeps all three as candidates, but inspecting their bytes eliminates "logs/auth.log" and groups "backup/app.log" with "logs/app.log" in sorted order.
Example 2
Input:
files = [
{"path": "tmp/blank_b.dat", "content": ""},
{"path": "tmp/readme.md", "content": "ok"},
{"path": "tmp/blank_a.dat", "content": ""},
]
Output: [["tmp/blank_a.dat", "tmp/blank_b.dat"]]
"tmp/readme.md" is the only 2-byte file and is skipped without content comparison, whereas the two 0-byte files match and are returned alphabetically.
Example 3
Input:
files = [
{"path": "srv/n3.cfg", "content": "port=8080"},
{"path": "srv/n1.cfg", "content": "port=8080"},
{"path": "srv/db.cfg", "content": "host=db01;port=5432"},
{"path": "srv/n2.cfg", "content": "port=8080"},
{"path": "etc/db.cfg", "content": "host=db01;port=5432"},
]
Output: [["etc/db.cfg", "srv/db.cfg"], ["srv/n1.cfg", "srv/n2.cfg", "srv/n3.cfg"]]
Both 19-byte database configs match each other and all three 9-byte node configs match each other; paths inside each group and the groups themselves are returned in ascending order.
Constraints
0 <= len(files) <= 10,000- Each element of
filescontains keys"path"(str) and"content"(str), and all"path"values are distinct. - Content equality is strict byte-for-byte equality on UTF-8 bytes (
content.encode("utf-8")). - Per-stream read buffers must use
O(1)bounded chunk sizes rather than reading arbitrarily large files in a single unbounded slice.
Step-by-step walkthrough
Understand the input, output, and the real-world disk constraint
The judge gives us
files, a list of{"path": str, "content": str}dictionaries, and expects a list of duplicate groups (List[List[str]]) where every group contains at least two paths whose byte contents are completely identical:- Paths inside each group (and the groups themselves) are sorted alphabetically (Example 3 turns
srv/n3.cfg, srv/n1.cfg, srv/n2.cfginto['srv/n1.cfg', 'srv/n2.cfg', 'srv/n3.cfg']). - Unique files are excluded, and empty files (
"") that match each other DO form a duplicate group (Example 2). - Nothing is modified or deleted.
Although the judge passes strings in memory, the engineering problem is about efficient filesystem I/O: on a real disk, files can be many gigabytes long and disk reads are orders of magnitude slower than CPU work. Our code therefore treats the encoded bytes map (
filesystem) strictly like a disk, touching files only through metadata size checks and fixed-size streaming reads.- Paths inside each group (and the groups themselves) are sorted alphabetically (Example 3 turns
Why reading whole files into a dictionary fails at scale
In a tiny script, you could map
file["content"] -> [paths]directly. On a real storage volume, that breaks down immediately:- Memory blowup: holding entire file contents as dictionary keys crashes RAM as soon as you hit a few multi-gigabyte video or dataset files.
- Wasted disk reads: reading every byte of a
10 GBfile is completely unnecessary if no other file on disk even has the same10 GBbyte length. - Quadratic pairwise reads: comparing every pair of files directly would re-read
Nfiles up toN * (N - 1) / 2times.
Design a four-stage filter funnel: cheap filters reject, bytes prove
The key principle is asymmetry between disproving and proving equality: a single difference in size, prefix, or hash proves two files are different, whereas matching on a summary only says "still a candidate."
We arrange checks into a four-stage funnel from cheapest to most expensive, discarding any singleton (
len == 1) bucket after every stage so unique files never advance to costlier reads:All N files | v Stage 1: File size (metadata only — 0 content bytes read) [size_groups: >= 2 files with identical byte length] | v Stage 2: First 4 KB prefix (1 tiny read per remaining file) +---> If file size <= 4 KB: prefix IS the whole file -> PROVEN DUPLICATES! | v Stage 3: Streaming SHA-256 digest in 64 KB chunks (1 full read, O(1) RAM) [digest_groups: >= 2 large files with identical 256-bit digest] | v Stage 4: Chunk-by-chunk byte comparison (eliminates theoretical hash collisions) Exact duplicate groups!Stage helpers: bounded chunk reads, metadata size, prefix, and streaming SHA-256
To guarantee bounded memory per open file,
_read_chunksyields slices of at mostCHUNK_SIZE(64 KB) bytes — mirroringf.read(CHUNK_SIZE)on a real file handle.Using
_read_chunks,_stream_sha256feeds a file's chunks one by one intohashlib.sha256(), hashing arbitrarily large files while holding only64 KBin memory. Similarly,_same_bytes_streamingcompares two files chunk by chunk in lockstep, usingitertools.zip_longest(..., fillvalue=None)so that if one stream ever ends earlier than the other,(None, b"...")compares unequal and returnsFalseright away.import hashlib from itertools import zip_longest CHUNK_SIZE = 64 * 1024 PREFIX_SIZE = 4 * 1024 def _read_chunks(data: bytes): """Simulate streaming disk reads of at most CHUNK_SIZE bytes at a time.""" for offset in range(0, len(data), CHUNK_SIZE): yield data[offset:offset + CHUNK_SIZE] def _get_size(data: bytes) -> int: # On a real filesystem this comes from `os.stat(path).st_size` with zero content reads. return len(data) def _read_prefix(data: bytes) -> bytes: # Read only the first PREFIX_SIZE bytes instead of the whole file. return data[:PREFIX_SIZE] def _stream_sha256(data: bytes) -> str: # Feed fixed-size chunks into SHA-256 so memory stays O(CHUNK_SIZE) for huge files. hasher = hashlib.sha256() for chunk in _read_chunks(data): hasher.update(chunk) return hasher.hexdigest() def _same_bytes_streaming(file_a: bytes, file_b: bytes) -> bool: """Compare two files chunk by chunk, stopping at the first differing chunk or EOF mismatch.""" for chunk_a, chunk_b in zip_longest(_read_chunks(file_a), _read_chunks(file_b), fillvalue=None): if chunk_a != chunk_b: return False return TrueGrouping candidates and verifying exact byte equality
Stages 1, 2, and 3 share the exact same bucketing pattern: compute a key for each candidate path, group matching keys in a dictionary, and keep only buckets with
len >= 2. Writing one_group_candidateshelper keeps all three stages clean.Stage 4 cannot rely on a hash key because its purpose is to verify actual bytes with zero collision risk. Because byte equality is transitive (if
C == AandB == A, thenC == B),_verify_exact_matchesmaintains equivalence classes and compares each incoming path only against the first representativemembers[0]of each class:def _group_candidates(paths: List[str], filesystem: Dict[str, bytes], key_fn) -> List[List[str]]: """Bucket `paths` by `key_fn(bytes)` and discard singleton buckets that cannot have duplicates.""" buckets = {} for path in paths: key = key_fn(filesystem[path]) if key not in buckets: buckets[key] = [] buckets[key].append(path) candidate_groups = [] for matching_paths in buckets.values(): if len(matching_paths) >= 2: candidate_groups.append(matching_paths) return candidate_groups def _verify_exact_matches(paths: List[str], filesystem: Dict[str, bytes]) -> List[List[str]]: """Partition digest-matching paths into true byte-identical equivalence classes of size >= 2.""" exact_classes = [] for path in paths: placed = False for members in exact_classes: representative_path = members[0] if _same_bytes_streaming(filesystem[representative_path], filesystem[path]): members.append(path) placed = True break if not placed: exact_classes.append([path]) verified_groups = [] for members in exact_classes: if len(members) >= 2: verified_groups.append(members) return verified_groupsAssemble the four-stage pipeline (and the small-file shortcut)
Now
find_duplicate_filesconnects Stages 1 through 4 sequentially without deep nesting. Notice the crucial shortcut in Stage 2: when a group's file size is<= PREFIX_SIZE(4 KB), reading the4 KBprefix already read every byte of those files! Equal size plus identical full bytes is already 100% proof of equality, so we emitsorted(prefix_group)immediately and skip Stages 3 and 4 for small files.def find_duplicate_files(files: List[Dict[str, str]]) -> List[List[str]]: # filesystem: simulated disk mapping file path -> raw UTF-8 byte content filesystem: Dict[str, bytes] = {} for entry in files: filesystem[entry["path"]] = entry["content"].encode("utf-8") all_paths = list(filesystem.keys()) duplicate_groups: List[List[str]] = [] # Stage 1 (Metadata filter): group by byte size; unique-size files are never read. size_groups = _group_candidates(all_paths, filesystem, _get_size) # Stage 2 (Prefix filter): within each size group, compare the first 4 KB. large_candidate_groups: List[List[str]] = [] for size_group in size_groups: prefix_groups = _group_candidates(size_group, filesystem, _read_prefix) for prefix_group in prefix_groups: if _get_size(filesystem[prefix_group[0]]) <= PREFIX_SIZE: duplicate_groups.append(sorted(prefix_group)) else: large_candidate_groups.append(prefix_group) # Stage 3 (Streaming digest filter): hash remaining large candidates in 64 KB chunks. digest_groups: List[List[str]] = [] for candidate_group in large_candidate_groups: digest_groups.extend(_group_candidates(candidate_group, filesystem, _stream_sha256)) # Stage 4 (Exact verification): confirm byte-for-byte equality with zero collision risk. for digest_group in digest_groups: for exact_group in _verify_exact_matches(digest_group, filesystem): duplicate_groups.append(sorted(exact_group)) duplicate_groups.sort() return duplicate_groupsTrace Example 1, Example 3, and large files through the funnel
Let's watch how candidates shrink at each stage:
Example 1: logs/app.log=" timeout\n" (9 B), backup/app.log=" timeout\n" (9 B), logs/auth.log="denied!!\n" (9 B) Stage 1 (size): {9: ['logs/app.log', 'backup/app.log', 'logs/auth.log']} -> all share size 9. Stage 2 (prefix): {b' timeout\n': ['logs/app.log', 'backup/app.log'], b'denied!!\n': ['logs/auth.log']} 'logs/auth.log' is dropped; size 9 <= 4096 -> emit ['backup/app.log', 'logs/app.log']! Example 3: srv/n3.cfg, srv/n1.cfg, srv/n2.cfg ("port=8080", 9 B); srv/db.cfg, etc/db.cfg ("host=db01;port=5432", 19 B) Stage 1 (size): {9: ['srv/n3.cfg', 'srv/n1.cfg', 'srv/n2.cfg'], 19: ['srv/db.cfg', 'etc/db.cfg']} Stage 2 (prefix): sizes 9 and 19 are both <= 4096 -> whole files already compared -> emit sorted [['etc/db.cfg', 'srv/db.cfg'], ['srv/n1.cfg', 'srv/n2.cfg', 'srv/n3.cfg']]! Large-file example: f1 (1 MB), f2 (1 MB, differs at byte 10), f3 (1 MB, differs at last byte), f4 (1 MB, copy of f1) Stage 1 (size): all four are 1 MB -> ['f1', 'f2', 'f3', 'f4'] Stage 2 (prefix): f2 differs in first 4 KB -> dropped after reading just 4 KB! ['f1', 'f3', 'f4'] advance to Stage 3. Stage 3 (SHA-256): f3 differs at last byte -> different digest -> dropped! ['f1', 'f4'] advance to Stage 4. Stage 4 (exact): f1 and f4 match chunk-by-chunk -> emit ['f1', 'f4'].Production filesystem considerations: concurrency, mutations, errors, and links
In a live operating system environment, four operational concerns round out the pipeline:
- Bounded concurrency and handles: run I/O through a small fixed worker pool so open file descriptors and total buffer memory (
<= 2 * workers * CHUNK_SIZE) stay strictly bounded, and always open files insidewithblocks so handles close on exceptions. Tune worker count to the storage medium: parallel readers can saturate an NVMe SSD or network store, whereas on a spinning HDD they cause disk-head thrashing and slow down throughput. - Files mutating mid-scan: record
(size, mtime_ns, ctime_ns, dev, inode)fromstat()before a file's first read and re-check after its final read (or read from an immutable filesystem snapshot / object version ID when available). If metadata changed across stages, quarantine the path under a"modified_during_scan"list (or retry once) rather than trusting a torn read. - Unreadable files vs non-duplicates: catch
OSError(PermissionError,FileNotFoundError) per file and recorderrors[path] = reasonseparately instead of crashing the scan or mislabeling unreadable files as "unique." - Symbolic and hard links: do not follow symlinks by default (prevents directory cycles and duplicate-counting link targets). Check
(st_dev, st_ino)for hard links: paths sharing the same device and inode point to the exact same physical bytes on disk and can either be collapsed as one physical file or grouped immediately with zero reads, per caller policy.
- Bounded concurrency and handles: run I/O through a small fixed worker pool so open file descriptors and total buffer memory (
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import hashlib from itertools import zip_longest # Maximum bytes read in a single I/O step; caps memory per open file. CHUNK_SIZE = 64 * 1024 # Bytes read in Stage 2 to cheaply separate same-size files that differ early. PREFIX_SIZE = 4 * 1024 def _read_chunks(data: bytes): """Simulate streaming disk reads of at most CHUNK_SIZE bytes at a time.""" for offset in range(0, len(data), CHUNK_SIZE): yield data[offset:offset + CHUNK_SIZE] def _get_size(data: bytes) -> int: # On a real filesystem this comes from `os.stat(path).st_size` with zero content reads. return len(data) def _read_prefix(data: bytes) -> bytes: # Read only the first PREFIX_SIZE bytes instead of the whole file. return data[:PREFIX_SIZE] def _stream_sha256(data: bytes) -> str: # Feed fixed-size chunks into SHA-256 so memory stays O(CHUNK_SIZE) for huge files. hasher = hashlib.sha256() for chunk in _read_chunks(data): hasher.update(chunk) return hasher.hexdigest() def _same_bytes_streaming(file_a: bytes, file_b: bytes) -> bool: """Compare two files chunk by chunk, stopping at the first differing chunk or EOF mismatch.""" # zip_longest with fillvalue=None ensures a length mismatch returns False # even if a file's size changed mid-scan instead of truncating at the shorter stream. for chunk_a, chunk_b in zip_longest(_read_chunks(file_a), _read_chunks(file_b), fillvalue=None): if chunk_a != chunk_b: return False return True def _group_candidates(paths: List[str], filesystem: Dict[str, bytes], key_fn) -> List[List[str]]: """Bucket `paths` by `key_fn(bytes)` and discard singleton buckets that cannot have duplicates.""" # buckets: maps stage key (int size, bytes prefix, or hex digest) -> list of matching paths buckets: Dict[Any, List[str]] = {} for path in paths: key = key_fn(filesystem[path]) if key not in buckets: buckets[key] = [] buckets[key].append(path) candidate_groups: List[List[str]] = [] for matching_paths in buckets.values(): if len(matching_paths) >= 2: candidate_groups.append(matching_paths) return candidate_groups def _verify_exact_matches(paths: List[str], filesystem: Dict[str, bytes]) -> List[List[str]]: """Partition digest-matching paths into true byte-identical equivalence classes of size >= 2.""" # exact_classes: list of groups, e.g. [['backup/app.log', 'logs/app.log']], where every member equals index 0 exact_classes: List[List[str]] = [] for path in paths: placed = False for members in exact_classes: representative_path = members[0] if _same_bytes_streaming(filesystem[representative_path], filesystem[path]): members.append(path) placed = True break if not placed: exact_classes.append([path]) verified_groups: List[List[str]] = [] for members in exact_classes: if len(members) >= 2: verified_groups.append(members) return verified_groups def find_duplicate_files(files: List[Dict[str, str]]) -> List[List[str]]: # filesystem: simulated disk mapping file path -> raw UTF-8 byte content filesystem: Dict[str, bytes] = {} for entry in files: filesystem[entry["path"]] = entry["content"].encode("utf-8") all_paths = list(filesystem.keys()) duplicate_groups: List[List[str]] = [] # Stage 1 (Metadata filter): group by byte size; unique-size files are never read. size_groups = _group_candidates(all_paths, filesystem, _get_size) # Stage 2 (Prefix filter): within each size group, compare the first 4 KB. large_candidate_groups: List[List[str]] = [] for size_group in size_groups: prefix_groups = _group_candidates(size_group, filesystem, _read_prefix) for prefix_group in prefix_groups: # If file size <= PREFIX_SIZE, the prefix read already inspected 100% of the bytes, # proving exact equality without needing a separate full-file hash or re-read. if _get_size(filesystem[prefix_group[0]]) <= PREFIX_SIZE: duplicate_groups.append(sorted(prefix_group)) else: large_candidate_groups.append(prefix_group) # Stage 3 (Streaming digest filter): hash remaining large candidates in 64 KB chunks. digest_groups: List[List[str]] = [] for candidate_group in large_candidate_groups: digest_groups.extend(_group_candidates(candidate_group, filesystem, _stream_sha256)) # Stage 4 (Exact verification): confirm byte-for-byte equality with zero collision risk. for digest_group in digest_groups: for exact_group in _verify_exact_matches(digest_group, filesystem): duplicate_groups.append(sorted(exact_group)) duplicate_groups.sort() return duplicate_groups✅ Submit now — all tests should pass.
Intuition & how it works
Imagine finding identical sealed binders in a huge warehouse without reading every page of every binder. First, you weigh each binder on a scale — any binder with a unique weight cannot possibly have a twin and is set aside unopened. For binders of the exact same weight, you peek at just the first page; only those with matching first pages get summarized with a cryptographic digest (a fixed-length mathematical fingerprint, such as SHA-256, computed over all bytes of a file), and finally any binders with matching fingerprints are compared page by page using streaming I/O (reading data in small fixed-size chunks rather than loading a whole file into memory at once) to guarantee 100% equality.
Naive approaches fail quickly on real disks: loading full file contents into a hash map (content -> paths) exhausts RAM as soon as files reach gigabytes, hashing every file up front wastes disk bandwidth on unique-size files, and comparing all file pairs directly takes O(N^2) full-file reads. By separating cheap rejection filters (size, 4 KB prefix, SHA-256) from final exact verification (chunked byte comparison), we avoid almost all unnecessary reads while keeping zero risk of a hash collision (two distinct byte sequences accidentally producing the same hash value).
Walk through a concrete 4-file example: logs/app.log (" timeout\n", 9 B), backup/app.log (" timeout\n", 9 B), logs/auth.log ("denied!!\n", 9 B), and srv/db.cfg ("host=db01;port=5432", 19 B):
- Stage 1 (Size metadata): sizes are
9, 9, 9, 19.srv/db.cfg(19B) is the only file of its size, so it is eliminated immediately with zero content reads;[logs/app.log, backup/app.log, logs/auth.log]continue. - Stage 2 (
4 KBprefix): reading up to4 KByieldsb" timeout\n"forlogs/app.logandbackup/app.log, andb"denied!!\n"forlogs/auth.log.logs/auth.logis alone and dropped;[logs/app.log, backup/app.log]have size9 <= 4096, meaning the prefix read already compared 100% of their bytes, so['backup/app.log', 'logs/app.log']is emitted immediately without re-reading! - Stages 3 & 4 (for files
> 4 KB): surviving large files are hashed in64 KBchunks with SHA-256, and any digest matches are verified chunk by chunk against the group's first file.
Complexity
Let N be the number of files, B be the total bytes across all files, and P = 4 KB (PREFIX_SIZE).
- Time and I/O: O(N + B) bytes processed, plus O(N log N) path comparisons for sorting. Stage 1 reads
0content bytes (Nmetadata lookups). Stage 2 reads at mostPbytes per same-size file (<= N * Pbytes). Stage 3 streams each remaining large candidate once (<= Bbytes). Stage 4 compares each duplicate against its class representative in64 KBchunks (<= 2Bbytes assuming no distinct files collide under SHA-256; ak-way SHA-256 collision would takeO(k^2)comparisons, though no SHA-256 collision has ever been found publicly). - Space: O(N) for path buckets plus O(CHUNK_SIZE) per active reader on disk. Each streaming hash holds one
64 KBbuffer and each streaming byte comparison holds two64 KBbuffers regardless of whether a file is1 MBor100 GB(in Stage 2, prefix keys inside a single size bucket can also be hashed to32bytes if a single size bucket holds millions of files). In the in-memory judge harness,filesystemholdsO(B)bytes only because the test input arrives in memory.
Edge cases
- Empty list or single file: Stage 1 produces no buckets of size
>= 2, returning[]. - Multiple empty files (
""): All have size0 <= 4 KBand prefixb"", so Stage 2 immediately groups them as verified duplicates without hashing (Example 2). - Same size, different bytes (
" timeout\n"vs"denied!!\n"): Kept together by Stage 1, separated immediately by Stage 2. - Identical
4 KBheader, differing tail or middle byte: Pass Stages 1 and 2, then separated cleanly by Stage 3 (or Stage 4 at chunk boundaries like byte65,536). - Small files (
<= 4 KB): Stage 2's prefix covers the entire file, proving exact equality without a redundant SHA-256 pass. - Visually similar text with different bytes:
"caf\u00e9"(precomposed UTF-8) vs"cafe\u0301"(combining accent) or"\n"vs"\r\n"have different byte sequences and are rightly kept separate.
Common mistakes
- Confusing a filter with proof: Equal file size, filename, timestamp, or
4 KBprefix never proves two10 MBfiles are identical. - Using a non-cryptographic checksum without byte verification: By the birthday bound (the statistical rule that collisions among
2^bbuckets become likely around2^(b/2)items), a 32-bit CRC32 has a ~50% collision chance across just77,000distinct files, and Python's built-inhash()is randomized across processes and prone to 64-bit collisions. - Calling
f.read()with no byte limit: Loads whole files into RAM and crashes on multi-gigabyte inputs. - Using
zip()instead ofzip_longest()in chunked equality checks: Plainzip()stops as soon as the shorter iterator ends, which would falsely reportTrueif one file were a prefix of another (for instance, if a file grew on disk mid-scan). - Opening files in text mode (
"r") instead of binary mode ("rb"): Fails withUnicodeDecodeErroron binary files and silently translates\r\nto\n, masking real byte differences. - Treating unreadable files as non-duplicates: A permission error means unknown, not unique; production scanners report errors and mid-scan mutations separately.
Alternative approaches
- Accept cryptographic SHA-256 equality without Stage 4: When the API contract explicitly allows probabilistic cryptographic matching (such as content-addressed storage like Git or Docker layers), skipping Stage 4 saves up to
2Bbytes of re-reading; document that the contract guarantees SHA-256 digest equality. - Multi-way lockstep chunk partitioning: Instead of hashing in Stage 3 and re-reading in Stage 4, open all
kfiles in a candidate group simultaneously, read chunk0, split any files whose chunks differ into sub-buckets, drop singletons, and continue to chunk1. Every file is read at most once with zero collision risk, at the cost of holdingkopen file descriptors andkchunk buffers at once (requiring batching ifkexceeds OS file-descriptor limits). - First-plus-last
4 KBsampling: Many formats (PDFs, MP4s, ZIP archives, database pages) start with identical template headers; sampling both the first4 KBand the last4 KBin Stage 2 rejects header-identical files before Stage 3.
Follow-up questions
- Under what file distributions does an early header-slice check save disk bandwidth, and when does it create wasted I/O? Reading a
4 KBheader slice saves substantial disk bandwidth when many large files share the exact same byte length (such as fixed-size log segments or uncompressed camera frames) yet diverge in their opening bytes, eliminating non-matches after reading4 KBinstead of megabytes. Conversely, it creates extra seek/open overhead when nearly all same-size files truly are duplicates (or share a> 4 KBboilerplate file header), because they all survive Stage 2 and must be streamed in full anyway. To avoid reading the first4 KBtwice on surviving files, seed each file'ssha256state with its already-read4 KBslice and continue streaming from offset4096. - How can raising the number of concurrent reader threads actually degrade throughput on a single physical drive? On a spinning hard disk drive (HDD), reading multiple files simultaneously forces the physical actuator arm to seek back and forth across platters; each mechanical seek costs several milliseconds while sequential reads stream rapidly, so extra threads drastically cut throughput. Even on NVMe SSDs, unbounded thread counts thrash OS page-cache read-ahead, exhaust file descriptors, and create queue contention beyond the device's native queue depth. Bound concurrency per underlying storage device (for example,
1sequential reader on an HDD and a modest pool such as4–16workers on NVMe or network object storage). - Which filesystem metadata or snapshot identifiers are needed before you can safely reuse previously computed content hashes? A cached hash is trustworthy only if keyed by an identifier guaranteed to change whenever any byte of the file changes. The strongest guarantee comes from immutable storage primitives such as a read-only filesystem snapshot ID or an object-store version/generation token. On a mutable POSIX filesystem without snapshots, key cache entries by
(st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns)— where an inode (st_ino) identifies the underlying filesystem object on devicest_dev, and POSIX change time (st_ctime_ns) is updated by the kernel on every content write or metadata update and cannot be set backward from user space viatouch, provided the timestamps are strictly older than the filesystem's clock granularity before the scan started.
Follow-up questions
- Under what file distributions does an early header-slice check save disk bandwidth, and when does it create wasted I/O?
- How can raising the number of concurrent reader threads actually degrade throughput on a single physical drive?
- Which filesystem metadata or snapshot identifiers are needed before you can safely reuse previously computed content hashes?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes