Skip to content

Improve DPM_cardinality for sparsely populated data pages (#9285) - #9410

Open
tomaszdubiel18 wants to merge 1 commit into
FirebirdSQL:masterfrom
tomaszdubiel18:fix-9285-sparse-cardinality
Open

tomaszdubiel18 wants to merge 1 commit into
FirebirdSQL:masterfrom
tomaszdubiel18:fix-9285-sparse-cardinality

Conversation

@tomaszdubiel18

@tomaszdubiel18 tomaszdubiel18 commented Dec 6, 2026 •

Copy link
Copy Markdown

Hello.
Please take a look. I would be grateful if you could review those changes. I'm open for suggestions.

Below is a pull request proposal prepared with AI assistance for issue #9285.

Summary

DPM_cardinality currently estimates table cardinality solely from dataPages * pageCapacity / avgRecordSize using the first data page, except for single-page tables. When a table undergoes churn (for example delete/insert cycles under concurrent snapshot readers) and retains sparsely populated data pages (ppg_dp_full cleared), cardinality can be overestimated by 10x–46x, causing join order reversals and unnecessary hash joins. This change refines DPM_cardinality directly inside src/jrd/dpm.epp using zero-allocation stratified page counting/sampling on single-pointer-page relations and bounded primary-record counting on shrunk multi-pointer-page relations, without introducing split-brain optimizer workarounds (csb_scan_cardinality), without adding prepare I/O on dense tables, and without a cliff at 32/33 data pages.

Motivation and Review of Reference Patch D (#9285)

Reference Patch D in #9285 demonstrates the physical-layout sensitivity on Firebird 5.0, but its design has several issues that make it unsuitable for merging as-is into master:

  • The dual-cardinality optimizer split (csb_cardinality vs csb_scan_cardinality across exe.h, Optimizer.cpp, InnerJoin.cpp, Retrieval.cpp) leaves FullTableScan::m_cardinality, InnerJoin::formRiver() HASH build-side selection, Optimizer::generateEquiJoin(), InnerJoin::getIndexedRelationships(), Retrieval::makeInversion(), Retrieval::applyNavigation(), and RDB$SQL.EXPLAIN reading csb_cardinality, while Retrieval::getInversion() and InnerJoin::estimateCost() switch to the inflated csb_scan_cardinality whenever access is non-unique without a matched index predicate. This breaks NATURAL-scanned and unindexed-filtered sparse tables (for example, SELECT ... FROM SPARSE_SMALL S JOIN BIG_FACT F ... or WHERE S.UNINDEXED_FLAG = 0) and is not a general safeguard for cached plans prepared against drained queues (which already exhibit the same behavior on compact 1-page tables).
  • Counting stops abruptly above 32 data pages, creating a sharp cliff between 32 and 33 sparse pages.
  • Sampling every 4th full page (fullPages++ % 4) carries forward the previous full page's count, multiplying outlier pages (including full pages containing only back-versions or blobs) and adding prepare fetches on dense tables of 2..32 pages.
  • Gating counting on dataPages <= 32 fails when rel_data_pages is stale-high due to DPM_delete marking emptied pages inside non-empty extents as ppg_dp_empty without decrementing rel_data_pages.
  • The master codebase also requires skipping ppg_dp_reserved pages (used by BulkInsert), checking dpg_length >= RHD_SIZE, calling tdbb->checkCancelState() across multi-pointer-page scans, and fixing a pre-existing bug in DPM_cardinality where CCH_HANDOFF overwrote the pointer-page WIN while continuing to dereference ppage if the first qualifying data page had zero records.

Design (src/jrd/dpm.epp only)

  1. Return 0.0 immediately when DPM_data_pages() returns 0, avoiding an unnecessary pointer-page scan on empty tables.
  2. Fetch pointer page 0 with LCK_read and inspect qualifying data pages (ppg_page[slot] != 0 and none of ppg_dp_secondary, ppg_dp_empty, ppg_dp_reserved) via a separate WIN dpWindow while retaining the pointer-page read latch (PP -> DP canonical latch ordering, fixing the pre-existing CCH_HANDOFF dangling-ppage issue).
  3. On single-pointer-page relations (ppg_eof set — up to 1,632 pages / 13 MB on 8 KB pages, 3,272 pages / 52 MB on 16 KB pages, 6,544 pages / 105 MB on 32 KB pages), classify qualifying pages in memory into fullCount (ppg_dp_full) and nonFullCount:
    • Dense fast-path (fullCount > 8 and nonFullCount * 8 < fullCount): inspect a single full page (bounded fallback up to 8 if recordCount == 0) and extrapolate using effectivePages = fullCount + 0.5 * nonFullCount. This keeps single-page prepare I/O (zero extra fetches on dense tables), avoids heap allocation, and self-heals stale rel_data_pages (both #9283 stale-low and extent ppg_dp_empty stale-high).
    • Small / sparse stratified path: count all qualifying pages directly when fullCount <= 8 and nonFullCount <= 32, or sample evenly spaced indices ((FB_UINT64) sample * count + count / 2) / samples per stratum (MAX_SAMPLED_FULL_PAGES = 8, MAX_SAMPLED_NONFULL_PAGES = 32) in a single zero-allocation pass over pointer-page slots, counting primary records (!(rhd_flags & (rhd_chain | rhd_fragment | rhd_blob))). Deleted but not yet garbage-collected primary records remain counted because active transactions may still visit them.
  4. On multi-pointer-page relations (!ppg_eof):
    • When dataPages <= 32 (shrunk table spread across older pointer pages, or #9283 stale-low rel_data_pages), count primary records across up to 32 qualifying data pages and 32 pointer pages (tdbb->checkCancelState() between pointer pages). If EOF is reached within the bound, return the exact primary count; if more than 32 qualifying pages are discovered, reset relPages->rel_data_pages = 0, refresh via DPM_data_pages(), and fall back to the capacity formula.
    • Otherwise (dataPages > 32), inspect only the first non-empty data page (identical I/O and estimate to baseline).

Verification (Firebird 6.0 master commit 7c2e0f50f7, Linux x86_64)

  • Built-in C++ unit tests (make tests && make run_tests): common_test 120/120 passed, libEngine14_test 35/35 passed, isql_test 8/8 passed, zero compiler warnings.
  • Official firebird-qa (baseline vs patched on identical commit 7c2e0f50f7): 0 regressions across 175 tests (gh_8161, gh_8379, gh_8940, gh_7675, gh_9157, gh_9173, tests/functional/arno/optimizer/ 90 passed / 4 skipped / 1 pre-existing failure identical to baseline, tests/functional/ltt/ and tests/functional/tablespace/ 64 passed / 7 skipped / 3 pre-existing failures identical to baseline), plus new regression test gh_9285_test.py (fails on baseline, passes on patched).
  • 27-table cardinality corpus (16 KB pages, RDB$SQL.EXPLAIN + warm prepare fetches): dense tables D2000..D50000 and FIFO_DENSE show 0 extra warm prepare fetches (242 -> 242) and 0.98x–1.04x accuracy; empty tables save 1 prepare fetch; sparse tables S10..S200 improve from 29.01x overestimate to 1.00x (S600: 14.00x -> 1.03x, no cliff at 32/33, max +31 prepare fetches); FIFO_REVERSE improves from 12.43x to 0.94x; ONE_PAGE_BV 3.00x -> 1.00x; BACKVER_HEAVY 3.87x -> 1.00x; STALE_EXT_SAME_ATT 46.41x -> 1.00x; GTT_SPARSE 30.94x -> 1.00x.
  • Supported FB 6.0 page sizes (8192, 16384, 32768): 1.00x exact cardinality on sparse ~20-page tables.
  • Dense/sparse boundary ratio sweep (50 pages, 0..50 sparse pages): smooth estimates 0.99x, 1.03x, 1.00x..1.00x across the 1/8 ratio transition.
  • Multi-pointer-page verification (8192 page size, Pointer pages: 3): full 3,500-row table unchanged (4,838.86 -> 4,838.86); shrunk 14-row table across 3 pointer pages 19.36 -> 14.0 exact; cold-reopen #9283 stale-low rel_data_pages on 3,512-row 3-PP table self-heals on first prepare (11.06 -> 4,855.45).
  • Plan-flipping joins (where reference Patch D fails): Q_natural_14p 6,004 -> 292 fetches (20.6x); Q_natural_50p 6,004 -> 601 fetches (10.0x); Q_indexed_50p 6,004 -> 403 fetches (14.9x). On the (Proposed fix) Improve cardinality estimates for small tables with sparsely populated data pages #9285 ERP schema without 6.0 optimizer regression: a three-table inner join needs 21.7x more page fetches than in 5.0 #9286's unindexed predicate: fb6_indexed_kt 948,895 -> 38,789 fetches (24.5x), fb6_natural_zgkl 200,152 -> 39,051 fetches (5.1x).
  • Concurrency stress (4 concurrent writers performing inserts/deletes + 4 concurrent preparing/executing readers, 10 s per mode) followed by gfix -v -full: SuperServer (116 writes, 1,216 prepares), SuperClassic (30 writes, 452 prepares), and Classic (28 writes, 396 prepares) completed with 0 errors and gfix -v -full exit code 0.
  • Note on cached plans prepared against nearly empty queues: a 20-row sparse table now receives the same accurate 20.0 estimate and identical query plans as a compact 20-row single-page table (improving queries while the table actually has 20 rows, e.g., Q8_filtr_C 50,844 -> 140 fetches, while stale cached plans reused after a 20,000-row refill behave identically to compact 1-page tables).
  • Backportability (v5.0-release commit 42561265d0, LI-V5.0.5.2013): the same single-file src/jrd/dpm.epp change backports cleanly (mechanical API adjustments only: rel_pages, rel_pg_space_id, MET_current, WIN(pageSpaceId, -1), no ppg_dp_reserved). Verified on Linux x86_64 against unmodified (Proposed fix) Improve cardinality estimates for small tables with sparsely populated data pages #9285 repro.py --scenario sparse (840,875 -> 38,788 fetches, ratio 1.00, RESULT: OK), 4 KB / 8 KB / 16 KB / 32 KB page sizes (303–403 -> 180 fetches, whereas Patch D kept 303–403), NATURAL and >32-page sparse joins (Q_natural_14p 757 -> 126, Q_natural_50p 757 -> 450, Q_indexed_50p 757 -> 2, all unchanged at 757 under Patch D), 3-PP 4 KB #9283 cold-reopen (16,398 -> 1,750 fetches), built-in C++ unit tests (common_test 17/17, libEngine13_test 6/6), firebird-qa (93 passed, 4 skipped, 0 failed, including gh_9285_test.py which fails on both baseline and Patch D), and 3-mode (Super, SuperClassic, Classic) concurrency stress + gfix -v -full (0 errors).
  • Platform scope: tested on Linux x86_64; Windows was not tested.

…L#9285)

Estimate cardinality on single-pointer-page relations using zero-allocation stratified counting/sampling of full and non-full data pages while keeping single-page prepare I/O on dense relations. For shrunk multi-pointer-page relations, count primary records within bounded page and pointer-page limits and refresh stale cached page counts if more pages are discovered. Also fix the pre-existing CCH_HANDOFF pointer-page latch issue in DPM_cardinality.
@tomaszdubiel18
tomaszdubiel18 force-pushed the fix-9285-sparse-cardinality branch from 14661bf to 367036a Compare December 6, 2026 21:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant