Skip to content

Follow the input order for events that share a timestamp in sequenceMatch, sequenceCount, sequenceMatchEvents and sequenceNextNode - #124812

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:sequence-functions-input-tie-order
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:sequence-functions-input-tie-order

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

sequenceMatch, sequenceCount, sequenceMatchEvents and sequenceNextNode now follow the input order for events that share a timestamp (for sequenceNextNode, events that also share the value), so sorting the input in a subquery, for example ORDER BY time, id, decides how such events are matched.

Description

Related: #124149 (follow-up asked for in #124149 (comment)).

On 26.9.9.28 (also 26.8, 26.3):

CREATE TABLE ev (t DateTime, x UInt8, e UInt8) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO ev VALUES ('2026-01-01 00:00:00', 2, 2), ('2026-01-01 00:00:00', 1, 1);
SELECT sequenceMatch('(?1)(?2)')(t, e = 1, e = 2) FROM (SELECT * FROM ev ORDER BY t, x); -- 0
-- 1 with SETTINGS query_plan_remove_redundant_sorting = 0

Two causes:

  1. The four functions are not registered is_order_dependent (sequenceNextNode sets it to false), so removeRedundantSorting drops the subquery ORDER BY.
  2. sequenceMatch, sequenceCount and sequenceMatchEvents sort events with the unstable ::sort, so even a kept ORDER BY does not decide tied events.

Change: flag the four registrations; AggregateFunctionSequenceMatchData::sort skips already ordered events and sorts the others with ::stableSort, on a trivially copyable struct instead of std::pair so that driftsort runs, not std::stable_sort. sequenceNextNode already sorts stably but breaks timestamp ties by the event value first; I can drop that tie-break if you prefer.

Released docs call the order of tied events undefined, hence Improvement.

Siblings: windowFunnel (checked on 96 queries) and retention do not depend on the input order.

Cost (release, median of 7, 20M rows): a subquery ORDER BY feeding these functions is now kept, so its sort is paid (3.58 s with ORDER BY t vs 0.86 s without). Without it, vs before: one random group 0.63x, one sorted group 1.02x, 1M groups 0.85x, all-ties groups 0.99x. Sorting unordered events needs driftsort's scratch buffer (up to the event list's size): 1.22x peak memory on one 500K-event group.

Test 05356_sequence_functions_tie_order, one function per query: every line differs from the reference on master; 51/51 with randomized settings. The four #124149 oracle-list entries go once it is merged.


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

groeneai and others added 2 commits October 9, 2026 03:14
…enceMatchEvents and sequenceNextNode

The result of these functions depends on the order in which events that
share a timestamp reach them, but a user could not control that order:

- The four functions were registered without `is_order_dependent`
  (`sequenceNextNode` set it to `false` explicitly), so
  `removeRedundantSorting` dropped a subquery `ORDER BY` feeding them,
  while it keeps one under `groupArray`.
- `sequenceMatch`, `sequenceCount` and `sequenceMatchEvents` sorted their
  events by timestamp with the unstable `::sort`, so even a kept
  `ORDER BY` did not decide the order of tied events (a debug build
  shuffles before sorting, so the result varied between runs).

Flag the four registrations and sort with `::stableSort`; `merge`
appends the other state after this one, so ties keep that order, as for
`groupArray`. `sequenceNextNode` already sorts stably and still breaks
timestamp ties by the event value. The docs said the order of tied
events is undefined; they now say it follows the input order, which is
defined when the input is sorted, and the `sequenceNextNode` section
states how it breaks timestamp ties (by value, then by input order).

The event was a `std::pair`, which is not trivially copyable, so
`::stableSort` fell back to `std::stable_sort`, a merge sort that does
not detect an already sorted input (2.26x slower than `::sort` on one
sorted group of 20M rows). It is now a plain struct with the same `first`
and `second` members, so `::stableSort` runs driftsort: 0.65x to 1.03x
of the old `::sort` time (release, median of 7). The state is still
serialized field by field, so its format is unchanged. Events that are
already ordered by timestamp, for example after a subquery `ORDER BY t`,
skip the sort: driftsort allocates its scratch buffer before it detects
the existing run, while `::sort` did not allocate for them.

The test runs one function per query, because the optimization keeps the
sort for the whole aggregation as soon as one function in it is
order-dependent.

Requested in ClickHouse#124149 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
State the TimestampEvents trivially-copyable requirement as an invariant instead of a comparison with std::pair.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 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 my own review; 8 findings over 4 rounds, the last round clean.

# Sev Finding Verdict Evidence / action
1 ⚠️ ::stableSort on std::pair falls back to std::stable_sort (not trivially copyable): one sorted group 2.26x, all-ties groups 1.27x slower AGREE, fixed event stored as a trivially copyable struct; now 0.63x / 1.02x / 0.85x / 0.99x of before
2 ⚠️ sequenceNextNode docs said nothing about its tie order AGREE, fixed note added to its docs section
3 ⚠️ That note promised ordering by timestamp and value, but UInt64 timestamps are kept as UInt32 and values are compared with strncmp AGREE, fixed note narrowed to the tie rules; widening the timestamp changes the state format, not in this PR
4 ⚠️ The test does not catch a revert to ::sort in release builds (ipnsort sorts up to 20 elements by insertion) DISAGREE CI runs it on amd_debug, where ::sort shuffles first (base/base/sort.h:165-167); with only that revert, the unsorted-input lines differ in 20/20 debug runs
5 💡 Changelog entry overstated the sequenceNextNode contract AGREE, fixed entry and description qualify it
6 💡 Oracle-list entries cannot be removed while #124149 is open AGREE stated in the description
7 💡 Docs tail "only events that share the same tick are ambiguous" no longer fits AGREE, fixed reworded
8 ⚠️ ::stableSort (driftsort) allocates its scratch buffer even for events already ordered by timestamp, where ::sort allocated nothing AGREE, fixed ordered events skip the sort (std::is_sorted); peak memory 1.00x of before on them, unordered input pays the buffer (stated in the description); a new test case covers the sorting path

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

Session id: cron:clickhouse-review-slot-9:20261009-031700

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --queries-file 05356_sequence_functions_tie_order.sql: released 26.9.9.28 prints the storage-order result on all 8 lines every run; the master debug build differs from the reference every run.
b Root cause explained? Yes. The four functions were not registered is_order_dependent, so removeRedundantSorting dropped the subquery ORDER BY; and sequenceMatch/sequenceCount/sequenceMatchEvents sorted events with the unstable ::sort, so even a kept ORDER BY did not decide tied events.
c Fix matches root cause? Yes. Both causes are fixed where they live: the registration flag and ::stableSort in AggregateFunctionSequenceMatchData::sort. The event is a trivially copyable struct instead of std::pair, so ::stableSort runs driftsort instead of falling back to std::stable_sort; events already ordered by timestamp skip the sort, since driftsort allocates its buffer before it finds the run.
d Test intent preserved / new tests added? New 05356_sequence_functions_tie_order, one function per query so a function that loses the flag is caught on its own. Existing tests and references unchanged.
e Both directions demonstrated? Fix build: identical to the reference in every run, 51/51 with randomized settings (plus clickhouse local on debug and release). Master: every run differs (the 8 tie lines 5/5, the 2 unsorted-input lines 3/3). Flag-only mutant (::sort, ordered-input skip kept): the 2 unsorted-input lines differ 20/20 (sort is load-bearing). Sort-only mutant: all 8 lines differ (flag is load-bearing).
f Fix is general across code paths? Yes. One shared sort() covers the three DFA/backtracking functions for every timestamp type; sequenceNextNode already sorts stably and gets the flag. windowFunnel measured order-independent in every mode (96 queries, 3 input orders); retention is order-independent by construction.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. -If, -OrNull, -State and the Nullable (-Null) wrapper keep the subquery sort (EXPLAIN on fix vs master); -Distinct loses input order by construction and is out of scope.
h Backward compatible? (maintainer-approved exception only) Yes. No state-format change (the struct is serialized field by field, as the pair was) and no setting. Results for tied timestamps can change, but that order was documented as undefined. Cost stated in the description: the kept subquery sort; the event sort itself is 0.63x to 1.02x of before (release, median of 7); unordered input pays driftsort's buffer (+3.8 MB peak on a 499K-event group), ordered input none.
i Invariants and contracts preserved? Yes. add/merge append and every read path calls sort() first; the stable sort keeps "this state, then the other" on merge. Ties across separately aggregated states follow merge order, as for groupArray, and the docs promise an order only for sorted input.

Session id: cron:clickhouse-impl-slot-4:20261009-024800

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e9e3b8b]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED

AI Review

Summary

This PR makes sequenceMatch, sequenceCount, sequenceMatchEvents, and sequenceNextNode preserve user-controlled tie order by keeping relevant subquery ORDER BY clauses and by switching the sequenceMatch family to a stable timestamp sort. I reviewed the current diff, the full PR discussion on https://github.com/ClickHouse/ClickHouse/pull/124812, and the current code paths around sort preservation and aggregation, and I did not find a correctness issue that warrants a new inline review comment.

Missing context / blind spots
  • ⚠️ I did not locally reproduce the large-group performance and memory claims from the PR description; the Praktika workflow for https://github.com/ClickHouse/ClickHouse/pull/124812 is green, but the performance-comparison jobs are skipped on this PR because it is not labeled pr-performance.
Final Verdict

✅ Looks good to me. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e9e3b8b

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, 2/4) / Build ClickHouse master-side build break, not from this PR (which changes the sequence* aggregate functions): src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25:11: error: use of undeclared identifier 'FifoQueue', the only error in the shard, in a file this PR does not touch. 17 true-master commits and 68 PRs fail this shard since 2026-10-09 00:30Z #124798 (external, open)
Mergeable Check, PR praktika rollups of the row(s) above (Dropped: 81), no independent failure #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

All 163 check runs completed. The other three arm_tidy shards passed. 81 jobs were dropped behind the shard 2/4 failure, so the functional test matrix has not run on this head yet.

Session id: cron:our-pr-ci-monitor:20261009-050007

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant