Repository navigation
Improve DPM_cardinality for sparsely populated data pages (#9285) - #9410
Open
tomaszdubiel18 wants to merge 1 commit into
Open
tomaszdubiel18 wants to merge 1 commit into
tomaszdubiel18 wants to merge 1 commit into
Conversation
…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
force-pushed
the
fix-9285-sparse-cardinality
branch
from
December 6, 2026 21:32
14661bf to
367036a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_cardinalitycurrently estimates table cardinality solely fromdataPages * pageCapacity / avgRecordSizeusing 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_fullcleared), cardinality can be overestimated by 10x–46x, causing join order reversals and unnecessary hash joins. This change refinesDPM_cardinalitydirectly insidesrc/jrd/dpm.eppusing 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:csb_cardinalityvscsb_scan_cardinalityacrossexe.h,Optimizer.cpp,InnerJoin.cpp,Retrieval.cpp) leavesFullTableScan::m_cardinality,InnerJoin::formRiver()HASH build-side selection,Optimizer::generateEquiJoin(),InnerJoin::getIndexedRelationships(),Retrieval::makeInversion(),Retrieval::applyNavigation(), andRDB$SQL.EXPLAINreadingcsb_cardinality, whileRetrieval::getInversion()andInnerJoin::estimateCost()switch to the inflatedcsb_scan_cardinalitywhenever 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 ...orWHERE 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).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.dataPages <= 32fails whenrel_data_pagesis stale-high due toDPM_deletemarking emptied pages inside non-empty extents asppg_dp_emptywithout decrementingrel_data_pages.mastercodebase also requires skippingppg_dp_reservedpages (used byBulkInsert), checkingdpg_length >= RHD_SIZE, callingtdbb->checkCancelState()across multi-pointer-page scans, and fixing a pre-existing bug inDPM_cardinalitywhereCCH_HANDOFFoverwrote the pointer-pageWINwhile continuing to dereferenceppageif the first qualifying data page had zero records.Design (
src/jrd/dpm.epponly)0.0immediately whenDPM_data_pages()returns0, avoiding an unnecessary pointer-page scan on empty tables.LCK_readand inspect qualifying data pages (ppg_page[slot] != 0and none ofppg_dp_secondary,ppg_dp_empty,ppg_dp_reserved) via a separateWIN dpWindowwhile retaining the pointer-page read latch (PP -> DPcanonical latch ordering, fixing the pre-existingCCH_HANDOFFdangling-ppageissue).ppg_eofset — 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 intofullCount(ppg_dp_full) andnonFullCount:fullCount > 8andnonFullCount * 8 < fullCount): inspect a single full page (bounded fallback up to 8 ifrecordCount == 0) and extrapolate usingeffectivePages = fullCount + 0.5 * nonFullCount. This keeps single-page prepare I/O (zero extra fetches on dense tables), avoids heap allocation, and self-heals stalerel_data_pages(both#9283stale-low and extentppg_dp_emptystale-high).fullCount <= 8andnonFullCount <= 32, or sample evenly spaced indices((FB_UINT64) sample * count + count / 2) / samplesper 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.!ppg_eof):dataPages <= 32(shrunk table spread across older pointer pages, or#9283stale-lowrel_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, resetrelPages->rel_data_pages = 0, refresh viaDPM_data_pages(), and fall back to the capacity formula.dataPages > 32), inspect only the first non-empty data page (identical I/O and estimate to baseline).Verification (Firebird 6.0
mastercommit7c2e0f50f7, Linux x86_64)make tests && make run_tests):common_test120/120 passed,libEngine14_test35/35 passed,isql_test8/8 passed, zero compiler warnings.firebird-qa(baseline vs patched on identical commit7c2e0f50f7): 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/andtests/functional/tablespace/64 passed / 7 skipped / 3 pre-existing failures identical to baseline), plus new regression testgh_9285_test.py(fails on baseline, passes on patched).RDB$SQL.EXPLAIN+ warm prepare fetches): dense tablesD2000..D50000andFIFO_DENSEshow 0 extra warm prepare fetches (242 -> 242) and0.98x–1.04xaccuracy; empty tables save 1 prepare fetch; sparse tablesS10..S200improve from29.01xoverestimate to1.00x(S600:14.00x -> 1.03x, no cliff at 32/33, max +31 prepare fetches);FIFO_REVERSEimproves from12.43xto0.94x;ONE_PAGE_BV3.00x -> 1.00x;BACKVER_HEAVY3.87x -> 1.00x;STALE_EXT_SAME_ATT46.41x -> 1.00x;GTT_SPARSE30.94x -> 1.00x.8192,16384,32768):1.00xexact cardinality on sparse ~20-page tables.0.99x,1.03x,1.00x..1.00xacross the 1/8 ratio transition.8192page size,Pointer pages: 3): full 3,500-row table unchanged (4,838.86 -> 4,838.86); shrunk 14-row table across 3 pointer pages19.36 -> 14.0exact; cold-reopen#9283stale-lowrel_data_pageson 3,512-row 3-PP table self-heals on first prepare (11.06 -> 4,855.45).Q_natural_14p6,004 -> 292fetches (20.6x);Q_natural_50p6,004 -> 601fetches (10.0x);Q_indexed_50p6,004 -> 403fetches (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_kt948,895 -> 38,789fetches (24.5x),fb6_natural_zgkl200,152 -> 39,051fetches (5.1x).gfix -v -full:SuperServer(116 writes, 1,216 prepares),SuperClassic(30 writes, 452 prepares), andClassic(28 writes, 396 prepares) completed with 0 errors andgfix -v -fullexit code 0.20.0estimate 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_C50,844 -> 140fetches, while stale cached plans reused after a 20,000-row refill behave identically to compact 1-page tables).v5.0-releasecommit42561265d0,LI-V5.0.5.2013): the same single-filesrc/jrd/dpm.eppchange backports cleanly (mechanical API adjustments only:rel_pages,rel_pg_space_id,MET_current,WIN(pageSpaceId, -1), noppg_dp_reserved). Verified on Linux x86_64 against unmodified (Proposed fix) Improve cardinality estimates for small tables with sparsely populated data pages #9285repro.py --scenario sparse(840,875 -> 38,788fetches, ratio1.00,RESULT: OK), 4 KB / 8 KB / 16 KB / 32 KB page sizes (303–403 -> 180fetches, whereas Patch D kept303–403), NATURAL and >32-page sparse joins (Q_natural_14p757 -> 126,Q_natural_50p757 -> 450,Q_indexed_50p757 -> 2, all unchanged at757under Patch D), 3-PP 4 KB#9283cold-reopen (16,398 -> 1,750fetches), built-in C++ unit tests (common_test17/17,libEngine13_test6/6),firebird-qa(93 passed, 4 skipped, 0 failed, includinggh_9285_test.pywhich fails on both baseline and Patch D), and 3-mode (Super,SuperClassic,Classic) concurrency stress +gfix -v -full(0 errors).