Skip to content

Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log - #115596

Merged
diegomestre2 merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/query-thread-log-progress-per-query
Aug 21, 2026
Merged

diegomestre2 merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/query-thread-log-progress-per-query

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105246

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):

Fix read_rows, read_bytes, written_rows and written_bytes in system.query_thread_log reporting a thread lifetime running total instead of the values for the logged query. Rows of long-lived pooled threads, in particular the query's initiating HTTPHandler thread, were affected.

Description

ThreadStatus::progress_in and progress_out live as long as the OS thread, and the four progress columns are read straight off them. Nothing ever cleared them, so for a pooled thread the row reported everything that thread had ever served. Worker threads get a fresh ThreadStatus, so the victim is the row with thread_id = master_thread_id.

ThreadStatus::initPerformanceCounters() already exists for this, runs on attach to a thread group, and says "Clear stats from previous query if a new query is started". It resets performance_counters and memory_tracker but never these two members, which predate it. The fix adds them.

Before the fix, over HTTP on one connection, four identical SELECTs each reading 200000 rows:

query_log.read_rows query_thread_log.read_rows same row's ProfileEvents['SelectedRows']
200000 1000000 200000
200000 1200000 200000
200000 1400000 200000
200000 1600000 200000

After the fix all three agree. Four identical INSERTs behaved the same way on written_rows, and are covered.

One semantic point to confirm, since it is a choice: this reset runs per attach to a thread group, not per query, so a thread logged on several rows for one query reports each attach cycle separately. ProfileEvents on the same row already behaves this way, so the two become consistent rather than gaining a new convention. Populating the columns from SelectedRows/InsertedRows instead was rejected: it redefines them and would tie them to log_profile_events.

Query-level accounting is untouched: query_log, system.processes, max_rows_to_read, leaf limits, throttling and quotas read the separate QueryStatus object, and I checked each of those.

The test drives the queries over HTTP on one keep-alive connection: over the native protocol the reads happen on a separate pipeline thread, so the initiating thread's row would assert nothing. It fails on master.

@PedroTadim

Validation
  • Negative control on a pristine master binary: all four assertion lines move (distinct read_rows 1 to 4, distinct written_rows 1 to 4, and every column comparing a progress value against ProfileEvents moves on both arms). Reproduced under randomized settings too.
  • New test passes on the fixed build, 50 of 50 randomized runs, and 12 concurrent copies over 6 workers.
  • Of the ten other stateless tests touching query_thread_log, the eight runnable in my sandbox still pass; the remaining two need a listener this sandbox does not provide, and neither reads the four columns.
  • Verified progress_in/progress_out on ThreadStatus have two writers (CurrentThread::updateProgressIn/Out), one reader (the log site), and no other reference in src/, programs/, base/, utils/.

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

Version info

  • Merged into: 26.8.1.1838 (included in 26.8 and later)
  • Backported to: 26.7.6.28, 26.6.4.9, 26.3.29.9, 25.8.34.9

groeneai and others added 2 commits August 20, 2026 08:37
system.query_thread_log.read_rows, read_bytes, written_rows and written_bytes
are read straight off ThreadStatus::progress_in and progress_out, which live
for the lifetime of the OS thread. Nothing ever cleared them, so the row of a
long-lived pooled thread reported the running total of everything that thread
had ever served rather than the values for the logged query. Short-lived worker
threads were unaffected because they get a fresh ThreadStatus, so the visible
victim is the row with thread_id = master_thread_id, i.e. the query's
initiating HTTPHandler thread.

Measured before this change, over HTTP on one connection, with four identical
SELECTs each reading exactly 200000 rows: query_log.read_rows was 200000 every
time and so was the same log row's ProfileEvents['SelectedRows'], while
query_thread_log.read_rows climbed 1000000, 1200000, 1400000, 1600000. Four
identical INSERTs behaved the same way on written_rows.

ThreadStatus::initPerformanceCounters() already exists for this purpose, runs
on attach to a thread group from its single call site in attachToGroupImpl,
and carries the comment "Clear stats from previous query if a new query is
started". It resets performance_counters and memory_tracker but never these
two members, which predate the hook. Adding them there completes the existing
mechanism instead of introducing a new one.

The reset is per attach to a thread group rather than per query, so a thread
logged on several rows for one query reports each attach cycle separately.
That is what performance_counters, and therefore ProfileEvents on the same
row, already does, so the two fields become consistent.

Query-level accounting is untouched: system.query_log, system.processes,
max_rows_to_read, leaf limits, speed throttling and quotas all read the
separate progress object on QueryStatus, and each was verified to still
behave correctly.

The regression test drives its queries over HTTP through a single keep-alive
connection, because over the native protocol the reads happen on a separate
pipeline thread and the initiating thread's row would assert nothing. It
asserts that the value no longer accumulates across queries, that it agrees
with the same row's ProfileEvents for both rows and bytes, and that it never
exceeds query_log; it also asserts the precondition that four queries finished
on one reused thread, so the oracle cannot pass vacuously. It fails on master.
The previous assertions were satisfiable by a master row whose thread-level
values are all zero, which happens whenever the initiating thread performs no
reads itself (measured over the native protocol, and reachable over HTTP under
parallel replicas). On such a configuration the test passed silently and would
keep passing after a regression.

Each precondition line now also pins the master row's value to the per-query
amount with non-zero bytes, so an all-zero row can no longer satisfy it. On a
row set constructed to be all zero the earlier assertions all matched the
reference while the new columns print 0 against a reference of 4.

Adds the missing written_bytes vs InsertedBytes assertion: written_bytes is one
of the four columns this change fixes and nothing covered it. On the unfixed
binary it accumulates 400000 to 1600000 across four inserts while InsertedBytes
stays correct at 400000, so the column reddens on its own.

Tags no-parallel-replicas, since parallel replicas move the reads off the
initiating thread. Both consumers of the tag were checked: the settings
randomizer stops promoting enable_parallel_replicas, and the feature-tag
override forces it off unconditionally.

Also fixes two style-check failures in the test itself: the log-table queries
now filter on current_database = currentDatabase(), and SYSTEM FLUSH LOGS is
wrapped in a bounded retry because the query_log entry is written after the
HTTP response returns.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open findings)

Reviewed by an independent model twice, plus my own cold review of the resulting code. Round 1 bounced the test back for hardening; round 2 returned no findings.

❌ Blockers: none.

⚠️ Major, both fixed before this PR was opened

  • The test was satisfiable by an all-zero row. Four master rows all reading 0 satisfied every round-1 assertion, and that state is reachable: over the native protocol the initiating thread reads nothing at all, and parallel replicas move the reads off it the same way. The test would have passed silently through a regression. Each precondition line now also pins the master row to the per-query amount with non-zero bytes, so an all-zero row fails it, and the test is tagged no-parallel-replicas. Both consumers of that tag were checked rather than assumed: the settings randomizer stops promoting enable_parallel_replicas, and the feature-tag override forces it off.
  • written_bytes was named in the changelog entry but asserted nowhere. Added the written_bytes vs InsertedBytes comparison, so all four fixed columns are covered. On the unfixed binary that column accumulates 400000 to 1600000 across four inserts while InsertedBytes stays correct, so it reddens on its own.
  • Two false counts in this PR's own description. The validation notes claimed all four rows disagree with ProfileEvents on both arms (true for SELECT, three of four for INSERT, because the first query on a fresh thread starts from zero and coincidentally matches), and undercounted the neighbouring tests. Both sentences now say what was measured, including that two of the ten neighbours need a listener my sandbox does not provide.

💡 Noted, no action

  • Async insert cannot perturb the INSERT arm: the async path is refused for any INSERT carrying a SELECT. Worth stating because WaitForAsyncInsertSource is the one place that reports progress without the matching ProfileEvents increment.
  • Test number 05023 is shared with another test. Duplicate numbers are common in the suite, the style check only flags gaps, and per-test databases key on the name.

Rounds: 1 approach gate, 2 code-review gates, 1 fix round.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Four identical queries over HTTP on one keep-alive connection; the master row's read_rows is wrong on every run, no retries and no timing involved. Encoded as the new test.
b Root cause explained? Yes. ThreadStatus::progress_in/progress_out (src/Common/ThreadStatus.h:203-204) live as long as the OS thread and are read directly by logToQueryThreadLog (ThreadStatusExt.cpp:747-751). initPerformanceCounters() (:535) is the per-attach reset hook and clears performance_counters and memory_tracker but never these two, so a pooled thread reports its lifetime total.
c Fix matches root cause? Yes. The two members are cleared at the subsystem's own established reset point, on its single call site (:404). Nothing is widened, tagged or guarded at the read site. The snapshot-and-subtract alternative was rejected for leaving the member semantically inconsistent.
d Test intent preserved / new tests added? New coverage; no existing assertion touched. None of the 12 stateless tests mentioning query_thread_log asserted these columns. The new test checks non-accumulation, agreement with the same row's ProfileEvents for rows and bytes on both arms, a bound against query_log, and preconditions that guard the oracle against becoming vacuous: each arm pins the master row's value to the per-query amount with non-zero bytes, so a row whose initiating thread read nothing can no longer satisfy the equalities. Verified by construction: on a configuration where the master row is all zeroes the earlier assertions all passed while these print 0 against a reference of 4.
e Both directions demonstrated? Yes, on two binaries with SELECT lower(buildId()) asserted before each verdict. Base: [ FAIL ], all four assertion lines move (4 1 4 0 and 4 1 4 1 on the preconditions, 4 4 4 and 3 3 3 on the comparisons). Fixed: [ OK ], plus 50 of 50 randomized repeat runs and 12 concurrent copies.
f Fix is general across code paths? Yes. Both the read pair and the write pair are fixed, with written_rows and written_bytes accumulation demonstrated independently on an INSERT arm (400000 to 1600000 while InsertedBytes stays correct at 400000) and both asserted by the test. initPerformanceCounters() has one call site, so no second path exists. The symmetric query-level carrier QueryStatus::progress_in/progress_out is deliberately untouched and was measured to still work.
g Fix generalizes across inputs (params/datatypes/wrappers)? Progress fields are plain std::atomic<UInt64>, so there is no Nullable / LowCardinality / Const dimension. Covered SELECT and INSERT arms, rows and bytes, max_threads 1 and 2, max_insert_threads = 1, plus the randomized-settings matrix over 50 runs. On the error path the reset happens before attachToGroupImpl's detach-and-rethrow, so a failed attach leaves zeroes rather than stale values.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialization format, so no SettingsChangesHistory.cpp entry and no experimental gate. The change makes a documented column match its documentation, so the docs need no change either. The per-attach semantics are stated explicitly in the description for confirmation.
i Invariants and contracts preserved? Yes. The reset runs on the attaching thread, on its own ThreadStatus, before any writer for the new query can fire; both writers are CurrentThread::updateProgressIn/Out, which run on that same thread by construction. Progress::reset() performs plain stores, consistent with the memory_order_relaxed loads at the read site. No new lock, no new ordering requirement, no lifetime change. Limits, leaf limits, throttling, quotas, query_log and system.processes were each re-checked after the change.

Session id: cron:clickhouse-impl-slot-7:20260820-093900

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73284ec]

Summary: ✅


AI Review

Summary

This PR resets ThreadStatus::progress_in and progress_out when a thread attaches to a new query so the four progress columns in system.query_thread_log stop accumulating across reused pooled threads, and it adds a focused HTTP keep-alive stateless test for the reused initiating-thread case. Tracing the current code through QueryScope / ThreadGroupSwitcher, QueryStatus::updateProgressIn / updateProgressOut, and logToQueryThreadLog matches that contract, and the changelog metadata is specific and correctly categorized; I did not find a new correctness or coverage issue in the current head.

Missing context / blind spots
  • ⚠️ I did not execute the new stateless test locally in this environment, so the verdict is based on source-level tracing plus the regression coverage added in the diff.
Final Verdict

✅ No blocking or major issues found in the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 86.90% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar, could you review this? The four progress columns of system.query_thread_log are read straight off two ThreadStatus members that live as long as the OS thread and were never cleared, so the row of the pooled initiating thread reported that thread lifetime running total instead of the logged query; the fix clears them in initPerformanceCounters, which is the existing per-attach reset hook and already clears every sibling piece of per-query state.

@diegomestre2 diegomestre2 self-assigned this Aug 20, 2026
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
@PedroTadim PedroTadim added pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Aug 20, 2026

@diegomestre2 diegomestre2 left a comment

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.

Properly addressed. No remarks besides the ones already checked.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 73284ec73 with master bddae8d72 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.40 MiB 701.35 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@diegomestre2
diegomestre2 enabled auto-merge August 20, 2026 15:28
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 73284ec

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR

CI finished clean at this head, so no line needs an owner. 171 unique check-runs, 0 incomplete,
154 success and 17 skipped, with Config Workflow and Finish Workflow both success. Corroborated
against the CI database at this commit: 0 FAIL or ERROR rows against a measured 300,865-row control
for the same commit, the only non-success job row being a skipped
Integration tests (amd_asan_ubsan, targeted).

Session id: cron:our-pr-ci-monitor:20260820-200000

clickhouse-gh Bot added a commit that referenced this pull request Aug 21, 2026
Backport #115596 to 26.6: Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #115596 to 25.8: Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log
alexey-milovidov added a commit that referenced this pull request Aug 27, 2026
Backport #115596 to 26.5: Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…rows/written_bytes in system.query_thread_log
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
…rows/written_bytes in system.query_thread_log
clickhouse-gh Bot added a commit that referenced this pull request Aug 29, 2026
Backport #115596 to 26.7: Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log
diegomestre2 added a commit that referenced this pull request Sep 2, 2026
Backport #115596 to 26.3: Fix read_rows/read_bytes/written_rows/written_bytes in system.query_thread_log
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…rows/written_bytes in system.query_thread_log
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
…rows/written_bytes in system.query_thread_log
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…rows/written_bytes in system.query_thread_log
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 groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants