Repository navigation
S3Queue: add failed_file_ttl_sec setting and SYSTEM DROP S3QUEUE FAILED FILES command (unordered mode) - #113784
adityaksolves wants to merge 122 commits into
Conversation
Implements automatic cleanup of old failed file entries from ZooKeeper based on a configurable TTL (failed_file_ttl_sec table setting). - Add failed_file_ttl_sec setting to ObjectStorageQueueSettings (default: 0 = store forever, matching tracked_file_ttl_sec behavior) - Enable cleanup_failed_files flag when failed_file_ttl_sec > 0 - Modify cleanupTrackedNodes to accept TTL parameter for both processed and failed file cleanup (was hardcoded to tracked_files_ttl_sec) - Periodic cleanup thread now removes failed files older than TTL from /failed/ znode path in Keeper Integration tests verify: - Failed files appear in Keeper /failed/ path and cache - After TTL expires, cleanup task removes from both Keeper and cache - Test uses 3-second TTL + 2-second cleanup interval for fast execution Related: ClickHouse#113054
Implements SQL command to manually clear all failed file entries from a specific S3Queue table's ZooKeeper metadata. Syntax: SYSTEM DROP S3QUEUE FAILED FILES [db.]table - Add new SYSTEM_DROP_S3QUEUE_FAILED_FILES access type permission - Add DROP_S3QUEUE_FAILED_FILES to parser and AST - Implement dropFailedFiles() in ObjectStorageQueueMetadata: * Acquires same distributed cleanup_lock as periodic TTL sweep * Batch-reads all failed file metadata from Keeper * Bulk-deletes all /failed/ znodes using removeChildren * Clears corresponding entries from in-memory cache - Command is idempotent (succeeds on empty failed set) Integration tests verify: - Single failed file deletion - Bulk deletion (5 files removed in one operation) - Idempotency (running on empty set returns success) - Both Keeper znodes and cache entries are cleared Closes: ClickHouse#113054
Both failed_file_ttl_sec and SYSTEM DROP S3QUEUE FAILED FILES are now explicitly restricted to unordered mode tables only, matching the Phase 1 scope commitment. - Enable cleanup_failed_files only when isUnordered(mode) is true (matching existing cleanup_processed_files pattern) - SYSTEM DROP command throws NOT_IMPLEMENTED error for ordered mode with clear message about future support - Add test confirming SYSTEM DROP is blocked in ordered mode - Add test confirming TTL cleanup does not trigger in ordered mode This ensures the feature behavior matches the documented Phase 1 scope (unordered mode only). Support for ordered mode will be added in Phase 2. Related: ClickHouse#113054
…LED FILES Documents the new failed file cleanup features for S3Queue tables: - Add failed_file_ttl_sec setting documentation to S3Queue engine page (CREATE TABLE syntax, setting description with example) - Add SYSTEM DROP S3QUEUE FAILED FILES command documentation to system.mdx (syntax, description, permissions, example) - Include cross-references between setting and command docs - Note unordered-mode-only restriction in both locations Related: ClickHouse#113054
|
Workflow [PR], commit [21af768] Summary: ❌
AI ReviewSummaryThis PR adds Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 21af768.
Changed lines: Changed C/C++ lines covered: 1019/1185 (85.99%) · Uncovered code |
The ErrorCodes::NOT_IMPLEMENTED was used at line 1477 but not declared in the namespace ErrorCodes block. This caused a style-check failure in CI. Added the missing extern declaration to fix the build.
e9c7857 to
0cd5a4e
Compare
Move failed_file_ttl_sec documentation into the Documentation string in registerQueueStorage.cpp so it is picked up by the docs autogeneration script, instead of being manually edited into the AUTOGENERATED region of s3queue.mdx. Regenerated s3queue.mdx accordingly.
|
@kssenii , The "Docs check (Mintlify)" failure is because the AUTOGENERATED region |
…setting into ALTER/getSettings, fix race condition in SYSTEM DROP S3QUEUE FAILED FILES
…mode compatibility for failed_file_ttl_sec
…QueueIFileMetadata
Verifies that TTL cleanup does not reset the retry counter stored in .retriable nodes: with s3queue_loading_retries=3 and a failed_file_ttl_sec shorter than the retry interval, the file must still reach the terminal failed state with exactly 3 retries instead of looping from retries=0.
4d12089 to
42c90e1
Compare
prepareProcessedRequestsImpl previously left the .retriable retry-state node behind after a file succeeded, since only .retriable nodes are now excluded from TTL cleanup and SYSTEM DROP S3QUEUE FAILED FILES. This left permanent Keeper garbage for any file that failed then later succeeded, and could cause a re-imported file to resume from a stale retry counter instead of starting at retries=0. Applies to both ordered and unordered mode. Uses tryGet to check for the node before adding a conditional remove request, so success requests for files with no prior failures (the common case) are unaffected. Adds an integration test that fails a file, replaces its S3 content with valid data, verifies it succeeds, and asserts no .retriable node remains.
When loading_retries is reduced to 0 via ALTER TABLE after a .retriable node already exists (from prior failures with retries enabled), the !retriable branch in prepareFailedRequestsImpl now removes the stale .retriable node before creating the terminal failed marker. Without this fix, the stale .retriable survives TTL/SYSTEM DROP cleanup and can interfere with future processing episodes (resuming from the old retry counter instead of starting from 0). Added integration test test_retriable_cleanup_on_loading_retries_reduced_to_zero that exercises: create .retriable with retries > 0, ALTER to loading_retries=0, force terminal failure, and verify no .retriable remains.
…failed files Both failed_file_ttl_sec and SYSTEM DROP S3QUEUE FAILED FILES intentionally skip files that are actively retrying (stored as .retriable nodes in Keeper) to preserve retry state. Only terminal failed files (those that have exhausted all retries) are cleaned up. Updated documentation to explicitly state this behavior: - Setting description now says 'terminal failed files' - SYSTEM DROP docs clarify what gets cleaned (terminal only) - S3Queue engine docs explain the terminal vs actively retrying distinction This addresses the semantic gap where system.s3queue_metadata_cache shows all failures as status='Failed', but cleanup features only touch terminal ones.
… via ALTER cleanupThreadFuncImpl() gated abandoned-/processing cleanup on cleanup_processing_files, a constructor-time snapshot, even though use_persistent_processing_nodes and persistent_processing_node_ttl_seconds are both alterable at runtime. A table created with processing-node cleanup disabled could therefore never turn it on later via ALTER TABLE ... MODIFY SETTING. Re-derived the guard from the live atomics on each run, matching the existing pattern already used for tracked_files_limit / tracked_file_ttl_sec / failed_files_ttl_sec in the same function. Also removed startup()'s flag-based gate on creating the periodic cleanup_task at all: in ordered mode, a table with all three constructor-time flags false never got a cleanup_task scheduled, so even after the guard above is fixed there would be nothing to run it. The task is now always created - cleanupThreadFuncImpl() already re-derives every cleanup category live and correctly no-ops when there is nothing to do, so an idle table only pays for a cheap ephemeral Keeper lock each interval, not a real sweep.
…hausted .retriable marker When tryTerminalizeExhaustedRetriableMarker() succeeds on the cold-cache state == None path (in both trySetProcessing() and prepareSetProcessingRequests()), the caller previously returned without updating file_status, leaving the local cache entry stuck at State::None even though Keeper now has a terminal /failed/<hash> node. That did not self-heal in unordered mode: filterOutProcessedAndFailed() strips terminal failures before getFileMetadata() runs again, and cache-reconciliation only prunes State::Failed rows -- so the replica that performed the terminalization could keep reporting the file as None in system.s3queue_metadata_cache indefinitely. Fixed by checking tryTerminalizeExhaustedRetriableMarker()'s return value and calling file_status->updateState(FileStatus::State::Failed) on success, mirroring the existing updateState() pattern already used for the Processed case in the same function. When the call returns false (marker already absent, or a benign race with another replica), the cache is left untouched -- a subsequent access will re-read fresh state from Keeper.
| ```sql | ||
| -- View current failed files | ||
| SELECT file_name, status, exception | ||
| FROM system.s3queue_metadata_cache |
There was a problem hiding this comment.
This section now says the command works for S3Queue and AzureQueue, but the only "view current failed files" example still queries system.s3queue_metadata_cache.
That is the S3Queue introspection table. The shared queue docs send AzureQueue users to system.azure_queue_metadata_cache on 25.1+, so an AzureQueue user following this new command docs block cannot inspect the failed set you just told them to drop.
Please either mark this snippet as S3Queue-only or add the AzureQueue counterpart (or an engine-qualified note) so the example matches the public surface the paragraph advertises.
There was a problem hiding this comment.
Fixed in 076a5e3. Rewrote the documentation example block to separate explanatory text from the code. The SQL code blocks now contain only runnable statements, and explicit instructions/queries are provided for both S3Queue (system.s3queue_metadata_cache) and AzureQueue (system.azure_queue_metadata_cache).
There was a problem hiding this comment.
The current head still does not make this available in the published docs. In docs/reference/statements/system.mdx:980-984, the generated example only shows system.s3queue_metadata_cache, with no AzureQueue counterpart or engine-qualified note, so an AzureQueue user following the page is still sent to the wrong introspection table.
Since system.mdx is generated from this source block, the example here likely needs to be reshaped so the Azure-specific guidance survives regeneration instead of existing only in the parser-side prose.
There was a problem hiding this comment.
The current head still does not expose this in the published page. docs/reference/statements/system.mdx:980-984 still contains only the system.s3queue_metadata_cache example, with no AzureQueue counterpart or engine-qualified note, so 076a5e3d082 did not actually fix the user-facing docs yet.
This still needs the ParserSystemQuery.cpp example block to be shaped so the autogenerated system.mdx output preserves the AzureQueue guidance instead of dropping it.
…nal_out parameter CI's arm_tidy build (which enables -Werror for this class of diagnostic) failed with 'default arguments on virtual or override' on the new is_terminal_out parameter added to getPathState() in 5250a85 -- the same mistake already fixed once before in ee810c7 for a different parameter on this exact function. Removed the '= nullptr' default from all four declarations (the pure virtual in IFileMetadata and the three overrides). Updated the two call sites in ObjectStorageQueueIFileMetadata.cpp that relied on the default (trySetProcessing() and prepareSetProcessingRequests(), which don't need the terminal-state distinction) to pass nullptr explicitly. The two call sites in StorageObjectStorageQueue.cpp already passed &is_terminal explicitly and are unaffected.
- Fix Blocker 1: Thread loading_retries by reference to honor live TTL changes for in-flight files. - Fix Blocker 2: Guard tryTerminalizeExhaustedRetriableMarker against empty Keeper paths in EXCLUSIVE mode. - Fix Major 1: Split SYSTEM DROP FAILED FILES docs into runnable SQL blocks and text. - Fix Major 2: Test direct RBAC grant with a minimal-privilege user.
…d of s3queue_metadata_cache
…ing polling interval
|
@kssenii — before I push another round, I'd like to settle the scope of this PR with you, since the review cycle keeps expanding it and I'd rather cut it deliberately than incrementally. Where things stand: the PR is at 116 commits / ~+5.9k lines for what started as two things ( Three questions, and I'll do whichever you prefer: 1. Exclusive-mode 2. The exclusive-mode regression test the bot asked for. This is the part I'm most wary of: tests in this area that wait across a retryable failure are timing-dependent, and an earlier attempt of mine ( 3. Remaining deferred Separately, the two failing stateless jobs are Happy to go either way on all three — I just want one decision rather than discovering the boundary one review round at a time. |
…ailed-file-ttl-113054 # Conflicts: # src/Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.cpp # src/Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.h
|
|
||
| **Required Permission** | ||
|
|
||
| Requires the `SYSTEM DROP S3QUEUE FAILED FILES` privilege: |
There was a problem hiding this comment.
The documented privilege contract is incomplete for the ON CLUSTER form advertised in the syntax above. executeDDLQueryOnCluster still requires the generic CLUSTER privilege before it even reaches SYSTEM_DROP_S3QUEUE_FAILED_FILES; the allow-path setup in tests/integration/test_storage_s3_queue/test_failed_files_ttl_and_drop.py:1660-1704 has to grant CLUSTER first for exactly that reason.
As written, a user who follows the docs and runs GRANT SYSTEM DROP S3QUEUE FAILED FILES ON db.table TO user will still get ACCESS_DENIED on SYSTEM DROP S3QUEUE FAILED FILES ... ON CLUSTER .... Please document the extra GRANT CLUSTER ON *.* requirement, or explicitly scope this permission section to the non-clustered form.
| json.set("mode", mode); | ||
| json.set("tracked_files_limit", tracked_files_limit.load()); | ||
| json.set("tracked_files_ttl_sec", tracked_files_ttl_sec.load()); | ||
| json.set("failed_files_ttl_sec", failed_files_ttl_sec.load()); |
There was a problem hiding this comment.
This turns the legacy fallback into an explicit failed_files_ttl_sec as soon as metadata is rewritten, so an existing unordered queue stops following tracked_file_ttl_sec after the first later ALTER. Concrete trace: attach a pre-PR table with tracked_file_ttl_sec = 3 and no failed_files_ttl_sec; parse() backfills failed_files_ttl_sec = 3, then ALTER ... MODIFY SETTING tracked_file_ttl_sec = 10 updates only tracked_files_ttl_sec, and toString() persists failed_files_ttl_sec = 3. From then on /failed cleanup stays at 3 instead of following the old knob, which breaks the backward-compatibility promise for existing tables. Could we preserve whether failed_files_ttl_sec is inherited, and keep updating it with tracked_file_ttl_sec until the new setting is set explicitly?
|
@kssenii, the AI review flagged one real edge case in the legacy fallback as a blocker, and I'd like your decision on scope before I change anything. Issue: for a pre-PR table with A proper fix needs a persisted "inherited" flag in the Keeper table metadata (format change, ALTER handling, tests). That would widen this PR further, so I see two options:
I'd suggest option 1 and handling the flag in the follow-up PR (Phase 2), together with the other deferred items. This is the same kind of decision as the three scope questions I asked above (exclusive-mode Two smaller items I'll fix in this PR unless you object:
|
|
|
||
|
|
||
| def test_legacy_metadata_inherits_failed_files_ttl_from_tracked_ttl(started_cluster): | ||
| """A table whose Keeper metadata predates `failed_files_ttl_sec` keeps its old cleanup behaviour. |
There was a problem hiding this comment.
This regression only proves the initial attach-time fallback. The still-open compatibility hole on src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp:118 is that a legacy table stops following tracked_file_ttl_sec after the first later ALTER: parse() backfills failed_files_ttl_sec, ALTER ... MODIFY SETTING tracked_file_ttl_sec updates only the tracked TTL, and the next metadata rewrite persists the old failed TTL as explicit. Because this test never changes tracked_file_ttl_sec after the re-attach, CI would stay green on that regression.
Please extend the scenario with an ALTER ... MODIFY SETTING tracked_file_ttl_sec = ... after ATTACH and assert /failed starts expiring on the new value. There is already an implementation thread on ObjectStorageQueueTableMetadata.cpp:118; this comment is about the missing regression that would catch it.
| node.query(f"DROP TABLE {dst_table_name}") | ||
|
|
||
|
|
||
| def test_system_drop_ordered_mode_blocked(started_cluster): |
There was a problem hiding this comment.
This only proves the direct form. The public contract in ParserSystemQuery.cpp / system.mdx is unordered-only for SYSTEM DROP S3QUEUE FAILED FILES [db.]table [ON CLUSTER cluster_name], but every clustered test in this module creates unordered tables. If the ordered-mode guard regressed specifically in the distributed path, or started surfacing a different exception there, this suite would still pass.
Please add an ordered ... ON CLUSTER ... rejection case, or narrow the docstring to the local form. I did not find an existing review thread that covers the clustered ordered-mode entrypoint.
| `AzureQueue` and `S3Queue` are the very same `StorageObjectStorageQueue`; only the | ||
| object storage backend differs (createQueueStorage<StorageAzureConfiguration> vs | ||
| <StorageS3Configuration>, both going through the shared ObjectStorageQueueMetadata). | ||
| The failed_files_ttl_sec / SYSTEM DROP S3QUEUE FAILED FILES paths added in this PR |
There was a problem hiding this comment.
The docstring now says the new failed_files_ttl_sec / SYSTEM DROP S3QUEUE FAILED FILES paths are proved through AzureQueue, but the body only exercises a single-node direct SYSTEM DROP on instance. It never sets failed_files_ttl_sec, never waits for automatic TTL cleanup, and this module's second replica is not started with with_azurite=True, so none of the ON CLUSTER coverage can run through AzureQueue either. A regression in AzureQueue TTL cleanup or distributed drop would still merge green.
Please either narrow the claim to "direct manual drop on AzureQueue" or add at least one AzureQueue TTL / clustered-drop regression. A broader AzureQueue coverage thread already existed on docs/reference/statements/system.mdx:941, but the test added to resolve it still leaves these surfaces unpinned.
…ailed-file-ttl-113054 # Conflicts: # docs/reference/statements/system.mdx # src/Parsers/ParserSystemQuery.cpp
…113054' into feature/s3queue-failed-file-ttl-113054
Yes, let's do this way. I see this PR grew noticeably, let's may be split it in parts so that it will be easier to review? For example system command and failed_file_ttl_sec are independent features, may be something else could be split. I'd first split the smaller parts out. It will really speed up the merge. Also do not hesitate to push back on what bot can sometimes ask, it can ask too much over reasonable. |
|
Update: Phase 1 split into two smaller PRs Following the review feedback, Phase 1 of this change has been split into two smaller pull requests: Split 1 — PR #121752:
Split 2 — PR #125392:
PR #121760, the earlier PR for Split 2, has been closed as superseded by PR #125392. Please use #125392 for further review and testing. Dependency: Split 2 depends on Split 1 (#121752), since it builds on the failed-file state-management functionality introduced there. Both splits together represent Phase 1 of the original change. The original issue and overall scope remain unchanged. |
Related to #113054
failed_files_ttl_secconfiguration to clean up failed files independently of
tracked_file_ttl_sec.Existing tables keep their previous failed-file retention behavior after
upgrade — no action needed unless you want failed-file cleanup on a new or
recreated table.
Previous Behavior (master): Setting
tracked_file_ttl_secimplicitly enabledTTL-based cleanup for both successfully processed files (
/processednodes) andfailed files (
/failednodes).New Behavior (this PR):
tracked_file_ttl_secnow cleans only/processednodes;
failed_files_ttl_seccleans only/failednodes. Existing tables thatalready had
tracked_file_ttl_secset retain their previous failed-filecleanup behavior via a legacy fallback, so no migration is required for them.
Migration: Only relevant for new tables, or existing tables you recreate,
that want failed-file cleanup alongside
tracked_file_ttl_sec:Check if a table would benefit from explicit configuration:
Scope of this PR (Phase 1, as discussed in the issue):
failed_files_ttl_secsetting (default: 0, disabled), reusing the existing cleanup thread andcleanup_interval_min_ms/cleanup_interval_max_mscadence, followingthe same pattern as
tracked_file_ttl_sec.SYSTEM DROP S3QUEUE FAILED FILES db.tablefor full, on-demand clearingof the failed set. Shares the same distributed lock as the periodic
cleanup sweep to avoid races, and clears both Keeper znodes and the
in-memory cache.
ordered mode support and
LIKE 'prefix/%'pattern filtering are plannedfor a follow-up PR (Phase 2), per the scoping discussion in the issue.
Not closing #113054 with this PR since Phase 2 work remains.
Changelog category
Backward Incompatible Change
Changelog entry
Added
failed_files_ttl_secfor unordered S3Queue/AzureQueue tables to removeterminal failed files from Keeper after a configurable TTL, and
SYSTEM DROP S3QUEUE FAILED FILESto clear them manually. Existing tables keep theirprevious failed-file retention after upgrade; only new tables or recreated
tables that want failed-file cleanup alongside
tracked_file_ttl_secneed toset
failed_files_ttl_secexplicitly.Workflow [PR]
Sync PR [sync-upstream/pr/113784]