One tree, two major versions: adapting pg_orca to PostgreSQL 19
How pg_orca added PostgreSQL 19.0 support in 13 #if guards across 6 files — without forking a branch — plus native SQL:2003 IGNORE NULLS support and the real optimizer bugs uncovered by PG 19's regression suite.
Porting a query optimizer extension to a new PostgreSQL major release sounds
like a risky rebase. An optimizer sits on PostgreSQL's sharpest internal seam:
it reads parsed Query trees, interrogates the syscache and statistics, and
hands back a PlannedStmt that the executor and EXPLAIN expect to obey
every undocumented invariant of that release.
pg_orca now supports both
PostgreSQL 18 and PostgreSQL 19.0 from the same source tree, with no
separate branch. Everything version-specific fits in 13
#if PG_VERSION_NUM >= 190000 guards across 6 files. Not a single one of
them lives inside ORCA's Cascades engine.
Getting the compiler happy, though, was only the first third of the work. The
second third was what broke once queries actually ran and EXPLAIN tried to
print them, plus wiring PostgreSQL 19's new SQL:2003 RESPECT/IGNORE NULLS
window clauses natively through ORCA instead of punting them to fallback. The
last third — and the most valuable — was running PostgreSQL 19's full 223-test
regression suite, which caught four real optimizer and translator bugs that
had been hiding in plain sight.
Thirteen #ifs, zero inside ORCA
Because ORCA talks to PostgreSQL strictly across the DXL boundary (Query →
DXL → ORCA → DXL → PlannedStmt), the Cascades search engine, Memo,
transformation rules, and cost model do not include PostgreSQL's internal
headers. Every PostgreSQL 19 API change stopped at the thin translation and
wrapper layer:
The first pass was purely mechanical: cross-compile against both PG 18 and PG
19 headers until pg_orca.so built cleanly on both. Every break was a
PostgreSQL 19 internal cleanup:
| File | #ifs | What changed in PostgreSQL 19 |
|---|---|---|
pg_orca.cpp | 2 | planner_hook_type gained ExplainState *es; forward it to prev_planner_hook / standard_planner on fallback |
compat/executor/dyn_scan.c | 2 | ExecInitScanTupleSlot() gained (uint16) eflags for lazy EXPLAIN-only slots; table_beginscan() gained user_flags |
gpopt/gpdbwrappers.cpp | 4 | Int8GetDatum() removed from postgres.h; CacheRegisterSyscacheCallback() takes SysCacheIdentifier instead of int; GetIndexAmRoutine() returns const IndexAmRoutine * |
CTranslatorDXLToPlStmt.cpp | 2 | PlannedStmt::resultRelations (List *) became resultRelationRelids (Bitmapset *); Result::result_type added |
CTranslatorDXLToScalar.cpp | 2 | WindowFunc::ignore_nulls restored; PG 19 SubPlan names (exists_1, any_2, …) |
CTranslatorScalarToDXL.cpp | 1 | WindowFunc::ignore_nulls captured from parser tree |
A few smaller cleanups did not even need version guards: PointerIsValid()
disappeared from c.h (plain NULL checks work on both versions), and
access/attmap.h and <climits> had to be included explicitly after PG 19
stopped pulling them in transitively. For Int8GetDatum() — removed in
upstream commit d4a080b8a1 because core never called it — gpdbwrappers.cpp
provides a byte-identical #ifndef Int8GetDatum shim so every call site stays
untouched.
Tracking PostgreSQL 19 from 19devel through 19beta4 to 19.0 also brought
a classic pre-release twist: SQL/PGQ (RTE_GRAPH_TABLE) landed in 19devel,
got a defensive fallback check in CTranslatorQueryToDXL, and was then
reverted upstream before 19beta4, breaking the beta build until we dropped
the guard. That is the real value of keeping a PG 19 job live in CI throughout
the beta cycle.
Compiling was not running
With those guards in place, pg_orca.so loaded cleanly on PostgreSQL 19 and
planned simple joins and aggregates. Then we ran test/test.sh --orca-tests
and immediately tripped two PostgreSQL 19 assertions — both cases where a PG
18 convention silently became illegal.
1. table_beginscan() internal vs. user flags
Our first PG 19 compile fix passed PG 18's old default flags
(SO_TYPE_SEQSCAN | SO_ALLOW_STRAT | SO_ALLOW_SYNC | SO_ALLOW_PAGEMODE) to
table_beginscan() in compat/executor/dyn_scan.c. The moment ORCA picked a
DynamicTableScan over a partitioned table, table_beginscan_common()
aborted on an assertion.
PostgreSQL 19 split scan flags into internal bits (now SO_INTERNAL_FLAGS,
supplied by table_beginscan() itself) and caller hints (user_flags), and
asserts (user_flags & SO_INTERNAL_FLAGS) == 0. Every single one of PG 18's
defaults had moved into SO_INTERNAL_FLAGS. Passing 0 fixed the crash: PG
19 fills in the exact same scan bits internally.
2. Result.result_type and the "Replaces:" surprise
PostgreSQL 19 added Result::result_type to distinguish gating Result nodes
(which have a subplan and apply a one-time filter above it) from one-row or
folded Result nodes (which have no child). explain.c asserts that any
childless Result is not RESULT_TYPE_GATING.
Because MakeNode(Result) zero-initializes the struct — and
RESULT_TYPE_GATING is 0 — every ORCA-built Result without a child (for
example, a scan folded to One-Time Filter: false) crashed EXPLAIN.
Our first fix reclassified childless Result nodes in
CTranslatorDXLToPlStmt::FinalizeParamIds() to RESULT_TYPE_UPPER, matching
make_one_row_result(). The crash disappeared, but EXPLAIN began printing
an unexpected Replaces: Aggregate annotation. Reading
show_result_replacement_info() in explain.c explained why:
if (nrels <= 1 && !found_non_result &&
result->result_type == RESULT_TYPE_SCAN)
return;
ORCA drops the folded-away relation from the plan's range table, so
result->relids stays NULL (nrels == 0). Marking childless Result nodes
as RESULT_TYPE_SCAN satisfies the assertion and triggers the suppression
rule cleanly. (On PG 19's case regression test, PostgreSQL's own planner
prints Replaces: Scan on case_tbl while ORCA's empty Result omits that
line — a documented EXPLAIN-only difference.)
3. SubPlan SubPlan 1
PostgreSQL 19 redesigned EXPLAIN SubPlan labels: ruleutils.c now prepends
"SubPlan " or "InitPlan " itself, expecting SubPlan.plan_name to hold a
short descriptive name from choose_plan_name() such as exists_1 or
any_2. Because ORCA's translator still set plan_name = "SubPlan 1", PG 19
faithfully printed "SubPlan SubPlan 1".
CTranslatorDXLToScalar::GetSubplanAlias() now emits <sublink_kind>_<plan_id>
(expr_1, exists_2, any_3, …) on PG 19+ while keeping "SubPlan N" on
PG 18. To avoid duplicating expected test files across versions,
test/init_file normalizes both formats back to SubPlan N during diffing.
(One smaller test-harness surprise came from pg_stats_ext.dependencies:
PostgreSQL 19 changed pg_dependencies_out() from {"2 => 1": 0.500000} to a
JSON array [{"attributes": [2], "dependency": 1, "degree": 0.500000}], so our
extended-stats test now extracts the degree from JSON rather than pinning the
raw text representation.)
Native IGNORE NULLS / RESPECT NULLS through DXL
PostgreSQL 19 adds SQL:2003 RESPECT NULLS and IGNORE NULLS on window
functions such as lag, lead, first_value, last_value, and nth_value.
Our initial commit added a precautionary walker to detect
WindowFunc::ignore_nulls != 0 and fall back to PostgreSQL's planner. That
was safe, but it meant every PG 19 analytical query using IGNORE NULLS lost
ORCA optimization. So we ripped the walker out and plumbed null_treatment
natively through the full DXL pipeline:
The subtle part is not XML serialization — it is Memo deduplication. ORCA
hashes and deduplicates scalar expressions in the Memo. If
CScalarWindowFunc::HashValue() and Matches() ignored m_null_treatment, a
single query requesting both treatments of the same column would silently
collapse them into one 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 both HashValue() and Matches() keeps the
two expressions distinct in the Memo, while PostgreSQL's own
WinCheckAndInitializeNullTreatment() still runs at execution time — so an
invalid call like rank() IGNORE NULLS OVER (...) produces PostgreSQL's exact
error message even though ORCA planned it. On PG 19's window regression
test, this single change wiped out over 50 IGNORE NULLS diffs at once.
What PostgreSQL 19's regression suite actually caught
Running test/test.sh --pg-tests against REL_19_STABLE executes 223 of
PostgreSQL's own regression tests with pg_orca enabled. Every new major
release expands that suite with nastier corner cases — and PG 19's new tests
caught four real bugs in pg_orca, three of which also applied to PG 18.
1. A two-minute LATERAL join query brought down to 15 ms
PostgreSQL 19 added a nested LATERAL join test (upstream 7c620d2bf87):
SELECT count(*)
FROM int4_tbl t1,
LATERAL (
SELECT * FROM tenk1 t2,
LATERAL (SELECT t2.ten AS x OFFSET 0) s0
JOIN tenk1 t3 ON t3.unique2 = t1.f1
WHERE t3.unique1 = t2.hundred + s0.x
) ss1;
PostgreSQL's planner runs it in 8 ms. Under ORCA, it took about two
minutes, rescanning tenk1 50,000 times.
The culprit was CNormalizer::FPushable(). It only allowed a predicate to be
pushed into a join child when that child produced every column the predicate
referenced. In t3.unique2 = t1.f1, t1.f1 is an outer LATERAL reference
produced outside the [s0, t3] join — not by t3. So FPushable() refused
to push it. Worse, predicate inference then wrapped duplicate Select nodes
for t3.unique2 = t1.f1 around the [s0, t3] join, which blocked
PexprCollapseJoins from flattening it into the enclosing join and forced a
correlated nested loop over full scans of tenk1.
Two small changes in CNormalizer.cpp fixed both halves:
PushThruJoinnow passes the join's outer references down toFPushablefor plain inner joins, accepting a predicate whose missing columns are all outer references (as long as it references at least one column of the child). Execution time dropped from ~2 minutes to ~15 ms.PushThruSelectnow does the same when oneSelectsits directly on top of anotherSelect, so duplicate inferred predicates carryingLATERALreferences merge and deduplicate into a single scan filter instead of stacking extraResultnodes.
2. Wrong results on correlated HashAggregate rescans
PostgreSQL 19's aggregates test (also backported to newer REL_18_STABLE)
contains a tiny LATERAL aggregate:
SELECT s1, s2, sm
FROM generate_series(1, 3) s1,
LATERAL (
SELECT s2, sum(s1 + s2) sm
FROM generate_series(1, 3) s2
GROUP BY s2
) ss
ORDER BY 1, 2;
ORCA answered it wrongly: for s1 = 2 and s1 = 3, it returned
sm = 1 + s2 — as if s1 were frozen at 1.
In PostgreSQL's executor, ExecReScanAgg() optimizes rescans of hashed
aggregates: if the child node has no changed parameters and none of the
changed parameters is listed in Agg.aggParams, it reuses the already-built
hash table. PostgreSQL's finalize_plan() populates Agg.aggParams with
every PARAM_EXEC referenced in aggregate arguments and FILTER clauses.
CTranslatorDXLToPlStmt::FinalizeParamIds() — pg_orca's replacement for
finalize_plan() — had never set Agg.aggParams, so it stayed NULL.
Collecting those PARAM_EXEC IDs in FinalizeParamIds() (skipping direct
arguments of ordered-set aggregates, matching PostgreSQL) fixed both LATERAL
hashed aggregates and hashed aggregates inside correlated SubPlans.
3. Multi-key DISTINCT aggregates
A new PG 19 aggregates test runs:
SELECT array_agg(DISTINCT r ORDER BY r USING <, r USING *<) FROM ...;
That aggregate has one input argument (r) and two DISTINCT sort
keys. TranslateDXLScalarAggrefToScalar() had inherited a Cloudberry line
that truncated aggdistinct to the number of aggregate inputs. Dropping the
second key tripped nodeAgg's assertion
numSortCols >= list_length(aggref->aggorder) — and in non-assert builds
would have silently ignored the second sort key. Keeping the full list fixed
the assertion and preserved exact sort semantics.
4. Sorting on an ORDER BY key already fixed to a constant
Cleaning up plan diffs against PG 19 also led to a nice quality-of-life
improvement in CQueryContext::PqcGenerate: for a query like
SELECT a, b FROM test WHERE b = 10 ORDER BY b DESC, ORCA used to place a
Sort on b above the filtered scan because COrderSpec::FSatisfies did not
consult the derived constant constraint b = 10. Stripping columns that
CPredicateUtils::FConstColumn proves constant from the top-level Limit's
required order spec removes those redundant sorts across both PG 18 and PG 19.
Where PostgreSQL 19.0 stands today
All of this runs continuously in CI: a rockylinux:9 job installs the stable
PGDG postgresql19 packages, builds pg_orca with Debug assertions on, and
runs all 34 tests in test/schedule (--orca-tests) on every push,
alongside the PG 18 builds on Linux x86_64, ARM64, and macOS.
Against PostgreSQL 19.0's own 223-test parallel_schedule:
- 0 server crashes across all 223 tests.
- With
--ignore-plans, 216 of 223 pass (7 failures). Six of those seven are the same known plan-behaviour or test-harness diffs tracked on PG 18 (subselect,aggregatesbalk,join_hashbatch count,select_parallel,windowtie-breaking, andstatsmissing thestats_exthelper). - The seventh (
join) is actually funny: PG 19's test expects PostgreSQL's planner to reject(int4_tbl a CROSS JOIN int4_tbl b) FULL JOIN int4_tbl c ON a.f1 = b.f1withERROR: FULL JOIN is only supported with merge-joinable or hash-joinable join conditions. ORCA can plan that query, so it succeeds and returns the 9 rows the SQL defines — causing a diff because it did not error. - Without
--ignore-plans, 48 tests show plan-shape diffs, including three minor PG 19-specific ones:case(noReplaces: Scan on case_tblon ORCA's emptyResult),create_aggregate(ORCA does not yet emit aWindowAggRun Condition), andstats.
Try it on PostgreSQL 19
Building against PostgreSQL 19 uses the exact same CMake command as PostgreSQL
18 — just point PG_CONFIG at your PG 19 installation:
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-pg19
To keep a second build's regression workspace separate when running tests,
pass BUILD_DIR:
BUILD_DIR=$PWD/build-pg19 test/test.sh --orca-tests
For how pg_orca prices plans in PostgreSQL's own units across both versions,
see Pricing plans in PostgreSQL's currency.
For an overview of the DXL boundary that kept ORCA's core at zero #ifs, see
ORCA 101.
Try it
Install pg_orca in one command
The ORCA query optimizer, now a PostgreSQL 18 & 19 extension. MIT-licensed, falls back to PostgreSQL's planner on unsupported queries.