Skip to content

Fix sequenceMatchEvents returning an event chain that does not match the pattern - #118497

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-sequence-match-events-invalid-chain
Sep 13, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-sequence-match-events-invalid-chain

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #118120

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 sequenceMatchEvents returning an event chain that the pattern does not authorize, for example one that skips a (?t...) time gate between two of the returned events. The returned chain now always matches a prefix of the pattern. Closes #118120.

Description

SELECT sequenceMatch('(?1)(?t<=10)(?2)(?3)')(t, e='A', e='B', e='C'),      -- 0
       sequenceMatchEvents('(?1)(?t<=10)(?2)(?3)')(t, e='A', e='B', e='C') -- [0,100,101]
FROM values('t UInt32, e String', (0,'A'),(5,'B'),(100,'B'),(101,'C'));

100 - 0 > 10 violates the gate, and sequenceMatch rejects that chain. It now returns [0,5], the longest chain the pattern does match.

remember_matched_events was meant to add bookkeeping, but it also changed the search: do_push_event pushed a backtrack frame for every matched SpecificEvent, and a frame means "retry this action at the next event". So in that instantiation alone a SpecificEvent could skip forward while earlier matches stayed in place, a gap the pattern authorizes only through .* or a (?t...) action. Here backtracking restored action_it past TimeLessOrEqual, so the gate was never re-evaluated. Removing the frame makes do_revert_event_if_needed's single pop insufficient, since one backtrack can now rewind past several matched actions, so it becomes a loop.

Gate-free patterns are affected too: on (0,'A'),(1,'B'),(2,'B'),(3,'C'), (?1)(?2)(?3) returned [0,2,3], a length-3 array for a three-condition pattern, while sequenceMatch returned 0. Since fullness is tested by comparing array size to condition count, a caller saw a full match where none occurred.

remember_matched_events is pure bookkeeping again: both edited lambdas are reached only under if constexpr (remember_matched_events), so sequenceMatch and sequenceCount are unchanged by construction and the two instantiations walk the same search. Their 46 assertions and the 23 pre-existing sequenceMatchEvents ones in 00222 stay byte-identical; 7 are added, 2 of them failing without this change, and 50 randomized repeats are green.

Output can change for existing queries, but every chain that disappears is one sequenceMatch already reports as no-match, and the docs promise the "longest event chains that matched the pattern".

Pre-existing, not fixed here: array length still cannot prove a full match, since a path may match every (?N) and then fail a trailing (?t...).


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

…tern

sequenceMatchEvents could return an event chain that its own pattern does not
match, and that sequenceMatch rejects on the same input. With a time gate:

  SELECT sequenceMatch('(?1)(?t<=10)(?2)(?3)')(t, e='A', e='B', e='C'),
         sequenceMatchEvents('(?1)(?t<=10)(?2)(?3)')(t, e='A', e='B', e='C')
  FROM values('t UInt32, e String', (0,'A'),(5,'B'),(100,'B'),(101,'C'));

returned 0 and [0,100,101], where 100 - 0 > 10 violates the gate. It now
returns [0,5], the longest chain that does satisfy the pattern.

The template parameter remember_matched_events was meant to add bookkeeping,
but it also changed the search. do_push_event pushed an extra backtrack frame
for every matched SpecificEvent, and a frame means "retry this action at the
next event", so in that instantiation alone a SpecificEvent could skip forward
while earlier matches stayed in place. The pattern authorises such a gap only
through .* or a (?t...) action, each of which pushes its own frame. After
SpecificEvent(2) failed at B@100, backtracking restored action_it to
SpecificEvent(1) and skipped the TimeLessOrEqual action, so the gate was never
re-evaluated for the new position and A@0, B@100, C@101 was accepted.

Removing that frame makes do_revert_event_if_needed's single pop insufficient,
since one backtrack can now rewind past several matched actions, so it becomes
a loop. Without that, sequenceMatchEvents('(?1)(?1)(?1)(?1)(?1)') would leave
stale entries and assemble a chain from two different start positions.

The defect also affects patterns with no time gate at all: on (0,'A'),(1,'B'),
(2,'B'),(3,'C') the pattern (?1)(?2)(?3) returned [0,2,3], a length-3 array
for a three-condition pattern, while sequenceMatch returned 0. Since fullness
is tested by comparing the array size to the number of conditions, a caller
concluded a full match had occurred when none had.

Both edited lambdas are called only under if constexpr (remember_matched_events),
so sequenceMatch and sequenceCount are unchanged by construction. Their 46
assertions and the 23 pre-existing sequenceMatchEvents assertions in 00222 are
byte-identical before and after.

Closes ClickHouse#118120
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

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

Pre-publication review by an independent model (engine: codex) plus a separate cold read of the
resulting code. Both gate passes returned 0 findings; the 2 items below are from the cold read.

# Sev Finding Verdict Evidence / action
1 💡 The one added comment is 2 lines against 1 added line of code, and coins the term "verdict traversal" AGREE, kept Nothing below it tells a reader why a backtrack point must not be pushed in that lambda, and re-adding that push is the regression it exists to prevent. Wording residual left as written
2 💡 The docs could say the returned array may be a strict prefix DISAGREE parametric-functions.mdx already reads "longest event chains that matched the pattern", so this aligns the code with the documented contract instead of changing it

Checked independently of the gates: all 23 pre-existing sequenceMatchEvents assertions in 00222
were hand-traced under the new code and reproduce; dfaMatch, which is the reference for gate-free
patterns and never had the extra frame, also rejects (?1)(?2)(?3) on (0,'A'),(1,'B'),(2,'B'),(3,'C'),
so the new [0,1] now agrees with a third implementation; and removing frames only shrinks the search,
so sequence_match_max_iterations cannot be reached sooner than before.

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

Session id: cron:clickhouse-review-slot-8:20260907-001501

@clickhouse-gh clickhouse-gh Bot closed this Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @rschu1ze, could you review this? sequenceMatchEvents shares its matcher with sequenceMatch, and the remember_matched_events instantiation was pushing an extra backtrack frame per matched event, so it alone could skip a condition forward without re-entering the intervening (?t...) action and returned a chain sequenceMatch rejects. Deleting that frame leaves both instantiations walking the same search, so sequenceMatch and sequenceCount are unchanged by construction.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1f22303]

Summary: ✅


AI Review

Summary

This PR removes the extra per-SpecificEvent backtrack frame from sequenceMatchEvents and makes matched-event rollback unwind all stale entries, which correctly fixes the skipped-intervening-gate bug while keeping sequenceMatch and sequenceCount on the old traversal. The code change itself looks coherent, but the review is not fully clean yet because the published sequenceMatchEvents contract still overstates what the implementation guarantees for trailing (?t...) gates.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118497#discussion_r3945941034] [src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp:415; docs/reference/functions/aggregate-functions/parametric-functions.mdx:235] The patch deliberately leaves the trailing-(?t...) case where sequenceMatchEvents can still return a full-length array from a branch that sequenceMatch rejects, but the official docs and source-level FunctionDocumentation still say the function returns timestamps for chains that matched the pattern. Narrowing only the PR text leaves users with a stronger contract than the implementation actually provides.
    Suggested fix: update the sequenceMatchEvents documentation and registration text in the same change to say that the function returns the longest valid prefix of (?N) matches, and that a trailing time condition can still make the full pattern fail.
Final Verdict

The matcher fix is correct for the bug this PR targets, but the sequenceMatchEvents contract still needs to be corrected before I would call the review clean.

LLVM Coverage Report

Measured on commit 1f22303.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 10/10 (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 Sep 7, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1f223037b with master 55c256363 (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

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

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

Job report

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6e6cbb2

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
Stateless tests (arm_asan_ubsan, azure, sequential) / 04648_distributed_plan_task_error_propagation flaky, failed 0 of 3 reruns: the recorded CANNOT_SCHEDULE_TASK (439) is lost and the client sees POCO_EXCEPTION (1000). Trunk-wide since 2026-09-06 01:34Z, 19 other PRs plus 9 master runs in 30 days #118390 (mine, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / 04340_distributed_plan_status_reenqueue_fault flaky, failed 0 of 3 reruns: reenqueue fault handled: 0 because the distributed_plan_record_failure_while_starting_tasks failpoint is REGULAR and leaks out of the 04648 case into this one in the same sequential run. 17 other PRs plus 6 master runs in 30 days #118417 (external, open)
Stateless tests (arm_asan_ubsan, azure, sequential) / job-level red the job summary of the two rows above and nothing else: Failed: 2, Passed: 896, Skipped: 91, with no sanitizer, OOM or test-runner check fired #118390 (mine, open) plus #118417 (external, open)

Stateless tests (arm_asan_ubsan, azure, sequential) is the only failing check on this head: of 170 checks, 151 are green, 18 skipped, 1 failed. Neither failing test touches this diff, which is confined to src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp and 00222_sequence_aggregate_function_family.

Session id: cron:our-pr-ci-monitor:20260907-060021

@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to no response for status checks Sep 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 13, 2026
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-request PR origin: a maintainer pinged or directed groeneai 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.

Issue with sequenceMatchEvents with time gates

3 participants