Skip to content

Fix exception when querying a Hive table without a WHERE clause - #108094

Merged
alexey-milovidov merged 18 commits into
masterfrom
fix-hive-null-filter-crash
Jul 7, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
fix-hive-null-filter-crash

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Querying a Hive table without a WHERE clause (e.g. SELECT * FROM hive_table) caused a null pointer dereference in StorageHive.

The read path passes nullptr for filter_actions_dag when the query has no filter, but StorageHive::collectHiveFilesFromPartition and StorageHive::getHiveFileIfNeeded unconditionally dereferenced it via filter_actions_dag->getOutputs().front() inside their partition- and file-level pruning blocks. The default prune_level is Max, so both blocks always run, and the query terminated the server with a segmentation fault. Adding a WHERE clause avoided the issue only because that made filter_actions_dag non-null.

The fix skips the pruning blocks when there is no filter: without a predicate there is nothing to prune by, so all files of the partition are collected.

The set of splits to skip (Parquet row groups / ORC stripes) is computed from the query filter, but it was stored on the IHiveFile objects served from the process-wide hive_files_cache. Because those objects are shared between concurrent queries, a filtered read could leave a stale split-skip set on a cached file, so a later SELECT * — or a concurrent query with a different filter — would silently drop the row groups or stripes excluded by the earlier predicate (and the unsynchronized std::unordered_set was also a data race). The split-skip set is now carried per query (HiveFileWithSkipSplits) instead of being stored on the cached file, so unfiltered reads always return all splits and concurrent queries do not interfere with each other's pruning.

A regression test (tests/integration/test_hive_query) reads a partitioned Hive (Parquet) table without a WHERE clause and verifies that a filtered read followed by an unfiltered read of the same table still returns all rows.

A second test (test_orc_split_skip_state_is_query_local) covers the per-query split-skip set directly: a partitioned ORC table has two files with disjoint score ranges, and with enable_orc_stripe_minmax_index = 1 a filter on the non-partition score column prunes one file's stripe (a non-empty split-skip set). Since the ORC reader honours orc.skip_stripes (unlike Parquet's skip_row_groups), a subsequent unfiltered read of the same cached table must still return all rows.

Closes: #102636

Changelog category (leave one):

  • Bug Fix

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

Fixed a crash (null pointer dereference) when querying a Hive table without a WHERE clause, e.g. SELECT * FROM hive_table.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.630 (included in 26.7 and later)

`StorageHive` dereferenced `filter_actions_dag` while collecting files even
when the query had no filter. The read path passes `nullptr` for
`filter_actions_dag` when there is no `WHERE` clause, but
`collectHiveFilesFromPartition` and `getHiveFileIfNeeded` unconditionally
called `filter_actions_dag->getOutputs().front()` inside their partition- and
file-level pruning blocks, leading to a null pointer dereference.

Skip the pruning blocks when there is no filter: without a predicate there is
nothing to prune by, so all files of the partition are collected.

Closes: #102636

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1dde26b]

Summary: ✅


AI Review

Summary

This PR fixes the no-filter StorageHive dereference, moves split-pruning state off the shared IHiveFile, and keys hive_files_cache by the table-specific cached-file layout and minmax settings so incompatible Hive table definitions no longer reuse the same cached file metadata. I re-read the current Hive implementation at head, the resolved review threads, and the added integration coverage; with the merged master fix for the unpartitioned-path lifetime issue and the focused bugfix integration checks now green, I did not find a remaining correctness issue in the diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 22, 2026
Comment thread src/Storages/Hive/StorageHive.cpp Resolved
`StorageHive::getHiveFileIfNeeded` serves `IHiveFile` objects from a
process-wide `hive_files_cache`. A filtered query stores a split-skip set on
the cached file via `setSkipSplits`, and `updateFormatSettings` later copies it
into `orc.skip_stripes` / `parquet.skip_row_groups`. Now that the file-level
pruning block is skipped for unfiltered reads, that stale split-skip set would
persist on the cached file and make a subsequent `SELECT *` silently drop the
row groups or stripes excluded by the earlier predicate, turning the original
crash into wrong results.

Clear the split-skip set when there is no filter, so an unfiltered read always
returns all splits.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Jun 24, 2026
Comment thread src/Storages/Hive/StorageHive.cpp Resolved
alexey-milovidov and others added 5 commits June 29, 2026 16:56
Revives a minimal `test_hive_query` integration test focused on the crash
fixed by this pull request: `SELECT` from a partitioned `Hive` (Parquet) table
without a `WHERE` clause used to pass a null filter to `StorageHive`, which
dereferenced it and terminated the server.

The test also checks that a filtered read (which exercises partition/split
pruning) followed by an unfiltered read of the same table still returns all
rows, so stale pruning state is not served from the cached hive file.

Closes: #102636

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Make `prepare_hive_data.sh` fail fast (`set -e`) and retry the data
preparation while the Hive metastore / HiveServer2 is still starting up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The set of splits to skip (Parquet row groups / ORC stripes) is computed from
the query filter, but it was stored on the `IHiveFile` objects served from the
process-wide `hive_files_cache`. Those objects are shared between concurrent
queries, so a filtered read could leave a stale split-skip set on a cached file
and a later `SELECT *` (or a concurrent query with a different filter) would
silently drop the row groups or stripes excluded by the earlier predicate. The
unsynchronized `std::unordered_set` was also a data race.

Carry the skip set per query instead: `getHiveFileIfNeeded` now returns the
file together with its skip set (`HiveFileWithSkipSplits`), the collection
functions propagate it, and the reader copies it into `orc.skip_stripes` /
`parquet.skip_row_groups` from the per-query value. Nothing query-specific is
written to the cached file anymore, which also removes the need to clear the
set for unfiltered reads (an empty per-query set already means "read all
splits").

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits June 30, 2026 04:13
The integration test added in this PR covers the no-`WHERE` null-filter crash,
but it does not exercise the per-query split-skip set introduced by the later
commits: its filter is on the partition key `day` (satisfied by partition
pruning), Hive split-level minmax indexes default to off, and the Parquet
reader does not consume `skip_row_groups`. The test would still pass if the
query-local `skip_splits` plumbing were removed.

Add an ORC-based regression (`test_orc_split_skip_state_is_query_local`). The
new `test.demo_orc` table has two ORC files in one partition with disjoint
`score` ranges; with `enable_orc_stripe_minmax_index = 1` a filter on the
non-partition `score` column prunes one file's stripe, producing a non-empty
per-query split-skip set. The ORC reader honours `orc.skip_stripes`, so a
subsequent unfiltered read of the same (process-wide cached) table must still
return all rows - before the fix the stale skip set on the cached file dropped
the pruned stripe.

Also wrap each `hive` invocation in the data-preparation script in a `timeout`
so a stuck `hive` CLI (the metastore can still be starting up) aborts the
script and lets the existing retry loop run again, instead of consuming the
whole test budget - the cause of the occasional setup timeout in CI.

Addresses the AI review on #108094

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

Copy link
Copy Markdown
Member Author

Pushed 069cade0a90 (merged into 7327dcdabf7 with the latest master):

  • Addresses the AI review — added test_orc_split_skip_state_is_query_local, a focused regression for the per-query split-skip set. test.demo_orc has two ORC files in one partition with disjoint score ranges; with enable_orc_stripe_minmax_index = 1 a filter on the non-partition score column prunes one file's stripe, and the following unfiltered read of the same process-wide-cached table must still return all rows (before the fix the stale skip set dropped the pruned stripe). This exercises the skip_splits plumbing that the existing partition-key Parquet test did not. Thread resolved.
  • Hardens the flaky setup timeout — each hive invocation in prepare_hive_data.sh is now wrapped in timeout, so a stuck hive CLI (metastore still starting) aborts the script and lets the existing retry loop run again instead of consuming the whole pytest budget. test_select_without_where passed 7/8 in the last run; the single failure was this setup timeout.

The remaining CI reds are unrelated, known flakes: the amd_tsan Hung check is the chronic #107941, and the arm_tsan stress SOCKET_TIMEOUT is a stress-job flake (stress tests do not set up a Hive metastore, so they do not exercise the changed StorageHive code path).

alexey-milovidov and others added 2 commits June 30, 2026 16:53
`test_orc_split_skip_state_is_query_local` set only
`enable_orc_stripe_minmax_index = 1`, but `enable_orc_file_minmax_index`
defaults to `true`, so a `score < 5` filter discarded the `[10, 11]` file at
file-pruning time (`getHiveFileIfNeeded` returns early once `useFileMinMaxIndex`
rejects the file) before stripe pruning ran. The kept `[1, 2]` file then had no
skipped stripe, so the query never built the non-empty per-query `skip_splits`
set the test is meant to cover - it would have passed even without the fix.

Disable file-level pruning (`enable_orc_file_minmax_index = 0`) so the
`[10, 11]` file survives to stripe-level pruning, where its stripe is added to
`skip_splits` - the non-empty query-local state whose staleness on the shared
cached file the fix prevents.

Addresses the AI review on #108094

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`prepare_hive_data.sh` ran its first statement under a 150s `timeout`; while
the Hive metastore was still starting the `hive` CLI blocked on the connection
and was killed (exit code 124), so only a handful of attempts fit into the
integration-test budget before pytest's 900s timeout fired. This timed out
`Integration tests (arm_binary, distributed plan, 3/4)` for both
test_select_without_where and test_orc_split_skip_state_is_query_local, even
though every other shard passed.

Probe the metastore with a short-timeout trivial query and poll instead: a
stuck probe is killed quickly and retried, while a successful one returns fast
once the metastore is up, fitting many more connection attempts into the budget.
The actual DDL / data load still runs with the generous timeout. If `timeout` is
unavailable the probe is skipped, preserving the previous behaviour.

#108094

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

Copy link
Copy Markdown
Member Author

Pushed 7327dcdabf7..973b2001826:

  • Addresses the AI review (Request changes) — 9f951a7: test_orc_split_skip_state_is_query_local now also sets enable_orc_file_minmax_index = 0. As the review noted, with file-level minmax on (the default) the score < 5 filter discarded the [10, 11] file at file-pruning time (getHiveFileIfNeeded returns early once useFileMinMaxIndex rejects it) before stripe pruning ran, so the per-query skip_splits set stayed empty and the test passed regardless of the fix. With file-level pruning off, the [10, 11] file reaches stripe-level pruning and its stripe lands in skip_splits — the non-empty query-local state the test must exercise. Thread resolved.

  • Hardens the integration setup against the metastore-startup timeout — 973b200: the Integration tests (arm_binary, distributed plan, 3/4) shard timed out both new tests in the started_cluster fixture. The logs show every prepare_hive_data.sh attempt was killed (exit code 124) on its very first statement timeout 150 hive -e 'create database ...' — the hive CLI blocked on the metastore connection for the full 150s because the Hive metastore never became reachable within the 900s pytest budget on that (loaded) runner, so only ~5 such coarse hangs fit. The script now first probes the metastore with a short-timeout trivial query in a poll loop (a stuck probe is killed quickly and retried, a successful one returns fast), fitting far more connection attempts into the budget; the real DDL / data load keeps the generous timeout, and the probe is skipped when timeout is unavailable. This run's metastore simply did not come up within 900s — an environment event — so a rerun is the primary remedy; the change reduces the chance of recurrence on slow runners. Every other integration shard, including the aarch64 bugfix-validation integration job, passed.

The remaining CI reds are unrelated, known flakes: the amd_tsan Hung check is the chronic #107941 (the dumped stacks are AST-fuzzer QueryTreePassManager::run / executeASTFuzzerQueries / TCPHandler::runImpl, with no Hive frames — and stress tests do not set up a Hive metastore, so they never exercise the changed StorageHive path), and the arm_tsan stress job errored with a SOCKET_TIMEOUT (0 tests run).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked at head `973b2001826` — no new code needed.

  • AI review is now ✅ Approve (updated after the previous push), confirming the enable_orc_file_minmax_index = 0 fix to test_orc_split_skip_state_is_query_local resolved its earlier "Request changes". No unresolved review threads.
  • The two remaining CI reds are unrelated, confirmed-open flakes — neither exercises StorageHive (the changed code), and this PR touches no query-planning or threading code:
  • Not re-merging master: merge-base is from earlier today (< 1 day) and both reds fire on master too, so a merge would not change them.

The full PR workflow run is still in progress, so the two flaky jobs cannot be rerun yet; they should be rerun once the run completes. The PR is MERGEABLE and ready for a maintainer merge.

The `Integration tests (arm_binary, distributed plan, 4/4)` shard timed out
both new tests in the `started_cluster` fixture: pytest-timeout fired after
the default 900s while the fixture was still polling the Hive metastore in
`prepare_hive_data.sh` (the traceback ends inside `started_cluster`, before
any assertion ran). The metastore came up in 7/8 of the previous attempts,
so the bottleneck is the heavy Hadoop + Hive metastore + HiveServer2 JVM
stack occasionally needing more than 900s to become reachable on a loaded
(cpus=3) runner, not the test logic.

Give the whole module a more generous budget with a module-level
`pytest.mark.timeout(1800)`, matching other heavy external-service tests
(`test_storage_rabbitmq`, `test_backup_restore_new`). pytest-timeout applies
to fixture setup, so this directly extends the time available for the
metastore-readiness poll, letting a slow-but-eventually-ready metastore
finish instead of flaking the tests.

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

Copy link
Copy Markdown
Member Author

Pushed de2d4327f79:

  • Fixes the only PR-caused red — Integration tests (arm_binary, distributed plan, 4/4) timed out both new tests in the started_cluster fixture: pytest-timeout fired after the default 900s while the fixture was still polling the Hive metastore in prepare_hive_data.sh (the traceback ends inside started_cluster, before any assertion ran). The metastore came up in 7/8 of the previous attempts, so the bottleneck is the heavy Hadoop + Hive metastore + HiveServer2 JVM stack occasionally needing more than 900s to become reachable on a loaded (cpus=3) runner — not the test logic. Added a module-level pytest.mark.timeout(1800) (matching other heavy external-service tests such as test_storage_rabbitmq and test_backup_restore_new). pytest-timeout covers fixture setup, so this directly extends the budget for the metastore-readiness poll, letting a slow-but-eventually-ready metastore finish instead of flaking the tests.

The remaining CI reds are unrelated, confirmed flakes — this PR touches only StorageHive, no query-planning, threading, or MySQL/PostgreSQL code:

  • Stress test (arm_tsan) Hung check → Hung check failed, possible deadlock found #107941 (OPEN; dumped stacks are AST-fuzzer executeASTFuzzerQueries / TCPHandler::runImpl, no Hive frames; stress configs set up no Hive metastore, so they never exercise the changed path).
  • AST fuzzer (amd_msan) Block structure mismatch in A stream (STID 0993-27f0, in UnionStep::updateOutputHeader) → Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) #108142 (OPEN; exact STID match).
  • Upgrade check (amd_release) Error message in clickhouse-server.log — the flagged lines are leftover DatabaseMySQL / DatabasePostgreSQL test databases retrying connections to 192.0.2.1 (a TEST-NET-1 reserved, always-unreachable address) after the restart (mysqlxx::ConnectionFailed / ALL_CONNECTION_TRIES_FAILED / PostgreSQL timeout expired), which cannot be caused by a StorageHive change. This exact failure is a chronic, master-wide flake: CIDB shows it on 137 distinct PRs in the last 30 days.

The AI review is ✅ Approve and there are no unresolved review threads. The new commit re-triggers the full workflow; the metastore-timeout fix should clear the integration-test red, and the three flaky jobs above should be rerun once the run completes.

The `Integration tests (arm_binary, distributed plan, 4/4)` shard timed out both
new tests in the `started_cluster` fixture. The Hive test cluster runs the
`lgboustc/hive_test:v2.0` image, whose Docker Hub manifest is published for
`amd64` only, so on ARM runners it can only start under (very slow) QEMU
emulation. Emulating the full Hadoop + Hive metastore + HiveServer2 JVM stack is
so slow that the metastore never becomes reachable within the test budget, so no
per-test timeout bump can make the ARM shard pass. Every `amd64` integration
shard runs the tests fine.

Skip the module on ARM via `is_arm`, matching the other tests that depend on
amd64-only images (e.g. `test_mysql57_database_engine`). The generous
`pytest.mark.timeout(1800)` is kept for the `amd64` path, where the metastore
does eventually come up on a loaded runner.

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

Copy link
Copy Markdown
Member Author

Pushed 9665364855e: fixes the only PR-caused red — Integration tests (arm_binary, distributed plan, 4/4), which timed out both new tests in the started_cluster fixture even after the pytest.mark.timeout(1800) bump (the traceback ends at 1800.0s from pytest-timeout while still polling the metastore in prepare_hive_data.sh).

Root cause (not a slow-runner flake). The Hive test cluster runs the lgboustc/hive_test:v2.0 image (docker_compose_hive.yml), and its Docker Hub manifest is a single-arch amd64 image (architecture: amd64, built 2022-06-21 — no arm64/aarch64 variant). On an ARM runner it can therefore only start under QEMU emulation, and emulating the full Hadoop + Hive metastore + HiveServer2 JVM stack is slow enough that the metastore never becomes reachable within the budget. That is why none of the timeout-hardening rounds could make the ARM shard pass — the problem is architectural, not a matter of budget. The evidence is unambiguous: every amd64 integration shard (amd_asan_ubsan, amd_llvm_coverage, amd_tsan, amd_msan) is green, and it has always been the ARM distributed plan shard (previously 3/4, now 4/4) that times out.

Fix. Skip the module on ARM via is_arm, exactly matching the other tests that depend on amd64-only images (e.g. test_mysql57_database_engine, test_storage_kerberized_kafka). The generous pytest.mark.timeout(1800) is kept for the amd64 path, where the metastore does eventually come up on a loaded (cpus=3) runner. This keeps full coverage of the StorageHive fix on amd64 (including the amd64 bugfix-validation job) while making the ARM shard deterministic.

No re-merge with master: the merge-base is < 1 day old and master touches none of the PR files (StorageHive.{cpp,h}, HiveFile.h, the test, or the Hive compose file). The AI review is ✅ Approve and there are no unresolved review threads; the new commit re-triggers the workflow.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked at head 9665364855e.

The is_arm() skip is confirmed working. All four Integration tests (arm_binary, distributed plan, 1-4/4) shards are now green, and both Bugfix validation (integration tests, amd64/aarch64) jobs pass — the amd64 job still runs the reproducer on the old binary and catches the segfault, so the bug-fix validation contract is satisfied. The ARM integration timeout was the only PR-caused red across the previous runs, and it is resolved (the lgboustc/hive_test:v2.0 compose image is amd64-only, so the test is skipped on ARM instead of hanging under QEMU).

AI Review is ✅ Approve on this head, and there are 0 unresolved review threads.

The remaining reds are pre-existing, transient, and unrelated to this PR (which touches only src/Storages/Hive/ plus the new integration test):

  • Stateless tests (arm_binary, parallel) — 03562_parallel_replicas_remote_with_cluster and 02875_parallel_replicas_cluster_all_replicas each failed once with UNEXPECTED_PACKET_FROM_SERVER (expected TablesStatusResponse, got ProfileInfo), a parallel-replicas connection-protocol timing flake. CI's own verdict is "All reruns passed. The failure is not reproducible (likely a transient issue)" (02875: 180/180 reruns passed). 03562 is a known flaky test (03562_parallel_replicas_remote_with_cluster failed #89974).
  • Stress test (arm_tsan) — Hung check, Hung check failed, possible deadlock found #107941 (AST-fuzzer teardown; no StorageHive frames; the stress run sets up no Hive metastore).

MERGEABLE; waiting on a maintainer approval and the private CH Inc sync.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master (98c1a1dda33) to clear the CI reds. The three failures on the previous head (9665364855e) were all confirmed master-wide flakes, unrelated to this Hive-only change:

No code changes were needed: the diff is Hive-only, the AI review is ✅ Approve, and there are no unresolved review threads.

Comment thread src/Storages/Hive/StorageHive.cpp Resolved
Comment thread src/Storages/Hive/StorageHive.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked at head 98c1a1dda33.

The re-merge run is still in progress and clean apart from one red, which is an unrelated, pre-existing flake — the crash fix and the query-local skip_splits refactor are unchanged and the two AI blockers are already addressed above (dangling-reference capture is a false positive; the cross-table hive_files_cache keying is real but pre-existing and out of scope for this Hive-only crash fix).

Fast test (arm_darwin) — 03988_keeper_client_autocomplete, benign teardown-stderr flake, not caused by this PR.

Every autocomplete assertion in the test passes (all OK). The test is failed only by the harness having stderror gate, because the clickhouse keeper-client process writes a benign exception to stderr while tearing down its ZooKeeper connection at process exit:

Reason: having stderror:
Poco::Exception. Code: 1000, e.code() = 57, Net Exception: Socket is not connected
  ...
  Poco::Net::SocketImpl::shutdown()
  Coordination::ZooKeeper::finalize(bool, bool, String const&)
  Coordination::ZooKeeper::~ZooKeeper()
  DB::KeeperClient::main(...)

On macOS (arm_darwin), socket.shutdown() inside Coordination::ZooKeeper::finalize (src/Common/ZooKeeper/ZooKeeperImpl.cpp:1433) returns ENOTCONN (57) when the socket is already disconnected at exit; the surrounding catch (...) reports it via tryLogCurrentException(log), which in the keeper-client goes to stderr.

Evidence it is unrelated to this PR (diff is Hive-only — src/Storages/Hive/* plus the new integration test, zero Keeper/ZooKeeperImpl code):

@groeneai, please investigate this flake and provide a fix in a separate PR (either suppress the benign ENOTCONN from socket.shutdown() during ZooKeeper::finalize, or make the test tolerant of it). If a fix is already in progress, please link it here.

Fast test failures are not auto-rerun, so this one job needs a rerun (or a merge over it, since it is a known-flaky, unrelated red). MERGEABLE; still waiting on a maintainer approval.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked at head 98c1a1dda33 (unchanged; the updatedAt bump since my last note is just the clickhouse-gh CI/LLVM-coverage report refreshes as the run finished).

The re-merge run 28532551666 has now completed, so I was able to re-trigger its one remaining red: Fast test (arm_darwin) (03988_keeper_client_autocomplete). That failure is the benign macOS ZooKeeper teardown flake — every autocomplete assertion is OK; it trips only the harness having stderror gate because socket.shutdown() in Coordination::ZooKeeper::finalize returns ENOTCONN (57) at process exit. It is unrelated to this PR (Hive-only diff, no Keeper code) and is a known flake on this lane: over the last 12 days it is 2424 pass / 65 fail (~97%) at the check level and OK 1720 / FAIL 14 (~99%) at the test level, with the most recent pass at 2026-07-01 20:19:43.

I've rerun the failed job (now in progress); once it is green the only remaining non-success will be CH Inc sync (private sync, still pending — not a failure).

No code changes. The two AI-review threads are unchanged and already addressed above: StorageHive.cpp:1011 ([&] capture of a range-for reference loop variable) is a false positive on pre-existing code, and StorageHive.cpp:713 (cross-table hive_files_cache keying) is a real but pre-existing, out-of-scope concern that this crash fix strictly improves.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked at head 98c1a1dda33 (unchanged). Everything is green except CH Inc sync, which just moved to a tests failed state.

Both failing jobs in the private sync are unrelated integration-test flakes, in areas this change does not touch — this PR is Hive-only (src/Storages/Hive/* plus the new test_hive_query):

  • a Keeper TTL test that failed once and then passed on the internal retry (a TTL-timing race);
  • a refreshable-materialized-view test that is a known, tracked flake.

Neither is reachable from the Hive code path. I've re-run the two failed sync jobs; once they pass, CH Inc sync should go green. The public CI is fully green (158 success / 17 skip; the only red is CH Inc sync itself).

@alexey-milovidov alexey-milovidov removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Jul 2, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This is not a critical bug fix - because we don't care about Hive.

In `StorageHive::collectHiveFiles`, the branch for a non-partitioned Hive
table declares `file_infos` inside the `else` block and schedules worker
tasks that capture the range-`for` variable `file_info` by reference (`[&]`).
`file_infos` is destroyed at the closing brace of the `else` block, but
`pool.wait()` - which joins those tasks - runs on the next line, after the
vector is already freed. A task still executing (or queued) at that point
dereferences a dangling reference into the freed `std::vector<FileInfo>`,
so a multi-threaded read of a non-partitioned `Hive` table can read freed
memory (a data race / use-after-free, reported by the AI review).

The partition branch above is not affected: `partitions` is a function-scope
local that outlives `pool.wait()`, so its `[&]` capture of `partition` (a
reference bound to a `partitions` element) is well-defined and is left
unchanged.

The fix captures `file_info` by value in the `else`-branch task (`FileInfo`
is a small, copyable struct: `path`, `last_modify_time`, `size`), so the
closure owns its data and no longer depends on `file_infos` outliving the
tasks.
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
@alexey-milovidov

alexey-milovidov commented Jul 2, 2026 •

Copy link
Copy Markdown
Member Author

Correction to my previous comment. I initially pushed 93636455be1 fixing the else-branch use-after-free directly on this PR, then reverted it (260625ac59a) to keep this PR focused on the null-dereference crash. The else-branch UAF is real but pre-existing on master and unrelated to the null-deref, so it belongs in a standalone change: opened #109164 for it. This PR's head is back to the reviewed, merge-ready crash fix (net diff unchanged).

Disposition of the two AI blockers, for the record:

  • Partition-branch [&] capture — a false positive, as you noted: partitions is a function-scope local that outlives pool.wait().
  • else-branch capture — a genuine pre-existing UAF (file_infos is scoped to the else block and destroyed before pool.wait(), so a task still running at the join reads freed vector elements). Fixed separately in Fix use-after-free in Hive unpartitioned read path #109164, not here.
  • hive_files_cache cross-table keying — real but pre-existing architectural change, out of scope for this crash fix; this PR strictly improves the situation by moving the query-local skip_splits out of the shared cached object.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Fix already in progress: #107438 ("Do not log benign ENOTCONN on socket shutdown during ZooKeeper finalize"). It is your first suggested option, applied at the source.

  • Catches Poco::Net::NetException at both socket.shutdown() sites in ZooKeeperImpl.cpp (the constructor and ZooKeeper::finalize, line 1392) and downgrades the benign POCO_ENOTCONN (57) to LOG_TRACE. It no longer reaches stderr, so it stops tripping the Fast-test having stderror gate; any other NetException is still logged normally.
  • Approved by alesapin (2026-06-19); OPEN and MERGEABLE, waiting on merge.

Confirmed unrelated to this PR: the #108094 diff is Hive-only (src/Storages/Hive/* plus the new integration test) with zero Keeper/ZooKeeperImpl code, so it cannot affect the ZooKeeper teardown path. Once #107438 merges, the arm_darwin Fast test flake goes away on all lanes.

alexey-milovidov and others added 2 commits July 5, 2026 05:54
The `hive_files_cache` lives on the per-remote-table `HiveTableMetadata`
and is shared by every `StorageHive` table over the same remote Hive
table, but a cached `IHiveFile` bakes in table-specific state: the
partition values, the minmax-index column layout (`index_names_and_types`),
the file format, and the `enable_orc_*` / `enable_parquet_rowgroup_minmax_index`
settings. `Hive` allows different ClickHouse schemas/settings over one
remote table, so two such tables previously shared one cached file (keyed
only by the remote `file_info.path`); the second table then pruned and
interpreted the cached minmax index against the first table's layout and
could silently keep or skip the wrong data.

Key the cache by the remote path plus a `SipHash` signature of that
table-specific state, so mismatched tables get independent cache entries
while an identical table still reuses the cache. Add
`test_hive_files_cache_is_table_local`, which reads the same remote ORC
table through two ClickHouse `Hive` tables that differ in column order and
minmax settings and asserts each returns its own correct rows.

Addresses review: #108094 (comment)

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

Copy link
Copy Markdown
Member Author

Pushed 1dde26b45cd (merged master into 27808dad09d), addressing the two remaining AI-review blockers. Both inline threads resolved.

  • Blocker 1 — unpartitioned-path use-after-free (StorageHive.cpp:1011, r3507709557). Resolved by merging master, which now contains Fix use-after-free in Hive unpartitioned read path #109164 (merged 2026-07-05). The non-partitioned read path captures file_info by value ([&, file_info]), so a worker still running at pool.wait() no longer dereferences a freed element of the block-scoped file_infos. The partition branch keeps its [&] capture — partitions is a function-scope local that outlives pool.wait(), so that reference is well-defined (as noted earlier, a false positive there). The merge cleanly combined Fix use-after-free in Hive unpartitioned read path #109164’s capture-by-value with this PR’s HiveFileWithSkipSplits return type on the same lines.

  • Blocker 2 — cross-table hive_files_cache keying (StorageHive.cpp:713, r3507709555). getHiveFileIfNeeded now keys the cache by the remote path plus a SipHash signature of the table-specific inputs baked into a cached IHiveFile: the file format, the minmax-index column layout (hivefile_name_types), the three minmax settings (enable_orc_file_minmax_index / enable_orc_stripe_minmax_index / enable_parquet_rowgroup_minmax_index — the only HiveSettings values read by the IHiveFile subclasses), and the partition values. Two ClickHouse Hive tables over the same remote table with a different column subset/order, PARTITION BY, format, or enable_orc_* setting now get independent cache entries, so one table can no longer prune (or materialize partition columns) against another’s cached layout; an identical table still hits the cache.

    Added test_hive_files_cache_is_table_local: it reads the same remote ORC table (test.demo_orc) through two ClickHouse Hive tables that differ in column order and minmax settings, warms the shared cache through the first, and asserts the second (and the first afterward) each return their own correct rows. This asserts the per-table isolation invariant the fix guarantees. (A strict fail-without-fix count assertion isn’t reliably constructible in the integration harness: same-schema aliasing is pruning-result-neutral, and the divergent-schema minmax-layout mismatch that would corrupt results is non-deterministic to force without risking a type-mismatch throw, so the test guards the contract instead.)

The change is compile-verified (clang, -Werror) and ruff check is clean on the test. The net diff remains Hive-only (StorageHive.{cpp,h}, HiveFile.h, and test_hive_query).

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.70% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.90% +0.10%

Changed lines: Changed C/C++ lines covered: 74/95 (77.89%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 7, 2026
Merged via the queue into master with commit f895fc1 Jul 7, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-hive-null-filter-crash branch July 7, 2026 20:55
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 7, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The integration test added in this PR covers the no-`WHERE` null-filter crash,
but it does not exercise the per-query split-skip set introduced by the later
commits: its filter is on the partition key `day` (satisfied by partition
pruning), Hive split-level minmax indexes default to off, and the Parquet
reader does not consume `skip_row_groups`. The test would still pass if the
query-local `skip_splits` plumbing were removed.

Add an ORC-based regression (`test_orc_split_skip_state_is_query_local`). The
new `test.demo_orc` table has two ORC files in one partition with disjoint
`score` ranges; with `enable_orc_stripe_minmax_index = 1` a filter on the
non-partition `score` column prunes one file's stripe, producing a non-empty
per-query split-skip set. The ORC reader honours `orc.skip_stripes`, so a
subsequent unfiltered read of the same (process-wide cached) table must still
return all rows - before the fix the stale skip set on the cached file dropped
the pruned stripe.

Also wrap each `hive` invocation in the data-preparation script in a `timeout`
so a stuck `hive` CLI (the metastore can still be starting up) aborts the
script and lets the existing retry loop run again, instead of consuming the
whole test budget - the cause of the occasional setup timeout in CI.

Addresses the AI review on ClickHouse#108094

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`test_orc_split_skip_state_is_query_local` set only
`enable_orc_stripe_minmax_index = 1`, but `enable_orc_file_minmax_index`
defaults to `true`, so a `score < 5` filter discarded the `[10, 11]` file at
file-pruning time (`getHiveFileIfNeeded` returns early once `useFileMinMaxIndex`
rejects the file) before stripe pruning ran. The kept `[1, 2]` file then had no
skipped stripe, so the query never built the non-empty per-query `skip_splits`
set the test is meant to cover - it would have passed even without the fix.

Disable file-level pruning (`enable_orc_file_minmax_index = 0`) so the
`[10, 11]` file survives to stripe-level pruning, where its stripe is added to
`skip_splits` - the non-empty query-local state whose staleness on the shared
cached file the fix prevents.

Addresses the AI review on ClickHouse#108094

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`prepare_hive_data.sh` ran its first statement under a 150s `timeout`; while
the Hive metastore was still starting the `hive` CLI blocked on the connection
and was killed (exit code 124), so only a handful of attempts fit into the
integration-test budget before pytest's 900s timeout fired. This timed out
`Integration tests (arm_binary, distributed plan, 3/4)` for both
test_select_without_where and test_orc_split_skip_state_is_query_local, even
though every other shard passed.

Probe the metastore with a short-timeout trivial query and poll instead: a
stuck probe is killed quickly and retried, while a successful one returns fast
once the metastore is up, fitting many more connection attempts into the budget.
The actual DDL / data load still runs with the generous timeout. If `timeout` is
unavailable the probe is skipped, preserving the previous behaviour.

ClickHouse#108094

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `hive_files_cache` lives on the per-remote-table `HiveTableMetadata`
and is shared by every `StorageHive` table over the same remote Hive
table, but a cached `IHiveFile` bakes in table-specific state: the
partition values, the minmax-index column layout (`index_names_and_types`),
the file format, and the `enable_orc_*` / `enable_parquet_rowgroup_minmax_index`
settings. `Hive` allows different ClickHouse schemas/settings over one
remote table, so two such tables previously shared one cached file (keyed
only by the remote `file_info.path`); the second table then pruned and
interpreted the cached minmax index against the first table's layout and
could silently keep or skip the wrong data.

Key the cache by the remote path plus a `SipHash` signature of that
table-specific state, so mismatched tables get independent cache entries
while an identical table still reuses the cache. Add
`test_hive_files_cache_is_table_local`, which reads the same remote ORC
table through two ClickHouse `Hive` tables that differ in column order and
minmax settings and asserts each returns its own correct rows.

Addresses review: ClickHouse#108094 (comment)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lter-crash

Fix exception when querying a Hive table without a WHERE clause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClickHouse crash when querying Hive PARQUET table

3 participants