Skip to content

Fix data race on the packed skip-indices archive reader - #107995

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:fix-packed-skip-indices-reader-uaf
Jun 22, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:fix-packed-skip-indices-reader-uaf

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Fixes a rare data race and use-after-free on the cached per-part skp_idx.packed archive reader.

A query reading packed skip-index substreams (for example during ReadFromMergeTree::buildIndexes) obtains the cached PackedFilesReader via getSkipIndicesPackedReader and 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 in free.

The archive index is path-independent: moving the part's directory does not change the offsets inside the archive. So PackedFilesReader now holds only the immutable index, readFile takes 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):

  • Not for changelog (changelog entry is not required)

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 MergeTree part, which could happen when a query read skip indices while the part was being moved or renamed.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1104

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.
@Algunenano Algunenano self-assigned this Jun 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3c6f0a9]

Summary: ✅


AI Review

Summary

This PR changes PackedFilesReader so the cached reader owns only the immutable archive index, while callers pass the current archive disk/path at read time. It also keeps live cached readers across part relocation, clears cached null probes after relocation, and handles a concurrent packed-archive disappearance during probing. I found no remaining code-review findings in the current diff.

Missing context / blind spots
  • ⚠️ At review time, the Praktika report fetched for the PR showed no failed tests, but GitHub still listed Fast test, Build (arm_tidy), and the aggregate PR check as in progress. Completion of those checks would close this CI-status gap.
Final Verdict

Status: ✅ Approve

No inline findings remain. The previously open stale cached-miss thread is fixed by the current rename / changeRootPath code and has been resolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 19, 2026
@Algunenano Algunenano added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

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.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 251 205 -18.3% <0.0001 PR only touches packed skip-index reader internals; ClickBench Q15 aggregation doesn't exercise that path
⚠️ 28 not_sure 7027 6616 -5.8% <0.0001 Off-path: skip-index reader concurrency fix can't drive a 5.8% SELECT improvement; run-to-run variance
⚠️ 33 not_sure 1484 1398 -5.8% <0.0001 Off-path: query doesn't touch packed skip-index read path; consistent delta is variance, not the PR

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
  • StressHouse run: 3985b787-a054-42b6-a1a7-58e1e3f36a1a
  • MIRAI run: 8ae8cfd5-671e-480a-b02d-5f8d650a67a7
  • PR check IDs:
    • clickbench_96960_1782069419
    • clickbench_96974_1782069419
    • clickbench_96980_1782069419
    • tpch_adapted_1_official_96984_1782069419
    • tpch_adapted_1_official_96993_1782069419
    • tpch_adapted_1_official_96996_1782069419

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.
@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 70/84 (83.33%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@Algunenano
Algunenano enabled auto-merge June 22, 2026 08:16
@Algunenano
Algunenano added this pull request to the merge queue Jun 22, 2026
Merged via the queue into ClickHouse:master with commit 03fb1b9 Jun 22, 2026
166 checks passed
@Algunenano
Algunenano deleted the fix-packed-skip-indices-reader-uaf branch June 22, 2026 08:32
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 22, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 21, 2026
`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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants