Skip to content

S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command - #125392

Open
adityaksolves wants to merge 36 commits into
ClickHouse:masterfrom
adityaksolves:feature/s3queue-system-drop-failed-files-clean-113054
Open

adityaksolves wants to merge 36 commits into
ClickHouse:masterfrom
adityaksolves:feature/s3queue-system-drop-failed-files-clean-113054

Conversation

@adityaksolves

@adityaksolves adityaksolves commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES [db.]table [ON CLUSTER cluster] [LIKE 'pattern'] command to manually clear terminal failed-file entries from Keeper, either all of them or only those whose file path matches the pattern (substring match, as in SQL LIKE).

Detailed Description

This is Phase 1 of splitting PR #113784 into smaller pull requests, following reviewer feedback.

Adds the SYSTEM DROP S3QUEUE FAILED FILES command for S3Queue / AzureQueue tables:

  • Allows users to manually clear tracked failed-file entries from Keeper.
  • Validates that the specified table uses the supported object storage queue engine.
  • Checks SYSTEM FLUSH OBJECT STORAGE QUEUE access for both local execution and ON CLUSTER.
  • Integrates with the existing failed-file metadata management to remove failed-file tracking state.
  • Skips .retriable nodes, because they hold the retry counter of files that are still being retried.
  • Optional LIKE 'pattern' removes only the failed files whose stored file_path matches the pattern (likePatternToRegexp + re2::RE2::PartialMatch, consistent with InterpreterDropQuery::matchesLikePattern). An explicit empty pattern (LIKE '') is distinguished from an omitted filter (like_pattern is std::optional<String>, preserved through formatting and AST JSON serialization), so it matches no non-empty path and drops nothing.
  • LIKE is rejected with BAD_ARGUMENTS when partitioning_mode = 'hive', since NodeMetadata::file_path is not used there. Drop-all without LIKE works in hive mode.
  • Local failed-files cache entries are removed with the same generation-snapshot guard as cleanupTrackedNodes, and reconcileFailedFilesCache() runs at the end.
  • Keeps the command formatting separate from SYSTEM FLUSH OBJECT STORAGE QUEUE, so the failed-files command does not print a PATH argument.

This PR depends on PR #121752, which introduces the failed_files_ttl_sec setting and related failed-file state management.
Only the commits from ec16ad1 onwards (through a253551) are new in this PR; the rest come from #121752 and will disappear from the diff once it is merged.

Bug fixed in this PR: the first version called cleanupTrackedNodes(..., ttl = 0, limit = 0) expecting "0 means drop all". After #121752 that call returns early (and hits chassert(check_nodes_limit || check_nodes_ttl) in debug builds), so the command deleted nothing. dropFailedFiles now has its own implementation.

Tests (test_failed_files_ttl.py):

  • test_system_drop_failed_files_removes_terminal_nodes: drop-all removes terminal failed nodes.
  • test_system_drop_failed_files_like_filter: two failed files; LIKE '' and an anchored prefix (alpha%) drop nothing, LIKE '%alpha%' removes only the matching one, LIKE '%bad.csv' removes the rest, and a plain drop works on an empty set.
  • test_system_drop_failed_files_requires_access: a user without the grant gets ACCESS_DENIED; a user with SYSTEM FLUSH OBJECT STORAGE QUEUE on the table succeeds.

Not in this PR


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

Adds the failed_files_ttl_sec engine setting, which controls time-based
expiry of terminal failed files in unordered mode. tracked_files_limit's
description is also updated to document that it caps the failed-files
set by count in both ordered and unordered mode, independently of the
new setting.

For tables created before this setting existed, the value is inherited
from tracked_file_ttl_sec at attach time; this inheritance is a one-time
fallback and is not kept in sync with later changes to tracked_file_ttl_sec.
…ck in hash-ring path; fix retriable marker test helper
@adityaksolves

Copy link
Copy Markdown
Contributor Author

@kssenii This is the second split from #113784 and depends on #121752. Could you please approve the workflows so CI can run? Thanks!

@george-larionov george-larionov added the can be tested Allows running workflows for external contributors label Oct 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f46a2a0]

Summary: ✅


AI Review

Summary

This PR adds SYSTEM DROP S3QUEUE FAILED FILES with optional LIKE filtering for object storage queues. At head f46a2a087197e50d1175e037efaeedd7236c5945, recovery can still stall across replicas, and the stacked changes retain a commit race and an upgrade incompatibility. One genuinely new finding is reported inline; seven remaining concerns from prior discussions are retained below with the author's deferrals respected.

Missing context / blind spots
  • ⚠️ No tests were run locally. The head-pinned Praktika report fetch did not expose matching test_failed_files_ttl cases. Focused integration output for this head would close the execution gap.
Findings

❌ Blockers

  • Active ownership must protect a successful commit. ObjectStorageQueueIFileMetadata.cpp:413 terminalizes .retriable without atomically checking that the processing node is absent. Another replica can remove a marker already referenced by an owner's successful commit, causing ZNONODE after rows have been inserted and allowing duplicates on replay without deduplication. Add an ownership check to the terminalization multi. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4263950054] The processing gate discussed in S3Queue: clear stale .retriable marker on terminal failure and skip terminalization while processing #125565 is absent from this head, so the race remains.

  • Upgrades must preserve failed-file expiry for existing ordered queues. ObjectStorageQueueMetadata.cpp:1391 restricts failed-file TTL to unordered mode. Legacy metadata still inherits tracked_file_ttl_sec into failed_files_ttl_sec, but an ordered table with a positive TTL and tracked_files_limit = 0 now retains terminal failures indefinitely. Preserve the old expiry behavior for existing tables or provide a compatibility setting. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4267379203] The current mode gate still prevents the inherited TTL from running, with no setting to restore it.

⚠️ Majors

  • A cleared failure must not block a later retry cycle through stale local state. ObjectStorageQueueIFileMetadata.cpp:615, 661 accepts an under-budget Keeper count but then rejects the file using an exhausted cached count. With loading_retries = 3, A can retain Failed/retries = 3 while B clears the terminal node and creates a new .retriable marker with count zero. A skips the file even if B stops and the object is repaired; reconciliation preserves the stale entry because the retry marker exists. Synchronize the cached retry state safely and fix both batched and single-file claim paths. New inline finding.

  • Cluster cleanup must complete on replicas sharing a Keeper path. ObjectStorageQueueMetadata.cpp:2024 immediately throws LOGICAL_ERROR when another replica or periodic cleanup owns the lock. Advertised ON CLUSTER execution therefore fails on a contending host, which also never reconciles its cache. Use bounded lock acquisition or verified completion followed by reconciliation. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4263950060] Explicitly deferring contention does not make the supported cluster command reliable at this head.

  • Batched claims must not serialize a Keeper round trip per fresh file. ObjectStorageQueueIFileMetadata.cpp:639 calls the synchronous isRetriableMarkerExhausted inside the locked claim-building loop. With hash-ring filtering and a 1,000-file batch, this adds 1,000 sequential reads before the claim multi or first file is returned. Batch these checks with the existing reads. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4263950067] The single-path read remains in the current loop; no measurement establishes an acceptable ingestion cost.

  • Background cleanup must avoid scanning the entire cache for every deletion. ObjectStorageQueueMetadata.cpp:1608, 1640 still uses predicate-based CacheBase::remove once per deleted path, producing O(deleted_files × cached_files) work while holding the cache mutex needed by ingestion. Apply keyed conditional removal or one generation-checked pass per batch. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4267379216] The manual command was fixed, but the explicitly deferred background branches still perform whole-cache scans.

  • Changing the retry limit must not abort the first failure's commit. ObjectStorageQueueIFileMetadata.cpp:1014, 1030 can observe loading_retries = 0 after the earlier nonzero read selected the retryable branch. On a first failure, it then removes a nonexistent .retriable node and aborts the multi with ZNONODE. Only remove a marker actually found, and make the decision from a consistent setting snapshot. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4270221624] The proposed fix in S3Queue: clear stale .retriable marker on terminal failure and skip terminalization while processing #125565 is not present here; removal remains unconditional.

  • A raised retry budget must govern an unclaimed file. ObjectStorageQueueIFileMetadata.cpp:371, 490, 602 uses constructor-time max_loading_retries rather than live loading_retries_ref. Raising the limit from two to five after metadata construction can still terminalize a live marker with count two, discarding the newly permitted retries. Read the live limit and revalidate exhaustion before terminalization. [dismissed by author -- https://github.com/S3Queue: add SYSTEM DROP S3QUEUE FAILED FILES command #125392#discussion_r4271988843] The author confirms the window and defers the fix; the stale snapshot remains at this head.

Tests
  • ⚠️ Add the two-replica cleanup/retry-handoff case described above and a shared-path ON CLUSTER completion case; single-replica deletion tests do not prove recovery across independent caches.
  • ⚠️ Cover active-owner terminalization, the first-failure transition to zero, and raising the budget after metadata construction with deterministic synchronization. object_storage_queue_pause_before_new_file_claim already supports the last case.
  • ⚠️ Attach an ordered table from metadata without failed_files_ttl_sec and verify its terminal failure beyond the processed pointer expires. test_1.py:509 removes the old ordered reprocessing assertion rather than establishing compatibility.
  • ⚠️ Measure fresh-file claim latency with remote Keeper and cleanup scaling with a populated cache to quantify the sequential reads and repeated cache scans.
Final Verdict

❌ Block. Minimum actions: protect active processing ownership during terminalization, preserve legacy ordered failure expiry, make cross-replica recovery honor Keeper's retry state, and handle shared-path cluster cleanup contention. Integrate the deferred dependency fixes before relying on their behavior, and close the focused regression and performance evidence gaps above.

@george-larionov

Copy link
Copy Markdown
Member

My agent is worried about an RBAC issue: "dropS3QueueFailedFiles has no access check for local execution (only the ON CLUSTER path checks, and with the broad SYSTEM_FLUSH). Please add context->checkAccess(AccessType::SYSTEM_FLUSH_OBJECT_STORAGE_QUEUE, table_id) as in flushObjectStorageQueue, use the same type in getRequiredAccessForDDLOnCluster, and add a negative test for a user without the grant.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 13, 2026
@adityaksolves

Copy link
Copy Markdown
Contributor Author

Added checkAccess(SYSTEM_FLUSH_OBJECT_STORAGE_QUEUE) for local execution and aligned the ON CLUSTER access type with it (b6fd981). Added a negative test for a user without the grant plus a positive test with the grant (57a0a3f).

Comment thread src/Parsers/ParserSystemQuery.cpp Resolved
@adityaksolves

Copy link
Copy Markdown
Contributor Author

@kssenii @george-larionov Config Workflow is failing on both of the last two runs (14:52 and 14:58 UTC+5:30) in the Check CI DB step with Connection refused to play.clickhouse.com:443, so all other jobs are DROPPED. This looks like a CI infrastructure issue rather than a code issue. Could you please re-run the workflow (or check CIDB)? Latest commit: 4f894b1 (functional change is e948e86).

dropFailedFiles runs from the query thread and talks to Keeper without a Coordination component set, which hits the 'Current component is empty' logical error in debug/sanitizer builds. Set the component guard in both StorageObjectStorageQueue::dropFailedFiles and ObjectStorageQueueMetadata::dropFailedFiles, as the other ObjectStorageQueue Keeper entry points do.
return std::nullopt;
}
/// Keeper's live retry count is under the current limit: allow processing
/// to proceed below (covers e.g. a cold cache observing an in-progress retry).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Major — an old exhausted cache suppresses a new retry cycle after cleanup

This branch accepts Keeper's retry count but leaves file_status->retries unchanged. Consider two replicas sharing a Keeper path with loading_retries = 3: A exhausts a file and caches Failed with retries = 3; while A is idle, B runs SYSTEM DROP S3QUEUE FAILED FILES and fails the file once in a new cycle, creating a .retriable marker with retries = 0. The command clears B's local cache, but A retains its old entry.

When A next lists the file, getPathState returns Failed with Keeper's count of zero, so this branch falls through. However, hasNonProcessableState at line 661 still compares A's cached count of three and rejects the claim. The same problem exists in trySetProcessing at lines 502–503. reconcileFailedFilesCache also preserves this entry because the new .retriable node exists. If B becomes unavailable, A cannot take over the remaining retries, even after the object is repaired, until its cache entry is evicted or explicitly cleared.

Reconcile the cached retry state with the live marker under the processing lock, or otherwise ensure both claim paths use the validated Keeper retry decision instead of reapplying the exhausted cached count. Add a two-replica recovery test where the replica with the old exhausted cache must claim an under-budget retry from the new cycle after the other consumer stops.

@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f46a2a087 with master a7cd67c8d (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 555235bd4; 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

23 object files changed (+205.63 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp.o 884.63 KiB 989.64 KiB +105.01 KiB (+11.87%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorageQueue/ObjectStorageQueueIFileMetadata.cpp.o 632.04 KiB 687.61 KiB +55.58 KiB (+8.79%)

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

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::Aggregator::executeFrozen(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::_… new 183.40 KiB +183.40 KiB
programs/clickhouse-keeper DB::Aggregator::executeFrozen(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::_… new 183.40 KiB +183.40 KiB
programs/clickhouse-keeper DB::Aggregator::executeFrozen(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::_… 166.94 KiB removed -166.94 KiB (-100.00%)
programs/clickhouse DB::Aggregator::executeFrozen(std::__1::vector<COW<DB::IColumn>::immutable_ptr<DB::IColumn>, std::_… 166.94 KiB removed -166.94 KiB (-100.00%)
programs/clickhouse ProfileEvents::global_counters_storage 12.94 MiB 13.00 MiB +64.00 KiB (+0.48%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 12.94 MiB 13.00 MiB +64.00 KiB (+0.48%)

Job report

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-s3queue S3Queue/AzureQueue engines (queue-based ingestion from object storage). external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants