Skip to content

Support the Vortex file format - #112950

Merged
alexey-milovidov merged 177 commits into
masterfrom
vortex-format
Oct 26, 2026
Merged

alexey-milovidov merged 177 commits into
masterfrom
vortex-format

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 1, 2026 •

Copy link
Copy Markdown
Member

Closes: #87327
Related: ClickHouse/rust_vendor#74
Related: ClickHouse/rust_vendor#79
Related: #115096
Related: #114373
Related: #116021

Changelog category (leave one):

  • New Feature

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

Added support for reading and writing the Vortex columnar file format (the Vortex input and output format). This closes #87327.

Documentation entry for user-facing changes

The implementation uses the Rust vortex crate (v0.84.0) through a new C FFI crate rust/workspace/vortex (_ch_rust_vortex), following the same pattern as prql and polyglot. Data crosses the FFI boundary through the Arrow C Data Interface and is converted with the same ArrowColumnToCHColumn/CHColumnToArrowColumn code as the Arrow format. IO is delegated back to ClickHouse through callbacks: reads go through ClickHouse's own read buffers (range reads for seekable inputs, whole-file buffering otherwise), and the produced file is streamed into the output buffer. The library spawns no threads of its own: a scan is split into tasks that ClickHouse runs on its own thread pools (max_parsing_threads for decoding, max_download_threads for reads), writing is driven on the calling thread, and Rust panics are caught at the FFI boundary and turned into exceptions.

Features:

  • Reading with projection pushdown: only the columns used by the query are read from the file.
  • Parallel reading (merged from feat: parallel reading for vortex #115096 by @m7kss1): the file is split into row ranges that are read, filtered, and decoded concurrently; nearby segment reads are coalesced into one request. Chunks are returned as soon as they are decoded, so the row order is not guaranteed unless input_format_vortex_preserve_order is set.
  • Schema inference and count()-only queries answered from file metadata without reading data.
  • Writing with the library's default adaptive compression (BtrBlocks-style cascading encodings + zstd), including a valid empty file for empty results.
  • Graceful errors on malformed and truncated files (fuzzer-friendly: no aborts, Rust panics become exceptions).

Limitations (documented in docs/reference/formats/Vortex.mdx):

  • Map, Int128/UInt128/Int256/UInt256, IPv6, and Interval columns cannot be written (no corresponding Vortex type).
  • String and FixedString are written as Vortex Binary (ClickHouse strings are arbitrary bytes, while Vortex requires Utf8 to be valid UTF-8).
  • The format is disabled in MSan builds: the MSan-instrumented library (with origin tracking) is so large that linking unit_tests_dbms overflows the 2 GiB R_X86_64_PC32 relocation range (same approach as wasmtime and delta-kernel-rs).
  • Writing is single-threaded in this first version: the adaptive compressor samples many encodings per column, so writes are slower than Parquet — parallelism can be added later. Reading is parallel since feat: parallel reading for vortex #115096 was merged into this PR: on ClickBench, reads went from geomean ~26.8x slower than Parquet to ~1.2x, winning 9 of 43 queries (see the benchmark results). Filter pushdown (added in Enhancement for Vortex format #114373, input_format_vortex_filter_push_down, on by default) lets the scan skip the statistics zones the predicate rules out and decode only the matching rows of the rest: on a file of 1 000 000 sorted values, WHERE n = 500000 reads 66 KiB with the pushdown against 7.5 MiB without it. The most selective ClickBench queries are nevertheless still 1.5-5.5x slower than Parquet. The pushdown was reworked in ref: rework filter pushdown: ActionsDAG converter, temporal types and… #116021 by @m7kss1 (merged into this PR): the filter is translated directly from the query's ActionsDAG instead of going through a KeyCondition, which adds Bool, Date, Date32 and DateTime64 columns and LIKE/NOT LIKE/startsWith prefix ranges, and reports what reached the scan through the VortexFilterPushdownConjunctsPushed, VortexFilterPushdownConjunctsDropped, VortexScanSplits and VortexScanEmptySplits profile events.

The 127 new vendored Rust crates were added in ClickHouse/rust_vendor#74, and ClickHouse/rust_vendor#79 moved them to 0.84.0. Both are merged, so contrib/rust_vendor points at main rather than at a pull request branch.


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

Version info

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

Add `Vortex` input and output formats for reading and writing Vortex
files (https://github.com/vortex-data/vortex), an extensible columnar
file format for compressed Apache Arrow-compatible data.

The implementation uses the Rust `vortex` crate through a new C FFI
crate `rust/workspace/vortex` (`_ch_rust_vortex`). Data crosses the
FFI boundary through the Arrow C Data Interface and is converted with
the same `ArrowColumnToCHColumn`/`CHColumnToArrowColumn` code as the
`Arrow` format. IO is delegated back to ClickHouse through callbacks,
so reads go through ClickHouse's own buffers (with range reads for
seekable inputs and whole-file buffering otherwise), and writes stream
into the output buffer. All work is driven by a single-threaded
runtime on the calling thread: the library spawns no threads.

The reader supports projection pushdown (only the requested columns
are read), count-only queries from file metadata, and schema
inference. The writer uses the library's default adaptive compression
(BtrBlocks-style cascading encodings plus zstd).

Closes #87327

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 1, 2026 21:39
@mintlify

mintlify Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 26, 2026, 12:17 AM

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9f8f660]

Summary: ✅


AI Review

Summary

The PR adds Vortex input/output, parallel decoding, predicate pushdown, schema inference, and Iceberg/lazy-read integration. Reviewed head 9f8f660bac06609a93c827422cdcbe500170ee69, the current code, and prior discussions. Earlier correctness findings are addressed; one resource-limit concern remains. No new inline findings.

Findings

⚠️ Majors

  • rust/workspace/vortex/src/lib.rs:554 — Rust decoding does not enforce the query memory budget before materialization. Read buffers and decoded Arrow arrays allocate through the Rust global allocator, whose ClickHouse C allocation wrappers charge memory without throwing. execute_arrow can therefore expand compressed data beyond max_memory_usage before a subsequent ClickHouse allocation rejects the query. [dismissed by author -- https://github.com/Support the Vortex file format #112950#discussion_r4355583936] A split-count limit does not bound decoded bytes: one large nested value can exceed the budget. The author's explanation that HostAllocator alone is insufficient is valid, but leaves this operational risk unresolved. Add a budget check based on a safe decoded-size bound before materialization, or fallible allocation support covering the actual decoders.
Tests
  • ⚠️ Missing a focused low-memory regression for a large, highly compressed nested value. Measure peak allocation and prove rejection before allocating its full decoded size. The concern is established by allocation-path tracing; the peak-memory effect was not reproduced locally. No local build or runtime tests were run.
Final Verdict

Status: ⚠️ Request changes. Provide a budget-enforcing decoding boundary and the focused regression above. The existing thread needs no further reply or reopening.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels Aug 1, 2026
# Conflicts:
#	src/Formats/registerFormats.cpp
Address the AI review of #112950 and the `arm_tidy` build failure.

- `VortexBlockInputFormat::prepareReader` pruned the scanned columns to the
  exact top-level names of the requested header. A header column addressing a
  subcolumn, such as `t.a`, dropped the parent field `t` from the scan, and
  `ArrowColumnToCHColumn` then silently filled the column with default values.
  Keep `Nested::extractTableName` of every header column, the same way the
  `ArrowIPC` reader does. Covered by a new case in `04669_vortex_format`.

- `VortexBlockOutputFormat` did not override `resetFormatterImpl`, so a
  formatter reused by `MessageQueueSink` kept the finished Rust writer and the
  next message failed with `writer is already finished`. Free the writer and
  the conversion state on reset, like `Arrow`, `ORC`, and `Parquet` do.

- Value-initialize the `ArrowArray` and `ArrowSchema` C structures, fixing the
  `cppcoreguidelines-pro-type-member-init` errors in `Build (arm_tidy)`:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112950&sha=d4debff97a3088dde960cc32e1d0ce8af1c997b6&name_0=PR&name_1=Build%20%28arm_tidy%29
alexey-milovidov and others added 2 commits August 4, 2026 02:53
The MSan build failed to link unit_tests_dbms with relocation
R_X86_64_PC32 out of range errors: the MSan-instrumented Vortex Rust
library (with origin tracking) adds so much code that the binary
exceeds the 2 GiB range of the small code model. Disable Vortex under
MSan, following the precedent of wasmtime and delta-kernel-rs.

Consequently, exclude Vortex from the format enumeration in
02187_async_inserts_all_formats (its availability now varies by build,
so it cannot appear in the static reference; this also fixes the
reference mismatch this PR introduced there), and tag
04669_vortex_format with no-msan.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112950&sha=645a6771def9e396863d6401ca67230109b220dd

Co-Authored-By: Claude Fable 5 <[email protected]>
Master removed the legacy Docusaurus tree (docs/en), which conflicted with
the Vortex doc added there. The Vortex format page is ported to the Mintlify
tree: docs/reference/formats/Vortex.mdx (body matches the embedded
documentation registered via FormatFactory::setDocumentation), a row in
docs/reference/formats/index.mdx, and an entry in docs/reference/navigation.json.
@alexey-milovidov alexey-milovidov added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Aug 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the two Hung check failed, possible deadlock found stress-test failures and provide a fix in a separate PR (if one is already in progress, link it here):

  • Stress test (amd_msan): a fuzzer query is stuck in ActionsDAG::evaluatePartialResult / ActionsDAG::updateHeader while building an ExpressionStep in the planner — uninterruptible CPU-bound expression evaluation, possibly the same class as Uninterruptible CPU-bound function evaluation over a large value #112203.
  • Stress test (arm_release): a fuzzer query over merge(REGEXP('.+'), '.*') joined to a constant subquery is stuck in ReadFromMerge::filterTablesAndCreateChildrenPlans during QueryPlan::optimize (optimizePrimaryKeyConditionAndLimit → applyFilters), single-threaded, tens of seconds in plan optimization over the stress database's many tables.

Both hangs are unrelated to this PR: the hung queries do not involve the Vortex format at all, and the amd_msan binary does not even include it (Vortex is disabled under MSan).

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Both hangs are the same defect, and it is not the one the amd_msan half is described as. Neither is caused by this PR.

amd_msan is not ActionsDAG::evaluatePartialResult. The hung query is

SELECT * FROM one AS A INNER JOIN system.one AS one ON A.dummy = one.dummy
             INNER JOIN merge('^') AS two ON A.dummy = two.dummy

and its stack (hung_check.log, thread 5193) is:

AnalysisTableExpressionData::ensureColumnMembershipSetsArePopulated
IdentifierResolver::tryResolveIdentifierFromTableExpression
... QueryAnalysisPass::run
ReadFromMerge::getModifiedQueryInfo
ReadFromMerge::createChildrenPlans          StorageMerge.cpp:849
ReadFromMerge::filterTablesAndCreateChildrenPlans
ReadFromMerge::applyFilters                 StorageMerge.cpp:1790
QueryPlanOptimizations::optimizePrimaryKeyConditionAndLimit
QueryPlan::optimize

The evaluatePartialResult / updateHeader / ExpressionStep frames do appear in that artifact, but in the Top messages not matching their format strings section, as the stack of a completed sleepEachRow exception (Code: 44. The argument of function sleepEachRow must be constant) raised on an unrelated HTTPHandler query. The reason they look like the hung query is that the CI report only renders the last 32 KiB of hung_check.log, and the hung row lives in the excluded head: 84% of the amd_msan log and 91% of the arm_release log are outside that window, and ReadFromMerge appears 0 times inside it. Reading the artifact directly instead of the report body is what separates the two.

So both rows are ReadFromMerge child-plan construction under QueryPlan::optimize, differing only in the leaf: amd_msan in ensureColumnMembershipSetsArePopulated, arm_release in FunctionFactory::tryGet under resolveFunction.

Cost vs interruptibility are two separate things, and only the first has a fix.

Cost: your #113140 is the right fix for it, and the amd_msan leaf is precisely the function its comment names as being rebuilt once per identifier. That accounts for the wall time.

Interruptibility: #113140 does not address it. Its 87 added lines contain no cancellation check (0 occurrences of isCancelled, checkTimeLimit, QueryStatus, ProcessList), and StorageMerge.cpp has none anywhere in its 2046 lines. Both rows show is_cancelled: 1 with max_execution_time = 10, yet ran 1757 s and 3994 s single-threaded. That is the gap: cancellation is observed between pipeline steps, and ReadFromMerge::applyFilters builds every child plan inside one optimizePrimaryKeyConditionAndLimit call with no checkpoint, so a cancelled query cannot leave. #113140 shrinks the window a lot but does not close it; a wide enough merge still exceeds any timeout uninterruptibly.

The phase counters confirm the hang is in the still-running phase rather than anything already finished: recorded phases sum to 6.6 s of 1757 s (amd_msan) and 29.4 s of 3994 s (arm_release), because QueryPlanOptimizeMicroseconds is only committed when its scope exits.

I am authoring the cancellation-checkpoint fix and will link the PR here when it opens. #112203 is a different mechanism (uninterruptible evaluation of one large value); this is uninterruptible plan construction, closer to #113003 and covered in general by #47272.

Unrelated to this PR, confirmed rather than assumed. Your MSan argument holds: rust/workspace/CMakeLists.txt in this PR sets ENABLE_VORTEX OFF when SANITIZE STREQUAL "memory", so the amd_msan binary cannot contain the format. For arm_release the diff touches 23 files, none of them under Storages/, Analyzer/, Planner/ or QueryPlan/, so it cannot appear on this stack; neither hung query references the format, and both shapes are recorded on other PRs.

The `Vortex` output format inherited the generic `CHColumnToArrowColumn`
mapping that serializes `DateTime` as plain Arrow `UINT32`, so the
temporal type was silently lost on round-trip: `DESC file(...)` of a
written file inferred `UInt32`.

Add an `output_datetime_as_timestamp` setting to `CHColumnToArrowColumn`
(following the existing `output_date_as_uint16` pattern) that exports
`DateTime` as Arrow `TIMESTAMP` with second precision and the column's
time zone, and enable it for `Vortex`. Such files are read back as
`DateTime64(0)`. `Arrow` and `Parquet` keep the old behavior.

Update the format documentation accordingly and add a test with
schema-inferred readback of `DateTime`, including `Nullable` and
`Array` nesting.

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

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Fixing PR for the ReadFromMerge::createChildrenPlans plan-time cancellation hung check on my
CI finish ledger: #113415 (external, open).

I had a fix for this on a local branch, but @alexey-milovidov opened #113415 with the identical
guard at the identical call site, so I dropped mine rather than open a duplicate. My analysis and
the one coverage gap I measured are in
#113415 (comment).

alexey-milovidov and others added 2 commits August 6, 2026 07:41
…ex` format

Vortex has no type for IP addresses, so `IPv4` columns are written through the
generic Arrow `UINT32` carrier (the same as in `Parquet` and `Arrow`), and schema
inference reads them back as `UInt32`. Document this explicitly, including the
explicit-schema way to read the column back as `IPv4`, and add a stateless test
covering inference, both round trips, and the documented `IPv6` write rejection.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for the reds on a56a056dafe (all unrelated to this PR; origin/master has been merged in and CI restarted on e5634f18090):

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

The AST fuzzer STID 2270-2caa failure on a56a056dafe is covered by a fix I already have open: #113469

I confirmed that on your exact query rather than by inference. A pre-fix binary reproduces your log line byte for byte (Expected 0, found 1, empty Header:, Chunk: Nullable(size = 2, UInt8(size = 2), UInt8(size = 2)), aborting in RemoteSource::prepare); the branch head returns the 8 correct rows and no error. Both arms asserted by build id.

Mechanism: cume_dist() OVER () references no column of the table expression, and defaultValueOfArgumentType(k) is constant-folded, so the outer query reads nothing from the shard. prepareBuildQueryPlanForTableExpression then synthesizes one column purely to learn the row count, and the window function is deferred to the initiator along with the projection that would have consumed that column, so nothing keeps it and it is pruned. The initiator's mergeable header ends up empty while the shard still streams the surviving Nullable(UInt8) constant, hence 1 column where 0 are expected.

The crash is the visible half. When no constant survives there is no error and rows are silently dropped instead: over two shards of 1000 rows, SELECT count(*) OVER () FROM remote(...) returned 1000 rows pre-fix, and 0 with prefer_localhost_replica = 0, against 2000 correct. The locally-read shard survives, every remote one is lost.

SAMPLE, QUALIFY, the four shards, and remoteSecure rather than remote are all incidental: dropping each of them still aborts pre-fix. What is load-bearing is more than one shard plus a window function referencing no column of the table. count(c0) OVER (), a single shard, and enable_analyzer = 0 are all clean pre-fix, so the fix is scoped to the analyzer path.

113469 covers this carrier; I am not claiming it clears the whole message class. Agreed that 96656 and 103695 are the same family with different stack IDs. One caveat on keying: within this family a single STID pools more than one query shape, so the shape identifies a carrier more reliably than the STID does.

Comment thread rust/workspace/vortex/src/lib.rs Resolved
alexey-milovidov and others added 3 commits October 17, 2026 00:57
# Conflicts:
#	src/Common/ProfileEvents.cpp
#	src/Storages/ObjectStorage/DataLakes/Iceberg/Compaction.cpp
…e row

`Set::execute` converts the column to the type of the set keys, and a comparison
with a `FixedString` constant pads the other side with zeros. Neither conversion
is injective, so the filter pushed into the Vortex scan, which converts the
constant to the column type and compares raw values, dropped rows that the final
filter would keep: a `String` `'a'` against a `FixedString(2)` key, a `UInt8` `2`
against a `Bool` key, a `DateTime64` at noon against a `Date` key, and `s =
toFixedString('a', 2)`.

`convertIn` now pushes only keys of the column's own type, and integer keys for
an integer column (converted exactly or not at all). `Bool` is checked apart
because it `equals` `UInt8`. `convertComparison` does not push `FixedString`
constants, nor non-string constants against a `String` column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The list of values `defer_drop` keeps for `drop_deferred` was process-wide, so
the exit guard of an FFI call of one query could free the tasks and buffers that
another query's teardown deferred. ClickHouse accounts the memory a thread frees
to the query it runs, so the wrong query was credited. The list is thread-local
now, and `vortex_ffi_scan_release`, which can wake a task of a runtime that is
gone, drops what it deferred on exit as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 18, 2026 14:59
# Conflicts:
#	src/Common/ProfileEvents.cpp
With `max_parsing_threads = 1` the `Vortex` reader runs its tasks inside
`read`. A `Parquet` reader that initialized the shared resources of an
Iceberg snapshot first still sets up a download pool, and the `Vortex`
reader scheduled its reads there. Once a pool thread took a read out of
the queue, `read` saw both queues empty and threw
`Deadlock in the Vortex reader (single-threaded)` while the read was
still in flight. `hasSeparateIORunner` is now false without a parsing
pool, so all tasks stay inline.

The new test reproduces the exception reliably without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Writing the 1M-row file dominated the test, which ran at about 175 s in
`Stateless tests (amd_tsan, flaky check)` and sometimes went over the
180 s limit. 400k rows still make 8 splits.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112950&sha=13ce1af69edab73b8ed369953b362983691c84b6&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
PR: #112950

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 21, 2026 03:00
…AzureQueue`

The queue sources call `StorageObjectStorageSource::createReader` without a
`FormatFilterInfo`, so nothing set `need_row_numbers`, and the Parquet reader
stopped attaching `ChunkInfoRowNumbers`: `_row_number` was read as NULL.
Ask for row numbers at the shared `createReader` boundary whenever a
row-dependent virtual column is requested, as is already done for files with
attached deletes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…conversions

A file `String` column read as `Nullable(UInt64)` turns a malformed string
into NULL after the scan, while a pushed `IS NULL` / `isNotNull` sees the
original non-null string and dropped the row. Push a null check only when the
types match, the header is `String`, or an integer is read as another integer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 23, 2026 00:48
…n builds

`oneshot` 0.2 gives `.await` an `AsyncReceiver` future rather than `Receiver`. Its `poll`
reads the payload behind the same standalone `fence(Acquire)` that `rustc` does not report to
ThreadSanitizer, so the existing `Receiver*::poll` entry no longer matched the inlined
`take_message`. The flaky check failed `05331_vortex_lazy_materialization_object_storage`,
`04821_vortex_filter_pushdown` and `04927_vortex_parallel_read` on it.

https://s3.amazonaws.com/clickhouse-test-reports/PRs/112950/9bc143e56853b7b122d17053abc6fa996ff22a93/pr/result_stateless_tests_amd_tsan_flaky_check.json
#112950

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…arses them

`tryConvertFieldToTypeExact` parsed a string constant with default `FormatSettings`, while
`FunctionComparison` uses `cast_string_to_date_time_mode`: `best_effort` reads `'20200101'`
as 2020-01-01, the default parsing as Unix seconds. The pushed literal then dropped rows that
ClickHouse would have matched. A string constant compared with a column of another type is now
converted with the `ComparisonParams`-equivalent settings derived from the query context, and
not pushed when that conversion fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Common/ProfileEvents.cpp
…oral columns

`'20200101'` compared with a `DateTime` / `DateTime64` column has to match the same rows with
and without `input_format_vortex_filter_push_down`, under both `cast_string_to_date_time_mode`
values.

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

fn make_session(runtime: &Arc<HostRuntime>) -> VortexSession {
VortexSession::default().with_handle(runtime.handle())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Enforce the query memory budget during Rust decoding

This session retains Vortex's default allocator, and CallbackReader::read_at likewise allocates its buffer directly with ByteBufferMut::with_capacity_aligned. Those Rust system allocations reach ClickHouse's C allocation wrappers, which call Memory::trackMemoryFromC → CurrentMemoryTracker::allocNoThrow: they charge memory but do not reject an allocation that exceeds max_memory_usage. No throwing budget check is installed before execute_arrow materializes the decoded batch.

Consequently, a single row holding a large, compressible Array(UInt64) can allocate far beyond the query budget before onChunk reaches the first throwing ClickHouse-column allocation. Limiting the number of splits and the compressed read size does not bound the decoded allocation; an eventual MEMORY_LIMIT_EXCEEDED happens after that memory has already been obtained. The sibling ArrowMemoryPool::Allocate explicitly uses a throwing ClickHouse allocator to avoid this problem.

Please provide a budget-enforcing allocation/check boundary for Rust read/decode buffers (Vortex exposes a session HostAllocator) and a focused low-memory-limit regression demonstrating that a large compressed split fails before allocating its decoded size. This concern follows from the allocation paths; the peak-memory effect has not been reproduced locally.

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.

🕵 Not changed in this PR, because a session HostAllocator would not give the bound you describe. In vortex-array 0.84.0, HostAllocator is only consulted at a handful of call sites (executor.rs, chunked canonicalization, variant_get, open.rs). The decode paths that would blow up on a compressible Array(UInt64) (builders, BufferMut::with_capacity, the run-end/constant/FSST decompressors) allocate through the global Rust allocator. That allocator cannot report an over-budget allocation either: a C++ exception must not unwind through Rust frames, and Rust aborts the process on a failed allocation, so returning null from malloc on the limit would turn a MEMORY_LIMIT_EXCEEDED into a server abort.

The allocations do run on ClickHouse threads (the runnables are driven by our task queues), so they are charged to the query's MemoryTracker, and the query fails at the next throwing ClickHouse allocation. The overshoot is bounded by what one split decodes. A real budget-enforcing boundary needs fallible allocation in the decoders upstream, or a per-split decoded-size estimate checked before execute_arrow. I'd rather do either as a follow-up than ship a partial HostAllocator that suggests a bound it doesn't provide. Leaving this thread open for that.

alexey-milovidov and others added 2 commits October 24, 2026 18:03
… pushed into a Vortex scan

Vortex compares floating-point values in their total order and bitwise:
`-0.0` is less than `+0.0` and `NaN` is greater (or, negative, less) than
every number. ClickHouse compares as IEEE 754 does. A pushed `f = 0` therefore
dropped a `-0.0` row, and `NOT (f > 1)` dropped a positive `NaN` row, before the
final filter could see them.

Now an equality with zero matches both zeros, a range bound at zero is taken
on the side that includes both, and a range comparison - which still lets
`NaN` through, a widening - is not pushed where the condition has to be exact,
under `NOT`. A zero key of `IN` is matched as both zeros, and not pushed
when the set is negated or the position has to be exact.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112950&sha=a96507265ec054a54f037bb5dc901b371a7b9e24&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29 (AddressSanitizer: heap-use-after-free on the logger in DatabaseReplicatedDDLWorker::tryEnqueueAndExecuteEntry, reached from RefreshTask::executeRefresh → StorageMaterializedView::prepareRefresh, STID 5629-5423) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other red jobs on this PR don't touch the Vortex code either:

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #117399 (mine, open, CI green on c46bb15).

The worker was freed by SYSTEM RESTORE DATABASE REPLICA (restoreDatabaseInKeeper sets ddl_worker = nullptr, DatabaseReplicated.cpp:2481) while the refresh thread was still inside tryEnqueueAndExecuteEntry. The refresh gets there through InterpreterCreateQuery::createTable, which holds the table DDLGuard (a shared lock on the database DDL mutex) until the entry is executed. #117399 makes the restore take the exclusive database DDL guard first, so it waits for that entry, and it turns ddl_worker into a shared_ptr that tryEnqueueReplicatedDDL keeps for the whole call.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed 9f8f660. It builds, and the 24 Vortex stateless tests that run on clickhouse-local pass on the merged tree. 05331 needs MinIO, so CI will check it.

The red jobs on 1239859 are unrelated to Vortex:

  • Upgrade check (amd_release): use_query_condition_cache_for_time_conditions was missing from the settings changes history. The merged master has the setting with default false again, so the merge should clear this.
  • Stateless tests (arm_asan_ubsan, azure, parallel): 05355_top_k_dynamic_filter_single_sort_column_ties is flaky. It was made non-parallel in Make 05355_top_k_dynamic_filter_single_sort_column_ties non-parallel #127694, which is now merged into this branch.
  • Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel), "Some queries hung": the hung query was select_04117_test_* from 04117_detach_database_kill_query running under parallel replicas. Mark a query as cancelled in the process list when its TCP client cancels it #127149 handles it.
  • Performance Comparison (arm_release, master_head, 6/6): parallel_index reads MergeTree and never touches the Vortex code. The runner again reported under-utilized CPU and an almost-full disk.

@groeneai, thanks for linking #117399 for the BuzzHouse use-after-free.

The five open review threads already have replies. Each one is waiting on a follow-up PR or a maintainer decision: Vortex extension dtypes, bulk string copy for view arrays, the MSan size limit / C++ rewrite, exact vs widened filter pushdown, and a memory-budget boundary for Rust decoding.

This branch was successfully deployed

1 active deployment
staging - docs — 9f8f660b Deployed Oct 26, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature request] please support read and write vortex columnar file format

5 participants