What Broke While Building a Flood-Risk Pipeline
Most of what went wrong while I built a flood-risk pipeline was not the model. It was a grid placed a few metres south of its terrain, a check that passed on a number that was not a number, a river level compared with a threshold measured from a different zero, and a paid cloud run that completed and was then paid for again. None of these raised an error. Each produced output that looked right, and each was found by accident or by a check written afterwards.
This post collects eight of them. For each: what happened, in general terms, why it survived, and the check that would have caught it. Each one comes with a small runnable version, the bug beside its fix, in a script you can download. The details of the original system are left out; the mechanisms are not specific to it, and most apply to any pipeline that turns gridded data into numbers someone acts on.
This is the last post in a series on flood models, after verification and validation, held-out terrain, climate allowances and satellite checks.
In short
- Grid code fails at edges and corners: an index that rounds towards zero, a coarsened grid anchored at the corner its crop moved.
- Gates fail on values they never expected: NaN passes "fail if over the limit", and Python's
max()skips it. - Numbers fail on what they are measured from: a level and a threshold on different datums, a budget over the wrong clock.
- Paid work fails on its preconditions: disk space, and inputs nobody checked were there.
1. The edge that int() let in
A service answered "what is the depth at this point?" by turning a coordinate into a grid cell and checking the cell was inside the grid. The index was computed with int():
i = int((x - x0) / (x1 - x0) * cols)
if 0 <= i < cols: ...
The index the code needs is a floor:
i = โ (x โ x0) / (x1 โ x0) ยท n โ, โโ0.5โ = โ1, int(โ0.5) = 0
int() truncates towards zero, so a point just west of the grid, at a fractional index between โ1 and 0, gets index 0 and passes the check. The service reported it inside, with the edge cell's depth:
East and south of the grid the index runs past the last cell and the check catches it, so only two edges were wrong. And there was a test for exactly this case. It asked for a point a hundred kilometres away, where any arithmetic, right or wrong, gives an index far out of range. The test could not fail.
What catches it: math.floor instead of int for any index computed by scaling, and boundary tests at the boundary: just outside each of the four edges, within a cell of the boundary, not somewhere obviously elsewhere.
2. A number that was not a number
A water-budget check failed a simulation when its imbalance exceeded a limit:
if abs(closure) > allowed: fail()
A run went unstable at its boundary and its budget came out as NaN. Every comparison with NaN is false, so abs(nan) > allowed is false and the run passed. The same limit, written three ways:
| Gate written as | x = 0.001 | x = 0.01 | x = NaN |
|---|---|---|---|
| fail if abs(x) > 0.003 | pass | fail | pass |
| fail if not (abs(x) <= 0.003) | pass | fail | fail |
| pass only if finite and abs(x) <= 0.003 | pass | fail | fail |
Python hid it a second way: max() skips a NaN that follows a finite value, so the run's peak volume looked healthy too. A search for the same pattern found it in several more checks across the code.
What catches it: check that a value is finite before comparing it, and fail by name when it is not. Where that is awkward, write the comparison so NaN lands on the failing side: not (abs(x) <= limit), never abs(x) > limit. And give every gate a test that feeds it NaN and infinity.
3. A level and a threshold from different zeros
A comparison of modelled and observed floods took a river gauge's level and compared its peak with the gauge's published "typical high" level. Usually both are on the same datum. At one gauge, the level was reported above sea-level datum and the threshold above the gauge's own zero, which sat about a metre higher:
At that gauge the result was two false "hits" in a scorecard. A related shortcut, taking the first measure a gauge lists, picked one that never reports at some gauges. It was found because a different reading looked implausible, not by any check.
What catches it: carry the datum with every level, like a unit, and refuse a comparison whose two sides cannot be shown to share one:
@dataclass(frozen=True)
class Level:
metres: float
datum: str # "sea level" or "gauge zero"
def exceeds(reading, threshold, offsets):
to_sea = lambda v: v.metres + offsets[v.datum] # KeyError on an unknown datum
return to_sea(reading) > to_sea(threshold)
A test fixture with one gauge that lists both datums keeps the rule honest.
4. A grid three metres south of its terrain
Coarsening a terrain grid by averaging blocks of cells is routine. With the usual array slicing, grid[:n * f, :n * f], the kept cells are the top-left ones, and in the common ESRI grid format row 0 is the north. When a side is not a whole number of blocks, the dropped strip is at the south:
Code that copied the fine grid's south-west corner onto the coarse grid put it south of its terrain by that strip, a fraction of a coarse cell. Nothing failed. A shift smaller than a cell looks right on a map, and most boxes were a whole number of blocks, so the bug appeared only in the odd one. When it was found, the same shape turned up in other places.
What catches it: a round-trip test on synthetic ground whose every cell holds its own centre's coordinates, coarsened by the real code with a side that is not a whole number of blocks. Each coarse cell must then hold the centre its header says it has:
rows, f, cell, north = 9, 2, 5.0, 1045.0 # 9 rows: not a whole number of 2-row blocks
fine = [[north - (r + 0.5) * cell] * 4 for r in range(rows)] # each cell holds its centre's northing
coarse, header = coarsen_with_header(fine, f) # the code under test
centre = header.south + 0.5 * f * cell # the bottom row's centre, according to the header
assert abs(coarse[-1][0] - centre) < 1e-9
Anchored at the south-west corner, the bottom row's centre is one fine cell off and the assertion fails. And a rule for every new coarsening: anchor at the corner the crop keeps, or refuse sides that do not divide.
5. Tests that could not fail
The far-away test above was not the only one. One test asserted a threshold was well clear of a danger zone, with an exemption written into the assertion for the one value that would have failed it, and the measured value was that value. Another checked a mask by reading the centre of an empty region, where a window averages to zero whether the mask works or not, so it passed with the mask deleted.
They survived for the simplest reason: they passed. A test that passes for the wrong reason looks exactly like one that passes for the right one.
What catches it: mutation testing. Break the code on purpose, one change at a time, and see which tests notice. Tools such as mutmut do this for Python automatically; on one function, doing it by hand is enough:
Applied by hand to the grid index from the first section, with five boundary tests (W and E for west and east of the grid, cell 0 for a point inside the first cell), the far-away test passes every broken version:
| Mutant | 100 km W | 0.5 m W | 0.5 m E | East edge | Cell 0 |
|---|---|---|---|---|---|
| None (original) | passes | passes | passes | passes | passes |
| floor to int | missed | caught | missed | missed | missed |
| floor to round | missed | caught | missed | missed | missed |
| < cols to <= cols | missed | missed | caught | caught | missed |
| 0 <= to 1 <= | missed | missed | missed | missed | caught |
Each edge test catches at least one mutant; the far-away test catches none. Without the edge tests, all four would have shipped. Read which mutants survive, not only how many: a survivor is either a gap in the tests or code that can never run, and the two need opposite responses.
6. A full disk during paid cloud runs
A batch of simulations ran on rented cloud machines, one per run, each uploading its results to cloud storage, from which they were downloaded to a laptop. The laptop's disk filled. The machines kept solving and uploading, and the downloads failed. The runner treated a failed download as a failed run, so several runs were paid for twice. One was also misjudged: a check that read the run's log to confirm how it had run found no log, because the log never arrived, and reported a run that had worked as one that had not.
What catches it: a free-space check before each launch and each download, which pauses the queue instead of starting machines whose results cannot land:
free = shutil.disk_usage(download_dir).free
if free < expected_bytes * 1.5:
pause_queue("disk nearly full: not starting runs whose results cannot land")
A download that resumes from storage instead of re-running: a run that finished and uploaded is done. And a rule for every check that reads evidence: refuse to judge when the evidence is missing, rather than reading its absence as a verdict.
7. A paid launch whose input was not there
A change to a batch of runs swapped one area for another. The new cases were uploaded; the area they read was not. The machines started, looked for their input, and stopped within minutes. Nothing was solved, and the check that would have found it beforehand did not exist: uploading verified each case's own files, and the launch trusted the upload. The one new thing in the run list was the one thing nothing listed.
What catches it: before any machine starts, list every object each case reads and confirm it exists, refusing the launch by naming the case and the missing object:
missing = {case: [p for p in paths if p not in stored]
for case, paths in inputs.items()}
missing = {c: m for c, m in missing.items() if m}
if missing:
raise SystemExit(f"not launching, inputs missing: {missing}")
It costs one listing call per case and saves a wasted boot per case.
8. A budget over the wrong clock
A water-budget check compared rain in with water out and water stored. Several runs failed it by small margins, and the natural reading was that the simulation did not conserve water. It did. The simulator's reported clock ran slightly behind the time it had actually stepped, so the check integrated rain over a shorter span than the one the water had moved in. In the lab, with 40% of the rain leaving as outflow, a 1% drift in the clock makes a perfectly balanced run look 0.6% out, with more water accounted for than fell, twice an illustrative 0.3% limit:
imbalance = (rain ร t โ outflow ร t โ stored) / (rain ร t)
with t taken from the clock instead of the stepped time. The budget closed exactly when computed on the simulator's own steps.
What catches it: a check that also compares its time base with the simulator's own count of steps, and refuses to judge when they diverge by more than its limit:
stepped = n_steps * dt
if abs(clock - stepped) / stepped > limit:
raise ValueError("clock and step count disagree; not judging the budget")
A check that cannot tell "water lost" from "the instrument's time base drifted" should not be allowed to say "water not conserved".
What the eight have in common
| Mistake | Why it survived | The check that catches it |
|---|---|---|
| int() let a point in | Wrong on two edges of four; the test used a point far away | floor(), and tests just outside every edge |
| NaN passed a gate | Every comparison with NaN is false | Check finite first; feed every gate NaN and infinity |
| Level and threshold on two datums | Right at most gauges | Carry the datum like a unit; refuse mixed comparisons |
| Grid anchored at the wrong corner | A shift smaller than a cell looks right; most boxes divided evenly | A round-trip test with a side that does not divide |
| Tests that could not fail | They passed | Mutation testing, and reading which mutations survive |
| Full disk in paid cloud runs | The machines kept working | Free space before launch; resume downloads; refuse to judge on missing evidence |
| Input never uploaded | The upload checked only each case's own files | List and confirm every input before any machine starts |
| Budget over the wrong clock | Small deficits look like lost water | Compare the clock with the step count; refuse to judge when they diverge |
Every one of them produced a plausible result, and every fix was a check that could fail on the case that mattered: the edge, the NaN, the second datum, the odd-sized box, the missing file. The habit that would have caught most of them early is the one that runs through all eight: before trusting a check, show it failing on purpose.
A small lab you can run
Each of the eight mechanisms has a toy version beside its fix. Download the lab (zip), then run python -m pytest -q. Its nine tests cover the eight mechanisms and the mutation table, each showing the bug and then the fix, for example that int(-0.5) puts a point inside the grid and math.floor(-0.5) does not.
Limits of this post
- The examples are reduced to their mechanism. The original cases involved more code, and some had more than one cause.
- The numbers in the figures are toy inputs, chosen to show each mechanism, not measurements from the original system.
- Eight lessons are a selection. The log they come from has many more, most of them variations on the same few shapes.