Repository navigation
Include the column statistics of Iceberg reads from manifest files for join reordering - #123553
Conversation
3b39196 to
5c1c948
Compare
f874ade to
98e0d91
Compare
groeneai
left a comment
There was a problem hiding this comment.
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 what05298T9 expects. - Cost, for the description if it helps: on 5000 data files in one manifest, reading 20 columns,
EXPLAINtakes 6 ms with the row estimate only and 82 ms withuse_iceberg_manifest_column_statistics = 1(debug build). - Nits:
(plan O3)inManifestColumnStatistics.h:138points to a document the reader does not have, and the twodecodeColumnBoundsmessages still say "skipping min/max pruning for this column" when the caller is the statistics path.
| /// 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)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
6ed1ff8 to
e436df4
Compare
|
Workflow [PR], commit [e3a2592] Summary: ✅
AI ReviewSummaryThe 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
Tests
Final Verdict |
e436df4 to
d4683d3
Compare
| bool hasCountableValues(const IDataType & type) | ||
| { | ||
| const WhichDataType which(type); | ||
| return which.isNativeInteger() || which.isDate() || which.isDate32() || which.isDateTime() || which.isDateTime64(); |
There was a problem hiding this comment.
same as canStatisticsTrackMinMax ?
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
why it can use range_width to estimate the NDV
There was a problem hiding this comment.
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; | |||
There was a problem hiding this comment.
If all data files are pruned by filter, what is the purpose of the DataLakeReadEstimate? Can we just return nullptr instead of an estimate
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
I think that simplification makes sense. I will try to apply it today and will post here the results.
There was a problem hiding this comment.
Done, implemented the simplification
|
|
||
| auto estimate = reading->estimateReadFromDataLakeMetadata(); | ||
| if (!estimate) | ||
| return RelationStats{}; |
There was a problem hiding this comment.
Sometimes we return RelationStats{} and sometimes unknown; What is the difference?
There was a problem hiding this comment.
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.
964b202 to
f0a7556
Compare
…-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]>
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]>
Can you calculate q-error for this, I think that would be more beneficial than improvements we have, and please open then new issue: |
|
@snelheidai cc ^^ |
|
@antoniofilipovic Here is the q-error of the join-order estimates, on TPC-DS SF10 written to Iceberg by ClickHouse and analyzed with Spark
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:
The worst join improves more than 2x in 31 queries and gets more than 2x worse in two:
The largest remaining errors are in q17, q25 and q29 (0–3 rows estimated at 175K–727K, with keys correlated across Method
I've posted these here rather than in a new issue, because they don't come with a change to propose. |
|
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? |
|
@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):
The queries of my previous comment at SF100, maximum (median) over their joins:
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 The Method and runners
Scripts
#!/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"
#!/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
#!/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"
#!/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)
#!/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])) |
|
@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 |
|
Acknowledged. I'm working on both, as two separate PRs:
I'll follow up here with the PR links (or my findings) shortly. |
|
SF10 is blocked on data: SF100 ( |
|
The q-error for filter estimates is in #131313. It is printed on the join's |
|
The SF100 TPC-DS over Iceberg test is in #131427. SF10 is not included, because of the |
`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]>
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]>
`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]>
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 requiresuse_statistics: withuse_statistics = 0an Iceberg read gets no estimate at all, as with the setting off.Each file becomes a MergeTree
Basicstatistics summary (newColumnStatistics::createBasicFromSummaryand aStatisticsBasic::buildoverload), andConditionSelectivityEstimatorBuildermerges the summaries as it merges the statistics of MergeTree parts. How the metrics are read:int->long.After the manifest walk,
ManifestColumnStatistics::finalizereads 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:max - min + 1of the merged bounds, when it is within the non-NULL rows;uniqstatistic.The number is given to the estimator with
ColumnStatistics::setCardinality, and equality andINdivide the rows by it, as by auniqsketch. 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 callssetCardinality, so nothing changes for it.Conditions
DataLakeReadEstimateis 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,estimateReadRowsCountestimates on that estimator the filter above the read and itsPREWHERE, as MergeTree does, and also its row policy (getConditionsToEstimate). Ranges interpolate between the merged min and max; equality andINuse 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,
=andINtake 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 sameWHERE, and a condition that is not a range would be counted twice (on MergeTree,x % 2 = 0in bothPREWHEREandWHEREtakes 10 estimated rows to 0). AWHEREabove aLIMIT, 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:
A fix in the statistics merge
Since the per-part statistics cache,
ConditionSelectivityEstimatorBuilder::addStatisticsmerges into a copy made byColumnStatistics::cloneEmpty, andStatisticsBasic::copyStructureFromcopied onlyhas_default_count. The summaries from the manifests have no string lengths, so for aStringcolumn the copy and the files' statistics were incompatible and every file after the first was skipped (a two-fileNullable(String)column, half NULL, showednull 1instead ofnull 0.5).copyStructureFromnow copies every flagisCompatibleWithcompares; 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.IN, ranges,IS NULL,LIKE, functions,ORString,Float64,Decimal,Date,DateTime64, mostly NULL, expression, compositeLEFT JOIN, aggregation subqueryTPC-H and TPC-DS at SF1, written with
IcebergLocal,use_iceberg_manifest_statistics0 → 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 = -5estimated 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
column_sizesdivided by the type width is not used: the size of a dictionary-encoded column grows with its rows, not with its distinct values (l_discountof TPC-H SF10, 11 values, got 3,271,353).Boolean, half the rows for strings, 30% otherwise).avg_bytesis not estimated: the manifests give only compressed sizes.Known limitations
String,Decimaland floating-point columns have no measured number of distinct values, so=andINon them take the default 1%, as on MergeTree without auniqstatistic; on a larger table this can be far below the truth (TPC-DS q56, q60). Measured numbers need the Iceberg table statistics (ndvinmetadata.json), which are not read yet.=more selective than it is.Tests: 05427 (a
Stringcolumn over two files), 05428 (conditions: equality,IN,IS NULL, ranges, pruning, identity partitions, a 4-way join, a filter aboveLIMIT, 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):
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,PREWHEREand row policy of an Iceberg read on them, as for MergeTree tables with column statistics. The setting now requiresuse_statistics.Workflow [PR]
Sync PR [sync-upstream/pr/123553]
Version info
26.11.1.1010-master(included in26.11and later)