Skip to content

Fix silent overwrites by concurrent *_create_new_file_on_insert inserts and a data race on the path list - #114995

Merged
alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/objectstorage-path-list-race-3437-4fb8
Nov 8, 2026
Merged

alexey-milovidov merged 12 commits into
ClickHouse:masterfrom
groeneai:groeneai/objectstorage-path-list-race-3437-4fb8

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #90967

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):

Fixed silent data loss when concurrent INSERTs with s3_create_new_file_on_insert = 1 (or azure_create_new_file_on_insert = 1) picked the same new file name, from one table or from different tables, servers or s3() queries on the same path: one INSERT overwrote the other's rows with no error. The write is now conditional (If-None-Match: *), so the INSERT that loses the race fails with a precondition error and can be retried. HDFS is unchanged. Also fixed a data race on the path list of object storage tables.

Description

Found by La Casa Del Dolor (amd_tsan), STID 3437-4fb8: report. Also seen on master (STID 3437-4705) and as an ASan double-free (3448-4fc3).

On released versions, two concurrent INSERTs with s3_create_new_file_on_insert = 1 derive the same <base>.<N>, both write it with WriteMode::Rewrite, and both are acknowledged while one writer's rows are gone. Writers in one table also race on the shared path list (std::vector::operator=).

Fix:

  • getPaths/setPaths are non-virtual base methods under a shared mutex, over protected *Impl virtuals with thread-safety annotations. A new name is appended to the current list (addPath), not written back from an earlier copy.
  • With *_create_new_file_on_insert (and no truncate), both sinks write with If-None-Match: *. HDFS rejects conditional writes, so it keeps writing unconditionally.
  • The sink writes the probed base key when it is free. It used to write the last listed key, so after TRUNCATE (which keeps the list) every INSERT rewrote the same file.

Measured stores: SeaweedFS 4.48 (CI), MinIO RELEASE.2025-09-07 and Azurite 3.35 reject an existing key for both single and multipart/block-list uploads. Under 16 concurrent writers, SeaweedFS let two multipart completes of one key succeed in 2 of 25 rounds; PUT, and MinIO, had one winner in every round.

Concurrent INSERTs into one table that pick the same name now fail instead of succeeding: 6 of 8 in a burst.

05497 fails on master and passes 10/10 with the fix.


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

Version info

  • Merged into: 26.11.1.1669-master (included in 26.11 and later)

…location atomic

Two concurrent INSERTs into the same object-storage table performed an unsynchronized
read-modify-write on the configuration's path list. StorageObjectStorage::write() read the
list, derived the next file name from it, and published the result, while the accessors
were bare member reads and assignments. The configuration is created once when the table
is loaded and shared by every query, so two INSERT pipelines building their sinks ran that
sequence on the same vector. ThreadSanitizer reported it as a data race between an
asynchronous-insert flush thread and an ordinary query thread, both inside
std::vector::operator= on that member.

The vector race is only the sanitizer-visible half. The next name is <base>.<N> where N is
the length of the list the caller was handed, so the list's length is the name allocator.
With the base object present, two concurrent INSERTs both observe length 1, both derive
the same name, both find it free, and both open a sink for it with WriteMode::Rewrite: one
INSERT's rows silently replace the other's, and no error is reported. The publish is
last-writer-wins on top of that, so the list can also end up without a path that a file
was written to, making that data unreachable through the table.

Move the concurrency into the class that owns the state. getPaths() and setPaths() become
non-virtual base methods that take a shared mutex and delegate to protected getPathsImpl()
and setPathsImpl(); the five subclass bodies move across unchanged, so the Local
implementation keeps assigning its scalar path and a future subclass cannot reintroduce
the bug by overriding an accessor. All twelve DataLakeConfiguration instantiations inherit
the fixed behaviour, since that template overrides neither accessor. getPaths() now
returns by value, because handing out a reference into mutex-protected state protects
nothing; the four call sites already copied or bind through a range-for.

The allocate-derive-publish sequence moves into allocatePathForWrite(), serialized by a
second mutex taken only by writers. That keeps the existence probes, which are remote
requests, outside the list's lock, so a slow or retried S3 request cannot stall an
unrelated SELECT. The writer lock is always acquired before the list lock, and the list
lock is only ever taken inside the two accessors and released before they return, so no
cycle is constructible. The cost is that concurrent INSERTs into one table serialize one
existence probe per query, which is what atomic name allocation means.

The unused defaulted copy constructor of StorageLocalConfiguration is removed: a mutex
member makes it ill-formed if instantiated, and nothing copies that class.

This does not address the case where the base object does not yet exist. There the helper
returns no new name, so nothing is published and no name is reserved, and both writers use
the base path. Preventing that needs an in-flight reservation released on completion or
cancellation, which is a different mechanism: creating a sink creates no object, so
existence probing cannot observe a writer that has not uploaded yet.

The new test seeds the base object, then runs eight concurrent INSERTs, half of them
through the asynchronous insert queue, and asserts every row survived in a file of its
own. It fails on unpatched master, where seven of nine rows are lost.
…for real

Review round 1 follow-ups to the path-list serialization fix.

The test only ever reached the path list through the write path, which holds
path_allocation_mutex across the whole allocate-derive-publish sequence, so the
writer mutex alone serialized it and the locked accessors were never exercised
concurrently. That left untested the half the reported TSAN race is actually
about: one racing thread was a reader calling vector::size(). Concurrent readers
now run for the duration of the writer burst. They assert nothing and pass
s3_ignore_file_doesnt_exist, because a path is published before its object is
uploaded, so any row count they observed would be legitimately racy; the
post-wait assertions remain the oracle.

The async arm was also inert. executeQuery sets reason = "insert query has
select" for any INSERT .. SELECT and only queues when hasInlinedData() is true,
so --async_insert had no effect and the advertised async-flush-versus-query
thread pairing never occurred. The arm now uses VALUES, which is genuinely
queued (confirmed via system.asynchronous_insert_log). Exactly one such writer,
because several are batched into a single file and the distinct-file assertion
would stop being deterministic.

Wildcard-partitioned writes are out of scope: PartitionedStorageObjectStorageSink
derives its own per-partition name and never consults the path list, so the
allocator cannot cover it. A partitioned regression test is not possible here
either, since reading a partitioned S3 table raises NOT_IMPLEMENTED and the
observable outcome via a glob varies run to run, so any assertion would encode
data loss as expected. The bound is stated as a local invariant comment instead.
The readers looped until a marker file appeared, so a reader whose run was cut
short kept querying a database that had already been dropped. Observed as 273
UNKNOWN_DATABASE errors from leftover readers saturating the server until it
stopped answering. A fixed iteration count still overlaps the writer burst,
which is all the arm needs.
The next name for a create_new_file_on_insert write is derived from the length of
the configuration's path list, but the probing loop in
checkAndGetNewFileOnInsertIfNeeded walks past every candidate that already exists
remotely and returns only the last one. Only that winner was appended, so the list
stopped being a faithful allocator cursor whenever numbered objects existed
remotely without being in it: the length no longer accounted for the names the
probe had consumed, and the next writer derived one of them again. Both writers
then opened the same key with WriteMode::Rewrite and one insert's rows were lost
with no error, which is the outcome the surrounding change set exists to prevent.

The list reaches that drifted state from ordinary SQL. Dropping a plain S3 table
deletes no objects (StorageObjectStorage::drop forwards to the configuration,
whose base body is empty) while fromAST rebuilds keys as {url.key}, so one
DROP/CREATE, a server restart, or a second table over the same filename is
enough.

The helper now optionally reports the candidates it stepped over and the
allocator appends them before the winner, which restores the list to
base, base.1 ... base.<n> and makes its length a truthful cursor again. The
partitioned sink is the helper's only other caller and derives its own
per-partition name, so it keeps the previous behaviour through the defaulted
parameter.

Read visibility is unchanged: the appended names are objects the probe just
confirmed to exist, and both arms return the same rows.
The next name for a create_new_file_on_insert write is derived from the length of the
configuration's path list, but the probing loop in checkAndGetNewFileOnInsertIfNeeded
walks past every candidate that already exists remotely and returns only the last one.
When numbered objects exist remotely without being listed, the length no longer accounts
for the names the probe consumed, so the next writer derives one of them again, both
writers open the same key with WriteMode::Rewrite, and one insert's rows are lost with no
error.

The previous attempt at this appended the probed-and-skipped names to the list. That list
is not only the allocator cursor: the same accessor supplies the set of objects a read
enumerates and the set TRUNCATE removes. Existence is not provenance, so adopting a name
merely because an object answers to it put objects this table never wrote into the delete
set, and a truncate would then remove them.

A writer-side cursor keeps the allocator honest without touching either set. It records
the lowest sequence number no write has taken, the probe starts from the greater of that
and the list length, and only the name actually written is published. The list can now
have gaps, which is what lets the read set and the delete set stay exactly as they were.

A name that does not have the derived shape leaves the cursor alone, so a list holding
paths from some other source degrades to the previous behaviour rather than moving the
cursor to an unrelated number.

Extends 04911 with a truncate arm: with a numbered object present remotely and unknown to
the table, TRUNCATE must leave it readable.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Four review rounds, each an independent cold read of the resulting code plus a second-model gate
review. Round 4 gate: 0 findings. Earlier rounds found and fixed three substantive defects in my
own work, listed here because two of them changed what this PR claims.

# Finding Verdict
❌ Partitioned writes bypassed the allocator. write() returned the partitioned sink before the allocation, and createSinkForPartition derived its own deterministic name and opened it WriteMode::Rewrite, so the same silent loss survived for partitioned tables. Agreed. No shared list exists to serialize on in that design, so it cannot be fixed by this mechanism. Disclosed in the description as unfixed rather than left implied.
❌ The path list was not a truthful allocator cursor. The next name came from the list's length, but the probe walks past every numbered object that exists remotely without being listed. After a DROP/CREATE (which deletes no S3 objects and rebuilds the list as one element) two serialized writers still derived one name. Reachable from pure SQL; it is now test 04911. Agreed. Fixed with a writer-side cursor recording the lowest sequence no write has taken.
❌ The first fix for that reintroduced data loss. Recording the probed-and-skipped names into the list made the list name objects this table never wrote, and that same list is the set TRUNCATE deletes, so a truncate would have removed a foreign object. Agreed. Replaced by the cursor, which appends only the name actually written, leaving the read set and the delete set exactly as they are today. 04911 gained a truncate arm that fails on the rejected variant and passes here.
⚠️ The reader side of the reported race was untested. Every list access the writers made sat under the writer mutex, so the test would have passed even with the list accessors reduced to no-ops. Agreed. A reader arm was added, and a three-arm experiment settles it: locks intact, 0 reports in 5 runs; locks removed, a report whose read side is getPaths() reached from executeQueryImpl; same defective binary with writers only, 0 reports.
⚠️ A third case was not disclosed. Two concurrent INSERT INTO FUNCTION s3(...) queries build a configuration each (TableFunctionFactory.h:54, TableFunctionObjectStorage.cpp:131, and table_function_results is query-scoped at Context.h:572), so the new mutexes do not serialize them. Agreed. Pre-existing and out of a lock's reach for the same reason as the other two residuals. Now named in the description.
💡 Suggested the Critical Bug Fix category. Declined. Not claimed proactively; happy to change it if a maintainer prefers it.
💡 Suggested Closes for issue #90967. Declined. That issue proposes deprecating the numbered-file mechanism outright and raises the wildcard-partition interaction, which this PR discloses as unfixed. Related avoids closing an open design question.
💡 TSA_GUARDED_BY on the new cursor is expressible here, unlike the subclass path vectors. Noted, not done. The declaration states the invariant and the member has exactly two accesses, both inside the allocator under that lock.

Reviewed but not changed: the two-lock scheme and its ordering, the base-class wrapper split across
all five subclasses, by-value getPaths(), setSchemaHash on the unlocked internals. A base-arm-only
SIGSEGV was seen once during verification and is deliberately not claimed here, as it did not
reproduce and has no root cause.

Session id: cron:clickhouse-review-slot-9:20260816-055300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, two of them, both shipped as tests. (1) 04910: seed the base object with s3_truncate_on_insert = 1, then 8 concurrent INSERTs with s3_create_new_file_on_insert = 1, one of them via async_insert = 1, wait_for_async_insert = 1, which is the reported thread pairing. Unpatched arm fails every run; measured directly, count() = 2 and countDistinct(_file) = 2 where 9 and 9 are expected, rows [0,1] instead of [0..8]. (2) 04911: the same burst against a table whose path list is shorter than the set of numbered objects present remotely, reached from pure SQL by a DROP/CREATE, since dropping a plain S3 table deletes no objects while fromAST rebuilds the list as a single element. Unpatched master 6 of 6 fail, losing writers' rows outright.
b Root cause explained? StorageObjectStorage::write() read the configuration's path list, derived the next name from it and published the result, with no synchronization; the accessors were a bare member read and assignment. The configuration is allocated once under DatabaseOrdinary::loadTableFromMetadata and shared by every query, so two INSERT pipelines ran the sequence on the same vector, which is the reported race. The same non-atomicity is also a data-loss bug: the new name is <base>.<N> with N the length of the list the caller was handed, so two writers observing length 1 both derive <base>.1, both find it free, and both open a sink with WriteMode::Rewrite. Serializing alone is not sufficient, because the probing loop walks past names that exist remotely without being listed, so the length stops being a truthful cursor and two serialized writers can still derive one name.
c Fix matches root cause? Yes: the read-modify-write becomes atomic at the layer owning the state, rather than guarding the crash site. getPaths/setPaths become non-virtual base methods holding a shared mutex and delegating to protected *Impl virtuals; allocate-derive-publish becomes allocatePathForWrite() under a separate writer-only mutex; and a writer-side cursor records the lowest sequence number no write has taken, so a probe never restarts inside a range already consumed. Four alternatives were rejected, either as symptom guards or for trading one defect for another: deleting the write-back and cloning the configuration both lose data visibility, refuted empirically by 02302_s3_file_pruning; a mutex inside the accessors alone silences the sanitizer while leaving the duplicate-name data loss; and adopting the probed-and-skipped names into the list would have put objects this table never wrote into the set TRUNCATE deletes.
d Test intent preserved / new tests added? Two new tests, no existing test weakened. Both assert the data-loss consequence rather than a log string or a deleted count. 04911 uses countDistinct(a) and countDistinct(_file) rather than count(), because a duplicated name is listed twice, so the winner's row is counted twice while the loser's is gone and a plain count() still matches the expected total. 04911 also carries a truncate arm: with a numbered object present remotely and unknown to the table, TRUNCATE must leave it readable. Both are parallel-safe .sh tests scoped by ${CLICKHOUSE_DATABASE} with no no-parallel tag. Deliberately no assertion for the absent-base case: that is out of scope, so such an assertion would be unsatisfiable by this diff.
e Both directions demonstrated? Yes, on identity-asserted binaries, and each arm reddens for the right reason. Fix arm Build ID 1f0927abdc5b8f74075eeaf4cbb0dc8e7a7cd4a0, asserted equal to SELECT lower(buildId()) on the server under test before every verdict. 04910: unpatched 12 of 12 fail, fix 60 of 60 pass. 04911: unpatched master 6 of 6 fail, fix 100 of 100 pass under randomized settings. Each of the two assertions in 04911 was shown to redden on its own arm: on master the name-allocation line fails, and on a binary carrying the rejected adopt-the-skipped-names variant the truncate line fails 9 of 9 while the allocation line passes, which is the discrimination that arm exists to make. Its non-vacuity was checked by inverting the assertion to count() = 0 on the fix arm, which fails, so the arm observes a real object rather than an empty read.
f Fix is general across code paths? The lock lives in the single non-virtual base wrapper rather than being duplicated per subclass, so all five path-list implementations are covered (S3::keys, Azure::blobs_paths, HDFS, Local, Web), and all twelve DataLakeConfiguration instantiations inherit it since that template overrides neither accessor. Verified no subclass still overrides the now non-virtual getPaths/setPaths. Every consumer of the list was treated as a carrier, not just the reported write path: the SELECT iterator sites, and truncate(), which iterated the shared vector by reference. That last one is why only the name actually written is ever published: the list is simultaneously the allocator cursor, the read set and the delete set. setSchemaHash uses the unlocked internals because it runs from the storage constructor before sharing, which also avoids re-entering a non-recursive lock. Two sibling mechanisms are disclosed and deliberately not fixed: the partitioned sink, which has no shared list to serialize on, and the absent-base-object collision.
g Fix generalizes across inputs? Type wrappers are N/A: in-memory control state, no columns or values. Axes covered instead: all five storage backends by construction; sync and async INSERT in the same test, the reported pairing; the seeded-base case (fixed) versus the absent-base case (out of scope, stated); a list consistent with remote state versus one that has drifted behind it (04911); truncate_on_insert, which early-returns before the derive and is unchanged; and the {_schema_hash} init path, where 04004_s3_schema_hash passes and passes promptly, which is the no-deadlock evidence. The name parser was exercised standalone across 7 base-key shapes, including extensionless, multi-dot, leading-dot and digit-bearing stems, and 12 malformed inputs; it fails closed, leaving the cursor at the list length, so a list holding paths from another source degrades to the previous behaviour instead of jumping to an unrelated number.
h Backward compatible? Yes. No new setting, no changed default, so no SettingsChangesHistory.cpp entry; no on-disk or serialization format change; no new error path. Two behaviour changes, both inherent to allocating names atomically: concurrent INSERTs into one table now serialize a single existence probe, and the sequence numbers a table hands out can skip values when objects already exist remotely, so the list may contain gaps. Reads and truncates are unaffected by those gaps because only written names are published. StorageLocalConfiguration's unused defaulted copy constructor is removed, since a mutex member makes it ill-formed if instantiated and nothing copies that class.
i Invariants and contracts preserved? The invariants: every access to the path list is serialized; allocate-derive-publish is atomic with respect to other writers; and the list names only objects this table wrote. Lock order is stated and enforced by construction: the writer mutex is always acquired first, and the list mutex is taken only inside the two accessors and released before they return, so it is never held while acquiring anything else and no cycle is constructible. The list mutex is never held across a remote request, which is why a slow S3 HEAD cannot stall a SELECT. getPaths() returning by value removes the escaping-reference hazard; the only site that bound the reference is a range-for, which gets lifetime extension. The cursor is guarded by the writer mutex, which is the only lock held while it is read or written. Subclass semantics are unchanged because the bodies moved verbatim, including Local's scalar-path assignment, and that assignment still happens on every publish that changes the list.

Session id: cron:clickhouse-impl-slot-4:20260816-044300

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b80912]

Summary: ✅


AI Review

Summary

Reviewed #114995 at 9b809124b05fd1a4b2e950edfa9f68d88a2719f6, including all prior discussion. The PR synchronizes the shared object-storage path list and uses conditional writes to prevent concurrent INSERT operations from silently overwriting one another on supporting backends. No new actionable findings. The previous post-TRUNCATE write-selection finding is fixed and its thread is resolved.

Missing context / blind spots
  • ⚠️ CI for the reviewed head is still running; functional bugfix validation and the S3 TSan jobs are pending. Their completion will provide independent confirmation of the author's reported before/after regression results. Tests were not rerun locally during this review.
Final Verdict

Status: ✅ Approve. No outstanding review findings; normal CI checks remain pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @kssenii, could you review this? Two concurrent INSERTs into one non-partitioned object-storage table derived the same new file name from the shared path list and both opened it with WriteMode::Rewrite, so one writer's rows silently replaced the other's, and the unsynchronized read-modify-write on that list is the reported ThreadSanitizer data race. The list accessors move into the base class behind a shared mutex, and allocate-derive-publish runs under a separate writer-only mutex with a cursor, so the existence probes stay off the list's lock.

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9b809124b with master 6398cafb6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of cdf882f5d; 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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.09 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +102.3 s (+9%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8db3d06

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6) runner-level wedge, not a test failure: the Run step ran 111 minutes and was killed without publishing a result #112984 (mine, open)

Not a test failure, and the distinction is measured rather than assumed. The job's steps Run and
Post Checkout code both end at conclusion: null (killed mid-step, not failed by a step), every
artifact for the shard is HTTP 403 (job.log, the shard result json, the run log), and CIDB holds
zero rows for this shard at this head while the sibling 6/6 shard published normally. There is also
no xdist session-timeout marker anywhere on this head, which is the discriminator between the
runner-wedge class owned by #112984 and the separate CORE_BLOCKING session-timeout class.

Not caused by this PR: no test ran, so no test result is attributable to the diff.

Session id: cron:our-pr-ci-monitor:20260816-170000

@PedroTadim

Copy link
Copy Markdown
Member

@bharatnc or @arthurpassos can help reviewing this PR?

@bharatnc bharatnc self-assigned this Aug 17, 2026
@bharatnc
bharatnc requested a review from kssenii August 17, 2026 08:18
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 4, 2026
…-4fb8

Resolved src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h: master added
checkFormat() to the protected section where this branch added the getPathsImpl/
setPathsImpl pure virtuals. Both are kept; the declarations are independent.
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Dear @bharatnc, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

…-4fb8

Resolved src/Storages/ObjectStorage/StorageObjectStorageConfiguration.cpp: master added
tryGetDiskConfigurationPrefix() at the spot where this branch added the anonymous namespace
with parseAllocatedSequence(). Both are kept; the definitions are independent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@Algunenano Algunenano 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.

🤖 The approach looks right: locking in the base-class getPaths/setPaths, and holding path_allocation_mutex across the whole allocation so two concurrent INSERTs can't pick the same name. Two requested changes before merge:

1. Add thread-safety annotations to the new mutexes.

  • next_write_sequence → TSA_GUARDED_BY(path_allocation_mutex).
  • The path list in each subclass (keys in S3, blobs_paths in Azure, paths in HDFS/Local/Web) → TSA_GUARDED_BY(paths_mutex).
  • getPathsImpl → TSA_REQUIRES_SHARED(paths_mutex), setPathsImpl → TSA_REQUIRES(paths_mutex).

The member annotations will flag the places that still write the list directly: S3 fromAST/fromDisk/initializeFromParsedArguments, the Local and HDFS initialization code, the Web constructor and fromAST, and setSchemaHash calling the *Impl functions without the lock. Please route all of them through the locking setPaths, not TSA_NO_THREAD_SAFETY_ANALYSIS. The lock is uncontended during setup, and nothing then depends on "this runs before the configuration is shared", which right now is only a comment.

2. Return the sequence number from checkAndGetNewFileOnInsertIfNeeded instead of parsing it back.
The function already increments sequence_number in its probe loop and then throws it away. Make the parameter size_t & (in/out) and the cursor update becomes next_write_sequence = sequence_number;. That removes parseAllocatedSequence, its fallback for names that don't parse, and the ReadHelpers.h include. The only other caller, in StorageObjectStorageSink.cpp, can pass a local variable.

The branch also needs to merge master: createSink has changed there since this PR (it now has a data lake branch first), and the test numbers 04910/04911 may be taken by now.

groeneai and others added 2 commits November 4, 2026 01:10
Review follow-up:

- `paths_mutex` is now protected, so each subclass declares its path list
  (`keys`, `blobs_paths`, `paths`) `TSA_GUARDED_BY(paths_mutex)`, and the
  `getPathsImpl`/`setPathsImpl` overrides carry `TSA_REQUIRES_SHARED` /
  `TSA_REQUIRES`. `next_write_sequence` is `TSA_GUARDED_BY(path_allocation_mutex)`.
- Every place that wrote the list directly during initialization (S3
  `fromAST`/`fromDisk`/`fromNamedCollection`, HDFS `setURL`, Local
  `fromAST`/`fromNamedCollection`, Web `setRawPath` and
  `initializeFromParsedArguments`) and `setSchemaHash` now go through the
  locking `setPaths`/`getPaths`, so correctness no longer depends on these
  running before the configuration is shared.
- `checkAndGetNewFileOnInsertIfNeeded` takes the sequence number by reference
  and leaves it one past the name it returns, so `allocatePathForWrite` stores
  it directly instead of parsing it back out of the key. This removes
  `parseAllocatedSequence` and the `ReadHelpers.h` include.
- Tests renumbered to 05497/05498, the 04910/04911 numbers are taken on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, all three are done.

  1. Thread-safety annotations (87dac77): paths_mutex is now protected, the list in each subclass (keys, blobs_paths, paths) is TSA_GUARDED_BY(paths_mutex), the getPathsImpl/setPathsImpl overrides carry TSA_REQUIRES_SHARED/TSA_REQUIRES, and next_write_sequence is TSA_GUARDED_BY(path_allocation_mutex). Every direct writer goes through the locking setPaths: S3 fromAST/fromDisk/fromNamedCollection, HDFS setURL, Local fromAST/fromNamedCollection, Web setRawPath/initializeFromParsedArguments, and setSchemaHash (back to getPaths/setPaths). No TSA_NO_THREAD_SAFETY_ANALYSIS. To check the annotations are live, I restored one unlocked keys = ... write, one getPathsImpl() call outside the lock and one next_write_sequence read outside its mutex: each fails the build with -Wthread-safety-analysis.
  2. checkAndGetNewFileOnInsertIfNeeded takes size_t & sequence_number, the cursor update is next_write_sequence = sequence_number;, and parseAllocatedSequence, its fallback and the ReadHelpers.h include are removed. StorageObjectStorageSink.cpp passes a local (same commit).
  3. Merged master (881fac4), no conflicts. allocatePathForWrite stays after the data lake and partition_strategy branches of createSink. The tests are renumbered to 05497/05498.

Local run (debug build, own MinIO, randomized settings): 05497/05498 pass 10/10 each and fail 6/6 on a current master build; 02302_s3_file_pruning, 04004_s3_schema_hash and 02703_storage_s3_race pass.

@Algunenano Algunenano self-assigned this Nov 4, 2026

@Algunenano Algunenano 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.

🤖 Thanks for finding this. The diagnosis is right: the path list is effectively the name allocator, and concurrent writers overwrite each other. I'd fix it differently, though.

The mutex only works within one process. Two tables pointing at the same URL (on one server or several), or two INSERT INTO FUNCTION s3(...) queries, each have their own configuration object, mutex and next_write_sequence. They still derive the same <base>.N and silently overwrite each other with WriteMode::Rewrite. The PR description lists the s3() case as left open, but cross-table and cross-server writers are the common way to share a bucket path, and they aren't covered.

It also serializes INSERTs. path_allocation_mutex is held across the exists HEAD probes: about 2 round trips per INSERT, and N after a restart because the cursor is in memory only. Concurrent INSERTs into one table now queue behind each other, and a slow or retrying endpoint stalls all of them.

Suggestion: make the write itself atomic. The plumbing already exists. WriteSettings::object_storage_write_if_none_match is honoured by WriteBufferFromS3 (PutObject and CompleteMultipartUpload), by Azure and by LocalObjectStorage, and Iceberg already uses it (DataLakes/Iceberg/Utils.cpp). In StorageObjectStorageSink the change would be roughly:

auto write_settings = context->getWriteSettings();
if (create_new_file)
    write_settings.object_storage_write_if_none_match = "*";
auto buffer = object_storage->writeObject(
    StoredObject(path), WriteMode::Rewrite, std::nullopt, DBMS_DEFAULT_BUFFER_SIZE, write_settings);

createSink would then be back to an unlocked probe. A writer that loses the race gets a precondition-failed error instead of silently destroying another writer's rows, and a retried INSERT probes again and picks the next free name. This covers every server, table and table function in one place, and the partitioned sink can do the same. With this, path_allocation_mutex, next_write_sequence and the size_t & change to checkAndGetNewFileOnInsertIfNeeded can go.

Two things to check:

  • HDFS: HDFSObjectStorage::writeObject throws UNSUPPORTED_METHOD for conditional writes, so HDFS needs either a create-without-overwrite or to stay as it is for now.
  • S3-compatible stores: some may not support conditional writes. If they ignore the header, we're back to today's behaviour; if they reject it, the INSERT fails. Either is better than silent data loss, but it's worth knowing which stores do which before enabling it by default.

The getPaths/setPaths locking for the TSan race is fine to keep, since it's a separate bug.

With `*_create_new_file_on_insert`, the sink now writes with `If-None-Match: *`,
so a writer that lost the race for a name gets a precondition error instead of
silently replacing the other writer's object. This also covers writers that do
not share a configuration object: other tables or servers on the same path, and
`INSERT INTO FUNCTION s3(...)`. The partitioned sink does the same. HDFS rejects
conditional writes, so it keeps writing unconditionally.

`createSink` is back to an unlocked probe, so `path_allocation_mutex`,
`next_write_sequence` and the in/out sequence number of
`checkAndGetNewFileOnInsertIfNeeded` are removed. The new name is appended to the
current path list (`addPath`) rather than written back from a copy taken before
the probe, which could drop a name appended concurrently by another writer.

The locking of the path list itself, which fixes the data race, is unchanged.

05498 tested the removed sequence cursor and is deleted; 05497 now accepts a
writer that loses the race and checks that every acknowledged INSERT is stored
and read back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix data race and silent data loss on the object-storage path list Fix silent overwrites by concurrent *_create_new_file_on_insert inserts and a data race on the path list Nov 4, 2026
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, reworked as suggested in 3d7f19d.

  • With *_create_new_file_on_insert (and no truncate), StorageObjectStorageSink and the partitioned sink now write with object_storage_write_if_none_match = "*". createSink is back to the unlocked probe; path_allocation_mutex, next_write_sequence and the size_t & change are gone. The getPaths/setPaths locking stays, and the new name is appended to the current list (addPath) rather than written back from the copy taken before the probe, so a concurrent writer's name is not dropped from what SELECT reads.
  • HDFS: left as it is, so it still writes unconditionally, as on master. Exclusive create looks possible (O_CREAT without overwrite, per the comment in HDFSObjectStorage::writeObject), but I can't validate it here.
  • Stores, If-None-Match: * on an existing key: SeaweedFS 4.48 (the CI store), MinIO RELEASE.2025-09-07 and Azurite 3.35 reject both a single upload and the multipart / block-list commit (PreconditionFailed / BlobAlreadyExists) and keep the original object. One gap: with 16 concurrent writers, SeaweedFS let two CompleteMultipartUpload of one key both succeed in 2 of 25 rounds. Single PUT on SeaweedFS, and both paths on MinIO, always had exactly one winner.
  • A lost race returns Code: 499 ... PreconditionFailed ... At least one of the pre-conditions you specified did not hold ... (S3_ERROR), and a retried INSERT picks the next free name. In a burst of 8 concurrent INSERTs into one table, 6 failed this way and both acknowledged rows were stored; on master the same burst loses acknowledged rows.
  • 05497 now accepts the losers, checks that every acknowledged INSERT is stored and read back, and adds a deterministic conflict between two s3() queries. It fails on master and passes 20/20. 05498 tested the removed cursor and is deleted.

The description is updated to match.

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Please fix conflicts

…age-path-list-race-3437-4fb8

Conflict in src/Storages/ObjectStorage/HDFS/Configuration.h: master added a
`read_only` member next to `paths`, which this branch annotates with
`TSA_GUARDED_BY(paths_mutex)`. Kept both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in a05b055. The only conflict was HDFS/Configuration.h: #112468 added read_only next to paths, which this PR annotates with TSA_GUARDED_BY(paths_mutex); I kept both. The PR's own diff is unchanged, and 05497 still fails on master and passes on the merged build.

The probe in `createSink` only checks the first path of the list, but the
sink wrote to the last one. `TRUNCATE` deletes every listed object and keeps
the list, so after `[data, data.1]` was truncated the next insert found `data`
free and wrote `data.1`; every insert after that picked `data.1` again and,
now that the write is conditional, failed with `PreconditionFailed` forever.
Before the conditional write the same inserts silently overwrote `data.1`.

The same happens when the base object is deleted outside the table, for
example by another table on the same path. Write the key that was probed;
`truncate_on_insert` keeps rewriting the last file as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9b80912

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (UNKNOWN_IDENTIFIER b) test fixture, not from this PR (it changes only the object storage insert path): its lines are retries of the all_1_1_1_2 mutation on the empty part that 04653 leaves after DETACH PART; seen on 25 PRs in 14 days #125293 (external, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log (ILLEGAL_DIVISION) test fixture, not from this PR: the remaining lines are the deliberately failing TTL merge of 05073_column_ttl_recompute_materialized (intDiv(100, x)); seen on 51 PRs in 14 days #127731 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #125293, #127731 (the owners of the rows above)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261104-230006

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 8, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Nov 8, 2026
Merged via the queue into ClickHouse:master with commit fe459fb Nov 8, 2026
369 of 370 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
alexey-milovidov added a commit that referenced this pull request Nov 9, 2026
Master merged #114995, which
guards the path list of `StorageObjectStorageConfiguration` with a
`SharedMutex` and `getPathsImpl` / `setPathsImpl`, and makes the writes of
`*_create_new_file_on_insert` conditional (`fail_if_exists`).

This branch already guards the same list with its own `paths_mutex` and
`getPathsUnlocked` / `getMutablePathsUnlocked` / `setPathsUnlocked`
accessors, needed for the reservations and the split tail. The resolution
keeps the accessors of this branch and drops the duplicate ones from
master (including `addPath`, superseded by `appendPath`), while keeping
master's `setPaths` calls in the backends. Master's conditional write is
kept: `StorageObjectStorageSink` takes `fail_if_exists` as its last
argument and applies it to every object it writes, both in
`StorageObjectStorage::createSink` and in the partitioned sink.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
qoega added a commit that referenced this pull request Nov 12, 2026
qoega added a commit to qoega/ClickHouse that referenced this pull request Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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 on StorageObjectStorageConfiguration::(get/set)Paths

7 participants