Skip to content

Add a new system table system.user_query_log - #110156

Merged
alexey-milovidov merged 27 commits into
masterfrom
user-query-log
Aug 2, 2026
Merged

alexey-milovidov merged 27 commits into
masterfrom
user-query-log

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #82539
Related: #104462

Changelog category (leave one):

  • New Feature

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

Added a new system table, system.user_query_log, which shows every user their own query log records without requiring access to the query log table. The original implementation and the idea belong to Yue Ni (@niyue), #104462.

Documentation entry for user-facing changes

  • Documentation is written

This is a simplified implementation of #104462.

The original PR implements system.user_query_log as an automatically created SQL SECURITY NONE view over the query log table. Since such a view is a first-class StorageView fused into the outer query plan, every user-controllable expression channel has to be defended individually, and every DDL path has to know that the name is special. This required introducing two new concepts across the codebase: "security barrier views" (bans on view inlining in both analyzers, stripping additional_table_filters from the inner context, rejecting additional_result_filter in three places, refusing predicate pushdown, removing LowCardinality from the exposed types) and "reserved table names" (guards in InterpreterCreateQuery, InterpreterRenameQuery, DatabasesCommon, DatabaseCatalog, plus validation of a pre-existing table at startup) — around 340 lines across 15 files in src.

Here the same feature is an ordinary system table, StorageSystemUserQueryLog (195 lines across 4 files in src, no changes to StorageView, Planner, QueryAnalyzer, the interpreters, or the database layer):

  • read() resolves the configured query log table (query_log.database/query_log.table) at query time and runs SELECT <requested columns> FROM <log table> WHERE if(initial_user != '', initial_user, user) = <current user> under an internal full-access context. The user's session settings are deliberately not propagated into it, so settings such as additional_table_filters cannot inject expressions into the inner query.
  • The inner query pipeline is fully built inside read() and embedded into the outer plan as an opaque ReadFromPreparedSource. Plan-level optimizations of the outer query (filter push-down, filter merging) cannot move any outer expression below the user filter, where it could observe other users' rows through a side channel such as throwIf. This makes the barrier structural instead of defending each channel separately. Note that in a plan-fused design, an outer WHERE merges with the inner filter into and(inner, outer) and the safety of a throwIf side channel then depends on the evaluation order and laziness of and, which is controlled by the user-settable short_circuit_function_evaluation — an opaque pipeline does not have this dependency at all.
  • A converting cast to the declared columns (with LowCardinality removed) materializes the result, so dictionaries shared with filtered-out rows cannot leak other users' values.
  • Since the table is always attached (when query_log.enable_user_query_log is enabled, which is the default), CREATE/RENAME/DROP of system.user_query_log are rejected by the existing generic mechanisms for system tables, and no reserved-name machinery is needed. A leftover user table with this name (e.g., created before an upgrade) produces a clear error at startup.

User-visible differences from #104462:

  • SHOW CREATE TABLE system.user_query_log shows a table with ENGINE = SystemUserQueryLog rather than a view definition.
  • Reading the table before the query log table has been created (e.g., on a fresh server before the first flush) returns an empty result instead of an UNKNOWN_TABLE error. This also resolves the blocker from the automated review of the original PR.
  • additional_result_filter is not rejected: it is applied above the user filter and is therefore safe.
  • The name is only occupied while the feature is enabled; with query_log.enable_user_query_log = 0 there are no restrictions on the name.
  • In clickhouse-local, the table always exists and is empty when the query log is not configured.

The integration test for the distributed initial_user semantics is taken from the original PR. The behavior was verified with a real binary: a user without any grants sees exactly their own records and cannot read system.query_log; a throwIf predicate never observes other users' rows regardless of how it is injected (WHERE, additional_table_filters keyed on the source table or on the table itself, additional_result_filter) across both analyzers and all short_circuit_function_evaluation modes.

Version info

  • Merged into: 26.8.1.638 (included in 26.8 and later)

Shows every user their own query log records without requiring access
to the query log table. The inner query over the configured query log
table runs under an internal full-access context and is embedded into
the outer query plan as an opaque, fully built pipeline, so no outer
expression (WHERE, additional_table_filters, additional_result_filter)
can be moved below the user filter.
@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a9357e]

Summary: ✅


AI Review

Summary

This PR adds system.user_query_log as a per-user projection of query_log, with dedicated access-control wiring, docs, and tests. The current head fixes the earlier grant / clickhouse-local / distributed-backend issues, but the new predicate pushdown reopens a security hole: it lets unprivileged users infer facts about other users' query_log rows through their own probe query's recorded execution statistics.

Findings

❌ Blockers

  • [src/Storages/System/StorageSystemUserQueryLog.cpp:290] Caller-controlled predicate pushdown breaks the table's "only my rows" contract through query metrics, even when the visible result set stays empty. A user can run a probe such as SELECT count() FROM system.user_query_log WHERE query_id = 'victim-id', then inspect that probe query's own read_rows / runtime via their next system.user_query_log lookup; because the pushed predicate participates in the backing system.query_log scan before the per-user filter, those metrics reveal whether foreign rows matched. The same oracle exists for user, initial_user, current_database, event_date, and the other pushed columns. The safest fix is to stop pushing outer predicates into the inner query and keep them above the opaque ReadFromPreparedSource barrier.
Final Verdict

❌ Changes requested. The current pushdown optimization leaks information about other users' log rows through the caller's own query-log statistics, so the feature is not yet safe to merge.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 12, 2026
@mintlify

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 2:24 PM

…ure being enabled

Address the code review of the pull request: `ContextAccess::addImplicitAccessRights`
granted `SELECT` on `system.user_query_log` to every user unconditionally. When
`query_log.enable_user_query_log = 0`, the name can back a regular table (or the raw query
log via `query_log.table = user_query_log`), which would then become world-readable instead
of requiring an explicit grant. The documented upgrade workaround (disabling the feature for
a pre-existing table with this name) had the same problem.

The implicit grant is now conditional on `AccessControl::isUserQueryLogEnabled`, mirroring the
`query_log.enable_user_query_log` server setting read at startup. This is exactly when
`system.user_query_log` is attached as `StorageSystemUserQueryLog` (the attach code rejects any
other table under this name while the feature is enabled), so the grant applies only when the
name is backed by the row-filtering storage. When the feature is disabled the name has no
implicit grant and behaves like any other table, so the disable/upgrade path is now safe.

Adds an integration test that starts a server with the feature disabled and the raw query log
configured under the `user_query_log` name, and verifies a user without grants cannot read it,
while a privileged user still can.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 12, 2026 16:54
…into the inner read context

Address review (clickhouse-gh @ `StorageSystemUserQueryLog.cpp`): the inner `query_log` read
started from a bare `Context::createCopy(context->getGlobalContext())` and never reapplied the
caller's execution settings or normalized query hash. As a result, `NORMALIZED_QUERY_HASH` quotas
were bucketed under `0`, and the backing query log scan ran with server-default settings (e.g.
`max_threads`) instead of the caller's profile.

Mirror `StorageInMemoryMetadata::getSQLSecurityOverriddenContext`: carry over the client info and
the normalized query hash, and apply the caller's settings changes. The expression-injection
settings `additional_table_filters` and `additional_result_filter` are dropped from the applied
changes, because they would inject expressions evaluated on other users' rows before the user
filter hides them.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The test shipped a custom `users.xml` that added `<grants>` to the `default` user. The integration
harness always merges `0_common_instance_users.xml`, which sets
`<access_management>1</access_management>` for `default`, and combining `grants` with
`access_management` is rejected with `Any other access control settings can't be specified with
grants` (`BAD_ARGUMENTS`), so the server exited during config load and the test errored.

The harness default `default` user already has full access (the base `users.xml` grants `ALL` and
the common config enables access management), so the custom `users.xml` was redundant. Remove it
and let the test rely on the default user.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110156&sha=a127abec2e86e75f6a90a354d6e01ee4bd623a65&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20flaky%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Access/AccessControl.cpp Resolved
…e-local too

`AccessControl::setUserQueryLogEnabled` was only called from
`AccessControl::setupFromMainConfig`, i.e. the server startup path.
`clickhouse-local` sets up its access control separately in
`LocalServer::setupUsers` and never set the flag, while still attaching
`system.user_query_log` through `attachSystemTablesServer`: a local user
without an explicit `SELECT` grant would get `ACCESS_DENIED` on a table
that is documented as readable without grants.

Mirror `query_log.enable_user_query_log` into the local access-control
setup and extend `04516_user_query_log_local` with regression checks:
`SHOW GRANTS WITH IMPLICIT` for a grantless user must list
`GRANT SELECT ON system.user_query_log` when the table is enabled and
must not list it when it is disabled.

Co-Authored-By: Claude Fable 5 <[email protected]>
`system.user_query_log` copied only `QueryLogElement::getColumnsDescription`
and dropped the alias columns exposed by `system.query_log`
(`ProfileEvents.Names`, `ProfileEvents.Values`, `Settings.Names`,
`Settings.Values`). As a result, queries that use those aliases stopped
working against the new table, and the doc's "same columns except
`LowCardinality`" contract was false.

Carry over `QueryLogElement::getNamesAndAliases` as well, de-LowCardinality-ing
the alias types the same way as the physical columns, so the new table exposes
exactly the same user-facing surface as `system.query_log`. The aliases are
computed by the outer query plan on top of the per-user-filtered, opaque
`ReadFromPreparedSource`, so they cannot observe other users' rows.

Extended `04515_user_query_log.sh` to check the alias column types are
de-LowCardinality-ed and that the aliases still resolve to the corresponding
`mapKeys`/`mapValues` of the physical columns.

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

Copy link
Copy Markdown
Member Author

CI note: the only non-green check is 02835_drop_user_during_session in Stateless tests (arm_asan_ubsan, targeted). This is a flaky "Test runs too long" timeout, not a functional failure:

  • The targeted check ran this test 34 times on this PR (its flaky-detection repetition); 29 passed, 5 failed, all with the "test runs too long" context under the arm_asan_ubsan sanitizer build.
  • The test has 0 failures on master in the last 60 days.
  • The test is a timing-sensitive session test (it polls system.processes up to 100×0.1s for concurrent sessions to appear); it is unrelated to this PR's logic, which only adds a plain system table and a conditional implicit SELECT grant — neither can make sessions disappear from system.processes.

@groeneai, could you take a look and confirm / open a tracking issue for the 02835_drop_user_during_session "runs too long" flakiness under arm_asan_ubsan? It appears to be pre-existing test fragility exposed by the targeted check hammering it many times on a slow sanitizer build, not a regression from this change.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed: pre-existing test fragility, not a regression from this PR.

CIDB (default.checks, 60d): 02835_drop_user_during_session has 0 FAIL/ERROR on master (16786 OK). Every "runs too long" FAIL is on arm_asan_ubsan only (targeted: 11 FAILs / 3 PRs, all "runs too long"). On this PR the targeted check ran it 34x (29 pass / 5 fail). Root cause is the test busy-polling on a slow sanitizer build: wait_for_queries_start (100x0.1s, x3) plus an unbounded final while true loop waiting for 9 matching LoginSuccess/Logout rows in system.session_log; under the many-times targeted repetition a single run occasionally crosses the 180s per-run backstop. The PR diff (new system.user_query_log + conditional implicit SELECT grant) cannot affect session lifecycle.

Tracking issue: #110190 (likely fix: add the long tag, which exempts the 180s flaky-check FAIL and cuts the targeted repeat count).

…d database

Address review: the startup guard for `system.user_query_log` only checked the raw
`query_log.database` value. `SystemLog::createSystemLog` coerces any non-`system`
database back to `system`, so a config like

    <query_log><database>foo</database><table>user_query_log</table></query_log>

still materializes a real `system.user_query_log` and only died later on a generic
"Table already exists" startup exception, bypassing the focused `BAD_ARGUMENTS`
message; the message wording was also misleading.

Drop the `query_log.database == system` condition so the guard fires on
`query_log.table = user_query_log` regardless of the configured database, and reword
the message. Add integration test `test_user_query_log_config_validation` covering
startup rejection for both a `system` and a non-`system` configured database.

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

The opaque `ReadFromPreparedSource` barrier protected the user filter from
plan-level optimizations, but it also stripped all predicate pushdown: every
lookup on `system.user_query_log` scanned the whole retained query log with
only the current-user filter, and `SELECT` on this table is implicitly granted
to every user.

The read is now built as a `SourceStepWithFilter`: the plan optimization
offers it the outer filter (and keeps the outer `FilterStep` in place, so the
full predicate is always re-applied on top), and a vetted subset of its
conjuncts is embedded into the internal query, restoring partition pruning and
index analysis on the backing table. A conjunct is pushed only when it
consists of logical connectives and comparisons (which cannot fail per row, so
they cannot act as an error-based oracle on other users' rows) over the
partition / point-lookup columns and constants whose values were already
computed by the outer query. The `LIKE` family additionally requires a
constant pattern, because a pattern from a cell is compiled per row and a
malformed one throws. The outer `LIMIT` is applied inside only when there is
no filter at all (the internal query applies the user filter before it).

Addresses the review finding on the PR.
alexey-milovidov and others added 2 commits July 18, 2026 10:48
The safe-predicate allow-list in `StorageSystemUserQueryLog` used the
names `lessOrEqual` and `greaterOrEqual`, but both analyzers emit the
`<=` and `>=` comparisons as functions named `lessOrEquals` and
`greaterOrEquals`. Because of the mismatch, those operators never
satisfied `pushable_functions.contains(function_name)`, so predicates
such as `event_date >= ...` or `query_start_time <= ...` stayed outside
the internal query and lost partition pruning and index analysis on the
backing `system.query_log` table.

Rename the two allow-list entries to the canonical function names, and
extend `04550_user_query_log_pushdown.sh` with a focused regression that
a `>=` and a `<=` predicate on the partition column each prune every
partition (read zero rows from the backing table), so this operator-name
mismatch cannot regress silently.

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

The `check_functional_test_cases` style check flagged
`04550_user_query_log_pushdown.sh` because it filtered `event_date >= today() + 2`,
and the rule bans `event_date` compared with `=` / `>=` against `today()` (it wants
`yesterday()` for a one-day buffer against midnight flakiness).

Rewrite the `04550_pruned_ge` predicate as the equivalent `event_date >= yesterday() + 3`
(`yesterday() + 3` folds to the same `Date` as `today() + 2`), so the predicate still
prunes every partition of the `event_date`-partitioned backing `system.query_log` and the
case still asserts `read_rows = 0`. The reference is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110156&sha=583dd0511086904fc4bfc10025c2b54045f24240&name_0=PR&name_1=Style%20check

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

`StorageSystemUserQueryLog::read` treated `Context::getQueryLog()` returning
`nullptr` as "no backing query log table exists" and returned an empty result.
That is wrong in `clickhouse-local --only-system-tables`: `LocalServer`
deliberately skips `initializeSystemLogs` there (so the live `QueryLog` object
is absent) while still loading the persisted `system` tables from disk, so the
configured `system.query_log` can be present and queryable. In exactly the mode
meant for inspecting existing system tables, `system.user_query_log` silently
went empty instead of filtering the loaded query log.

When the live `QueryLog` object is absent, resolve the backing table from the
`query_log.database` / `query_log.table` server settings (`system.query_log` by
default; a custom `query_log.database` is coerced back to `system` in
`createSystemLog`, so only the table name is configurable) and read it if it
exists, instead of equating "logger not running" with "query log not
configured".

Extends `04516_user_query_log_local.sh` with a regression test: a persistent
`system` database is seeded, a first invocation persists query log records, and
a second `--only-system-tables` invocation still sees the current user's own
records instead of an empty result.
…y log is configured

`StorageSystemUserQueryLog::read` resolved `system.<query_log.table>` from the catalog whenever
`Context::getQueryLog` returned nothing. That is the right thing for
`clickhouse-local --only-system-tables`, which skips starting the loggers while still loading the
persisted `system` tables, but `createSystemLog` also returns nothing when the `query_log` section is
missing from the configuration altogether, while a `system.query_log` table created by an earlier run
is still attached from disk on startup. So after removing `<query_log>` and restarting,
`system.user_query_log` kept reading that stale table instead of being empty, contrary to the
documented "the query log is not configured, so the table is empty" behavior.

Gate the resolution on a configured `query_log` section, and extend
`04516_user_query_log_local` with the case: after the persisted query log table is written, an
`--only-system-tables` run with the `query_log` section removed sees the table attached, while
`system.user_query_log` reads no rows.
…for the read

The internal query is built by an interpreter inside `ReadFromUserQueryLog::initializePipeline`, so
its processors were accounted to the steps of that internal query plan, which does not outlive the
call and is not part of the plan the outer query knows about. `EXPLAIN ANALYZE` populates its per-step
wall clocks from the explained plan and looks one up for every executed processor by its plan step
(`ExecutionThreadContext::executeTask`, `chassert(clock)`), so a processor of the internal query had
no clock: its time was not accounted to `ReadFromUserQueryLog`, and the assertion fired in a build
with assertions enabled.

Hand these processors to `ISourceStep::updatePipeline`, which accounts them to this step, the way
other source steps do. Now `EXPLAIN ANALYZE SELECT count() FROM system.user_query_log` reports the
time of the read (0.5 ms, 45% of the query) at `ReadFromUserQueryLog` instead of 770 ns, and
`EXPLAIN PIPELINE` describes the processors of the read.

`04516_user_query_log_local` runs `EXPLAIN ANALYZE` over the table, which covers the assertion in the
builds that enable it (a release build only silently misaccounts the time).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note on Stress test (amd_debug): Logical error: 'clock' (STID: 2508-42dd) — the assertion is chassert(clock) in ExecutionThreadContext::executeTask, which fires when an executed processor is accounted to a query plan step that is not in the per-step wall clock registry that EXPLAIN ANALYZE populates from the explained plan. The reported stack is an EXPLAIN ANALYZE query from the in-server AST fuzzer, and the failure predates this PR (the same test name fails on unrelated PRs on master: #107292, #110153, #109354, #110080, #101841, #109490, #106586 in the last 90 days, none of them related to system.user_query_log), so it is not a new regression here.

That said, system.user_query_log did have exactly this defect, so it is fixed in ed4723a: the internal query is built by an interpreter inside ReadFromUserQueryLog::initializePipeline, so its processors kept the steps of the internal query plan, which the explained outer plan knows nothing about. They are now handed to ISourceStep::updatePipeline, which accounts them to ReadFromUserQueryLog — so EXPLAIN ANALYZE SELECT count() FROM system.user_query_log reports the read as 0.5 ms / 45% of the query instead of 770 ns, and 04516_user_query_log_local now runs EXPLAIN ANALYZE over the table to cover the assertion.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's not as straightforward as I expected, but all good.

@alexey-milovidov alexey-milovidov self-assigned this Jul 31, 2026
log_table_id.getFullTableName(),
quoteString(outer_context->getClientInfo().initial_user));

if (String pushed_conditions = buildPushedDownConditions(); !pushed_conditions.empty())

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.

This reintroduces a side channel on other users' query_log rows through the probe query's own execution statistics. Once we splice caller-controlled predicates into the inner system.query_log read here, the backing scan is narrowed before the per-user filter, so a low-privilege user can probe for foreign activity with something like WHERE query_id = 'victim-id' or WHERE user = 'victim', then read the probe query's recorded read_rows (or just time it) back from their own system.user_query_log entry. 04550_user_query_log_pushdown.sh already demonstrates that these pushed predicates measurably change read_rows; because this feature exposes the caller's own query-log rows without extra grants, that measurement becomes a direct oracle on the global log.

I don't think the current allow-list can make this safe: even "harmless" columns like query_id, user, initial_user, current_database, or event_date leak whether matching foreign rows exist once their effect is observable through read_rows / runtime. The fix needs to keep caller-controlled predicates above the opaque ReadFromPreparedSource barrier again (or otherwise suppress those stats for this storage, which is much harder).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is expected but unavoidable.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 170/179 (94.97%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 2, 2026
Merged via the queue into master with commit 457fef9 Aug 2, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the user-query-log branch August 2, 2026 16:13
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 2, 2026

This branch was successfully deployed

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

Labels

pr-feature Pull request with new product feature 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.

A new system table, user_query_log

3 participants