[RFC] Property-based testing for Postgres

Started by Greg Burd22 days ago6 messageshackers
Jump to latest
#1Greg Burd
greg@burd.me

Hello,

This proposes an opt-in, default-off, property-based testing (PBT) [1]https://www.cis.upenn.edu/~bcpierce/papers/icse24-pbt-in-practice https://antithesis.com/docs/resources/property_based_testing/ https://drmaciver.com/notebook/2018/12/etymology-of-property-based-testing/ https://wyounas.github.io//2026/10/26/finding-bugs-in-duckdb-with-property-based-testing/
framework under src/test/prop/, gated on an external PBT engine
(libhegel) the way TAP tests are gated on Perl and IPC::Run. I want to
gauge interest before polishing and then proposing it for commit.

Why bring it up at all? It finds bugs and then reduces the reproduction
to the minimal set of steps required to trigger them. It does this by
exploring the various properties that could be acceptable and comparing
them against some "oracle", like comparing qsort() vs my_sort() across
all list sizes and various contents each time checking that the two
functions produce the same outcome.

I was excited to find that Hegel[2]https://hegel.dev/ https://github.com/hegeldev https://github.com/hegeldev/hegel-cpp is a credible open source
implementation of this testing technique. Credible in my book means
fast, functional, and efficient when finding the minimal reproduction.

Also, I had used PBT back in the early 2000s with Erlang when it first
arrived on the scene from Quviq called QuickCheck and it was a huge
help.

So I took it for a spin and it did indeed find real new bugs as well as
help me to classify commit-fest items listed as "ready for commit" into
"really ready" or "there's still an identifiable issues to work out." I
can think of other ways to use this, but I'll stick to the basics in
this intro email.

Rather than argue the value of PBT in the abstract, here is what this
method turned up on recent master:

- A SERIALIZABLE write-skew that commits after a savepoint swallows the
serialization failure (SSI doom-before-error). Reproduced fail-on-master,
pass-on-fix:
/messages/by-id/165342c0-0c75-461e-b334-b997639ad48d@aphyr.com

- IS NOT DISTINCT FROM join selectivity off by ~4900x with NULLs on both
sides (BUG #17545):
/messages/by-id/17545-a0ca4de888953169@postgresql.org

- var_eq_const undercounting by stopping at the first matching MCV entry
under a nondeterministic collation:
/messages/by-id/tencent_A15A9D89A86F2E4B086ABA462578B9B64307@qq.com

I posted the independent reproductions into those threads; the finds are
the authors', the corroboration is from this method. These are just a
few examples.

At its core, the PBT engine generates many inputs, and on failure
shrinks to a minimal counterexample and prints a seed that replays it.

A property is an ordinary C function that draws inputs and asserts an
invariant; a round-trip, an algebraic law, or a differential check that
two ways of computing the same answer agree.

What's in this RFC (the two attached patches) is deliberately small:

0001: build plumbing. --with-hegel for configure, -Dprop_tests for meson.
Default off. When enabled, a missing libhegel is a hard error (so the
opt-in cannot silently do nothing); when not enabled, nothing in the tree
changes and CI is unaffected.

0002: the harness (pg_prop.c/.h, a thin binding to libhegel's stable C ABI,
a TAP driver) plus a curated set of six single-table areas whose oracles
are round-trips and algebraic laws: base64, bytea, uuid, numeric,
interval I/O, jsonb round-trip (37 properties). These replay
deterministically from a printed seed, which is the property a buildfarm
test needs.

I have deliberately left out the larger parts I have locally, and I've
kept the first set of example property tests very basic as a place to
start not as examples of the best ways to apply this type of testing.
Testing the properties of UUIDs, bytea, etc. are not very exciting or
likely to find bugs at this stage of the game. They are meant as a
starting point for a discussion around adding PBT as a new category in
core.

I have explored much more complicated/useful PBTs such as a multi-table
query generator with a differential oracle (the thing that found the
selectivity bugs above), and a few hundred more scalar properties. This
is the generator where the interesting finds I pointed to earlier come
from, but its deep multi-table cases are not yet reproducible to the
standard a committed buildfarm test demands, so not in the proposed
patches/examples just yet.

I would rather present a small, sound, reproducible core and grow it
from there if there is interest.

So, is there appetite for a PBT framework in the tree on these terms? If
this is a non-starter, that is useful to know now. If it's worth
pursuing, I'd like to hear from you.

best,

-greg

[1]: https://www.cis.upenn.edu/~bcpierce/papers/icse24-pbt-in-practice https://antithesis.com/docs/resources/property_based_testing/ https://drmaciver.com/notebook/2018/12/etymology-of-property-based-testing/ https://wyounas.github.io//2026/10/26/finding-bugs-in-duckdb-with-property-based-testing/
https://antithesis.com/docs/resources/property_based_testing/
https://drmaciver.com/notebook/2018/12/etymology-of-property-based-testing/
https://wyounas.github.io//2026/10/26/finding-bugs-in-duckdb-with-property-based-testing/
[2]: https://hegel.dev/ https://github.com/hegeldev https://github.com/hegeldev/hegel-cpp
https://github.com/hegeldev
https://github.com/hegeldev/hegel-cpp

Attachments:

t254531_1
v1-0001-Add-build-plumbing-for-property-based-tests-src-t.patchtext/plain; charset=us-ascii; name=v1-0001-Add-build-plumbing-for-property-based-tests-src-t.patchDownload+93-34
v1-0002-Add-property-based-test-harness-and-a-curated-set.patchtext/plain; charset=us-ascii; name=v1-0002-Add-property-based-test-harness-and-a-curated-set.patchDownload+4193-2
#2Jeff Davis
pgsql@j-davis.com
In reply to: Greg Burd (#1)
Re: [RFC] Property-based testing for Postgres

On Mon, 2026-11-02 at 21:28 +0000, Greg Burd wrote:

I would rather present a small, sound, reproducible core and grow it
from there if there is interest.

So, is there appetite for a PBT framework in the tree on these terms?
If
this is a non-starter, that is useful to know now.  If it's worth
pursuing, I'd like to hear from you.

Thank you for including a README, that's helpful.

Right now it's about 4KLOC, which seems reasonable for a new testing
approach, if it's useful.

I'd suggest that we try to control the scope here. Some of these seem
like property testing for the sake of property testing:

+/*
+ * sqrt bound: S = sqrt(abs(X)) is non-negative and, since numeric
sqrt rounds
+ * to a scale, S*S must not exceed abs(X) by more than a small
relative-plus-
+ * absolute tolerance.  This is a sound one-sided bound: an exact sqrt
gives
+ * S*S = X, and the only slack is the rounding of the last digit, well
within
+ * abs(X) * 1e-10 + 1e-10.  (The symmetric lower bound is scale-
dependent and
+ * fiddly to state soundly, so we assert only the clean upper side
plus the
+ * sign.)
+ */

It seems much more valuable to test, say, data structure invariants,
where we are likely to get creative with optimizations and might break
something. Is this property testing system good for that?

Also, how do you see this affecting the dev process? Do most people
need to be aware of this framework, adding new tests along with
features? Or would most of the value come from adding lots of new
property tests in a big batch, hoping to catch some longstanding bugs?

The timing of your proposal is not ideal, because AI is already finding
a lot of bugs, so finding more might be a thankless exercise until this
wave passes. So, if it doesn't get a lot of attention that may be the
reason why.

Regards,
Jeff Davis

#3Greg Burd
greg@burd.me
In reply to: Jeff Davis (#2)
Re: [RFC] Property-based testing for Postgres

On Monday, November 2nd, 2026 at 5:33 PM, Jeff Davis <pgsql@j-davis.com> wrote:

On Mon, 2026-11-02 at 21:28 +0000, Greg Burd wrote:

I would rather present a small, sound, reproducible core and grow it
from there if there is interest.

So, is there appetite for a PBT framework in the tree on these terms?
If
this is a non-starter, that is useful to know now. If it's worth
pursuing, I'd like to hear from you.

Hey Jeff,

Thank you for including a README, that's helpful.

Thanks for taking a look at the README.

Right now it's about 4KLOC, which seems reasonable for a new testing
approach, if it's useful.

Agreed, the first intro on the list was intentionally "bite-sized" so as
to test the waters.

I'd suggest that we try to control the scope here. Some of these seem
like property testing for the sake of property testing.

Again, just a demo at this point. None of the examples given were meant
to illustrate how PBT pays off in practice within Postgres. The intention
was to have very small examples to educate people on the concepts without
distracting them with too many details. The sqrt bound is exactly the kind
of thing I would drop before proposing a real set: it is a contrived
property on a scalar function, and the README itself warns against inventing
a formula to check a function. Point taken that the demo blurred the line.

+/*
+ * sqrt bound: S = sqrt(abs(X)) is non-negative and, since numeric
sqrt rounds
+ * to a scale, S*S must not exceed abs(X) by more than a small
relative-plus-
+ * absolute tolerance.  This is a sound one-sided bound: an exact sqrt
gives
+ * S*S = X, and the only slack is the rounding of the last digit, well
within
+ * abs(X) * 1e-10 + 1e-10.  (The symmetric lower bound is scale-
dependent and
+ * fiddly to state soundly, so we assert only the clean upper side
plus the
+ * sign.)
+ */

Yep, all those PBTs were basic examples I'd remove before offering up a
solid set of real tests for commit.

It seems much more valuable to test, say, data structure invariants,
where we are likely to get creative with optimizations and might break
something. Is this property testing system good for that?

Yes, and that is one area where I think it earns its place. I kept those
areas out of the first cut to keep it bite-sized, but they already exist
in the larger tree and are a better advertisement than the scalar ones:

- binaryheap: build a heap from random inserts, then assert pop order is
sorted, the first element is the minimum, and an incrementally-built heap
matches one built in a batch. That is a pure data-structure invariant on
binaryheap.c, no SQL involved.

- btree / index scans: a differential oracle, an index scan must return
the same rows as a sequential scan, over random tables, predicates, and
index kinds (btree, gin, gist, partial, expression, multicolumn). This is
exactly the "we got creative with an optimization and broke something"
case you describe: the property doesn't know the right answer, it only
knows the two paths must agree, so any divergence is a bug by construction.

The three live bugs I cited in the first mail are all of that shape: an
optimization computing a different result than the unoptimized path (SSI
serialization, outer-join selectivity, MCV selectivity). Differential
oracles over data structures and plans are the strong suit; the scalar
round-trips are the warm-up.

Also, how do you see this affecting the dev process? Do most people
need to be aware of this framework, adding new tests along with
features? Or would most of the value come from adding lots of new
property tests in a big batch, hoping to catch some longstanding bugs?

Good question, mostly the former. Today we have a few models for testing:
regression tests pin exact output for a known case, TAP scripts a scenario,
and isolation tests pin an interleaving. A PBT is a fourth model that sits
alongside them, it pins a property that must hold across an input space the
author can't enumerate by hand. It doesn't replace any of those; the README
is explicit that a PBT belongs only where a disagreement is unambiguously a
bug, and that a good unit test beats a contrived property.

So no, most people would not need to think about it for routine work. The
value concentrates where someone is doing something risky (a new scan
optimization, a data-structure rework, a selectivity change) and wants a
standing net under that specific area. The person making that change adds
the property, the same way they'd add a regression test, because they know
what invariant their change must not break. The big-batch "mine for
longstanding bugs" mode does happen (that's how the three bugs surfaced), but
I'd treat that as a bonus, not the pitch; the durable value is the standing
differential net on the tricky areas, maintained by the people who work in
them.

The timing of your proposal is not ideal, because AI is already finding
a lot of bugs, so finding more might be a thankless exercise until this
wave passes. So, if it doesn't get a lot of attention that may be the
reason why.

I'd argue the opposite.

This style of testing fits AI well: the properties are easy for an agent to
write, cheap to run, and the counterexample the engine shrinks to is exactly
the artifact an agent can consume to produce a fix, a minimal input plus a
seed that replays it.

An LLM alone can find bugs, but it does so by reading and reasoning, which
burns tokens fast and doesn't reproduce, a property test is the opposite.
The engine does the searching deterministically and cheaply, and the agent
spends its tokens only on the one minimal case that actually failed. So I
see PBT less as "more bugs to triage during the AI wave" and more as the
scaffolding that makes the AI wave efficient, reproducible, and long-term
helps collapse and manage that wave..

What I'm actually hoping people latch onto is using this as the foundation
for harnesses that eliminate *categories* of bugs in tricky code, not one
test per bug, but one property that rules out a whole class of bugs.

Ideally the division of labor is: humans and LLMs write ordinary regression
tests for the specific things they know a change must get right, and they
write a property for the invariant that change must never violate. Then the
engine, not the person, finds the input that breaks it. The human states
the law; the machine hunts down the counterexample. That split is where I
think the leverage is, and it's why I'd rather land a small sound core now
and grow it than wait for the wave to pass.

Regards,
Jeff Davis

best.

-greg

#4Jeff Davis
pgsql@j-davis.com
In reply to: Greg Burd (#3)
Re: [RFC] Property-based testing for Postgres

On Tue, 2026-11-03 at 14:34 +0000, Greg Burd wrote:

It seems much more valuable to test, say, data structure
invariants,
where we are likely to get creative with optimizations and might
break
something. Is this property testing system good for that?

Yes, and that is one area where I think it earns its place.

For something in core, I think a few strong examples in this area would
be the best route.

This style of testing fits AI well: the properties are easy for an
agent to
write, cheap to run, and the counterexample the engine shrinks to is
exactly
the artifact an agent can consume to produce a fix, a minimal input
plus a
seed that replays it.

AI can create tons of these tests, and that some percentage will find
bugs that others have missed, which is valuable. But carrying all those
tests in core doesn't sound very appealing to me.

Let's first look at the high-value testing areas and get feedback from
the people that work in those areas.

Regards,
Jeff Davis

In reply to: Jeff Davis (#2)
Re: [RFC] Property-based testing for Postgres

On Mon, Nov 2, 2026 at 5:33 PM Jeff Davis <pgsql@j-davis.com> wrote:

The timing of your proposal is not ideal, because AI is already finding
a lot of bugs, so finding more might be a thankless exercise until this
wave passes. So, if it doesn't get a lot of attention that may be the
reason why.

I conservatively estimate that I have 25 unreported correctness bugs
found by AI. No doubt some of those are invalid issues, but most
aren't.

Most of the worst bugs have already been fixed. But there are still at
least a handful of fairly bad ones. Or at least issues that have nasty
consequences when users encounter them. Some of these will be hard to
fix because they involve pretty fundamental assumptions. For example,
it's possible for deletion of LP_DEAD bits to delete items that are
still required by a transaction that started during recovery, after
recovery ends. See the attached repro.

I find it extraordinary that we're living in a world where I have an
unpublished B roll of bugs that includes issues as tricky and
potentially severe as this one. But we are. Naturally this has
significantly changed how I assess what to work on.

--
Peter Geoghegan

Attachments:

t254531_5
0001-Simple-deletion-on-a-promoted-standby-trusts-the-old.patchapplication/octet-stream; name=0001-Simple-deletion-on-a-promoted-standby-trusts-the-old.patchDownload+98-1
#6Greg Burd
greg@burd.me
In reply to: Peter Geoghegan (#5)
Re: [RFC] Property-based testing for Postgres

On Mon, 2026-11-03 at 08:28 -0800, Jeff Davis wrote:

For something in core, I think a few strong examples in this area would
be the best route.

AI can create tons of these tests, and that some percentage will find
bugs that others have missed, which is valuable. But carrying all those
tests in core doesn't sound very appealing to me.

Let's first look at the high-value testing areas and get feedback from
the people that work in those areas.

Yes, complete agreement here.

I'm not proposing to carry a few hundred generated properties; the value isn't
the volume, it's a small number of properties that stand as a net under code
that is hard to get right and likely to be re-optimized. The scalar
round-trips in the first patch were a mechanism demo.

So, concretely, three examples in high-value areas, as the starting point for
the "get feedback from the people who work there" step you're asking for:

Example 1: a data-structure model test (binaryheap)

binaryheap.c is the shared binary heap behind merge append and the executor's
bounded sorts. A heap has a crisp model, a priority queue, so the test drives
the real structure and a trusted reference (a sorted array) through the same
random operations and requires they agree on a few properties:
* pop order is sorted,
* binaryheap_first() is the minimum, and
* a heap built incrementally (sift-up each) and one built with binaryheap_build
(Floyd's bulk heapify) pop in the same order.

Those are two different algorithms that must behave identically. A regression
test pins one hand-chosen input, this asserts the equivalence across every
input including the empty heap, a single element, all-equal values, and
INT_MIN/INT_MAX.

The hope is that if someone rewrites binaryheap_build it will fail the day it
diverges from the properties that define it and when it fails there will be a
minimal array and seed that reproduce the issue.

Example 2: a plan-results differential (nbtree index scans)

The skip-scan work (92fe23d93aa plus the long tail of follow-up fixes;
premature array advancement, NULLs advancing skip arrays, DESC commute
strategy, row-compare robustness) made nbtree scan-key handling a dense bug
surface.

The property is a differential oracle: the same query under a forced index scan
and under a forced sequential scan must return the same rows, over a
randomly-shaped index (column count, ASC/DESC, NULLS FIRST/LAST) and a predicate
mixing equality, inequality, IN-lists, and IS NULL, with a random ORDER BY
direction for backward scans.

The nice thing about PBT is that it does NOT need to know the right answer. It
never computes an expected row set, it only knows the two paths must agree, so
any divergence is a bug in the index path by construction. Plan results, not
plan shape EXPLAIN output is cost-model dependent and is not a target; the
rows a correct plan returns are.

Example 3: transaction isolation across concurrent backends (isolation)

MVCC is the case everyone agrees is tricky and worth a net, so this example
keeps that framing but drives it the way the bugs actually arise. Two
concurrent backends, each property asserting the documented guarantee of an
isolation level:

- under SERIALIZABLE, the classic write-skew pair (each txn reads a set and
writes based on it) cannot both commit. At least one must fail with a
serialization error. A phantom is likewise prevented;
- under REPEATABLE READ, a txn's repeated read returns the same value even
after a concurrent committed update (snapshot stability);
- under READ COMMITTED, a new statement sees a concurrently committed change
and not an uncommitted one;
- two txns locking rows in opposite order deadlock with exactly one victim.

The oracle is the documented guarantee, not a generated reference: a
SERIALIZABLE anomaly committing, a REPEATABLE READ snapshot shifting, or a
deadlock taking down both sessions would each be a serious isolation bug. The
interleaving between the two sessions is driven randomly, so this asserts the
guarantee holds across the schedules a fixed isolation spec does not enumerate.
An isolation spec pins one hand-written interleaving, this explores many.
The SSI write-skew in my first mail is exactly a multi-session schedule bug,
and ser_write_skew_prevented here is the property that corresponds to it. It
rounds out the set with a third distinct area: a data structure, an
access-method optimization, and concurrent transaction semantics.

These three are in the attached v2. It drops v1's scalar round-trips entirely
(base64, bytea, uuid, and the rest. The mechanism demo you rightly flagged)
and keeps only the plumbing plus binaryheap, nbtree, and isolation. But I
don't think the patch is the interesting artifact right now. The question you
posed is: which areas are worth a standing property, according to the people who
own them. The heap, nbtree, and the MVCC/SSI machinery are my guesses;
the committers in planner selectivity, SSI, and the executor would each have a
better one.

On Peter's reply in this thread: that's the case in point. A B-roll of
unreported correctness bugs, and the LP_DEAD-deletion-on-a-promoted-standby one
he attached is exactly the shape where a property earns its place, it's a
correctness invariant (an index must not drop an item a recovery-era snapshot
still needs) that no fixed regression test is likely to stumble onto, and it
lives in the nbtree/recovery area I'm pointing at. I'm not claiming the PBT
engine would have found that specific bug; I'm saying the area it's in is
precisely the "high-value, hard to get right, worth a net" category, and that
the AI wave Peter describes is the argument for having reproducible nets rather
than against it: a shrunk, seed-replayable counterexample is the artifact that
turns "AI found something odd" into "here is the minimal case, fixed."

AI can create tons of these tests ... But carrying all those tests in
core doesn't sound very appealing to me.

Agreed.

The discipline the README argues for is the guard against that. A property
belongs in core only where a disagreement is unambiguously a bug (a round-trip,
a model, two paths that must agree), and a good unit test beats a contrived
property. The job is to keep the set small and sound, not to let a generator
flood it. I'd rather land binaryheap, nbtree, and isolation, see whether the
heap, nbtree, and isolation folks find them worth keeping, and let that set
the bar for anything else.

best.

-greg

Attachments:

t254531_6
v2-0001-Add-build-plumbing-for-property-based-tests-src-t.patchtext/x-patch; name=v2-0001-Add-build-plumbing-for-property-based-tests-src-t.patchDownload+93-39
v2-0002-Add-property-based-test-harness-and-a-few-high-va.patchtext/x-patch; name=v2-0002-Add-property-based-test-harness-and-a-few-high-va.patchDownload+3276-2