Skip to content

Include the column statistics of Iceberg reads from manifest files for join reordering - #123553

Merged
antoniofilipovic merged 39 commits into
masterfrom
afilipovic-iceberg-column-stats
Nov 1, 2026
Merged

antoniofilipovic merged 39 commits into
masterfrom
afilipovic-iceberg-column-stats

Conversation

@antoniofilipovic

@antoniofilipovic antoniofilipovic commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Related: #120440
Related: #123085
Related: #124395
Related: #124857
Related: #124448

The second PR for #120440, after #123085 (merged), which gives join reordering the row count of an Iceberg read. It gives the read column statistics from the manifest files, and estimates the conditions of the read on them, as for MergeTree tables with column statistics. The condition estimate was #124448, which is closed and moved here (see the review discussion below).

Column statistics

For each column the query reads, the data files that survive pruning carry manifest metrics: lower and upper bounds, NULL count and identity partition value. They now give the read column statistics as well, under the same setting as the rows, use_iceberg_manifest_statistics, which now also requires use_statistics: with use_statistics = 0 an Iceberg read gets no estimate at all, as with the setting off.

Each file becomes a MergeTree Basic statistics summary (new ColumnStatistics::createBasicFromSummary and a StatisticsBasic::build overload), and ConditionSelectivityEstimatorBuilder merges the summaries as it merges the statistics of MergeTree parts. How the metrics are read:

  • Bounds are decoded with the type of the schema the file was written with and converted to the current type, so they survive int -> long.
  • A file written before a column was added counts its rows as NULLs.
  • A file adds nothing to the statistics of a column only when it has neither its NULL count nor its bounds, as MergeTree skips a part without statistics; with the bounds alone its NULL count is taken as 0.

After the manifest walk, ManifestColumnStatistics::finalize reads the merged bounds and NULL counts and sets the number of distinct values of each column by the first rule that applies, clamped to the non-NULL rows:

  1. an identity partition column: the number of distinct partition values;
  2. integers, dates and timestamps: max - min + 1 of the merged bounds, when it is within the non-NULL rows;
  3. otherwise the estimator keeps its own guess, 10% of the rows, as for a MergeTree table without a uniq statistic.

The number is given to the estimator with ColumnStatistics::setCardinality, and equality and IN divide the rows by it, as by a uniq sketch. A range wider than the non-NULL rows (sparse keys, timestamps) gives no number, so the estimator keeps its guess, as rule 3. MergeTree never calls setCardinality, so nothing changes for it.

Conditions

DataLakeReadEstimate is the result of the manifest walk, computed once per read: the rows of the remaining files, the estimator built from them, and the pruning and delete flags of #123085. On every call, estimateReadRowsCount estimates on that estimator the filter above the read and its PREWHERE, as MergeTree does, and also its row policy (getConditionsToEstimate). Ranges interpolate between the merged min and max; equality and IN use the numbers of distinct values.

A read with rows is estimated at 1 row at least, and its numbers of distinct values at 1 at least. Without a measured number of distinct values, = and IN take the default 1%, which truncates to 0 rows on a table of a few rows; the join above it was then estimated at 1 row and its real result became a build side (TPC-DS q43 at SF1: 2,750,382 rows put into hash tables instead of 378).

The read's own filter (filter_actions_dag) only prunes data files. It is not ANDed with the conditions: it usually holds the same WHERE, and a condition that is not a range would be counted twice (on MergeTree, x % 2 = 0 in both PREWHERE and WHERE takes 10 estimated rows to 0). A WHERE above a LIMIT, an aggregation or a window function stays out of the read, and is still estimated, then capped by the step above, as for MergeTree.

The cases of the Iceberg branch:

  • no conditions, or no rows: the rows of the remaining files; exact only without a read filter and without delete files, or with no rows;
  • column statistics: the estimate of the conditions, imprecise;
  • no column statistics and nothing pruned: no estimate, as for MergeTree without column statistics;
  • no column statistics, files pruned: the rows of the remaining files, an upper bound.

A fix in the statistics merge

Since the per-part statistics cache, ConditionSelectivityEstimatorBuilder::addStatistics merges into a copy made by ColumnStatistics::cloneEmpty, and StatisticsBasic::copyStructureFrom copied only has_default_count. The summaries from the manifests have no string lengths, so for a String column the copy and the files' statistics were incompatible and every file after the first was skipped (a two-file Nullable(String) column, half NULL, showed null 1 instead of null 0.5). copyStructureFrom now copies every flag isCompatibleWith compares; for MergeTree statistics these flags follow the type, so nothing changes there.

Measured

A catalog of 87 queries compares the Iceberg estimates with a MergeTree twin that holds the same data with the default column statistics (auto_statistics_types = 'basic, uniq_v2'). The data is a TPC-H-like schema written with ClickHouse's Iceberg writer: 1M orders in 10 data files, 3M lineitems, 100k customers and smaller dimensions, plus a month-partitioned copy of orders and copies with 10%, 49% and 91% of the rows deleted. A query is off when the Iceberg estimate, or the rows put into hash tables (JoinBuildTableRowCount) by its plan, is at least 3x worse than with the MergeTree twin. "Before" is the stack without the condition estimate. It was measured on the first version of the stack (2026-10-08); the numbers of the tests are unchanged since, the catalog was not re-run.

Query family Queries Within 3x of MergeTree, before → after
single-table filters: equality, IN, ranges, IS NULL, LIKE, functions, OR 22 5 → 20
the same filters on the month-partitioned table 7 3 → 7
deleted rows 7 7 → 7
join key types: dense and sparse integers, String, Float64, Decimal, Date, DateTime64, mostly NULL, expression, composite 17 11 → 11
2-way joins with a filtered side 7 1 → 3
multi-way shapes: star, chain, TPC-H Q3 and Q5 shapes, 6- and 7-way, LEFT JOIN, aggregation subquery 17 5 → 9
3- and 4-way joins sensitive to the number of distinct values of the keys 6 0 → 0
aggregation below a join 4 0 → 0
total 87 32 → 57

TPC-H and TPC-DS at SF1, written with IcebergLocal, use_iceberg_manifest_statistics 0 → 1 (4 threads, medians of 3, use_hash_table_stats_for_join_reordering = 0, results identical): TPC-DS 21.1 → 18.2 s, TPC-H 4.31 → 3.88 s; without the 1-row floor TPC-DS was 21.2 → 20.9 s, with q68 +326%, q46 +300% and q43 +167%. The worst queries left are q56 and q60, +44% (ca_gmt_offset = -5 estimated at 1%, the truth is 16%), and q72, +25%. Details: #123553 (comment). At SF10, a rerun at bdbf42e with the same settings gives TPC-H −18% and TPC-DS −12%; q56 (+59%), q60 (+17%) and q33 (+22%) remain, and q72 is +59% while its peak memory drops from 2.5 to 0.4 GB (#123553 (comment)).

Differences from the issue

  • The issue's rule from column_sizes divided by the type width is not used: the size of a dictionary-encoded column grows with its rows, not with its distinct values (l_discount of TPC-H SF10, 11 values, got 3,271,353).
  • Rule 3 is MergeTree's guess (10% of the rows) instead of the issue's guess by type (2 for Boolean, half the rows for strings, 30% otherwise).
  • Partial metrics are merged as MergeTree merges them (a file without a metric adds nothing), rather than leaving the statistic unset when one file lacks it, except for rule 1.
  • avg_bytes is not estimated: the manifests give only compressed sizes.

Known limitations

  • String, Decimal and floating-point columns have no measured number of distinct values, so = and IN on them take the default 1%, as on MergeTree without a uniq statistic; on a larger table this can be far below the truth (TPC-DS q56, q60). Measured numbers need the Iceberg table statistics (ndv in metadata.json), which are not read yet.
  • ClickHouse's Iceberg writer writes no bounds for floating-point columns, so ranges on them take the default 33%.
  • Rule 2 is an upper bound: an integer column with large gaps makes = more selective than it is.
  • The column statistics include deleted rows; Count deleted rows count for single files in iceberg join ordering #124395 subtracts from the row count the deleted rows it can count.

Tests: 05427 (a String column over two files), 05428 (conditions: equality, IN, IS NULL, ranges, pruning, identity partitions, a 4-way join, a filter above LIMIT, a row policy, a condition counted once, a 12-row table estimated at 1 row, also below an aggregation), 05298, 05299, 05339; 05292 and 05293 now show the estimated filters.

Changelog category (leave one):

  • Improvement

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

With use_iceberg_manifest_statistics, join reordering also uses the number of distinct values, min/max and NULL fraction of Iceberg columns, estimated from the manifest metrics of the data files without reading data, and estimates the filter, PREWHERE and row policy of an Iceberg read on them, as for MergeTree tables with column statistics. The setting now requires use_statistics.


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

Version info

  • Merged into: 26.11.1.1010-master (included in 26.11 and later)

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Oct 2, 2026
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-column-stats branch from 3b39196 to 5c1c948 Compare October 5, 2026 15:04
@antoniofilipovic antoniofilipovic changed the title Add column statistics for iceberg Estimate the column statistics of Iceberg reads from manifest files for join reordering Oct 6, 2026
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-column-stats branch from f874ade to 98e0d91 Compare October 6, 2026 11:17
@antoniofilipovic
antoniofilipovic marked this pull request as ready for review October 6, 2026 12:13

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the diff on top of #123085 and built it merged into current master (debug). The base is a feature branch, so CI has not run here; locally the five *_iceberg_manifest_stats_* tests of both PRs pass (pinned, and 25/25 over 10 randomized runs), clang-tidy is clean on every TU this PR touches apart from the bugprone-optional-value-conversion already raised on #123085, and the style check passes.

  • The description's rule 4 ("half the rows for String, 30% for the rest") is stale: since 40afa7d the code falls back to the estimator's 10% of the rows, which is what 05298 T9 expects.
  • Cost, for the description if it helps: on 5000 data files in one manifest, reading 20 columns, EXPLAIN takes 6 ms with the row estimate only and 82 ms with use_iceberg_manifest_column_statistics = 1 (debug build).
  • Nits: (plan O3) in ManifestColumnStatistics.h:138 points to a document the reader does not have, and the two decodeColumnBounds messages still say "skipping min/max pruning for this column" when the caller is the statistics path.

Comment on lines +224 to +227
/// A missing metric adds nothing, as a MergeTree part without the statistic.
statistics_builder.addStatistics(
targets[i].name,
ColumnStatistics::createBasicFromSummary(targets[i].storage_type, rows, metrics.min_value, metrics.max_value, metrics.nulls));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A file without null_value_counts for a column still adds a summary with its rows and nulls = 0, so its rows count as non-NULL rather than being skipped as the description says. MergeTree adds only the statistics a part has (MergeTreeData.cpp:1033-1035), so its NULL fraction is over the parts that have one.

Measured with a pyiceberg table: two 1000-row files with x NULL in every other row, the second written with write.metadata.metrics.column.x = none. countIf(x IS NULL) / count() is 0.5, the trace gives __table1.x: 999 [min 1, max 999, null 0.25] (the max is the documented partial merge of the bounds; the NULL fraction is not).

Making ColumnMetrics::nulls optional and skipping addStatistics for a Nullable target without it would match MergeTree. In Iceberg's metrics modes a column without counts (none) has no bounds either, so nothing else is lost.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: a file now adds nothing to a column when it has neither its NULL count nor its bounds, which is what the none metrics mode writes; with the bounds alone its NULL count is taken as 0. 05339 is your case, with a Spark fixture of two 1000-row files, the second written with write.metadata.metrics.column.x = none: the NULL fraction is 0.5 instead of 0.25.

@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-column-stats branch 3 times, most recently from 6ed1ff8 to e436df4 Compare October 7, 2026 15:01
@antoniofilipovic antoniofilipovic changed the title Estimate the column statistics of Iceberg reads from manifest files for join reordering Include the column statistics of Iceberg reads from manifest files for join reordering Oct 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3a2592]

Summary: ✅


AI Review

Summary

The PR derives Iceberg column statistics from manifest metrics and uses them to estimate read predicates for join planning. Request changes: nullable subcolumn predicates lose available statistics, and the previously reported runtime-filter transport guard remains deferred to another open PR.

Findings

⚠️ Majors

  • [P2] Nullable subcolumn predicates lose their parent statistics. ManifestColumnStatistics.cpp:91: requiredSourceColumns retains n.null, but tryGetPhysical skips it. The estimator recognizes n.null != 0 as a NULL check on n, then uses its default 1% because n was never collected. With the 05428 T1 fixture and optimize_move_to_prewhere = 0, this estimates 100 rows instead of the 9,000 estimated for equivalent n IS NULL, potentially changing join ordering. Resolve nullable subcolumns to their storage parent and deduplicate targets.

  • [P2] Runtime-filter transport still consumes a selectivity guess. RelationStatisticsEstimator.cpp:333 [dismissed by author -- https://github.com/Include the column statistics of Iceberg reads from manifest files for join reordering #123553#discussion_r4327451337]: the author deliberately deferred the guard to Use iceberg row and column stats for Cascades CBO #124857, which remains open. This head still ignores for_runtime_filter_transport in the Iceberg branch. An unpruned k % 2 = 0 over 10 million rows supplies a 100,000-row guess to makeTransportBudget, raising exact-set limits before five million actual keys force conversion to a Bloom filter. Keep guesses out of transport sizing in this PR, as the existing MergeTree branch does. No duplicate inline comment was posted.

Tests
  • ⚠️ Add an EXPLAIN comparison of n IS NULL and n.null != 0 using the existing 05428 fixture, with optimize_move_to_prewhere = 0; both should use the manifest NULL fraction. This finding follows the source path; no local ClickHouse executable or build was available to execute the comparison.
  • ⚠️ Cover a transported runtime filter built from a filtered Iceberg read, verifying that an unpruned predicate's selectivity guess does not enlarge the configured exact-set limits.
Final Verdict

⚠️ Request changes — collect the parent statistics for nullable subcolumns and include the runtime-filter transport guard before merging this PR independently.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 8, 2026
@antoniofilipovic
antoniofilipovic force-pushed the afilipovic-iceberg-column-stats branch from e436df4 to d4683d3 Compare October 8, 2026 11:00
bool hasCountableValues(const IDataType & type)
{
const WhichDataType which(type);
return which.isNativeInteger() || which.isDate() || which.isDate32() || which.isDateTime() || which.isDateTime64();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as canStatisticsTrackMinMax ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, we need here only the ones which are countable so max-min+1 gives number of distinct values. For float which is not here, max - min + 1 would not give number of distinct values, (i.e if values are 7.1, 7.2, ..., 7.9) max - min + 1 is 1.8, where NDV is 9, but for ints that works and other types here.

/// A timestamp counts microseconds, but its values usually step by thousands of them or more, so its range is far
/// above the rows and the clamp below gives the estimate.
else if (range_width)
num_distinct_values = *range_width;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why it can use range_width to estimate the NDV

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is based on comment above with hasCountableValues, so if the values lie between min and max you can use range width to estimate NDV. however, it can be wrong for dense keys or sparse ones, so we use minimum between the two of range_width and number of non null rows. Imagine a case where we have sparse keys in range from 1 to 100 000 but actually every 10 000th key appears, and you have only 1000 values. So NDV with range_width would be 100k, with num_rows it is 1000. We would estimate 1000.

@@ -59,6 +62,11 @@ struct DataLakeReadEstimate
bool pruned_data_files = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If all data files are pruned by filter, what is the purpose of the DataLakeReadEstimate? Can we just return nullptr instead of an estimate

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The meaning of the flag pruned_data_files is we pruned one file at least. When we pruned all of them we actually have rows=0 so the estimation is exact and you get something like this for join: m[0] ⋈ t[0]. So for that case we cannot return nullptr. And why do we have that flag at all, when we pruned at least one file, but we have a filter which could have pruned, we return unknown estimate, here. This is to follow MergeTree statistics what it does in the same case.

In the last PR that is changed, and if you have column statistics, we make an estimate on top of filter, then we do not return unknown row count

bool has_delete_files = false;
/// Statistics of the requested columns over the remaining data files, merged as those of MergeTree parts;
/// nullptr unless `rows` is known and positive.
ConditionSelectivityEstimatorPtr column_statistics;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now we have column_statistics in DataLakeReadEstimate, which both contain rows and num_distinct_values. Why not only return column_statistics and get estimates by estimateRelationProfile and get everything we need

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that simplification makes sense. I will try to apply it today and will post here the results.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, implemented the simplification


auto estimate = reading->estimateReadFromDataLakeMetadata();
if (!estimate)
return RelationStats{};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sometimes we return RelationStats{} and sometimes unknown; What is the difference?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is more of a semantic meaning than the join order difference meaning. RelationStats{} means the stats for iceberg are not called at all, there is no estimate at all, since the feature is disabled or missing. With unknown, we tried to figure out, but there is no data or something is missing. On the EXPLAIN the difference is manifested in the label of output. The RelationStats{} shows only b, and unknown as b[no_stats~?]. I think it is okay to have a semantic difference between these two, but on the output there is no difference. I will add a comment explaining.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 1, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 3, 2026
…-iceberg-nan-manifest-pruning

Master ClickHouse#123553 moved the per-column bound decoding of
getDataFileHyperrectangles into decodeColumnBounds, which returns
std::optional<ColumnBounds>. The NaN-bound guard now lives there, so it
returns std::nullopt instead of continuing the old loop, and it also
covers the new getDataFileColumnBounds caller (manifest column
statistics), which must not report a NaN as a column minimum or maximum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to raimannma/ClickHouse that referenced this pull request Nov 7, 2026
With `use_iceberg_manifest_statistics`, an Iceberg read gets a counted
number of distinct values only from the manifests: identity partition
values and `max - min + 1` of integer/date bounds. Every other column
(`String`, `Decimal`, floats, sparse keys) keeps the estimator guesses
(1% for `=`, 10% of the rows as NDV), which is what is left of the
TPC-DS q33/q56/q60 regressions after ClickHouse#123553 (`ca_gmt_offset = -5` on a
`Decimal(5, 2)` is estimated at 1% while 16% of the rows match).

Spark `compute_table_stats` and Trino `ANALYZE` write the NDV of each
column into `metadata.json`: `statistics[].blob-metadata[]` with type
`apache-datasketches-theta-v1`, one field id and `properties.ndv`. The
new setting `use_iceberg_table_statistics_ndv` (default off) makes the
read take it as a third NDV rule, after the two manifest rules, so a
manifest count keeps priority (overriding it made TPC-H q21 2x slower
in the prototype on ClickHouse#123553).

As in Spark's `SparkScan.estimateStatistics`, only the first statistics
file whose `snapshot-id` is the read snapshot is used; statistics of an
older snapshot are stale after an append, and the prototype's ancestor
fallback reported 7 distinct values for 10. Blobs over several fields
count combinations and are skipped. The table-wide NDV is clamped to the
non-NULL rows of the read, as the existing rules are, so a pruned read
uses it as an upper bound, as Spark does.

The statistics are optional metadata, so a malformed entry is skipped
and never fails the query; the parse uses Poco's null-returning
accessors and runs only inside `estimateRead` with the setting on.

The test uses a fixture written by Spark 4.0 / Iceberg 1.11
(`compute_table_stats` over 3000 rows) and covers the current snapshot
with the setting on and off, a ClickHouse append (the statistics of the
previous snapshot are ignored) and time travel back to the analyzed
snapshot.

Closes ClickHouse#129260

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@antoniofilipovic

Copy link
Copy Markdown
Member Author

884 0.66 (0.62–0.69)
q60 1378 951 0.70 (0.67–0.73)
q96 349

Can you calculate q-error for this, I think that would be more beneficial than improvements we have, and please open then new issue:
q-err = max(true_val / est_val, est_val / true_val)

@antoniofilipovic

Copy link
Copy Markdown
Member Author

@snelheidai cc ^^

@snelheidai

Copy link
Copy Markdown

@antoniofilipovic Here is the q-error of the join-order estimates, on TPC-DS SF10 written to Iceberg by ClickHouse and analyzed with Spark compute_table_stats as before, on master 0d3338b with use_iceberg_manifest_statistics = 1 and use_iceberg_table_statistics_ndv 0 vs 1. Each join's q-error is the one EXPLAIN ANALYZE prints for its output rows. The table shows the maximum (median) over the joins of each query:

Query Joins NDV off NDV on Main input estimate, off → on (actual rows)
q33 9 37.5 (22.7) 1.75 (1.36) customer_address, ca_gmt_offset = -5: 2,420 → 40,420 (90,670)
q56 9 37.5 (20.1) 1.92 (1.84) same
q60 9 49.3 (37.2) 3.01 (2.80) same
q96 3 13.1 (7.2) 1.91 (1.49) store, s_store_name = 'ese': 1 → 10 (14)
q07 4 381,973 (228,787) 1.08 (1.08) customer_demographics: 2 → 27,440 (27,440); promotion: 10 → 500 (498)
q70 2 34.0 (32.9) 1.05 (1.04) store, s_state IN (...): 3 → 102 (102)

With NDV on, q07 and q70 get slower even though their estimates are almost exact, so their slowdown is not an estimation error. For q07 it comes from the runtime filters described in my earlier comment.

Over all 95 single-statement queries, 509 joins have an estimate in both settings:

NDV off NDV on
Median q-error 2.61 1.34
90th percentile 203 9.0
Joins with q-error > 10 164 48
Joins with q-error > 100 54 21
Queries whose worst join is > 10 46 of 92 19 of 92
90th percentile of the 803 table and subquery inputs 14.0 2.19

The worst join improves more than 2x in 31 queries and gets more than 2x worse in two:

  • q31, 5.3e8 → 1.8e12: its GROUP BY ca_county, d_qoy, d_year CTEs are estimated at 358K–672K rows instead of about 1,850. With the true NDV of ca_county (1,846 instead of the default 25,000, 10% of customer_address), each join between these CTEs is estimated as the product of their rows divided by 1,846, which multiplies that error.
  • q84, 2.1 → 8.7: ca_city = 'Edgewood' is estimated at 250 rows (1/969 of the non-NULL rows) and matches 2,210. Edgewood is a frequent value, and the 1% default happened to be closer.

The largest remaining errors are in q17, q25 and q29 (0–3 rows estimated at 175K–727K, with keys correlated across store_returns, store_sales and catalog_sales), the top-10 subqueries of q44 (102,000 rows estimated for 10), and the item filter of q53 and q63 (14 rows estimated for 5,280). That filter is an OR of two conjunctions of IN lists on the correlated i_category, i_class and i_brand.

Method
  • One EXPLAIN ANALYZE per query and setting; the estimates are deterministic. Input q-errors come from the Left / Right lines (rows estimated vs rows) of joins whose side is a table or a subquery. An actual 0 counts as 1 row.
  • enable_join_runtime_filters = 0. With runtime filters on (the default), a filter built for an upper join is applied to the scan under the lower joins. Those joins then report fewer actual rows than their true cardinality, so the q-error is overstated (NDV on: 90th percentile 36 instead of 9.0). Join orders and estimates are the same either way.
  • use_hash_table_stats_for_join_reordering = 0 and collect_hash_table_stats_during_joins = 0, so the estimates come only from the statistics. The other settings are from tests/benchmarks/tpc-ds/settings.json.
  • 131 joins have no estimate in either setting and are left out, mostly in q64, q04, q72, q11, q74 and q54. With use_iceberg_manifest_statistics = 0, no join has an estimate.
  • q14, q23, q24 and q39 have two statements each and are skipped.
  • The data was generated and written by ClickHouse as for my earlier comments, then analyzed again with Spark 4.0.5 and Iceberg 1.12.0. Some of the resulting NDVs: ca_gmt_offset 6, ca_county 1,846, ca_city 969, and cd_gender, cd_marital_status, cd_education_status 2, 5 and 7. The binary is the official aarch64 build of master 0d3338b, run on a 4-vCPU VM.

I've posted these here rather than in a new issue, because they don't come with a change to propose.

@antoniofilipovic

Copy link
Copy Markdown
Member Author

Can you run it also on SF100 TPCDS? @snelheidai and what methodology did you use to run it can you post the queries and runner info?

@snelheidai

Copy link
Copy Markdown

@antoniofilipovic On TPC-DS SF100 the q-errors look the same as on SF10. This is the measurement of my previous comment, on master 6618395, whose changes since 0d3338b do not touch the estimation code. Over the joins with an estimate in both settings (509 joins of 95 queries at SF10, 508 of 94 at SF100):

SF10, NDV off SF10, NDV on SF100, NDV off SF100, NDV on
Median q-error 2.61 1.34 2.77 1.38
90th percentile 203 9.0 357 8.4
Joins with q-error > 10 164 48 159 45
Joins with q-error > 100 54 21 65 22
Queries whose worst join is > 10 46 of 92 19 of 92 43 of 91 17 of 91
90th percentile of the table and subquery inputs 14.0 2.19 11.2 2.21

The queries of my previous comment at SF100, maximum (median) over their joins:

Query Joins NDV off NDV on Main input estimate, off → on (actual rows)
q33 9 37.6 (22.3) 1.75 (1.34) customer_address, ca_gmt_offset = -5: 9,700 → 161,650 (364,760)
q56 9 37.6 (20.2) 1.94 (1.83) same
q60 9 49.4 (37.4) 2.98 (2.79) same
q96 3 12.8 (6.83) 1.92 (1.50) store, s_store_name = 'ese': 4 → 40 (55)
q07 4 767,291 (766,220) 1.07 (1.06) customer_demographics: 2 → 27,440 (27,440); promotion: 20 → 1,000 (995)
q70 2 11.3 (10.9) 1.05 (1.04) store, s_state IN (...): 36 → 400 (400)

As at SF10, the worst join improves more than 2x in 31 queries and gets more than 2x worse in q31 (2.1e11 → 6.4e12) and q84 (2.1 → 8.9), for the same reasons. The largest remaining errors are in the same queries. Two errors that do not depend on the setting grow with the scale: q59 from 202 to 772 (its weekly aggregates R0 and R3 are estimated at 4.17M rows for 52,920) and q51 from 12 to 118 (the full join of its two window CTEs is estimated at 3.42 billion rows for 29.0 million).

The ROLLUP of q67 exceeded 20 GB, so q67 ran with max_memory_usage = 27000000000 and external aggregation and sorting from 8 GB, which do not change the estimates. q72 is left out because its run without NDV did not finish within 1,200 s with runtime filters off.

Method and runners
  • Data. dsdgen of gregrahn/tpcds-kit at 5a3a8179 (TPC-DS 2.10.0), -scale 10 or -scale 100, 4 parallel children. The .dat files were loaded into MergeTree tables created by tests/benchmarks/tpc-ds/init.sql with data_type_default_nullable = 1 (| replaced by tabs, TabSeparatedRaw, an empty field is NULL). ClickHouse then copied each table with INSERT ... SELECT into an IcebergLocal table: Parquet (zstd), format version 2, unpartitioned, no sort order, about 1M rows per data file (the default iceberg_insert_max_rows_in_data_file). FixedString(N) columns became String with the zero padding cut, UInt32 became Int64, and nullability was kept. The SF10 tables were written by a 26.11 build from the end of October (26.11.1.941), the SF100 tables by the measured binary.
  • Statistics. Spark 4.0.5 with Iceberg 1.12.0 (local[4], a Hadoop catalog on the local files) ran CALL system.compute_table_stats(table => ...) for each of the 24 tables, which covers all columns. This writes one apache-datasketches-theta-v1 blob with an ndv property per column into a Puffin file and adds it to the statistics of metadata.json. Spark ran on copies of the tables' metadata, which share the data files.
  • Arms. One server, one ENGINE = IcebergLocal('<table dir>', 'Parquet') table per table. Both arms use the settings of tests/benchmarks/tpc-ds/settings.json, use_statistics = 1, use_iceberg_manifest_statistics = 1, use_hash_table_stats_for_join_reordering = 0, collect_hash_table_stats_during_joins = 0 and enable_join_runtime_filters = 0. NDV off is use_iceberg_table_statistics_ndv = 0, NDV on is = 1. The limits were max_memory_usage = 20000000000 and max_execution_time 300 s at SF10, 1,200 s at SF100. The rest is default, including query_plan_optimize_join_order_algorithm = 'dpsub,greedy' and query_plan_optimize_join_order_limit = 10.
  • Measurement. EXPLAIN ANALYZE of each query, once per arm. Each Join step gives its estimate and actual in Output rows: estimated E · actual A · q-error Q, and those of its inputs in the Left: / Right: lines (rows estimated E · rows A); an input counts when it is a table read or a subquery rather than another join. q-error = max(E / A, A / E), with 0 counted as 1. Both arms run the same statements, so a query has the same number of joins in both; joins are paired by position, and a join counts when it has an estimate in both arms. Per query, the table gives the maximum and median over its joins.
  • Queries. The queries in tests/benchmarks/tpc-ds/queries (ClickHouse's adaptation, with the changes listed in the README; unchanged since June), with EXPLAIN ANALYZE prepended and the final ; removed. q14, q23, q24 and q39 consist of two statements and were skipped, which leaves 95.
  • Runners. SF10: AWS r7g.xlarge (4 vCPU Graviton3, 32 GiB RAM, 500 GB EBS volume) with the official aarch64 build of master 0d3338b. SF100: r6i.xlarge (4 vCPU Xeon Platinum 8375C, 32 GiB RAM, 500 GB EBS volume) with the official x86-64 build of master 6618395. The estimates and the actual row counts do not depend on the hardware.
Scripts

build100.sh generates the data and writes the Iceberg tables. The SF10 tables were built the same way with SCALE=10, all tables in one pass:

#!/usr/bin/env bash
# TPC-DS SF100 for PR #123553 with the recipe of the SF10 tables:
# tpcds-kit 5a3a8179 dsdgen -parallel 4 -> MergeTree tables of tests/benchmarks/tpc-ds/init.sql (data_type_default_nullable=1,
# '|' -> TAB, TabSeparatedRaw, empty field = NULL) -> ClickHouse-written IcebergLocal Parquet copies by INSERT ... SELECT
# (FixedString(N) -> String cut at zero, UInt32 -> Int64). One dsdgen table at a time to bound disk: raw files are removed after
# the MergeTree load, the MergeTree table after its Iceberg copy. Resumable through $W/done/<table>.
set -Eeuo pipefail
W=/data/tpcds; KIT=$W/tools/tpcds-kit; RAW=$W/raw; SRV=$W/srvload; ICE=$W/user_files/ice100
CH=$W/bin/clickhouse; PORT=9781; SCALE=100; PAR=4
mkdir -p $W/logs $SRV/tmp $ICE $RAW $W/done
stage() { echo "=== [$(date -u +%H:%M:%S)] $* ==="; }
cat > $SRV/config.xml <<XML
<clickhouse>
  <logger><level>warning</level><log>$W/logs/load-server.log</log><errorlog>$W/logs/load-server.err.log</errorlog></logger>
  <tcp_port>$PORT</tcp_port><listen_host>127.0.0.1</listen_host>
  <path>$SRV/</path><tmp_path>$SRV/tmp/</tmp_path><user_files_path>$W/user_files/</user_files_path>
  <users><default><password></password><networks><ip>::/0</ip></networks><profile>default</profile><quota>default</quota><access_management>1</access_management></default></users>
  <profiles><default><max_memory_usage>25000000000</max_memory_usage></default></profiles><quotas><default></default></quotas>
</clickhouse>
XML
$CH server --config-file=$SRV/config.xml > $W/logs/load-server.out 2>&1 & SPID=$!
trap 'kill $SPID 2>/dev/null; wait $SPID 2>/dev/null' EXIT
for w in $(seq 1 120); do $CH client --port $PORT -q "SELECT 1" >/dev/null 2>&1 && break; sleep 1; done
cli() { $CH client --port $PORT "$@"; }
cli -q "SELECT version()"
if [ ! -f $W/done/.mt_created ]; then
  stage "create MergeTree tables"
  cli -q "DROP DATABASE IF EXISTS mt SYNC"; cli -q "CREATE DATABASE mt"
  cli --database mt --data_type_default_nullable=1 --multiquery < $W/init.sql
  [ "$(cli -q "SELECT count() FROM system.tables WHERE database = 'mt'")" = 24 ] || { echo "init.sql did not create 24 tables"; exit 1; }
  touch $W/done/.mt_created
fi
cli -q "CREATE DATABASE IF NOT EXISTS ice100"

gen() {  # dsdgen for one table (fact tables also write their returns table)
  local t=$1 pids=() rc=0
  stage "generate $t SF$SCALE"
  for c in $(seq 1 $PAR); do ( cd $KIT/tools && ./dsdgen -scale $SCALE -dir $RAW -terminate n -force -parallel $PAR -child $c -table $t > $W/logs/dsdgen-$t-$c.log 2>&1 ) & pids+=($!); done
  for p in "${pids[@]}"; do wait $p || rc=1; done
  [ $rc = 0 ] || { tail -5 $W/logs/dsdgen-$t-*.log; exit 1; }
  ls -la $RAW | tail -n +2 | awk '{s+=$5} END {printf "raw %.1f GB\n", s/1e9}'
}
load() {  # raw files -> MergeTree, then remove the raw files
  local t=$1 files=() g
  for g in $RAW/${t}_[0-9]*_[0-9]*.dat $RAW/${t}.dat; do [ -f "$g" ] && files+=("$g"); done
  [ ${#files[@]} -gt 0 ] || { echo "no raw files for $t"; exit 1; }
  stage "load $t (${#files[@]} files)"
  cli -q "TRUNCATE TABLE mt.\`$t\`"
  cat -- "${files[@]}" | tr '|' '\t' | cli -q "INSERT INTO mt.\`$t\` FORMAT TabSeparatedRaw" --format_tsv_null_representation='' --input_format_null_as_default=0 --max_insert_threads=4
  local have; have=$(cli -q "SELECT count() FROM mt.\`$t\`")
  echo -e "$t\t$have" >> $W/rowcounts.tsv
  rm -f -- "${files[@]}"
}
copy() {  # MergeTree -> IcebergLocal Parquet, then drop the MergeTree table
  local t=$1 cols sel a b
  stage "iceberg $t"
  cols=$(cli -q "SELECT arrayStringConcat(groupArray(concat('\`', name, '\` ', replaceRegexpAll(replaceRegexpAll(type, 'FixedString\\\\(\\\\d+\\\\)', 'String'), 'UInt32', 'Int64'))), ', ') FROM (SELECT name, type FROM system.columns WHERE database = 'mt' AND table = '$t' ORDER BY position)")
  sel=$(cli -q "SELECT arrayStringConcat(groupArray(if(type LIKE '%FixedString%', concat('toStringCutToZero(\`', name, '\`)'), concat('\`', name, '\`'))), ', ') FROM (SELECT name, type FROM system.columns WHERE database = 'mt' AND table = '$t' ORDER BY position)")
  rm -rf "$ICE/$t"
  cli -q "DROP TABLE IF EXISTS ice100.\`$t\`"
  cli -q "CREATE TABLE ice100.\`$t\` ($cols) ENGINE = IcebergLocal('$ICE/$t/', 'Parquet')"
  cli --allow_insert_into_iceberg=1 -q "INSERT INTO ice100.\`$t\` SELECT $sel FROM mt.\`$t\`"
  a=$(cli -q "SELECT count() FROM mt.\`$t\`"); b=$(cli -q "SELECT count() FROM ice100.\`$t\`")
  echo -e "$t\t$a\t$b" | tee -a $W/icecounts.tsv
  [ "$a" = "$b" ] || { echo "iceberg count mismatch $t"; exit 1; }
  cli -q "DROP TABLE mt.\`$t\` SYNC"
  touch $W/done/$t
}
# parent table: tables it writes
for spec in store_sales:store_sales,store_returns catalog_sales:catalog_sales,catalog_returns web_sales:web_sales,web_returns \
            inventory:inventory customer:customer customer_address:customer_address customer_demographics:customer_demographics \
            date_dim:date_dim time_dim:time_dim item:item household_demographics:household_demographics catalog_page:catalog_page \
            promotion:promotion store:store web_page:web_page call_center:call_center web_site:web_site warehouse:warehouse \
            income_band:income_band reason:reason ship_mode:ship_mode; do
  p=${spec%%:*}; ts=${spec#*:}; ts=${ts//,/ }
  pending=0; for t in $ts; do [ -f $W/done/$t ] || pending=1; done
  [ $pending = 1 ] || continue
  rm -f $RAW/*.dat
  gen $p
  for t in $ts; do [ -f $W/done/$t ] || load $t; done
  rm -f $RAW/*.dat
  for t in $ts; do [ -f $W/done/$t ] || copy $t; done
  df -h / | tail -1
done
[ "$(ls $W/done | wc -l)" = 24 ] || { echo "not all tables done: $(ls $W/done | wc -l)"; exit 1; }
cli -q "SELECT i_category, count() FROM ice100.item GROUP BY 1 ORDER BY 1 LIMIT 3"
cli -q "SELECT count() FROM ice100.item WHERE i_category = 'Books'"
du -sh $ICE; df -h / | tail -1
stage "BUILD_DONE"

mkstats100.sh adds the Spark statistics:

#!/usr/bin/env bash
# Metadata-only copies of the CH-written TPC-DS SF100 Iceberg tables (ice100, location rewritten, data files shared),
# then Spark 4.0.5 + Iceberg 1.12.0 compute_table_stats (theta sketches of all columns) on the copies.
set -euo pipefail
W=/data/tpcds; SRC=$W/user_files/ice100; NS=ice100st; DST=$W/user_files/$NS
mkdir -p $DST
for t in $(ls $SRC); do
  if [ ! -d "$DST/$t/metadata" ]; then
    mkdir -p "$DST/$t/metadata"
    latest=$(ls "$SRC/$t/metadata" | grep -E '^v[0-9]+\.metadata\.json$' | sed -E 's/^v([0-9]+).*/\1/' | sort -n | tail -1)
    python3 - "$SRC/$t/metadata/v$latest.metadata.json" "$DST/$t/metadata/v$latest.metadata.json" "$DST/$t/" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); d['location'] = sys.argv[3]
json.dump(d, open(sys.argv[2], 'w'), indent=2)
PY
    echo "$t v$latest"
  fi
done
SQL=$W/stats-$NS.sql; : > $SQL
for t in $(ls $DST); do
  ls $DST/$t/metadata | grep -q '\.stats$' || echo "CALL loc.system.compute_table_stats(table => '$NS.$t');" >> $SQL
done
wc -l < $SQL
if [ -s $SQL ]; then
docker run --rm --user 1000:1000 -v $W:$W -e HOME=/tmp -w /tmp eclipse-temurin:21-jdk bash -c "time $W/tools/spark-4.0.5-bin-hadoop3/bin/spark-sql --master 'local[4]' --driver-memory 10g \
  --jars $W/tools/iceberg-spark-runtime-4.0_2.13-1.12.0.jar \
  --conf spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions \
  --conf spark.sql.catalog.loc=org.apache.iceberg.spark.SparkCatalog \
  --conf spark.sql.catalog.loc.type=hadoop \
  --conf spark.sql.catalog.loc.warehouse=file://$W/user_files \
  --conf spark.ui.enabled=false \
  -f $SQL" > $W/stats-$NS.out 2> $W/stats-$NS.err || { echo SPARK_FAILED; tail -30 $W/stats-$NS.err; exit 1; }
fi
grep -E "Time taken|^real|^user|^sys" $W/stats-$NS.err | tail -30
ls $DST/*/metadata/*.stats | wc -l
du -ch $DST/*/metadata/*.stats | tail -1
echo STATS_DONE

ea100.sh rf0 0 'off on' runs the queries, on a server with the default configuration apart from max_memory_usage = 25000000000:

#!/usr/bin/env bash
# usage: ea100.sh OUTDIR RF "ARMS" [QUERY_NUM...] : EXPLAIN ANALYZE per query and arm
#   none: use_iceberg_manifest_statistics 0; off: manifest 1 + use_iceberg_table_statistics_ndv 0; on: manifest 1 + ndv 1
set -uo pipefail
W=/data/tpcds; CH=$W/bin/clickhouse; PORT=9782
Q=$W/tpcds/queries
OUT=$W/out/$1; RF=$2; ARMS=$3; shift 3; mkdir -p $OUT
QSET="--data_type_default_nullable=1 --group_by_use_nulls=1 --intersect_default_mode=DISTINCT --joined_subquery_requires_alias=0 --join_use_nulls=1 --union_default_mode=DISTINCT"
BASE="$QSET --max_memory_usage 20000000000 --max_execution_time 1200 --use_statistics 1 --use_hash_table_stats_for_join_reordering 0 --collect_hash_table_stats_during_joins 0 --enable_join_runtime_filters $RF ${EXTRA:-}"
declare -A XARM=([none]="--use_iceberg_manifest_statistics 0 --use_iceberg_table_statistics_ndv 0" [off]="--use_iceberg_manifest_statistics 1 --use_iceberg_table_statistics_ndv 0" [on]="--use_iceberg_manifest_statistics 1 --use_iceberg_table_statistics_ndv 1")
[ "$#" -eq 0 ] && set -- $(seq 1 99)
for n in "$@"; do
  case $n in 14|23|24|39) continue;; esac   # two statements each
  f=$(printf "$Q/query_%02d.sql" $n)
  for arm in $ARMS; do
    o=$OUT/q$(printf %02d $n)-$arm
    [ -s $o.txt ] && continue
    s=$(date +%s.%N)
    { echo "EXPLAIN ANALYZE"; sed -e 's/;[[:space:]]*$//' "$f"; } | timeout 1300 $CH client --port $PORT --database ice100st $BASE ${XARM[$arm]} > $o.txt 2> $o.err
    rc=$?; e=$(date +%s.%N)
    awk -v n=$n -v a=$arm -v r=$rc -v s=$s -v e=$e 'BEGIN { printf "q%02d\t%s\t%s\t%.1f\n", n, a, r, e - s }' >> $OUT/times.tsv
    [ $rc = 0 ] || { echo "q$n $arm rc=$rc $(head -c 300 $o.err)"; mv $o.txt $o.failed.txt; }
  done
done
echo "EA_DONE $(ls $OUT/*.txt | grep -v failed | wc -l) files"

qerr.py out/rf0 off,on extracts the q-errors into joins.csv:

#!/usr/bin/env python3
"""Parse EXPLAIN ANALYZE outputs (qNN-ARM.txt) into join-level q-errors.

q-error = max(est/act, act/est). Join outputs use the estimate the join-order optimizer attached to the
join step; join inputs use the per-side 'rows estimated' vs 'rows'. A side is a leaf (a relation of the
join graph: a filtered table read or a subquery) when it is not itself a join of this plan.
Zero values are clamped to 1 row (only for the q-error; ClickHouse prints no q-error then).
"""
import csv, glob, json, math, os, re, statistics, sys

QTY = re.compile(r'(no stats|[\d.]+(?:e[+-]?\d+)?)(?: (thousand|million|billion|trillion|quadrillion))?')
MULT = {None: 1, 'thousand': 1e3, 'million': 1e6, 'billion': 1e9, 'trillion': 1e12, 'quadrillion': 1e15}
STEP = re.compile(r'^([\s│]*)(?:[├└]──)?([A-Za-z][A-Za-z ]*?) \(')
PREFIX = re.compile(r'^[\s│├└─]*')


def qty(text):
    m = QTY.match(text.strip())
    if not m or m.group(1) == 'no stats':
        return None
    return float(m.group(1)) * MULT[m.group(2)]


def qerr(est, act):
    if est is None or act is None:
        return None
    e, a = max(est, 1.0), max(act, 1.0)
    return max(e / a, a / e)


def split_top(rel):
    """Split 'a ⋈ b ⋈ (c ⋈ d)' on top-level ⋈."""
    parts, depth, cur = [], 0, ''
    i = 0
    while i < len(rel):
        ch = rel[i]
        if ch == '(':
            depth += 1
        elif ch == ')':
            depth -= 1
        if depth == 0 and rel.startswith(' ⋈ ', i):
            parts.append(cur); cur = ''; i += 3; continue
        cur += ch; i += 1
    parts.append(cur)
    return [p.strip() for p in parts]


def short(label):
    return re.sub(r'\[[^\]]*\]', '', label or '?')


def parse_file(path):
    lines = open(path, encoding='utf-8').read().split('\n')
    joins = []
    cur = None
    for line in lines:
        body = PREFIX.sub('', line)
        if re.match(r'^(?:[│\s]*)(?:[├└]──)?Join \(', line.lstrip()) or body.startswith('Join ('):
            if cur:
                joins.append(cur)
            cur = {'step': body}
            continue
        if cur is None:
            continue
        if STEP.match(line) and not line.lstrip(' │').startswith(('Input', 'Type', 'Join conditions')) and '──' in line:
            joins.append(cur); cur = None
            continue
        if '⋈' in body and 'rel' not in cur:
            cur['rel'] = body
        elif body.startswith('Type:'):
            cur['type'] = body
        elif body.startswith('Join conditions:') and 'cond' not in cur:
            cur['cond'] = body[len('Join conditions:'):].strip()
        elif body.startswith('Output rows:'):
            m = re.match(r'Output rows: estimated (.*?) · actual (.*?)(?: · q-error (.*))?$', body)
            if m:
                cur['est'], cur['act'] = qty(m.group(1)), qty(m.group(2))
                cur['ch_q'] = float(m.group(3)) if m.group(3) else None
        elif body.startswith('Left:') or body.startswith('Right:'):
            side = 'left' if body.startswith('Left:') else 'right'
            m = re.match(r'(?:Left|Right): +rows estimated (.*?) · rows (.*?)(?: · |$)', body)
            if m:
                cur[side + '_est'], cur[side + '_act'] = qty(m.group(1)), qty(m.group(2))
    if cur:
        joins.append(cur)
    out = []
    for j in joins:
        rel = j.get('rel') or ''
        if not rel:
            j['rel'] = '{' + (j.get('cond') or j.get('step', '')) + '}'
        parts = split_top(rel) if rel else []
        left_label = ' ⋈ '.join(parts[:-1]) if len(parts) >= 2 else ''
        right_label = parts[-1] if parts else ''
        j['left_label'], j['right_label'] = left_label, right_label
        j['left_leaf'] = len(parts) == 2
        j['right_leaf'] = bool(right_label) and not right_label.startswith('(')
        j['q_out'] = j.get('ch_q') or qerr(j.get('est'), j.get('act'))
        j['q_left'] = qerr(j.get('left_est'), j.get('left_act'))
        j['q_right'] = qerr(j.get('right_est'), j.get('right_act'))
        out.append(j)
    return out


def gmean(xs):
    return math.exp(sum(math.log(x) for x in xs) / len(xs)) if xs else None


def pct(xs, p):
    if not xs:
        return None
    s = sorted(xs)
    k = (len(s) - 1) * p
    f, c = math.floor(k), math.ceil(k)
    return s[f] if f == c else s[f] + (s[c] - s[f]) * (k - f)


def main(d, arms):
    rows = []
    for path in sorted(glob.glob(os.path.join(d, 'q*-*.txt'))):
        q, arm = os.path.basename(path)[:-4].split('-')
        if arm not in arms:
            continue
        for i, j in enumerate(parse_file(path)):
            rows.append({'query': q, 'arm': arm, 'idx': i, **{k: j.get(k) for k in (
                'rel', 'type', 'est', 'act', 'ch_q', 'q_out', 'left_label', 'left_est', 'left_act', 'q_left', 'left_leaf',
                'right_label', 'right_est', 'right_act', 'q_right', 'right_leaf')}})
    with open(os.path.join(d, 'joins.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader(); w.writerows(rows)
    # per query / arm summary
    per = {}
    for r in rows:
        per.setdefault((r['query'], r['arm']), []).append(r)
    summ = {}
    for (q, arm), js in sorted(per.items()):
        outs = [(r['q_out'], r) for r in js if r['q_out'] is not None]
        leaves = []
        for r in js:
            for side in ('left', 'right'):
                if r[side + '_leaf'] and r['q_' + side] is not None:
                    leaves.append((r['q_' + side], r[side + '_label'], r[side + '_est'], r[side + '_act']))
        nostats = sum(1 for r in js if r['est'] is None)
        s = {'joins': len(js), 'joins_est': len(outs), 'joins_no_est': nostats}
        if outs:
            qs = [x for x, _ in outs]
            worst = max(outs, key=lambda t: t[0])
            s.update(max_out=max(qs), med_out=statistics.median(qs), gm_out=gmean(qs),
                     worst_out=f"{short(worst[1]['rel'])}: est {worst[1]['est']:.0f} / act {worst[1]['act']:.0f}")
        if leaves:
            lq = [x[0] for x in leaves]
            wl = max(leaves, key=lambda t: t[0])
            s.update(max_in=max(lq), med_in=statistics.median(lq), worst_in=f"{short(wl[1])}: est {wl[2]:.0f} / act {wl[3]:.0f}")
        summ[(q, arm)] = s
    with open(os.path.join(d, 'summary.json'), 'w') as f:
        json.dump({f'{q}-{a}': v for (q, a), v in summ.items()}, f, indent=1)
    # suite-wide per arm
    print('arm  joins_est  no_est  median  gmean   p90      max     >2   >10   >100  | leaf_in: n median p90 max >10')
    for arm in arms:
        qs = [r['q_out'] for r in rows if r['arm'] == arm and r['q_out'] is not None]
        ne = sum(1 for r in rows if r['arm'] == arm and r['est'] is None)
        li = [r['q_' + s] for r in rows if r['arm'] == arm for s in ('left', 'right') if r[s + '_leaf'] and r['q_' + s] is not None]
        if not qs:
            continue
        print(f"{arm:4} {len(qs):9d} {ne:7d} {statistics.median(qs):7.2f} {gmean(qs):7.2f} {pct(qs, .9):8.1f} {max(qs):9.0f} "
              f"{sum(q > 2 for q in qs):5d} {sum(q > 10 for q in qs):5d} {sum(q > 100 for q in qs):5d}  | "
              f"{len(li)} {statistics.median(li):.2f} {pct(li, .9):.1f} {max(li):.0f} {sum(q > 10 for q in li)}")
    return rows, summ


if __name__ == '__main__':
    d = sys.argv[1]
    arms = sys.argv[2].split(',') if len(sys.argv) > 2 else ['none', 'off', 'on']
    main(d, arms)

an100.py out/rf0 computes the tables above:

#!/usr/bin/env python3
"""Summaries of qerr.py's joins.csv for arms off/on (as posted for SF10 on PR #123553).

Joins are paired by (query, idx): both arms run the same statements, so they have the same number of join steps; a join counts
when both arms have an estimate. Leaf inputs: Left/Right sides that are a table read or a subquery, per arm.
usage: an100.py DIR [QUERIES...]
"""
import csv, statistics, sys, math
from collections import defaultdict

d = sys.argv[1]
focus = sys.argv[2:] or ['q33', 'q56', 'q60', 'q96', 'q07', 'q70', 'q31', 'q84']
rows = list(csv.DictReader(open(f'{d}/joins.csv')))
f = lambda x: float(x) if x not in ('', None, 'None') else None
by = defaultdict(dict)
for r in rows:
    by[(r['query'], int(r['idx']))][r['arm']] = r


def pct(xs, p):
    s = sorted(xs); k = (len(s) - 1) * p; lo, hi = math.floor(k), math.ceil(k)
    return s[lo] if lo == hi else s[lo] + (s[hi] - s[lo]) * (k - lo)


pairs = [(k, v['off'], v['on']) for k, v in by.items() if 'off' in v and 'on' in v]
both = [(k, a, b) for k, a, b in pairs if f(a['q_out']) is not None and f(b['q_out']) is not None]
neither = [(k, a, b) for k, a, b in pairs if f(a['q_out']) is None and f(b['q_out']) is None]
one = len(pairs) - len(both) - len(neither)
print(f'join pairs {len(pairs)}: estimate in both {len(both)}, in neither {len(neither)}, in one only {one}')
nq = defaultdict(int)
for (q, _), _a, _b in neither:
    nq[q] += 1
print('  no-estimate joins by query:', sorted(nq.items(), key=lambda t: -t[1])[:10])
qs = sorted({k[0] for k, _, _ in pairs})
print(f'queries with joins: {len(qs)}')
for arm, j in (('off', 1), ('on', 2)):
    xs = [f(t[j]['q_out']) for t in both]
    worst = defaultdict(float)
    for t in both:
        worst[t[0][0]] = max(worst[t[0][0]], f(t[j]['q_out']))
    leaves = []
    for r in rows:
        if r['arm'] != arm:
            continue
        for s in ('left', 'right'):
            if r[s + '_leaf'] == 'True' and f(r['q_' + s]) is not None:
                leaves.append(f(r['q_' + s]))
    print(f'{arm:3}: median {statistics.median(xs):.2f}  p90 {pct(xs, .9):.1f}  >10 {sum(x > 10 for x in xs)}  >100 {sum(x > 100 for x in xs)}  '
          f'max {max(xs):.3g} | worst join >10: {sum(v > 10 for v in worst.values())} of {len(worst)} queries | '
          f'leaf inputs {len(leaves)}: median {statistics.median(leaves):.2f} p90 {pct(leaves, .9):.2f} >10 {sum(x > 10 for x in leaves)}')
# per query worst/median, off vs on
per = defaultdict(lambda: {'off': [], 'on': []})
for (q, _), a, b in both:
    per[q]['off'].append(f(a['q_out'])); per[q]['on'].append(f(b['q_out']))
better = sorted((q for q in per if max(per[q]['off']) / max(per[q]['on']) > 2), key=lambda q: -max(per[q]['off']) / max(per[q]['on']))
worse = sorted((q for q in per if max(per[q]['on']) / max(per[q]['off']) > 2), key=lambda q: -max(per[q]['on']) / max(per[q]['off']))
print(f'worst join >2x better: {len(better)}; >2x worse: {len(worse)} {[(q, round(max(per[q]["off"]), 2), round(max(per[q]["on"]), 2)) for q in worse]}')
print('largest remaining (on):', sorted(((q, round(max(v['on']), 1)) for q, v in per.items()), key=lambda t: -t[1])[:12])
for q in focus:
    if q not in per:
        print(q, 'no estimated joins'); continue
    v = per[q]
    print(f"{q}: joins {len(v['off'])}  off {max(v['off']):.4g} ({statistics.median(v['off']):.3g})  on {max(v['on']):.4g} ({statistics.median(v['on']):.3g})")
    for arm in ('off', 'on'):
        lv = []
        for r in rows:
            if r['query'] == q and r['arm'] == arm:
                for s in ('left', 'right'):
                    if r[s + '_leaf'] == 'True' and f(r['q_' + s]) is not None:
                        lv.append((f(r['q_' + s]), r[s + '_label'][:70], f(r[s + '_est']), f(r[s + '_act'])))
        lv.sort(key=lambda t: -t[0])
        print(f'   {arm} worst inputs:', '; '.join(f'{l} est {e:.0f} act {a:.0f} (q {x:.3g})' for x, l, e, a in lv[:3]))

@antoniofilipovic

Copy link
Copy Markdown
Member Author

@groeneai can you include SF10 and SF100 here, similar as #130763 from technique @snelheidai described.

Also @groeneai it seems we are not using q-error on filters, can you include it somehow in explain analyze? Make these two different PRs

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm working on both, as two separate PRs:

  1. SF10 and SF100 TPC-DS over Iceberg, next to iceberg_suite_local_tpcds.xml from Add a TPC-DS performance test over Iceberg #130763: tables written to Iceberg by ClickHouse, as in the method above.
  2. A q-error for filter estimates in EXPLAIN ANALYZE (estimated vs actual rows of a filtered read or Filter step), the same way it is printed for joins today.

I'll follow up here with the PR links (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

SF10 is blocked on data: ds/scale_10/ in the clickhouse-datasets bucket is not an SF10 set. 34 of its 61 .dat files are byte-identical to ds/scale_1/ (same ETag and size), e.g. store_sales_1_10.dat has 2,878,334 rows (SF10: 28,800,991) and store_1_10.dat has 12 (SF10: 102). Only catalog_sales, catalog_returns and inventory have SF10 chunks. CI has no dsdgen, so an SF10 test needs a complete dsdgen -scale 10 upload there first. Could someone with write access to that bucket upload one? The SF10 test is then the SF100 one with scale_10 and the SF10 row counts.

SF100 (ds/scale_100/, complete, loaded every night by tpcds_sf100.xml) is in progress as a nightly long test. I'll post the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator

The q-error for filter estimates is in #131313. It is printed on the join's Left: and Right: lines (rows estimated E · rows A · q-error Q): a filtered table read is a join input, and that side estimate is the one join reordering uses, while a Filter step outside a join has no estimate that anything uses. With join runtime filters on (the default), the side they prune reads fewer rows than estimated without any estimation error, so set enable_join_runtime_filters = 0 to compare the estimate alone.

@groeneai

Copy link
Copy Markdown
Collaborator

The SF100 TPC-DS over Iceberg test is in #131427. SF10 is not included, because of the ds/scale_10 data gap above; with a complete upload it is the same file with scale_10 and its row counts.

alexey-milovidov pushed a commit to pugachevdmitry/ClickHouse that referenced this pull request Nov 14, 2026
`EXPLAIN ANALYZE` printed a q-error only for a join's output rows. The `Left:`
and `Right:` lines already carry the join-order optimizer's estimate of each
input next to its actual rows, but without a q-error, so the worst estimates
(a filtered table read whose filter estimate is far off) had to be computed by
hand.

Each side line now reads `rows estimated E · rows A · q-error Q · matched ...`,
using the same `resultRowsQError` (max(E / A, A / E)) and the same metric as
`Output rows`. It is absent when the estimate is missing or 0 or the side read
no rows.

This is where the planner uses a filter estimate: a filtered table read is a
leaf of the join graph, estimated by `estimateReadRowsCount` in
`optimizeJoin.cpp`, and the side estimate printed here is the one join
reordering used, including the hash-table cache override. Recomputing an
estimate for `Filter` steps at EXPLAIN time would print a number nothing used.

Join runtime filters lower a side's actual rows without any estimation error;
the docs say so and name `enable_join_runtime_filters = 0` to compare the
estimate alone.

Related: ClickHouse#123553

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to pugachevdmitry/ClickHouse that referenced this pull request Nov 14, 2026
05629 covered an exact estimate and an overestimate (500 estimated, 20
read), so a one-sided `estimated / actual` ratio would still pass. Add
`WHERE d.s = 'common'` (500 estimated, 980 read, q-error 1.96): the
underestimate direction, which is the direction of the filter errors
reported on ClickHouse#123553.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 17, 2026
`iceberg_suite_local_tpcds_sf100.xml` runs the 98 queries of
`iceberg_suite_local_tpcds.xml` (SF1) over Iceberg copies of the
`tpcds_sf100.xml` tables. The data is loaded from the same
`ds/scale_100` files into MergeTree staging tables, copied to
`IcebergLocal` tables under `user_files` in primary-key order with
one insert stream (about 1M rows per data file, the same files on both
servers), and the staging tables are dropped before the queries.
`use_datalake_metadata_statistics = 1` lets the Iceberg manifest
statistics reach join reordering, which the test exists to measure.

The copies are `IcebergLocal` tables under `user_files`, as in
`iceberg_suite_local_tpcds.xml`. A dropped table keeps its files; the
nightly removes them after every test (`cleanup_user_files` in
`ci/jobs/performance_tests.py`).

The test is tagged `long` and pinned to `NightlyExtendedPerformance`
batch `2/4`. No SF10 variant: the public `ds/scale_10` files are mostly
copies of `ds/scale_1`.

Related: ClickHouse#123553, ClickHouse#130763

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants