Skip to content

Fix currentUser() being empty during async_insert flush - #107541

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-current-user-107530
Jun 17, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-current-user-107530

Conversation

@groeneai

@groeneai groeneai commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #107530

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 currentUser(), user(), SESSION_USER and authenticatedUser() evaluating to an empty string on the asynchronous insert flush path (with async_insert = 1). This affected DEFAULT/MATERIALIZED column expressions and materialized views that reference these functions, which silently stored an empty string instead of the inserting user.

Description

Reported in #107530 (confirmed on master, 26.5, 26.4, 26.3, 26.2, 26.1; present since at least v24.1).

Root cause: with async_insert = 1, the rows are written later on a background flush thread. AsynchronousInsertQueue::processData builds the flush context from the server global context (which carries an empty ClientInfo) and then calls only Context::setUser. setUser restores the access-control identity (user id, profiles, roles, default database) but not the ClientInfo user-name strings (current_user/initial_user/authenticated_user). currentUser() reads ClientInfo.initial_user, so it returned an empty string on the flush path and in every materialized view the flush triggered. The synchronous path sets these names in Session::makeQueryContextImpl and was unaffected, so the same DEFAULT currentUser() column recorded the user for async_insert = 0 but an empty string for async_insert = 1.

Fix: capture the originating query's ClientInfo identity (current_user, initial_user, authenticated_user) into AsynchronousInsertQueue::InsertQuery when the insert is queued, and restore it onto the flush context in processData. The identity is included in the batching key so inserts issued by different users (e.g. impersonation / EXECUTE AS, forwarded distributed queries) are never coalesced into a single flush.

Added a stateless regression test (04338_async_insert_current_user) covering a DEFAULT currentUser() column, a MATERIALIZED currentUser() column, and a materialized view selecting currentUser(), asserting the async-flushed value matches the inserting user. The test fails without the fix (async rows record an empty string) and passes with it.

Version info

  • Merged into: 26.6.1.946

On the async_insert flush path, AsynchronousInsertQueue::processData built
the flush context from the server global context (empty ClientInfo) and only
called Context::setUser, which restores the access-control identity (user id,
profiles, roles, default database) but not the ClientInfo user-name strings.
As a result currentUser()/user()/SESSION_USER/authenticatedUser() evaluated to
an empty string in DEFAULT/MATERIALIZED column expressions and in the
materialized views triggered by the flush, silently corrupting audit/ownership
columns. The synchronous path sets these names via Session::makeQueryContextImpl
and is unaffected.

Capture the originating query's ClientInfo identity (current_user, initial_user,
authenticated_user) into AsynchronousInsertQueue::InsertQuery at push time and
restore it onto the flush context in processData. The identity is part of the
batching key so inserts from different identities are never coalesced into one
flush.

Closes ClickHouse#107530

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (x Int32, u String DEFAULT currentUser()) ENGINE=MergeTree ORDER BY x; INSERT INTO t(x) SETTINGS async_insert=1, wait_for_async_insert=1 VALUES (1); INSERT INTO t(x) SETTINGS async_insert=0 VALUES (2); SELECT x,u FROM t ORDER BY x; → async row records u='', sync row records the user, every time.
b Root cause explained? Yes. currentUser() reads ClientInfo.initial_user. The async flush (AsynchronousInsertQueue::processData) copies the server global context (empty ClientInfo) and calls only Context::setUser, which restores the access-control identity (user id, profiles, roles, DB) but NOT the ClientInfo user-name strings. So current_user/initial_user/authenticated_user stay empty → currentUser()='' on the flush and in its MVs. The sync path sets these names in Session::makeQueryContextImpl, hence the divergence.
c Fix matches root cause? Yes. Capture current_user/initial_user/authenticated_user from the originating query's ClientInfo into InsertQuery at push time, and restore them onto the flush context in processData via setCurrentUserName/setInitialUserName/setAuthenticatedUserName (new symmetric setter). No symptom guard — it restores the missing state at the exact point the sync path sets it.
d Test intent preserved / new tests added? New test 04338_async_insert_current_user added: asserts the async-flushed currentUser() matches the inserting user for a DEFAULT column, a MATERIALIZED column, and an MV. Existing unit test gtest_async_insert_key updated for the new ctor signature; its keying intent (settings-driven equality) is preserved (identity left empty for all 4 keys).
e Both directions demonstrated? Yes. Without the fix the new test FAILS (async rows: default_matches=0, default_non_empty=0); with the fix it PASSES 30/30 with randomization enabled. Both runs on Build-ID-verified binaries (fixed e86683e9…, baseline e63c88e6…).
f Fix is general, not a narrow patch? Yes. The identity is restored once on the flush context, so all three readers (currentUser/user/session_user → initial_user; authenticatedUser → authenticated_user) and every MV the flush triggers are covered, not just one call site. Identity is folded into the batching key/hash so inserts from different users are never coalesced.

Session id: cron:clickhouse-worker-slot-5:20260615-160100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @CurtizJ — could you review this? It restores the originating query's ClientInfo identity (current_user/initial_user/authenticated_user) on the async_insert flush context, so currentUser()/user()/authenticatedUser() and the MVs the flush triggers see the inserting user instead of an empty string. The identity is folded into the InsertQuery batching key so inserts from different users are never coalesced.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jun 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12e12d6]

Summary: ✅


AI Review

Summary

This PR restores the originating query ClientInfo user identity when flushing async_insert batches, and keeps that identity in the async insert batching key. I found no remaining correctness issues after the prior hash-boundary and authenticatedUser regression-test comments were addressed in the current code.

Missing context / blind spots
  • ⚠️ The direct Praktika PR report from the bot-linked S3 URL currently returned zero test entries, and this checkout has no build* directory, so I did not independently run gtest_async_insert_key or the new stateless tests.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 15, 2026
The async insert queue is indexed by InsertQuery::hash alone
(QueueIteratorByKey = unordered_map<UInt128, QueueIterator>), and equality
is never consulted on the push path. SipHash::update(String) streams only
the bytes, so concatenating the three identity strings without a delimiter
makes ("a","a","aaa") and ("aa","aa","a") hash to the same value: the
second insert would be appended to the first user's pending batch and
flushed under the wrong ClientInfo, which is the same wrong-user corruption
this change set is meant to prevent.

Hash each identity field with its length prefix so distinct triples produce
distinct hashes. Add a key unit test covering the collision boundary cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…t flush

The existing 04338 test only asserts currentUser() (ClientInfo.initial_user),
so it would still pass if setAuthenticatedUserName were removed or mis-wired:
authenticatedUser() reads a different field (ClientInfo.authenticated_user).

This test uses EXECUTE AS so currentUser() and authenticatedUser() diverge
(impersonated user vs originally authenticated user) and asserts both are
restored independently on the async-insert flush path, in DEFAULT columns and
in a materialized view. Verified the async/MV assertions fail when
setAuthenticatedUserName is removed and pass with the fix.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up: authenticatedUser test coverage, commit 12e12d6)

# Question Answer
a Deterministic repro? Yes. EXECUTE AS app_user then async INSERT into a table with DEFAULT authenticatedUser(): the async-flushed row records an empty authenticatedUser() without the fix, on demand.
b Root cause explained? currentUser() reads ClientInfo.initial_user, authenticatedUser() reads ClientInfo.authenticated_user (a different field). The async flush context is built from global_context (both empty) and setUser restores only the access identity. The fix's setAuthenticatedUserName restores authenticated_user; 04338 only asserted currentUser(), so it could not detect that field being unset or mis-wired.
c Fix matches root cause? N/A here (no code change in this commit). The new test locks in the authenticatedUser() half of the already-pushed fix.
d Test intent preserved / new tests added? New test 04339_async_insert_authenticated_user.sh added; 04338 unchanged. EXECUTE AS makes currentUser() and authenticatedUser() diverge, so it asserts au = auth_user and cu != au for an async insert, a sync control, and a materialized view.
e Both directions demonstrated? Yes. With setAuthenticatedUserName commented out the async row and MV row report au_is_authenticated = 0 (sync row stays correct); with the fix all rows pass. Stable over repeated runs. Build-ID verified between binaries.
f Fix is general, not a narrow patch? The fix already restores all three user-name fields together; this commit extends test coverage to the authenticated_user field that diverges from initial_user only under impersonation.

Session id: cron:clickhouse-worker-slot-1:20260615-181200

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 81/90 (90.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov 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.

This is good! Thank you!

@alexey-milovidov alexey-milovidov self-assigned this Jun 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 12e12d6557d1. All checks pass except non-gating ones:

  • CH Inc sync (fail) — internal clickhouse-private mirror sync, not a public gate.
  • Bugfix validation (functional tests) rows (OOM in dmesg / Lost s3 keys / Lost forever for SharedMergeTree / S3_ERROR No such key / Exception in test runner) — standard bugfix-validation infra noise, identical across the current PR queue, no real test rows.

No PR-caused failures. The async_insert currentUser/authenticatedUser fix, the length-prefixed identity hashing, and both regression tests (04338 + 04339 EXECUTE AS) pass. Ready for review.

Session id: cron:our-pr-ci-monitor:20260615-233000

@alexey-milovidov
alexey-milovidov merged commit edb9295 into ClickHouse:master Jun 17, 2026
165 of 166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 17, 2026
alexey-milovidov added a commit that referenced this pull request Nov 2, 2026
…flush context

On 26.3 `async_insert` is enabled by default, and the flush context of
`AsynchronousInsertQueue` is built from the global context with only
`Context::setUser`, so its `ClientInfo` user names are empty. A direct
`INSERT` into a `Distributed` table over a cluster with an interserver
`<secret>` was therefore flushed to the shard with an empty `initial_user`,
which the shard executes in interserver mode with full access. This is the
same hole that #117798 closes for the definer of `SQL SECURITY DEFINER`
views, and `test_streaming_engines_definer_interserver_secret::test_rabbitmq[tenant]`
caught it in its control case: the tenant's direct insert was accepted on the
shard.

Bring the fix from #107541 (merged to master in edb9295): capture
`current_user`, `initial_user` and `authenticated_user` in the async insert
queue key at push time and restore them on the flush context. The only
conflict is in `InsertQuery::toTupleCmp`, where 26.3 already uses
`query_str_with_secrets` instead of `query_str`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128668&sha=0dc411340520ff9f52dfdb04638aa63196712372&name_0=BackportPR&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29
PR: #128668
Related: #107541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…flush context

On 26.3 `async_insert` is enabled by default, and the flush context of
`AsynchronousInsertQueue` is built from the global context with only
`Context::setUser`, so its `ClientInfo` user names are empty. A direct
`INSERT` into a `Distributed` table over a cluster with an interserver
`<secret>` was therefore flushed to the shard with an empty `initial_user`,
which the shard executes in interserver mode with full access. This is the
same hole that #117798 closes for the definer of `SQL SECURITY DEFINER`
views, and `test_streaming_engines_definer_interserver_secret::test_rabbitmq[tenant]`
caught it in its control case: the tenant's direct insert was accepted on the
shard.

Bring the fix from #107541 (merged to master in edb9295): capture
`current_user`, `initial_user` and `authenticated_user` in the async insert
queue key at push time and restore them on the flush context. The only
conflict is in `InsertQuery::toTupleCmp`, where 26.3 already uses
`query_str_with_secrets` instead of `query_str`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=128668&sha=0dc411340520ff9f52dfdb04638aa63196712372&name_0=BackportPR&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29
PR: #128668
Related: #107541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-bugfix Pull request with bugfix, not backported by default 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.

currentUser() evaluates to empty during async_insert flush

4 participants