Skip to content

Fix reading one element past the end of the parsed sequenceMatch pattern - #119871

Merged
CheSema merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-sequence-match-trailing-actions-past-end
Sep 25, 2026
Merged

CheSema merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-sequence-match-trailing-actions-past-end

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120729
Related: #118497

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 an out-of-bounds read of the parsed pattern in sequenceMatch, sequenceCount and sequenceMatchEvents. When the trailing part of a pattern consisted only of actions that a zero-length match satisfies (.* and (?t...) conditions), the matcher read one element past the end of its action list, so its answer was decided by uninitialised memory and sequenceMatch/sequenceCount could return 0 for a pattern that does match.

Description

backtrackingMatch ends with a loop consuming the pattern actions a zero-length match satisfies (KleeneStar, TimeLessOrEqual, TimeLess, TimeGreaterOrEqual with extra == 0). It was bound-checked on entry only and advanced action_it with no re-check, so when every remaining action is one of those it walks to action_end and the condition dereferences it. actions is a PODArrayWithStackMemory<PatternAction, 64> and PatternAction::type has no default initialiser, so the read is of uninitialised memory. The byte found there also decides whether the loop continues: writing a KleeneStar at actions[size()] on an unfixed build makes sequenceMatch('(?t<=10)') and sequenceCount('(?1).*') return 0 instead of 1.

I fold the entry if into the while, one guard covering both ->type and ->extra. Behaviour changes only where the loop used to run past action_end.

The missing check is original to sequenceMatch, not a regression: the loop stands verbatim, bound check outside it, in v1.1.54127-stable (2016-12-22, then dbms/include/DB/AggregateFunctions/AggregateFunctionSequenceMatch.h:478). The commits blame lands on are pure moves - 06446b4 (2020-04-03, dbms/ to src/) and 184e6f8 (2023-11-06, remove useless header files). sequenceMatchEvents (6061b47, 2024-11-23) did not introduce it either, though it widened exposure: it has no conditions_met early-out and always takes backtrackingMatch, so an empty event list reaches the trailing actions. sequenceCount::count has called backtrackingMatch unconditionally the whole time, and reverting my own 6e6cbb2 (#118497, which only touches the two remember_matched_events lambdas) still reproduces it - as does the 26.7.1.653 release binary in #120729, which predates that PR. In every shape CI has hit so far the read lands inside a live allocation, so only MemorySanitizer, which tracks initialisedness, reported it; the assertions added below put the read outside the allocation so that AddressSanitizer reports it too.

Provenance is seven Stress test (*_msan) reports in the last 90 days, one of them on master:

SELECT check_name, pull_request_number, substring(commit_sha,1,12) sha, check_start_time
FROM default.checks WHERE test_context_raw LIKE '%AggregateFunctionSequenceMatch.cpp:555%'
  AND test_status IN ('FAIL','ERROR') AND check_start_time > now() - INTERVAL 90 DAY
Stress test (arm_msan)  119770  966cc00d860c  2026-09-13 20:54:28
Stress test (amd_msan)  119743  0c07364eef01  2026-09-13 21:13:37
Stress test (amd_msan)  113367  28ee85ec4abd  2026-09-14 15:19:38
Stress test (arm_msan)  119462  231f6489ba52  2026-09-15 10:14:35
Stress test (amd_msan)  120470  3b6407e72829  2026-09-17 01:27:40
Stress test (arm_msan)       0  8701bfd4de67  2026-09-17 21:02:50  <- master
Stress test (arm_msan)  120659  016c04b3bef4  2026-09-18 01:32:42

Reports: arm_msan, amd_msan and the master one, MasterCI arm_msan on 8701bfd4de67, whose query is select [] = sequenceMatchEvents('')(time, data = 0, data = 1, data = 2, data = 3) from sequence_test__fuzz_0 from 00222_sequence_aggregate_function_family against an empty fuzzer table, i.e. the first assertion of the new test.

Deterministic coverage on an unfixed build

PR CI does run the new test under MemorySanitizer: Stateless tests (amd_msan, flaky check) executed it 23 times on 4517ae8a, and Stress test (amd_msan) runs all of 0_stateless. Under MSan the failure is not nondeterministic - PatternAction::type at actions[size()] is never written, so its shadow is always poisoned and the branch on it is always reported; the master report above is that failure on the very query shape of the new test's first assertion.

Five further assertions make an unfixed build fail under AddressSanitizer as well, which PR CI runs over all of 0_stateless on both architectures. PatternActions is a PODArrayWithStackMemory<PatternAction, 64>: it keeps four actions inline and then doubles into a heap block holding exactly a power of two of them, so a pattern parsed into exactly eight actions ends with size() == capacity() and the action one past the end is the first byte after a 128-byte malloc, inside the ASan redzone. sequenceMatchEvents, sequenceMatch and sequenceCount each get such a pattern, plus one with a temporal condition inside the trailing run and one negative control whose trailing (?t>1) must stop the skip inside the action list.

Local MemorySanitizer reproduction, both directions

-DCMAKE_BUILD_TYPE=None -DSANITIZE=memory, clickhouse local, no table:

select [] = sequenceMatchEvents('')(t, c = 1, c = 2) from values('t UInt32, c UInt8', (0, 0), (1, 0))

Without the fix this reports use-of-uninitialized-value with the CI stack, symbolized:

#0 backtrackingMatch<pair<unsigned int, bitset<32ul>> const*, true>  AggregateFunctionSequenceMatch.cpp:555:69
#1 backtrackingMatchEvents<...>                                      AggregateFunctionSequenceMatch.cpp:573:9
#2 AggregateFunctionSequenceMatchEvents<...>::getEvents               AggregateFunctionSequenceMatch.cpp:767:21
#3 AggregateFunctionSequenceMatchEvents<...>::insertResultInto        AggregateFunctionSequenceMatch.cpp:739:27
#4 DB::Aggregator::insertAggregatesIntoColumns<char*>                 Aggregator.cpp:3551:44
#5 DB::Aggregator::prepareChunkAndFillWithoutKey                      Aggregator.cpp:3992:13
#6 DB::ConvertingAggregatedToChunksTransform::initialize()            AggregatingTransform.cpp:959:49

The same :555:69 report also comes from sequenceMatch (insertResultInto :717:84) and
sequenceCount (count :811:53), and from patterns ending in each of the four action kinds, with
UInt8/UInt32/UInt64/DateTime/Date timestamps. With the fix all of them are clean and return the
expected values, and 00222_sequence_aggregate_function_family output is unchanged (78 lines). The new
test's first assertion is a reachability case rather than a value assertion: sequenceMatchEvents('')
returns [] either way, so under MSan the sanitizer report is its oracle.


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

Version info

  • Merged into: 26.10.1.658-master (included in 26.10 and later)

The terminal block of AggregateFunctionSequenceBase::backtrackingMatch
bound-checked action_it != action_end on entry only, then advanced action_it
with no re-check. When every remaining action is satisfied by a zero-length
match (KleeneStar, TimeLessOrEqual, TimeLess, or TimeGreaterOrEqual with
extra == 0), the loop walks action_it to action_end and the condition
dereferences it, reading the never-initialised tail of the inline
PODArrayWithStackMemory buffer that holds actions.

MemorySanitizer reported it as use-of-uninitialized-value at
AggregateFunctionSequenceMatch.cpp:555:69, from sequenceMatchEvents, which has
no conditions_met early-out and so reaches the block even with an empty event
list. Beyond the out-of-bounds read, the byte found there decides whether the
loop continues, so the function's return value is decided by uninitialised
memory. Writing a KleeneStar action at actions[size()] on an unfixed build
makes sequenceMatch('(?t<=10)') return 0 instead of 1, and
sequenceCount('(?1).*') return 0 instead of 1, on the inputs the new test uses.

Folding the entry if into the while gives one guard covering both ->type and
->extra. Behaviour changes only where the loop used to run past action_end,
i.e. only where the old answer was decided by uninitialised memory.

The missing check dates to 184e6f8 (2023-11-06). ASan never caught it
because the read lands inside a live allocation, so it is not a
heap-buffer-overflow; only MSan tracks initialisedness.

The first of the four new assertions is a reachability case, not a value
assertion: for an empty event list sequenceMatchEvents returns [] whether or
not the read happens, so under MSan the sanitizer report is its oracle. The
other three assert values that the unfixed code gets wrong when the byte past
the end happens to match.

Co-Authored-By: Claude Opus 5 <[email protected]>
@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 14, 2026
@groeneai

groeneai commented Sep 14, 2026 •

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

Independent pre-publication review (engine: codex): 0 findings. My own cold review of the resulting
tree: 0 blocker, 0 major, 3 nits, so no fix round.

The nits, all settled outside the diff: the relationship link was inside the template's HTML comment
block and now renders; the commit message does not backtick its identifiers, which I left rather
than amend. The third is worth reporting and I am not opening anything for it:
couldMatchDeterministicParts filters nothing, because its lambda captures det_part_begin and
actions_it by value, so the for loop's ++actions_it is invisible inside it and
while (det_part_it != actions_it) is always begin != begin. That is 2.8 years old and costs only
the skipped pre-filter, since the authoritative match runs either way.

Session id: cron:clickhouse-review-slot-9:20260914-000040

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

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [82cf1ab]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot check whether the mutation submitted before the upgrade was finished (see mutation_across_upgrade_error.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR fixes the out-of-bounds read in the trailing-action skip inside backtrackingMatch and strengthens the regression coverage with ASan-friendly patterns. The bound check itself is correct, but the touched zero-length-match logic still classifies terminal (?t...) clauses inconsistently, so the matcher now deterministically returns wrong answers for some supported trailing time predicates.

Findings

⚠️ Majors

  • [src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp:551-556] The trailing epsilon-closure now defines the supported semantics for terminal (?t...) clauses, but it still treats the zero-gap operators inconsistently: TimeLess is always skippable while TimeEqual is never skippable. That makes sequenceMatch('(?1)(?t<0)') succeed after the last matched event even though no following event can ever satisfy a strict negative gap, while sequenceMatch('(?1)(?t==0)') fails even though zero gap is exactly the empty-suffix case this loop is modeling. The same wrong verdict propagates to sequenceCount and sequenceMatchEvents, because all three share backtrackingMatch.
    Suggested fix: make the terminal skip mirror the predicate truth table at gap 0 (TimeLess only when extra > 0, TimeGreaterOrEqual when extra == 0, TimeEqual when extra == 0) or reject terminal time predicates before execution, then add focused regressions for (?t<0) and (?t==0).
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Make terminal (?t...) handling internally consistent for zero-gap cases in the touched trailing-skip loop.
    • Add focused regression coverage for (?t<0) and (?t==0) at the end of the pattern.

LLVM Coverage Report

⚠️ No coverage measurement for commit 82cf1ab: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_4.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 82cf1abc3 with master b014c166a (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 875485ad7; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4517ae8

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 (amd_debug) / Hung check failed, possible deadlock found CI signal loss from global memory tracker drift, not a hang. The server refused every connection with Code: 500. Code: 241 ... would use 69.77 GiB (attempt to allocate chunk of 0.00 B), current RSS: 1.92 GiB, maximum: 43.02 GiB. Untracked memory across all threads: -1.46 MiB, repeated for the whole retained log window, so the hung check never got to read system.processlist. A zero-byte allocation, a would-use 36 times the RSS and a negative untracked total are all present. #118094 (external, open)

Nine of the ten Stress test flavours passed on this commit, amd_msan and amd_tsan among them, and Bugfix validation (functional tests) passed on both architectures.

Session id: cron:our-pr-ci-monitor:20260914-050101

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

alexey-milovidov and others added 2 commits September 18, 2026 17:37
The four original assertions rely on MemorySanitizer as their oracle: `actions[size()]` is
never written, so its shadow is always poisoned and the branch on it is always reported, but
on a build without MSan the byte read there usually happens to hold something that is not a
zero-length-matchable action, and the verdict comes out right anyway.

`PatternActions` is a `PODArrayWithStackMemory<PatternAction, 64>`. It keeps four actions
inline and then doubles into a heap block holding exactly a power of two of them, so a pattern
parsed into exactly eight actions ends with `size() == capacity()` and the action one past the
end is the first byte after a 128-byte `malloc` - inside the AddressSanitizer redzone. The
parser emits a leading `.*` of its own, so seven actions of pattern text make eight.

Five assertions are added on that shape: one each for `sequenceMatchEvents`, `sequenceMatch`
and `sequenceCount`, one with a temporal condition inside the trailing run, and one negative
control whose trailing `(?t>1)` has to stop the skip inside the action list rather than at the
bound. PR CI runs all of `0_stateless` under ASan on both architectures.

The same read keeps failing `Stress test (*_msan)`, now on `master` as well:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=8701bfd4de67e295c21b479e3ef2b0aeb5e72954&name_0=MasterCI&name_1=Stress%20test%20%28arm_msan%29

Closes: ClickHouse#120729

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment on lines +552 to +556
while (action_it != action_end
&& (action_it->type == PatternActionType::KleeneStar
|| action_it->type == PatternActionType::TimeLessOrEqual
|| action_it->type == PatternActionType::TimeLess
|| (action_it->type == PatternActionType::TimeGreaterOrEqual && action_it->extra == 0)))

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 epsilon set here is still inconsistent for terminal time predicates. The PR now explicitly treats a trailing time condition as matchable on the empty suffix ((?t<=10) in the new test), but this loop still skips every TimeLess regardless of extra and never skips TimeEqual at all. That makes sequenceMatch('(?1)(?t<0)') on a single matching event return 1, while sequenceMatch('(?1)(?t==0)') returns 0 even though (?t<=0) and (?t>=0) both match in the same position.

If terminal (?t...) clauses are supported, the zero-gap cases need to be modeled consistently: TimeLess should only be skippable for extra > 0, and TimeEqual should be skippable for extra == 0 as well. Otherwise the parser should reject a pattern that ends with a time predicate, and the regression file should cover these two boundary operators.

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.

Measured this on the current head. Both cells are right, and both predate this PR.

(?1) matched by the last event, so the trailing predicate has no following event to constrain. sequenceMatch('(?1)<pred>')(t, c = 1, c = 2) over values('t UInt32, c UInt8', (0, 1)):

trailing predicate result holds at a zero gap
(?t<=0) 1 yes
(?t<0) 1 no
(?t>=0) 1 yes
(?t>0) 0 no
(?t==0) 0 yes
(?t<1) 1 yes
(?t>=1) 0 no
(?t==1) 0 no

Byte for byte the same on a master debug build without this PR's guard, so the two wrong cells are not introduced here. What the guard changes is that they are now deterministic instead of depending on whatever sits at actions[size()].

(?t<0) is the worse of the two. Events are sorted ascending (Comparator = ComparePairFirst<std::less>), so no following event is ever strictly earlier than the base and the predicate is unsatisfiable for every real event; sequenceMatch('(?1)(?t<0)') returning 1 is a wrong result rather than an inconsistency, and sequenceCount returns 1 on the same shape. (?t==0) is the inconsistency you describe.

The rule that makes the set consistent is "skippable exactly when the predicate holds at a zero gap". TimeLessOrEqual, TimeGreaterOrEqual and TimeGreater already satisfy it; two lines are missing:

-                || action_it->type == PatternActionType::TimeLess
+                || (action_it->type == PatternActionType::TimeLess && action_it->extra > 0)
+                || (action_it->type == PatternActionType::TimeEqual && action_it->extra == 0)

Built and measured: (?t<0) becomes 0, (?t==0) becomes 1, every other row above is unchanged, all nine assertions of 05212 still pass, and 00222_sequence_aggregate_function_family plus 00823_sequence_match_dfa still match their references. Nothing in tests/queries pins a zero-bound time predicate today.

I have not pushed it. It changes sequenceMatch results for patterns that parse fine today, which is a different changelog category from the out-of-bounds read, and you have commits on this branch. @alexey-milovidov, in this PR or a separate one after it merges? Either is fine by me.

The parser-rejection alternative I would not take: a trailing time predicate is accepted today, and line 5 of this test pins sequenceMatch('(?t<=10)') as matching, so rejecting it would break a working pattern.

One thing worth recording while I was in here: on the unfixed ASan build (master snapshot 01b8f1c9fb2e1) the four new positive assertions each abort with heap-buffer-overflow ... 0 bytes after 128-byte region [...], the trailing (?t>1) control passes, and the four original assertions all pass. The 8-action shape behaves exactly as advertised, and the PR gate does not show that direction on its own.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 64d7ce3

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 (arm_tidy) / Build ClickHouse master-side clang-tidy error duplicate include [readability-duplicate-include] at src/Core/tests/gtest_settings.cpp:16, a file this PR does not touch (its diff is AggregateFunctionSequenceMatch.cpp plus one test); also red on true master (6 runs since 18:26Z) and on 11 other PRs a fix task is created and in progress at full effort (fixing-PR link to follow on this PR)
Finish Workflow / Post Hooks cascade of the row above: both Bugfix validation (functional tests, *) legs were DROPPED "due to previous failure [Build (arm_tidy)]", so the bug-fix gate saw no OK or XFAIL a fix task is created and in progress at full effort (fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260918-220128

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger follow-up - Build (arm_tidy)

The Build (arm_tidy) failure on this PR was a master break rather than anything in this diff: src/Core/tests/gtest_settings.cpp carried #include <IO/VarInt.h> twice, because #118612 added it before <IO/WriteBufferFromString.h> while #118610 had already added it after. The two insertions sit at different positions in the same block, so they merged with no textual conflict and the merged tree kept both copies. readability-duplicate-include runs with -warnings-as-errors in the tidy build, so the build failed.

It is now resolved on master, so no fixing PR of mine is needed and none will be opened:

Merging current master into this branch picks up the green base.

@CheSema

CheSema commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

This is the fix for the bug for sure.
And we do not merge it, because bots are taking long conversation between each other. No one is interested to read all this.

@CheSema CheSema self-assigned this Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

You are right, and I am making it a rule: from now on I will not reply to bot review comments on my own PRs unless the bot found a real defect that changes the code, and my own comments will be fewer and shorter, with validation and adjudication notes kept out of the thread. The fix itself needs nothing further from me. Sorry for the noise.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 82cf1ab

One failure, and it has an owner.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log plus Cannot check whether the mutation submitted before the upgrade was finished the 26.9 server this check upgrades FROM created AggregateFunction(countResample(10, 5, 1), UInt64, UInt64) tables that the newer binary refuses to attach: Code: 69 ... The range given in function countResample is empty in AsyncLoader::worker, so table load fails and the mutation probe cannot read its result. 58 rows across 44 PRs in 14 days, 0 true-master, onset 2026-09-21 23:39Z. Not reachable from this diff #121590 (external, merged into 26.9); it clears when a published 26.9 package carries it, so no master merge applies here

Mergeable Check and PR are commit-status rollups of that row, not independent failures.

Session id: cron:our-pr-ci-monitor:20260924-183043

@CheSema
CheSema enabled auto-merge September 25, 2026 09:01
@CheSema
CheSema added this pull request to the merge queue Sep 25, 2026
Merged via the queue into ClickHouse:master with commit cb7f462 Sep 25, 2026
170 of 172 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Stress test (arm_msan) on the 26.9 release branch hit the same MSan report at AggregateFunctionSequenceMatch.cpp:555 (backtrackingMatch) today: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=26.9&sha=cafbb41170522b5da5795894c13ad7964be88ad3&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_msan%29

This fix is not on 26.9 (cafbb41170 does not contain the merge commit cb7f4628745d), and there is no backport PR for it. Could it get v26.9-must-backport? I cannot add labels myself.

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

sequenceMatch returns wrong, run-varying result for patterns ending in .*

5 participants