Skip to content

[Experiment] Antalya 26.6: Parquet v3 constant column skip - #2181

Open
UnamedRus wants to merge 70 commits into
antalya-26.6from
parquet-v3-constant-column-skip-antalya
Open

UnamedRus wants to merge 70 commits into
antalya-26.6from
parquet-v3-constant-column-skip-antalya

Conversation

@UnamedRus

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

...

Documentation entry for user-facing changes

...

CI/CD Options

Exclude tests:

  • Fast test
  • Integration Tests
  • Stateless tests
  • Stateful tests
  • Performance tests
  • Aarch64 tests
  • All with ASAN
  • All with TSAN
  • All with MSAN
  • All with UBSAN
  • All with Coverage
  • All Regression
  • Disable CI Cache

Regression jobs to run:

  • Fast suites (mostly <1h)
  • Aggregate Functions (2h)
  • Alter (1.5h)
  • Benchmark (30m)
  • ClickHouse Keeper (1h)
  • Iceberg (2h)
  • LDAP (1h)
  • OAuth (5m)
  • Parquet (1.5h)
  • RBAC (1.5h)
  • SSL Server (1h)
  • S3 (2h)
  • S3 Export (2h)
  • Swarms (30m)
  • Tiered Storage (2h)

UnamedRus and others added 13 commits August 6, 2026 14:36
When a Parquet column chunk provably holds a single value in every row -
its min/max statistics have `min_value == max_value`, no nulls, and the
value is exact - the reader no longer fetches or decodes that chunk's
data pages. Instead `detectConstantColumn` records the value and
`decodePrimitiveColumn`/`formOutputColumn` materialize it directly.

This skips the offset index, column index, dictionary page and data page
reads for such chunks (the row group already passed the key condition via
its `min == max` hyperrectangle), which is a byte-level I/O win for wide
constant columns, plus the decode/decompression CPU.

Restricted to flat, top-level primitive columns with no element nulls.
For `BYTE_ARRAY`/`FIXED_LEN_BYTE_ARRAY` the writer may truncate min/max,
so `min == max` is trusted only when `is_min_value_exact` and
`is_max_value_exact` are both set; fixed-width numeric types are never
truncated.

The value is taken from `PageDecoderInfo::decodeField`, which yields it
in the final output (post-cast) domain - e.g. `DateTime` written as
`TIMESTAMP_MILLIS` decodes to seconds, not the raw millisecond
`decoded_type`. So the constant is materialized directly in the output
type, bypassing the `decoded_type` column and `castColumn`.

Gated by the new setting
`input_format_parquet_use_constant_column_optimization` (default on). A
new `ParquetConstantColumnChunks` ProfileEvent counts materialized
chunks.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Two independent scheduling fixes for the v3 reader on large remote files.

A. Split the per-stage memory budget from the thread budget. Previously
`Stage::memory_target_fraction` drove both a stage's memory watermark and
its thread count (`getLimitsPerReader`), and every active stage defaulted
to an equal 0.2 share. So `ColumnData` - the one stage that decodes large
row groups - was capped at 0.2 of both memory and threads, and on a
single large cross-region file only ~2 row groups were read/decoded
ahead, leaving the link idle. `Stage` now has a separate
`thread_target_fraction`; `getLimitsPerReader` takes both. `ColumnData`
gets the lion's share of memory and a larger thread share, while the
small, latency-bound index/bloom reads keep enough threads for parallel
small reads. The split is static and wants a perf run to tune; it still
couples prefetch depth to decode concurrency (decoupling those is a
separate, larger change).

B. Charge decoded output by its actual footprint. The memory reserved
for a subchunk before decoding was an estimate
(`estimateColumnMemoryBytesPerRow`) that undershoots for long strings and
skewed data, so real RAM overshot the watermark and the overshoot grew
with decode-ahead depth. After `decodePrimitiveColumn`, reconcile the
`MemoryUsageToken` up to the real `allocatedBytes` of the decoded column,
offsets and null maps (grow-only, fail-closed), so the stage counter is
honest and the scheduler stops decoding ahead before RAM exceeds the cap.

Both are internal scheduling/accounting changes with no query-result
change. NOT YET BUILT OR PERF-TESTED; the stage split numbers are a
starting point.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Fixes the placement of the honest-accounting reconciliation from the
previous commit. It ran in `runTask` after `decodePrimitiveColumn`
returned, but for the common single-primitive column the function's tail
already `std::move`s `subchunk.column` into the output via
`formOutputColumn`, so the measurement saw a null column and was a no-op.

Thread `MemoryUsageDiff &` into `decodePrimitiveColumn` and reconcile the
`MemoryUsageToken` up to the real `allocatedBytes` of `subchunk.column`
(plus array offsets and the group null map) at the end of decoding, just
before the bookkeeping that may move the column out. Grow-only,
fail-closed. Matches the earlier `parquet/honest-memory-cap` prototype.

Still not built or perf-tested.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Two gate bugs made detectConstantColumn reject every column, so the
optimization never triggered on real files. Found by building and testing
against CH-written Parquet.

1. Null gate. The CH writer omits `null_count` for physically non-nullable
   (`REQUIRED`) columns, but the gate required `null_count` to be present
   and zero, rejecting every non-nullable column. A `REQUIRED` column can
   have no nulls regardless of the statistic, so only require zero
   `null_count` when the column is physically nullable (max definition
   level > 0).

2. Structural gate. `levels[0]` is a synthetic root sentinel with
   `is_array = true`, so a flat `REQUIRED` column's `levels.back()` IS that
   root (`size() == 1`, `is_array == true`) and a `Nullable` column has
   `size() == 2`. The old `levels.size() == 1 && !levels.back().is_array`
   test therefore rejected exactly the flat columns it meant to accept.
   Replace with the correct flatness signals (`levels.back().rep == 0` and
   `max_array_def == 0`), keep the `group_nullable` exclusion, and require
   the output column to be primitive (top-level, not a Tuple/Map/Array
   leaf) via `output_columns`.

Verified on a CH-written file (1M rows, constant Int64/String/DateTime/
Nullable columns): the optimization now fires (`ParquetConstantColumnChunks`
= columns x row groups), results are correct (including the
TIMESTAMP_MILLIS -> DateTime seconds path), reading the constant columns
drops `ParquetPrefetcherReadRandomRead` 10 -> 1 and `ParquetDecodingTasks`
96 -> 64, and a varying column is correctly not treated as constant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…tch stage)

Adds a ColumnDataPrefetch pipeline stage between OffsetIndex and
ColumnData. It runs `determinePagesToPrefetch` and issues the compressed
data-page reads (`startPrefetch`) but does not decode; ColumnData then
only decodes from the already-in-flight buffers.

The two stages have separate memory budgets: ColumnDataPrefetch gets a
large share (compressed row groups are cheap, ~tens of MB) so many row
groups can have their reads outstanding, while ColumnData gets a bounded
share (decoded row groups are large, ~hundreds of MB) that caps how many
are decoded/resident at once. Because row groups are independent and
their reads run in the Prefetcher's own io pool (not the parsing
threads), fetch depth is now decoupled from decode-ahead depth - the
fetch-deep / decode-shallow mode that finding #5 called for. Within a row
group subgroups stay sequential, so `determinePagesToPrefetch`'s in-order
requirement is preserved.

The compressed-read memory is charged to the ColumnDataPrefetch stage via
startPrefetch and released when ColumnData resets the prefetch handles
(the handle records its allocating stage, so the release credits the
right budget regardless of which stage's diff performs it).

Verified on the Debug build: reads are correct with and without PREWHERE
(3M-row multi-row-group file), the constant-column optimization still
fires, and there is no deadlock. Perf/prefetch-depth gains need a
high-RTT remote (S3) run to observe.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds read back-pressure on the ColumnDataPrefetch stage: once the
compressed data already in flight covers more than
`input_format_parquet_prefetch_bandwidth_hide_seconds` of the measured
read throughput, stop prefetching further ahead. Beyond that point the
storage link is already fed, so extra compressed buffering only wastes
memory without improving throughput (the "+21 GB RAM for +3.6 s" case in
finding #4).

The Prefetcher now tracks completed-read throughput (bytes since init /
elapsed, `averageThroughputBytesPerSec`). The scheduler compares it
against the ColumnDataPrefetch stage's in-flight compressed bytes (that
stage's memory usage) and stops admitting more prefetch tasks when the
in-flight bytes exceed throughput x hide_seconds. The privileged-task
escape (lowest incomplete row group is always schedulable) still applies,
so back-pressure can never deadlock.

Defaults to 0 (disabled): the throughput heuristic and the hide-seconds
target can only be validated on a high-RTT remote (S3) run, and on local
fast IO the estimate is meaningless, so it is opt-in for cluster tuning.
With C's ColumnDataPrefetch memory budget already providing a static
cap on compressed buffering, this setting makes that cap adaptive.

Verified on the Debug build: results are correct with the setting off
(default) and with an aggressively small value (0.001s) that forces heavy
throttling - no deadlock, identical results.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Port adaptation: antalya-26.6 predates the Nullable(Tuple) support on
master, so PrimitiveColumnInfo::group_nullable and
ColumnSubchunk::group_null_map do not exist there. Remove those
references from the constant-column detection gate and the decoded-memory
reconciliation. Both are safe: nested-in-nullable-struct leaves are
already excluded from the constant-column optimization by the
`output_columns[...].is_primitive` guard, and the group null map (when it
would exist) is negligible in the memory reconciliation.

Also resolved during the rebase onto antalya-26.6:
- ProfileEvents/Reader: keep only the new ParquetConstantColumnChunks
  event (antalya has no ParquetPrunedPages).
- Column index uses antalya's singular `column_index_condition`.
- Dropped the master-only `pruningMemoryReservation` (antalya's
  applyBloomAndDictionaryFilters takes no reservation).

NOT YET COMPILED against antalya-26.6.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: c6b70b3
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: 34816a3
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: f260506
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: 2a20ab9
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: 114640e
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: a019cd7
I, UnamedRus <dtitmoav@gmail.com>, hereby add my Signed-off-by to this commit: a3ee936

Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Commit c6b70b3 accidentally added a `unique_key_probe_implementation`
entry to `SettingsChangesHistory.cpp` under version 26.8. That setting is
not registered anywhere in `Settings.cpp`, so `02324_compatibility_setting`
failed with `UNKNOWN_SETTING` when applying `compatibility` to old versions.
The entry is unrelated to the parquet constant-column work; remove it.

CI: https://github.com/Altinity/ClickHouse/actions/runs/31099889198/job/92610989464

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Extends the constant-column optimization to the all-null case. When a
Parquet column chunk provably holds only nulls - its `null_count` statistic
equals `num_values` on a physically nullable leaf - the reader no longer
fetches or decodes that chunk's dictionary or data pages. `detectConstantColumn`
marks the chunk constant (and `is_all_null`), and `formOutputColumn`
materializes the result directly: `Null` for a Nullable output, or the output
default when `input_format_null_as_default` substitutes nulls for a
non-nullable output. A non-nullable output without null substitution cannot
represent the result, so such a chunk is left to the normal decode path.

Unlike the single-value case this needs no value decode, so it sidesteps the
min/max exactness and `BYTE_ARRAY` truncation checks entirely; it only reads
the `null_count` count. `formOutputColumn` records every row of an all-null
chunk in `block_missing_values` (the single-value case has no nulls and records
nothing), matching the normal decode path's null-map bookkeeping so
`input_format_null_as_default` stays correct.

All-null wide chunks are common in schema-evolved files (a column added later
is all-null in older row groups), so this skips dictionary, data page, offset
index and column index reads for a frequent real-world shape. Reuses the
existing `input_format_parquet_use_constant_column_optimization` setting and
the `ParquetConstantColumnChunks` ProfileEvent.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Commit c6b70b3 fabricated two entire version blocks (26.8 and 26.7) in
SettingsChangesHistory.cpp holding ~80 setting entries pulled in by a bad
merge. 63 of them reference settings that are not registered on this branch
and 10 duplicate entries recorded elsewhere, so applying `compatibility` to an
older version threw `UNKNOWN_SETTING` (e.g. `s3_base`,
`unique_key_probe_implementation`), failing 02324_compatibility_setting.

The only entry that belongs to this parquet commit is
`input_format_parquet_use_constant_column_optimization`. Remove both fabricated
blocks and keep just that setting, moved into the pre-existing 26.6 block. The
resulting history equals the commits parent plus that single line.

Follow-up to 77c2c72 which removed only the first offending entry.

CI: https://github.com/Altinity/ClickHouse/actions/runs/31105816361/job/92630866726

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
…ds in history

The setting was added by a019cd7 but never given a SettingsChangesHistory
entry, so 02995_new_settings_history reported it as an undocumented new setting
(the failure surfaced once 02324_compatibility_setting stopped failing first).
Add it to the 26.6 block next to input_format_parquet_use_constant_column_optimization;
default 0 disables the back-pressure and matches the pre-existing behavior.

Reproduced the full 02995 check locally (registered settings minus both baseline
TSVs minus recent-version history): this was the only missing setting.

CI: https://github.com/Altinity/ClickHouse/actions/runs/31110878761/job/92648476492

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
The previous run failed in Config Workflow / Set up job with
"Failed to resolve action download info. Error: Service Unavailable" - a
transient GitHub Actions outage, not a code failure. Empty commit to re-run CI.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
@github-actions

github-actions Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Workflow [PR], commit [9ab3e8e]

UnamedRus and others added 7 commits August 7, 2026 12:55
Adds the DataLakeCatalog `namespaces` setting: a comma-separated list of
allowed namespaces for `rest`, `glue` and `unity` catalog types, so a
DataLake database exposes only the selected namespaces. `rest` supports nested
rules (`foo`, `foo.bar`, `foo.*`) via `RestCatalog::AllowedNamespaces`;
`glue`/`unity` use a flat allow-set. Default `*` allows everything
(pre-existing behavior).

Ported from the merged antalya-25.8 PR onto antalya-26.6. Cross-version
adaptations:
- Catalog construction moved into `DatabaseDataLake` in 26.6, so the namespaces
  are threaded through `CatalogSettings` / the catalog constructors there; the
  25.8 inline construction in `DataLakeConfiguration::getCatalog` (and its
  `catalog_namespaces` plumbing) is obsolete and dropped, leaving
  `DataLakeConfiguration.h` unchanged.
- `CATALOG_NAMESPACE_DISABLED` error code renumbered 757 -> 779 (757..778 are
  already taken on this branch).
- The namespace filter checks were merged into 26.6-refactored code paths
  (threadpool-based `RestCatalog::getTables`, extracted Glue credentials
  provider, 26.6 `resolveMetadataPathFromTableLocation`).
- The delegating 6-arg `RestCatalog` constructor (used by OneLake/BigLake,
  which do not support the filter) defaults `allowed_namespaces` to `*`.
- Added explicit `<boost/algorithm/string.hpp>` and `<unordered_map>`/
  `<unordered_set>` includes (the upstream PR relied on transitive includes).

PR: #1337

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
The ported AllowedNamespaces block opened a public: section for the nested
class and closed with private:, which downgraded every RestCatalog member
after it (loadConfig, getAuthHeaders, retrieveAccessToken, ...) from protected
to private. Subclasses (OneLake/BigLake/Paimon REST catalogs) call those, so
Build failed with "is a private member of DataLake::RestCatalog". Restore the
trailing access specifier to protected; AllowedNamespaces stays public (the
gtest references it).

CI: https://github.com/Altinity/ClickHouse/actions/runs/31171012685/job/92846936566
PR: #2181

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Adding the namespaces_ parameter to the primary RestCatalog constructor broke
the pre-existing unit test gtest_rest_catalog.cpp, which constructed a
RestCatalog without it (no matching constructor). Pass namespaces = "*"
(allow all) in the new argument slot, before the context argument.

CI: https://github.com/Altinity/ClickHouse/actions/runs/31176356154/job/92863225108
PR: #2181

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
formOutputColumn previously expanded a constant column chunk with
insertMany(Field, num_rows) - an O(rows) per-row Field-dispatch fill that
showed up as a consistent ~20% UserTime increase in profiling (the baseline
decoded the same near-constant chunk cheaply via RLE/dictionary).

Emit a ColumnConst instead: O(1) to build, and the const-ness propagates
through the pipeline. A PREWHERE/WHERE predicate computes its result from the
value without expanding the stored column, and GROUP BY / aggregation over the
column get a const key. The value is already in the output (post-cast) domain.
The all-null block_missing_values bookkeeping is unchanged.

The reader path preserves the const: getOrFormOutputColumn returns it as-is,
ColumnConst::size() == rows_pass satisfies the delivery checks, and
ColumnConst::filter keeps it const through multistage PREWHERE.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Extends the constant-column optimization from whole-chunk (tier 1, footer
statistics) to per-row-subgroup granularity using the Column Index per-page
min/max/null_pages, which the reader already loads for predicate push-down.
Catches columns constant over a run of pages without the whole row group being
constant (common in sorted/clustered data), with no change to subgroup/chunk
sizing.

- constColumnMaterializationEligible: shared flat-top-level-primitive gate,
  factored out of detectConstantColumn.
- applyColumnIndex: retain per-page constant info (value / is_const / all_null)
  in ColumnChunk::page_const_info. Fixed-width numeric/date/time only for value
  constants (the Column Index has no per-page exactness flag, so a truncated
  BYTE_ARRAY min==max is untrustworthy); all_null is a plain flag, always safe.
- detectConstantSubchunk: a column is constant for a subgroup iff every page
  overlapping the subgroup row range is all-null, or all hold the same value.
- Wired into intersectColumnIndexResultsAndInitSubgroups; sets the subchunk
  constant fields so decodePrimitiveColumn skips decode and formOutputColumn
  materializes a ColumnConst. New ParquetConstantColumnSubchunks ProfileEvent.

Tier 1 stays the always-on baseline and the only detector for BYTE_ARRAY. Tier 2
is opportunistic: only where the Column Index is already loaded (predicate
push-down columns), never force-fetched.

Deferred (follow-up): skipping the prefetch of constant subgroups pages (the I/O
win). Currently those pages are still fetched and skipped forward by the next
subgroups skipToRowOrNextPage; correct but does not yet save the read.

Design: docs/design/parquet-v3-page-level-constant-column.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Completes tier-2: a per-subgroup constant column (detectConstantSubchunk) now
also skips fetching its data pages, not just decoding them. In
determinePagesToPrefetch, a constant subchunk claims no pages; a page fully
inside it is released (never fetched), while a page shared with a neighbouring
non-constant subgroup is left for that subgroup to claim.

Safe because tier 2 only exists when the Column Index (hence Offset Index) is
loaded: a constant subgroup never calls skipToRowOrNextPage, and a non-constant
subgroup jumps directly via the offset index to its own claimed pages, so a
released constant page between them is never accessed. The whole-chunk
data_pages_prefetch is still split (likely_to_be_used=false), so only claimed
pages are actually read.

This turns the tier-2 CPU/memory win into an I/O win as well (fewer S3 GETs /
ParquetPrefetcherReadRandomRead), matching tier 1 but at page granularity.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Adds input_format_parquet_use_column_index_for_constant_columns (default off).
By default tier-2 per-subgroup constant detection only runs where the Column
Index is already loaded (columns with a predicate). This setting force-loads the
Column Index (and Offset Index) for eligible read columns without a predicate,
so tier-2 can skip single-valued page runs on them too - worthwhile for sorted /
low-cardinality columns, at the cost of a small extra (tail-contiguous,
coalesced) index read.

A force-loaded column takes the same load path as a predicate column
(use_column_index = true); applyColumnIndex records per-page constant info but
skips page-level predicate pruning when the column has no condition (prev_row_idx
stays 0 -> whole chunk selected -> no restriction).

Setting is declared in FormatFactorySettings, plumbed through FormatSettings /
FormatFactory, and recorded in SettingsChangesHistory (26.6).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
@UnamedRus

Copy link
Copy Markdown
Collaborator Author

RowGroup level + push ColumnConst to transforms

┌───────────────────────────────────┬──────────┬─────────────┬───────────────┐
│              Metric               │ baseline │ ColumnConst │       Δ       │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ DefaultImplementationForNullsRows │ 3.367B   │ 0.718B      │ −78.7%        │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ RealTimeMicroseconds (wall)       │ 333.5M   │ 243.1M      │ −27.1%        │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ UserTimeMicroseconds              │ 21.17M   │ 18.22M      │ −13.9%        │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ OSCPUVirtualTimeMicroseconds      │ 23.93M   │ 21.04M      │ −12.1%        │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ S3GetObject                       │ 663      │ 467         │ −196 (−29.6%) │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ ParquetPrefetcherReadRandomRead   │ 662      │ 466         │ −196 (−29.6%) │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ ParquetFetchWaitTimeMicroseconds  │ 104.5M   │ 69.0M       │ −34%          │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ ReadBufferFromS3InitMicroseconds  │ 63.1M    │ 37.0M       │ −41%          │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ MemoryAllocatedWithoutCheckBytes  │ 486.8M   │ 359.3M      │ −26.2%        │
├───────────────────────────────────┼──────────┼─────────────┼───────────────┤
│ SelectedBytes                     │ 2214.1M  │ 2115.7M     │ −4.4%         │
└───────────────────────────────────┴──────────┴─────────────┴───────────────┘

UnamedRus and others added 6 commits August 7, 2026 19:57
…off]

Approach B: when only PART of a row subgroup is single-valued (a constant run
shorter than, or straddling, a subgroup), fill those pages from the per-page
Column Index while decoding only the varying pages - producing a full column
where whole-subgroup tier-2 cannot make a ColumnConst.

Gated behind input_format_parquet_fill_constant_pages (default off). Additional
gates keep it correct and simple:
- output column must not need a post-decode cast (we fill the decoded_type
  column with the Column Index value, valid only when decoded == output value
  type);
- no predicate on the column (so no page pruning; data_pages == all pages);
- no prewhere filtering in the subgroup (avoids filter/range intersection);
- at least one single-value page and no all-null page in the subgroup (all-null
  pages fall back to the standard decode).

fillConstantPagesAndDecodeRest walks the subgroup page by page: a single-value
page is filled via insertMany (+ null-map zeros) without reading it; a varying
page is decoded with the existing skipToRowOrNextPage + readRowsInPage, which
jumps over the filled pages via the offset index without loading them.

First cut is decode-fill only: constant pages are still prefetched (correct,
some wasted I/O). Skipping their prefetch needs cross-subgroup coordination and
is a follow-up.

Design: docs/design/parquet-v3-page-level-constant-column.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Completes the mixed-topology fill (input_format_parquet_fill_constant_pages,
default off): a subgroup that fills its single-value pages from the Column Index
no longer prefetches them. determinePagesToPrefetch consults
willFillConstantPages (the same deterministic predicate the decode path uses) and,
for a fill subgroup, does not claim its is_const pages - so a page overlapped
only by fill subgroups is released and never read, while a page also decoded
normally by another subgroup is still fetched.

Also adds a no-prewhere / no-row-level-filter gate to willFillConstantPages so
rows_pass == rows_total holds identically at prefetch time and decode time,
keeping the two decisions consistent.

This turns the mixed-topology fill from a decode-CPU-only win into an I/O win
too (fewer page reads), matching tier-2 at sub-subgroup granularity.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
min_value == max_value provably means a single exact value for every physical
type, including BYTE_ARRAY / FIXED_LEN_BYTE_ARRAY. Statistics and Column Index
bounds are always valid (min_value <= every value <= max_value) and truncation
only ever widens them, so a truncated value - or any page/chunk with two
distinct values - yields min_value < max_value. Equality therefore requires a
single value short enough to be stored exactly; the is_*_value_exact flags are
implied and, for the Column Index (which has no per-page exact flag), never
needed.

Remove the BYTE_ARRAY/FIXED_LEN exclusion from tier 1 (detectConstantColumn) and
the per-page recording in tier 2 (applyColumnIndex), so constant string columns
and string constant page runs get the optimization too. Also fixes tier 1 for
writers that omit is_*_value_exact (previously any such BYTE_ARRAY constant was
skipped even when short and exact).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Previously a mixed-topology subgroup (input_format_parquet_fill_constant_pages)
bailed to normal decode if any overlapping page was all-null. Now fill them too:
an all-null page appends no non-null values and marks its rows null in the null
map; the existing expand() + Nullable-wrap / null_as_default tail finalizes them
exactly as the normal decode does (the column holds compact non-null values, the
null map covers all rows). determinePagesToPrefetch also skips prefetching
all-null pages, matching the fill.

willFillConstantPages now accepts all-null pages as fillable, but still bails
when an all-null page is present and the output can represent neither null
(non-Nullable output) nor a default (no null_as_default) - the standard decode
raises the usual not-null error there.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
Drop the column_index_condition gate from willFillConstantPages. A page-pruning
predicate on the column (column_index_condition) is safe for the fill: subgroups
are built only over contiguous surviving row ranges, so a pruned page never
overlaps a subgroup and the fill never walks it; the prefetch-skip indexes
page_const_info by each page global position (page.meta into page_locations),
which is correct regardless of the data_pages subset. A column carrying an
actual prewhere/row-level filter is still blocked by the no-prewhere gate.

Gate 2 (output needs_cast) is intentionally left in place: whether decodeField
yields the decoded or the output value domain is ambiguous from static reading
(SchemaConverter/convertField vs the tier-1 is_constant branch), and guessing
wrong is silent wrong data. It needs a build + a needs_cast test to resolve
(and that test would also confirm tier-1/tier-2 on hint-cast columns).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
The mixed-topology fill now walks the rows that pass the filter
(row_subgroup.filter) instead of the whole subgroup range, so it works under
PREWHERE / row-level filters: it iterates passing ranges (like the standard
row-range decode) and, within each, fills constant / all-null pages for their
overlapping passing rows and decodes varying pages for the contiguous passing
sub-range. It therefore produces exactly rows_pass values for any filter, and
willFillConstantPages no longer depends on rows_pass - so the decision is
identical at prefetch time and decode time and the prefetch-skip can never drop
a page the decode needs.

Removes the no-prewhere and rows_pass == rows_total gates from
willFillConstantPages. The only remaining gate is needs_cast (build-gated; see
the decodeField value-domain question).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: UnamedRus <dtitmoav@gmail.com>
@ianton-ru

ianton-ru commented Nov 23, 2026 •

Copy link
Copy Markdown

List of features.

  1. S3 object identity cache - Object storage identity cache #2888
  2. Latency-weighted host selection - Latency-weighted host selection for endpoints with several addresses (http_latency_aware_host_selection) #2945
  3. Do not shadow random-access formats with a from-start prefetch - can be covered with Disable 1MB Head prefetch for small random access files (Parquet) ClickHouse/ClickHouse#115681
  4. Parquet footer-size hint, plus reuse of that tail - Antalya 26.8: Parquet footer-size hint from Iceberg manifests and reuse of the footer tail #2950
  5. Parquet constant columns
  6. Parquet prefetch/decode split and read back-pressure
  7. Align Parquet reads to S3 part boundaries
  8. Parallel per-part GETs and a speculative footer read
  9. Hedged Parquet reads
  10. Fill-ratio guard for Parquet coalescing - Parquet v3: fill-ratio guard for read coalescing (input_format_parquet_read_min_fill_ratio) #2946
  11. Parallel Iceberg manifest processing - can be covered with Read Iceberg manifest files on the IO thread pool and remove the manifest decode pool ClickHouse/ClickHouse#127100
  12. Iceberg metadata-cache identity for the first read - Iceberg: key the metadata files cache on the first read by the catalog table-uuid #2947
  13. Distributed plans for object-storage reads - solved in closed-source ClickHouse Cloud version.

ianton-ru added a commit that referenced this pull request Nov 23, 2026
…m master.

The setting description of `input_format_parquet_footer_read_size` now says the 64 KiB tail applies when the file is read directly from the local filesystem (the reader's buffer reports `isRegularLocalFile`). Reads through a file descriptor or a wrapping buffer keep the adaptive size. The `SettingsChangesHistory` reason no longer says that `0` keeps the adaptive behavior.

Cherry-picked from 6fbb4e7; on 26.8 the history reason is in `SettingsChangesHistory.cpp`, so it is changed there.

ClickHouse#124883
Related: #2181
ianton-ru added a commit that referenced this pull request Nov 26, 2026
…cancelled after the upload started

`WriteBufferFromS3::preFinalize` can already have sent `PutObject`, or scheduled `CompleteMultipartUpload`,
when the buffer is cancelled. `cancelImpl` waits for those tasks and drops their errors, so the object may
have been replaced while the identity cache kept the previous size and ETag.

`cancelImpl` now runs the upload callback when an object-creating request was sent. The callback runs at
most once, because a failed `finalize` runs it and then cancels the buffer.

Related: #2181
Related: #2888
Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
The delete paths invalidated the identity cache only after the request returned. A `DeleteObject` or
`DeleteObjects` whose response was lost can still have removed the objects, and a batch that fails in a
later chunk has already removed the earlier ones, so the cache kept the previous size and ETag.

Invalidate on every exit of `removeObjectImpl`, `removeObjectsImpl`, the single-key branch of
`removeObjectsIfExistImpl`, `BackupWriterS3::removeFile` and `BackupWriterS3::removeFiles`. Also invalidate
before throwing on a whole-batch failure in `removeObjectsIfExistImpl` and on an unclassified error in
`removeObjectIfTokenMatchesImpl`, where the outcome is unknown.

Related: #2181
Related: #2888
Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
…tion guards

The delete paths invalidate the identity cache from `SCOPE_EXIT` guards. A scope guard's destructor is
implicitly `noexcept`, and invalidating allocates the cache key. On the normal exit of a successful delete,
the memory tracker may throw `MEMORY_LIMIT_EXCEEDED` for that allocation, and the exception then escapes the
destructor and terminates the server.

Use `SCOPE_EXIT_MEMORY` for the guards in `removeObjectImpl`, `removeObjectsImpl`, the single-key branch of
`removeObjectsIfExistImpl`, `BackupWriterS3::removeFile` and `BackupWriterS3::removeFiles`. It blocks memory
exceptions for the duration of the guard, as `WriteBuffer::cancel` does.

Related: #2181
Related: #2888
Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
…n object to an S3 disk

`BackupReaderS3::copyToDiskImpl` copies a backup object straight into a destination S3 disk with
`copyS3File` or `copyS3FileRange`. It did not invalidate the destination key, so a fixed key that was
read earlier kept its previous size and ETag. The next read then sent `If-Match` for the old generation.
Every other copy into an S3 object (backup writes, the queue post-processor, `S3ObjectStorage`) already
drops the entry.

Pass an invalidation callback to the copy, so it also runs when the copy throws after an object-creating
request was sent. Invalidate again after the copy returns. The entry is keyed by the destination endpoint,
the blob bucket and the blob key. A destination that is not an S3 storage now fails before the copy.

Related: #2181
Related: #2888
Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
…S3ObjectStorage

`BackupReaderS3::copyToDiskImpl` read the destination endpoint with a `dynamic_cast` to `S3ObjectStorage`,
added by e65b47a. A disk with a `cache` layer is `DiskObjectStorage(CachedObjectStorage(S3ObjectStorage))`,
so the cast returned null and the restore failed with `LOGICAL_ERROR` before any copy started. Read the endpoint
through the virtual `getDescription` instead. `S3ObjectStorage` returns the same `uri.endpoint` that its own
invalidation uses, and `CachedObjectStorage` forwards the call. The native copy is still taken only when the
destination has the S3 data source kind.

Add the test `05815_object_storage_identity_cache_restore_to_cached_disk`: it restores a table on the `s3_cache`
disk with `allow_s3_native_copy` and checks the rows and the `S3CopyObject` event.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
… test

`05497_object_storage_identity_cache_parquet_count_after_replace` expects a Parquet `count` after an external
replace to succeed. That holds only for the footer-only count: it needs `need_only_count`, which depends on
`optimize_count_from_files`. With that setting off the count reads the file with the GET pinned to the cached
ETag, so a replaced object fails with `S3_OBJECT_CHANGED_DURING_READ`, as designed. The stateless runner
randomizes the setting, so the test failed intermittently.

Pin `optimize_count_from_files` and `optimize_trivial_count_query` in the read settings. With
`optimize_count_from_files 0` forced at the client, the previous settings fail with
`S3_OBJECT_CHANGED_DURING_READ` and the pinned settings pass.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
`s3CredentialHash` hashed only the AWS access key, secret and session token. A principal that authenticates with
request headers, such as `headers('Authorization' = 'Bearer ...')` of the `s3` table function or the SSE-C key
headers, has no AWS credentials or the same ones as another principal. All of them hashed to the same value, so
a metadata-only read (`_size`, `_etag`, `_time`, existence, no-GET paths) by one principal could be answered from
the identity cached by another one without any request to S3. The file contents were not exposed, because
`createReadBuffer` revalidates with the caller's own headers before a content cache can answer without a GET.

Hash the extra request headers of the client (name and value, in order) together with the credentials.
Headers configured on the server are identical for every user and do not split the cache. Clients without
headers still share one hash, as before.

Add the test `05816_object_storage_identity_cache_request_headers_principal`: the same object read with
`headers(...)` A, then B, then none. Each principal misses and sends its own HEAD, and then hits with the same
headers. Without the change principal B reuses the entry of A and sends no HEAD.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
`ObjectStorageIdentityCache::setIfEpoch` compared the sequence of a fetch only with the resident entry. If fetch A
started before an external overwrite, fetch B started after it and stored the new identity, and the entry of B was
evicted by cache pressure before A finished, A found no entry and stored the older identity. The next read then
reused a stale size and ETag.

Remember the highest sequence that stored an entry in a fixed array of slots indexed by the hash of the key. It
is not tied to the residency of the entry, so eviction does not forget it. Two keys can share a slot, which
only skips a store that would have been safe: the next read of that key requests the metadata again.
The per-entry `fetch_seq` is no longer needed and is removed.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
…nal replaces

The section on `SYSTEM CLEAR OBJECT STORAGE IDENTITY CACHE` only said that a write, copy or delete by this server
drops an entry. The cache is enabled by default, so a metadata-only read of an object that was replaced outside this
server, such as `_size`, `_etag` or `_time`, can return the previous generation. A read that downloads the object
detects the replacement through `If-Match` and drops the entry.

Describe that contract and the ways to see current metadata: `s3_validate_etag_on_read = 0` for the query,
`object_storage_identity_cache_size = 0`, or `SYSTEM CLEAR OBJECT STORAGE IDENTITY CACHE`.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
… errors

`invalidateObjectStorageIdentityCache` builds the cache key, which allocates. Several callers run it after an
object-changing request has already succeeded: `copyObject`, the conditional delete in
`removeObjectIfTokenMatchesImpl`, and the failed-delete branch of `removeObjectsIfExistImpl`. Those callers do not
all sit in a `SCOPE_EXIT_MEMORY`. Under a query memory limit the allocation can throw `MEMORY_LIMIT_EXCEEDED` after
the object has changed. The query then reports a failure, and the previous size and ETag stay cached, so
metadata-only reads return the old object.

Lock memory exceptions inside the helper, so every caller is covered, the same way `SCOPE_EXIT_MEMORY` does.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
`ObjectStorageIdentityWeight` counted the identity, its ETag and a fixed 128 bytes. The cache stores each entry
under the full composite key `endpoint`, `bucket` and `path`, and that key was not counted. With long object paths
an entry can take several times its weight, so `object_storage_identity_cache_size` and the
`ObjectStorageIdentityCacheBytes` metric understate the memory the cache holds, and the process can use hundreds of
megabytes beyond a 64 MiB limit.

The weight function sees only the value, so `setIfEpoch` stores the capacity of the key in the entry, and
`memoryUsage` counts it. The fixed overhead now covers the hashmap node, list links and `shared_ptr` only.

Add the test `05817_object_storage_identity_cache_weight_counts_key`: after a cold read of an object with a 700-byte
path, `ObjectStorageIdentityCacheBytes` must be at least 700.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
The S3 mock rejects keys above its limit (`KeyTooLongError`), so the 700-byte path of
`05817_object_storage_identity_cache_weight_counts_key` failed on the INSERT. Use a 400-byte path. Without the
key in the weight an entry weighs about 260 bytes, so the test still tells the two cases apart.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
The S3 mock still rejected the 400-byte path (`KeyTooLongError`), because the object key also contains the test
name. Use a 100-byte path and require a weight of at least 400 bytes. The entry weighs about 450 bytes with the key
counted and about 250 without it, so the threshold separates the two cases.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
The cache policies keep every key twice: as the key of the hashmap and in the
eviction queue list. The entry weight counted the key once, so a long object
path still made the cache hold up to about 40% more memory than
`object_storage_identity_cache_size` and `ObjectStorageIdentityCacheBytes`
reported. Count the key capacity twice.

`05817_object_storage_identity_cache_weight_counts_key` now requires at least
600 bytes for one entry: about 240 without the key, 450 with one copy, 661 with
both.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 26, 2026
The field holds the memory of both copies of the key that the cache policy
keeps, not the capacity of one key.

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 27, 2026
The identity cache keeps the modification time of an object, but that time is
not proof the object is unchanged, so the schema inference and number-of-rows
caches do not use it. `test_schema_inference_cache` runs a HEAD for the schema,
then a count of the same object in the same query, which now gets the time
from the identity cache. For `s3` the count expects no number-of-rows cache
hit. `url` storage does not use the identity cache and keeps the hit.

Document the bypass in `SYSTEM CLEAR OBJECT STORAGE IDENTITY CACHE`.

CI report: https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2888&sha=32fbd93f3b464e9b584c624481c42ffc36b985a4&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%201%2F8%29

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 27, 2026
… objects

`invalidate` advanced one epoch for the whole cache, so a write to any S3
object on the server made every metadata fetch in flight skip its store. A
server that writes to S3 all the time, for example a MergeTree table or a
system log on an S3 disk, then rarely filled the cache, and the next read of
an object sent a HEAD again. In the CI job with an S3 storage policy this made
`05485_object_storage_identity_cache_endpoint_key` and
`05500_object_storage_identity_cache_backup_replace` flaky: a warm read had
`S3HeadObject=1` instead of 0.

Replace the epoch with a logical clock. `invalidate` stamps the hash slot of
its key, `clear` stamps the whole cache, and a fetch stores only if nothing
stamped its slot after it began. The stamp of the last store in the slot keeps
the ordering of fetches of one key, as before. Two keys can share a slot, which
only skips a store that was safe to do.

`05818_object_storage_identity_cache_unrelated_writes` pauses a read before
its store, overwrites another object, and requires the next read to hit.
Before the change it fails with `S3HeadObject=1, expected 0`.

CI report: https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2888&sha=050bc00e5dab4d79a79aa35e074037b601a3f5ac&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20sequential%29

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 27, 2026
…lookups off

`test_schema_inference_cache` expected no number-of-rows cache hit for S3, so
it no longer checked the hit path for S3 at all. A query with
`s3_validate_etag_on_read = 0` skips the identity cache, so its HEAD gives a
fresh modification time, and it must hit the number-of-rows cache.

Also fix the comment in `05489_object_storage_identity_cache_clear_during_fetch`:
the clear stops the stores in flight, it does not advance an epoch.

CI report: https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2888&sha=050bc00e5dab4d79a79aa35e074037b601a3f5ac&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20sequential%29

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>
ianton-ru added a commit that referenced this pull request Nov 27, 2026
… commit reverted

`126f57cbb8fc` committed `05489_object_storage_identity_cache_clear_during_fetch` from a stale
working-tree copy and so undid `85c874d738b7`. The test ran every read with
`s3_validate_etag_on_read = 0`, which skips the identity-cache lookup, so the final read counted no
miss and failed with `Misses=0, expected >= 1`.

Run the final read with validation on and only the paused reader with validation off, as before.
Also fix the header comment, which still described the removed epoch.

CI report: https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2888&sha=126f57cbb8fcdd01c4ff743d5434d7aadf4fb19a&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20sequential%2C%20selected%20tests%29

Related: #2181
Related: #2888

Co-authored-by: Cursor <cursoragent@cursor.com>

This branch has not been deployed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants