Skip to content

Authorize a restored view's external targets - #117423

Merged
jkartseva merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-restore-mv-target-access
Nov 7, 2026
Merged

jkartseva merged 12 commits into
ClickHouse:masterfrom
groeneai:fix-restore-mv-target-access

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #115351

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 a privilege check that RESTORE skipped: restoring a MATERIALIZED VIEW with an external TO target, or a TimeSeries table with external targets, needed no privilege on those targets, so the restored view could write into a table the user has no INSERT grant on. Restoring one now requires SELECT, INSERT on each external target, the same as CREATE MATERIALIZED VIEW ... TO .... Targets of objects the restore skips are exempt, since they are never created.

Description

RESTORE of backup metadata that is MATERIALIZED VIEW ... TO other_db.other_table checked no privilege on the TO target, so the restored view was an arbitrary write primitive: rows inserted into the user's own source table landed in a table they hold no INSERT grant on. External TimeSeries targets sit in the same list, reached the same way.

The backup need not be anyone else's. BACKUP authorizes only the original element names, while the per-element AS name drives the renaming DDLRenamingVisitor applies to create.targets, so BACKUP TABLE own.mv, TABLE own.dummy AS victim.ledger forges it from the user's own objects alone.

Root cause: createTableRestoredFromBackup runs InterpreterCreateQuery with setInternal(true), so getRequiredAccess returns nothing and the SELECT | INSERT requirement on create.targets never fires. checkAccessForObjectsFoundInBackup is the only gate left running as the real user, and did not read them. This mirrors getRequiredAccess there, which also covers the ON CLUSTER CHECK_ACCESS_ONLY pre-flight. The if (target_id) guard keeps inner-table views working, and the loop sits above the temporary-table branch so restored temporary tables are covered.

Targets are not required where nothing is created: under restore_replace_external_engines_to_null an external-engine database and every table under it are skipped. That gate and the skip share one predicate, so they cannot disagree.

This tightens grants, deliberately. Found by an internal security review; no public issue.

Left for later PRs: a restored database engine is not checked against TABLE ENGINE, a restored temporary object asks for CREATE_TEMPORARY_TABLE where CREATE requires CREATE_ARBITRARY_TEMPORARY_TABLE or CREATE_TEMPORARY_VIEW, and a skipped database still demands create grants it never uses.

05055_restore_mv_target_access covers the denial, a temporary TimeSeries target, the skipped-database exemption, that the setting does not lift the check elsewhere, that nothing is created, the granted-target and inner-table passes, and a CREATE-path control.


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

Version info

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

groeneai and others added 2 commits August 31, 2026 19:36
RESTORE of a table whose backup metadata is a MATERIALIZED VIEW with an
external TO target never checked any privilege on that target, so the
restored view became an arbitrary write primitive: rows inserted into the
user's own source table were written into a table they hold no INSERT
grant on. External TimeSeries targets (Samples, Tags, Metrics,
RecentSamples) live in the same create.targets list and were reachable
the same way.

The attacker does not need a backup produced by anyone else.
getRequiredAccessToBackup authorizes AccessType::BACKUP on the original
element names only, while the per-element AS name drives makeRenamingMap
and DDLRenamingVisitor rewrites create.targets with it. So
"BACKUP TABLE own.mv, TABLE own.dummy AS victim.ledger" forges a backup
whose view points at victim.ledger using no privilege on it at all.

Root cause: the restore path voids the create query's own authorization
and re-derives it by hand, and the hand-written version never read
create.targets. createTableRestoredFromBackup runs InterpreterCreateQuery
with setInternal(true), so getRequiredAccess() returns {} and the
SELECT | INSERT requirement it normally imposes on create.targets never
fires. checkAccessForObjectsFoundInBackup() is the only gate that still
runs as the real user, before anything is created, for all three
createTableRestoredFromBackup implementations at once, and it is also
what the ON CLUSTER CHECK_ACCESS_ONLY pre-flight evaluates.

The fix mirrors InterpreterCreateQuery::getRequiredAccess() verbatim at
that gate. The if (target_id) guard is load-bearing: ASTViewTargets::
setTableID appends a target only for a non-empty StorageID, so an
inner-table view carries its target as an inner engine plus inner_uuid
and is correctly skipped. The loop sits inside the existing
create_table != kMustExist block because under kMustExist createTable()
returns before doing anything and the backup's create query is only
compared, never executed, so requiring the target there would be a
spurious denial.

This tightens grants: restoring a view with an explicit external target
now needs SELECT, INSERT on that target. That is exactly what creating
the same view by hand already requires.

Same threat model and remedy as the existing local-target check on
RESTORE of a Remote engine in StorageDistributed.

Co-Authored-By: Claude Opus 5 <[email protected]>
Review round 1 found the previous commit incomplete inside its own contract.
checkAccessForObjectsFoundInBackup() short-circuits the temporary-database
branch with `continue` before the create query is bound, so the target loop
never ran for a restored `TEMPORARY TABLE`. InterpreterCreateQuery's
getRequiredAccess has no such asymmetry: its own target loop sits after its
temporary/non-temporary chain, so a direct
`CREATE TEMPORARY TABLE t ENGINE = TimeSeries METRICS <external>` does require
`SELECT, INSERT` on that target while the restore did not. Since this change
claims to cover a TimeSeries table with external targets, that gap was in
scope rather than a pre-existing residual.

Bind the create query and run the loop once, above the temporary branch, so
both shapes share a single loop and cannot drift apart again. The loop is
gone from its old position; there is no second copy. Requiring the target is
still gated on `create_table != kMustExist`, because under kMustExist the
backup's create query is only compared, never executed, so demanding the
target there would be a spurious denial. The hoisted dereference is safe:
table_infos has one insertion point, BackupMetadataFinder.cpp:312, whose next
line assigns create_table_query unconditionally from a parseQuery that throws
rather than returning null.

Two test arms were added, each with its own proof that it fails on a binary
lacking precisely the change it covers.

The first pins the SELECT half of the requirement separately. The forged
target held neither privilege and the diagnostic arm grepped only for
`INSERT ON <db>.dst`, so weakening the requirement to `AccessType::INSERT`
alone left the reference byte-identical. Granting INSERT and re-running now
asserts the denial still fires and names the SELECT it is missing, then
grants SELECT and asserts the same restore succeeds. The trailing REVOKE and
DROP keep the later positive arms meaning what they meant.

The second is the regression test for the hoist: a user granted only inside
their own database creates a temporary TimeSeries table, backs it up while
renaming its metrics target onto a table they cannot write, and the restore
must be denied naming that target. It needs `structure_only = 1`, because
backing up a temporary TimeSeries table otherwise fails on its own inner
samples table, which is an unrelated pre-existing limitation.

Comments in both files stay within 140 characters, measured rather than
estimated: the source comment is 124 including its indentation.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 31, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex) across two passes, plus my own cold
review of the resulting code, in each round, before it ran. Rows below are the findings that touch
the code, the test or the metadata a reviewer sees; verdicts are mine.

# Sev Finding Verdict Evidence / action
1 ❌ The temporary-table branch of checkAccessForObjectsFoundInBackup returns before the create query is read, so a restored TEMPORARY TABLE ... ENGINE = TimeSeries with external targets still skipped the new authorization AGREE, fixed in this PR Confirmed by reading. RestorerFromBackup.cpp continued out of the loop before binding create, so the new target loop could not run for a temporary element, while InterpreterCreateQuery::getRequiredAccess has no such asymmetry: its create.targets loop sits after its own temporary branch, so the direct CREATE of that same table does require SELECT, INSERT on the targets. The parser accepts TEMPORARY and parses the four TimeSeries target kinds in the same lambda with no exclusion; registerStorageTimeSeries does not reject a temporary table; backing up a temporary table requires no privilege at all; and the metadata finder applies the renaming map to every collected create query, so a temporary table's targets are rewritten by the same map that makes the reported forge work. The fix hoists one shared loop above the temporary branch, so the two shapes cannot drift apart again.
2 ⚠️ The test cannot distinguish SELECT, INSERT from INSERT alone, so a weaker requirement would leave it green, and no target kind other than a view's TO is observed AGREE in part, fixed in this PR The first half is correct: the denied target held neither privilege and the diagnostic assertion pinned only INSERT, so the assert was weaker than the stated contract. An arm now grants INSERT alone, asserts the restore is still denied naming SELECT, then grants both and asserts it succeeds; the mutation was run in both directions on binaries whose build IDs were asserted per arm. A temporary-target arm was added for finding 1. DISAGREE on enumerating all four TimeSeries kinds: the loop is kind-agnostic, so those arms would exercise ParserViewTargets rather than anything this change touches.
3 ❌ RESTORE ... ON CLUSTER could authorize a different database from the one an unqualified external target ends up using, because metadata may name TO target with no database, the initiator resolves it through its own current database, and the executing host qualifies it through its own DISAGREE Restated and tested step by step; two necessary steps fail. A server-produced backup cannot carry an unqualified target: InterpreterCreateQuery fills the current database into create.targets and mutates the AST that is then persisted, so stored metadata, and hence backed-up metadata, is always qualified. Forging an unqualified one needs write access to the backup bytes, which is the precondition this defect deliberately does not require. And the host that performs the write runs this same check itself, unconditionally in RestorerFromBackup::run and before any database or table is created, with the restore query's current database taken from that host's own context beforehand, so the context that authorizes is the context that qualifies. The initiator's pre-flight is an extra early check, which is why it walks every address in the cluster. The requirement is also the mirror's own semantics rather than a new one: getRequiredAccess is evaluated before qualification and forwards the same possibly-empty database to the same substitution. Rejecting unqualified targets on restore would make RESTORE stricter than the CREATE it is being made symmetric with, and would risk denying legitimate restores of older or foreign backups. I would rather not add a rule I cannot back with a reproducer.
4 💡 The added comment writes getRequiredAccess() and an unquoted CREATE, against the repository convention for literal SQL and function names AGREE, fixed in this PR Raised independently in my own review before the gate ran. The tracked in-tree rulebook asks for inline code blocks around literal SQL, class and function names, and for function names written without the call suffix. The four pre-existing comments in this file that use the f() form all predate that rulebook, so they are superseded rather than precedent.
5 💡 Critical Bug Fix (crash, data loss, RBAC) is the category the template assigns to an RBAC defect DISAGREE The category is not taken proactively here, only when a maintainer asks for it, and the in-repo precedent for this same function is the earlier restore-path access fix that shipped as Bug Fix. Happy to relabel if a maintainer would rather it were Critical.
6 💡 The new test carries no no-replicated-database tag, unlike the sibling restore access tests DISAGREE Checked on the mechanism rather than by matching the siblings. Their tag exists because the check they assert lives inside a storage or the interpreter, which on a replicated or shared-catalog database runs with no user, so their deny path silently allows. This check is the RESTORE pre-flight, running as the real user before any DDL is produced, so that mechanism cannot neuter it, and there is an untagged in-tree precedent for backing up and restoring a materialized view with an external TO target. Separately, the two TimeSeries tests that do carry the tag carry it because ATTACH or DETACH of a TimeSeries table hangs waiting on the replicated DDL log; this test does neither, and its only TimeSeries object is temporary, so it never enters that log. The rulebook asks for no no-* tag that is not strictly necessary.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Also checked and found clean, so a reviewer does not have to re-derive it. ENGINE = Backup is not
a second carrier of this primitive, because its attach loop skips a create query with no storage
clause and any engine whose name does not end in MergeTree, and a view with an external TO
target has no storage clause. Hoisting the create-query binding above the temporary branch is
null-safe: the map it reads has exactly one writer in the restore path, which assigns that field
unconditionally from a parse that throws rather than returning null, and the pre-existing code
already dereferenced it unconditionally for every non-temporary element. One gate covers all three
createTableRestoredFromBackup implementations and the ON CLUSTER pre-flight, because the access
check is unconditional in RestorerFromBackup::run and precedes the check-access-only return. The
regression surface of the grant tightening is one file: of every test in either suite that runs
RESTORE as a non-superuser, only the one added here involves a materialized view or a TimeSeries
table, and the integration arm that does restore a view with an external target runs as default.

@clickhouse-gh clickhouse-gh Bot closed this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9106339]

Summary: ✅


AI Review

Summary

The PR requires SELECT, INSERT on external targets when restoring a MATERIALIZED VIEW or TimeSeries table, including temporary tables, and exempts targets belonging to skipped databases. The target check addresses the reported write primitive. No genuinely new inline findings were identified at 91063393942c2812ed650add2601665ede9c5e1e. Four previously reported concerns remain in the current code; they are preserved below with their existing discussions and explicit scope dispositions.

Missing context / blind spots
  • ⚠️ The current-head CI workflow was still running: targeted stateless tests and functional bugfix validation were pending. No local runtime tests were run. Completed results for 05055_restore_mv_target_access would close this current-head validation gap.
Findings

The following findings predate this patch. The author explicitly defers them to follow-up work; none is being posted again inline.

❌ Blockers

  • RestorerFromBackup.cpp:475: Non-Memory temporary tables bypass their creation privilege. Restoring one requires only CREATE_TEMPORARY_TABLE, whereas direct creation requires CREATE_ARBITRARY_TEMPORARY_TABLE. A user holding the former and the engine grant, without any CREATE TABLE grant that would imply the latter, can restore an otherwise forbidden temporary table. [dismissed by author -- https://github.com/Authorize a restored view's external targets #117423#discussion_r3900444245] Still real: the current branch remains unconditional, and internal creation bypasses getRequiredAccess. Follow-up: mirror the engine-sensitive privilege split and test the restricted user.

  • RestorerFromBackup.cpp:367: Restored database engines bypass TABLE ENGINE authorization. When engine grants are enforced, a user with CREATE DATABASE can restore a database using an engine that direct creation would deny. The preflight adds no engine grant, and database creation runs internally without the additional engine check used for tables. [dismissed by author -- https://github.com/Authorize a restored view's external targets #117423#discussion_r3900444249] Still real: neither the current preflight nor the database creation path enforces the missing grant. Follow-up: authorize the database engine before creation and add a negative restore case.

  • RestorerFromBackup.cpp:475: Temporary views use the table privilege instead of the view privilege. Backup collection accepts temporary views through the temporary-table element, but restore requires CREATE_TEMPORARY_TABLE for every temporary object. This permits restoration without CREATE_TEMPORARY_VIEW and denies a user holding only the correct view privilege. [dismissed by author -- https://github.com/Authorize a restored view's external targets #117423#discussion_r3942232973] Deferred in the PR description; still real because the current branch never distinguishes create.isView. Follow-up: mirror the view-specific creation check and test both grant combinations.

⚠️ Majors

  • RestorerFromBackup.cpp:461: Skipped databases still require unused object grants. database_skipped exempts only external-target rights. The preflight still requires database creation/show privileges and each skipped table's creation, insertion, or show privileges, although the later creation and data paths skip those objects. [dismissed by author -- https://github.com/Authorize a restored view's external targets #117423#discussion_r4017270554] Deferred in the PR description; still real because the remaining access accumulation is unconditional. Follow-up: apply the skip predicate to those requirements and test without the unused grants; the added test currently grants them.
Final Verdict

Status: ❌ Block on the preserved, unresolved privilege bypasses. The new external-target check itself has no additional finding. Minimum remediation is to enforce the database-engine and temporary-object creation privileges with focused negative tests. The skipped-object grant concern remains a separate follow-up; no existing discussion was duplicated or reopened.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on every attempt, not probabilistic. As a user granted only on their own database: BACKUP TABLE own.mv, TABLE own.dummy AS victim.ledger TO Disk('backups','e2e') SETTINGS structure_only=1, then RESTORE TABLE own.mv AS own.mv_restored FROM Disk('backups','e2e') SETTINGS structure_only=1, then INSERT INTO own.src VALUES (...). On master the row lands in victim.ledger, while both direct routes to it (INSERT INTO victim.ledger and CREATE MATERIALIZED VIEW ... TO victim.ledger) return Code: 497.
b Root cause explained? Yes. createTableRestoredFromBackup runs InterpreterCreateQuery with setInternal(true), so getRequiredAccess returns {} and the SELECT | INSERT requirement it normally imposes on create.targets never fires. RestorerFromBackup::checkAccessForObjectsFoundInBackup is the only gate that still runs as the real user before anything is created, and it built required_access from the restored table's own name only, never reading create.targets. The forged target reaches the metadata because BACKUP authorizes only the original element names while the per-element AS name drives the renaming map that DDLRenamingVisitor applies to create.targets.
c Fix matches root cause? Yes. It restores the missing requirement at that one gate, as a literal mirror of InterpreterCreateQuery::getRequiredAccess, so the CREATE and RESTORE paths agree again. Not a guard at the write site, not a widened bound, not a defensive check. Alternatives rejected: dropping setInternal(true) (changes far more than targets, and on ON CLUSTER the create runs on worker hosts whose user depends on distributed_ddl_use_initial_user_and_roles, so a check only there enforces nothing on the initiator); rewriting or stripping the target during restore (silently mutating persisted user metadata); exempting targets inside the same restore set (unsound, because with the default create_table = 'if not exists' a target that already exists locally is silently reused, which reopens the hole).
d Test intent preserved / new tests added? Yes. No existing test was changed or weakened. I re-verified that none pinned the vulnerable behaviour: the only two stateless tests combining RESTORE with MATERIALIZED VIEW ... TO (02907_backup_mv_with_no_source_table, 04027_mv_view_dependencies_drop_recreate) run as default with full access, so neither changes verdict. New test 05055_restore_mv_target_access ships in this PR, with nine arms: the forged restore and its aftermath, four controls, an arm that pins the SELECT half of the requirement separately from the INSERT half, and an arm covering a temporary table whose external target was forged the same way.
e Both directions demonstrated? Yes, with the serving binary's SELECT lower(buildId()) asserted against the on-disk Build ID before each verdict, and separately for each assertion the test makes. Against master: the forged RESTORE goes allowed to denied and the count of the forged view in system.tables goes 1 to 0. Against a build that weakens the new requirement to INSERT alone: the SELECT-half arm goes denied to allowed. Against a build that authorizes targets for ordinary tables but not for temporary ones: the temporary-target arm goes denied to allowed. In each case exactly the arms under test flip and every other line is byte-identical, and the permissive side prints a real success rather than a different error, so each red is the defect and not a broken fixture.
f Fix is general across code paths? Yes. The single gate covers all three createTableRestoredFromBackup implementations (DatabaseWithOwnTablesBase, DatabaseOverlay, DatabaseReplicated; DatabaseAtomic/Ordinary/OnDisk/Memory do not override) and the ON CLUSTER CHECK_ACCESS_ONLY pre-flight, which evaluates before run()'s early return. RESTORE DATABASE and RESTORE ALL fan out through findTableInBackup into the same table_infos loop. The requirement is imposed above the temporary-database branch, so a restored TEMPORARY TABLE is authorized too and no element shape the gate reaches is left diverging from getRequiredAccess. IDatabase's default implementation throws CANNOT_RESTORE_TABLE, so there is nothing to guard there.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The loop covers every target kind exactly as getRequiredAccess does: To (the reported carrier) and the external TimeSeries targets Samples, Tags, Metrics and RecentSamples, which are a second exploitable carrier of the same primitive; and it covers them whether the restored object is an ordinary or a temporary table. Legacy Inner carries no table_id and is skipped. Boundary case: an empty StorageID is skipped by if (target_id), which is what keeps inner-table views working and is pinned by its own arm. create_table = 'must-exist' is deliberately excluded because the backup's create query is only compared there, never executed, so requiring the target would be a spurious denial. Pre-existing shared blind spot, not introduced here: a target expressed with query parameters is invisible to table_id in getRequiredAccess too.
h Backward compatible? (maintainer-approved exception only) This is a deliberate grant tightening, stated in the changelog entry and the description: restoring a view with an explicit external target now needs SELECT, INSERT on it, which is exactly what creating the same view by hand already requires. No setting default changed, so no SettingsChangesHistory.cpp entry; no new AccessType, so 01271_show_privileges.reference is unaffected; no serialization or format change, so no versioning or upgrade path.
i Invariants and contracts preserved? Yes. The change only appends to a local AccessRightsElements before the existing containment comparison and context->checkAccess(); no early return, no new lock (the loop is already under the function's std::lock_guard), no ordering change, method stays const. Access is still checked strictly before createAndCheckDatabases() and createAndCheckTables(), so no partial creation can precede a denial, which the "nothing was created" assertion measures directly.

Session id: cron:clickhouse-impl-slot-4:20260831-210700

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

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni @vitlibar, could you review this? The restored CREATE runs internal, so getRequiredAccess imposes nothing and RESTORE of a MATERIALIZED VIEW ... TO other.table checked no privilege on the target, which let a user restore a backup forged from their own objects and then write into a table they hold no INSERT grant on. I mirror that requirement in the restore pre-flight, where it also covers external TimeSeries targets.

Comment thread src/Backups/RestorerFromBackup.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 910633939 with master 5087d8155 (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

Review feedback found the previous commit over-denying inside its own
contract. Under restore_replace_external_engines_to_null,
createAndCheckDatabaseImpl skips a database whose engine is external and
createAndCheckTableImpl then returns early for every table under it, so
nothing there is created. The target loop in
checkAccessForObjectsFoundInBackup still ran for those tables, and that
check runs first: it is called at the top of run(), long before any
database is classified. So a restore that creates nothing could be
refused for a grant it would never use.

Measured on three binaries, each asserted by build id, restoring a
backup whose view sits under a Filesystem-engine database and points at
a table the user cannot write. Before this change the restore is denied
naming SELECT, INSERT on that target; granting exactly that makes it
succeed and still creates no database, no table and no row, which is
what makes the denial spurious rather than merely strict. Before the
parent commits the same restore was allowed, so the denial came from
this change and is not pre-existing.

Gate the target requirement on the same predicate the skip uses. Both
sites now call one helper, so they cannot answer differently: a database
absent from database_infos is never skipped, matching
createAndCheckDatabases, which derives its work list from that map.
Nothing erases from it, so reading it unconditionally cannot throw where
the old code did not.

The requirement is unchanged wherever the table is really created. With
the setting off the same backup is restored and does demand the target,
and a view under an ordinary database is still refused with the setting
on, so the setting is not a way to skip the check. Both are asserted.

The new arm reddens in both directions: against the parent commit only
the skipped-database line moves, allowed to denied, with the other 25
lines byte-identical; against master before this work the two lines that
pin the requirement move instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
@PedroTadim PedroTadim self-assigned this Sep 1, 2026
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6e5a51f

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
Bugfix validation (functional tests, amd64) harness error before any test ran: AssertionError: Could not find master builds in S3 at ci/jobs/functional_tests.py:734 (the S3 prefix gained a workflow-name segment; find_master_builds still spells the old path) #117433 (mine, open)
Bugfix validation (functional tests, aarch64) same harness error, both arches #117433 (mine, open)
Finish Workflow / new_tests_check.py cascade of the two rows above: the hook requires a measured Bugfix validation result and both arms errored before running #117433 (mine, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) infrastructure resource kill, node lost the result; shards 1/6 to 5/6 all green (0 failures) #117411 (external, open)
Docs examples / Documentation examples (Function/toYYYYMM#0) trunk bug, not reachable from this diff: the documented output is hardcoded to 202608 and the example reads now(), so it flipped to 202609 at the September 1 month rollover #117459 (mine, open)

No failure on this head is caused by this PR: the two Bugfix validation arms never executed a
test, Finish Workflow only aggregates them, and the remaining two rows reproduce on unrelated
PRs at the same time.

Session id: cron:our-pr-ci-monitor:20260901-080000

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e52b2c3845a8464d83f1f3fa6529b2688612390e

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, 6/6) / Container memory budget exceeded (/docker) the shard's nested containers breach the /docker cgroup leaf, the kernel OOM-kills processes inside it and the job errors with no test attributed #117412 (external, merged 2026-09-01T11:31:33Z)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_polymorphic_parts/test.py::test_polymorphic_parts_index node1.query(...) fails Code: 209. DB::NetException: Timeout: connect timed out: 172.16.1.17:9000 because the server it talks to was one of the processes the kernel killed inside that leaf #117412 (external, merged 2026-09-01T11:31:33Z)
Finish Workflow / Post Hooks both Bugfix validation (functional tests, *) jobs are DROPPED due to previous failure [Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6)], so no arch reported OK or XFAIL and new_tests_check.py reds the post hook #117412 (external, merged 2026-09-01T11:31:33Z)

The /docker breach is a job-level condition, not a test result. I measured #117412 ABSENT from the tree that ran, from the job's own environment rather than from git ancestry: this job was launched with CI_DIND_INIT_RESERVE=17179869184 (the 16 GiB share #117412 replaces), and so were all ten failing legs I read this tick. The probe discriminates, with a positive control: two shards launched at 14:53Z and 14:59Z carry CI_DIND_INIT_RESERVE=8589934592 (the flat 8 GiB reserve #117412 introduces) and both passed. So this is rule 3c and not rule 3d, and #117411 is not a co-owner: it was closed unmerged at 11:11:48Z in favour of #117412, whose own diff comment states the causal link.

The test_polymorphic_parts_index row is a passenger of that same kill, and I tested that rather than assuming it. This job's own dmesg-follow.log records 5 oom-killer invocations with constraint=CONSTRAINT_MEMCG and clickhouse among the victims 3 times. Across 30 days, all 5 jobs carrying this leaf's client-failure signature also carry the /docker breach and none fires without it. The 3 remaining hits of the same leaf NAME are a different signature entirely (start_cluster / cluster.shutdown() / Crash in instance 'node5') and belong to the pull request that produces them.

An earlier head of this PR, 6e5a51fc3db0, failed the post hook through the other route, the Could not find master builds in S3 abort that #117433 (mine, open) fixes. That route will reappear once the breach stops dropping those jobs, which is why a master merge alone will not settle this head.

I have not merged master to pick those fixes up yet. It would not clear Mergeable Check on this head, because the Bugfix validation abort behind the dropped jobs is fixed only by a PR that is still open, so a merge now would cost a full CI cycle and leave the head red on the same count. One master merge picks everything up once the remaining fixes land.

Mergeable Check reports Failed: 2, Dropped: 102 at this head, which counts only the jobs it gates on. The table above is the complete non-OK, non-SKIPPED node set of the head's praktika report, so it also covers the rows Mergeable Check does not gate.

CH Inc sync was pending at this head.

Session id: cron:our-pr-ci-monitor:20260901-163000

@PedroTadim

Copy link
Copy Markdown
Member

@jkartseva maybe you can review this

@PedroTadim PedroTadim removed their assignment Sep 1, 2026
@jkartseva jkartseva self-assigned this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-backup Backup/restore infrastructure and backup formats. label Sep 4, 2026
groeneai and others added 2 commits September 5, 2026 16:46
Picks up three merged fixes that post-date this branch's previous master
merge and that its CI run was red on:

  ClickHouse#117580  Bugfix validation master-build lookup for the new S3 prefix
  ClickHouse#117459  date-dependent toYYYYMM documentation example
  ClickHouse#117412  integration tests' nested-container memory budget

Co-Authored-By: Claude Opus 5 <[email protected]>
A `Disk(...)` backup location is now authorized against the DISK source
(ClickHouse#117406): the Disk backup engine's SourceAccessFn returns a real
SourceAccessTarget, so writing a backup demands `WRITE ON DISK` and
reading one demands `READ ON DISK`. This test's user holds neither, so
after merging master every statement it issues as that user stopped at
the location check before reaching the materialized-view target logic
under test: six `allowed` lines flipped to `denied`, both assertions that
the denial names the target went 1 -> 0, and the TimeSeries arm reported
`forge failed`.

Grant both halves to the test user, the spelling ClickHouse#117406 used for its own
tests. The DISK source says nothing about a view target, so the oracle is
unchanged: with the grants in place the forged restore is denied with
`SELECT, INSERT ON <db>.dst` again, and with the RestorerFromBackup
change reverted the same test file still fails on six assertion lines.
continue;
}

const ASTCreateQuery & create = table_info.create_table_query->as<const ASTCreateQuery &>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RESTORE TEMPORARY TABLE can still carry a backed-up CREATE TEMPORARY VIEW definition through this branch: the backup grammar uses the TEMPORARY TABLE element for session-scoped objects, BackupEntriesCollector maps that element to DatabaseCatalog::TEMPORARY_DATABASE, and it accepts any create->isTemporary() object it finds there. But this preflight always asks for CREATE_TEMPORARY_TABLE, while direct CREATE TEMPORARY VIEW requires CREATE_TEMPORARY_VIEW (InterpreterCreateQuery::getRequiredAccess).

Because the restore later executes the CREATE internally, there is no second privilege check to correct that mismatch. A user with CREATE_TEMPORARY_TABLE but no temporary-view grant can still restore a temporary view, while a user who only has the view grant is denied. Can we mirror the create.isView() split here and add a focused BACKUP/RESTORE TEMPORARY TABLE case for a temporary view?

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8f6c4316969230ee19799531b03487484cacf0b6

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
Stateless tests (arm_binary, parallel) / 05098_client_psql_describe_table flaky expect stall: the script exits 1 through its own expect_after ... timeout arm, and the job's randomized-settings diagnosis then re-ran it 71 times with the same settings for 0 failures. The test is one day old (added in 2a7ccd72b648) and this is its only failure in 30 days of CIDB, none of them on master a fix task is created (investigating at full effort - fixing-PR link to follow here)

174 check-runs on this head: 153 success, 18 skipped, 3 failure. Mergeable Check and PR are aggregate statuses rolling up that same single leaf, not separate failures. CH Inc sync is success here, so nothing is exempt.

Not PR-caused: this diff is src/Backups/RestorerFromBackup.cpp plus 05055_restore_mv_target_access.{sh,reference}, which is neither the interactive client, the psql-protocol \d path, nor the expect harness.

Every row of my previous ledger (e52b2c3845a8) is clear on this head without a master merge: both Bugfix validation (functional tests, *) legs, Bugfix validation (unit tests), Docs examples, all six Integration tests (amd_asan_ubsan, db disk, old analyzer, *) shards and Finish Workflow are success.

Session id: cron:our-pr-ci-monitor:20260906-030103

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 05098_client_psql_describe_table expect stall on my CI finish ledger above (head 8f6c4316969230ee19799531b03487484cacf0b6): #118379.

Root cause: match_max 100000 in that test runs before the spawn and without -d, so the client kept expect's 2000-byte default and the bare \l listing (15,754 chars on that runner) overflowed the window. Nothing to do with this PR's diff.

pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Sep 6, 2026
`match_max 100000` on line 23 runs before the `spawn` on line 41, and without
`-d` it applies to the *current* spawn id, of which there is none at that point,
so the client ran with expect's 2000-byte default buffer, i.e. 6001 chars of
capacity.

The bare `\l` expands to `SHOW DATABASES`. On a shared `arm_binary, parallel`
runner that listed 69 databases with every row padded to 219 chars, because a
concurrent test held a ~200-char database name: a 15,754-char burst, 2.6x the
window. The test failed by timeout there, on
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117423&sha=8f6c4316969230ee19799531b03487484cacf0b6&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
(ClickHouse#117423), where the
`.expect.debuglog` shows expect forgetting output four times while matching the
prompt on line 94, ending with the buffer pinned at 6001 and a final read of 13
chars.

Use `match_max -d 100000` so the value the test already asks for is inherited by
the `spawn`.

Verified locally: `[match_max]` after a `spawn` reports 2000 without `-d` and
100000 with it. With 75 databases and one 206-char name making the listing
17,679 chars, the debuglogs of 50 runs hold 304 full-buffer discards without
this change and 0 with it, and the widest buffer expect examines rises from the
6001-char ceiling to the whole listing; reverting only the `-d` brings the
discards back. 50/50 runs pass with and without that fixture. The 60 s timeout
itself is rate-dependent and did not reproduce locally, so what is shown here is
that the assertion ran inside a discard regime the test's declared buffer would
never have entered.

Of the 62 `.expect` tests under `tests/queries/0_stateless`, the other 60 set
`match_max` the same ineffective way; as in
ClickHouse#112160 this commit only changes
the test that is failing, since a larger buffer also makes expect retain older
output, which could affect negative `expect` patterns in the other tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai merge master.

…et-access

# Conflicts:
#	src/Backups/RestorerFromBackup.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master and pushed 67fb906647b32e8b433026689eb14deefd00eb0c; the PR is mergeable again.

The single conflict was in src/Backups/RestorerFromBackup.cpp, where master's new isSystemWorkloadsTableName / isSystemResourcesTableName helpers landed at the same spot as my helper, so I kept both. On the merged tree 05055_restore_mv_target_access passes, and it still fails when I revert my src/ change to master's bytes, so the check is still the thing the test measures.

Comment thread src/Backups/RestorerFromBackup.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 67fb906

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
Build profile diff job-level RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes, raised in has_pr_data at ci/jobs/build_profile_diff_job.py:723: the readiness probe collapses every non-ok response into a bare False, so a transient CI logs cluster refusal is fatal and the job prints a single opaque line. Not reachable from this diff: the job only reads binary_sizes on the logs cluster. Measured 137 red heads across 123 distinct pull requests since 13:14Z today and 204 error rows in 7 days; the job runs on pull requests only, so there is no master arm #120121 (mine, open)
Stress test (amd_debug) / Cannot start clickhouse-server and Check failed after the stress phase the server refuses to come back up (11 start attempts) because a table left behind by 05079_parse_aggregate_function_typed_param cannot be re-attached: ATTACH TABLE test_7.t_pfl_05079 ... (s AggregateFunction(quantile('"0.5"'), Float64)) fails with Code: 70 ... Cannot convert String to double (CANNOT_CONVERT_TYPE), so loadMetadata aborts with ASYNC_LOAD_FAILED and the job never reaches a test. Trunk defect, not reachable from a RESTORE authorization diff: 49 rows across 42 distinct pull requests, 6 true-master rows and 11 stress flavours in 7 days, first seen 2026-09-13 11:36Z. The Check failed row is the exit-code rollup of the same unstartable server #119810 (mine, open)

Mergeable Check and PR are the two praktika aggregators of the rows above, not independent
failures. This head is the master merge 67fb906647b3 requested on the PR, and CH Inc sync is
green on it.

Session id: cron:our-pr-ci-monitor:20260915-213215

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai refresh the PR.

TimeSeries engine version 6 renamed the inner metric families column from
`metric_family_name` to `metric_family` (a78d687, after the previous
master merge on this branch), so `CREATE TEMPORARY TABLE ts ENGINE =
TimeSeries METRICS <t>` now rejects the test's fixture with
THERE_IS_NO_COLUMN. That aborted the forge step of the temporary-TimeSeries
arm, and the RESTORE it sets up then failed with BACKUP_NOT_FOUND instead of
the access denial the arm asserts.

Only the fixture's column name changes. The arm, the reference and the fix
itself are untouched: on the merged tree the test is 5/5 green, and 3/3 red
with the `RestorerFromBackup.cpp` change reverted, where the forged restore
is allowed again and the denial no longer names the target.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Refreshed: merged master (e5e8b4997c62) and pushed 459e4e79cbc4. No conflicts, and the PR is mergeable.

The refresh did catch one thing. 05055_restore_mv_target_access went red on the merged tree, because a78d687 renamed the TimeSeries inner column metric_family_name to metric_family, so CREATE TEMPORARY TABLE ts ENGINE = TimeSeries METRICS <t> now rejects the test's fixture with THERE_IS_NO_COLUMN and the temporary-TimeSeries arm never got as far as the restore it asserts on. I renamed the fixture column, which is the whole of that commit; the arm, its reference and the fix itself are unchanged.

Re-measured on the merged head: the test is green with the fix (40/40 on valid randomized draws) and red with the RestorerFromBackup.cpp change reverted, where the forged restore is allowed again and the denial no longer names the target. So the defect is still live on master.

CI is running on the new head; I will post the finish ledger here when it completes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 459e4e7

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 (see upgrade_error_messages.txt) Not caused by this PR. The pre-upgrade release writes AggregateFunction(quantile('0.5'), Float64) with the parameter persisted as a quoted String, so after the restart the new server cannot attach t_pfl_05079: Code: 70 ... Cannot convert String to double ... (CANNOT_CONVERT_TYPE) in AsyncLoader::worker. CIDB, 14 days, this exact context: 38 rows across 32 unrelated pull requests, 0 on master, clean onset 2026-09-21 23:34 UTC. #121590 (external, merged into 26.9) fixes the side that actually writes the metadata, the previous-release server, so it is deliberately absent from the tree that ran here and takes effect only once a 26.9 package containing it is published; the newest published tag v26.9.2.8-stable is still 9 commits behind that merge. My merged #119810 fixes the master side and IS present in the tree that ran (2889 commits after its merge commit), so it does not cover this row on its own.
Upgrade check (amd_release) / Cannot check whether the mutation submitted before the upgrade was finished (see mutation_across_upgrade_error.txt) Same job, downstream of the row above: the probe query waits on the failed load job for t_pfl_05079 and gets Code: 722 ... ASYNC_LOAD_WAIT_FAILED wrapping the same Code: 70. Not an independent mutation failure. #121590 (external, merged into 26.9), as above.

Mergeable Check and PR are the praktika aggregators for the single red job above, not separate failures. Everything else on this head is green or skipped: 133 successes, 39 skipped, 1 failure.

Session id: cron:our-pr-ci-monitor:20260924-040113

@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

groeneai and others added 2 commits October 21, 2026 12:42
…et-access

# Conflicts:
#	src/Backups/RestorerFromBackup.cpp
…on 9

Master's 681c2e1 made version 10 the default for new `TimeSeries` tables,
and a table of version 10 can have inner targets only, so the `CREATE` in this
arm now fails with `INCORRECT_QUERY` and the arm checked nothing. Tables of
version 9 and earlier still accept external targets and are still restored with
them, so the arm pins `version = 9`, the same way master pinned its own tests of
external targets. Version 9 keeps the tags in a `ReplacingMergeTree` inner table,
which needs its engine grant under `table_engines_require_grant`; that grant
confers no `SELECT` or `INSERT`, so the denial still comes from the forged target.

Also quote the SQL names in the test's shell comments.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 399030d

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05407_distributed_plan_exchange_compression_default flaky, not from this PR (it only touches RESTORE access checks): the new test from #126743 prints 1 0 instead of 1 1 in compressed under randomized group_by_two_level_threshold_bytes = 1 + materialize_statistics_on_insert = 0 (diagnosis: 69/69 same-settings reruns failed, 182/182 passed without randomization); it fails the same way on master and on other PRs since 2026-10-21 #127186 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127186 (the owner of the row above)

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

Session id: cron:our-pr-ci-monitor:20261021-180006

@jkartseva

Copy link
Copy Markdown
Member

Taking a closer look at the bot comments before merging.

…et-access

Resolves the conflict in checkAccessForObjectsFoundInBackup with ClickHouse#127180, which
also binds create above the temporary branch: keep master's is_temporary and
export-access check, then authorize the view targets as before.

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

Copy link
Copy Markdown
Member

@jkartseva let's merge?

@jkartseva
jkartseva added this pull request to the merge queue Nov 7, 2026
Merged via the queue into ClickHouse:master with commit 48a8c98 Nov 7, 2026
186 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 7, 2026
@nikitamikhaylov nikitamikhaylov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 11, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 11, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-backup Backup/restore infrastructure and backup formats. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

7 participants