Repository navigation
Conversation
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
Clang rejects the init-capture `helper = helper` in `buildKernelSnapshotState` with `-Wshadow-uncaptured-local` because it shadows the `TableSnapshot::helper` field.
|
Workflow [PR], commit [61c39f5] Summary: ❌
AI ReviewSummaryMakes 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 Missing context / blind spots
Final VerdictStatus: ✅ Approve on code review. CI completion remains pending. No new inline findings or thread replies were posted. |
|
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 ( The kernel call runs on a 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 3. Default of 10 min is meant as a safety net, not an SLA: a long 4. Forwarding 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 |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes21 object files changed (+117.82 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units385 translation units recompiled, 2874 s compile time in total, 385 of them have a recent master baseline. |
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.
ae08645 to
5f105b0
Compare
…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.
…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)
| 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`."}) \ |
There was a problem hiding this comment.
Ok to set a limit 600000 even to previous versions even if review bot claimed it needs to be 0 for compatibility
There was a problem hiding this comment.
Done in f8c60ad: the history entry keeps 600000 for older versions as well.
| /// 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). |
There was a problem hiding this comment.
| /// 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)
| /// 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. |
There was a problem hiding this comment.
| /// 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.
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
…Str, keep the load timeout for older compatibility versions
…etRawDeltaSchemaFields
…ad wait in timeout_overflow_mode 'break'
…ecreated at a lower version; build the kernel engine with the storage's live S3 timeouts instead of keying builds by query options
|
@kssenii Changes since your last review:
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
|
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 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: @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
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_buildreads_delta_logthrough the kernel's own object store client and blocks inread_fileson 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 QUERYhad no cancellation point to hit, none of thes3_*timeouts applied because the kernel uses its own object store client, and since the statement was executed byDDLWorkerwithdistributed_ddl.pool_size = 1, every subsequentON CLUSTERDDL timed out behind it.The kernel call itself cannot be cancelled, so the wait for it is made interruptible instead:
TableSnapshotruns 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, soKILL QUERY,max_execution_timeand the new settingdelta_lake_snapshot_load_timeout_ms(default 10 minutes,0disables it) abort the wait for that query only, withTIMEOUT_EXCEEDEDfor 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.DeltaLakeMetadataDeltaKernelresolves "latest" single-flight, outsidesnapshots_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.clamp(min(max(pool / 8, 1), pool - 2), 0, 128); a pool too small to keep two workers free refuses withCANNOT_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.DeltaLakeSnapshotLoadsStuckcounts loads every waiter gave up on, andDeltaLakeSnapshotLoadWorkerscounts 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 withCANNOT_SCHEDULE_TASK.totalRows/totalBytespropagate cancellation, the load timeout and the permit refusal instead of falling back to a second load.s3_connect_timeout_ms/s3_request_timeout_msto 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_pausekeeps the worker thread paused to simulate a kernel call which never returns, anddelta_kernel_snapshot_load_worker_droppedends the job before it runs. The new integration tests check thatKILL QUERYcancels aCREATE TABLEstuck in the snapshot load, thatdelta_lake_snapshot_load_timeout_msandmax_execution_timefail the query withTIMEOUT_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_buildand every path that rebuildsKernelSnapshotState). 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 underTableSnapshot::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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
CREATE TABLE ... ENGINE = DeltaLakeand other Delta Lake snapshot loads hanging forever when the delta-kernel object store client never answers. The snapshot load can now be interrupted byKILL QUERYandmax_execution_time, is bounded by the new settingdelta_lake_snapshot_load_timeout_ms(default 10 minutes), and the kernel's S3 client honours non-zeros3_connect_timeout_ms/s3_request_timeout_mswhen 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 newDeltaLakeSnapshotLoadsStuckandDeltaLakeSnapshotLoadWorkersmetrics.Workflow [PR]
Sync PR [sync-upstream/pr/117431]