PostgreSQL 18Dev & Eng
Content type: Hands-on
8 min read
pg_orca extension supports PostgreSQL 18 and 19 on the same codebase without a fork
An open-source query optimizer now compiles and runs on both PostgreSQL 18 and PostgreSQL 19.0 without needing a separate branch per version.
- Reading
- 8 min
- Tables
- 1
- Code
- 3
An open-source query optimizer now compiles and runs on both PostgreSQL 18 and PostgreSQL 19.0 without needing a separate branch per version.
The extension that refused a fork
pg_orca is the adaptation of the ORCA optimizer, originated in Greenplum and now maintained as an open-source extension, for modern PostgreSQL. With every new major release, the same question came up: is it worth maintaining a separate branch per version? According to the post published on the pg_orca blog, on Planet PostgreSQL, the answer for PostgreSQL 19.0 was no: the same codebase compiles and runs on both PostgreSQL 18 and PostgreSQL 19.0.
The decision is not cosmetic. Maintaining two branches of an extension that handles query optimization means duplicating tests, duplicating bug fixes, and, sooner or later, letting one of the versions fall behind. What makes the single codebase viable is the architecture behind pg_orca: ORCA's Cascades engine, the Memo structure, and the transformation rules never see a single internal PostgreSQL struct. All communication goes through a translation layer called DXL, which converts the parser's Query into ORCA's own representation and returns a PlannedStmt in the format that the executor and EXPLAIN expect.
Where PostgreSQL 19 actually made changes
This design translated into concrete numbers: the entire PostgreSQL 19 adaptation fit into 13 #if PG_VERSION_NUM >= 190000 blocks, spread across just 6 files. None of them are inside ORCA's core; all of them sit in the thin translation layer and in the wrappers that touch PostgreSQL's structures directly.
| File | Number of #if | What changed in PostgreSQL 19 |
|---|---|---|
pg_orca.cpp | 2 | planner_hook_type gained ExplainState *es, passed through to the fallback |
compat/executor/dyn_scan.c | 2 | ExecInitScanTupleSlot() and table_beginscan() gained new parameters |
gpopt/gpdbwrappers.cpp | 4 | Int8GetDatum() removed; CacheRegisterSyscacheCallback() signature changes; GetIndexAmRoutine() returns a const pointer |
CTranslatorDXLToPlStmt.cpp | 2 | PlannedStmt::resultRelations (list) became resultRelationRelids (bitmapset) |
CTranslatorDXLToScalar.cpp | 2 | WindowFunc::ignore_nulls restored; new SubPlan naming scheme |
CTranslatorScalarToDXL.cpp | 1 | Capturing ignore_nulls directly from the parser tree |
Some changes didn't even need a version guard: PointerIsValid() was removed from c.h, but a plain NULL works in both versions; access/attmap.h and <climits> had to start being included explicitly because PostgreSQL 19 stopped pulling them in transitively. For Int8GetDatum(), removed because the PostgreSQL core no longer called it (upstream commit d4a080b8a1), the team opted for an #ifndef shim that reproduces the original function without touching any call site.
Tracking PostgreSQL 19 from 19devel all the way to version 19.0, passing through 19beta4, also brought a classic beta-cycle trap: the SQL/PGQ feature (RTE_GRAPH_TABLE) existed for a while in 19devel, received a defensive fallback check in CTranslatorQueryToDXL, and was reverted before 19beta4, breaking the pg_orca build until the version guard was removed. It's the kind of pitfall that only shows up for whoever keeps a CI job running against the development version throughout the entire beta cycle, not just on release day.
Compiling clean isn't the same as running correctly
After pg_orca.so loaded without errors on PostgreSQL 19 and planned simple joins and aggregations, the test suite (test/test.sh --orca-tests) revealed two assertion failures that halted execution, both cases where a convention valid in PostgreSQL 18 became illegal in the new version.
The first was in table_beginscan(): PostgreSQL 19 split scan flags into internal bits (SO_INTERNAL_FLAGS, filled in by table_beginscan() itself) and caller hints (user_flags), with an assert that forbids overlap between the two sets. The pg_orca code was still passing PostgreSQL 18's old flags as user_flags, and all of them now belonged to the internal set. The fix was to pass 0: PostgreSQL 19 already fills in the same bits on its own.
The second was subtler. PostgreSQL 19 added Result::result_type to distinguish Result nodes that gate a subplan from those with no child at all, such as a One-Time Filter: false. Since MakeNode(Result) zeroes out the struct by default and RESULT_TYPE_GATING equals zero, every childless Result generated by ORCA ended up with the wrong type and crashed EXPLAIN. Classifying these nodes as RESULT_TYPE_UPPER fixed the crash but opened up a side effect: EXPLAIN started printing a spurious Replaces: Aggregate line, because ORCA removes from the range table the relation folded into the plan. The final fix was to mark these nodes as RESULT_TYPE_SCAN, which satisfies both the assert and the suppression rule in explain.c.
A third adjustment came from the new EXPLAIN label scheme for SubPlan: PostgreSQL 19 started automatically prefixing "SubPlan " or "InitPlan ", expecting SubPlan.plan_name to already carry something like exists_1 or any_2. Since pg_orca's translator was still filling plan_name with the old full string, the printed result became a duplicate. The fix generates the new format on PostgreSQL 19 while keeping the old format on PostgreSQL 18, and the tests started normalizing both before comparing.
IGNORE NULLS and RESPECT NULLS without losing the optimizer
PostgreSQL 19 implements the SQL:2003 RESPECT NULLS / IGNORE NULLS clause in window functions such as lag, lead, first_value, last_value, and nth_value. The first version of support in pg_orca was conservative: a walker detected WindowFunc::ignore_nulls != 0 and pushed the entire query back to PostgreSQL's native planner. It worked, but it was costly: every analytical query on PostgreSQL 19 using IGNORE NULLS lost ORCA's optimization entirely.
The team reverted this fallback and carried null handling (null_treatment) end to end through the DXL pipeline. The subtle part wasn't the XML serialization, it was deduplication in ORCA's Memo structure. If CScalarWindowFunc::HashValue() and Matches() ignored m_null_treatment, a query requesting both treatments of the same column would silently collapse into a single window function:
SELECT id,
lag(val) IGNORE NULLS OVER (ORDER BY id) AS prev_non_null,
lag(val) RESPECT NULLS OVER (ORDER BY id) AS prev_raw
FROM readings;Including m_null_treatment in the hash and comparison kept the two expressions distinct in the Memo, while PostgreSQL's runtime validation (WinCheckAndInitializeNullTreatment()) keeps running normally: an invalid call like rank() IGNORE NULLS OVER (...) still produces the exact error PostgreSQL would generate without ORCA. In PostgreSQL 19's window test suite, this single change eliminated more than 50 IGNORE NULLS differences at once.
Four bugs that only PG 19's regression suite revealed
Running test/test.sh --pg-tests against REL_19_STABLE executes 223 of PostgreSQL's own regression tests with pg_orca active. Every new major release expands this suite with tougher edge cases, and PostgreSQL 19's new tests found four real bugs in pg_orca, three of which were also present in PostgreSQL 18:
- Nested LATERAL join: a query with double LATERAL that the native planner resolves in 8 ms took about two minutes under ORCA, because it scanned
tenk150 thousand times. The cause wasCNormalizer::FPushable(), which refused to push a predicate into a join when it referenced an external column not produced by that specific child. Two fixes inCNormalizer.cpp, propagating external references inPushThruJoinandPushThruSelect, brought the time down to about 15 ms. - Wrong result in correlated HashAggregate: when an external parameter appears only inside the arguments of a hashed aggregation, pg_orca never filled in
Agg.aggParams. PostgreSQL's executor uses this field to decide whether it needs to discard the hash table between executions of a correlated subplan; without it, ORCA reused a stale hash and returned values from a previous execution. - DISTINCT with multiple sort keys: an
array_agg(DISTINCT r ORDER BY r USING <, r USING *<)has two sort keys for a single argument. An inherited line truncatedaggdistinctto the aggregation's number of arguments, discarding the second key and tripping an assert innodeAgg. - Redundant sort on a column already fixed to a constant: in
SELECT a, b FROM test WHERE b = 10 ORDER BY b DESC, ORCA inserted an unnecessarySortonb, becauseCOrderSpec::FSatisfiesdidn't check the constant constraint already derived for the column. Fixed in both PostgreSQL 18 and 19.
Where PostgreSQL 19.0 stands today, in numbers
Against the complete parallel_schedule suite of PostgreSQL 19.0 (223 tests), pg_orca records zero server crashes. With the --ignore-plans option (which compares only results, not the printed plan format), 216 of the 223 tests pass.
Of the 7 remaining failures, 6 were already known plan-behavior differences in PostgreSQL 18, in subselect, aggregates, join_hash, select_parallel, windows, and stats. The seventh is a curiosity: PostgreSQL 19's join test expects the native planner to reject a FULL JOIN with no mergeable or hashable condition, but ORCA knows how to plan this case and returns the correct 9 rows; the difference shows up because pg_orca doesn't produce the error the test expects, not because the result is wrong.
Reproducing the build on PostgreSQL 19
For anyone maintaining a PostgreSQL extension who wants to test this kind of cross-version compatibility, the build command doesn't change between versions, only the PG_CONFIG it points to:
cmake -S . -B build-pg19 -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DPG_CONFIG=/usr/pgsql-19/bin/pg_config
cmake --build build-pg19 -j "$(nproc)"
cmake --install build-pg19To keep the regression workspace of a second build isolated, the BUILD_DIR variable separates the test directories:
BUILD_DIR=$PWD/build-pg19 test/test.sh --orca-testsThe lesson for extension maintainers
The pg_orca case is an argument for architecture, not luck: isolating the entire surface of contact with PostgreSQL's internal structures behind a translation layer is what allows trading 13 adjustment points in 6 files for an entire fork. For those developing extensions that read Query, PlannedStmt, or system catalogs directly, the opposite path, spreading that access throughout the business logic, is what turns every major release into a migration project.
The other lesson, a more uncomfortable one, is that compiling clean against the new headers guarantees nothing: of the most serious problems found, the two assertion failures and the four regression-suite bugs, none showed up during the build. All of them only surfaced by running real queries and comparing plans and results line by line. Keeping a CI pipeline against PostgreSQL's development version throughout the entire beta cycle, as the pg_orca team did, is what brought these bugs to light before release, not afterward in production.
Translated from the Brazilian Portuguese original · Read the original
PostgreSQL 16 Swaps SIGKILL for SIGABRT to Preserve Core Dumps of Stuck Processes
Two parameters added to PostgreSQL 16 swap the signal that terminates processes during a crash for SIGABRT, trading silent discard for forensic evidence, at a disk and availability cost that the documentation summarizes but does not quantify.





