Incremental Processing: How a Batch Job Knows What Changed
On this page
Problem statement
A folder of files arrives every night. On most nights almost none of them differ from yesterday's, and a job that reprocesses everything spends its window redoing work that was already correct. The outputs it rewrites are identical to the ones they replace, their modification times all jump to tonight, and anything downstream watching for changes sees every file as changed.
Example 1 below runs exactly this on HM Land Registry's Leeds titles split into 33 ward files: 3.8 seconds to process them all, 0.2 seconds for a night when nothing changed, 0.3 seconds for a night when one ward was edited. Scale the folder up to hundreds of files and gigabytes, and the same ratio is the difference between a job that fits overnight and one that does not.
The obvious fix β skip files whose output already exists β is wrong in a way that only shows up later: it never reprocesses a file whose content changed but whose output still exists. The job silently stops updating.
Getting this right means answering one question precisely: what does "changed" mean, and what evidence proves it?
Quick answer
Four ways to decide, in increasing order of reliability and cost:
| Signal | Detects | Misses | Cost |
|---|---|---|---|
| output exists | never-processed items | any content change | free |
| mtime newer than output | edits and re-deliveries | touched-but-unchanged files (false positive) | one stat() |
| content hash | genuine content changes only | nothing | reads every byte |
| manifest | changes to input or to the code/config | nothing | a state file |
import hashlib, json
from pathlib import Path
def content_hash(path, chunk=1 << 20):
h = hashlib.blake2b(digest_size=16)
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
def needs_processing(src: Path, state: dict, recipe: str) -> bool:
prev = state.get(str(src))
if prev is None:
return True # never seen
if prev["recipe"] != recipe:
return True # the code or config changed
if prev["size"] != src.stat().st_size:
return True # cheap pre-filter
return prev["hash"] != content_hash(src) # the authority
On the Leeds job in Example 1, the third night's discovery reported 33 files Β· 1 to process {'content': 1} β one ward edited, found by its hash, and 32 skipped.
The recipe field is the part people leave out and regret. If the transformation changes, every output is stale regardless of whether any input moved β and a job that only watches inputs will never notice.
The four signals
Existence, mtime, content hash, manifest
Signal 1: output exists β the one that quietly stops working
def needs_processing(src, dst):
return not output_for(src, dst).exists()
This is correct for exactly one situation: inputs are immutable. Archive tiles, dated deliveries in dated folders, anything with a content-addressed name. If 2024-03-01_parcels.gpkg never changes after it lands, its output never needs rebuilding.
It is wrong the moment a supplier overwrites a file in place. The output exists, so the file is skipped, and the job reports success while serving data from March forever. This failure is completely silent β the counts look normal, no error is raised, and the only symptom is that a number downstream stops moving.
If you use this signal, be explicit about the assumption:
# Inputs are immutable: the supplier writes dated files and never edits them.
# If that stops being true, this check must change to a content hash.
def needs_processing(src, dst):
return not output_for(src, dst).exists()
Signal 2: mtime β cheap, and a little bit of a liar
def needs_processing(src, dst):
out = output_for(src, dst)
return not out.exists() or src.stat().st_mtime > out.stat().st_mtime
Almost free, and catches genuine edits. Its failure modes are all in the direction of doing too much work rather than too little, which is the safe direction:
rsyncandcpupdate mtime even when the content is identical, so a re-delivery of unchanged data reprocesses everything.touchmarks a file changed without changing a byte.- Clock skew between machines makes a file look older than an output produced from it.
- Filesystem granularity is one second on some systems, so a file rewritten within the same second as its output looks unchanged β the one direction where mtime does too little.
Guard against the last one by comparing with a margin:
return src.stat().st_mtime > out.stat().st_mtime + 1
Signal 3: content hash β the authority
def content_hash(path, chunk=1 << 20):
h = hashlib.blake2b(digest_size=16) # faster than sha256, plenty for this
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
A hash answers the real question: is this file's content the same as the content we processed? It has no false positives and no false negatives.
The cost is reading every byte. On this site's build machine, hashing a 926 MB GeoJSON already in the page cache ran at 0.8 GB/s with BLAKE2b and 1.7 GB/s with SHA-256; from disk, and far more over a network share, it is slower. Tens of gigabytes is still tens of seconds locally β nothing next to reprocessing them.
Use size as a free pre-filter, because a different size guarantees different content:
if prev["size"] != src.stat().st_size:
return True # certainly changed, no need to hash
return prev["hash"] != content_hash(src)
The size check is a shortcut for "certainly changed", never for "unchanged". On the Leeds job's third night, deleting one title from a ward's GeoPackage left the file exactly the same size, because SQLite allocates in whole pages, and only the hash noticed.
For very large files where even reading is too slow, hash a sample β first megabyte, last megabyte, size β and accept a small chance of missing a change:
def cheap_fingerprint(path, edge=1 << 20):
size = path.stat().st_size
h = hashlib.blake2b(digest_size=16)
h.update(str(size).encode())
with open(path, "rb") as f:
h.update(f.read(edge))
if size > 2 * edge:
f.seek(-edge, 2)
h.update(f.read(edge))
return h.hexdigest()
Be honest in the name and the comment: this is a fingerprint, not a hash, and an edit in the middle of a large file will be missed.
Signal 4: the manifest β inputs and the recipe
The complete version records everything the output depends on:
def recipe_id(config: dict, version: str) -> str:
"""Anything that changes the output, other than the input file."""
payload = json.dumps({"version": version, "config": config}, sort_keys=True)
return hashlib.blake2b(payload.encode(), digest_size=8).hexdigest()
state = {
"data/orkney.gpkg": {
"hash": "9f2cβ¦", "size": 8412193, "mtime": 1723190400.0,
"recipe": "a1b2c3d4", # β code + config at the time
"output": "out/orkney.gpkg",
"processed_at": "2026-08-15T02:03:11Z",
"rows": 4102
},
...
}
Now bumping VERSION or changing the target CRS in the config invalidates everything, exactly as it should. Without it, a change to the transformation produces a job that skips every file and reports success β the same silent failure as signal 1, arriving from the other direction.
What "changed" means for a database source
Files have hashes; tables do not, at least not cheaply. The equivalents:
-- an updated_at column, if the source maintains one honestly
SELECT * FROM parcels WHERE updated_at > :last_run;
-- a monotonically increasing id, for append-only tables
SELECT * FROM events WHERE id > :last_id;
-- xmin, the Postgres row version β works without cooperation from the schema
SELECT * FROM parcels WHERE xmin::text::bigint > :last_xmin;
The first is only as good as whoever maintains the column β a bulk update that forgets to touch it makes rows invisible to the job forever. The second is reliable and only works for inserts. The third needs care around transaction id wraparound but requires nothing of the schema.
Store the state where it survives
STATE = Path("state/manifest.json")
def load_state():
return json.loads(STATE.read_text()) if STATE.exists() else {}
def save_state(state):
STATE.parent.mkdir(parents=True, exist_ok=True)
tmp = STATE.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2, sort_keys=True))
tmp.replace(STATE) # atomic β a crash never leaves half a manifest
The write-to-temp-then-rename is not optional. A manifest truncated by a crash is worse than no manifest: the job forgets what it did and reprocesses everything, or worse, forgets only some entries.
Update the state after the output is safely written, never before:
for item in changed:
result = apply_one(item) # writes the output
if result.status == "ok":
state[str(item)] = fingerprint(item, recipe) # only now
save_state(state)
Recording first and processing second means a crash leaves the manifest claiming work that never happened β and that file is then skipped forever.
Five nights of an incremental job over Leeds ward files
The data used on this page
HM Land Registry's INSPIRE polygons for Leeds, split into one GeoPackage per electoral ward β 33 files in data/ β so the job has a real folder of inputs to be incremental about. Each title goes to the ward containing a point inside it. Land Registry data Β© Crown copyright and database right 2026, OGL v3; wards from the ONS.
import sys
from pathlib import Path
import geopandas as gpd
import pyogrio
import requests
reply = requests.Session().get("https://use-land-property-data.service.gov.uk/datasets/inspire/download/Leeds.zip",
timeout=600) # sets a cookie, then redirects to itself
reply.raise_for_status()
Path("leeds_inspire.zip").write_bytes(reply.content)
pyogrio.set_gdal_config_options({"GML_DOWNLOAD_SCHEMA": "NO"})
parcels = gpd.read_file("zip://leeds_inspire.zip!Land_Registry_Cadastral_Parcels.gml", columns=["INSPIREID"])
ONS = "https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services"
wards = gpd.read_file(f"{ONS}/Wards_December_2024_Boundaries_UK_BFC/FeatureServer/0/query"
"?where=LAD24NM%3D%27Leeds%27&outFields=WD24CD&outSR=27700&f=geojson"
).set_crs(27700, allow_override=True)
points = parcels.set_geometry(parcels.representative_point())
ward_of = gpd.sjoin(points, wards, predicate="within")["WD24CD"]
Path("data").mkdir(exist_ok=True)
for code, rows in parcels.join(ward_of, how="inner").groupby("WD24CD"):
rows.drop(columns="WD24CD").to_file(f"data/{code}.gpkg")
files = sorted(Path("data").glob("*.gpkg"))
print(f"{len(files)} ward files, {sum(f.stat().st_size for f in files) / 1e6:.0f} MB")
33 ward files, 158 MB
Example 1: the complete incremental job
%%writefile incremental.py
"""Reproject a folder of GeoPackages, processing only what changed."""
import argparse
import hashlib
import inspect
import json
from collections import Counter
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
import geopandas as gpd
STATE = Path("state/manifest.json")
CONFIG = {"target_crs": 4326}
def content_hash(path, chunk=1 << 20):
h = hashlib.blake2b(digest_size=16)
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
def load_state():
return json.loads(STATE.read_text()) if STATE.exists() else {}
def save_state(state):
STATE.parent.mkdir(parents=True, exist_ok=True)
tmp = STATE.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2, sort_keys=True))
tmp.replace(STATE)
def changed_files(src, state, recipe):
for path in sorted(src.rglob("*.gpkg")):
prev = state.get(str(path))
if prev is None:
yield path, "new"
elif prev["recipe"] != recipe:
yield path, "recipe"
elif prev["size"] != path.stat().st_size:
yield path, "size"
elif prev["hash"] != content_hash(path):
yield path, "content"
def recipe_id(config, *functions):
h = hashlib.blake2b(digest_size=8)
h.update(json.dumps(config, sort_keys=True, default=str).encode())
for fn in functions:
h.update(inspect.getsource(fn).encode())
return h.hexdigest()
def guard(work, total, *, threshold=0.5, force=False):
if force or not total or len(work) / total <= threshold:
return work
raise SystemExit(f"{len(work):,}/{total:,} ({len(work) / total:.0%}) look changed β that is unusual. "
f"Check the manifest and the recipe id, then re-run with --force if it really is a rebuild.")
def prune(state, src, out_dir, *, delete_outputs=False):
gone = [k for k in state if not Path(k).exists()]
for key in gone:
entry = state.pop(key)
if delete_outputs and entry.get("output"):
Path(entry["output"]).unlink(missing_ok=True)
return gone
@dataclass
class Result:
ok: bool
rows: int = 0
error: str = ""
def now_iso():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def output_for(src, src_root, out_root):
return (out_root / src.relative_to(src_root)).with_suffix(".gpkg")
def process(src, src_root, out_root, config):
gdf = gpd.read_file(src)
if gdf.crs is None:
return Result(False, error="no CRS")
gdf = gdf.to_crs(config["target_crs"])
out = output_for(src, src_root, out_root)
out.parent.mkdir(parents=True, exist_ok=True)
tmp = out.with_suffix(".tmp.gpkg")
gdf.to_file(tmp, driver="GPKG")
tmp.replace(out)
return Result(True, rows=len(gdf))
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--src", type=Path, default=Path("data"))
ap.add_argument("--out", type=Path, default=Path("output"))
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--force", action="store_true", help="ignore the manifest")
args = ap.parse_args(argv)
state = {} if args.force else load_state()
recipe = recipe_id(CONFIG, process)
all_files = sorted(args.src.rglob("*.gpkg"))
work = list(changed_files(args.src, state, recipe))
reasons = Counter(r for _, r in work)
print(f"{len(all_files):,} files Β· {len(work):,} to process {dict(reasons)}")
if args.dry_run:
for path, reason in work[:20]:
print(f" would process {path} ({reason})")
return {"processed": 0, "planned": len(work)}
if state: # a first run legitimately processes everything
work = guard(work, len(all_files), force=args.force)
ok = failed = 0
for path, reason in work:
try:
result = process(path, args.src, args.out, CONFIG)
except Exception as exc: # one bad file must not stop the run
result = Result(False, error=f"{type(exc).__name__}: {str(exc)[:80]}")
if result.ok:
ok += 1
state[str(path)] = {
"hash": content_hash(path), "size": path.stat().st_size,
"mtime": path.stat().st_mtime, "recipe": recipe,
"output": str(output_for(path, args.src, args.out)),
"processed_at": now_iso(), "rows": result.rows,
}
else:
failed += 1
print(f" β {path}: {result.error}")
removed = prune(state, args.src, args.out)
save_state(state)
print(f"done β {ok} processed, {len(all_files)-len(work)} skipped, "
f"{failed} failed, {len(removed)} pruned")
return {"processed": ok, "failed": failed, "skipped": len(all_files) - len(work)}
Run it the way a scheduler would, night after night β with one ward's file edited before the third run, and the target CRS changed before the fourth:
import time
import geopandas as gpd
import incremental
def night(label, argv=()):
t0 = time.perf_counter()
try:
counts = incremental.main(["--src", "data", "--out", "output", *argv])
except SystemExit as stop:
print(f" stopped: {stop}")
counts = None
print(f" [{label}: {time.perf_counter() - t0:.1f} s]\n")
return counts
night("first run")
night("second run, nothing changed")
edited = sorted(Path("data").glob("*.gpkg"))[5]
g = gpd.read_file(edited)
g.iloc[:-1].to_file(edited) # the supplier drops one title
night("third run, one ward edited")
incremental.CONFIG["target_crs"] = 3857 # a change to the recipe
night("fourth run, target CRS changed")
night("fifth run, the rebuild confirmed", ["--force"])
33 files Β· 33 to process {'new': 33}
done β 33 processed, 0 skipped, 0 failed, 0 pruned
[first run: 3.8 s]
33 files Β· 0 to process {}
done β 0 processed, 33 skipped, 0 failed, 0 pruned
[second run, nothing changed: 0.2 s]
33 files Β· 1 to process {'content': 1}
done β 1 processed, 32 skipped, 0 failed, 0 pruned
[third run, one ward edited: 0.3 s]
33 files Β· 33 to process {'recipe': 33}
stopped: 33/33 (100%) look changed β that is unusual. Check the manifest and the recipe id, then re-run with --force if it really is a rebuild.
[fourth run, target CRS changed: 0.0 s]
33 files Β· 33 to process {'new': 33}
done β 33 processed, 0 skipped, 0 failed, 0 pruned
[fifth run, the rebuild confirmed: 4.0 s]
The whole story in five nights. The first run processes all 33 files; the second processes none; the third finds exactly the one file that changed, by content hash; the fourth sees that every file was produced by a different recipe β and the guard refuses, because a run that suddenly wants to redo everything is more often a bug than a decision; the fifth, with --force, does the deliberate rebuild.
The if state: in front of the guard is there because the first version of this job, run for this page, refused its own first run: with an empty manifest every file is "new", 33 of 33 look changed, and the guard does exactly what it was written to do. A guard needs to know what normal looks like, and on the first night there is no normal yet.
--force and --dry-run are both essential in practice, and main takes its arguments as a list so that a test β or the cell above β can call it without touching sys.argv: the first for a deliberate rebuild, the second for answering "what would tonight do?" without doing it.
The guard and the recipe id are the two parts that catch bugs rather than edits. The recipe hashes the source of process together with the config, so editing the transformation invalidates every output with no version to remember to bump; it does not see changes inside the functions process calls, or in library versions, so pin those in the config and treat the hash as a strong default rather than a proof. And reporting the reason is what makes a surprising night debuggable: everything changed with reason recipe says somebody changed the code, content says the supplier re-exported, new says the manifest was lost.
Example 2: proving it works
%%writefile test_incremental.py
import shutil
from pathlib import Path
import geopandas as gpd
import pytest
import incremental
@pytest.fixture
def three_files(tmp_path, monkeypatch):
"""Three real ward files, in a folder of their own, with a fresh manifest."""
src = tmp_path / "src"
src.mkdir()
for name in sorted(Path("data").glob("*.gpkg"))[:3]:
shutil.copy(name, src / name.name)
monkeypatch.chdir(tmp_path) # manifest and outputs land in tmp_path
return src
def run(src, force=False):
return incremental.main(["--src", str(src), "--out", "out", *(["--force"] if force else [])])
def test_first_run_processes_everything(three_files):
assert run(three_files)["processed"] == 3
def test_second_run_processes_nothing(three_files):
run(three_files)
assert run(three_files)["processed"] == 0
def test_edited_file_is_reprocessed(three_files):
run(three_files)
path = sorted(three_files.glob("*.gpkg"))[1]
gpd.read_file(path).iloc[:-1].to_file(path)
assert run(three_files)["processed"] == 1
def test_recipe_change_is_caught_by_the_guard(three_files, monkeypatch):
run(three_files)
monkeypatch.setitem(incremental.CONFIG, "target_crs", 3857)
with pytest.raises(SystemExit):
run(three_files)
assert run(three_files, force=True)["processed"] == 3
def test_failed_item_is_retried(three_files):
broken = three_files / "broken.gpkg"
broken.write_bytes(b"not a geopackage")
first = run(three_files)
assert first["failed"] == 1
broken.unlink()
shutil.copy(sorted(three_files.glob("*.gpkg"))[0], broken)
assert run(three_files)["processed"] == 1 # retried, not skipped
!{sys.executable} -m pytest -q --no-header -p no:cacheprovider --color=no --tb=no -rf test_incremental.py
..... [100%]
5 passed in 2.87s
The last two are the ones that catch real regressions, and on this page the last one did. process only returned a failure for the problem its author had thought of β a missing CRS β so a corrupt file raised out of the loop and took the whole run down with it, before the manifest was saved. The try around each item in main is the fix: every failure becomes a recorded failure, retried next time, whatever caused it.
Example 3: incremental and parallel together
The manifest must be written by one process. Workers return facts; the parent records them.
from concurrent.futures import ProcessPoolExecutor
def run_parallel(work, src_root, out_root, config, workers=8):
updates = {}
with ProcessPoolExecutor(workers) as pool:
futures = {
pool.submit(process_and_fingerprint, p, src_root, out_root, config): p
for p, _ in work
}
for fut in as_completed(futures):
path = futures[fut]
try:
entry = fut.result()
if entry:
updates[str(path)] = entry # collected, not written
except Exception as exc:
print(f" β {path}: {type(exc).__name__}: {exc}")
return updates # parent writes once
Two processes writing one JSON file interleave and produce a corrupt manifest. Since a corrupt manifest triggers a full rebuild, that bug costs an entire overnight window β worth the discipline of returning data rather than writing from workers.
Incremental processing is a cache
Incremental processing is a cache, and it inherits every hard problem caches have. The output is a cached value; the input file and the transformation are its key; and the entire question is whether the key is complete.
An incomplete key produces stale results with no error. That is the failure mode running through this whole page, and it arrives in two ways. Watching only the output's existence misses input edits. Watching only the input misses code and config changes. Both produce a job that runs, reports success, and serves data from weeks ago β the worst kind of failure, because every signal says fine.
The mirror-image failure is over-invalidation: a key that includes something irrelevant, so everything looks changed and the job does full work every night while claiming to be incremental. The usual cause is a timestamp or an absolute path leaking into the recipe id. The guard in Example 1 exists because this failure is otherwise invisible β the job still produces correct output, just slowly, and nobody investigates a job that works.
Between the two, stale is much worse than slow, which is why the recommended default is a content hash plus a recipe id: it never misses a change, and the cost is bounded by read bandwidth.
The last piece is ordering. State must be written after the output, and atomically. A manifest updated before processing records work that may never happen; a manifest written in place can be truncated by a crash. Temp-file-plus-rename makes the update atomic on the same filesystem, so the manifest is always either the old complete one or the new complete one β which is the same idempotency argument that applies to the outputs themselves.
mtime granularity, network filesystems and deleted inputs
st_mtimegranularity is 1 second on some filesystems and 1 nanosecond on others. Compare with a margin.- Network filesystems have unreliable mtimes and clock skew between client and server. Hash instead.
- Pick the hash for speed on your hardware. On CPUs with SHA extensions β most x86 chips from the last few years β
hashlib.sha256beatblake2bby two to one on this site's machine (1.7 against 0.8 GB/s). Either is ample for change detection, which is not cryptography. - A hash of a GeoPackage changes when SQLite reorganises pages, even with identical data. Hashing the data rather than the file requires reading it as a layer, which is far more expensive.
- Deleted inputs need handling. An entry in the manifest whose file is gone means the output should probably be removed too.
- The manifest grows forever. Prune entries whose source no longer exists, or it slowly becomes the largest file in the project.
- Do not put the manifest in the output directory if anything downstream syncs that directory β it will be treated as a deliverable.
- Parallel workers must not write the manifest concurrently. Collect results and write once in the parent.
- Empty or zero-byte inputs hash consistently and will be marked processed. Validate before recording.
Path.replace()is atomic only on the same filesystem. Put the temp file next to the final one, not in/tmp.- The manifest is not a lock. Two concurrent runs of the same job will both process and both write; use a lock file if that can happen.
--forceshould still write the manifest, so the next normal run is incremental again.
Internal links
- How to add a dry-run mode to a batch GIS script β inspecting the plan
- The anatomy of a batch job: discover, apply, report β where change detection lives
- How to build a resumable batch GIS job in Python β resuming within a run, versus skipping between runs
- Idempotency explained: why a GIS job must be safe to re-run β the property this depends on
- Batch job gives different results each run β when the recipe is not as fixed as it looks
- How to cache pipeline steps so only changed data is reprocessed β the same idea within a pipeline
- How to record run metadata and data lineage in a GIS pipeline β the manifest as a lineage record
- Choosing the unit of work in a batch job β what a "changed item" is
FAQ
Is checking whether the output exists good enough?
Only if inputs are genuinely immutable β dated files that are never overwritten. If a supplier can edit a file in place, this check silently stops updating and never reports a problem.
mtime or content hash?
mtime when inputs are local and re-deliveries are rare; a hash when correctness matters more than a few seconds of read time. mtime's errors are all in the direction of extra work, except when the filesystem's resolution is coarse.
Why include a recipe id?
Because the output depends on the code and config as well as the input. Without it, changing the target CRS produces a run that skips every file and reports success.
What if the manifest is lost?
Everything looks new and the job does a full rebuild β which is correct but expensive. The guard in Example 1 turns that into a visible prompt rather than a silent full night's work.
How do I do this for a database table?
Use an updated_at column if one is honestly maintained, a monotonic id for append-only data, or Postgres xmin if the schema offers nothing.
Should the manifest live in version control?
No β it is run state, not source. Keep it beside the outputs or in a state directory, and make sure it is backed up with them.
How do I test change detection?
Process, assert everything ran; re-run, assert nothing ran; touch a file's content, assert exactly one item ran; bump the recipe, assert everything ran.
What happens to an item that fails?
It gets no manifest entry, so the next run retries it: in Example 2 a corrupt file failed once and was processed on the next run after it was replaced. Retry is a consequence of recording only what succeeded, not something you add.