Testing¶
postpile's tests are organized as a pyramid. The backends are held to differential oracles: a compiled POST function must match CPython; where the arithmetic is exact, the C backend and the other available backends (QBE, LLVM) must agree byte-for-byte. Because POST Python is a typed subset of Python, the reference implementation of any POST function is the function itself, run under CPython; no golden values to hand-maintain.
On top of those sits a third, borrowed layer: LPython's test corpus, whose programs assert their own results and must hold both interpreted and compiled.
The test pyramid¶
Tests live in three tiers under tests/, fastest first:
| Directory | Tier | Marker | Scope |
|---|---|---|---|
tests/a_unit/ |
unit | unit |
Fast, isolated: checker, IR, backend emit |
tests/b_integration/ |
integration | integration |
Component interactions, file I/O, the C ABI |
tests/c_e2e/ |
e2e | e2e |
Full source → shared-library → call workflows |
The tier directory sets the marker. tests/conftest.py inspects each collected item's path in pytest_collection_modifyitems and adds unit, integration, or e2e accordingly: you never decorate a test by hand. The three markers are declared in pyproject.toml under [tool.pytest.ini_options], and testpaths covers both tests and src (docstring tests).
make test # everything (pytest)
uv run pytest -m unit # one tier by marker
uv run pytest -m "integration or e2e"
uv run pytest tests/a_unit/ # or by directory
The third instrument: AddressSanitizer¶
There is a fourth marker, asan, and it is the one exception to "the marker comes
from the directory": tests/b_integration/test_asan.py sets it on the module, and
addopts = "-m 'not asan'" deselects it from the default run.
make asan # the memory-model program set, instrumented
uv run pytest -m asan # the same thing directly
Why it is opt-in and why it exists at all. Each program in the set is
compiled and linked with -fsanitize=address on the available backends, which
takes a few minutes, too slow for an inner loop. It exists
because the instruments above each have a blind spot, symmetrically (pygo
arbitration A70):
| the mistake | the stdout differential | a retention counter | ASan |
|---|---|---|---|
| a leak | passes: a leak has no stdout | fails | (no leak detector on macOS) |
| an over-release | passes, unreliably: a freed block reads back plausibly | passes: the count reached zero correctly | fails |
The bottom row comes from a real case: a guard deleted on purpose printed the right answer five times on three backends while reading freed memory, and only ASan named it. So a container of refcounted elements (where a use-after-free actually lives) has no guard behind it without this file.
The program set is chosen by ownership position; each entry states its reason in the source. The rule for adding one: a new position where a reference is taken or released gets a program; a new expression form that reaches an existing position does not.
The two oracles¶
Both oracles are provided by postpile.testing.differential. Given POST source, a function name and an argument tuple, it runs the function under CPython and under each backend and returns the results keyed by runtime:
from postpile.testing import differential
SRC = """
from postyp import Int64
def m(a: Int64, b: Int64) -> Int64:
return a % b
"""
def test_mod(tmp_path):
results = differential(SRC, "m", (-7, 3), tmp_path)
# results == {"cpython": 2, "c": 2, "qbe": 2}
reference = results.pop("cpython")
for name, value in results.items():
assert value == reference, f"{name}={value} != cpython={reference}"
- Semantic oracle: each backend's result must equal
results["cpython"]. This is the primary correctness check: the compiled code must mean the same thing as the Python it was compiled from. - Parity oracle: the backends must agree with each other (byte-identical where the arithmetic is exact). This catches a backend that is self-consistently wrong.
Signature
differential(source, func, args, tmp_path, *, backends=("c", "qbe"))
builds source once per backend via build_source, loads the shared
library with ctypes, and calls the exported pp_<func> symbol. The ctypes
argtypes/restype are derived from the function's postyp annotations, so
it supports scalar POST functions only (int/float/bool). Array and ufunc
kernels are exercised through the NumPy ABI in the integration suite instead.
Lower-level helpers load_namespace(source) and
build_and_call(source, func, args, tmp_path, backend=...) are available
when you need one runtime at a time.
The c_e2e golden-program corpus¶
tests/c_e2e/programs/ holds whole POST modules; tests/c_e2e/test_programs.py drives them. A PROBES table maps each program file to the (func, args) calls that exercise it. Each probe runs through CPython, C and the other available backends (QBE when its binary is on PATH, LLVM when llvmlite is installed):
PROBES = {
"floor_and_mod.py": [
("modulo", (-7, 3)), ("modulo", (7, -3)),
("fdiv", (-7, 2)), ("fdiv", (7, -2)),
],
"int_pow.py": [("ipow", (2, 10)), ("ipow", (5, 3))],
...
}
The probes that matter most are the mixed-sign cases (negative floor-division, modulo, and integer **), exactly where a naive C lowering diverges from Python semantics. Float comparisons use math.isclose (rel_tol=abs_tol=1e-12); integers and bools must match exactly.
The ratchet¶
The corpus is designed to grow ahead of the compiler (the p2w, "parked to working", pattern). WORKING = set(PROBES): a program with probes must pass on the available backends; a BuildError there is a hard failure. Programs not yet supported are xfailed, so the corpus documents the target surface before the compiler reaches it. A second ratchet, test_program_compiles, parametrizes all of programs/*.py (including the array/ufunc kernels that aren't scalar-probeable, like vec_square.py and gu_dot.py) across the available backends and checks that each still compiles.
Adding a golden program¶
- Drop a POST module into
tests/c_e2e/programs/, e.g.saturating.py. It is picked up automatically bytest_program_compilesand must compile on every available backend. - To check the module's runtime behavior, add scalar probes to
PROBES:
That makes it a WORKING program: each probe must agree across CPython, C and the other available backends (QBE, LLVM). No expected values are written down; CPython supplies them.
Why both oracles earn their keep
The semantic oracle caught a real bug the parity oracle alone could not:
integer % was lowered with C's truncated remainder, while Python's is
floored. On -7 % 3 C returns -1 while CPython returns 2. But
the C and QBE backends agreed on -1, so parity was green. Only the
check against CPython flagged the divergence. It is now pinned by
test_int_mod_follows_python_floor_semantics, which sweeps mixed-sign
operands so % stays consistent with the Python-floored //.
The shared scalar corpus¶
tests/corpus.py holds one list of scalar cases (a POST function named k and the inputs to run it on). The backends run all of it, checked against CPython. Two harnesses drive the same list: test_corpus_native.py goes through ctypes for C, LLVM and QBE, and tests/c_e2e/test_wasi_target.py calls the same functions in a WebAssembly reactor, the C backend's output built for wasm32-wasip1, in wasmtime.
It exists because the three backends used to keep private corpora, and none was a superset of the others. Only QBE ran sub-word arithmetic. Only LLVM ran while/for reductions. The inputs that catch a broken fmod lived only in the WASM file, which is why QBE's mod_f case held (7.5, 2.0) and (-7.0, 2.0), two values that are exact under the wrong formula and therefore proved nothing. Each backend's corpus held only the mistakes found in that backend.
Two rules keep it sound:
divergesnames, in a sentence, why a case does not match CPython: POST'sint ** negative intis0where Python promotes to float and gives0.5; a case that relies on integer wraparound is pinned to release, because postyp's arithmetic does not wrap. A case may only skip the CPython oracle by saying why. A test fixes the set of such cases, so a new silent divergence fails the suite.- On the WebAssembly target the oracle is CPython built for WebAssembly (ADR 0079): Pyodide under node, which
make pyodideinstalls intotests/pyodide/. Without it the tests use the host's CPython, andHOST_LIBMintest_wasi_target.pynames the cases where the host's libm and the target's round differently, as strict expected failures;WASI_GAPSnames what the target cannot run yet. If a gap closes, the test fails and tells you to delete the entry. An unexamined skip is a coverage hole that reads as a pass.
The LPython corpus¶
The directory tests/c_e2e/programs/lpython/ holds 40 of LPython's integration tests, translated from LPython's dialect into POST Python by tools/harvest_lpython.py with LPython's own assertions unchanged. They are BSD-3-Clause (© 2019-2020 Triad National Security, LLC); the licence sits beside them and each file records that it was modified.
test_lpython_corpus.py runs each program in both settings below, which must both hold:
- under CPython, because POST Python is a subset of Python: the module is imported and its entry points called;
- on every backend, in a subprocess, because a violated assertion aborts the process and would take the test runner down with it.
Each program names the entry points in the docstring (Entry points: test_loop_01, test_loop_02). LPython drives assertions from module-level calls, which POST has no place for, so the harvester lifts them out.
These programs are a different kind of oracle from the ones above. They exposed eleven compiler defects that the whole existing suite had missed, among them for i in range(10, 0, -1) running zero times and a loop's else clause being dropped from the program entirely. Others were round(0.5) returning 1.0, a ternary evaluating the arm it did not take (recursing forever), a libm call passing a Float32 to a symbol that takes a double, and fib written with a returning if/else failing to build at all on two backends.
Nearly all of them had passed a green parity oracle: backends agreeing with each other is not correctness; three backends can (and did) agree on the same wrong answer. Programs that check their own results, written in shapes the project's tests never tried, find these.
To re-run the harvest (it needs an LPython checkout in sandbox/lpython/):
python tools/harvest_lpython.py # classify, write nothing
python tools/harvest_lpython.py --write # emit the ones that build and run clean
It translates mechanically and hands the result to the compiler: postpile's own diagnostics say why each rejected program is out of reach, so there is no second definition of "what POST supports" to keep in sync.
Build modes in the suite¶
The suite runs in debug, by taking the default. A suite that does not exercise the shipped default is not testing the product, and here it is not a neutral choice: it is required by the one true oracle in the repo. The LPython corpus is driven almost entirely by assert, and its compiled driver checks nothing but the exit code. In a release build those assertions are elided (spec §5.1), so all 40 programs would compile to functions that do nothing observable and pass vacuously: the exact failure mode that made fixing assert worthwhile in the first place. test_the_corpus_is_built_in_a_mode_that_keeps_its_assertions makes a future flip of that default fail the suite, so the corpus cannot be silently hollowed out.
Some tests pin mode=BuildMode.RELEASE explicitly; the docstring of each says why:
- The test checks that arithmetic wraps. Wrapping is the release contract; a debug build diagnoses the same arithmetic as overflow and aborts. Both contracts matter, so each of these has a debug twin in
test_integer_overflow.pythat checks the abort, out of process. - The test is about codegen. The QBE strength-reduction and unroll tests ask whether the shipped codegen fires. The codegen that ships, and that the published benchmark numbers measure, is release. (They also check that the passes still fire in a debug build, which they only do because the bounds checks are hoisted out of the loop body.)
A test that touches the checks must allow for these:
- A failed check aborts. Compiled POST has no exceptions, so a violated assertion, an out-of-bounds index and an integer overflow all report on stderr and
abort(). That takes the pytest worker down with it, so the failure cases must run in a subprocess and assert on the exit status. dlopencaches by path. The build mode is part of the artifact filename for exactly this reason: building the same function in debug and then in release into one directory would otherwise hand back the debug library both times, and pass, because the answers usually agree.
The suite under a non-default setting¶
An executable's int grows past 64 bits by default (ADR 0075); a user can choose the 64-bit int with --no-grow-ints. The suite runs the default; pytest --no-grow-ints runs it with the other choice, by making in-process build_executable calls default to the 64-bit int (a test that passes grow_ints= keeps its value, and a ppc build run as a subprocess keeps the CLI's default). Run it before a release: a test of the growing int that relies on the default fails under it, and is expected to; anything else that fails is a defect of the 64-bit int.
Linux¶
Development happens on macOS; a release is also tested on Linux x86_64. Without a Linux machine, a container does it; this streams the working tree in, so it needs no shared directory:
COPYFILE_DISABLE=1 tar cf - --no-xattrs --exclude .venv --exclude sandbox \
--exclude __pycache__ --exclude dist . |
docker run --rm -i --platform linux/amd64 python:3.14 bash -c '
mkdir /work && cd /work && tar xf - && pip install -q uv &&
uv sync -q --all-extras --all-groups &&
uv run --no-sync pytest -n 4 -q tests &&
uv run --no-sync pytest -m asan -q tests/b_integration/test_asan.py &&
make clean-room'
COPYFILE_DISABLE=1 and --no-xattrs keep macOS's ._* metadata files out of the archive; the corpus tests would collect them as programs. Linux differs from macOS where the C toolchain does. GNU ld resolves libraries in link order. glibc's malloc reuses freed memory without zeroing it; glibc's abort() does not flush stdio. A shared object's calls resolve in the process's global scope unless it is linked -Bsymbolic. glibc's headers also declare names macOS's do not (accept-then-wrong §84).
Prerequisites and CI¶
The suite runs on Python 3.14 or 3.15 and stops before collecting on any other interpreter: each compiled program is held to the CPython running the suite, and compiled programs follow 3.14's error messages and annotations. CI runs on sourcehut (.builds/): ubuntu 24.04 with every extra, and alpine for musl libc.
End-to-end tests need a C compiler; the suite discovers cc/clang/gcc and skips (needs_cc) when none is found. QBE probes and QBE compile-checks are included only when the qbe binary is present, so a machine without QBE runs a correct C-only subset. See Benchmarking for the performance side of the same corpus, and the IR reference and C / QBE backend pages for what the oracles are validating.