Skip to content

Fix Kafka offset commit skipped when pipeline completes before cancel callback fires - #101217

Closed
azat wants to merge 2 commits into
ClickHouse:masterfrom
azat:fix-kafka-commit-on-shutdown
Closed

azat wants to merge 2 commits into
ClickHouse:masterfrom
azat:fix-kafka-commit-on-shutdown

Conversation

@azat

@azat azat commented Mar 30, 2026 •

Copy link
Copy Markdown
Member

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 Kafka offset commit skipped when pipeline completes before cancel callback fires

When DROP TABLE sets shutdown_called concurrently with a naturally completing pipeline, the offset commit was incorrectly skipped because the check at line 738 tested shutdown_called (a global flag) rather than whether the pipeline was actually cancelled.

The cancel callback polls every 100ms. If the pipeline finishes in the sub-millisecond window between writing a block and the next callback poll, the data is fully written to MergeTree but shutdown_called is already true, so the commit is skipped. On table recreation the consumer resumes from the last committed offset, re-reading messages that were already written — causing duplicates.

Track whether the cancel callback actually fired (cancelled flag) and only skip the commit when the pipeline was truly interrupted.

Regression introduced by #100388 @ c964e8e

Relevant logs:

2026.03.29 18:12:38.213836 [ 932 ] {} <Trace> StorageKafka (test.kafka_QRMOCX): Polled batch of 100 messages. Offsets position: [blockold[0:1600]]
2026.03.29 18:12:38.219505 [ 932 ] {} <Test> DedupInfo: Clone DeduplicationInfo 2039 from instance_id: 2038, sync, enabled, level SOURCE, rows/tokens 100/1, in block: rows/cols 0/10, tokens: 1:[data-hash<14668832234726696155_13389564701822897784>/source-id-empty/source-number-0::100], visited views: 1:[<empty>], retried view id: <empty>, original block id: <empty>, data_hashes: 14668832234726696155_13389564701822897784, unification_stage COMPATIBLE_DOUBLE_HASHES
2026.03.29 18:12:38.226820 [ 16 ] {d4bbd5c9-d59a-4b7e-863d-f2470caa7363} <Debug> executeQuery: (from 172.16.3.1:55538) (query 1, line 1) DROP TABLE test.kafka_QRMOCX SYNC (stage: Complete)
2026.03.29 18:12:47.939941 [ 634 ] {} <Trace> StorageKafka (test.kafka_QRMOCX): Polled batch of 100 messages. Offsets position: [blockold[0:1600]]
2026.03.29 18:12:47.943600 [ 634 ] {} <Test> DedupInfo: Clone DeduplicationInfo 2057 from instance_id: 2056, sync, enabled, level SOURCE, rows/tokens 100/1, in block: rows/cols 0/10, tokens: 1:[data-hash<14668832234726696155_13389564701822897784>/source-id-empty/source-number-0::100], visited views: 1:[<empty>], retried view id: <empty>, original block id: <empty>, data_hashes: 14668832234726696155_13389564701822897784, unification_stage COMPATIBLE_DOUBLE_HASHES

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101092&sha=246d165cac385dac5d10b74e71cddf422fec5a5e&name_0=PR&name_1=Integration+tests+%28amd_tsan%2C+2%2F6%29
#101092

… callback fires

When `DROP TABLE` sets `shutdown_called` concurrently with a naturally
completing pipeline, the offset commit was incorrectly skipped because
the check at line 738 tested `shutdown_called` (a global flag) rather
than whether the pipeline was actually cancelled.

The cancel callback polls every 100ms. If the pipeline finishes in the
sub-millisecond window between writing a block and the next callback
poll, the data is fully written to MergeTree but `shutdown_called` is
already true, so the commit is skipped. On table recreation the
consumer resumes from the last committed offset, re-reading messages
that were already written — causing duplicates.

Track whether the cancel callback actually fired (`cancelled` flag)
and only skip the commit when the pipeline was truly interrupted.

Regression introduced by c964e8e.

Relevant logs:

    2026.03.29 18:12:38.213836 [ 932 ] {} <Trace> StorageKafka (test.kafka_QRMOCX): Polled batch of 100 messages. Offsets position: [blockold[0:1600]]
    2026.03.29 18:12:38.219505 [ 932 ] {} <Test> DedupInfo: Clone DeduplicationInfo 2039 from instance_id: 2038, sync, enabled, level SOURCE, rows/tokens 100/1, in block: rows/cols 0/10, tokens: 1:[data-hash<14668832234726696155_13389564701822897784>/source-id-empty/source-number-0::100], visited views: 1:[<empty>], retried view id: <empty>, original block id: <empty>, data_hashes: 14668832234726696155_13389564701822897784, unification_stage COMPATIBLE_DOUBLE_HASHES
    2026.03.29 18:12:38.226820 [ 16 ] {d4bbd5c9-d59a-4b7e-863d-f2470caa7363} <Debug> executeQuery: (from 172.16.3.1:55538) (query 1, line 1) DROP TABLE test.kafka_QRMOCX SYNC (stage: Complete)
    2026.03.29 18:12:47.939941 [ 634 ] {} <Trace> StorageKafka (test.kafka_QRMOCX): Polled batch of 100 messages. Offsets position: [blockold[0:1600]]
    2026.03.29 18:12:47.943600 [ 634 ] {} <Test> DedupInfo: Clone DeduplicationInfo 2057 from instance_id: 2056, sync, enabled, level SOURCE, rows/tokens 100/1, in block: rows/cols 0/10, tokens: 1:[data-hash<14668832234726696155_13389564701822897784>/source-id-empty/source-number-0::100], visited views: 1:[<empty>], retried view id: <empty>, original block id: <empty>, data_hashes: 14668832234726696155_13389564701822897784, unification_stage COMPATIBLE_DOUBLE_HASHES

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101092&sha=246d165cac385dac5d10b74e71cddf422fec5a5e&name_0=PR&name_1=Integration+tests+%28amd_tsan%2C+2%2F6%29
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@azat
azat requested a review from alexey-milovidov March 30, 2026 13:04
@azat azat mentioned this pull request Mar 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c2e74e]

Summary: ❌

job_name test_name status info comment
Fast test error
Build (amd_debug) error
Build (amd_asan_ubsan) error
Build (amd_tsan) error
Build (amd_msan) error
Build (amd_binary) error
Build (arm_debug) error
Build (arm_asan_ubsan) error
Build (arm_tsan) error
Build (arm_msan) error

AI Review

Summary

This PR fixes a real Kafka offset-commit race by switching the commit guard from global shutdown_called to a local cancelled flag that tracks whether cancellation was actually requested by CompletedPipelineExecutor. The fix direction is correct, but merge should wait for a targeted regression test that validates the exact DROP TABLE/natural-finish interleaving to prevent recurrence.

Findings
  • ⚠️ Majors
    • [src/Storages/Kafka/StorageKafka.cpp:751] The fix covers a narrow timing race, but there is no regression test that reproduces the specific interleaving described in the PR (pipeline fully writes, then shutdown is observed). This is fragile and likely to regress.
    • Suggested fix: add an integration test that forces shutdown near batch completion and verifies offsets are committed when pipeline finishes naturally (no duplicate reread after table recreate).
Tests
  • ⚠️ Add an integration regression test for the DROP TABLE vs pipeline-finish race in Kafka ingestion, asserting that completed batches are committed and not reread as duplicates after restart/recreate.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add a deterministic regression test for this race to lock in the intended commit semantics.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 30, 2026
@azat
azat requested a review from antaljanosbenjamin March 30, 2026 13:06
{
if (shutdown_called.load())
{
cancelled = true;

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.

There is still a race window where cancelled can become true even though the pipeline has already completed successfully.

Concrete trace with interactive_timeout_ms = 100:

  1. In CompletedPipelineExecutor::execute, tryWait(100) returns false at line 89 (timeout).
  2. Immediately after that, worker thread finishes, sets is_finished = true and finish_event.set() at lines 50-51.
  3. Main thread then executes this callback, sees shutdown_called == true, sets cancelled = true, and calls cancel() at lines 92-95.
  4. streamToViews returns, cancelled stays true, and we skip source->commit() even though data was fully written.

So this can still reproduce duplicate re-reads in a narrow timing window. Please gate cancelled = true on confirmed interruption, not on "callback observed shutdown". One way is to move this state into CompletedPipelineExecutor (e.g. expose whether cancel actually won before finish) and use that result here.

@antaljanosbenjamin antaljanosbenjamin self-assigned this Mar 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.70% 76.70% +0.00%

Changed lines: 100.00% (21/21) · Uncovered code

Full report · Diff report

@azat
azat marked this pull request as draft April 2, 2026 17:50
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

/// `shutdown_called`, because the pipeline may have completed naturally before
/// the cancel callback had a chance to fire. In that case the data was fully
/// written and offsets must be committed to avoid duplicates on restart.
if (!cancelled)

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.

⚠️ This change addresses a narrow timing race, but there is still no regression test covering the exact DROP TABLE/pipeline-finish interleaving described in the PR. Without such a test, this path is likely to regress again.

Please add an integration test that exercises shutdown during a batch where data can be fully written before cancellation polling observes shutdown_called, and assert offsets are committed (no duplicate reread after recreate).

@azat azat closed this Apr 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants