Skip to content

Restore query-log attribution and prevent user-log metadata exposure - #126334

Closed
skuznetsov-clickhouse wants to merge 21 commits into
masterfrom
codex/issue-8826-query-access-info-20261015
Closed

skuznetsov-clickhouse wants to merge 21 commits into
masterfrom
codex/issue-8826-query-access-info-20261015

Conversation

@skuznetsov-clickhouse

@skuznetsov-clickhouse skuznetsov-clickhouse commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

View reads and serialized-plan reads can leave dependency access details out of the initiating query's log record. This change adds opt-in attribution for new view and materialized-view paths while preserving their existing security roots, settings, and snapshot/cache scopes.

query_log.enable_query_access_info_attribution is a server-admin option and defaults to false. It gates new access-info sharing and attribution for eligible view/MV paths. The user-log privacy filters remain unconditional: system.user_query_log includes only is_initial_query = 1 rows with an explicit query_access_info_is_hidden = 0 marker. Secondary rows and NULL or unknown markers are omitted even when the option is OFF; if the marker column is absent, the user log is empty. Existing protected rows stay hidden after switching OFF or restarting. With OFF, a fresh otherwise-eligible DEFINER/NONE ordinary-view row may appear without newly attributed dependency details. This unconditional omission of secondary rows is backward incompatible.

Custom per-user policies on system.query_log must retain their identity predicate and add is_initial_query = 1 AND query_access_info_is_hidden = 0, or migrate to system.user_query_log. The marker alone does not protect a direct system.query_log policy, including when the option is OFF. These user-log filters do not apply to system.query_log; its normally logged rows remain subject to existing logging settings.

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix missing query-access details for view and serialized-plan reads. New view and materialized-view attribution is controlled by the server-admin option query_log.enable_query_access_info_attribution (default false). Independently of this option, system.user_query_log omits secondary rows and includes only initial-query rows with an explicit query_access_info_is_hidden = 0 marker; NULL or unknown markers are omitted, and a missing marker column leaves the user log empty. Custom per-user policies on system.query_log must retain their identity predicate and add is_initial_query = 1 AND query_access_info_is_hidden = 0, or use system.user_query_log.

Candidate validation

Nine numbered stateless SQL invocations passed with no skips; their outer wrapper exited nonzero while parsing grouped summaries. The standalone config-restart check passed. The isolated lifetime test (1/1) and nonproxy suite (20/20) passed under ASan/UBSan. The canonical proxy batch failed on its first test (34/35); the same 35-test log was byte-identical on the preserved pre-fixture binary, so this batch remains a failure, not a pass. The lifetime child uses _Exit, so child exit-time LSan and global test-main shutdown are not covered. The clickhouse target linked, and unit_tests_dbms linked in the ASan/UBSan build.

The published e931 CI had one arm_binary integration failure because a blanket Nullable assertion rejected the intentional Nullable(UInt8) marker. A local full-schema assertion fix is present, but the corrected test has not run on the current candidate. Standard CI/Praktika, current-candidate integration, mixed-version behavior, and fresh-base integration remain open. Removing the QueryNode owner causes an expired-context failure; removing the Planner owner loses the root while the plan is alive. This supports retaining both owners for this fixture, not a claim of global minimality.


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

Retain canonical query context through `QueryNode` and `QueryPlan`, and share
the outer `QueryAccessInfo` in both `StorageView` paths so the tested
synthetic view paths record projection usage.

The native fixture misses three projection rows on tested base
826aeb7 and passes with this candidate;
four focused query-context lifetime/clone tests pass. Restricted-caller
validation shows that full access-info sharing exposes inner object names in
the caller's own `system.user_query_log`, while direct base-table `SELECT`
still returns Code 497. The metadata-visibility policy remains unresolved,
so this draft is not merge-ready. Fresh-base runtime, CI, sanitizer, and
cancellation/concurrency/lifetime-stress gates remain open.

Related: ClickHouse/support-escalation#8826

🕵️‍♂️
@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79c55d6]

Summary: ✅


AI Review

Summary

The PR adds opt-in dependency attribution for view reads and materialized views, and restricts system.user_query_log to initial queries with explicitly unrestricted provenance. Reviewed head 79c55d64643d3e6edaab62284e705a0130c3adb4. All three new SQL tests matched their references on the head's Fast test binary; restricted-reader checks also passed. One previously dismissed correctness finding remains reproducible. No new inline findings.

Findings

❌ Blockers

  • src/Storages/StorageView.cpp:1031 — Inlined views override explicitly requested snapshot consistency. [dismissed by author -- https://github.com/Restore query-log attribution and prevent user-log metadata exposure #126334#discussion_r4526200327] The override remains unconditional, including for SQL SECURITY INVOKER views with compatible settings and with attribution disabled. The experimental status of analyzer_inline_views does not prevent the demonstrated incorrect result when a caller explicitly requests snapshot sharing.

    Reproduced again on the current head's Fast test binary with attribution off: create two parts containing user_id = 1 and user_id = 2, and an invoker view v AS SELECT user_id, _part AS part, _part_offset AS offset FROM t. Run:

    SELECT count() FROM v
    WHERE (part, offset) IN
        (SELECT part, offset FROM v WHERE user_id = 2)
    SETTINGS enable_shared_storage_snapshot_in_query = 1,
             analyzer_inline_views = 1;

    Synchronize OPTIMIZE TABLE t FINAL between the two snapshot acquisitions using merge_tree_storage_snapshot_sleep_ms, as in 03443_shared_storage_snapshots.sh. The query returns 0; the same synchronized control with analyzer_inline_views = 0 returns 1. Both executions complete successfully. Preserve snapshot sharing for compatible contexts, isolate incompatible mutation/patch settings separately, and add this concurrent-merge regression. The existing thread remains resolved in accordance with the author's decision.

Final Verdict

Status: ❌ Block. Preserve explicitly requested snapshot consistency through compatible inlined views and cover the concurrent-merge case above. No new threads or replies were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
Comment thread src/Storages/StorageView.cpp Resolved
The canonical query context getter returns a const shared-pointer reference.
Four callers relied on auto to deduce const, which fails
readability-qualified-auto in both arm_tidy shards and drops the downstream
bugfix validation jobs. Spell out const on these references while preserving
the existing Context mutability and ownership.

Validation: the three affected analyzer objects compile with Clang 21.1.8 on
the personal devserver; an independent syntax-only repeat also passes.
CI clang-tidy 22 remains pending. The draft's metadata-policy and broader
lifetime validation gates remain open.

🕵️‍♂️
@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Oct 16, 2026
The old lifetime test manually populated an empty QueryPlan, so it could
pass if Planner stopped retaining the canonical query context.

Replace it with a real Planner-created plan and pipeline. Release the
tree, interpreter, and caller contexts, then check plan-only retention,
pipeline-only retention, and final root release.

Validation: focused Release dev build, six tests passed. Removing only
the production canonical-context registration makes the new test fail
at its plan-only assertion; restoring and rebuilding passes again.
Root independently reran both binaries and verified matching edited
sources. This is not a whole-current-head or sanitizer validation.
The separate privileged-view metadata visibility concern stays open.

🕵️‍♂️
Keep canonical query context alive through view planning and execution so
system.query_log retains table and projection attribution. Mark ordinary
DEFINER/NONE view access and mask its seven access arrays in
system.user_query_log before outer expressions can inspect them.

Validation: candidate build 359/359; 05394, authenticated red/green controls,
and the four-case legacy matrix passed. Native 05395/05396 are blocked before
transfer pending explicit authorization; no server or test was started.
unit_tests_dbms, whole-head CI, sanitizers, and the current-master build remain
unrun.
@skuznetsov-clickhouse skuznetsov-clickhouse added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Oct 18, 2026
QueryAccessInfo was lost in materialized-view dependency contexts, leaving
base tables and projections out of query_log. A column-only user_query_log
mask also left protected or remote-child rows readable, and a forged Native
initial_user could select another user's top-level record.

Share the canonical access state across dependency contexts and mark
DEFINER/NONE boundaries. Expose only authenticated, top-level rows with an
explicit unhidden marker in user_query_log. Add focused regression coverage
for views, projections, nested materialized views, remote children, and the
forged initial-user case.

Verification: cycle7 x86 build and exact 05395 ordinary, 05397 ordinary and
ParallelReplicas, and 05398 tests passed; 05396 passed on cycle4. The final
secretless interserver integration assertion, ARM/S3 CI, sanitizer, and a
combined current-master build remain unverified.
@mintlify

mintlify Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 16, 2026, 7:44 PM

@skuznetsov-clickhouse skuznetsov-clickhouse changed the title Restore projection attribution for SQL SECURITY DEFINER views Restore query-log attribution and prevent user-log metadata exposure Oct 19, 2026
@clickhouse-gh clickhouse-gh Bot added comp-system-table system.* tables (introspection, system metadata, performance visibility). and removed comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 19, 2026
Reading a SQL SECURITY DEFINER or NONE materialized view through readImpl did not mark the outer query access information hidden, so the grant-free user_query_log could expose its query row. Share the access state with the view context and mark the outer row. Permit the empty identity used by clickhouse-local only for its LOCAL application and interface; authenticated and interserver identities remain fail-closed. Keep generated system-table docs in sync with their C++ sources by dropping the manual generated edits.

Validation: cycle8 reproducer showed the pre-fix materialized-view marker 0,0 instead of 1,1; focused cycle8 04516/04550/05398 passed, and Luna Max local diff review found no source issue. Final candidate build, 05400 green run, interserver integration, and new CI are pending.
@skuznetsov-clickhouse skuznetsov-clickhouse removed the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Oct 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79c55d646 with master 9005321e3 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of e4cde4748; 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

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

Job report

Split the remote-child checks in 05397 so each signal is visible, and serialize its shared test user. Assert that protected inline QueryStart and QueryFinish rows are absent from user_query_log while direct controls remain visible.

The exact 05397 and 05394 stateless runs passed on the pinned cycle10 candidate, and a Luna Max source review approved the diff. The final interserver product run and new-head CI remain pending.
Flaky-check repeats ran four new tests concurrently, so CREATE USER sometimes found an existing global user. Mark those tests no-parallel to route repeated copies through the sequential test queue.

Verified the runner tag parser and sequential routing, bash -n, and staged diff --check. Repeated runtime validation and new CI remain pending.
Serialized QueryPlan reads bypassed access-info registration, so the remote child QueryFinish could omit its table. Materialized views created without an explicit SQL SECURITY clause also exposed protected access metadata in user_query_log.

Register the resolved storage after direct serialized reads, mark implicit-security MV insert and read paths hidden, clarify the query-log documentation, and add focused 05401/05402 regressions.

Verified: pinned Release -j2 build; exact 05397 with serialization off/on and 05401/05402 twice each passed native references and raw-log oracles. Remaining: new-head CI, a current-master build, final-candidate interserver and sanitizer execution, and customer validation.
@skuznetsov-clickhouse
skuznetsov-clickhouse marked this pull request as ready for review October 20, 2026 14:25
@vdimir vdimir self-assigned this Oct 20, 2026

@vdimir vdimir 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.

Thanks for the PR!

QueryNode change. My main concern is the change in QueryNode. It looks too wide for what it fixes and can probably be narrowed down to the two places that actually drop the view's query context (see the inline comment on setContext).

Tests. The number of tests can also be reduced. Eight files cover three behaviors, and most of them repeat the same scaffolding for one more object kind.

Behavior change in system.query_log. This deserves a note in the changelog and the docs. The docs never promised to hide the view's definition or the names of its sources, but the sealed-view work established a de facto rule that the caller must not learn what a DEFINER view body contains or touches. Before this PR the caller's query_log row showed nothing behind such a view, by accident; after it, it shows the tables, columns, projections, row-policy names and partition IDs reached under the definer, marked with query_access_info_is_hidden = 1.

system.user_query_log handles that by dropping the row, but deployments that give users self-service access to system.query_log through a row policy like user = currentUser() get no protection from the marker. That should be stated in the PR, with the fix for such setups being:

  • AND query_access_info_is_hidden = 0 in the policy, or
  • switching users to system.user_query_log.

A sentence in the SQL security section of the CREATE VIEW docs that system.query_log records what the body accessed under the definer would close the gap between the documented and the de facto guarantee.

Comment thread src/Interpreters/SystemLog.h Resolved
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Analyzer/QueryNode.cpp Resolved
The runner can disable optimize_use_projections, which also disables the
force-projection settings. This reproduces the reader-filter test's third
reference-row mismatch. Enable the prerequisite before forcing projection pn.

The unchanged fixture fails/passes with incoming projection setting 0/1;
the candidate passes all four alternating 0/1 arms. On the existing Release
build with the official test cluster, one forced parallel-replica mode-2 case
and 50 randomized cases pass with the original reference and zero skips.

Exact sanitizer/S3/meta-in-Keeper CI remains pending. No product code changes.
@clickhouse-gh clickhouse-gh Bot added comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). and removed comp-system-table system.* tables (introspection, system metadata, performance visibility). labels Nov 8, 2026

@vdimir vdimir 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.

Discussed additionally in private:

  • query_access_info_is_hidden is probably not necessary, and we can rely on user or possibly other existing query_log fields, but need investigation.
  • The number of added test lines can probably be reduced to clearly cover only the essential scenarios in a few files.

vdimir and others added 2 commits November 10, 2026 13:03
`getSQLSecurityOverriddenContext` makes a `DEFINER`/`NONE` body its own query
context, and copies of it reference that context only weakly. Instead of an
owner on every `QueryNode` (`setContext`, `query_context_lifetime`), another one
in `Planner::extendQueryContextAndStoragesLifetime` and gtests pinning them,
fix the two places that drop the context:

- `StorageView::readImpl` adds the view context to the plan, which still
  records the chosen projections into it during optimization.
- The body inlined by the analyzer resolves to the caller's query context when
  attribution is enabled, instead of sharing the access info pointer: it is
  planned as part of the caller's query, and an inlinable body is a plain
  projection of a MergeTree table (see `isSealed`). It takes its own storage
  snapshot, because the shared snapshot cache is keyed by table only while the
  body may read with other `apply_mutations_on_fly` / `apply_patch_parts`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ess tests

The previous tests were about 1900 lines for three behaviors: templated
`.sql.in` inputs rendered through a helper, a raw native-protocol Python client
and an integration test with restarts. Cover the same behaviors in plain SQL,
without users or shell:

- `05616_query_log_access_info_sql_security_view`: `DEFINER`, `NONE` and
  `INVOKER` views, read directly and inlined; table and projection attribution,
  the hidden marker on `QueryStart` and `QueryFinish`, `system.user_query_log`
  keeping only unmarked rows.
- `05617_query_log_access_info_materialized_view`: `INSERT ... SELECT` through
  a `DEFINER` and a legacy (no `SQL SECURITY`) materialized view, and reads
  through both.
- `05618_user_query_log_access_info_secondary_query`: a remote child, shipped
  as query text and as a serialized plan, records the table it read, and
  `system.user_query_log` excludes secondary rows.

Not covered: the server option switched off (a server config value), a reader
forging `initial_user` (needs a raw native-protocol client), rows with a `NULL`
or missing marker.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vdimir

vdimir commented Nov 10, 2026

Copy link
Copy Markdown
Member

I pushed two commits to this branch.

c993287: the lifetime fix is now local to StorageView.cpp. The QueryNode owner (setContext, query_context_lifetime), the owner in Planner::extendQueryContextAndStoragesLifetime and both gtests are reverted. Instead:

  • readImpl adds view_context to the plan, so the optimizer can still record projections into it.
  • getViewSubqueryContext, when attribution is on, makes the inlined body use the caller's query context instead of sharing the access-info pointer. This is safe because only non-sealed views are inlined, and isSealed allows nothing but a plain projection over one MergeTree table.
  • The inlined body gets enable_shared_storage_snapshot_in_query = 0. The shared snapshot cache is keyed by table only and ignores apply_mutations_on_fly / apply_patch_parts, so two inlined DEFINER views with different definer profiles would otherwise return order-dependent results. That cache bug is pre-existing (Add support for shared storage snapshots across subqueries to ensure query-level consistency #79471) and shows up on master with plain subqueries too; it deserves its own fix.

The lifetime gtest only pinned the owner mechanism, so it goes with it; 05616 covers the behaviour.

e73e2d9: the ~1900 lines of tests are replaced by three plain .sql tests: 05616 (views: DEFINER, NONE, INVOKER, inlined too, projections, marker, user_query_log), 05617 (materialized views on insert and read, including the legacy no-SQL SECURITY case), 05618 (remote child rows, serialized plan, user_query_log excludes them). Not covered on purpose: the option switched off, a forged initial_user, NULL markers. The old tests passed on the new code before I replaced them.

@vdimir

vdimir commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

A proposal to simplify the rest.

The option and the query_access_info_is_hidden column exist only because the body's access info is merged into the caller's query_log row. Once merged, something must mark the row, and the marker drags in the reader filters, the NULL handling and the option that ships the fix disabled.

Instead, log the body of a sealed DEFINER/NONE view (and the materialized-view paths) as a child row, like distributed execution already does: is_initial_query = 0, initial_query_id = the caller's query, user = the definer, query = the view's inner query, and tables / columns / partitions / projections = what the body touched. The provenance is then carried by columns that already mean exactly this, operators trace it with initial_query_id, and system.user_query_log hides it with the is_initial_query = 1 filter this PR adds anyway. The marker column, the five marking sites, the reader's marker logic and the server option all go away.

Transparent (inlinable) views stay in the caller's row: EXPLAIN already shows their body to the caller. The body's QueryAccessInfo already exists; the four callers of getSQLSecurityOverriddenContext would register it on the caller's query context, and executeQuery would write one row per view at finish. Cost: a new kind of child row with a generated query_id and no per-row metrics.

…o test

In the Fast test `sum(id)` over the two-row target was answered from part
statistics without reading any part, so no partition was recorded and the
target did not show up in the caller's row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 10, 2026
`BINARY_DOCKER_COMMAND`, `LIMITED_MEM`, `KEEPER_DIND_MEM` and the
`CI_DIND_*` budgets put byte counts derived from `Utils.physical_memory`
into `run_in_docker`, and the job config (including `run_in_docker`) is
hashed into the job digest. The digest is computed in "Config Workflow",
whose runner has a slightly different amount of memory from run to run,
so every build and most tests got a new digest - a cache miss - even on
a rerun of the same commit. Checked by computing the digests of the `PR`
workflow with the physical memory differing by 4 MB: 102 of 178 jobs
changed before, none after.

Example: run 42383050264 (PR #126334), attempt 2 rebuilt all ~30 builds
that had succeeded in attempt 1 for the same merge commit, because their
digests changed (e.g. `Build (amd_debug)`: `...-a08a` -> `...-3ed4`).

Mask byte counts (10+ digits) in `run_in_docker` before hashing. The job
still applies the limits computed on its own runner.

Related: #130509 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 10, 2026
The jobs of a run are fetched with `--paginate`, so a `PR` run (more than
100 jobs) gives several JSON documents. The `finish_window` filter ran
per document and printed an empty window for the page without
"Finish Workflow", so the window bounds started with a newline and the
`created_at <= $to` comparison never matched the
"Failed: review threads only" marker. Every run held by the
unresolved-review-threads gate was then retried as an infrastructure
failure ("job-level heuristic") - a whole rerun that changes nothing,
because the threads are still unresolved.

Example: run 42383050264 (PR #126334, 7 unresolved threads) was rerun by
the 2026-11-07 16:46 tick although its marker was posted inside the
"Finish Workflow" window. Slurp the pages before selecting the job.

Related: #130509 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageView.cpp Resolved
@vdimir

vdimir commented Nov 10, 2026

Copy link
Copy Markdown
Member

@groeneai try to implement my proposal above in separate branch

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm implementing your child-row proposal (sealed DEFINER/NONE view and materialized-view bodies logged as is_initial_query = 0 rows, without the marker column and the server option) in a separate PR; I'll link it here when it opens.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #130654 with the child-row design. Its first commit is this PR at b4be48e6; the second removes the marker column, the marking sites, the reader's marker logic and the server option, and logs each DEFINER/NONE body as a child row (is_initial_query = 0, initial_query_id = the caller's query, user = the definer, query = what ran, with the tables, columns, partitions and projections it accessed).

Deviations from the proposal:

  • Transparent views, reads through a materialized view and inserts into one are child rows too: kept in the caller's row, a transparent body would put partition ids of a key the view need not expose into the grant-free system.user_query_log.
  • analyzer_inline_views no longer inlines DEFINER/NONE views, because an inlined body's query context has no owner. That drops the inlined-body context switch and the enable_shared_storage_snapshot_in_query override from c993287.
  • The caller's row no longer lists the tables a DEFINER/NONE materialized view writes; they are in that view's child row.
  • 05257_sql_security_view_sealed counts only forwarded rows (distributed_depth > 0).

@vdimir

vdimir commented Nov 13, 2026

Copy link
Copy Markdown
Member

@groeneai, who is the expert on the VIEW DEFINER feature? Let's ask them how to design a fix, since I'm not sure what is correct here. Please briefly explain what we tried to do.

@groeneai

Copy link
Copy Markdown
Collaborator

The SQL SECURITY / DEFINER feature was added by @pufit (#54901, re-landed as #60439).

@pufit, a design question about system.query_log. A DEFINER/NONE view or materialized view runs its body in a separate query context under the definer (getSQLSecurityOverriddenContext). The tables, columns, partitions and projections the body accesses are recorded in that context and never logged, so query_log does not show what a query read through such a view. Two attempts to log them:

  1. This PR merges the body's access info into the caller's row (user = the caller). Because system.user_query_log shows users their own rows without a grant, such rows get a query_access_info_is_hidden marker that user_query_log filters out, and the attribution is behind a server option that is off by default.
  2. Log what runs under a SQL SECURITY DEFINER or NONE view as a child query_log row #130654, following the proposal above, logs each body as a child row instead: is_initial_query = 0, initial_query_id = the caller's query, user = the definer. The caller's row is unchanged, and user_query_log returns only is_initial_query = 1 rows.

Which is right for DEFINER/NONE bodies: (1), (2), or neither (keep them unlogged, as on master)? Both keep the body's access out of the caller's system.user_query_log.

Resolve the StorageView.cpp include conflict by retaining both includes.\n\nhttps://github.com//pull/126334
@pufit

pufit commented Nov 17, 2026

Copy link
Copy Markdown
Member

2 is the right path to me

@pufit pufit closed this Nov 18, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 18, 2026
This is ClickHouse#126334 at head b4be48e, applied
verbatim as the base of the child-row variant proposed by @ vdimir in
ClickHouse#126334 (comment).

Co-authored-by: Sergey Kuznetsov <[email protected]>
Co-authored-by: vdimir <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 18, 2026
…ery_log row

The body of a `SQL SECURITY DEFINER` / `NONE` view or materialized view runs in a query
context of its own (`getSQLSecurityOverriddenContext`), and everything it records goes to that
context's `QueryAccessInfo`, which nothing logs. The previous commit (ClickHouse#126334) merges it into
the caller's row, and so needs the `query_access_info_is_hidden` marker, its marking sites, the
reader's marker logic and the `query_log.enable_query_access_info_attribution` option. This
replaces all of that with the design proposed by @ vdimir in
ClickHouse#126334 (comment): the body is logged
as a child row of the query, like the shard query of a distributed query.

- `Context::addSQLSecurityOverriddenBody` registers a body's `QueryAccessInfo` on the enclosing
  query context. It is called where the body context is created: `getViewContext` (a view read),
  `StorageMaterializedView::readImpl` (a read through an MV, logged as `SELECT <columns> FROM
  <target>`), the root of `InsertDependenciesBuilder` (an insert into an MV, logged as `INSERT
  INTO <target>`) and `createSelectInsertContext` (an MV run on INSERT). A body registered again
  with the same view, query tree hash and user is redirected to the first registration, so a
  view planned for every block of an MV insert is one row. The registry is not copied with a
  context.
- `executeQuery` writes one row per registered body after the caller's row at QueryFinish,
  ExceptionWhileProcessing and ExceptionBeforeStart, recursively for nested bodies, and consumes
  the registry: `is_initial_query = 0`, a generated `query_id`, the caller's `initial_query_id`,
  `user` = the definer (empty for NONE), the body's query formatted for logging, and what it
  accessed; no metrics.
- `InsertDependenciesBuilder` records an MV's target and the views its write triggers on the
  context that writes them, so for a DEFINER/NONE MV they are in its child row. INVOKER and
  legacy MVs share the caller's query context, so their rows do not change.
- `analyzer_inline_views` no longer inlines a DEFINER/NONE view (the parallel-replicas bail-out
  becomes unconditional): an inlined body's query context has no owner, and keeping every inlined
  occurrence alive would grow per block inside an MV body. The view is read through `readImpl`,
  whose transparent plan is still merged into the caller's. ClickHouse#126334's switch of the inlined body
  to the caller's query context and its `enable_shared_storage_snapshot_in_query` override are
  reverted with it.

Deviation from the proposal: transparent views, reads through an MV and inserts into an MV are
child rows too. Attributed to the caller, a transparent body would put the partition ids it
selected, of a partition key the view need not expose, into the grant-free
`system.user_query_log`.

`system.user_query_log` keeps ClickHouse#126334's identity check and its `is_initial_query = 1` filter,
which now also hides the child rows. 05257 counted every non-initial row as a query shipped to
another server; it now counts only rows with `distributed_depth > 0`.

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

This branch was successfully deployed

1 active deployment
staging - docs — 79c55d64 Deployed Nov 16, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants