Repository navigation
Lazy materialization for reading Parquet from object storage and Iceberg - #110970
Conversation
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]>
|
Workflow [PR], commit [24d3587] Summary: ✅
AI ReviewSummaryThis PR adds lazy materialization for Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 527/594 (88.72%) · Uncovered code |
…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]>
|
Addressed the CI failures and the AI review in the latest commits:
Also merged the latest |
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.
|
Addressed the AI review verdict and the flaky-check timeout:
|
…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.
|
Pushed three commits:
The remaining CI red on the previous commit, @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 ( |
|
Confirmed unrelated to this PR's lazy-materialization changes. No fix PR is in progress. I will investigate the root cause and open a separate fix PR, linked back here. |
|
Fix PR: #111121 Root cause of the The PR replaces the fixed cleanup renames with a helper that re-drives the idempotent rename-back and waits for |
…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.
|
🕵 Pushed 2ece842, addressing the AI review Major (
CI on
|
…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.
|
🕵 Status update (pushed 24d3587). AI review Major (hive-partition CI on
|
|
🕵 Status update on head CI: 163 checks green, 15 skipped, and That red is unrelated. The reported victim was The read is 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 A fix is already in flight: #113552 adds a 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 |
|
🕵 The re-run of CI is now fully green on |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation is fairly good (I expected worse). Approved.
|
Two questions:
|
|
🕵 Answers to both questions: 1. Local Parquet filesNot yet, with one exception: Plain local files (
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 The optimization affects exactly one of the 43 queries: Q23, Q23, 3 runs each (bytes =
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 — Addendum (caching/ordering check): each number above is a fresh Addendum 2 (warm runs with a local filesystem cache): same single-file table with |
…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
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]>
Changelog category (leave one):
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 nqueries, the columns that are not needed for sorting and filtering are read only for thenrows that survive theLIMIT. On a 200 MB Parquet file on S3,SELECT k, s ... ORDER BY k DESC LIMIT 10reads 3.3 MB instead of 171 MB (51x less IO, 8x faster). Controlled by the new settingquery_plan_optimize_lazy_materialization_for_object_storage(enabled by default, also requiresquery_plan_optimize_lazy_materialization).This extends the existing
MergeTreelazy materialization (optimizeLazyMaterialization2) toReadFromObjectStorage:__global_row_indexcolumn,(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 fromChunkInfoRowNumbers— the same machinery that serves the_row_numbervirtual column and Iceberg position deletes.ILazyMaterializingRowsinterface, soJoinLazyColumnsStep/LazyMaterializingTransformare now storage-agnostic; theMergeTreepath is unchanged.LazilyReadFromObjectStoragestep. Its source waits until the main branch (with theLIMIT) finishes, then re-reads the surviving files through the regularStorageObjectStorageSource(so Iceberg schema evolution and delete transforms are reapplied), passing the exact set of rows to read per file via the newFormatFilterInfo::rows_to_read.rows_to_readon 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
Parquetand, 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 itsDEFAULTexpression byAddingDefaultsTransform, 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 theLIMITis 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. ADEFAULTexpression can never see the real value of a hive partition column — those are appended to the chunk after the per-file reader pipeline, whereAddingDefaultsTransformruns — so a query that has to evaluate such a default fails withUNKNOWN_IDENTIFIERon any plan, with and without this optimization (a pre-existing limitation of hive partitioning, shared by e.g. theFileengine); 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,truefor data lakes) — or the backend pins the actual read to the captured generation: S3 withs3_validate_etag_on_read(the default) issues the GET with anIf-Matchon the ETag captured by the main pass, which is atomic with respect to an overwrite (a concurrent overwrite fails the query withS3_OBJECT_CHANGED_DURING_READ). Other backends (Azure,HDFS, the local disk) ignoreStoredObject::etagon 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-emptyETag, and GCS accessed through the S3 API is documented to legitimately return objects without one — so an S3 client whose deduced provider isGCSis not treated as pinned either, and if any other provider unexpectedly yields an emptyETagat read time for a mutable file, the lazy pass fails close withS3_OBJECT_CHANGED_DURING_READinstead of degrading to an unpinned read. Backends whose metadata may carry no comparable generation token at all — a valid web origin may omitETag,Content-Length, andLast-Modifiedaltogether — are also excluded up front (IObjectStorage::supportsObjectGenerationComparison), sourlreads stay on the single-pass plan instead of failing on the reread.Also fixes a pre-existing bug: Iceberg equality deletes used a plain
FilterTransforminside the per-file reading pipeline, which does not maintainChunkInfoRowNumbers, so the_row_numbervirtual column produced wrong values (or an exception) on files with equality deletes. They now use a newRowNumbersPreservingFilterTransform.Tests:
04612_parquet_lazy_materialization_object_storage(s3 + Minio: multiple files, filters, expressions split around theLIMIT, duplicate sort values, virtual columns across file boundaries,EXPLAIN),04613_iceberg_lazy_materialization(IcebergLocalwith position deletes, including the positiveEXPLAINproof that such snapshots keep the lazy path),04614_iceberg_equality_deletes_row_number(physical_row_numbervalues with gaps at equality-deleted positions, and theEXPLAINproof that snapshots with equality deletes do not take the lazy path),04624_url_parquet_no_lazy_materialization(theEXPLAINproof thaturlnever takes the lazy path, and that the query still works with the optimization enabled),04625_lazy_materialization_object_storage_unpinned(theEXPLAINproof that a plain object storage takes the lazy path only when the reread is ETag-pinned: withs3_validate_etag_on_read=1the plan keeps the lazy step, with=0it stays single-pass, and the results are identical either way),04635_lazy_materialization_gcs_no_etag_pin(theEXPLAINproof that a GCS-provider S3 client — whose objects may carry noETag, 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(theDEFAULT-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 thePREWHEREpush-down),04824_parquet_lazy_materialization_distributed_plan(theEXPLAINproof 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 sameUNKNOWN_IDENTIFIERwith 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
Settings.cpp)Version info
26.8.1.1152(included in26.8and later)