Skip to content

Add a new system table user_query_log - #104462

Closed
niyue wants to merge 38 commits into
ClickHouse:masterfrom
niyue:feat/user-query-log
Closed

niyue wants to merge 38 commits into
ClickHouse:masterfrom
niyue:feat/user-query-log

Conversation

@niyue

@niyue niyue commented May 9, 2026

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry:

  • Added system.user_query_log system table that allows users to read only their own query log records without direct access to system.query_log.

Documentation entry for user-facing changes

  • Documentation is written

This PR will address #82539

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4c40b2a]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6) FAIL
test_search_orphaned_parts/test.py::test_search_orphaned_parts[False] FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_checking_s3_blobs_paranoid/test.py::test_upload_after_check_works FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[none] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[gzip] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[br] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[xz] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[zstd] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[bz2] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[deflate] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_create_multi_part_upload[lz4] FAIL cidb
test_checking_s3_blobs_paranoid/test.py::test_upload_s3_fail_upload_part_when_multi_part_upload[none] FAIL cidb
26 more test cases not shown
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) FAIL
test_s3_aws_sdk_has_slightly_unreliable_behaviour/test.py::test_dataloss FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED

AI Review

Summary

This PR adds system.user_query_log as a filtered security-barrier view over the query log, along with startup wiring, reserved-name protection, introspection support, and focused tests. The main remaining issue is a user-visible contract mismatch: the new docs say the view follows both query_log.database and query_log.table, but the underlying SystemLog code still forces system logs back into the system database.

Findings

⚠️ Majors

  • [docs/en/operations/system-tables/user_query_log.md:34] The new docs say the view follows query_log.database / query_log.table, but createSystemLog still rewrites any non-system database back to system in src/Interpreters/SystemLog.cpp:150-163. Users who configure query_log.database = my_logs will still get system.<table>, so this wording over-promises behavior the server does not implement.
    Suggested fix: either lift the SystemLog restriction in the same PR, or narrow the docs and shipped config comments to say that the view follows the configured query_log.table in the system database.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 9, 2026
Comment thread src/Storages/StorageView.cpp Resolved
@niyue
niyue force-pushed the feat/user-query-log branch from ea9e2d4 to bca687e Compare May 10, 2026 13:58
@niyue

niyue commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov,

This PR is ready for review, could you please help? Thanks.

@alexey-milovidov

Copy link
Copy Markdown
Member

The FileCacheTest.SLRUFreeSpaceKeepingProtectedOnly failure on this PR is a known flaky test that was fixed in #104418. Could you please update the branch with the latest master to pick up the fix?

niyue added 10 commits May 13, 2026 09:40
Introduce a  security barrier mode that prevents view inlining and outer filter pushdown, and exposes barrier view columns without wrappers. Use it so user-supplied predicates cannot evaluate against filtered-out values.
Expose `attachSystemUserQueryLog` so `clickhouse-local` can create `system.user_query_log` after `initializeSystemLogs` creates `system.query_log`.
Add the required `current_database = currentDatabase()` predicate to `system.query_log` and `system.user_query_log` queries in the stateless test, so the query log style check accepts the test and concurrent test logs are ignored.

Issue: ClickHouse#82539
@niyue
niyue force-pushed the feat/user-query-log branch from 01c8e4d to a6045a2 Compare May 13, 2026 01:45
@niyue

niyue commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Thanks for the guidance. I've updated the branch with the latest master.

@niyue
niyue force-pushed the feat/user-query-log branch from 460b718 to ffd3010 Compare May 13, 2026 15:06
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed a follow-up (0dd9b82) addressing the AI Review verdict.

Major — additional_table_filters guard was too broad. The previous guard rejected any non-empty additional_table_filters map whenever a query touched system.user_query_log, even for entries targeting unrelated outer tables (e.g. {'system.one': ...} in a join) or the view itself. Since additional_table_filters is table-scoped, this regressed valid queries.

Instead of rejecting the whole query, I now strip additional_table_filters from the barrier viewʼs inner query context in getViewContext. This is the single choke point for both analyzers and every access path, so a filter keyed on the inner source table (system.query_log) can never be evaluated inside the barrier and observe hidden rows, while filters targeting unrelated tables in the outer query keep working (they are applied in the untouched outer context). The readImpl reject for additional_result_filter is kept — it is not table-scoped and has no safe outer-only case, and it already has the more precise getSecurityBarrierViewName guards in Planner.cpp.

The regression test 04402 was updated: the inner-source filter is now silently neutralized (no leak, no exception) rather than rejected, and it additionally verifies that an unrelated-table filter and a view-name filter are accepted.

Nit — stale doc. Updated the enable_user_query_log description in _server_settings_outside_source.md to match system.user_query_log: it reads from the configured query_log.database / query_log.table and filters by the initiating user.

The only red CI check, BuzzHouse (arm_asan_ubsan) (Logical error: ScatterExchangeStep should have one source shard), is unrelated to this PR — it is a pre-existing distributed-plan / Merge fuzzer bug tracked in #107946 and reproduces across many unrelated PRs.

The test starts its own `clickhouse server` to exercise `system.user_query_log`
over a `Null`-engine query log. It derived five listen ports (TCP, HTTP, MySQL,
PostgreSQL, interserver) from `$$ % 20000`, i.e. the range 20000..40000, which
overlaps the Linux ephemeral port range. In the highly parallel stateless test
run another server (or an ephemeral socket) could already hold one of them, so
the server aborted on startup with `Address already in use` and the readiness
loop timed out. CI observed this on the unused `postgresql_port`, and the
randomized-settings diagnosis reran the test 44 times without a single failure,
confirming a transient port clash rather than a real regression.

Fix: the test only connects over the native TCP protocol, so configure just
`tcp_port` (dropping the four unused ports), obtain it from the OS with a
`bind(('127.0.0.1', 0))` probe instead of the PID, and wrap startup in a small
retry loop that picks a fresh port if the server still races another process
for the port and exits before becoming ready.

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

Copy link
Copy Markdown
Member

Pushed cbb783888e6 fixing a flaky test that this PR added.

Flaky 04342_user_query_log_null_engine. The test starts its own clickhouse server and derived five listen ports (TCP/HTTP/MySQL/PostgreSQL/interserver) from $$ % 20000 (range 20000..40000, which overlaps the Linux ephemeral port range). In the parallel stateless run another server or an ephemeral socket could already hold one of them, so the server aborted on startup with Address already in use and the readiness loop timed out. The failure surfaced on the (unused) postgresql_port, and the randomized-settings diagnosis reran the test 44/44 times without a failure — a transient port clash, not a real regression.

Fix: the test only connects over native TCP, so it now configures just tcp_port (the four unused ports are dropped), obtains it from the OS with a bind(('127.0.0.1', 0)) probe instead of the PID, and retries with a fresh port if the server still loses the port race before becoming ready.

Unrelated CI failure — AST fuzzer Logical error: '!part.empty()'. This is not caused by this PR. It crashes in IdentifierNode::toASTImpl → the ASTIdentifier constructor (ASTIdentifier.cpp:48) while converting a query tree back to AST for EXPLAIN SYNTAX ... query_tree_passes = 1 on a fully fuzzer-generated query with pathological backtick identifiers (e.g. `10.0.0.1`.`3-1`.field); the query does not touch system.user_query_log, views, or the query log, and this PR does not modify any of ASTIdentifier, IdentifierNode, IQueryTreeNode::toAST, or InterpreterExplainQuery. It is a pre-existing bug: over the last 30 days it hit 6 distinct unrelated PRs (this one, #107585, #109085, #92323, #98533, #108725), all on master.

@groeneai, please investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104462&sha=0dd9b82adc98005d1c9b47e1c0836e336256cf68&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR. If a fix or tracking issue already exists, please link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Thanks. This is the known chronic trunk bug, STID 2508-2ef2 (Logical error: '!part.empty()'), not caused by this PR. We are tracking it.

Root cause: a backquoted identifier that contains or ends in a dot (e.g. `10.0.0.1`, `3-1`, or a trailing-dot name) is stored with an empty name-part after boost::split(..., '.'). When the query tree is converted back to AST (here for EXPLAIN SYNTAX query_tree_passes = 1), IdentifierNode::toASTImpl rebuilds ASTIdentifier from those parts and hits chassert(!part.empty()) at src/Parsers/ASTIdentifier.cpp:48, which aborts in debug/sanitizer builds.

Existing fix: #108735 ("Fix logical error when a lambda argument is a backquoted dotted identifier"), approved by @vdimir, open and awaiting merge. It fixes the lambda-argument path in src/Analyzer/LambdaNode.cpp (an atomic lambda arg name was re-split on dot into an empty trailing part).

Caveat, and why #108735 alone likely does not close this instance: your failing query does not use a dotted lambda argument. The empty-part identifier here is a qualified-asterisk qualifier / compound backtick identifier inside EXPLAIN SYNTAX (`-170141183460469231731687303715884105728`.`1-1`.* and `10.0.0.1`.`3-1`.field), which reconstructs ASTIdentifier through a different toASTImpl route than the LambdaNode path #108735 touches. So the same ASTIdentifier.cpp:48 assertion can still fire after #108735 lands.

Plan: once #108735 is on master (or applied to a local debug build) I will re-run your exact EXPLAIN SYNTAX query. If it still aborts, I will fix it deeper (at the ASTIdentifier / IdentifierNode::toASTImpl reconstruction so empty/embedded-dot name-parts round-trip safely for the qualified-asterisk / qualifier path), add a regression test covering the edge matrix (leading dot, trailing dot, double dot, quoted vs unquoted, lambda-arg vs qualifier vs column), and open a follow-up PR linked back here.

Comment thread src/Databases/DatabasesCommon.cpp Resolved
niyue added 2 commits July 10, 2026 15:40
Explain that an existing object using the newly reserved name must be renamed or dropped before upgrading, and document the related `query_log` configuration change.
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Dear @jkartseva, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.


## Columns {#columns}

The columns match the configured query log table, which uses the same structure as [`system.query_log`](query_log.md), except `LowCardinality` wrappers are removed from exposed column types.

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.

except LowCardinality wrappers are removed from exposed column types.

Why?

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.

The wrapper removal is what keeps the barrier view from exposing the underlying LowCardinality encoding to outer expressions. Without materializing to the dictionary type, the visible schema can still carry storage-level dictionary state from rows the barrier filtered out, which breaks the point of treating the view output as an already-sanitized row set.

"functions", /// Can contain user-defined functions

/// View over `system.query_log` filtered by the current user.
"user_query_log",

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.

Why don't we require an explicit grant?
So the user will need a grant to the user_query_log view, but not to the query_log.

At least an explicit grant will allow us not to give access to this table, as the queries can be resource-intensive.

Also, why do we use SQL_SECURITY NONE instead of DEFINER? As the view is created by the server, it should be equivalent, shouldn't it?

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.

The current implementation follows the feature contract this PR documents: ordinary users can inspect their own rows without needing either direct access to system.query_log or a separate rollout of grants on the filtered view. If the product decision is that access should be opt-in instead, that is a compatible policy change, but it is separate from the barrier-isolation mechanism itself.

bool supportsTruncate() const override { return false; }
bool isParameterizedView() const { return is_parameterized_view; }
bool isSecurityBarrier() const { return security_barrier; }
bool allowsViewInlining() const { return !security_barrier; }

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.

What/why?

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.

allowsViewInlining is the guard that keeps both analyzers from rewriting a barrier view back into a transparent subquery. Once the view is inlined, outer predicates and setting-derived filters can be planned directly against the inner source, which is exactly the leak this flag is preventing.


protected:
bool is_parameterized_view;
bool security_barrier;

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.

Why do we have all those complications?

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.

The extra state is there because a barrier view has to diverge from an ordinary StorageView in several later code paths: it must not be inlined, it must strip inner additional_table_filters, and it must reject additional_result_filter. After the AST is parsed those call sites only see a StorageView, so they need a persistent flag to choose the fail-closed path.

const size_t /*max_block_size*/,
const size_t /*num_streams*/)
{
if (security_barrier)

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.

Why?

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.

additional_result_filter is query-wide rather than table-scoped, so there is no safe way to keep only the dangerous part out of the barrier. Unlike additional_table_filters, it cannot be neutralized per inner source table, so the fail-closed behavior here is to reject it when a security-barrier view participates in the query.

/// predicate. Strip the setting from the inner query context so it can never be applied there,
/// while filters targeting unrelated tables in the outer query keep working - those are applied
/// in the outer context, which is left untouched.
if (view->isSecurityBarrier())

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.

I'm sure we should approach it differently.
For example, all SQL SECURITY (other than INVOKER) views can't use additional_table_filters.

Comment thread programs/server/config.xml Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 226/257 (87.94%) · Uncovered code

Full report · Diff report

`SystemLog` creates its backing table lazily, on the first flush, but the
`system.user_query_log` view is exposed as soon as it is attached at startup.
On a freshly started server the very first read from the view therefore failed
with `UNKNOWN_TABLE`, because the inner `SELECT` targets a table that does not
exist yet:

    Code: 60. DB::Exception: Unknown table expression identifier 'system.query_log'
    in scope SELECT * FROM system.query_log WHERE if(initial_user != '', initial_user, user) = currentUser().

Prepare the configured query log table in `attachSystemUserQueryLog` right
before attaching the view, so that the view is readable (and empty) from the
moment it appears. A system log does not create its own database, so this is
only done when the configured database has already been loaded - which is
always the case for the default `system` database, as it is loaded before
system tables are attached.

Also refresh the stale `enable_user_query_log` comment in the shipped
`config.xml`: the view reads the configured query log table, which is not
necessarily `system.query_log`, and it filters by the initiating user.

Addresses the AI review findings on
ClickHouse#104462
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current `master` and addressed the AI review findings (commit 4c40b2a):

  • Major (attachSystemTables.cpp, also raised by the bot thread on line 323): SystemLog creates its backing table lazily on the first flush, so on a freshly started server the first SELECT FROM system.user_query_log failed with UNKNOWN_TABLE. Reproduced locally:
    Code: 60. DB::Exception: Unknown table expression identifier 'system.query_log' in scope
    SELECT * FROM system.query_log WHERE if(initial_user != '', initial_user, user) = currentUser(). (UNKNOWN_TABLE)
    
    attachSystemUserQueryLog now calls prepareTable on the configured query log before attaching the view, guarded on the configured database already being loaded (a system log does not create its own database; the default system database is always loaded before system tables are attached).
  • New regression test 04652_user_query_log_before_first_flush — starts a server with a 10-minute flush_interval_milliseconds and reads the view before anything is flushed. Verified it fails with UNKNOWN_TABLE without the fix and passes with it; 04342 and 04341 still pass locally.
  • Nit: refreshed the stale enable_user_query_log comment in programs/server/config.xml to say the view reads the configured query log table and filters by the initiating user (initial_user, falling back to user).

The 7 open threads from @alexey-milovidov (explicit grant vs. implicit access, SQL SECURITY NONE vs. DEFINER, the security_barrier machinery, and generalizing the additional_table_filters restriction to all non-INVOKER SQL SECURITY views) are design questions for @niyue and @alexey-milovidov — I have not touched them.


## Description {#description}

The `system.user_query_log` table is a view over the query log table configured by the `query_log.database` and `query_log.table` server configuration parameters. By default, this is `system.query_log`. The view returns only rows where the initiating user is equal to the result of `currentUser()`. For distributed query log rows, the initiating user is stored in `initial_user`; otherwise, `user` is used.

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.

query_log.database is still not honored here. createSystemLog rewrites any non-system database back to system in src/Interpreters/SystemLog.cpp:150-163, so this wording currently promises behavior the server does not implement: a user can set query_log.database = my_logs, read this page, and expect system.user_query_log to read my_logs.<table>, but the runtime still uses system.<table>.

Either lift that SystemLog restriction in the same PR, or narrow the docs/comments to say that the view follows the configured query_log.table in the system database.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Closing this PR: the feature has been merged into master via #110156, a simplified reimplementation (ENGINE = SystemUserQueryLog system table instead of an auto-created SQL SECURITY NONE view) that resolves the open design threads here (explicit security-barrier machinery, reserved-name guards, additional_table_filters/additional_result_filter handling, and the read-before-first-flush UNKNOWN_TABLE case). It closed #82539 and is available since 26.8.

The idea and the original implementation belong to @niyue, as credited in the changelog entry of #110156 — the integration test for the distributed initial_user semantics was taken from this PR as well. Thank you for the contribution and for the many review iterations that shaped the final design!

Related: #110156

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants