Skip to content

Support DateTime64 in sequenceMatch, sequenceCount and sequenceMatchEvents - #118427

Merged
alexey-milovidov merged 10 commits into
masterfrom
sequence-match-datetime64
Sep 24, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
sequence-match-datetime64

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

sequenceMatch, sequenceCount and sequenceMatchEvents rejected a DateTime64 timestamp:

SELECT test_key FROM t GROUP BY test_key
HAVING sequenceMatch('(?1)(?t<1296000)(?2)')(test_timestamp, test_field = 1000, test_field = 2000);

Code: 43. DB::Exception: Illegal type DateTime64(6) of first argument of aggregate function
sequenceMatch, must be DateTime. (ILLEGAL_TYPE_OF_ARGUMENT)

which forced a toDateTime(...) cast and threw away the sub-second part that decides the order of events inside a second. DateTime64 is what tables imported from PostgreSQL get for a timestamp column (#26216), so this is easy to hit without asking for it.

The family is now instantiated with DataTypeDateTime64::FieldType for the column type and Int64 for the stored timestamp, reading the tick value out of the ColumnDecimal. Two decisions worth calling out:

Timestamps keep the column's precision. Events are ordered and compared in the column's own ticks, so two events in the same second still order by their sub-second part rather than being ambiguous. sequenceMatchEvents returns Array(DateTime64(scale)) with that precision intact.

(?t...) durations stay in seconds. (?t<1296000) means 15 days whether the column is DateTime, DateTime64(3) or DateTime64(9), so a pattern keeps its meaning when a column's precision changes - which is the migration this issue was reported from. No duration is rejected: even a window that does not fit the ticks of the type is still evaluated.

The temporal conditions are compared on the distance between the two timestamps rather than on base + duration, with the distance and the scaled duration widened to Int128 (timeConditionSatisfied). A DateTime64 timestamp is signed and can sit at either end of Int64, so forming base + duration - or pre-scaling the duration into ticks - overflows for values the type itself accepts; comparing the distance does not.

windowFunnel still rejects DateTime64 - its data structures cast timestamps to UInt64 in several places, so it needs its own change and is not in scope here.

Closes: #31911

Changelog category (leave one):

  • Improvement

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

sequenceMatch, sequenceCount and sequenceMatchEvents now accept a DateTime64 timestamp instead of failing with Illegal type DateTime64(6) of first argument. Events are ordered at the column's full precision, so two events within the same second are no longer ambiguous. The durations in the (?t...) conditions of the pattern are in seconds for every timestamp type, so an existing pattern keeps its meaning when a column changes from DateTime to DateTime64.


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

Version info

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

…vents

    SELECT sequenceMatch('(?1)(?t<1296000)(?2)')(ts, e = 1000, e = 2000) FROM t

    Code: 43. DB::Exception: Illegal type DateTime64(6) of first argument of
    aggregate function sequenceMatch, must be DateTime. (ILLEGAL_TYPE_OF_ARGUMENT)

A `DateTime64` timestamp had to be wrapped in `toDateTime`, throwing away the
sub-second part that decides the order of events within a second.

Instantiate the family with `DataTypeDateTime64::FieldType` for the column type and
`Int64` for the stored timestamp, reading the tick value out of the `ColumnDecimal`.
Timestamps are compared at the column's own precision, so events sharing a second
still order by their sub-second part.

The durations in the `(?t...)` conditions of the pattern stay in seconds for every
timestamp type: they are converted to the argument's ticks once, when the pattern is
parsed, so the same pattern keeps its meaning when a column changes from `DateTime`
to `DateTime64` or between two `DateTime64` scales. A duration whose tick value does
not fit `Int64` is rejected with `ARGUMENT_OUT_OF_BOUND` instead of wrapping.

`PatternAction::extra` becomes signed, because a `DateTime64` timestamp can be
negative and `base_it->first + extra` would otherwise be evaluated in unsigned
arithmetic and wrap around zero.

`windowFunnel` still rejects `DateTime64`; its data structures cast timestamps to
`UInt64` in several places and are left for a separate change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 24, 2026, 1:48 AM

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6db11b7]

Summary: ✅


AI Review

Summary

This PR extends sequenceMatch, sequenceCount, and sequenceMatchEvents to accept DateTime64, keeps event ordering at the column's full tick precision, and evaluates (?t...) conditions in overflow-safe delta space. I re-checked the current diff together with the prior review threads; the earlier signed-overflow, oversized-window, wide-UInt, and docs issues are fixed in the current code, and I did not find a new unresolved correctness, compatibility, or documentation problem worth an inline comment.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 6db11b7.

Metric Baseline Current Δ
Lines 88.10% 88.20% +0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 70/71 (98.59%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6db11b7cc with master da7ece5f9 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 455029b82; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

9 object files changed (+313.59 KiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSequenceMatch… 1.80 MiB 2.10 MiB +310.81 KiB (+16.88%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

`GROUP BY type`, where `type` is an alias of `toTypeName(ts)`, is only accepted by the analyzer.
The old analyzer does not treat `toTypeName(ts)` in the `GROUP BY` as covering `ts`, and rejects
the query with `Column ts is not under aggregate function and not in GROUP BY` (`NOT_AN_AGGREGATE`),
so the test failed in `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated,
parallel, 1/3)`.

The type is only wanted as a label for the row, so take it from `any` instead and drop the
`GROUP BY` altogether. Every query still returns exactly one row, and the reference is unchanged.

Verified with `enable_analyzer` both 0 and 1.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118427&sha=86ce3f656c609f64c0654c838a67859237cd0be3&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F3%29
Related: #118427

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 5 commits September 11, 2026 10:21
Review feedback: making `PatternAction::extra` signed fixed the pre-epoch
wraparound, but the comparison sites still evaluated `base + duration`, which can
overflow for timestamps the `DateTime64` type accepts, and converting the
duration of a `(?t...)` condition to the ticks of the timestamp type rejected
durations that are perfectly meaningful at a high scale.

Both go away by comparing the distance between the two timestamps instead: the
duration stays in seconds, and `timeConditionSatisfied` widens the distance and
the duration to `Int128` before comparing them. Nothing is rejected any more.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A cast clamps a `DateTime64` to the range the type can print, so the test did not
actually reach the boundary it claims to test. `reinterpret` keeps the raw ticks.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review feedback asked for a case near the supported precision-9 upper boundary.
`2262-04-11 23:47:16` is the last whole second the type holds, so the old
`base + duration` formulation left the range of `Int64` for a one-second window:
a control binary built from the previous commit answers `0 1` for this query,
and it throws `ARGUMENT_OUT_OF_BOUND` for the large-window case above it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118427&sha=b03a2ce323b1c7f4befb8ff7094f2b2e46191a65&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is the ThreadSanitizer: data race on FutureSetFromSubquery::buildOrderedSetInplace reached from IcebergIterator, unrelated to this pull request (which only touches sequenceMatch and friends). The fix looks to be in flight in #118486, which has not merged yet, so the red is expected to persist here until it does.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed: this is the shared FutureSetFromSubquery in-place build race, unrelated to your change.

On b03a2ce3 the reader you spotted (buildOrderedSetInplace, called from the IcebergIterator prepare callback on the manifest reader thread) holds inplace_build_mutex; the writer is buildSetInplace on the query thread, from the ObjectIteratorWithPathAndFileFilter constructor, and it takes no lock. Both reach the same FutureSetFromSubquery because makeManifestFilterDag clones the filter DAG and the clone shares the ColumnSet.

Two of my PRs are open on it, and either one closes this pair:

Tracked in #118784. Master still builds those sets inside the callback (IcebergIterator.cpp:372), so the race will keep landing on unrelated branches until one of them merges. Nothing to do on this PR.

alexey-milovidov and others added 2 commits September 18, 2026 14:53
…amps

`timeConditionSatisfied` computed the distance between two events in `Int128`,
which is not wide enough for the `UInt256` timestamps that `sequenceMatch` has
always accepted: a gap of `2 ^ 200` lost all of its bits and a `(?t>1)`
condition was evaluated as if the two events shared a timestamp.

The distance is now computed in a type that holds every value of the timestamp
type - `Int128` for the types that fit into 64 bits, including the signed ticks
of `DateTime64`, and the unsigned timestamp type itself for `UInt128` and
`UInt256`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 709afee6:

Related: #118486 (the earlier FutureSetFromSubquery TSan race on this PR, still open).

Only `DateTime64` timestamps get their durations rescaled to seconds.
`Date` timestamps still compare `(?t...)` values in days and unsigned
integer timestamps in their own units, so say that explicitly instead of
claiming the value is always in seconds.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 24, 2026
Merged via the queue into master with commit 659b579 Sep 24, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the sequence-match-datetime64 branch September 24, 2026 16:30
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 6db11b7c Deployed Sep 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-improvement Pull request with some product improvements 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 doesn't support DateTime64(6) type fields

3 participants