Repository navigation
Conversation
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]>
Internal second-model review: adjudication log (click to expand)Independent pre-publication review (engine: codex): 0 findings. My own cold review of the resulting The nits, all settled outside the diff: the relationship link was inside the template's HTML comment Session id: cron:clickhouse-review-slot-9:20260914-000040 |
|
Workflow [PR], commit [82cf1ab] Summary: ❌
AI ReviewSummaryThis PR fixes the out-of-bounds read in the trailing-action skip inside Findings
Final Verdict
LLVM Coverage Report |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 16 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 4517ae8Every 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
Nine of the ten Session id: cron:our-pr-ci-monitor:20260914-050101 |
…trailing-actions-past-end
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]>
| 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))) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - 64d7ce3Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260918-220128 |
CI finish ledger follow-up -
|
|
This is the fix for the bug for sure. |
|
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. |
CI finish ledger - 82cf1abOne failure, and it has an owner.
Session id: cron:our-pr-ci-monitor:20260924-183043 |
cb7f462
|
This fix is not on |
Closes: #120729
Related: #118497
Changelog category (leave one):
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,sequenceCountandsequenceMatchEvents. 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 andsequenceMatch/sequenceCountcould return0for a pattern that does match.Description
backtrackingMatchends with a loop consuming the pattern actions a zero-length match satisfies (KleeneStar,TimeLessOrEqual,TimeLess,TimeGreaterOrEqualwithextra == 0). It was bound-checked on entry only and advancedaction_itwith no re-check, so when every remaining action is one of those it walks toaction_endand the condition dereferences it.actionsis aPODArrayWithStackMemory<PatternAction, 64>andPatternAction::typehas no default initialiser, so the read is of uninitialised memory. The byte found there also decides whether the loop continues: writing aKleeneStaratactions[size()]on an unfixed build makessequenceMatch('(?t<=10)')andsequenceCount('(?1).*')return0instead of1.I fold the entry
ifinto thewhile, one guard covering both->typeand->extra. Behaviour changes only where the loop used to run pastaction_end.The missing check is original to
sequenceMatch, not a regression: the loop stands verbatim, bound check outside it, inv1.1.54127-stable(2016-12-22, thendbms/include/DB/AggregateFunctions/AggregateFunctionSequenceMatch.h:478). The commits blame lands on are pure moves - 06446b4 (2020-04-03,dbms/tosrc/) 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 noconditions_metearly-out and always takesbacktrackingMatch, so an empty event list reaches the trailing actions.sequenceCount::counthas calledbacktrackingMatchunconditionally the whole time, and reverting my own 6e6cbb2 (#118497, which only touches the tworemember_matched_eventslambdas) 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 onmaster:Reports: arm_msan, amd_msan and the
masterone, MasterCI arm_msan on8701bfd4de67, whose query isselect [] = sequenceMatchEvents('')(time, data = 0, data = 1, data = 2, data = 3) from sequence_test__fuzz_0from00222_sequence_aggregate_function_familyagainst 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 on4517ae8a, andStress test (amd_msan)runs all of0_stateless. Under MSan the failure is not nondeterministic -PatternAction::typeatactions[size()]is never written, so its shadow is always poisoned and the branch on it is always reported; themasterreport 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_statelesson both architectures.PatternActionsis aPODArrayWithStackMemory<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 withsize() == capacity()and the action one past the end is the first byte after a 128-bytemalloc, inside the ASan redzone.sequenceMatchEvents,sequenceMatchandsequenceCounteach 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:Without the fix this reports
use-of-uninitialized-valuewith the CI stack, symbolized:The same
:555:69report also comes fromsequenceMatch(insertResultInto:717:84) andsequenceCount(count:811:53), and from patterns ending in each of the four action kinds, withUInt8/UInt32/UInt64/DateTime/Datetimestamps. With the fix all of them are clean and return theexpected values, and
00222_sequence_aggregate_function_familyoutput is unchanged (78 lines). The newtest'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
26.10.1.658-master(included in26.10and later)