Bash pipefail: why our tests passed when one had crashed
By default bash gives a pipeline the exit status of its last command, so a crash before a pipe to grep goes unseen. What set -o pipefail and PIPESTATUS change.

If your test script pipes a command's output into something else, to drop noisy log lines with grep, keep a copy with tee or tidy it with sed, it can report a crashed test as a pass. Bash gives a pipeline the exit status of its last command. When the test dies and grep carries on printing, the pipeline succeeds.
That's what happened to the tests for our member area, the part of our site where customers sign in to their account. A suite crashed on a template error, and the test runner said every suite had passed. So did the deploy that called it, which is the whole reason a test runner exists.
The fix starts with one line. This article covers that line, then what the same script taught us afterwards: a test that depended on the date, a release that ran the same tests twice, and how to prove a speed-up changed nothing. Each comes with the code and the timings, measured on our own machines.
A pipeline reports only its last command#
On 9 September 2026 the runner was a handful of lines. Two suites printed JSON log lines among their results, so their output went through grep to drop any line starting with a brace. This is the script, shortened:
#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
echo "=== ownership ==="; python3 test_ownership.py 2>/dev/null
echo "=== app ==="; python3 test_app.py 2>/dev/null | grep -Ev '^\{'
echo "=== forms ==="; python3 test_forms.py 2>/dev/null | grep -Ev '^\{'
Two things in it hid the crash between them. test_app.py died on a template error after 238 checks had passed. Its traceback went to standard error, which the script sent to /dev/null, so the last thing on screen was a passing check. And its non-zero exit status went nowhere, because the pipeline's status was grep's, and grep had found lines to print. In the code under test, the member area's main page was returning a server error. The runner said everything was fine.
set -e doesn't help here, and that's the part that catches people out. It stops a script when a command fails, and a pipeline counts as one command with one status. The Bash manual's section on pipelines says that status is the last command's "unless the pipefail option is enabled". The first suite, which wasn't piped, would have stopped the script. The two that were piped couldn't.
Make any failure in a pipeline fail the pipeline#
The fix went in the same day, in three parts:
set -euo pipefail
fails=0
run() {
echo; echo "=== $1 ==="
# 2>&1 so a traceback is visible; the grep only drops log lines
if python3 "$2" 2>&1 | grep -Ev '^\{'; then :; else fails=$((fails + 1)); fi
}
run app test_app.py
run forms test_forms.py
# ...one line per suite
if [ "$fails" -gt 0 ]; then echo "!!! $fails suite(s) FAILED"; exit 1; fi
echo "All suites passed."
pipefailgives a pipeline the status of the rightmost command that failed, so a crashed suite fails it even whengrepsucceeds. It's listed with the other options of thesetbuiltin.2>&1instead of2>/dev/nullkeeps the traceback on screen, so a failure says why it failed.- An explicit count. Wrapping each suite in
ifstopsset -eending the script at the first failure, so every suite still runs and the summary says how many failed.
It was proved the plain way: break a template on purpose, run the script, and watch it exit with 1.
Watch for one side effect. grep exits with 1 when it selects no lines, as its manual says, so with pipefail on, a suite that printed only log lines would read as a failure. That fails safe, but it's a reason to keep the status you care about apart from the filter. Bash's PIPESTATUS array holds each command's status from the last pipeline if you need one in particular.
A test passed for a week, then failed on a Monday#
The runner grew from four suites to 80. On 12 October 2026 one of them, the suite for the sign-up form on our articles, failed for a reason that had nothing to do with the code it tests.
The form has an hourly ceiling on confirmation emails, for everybody together. The code counts the sign-ups asked for in the last hour:
# The application: has this hour's ceiling been reached?
busy = insights_asked_since(time.time() - 3600) >= INSIGHTS_PER_HOUR
To prove nobody gets past the ceiling, the test set it to the number of sign-ups already made, tried one more, and expected a refusal. But it set the ceiling from every row in the test's database, not from the last hour's. Earlier in the same file, one sign-up was dated at a fixed moment a few hours before 8 am on Monday 12 October 2026, to test the Monday morning digest. The test was written on 5 October, when that Monday was a week away.
A row dated in the future is inside "the last hour" by that count, so for a week every row counted, the ceiling matched, and the test passed. Once the real clock passed that row's time by an hour, the row dropped out of the count, the ceiling sat one above it, the extra sign-up got through, and the check failed. The code hadn't changed. The date had. The fix makes the test ask the same question as the code:
# Before: every row the test had made
INSIGHTS_PER_HOUR = len(insights_all())
# After: the same window the code counts
INSIGHTS_PER_HOUR = insights_asked_since(time.time() - 3600)
The same file had another. A check that the confirmation email doesn't repeat the visitor's name, "Jo", searched the whole email, including a link with a random token in it, and now and then the token contained "Jo". It now looks for "Jo" as a word. When a test fails now and then, look for the clock and for randomness first.
The release ran the same 80 suites twice#
Speed came next, measured before anything changed. A release here builds the site, runs tools/check, which checks everything that can be checked without touching the live systems, then runs the member area's deploy script. On 12 October 2026 the build took 3 seconds and tools/check took 117, of which the member area's tests were 107. Then the deploy's first step ran the same 80 suites again, on the same code, for another 107 seconds.
Both runs had a reason. tools/check is what you run after every change, and the deploy refuses to go on if a test fails, because a broken member area locks customers out of their own account. So the aim was a faster check, run once, and no weaker than before.
Run the suites side by side, then print them in order#
Running suites in parallel is only safe if they share nothing. Each of ours keeps its data in its own temporary directory, so they can. The usual bash tool for a simple job pool is wait -n, which waits for the next background job to finish. It arrived in bash 4.3, and the bash that comes with macOS, which we develop on, is 3.2. So the runner hands the work to xargs instead:
# "run NAME FILE" now only records the suite; nothing runs yet
names=(); files=()
run() { names+=("$1"); files+=("$2"); }
run app test_app.py
run forms test_forms.py
# ...80 in all
jobs="${SC_TEST_JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)}"
[ "$jobs" -gt 8 ] && jobs=8
out="$(mktemp -d "${TMPDIR:-/tmp}/sc-tests.XXXXXX")"
trap 'rm -rf "$out"' EXIT
# Each suite writes its output and its exit status to files of its own
i=0
for f in "${files[@]}"; do printf '%s %s\n' "$i" "$f"; i=$((i + 1)); done |
xargs -P "$jobs" -n 2 sh -c 'python3 "$2" >"$0/$1.out" 2>&1; echo $? >"$0/$1.rc"' "$out"
# Read back in the listed order; a missing status counts as a failure
fails=0; i=0
for name in "${names[@]}"; do
echo; echo "=== $name ==="
grep -Ev '^\{' "$out/$i.out" || true
if [ "$(cat "$out/$i.rc" 2>/dev/null || echo 1)" != 0 ]; then fails=$((fails + 1)); fi
i=$((i + 1))
done
xargs -Pruns up to that many commands at once, one per processor and never more than eight, and-n 2gives each two arguments: a number and a file name.-Pisn't in POSIX, but GNU xargs and the BSD xargs that macOS uses both have it.- In
sh -c '…' "$out", the first argument after the script becomes$0, so every job knows the output folder, and the pair fromxargsarrives as$1and$2. - Each suite's own status goes to a file.
xargs's exit status can say at most that something failed, not which suite, and underset -eit would end the script before anything was printed.grepnow only filters a file for display, so its status no longer matters.
Output is printed suite by suite, in the listed order, once every suite has finished, with failures counted exactly as before. SC_TEST_JOBS=1 runs them one at a time, which is the first thing to try if a suite ever fails only beside the others.
Eight at a time, all 80 suites take 34 seconds. That's the floor: the slowest suite, test_app.py, takes about 34 seconds on its own. Part of that is deliberate. Its fake billing system waits 0.15 seconds on every call, because one test proves the member area makes its calls in parallel by timing them, and a fake that answered instantly couldn't prove it.
Skip the second run only when the code is identical#
Faster tests still ran twice. The obvious shortcut, a flag that says "tests passed", is dangerous: change one line after tools/check and the deploy would ship code nobody tested. So a pass records a fingerprint of exactly what was tested:
#!/usr/bin/env bash
# code-key: a fingerprint of exactly the code in this checkout
set -euo pipefail
cd "$(dirname "$0")/../.."
{
git rev-parse HEAD
git diff HEAD --binary
git ls-files -o --exclude-standard | while IFS= read -r f; do
printf '%s\n' "$f"; shasum -a 256 < "$f"
done
} | shasum -a 256 | cut -d' ' -f1
Each part covers what the one before it misses. The commit alone ignores uncommitted edits. git diff HEAD adds those, staged or not, and --binary includes the actual binary changes instead of a line saying the file differs, so two different edits to one image can't look alike. (If your repository uses textconv or an external diff driver, add --no-textconv --no-ext-diff.) Neither sees a file not yet added to git, so the third part hashes the name and contents of every untracked file that isn't ignored. One changed byte in any tracked file, or in any untracked file git isn't told to ignore, changes the fingerprint. Ignored files, such as a local settings file, aren't covered, so keep anything that changes how tests behave out of the ignore list or add it to the fingerprint.
When every suite passes, the runner writes the fingerprint into the repository's .git folder. The deploy works out a fresh one and compares them. Shortened:
# deploy, step 1: tests, unless they passed for exactly this code
passed="$(git rev-parse --git-dir)/sc-tests-passed"
if [ -f "$passed" ] && [ "$(cat "$passed")" = "$(./account/tests/code-key)" ]; then
echo " all suites passed for this exact code already; not run again"
elif ! ./account/tests/run >"$log" 2>&1; then
echo "TESTS FAILED -- not deploying."; tail -30 "$log"
exit 1
fi
Building it turned up a bug of its own, and a useful one. The runner moves into the tests folder when it starts, and the first version called the fingerprint script by its path from the top of the repository. From where the runner was, that path didn't exist, the error was thrown away, and the fingerprint was written empty. An empty fingerprint never matches a real one, so the deploy ran the tests again. The bug cost time, not safety, because the comparison was built to fail towards doing the work. The runner now calls the script from where it really is, and writes nothing if the fingerprint comes back empty.
We accepted one limit: the fingerprint covers the code, not the machine. Here both runs happen on the same machine, minutes apart. If yours run on different machines, add the toolchain versions to the fingerprint.
Prove the faster runner still stops a release#
A faster runner that misses failures is worse than a slow one, which is where this article started. So a suite was broken on purpose, and the run had to fail and stop the release. It did.
Before the change, the build, tools/check and the deploy's own test run came to 227 seconds (3 + 117 + 107) before the deploy had copied anything. After it, a full release of the site took 68 seconds.
| Measured | Before | After |
|---|---|---|
| The member area's 80 test suites | 107 s, one at a time | 34 s, eight at a time |
| Test runs in a release | 2, so 214 s | 1, unless the code changed in between |
| A full release of the site | More than 227 s | 68 s |
| Making 38 quote PDFs | 33 s | 12 s |
Prove a speed-up changed nothing, and that both sides are right#
The last row comes from the same day's work on the PDFs our quotes are sent as. They're made with WeasyPrint, which turns an HTML page into a PDF. A batch of 38 took 33 seconds on a developer's machine, close to a second each, and a profiler showed about 60% of that going on a single job: reading and working through the site's main stylesheet, more than 10,000 lines, from scratch for every PDF.
Each linked stylesheet is now parsed once per process and kept, keyed by its address and its file's modified time, so a deploy that changes the file gets it read afresh. The page goes to WeasyPrint without its <link> tags, and the kept stylesheets are handed in with one shared font configuration: CSS with @font-face rules needs a FontConfiguration, as WeasyPrint's guide to HTML and CSS objects shows. Because it's shared, a lock is held while each PDF is made.
# Parsed once per process, keyed by address and file time (shortened)
def _sheet(weasyprint, href, font_config):
key = (href, modified_time_of(href))
if key not in _kept:
_kept[key] = weasyprint.CSS(url=urljoin(BASE_URL, href), url_fetcher=fetch,
font_config=font_config, media_type="print")
return _kept[key]
with _lock:
sheets = [_sheet(weasyprint, href, fonts) for href in LINK_RE.findall(html)]
doc = weasyprint.HTML(string=LINK_RE.sub("", html), base_url=BASE_URL,
url_fetcher=fetch)
return doc.write_pdf(stylesheets=sheets, font_config=fonts)
One subtlety: stylesheets handed in this way count as the reader's styles, not the page's, and in the CSS cascade the page's rules normally win. Nothing on the quote page competes with them except style attributes, which win either way, so the result should be the same. "Should be" isn't proof.
The test makes the same quote page both ways, the new way and WeasyPrint's own, turns every page of both PDFs into images with pdftoppm from Poppler, and compares them:
# The same page, made both ways (shortened)
kept = quote_pdf.render(html, title="t", number="Q-2026-0001")
plain = weasyprint.HTML(string=html, base_url=BASE_URL, url_fetcher=fetch).write_pdf()
# ...each PDF turned into one PNG per page with pdftoppm -r 60 -png
check("the same number of pages", len(pages["kept"]) == len(pages["plain"]) > 0)
check("every page identical, pixel for pixel",
all(open(a, "rb").read() == open(b, "rb").read()
for a, b in zip(pages["kept"], pages["plain"])))
check("and in our own font", "Plus-Jakarta-Sans" in pdffonts_out and "Serif" not in pdffonts_out)
The last check matters as much as the others. A comparison proves two things are the same, not that either is right: if the fonts failed to load both ways, both PDFs would fall back to the same serif font and match perfectly. So the test also asks pdffonts which fonts are really in the PDF. Without pdftoppm installed, the test says it skipped rather than claiming a pass.
That kind of gap turned up for real. The stylesheet draws the ticks and dashes in a quote's lists as small SVG pictures written into the CSS as data:image/ URLs. The fetcher WeasyPrint uses for our PDFs serves only our own files from disk and refuses everything else, which is what WeasyPrint's security guidance suggests for a renderer that could otherwise reach local files. It refused the pictures too, so every quote PDF showed empty circles where the ticks should be, identically both ways. The fetcher now accepts data:image/ URLs, which carry their own content and fetch nothing. Every other data: URL is still refused, and the test checks that other sites and paths climbing out of the site's folder are too.
If you copy this pattern, use WeasyPrint 70.0 or later. Earlier versions, affected by CVE-2026-55073, could bypass a restrictive url_fetcher through the stylesheets and xmp_metadata options when an application passes them anything an attacker can influence. Hand in only stylesheets you've built yourself, with your own fetcher, from your own files.
Thirty-eight quotes took 33 seconds before and 12 after. The pixel comparison now runs in every release, so any later change to how PDFs are made has to pass it too.
What we learned#
- Look at every pipe in your test scripts. Put
set -o pipefailin any bash script whose exit status means something, and keep standard error during a test run. - Prove your test runner fails. Break something on purpose and watch the runner, and whatever calls it, stop. Repeat whenever the runner changes.
- Treat a missing result as a failure. Read the status each job wrote, and count no status as a failed one.
- Make a test ask the code's question. If the code counts the last hour, so does the test. Fixed dates and random values are where tests that fail now and then come from.
- Skip work only on an exact match. A fingerprint of the commit, uncommitted changes and untracked files takes moments. "The tests passed recently" isn't the same thing.
- Build shortcuts that fail towards doing the work. The empty fingerprint cost one extra test run, not an untested deploy.
- Time each step before changing any. The biggest saving, not running the tests twice, only showed once every step had a number.
- When you prove a speed-up changed nothing, check one thing is right as well. Two outputs that are equally broken compare as identical.
What's next#
One saving was measured and left for later: the deploy makes about 40 SSH connections at 0.59 seconds each, and sharing one connection measured 0.27 seconds a call, about 13 seconds a release. The 34-second floor stays, because the slowest suite's timing test needs its slow fake.


