Skip to content

Make RestorerFromBackup use its own context copy, not the live query context - #108765

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-restore-uses-own-context
Jul 1, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-restore-uses-own-context

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Documentation entry for user-facing changes

Not applicable — internal backup/restore robustness change.


What & why

Background RESTORE workers (RestorerFromBackup::createDatabase / createTable, scheduled on the RESTORE thread pool) copied the live query context via Context::createCopy(query_context). For a RESTORE ASYNC query the originating thread can still touch that same Context after the query has returned — most notably the server-side AST fuzzer (executeASTFuzzerQueries), which resets merge_tree_transaction in its query-finish callback. The background copy then reads merge_tree_transaction under Context::mutex while the originating thread writes it unsynchronized → the TSAN data race seen on BuzzHouse (amd_tsan):

WARNING: ThreadSanitizer: data race
  Write  ...  DB::Context::setCurrentTransaction  <- executeASTFuzzerQueries (caller thread)
  Read   ...  DB::ContextData::ContextData(const&) <- Context::createCopy
              DB::RestorerFromBackup::createDatabase  (Restore_MakeDB worker)
SUMMARY: ThreadSanitizer: data race ... swap<DB::MergeTreeTransaction*>   (STID 3336-2c6d)

Fix

RestoreStarter already creates a dedicated restore_context copy that the restorer holds as context, precisely so background work does not depend on the live query context. This PR switches the remaining query_context uses in RestorerFromBackup (createDatabase, createTable, checkTable, checkAccessForObjectsFoundInBackup) over to that context, and drops the now-unused query_context member and constructor/doRestore parameter.

This resolves the long-standing in-code TODO: Get rid of using query_context in class RestorerFromBackup and the root cause @tavplubix asked for in review on #103158 ("async tasks shouldn't share the same context that can be used concurrently by other queries"). context is a copy made when the restore started and is only read on the worker threads, so concurrent Context::createCopy(context) calls are safe.

Relationship to #103158

This is the root-cause / read-side follow-up to #103158, which fixes the write side in the AST fuzzer (and skips fuzzing BACKUP/RESTORE). The two are complementary: with this change in place the background restore never touches the live query context regardless of what the originating thread does to it, so the same class of race cannot reappear from other post-query mutations. #103158 remains valuable on its own (the fuzzer should not clobber the caller's transaction).

No new test: the symptom is a sanitizer-only data race with no deterministic functional repro (same limitation noted on #103158); the BuzzHouse/TSAN jobs provide coverage.

Evidence on master

This race is not BuzzHouse-only — it also fired on the regular Stress test (amd_tsan) for a master commit (same STID 3336-2c6d, write side executeASTFuzzerQueries -> setCurrentTransaction, read side RestorerFromBackup::createTable -> Context::createCopy):

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=75154b382fe8161e14ef5c505b251ebb876d19a8&name_0=MasterCI&name_1=Stress%20test%20%28amd_tsan%29

(The remaining red Stress test (amd_tsan)/(arm_tsan) jobs on this PR are an unrelated Hung check flake that currently hits nearly every master tsan stress run since 2026-06-29; the data race STID 3336-2c6d no longer appears in this PR's runs.)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.364 (included in 26.7 and later)

…context

Background `RESTORE` workers (`createDatabase`/`createTable`, running on the
`RESTORE` thread pool) copied the live query context via
`Context::createCopy(query_context)`. For a `RESTORE ASYNC` query the originating
thread can still touch that same `Context` after the query has returned (for
example the server-side AST fuzzer resets `merge_tree_transaction` in its finish
callback), so the background copy reads `merge_tree_transaction` under
`Context::mutex` while that thread writes it -- the TSAN data race seen on
`BuzzHouse (amd_tsan)` (STID 3336-2c6d).

`RestoreStarter` already creates a dedicated `restore_context` copy that the
restorer holds as `context`, precisely so background work does not depend on the
live query context. Switch the remaining `query_context` uses in
`RestorerFromBackup` (`createDatabase`, `createTable`, `checkTable`,
`checkAccessForObjectsFoundInBackup`) over to `context`, and drop the now-unused
`query_context` member and constructor/`doRestore` parameter. This resolves the
long-standing `TODO: Get rid of using query_context in class RestorerFromBackup`
and the root cause raised in review on #103158 (background backup/restore tasks
must not share a `Context` that another query can mutate concurrently).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [024f574]

Summary: ✅


AI Review

Summary

This PR moves RESTORE background work off the live query context by making RestorerFromBackup use the restore-owned context copy, while explicitly sharing the original query's QueryPrivilegesInfo so system.query_log keeps the expected privilege accounting. I checked the current diff, surrounding restore startup/object creation paths, existing review threads, and the public PR CI report; I found no remaining blocker or major issue.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 28, 2026
@jkartseva jkartseva self-assigned this Jun 29, 2026
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
Comment thread src/Backups/BackupsWorker.cpp Resolved
alexey-milovidov and others added 3 commits June 29, 2026 20:49
Switching `RestorerFromBackup` off the live `query_context` regressed
`03315_query_log_privileges_backup_restore` (Fast test): the restore
worker now runs on `restore_context`, but `RestoreStarter` calls
`makeQueryContext` on that copy, which resets it to a fresh, empty
`QueryPrivilegesInfo`. As a result the access checks performed during the
restore (`checkAccessForObjectsFoundInBackup` and the `TABLE ENGINE` check
when creating tables from the backup) were recorded into the restore
context's own privileges object, while `system.query_log` reads the
privileges from the original query context, so the restore query's
`used_privileges`/`missing_privileges` columns became empty:

    -[]	['INSERT, CREATE TABLE ON default.d_03315_query_log']
    -['TABLE ENGINE ON MergeTree']	[]
    +[]	[]
    +[]	[]

Share the `QueryPrivilegesInfo` object of the original query context with
`restore_context` via a new `Context::setQueryPrivilegesInfo` helper, so the
privileges checked while restoring are accounted to the RESTORE query in
`system.query_log`, restoring the pre-change behavior. `QueryPrivilegesInfo`
has its own mutex and is not one of the context fields a concurrent
originating thread mutates, so sharing it does not reintroduce the data race
that moving the background workers off the live query context avoids.

CI report: #108765

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@jkartseva jkartseva 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

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr review of 98a2b60c)

This PR is green except for 3 stress jobs, and all three are the known hung-check flake (#107941), unrelated to this change. I downloaded and inspected each hung_check.log:

  • Stress test (amd_tsan) — the hung query is SELECT formatQuery($$SELECT [[[[…$$), a deeply-nested array literal stuck ~1505 s in DB::Field::dispatch / DB::Field::create recursion (single thread, is_cancelled = 1). No backup/restore/Context frames in the dump.
  • Stress test (arm_release) — the hung query is a trivial DESC TABLE numbers(2); the thread dump is dominated by idle BackgroundSchedulePool::threadFunction threads (saturated-server pattern). The only Backup frame is the routine idle SystemLog<DB::BackupLogElement>::savingThreadFunction() log writer — not the restore path.
  • Stress test (arm_tsan) — same "Hung check failed"; the only restore activity in the log is a successful CREATE TABLE … t_restore_archive_plain (restore working, not hung).

None of the three contain a RestorerFromBackup / BackupsWorker / Context::createCopy / setCurrentTransaction frame, so the context-ownership change is not implicated.

Notably, the job that originally caught the race this PR fixes — BuzzHouse (amd_tsan) — is now green, along with all other functional / integration / AST-fuzzer / unit jobs. AI Review is ✅ Approve and there are no unresolved review threads.

Not re-merging master: the merge-base is from 2026-06-29 23:39 UTC (< 1 day old) and the red checks are a known flake that a re-merge would not fix.

No code change required. Ready to merge pending a stress re-run or a maintainer override of the known hung-check flake.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr, 98a2b60c)

Two distinct red signals; one was a real build break that I fixed, the other is a known flake.

1. CH Inc sync — was genuinely build failed, now fixed

This was not a flake. Removing the query_context_ parameter from the BackupMetadataFinder constructor (the read-side root-cause change of this PR) broke two private-only subclasses that still passed the old 5-argument form, so the private build failed on amd_asan_ubsan/arm_asan_ubsan/arm_tidy/arm_darwin:

src/Backups/SnapshotUnlockerFromBackup.cpp:30:7: error: no matching constructor for initialization of 'BackupMetadataFinder'
src/Backups/SnapshotEntriesCollector.cpp:28:7: error: no matching constructor for initialization of 'BackupMetadataFinder'
note: candidate constructor not viable: requires 4 arguments, but 5 were provided

Fixed on the sync branch (ClickHouse/clickhouse-private PR #62543) by dropping the now-removed argument so both callers match the new 4-argument signature BackupMetadataFinder(restore_settings_, backup_, context_, thread_pool_) — mirroring the public RestorerFromBackup.cpp call. The two subclasses only used the base constructor; neither referenced the removed query_context member, so no other private code needed adaptation. The private CI is rebuilding with the fix.

2. Three Stress test jobs — known hung-check flake #107941 (re-triggered)

amd_tsan / arm_tsan / arm_release all failed with Hung check failed, possible deadlock found (#107941). The amd_tsan dump is the recurring server-side AST-fuzzer hang on a deeply-nested array literal stuck in DB::Field::dispatch / executeASTFuzzerQueries recursion — no RestorerFromBackup / BackupMetadataFinder / Context::createCopy / setCurrentTransaction frame, so this change is not implicated. I re-ran the three failed jobs (now queued/in-progress; all other stress configs are green).

The job that originally caught the race this PR fixes — BuzzHouse (amd_tsan) — is green, as are all other functional / integration / AST-fuzzer / unit jobs. AI Review is ✅ Approve and there are no unresolved review threads.

Not re-merging master: the merge-base is 2026-06-29 23:39 UTC (< 1 day old) and the remaining red was a build break (now fixed) plus a known flake, neither of which a re-merge would address.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes backup/RESTORE code paths — it drops the redundant query_context from the restorer classes and shares privilege accounting so RESTORE access checks show up in query_log. None of that touches the query-execution hot path a ClickBench SELECT exercises, so the flagged -14.23% (Q4) and -10.55% (Q5) improvements cannot plausibly be caused by this change; both are downgraded to not-sure as off-path run-to-run variance (Q4's baseline was also fairly noisy). No genuine, PR-attributable regressions or improvements were found.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 250 214 -14.2% <0.0001 PR only touches backup/RESTORE privilege accounting; cannot affect a ClickBench SELECT. Off-path improvement.
⚠️ 5 not_sure 379 339 -10.6% <0.0001 Same: RESTORE-only diff doesn't touch SELECT execution. -10.55% is run-to-run variance, not a PR effect.

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: 16345aba-2e5e-48c0-9227-c5ad3570d139
  • MIRAI run: fad8b294-9645-4c44-a8e0-ca1bd1d9440d
  • PR check IDs:
    • clickbench_595290_1782892264
    • clickbench_595296_1782892264
    • clickbench_595306_1782892264
    • tpch_adapted_1_official_595313_1782892264
    • tpch_adapted_1_official_595325_1782892264
    • tpch_adapted_1_official_595338_1782892264

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr, 98a2b60c) — the CH Inc sync build break is now fixed and confirmed green; everything else red is a known flake.

CH Inc sync — build break fixed, only flakes remain

The build break I fixed earlier (the private BackupMetadataFinder subclasses still passing the removed 5th query_context_ argument) is resolved on the sync branch (ClickHouse/clickhouse-private PR #62543). The four configs that failed to build now pass:

  • Build (amd_asan_ubsan) ✅, Build (arm_asan_ubsan) ✅, Build (arm_tidy) ✅, Build (arm_darwin) ✅

The sync run still has 3 red jobs, and all three are unrelated flakes (not the build break, not this change):

  • Unit tests (tsan, function_prop_fuzzer) — FunctionsStress.stress / AllTests. This is the randomized function-property fuzzer; it does not touch backup/restore. It is a master-wide flake spiking today: CIDB shows 71 failures across ~50 distinct PRs on 2026-06-30. The public copy of this exact job (Unit tests (tsan, function_prop_fuzzer)) is green on this PR.
  • Stress test (amd_tsan, SharedCatalog, meta in keeper) and Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) — both Hung check failed, possible deadlock found (Hung check failed, possible deadlock found #107941), the same Cloud-config form of the hung-check flake hitting nearly every tsan/asan stress run since 2026-06-29.

The remaining integration-test shards (amd_asan_ubsan, db disk) are still queued, so the sync job is PENDING; it can be re-run once the run completes.

Public stress — same #107941

Stress test (amd_tsan) and (arm_tsan) are the same Hung check failed flake (#107941). I re-inspected both hung_check.log dumps: the hung query is the server-side AST-fuzzer recursion (executeASTFuzzerQueries → DB::Field::dispatch), with no RestorerFromBackup / BackupsWorker / Context::createCopy / setCurrentTransaction frame, so this change is not implicated. BuzzHouse (amd_tsan) — the job that originally caught the race this PR fixes — is green, as are all other functional / integration / AST-fuzzer / unit jobs.

AI Review is ✅ Approve, jkartseva approved at the head commit, and there are no unresolved review threads. Not re-merging master: the merge-base is 2026-06-29 23:39 UTC (< 1 day old) and the remaining red is purely flaky, which a re-merge would not fix. No code change required — ready to merge pending a stress/sync re-run or a maintainer override of the known flakes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr, 98a2b60c) — the CH Inc sync integration jobs that were still queued last time have now finished; the two newly-red shards are an unrelated refreshable-MV flake, not this change.

CH Inc sync — integration shards finished, only flakes remain

The private sync run (ClickHouse/clickhouse-private #62543) completed. The four build configs stay green (the earlier BackupMetadataFinder build break is fixed). The remaining red jobs are all flakes with no connection to this PR:

  • Integration tests (amd_asan_ubsan, db disk, 6/7) and Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/7) — both fail only on test_refreshable_mv_no_multi_read::test_refreshable_mv_attach_without_multi_read:
    assert "Disabled" in status, status
    E   AssertionError: Scheduled
    E   assert 'Disabled' in 'Scheduled\t\n'
    
    This is a refreshable-materialized-view state-transition timing race (the view is still Scheduled when the assertion reads it, expecting Disabled) — the test's own comment and its two stabilization commits on 2026-06-25 (Stop refreshable MV gracefully on Keeper without MULTI_READ on ATTACH/restore, Wait for the scheduled pass before asserting view state) target this exact symptom. The "ATTACH/restore" there is server-restart re-attach (node.restart_clickhouse()); the test issues no BACKUP/RESTORE FROM and never touches RestorerFromBackup. This PR changes only backup/restore plumbing plus a query-privileges accessor, so there is no mechanism for it to affect refreshable-MV scheduling.
  • Unit tests (tsan, function_prop_fuzzer) — master-wide function-property fuzzer flake; the public copy of this job is green on this PR.
  • Stress test (amd_tsan, SharedCatalog, meta in keeper) and Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) — the known Hung check flake (#107941).

I re-ran the sync run's failed jobs to confirm the integration/fuzzer flakes are transient.

Public CI

Unchanged: green except Stress test (amd_tsan) and Stress test (arm_tsan), both the same Hung check flake (#107941, still open) with no RestorerFromBackup / BackupsWorker / Context::createCopy / setCurrentTransaction frames in the dumps.

jkartseva has approved, the AI review verdict is ✅ Approve, and there are no unresolved review threads. No code change is needed — all red signals are unrelated flakes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr) — re-merged master to validate against the evolved backup code and get a fresh CI run; no code change.

Re-merge (98a2b60c → 024f5746)

Departing from the earlier "not re-merging" note: the branch was 636 commits behind, the merge-base had aged past a day (2026-06-29 23:39 UTC), and—more importantly—master has since substantially evolved the exact file this PR touches, src/Backups/BackupsWorker.cpp, via the merged #108334 (jkartseva/backup-settings-observability: engine_settings in system.backups/system.backup_log). Re-merging validates that the context-ownership change still applies cleanly on top of that work and produces a fresh CI run to re-roll the known stress flake.

  • Merge was conflict-free.
  • Net diff vs master is unchanged: +34/-23 across the same 7 files. The RestoreStarter::setQueryPrivilegesInfo(query_context->getQueryPrivilegesInfoPtr()) accounting line, the doRestore signature (dropped query_context), and all RestorerFromBackup/BackupMetadataFinder call-site changes survived intact; the only movement is context-line shifts from Expose backup/restore settings in system.backups and system.backup_log #108334's additions in non-overlapping functions.
  • Verified no dangling references: the only remaining query_context uses are the legitimate BackupStarter/RestoreStarter members (kept, they own the ThreadGroup context), and no new caller of the removed 5-argument forms was introduced on master.
  • Compile-checked the three affected translation units (BackupsWorker.cpp, RestorerFromBackup.cpp, BackupMetadataFinder.cpp) against the merged headers — all pass. The Context::setQueryPrivilegesInfo addition in Context.h is purely additive.

Fresh CI is running on 024f5746.

Prior red signals (unchanged assessment)

  • Stress test (amd_tsan) / (arm_tsan) — the known Hung check flake (#107941), which is master-wide (CIDB: 531 failures across 183 PRs on 2026-06-30, incl. 53 on master trunk itself). The dumps are the server-side AST-fuzzer recursion (executeASTFuzzerQueries → DB::Field::dispatch) with no RestorerFromBackup / BackupsWorker / Context::createCopy / setCurrentTransaction frame — this change is not implicated.
  • CH Inc sync — the private BackupMetadataFinder build break was already fixed on the sync branch (ClickHouse/clickhouse-private Add asserts to COW example programs #62543); the remaining sync reds were unrelated flakes (function_prop_fuzzer, refreshable-MV timing, hung-check). The re-merge re-triggers the sync at the new head.

jkartseva approved, AI Review is ✅ Approve, and there are no unresolved review threads. Ready to merge pending the fresh CI (flake clear or a maintainer override of the known hung-check flake).

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 51/53 (96.23%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr, 024f5746) — the fresh CI on the re-merged head cleared the stress hung-check flakes; the two remaining reds are different, unrelated flakes, which I re-ran. No code change.

CI on 024f5746: 149 SUCCESS / 20 SKIP / 4 FAILURE / 1 PENDING

The four FAILUREs are two flaky jobs plus the two aggregate statuses they drive:

  • Integration tests (amd_msan, 8/8) — the single failure is test_rename_column/test.py::test_rename_distributed_parallel_insert_and_select: a NO_SUCH_COLUMN_IN_TABLE: num2 raised while the test's own concurrent RENAME COLUMN races a parallel distributed INSERT INTO … (num, num2) … (stack is DistributedSink → InterpreterInsertQuery::getSampleBlock, no RestorerFromBackup / BackupsWorker / Context frame). CIDB shows it flaking one-off across unrelated PRs over the last 14 days (this PR, Report cancellation instead of a network error for cancelled S3 requests #108673 = S3 request cancellation, Use LLVM-libc memory functions instead of glibc ones #107566 = LLVM-libc memcpy) — i.e. independent of PR content. This change touches only backup/restore plumbing and cannot affect a distributed rename.
  • Performance Comparison (arm_release, master_head, 6/6) — all 16 failing entries are marked unstable (noisy run-to-run timing), not regressions. Across all 6 shards the machine-readable metrics show no significant changes (3 faster / 7 slower / 10 unstable, all within noise), matching the Cloud report's ✅ no_change verdict. Backup/restore code is not on the ClickBench SELECT path.
  • Mergeable Check / PR — aggregate statuses computed from the two flaky jobs above.
  • CH Inc sync — PENDING (not failed).

The previously-red Stress test (amd_tsan) / (arm_tsan) (the #107941 hung-check flake) are green on this fresh run, and BuzzHouse (amd_tsan) — the job that originally caught the race this PR fixes — is green.

I re-ran the two flaky jobs (gh run rerun … --failed); they are re-queued.

jkartseva approved at the current head, AI Review is ✅ Approve, and there are no unresolved review threads. No code change required — ready to merge once the re-run clears the flakes (or a maintainer overrides them).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status update (continue-pr, 024f5746) — the re-run cleared the last flakes; the PR is now fully green. No code change.

Following up on the previous note ("ready to merge once the re-run clears the flakes"): that condition is now satisfied. The full status rollup is:

  • 154 SUCCESS / 20 SKIP / 0 FAILURE / 0 PENDING — no red, nothing in progress.
  • The two flaky jobs I re-ran are green: Integration tests (amd_msan, 8/8) (the test_rename_distributed_parallel_insert_and_select rename race) and Performance Comparison (arm_release, master_head, 6/6) (all entries were unstable, no regression). The aggregate Mergeable Check / PR statuses that they drove are now SUCCESS.
  • CH Inc sync = SUCCESS — the private BackupMetadataFinder build break (fixed on ClickHouse/clickhouse-private Add asserts to COW example programs #62543) stays resolved and the sync run's earlier integration/fuzzer flakes cleared on re-run.
  • BuzzHouse (amd_tsan) — the job that originally caught the STID 3336-2c6d data race this PR fixes — is green, and that race no longer appears.

jkartseva approved at the current head, the AI Review verdict is ✅ Approve (re-checked on 024f5746), and there are no unresolved review threads. The net diff is unchanged at +34/-23 across the same 7 files; merge-base is d584c4a2 (today, 2026-07-01 04:14 UTC, conflict-free), so no re-merge is needed. Ready to merge.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 1, 2026
Merged via the queue into master with commit bb069de Jul 1, 2026
342 of 344 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-restore-uses-own-context branch July 1, 2026 17:49
alexey-milovidov added a commit that referenced this pull request Jul 1, 2026
Re-merge master to pick up #108765 (RestorerFromBackup uses its own context
copy), which fixes the chronic transaction-context data race `ThreadSanitizer:
data race (STID: 3336-2c6d)` (tracking issue #101319) that was the sole public
test failure (Stress test amd_tsan) on the prior head. The branch was behind
and red, so re-merging is warranted.
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Switching `RestorerFromBackup` off the live `query_context` regressed
`03315_query_log_privileges_backup_restore` (Fast test): the restore
worker now runs on `restore_context`, but `RestoreStarter` calls
`makeQueryContext` on that copy, which resets it to a fresh, empty
`QueryPrivilegesInfo`. As a result the access checks performed during the
restore (`checkAccessForObjectsFoundInBackup` and the `TABLE ENGINE` check
when creating tables from the backup) were recorded into the restore
context's own privileges object, while `system.query_log` reads the
privileges from the original query context, so the restore query's
`used_privileges`/`missing_privileges` columns became empty:

    -[]	['INSERT, CREATE TABLE ON default.d_03315_query_log']
    -['TABLE ENGINE ON MergeTree']	[]
    +[]	[]
    +[]	[]

Share the `QueryPrivilegesInfo` object of the original query context with
`restore_context` via a new `Context::setQueryPrivilegesInfo` helper, so the
privileges checked while restoring are accounted to the RESTORE query in
`system.query_log`, restoring the pre-change behavior. `QueryPrivilegesInfo`
has its own mutex and is not one of the context fields a concurrent
originating thread mutates, so sharing it does not reintroduce the data race
that moving the background workers off the live query context avoids.

CI report: ClickHouse#108765

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-own-context

Make RestorerFromBackup use its own context copy, not the live query context
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.

3 participants