Skip to content

Fix race condition in MergeTreeRestartingThread - #68513

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-race-condition-restarting-thread
Aug 19, 2024
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-race-condition-restarting-thread

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

This closes #68512

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

@alexey-milovidov alexey-milovidov added the 🍃 green ci 🌿 Fixing flaky tests in CI label Aug 18, 2024
@robot-clickhouse robot-clickhouse added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 18, 2024
@robot-ch-test-poll4

robot-ch-test-poll4 commented Aug 18, 2024 •

Copy link
Copy Markdown
Contributor

This is an automated comment for commit a258b4f with description of existing statuses. It's updated for the latest CI running

✅ Click here to open a full report in a separate page

Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
BuildsThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integration tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success

@alexey-milovidov alexey-milovidov self-assigned this Aug 19, 2024
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 19, 2024
Merged via the queue into master with commit 66ef0d8 Aug 19, 2024
@alexey-milovidov
alexey-milovidov deleted the fix-race-condition-restarting-thread branch August 19, 2024 02:25
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2024
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 7, 2026
The previous commit made the attach-path call `restarting_thread.start(true)`, that is
`BackgroundSchedulePoolTaskInfo::activateAndSchedule`. That helper only tests `scheduled`,
so when the inline `run()` had already armed a delay it went on to `scheduleImpl`, which
cancels the pending delayed entry and enqueues the task for immediate execution instead.

Recovering the deactivated task does not need that. When the task is deactivated, `run()`'s
own `scheduleAfter` is refused and nothing is armed, so there is no delay to keep. When it is
not deactivated, `run()` has already chosen the interval: `zookeeper_session_expiration_check_period`
after a successful attempt, or `min(10000, 100 * (n + 1) * (n + 2) / 2)` ms after a failed one.
Cancelling it retried `tryStartup()` immediately on every attach-path startup, not only in the
window the previous commit fixes.

Replace the call with `ensureArmed`, which activates the task and then arms a retry through
`scheduleAfter(0, /*overwrite=*/false)`. With `overwrite` unset that call returns false while a
delay is already armed, so an interval `run()` chose is kept and only a refused re-arm is
replaced. `DistributedAsyncInsertDirectoryQueue` and `BackgroundJobsAssignee` already use the
same argument for the same reason. The call still happens after the inline `run()` returns, so
the ordering from ClickHouse#68513 is unchanged.

Measured on a failing attach-path startup whose task was never deactivated, with
`zookeeper_session_expiration_check_period` left at its default: the interval between the inline
attempt and the next one is 22.5 to 114.4 ms over five runs with the previous commit, against
121.6 to 149.4 ms over five runs with this one, which is the 100 ms first-failure backoff
`run()` selected. The subsequent intervals are 300, 600, 1000 and 1500 ms in both arms.

Both integration tests added by the previous commits still pass, and still fail when the fix is
reverted.
pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Aug 9, 2026
…h startup

A ReplicatedMergeTree table whose startup goes through
ReplicatedMergeTreeAttachThread could stay in readonly mode indefinitely,
rejecting every write with TABLE_IS_READ_ONLY. Recovery then depended on an
unrelated ZooKeeper session loss, a SYSTEM RESTART REPLICA, or a server
restart, rather than on the table's own retry.

BackgroundSchedulePoolTaskInfo::schedule and ::scheduleAfter both refuse a
deactivated task and return false, and ReplicatedMergeTreeRestartingThread
ignores that return value, so a rejected re-arm is silent.

When a startup attempt on the attach path throws after startBeingLeader,
startupImpl's catch calls restarting_thread.shutdown(false), which deactivates
the restarting task. ReplicatedMergeTreeAttachThread::run sees a hardware error
and retries, and the next attempt gets past startBeingLeader and enters the
from_attach_thread branch with the task still deactivated. The inline
restarting_thread.run() there therefore cannot re-arm itself on either outcome,
neither scheduleAfter(check_period_ms) on success nor
scheduleAfter(next_failure_retry_ms) on failure, and the following
restarting_thread.start(false) only cleared the deactivated flag without
enqueuing anything. The task was left activated but neither scheduled nor
delayed, that is, owned by no pool collection, so nothing retried the
activation and nothing armed the zookeeper_session_expiration_check_period
timer. A replica that did activate through this path silently lost its periodic
session-expiration check.

The ZSESSIONEXPIRED callback installed later in startupImpl does call
start(true), so an unrelated session loss can rescue the table, but only if one
happens to occur after this table subscribed. In the reported failure the only
session-expiry notify in the affected server process fired 91 ms before that
subscription, and belonged to a sibling table. The wedged table's restarting
task then logged nothing at all for the remaining 417 seconds of the run, while
the sibling's task logged its periodic scheduling line seven times at exact 60
second intervals.

Call start(true), that is activateAndSchedule(), which clears the flag and
enqueues under a single schedule_mutex hold. It runs strictly after the inline
run() returns, so the ordering introduced in ClickHouse#68513 to keep a pool thread from
entering run() concurrently is preserved. On a healthy first attempt the extra
scheduled run takes runImpl's early-return fast path and re-arms the periodic
check, measured on both a patched and an unpatched binary.

Two failpoints make the two-attempt sequence deterministic in
test_restarting_task_rearmed_after_failed_attach_startup, which asserts that
the task is owned by the pool while the replica is still readonly and that the
replica recovers once the injected failure is disabled. With the re-arm
reverted to start(false) it fails on that ownership assertion; with the fix it
passed every countable repetition, 60 of 60.
test_startup_with_small_bg_pool_partitioned, which reported this failure, is
unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🍃 green ci 🌿 Fixing flaky tests in CI pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition in ReplicatedMergeTreeRestartingThread

4 participants