Skip to content

Fix DeltaLake snapshot load hanging forever and blocking KILL QUERY - #117431

Open
xenx96 wants to merge 39 commits into
ClickHouse:masterfrom
xenx96:fix-deltalake-snapshot-load-hang
Open

xenx96 wants to merge 39 commits into
ClickHouse:masterfrom
xenx96:fix-deltalake-snapshot-load-hang

Conversation

@xenx96

@xenx96 xenx96 commented Sep 1, 2026 •

Copy link
Copy Markdown

Closes: #117280
Related: #47272
Related: #58479
Related: #117434
Related: #117435

CREATE TABLE ... ENGINE = DeltaLake(...), and any other query that loads a Delta Lake snapshot, can block forever inside delta-kernel. The FFI is synchronous and has no cancellation hook: snapshot_builder_build reads _delta_log through the kernel's own object store client and blocks in read_files on a channel fed by the kernel's background executor, so if the object store never answers, the call never returns. In the reported case the statement was still running after 4,718 s, KILL QUERY had no cancellation point to hit, none of the s3_* timeouts applied because the kernel uses its own object store client, and since the statement was executed by DDLWorker with distributed_ddl.pool_size = 1, every subsequent ON CLUSTER DDL timed out behind it.

The kernel call itself cannot be cancelled, so the wait for it is made interruptible instead:

  • TableSnapshot runs the kernel snapshot build on a worker thread and waits for it with its mutex released. Every query which needs the snapshot waits on one shared in-flight load (InflightSnapshotLoad) and polls with its own cancellation checks, so KILL QUERY, max_execution_time and the new setting delta_lake_snapshot_load_timeout_ms (default 10 minutes, 0 disables it) abort the wait for that query only, with TIMEOUT_EXCEEDED for the timeouts. A load is considered dead only once every waiter has given up on it (waiters are counted under the mutex); then a fresh, permit-bounded load is started for a pinned version, or a fresh object takes over for the latest version. DeltaLakeMetadataDeltaKernel resolves "latest" single-flight, outside snapshots_mutex, and publishes resolutions in the order they started, so an older one finishing late never moves "latest" back. A newer resolution which finds a lower version means the table was deleted and recreated at the same location; the cached versions of the old table are then dropped. An installed snapshot state never changes its version.
  • Workers are bounded by an atomic permit reserved before launch and derived from the global thread pool (clamp(min(max(pool / 8, 1), pool - 2), 0, 128); a pool too small to keep two workers free refuses with CANNOT_SCHEDULE_TASK). They run under a thread group of their own, built from the starting query's context so the kernel's log lines keep the query id, but without that query's memory limits. DeltaLakeSnapshotLoadsStuck counts loads every waiter gave up on, and DeltaLakeSnapshotLoadWorkers counts the loads holding a permit. The permit and the waiters' answer are owned by the scheduled job itself, so a job which the pool drops without running it still returns its permit and fails its waiters with CANNOT_SCHEDULE_TASK. totalRows / totalBytes propagate cancellation, the load timeout and the permit refusal instead of falling back to a second load.
  • The S3 kernel helper passes the object storage's live s3_connect_timeout_ms / s3_request_timeout_ms to the kernel's object store client when it builds an engine (read through a virtual accessor so cache wrappers are covered; the storage's own S3 client uses the same values). A build is shared by every query which needs it, whatever its own S3 settings. The credentials fingerprint stored with a state is that of the very client snapshot the builder was filled with, so credentials-rotation recovery judges the right engine.

The failpoint delta_kernel_snapshot_load_pause keeps the worker thread paused to simulate a kernel call which never returns, and delta_kernel_snapshot_load_worker_dropped ends the job before it runs. The new integration tests check that KILL QUERY cancels a CREATE TABLE stuck in the snapshot load, that delta_lake_snapshot_load_timeout_ms and max_execution_time fail the query with TIMEOUT_EXCEEDED, that the table is readable again once the worker is released, that a query with other S3 settings joins a build in flight, that a table recreated at the same location is read although its version is lower, and that a job which never runs fails its query and returns its permit.

Scope. This PR deliberately covers only the snapshot load (snapshot_builder_build and every path that rebuilds KernelSnapshotState). The remaining un-cancellable kernel waits are tracked in #117434: the data-file scan on the iterator thread, the snapshot statistics scan (getSnapshotStatsImpl, still performed under TableSnapshot::mutex), CDF reads and writes. The Azure timeout forwarding is #117435. Building or caching engines per query-level S3 settings is deliberately not part of this fix either: an engine is built with the storage's S3 settings at the time, and a cached engine is shared as cached.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix CREATE TABLE ... ENGINE = DeltaLake and other Delta Lake snapshot loads hanging forever when the delta-kernel object store client never answers. The snapshot load can now be interrupted by KILL QUERY and max_execution_time, is bounded by the new setting delta_lake_snapshot_load_timeout_ms (default 10 minutes), and the kernel's S3 client honours non-zero s3_connect_timeout_ms / s3_request_timeout_ms when a snapshot engine is built (0, which object_store cannot express as "no timeout", keeps its built-in defaults and logs a warning). An engine already cached for a snapshot keeps the timeouts it was built with. Abandoned snapshot loads are bounded and observable via the new DeltaLakeSnapshotLoadsStuck and DeltaLakeSnapshotLoadWorkers metrics.


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

The delta-kernel FFI is synchronous and has no cancellation hook: when the
kernel's object store client never answers, `snapshot_builder_build` blocks
forever in `read_files` -> `recv`. The query cannot be killed, no timeout
applies and, when the statement is executed by `DDLWorker`, the whole
distributed DDL queue is stuck behind it.

Run the kernel snapshot build on a separate thread and wait for it while
re-checking the query status, so that `KILL QUERY`, `max_execution_time`
and the new `delta_lake_snapshot_load_timeout_ms` setting abort the wait.
Forward `s3_connect_timeout_ms` and `s3_request_timeout_ms` to the kernel's
object store client, which previously used its own defaults.

Closes: ClickHouse#117280
@CLAassistant

CLAassistant commented Sep 1, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Clang rejects the init-capture `helper = helper` in `buildKernelSnapshotState`
with `-Wshadow-uncaptured-local` because it shadows the `TableSnapshot::helper`
field.
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Sep 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61c39f5]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
05397_clickhouse_local_locked_path_untouched FAIL cidb

AI Review

Summary

Makes Delta Lake snapshot-load waits cancellable and time-bounded, shares in-flight loads between queries, bounds worker usage, and forwards live S3 timeouts to the kernel. Review of commit 61c39f5bae5adaa7444a6f177f860bc0298a3ba4, including all prior PR discussion, found no new actionable defects within the stated snapshot-load scope.

Missing context / blind spots
  • ⚠️ The current Praktika workflow is still running, with relevant integration jobs pending. The added regression coverage was reviewed, but its execution on this head is not yet confirmed; passing integration results would close this validation gap. No local build or integration run was performed.
Final Verdict

Status: ✅ Approve on code review. CI completion remains pending. No new inline findings or thread replies were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@xenx96

xenx96 commented Sep 1, 2026

Copy link
Copy Markdown
Author

A few notes on design decisions in this PR, so the reasoning is visible up front.

1. Why a worker thread + polling instead of cancelling the kernel call

The kernel FFI (snapshot_builder_build) is synchronous and exposes no cancellation hook, and the hang observed in #117280 was inside the kernel's own executor: the thread sat in mpmc::Channel::recv under ObjectStoreStorageHandler::read_files, i.e. waiting for the background reader task, not on a socket the server controls. Note that object_store's client already applies default request/connect timeouts (30 s / 5 s), so an ordinary unanswered HTTP request should have failed long before the 78 minutes observed — which is why this PR does not rely on request timeouts alone and makes the wait interruptible instead.

The kernel call runs on a ThreadFromGlobalPool (reused pool thread) and the query thread waits on the future, calling QueryStatus::checkTimeLimit() on each wake-up. That is the only way KILL QUERY / max_execution_time can reach this code path. The 100 ms wake-up interval only applies while a load is in flight; initOrUpdateSnapshot() returns early when kernel_snapshot_state already exists and the credentials fingerprint is unchanged, so the loop runs once per snapshot (re)build, not per read. I'm happy to switch to a smaller interval or a different wait primitive if you prefer.

2. Abandoned workers

When the wait is given up, the worker is detached and keeps the kernel handles alive until the kernel call returns; it never touches TableSnapshot. Under a sustained object-store outage with repeated retries this can accumulate stuck pool threads (one per abandoned load), which the WARNING log makes visible but does not bound. If you'd like, I can add a CurrentMetrics counter (e.g. DeltaLakeAbandonedSnapshotLoads) and/or a server-level cap that fails new loads fast once too many workers are stuck — I kept the first version minimal on purpose.

3. Default of delta_lake_snapshot_load_timeout_ms = 10 min, and backports

10 min is meant as a safety net, not an SLA: a long _delta_log without a recent checkpoint on slow storage can legitimately take minutes, and max_execution_time remains the per-query knob. For LTS backports (this was hit on 26.3), the setting could default to 0 (disabled) so behaviour stays identical, while KILL QUERY / max_execution_time still work — that alone would have been enough to unblock the DDL queue in the reported incident.

4. Forwarding s3_connect_timeout_ms / s3_request_timeout_ms to the kernel client

This makes the kernel's S3 client honour the same settings users already tune for the server's own S3 client (the reporter had set them and expected them to apply), replacing object_store's built-in defaults. With server defaults this keeps the request timeout at 30 s but tightens the connect timeout from 5 s to 1 s (S3::DEFAULT_CONNECT_TIMEOUT_MS), so a slow-to-connect endpoint now fails the same way it already does for the server's own S3 client. It is a consistency change rather than the fix itself; the Azure counterpart is tracked in #117435, and the remaining un-cancellable kernel waits (scan / CDF / writes) in #117434.

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 61c39f5ba with master ac54778bd (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 183951ab4; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

21 object files changed (+117.82 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorage/DataLakes/DeltaLake/TableSnapshot.cpp.o 388.60 KiB 473.71 KiB +85.11 KiB (+21.90%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

385 translation units recompiled, 2874 s compile time in total, 385 of them have a recent master baseline.

Job report

xenx96 added a commit to xenx96/ClickHouse that referenced this pull request Sep 2, 2026
Address review on ClickHouse#117431:
- Abandoned delta-kernel snapshot-load workers (KILL QUERY or a timeout
  gave up the wait) are counted in the new DeltaLakeSnapshotLoadsStuck
  metric and hard-capped: at 16 stuck workers, new snapshot loads fail
  fast with CANNOT_SCHEDULE_TASK instead of occupying another
  GlobalThreadPool worker. When the worker finishes while the wait is
  being abandoned, it is joined instead of detached, and an abandoned
  worker unregisters itself once the kernel call returns.
- s3_connect_timeout_ms / s3_request_timeout_ms = 0 ("no timeout" for
  the server's S3 client) cannot be expressed through object_store's
  string options (a literal 0 makes every request time out immediately),
  so 0 now explicitly leaves object_store's built-in defaults in effect,
  documented in the code and logged as a warning.
- The kill-query integration test asserts the metric's add/remove cycle.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VsKi3WZHT4bHQ6f4caz9Es
Address review on ClickHouse#117431:
- Abandoned delta-kernel snapshot-load workers (KILL QUERY or a timeout
  gave up the wait) are counted in the new DeltaLakeSnapshotLoadsStuck
  metric and hard-capped: at 16 stuck workers, new snapshot loads fail
  fast with CANNOT_SCHEDULE_TASK instead of occupying another
  GlobalThreadPool worker. When the worker finishes while the wait is
  being abandoned, it is joined instead of detached, and an abandoned
  worker unregisters itself once the kernel call returns.
- s3_connect_timeout_ms / s3_request_timeout_ms = 0 ("no timeout" for
  the server's S3 client) cannot be expressed through object_store's
  string options (a literal 0 makes every request time out immediately),
  so 0 now explicitly leaves object_store's built-in defaults in effect,
  documented in the code and logged as a warning.
- The kill-query integration test asserts the metric's add/remove cycle.
@xenx96
xenx96 force-pushed the fix-deltalake-snapshot-load-hang branch from ae08645 to 5f105b0 Compare September 2, 2026 01:01
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…waiter

Second review round on ClickHouse#117431:
- The cap was a pre-launch metric check while the counter was only bumped
  later on the give-up path, so N concurrent loads could all pass the
  check and strand more than the cap. Reserve one of MAX_SNAPSHOT_LOAD_WORKERS
  (128) atomic permits before launching the worker and release it in the
  worker when the kernel call returns, so live workers are bounded under
  concurrency. DeltaLakeSnapshotLoadsStuck now purely observes loads that
  a query gave up on.
- A stuck snapshot load only made its own waiter killable: sibling queries
  reusing the same cached TableSnapshot slept inside TableSnapshot::mutex
  (and latest-version lookups inside snapshots_mutex), unreachable by
  KILL QUERY. The build now runs once as a shared InflightSnapshotLoad and
  every entry point waits for it with the mutex released, each waiter
  polling and cancelling independently; DeltaLakeMetadataDeltaKernel builds
  snapshots outside snapshots_mutex.
- SettingsChangesHistory recorded delta_lake_snapshot_load_timeout_ms as
  600000 -> 600000, so compatibility below 26.9 kept the timeout instead of
  restoring the pre-26.9 no-timeout behavior; record 0 -> 600000.
- Add a test that a waiter on a shared, still-running snapshot load is
  independently killable.
The previous commit passed the caller's std::unique_lock into
initOrUpdateSnapshot and released it there while waiting; clang's
thread-safety analysis then dropped the held-lock fact at the call site,
so every guarded call after it (getVersionUnlocked, initOrUpdateSchemaIfChanged,
getKernelSnapshotState) failed Build (arm_tidy) with -Werror.

initOrUpdateSnapshot now acquires and releases `mutex` itself and is
called WITHOUT the lock held; each entry point re-takes a plain
lock_guard for its guarded reads, so the analysis sees the lock the same
way the original code did. The rare stale-token stats rebuild now
reassigns kernel_snapshot_state directly under the lock instead of
resetting it to null and re-entering init, so it is never observed null
while unlocked.
Third review round on ClickHouse#117431:
- update() and getTableSnapshot(latest) each allocated a fresh TableSnapshot
  before the latest version was known, so concurrent latest resolutions of
  one table each started their own snapshot_builder_build (the in-flight
  sharing inside TableSnapshot could not help), and a slower one could
  publish an older latest_snapshot_version. Resolve "latest" through one
  shared TableSnapshot held in latest_snapshot_in_flight under
  snapshots_mutex, wait outside the mutex, publish the version only when it
  does not move latest backwards, and reuse the cached snapshot for that
  version.
- The stale-credentials retry in getSnapshotStats waited on the rebuilt
  load with TableSnapshot::mutex held, which reintroduced an unkillable wait
  on the SELECT count() path. The retry now flags the state for rebuild and
  goes back through initOrUpdateSnapshot, so the rebuild uses the same
  interruptible shared load with the mutex released and the state is never
  observed null.
…ruptible load

TableSnapshot::Iterator::tryRefreshAndRetryScanState constructed
KernelSnapshotState synchronously on the scan thread, bypassing the
permit bound and the cancellation checks; a rebuild that blocked in
snapshot_builder_build left StorageObjectStorageSource stuck in
file_iterator->next() with no way for KILL QUERY or max_execution_time
to reach it.

Make startKernelSnapshotLoad / waitForSnapshotLoad static (they only need
the kernel helper and a logger) and add loadKernelSnapshotState for a
single waiter, so the iterator rebuilds through the same bounded,
interruptible path. The worker task is now the only place that constructs
KernelSnapshotState.
Build (arm_tidy) failed with -Werror=unused-parameter after the helper
became static: only waitForSnapshotLoad logs, so the launcher does not
need a logger.
…healing cache

Fourth review round on ClickHouse#117431:
- The shared build worker attached to the starting query's thread group,
  so that query's max_memory_usage, quota and accounting silently applied
  to every waiter. Run the worker under a neutral ThreadGroup created from
  the global context instead.
- The 128 cap assumed the default max_thread_pool_size. Derive it from
  GlobalThreadPool's actual size (pool/8, clamped to [1, 128]) so a dead
  object store cannot occupy every worker on a small pool.
- resolveLatestSnapshot preferred an already cached object for the resolved
  version, which could be poisoned by a stuck in-flight load; on success
  replace the cache entry with the freshly loaded snapshot. In the same
  spirit, initOrUpdateSnapshot no longer adopts an in-flight load that a
  waiter already gave up on: it starts a fresh (permit-bounded) load, so a
  snapshot recovers once the object store does instead of waiting on a
  possibly dead worker forever.
…ws/totalBytes

- maxSnapshotLoadWorkers() still returned 1 for max_thread_pool_size <= 7,
  so on a pool of 1 a hung load could occupy the only worker. The cap now
  also leaves at least two workers free (min(pool / 8, pool - 2)), and is 0
  when even that is impossible: snapshot loads then fail fast with
  CANNOT_SCHEDULE_TASK instead of starving the pool.
- DeltaLakeMetadataDeltaKernel::totalRows / totalBytes swallowed every
  exception, including TIMEOUT_EXCEEDED, QUERY_WAS_CANCELLED and
  CANNOT_SCHEDULE_TASK, so a trivial SELECT count() fell back to the read
  path and waited through a second full snapshot load. Those control-flow
  errors now propagate; genuine statistics failures still degrade to
  nullopt.
…mit exception-safe

- Two latest-version loads on one TableSnapshot (a fresh one started after
  the first was given up) can resolve different versions; the later
  completion overwrote kernel_snapshot_state, so one cached object could be
  reached under two version keys and flip between them. An installed
  version is now final: a stale completion with a different version is
  ignored (rebuilds after a credentials refresh are pinned to the installed
  version and still pass).
- The pool-derived cap returned 0 for max_thread_pool_size <= 7, making
  Delta Lake unusable on configurations that worked before this PR. Allow
  at least one worker whenever two can stay spare; only a pool of <= 2 gets
  a cap of 0.
- The permit reserved before launching was released only on two paths;
  allocations and thread-group creation in between could leak it forever.
  A scope guard now releases it unless it was handed over to the worker.
@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
…hot-load-hang

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

- retargeted PR record [email protected] to 26.10 (settings-history check rule)

Also resolved conflicts in:
- `src/Common/FailPoint.cpp`
- `src/Disks/DiskObjectStorage/ObjectStorages/S3/S3ObjectStorage.h`
- `src/Storages/ObjectStorage/DataLakes/DeltaLake/KernelHelper.h`
- `src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadataDeltaKernel.cpp`
- `tests/integration/test_storage_delta/test.py`

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…one slot

`DeltaLakeMetadataDeltaKernel` kept the latest-version object in flight in a
single slot, `latest_snapshot_in_flight`, and a query whose effective
`KernelClientOptions` differed from the ones of that object replaced it.
With an A, B, A arrival order the second query with options A no longer
found the object the first one was still loading and started a duplicate
load for the same options. During an object-store outage every such
alternation left one more stuck worker behind, up to the worker cap, after
which snapshot loads were refused with `CANNOT_SCHEDULE_TASK`.

The objects in flight are now kept in a map keyed by `KernelClientOptions`:
a query joins the load in flight for its own options and never displaces
the one of other options. Each entry counts the callers resolving through
its object and is removed when the version is resolved or when the last
caller is gone (killed, timed out, or failed), so the map does not outgrow
the set of options being resolved at the moment.

As the options are the key now, `TableSnapshot::canShareInflightLoad` is no
longer needed and is removed. The reservation of the options for the first
load of such an object stays, so that the build runs with exactly the
options it is shared under even if the storage's live settings change
between the lookup and the start of the load.

The new integration test
`test_latest_snapshot_load_shared_per_client_options` pauses the load of
one query, runs a query with other S3 timeouts on the same table, and
checks that the next query with the first options joins the paused load.

ClickHouse#117431 (review)
@kssenii kssenii self-assigned this Oct 1, 2026
Comment thread src/Core/Settings.cpp Outdated
The load runs on a separate thread and the query waits for it, so the wait is interrupted by `KILL QUERY` and `max_execution_time`,
and fails with `TIMEOUT_EXCEEDED` once this timeout is exceeded. Value 0 means no timeout.
)", 0, \
{"26.10", 0, 600000, "New setting bounding how long a query waits for delta-kernel to load a Delta Lake table snapshot; the wait is also interrupted by `KILL QUERY` and `max_execution_time`."}) \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok to set a limit 600000 even to previous versions even if review bot claimed it needs to be 0 for compatibility

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in f8c60ad: the history entry keeps 600000 for older versions as well.

Comment on lines +464 to +466
/// The live S3 settings of the storage (the ones applyNewSettings reapplies), or nullptr
/// when the storage is not backed by S3. For clients which build their own S3 client and
/// must follow the same settings as the storage's client (e.g. delta-kernel).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
/// The live S3 settings of the storage (the ones applyNewSettings reapplies), or nullptr
/// when the storage is not backed by S3. For clients which build their own S3 client and
/// must follow the same settings as the storage's client (e.g. delta-kernel).

(method name is already self-explanatory)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed in f8c60ad.

Comment on lines +30 to +35
/// The effective client options of one kernel engine build, resolved on the query thread by
/// IKernelHelper::resolveClientOptions (the worker which performs the build has no query
/// context of its own). They are also the key under which an in-flight build may be shared:
/// two queries share one only if the builder would be filled identically, so the values here
/// are the effective ones — the storage's live settings overridden by the query — never a
/// mere "the query changed this setting" bit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
/// The effective client options of one kernel engine build, resolved on the query thread by
/// IKernelHelper::resolveClientOptions (the worker which performs the build has no query
/// context of its own). They are also the key under which an in-flight build may be shared:
/// two queries share one only if the builder would be filled identically, so the values here
/// are the effective ones — the storage's live settings overridden by the query — never a
/// mere "the query changed this setting" bit.
/// Effective S3 client options for one kernel engine build: the storage's live settings overridden
/// by the query's, resolved on the query thread because the snapshot-load thread has no query context.
/// Two queries share an in-flight build only when these options are equal.

Let's also compact other comments in this PR to 1-3 lines, more if really difficult otherwise, may be remove comments from some places completely since the code is simple, too many and too big comments are hard to read.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Applied in f8c60ad, and compacted the rest of the comments in this PR the same way: most are now one or two lines, and the ones that only restated the code are gone.

Comment on lines +291 to +294
std::lock_guard lock(snapshots_mutex);
LOG_TEST(
log, "Using snapshot version: {}, latest loaded snapshot version: {}, reused cached snapshot: {}",
result_snapshot_version.value(), latestSnapshotVersionToStr(), !created);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd put the mutex inside latestSnapshotVersionToStr() since extending the scope here is unnecessary, also here mutex does not add any guarantees, so may be use an atomic instead

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Moved the lock into latestSnapshotVersionToStr() in f8c60ad and dropped the extra scopes around the two log calls (its only callers). I kept the mutex rather than an atomic, since latest_snapshot_version is still read and updated together with the snapshot cache under snapshots_mutex elsewhere.

…ecreated at a lower version; build the kernel engine with the storage's live S3 timeouts instead of keying builds by query options
@xenx96

xenx96 commented Oct 28, 2026

Copy link
Copy Markdown
Author

@kssenii Changes since your last review:

  • checkTimeLimit returning false under timeout_overflow_mode = 'break' now ends the wait with TIMEOUT_EXCEEDED instead of waiting on.
  • A stale-token retry keeps the snapshot's version.
  • "Latest" resolutions publish in the order they started, and a table recreated at the same location at a lower version is read (the old table's cached snapshots are dropped).
  • In-flight builds are no longer keyed by per-query S3 options: the kernel engine uses the storage's live S3 timeouts and every waiter shares one build. KernelClientOptions is gone, so the change is smaller.

The PR description is updated accordingly.

…olving the latest version never waits on a statistics scan under snapshots_mutex
…en the pool drops the job without running it
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
@xenx96
xenx96 requested a review from kssenii November 6, 2026 01:02
@xenx96

xenx96 commented Nov 17, 2026

Copy link
Copy Markdown
Author

An update on the cause, since it changes what this PR is for.

A later recurrence with the same stack as #117280 logged the cause: delta-kernel's block_on handed every result back through spawn_blocking, and at a container PID limit no thread could be spawned, so the result sender was never dropped and the caller's recv() waited forever (#128033). That is fixed in master by #130544 (delta-io/delta-kernel-rs#3202). The logs of the original #117280 report had expired, so I cannot prove it was the same cause, but the stack matches. The object store was most likely not the problem.

So this PR no longer fixes a known hang. What it still adds is a way out of a kernel snapshot load that never returns, whatever the cause: KILL QUERY, max_execution_time and delta_lake_snapshot_load_timeout_ms end the wait for that query.

@kssenii is that still worth the change now that the known cause is fixed? If yes, I will rewrite the description around that and drop Closes: #117280. If not, I will close this PR and close #117280 as fixed by #130544.

@clickhouse-gh clickhouse-gh Bot added comp-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 19, 2026

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

Labels

can be tested Allows running workflows for external contributors comp-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

6 participants