← All posts

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:

A row of eight grid cells numbered 0 to 7 starting at x equals 0, with a point at x equals minus 0.5 west of the grid. int of minus 0.5 is 0, cell 0, reported inside; floor of minus 0.5 is minus 1, refused A point half a metre west of the grid, indexed two ways 0 1 2 3 4 5 6 7 x = 0 x = โˆ’0.5 int(โˆ’0.5) = 0: cell 0, reported inside, with the edge cell's depth floor(โˆ’0.5) = โˆ’1: refused by the bounds check, correctly outside East of the grid both give an index past the last cell, so only the west and north edges were wrong.
Figure 1. The bug lived on two of four edges, which is why it survived.

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 asx = 0.001x = 0.01x = NaN
fail if abs(x) > 0.003passfailpass
fail if not (abs(x) <= 0.003)passfailfail
pass only if finite and abs(x) <= 0.003passfailfail

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:

Two bars on a vertical scale. A reading of 3.10 m above sea-level datum, and a threshold of 2.90 m above a gauge zero that sits 1.01 m above sea-level datum, so 3.91 m above sea level. Compared as plain numbers, the reading exceeds the threshold; on one datum it is 0.81 m below A river level and a flood threshold, measured from different zeros sea-level datum 0 m gauge zero +1.01 m reading 3.10 m above sea level threshold 2.90 m above gauge zero 3.91 m above sea level As plain numbers 3.10 > 2.90 is an exceedance; on one datum 3.10 < 3.91, 0.81 m below the threshold.
Figure 2. Both numbers were right. Their comparison was not.

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:

A fine grid of nine rows with the bottom row marked as dropped. Two coarse grids of four block rows: one anchored at the south-west corner, which sits one fine row too far south; one anchored at the north-west corner, aligned with the terrain Coarsening 9 rows by 2 keeps the north rows and drops the southern strip fine grid, 9 rows dropped anchored at the south-west: wrong anchored at the north-west: right dashed: the terrain's north edge Copying the fine grid's south-west corner onto the coarse grid moves it south by the dropped strip.
Figure 3. Copying the fine grid's south-west corner moves the coarse grid south by the strip that was dropped.

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:

A flow: the code is copied with one small change, a mutant; the tests run on each mutant; a mutant the tests fail is killed; one they pass survives, and a survivor means a gap in the tests or code that can never run Mutation testing: break the code on purpose and see which tests notice The code mutant 1: int() mutant 2: <= cols mutant 3: 1 <= i Run the tests on each mutant Tests fail mutant killed Tests pass mutant survives A survivor means a gap in the tests or code that can never run. The two need opposite responses: a new test, or deletion.
Figure 4. A test suite is measured by the mutants it kills, not by its pass rate.

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:

Mutant100 km W0.5 m W0.5 m EEast edgeCell 0
None (original)passespassespassespassespasses
floor to intmissedcaughtmissedmissedmissed
floor to roundmissedcaughtmissedmissedmissed
< cols to <= colsmissedmissedcaughtcaughtmissed
0 <= to 1 <=missedmissedmissedmissedcaught

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.

Two time axes. Stepped time runs 10 hours. The simulator's clock reads 9.9 hours at the same point. Rain integrated over the clock's span is 1% short, and the balance shows a 0.6% gap that is not lost water A water budget integrated over the simulator's clock instead of its stepped time stepped time 10.00 h reported clock 9.90 h Rain 10 mm/h, outflow 4 mm/h, 60 mm stored after 10 stepped hours: the balance closes exactly. Over the clock's 9.90 h: rain 99.0 mm, outflow 39.6 mm, stored 60 mm. That is 0.6 mm more than fell.
Figure 5. The water balance was right on stepped time and wrong on the clock.

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

MistakeWhy it survivedThe check that catches it
int() let a point inWrong on two edges of four; the test used a point far awayfloor(), and tests just outside every edge
NaN passed a gateEvery comparison with NaN is falseCheck finite first; feed every gate NaN and infinity
Level and threshold on two datumsRight at most gaugesCarry the datum like a unit; refuse mixed comparisons
Grid anchored at the wrong cornerA shift smaller than a cell looks right; most boxes divided evenlyA round-trip test with a side that does not divide
Tests that could not failThey passedMutation testing, and reading which mutations survive
Full disk in paid cloud runsThe machines kept workingFree space before launch; resume downloads; refuse to judge on missing evidence
Input never uploadedThe upload checked only each case's own filesList and confirm every input before any machine starts
Budget over the wrong clockSmall deficits look like lost waterCompare 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.