Skip to content

Fix assertHasValidVersionMetadata exception when part directory is externally removed - #99399

Merged
Algunenano merged 4 commits into
ClickHouse:masterfrom
Algunenano:i99375
Mar 15, 2026
Merged

Algunenano merged 4 commits into
ClickHouse:masterfrom
Algunenano:i99375

Conversation

@Algunenano

@Algunenano Algunenano commented Mar 13, 2026 •

Copy link
Copy Markdown
Member

Summary

In CI, test 03915_intersecting_parts_rollback runs in parallel with tests that query system.columns (e.g., 00941_system_columns_race_condition). The race condition:

  1. Test 03915 creates a MergeTree table in an Ordinary database and does BEGIN TRANSACTION; INSERT, creating a part with non-prehistoric creation_tid
  2. A concurrent system.columns query captures shared_ptr<IStorage> to all tables, including this one
  3. Test 03915 does DETACH TABLE, then rm -rf on part directories as part of its normal intersecting-parts-rollback test procedure
  4. The system.columns query finishes and releases its shared_ptr — now the last reference to the storage
  5. Storage destructor fires, removeIfNeeded calls assertHasValidVersionMetadata, which tries to read txn_version.txt from the already-deleted part directory, returns false, and chassert fires

The fix: in assertHasValidVersionMetadata, when the version metadata file is missing, check whether the part directory itself still exists. If the directory is gone, there is nothing to validate — return true instead of false.

Also adds a regression test that reproduces this race.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99272&sha=8a1f5e87eee68b39005270be969516abd1fcbb48&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%202%2F2%29
#99272

Closes #99375
Closes #98949

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Low Risk
Low risk: changes only a debug-only validation path to tolerate externally deleted part directories, plus adds a race-focused stateless regression test.

Overview
Prevents chassert(assertHasValidVersionMetadata()) from aborting when txn_version.txt is missing because the entire part directory was removed externally; assertHasValidVersionMetadata() now treats a missing version file as valid if the part storage no longer exists.

Adds a stateless regression test (04039_assert_valid_version_metadata_race.sh) that reproduces the system.columns/DETACH race by deleting a part directory during concurrent metadata queries.

Written by Cursor Bugbot for commit e0140dd. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.684

…externally removed

When `system.columns` captures `shared_ptr<IStorage>` to a MergeTree table
in an Ordinary database with parts having non-prehistoric `creation_tid`,
and the table is DETACH'ed while its part directories are externally removed,
the storage destructor can fire with parts referencing deleted `txn_version.txt`
files, causing `chassert(assertHasValidVersionMetadata())` to fail.

The fix: when the version metadata file is missing, check whether the part
directory itself still exists. If the directory is gone, there is nothing to
validate -- return true instead of false.

Add a regression test that reproduces the race condition.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99272&sha=8a1f5e87eee68b39005270be969516abd1fcbb48&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%202%2F2%29

Closes ClickHouse#99375

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [427981d]

Summary: ❌

job_name test_name status info comment
SQLLogic test failure
Report & Thresholds failure cidb IGNORED

AI Review

Summary

This PR hardens assertHasValidVersionMetadata for Ordinary-database races where part directories or reused paths make on-disk transaction metadata unavailable or stale during teardown, and adds a regression test for the concurrent system.columns/DETACH scenario. I did not find high-confidence correctness, safety, or performance regressions in the final patch.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsHistory.cpp ➖
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 13, 2026

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM


$CLICKHOUSE_CLIENT --allow_deprecated_database_ordinary=1 -q "DROP DATABASE IF EXISTS ${db_name}"

echo "OK"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is printed if the client succeeded or not. Is it intended?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It doesn't matter. It was initially part of the script to reproduce it, but I kept it when migrating to a stateless test. I'll remove it

Algunenano and others added 2 commits March 13, 2026 17:53
Reduce concurrent `system.columns` queries from 20 to 5 to avoid OOM
under ASan, and wait per-PID to suppress bash "Killed" messages that
the test framework flags as stderr errors.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
When an Ordinary database reuses the same data directory path after
DROP + CREATE, the `txn_version.txt` file may belong to a different
incarnation of the part. In this case, the `creation_tid` on disk
won't match the in-memory state. This is not corruption — skip
validation instead of asserting.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.20% -0.10%

PR changed lines: PR changed-lines coverage: 0.00% (0/21, 0 noise lines excluded)
Diff coverage report
Uncovered code

@Algunenano
Algunenano added this pull request to the merge queue Mar 15, 2026
Merged via the queue into ClickHouse:master with commit 3915a2c Mar 15, 2026
158 of 159 checks passed
@Algunenano
Algunenano deleted the i99375 branch March 15, 2026 22:38
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 15, 2026
alexey-milovidov added a commit that referenced this pull request Mar 16, 2026
On object-storage disks (e.g. Azure), `readFileIfExists` can still throw
because `IMetadataStorage::getStorageObjectsIfExist` has a TOCTOU race:
`existsFile()` succeeds, then `getStorageObjects()` tries to read metadata
that was already deleted by a concurrent `rm -rf` of the part directory.

The existing fix from #99399 only handled the case where `readFileIfExists`
returns nullptr (local disk). This adds the same directory-existence check
in the catch block to handle the throwing case on object-storage disks.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99545&sha=a9ef26aeae01e50aab174ae4fb26d37b8e36cba6&name_0=PR&name_1=Stateless%20tests%20%28arm_asan%2C%20azure%2C%20parallel%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
if [ -n "$data_dir" ]; then
for d in "${data_dir}"all_*; do
[ -d "$d" ] || continue
rm -rf "$d"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Unfortunately, the test breaks the invariant of ReplicatedMergeTree, leading to inconsistency, detected by Stress test: assertHasValidVersionMetadata.

Doing rm manually is an illegal operation in tests. I will remove. The fix is good on its own.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Doing rm manually is an illegal operation in tests. I will remove. The fix is good on its own.

Hi @alexey-milovidov

In this case then, is there some "legal" way to test changes like this? Should we consider to implement one in the future?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Comment on lines +2235 to +2236
/// belongs to a different incarnation of the part (e.g., an Ordinary database
/// reusing the same data directory path after DROP + CREATE). There is nothing

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think this situation is not okay, and we should not handle it. Btw, how exactly does this happen? Looks like it should throw an exception if the data dir is not empty on table creation:

if (mode < LoadingStrictnessLevel::ATTACH && !getDataPartsForInternalUsage().empty() && !isStaticStorage())
throw Exception(ErrorCodes::INCORRECT_DATA,
"Data directory for table already containing data parts - probably "
"it was unclean DROP table or manual intervention. "
"You must either clear directory by hand or use ATTACH TABLE instead "
"of CREATE TABLE if you need to use those parts");

Comment on lines +2222 to +2223
/// The part directory may have been removed externally (e.g., between
/// DETACH and ATTACH in an Ordinary database). If the directory is gone,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

How did we get this IMergeTreeDataPart instance at all if the part dir was removed between DETACH and ATTACH? We would not load this data part on ATTACH if it was removed

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The part instance isn't from the ATTACH after rm -rf. It's from a previous ATTACH, held alive by system.columns's StoragePtrs. The sequence is:

  • ATTACH (loads part)
  • system.columns captures references in ColumnsSource.
  • DETACH
  • rm -rf
  • system.columns releases the reference
  • The destructor fires on the part whose directory is gone.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yes, I understand the problem, but I don't understand the comment:

The part directory may have been removed externally (e.g., between DETACH and ATTACH in an Ordinary database)

But in this case we would not load the removed data part. Also, it's not possible to detach and re-attach a table while some query is still using it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, the comment is wrong, because it was based in what the test was doing, but not what was triggering the assert (the destructor is delayed and being called at the end of the system.columns query).

I can adjust the comment, or since we've removed the tests deleting data (thinking it was ok doing so after detach returned) we can revert the change altogether (the test was already removed). WDYT?

@tavplubix tavplubix Mar 18, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think it's better to keep the check stricter given that the root cause is addressed by removing the inconsistent test. We also have some other asserts/logical errors that can be triggered by manual intervention into keeper or data on disk

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Perfect. I'll remove it then. Thanks for having a look!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

Logical error: 'assertHasValidVersionMetadata()' (STID: 2508-44a2) [CI crash] Double free or corruption in MergeTreeDataPartCompact

5 participants