Repository navigation
Fix data race on the packed skip-indices archive reader - #107995
Conversation
The cached skp_idx.packed reader was reset on rename/changeRootPath while a concurrent query could be reading its index, causing a TSan data race and use-after-free. Make PackedFilesReader a path-independent, shared, immutable index: readFile now takes the archive's current (disk, path) from the caller, so relocation no longer needs to free the reader.
|
Workflow [PR], commit [3c6f0a9] Summary: ✅
AI ReviewSummaryThis PR changes Missing context / blind spots
Final VerdictStatus: ✅ Approve No inline findings remain. The previously open stale cached-miss thread is fixed by the current |
|
📊 Cloud Performance Report ✅ AI verdict: This PR is a correctness and concurrency fix for the packed skip-index reader: it makes the reader hold only an immutable, path-independent archive index and passes the disk and path at read time, eliminating a use-after-free when a cached reader is reseeded or a part is renamed concurrently. None of the three flagged ClickBench improvements (Q15 -18.3%, Q28 -5.8%, Q33 -5.8%) run through that path — these are plain aggregation/scan queries with no packed skip indices — so the deltas, although they look clean, cannot be attributed to this change and are treated as run-to-run variance. All three were downgraded to not-sure; no query-execution hot path is touched here. clickbenchFlagged queries (3 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
existsFile/getFileSize for a packed skip-index file open skp_idx.packed via getSkipIndicesPackedReader. On shared storage another replica can remove the archive between the existence check and the open, so the read throws NO_SUCH_KEY and existsFile propagates it (and the error is counted as a DiskS3NoSuchKeyError, which fails stress tests). Wrap the open in Expect404ResponseScope (so the 404 is not logged/accounted) and treat NO_SUCH_KEY as 'no archive present'. Reported in review of ClickHouse#105321.
S3Exception/Aws::S3::S3Errors are guarded by USE_AWS_S3 and absent in the fast-test build (no S3), so the previous catch did not compile. Use the generic public mechanism instead: Expect404ResponseScope (suppresses the DiskS3NoSuchKeyError accounting) plus a plain catch that re-checks existsFile -- treat the archive as gone if it no longer exists, otherwise rethrow.
A failed open can mean the archive was relocated (rename/changeRootPath no longer resets the probe state since the reader is path-independent), not removed. Caching probed=true with a null reader would then permanently hide the overlay even though it exists at the new path. Return without caching so the next access re-probes the current path; a genuinely absent archive is still cached via the existsFile-false branch, so this does not loop.
Close the remaining window: a probe running mid-rename can build packed_path from the old path, find no file (existsFile false, so the open is never attempted), and cache probed=true with a null reader; after rename updates the path that miss is served forever. On rename/changeRootPath, clear the cached probe state when the reader is null, so the next access re-probes the new path. A successfully-loaded reader is path-independent and is kept (not dropped), so no use-after-free.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 70/84 (83.33%) | Lost baseline coverage: none · Uncovered code |
`IMergeTreeDataPart::removeIndexMarksFromCache` runs from `clearCaches` during
part destruction and needs nothing but mark-cache key strings. It asked
`getDeserializedFormat`, i.e. "which substreams does THIS PART hold?", and for a
part whose skip indices are bundled into `skp_idx.packed` answering that performs
a real object-storage read:
removeIndexMarksFromCache
-> IMergeTreeIndex::getDeserializedFormat
-> indexFileExistsInChecksums (packed branch)
-> IDataPartStorage::existsFile
-> DataPartStorageOnDiskBase::getSkipIndicesPackedReader
-> PackedFilesReader ctor -> disk->readFile(skp_idx.packed)
When the blob has been reclaimed while its metadata entry survives, that read
fails and the error is rethrown: `getSkipIndicesPackedReader` decides
swallow-vs-rethrow by re-checking `disk->existsFile`, which on object storage is
metadata-only and so still answers "present". The exception escapes into
`removeIfNeeded`'s `catch (...)` -> `tryLogCurrentException`, which re-emits the
whole `Code: 499 ... The specified key does not exist` text at `<Error>` level,
and it aborts the substream loop so the remaining keys are never evicted.
Ask the static, I/O-free question instead. `IMergeTreeIndex::getPotentialSubstreams`
returns every substream any version of the index could have written, taking
neither a part nor a storage, so it cannot do part I/O by construction:
- default: `getSubstreams`
- minmax: `.idx2` (v2) and legacy `.idx` (v1); `getDeserializedFormat` and
`getAllSubstreamsInPart` already probe both, which is the evidence a part may
hold either
- text: `.idx` / `.dct` / `.pst` / `.pos`, with `.pos` unconditional. Whether a
part holds `.pos` is a property of that part, not of the current
`params.positions`, so the writer-side view would miss it after the index was
redefined without positions
Removing an absent key is a no-op (`CacheBase::remove`), so the superset costs
nothing, and the computed keys are unchanged: the
`getStreamNameOrHash(..., checksums)` / `.value_or(full_stream_name)` /
`getMarksFilePath` chain is byte-identical to the one `loadIndexMarksToCache`
uses when inserting.
This deliberately touches neither `getSkipIndicesPackedReader` nor
`getArchiveReaderForFile`. Swallowing the 404 there instead would revert
7346f47 and e9f818e (PR ClickHouse#107995), which made that path fail
closed because callers treat a null reader as authoritative and could then
hardlink `skp_idx.packed` while dropping packed substreams.
One intentional behaviour change: a part with an invalidated system column
previously skipped eviction entirely, because `getDeserializedFormat` reports
nothing for it and the caller did `if (!index_format) continue;`. Its keys are
now evicted too, so those parts no longer leak marks.
Validated on an object-storage disk with the packed object deleted under a live
metadata entry: the eviction-frame error appears 3/3 runs before the change and
0/3 after, while the unrelated part-load error stays present in both arms as a
positive control that the object really is gone. A mutant that reverts only the
caller while keeping the new API still reproduces it 3/3, so the two unit tests
pin the API and this repro covers the caller.
Fixes a rare data race and use-after-free on the cached per-part
skp_idx.packedarchive reader.A query reading packed skip-index substreams (for example during
ReadFromMergeTree::buildIndexes) obtains the cachedPackedFilesReaderviagetSkipIndicesPackedReaderand then dereferences it after the internal mutex has already been released. Concurrently, relocating the part (rename/changeRootPath) reset and freed that cached reader, so the reading thread could access a freed archive index. ThreadSanitizer reports this as a data race infree.The archive index is path-independent: moving the part's directory does not change the offsets inside the archive. So
PackedFilesReadernow holds only the immutable index,readFiletakes the archive's current(disk, path)from the caller, and the cached reader is handed out as a shared owning handle. Relocation no longer needs to free or rebuild the reader, which removes the race at its source.setRelativePath, which can repoint the storage at unrelated content, still drops the cached reader (now safely, since callers co-own it).Not for changelog since this isn't released
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a rare data race and possible use-after-free on the cached skip-index archive reader of a
MergeTreepart, which could happen when a query read skip indices while the part was being moved or renamed.Documentation entry for user-facing changes
Version info
26.6.1.1104