Skip to content

Order sequenceNextNode events by the full UInt64 timestamp - #125015

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:sequence-next-node-uint64-timestamps
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:sequence-next-node-uint64-timestamps

Conversation

@groeneai

@groeneai groeneai commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124812

Changelog category (leave one):

  • Improvement

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

sequenceNextNode with a UInt64 timestamp now orders events by the full timestamp instead of its low 32 bits, so groups whose timestamps cross a multiple of 2^32 (every ~49.7 days of millisecond epochs) return the correct next node. Its state gets version 1 with 8-byte event times; states written by older servers stay readable.

Description

Found while working on #124812.

With a UInt64 timestamp, sequenceNextNode kept only the low 32 bits of each event time (NodeBase::event_time was UInt32), so events were ordered by t mod 2^32:

SET enable_funnel_functions = 1;
SELECT sequenceNextNode('forward', 'head')(t, page, page = 'A', page = 'A')
FROM values('t UInt64, page String', (1700807049215, 'A'), (1700807049217, 'B'));
-- 26.9.9.28 and master: \N, expected B

The in-memory event time is now UInt64, and the UInt64 instantiation gets state version 1 at protocol revision 54498, following the uniq scheme (#115393): a flags byte, then the old layout with 8-byte times. Unversioned types keep the old bytes, so existing tables and older peers read and write what they did. As with uniq, a new column is pinned to version 1, which older servers accept but write in the version 0 layout, so create such tables after every replica is upgraded. A state from version 0 data has only the low 32 bits; merging a full state with it drops the high bits of the full one, so such a merge orders like older servers (correct when a group fits in one 2^32 block). Version 1 head/tail states also keep the nodes the low 32-bit order would keep, so that result does not depend on where the state was serialized. ColumnAggregateFunction::updateHashFast now hashes at the state version, so states that differ only in the high bits no longer share an IN set or an aggregate projection. Other timestamp types are unchanged; windowFunnel, sequenceMatch and sequenceCount already keep the full timestamp.

Aggregate projections still store version 0 states and so still order by the low 32 bits: projection column types carry no state version, which already makes quantileDeterministic answer differently through a projection on released versions. That is a separate issue.

Validation: the new test fails on master; mutating each mechanism reddens its line; 50 randomized runs pass; on-disk and remote() checks against 26.9.9.28 pass in both directions.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 9, 2026 23:25
With a UInt64 timestamp, sequenceNextNode stored each event time in a
UInt32 (`NodeBase::event_time` was `DataTypeDateTime::FieldType`) and `add`
narrowed it, so events were sorted, merged and serialized by `t mod 2^32`.
A group whose events straddle a multiple of 2^32 (every ~49.7 days of a
millisecond epoch) was misordered: (1700807049215, 'A'), (1700807049217, 'B')
returned NULL instead of 'B' on 26.9.9.28 and master.

The node now keeps the full UInt64 (still 32 bytes), and the UInt64
instantiation gets state version 1 at protocol revision 54494, following
the scheme of `uniq` (fa37ee3):
- version 1 is a flags byte (bit 0: the times carry only their low 32
  bits) followed by the version 0 layout with 8-byte event times;
- unversioned types keep the version 0 bytes, so persisted states and
  older peers are unaffected; a fresh state spells version 1 in its type
  and a fresh table gets it pinned at DDL time;
- the version 0 writer of a full state sorts and prunes by the low 32
  bits, so its bytes and its `sorted` mark are those of an older server;
- a state read at version 0 is marked as truncated, and merging a full
  state with it truncates the full side first: such a merge orders like
  older servers, which is correct when a group fits in one 2^32 block;
- a version 1 head/tail state also keeps the nodes the low 32-bit order
  would keep (skipped when all times are in one 2^32 block, where the two
  orders coincide), so a later merge with version 0 data gives the same
  result whether or not the state was serialized first;
- the low 32-bit order breaks ties of equal low bits and value by the full
  time, so it does not depend on the order in which states arrive.

Other timestamp types keep the unversioned state and identical bytes.

Alternatives: widening only the in-memory value leaves distributed
queries, spills and -State/-Merge truncating; changing the layout without
a version breaks old parts and mixed-version clusters; rejecting
timestamps >= 2^32 rejects documented input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the version 1 dual-summary comment in sequenceNextNode serialize() to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Oct 10, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 4 findings) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Merging a version 0 state with a version 1 state depends on the merge order when two nodes share the low 32 bits and the value DISAGREE Such a merge is specified to order like older servers, and older servers order these nodes by arrival too. The version 0 node has no high bits, so there is no full order to restore. Not a regression.
2 ❌ Protobuf serializes aggregate states without their version, so a version 1 state is written as version 0 DISAGREE ProtobufSerializer.cpp has passed no version since 2021, for every versioned function (uniq, quantileDeterministic too). A Protobuf round trip therefore keeps the old 32-bit order, read back consistently. Passing the version there changes the Protobuf payload of uniq as well, so it is a separate format change.
3 ⚠️ Needs proof against a real older binary DISAGREE Checked against 26.9.9.28: remote() in both directions, tables written by 26.9.9.28 read and merged by this build, then reopened by 26.9.9.28. Freshly created columns are pinned to version 1 and use the same version 1 writer as the remote() test lines.
4 💡 Category should be Bug Fix DISAGREE sequenceNextNode is behind the experimental enable_funnel_functions setting, so this goes as Improvement.
5 💡 The full-time tie-break makes the order independent of arrival only among full states, not after one of them met version 0 data noted The commit message overstates this. Behaviour matches older servers.
6 💡 The tail side of the version 1 head/tail summary has no test line noted Only reachable in a mixed-version merge after a version 1 round trip.

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

Session id: cron:clickhouse-review-self-slot-58:20261009-232900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: sequenceNextNode('forward', 'head')(t, page, page = 'A', page = 'A') over (1700807049215, 'A'), (1700807049217, 'B') returns \N on 26.9.9.28 and master, B with the fix, every run.
b Root cause explained? The node stored the event time as UInt32 and add narrowed a UInt64 timestamp into it, so sorting, merging and the serialized state all compared t mod 2^32.
c Fix matches root cause? Yes: the node keeps the full UInt64, and the UInt64 state gets version 1 so the full value survives serialization.
d Test intent preserved / new tests added? New stateless test 05353_sequence_next_node_uint64_timestamps (in memory, window, state type, wire, legacy bytes, compat merges, tie order). Existing sequenceNextNode tests pass.
e Both directions demonstrated? Yes: the test fails on master (in-memory, wire, state-type and tie-order lines) and passes with the fix; deleting each mechanism (narrowing, 8-byte times, compat merge, state type, version 0 order, dual summary, tie-break) reddens its own line.
f Fix is general across code paths? add, sort, mergeImpl, serialize/deserialize and the window path all use the full time. windowFunnel, sequenceMatch, sequenceCount already keep the timestamp type and are correct on the same input.
g Fix generalizes across inputs (params/datatypes/wrappers)? Forward/head, backward/tail, first/last match and OVER () covered. UInt8/16/32, Date, DateTime keep the unversioned state and identical bytes. Nullable arguments go through the -Null adaptor, which forwards the version.
h Backward compatible? (maintainer-approved exception only) Yes: unversioned types keep the old bytes (equal to 26.9.9.28); older peers negotiate version 0. Tables written by 26.9.9.28 are read, merged and re-read by 26.9.9.28 after the fix wrote to them; mixed-version remote() works both ways.
i Invariants and contracts preserved? Every written state is sorted under its reader's order (version 0 by the low 32 bits, version 1 by the full time). A truncated state holds only truncated times. serialize sorts local copies only, and a node is still 32 bytes.

Session id: cron:clickhouse-impl-self-slot-57:20261009-215600

@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6a70e4c]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
UndefinedBehaviorSanitizer: undefined behavior (STID: 0993-9a84) FAIL cidb

AI Review

Summary

The PR preserves full UInt64 timestamps in sequenceNextNode, introduces a compatible versioned state, and makes ColumnAggregateFunction::updateHashFast respect the column version. Two previously reported serialization paths still lose the high timestamp bits. Both findings were dismissed by the author and remain in this summary only; there are no new inline findings. The previous hashing and std::iota findings are fixed.

Version flow checked: Native transfers negotiate the state version; temporary aggregation streams use the current protocol revision; generic aggregate serializers, column hashes, Field extraction, and arena serialization use the type or column version; State, Merge, and nullable adaptors forward it. The remaining exceptions are below.

Findings

❌ Blockers

  • src/AggregateFunctions/AggregateFunctionSequenceNextNode.cpp:259–264 — Aggregate projections can change query results. [dismissed by author -- https://github.com/Order sequenceNextNode events by the full UInt64 timestamp #125015#discussion_r4506699179] The current projection metadata still constructs an unversioned DataTypeAggregateFunction in InterpreterSelectQuery::getSampleBlockImpl, and MergeTreeDataWriter::writeProjectionPartImpl persists states using that metadata. Consequently, newly written projections still serialize at version 0. For a group containing A at timestamp 4294967295 and B at 4294967297, the ordinary forward/head calculation returns B, while the persisted projection contains B(1), A(4294967295) and returns NULL when the base condition is page = 'A'. This remains a correctness issue because projection selection must preserve query results, including on a fully upgraded server. Persist new projection states with full timestamps while retaining legacy decoding, and prevent truncated projection parts from answering queries requiring the full order.

  • src/AggregateFunctions/AggregateFunctionSequenceNextNode.cpp:259–264 — A Protobuf round trip discards full timestamps. [dismissed by author -- https://github.com/Order sequenceNextNode events by the full UInt64 timestamp #125015#discussion_r4235676601] ProtobufSerializerAggregateFunction::dataToString still calls serialize without the data type's version, and stringToData passes std::nullopt to deserialize. Both therefore select version 0, even for an explicitly versioned AggregateFunction(1, sequenceNextNode(...), UInt64, ...) column. The same two-event state above changes its finalized result from B to NULL after export and import. The pre-existing omission for other aggregate functions does not preserve this new state's semantics. Make this path version-aware with an explicit compatibility policy, or reject unsupported versioned states rather than silently truncating them.

Tests
  • ⚠️ The Fast test report for head 6a70e4c395d87 reports 05353_sequence_next_node_uint64_timestamps passing. It does not cover either remaining path. Add a forced-projection versus base-table comparison across a 2^32 boundary and a version-1 Protobuf export/import comparison of the finalized result. These findings were verified by tracing the current source; no local ClickHouse tests were run.
Final Verdict

Status: ❌ Block

Preserve full timestamps through projection persistence and Protobuf round trips, or explicitly exclude unsupported uses, with focused regression coverage. Author-resolved threads remain untouched.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7d673a4

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_binary, ParallelReplicas, s3 storage, parallel) / 05210_lightweight_update_materialized_cte_in_ignore flaky, not from this PR (145 of 146 reruns pass): Code: 60 ... Unknown table expression identifier '_materialized_cte_c_...' when a reused MATERIALIZED CTE is read through parallel replicas with a local plan. 51 PRs and 2 master runs show it in the last 3 days #123121 (mine, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log not from this PR: a background mutation of part all_1_1_1_2 keeps failing with Code: 47 ... Unknown expression identifier 'b' in MutatePlainMergeTreeTask. 79 PRs show it in the last 30 days #118499 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above #123121, #118499 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-060011

…uint64-timestamps

Resolve the protocol revision conflict: master took 54494
(`DBMS_MIN_REVISION_WITH_MERGE_COMBINATOR_STATE_VERSION`) and 54495
(`DBMS_MIN_REVISION_WITH_INSERT_RETURNING`), so
`DBMS_MIN_REVISION_WITH_SEQUENCE_NEXT_NODE_FULL_TIMESTAMPS` moves to 54496 and
`DBMS_TCP_PROTOCOL_VERSION` to 54496. The native-protocol docs follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 6a70e4c.

Approve preview

`ColumnAggregateFunction::updateHashFast` serialized the states without the
column's version, unlike `updateHashWithValue` and `computeHashInto`. A
`sequenceNextNode` state with `UInt64` timestamps written at version 0 keeps
only the low 32 bits of each event time, so two version 1 states that differ
only in the high bits hashed the same. The planner keys `IN` sets by the
constant's tree hash and the aggregate projection matcher compares `IN` sets
by content hash, so one set was reused for the other:

    materialize(<state of (4294967297, 'A'), (2, 'B')>) IN (<state of (1, 'A'), (2, 'B')>),
    materialize(<state of (4294967297, 'A'), (2, 'B')>) IN (<state of (4294967297, 'A'), (2, 'B')>)

returned `0 0` instead of `0 1`, and a projection grouping by membership in
one state was used for a query grouping by membership in the other.

Reported by the automated review on ClickHouse#125015.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ecf844

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 (arm_asan_ubsan, s3) / Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) not from this PR (it changes sequenceNextNode states, not parallel replicas): Got read request from replica 0 for unknown stream test_5.t_mt_index_rp when a row policy applies to a read shipped as a serialized query plan; 6 PRs and 1 master run in the last 30 days #114955 (mine, open)
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history says its default became true in 26.10; 94 PRs show the same row today #127687 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #114955, #127687 (the owners of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261024-173006

@rschu1ze
rschu1ze removed their request for review November 6, 2026 23:08
…uint64-timestamps

Master took protocol revision 54496 (`DBMS_MIN_PROTOCOL_VERSION_WITH_PROFILE_EVENTS_IN_SECONDARY_INSERT`),
so `DBMS_MIN_REVISION_WITH_SEQUENCE_NEXT_NODE_FULL_TIMESTAMPS` moves to 54497 and
`DBMS_TCP_PROTOCOL_VERSION` to 54497. The native-protocol docs (`format.mdx`, `protocol.mdx`)
follow the new number; master's 54496 entries are kept as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6a70e4c39 with master d31a6eff9 (stripped binary size, per-symbol sizes and ThinLTO time; 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 ⚠️

14 object files changed (+973.89 KiB total), 0 added.

Object file Master PR Δ
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemChangelog.generated.cpp.o 3.10 MiB 4.00 MiB +921.19 KiB (+29.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSequenceNextN… 447.79 KiB 500.45 KiB +52.66 KiB (+11.76%)

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

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

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::auto_changelog 292.03 KiB 371.81 KiB +79.78 KiB (+27.32%)

Job report

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1881890

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_tsan) / Segmentation fault (STID: 3366-4548) crash, not from this PR (it changes sequenceNextNode and its state serialization): the Pretty output format's squash thread renders a chunk whose column pointers are NULL (PrettyBlockOutputFormat::writingThread -> Chunk::checkNumRowsIsConsistent), on a query from an unrelated test a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found hung query, not from this PR (no window function or CrossTab code in the diff): a server-side AST fuzzer variant of 03711_contingency_window_function computes cramersV, cramersVBiasCorrected, theilsU and contingency over window frames on numbers(100000) and recomputes them in AggregateWindowFunctionRecalculate::evaluate; it was still running 846 s after it was cancelled a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the rows above a fix task is created (investigating at full effort, fixing-PR link to follow here)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261108-203007

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

About the Stress test (arm_asan_ubsan, s3) hung check row of the ledger above: I am not opening a fix for it. The fuzzed query computes cramersVBiasCorrected over ROWS BETWEEN 1024 PRECEDING AND 99999 FOLLOWING, so its frame start moves every row and the frame is re-aggregated per row, and window functions evaluate each batch without cancellation checks by design (see WindowTransform::computeReadyRows). The query keeps running until its batch ends. It is not caused by this PR, and this PR needs no change for it.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (amd_tsan) / Segmentation fault (STID: 3366-4548) row of the ledger above: #130211 (mine, open).

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found row of the ledger above: #130328 (external, open). It replaces my comment above that said no fix was needed.

…uint64-timestamps

Master took protocol revision 54497 for
DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD, so the
sequenceNextNode full-timestamp revision moves to 54498 (and
DBMS_TCP_PROTOCOL_VERSION with it); the native-protocol docs follow. Git
merged ProtocolDefines.h without a conflict, which would have left both
features on 54497.

The new sequenceNextNode overrides get [[nodiscard]], as master's
modernize-use-nodiscard now requires.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A backward/tail state with six nodes across a 2^32 boundary is sent at
version 1 and merged with a version 0 state. The answer depends on the
serialized state keeping the last nodes of the low 32-bit order: dropping
them gives U, keeping the head's nodes instead gives Q, the legacy answer
is R.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
std::iota deduces its counter type from the initial value, so the literal 0
made the counter a signed int while the vector holds size_t. A version 1
Head/Tail state with 2^31 or more nodes (add and merge do not cap the node
count, only deserialize does) would overflow the counter and store huge
indexes. Start the sequence at size_t{0}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6a70e4c

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 (arm_asan_ubsan) / UndefinedBehaviorSanitizer: undefined behavior (STID: 0993-9a84) sanitizer report from master: unsigned wraparound in offsets[row - 1] at src/Functions/FunctionsConversion.cpp:3649 (JSON conversion), not touched by this PR; the tested merge tree predates the fix #133910 (external, merged)
Mergeable Check / PR praktika rollups of the row above #133910 (external, merged)

The Finish Workflow / Post Hooks row in CIDB is from the first run, limited by an unresolved review thread; the re-run on the same head finished green. CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20261124-063028

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-self PR origin: self-found defect (impact-bar validated) pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant