Repository navigation
Conversation
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.
|
@yariks5s this is ready for review, as offered on #109034. One decision worth your view: |
|
Workflow [PR], commit [8838c45] Summary: ⏳
AI ReviewSummaryAdds Findings❌ Blockers
Final VerdictChanges requested. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes124 object files changed (+427.29 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units913 translation units recompiled, 6134 s compile time in total, 913 of them have a recent master baseline. |
…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.
We can leave the issue with |
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.
|
Thanks, that settles both. Left Pushed fixes for the review findings since:
Each has a case in |
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); |
There was a problem hiding this comment.
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( | |||
There was a problem hiding this comment.
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.
yariks5s
left a comment
There was a problem hiding this comment.
-
The new fields change the serialized join layout, but
masteralready uses version9. Bump the query-plan version so incompatible readers reject it, and updateNativeProtocol.mdxClickHouse/src/Interpreters/JoinOperator.cpp
Line 381 in 79a8107
-
For
Decimal64(2), tolerance1.50becomes raw bound1instead of150. Keys2.00and1.00then fail to match. Preserve the scaled integerClickHouse/src/Interpreters/RowRefs.cpp
Line 110 in 79a8107
-
DateTimerejectsINTERVAL 5 SECOND.,DateTime64(9)overflows onINTERVAL 10 SECONDbecause ticks are scaled twice. Convert durations directly to the key’s storage units -
TOLERANCE 4294967296onDateTimesilently becomes zero. Check theUInt32range before narrowing
5.Float32 keys 16777218 and 16777216 match with tolerance 1.5, despite their distance being 2. Adding the bound to an endpoint rounds upward
ClickHouse/src/Interpreters/RowRefs.cpp
Line 149 in 79a8107
-
TOLERANCE rand(5)is treated as tolerance5. Require a resolved constant instead of taking a function’s argument
…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]>
Closes: #109034
ASOF JOINmatches the closest row however far away it is, so a trade can be matched against a quote from hours earlier.TOLERANCEbounds that distance:The bound is inclusive. With
ASOF LEFT JOINa row whose closest match is out of tolerance is kept with default orNULLvalues on the right, followingjoin_use_nulls, which is whatpandas.merge_asof(tolerance=...)does. WithASOF JOINit 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 theASOFcolumn. For aDateTime64(3)columnTOLERANCE 5000andTOLERANCE INTERVAL 5 SECONDare the same bound.Implementation notes
The bound is converted into the units of the
ASOFkey once, during planning, so the join implementation compares it against key values directly with no per-probe conversion.findAsofalready 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 SECONDis writtentoIntervalSecond(5)but is constant folded during resolution into a constant whose value is5and whose type isIntervalSecond, so treating it as a bare number silently means five milliseconds against aDateTime64(3)key.Rejected rather than approximated
MONTH,QUARTERandYEAR, which are not fixed lengths of time.INTERVALagainst anASOFkey that is not a date or time, where the unit would be undefined.INTERVAL 1 MICROSECONDagainstDateTime64(3), which would otherwise round down to "exact matches only".ASOFkey's type, whether written directly or reached by rescaling anINTERVAL. Narrowing it instead wraps a large bound into a small one, which quietly rejects valid matches.CROSSand comma joins, which have nowhere to put a bound at all.enable_analyzer = 0, which buildsTableJoinwithout the query tree the bound travels on and would silently ignore it.full_sorting_merge, which matches throughIColumn::compareAtand so has ordering but not distance. The planner falls back to another enabled algorithm; if onlyfull_sorting_mergeis 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a
TOLERANCEclause toASOF JOIN, bounding how far apart the left and the matched right value of theASOFcolumn may be, so that stale rows are not matched. The bound can be given as anINTERVALor as a number in the units of theASOFcolumn, for exampleASOF 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]