Skip to content

Lazy materialization for reading Parquet from object storage and Iceberg - #110970

Merged
alexey-milovidov merged 39 commits into
masterfrom
parquet-lazy-materialization
Aug 11, 2026
Merged

alexey-milovidov merged 39 commits into
masterfrom
parquet-lazy-materialization

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Lazy materialization (late materialization) for reading Parquet files from object storage, including Iceberg tables: for ORDER BY ... LIMIT n queries, the columns that are not needed for sorting and filtering are read only for the n rows that survive the LIMIT. On a 200 MB Parquet file on S3, SELECT k, s ... ORDER BY k DESC LIMIT 10 reads 3.3 MB instead of 171 MB (51x less IO, 8x faster). Controlled by the new setting query_plan_optimize_lazy_materialization_for_object_storage (enabled by default, also requires query_plan_optimize_lazy_materialization).

This extends the existing MergeTree lazy materialization (optimizeLazyMaterialization2) to ReadFromObjectStorage:

  • The row identity is a __global_row_index column, (file_index << 40) | row_number_in_file. The file index is assigned at run time by a registry shared between the main and lazy branches (files are discovered dynamically from the object storage iterator, so there is no plan-time file list); the row number is the physical (pre-filtering) row number within the Parquet file, taken from ChunkInfoRowNumbers — the same machinery that serves the _row_number virtual column and Iceberg position deletes.
  • The shared state between the two branches is generalized behind a new ILazyMaterializingRows interface, so JoinLazyColumnsStep / LazyMaterializingTransform are now storage-agnostic; the MergeTree path is unchanged.
  • The lazy branch is a new LazilyReadFromObjectStorage step. Its source waits until the main branch (with the LIMIT) finishes, then re-reads the surviving files through the regular StorageObjectStorageSource (so Iceberg schema evolution and delete transforms are reapplied), passing the exact set of rows to read per file via the new FormatFilterInfo::rows_to_read.
  • The native Parquet reader implements rows_to_read on top of its existing filtering machinery: row groups with no requested rows are skipped entirely, and within the remaining row groups the requested row set is applied like a precomputed PREWHERE filter, so only the pages containing requested rows are fetched (via the offset index) and decoded.

The optimization applies when the format is Parquet and, among data lakes, only to Iceberg (mirroring the PREWHERE support matrix). For Iceberg, the planner proves against the concrete data snapshot (by scanning its cached manifest files, the same ones the read will traverse) that every data file is Parquet, none of them needs schema evolution, and there are no equality deletes — otherwise the plan is left unchanged, because those cases force reading all physical columns and would turn the optimization into a pessimization. It composes correctly with PREWHERE, row-level filters, hive partitioning, virtual columns, position deletes and deletion vectors. A column that a file does not contain is computed from its DEFAULT expression by AddingDefaultsTransform, which runs inside each branch and evaluates the expression over the columns of that branch alone (an input it cannot see is substituted with the type's default value), so the split keeps a defaulted column and the transitive inputs of its expression on the same branch. That branch does not have to be the main one: a defaulted column that nothing needs before the LIMIT is deferred together with the inputs of its expression and computed on the lazy branch over just the surviving rows; only a defaulted column that stays on the main branch (or whose expression consumes an input the lazy branch would not see) pins the inputs of its expression to the main branch. A DEFAULT expression can never see the real value of a hive partition column — those are appended to the chunk after the per-file reader pipeline, where AddingDefaultsTransform runs — so a query that has to evaluate such a default fails with UNKNOWN_IDENTIFIER on any plan, with and without this optimization (a pre-existing limitation of hive partitioning, shared by e.g. the File engine); the closure keeps such a defaulted column on the main branch, preserving the single-pass behavior exactly.

Since the lazy pass re-opens the surviving files after the main pass has finished, it must read the same object generation the main pass read: a concurrent in-place overwrite between the two passes would otherwise stitch together rows of two versions of a file. The re-read is only generation-safe when either the data files are immutable by the format's contract — a data lake never overwrites a data file in place, so a file identified by path is always the same generation (dataFilesAreImmutable, true for data lakes) — or the backend pins the actual read to the captured generation: S3 with s3_validate_etag_on_read (the default) issues the GET with an If-Match on the ETag captured by the main pass, which is atomic with respect to an overwrite (a concurrent overwrite fails the query with S3_OBJECT_CHANGED_DURING_READ). Other backends (Azure, HDFS, the local disk) ignore StoredObject::etag on read, so a metadata probe before the read cannot close the HEAD-to-GET window; for a mutable file on such a backend the planner keeps the single-pass plan (ReadFromObjectStorageStep::canUseLazyMaterialization). The ETag pin itself only takes effect when the captured metadata carries a non-empty ETag, and GCS accessed through the S3 API is documented to legitimately return objects without one — so an S3 client whose deduced provider is GCS is not treated as pinned either, and if any other provider unexpectedly yields an empty ETag at read time for a mutable file, the lazy pass fails close with S3_OBJECT_CHANGED_DURING_READ instead of degrading to an unpinned read. Backends whose metadata may carry no comparable generation token at all — a valid web origin may omit ETag, Content-Length, and Last-Modified altogether — are also excluded up front (IObjectStorage::supportsObjectGenerationComparison), so url reads stay on the single-pass plan instead of failing on the reread.

Also fixes a pre-existing bug: Iceberg equality deletes used a plain FilterTransform inside the per-file reading pipeline, which does not maintain ChunkInfoRowNumbers, so the _row_number virtual column produced wrong values (or an exception) on files with equality deletes. They now use a new RowNumbersPreservingFilterTransform.

Tests: 04612_parquet_lazy_materialization_object_storage (s3 + Minio: multiple files, filters, expressions split around the LIMIT, duplicate sort values, virtual columns across file boundaries, EXPLAIN), 04613_iceberg_lazy_materialization (IcebergLocal with position deletes, including the positive EXPLAIN proof that such snapshots keep the lazy path), 04614_iceberg_equality_deletes_row_number (physical _row_number values with gaps at equality-deleted positions, and the EXPLAIN proof that snapshots with equality deletes do not take the lazy path), 04624_url_parquet_no_lazy_materialization (the EXPLAIN proof that url never takes the lazy path, and that the query still works with the optimization enabled), 04625_lazy_materialization_object_storage_unpinned (the EXPLAIN proof that a plain object storage takes the lazy path only when the reread is ETag-pinned: with s3_validate_etag_on_read=1 the plan keeps the lazy step, with =0 it stays single-pass, and the results are identical either way), 04635_lazy_materialization_gcs_no_etag_pin (the EXPLAIN proof that a GCS-provider S3 client — whose objects may carry no ETag, so the reread cannot be pinned — stays on the single-pass plan, with an AWS-provider control showing the lazy step), 04650_lazy_materialization_object_storage_column_defaults (the DEFAULT-expression dependency across the split in every direction: a defaulted column in the sort key whose input is selected, a selected defaulted column whose input is the sorting key, an output-only defaulted column deferred to the lazy branch together with the inputs of its expression, and a defaulted column pinned to the main branch because its expression's input is the sorting key), 04660_lazy_materialization_object_storage_filter_only_default (a defaulted column used only as a filter input: its expression's input stays on the main branch even though the defaulted column is stripped from the step's output header by the PREWHERE push-down), 04824_parquet_lazy_materialization_distributed_plan (the EXPLAIN proof that the optimization does not fire while the initiator builds a distributed plan (make_distributed_plan): the sort is exchange-split earlier in the same optimization pass and a lazy branch must stay within one fragment, so the plan keeps no lazy read step and the distributed conversion succeeds), 04829_lazy_materialization_hive_partition_defaults (a hive-partitioned table: a defaulted column with file-only inputs is still deferred together with the inputs of its expression while the hive partition column stays on the main branch, and a default over a hive partition column fails with the same UNKNOWN_IDENTIFIER with the optimization on and off — the pre-existing hive-partitioning limitation is not widened by the split). Every query battery is executed with the optimization enabled and disabled, and the results must match.

Documentation entry for user-facing changes

  • Documentation is written (the setting description is generated from Settings.cpp)

Version info

  • Merged into: 26.8.1.1152 (included in 26.8 and later)

alexey-milovidov and others added 2 commits July 19, 2026 05:11
For ORDER BY ... LIMIT n queries reading Parquet files from object storage
(including Iceberg tables), read the columns that are not needed for sorting
and filtering only for the n rows that survive the LIMIT.

The row identity is a __global_row_index column combining the index of the
file within the query with the physical row number within the file, produced
by the main read from ChunkInfoRowNumbers. The lazy branch reads the deferred
columns back through FormatFilterInfo::rows_to_read, which makes the Parquet
reader skip row groups and pages that contain no requested rows.

Also fix Iceberg equality deletes breaking ChunkInfoRowNumbers (and therefore
the _row_number virtual column) by replacing the plain FilterTransform with a
new RowNumbersPreservingFilterTransform.

Co-Authored-By: Claude Fable 5 <[email protected]>
typeid_cast matches the exact dynamic type, so casting the reading step to
SourceStepWithFilter returned nullptr (an exception in debug builds, a null
dereference in release); dispatch through the concrete step types instead.

Verified on a 200 MB Parquet file on Minio: SELECT k, s ORDER BY k DESC LIMIT 10
reads 3.3 MB with lazy materialization vs 171 MB without (51x less IO, 8x faster).

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [24d3587]

Summary: ✅


AI Review

Summary

This PR adds lazy materialization for Parquet reads from object storage and Iceberg, including the row-number plumbing, generation-safety gates, and the regression coverage around deletes, defaults, distributed planning, and backend capability checks. Re-reviewing the current head together with the full thread history, I did not find any outstanding correctness, safety, or performance blockers in the diff.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 527/594 (88.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 19, 2026
alexey-milovidov and others added 4 commits July 19, 2026 21:57
…tion tests

The CI settings randomizer sets `query_plan_max_limit_for_lazy_materialization`
to `1`, which disables the lazy materialization optimization for the `LIMIT 3`
queries used by the `EXPLAIN` checks in `04612_parquet_lazy_materialization_object_storage`
and `04613_iceberg_lazy_materialization`. As a result the `LazilyReadFromObjectStorage`
step was absent from the plan and the tests failed with `result differs with reference`.

Pin the setting to `0` (no limit) in the query invocations that rely on the
optimization being applied, so the tests are deterministic under randomized settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Lazy materialization for object storage requires physical row numbers, which only
the Parquet reader provides. For a mixed-format Iceberg snapshot (the table-level
format is Parquet, but an individual data file has a different format) the missing
`ChunkInfoRowNumbers` was reported as a `LOGICAL_ERROR`. The file list is built
dynamically, so this condition is only discovered at read time and is reachable by
users. Report it as an actionable `UNSUPPORTED_METHOD` error that names the file and
its format and tells the user to disable
`query_plan_optimize_lazy_materialization_for_object_storage`, instead of an internal
logical error.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Iceberg equality deletes previously used a plain `FilterTransform`, which does not
maintain `ChunkInfoRowNumbers`, so the `_row_number` virtual column produced wrong
values or an exception. They now use `RowNumbersPreservingFilterTransform`. This test
reads `_row_number` from an equality-delete table and checks it is present (not NULL)
and forms a distinct physical identity per file.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the CI failures and the AI review in the latest commits:

  • Failing 04612/04613 (result differs with reference): the CI settings randomizer sets query_plan_max_limit_for_lazy_materialization to 1, which disabled the optimization for the LIMIT 3 EXPLAIN checks, so LazilyReadFromObjectStorage was absent from the plan. The tests now pin query_plan_max_limit_for_lazy_materialization=0 in the invocations that rely on the optimization being applied.

  • AI review blocker (mixed-format Iceberg): the file list is built dynamically from the object storage iterator, so a plan-time all files are Parquet proof is not available and there is no clean way to fall back once the plan is split into the main and lazy branches. Instead of the internal LOGICAL_ERROR that was thrown when a non-Parquet file yields no ChunkInfoRowNumbers, the source now reports an actionable UNSUPPORTED_METHOD error naming the file and its format and advising to disable query_plan_optimize_lazy_materialization_for_object_storage. Whether to additionally attempt a per-file/whole-query fallback for mixed-format Iceberg snapshots is a design decision left to review.

  • Test gap (equality-delete _row_number): added 04614_iceberg_equality_deletes_row_number, which reads _row_number from an equality-delete Iceberg table and checks it is present (not NULL) and forms a distinct (_file, _row_number) identity per file.

Also merged the latest master (the branch was ~170 commits behind).

The plan-time gate for LIMIT lazy materialization on object storage used to accept
any Iceberg table, but mixed-format snapshots would then fail at runtime with
`UNSUPPORTED_METHOD` once a non-Parquet file was reached, and files needing schema
evolution or equality deletes force full-schema reads (see
`IcebergMetadata::getInitialSchemaByPath`), turning the optimization into a
pessimization. `supportsLazyMaterialization` now takes the storage metadata snapshot
and the context, and `IcebergMetadata` proves against the pinned data snapshot (by
scanning its cached manifest files, which the read traverses anyway) that every data
file is Parquet, none needs schema evolution, and there are no equality deletes;
otherwise the plan is left unchanged.
After `ALTER TABLE ... ADD COLUMN` and an insert with the new schema, the older
files need schema evolution, so `EXPLAIN` must not contain
`LazilyReadFromObjectStorage` even with the optimization enabled, and the results
must stay correct. Verified locally against `IcebergLocal`.
The regression test only proved that `_row_number` is non-NULL and unique, which a
broken implementation that renumbers survivors densely would also satisfy. Now it
prints the physical row numbers of the second batch of `eq_deletes_table` (ids 0..9,
two files with rows 0..4 each, ids 3 and 9 removed by an equality delete), so the
expected output contains a gap: id 4 keeps physical row number 4. Also assert via
`EXPLAIN` that a snapshot with equality deletes does not take the lazy
materialization path.
The test exceeded 180 seconds in the flaky check under ASan:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110970&sha=4f237a3325f1f42e4a296510ec24e9626764a954&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#110970

Client invocations dominated the runtime (18 of them, each paying the client startup
cost under ASan with randomized settings). The whole query battery now runs as one
multiquery invocation per optimization setting, the `EXPLAIN` checks moved into the
battery as subqueries, and the dataset is 10x smaller (3 x 1000 rows, row groups of
100), which keeps multiple files, multiple row groups per file, and the cross-file
`OFFSET` coverage. 3 client invocations in total instead of 18.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review verdict and the flaky-check timeout:

  • Iceberg gate (Blocker + Major): supportsLazyMaterialization now proves per data snapshot — by scanning its cached manifest files, which the read traverses anyway — that every data file is Parquet, none needs schema evolution, and there are no equality deletes. Mixed-format snapshots and snapshots forced into full-schema reads never take the lazy path anymore; the runtime UNSUPPORTED_METHOD throw remains only as a safety net.
  • Tests: 04613 gained a schema-evolution section (EXPLAIN proves the lazy step disappears; results stay correct — verified locally against IcebergLocal), and 04614 now asserts the actual preserved _row_number values with a gap at an equality-deleted position, plus an EXPLAIN proof that such snapshots stay off the lazy path.
  • Flaky check: 04612 ran over 180 s under ASan because of 18 client invocations; it is now 3 invocations (one multiquery battery per optimization setting) over a 10x smaller dataset that still covers multiple files, multiple row groups, and the cross-file OFFSET.
  • Changelog category switched to Performance Improvement as suggested.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-feature Pull request with new product feature labels Jul 20, 2026
…alization

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeLazyMaterialization.cpp
Lazy materialization is applied only with the analyzer
(`optimize_lazy_materialization` is derived as
`query_plan_optimize_lazy_materialization && allow_experimental_analyzer`),
so on the old-analyzer CI configuration the `EXPLAIN` checks in
04612/04613 saw no `LazilyReadFromObjectStorage` step and failed.
Pin `enable_analyzer = 1` in these tests, and also in the negative
`EXPLAIN` check of 04614 so it does not pass vacuously.

Failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110970&sha=b16c36ef0ff5c635f3cd4ffb7175c840a7198cc3&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29
Address review: the lazy pass re-opens the surviving files after the main
pass has finished, so an in-place overwrite between the two passes could
silently combine rows of two generations of a file.

On `S3` with `s3_validate_etag_on_read` (the default) the re-read was
already pinned race-free: the lazy pass reuses the `ObjectInfo` instances
registered by the main pass, whose captured ETag makes the GET conditional
in `ReadBufferFromS3`. For all other backends (`Local`, `Web`, `Azure`,
and `S3` with the check disabled), `LazyRowsObjectIterator` now re-fetches
the object metadata before reading each surviving file and compares it with
the metadata captured by the main pass (ETag when both sides have one,
otherwise size and modification time), failing close with
`S3_OBJECT_CHANGED_DURING_READ` when the object changed or cannot be
proven unchanged.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed three commits:

  1. Fixed the 04612/04613 failures on the old-analyzer shard (report): lazy materialization is applied only with the analyzer (optimize_lazy_materialization is derived as query_plan_optimize_lazy_materialization && allow_experimental_analyzer), so the EXPLAIN checks saw no LazilyReadFromObjectStorage step there. The tests now pin enable_analyzer = 1 (also in the negative EXPLAIN check of 04614, so it does not pass vacuously). Reproduced the failure and verified the fix locally against a fresh build.

  2. Merged master (the branch was ~100 commits behind; clean merge).

  3. Addressed the AI review Major (generation pinning between the two passes) — see the reply on the thread. On S3 with s3_validate_etag_on_read (the default) the lazy pass was already pinned race-free via the captured ETag in the reused ObjectInfo; for the other backends LazyRowsObjectIterator now re-fetches the object metadata before reading each surviving file and fails close with S3_OBJECT_CHANGED_DURING_READ when the object changed or cannot be proven unchanged. Smoke-verified the lazy path end-to-end with IcebergLocal (the non-ETag branch).

The remaining CI red on the previous commit, test_rename_column/test.py::test_rename_distributed_parallel_insert_and_select (UNKNOWN_IDENTIFIER during concurrent RENAME COLUMN), is unrelated: it also failed on master on 2026-07-18 and on several unrelated PRs (#110613, #109453, #109768, #109976).

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110970&sha=b16c36ef0ff5c635f3cd4ffb7175c840a7198cc3&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%208%2F8%29 (test_rename_column/test.py::test_rename_distributed_parallel_insert_and_select) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed unrelated to this PR's lazy-materialization changes. test_rename_distributed_parallel_insert_and_select is a pre-existing chronic flaky race (concurrent RENAME COLUMN against parallel INSERT/SELECT on a Distributed table): CIDB shows 9 failures across 8 unrelated PRs plus 1 on master (commit 6b5099c, 2026-07-18, amd_tsan) in the last 30 days, roughly 1 hit per run, spanning both amd_msan and amd_tsan. It matches the PRs you listed (#110613, #109453, #109768, #109976).

No fix PR is in progress. I will investigate the root cause and open a separate fix PR, linked back here.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR: #111121

Root cause of the amd_msan test_rename_distributed_parallel_insert_and_select red: the cleanup renames back to num2 are ON CLUSTER (async distributed DDL + async ReplicatedMergeTree metadata replication) with ignore_exception=True, so a failed or late rename is swallowed. The strict final selects then run with no wait for convergence; a distributed select forwarded to a shard replica whose local _replicated schema is not yet num2 (still foo2/foo3) throws UNKNOWN_IDENTIFIER. Confirmed unrelated to this PR.

The PR replaces the fixed cleanup renames with a helper that re-drives the idempotent rename-back and waits for system.columns to show num2 on every node before the strict selects. Reproduced deterministically (local-only rename making the Distributed schema outrun a shard replica gives the exact Code: 47); fixed test passes 10/10.

alexey-milovidov and others added 2 commits July 21, 2026 02:00
…s rereads

The metadata probe in `validateObjectGeneration` used the plain
`object.getPath()` string, but the reading pass identifies the physical
object differently in two modes: for an entry of an archive the object
that is read (and whose metadata is captured by the main pass) is the
archive itself (`getPathToArchive`), and for web URL shards the probe
must go through the `RelativePathWithMetadata` overload so that
`read_source_index` is preserved. Build the probe exactly the way
`createReader` does, so the check compares like with like.

Co-Authored-By: Claude Fable 5 <[email protected]>
…the inputs of their expressions

The default-expression closure in `keepOnlyRequiredColumnsAndCreateLazyReadStep`
was seeded from every defaulted column in `info.source_header`, so a defaulted
column that nothing needs before the `LIMIT` (an output-only column such as
`a UInt64 DEFAULT b + 1` in `SELECT a, b, s ... ORDER BY k LIMIT 3`) pinned the
inputs of its expression to the main branch and lost the deferred-read I/O win.

`AddingDefaultsTransform` runs inside every branch of the split, so such a column
can move to the lazy branch whenever every input of its expression is deferred with
it - the expression is then evaluated there over just the surviving rows. Only a
defaulted column that stays on the main branch, or one whose expression consumes an
input the lazy branch would not see (an input pinned to the main branch, or one the
format does not read at all), still pins its inputs; since pinning an input can
strand another default's expression, the rule is iterated to a fixpoint.

`04650_lazy_materialization_object_storage_column_defaults` gains an `EXPLAIN`
regression for the deferred shape (`Lazily read columns: a, b, s`) and a
result-checked battery for the mixed shape (`SELECT a, s ... ORDER BY b LIMIT 3`,
where the input stays on the main branch and the defaulted column is pinned with it).

Addresses the AI review Major on the PR head 0cca27d.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 2ece842, addressing the AI review Major (Request changes on head 0cca27d4):

  • Output-only defaulted columns are now deferred. The default-expression closure in keepOnlyRequiredColumnsAndCreateLazyReadStep is seeded only from the defaulted columns that stay on the main branch (needed before the LIMIT, or consumed by the PREWHERE / row-level filter) instead of from every defaulted column in the output header. A defaulted column needed only after the LIMIT moves to the lazy branch together with the inputs of its expression and is computed there over just the surviving rows — SELECT a, b, s ... ORDER BY k LIMIT 3 with a UInt64 DEFAULT b + 1 now defers a, b, s instead of only s. A deferred default whose expression consumes an input the lazy branch would not see (an input pinned to the main branch, or one the format does not read) stays on the main branch; that rule feeds itself, so it is iterated to a fixpoint. Runtime-verified against an ETag-serving S3 endpoint: results identical with the optimization enabled and disabled for the deferred, mixed, and chained shapes. 04650_lazy_materialization_object_storage_column_defaults gained the requested EXPLAIN regression plus a result-checked mixed-shape battery; 04660 (filter-only defaults) re-verified unchanged. Details in the thread reply.

CI on 0cca27d4 — both reds are unrelated with fixes already in flight:

…n stays on the main branch

A hive partition column is parsed from the file path and appended to the
chunk only after the per-file reader pipeline, where
`AddingDefaultsTransform` runs - so a `DEFAULT` expression never sees the
real value of a hive partition column on any plan: a query that has to
evaluate such a default fails with `UNKNOWN_IDENTIFIER` with and without
this optimization (a pre-existing limitation of hive partitioning, shared
by e.g. the `File` engine). The dependency closure keeps such a defaulted
column on the main branch, preserving the single-pass behavior exactly.

A defaulted column whose expression only consumes columns read from the
file is unaffected by hive partitioning and is still deferred to the lazy
branch, keeping the I/O reduction.

New regression test `04829_lazy_materialization_hive_partition_defaults`
pins both shapes with the optimization enabled and disabled.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update (pushed 24d3587).

AI review Major (hive-partition DEFAULT inputs) — investigated, refuted in its premise, and narrowed explicitly (details in the thread reply): a DEFAULT expression can never see the real value of a hive partition column on any plan, because those columns are appended to the chunk after the per-file reader pipeline where AddingDefaultsTransform runs. The suggested shape fails with UNKNOWN_IDENTIFIER with the optimization disabled too, and likewise on the File engine, which this PR does not touch — a pre-existing limitation of hive partitioning, not a regression of this optimization. Per the review's second option, I documented the contract in the dependency-closure code and added regression test 04829_lazy_materialization_hive_partition_defaults: on a hive-partitioned table, a defaulted column with file-only inputs is still deferred (Lazily read columns: a, b, s — the I/O win is kept, the hive column stays on the main branch, results identical with the optimization on and off), and a default over a hive partition column fails with the same UNKNOWN_IDENTIFIER either way.

CI on 2ece84278 — the two public reds are both unrelated to this PR:

CH Inc sync = "tests failed (2 new, 5 known)" — I analyzed all four failing jobs of the private sync PR; none touches anything from this PR: an integration-harness FileNotFoundError in test_attach_table_from_s3_plain_readonly setup (known recurring signature), two private SharedMergeTree timing flakes (04210_smt_replace_partition_no_retries_under_concurrent_insert retry off-by-one, 03519_shared_merge_tree_part_info_unpack detached-part visibility race), and a SharedCatalog/Keeper stress-environment collapse (DROP DATABASE drop-queue drain timeout cascading into hung-check and server-start failures, no sanitizer report). The sync will regenerate against the new head.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Follow-up on the Stress test (arm_debug) harness flake above: I opened the fix myself — #114063 (the fault-injection verify query in stress.py now gets the same retry treatment as the SYSTEM RELOAD CONFIG it follows). @groeneai no separate investigation needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status update on head 24d3587e9f9d — nothing to change on this PR, one unrelated flake re-triggered.

CI: 163 checks green, 15 skipped, and CH Inc sync is SUCCESS. The only red was Integration tests (amd_tsan, 6/6).

That red is unrelated. The reported victim was test_replicated_mutations/test.py::test_mutations_dont_prevent_merges[nodes1] (already labelled retry_ok), but it failed only in cluster.shutdown() with Sanitizer assert found for instance zoo1 — the abort is inside the clickhouse-keeper container, not in the test:

WARNING: ThreadSanitizer: data race on vptr (ctor/dtor vs virtual call)
SUMMARY: ... src/Coordination/KeeperRequestDispatcher.cpp:92:12 in DB::getRequestBytesCost(Coordination::ZooKeeperRequest const&)

The read is getRequestBytesCost calling the virtual bytesSize from KeeperRequestDispatcher::dispatchThread; the previous write is the vptr store in the Coordination::ZooKeeperMultiRequest constructor inside KeeperTCPHandler::receiveRequest. The request is published through the dispatcher queue, so the two accesses are in fact ordered — the report is the known false positive.

History confirms it is not PR-specific: over the last 12 days this teardown assert appears in 234 rows across 9 unrelated pull requests (including pure backport branches backport/26.5/111103 and backport/26.6/109724) and 231 distinct victim test names — the reddened test is essentially whichever one runs last. This PR touches no Keeper, ZooKeeper, or replicated-mutation code.

A fix is already in flight: #113552 adds a race_top:^DB::getRequestBytesCost suppression (still open, so merging master would not clear this red). I re-ran the failed job instead.

Review state: AI review verdict on this head is ✅ Approve ("no outstanding correctness, safety, or performance blockers"), there are no unresolved review threads, and the Cloud performance verdict remains no_change. Branch is MERGEABLE, 527 commits behind master (well under a day) — no master merge needed, and nothing new to push.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The re-run of Integration tests (amd_tsan, 6/6) passed, confirming the Keeper getRequestBytesCost vptr TSan report was the known false-positive flake rather than anything from this PR.

CI is now fully green on 24d3587e9f9d: 166 successful checks, 0 failures, 15 skipped, CH Inc sync SUCCESS, and mergeStateStatus is CLEAN. AI review verdict is ✅ Approve, there are no unresolved review threads, and the Cloud performance verdict is no_change. Nothing left to push here.

@alexey-milovidov alexey-milovidov left a comment

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 implementation is fairly good (I expected worse). Approved.

@alexey-milovidov alexey-milovidov self-assigned this Aug 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Two questions:

  1. Does it work for local Parquet files, and what does it take to make it work?
  2. Did we test it on ClickBench ("datalake" variants)?

@alexey-milovidov

alexey-milovidov commented Aug 11, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Answers to both questions:

1. Local Parquet files

Not yet, with one exception: IcebergLocal (Iceberg over the local disk) already takes the lazy path — it reads through ReadFromObjectStorageStep, and the immutability of data-lake files satisfies the generation-safety gate. 04613_iceberg_lazy_materialization proves it with EXPLAIN on an IcebergLocal table.

Plain local files (file() / the File engine) read through StorageFile, which has its own ReadFromFile plan step, and the pass only dispatches on ReadFromMergeTree and ReadFromObjectStorageStep (LocalObjectStorage is used only for Iceberg — regular file access does not go through object storage). What it takes to make it work:

  • Nothing on the format side — the plan-split machinery (ILazyMaterializingRows, JoinLazyColumnsStep, LazyMaterializingTransform) and the whole Parquet FormatFilterInfo::rows_to_read reader implementation from this PR are storage-agnostic and reusable as-is.
  • StorageFile needs the counterpart of what StorageObjectStorageSource got here: attaching the __global_row_index column on the main pass (a shared file registry + the ChunkInfoRowNumbers row numbers), and a lazy read step that re-opens the surviving files (at most LIMIT n of them) with a per-file rows_to_read.
  • The one open design question is the same generation-safety issue that keeps mutable files on Azure/HDFS single-pass: POSIX has no conditional read, so the reread cannot be pinned the way If-Match pins it on S3. The realistic option is to reopen by path and fail close if (inode, size, mtime) changed since the first pass — that catches replace-by-rename (the common atomic-update pattern) exactly, and in-place rewrites up to mtime resolution. An in-place rewrite already tears a single-pass read today, so this is arguably not weaker than the status quo, unlike the completely unpinnable network reread we chose to forbid.

Overall a follow-up PR of moderate scope — the hard parts (row-selective Parquet reads and the plan split) are done here.

2. ClickBench (datalake variants)

It had not been run before (the PR was verified on a synthetic 200 MB file: 51x less IO, 8x faster). I have now run both datalake variants against this PR's CI binary (arm release, commit 24d3587e9f9), on a 96-core aarch64 box reading clickhouse-public-datasets.s3.eu-central-1 cross-region, tables created exactly as in ClickBench create.sql, fresh process per run (no caches).

The optimization affects exactly one of the 43 queries: Q23, SELECT * FROM hits WHERE URL LIKE '%google%' ORDER BY EventTime LIMIT 10. An EXPLAIN diff over all 43 queries shows the other 42 plans are byte-identical with the setting on and off — Q24–Q26 also have ORDER BY ... LIMIT, but their only output column is also a filter input, so there is nothing to defer (same as on MergeTree).

Q23, 3 runs each (bytes = ReadBufferFromS3Bytes):

variant lazy materialization wall time data read from S3 S3 GET requests
clickhouse-datalake (single 14 GB file) off 12.7 / 14.1 / 14.9 s 14.71 GB ~690
clickhouse-datalake (single 14 GB file) on 4.3 / 4.6 / 3.9 s 3.86 GB 320
clickhouse-datalake-partitioned (100 files) off 6.7 / 6.2 / 6.0 s 14.68 GB ~824
clickhouse-datalake-partitioned (100 files) on 3.9 / 4.5 / 3.6 s 3.80 GB 499

So on ClickBench data: 3.3x faster and 3.8x less data on the single-file variant, 1.6x faster and 3.9x less data on the partitioned one (its baseline is already faster because 100 files parallelize the download better). The gain is bounded by the main pass still reading the filter and sort inputs in full — URL is one of the largest columns in hits and accounts for most of the remaining 3.8 GB; the other 103 columns drop from ~11 GB to just the pages containing the 10 surviving rows. Results are identical on and off (verified with a deterministic tie-break, same sha256 of the output; plain Q23 has ties in EventTime). These numbers are an on/off comparison on this box, not comparable to the published leaderboard (which runs on c6a.4xlarge).

Addendum (caching/ordering check): each number above is a fresh clickhouse-local process with no filesystem cache, and ReadBufferFromS3Bytes confirms every "off" run transferred the full ~14.7 GB from S3 (so no run was served from any cache). To also rule out S3-side warming (the "off" batch ran before the "on" batch), I re-ran the single-file variant with the two settings interleaved and the order reversed: on 3.35 / 3.65 / 3.31 s (3,860,383,598 bytes each), off 12.07 / 12.61 / 12.59 s (~14.71 GB each). Same conclusion, ~3.6x on this batch.

Addendum 2 (warm runs with a local filesystem cache): same single-file table with enable_filesystem_cache = 1 and a 30 GiB cache declared in filesystem_caches (the populate run fills it with the whole 14.7 GB; all warm runs show ReadBufferFromS3Bytes = 0, i.e. they are served entirely from the local cache). Steady-state warm (data in the OS page cache), interleaved runs: lazy on 1.58 / 1.29 s reading 3.86 GB from the cache, lazy off 5.65 / 5.63 s reading 14.71 GB. So fully warm the optimization still gives ~3.9x — with the network out of the picture it becomes a decompress/decode saving (all 105 columns vs the filter and sort columns plus 10 rows of the rest). The very first warm run after population is slower on both sides (17.4 s on, 43.3 s off, ~300 MB/s — reading the freshly written cache files back from disk), same ratio. The lazy reread also works against the cache: the warm lazy runs make no S3 requests at all.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 11, 2026
Merged via the queue into master with commit 03ad500 Aug 11, 2026
355 of 356 checks passed
@alexey-milovidov
alexey-milovidov deleted the parquet-lazy-materialization branch August 11, 2026 01:53
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
andremm pushed a commit to andremm/ClickHouse that referenced this pull request Aug 12, 2026
…on one client timeout

The stress harness died before any stress testing started: in
`install_thread_pool_fault_injection`, the verify query
`SELECT value FROM system.server_settings WHERE name = 'cannot_allocate_thread_fault_injection_probability'`
hit the client's 15 s `receive_timeout` right after `SYSTEM RELOAD CONFIG`
and the single `check_output` call took the whole job down with
"Test script failed, script exit code: 1". The reload itself already goes
through `call_with_retry`, but the verification did not. Seen on unrelated
PRs ClickHouse#110970 and ClickHouse#114029 on 2026-08-09 (`Stress test (arm_debug)`): a debug
server under ThreadFuzzer can be slow enough right after a config reload.

Give the verify query the same retry treatment (5 attempts, backoff), and
keep the fail-close behavior if it persistently fails or the setting is
inactive.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110970&sha=2ece842784cf0369655d3a55a7b4363eb3977f50&name_0=PR&name_1=Stress%20test%20(arm_debug)
ClickHouse#110970
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 22, 2026
Follow-up to ClickHouse#110970 for plain local files, as discussed in
ClickHouse#110970 (comment)

For `ORDER BY ... LIMIT n` queries over local Parquet files read through
`StorageFile` (the `file` table function and the `File` table engine), the
columns that are not needed for sorting and filtering are now read only for
the `n` rows that survive the `LIMIT`.

- The storage-agnostic column-split logic of
  `ReadFromObjectStorageStep::keepOnlyRequiredColumnsAndCreateLazyReadStep`
  is extracted into the shared `splitLazilyReadColumnsFromFormatInfo`
  (`prepareReadingFromFormat`) and reused by the new
  `ReadFromFile::keepOnlyRequiredColumnsAndCreateLazyReadStep`.
- The main pass appends a `__global_row_index` column
  (file index in a per-query `LazyFileRegistry` + physical row numbers from
  `ChunkInfoRowNumbers`) in `StorageFileSource::generate`.
- The lazy branch (`LazilyReadFromFile` -> `LazyReadFromFileSource` ->
  `StorageFileLazyRowsSource`) reopens only the surviving files (at most
  `LIMIT n` of them) with per-file `FormatFilterInfo::rows_to_read` and
  `parquet.preserve_order`.
- Generation safety: POSIX has no conditional read, so the reread fails close
  with the new `FILE_CHANGED_DURING_READ` error when the file's generation
  token - sub-second mtime + inode + size, reusing
  `computeFileCacheVersionToken` - no longer matches the one captured when the
  main pass opened the file. The token is validated at registration time in
  the main pass, and both before and right after the reopen in the lazy pass.
  Replace-by-rename (the common atomic-update pattern) is always caught;
  an in-place rewrite is caught up to the filesystem timestamp tick.
- Gates (`ReadFromFile::canUseLazyMaterialization`): Parquet format only, no
  file descriptor reads (stdin cannot be reopened), no archives, no
  `distributed_processing`, no `rename_files_after_processing`, uncompressed
  files only. New setting `query_plan_optimize_lazy_materialization_for_file`
  (default true).
- Fixes a latent bug shared with the object storage path (via the shared
  helper): deferring a requested subcolumn (e.g. of `JSON`) left the lazy
  branch's format header empty and the query failed with `Not found column
  or subcolumn ... in block`, because `format_header` contains the parent
  column of a requested subcolumn. The split now maps requested columns to
  their storage-level names, and keeps the parent on the main branch as well
  when a sort key still needs another subcolumn of it.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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.

3 participants