Skip to content

Do not lose the held back rows of a preliminary DISTINCT when its input finishes concurrently - #132147

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-distinct-held-rows-lost-on-input-finish
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-distinct-held-rows-lost-on-input-finish

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #114550

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not required.

Description

05401_aggregation_nullable_fixed_keys_batch_pack got 17013 instead of 17146 rows from a plain SELECT DISTINCT a, nb in Stateless tests (arm_asan_ubsan, azure, targeted), twice, byte-identical (1, 2). On a remote disk the table is read by 6 streams, so the DISTINCT runs in parallel with one preliminary DistinctTransform per stream, which coalesces its output (#114550) and emits the rows it still holds when its input is exhausted.

DistinctTransform::prepare checked input.isFinished() and then called ISimpleTransform::prepare, which checks the port again and finishes the output when the input is finished. The upstream finishes the port from its own prepare on another thread, so the input can become finished between the two checks: the first keeps the rows, the second finishes the output without them. The 133 missing keys are exactly the end-of-input chunk of the second stream.

While rows are held, prepare now looks at the input once: it flushes when the input is finished, otherwise it requests data, and it calls the base class only in states where the base class cannot see the input finish. FillingTransform::prepare and BuildRuntimeFilterTransform::prepare check the input before delegating in the same way; they are not changed here.

Validation: with a 500 us sleep at the equivalent point of the old and the new code, 8 concurrent clickhouse local loops of the 05401 query with the CI settings return 139 wrong results of 6400 on master, each one a lost end-of-input chunk (one of them the CI result), and 0 of 6400 with the fix. No new test: the race needs a thread switch between two loads in one call; 05401 stays the coverage. The code is master-only (not in 26.10).


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

…ut finishes concurrently

A preliminary `DistinctTransform` that coalesces its output (ClickHouse#114550) emits the rows it still
holds once its input is exhausted, from `prepare`. It checked `input.isFinished()` and then
called `ISimpleTransform::prepare`, which checks the port again and finishes the output when the
input is finished. The upstream finishes the shared port from its own `prepare` on another
executor thread, so the port could become finished between the two checks: the first one saw an
open input and kept the rows, the second one finished the output with the rows still held, and
the later port update of the finished node is ignored. A plain `SELECT DISTINCT` read by several
streams then returned fewer rows (05401 on `Stateless tests (arm_asan_ubsan, azure, targeted)`
lost exactly the 133 keys of one stream's end-of-input chunk).

While rows are held, `prepare` now observes the input once: it flushes when the input is
finished, otherwise it requests data and returns `NeedData` when there is none, and delegates to
the base class only when the base class cannot see the input finish (the flushed rows are pushed
before the input is looked at, or the input has a chunk that only this processor can pull).
`PortFull` / `NeedData` and the `setNeeded` / `setNotNeeded` calls mirror what the base class
does in the same states.

Validated by widening the window with a 500 us sleep at the equivalent point of the old and the
new code (8 concurrent `clickhouse local` loops of the 05401 query with the CI settings and a
6-stream read): old code 139 of 6400 results wrong, each one a lost end-of-input chunk (including
the CI result byte for byte); new code 0 of 6400.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (1 nit, the same sibling).

# Sev Finding Verdict Evidence / action
1 ❌ FillingTransform::prepare has the same check-then-delegate race and can lose the trailing WITH FILL rows (FillingTransform.cpp:864-882) DISAGREE (out of scope: separate PR) Mechanism accepted. Other code with its own state machine (it returns Ready with an output that may be unpushed), so this fix does not carry over as is. 0 failures of any WITH FILL test on master in 60 days (CIDB). Named in the description, not changed here.
2 💡 Same pattern in BuildRuntimeFilterTransform::prepare (BuildRuntimeFilterTransform.cpp:84-87) DISAGREE (out of scope: separate PR) Same reasons as 1. Named in the description.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261116-213601

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, with a widened window: a 500 us sleep before ISimpleTransform::prepare while rows are held, 8 concurrent clickhouse local loops of the 05401 query with the CI settings and a 6-stream read. Every batch of 1600 reproduces (24 to 46 wrong, 4 of 4 batches), always one of two values, one of them the CI result byte for byte.
b Root cause explained? DistinctTransform::prepare checked input.isFinished(), then ISimpleTransform::prepare checked it again and finished the output. The upstream finishes the port from another thread, so between the two checks the held back rows are neither flushed nor kept: the output is finished without them and the later port update of the finished node is ignored.
c Fix matches root cause? Yes. While rows are held, the end of the input is decided from one observation; the base class is called only when it cannot see the input finish (rows already flushed, or a chunk in the input port that only this processor can pull). No setting, no test change.
d Test intent preserved / new tests added? 05401 is unchanged and stays the coverage. No new test: the race needs a thread switch between two loads inside one prepare call, so a test would pass on the old code almost always.
e Both directions demonstrated? Old code with the sleep: 139 wrong of 6400, each one a lost end-of-input chunk. Fix with the same sleep at the equivalent point: 0 of 6400 (the sleep is reached: the runs are measurably slower).
f Fix is general across code paths? All paths that hold or release rows in DistinctTransform checked (coalescing, the ChunkInfo flush, pass-through after spill/abandon, stopReading). The other DISTINCT processors observe the input once per call. FillingTransform::prepare and BuildRuntimeFilterTransform::prepare use the same check-then-delegate shape; not changed here, named in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change is in port handling, independent of key types and settings; with nothing held the function is unchanged. The 166 DISTINCT stateless tests pass (3 skipped locally for missing stateful datasets), plus 146 DISTINCT/scatter unit tests.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? Rows held across prepare now reach the output before it finishes on every path. PortFull/NeedData and the setNotNeeded/setNeeded calls are what the base class does in the same states; a finished output still goes through the base class, which closes the input and calls onFinish.

Session id: cron:clickhouse-impl-slot-41:20261116-210201

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ad6eb05]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

The change prevents preliminary DISTINCT from losing buffered rows when its upstream finishes between port checks. No actionable findings at ad6eb050c477af66bdcaea4f275b57530d9c70e0. The existing 05401_aggregation_nullable_fixed_keys_batch_pack test passes in Fast test CI; the PR also documents a race reproduction yielding 139 incorrect results before the fix and zero afterward across 6,400 runs each. No local build or tests were run for this review.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot 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.

AI review approves this commit, see the AI Review comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ad6eb05

Every failure below has an owner: a fixing PR (mine 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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same job errored on 40 PRs in the last 24 hours #129675 (mine, open)
PR praktika rollup of the row above #129675 (mine, open)

CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20261117-003016

This branch has not been deployed

No deployments
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant