Skip to content

Do not register a JOIN runtime filter whose build failed - #120940

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/runtime-filter-abandon-failed-build
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/runtime-filter-abandon-failed-build

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107108

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 LOGICAL_ERROR: offsets_column has data inconsistent with nested_column when building a JOIN runtime filter failed part way through, for example on a memory limit. The half-built filter was registered anyway, and a later merge read its partially appended key column, replacing the error the query actually hit (and aborting the server where LOGICAL_ERROR is fatal: sanitizer builds, abort_on_logical_error). Such a build is now abandoned, and an unregistered runtime filter passes all rows. Runtime filters are on by default (enable_join_runtime_filters).

Description

Found in CI (Stress test (arm_release)); first sighting in 90 days of CIDB, and the carrier PR is
test-only, so the failing code is master's. No related issue.
Provenance: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120711&sha=6c62261a7eb5abed01a007c5bf0cd1906b84e573&name_0=PR&name_1=Stress%20test%20%28arm_release%29

What breaks. ISimpleTransform::work turns an exception thrown by transform into port data and
keeps the transform alive, so a build stream whose build failed still reaches prepare() == Finished,
where BuildRuntimeFilterTransform::finish() registered it unconditionally. RuntimeFilterLookup::add
then merges it, reading a Set value column the interrupted insert had left mid-append, so the
ColumnArray consistency check throws, in a different build stream than the one that failed.

Change. Abandon the build instead of publishing it: release built_filter on any exception from
transform(Chunk &) (rethrowing it unchanged) and on the transform(std::exception_ptr &) upstream
hook, and skip registration in finish() once it is gone. The early return in transform(Chunk &) is
needed because the transform is re-entered on later chunks. No new state: built_filter == nullptr is
the abandoned state, and a filter missing from the lookup is already all-pass on the probe side
(FunctionApplyFilter).

Validation. A new lifecycle gtest fails on master and passes here, reverting each guard on its own
reddens a different arm, and the *runtime_filter* stateless family, the runtime-filter gtests and
type-coverage tests (50x) pass. A gtest rather than SQL because this is a transform lifecycle property:
with one build stream master need not reach finish() after the throw, with several the created-filter
counter reads the same either way, and the remaining SQL observable is the abort, which needs an
allocation failure at a precise instant. Such a query always fails rather than completing with a
partial key set, so there is no wrong-results path.


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

groeneai and others added 2 commits September 18, 2026 23:38
A stress run aborted the server with

    Logical error: 'offsets_column has data inconsistent with nested_column.
    Data size: 100000, last offset: 44460'

from ExactSetRuntimeFilter::insert, reached through RuntimeFilterLookup::add
<- BuildRuntimeFilterTransform::prepare (STID 2632-398f, first sighting of the
signature in 90 days of CIDB; the carrier PR was test-only).

ISimpleTransform::work does not tear the pipeline down where a transform throws:
it converts the exception into port data and returns, and for an exception
arriving from upstream it calls the transform(std::exception_ptr &) hook and
forwards it. Either way the transform still reaches Finished, and
BuildRuntimeFilterTransform::prepare() called finish() on that status
unconditionally, so a build stream whose build had failed registered its
half-built filter anyway. RuntimeFilterLookup::add then merged it, and the merge
reads the source filter's Set value columns through getValuesColumn() ->
Set::getSetElements(): one of those columns had been left mid-append by the
interrupted insert, so re-running the ColumnArray consistency check on it fired
LOGICAL_ERROR and abortOnFailedAssertion took the whole server down, from a
thread of a different build stream than the one that failed.

The interrupted column is a ColumnArray(ColumnVariant) grown by
Set::appendSetElements. ColumnVariant::insertRangeFromImpl's general path grows
local_discriminators and offsets first (and ColumnVariant::size() is
offsets->size()), then appends the variant payloads, which is what threw under
the job's memory_tracker_fault_probability; ColumnArray::insertRangeFrom writes
its own offsets only after getData()->insertRangeFrom returns, so the data grew
and the offsets did not. That is the trigger, not the defect: IColumn documents
no all-or-nothing contract for insertRangeFrom and ships
getCheckpoint()/rollback() precisely so a caller that must retain a column
across a throwing append can undo it. The defect is publishing a filter whose
build failed.

So abandon the build instead. built_filter == nullptr is the abandoned state -
the constructor assigns it on all three of its paths, so a null pointer cannot
arise otherwise - and three guards carry the invariant "a build stream whose
build failed must never register its filter and never re-enter the build with
it": a catch-all in transform(Chunk &) that releases the filter and rethrows
unchanged (covering both the insert and the CAST that precedes it), a
transform(std::exception_ptr &) override that releases it when the build side
stopped early, and an early return in finish(). The entry guard in
transform(Chunk &) is needed because ISimpleTransform keeps the transform alive
and re-enters it on later chunks; without it the released pointer is
dereferenced, which the same-shaped LimitBySortedStreamTransform regression test
already documents for its own scratch buffer.

Withholding is safe by construction rather than by a new rule: a runtime filter
is an optimization, and FunctionApplyFilter already treats a filter that is
absent from the lookup, or not yet ready, as all-pass. On a multi-stream build
the surviving siblings still register, so the withheld merge leaves
hasPendingMerges() true, isReady() false and the probe passing every row, which
gtest_runtime_filter_lookup already asserts. Releasing the pointer is also what
makes the corrupt column unreachable: the filter is the only owner of the Set.

The new gtest drives the transform the way the executor does, injecting a
deterministic allocation failure with a MemoryTracker hard limit rather than a
failpoint, and forces the registration path by closing a connected downstream
port. Its third arm is an anti-vacuity arm: a build that completes must still
register a filter that actually filters, so a bare return in finish() cannot
satisfy the other two. An Array(String) key selects the exact-set filter variant
from the reported stack. Reverting any one of the three guards reddens a
different arm.

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the three clauses that narrate the fix; keep the base-class and probe-side properties a reader cannot derive locally.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 19, 2026
@groeneai

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

An independent-model gate pass over this branch (engine: codex) returned 0 findings; my own cold
read, done before reading the implementation notes, returned 4. None required a code change, so the
reviewed tree is the tree published here.

# Sev Finding Verdict Evidence / action
1 ⚠️ The changelog said "Fixed a server abort" unqualified AGREE LOGICAL_ERROR is fatal only under debug_or_sanitizer_build || abort_on_logical_error (src/Common/Exception.cpp:112-116; that server setting defaults to false, "Only for experts"), so a default release build throws an error that replaces the one the query hit rather than aborting; entry and description rescoped. The detector is not debug-only: the size check at src/Columns/ColumnArray.cpp:60-68 is always compiled (only the monotonicity scan at :71-81 is not), so release throws instead of building an out-of-bounds column
2 💡 The description did not say why the test is a gtest, although the default is SQL AGREE Added the two discriminating reasons: with one build stream master need not reach finish() after the throw, and with several the created-filter counter reads the same either way
3 💡 One lookup consumer was missing from the plan's enumeration: the skip-index predicate at src/Processors/QueryPlan/ReadFromMergeTree.cpp:5246-5260 reads the lookup directly, not through buildRuntimeRangePredicate AGREE, no action Verified fail-safe: if (!filter) return false only disables the bloom skip index, and getRecordedKeyValues() is null unless the build state is finished
4 💡 The first gtest arm asserts the error code but not that the throw landed inside the filter insert AGREE, no action The guarded region has a catch-all, so the contract holds wherever the throw lands, and a 50000-row Array(String) insert far exceeds the injected headroom, so the insert is the thrower; pinning a frame would be more brittle than the property tested

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

Checked independently and found sound: the reported stack reads as an abort on the insert path, which
would put the fix in the wrong place, but ExactSetRuntimeFilter::mergeFrom(source) is
insert(source.getValuesColumn()), so that frame is the destination's, fed the failed source's
mid-append column by RuntimeFilterLookup::add, which has exactly one caller in the tree. Withholding
is safe on every consumer I enumerated: the probe all-passes on absent-or-not-ready, both
index-analysis consumers fail open, and a withheld merge leaves the entry permanently not-ready, which
is polled per block and never awaited, so nothing hangs. Cancellation is out of scope: it registers a
filter that is partial but internally consistent, which cannot reach this check. That permanent
not-ready state is why #107108 is linked rather than the open PRs that merely touch this file: it adds
the profile event and the regression tests for the "registered but not yet ready" window, which this
change turns from a transient race into a lasting state whenever one build stream of several fails.

Noticed while reviewing and deliberately not raised as separate work, no user-reachable consequence
once a failed build is abandoned: Set::appendSetElements retains a partially mutated element without
an IColumn checkpoint and outside Set::rwlock, ExactSetRuntimeFilter::getValuesColumn() const
mutates while merge holds only a shared lock on the source, RuntimeFilter::insert extends the
recorded key range before the payload insert that may throw, and ColumnVariant::insertRangeFrom is
not all-or-nothing, which matches IColumn's contract.

Session id: cron:clickhouse-review-slot-11:20260918-234200

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e1bebf8]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR prevents the original LOGICAL_ERROR by dropping a runtime filter when BuildRuntimeFilterTransform itself throws or when it explicitly consumes an upstream exception packet. That fixes the mid-append registration path, but the current head still has one Finished path that can publish a failed stream's partial filter before that exception is consumed, so I do not consider the fix complete yet.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Do not register a JOIN runtime filter whose build failed #120940#discussion_r4052434578] [src/Processors/Transforms/BuildRuntimeFilterTransform.cpp:101-156] The new abandonment logic still depends on work() reaching either transform(Chunk &)'s catch block or transform(std::exception_ptr &). ISimpleTransform::prepare() returns Finished immediately when output.isFinished() (src/Processors/ISimpleTransform.cpp:27-32), and BuildRuntimeFilterTransform::prepare() still calls finish() on every Finished status. If another build-stream failure or cancellation closes this stream's output before its queued exception is consumed, built_filter is still non-null at finish(), so the stream registers a structurally consistent but incomplete key set anyway. That breaks the PR's promised invariant that a failed build is withheld and probe-side filtering stays all-pass, and it can still let the lookup reach isReady() on only a subset of the build keys.
    Suggested fix: make finish() distinguish natural end-of-input from downstream/cancelled finish, or clear built_filter on the output.isFinished()/cancellation path before registration.
Final Verdict

⚠️ Needs changes before merge: the original abort path is fixed, but a failed build can still be published on the early-Finished lifecycle edge above.

LLVM Coverage Report

Measured on commit e1bebf8.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 119/121 (98.35%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 31fc30d

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
Stress test (arm_release) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 1815-2040) logical error on a zero-byte aggregate state, not caused by this PR: the raised header is s AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) against Chunk: UInt64(size = 400), i.e. start=10 > end=5, so the resample state holds no buckets and serializes to nothing. This diff touches only BuildRuntimeFilterTransform. The identical countResample header hit 25 distinct pull requests plus 2 true-master runs in 3 days, across 11 check flavours #119728 (mine, merged 2026-09-19 04:30:45Z), merged master @ fbfc27cb5cacc
Performance Comparison (arm_release, master_head, 5/6) measurement run, not a regression of this diff: the job-level summary is 10 errors, 3 too long while every per-query row on the shard is success or unstable. The shard went from about 1 red/day to 163 reds on 2026-09-18, starting right after #120176 merged at 21:10Z, and it is red on master too #120923 (external, open)
Build profile diff infra: RuntimeError: CI logs cluster query failed, raised in Db.query at ci/jobs/build_profile_diff_job.py:234 from compare_symbols, so the job aborts with a traceback instead of degrading to "no baseline". 74 distinct pull requests carry the identical traceback in the last 24 hours #118708 (mine, open)
Mergeable Check, PR praktika rollups of the three rows above, no independent failure of their own #119728 (mine, merged), #120923 (external, open) and #118708 (mine, open)

Rule 3c, not 3d, decided at the tree that ran rather than at the head: praktika builds the merge
commit pinned at run creation, so the branch tip is not what CI compiled. Job 105828397287 of run
35409784057 checked out 71e3784df5bf, and that tree does NOT carry the fix, while the fix commit
does (needle serializes to zero bytes in AggregateFunctionResample.h: pre-fix fcbf73ea6f67 = 0,
at 5ea18126eb8e = 1, tested tree = 0, live master = 1, so both controls discriminate). Timing agrees:
the run started 2026-09-19 03:05:25Z, #119728 merged at 04:30:45Z. Master is now merged into this
branch at fbfc27cb5cacc, where merge commit 5ea18126eb8e is an ancestor of HEAD. My own change is unchanged across the merge (3 files, 308 insertions, 8 deletions,
same patch id); the merge also advances the contrib/musl gitlink, which master moved and this branch
never touched. CI is re-running on fbfc27cb5cacc.

Session id: cron:our-pr-ci-monitor:20260919-053557

if (filter_key.empty())
return;
/// A filter missing from the lookup is all-pass on the probe side.
if (!built_filter)

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.

transform(std::exception_ptr &) only handles the path where work() actually consumes an exception packet. ISimpleTransform::prepare() returns Finished immediately when output.isFinished() is true (src/Processors/ISimpleTransform.cpp:27-32), and BuildRuntimeFilterTransform::prepare() still calls finish() on every Finished status. In the teardown where another build stream fails first, this stream can still have an unprocessed upstream exception queued while its output gets closed; built_filter is still non-null here, so finish() will register an incomplete filter anyway. That means the new upstream-exception fix is still bypassable unless registration distinguishes natural end-of-input from downstream/cancelled finish, or abandons the filter on that path too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The early-Finished path is real and finish() does run on it, but it cannot register a filter in the state this PR is about.

built_filter != nullptr at finish() is itself the proof that no insert was interrupted. The only mutation of the filter's contents is built_filter->insert(...) at BuildRuntimeFilterTransform.cpp:126, inside the try whose catch (...) at :128-133 resets built_filter unconditionally and rethrows. So if built_filter survives to the check at :148, every insert that ran on it returned normally, and its exact-value columns are structurally consistent.

That distinction is the defect. The abort is RuntimeFilter::merge -> ExactSetRuntimeFilter::mergeFrom -> Set::insertFromColumns -> convertToFullIfWrapped -> the ColumnArray size check data->size() != offsets.back(). It needs a mid-append column, not a short one: a filter that stopped early holds fewer values than the full build side, but its offsets and its nested data still agree, so the check passes. Incomplete and mid-append are different states. That also makes the queued-exception interleaving moot here: whichever way that race goes, the column that gets registered is consistent.

prepare() is byte-for-byte master's at :97-105 (the hunks start at transform(Chunk &)), and the diff adds no registration site: one entry guard, one catch-all reset, one transform(std::exception_ptr &) reset, one finish() guard. Every registration reachable at this head is reachable on master too, so the change strictly narrows registration. ISimpleTransform::prepare() returns Finished from three places: output.isFinished() (:27-32), no_more_data_needed (:52-57, unreachable here because this transform never calls stopReading()), and input.isFinished() (:62-67). All three reach finish(), and on all three the built_filter != nullptr precondition carries the same guarantee.

So I am not extending the fix to reset on the downstream-closed path: registering a short filter there is master's existing behavior, it is orthogonal to this abort, and withholding it would change filter publication on a path I have no failure for.

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit e1bebf8da4f7fbead24c45bab2790e34cae39476 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_cou….

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fbfc27c

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
Performance Comparison (arm_release, master_head, 5/6) measurement shard, not a regression of this diff: the job-level summary is 10 errors, 3 too long, 1 unstable, while 1366 of the 1368 per-query rows on the shard are success and the other 2 are unstable. The shard is trunk-wide red since 2026-09-18, master-side too: reds per day on true master are 0 up to and including 09-16, then 1 on 09-17, 10 on 09-18 and 4 so far on 09-19. In the last 24 hours the shard failed on 156 distinct pull requests #120923 (external, open)
Mergeable Check, PR praktika rollups of the row above, no independent failure of their own #120923 (external, open)

The two other rows of the previous ledger are green at this head: Stress test (arm_release) passes
now that the countResample fix #119728 is an ancestor of this branch, and Build profile diff
passed on this run.

Session id: cron:our-pr-ci-monitor:20260919-110331

@rschu1ze

Copy link
Copy Markdown
Member

Looks like a quickhack.

@rschu1ze rschu1ze closed this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed on the shape: it guards one consumer instead of removing the bad state.

The defect is still on master. Set::appendSetElements appends into the retained set_elements[i] (src/Interpreters/Set.cpp:287), so a throw in the middle of that insertRangeFrom leaves the set holding a column whose nested data and offsets disagree (ColumnVariant grows its offsets and discriminators before it appends the variant payloads, and the stress run injects MEMORY_LIMIT_EXCEEDED via memory_tracker_fault_probability). The next reader re-runs the ColumnArray check, gets offsets_column has data inconsistent with nested_column and aborts a debug or sanitizer build. That is how it reached Stress test (arm_release): another thread merged the failed build's set.

What I sent only stops BuildRuntimeFilterTransform from publishing such a set. It does nothing for ExactSetRuntimeFilter::mergeFrom, where the same throw leaves the destination set, already in the lookup, mid-append.

Smaller and at the right level: take checkpoints of set_elements before the append and rollback() them in catch (...), as appendBlock already does for this failure mode (src/Storages/StorageBuffer.cpp:690). ColumnArray::rollback and ColumnVariant::rollback restore by recorded size, so the Array(Variant(...)) case recovers. About 10 lines, and the 275-line gtest goes away.

Want me to open that instead?

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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants