DevOps for Geospatial Pipelines: Packaging, Testing, CI, Containers and Schedules
A notebook answers a question once. A monitoring service answers it again every few days, for years, on machines you do not watch. Getting there takes the practices of DevOps: code in a package, automated tests, checks that run on every change (continuous integration), a container that runs the same everywhere, a schedule, configuration outside the code, logs you can query, and versioned outputs.
This notebook applies them to a small but real pipeline, haor_monitor, in the haor_monitor/ folder next to it. Every few days the pipeline looks for new Sentinel-2 overpasses of Tanguar Haor, a Ramsar wetland in Sunamganj, Bangladesh, and records how much of the haor is open water and how green its land is. The notebook runs every practice for real: linting, tests with coverage, a deliberately broken change that the tests catch, git history, the CI workflow’s steps, container checks, and the pipeline itself on a simulated schedule against Planetary Computer.
Learning objectives
Structure a geospatial pipeline as a package: pure processing functions, input/output at the edges, configuration from the environment.
Write fast tests that need no network, and enforce lint, formatting and coverage as quality gates.
Use git and a CI workflow (GitHub Actions) so that every change is checked the same way.
Package the pipeline as a container image with good practices.
Make scheduled jobs idempotent and observable: incremental runs, structured logs, exit codes, versioned outputs.
Data
Data
Source
Sentinel-2 L2A over Tanguar Haor, 2024
Planetary Computer STAC (read by the pipeline)
The pipeline project
haor_monitor/ next to this notebook (package, tests, Dockerfile, workflows)
Install the tools with pip install pytest pytest-cov ruff pystac-client planetary-computer odc-stac. Docker is optional: Section 7 builds the image only where Docker is installed.
Contents
Setup
DevOps in one page
The project
Quality gates: lint, format, tests, coverage
A broken change, caught
Version control and the CI workflow
Containers
Scheduled, idempotent runs
Observability and versioned outputs
Summary and exercises
Setup
Installation. This notebook needs installation option 1 (vector, raster, CRS and visualization): pip install "geolattice[core]". See “Installation options” in the GeoLattice README. It also uses pyyaml, which no GeoLattice option installs: pip install pyyaml.
Code
# Imports, paths, and a small helper to run shell commands from the notebook%matplotlib inlineimport jsonimport osimport reimport shutilimport subprocessimport sysimport timeimport warningsfrom pathlib import Pathwarnings.filterwarnings("ignore")import pandas as pdimport matplotlib.pyplot as pltimport yamlfrom IPython.display import Code, displayimport geolatticeplt.rcParams.update({"figure.dpi": 110})DATA = Path("../../../Data")WEB = DATA /"00_shared"/"data_web_cloud_gis"PROJECT = Path("haor_monitor").resolve() # the project as shipped with the tutorialOUT = (WEB /"08_10_outputs").resolve()# Fresh output directory; pin git identity for local demo commits onlyif OUT.exists(): shutil.rmtree(OUT)OUT.mkdir(parents=True)PY = sys.executableGIT = ["git", "-c", "user.name=GeoLattice tutorial", "-c", "user.email=tutorial@example.org", "-c", "init.defaultBranch=main"]def sh(cmd, cwd=PROJECT, env=None, check=False):"Run a command, return (exit code, seconds, output)." t0 = time.perf_counter() base = {k: v for k, v in os.environ.items() if k notin ("FORCE_COLOR", "CLICOLOR_FORCE")} p = subprocess.run(cmd, cwd=cwd, env={**base, "NO_COLOR": "1", "PY_COLORS": "0", **(env or {})}, capture_output=True, text=True)return p.returncode, time.perf_counter() - t0, (p.stdout + p.stderr).strip()# Check that the local toolchain is availabletools = {name: sh(cmd)[2].splitlines()[0] for name, cmd in {"python": [PY, "--version"], "ruff": [PY, "-m", "ruff", "--version"], "pytest": [PY, "-m", "pytest", "--version"],"git": ["git", "--version"]}.items()}tools["docker"] = shutil.which("docker") or"not installed"print("geolattice", geolattice.__version__);print(json.dumps(tools, indent=1))
HAOR_* environment variables; secrets in the CI secret store
Idempotent, observable jobs
Safe retries; problems are visible
skip processed dates; JSON-lines logs; non-zero exit on failure
Versioned outputs
Know what changed, when, and roll back
results committed to a data branch
The project
Code
# Inventory project files by role (package, tests, CI, other)def tree(root, skip=("__pycache__", ".pytest_cache", ".ruff_cache", "monitor_data", ".git")): lines = []for path insorted(root.rglob("*")):ifany(part in skip for part in path.relative_to(root).parts) or path.is_dir():continue rel = path.relative_to(root) n =len(path.read_text().splitlines()) lines.append({"file": str(rel), "lines": n, "role": {"src": "package", "tests": "tests", ".github": "CI / schedule"}.get(rel.parts[0], "project")})return pd.DataFrame(lines)files = tree(PROJECT)display(files.groupby("role").lines.agg(["count", "sum"]).rename(columns={"count": "files", "sum": "lines"}))files
files
lines
role
CI / schedule
2
87
package
6
342
project
4
92
tests
4
190
file
lines
role
0
.dockerignore
8
project
1
.github/workflows/ci.yml
39
CI / schedule
2
.github/workflows/monitor.yml
48
CI / schedule
3
Dockerfile
21
project
4
README.md
24
project
5
pyproject.toml
39
project
6
src/haor_monitor/__init__.py
3
package
7
src/haor_monitor/__main__.py
45
package
8
src/haor_monitor/config.py
39
package
9
src/haor_monitor/pipeline.py
138
package
10
src/haor_monitor/process.py
58
package
11
src/haor_monitor/stac.py
59
package
12
tests/__init__.py
0
tests
13
tests/test_cli.py
53
tests
14
tests/test_pipeline.py
84
tests
15
tests/test_process.py
53
tests
Code
# Show the processing module that turns scenes into observationsdisplay(Code(filename=str(PROJECT /"src/haor_monitor/process.py"), language="python"))
"""Pure functions that turn one day's Sentinel-2 bands into statistics. No input/output: easy to test."""from__future__importannotationsimportmathimportnumpyasnpCLEAR_CLASSES=(4,5,6)# SCL: vegetation, bare soil, waterEXPECTED={"clear_fraction":(0.0,1.0),"water_fraction":(0.0,1.0),"ndvi_land_median":(-1.0,1.0)}defreflectance(dn:np.ndarray,processing_baseline:str|float)->np.ndarray:"""Surface reflectance from Sentinel-2 L2A DN as distributed by ESA / Planetary Computer. From processing baseline 04.00 (January 2022) DN carry an offset of 1000: reflectance = (DN - 1000) / 10000. Earlier baselines have no offset. DN 0 means no data. """offset=1000.0iffloat(processing_baseline)>=4.0else0.0out=(dn.astype("float32")-offset)/10_000.0out[dn==0]=np.nanreturnoutdefscene_stats(green:np.ndarray,red:np.ndarray,nir:np.ndarray,scl:np.ndarray)->dict:"""Clear fraction, open-water fraction (NDWI > 0) and median land NDVI of one observation. Bands are reflectances on the same grid; ``scl`` is the scene classification layer. """clear=np.isin(scl,CLEAR_CLASSES)&np.isfinite(green)&np.isfinite(red)&np.isfinite(nir)n=int(scl.size)ifnotclear.any():return{"pixels":n,"clear_fraction":0.0,"water_fraction":math.nan,"ndvi_land_median":math.nan}withnp.errstate(invalid="ignore",divide="ignore"):ndwi=(green-nir)/(green+nir)ndvi=(nir-red)/(nir+red)water=clear&(ndwi>0)land=clear&~waterreturn{"pixels":n,"clear_fraction":float(clear.mean()),"water_fraction":float(water.sum()/clear.sum()),"ndvi_land_median":float(np.nanmedian(ndvi[land]))ifland.any()elsemath.nan,}defquality_flags(stats:dict,min_clear:float=0.2)->list[str]:"""Data-quality checks; an empty list means the observation is usable."""flags=[]forkey,(lo,hi)inEXPECTED.items():value=stats.get(key)ifvalueisNone:flags.append(f"missing:{key}")elifnotmath.isnan(value)andnotlo<=value<=hi:flags.append(f"out_of_range:{key}")ifstats.get("clear_fraction",0.0)<min_clear:flags.append("low_clear_fraction")returnflags
process.py holds the science: the reflectance offset of Notebook 08_09 (which depends on the processing baseline), the cloud mask (scene classes vegetation, bare soil and water count as clear), open water as NDWI > 0, and data-quality flags. It has no input/output, so it is tested with small synthetic arrays. stac.py searches the catalogue and reads bands; pipeline.py combines them, skips dates already processed, writes the table atomically and logs every step as JSON.
Code
# Show the pipeline entry points used by CLI, CI, and the scheduledisplay(Code(filename=str(PROJECT /"src/haor_monitor/pipeline.py"), language="python"))
"""The monitoring job: find new observations, process them, append to the table, log the run.Idempotent: dates already in ``observations.parquet`` are skipped, so the job can run on anyschedule, be retried after a failure, or run twice by accident without duplicating data."""from__future__importannotationsimportjsonimportloggingimporttimeimportuuidfromdatetimeimportdate,datetime,timezonefrompathlibimportPathimportpandasaspdfrom.importstacfrom.configimportSettingsfrom.processimportquality_flags,scene_statslog=logging.getLogger("haor_monitor")COLUMNS=["date","scenes","baseline","pixels","clear_fraction","water_fraction","ndvi_land_median","flags","processed_at",]classJsonFormatter(logging.Formatter):"""One JSON object per log line: easy to search and aggregate in any log service."""defformat(self,record:logging.LogRecord)->str:entry={"time":datetime.fromtimestamp(record.created,timezone.utc).isoformat(timespec="seconds"),"level":record.levelname,"message":record.getMessage(),}entry.update(getattr(record,"fields",{}))returnjson.dumps(entry)defsetup_logging(path:Path|None=None)->None:handlers:list[logging.Handler]=[logging.StreamHandler()]ifpathisnotNone:path.parent.mkdir(parents=True,exist_ok=True)handlers.append(logging.FileHandler(path))forhandlerinhandlers:handler.setFormatter(JsonFormatter())log.handlers[:]=handlerslog.setLevel(logging.INFO)log.propagate=Falsedeftable_path(settings:Settings)->Path:returnsettings.data_dir/"observations.parquet"defload_table(settings:Settings)->pd.DataFrame:path=table_path(settings)ifpath.exists():returnpd.read_parquet(path)returnpd.DataFrame(columns=COLUMNS)defrun(settings:Settings,start:date,end:date,*,search=stac.search,load=stac.load_day)->dict:"""Process every new daily observation between start and end; return a run summary."""run_id=uuid.uuid4().hex[:8]t0=time.perf_counter()settings.data_dir.mkdir(parents=True,exist_ok=True)table=load_table(settings)done=set(pd.to_datetime(table["date"]).dt.date)iflen(table)elseset()days=stac.group_by_day(search(settings,start,end))new={d:itemsford,itemsindays.items()ifdnotindone}log.info("run started",extra={"fields":{"run_id":run_id,"start":str(start),"end":str(end),"days_found":len(days),"days_new":len(new),}},)rows,failed=[],[]forday,itemsinnew.items():try:bands=load(items,settings)stats=scene_stats(bands["green"],bands["red"],bands["nir"],bands["scl"])flags=quality_flags(stats,settings.min_clear)rows.append({"date":pd.Timestamp(day),"scenes":len(items),"baseline":bands["baseline"],**stats,"flags":";".join(flags),"processed_at":pd.Timestamp.now(tz="UTC"),})log.info("day processed",extra={"fields":{"run_id":run_id,"date":str(day),**stats,"flags":flags}},)exceptExceptionasexc:# one bad day must not stop the runfailed.append(str(day))log.error("day failed",extra={"fields":{"run_id":run_id,"date":str(day),"error":f"{type(exc).__name__}: {exc}"}},)ifrows:new_rows=pd.DataFrame(rows,columns=COLUMNS)table=new_rowsiftable.emptyelsepd.concat([table,new_rows],ignore_index=True)table=table.sort_values("date").reset_index(drop=True)tmp=table_path(settings).with_suffix(".tmp")table.to_parquet(tmp,index=False)tmp.replace(table_path(settings))# atomic: readers never see a half-written filesummary={"run_id":run_id,"days_found":len(days),"days_new":len(new),"processed":len(rows),"failed":failed,"rows_total":len(table),"seconds":round(time.perf_counter()-t0,1),}log.info("run finished",extra={"fields":summary})returnsummary
Quality gates: lint, format, tests, coverage
CI runs three commands; any non-zero exit code fails the build. They run here exactly as CI runs them (with PYTHONPATH=src in place of installing the package).
Code
# Run local quality gates: lint, format check, and tests with coverageenv = {"PYTHONPATH": f"{PROJECT /'src'}:{PROJECT}"}gates = {"lint (ruff check)": [PY, "-m", "ruff", "check", "."],"format (ruff format --check)": [PY, "-m", "ruff", "format", "--check", "."],"tests + coverage >= 80 %": [PY, "-m", "pytest", "-p", "no:cacheprovider", "--cov=haor_monitor","--cov-report=term", "--cov-fail-under=80"]}results = {}for name, cmd in gates.items(): code_, sec, out = sh(cmd, env=env) results[name] = {"exit code": code_, "seconds": round(sec, 1), "last line": out.splitlines()[-1]}if"pytest"in cmd: coverage = out(PROJECT /".coverage").unlink(missing_ok=True)display(pd.DataFrame(results).T)print("\n".join(l for l in coverage.splitlines() if l.startswith(("src/", "TOTAL", "Name"))))
Format: all 11 Python files already match the formatter.
Tests: the 12 tests pass in 0.39 s, and coverage is 93%, above the 80% threshold.
The tests run in well under a second because none of them touches the network: processing functions get synthetic 10 × 10 scenes, and the pipeline gets a fake catalogue with two tiles per overpass. The one module with low coverage is stac.py (57%), the thin layer that calls Planetary Computer; it is exercised by the real runs in Section 8, not by unit tests.
These gates were not green at first. The first check of this project found 7 over-long lines, 7 files that needed formatting, and 71% coverage (the command-line module was untested), so the CI workflow would have failed. Adding command-line and logging tests and running ruff format fixed it. That is exactly the work CI is meant to force.
A broken change, caught
Suppose a contributor “simplifies” reflectance() by always subtracting the offset, forgetting that scenes processed before 2022 have none. We apply that change to a copy of the project and run the tests, as CI would on their pull request.
Code
# Deliberately break the baseline offset logic and confirm tests catch itbroken = OUT /"broken_copy"shutil.copytree(PROJECT, broken, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", ".ruff_cache", ".coverage"))p = broken /"src/haor_monitor/process.py"original = p.read_text()changed = original.replace('offset = 1000.0 if float(processing_baseline) >= 4.0 else 0.0', 'offset = 1000.0')assert changed != originalp.write_text(changed)code_, sec, out = sh([PY, "-m", "pytest", "-p", "no:cacheprovider", "-q", "-rf", "--no-header"], cwd=broken, env={"PYTHONPATH": f"{broken /'src'}:{broken}"})print(f"exit code {code_} after {sec:.1f} s")print("\n".join(l for l in out.splitlines() if l.startswith(("FAILED", "E ", ">")) or" passed"in l or" failed"in l)[:1500])shutil.rmtree(broken)
exit code 1 after 1.3 s
> assert old[:2] == pytest.approx([0.1, 0.15]) and math.isnan(old[2])
E assert (array([0. , ...dtype=float32) == approx([0.1 ±...15 ± 1.5e-07])
E
E comparison failed. Mismatched elements: 2 / 2:
E Max absolute difference: 0.10000000894069672
E Max relative difference: inf
E Index | Obtained | Expected
E 0 | 0.0 | 0.1 ± 1.0e-07
E 1 | 0.05 | 0.15 ± 1.5e-07)
FAILED tests/test_process.py::test_reflectance_offset_depends_on_processing_baseline
The test suite failed (exit code 1, after 1.3 s) at test_reflectance_offset_depends_on_processing_baseline. For a pre-2022 scene (baseline 03.01), DN 1000 and 1500 now give reflectances of 0.0 and 0.05 instead of 0.10 and 0.15. Every older scene would silently become 0.1 darker, and NDVI and water fractions would shift with it.
On GitHub this pull request would show a red check and could not be merged under branch protection. The test exists because Notebook 08_09 found exactly this kind of offset confusion between data providers.
Version control and the CI workflow
The project becomes a git repository (here a copy under the outputs folder, so the tutorial folder stays untouched). .gitignore keeps data and caches out of the code history.
Code
# Copy the project into the output folder and make an initial git commitrepo = OUT /"haor_monitor"shutil.copytree(PROJECT, repo, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", ".ruff_cache", ".coverage"))(repo /".gitignore").write_text("monitor_data/\n__pycache__/\n.pytest_cache/\n.ruff_cache/\n.coverage\n*.egg-info/\n")for cmd in [["init", "-q"], ["add", "."], ["commit", "-q", "-m", "haor_monitor 1.0.0: pipeline, tests, Dockerfile, workflows"]]:assert sh(GIT + cmd, cwd=repo)[0] ==0print(sh(["git", "log", "--stat", "--format=%h %s"], cwd=repo)[2])
The CI workflow is a YAML file. Each job runs on a fresh virtual machine; strategy.matrix repeats the job for three Python versions. Below we read the workflow and run its run: steps locally, in the committed copy, skipping the install step (the environment already has the packages) and the Docker job (Section 7).
Code
# Inspect the CI workflow, then replay its runnable steps locallydisplay(Code(filename=str(repo /".github/workflows/ci.yml"), language="yaml"))wf = yaml.safe_load((repo /".github/workflows/ci.yml").read_text())triggers = wf[True] ifTruein wf else wf["on"] # YAML 1.1 reads the key `on` as Trueprint("triggers:", list(triggers), "| jobs:", list(wf["jobs"]), "| Python versions:", wf["jobs"]["test"]["strategy"]["matrix"]["python-version"])rows = []for step in wf["jobs"]["test"]["steps"]:if"run"notin step: rows.append({"step": step.get("uses"), "result": "action (runs on GitHub)"});continueif step["run"].startswith("pip install"): rows.append({"step": step["name"], "result": "skipped here (environment ready)"});continue# Map workflow shell lines onto the local Python interpreter cmd = step["run"].replace("pytest", f"{PY} -m pytest -p no:cacheprovider").replace("ruff", f"{PY} -m ruff").split() code_, sec, out = sh(cmd, cwd=repo, env={"PYTHONPATH": f"{repo /'src'}:{repo}"}) rows.append({"step": step["name"], "command": step["run"], "result": "pass"if code_ ==0elsef"FAIL ({code_})","seconds": round(sec, 1)})(repo /".coverage").unlink(missing_ok=True)pd.DataFrame(rows)
# Continuous integration: lint and test on every push and pull request.name:cion:push:branches:[main]pull_request:jobs:test:runs-on:ubuntu-latesttimeout-minutes:15strategy:matrix:python-version:["3.10","3.11","3.12"]steps:-uses:actions/checkout@v4-uses:actions/setup-python@v5with:python-version:${{ matrix.python-version }}cache:pip-name:Installrun:pip install -e ".[dev]"-name:Lintrun:ruff check .-name:Format checkrun:ruff format --check .-name:Testrun:pytest --cov=haor_monitor --cov-report=term-missing --cov-fail-under=80image:needs:testruns-on:ubuntu-lateststeps:-uses:actions/checkout@v4-name:Build the container imagerun:docker build -t haor-monitor:${{ github.sha }} .-name:Smoke test the imagerun:docker run --rm haor-monitor:${{ github.sha }} report
The workflow runs on pushes to main and on pull requests, with two jobs:
test: lint, format check and tests with coverage, repeated for Python 3.10, 3.11 and 3.12.
image: runs only if the tests pass; builds the Docker image and smoke-tests it.
Run locally, its three check steps passed in the committed copy. Checkout, Python setup and installation are done by GitHub’s runners, and the image job needs Docker (Section 7). The first commit records the 17 files of version 1.0.0; the generated .gitignore keeps data and caches out of the code history.
Containers
A container image bundles the code with an operating system layer and every dependency, so the pipeline runs identically on a laptop, in CI, on a VM or in a managed service (AWS Batch, Cloud Run jobs, Azure Container Apps jobs, Kubernetes CronJobs).
Code
# Review the Dockerfile and check common container hardening practicesdisplay(Code(filename=str(PROJECT /"Dockerfile"), language="docker"))dockerfile = (PROJECT /"Dockerfile").read_text()ignore = (PROJECT /".dockerignore").read_text().split()checks = {"base image pinned to an exact version": bool(re.search(r"^FROM \S+:\d+\.\d+\.\d+", dockerfile, re.M)),"slim base image": "slim"in dockerfile,"runs as a non-root user": bool(re.search(r"^USER (?!root)\S+", dockerfile, re.M)),"no secrets in ENV (KEY, TOKEN, PASSWORD, SECRET)": not re.search(r"^ENV .*(KEY|TOKEN|PASSWORD|SECRET)", dockerfile, re.M | re.I),"pip cache disabled (smaller image)": "PIP_NO_CACHE_DIR=1"in dockerfile,"data mounted as a volume, not baked in": "VOLUME"in dockerfile and"monitor_data/"in ignore,"tests and git history excluded from the build context": "tests/"in ignore and".git/"in ignore,"no ADD of remote URLs": not re.search(r"^ADD https?://", dockerfile, re.M),}display(pd.Series(checks, name="passes").to_frame())# Build and smoke-test the image when Docker is availableif shutil.which("docker"): code_, sec, out = sh(["docker", "build", "-t", "haor-monitor:1.0.0", "."], cwd=repo)print(f"docker build: exit {code_} in {sec:.0f} s") code_, sec, out = sh(["docker", "run", "--rm", "haor-monitor:1.0.0", "report"], cwd=repo)print("docker run report:", out.splitlines()[-1] if out else code_)else:print("Docker is not installed on this machine: the image is built by the `image` job of the CI workflow instead.")
# Container image for the Tanguar Haor monitor (GeoLattice Notebook 08_10).# docker build -t haor-monitor:1.0.0 .# docker run --rm -v "$PWD/monitor_data:/data" haor-monitor:1.0.0 run --start 2024-01-01 --end 2024-12-31FROMpython:3.11.11-slim-bookwormENVPYTHONUNBUFFERED=1\PIP_NO_CACHE_DIR=1\PIP_DISABLE_PIP_VERSION_CHECK=1\HAOR_DATA_DIR=/data
# rasterio and odc-stac install from wheels that bundle GDAL: no system GDAL neededWORKDIR/appCOPYpyproject.tomlREADME.md./
COPYsrc./src
RUNpipinstall.&&useradd--create-home--uid10001monitor&&mkdir/data&&chownmonitor/data
USERmonitorVOLUME["/data"]HEALTHCHECKNONE
ENTRYPOINT["python","-m","haor_monitor"]CMD["run"]
passes
base image pinned to an exact version
True
slim base image
True
runs as a non-root user
True
no secrets in ENV (KEY, TOKEN, PASSWORD, SECRET)
True
pip cache disabled (smaller image)
True
data mounted as a volume, not baked in
True
tests and git history excluded from the build context
True
no ADD of remote URLs
True
Docker is not installed on this machine: the image is built by the `image` job of the CI workflow instead.
The Dockerfile passes all eight checks:
an exact, slim base image (python:3.11.11-slim-bookworm);
a non-root user;
no secrets in environment variables;
no pip cache;
data on a volume rather than in the image;
tests and git history excluded from the build context;
no downloads with ADD.
rasterio and odc-stac install from wheels that bundle GDAL, so no system GDAL packages are needed.
Docker is not installed on this machine, so the image was not built here. The image job of the CI workflow builds it on every change instead. On a machine with Docker, the same cell builds the image and runs report inside it. Use hadolint for a complete lint of Dockerfiles.
Scheduled, idempotent runs
monitor.yml runs the pipeline on a cron schedule (30 6 */5 * *: 06:30 UTC every fifth day, matching Sentinel-2’s revisit), never two runs at once (concurrency), and commits the results to a data branch.
# Scheduled monitoring: every 5 days (Sentinel-2's revisit), plus manual runs.# Results are kept on the `data` branch, so every update is versioned by git.name:monitoron:schedule:-cron:"306*/5**"# 06:30 UTC every fifth day of the monthworkflow_dispatch:inputs:start:description:"Firstdate(YYYY-MM-DD);default:30daysago"required:falseconcurrency:group:monitor# never two runs at once: they would race on the tablecancel-in-progress:falsepermissions:contents:writejobs:run:runs-on:ubuntu-latesttimeout-minutes:60steps:-uses:actions/checkout@v4-uses:actions/checkout@v4with:ref:datapath:monitor_data-uses:actions/setup-python@v5with:python-version:"3.11"cache:pip-name:Installrun:pip install .-name:Run the monitorenv:HAOR_DATA_DIR:monitor_datarun:python -m haor_monitor run ${{ inputs.start && format('--start {0}', inputs.start) || '' }}-name:Commit new observationsworking-directory:monitor_datarun:|git config user.name "haor-monitor bot"git config user.email "actions@users.noreply.github.com"git add observations.parquet runs.jsonlgit diff --cached --quiet || git commit -m "Observations update $(date -u +%Y-%m-%d)"git push
We imitate three scheduled runs against the real catalogue. The data folder is its own git repository, standing in for the data branch, and each run’s results are committed when they changed:
a first run covering January to June 2024;
the same window again, as when a scheduler fires twice or a run is retried;
a later run covering the whole year, after the second half of 2024 “arrived”.
Code
# Run the monitor CLI for a few date windows and commit data changesdata_dir = OUT /"monitor_data"data_dir.mkdir()assert sh(GIT + ["init", "-q"], cwd=data_dir)[0] ==0runs = []for start, end in [("2024-01-01", "2024-06-30"), ("2024-01-01", "2024-06-30"), ("2024-01-01", "2024-12-31")]: code_, sec, out = sh([PY, "-m", "haor_monitor", "run", "--start", start, "--end", end], cwd=repo, env={"PYTHONPATH": str(repo /"src"), "HAOR_DATA_DIR": str(data_dir)}) summary = [json.loads(l) for l in out.splitlines() if l.startswith("{") and'"run finished"'in l][-1] sh(GIT + ["add", "-A"], cwd=data_dir) committed = sh(GIT + ["commit", "-q", "-m", f"observations {start} to {end}"], cwd=data_dir)[0] ==0 runs.append({"window": f"{start} to {end}", "exit code": code_, "days found": summary["days_found"],"new": summary["days_new"], "processed": summary["processed"], "failed": len(summary["failed"]),"rows in table": summary["rows_total"], "seconds": round(sec, 1), "data commit": committed})pd.DataFrame(runs)
window
exit code
days found
new
processed
failed
rows in table
seconds
data commit
0
2024-01-01 to 2024-06-30
0
16
16
16
0
16
212.0
True
1
2024-01-01 to 2024-06-30
0
16
0
0
0
16
3.5
True
2
2024-01-01 to 2024-12-31
0
31
15
15
0
31
184.5
True
The three runs show what idempotence buys:
Run
Days found
Days processed
Time
1: January-June
16
16
212 s
2: the same window again
16
0
3.5 s (only the catalogue search)
3: the whole year
31
15 new
185 s
No run failed, and the table ended with 31 rows and no duplicates. Each day took about 12 s, almost all of it network reads from Planetary Computer.
The data repository got a commit for every run. The second run’s commit contains only the two new log lines; observations.parquet was unchanged. That is how a data branch shows, line by line, when results changed and when a run merely checked.
Observability and versioned outputs
Every run appended JSON lines to runs.jsonl: one record when a run starts, one per processed day, one when it finishes. Because every line is JSON, the log is a table.
Code
# Summarize run logs and the git history of the data directorylog = pd.DataFrame([json.loads(l) for l in (data_dir /"runs.jsonl").read_text().splitlines()])print(f"{len(log)} log records:", log.message.value_counts().to_dict())display(log[log.message =="run finished"][["time", "run_id", "days_found", "days_new", "processed", "failed", "seconds"]])print(sh(["git", "log", "--format=%h %s", "--stat"], cwd=data_dir)[2])
# Load observations and plot open water and land NDVI through 2024obs = pd.read_parquet(data_dir /"observations.parquet")ok = obs[obs["flags"] ==""] # obs["flags"], not obs.flags: DataFrame.flags is a pandas propertyprint(f"{len(obs)} observations, {len(ok)} usable; flagged: {obs.loc[obs['flags'] !='', ['date', 'flags']].astype(str).values.tolist()}")fig, ax = plt.subplots(2, 1, figsize=(10, 5.2), sharex=True)ax[0].bar(ok.date, ok.water_fraction, width=4, color="#2b8cbe"); ax[0].set_ylabel("open water (share of clear area)")ax[0].set_title("Tanguar Haor, 2024: Sentinel-2 observations recorded by haor_monitor")ax[1].plot(ok.date, ok.ndvi_land_median, "o-", color="#31a354"); ax[1].set_ylabel("median NDVI of land")for a in ax: a.axvspan(pd.Timestamp("2024-06-01"), pd.Timestamp("2024-08-31"), color="grey", alpha=0.15)ax[0].text(pd.Timestamp("2024-06-05"), 0.9, "no usable optical\nscene (monsoon)", fontsize=8)plt.tight_layout(); plt.show()display(ok.set_index(ok.date.dt.strftime("%Y-%m-%d"))[["scenes", "clear_fraction", "water_fraction", "ndvi_land_median"]].round(3).T)
The 37 log records (3 run starts, 31 processed days, 3 run ends) are directly a table of run history: durations, days found and processed, failures. In production the same JSON lines go to a log service (CloudWatch, Cloud Logging, Loki), where an alert on level = ERROR or on a non-zero exit code replaces watching the job.
The data quality flags removed one observation, 2 September 2024, when the haor was completely cloud-covered.
The 30 usable observations trace the haor’s year:
Dry season: open water fell from 31% of the clear area on 1 January to 3.6% at the end of January.
Boro rice: land NDVI peaked at 0.70 in mid-March.
Monsoon gap: there is no usable optical observation from June to August.
Flood: after the monsoon the haor was 97.7% water on 17 October, then drained to 47% by 31 December.
The monsoon gap is the limit of optical monitoring here. Notebook 08_11 fills it with Sentinel-1 radar, which sees through cloud.
Summary and exercises
Key ideas
Put science in pure functions, input/output at the edges, and configuration in the environment.
Tests that need no network run in seconds anywhere; quality gates make style and coverage automatic.
CI runs the same checks on every change on a clean machine; a red build blocks a bad merge.
Containers fix the environment; keep images small, pinned and non-root, and keep data and secrets out.
Scheduled jobs must be idempotent (safe to repeat), observable (structured logs, exit codes) and write atomically; version their outputs.
What we did
The project: a package (342 lines), tests (190 lines), a Dockerfile and two workflows.
Quality gates: lint, format and 12 tests with 93% coverage, all passing; a deliberately broken offset rule was caught by a test in 1.3 s.
Git and CI: git history for code and data; the CI workflow’s checks run locally, green.
Container: the Dockerfile passes 8 best-practice checks. It is built by CI; Docker is not available here.
Scheduled runs: three simulated runs against Planetary Computer (16, 0 and 15 new days) gave a 31-row table without duplicates, logged as JSON lines.
Science: Tanguar Haor was 97.7% open water in October 2024 and 3.6% in January; Boro rice NDVI peaked at 0.70 in March.
Exercises
Add a test that fails if a day’s water_fraction changes by more than 0.5 between consecutive usable observations, and decide whether that is a data error or a real event.
Add HAOR_RESOLUTION=10 support to the CI matrix as a second configuration. What does it cost in run time?
Make the pipeline write a small STAC catalogue (one item per observation) next to the table.
Replace the GitHub Actions schedule with a Kubernetes CronJob manifest that runs the container image.
Send an alert (an issue, an email or a chat message) when the monitor workflow fails, using the job’s failure status.
References
Kim, G., Humble, J., Debois, P. & Willis, J. (2021). The DevOps Handbook, 2nd ed. IT Revolution.