Skip to content

PoC: Data properties for join order cardinality cap - #120784

Closed
cv4g wants to merge 14 commits into
masterfrom
data-properties-poc
Closed

cv4g wants to merge 14 commits into
masterfrom
data-properties-poc

Conversation

@cv4g

@cv4g cv4g commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Proof of concept serving as a discussion starter on introducing data properties to ClickHouse. A potential use case is join order optimization which could use data properties to cap cardinality estimates.

Known conflicts: #116684 (Split Join Order Optimizer)

Changelog category (leave one):

  • New Feature
  • Experimental Feature
  • Improvement
  • Performance Improvement
  • Backward Incompatible Change
  • Build/Testing/Packaging Improvement
  • Documentation (changelog entry is not required)
  • Critical Bug Fix (crash, data loss, RBAC)
  • Bug Fix (user-visible misbehavior in an official stable release)
  • CI Fix or Improvement (changelog entry is not required)
  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...


Workflow [PR]
Sync PR [sync-upstream/pr/120784]

cv4g added 13 commits September 1, 2026 08:34
Represent traced lineage directly in output order, add reusable unique
name-and-type position indexes, and keep iterative lineage traversal
memoized. Update column-statistics consumers and regression coverage to
the positional interface.
Add `deriveDataPropertiesForPlanDAG`: one-shot iterative topology
discovery and evaluation over a query plan DAG. Results are released
after their last consumer, exact pass-through steps adopt child buffers,
and the traversal neither mutates the plan nor persists derived data in
it.

Resolve common subplan references to their producer and remap the
producer's facts through the reference's output contract. Fail closed
on structurally unresolved or invalid references, name, count, and
type mismatches, and on ordinary, common, or mixed cycles.
Intern per-relation data property facts into an immutable,
source-qualified catalog for join ordering: columns with types and
nullability, unique keys, functional dependencies, and lineage, each
behind a strong per-table id (one tagged type per table) so handles
cannot be mixed up or cross providers. Sizes that become UInt32 ids or
offsets go through a checked narrowing helper that names the
overflowing table.

Introduce isProvenStrongBagKey as the single trust gate for bag
uniqueness: only proven, ordinary-equality facts originating from final
aggregation grouping qualify. Storage declarations stay diagnostic-only
and transformations cannot create a new origin.

The catalog is exercised through the canonical join-order properties
provider and the join-order integration tests in follow-up commits.
Answer bag-uniqueness and inner-join cardinality-cap questions for join
ordering from a canonical provider keyed by semantic region, relation
subset, predicate equality closure, and output contract, so every
enumeration algorithm shares one cached answer per canonical question
instead of deriving properties per winner.

Derive demand-driven answers from the catalog's trusted keys and
ordinary equality classes. Record the equality-class links each
uniqueness proof relied on as obligations, so a consumer can verify
that every link is enforced by the selected physical plan. Fail closed
with explicit unsupported reasons for non-inner-ALL and cross regions,
non-deterministic predicates, null-safe equalities, ambiguous or
type-mismatched bindings, incomparable equality-class members, and
invalid or cross-provider handles.

Covered by gtest_join_order_canonical_properties: region and handle
validation, equality-cut construction, finite-bag cardinality checks,
obligation recording, and rejection reasons.
Introduce `query_plan_optimize_join_order_use_proven_uniqueness` and
`query_plan_optimize_join_order_data_property_diagnostics`. When either
is enabled, the join-graph builder collects a per-relation
`JoinOrderDataPropertyCatalog` (leaf facts derived by
`deriveDataPropertiesForPlanDAG`, gated by
`the two-boolean DataPropertyCollectionPolicy`) and records a canonical region
rejection for non-`INNER ALL` joins. `optimizeJoinOrder` materializes
column equivalences whenever the catalog may be consumed, constructs
the canonical properties provider from source-bound predicates
(designated initializers so adjacent bool fields cannot swap silently),
and marks predicates of equality classes containing physically
incomparable member pairs so the provider refuses exactly the proofs
that would rely on synthesizing such a link.

Only the greedy solver consumes the resulting caps for now. The shared
`assessCandidate` decides admission (legacy predicates, the independent
transitive setting, or a `Proven` canonical cut), equivalence-derived
selectivity, and the cap; `DPJoinEntry` records `used_canonical_cap`
and the proof's equality-class obligations, and
`verifySelectedPlanCapObligations` audits them against the selected
plan after cleanup. `cleanupJoinPredicates` now materializes the full
canonical equality cut (every projected member, in deterministic class
order), skips member pairs `equals` cannot resolve, and synthesizes
into greedy's disconnected-pair `Cross` fallback entries in all-inner
regions, converting them to `Inner`.

The DP solvers keep exact feature-off behavior in this commit even
though column equivalences may now be materialized without the
independent transitive setting: DPsize admission, `evaluateJoin`
selectivity, and DPsub admission and selectivity are gated on that
setting (DPsub through the new `canAcceptTransitivePair` consumer hook,
invoked before `setTableNeighbor` so a rejected pair cannot mark subset
connectivity or consume enumeration budget), and DPhyp's synthetic
phase-2 hyperedges are installed only under that setting. Follow-up
commits extend cap consumption to DPsize, DPsub, and DPhyp.

Diagnostics stay query-local: an `EXPLAIN`-time
`JoinOrderOptimizationDebugInfo` sink counts cap assessment outcomes
and carries provider metrics, and trace logging is emitted only under
the diagnostics setting.
`evaluateJoin` - the plan-building path shared by DPsize and DPhyp -
now takes the shared `JoinCandidateAssessment` instead of gating
equivalence-derived selectivity on the independent transitive setting
directly: admission, selectivity, the canonical cap, and the recorded
`used_canonical_cap`/`canonical_cap_obligations` all come from one
assessment per candidate. `solveDPsize` builds that assessment
(tracking whether any predicate actually crosses the candidate split,
so an early-attached unary predicate cannot authorize transitive
admission), admits proof-gated transitive pairs, and caps ordinary
`INNER ALL` estimates exactly like the greedy solver. DPhyp's
`tryJoin` passes the same assessment, so DPhyp candidates reachable
through explicit predicates are capped as well, while its synthetic
transitive topology stays gated on the independent transitive setting.
The now-unused base cost/cardinality helpers are removed.

DPsub keeps exact feature-off behavior; its acceptor is converted in a
follow-up commit.

Precompute one relation mask per equality class while materializing column
equivalences, avoiding repeated member scans in DPsize candidate checks.
The DPsub acceptor now performs the same candidate-specific canonical
assessment as the other solvers. `canAcceptTransitivePair` replaces the
setting-only gate: a predicate-free transitively-connected pair is
admitted by the independent transitive setting or by a `Proven`
canonical assessment (`assessTransitivePair`, which fails closed on
every other outcome), and the admission's cap is remembered in
`pending_transitive_admission` so one candidate performs one canonical
lookup. `accept` assesses edge-connected `Inner` pairs itself, allows
equivalence-derived selectivity only under the setting or a proven
cut, caps the estimate and the local cost, and records
`used_canonical_cap`/`canonical_cap_obligations` in the mask DP entry;
`buildPhysicalPlan` copies both onto the produced `DPJoinEntry`. The
now-unused 4-argument `estimateCardinality` member is removed.

The DPsub mask tables share one checked UInt32 narrowing helper
(`checkedRelationBit32`) instead of ad-hoc shifts, so an out-of-range
relation id fails loudly rather than silently wrapping.
DPhyp discovers join candidates through a static hypergraph, so unlike
greedy, DPsize, and DPsub it cannot assess a predicate-free
transitively-connected pair during enumeration. Its synthetic phase-2
hyperedges now have three modes: the independent transitive setting
installs every class-connected relation pair; the new default-off
`query_plan_optimize_join_order_dphyp_proven_edges` mode assesses
exact singleton pairs against static leaf estimates and installs only
`Proven` pairs without unresolved equality obligations, rejecting
defensively otherwise so topology never relies on a debug-only
finalization check; with both off, Policy A keeps precisely the
explicit topology, so materialized column equivalences alone cannot
enlarge the search space, its budget consumption, or the fallback
behavior. Candidate relation pairs are gathered, sorted, and
deduplicated before installation because equivalence classes are
pointer-hashed, keeping hyperedge ids deterministic across runs.

Each DPhyp attempt accumulates query-local counters
(`DPhypAttemptMetrics`) that are flushed once to the eight new
`JoinOrderDPhyp*` profile events when the attempt ends, including the
searched-plan count; `solve` additionally counts fallbacks from a
failed DPhyp attempt to a later configured algorithm.
`DataPropertySet` gains a `SortingProperty`: a `SortDescription` plus a
Stream/Global scope, where a non-empty description also guarantees
every prefix. `dump()` renders it (e.g. `sorting=global:[id ASC NULLS
LAST]`) so diagnostics cover ordering alongside unique keys, functional
dependencies, non-null columns, and lineage.

The per-step ordering propagation that lived inside `applyOrder`
becomes a shared pure transfer function, `deriveSortingProperty`:
`ReadFromMergeTree` reports per-stream read order; in-order
(merging) aggregation and `SortingStep` produce global (or
per-partition stream) order; `UnionStep` keeps the common child prefix
as stream order; `DistinctStep`, `ExpressionStep`, `FilterStep`,
`(Negative)LimitByStep`, and generic `preserves_sorting` transforming
steps preserve or remap the input order.

A narrowable `UnionStep` reports its sorting guarantee together with an
explicit requirement to disable narrowing. `applyOrder` satisfies that
requirement before advertising the property; non-mutating whole-plan
derivation fails closed and omits the conditional property. This keeps
the transfer function pure without claiming an order that narrowing
could invalidate. `applyOrder` retains only plan mutations such as
distinct-in-order, `FinishSorting` conversion, LIMIT BY in-order,
union narrowing, and memory-bound merging.

Whole-plan derivation now feeds child properties to every step —
including steps with more than two children, where the logical facts
still bail out but sorting (e.g. a multi-input `Union` common prefix)
survives — and `CommonSubplanReferenceStep` remaps the producer's sort
description through its output mapping, truncating at the first
missing or ambiguous column.

The join-order data property catalog stores an optional per-relation
sorting fact (column ids with direction, NULLS direction, and interned
collation locale, plus the scope), rejecting ambiguous column names
and non-normalized directions, so join-order solvers can later consume
leaf ordering.
Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)
- retargeted PR record [email protected] to 26.10 (settings-history check rule)
- retargeted PR record [email protected] to 26.10 (settings-history check rule)
- semantic merge fixes in non-conflicting files: src/Processors/QueryPlan/Optimizations/DataPropertyDerivation.cpp, src/Processors/QueryPlan/Optimizations/RelationStatistics.cpp, src/Processors/QueryPlan/Optimizations/joinOrderAlgorithms.h, src/Processors/QueryPlan/Optimizations/joinOrderCommon.h, src/Processors/QueryPlan/Optimizations/joinOrderDP.cpp, src/Processors/QueryPlan/Optimizations/joinOrderDP.h, src/Processors/QueryPlan/Optimizations/joinOrderDPHyp.cpp, src/Processors/QueryPlan/Optimizations/joinOrderDPSize.cpp, src/Processors/QueryPlan/Optimizations/joinOrderDPSub.cpp, src/Processors/QueryPlan/Optimizations/joinOrderGreedy.cpp

Also resolved conflicts in:
- `src/Processors/QueryPlan/Optimizations/applyOrder.cpp`
- `src/Processors/QueryPlan/Optimizations/enumeratorChecker.h`
- `src/Processors/QueryPlan/Optimizations/joinEnum.h`
- `src/Processors/QueryPlan/Optimizations/joinOrder.cpp`
- `src/Processors/QueryPlan/Optimizations/joinOrder.h`
- `src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp`

Master split `joinOrder.cpp` into `joinOrderGreedy.cpp`, `joinOrderDPSize.cpp`, `joinOrderDPSub.cpp`, `joinOrderDPHyp.cpp`, `joinOrderBitSet.cpp`, `joinOrderDP.cpp` and `joinOrderCommon.h`; the join-order changes are ported into those files through a `JoinOrderPropertyContext` passed to each solver. The `EXPLAIN` output of tests 04658-04661 may need updating.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e02ba2]

Summary: ❌

job_name test_name status info comment
Config Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/pr_labels_and_category.py FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/pr_body_check.py FAIL
Dockers Build (amd) DROPPED
Dockers Build (arm) DROPPED
Dockers Build (multiplatform manifest) DROPPED
Style check DROPPED
Code Review DROPPED
Docs check (Mintlify) DROPPED
Fast test DROPPED
Fast test (arm_darwin) DROPPED

@rschu1ze

Copy link
Copy Markdown
Member

This PR is generally useful but stuck and we'll need an RFC for this topic. Allow me to close it to get it off the radar for now. We can re-open at some point (it would need more activity then).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa...

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants