Skip to content

Add a TOLERANCE clause to ASOF JOIN - #115530

Closed
elkinal wants to merge 8 commits into
ClickHouse:masterfrom
elkinal:asof-tolerance-clause
Closed

elkinal wants to merge 8 commits into
ClickHouse:masterfrom
elkinal:asof-tolerance-clause

Conversation

@elkinal

@elkinal elkinal commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #109034

ASOF JOIN matches the closest row however far away it is, so a trade can be matched against a quote from hours earlier. TOLERANCE bounds that distance:

SELECT trades.time, trades.price, quotes.bid
FROM trades
ASOF LEFT JOIN quotes
ON trades.symbol = quotes.symbol AND trades.time >= quotes.time
TOLERANCE INTERVAL 5 SECOND

The bound is inclusive. With ASOF LEFT JOIN a row whose closest match is out of tolerance is kept with default or NULL values on the right, following join_use_nulls, which is what pandas.merge_asof(tolerance=...) does. With ASOF JOIN it is dropped, like a row with no match at all.

It can be written as an INTERVAL, or as a plain number in the units of the ASOF column. For a DateTime64(3) column TOLERANCE 5000 and TOLERANCE INTERVAL 5 SECOND are the same bound.

Implementation notes

The bound is converted into the units of the ASOF key once, during planning, so the join implementation compares it against key values directly with no per-probe conversion. findAsof already returns the closest match in the direction the inequality fixes, so if that one is out of bounds no other can be closer and the probe has no match.

The interval unit is read from the result type rather than from the shape of the expression: INTERVAL 5 SECOND is written toIntervalSecond(5) but is constant folded during resolution into a constant whose value is 5 and whose type is IntervalSecond, so treating it as a bare number silently means five milliseconds against a DateTime64(3) key.

Rejected rather than approximated

  • MONTH, QUARTER and YEAR, which are not fixed lengths of time.
  • An INTERVAL against an ASOF key that is not a date or time, where the unit would be undefined.
  • A bound finer than the key's resolution, such as INTERVAL 1 MICROSECOND against DateTime64(3), which would otherwise round down to "exact matches only".
  • A negative bound, which nothing can satisfy.
  • A bound that does not fit the ASOF key's type, whether written directly or reached by rescaling an INTERVAL. Narrowing it instead wraps a large bound into a small one, which quietly rejects valid matches.
  • CROSS and comma joins, which have nowhere to put a bound at all.
  • enable_analyzer = 0, which builds TableJoin without the query tree the bound travels on and would silently ignore it.
  • full_sorting_merge, which matches through IColumn::compareAt and so has ordering but not distance. The planner falls back to another enabled algorithm; if only full_sorting_merge is enabled the query fails.

Each of these silently returns matches further away than the query asked for if it is accepted instead, which is the failure this clause exists to prevent.

Changelog category (leave one):

  • New Feature

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

Added a TOLERANCE clause to ASOF JOIN, bounding how far apart the left and the matched right value of the ASOF column may be, so that stale rows are not matched. The bound can be given as an INTERVAL or as a number in the units of the ASOF column, for example ASOF LEFT JOIN quotes ON trades.symbol = quotes.symbol AND trades.time >= quotes.time TOLERANCE INTERVAL 5 SECOND.


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

Implements ClickHouse#109034 for constant
numeric tolerances. INTERVAL tolerances are not supported yet, see below.

- Parser: `TOLERANCE <expr>` after the ON/USING clause, stored on `ASTTableJoin`
  and carried through clone, formatting and AST JSON.

- Analyzer: `JoinNode` gains a fourth child for the bound. `TOLERANCE` on a
  non-ASOF join is rejected with a clear message rather than silently ignored.

- Planner: the bound must be constant, since it applies to every probe. It is
  carried on `JoinOperator` and set on `TableJoin` next to the ASOF inequality.

- Hash join: `findAsof` already returns the closest match in the direction the
  inequality fixes, so if that one is out of bounds no other can be closer and
  the probe has no match. For a LEFT join that yields NULLs and keeps the left
  row, matching `pandas.merge_asof(tolerance=...)`.

- Full sorting merge declines a join carrying a tolerance. It matches through
  `IColumn::compareAt`, which gives ordering but not distance, so it cannot
  enforce the bound. Declining makes the planner fall back to an algorithm that
  can, instead of silently returning matches beyond the requested distance.

Not done yet: `TOLERANCE INTERVAL 5 SECOND` parses to `toIntervalSecond(5)`,
a function rather than a constant, and converting an interval to the scale of a
`DateTime64` key needs unit handling that is not written. Numeric tolerances in
the key's own units work today.
- `TOLERANCE INTERVAL 5 SECOND` now works. The unit is read from the result type
  rather than from the shape of the node: `toIntervalSecond(5)` is constant
  folded during resolution into a constant whose value is 5 and whose type is
  `IntervalSecond`, so treating a constant as a bare number silently took it as
  5 in the key's own units, which for a `DateTime64(3)` key meant 5 milliseconds.

- The tolerance expression is now resolved in `resolveJoin`. Without that the
  interval stayed an unresolved function with no result type.

- Intervals are converted to the units of the ASOF key once that type is known,
  so `INTERVAL 5 SECOND` becomes 5000 against a `DateTime64(3)` key.

- Rejected rather than approximated: `MONTH`, `QUARTER` and `YEAR`, which have no
  fixed length; an `INTERVAL` against a key that is not a date or time; a bound
  finer than the key's resolution, which would round down to "exact matches
  only"; and a negative bound, which nothing can satisfy.

- Adds 05023_asof_join_tolerance covering matching, the inclusive boundary, one
  unit past it, `LEFT` nulling versus `INNER` dropping, bare numeric bounds, and
  each rejection.

- Documents the clause under ASOF JOIN, including that `full_sorting_merge`
  cannot run it.
Self review before opening the pull request, prompted by the same class of gap
found in review of ClickHouse#115226: a change that is narrower than the claim made for it.

- With `enable_analyzer = 0` the bound was silently dropped. That path builds
  `TableJoin` directly and never sees the query tree the tolerance travels on, so
  a query asking for a five second bound quietly matched a row an hour away. It
  now fails with a clear message. Refusing is deliberate; returning matches
  further away than asked for is worse than not supporting the clause.

- Extends the test with the cases that were not covered: the `USING` form,
  `parallel_hash`, two queries differing only in the bound answering differently
  (which a shared plan or cache entry would break), and both refusals.

- Documents that the clause requires the analyzer.
@elkinal

elkinal commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

@yariks5s this is ready for review, as offered on #109034.

One decision worth your view: full_sorting_merge declines a join carrying a tolerance rather than implementing it, because it matches through IColumn::compareAt, which gives ordering but not distance. The planner falls back to another enabled algorithm, and the query fails if only full_sorting_merge is allowed. Same for enable_analyzer = 0, which never sees the query tree the bound travels on. Both refuse rather than silently returning matches beyond the requested distance, but I am happy to change either if you would rather they were implemented.

@tuanpach tuanpach added the can be tested Allows running workflows for external contributors label Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8838c45]

Summary: ⏳

job_name test_name status info comment
Docs check (Mintlify) FAIL
Check internal links and anchors FAIL cidb
AST fuzzer (amd_debug, targeted) FAIL
Logical error: CROSS JOIN has A expressions: [B, ...] (STID: 0250-2608) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: CROSS JOIN has A expressions: [B, ...] (STID: 0250-2608) FAIL cidb

AI Review

Summary

Adds TOLERANCE to ASOF JOIN, threads the bound from parsing through planning to hash-join execution, documents it, and adds focused stateless coverage. The main behavior looks solid after the follow-up fixes, but I still see one blocker in query-plan serialization compatibility and one major omission in the parallel-replicas statistics cache key.

Findings

❌ Blockers

  • [src/Interpreters/JoinOperator.cpp:375] Appending asof_tolerance to JoinOperator changes the JoinStepLogical payload while DBMS_QUERY_PLAN_SERIALIZATION_VERSION stays 9. A mixed-version cluster will deserialize the stream at the wrong offset: old readers treat the first new boolean as the actions_after_join length, and new readers consume an old node-list as the tolerance flags. That can break distributed plan shipping even for joins that do not use TOLERANCE. Suggested fix: bump the query-plan serialization version and gate this payload on it, or add a self-describing step-level extension that older readers reject before continuing.

⚠️ Majors

  • [src/Processors/QueryPlan/JoinStepLogical.cpp:1626] Bounded and unbounded ASOF joins now have different output cardinalities, but calculateHashTableCacheKeys.cpp still keys ASOF runtime-dataflow statistics only by inequality. Queries that differ only by TOLERANCE can therefore share the same cache entry, skewing Auto-PR / parallel-replica decisions for parallel_hash ASOF joins. Suggested fix: mix a presence bit and the converted table_join->getAsofTolerance() value into the orientation-invariant ASOF hash alongside the inequality.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 20, 2026
Comment thread src/Interpreters/JoinOperator.h Resolved
Comment thread src/Interpreters/RowRefs.cpp Resolved
Comment thread src/Interpreters/RowRefs.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8838c4566 with master 2797514bd (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
Binary Master PR Δ
programs/clickhouse-stripped 709.23 MiB 706.24 MiB -2.99 MiB (-0.42%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

124 object files changed (+427.29 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/RowRefs.cpp.o 1.17 MiB 1.36 MiB +189.81 KiB (+15.83%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStepLogical.cpp.o 887.34 KiB 960.34 KiB +72.99 KiB (+8.23%)
src/CMakeFiles/dbms.dir/QueryPipeline/QueryPipelineBuilder.cpp.o 355.63 KiB 373.88 KiB +18.25 KiB (+5.13%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/convertOuterJoinToInnerJoin.cpp.o 111.31 KiB 128.94 KiB +17.62 KiB (+15.83%)
src/CMakeFiles/dbms.dir/Planner/PlannerJoinsLogical.cpp.o 399.27 KiB 416.44 KiB +17.16 KiB (+4.30%)
src/CMakeFiles/dbms.dir/Interpreters/JoinOperator.cpp.o 153.73 KiB 169.85 KiB +16.12 KiB (+10.49%)

737 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

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

Job report

…flow

- The bound was not serialized with `JoinOperator`, so a plan serialized and
  executed elsewhere, as on the distributed paths, deserialized into an ASOF JOIN
  with no bound and returned matches the query had excluded. Now written and read
  back with the rest of the operator.

- A bare numeric bound was cast into the key type without checking it fit, so
  `TOLERANCE 0.5` against an integer backed key truncated to zero and quietly
  became exact matches only, and `TOLERANCE 1000` against a `UInt8` key wrapped to
  232. It is now converted strictly and rejected when it cannot be represented,
  which is what the `INTERVAL` path already did.

- The check added the bound to one endpoint, which leaves the type's range near
  the top of the key domain: with a `UInt8` key, right value 250 and probe 255, a
  bound of 10 computed 250 + 10 = 4 and dropped a valid match. It now detects
  that the endpoint cannot be shifted and treats everything on that side as
  within the bound.

The native type of the key is selected through a specialisation rather than
`std::conditional_t`, which named `TKey::NativeType` even for plain arithmetic
keys that have no such member, and `UInt8` is `char8_t` here.

Each defect is covered by a case in 05023_asof_join_tolerance.
Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
@yariks5s yariks5s self-assigned this Aug 20, 2026
@yariks5s

Copy link
Copy Markdown
Member

One decision worth your view: full_sorting_merge declines a join carrying a tolerance rather than implementing it, because it matches through IColumn::compareAt, which gives ordering but not distance. The planner falls back to another enabled algorithm, and the query fails if only full_sorting_merge is allowed. Same for enable_analyzer = 0, which never sees the query tree the bound travels on. Both refuse rather than silently returning matches beyond the requested distance, but I am happy to change either if you would rather they were implemented.

We can leave the issue with full_sorting_merge for now and someone (probably me) will cover this case in the follow-up PR. Regarding analyzer=0, we can skip the support of this case without analyzer

Both from review, and both the same shape as earlier findings: a path that did
not get the check.

- The rejection for non-ASOF joins sat inside the branch that builds a
  `JoinNode`, but `CROSS` and comma joins take the branch above it and build a
  `CrossJoinNode`, which has nowhere to put a bound. `CROSS JOIN ... TOLERANCE 5`
  was accepted and ran as a plain cross join with the bound discarded. The check
  now happens before either branch, so no path can drop it.

- The `INTERVAL` path returned the rescaled value without the exact conversion
  the bare-number path had gained, so it was narrowed into the key type unchecked
  later: `INTERVAL 70000 DAY` against a `Date` key arrived as 70000 and wrapped to
  4464, rejecting matches a whole-domain bound should have kept. It now goes
  through the same conversion and reports being out of range.
@elkinal

elkinal commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, that settles both. Left full_sorting_merge refusing rather than half-implementing, and dropped support for enable_analyzer = 0, as you suggested.

Pushed fixes for the review findings since:

  • TOLERANCE was silently dropped on CROSS and comma joins. The non-ASOF rejection sat inside the branch that builds a JoinNode, and those take the branch above it, so the bound just disappeared. Checked before either branch now.
  • The INTERVAL path skipped the exact conversion the bare-number path had, so INTERVAL 70000 DAY against a Date key arrived as 70000 and wrapped to 4464. Both paths now go through the same conversion.
  • Earlier: the bound was not serialized with JoinOperator, so a serialized plan came back unbounded; a bare numeric bound was narrowed without a range check; and adding the bound to an endpoint overflowed near the top of the key domain, dropping a valid match with a UInt8 key at 250 and 255.

Each has a case in 05023_asof_join_tolerance.

Found while reading the diff rather than in review. The rescaled duration was cast
from `Int128` down to `Int64` before being range checked, so a value past the key's
range wrapped into a valid looking number and the check then accepted it.

`TOLERANCE INTERVAL 9223372036854775807 SECOND` against a `DateTime64(3)` key
rescales to roughly 9.2e21 milliseconds. That does not fit, but it wrapped into
range and was taken as a bound the query never asked for. Larger literals were
accepted while smaller ones were correctly rejected, which is how it surfaced.

The value is now checked while still wide and rejected if it will not fit. Also
guards the multiplication into nanoseconds, which can overflow before anything
downstream gets a chance to look at the result.
The implementation rejects a negative bound and one that does not fit the ASOF
key's type, including after an INTERVAL is rescaled, but the documentation listed
neither, so a user hitting either got an error the page did not mention.
/// The ASOF `TOLERANCE` bound. Without this a serialized plan executed elsewhere, as on the
/// distributed paths, would deserialize into an ASOF JOIN with no bound at all and quietly
/// return matches further away than the query asked for.
writeBinary(asof_tolerance.has_value(), out);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This changes the JoinOperator wire layout at the existing query-plan serialization version. DBMS_QUERY_PLAN_SERIALIZATION_VERSION is still 9 in src/Core/ProtocolDefines.h, and JoinStepLogical::deserialize still reads actions_after_join immediately after JoinOperator. An older v9 reader will treat the first new boolean as the node-list length; a newer reader will consume an old stream's node-list bytes as has_tolerance / has_interval_kind. That breaks distributed plan exchange during a rolling upgrade even for joins that do not use TOLERANCE.

I think this needs a query-plan serialization version bump (or a step-level extension that older readers reject before touching the rest of the payload), not just appending fields here.

@@ -1504,6 +1622,9 @@ static QueryPlanNode buildPhysicalJoinImpl(
used_expressions.push_back(rhs);

table_join->setAsofInequality(*asof_inequality_op);
if (join_operator.asof_tolerance)
table_join->setAsofTolerance(convertAsofToleranceToKeyUnits(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Once TOLERANCE reaches TableJoin, it also needs to become part of the runtime-dataflow stats key in src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp. That code already special-cases ASOF inequality, but it still ignores getAsofTolerance(), so two queries that differ only by the bound collapse to the same cache entry. For parallel_hash ASOF joins that means Auto-PR / parallel-replica costing can reuse output_bytes from an unbounded join for an exact-match-only join, or vice versa.

Please mix a presence bit plus the converted tolerance value into the orientation-invariant ASOF hash alongside the inequality.

Both from review.

- The bound was appended to the serialized `JoinOperator` without changing the
  query plan serialization version, so the layout changed underneath version 8.
  A version 8 reader takes the first new byte for the length of the node list
  that follows and desynchronises the stream, which breaks distributed plan
  exchange during a rolling upgrade for every join, not only those using
  TOLERANCE. The version is now 9 and the fields are written only from 9, with
  the version threaded through `JoinOperator::serialize` and `deserialize`.

- `calculateHashTableCacheKeys` already mixes the ASOF inequality into the
  runtime stats key, because it changes which rows match. A tolerance changes
  which rows match in the same way and was ignored, so a bounded and an
  unbounded join over the same inputs shared a statistics entry and parallel
  replica costing could reuse one's `output_bytes` for the other. The presence
  bit and the value are now mixed in alongside the inequality.

Covered by a case asserting a bounded, a wider and an unbounded join stay
distinct with `collect_hash_table_stats_during_joins` enabled.
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

  1. The new fields change the serialized join layout, but master already uses version 9. Bump the query-plan version so incompatible readers reject it, and update NativeProtocol.mdx

    if (version < DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_ASOF_TOLERANCE)

  2. For Decimal64(2), tolerance 1.50 becomes raw bound 1 instead of 150. Keys 2.00 and 1.00 then fail to match. Preserve the scaled integer

    if constexpr (is_decimal<TKey>)

  3. DateTime rejects INTERVAL 5 SECOND., DateTime64(9) overflows on INTERVAL 10 SECOND because ticks are scaled twice. Convert durations directly to the key’s storage units

    const Field rescaled = Field(static_cast<Int64>(rescaled_value));

  4. TOLERANCE 4294967296 on DateTime silently becomes zero. Check the UInt32 range before narrowing

    return convertFieldToTypeOrThrow(tolerance, *removeNullable(key_type));

5.Float32 keys 16777218 and 16777216 match with tolerance 1.5, despite their distance being 2. Adding the bound to an endpoint rounds upward

return probe_value <= static_cast<Native>(matched_value + bound);

  1. TOLERANCE rand(5) is treated as tolerance 5. Require a resolved constant instead of taking a function’s argument

    else if (const auto * tolerance_function = tolerance_node->as<FunctionNode>())

@yariks5s yariks5s added the close in a month if not active This will be closed in case of no information label Sep 9, 2026
pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 26, 2026
…ness's own queries

After a clean fuzz run (`Fuzzer exit code is 143`), the post-fuzz liveness
probe `clickhouse-client --handshake_timeout_ms=30000 --receive_timeout=5
--query 'SELECT 1'` sometimes never returns. status.tsv is then never
written, praktika kills the job at its 18000 s timeout before any artifact
is uploaded, and the job reports a bare ERROR with no server log. Five such
runs in 45 days: PR ClickHouse#112304 (2026-08-18), PR ClickHouse#98670 (2026-08-19), PR ClickHouse#115530
(2026-08-20), true master 9816d0a `AST fuzzer (amd_release, oracle)`
(2026-09-24) and PR ClickHouse#119237 `AST fuzzer (amd_debug, targeted,
old_compatibility)` (2026-09-25). Only the last one printed the `1`.

Two harness defects make the probe unbounded.

(a) The probe is itself fuzzed on the server. query-fuzzer-tweaks-users.xml
sets ast_fuzzer_runs=5 and ast_fuzzer_any_query=true on the `default`
profile, and no harness-owned client call opted out. The server runs the
mutated copies in a query-finish callback, and TCPHandler calls
io.onFinish() after sending the data and before EndOfStream, so a fuzzed
follow-up that does not finish holds the reply open after the `1` was
printed. The same pin was part of ClickHouse#113248, which was closed as already
integrated, but its run-fuzzer.sh half never reached master. The stress
harness (ClickHouse#114127), the log export (ClickHouse#117996) and tests/clickhouse-test
already pin it.

(b) --receive_timeout does not bound the probe either. On a receive
timeout ClientBase::receiveResult only records TIMEOUT_EXCEEDED and cancels
the query; from then on it polls the connection until the server sends a
packet, with no bound. A server whose connection thread never gets back to
the socket holds the probe forever, which is what the four runs that
printed nothing show.

Pin --ast_fuzzer_runs=0 on every harness-owned client call through one
variable; the fuzzer's own client stays unpinned. Run the two post-fuzz
probes (the restart liveness check and the probe loop) under
`timeout --signal TERM --kill-after=10 60`. A probe killed by timeout
(rc 124, or 137 after the kill) is counted like the client's own
"Timeout exceeded while", so a server that stops answering reaches the
existing "treating server as hung" verdict after 12 retries (about
14 minutes) and the job keeps its logs. 60 s covers the probe's own worst
case (30 s handshake, 5 s receive timeout, the cancel round trip) with room
for a slow sanitizer server. The fallback branch now prints the probe's
exit code instead of the last grep's.

The pre-fuzz probes are not wrapped: the check after attaching gdb waits
for gdb to load debug info on purpose, and the server is fresh there.

One server-side hang the fuzzer produces, a self-deadlock when one query
builds two system.stack_trace sources, is fixed separately in ClickHouse#120216.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@yariks5s yariks5s closed this Oct 8, 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 close in a month if not active This will be closed in case of no information comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a TOLERANCE clause to ASOF JOIN

3 participants