Repository navigation
Fix silent overwrites by concurrent *_create_new_file_on_insert inserts and a data race on the path list - #114995
Conversation
…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.
Internal second-model review (click to expand)Four review rounds, each an independent cold read of the resulting code plus a second-model gate
Reviewed but not changed: the two-lock scheme and its ordering, the base-class wrapper split across Session id: cron:clickhouse-review-slot-9:20260816-055300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260816-044300 |
|
Workflow [PR], commit [9b80912] Summary: ✅
AI ReviewSummaryReviewed #114995 at Missing context / blind spots
Final VerdictStatus: ✅ Approve. No outstanding review findings; normal CI checks remain pending. |
|
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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units124 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. |
CI finish ledger - 8db3d06Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not a test failure, and the distinction is measured rather than assumed. The job's steps 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 |
|
@bharatnc or @arthurpassos can help reviewing this PR? |
…-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.
|
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
left a comment
There was a problem hiding this comment.
🤖 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 (
keysin S3,blobs_pathsin Azure,pathsin 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.
…age-path-list-race-3437-4fb8
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]>
|
Thanks, all three are done.
Local run (debug build, own MinIO, randomized settings): |
Algunenano
left a comment
There was a problem hiding this comment.
🤖 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::writeObjectthrowsUNSUPPORTED_METHODfor 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
INSERTfails. 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]>
*_create_new_file_on_insert inserts and a data race on the path list
|
Thanks, reworked as suggested in 3d7f19d.
The description is updated to match. |
|
@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]>
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]>
CI finish ledger - 9b80912Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261104-230006 |
fe459fb
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]>
Include the upstream S3 path-list race fix without changing the query-context accounting scope. The previous core run failed on ThreadSanitizer STID 5233-4bfc. Related: #114995 Related: #123112 CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=3a5afb647af4c784ea193d741ea03c598534388d&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29
Include the upstream S3 path-list race fix without changing the query-context accounting scope. The previous core run failed on ThreadSanitizer STID 5233-4bfc. Related: ClickHouse#114995 Related: ClickHouse#120422 CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120422&sha=3a5afb647af4c784ea193d741ea03c598534388d&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29
Closes: #90967
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed silent data loss when concurrent
INSERTs withs3_create_new_file_on_insert = 1(orazure_create_new_file_on_insert = 1) picked the same new file name, from one table or from different tables, servers ors3()queries on the same path: oneINSERToverwrote the other's rows with no error. The write is now conditional (If-None-Match: *), so theINSERTthat 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), STID3437-4fb8: report. Also seen on master (STID3437-4705) and as an ASan double-free (3448-4fc3).On released versions, two concurrent
INSERTs withs3_create_new_file_on_insert = 1derive the same<base>.<N>, both write it withWriteMode::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/setPathsare non-virtual base methods under a shared mutex, over protected*Implvirtuals with thread-safety annotations. A new name is appended to the current list (addPath), not written back from an earlier copy.*_create_new_file_on_insert(and no truncate), both sinks write withIf-None-Match: *. HDFS rejects conditional writes, so it keeps writing unconditionally.TRUNCATE(which keeps the list) everyINSERTrewrote the same file.Measured stores: SeaweedFS 4.48 (CI), MinIO
RELEASE.2025-09-07and 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.05497fails on master and passes 10/10 with the fix.Workflow [PR]
Sync PR [sync-upstream/pr/114995]
Version info
26.11.1.1669-master(included in26.11and later)