Skip to content

fix(join): enforce typed-key equality across spill and runtime filters - #26472

Merged
XuPeng-SH merged 23 commits into
matrixorigin:mainfrom
XuPeng-SH:agent/issue-26432-float32-scale-contract
Aug 1, 2026
Merged

XuPeng-SH merged 23 commits into
matrixorigin:mainfrom
XuPeng-SH:agent/issue-26432-float32-scale-contract

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes

Related to #26432. This is an incremental typed-key/spill contract PR and intentionally does not close the entire issue.

Why

Spill is not a second equality implementation. If scalar SQL says two join keys are equal, resident join, initial spill, probe partitioning, recursive re-spill, and any pre-join runtime filter must preserve that match.

Two correctness gaps violated that rule:

  1. Scaled FLOAT32 scalar comparison normalizes each operand to its declared scale, but resident hash keys and spill partition keys previously used raw IEEE-754 bytes. SQL-equal values could land in different hash groups/buckets.

  2. An exact runtime filter is optional but may run before the join in scans, zonemaps, and Bloom filters. Those consumers compare encoded payloads, not the final join equality. A stale or under-specified plan could therefore silently remove a row that the join itself would match. The concrete stale-plan shape is:

    probe:   DECIMAL(...,2), raw 100  = 1.00
    spec:    DECIMAL(...,3)
    payload: DECIMAL(...,3), raw 1000 = 1.000
    

    SQL = is true, while old raw IN compares 100 != 1000.

What this PR changes

One typed-key contract for resident and spill

  • Float32ScaleNormalizer is shared by scalar comparison and key encoding.
  • Each operand is normalized with its own declared scale, so mixed-scale equality is symmetric.
  • Float32Codec supplies the canonical resident/spill key and closes +0/-0.
  • The same codec is used by IntHashMap, composite StrHashMap, initial build spill, probe partitioning, and recursive re-spill.
  • Only ephemeral hash/partition keys are canonicalized. Input vectors and spill-file payloads retain their original values and format.
  • Type dispatch and scale setup happen once per vector/comparison; there is no per-row allocation or interface dispatch.

Exact runtime filters are versioned, selective, and fail open

The planner and all producers now share an explicit contract:

probe declared type
        ↕ SQL equality
declared build type
        ↕ physical payload
actual materialized build type
  • RuntimeFilterKeyEncoding is an explicit versioned marker. Default, legacy, unknown, contradictory, or incomplete metadata publishes PASS.
  • RuntimeFilterSpec carries the probe type, producer expression, and ordered component probe types for tuple encodings.
  • HashBuild, IndexBuild, and FuzzyFilter validate the complete triangle before collecting or publishing an exact payload.
  • Decimal scale is part of the contract. The real scale-2 probe / scale-3 spec+payload stale-plan case now fails open.
  • Metadata-independent raw types such as integer and string retain the legacy expression as well as the v1 contract. They continue to produce exact filters on protocol v6 during rolling upgrade.
  • Metadata-dependent decimal, signed-zero-closed float, serialized tuple, and FuzzyFilter contracts require protocol v8. An old producer sees no usable legacy expression and publishes PASS.
  • Safe FLOAT64 and unscaled FLOAT32 exact filters remain enabled. If zero exists, the payload contains both physical +0 and -0, so raw Bloom consumers cannot reject a SQL-equal zero.
  • Scaled FLOAT32 remains PASS for exact raw filters: its rounded SQL equivalence class cannot be represented by the current raw IN/zonemap/Bloom payload without false negatives.
  • Planner statistics, dependencies, placement, and index rewrites are changed only after a filter is proven materializable. A filter that must be PASS no longer creates optimistic side effects.
  • Cached/cross-version plans remain defensive at execution; an optional filter failure never turns into wrong results.

This is selective conservatism, not a blanket FLOAT runtime-filter disable.

Spill/runtime-filter memory and unhappy paths

  • Runtime-filter payloads use one shared budgeted marshaller and reserve actual wire/capacity costs before allocation.
  • HashBuild accounts selected key slots only, actual vector capacity, varlen area copied by UnionBatch, reallocation overlap, tuple packer classes, scratch memory, and message-owned wire payloads.
  • A whole-vector varlen copy now budgets the complete source area, including dead/stale area, before destination allocation.
  • Optional filter collection or serialization failure abandons the optional state and publishes PASS; mandatory hash-map construction continues.
  • Terminal success/error paths publish exactly one terminal message and release retained optional keys.
  • Dedup's destructive retained-batch rewrite marks recovery unsafe before mutation. Admission failure re-spills only while retained rows are still replayable; otherwise it stops safely instead of duplicating or losing rows.
  • Capacity checks return immediately when no vector growth is needed, avoiding repeated chunks × retained-batches scans.

NaN scope is deliberately narrow

This PR does not define NaN join equality and does not redesign every zonemap predicate.

  • Float min/max construction skips NULL and NaN.
  • All-NaN/all-NULL input leaves the zonemap uninitialized.
  • Legacy float zonemaps already poisoned by a NaN bound fail open only in the runtime-IN pruning chain (AnyGEByValue, AnyLEByValue, SubVecIn, AnyIn).
  • Float AnyIn/SubVecIn uses the same total-order comparator as sorting.

This is the minimum compatibility fix needed to prevent a poisoned legacy bound from silently hiding an ordinary matching value.

Contract status

Every active equality case uses the real scalar = evaluator as the oracle.

Type / values SQL equality Resident Initial spill Re-spill Exact runtime filter
DOUBLE +0 / -0 TRUE match match match enabled with zero closure on v8
unscaled FLOAT32 +0 / -0 TRUE match match match enabled with zero closure on v8
scaled/mixed-scale FLOAT32 equal after declared-scale normalization TRUE exact match exact match exact match PASS
nearby scaled FLOAT32 values that normalize differently FALSE no match no match no match PASS
equal-scale DECIMAL TRUE match match match enabled on v8
stale/mismatched-scale DECIMAL contract may be TRUE join remains authoritative join remains authoritative join remains authoritative PASS
integer/string raw keys normal SQL equality unchanged unchanged unchanged remains enabled on v6/v7/v8
NULL / NULL NULL no match no match no match NULL removed / conservative
JSON 1 / 1.0 TRUE pending #26432 pending pending pending
VECF32 +0 / -0 TRUE pending #26432 pending pending pending
NaN / NaN join semantics FALSE pending #26432 pending pending only legacy runtime-IN zonemap poisoning addressed

The regular planner still restricts remote shuffle join keys to its existing type set. This PR does not silently enable remote FLOAT shuffle.

Test plan

The regression is small, deterministic operator execution. It does not require large BVT data or an embedded-cluster SQL fixture.

Resident / initial spill / re-spill

  • Use the real scalar evaluator as the oracle.
  • Run the same mixed-scale FLOAT32 inputs through all three physical modes.
  • Low memory thresholds force spill with 257 build rows and one probe row.
  • The true case returns exactly 129 distinct payload rows; the near-but-distinct case returns zero.
  • The test proves the expected spill depths/buckets, row conservation, and zero retained mpool/spill-disk/open-FD state after cleanup.
  • Shared HashJoin/HashBuild/spill paths are exercised directly; existing HashJoin, DedupJoin, and RightDedupJoin spill suites continue to cover the three operators without adding large fixtures.

Runtime-filter correctness and rollout

  • Real planner serialization into real HashBuild for integer, string, float-zero, decimal, and tuple contracts.
  • Real scale-2 probe / scale-3 spec+payload regression proves scalar = is true, old raw IN is false, and the new producer publishes PASS.
  • Legacy/default/unknown markers, forged function layouts, mismatched component order/type, missing payload, and old/new protocol directions all fail open.
  • Safe integer/string v6 plans still publish exact filters.
  • Safe float v8 plans publish both zero bit patterns; scaled float publishes PASS.
  • IndexBuild and FuzzyFilter cover the same validation, allocation-failure, Reset, and terminal-message contracts.

Budget, liveness, and recovery

  • Whole-vector varlen dead-area admission is rejected before destination allocation.
  • Wire payload, allocator size class, scratch, retained capacities, and reallocation overlap return to zero.
  • Unsafe post-Dedup rewrite cannot re-spill; safe pre-rewrite admission can re-spill and conserves all rows.
  • Terminal and cancellation paths cannot hang consumers or publish duplicate terminal messages.

NaN compatibility

  • [NaN, 7] and [7, NaN] build [7, 7].
  • all-NaN remains uninitialized.
  • legacy NaN-poisoned bounds fail open for runtime IN.
  • ordinary zonemaps still prune precisely with sorted lists containing NaN and ordinary keys.

Local validation after merging latest main

All tests use .agents/skills/mo-dev/scripts/mo-cgo-test.

  • Full related matrix passed for hashmap/keycodec/malloc/types/vector/zonemap/readutil; runtimefilter/hashbuild/indexbuild/fuzzyfilter/spillutil; HashJoin/DedupJoin/RightDedupJoin; plan/function/explain/compile/frontend.
  • Targeted -race passed for runtimefilter, HashBuild, IndexBuild, FuzzyFilter, and spillutil.
  • Eleven high-risk stale-plan/budget/re-spill/NaN/protocol regressions passed with -count=10.
  • Proto bindings were regenerated from the merged definitions. Main's gap_fill_mode=75 is preserved and the not-yet-released fuzzy_build_side moved to 76.
  • Existing optimizer BVT changes are plan-golden updates only; no large-data BVT was added.

Performance

No measurable non-spill regression was found.

Alternating precompiled A/B runs used one core, five paired one-second samples, and compared the same workloads before/after the runtime-filter/budget changes:

Non-spill path baseline candidate paired median
cached integer build 4,954 ns/op 4,921 ns/op -0.02%
cached string build 8,996 ns/op 9,106 ns/op +0.88%
cold integer build 10,164 ns/op 10,110 ns/op -0.03%
cold string build 24,232 ns/op 24,366 ns/op +0.38%

bytes/op and allocs/op were exactly unchanged:

  • cached: 560 B/op, 8 allocs/op
  • cold integer: 10,376 B/op, 24 allocs/op
  • cold string: 24,152 B/op, 539 allocs/op

Float zonemap update at 10k rows measured +0.53% for FLOAT32 and -1.27% for FLOAT64, with unchanged allocation; both are within observed noise.

Why the hot path remains stable:

  • integer/string row loops do not execute float normalization;
  • contract checks run once per planned/built filter, not per probe row;
  • safe float zero closure scans the already-unique optional payload once;
  • unsafe/legacy filters stop before collecting, sorting, or serializing optional keys;
  • no-growth retained-vector checks return before scanning batches.

The intentional tradeoff is pruning, not join execution: scaled FLOAT32 or an unprovable stale contract may scan more rows because the optional exact filter publishes PASS. Correct matches are preserved, and safe float/integer/string filters remain enabled.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner July 30, 2026 20:51
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Jul 30, 2026
@mergify mergify Bot added kind/bug Something isn't working kind/enhancement kind/test-ci kind/refactor Code refactor labels Jul 30, 2026
@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Jul 30, 2026
@XuPeng-SH
XuPeng-SH requested a review from a user July 30, 2026 23:10
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Final first-principles follow-up at f934a5b.

Design / scope

  • Spill is a rare cold path and its files are ephemeral. This update adds no compatibility layer for temporary spill files or in-memory spill state. Existing compatibility remains only at real cross-CN planner/wire boundaries.
  • The resident HashBuild now decides to spill before retaining the threshold-crossing batch. It does not preflight or reserve speculative scatter scratch on the normal non-spill path.
  • Rebuild recovery headroom is admitted only after a spill has already occurred. A bounded one-batch scatter floor is held across map-build commit so shared-CN contention cannot create a release/reacquire TOCTOU; it is released idempotently on success and every failure path.
  • Error fidelity is unchanged and explicit: only typed capacity Admission may enter spill/re-spill recovery. Closed, Invalid, cancellation, lifecycle, and accounting failures remain terminal. A best-effort scratch-floor admission miss is counted but does not turn an otherwise valid resident rebuild into an internal failure.
  • Recursion is bounded by 32 buckets, 3 spill passes, and a 1024-entry queue. Skew/no-progress and exhausted recovery headroom return controlled errors rather than growing without bound.

Correctness and unhappy paths

  • A deterministic 12 MiB-cap regression proved the previous intermediate head 8f5ea4b failed while rebuilding three full wide records: requested=5144844 used=7831552 cap=12582912. The final head re-spills and succeeds.
  • The regression checks the exact ownership partition: retained, pending, and unread are disjoint and their union contains every unique key exactly once. It also verifies result rows, memory reservation, disk tokens, spill FDs, and mpool all return to zero.
  • Added coverage includes pre-copy threshold recovery, retained-copy admission recovery, map admission recovery, Dedup safe/unsafe paths, partial-tail accounting, builder full/partial MemSize, scratch-floor best-effort rejection, fatal lifecycle-error preservation, and idempotent cleanup.
  • New metrics distinguish scratch floor reserve/reject/grow, pre-copy/copy/map re-spill attempts, and floor bytes. Terminal memory errors include resource, requested/used/limit, and actionable operator guidance.

Non-spill cost

  • The f934 rebuild-floor change performs zero work on a normal resident join because it is confined to SpillEngine.RebuildHashmap.
  • The PR-wide hard-budget path still has small O(1) accounting and synchronization cost; it is not claimed to be literally free. Serialized alternating A/B measurements found no material regression: INT64 +0.28 percent (noise), VARCHAR -2.37 percent, and 2 fewer allocations/op.

Real MatrixOne harness on 10.222.1.55

  • Exact binary SHA256: 2078a59d480c07458d80da259a6326ccf642e5bca8f886ac1af55e8c1e957dc6, built from f934a5b.
  • Isolated Docker container: 4 GiB memory, no swap, 4 CPUs. Build side was 1.6 million rows x 4000-byte payload = 6.4 GB logical data; probe side was 500,000 rows.
  • Automatic mode, join_spill_mem=0: PASS in 48 s. Exact oracle was 500000 / 500000 / 0 / 125000250000 / 2000000000. Peak live deleted spill state was 32 FDs and 6,452,002,816 bytes; it returned to zero. Container stayed healthy, OOM=false.
  • Forced 32 MiB threshold: PASS in 55 s with the identical oracle. Peak sampled spill state was 32 FDs and 6,394,105,408 bytes; it returned to zero. Container stayed healthy, OOM=false.
  • Automatic run metrics observed spill depth 1 once and re-spill depth 2 thirty-two times. Cumulative disk reserve/release matched at 12,931,003,530 bytes and FD reserve/release matched at 2,112.
  • No-spill negative control used a non-shuffle expression join and a 1 TiB spill threshold. EXPLAIN contained no shuffle. It created zero spill files and was rejected safely in 1 s by the 214,748,364-byte hard memory budget, with requested=33,357,824 and used=199,753,728. The returned ResourceExhausted message tells the operator to reduce build width/concurrency, increase processLimitationSize, or lower join_spill_mem for an eligible shuffle join. The service remained healthy and oom_kill stayed zero. We did not bypass the product guard merely to manufacture a kernel OOM.

Validation / review state

  • Final spillutil package passes with race; fresh hashbuild, hashjoin, dedupjoin, and rightdedupjoin packages pass; targeted go vet and make build pass; diff checks are clean.
  • Both existing inline review threads are resolved. CI has restarted for this new semantic head and is not being claimed green yet.

@aunjgr @gouhongshen @heni02 @aptend @LeftHandCold please re-review the complete final head.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Conflict resolution pushed at 19dbe7f, merging current main ecc389d.

The real semantic conflict was protocol allocation, not just generated-code text: main now owns v7 for structured CHECK constraints, while this PR had previously allocated v7 to the exact runtime-filter contract. The resolution preserves main v7, assigns the exact runtime-filter contract to v8, and makes MORPCLatestVersion v8. All exact-filter gates/tests moved to v8; CHECK remains gated at v7.

I also strengthened the boundary regression: a CHECK-capable v7 service must still suppress metadata-dependent exact runtime filters, while v8 enables them; lowering v8 back to v7 suppresses them again and invalidates cached/prepared plans.

Both conflicting generated files were regenerated from the cleanly merged proto sources. The result simultaneously preserves upstream CheckDef.origin_sql and removed-field reservations for SOURCE_SCAN, stream_scan, and SHOW_CONNECTORS, plus this PR's FuzzyFilter runtime-filter field, RuntimeFilterSpec tags 7-10, and FuzzyBuildSide tag 76. No removed source/stream operator symbol remains.

Per request, I did not rerun the heavy spill harness, race suite, or full packages. The spill admission/re-spill/cleanup implementation is unchanged from f934a5b. Lightweight targeted checks passed:

  • protocol constants and plan/pipeline protobuf package compilation
  • v7-disabled / v8-enabled exact runtime-filter planner cases
  • upstream CHECK-v7 contract
  • frontend session-plan and prepared-plan v7-to-v8 / v8-to-v7 invalidation
  • FuzzyFilter and HashBuild protobuf roundtrips
  • append-only IN overload and function wire IDs
  • diff checks, conflict-marker scan, and generated-code determinism

GitHub now reports the PR MERGEABLE; it is BLOCKED only by the restarted checks/reviews, not by conflicts.

@aunjgr @gouhongshen @heni02 @aptend @LeftHandCold please re-review the conflict-resolution head.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Deep re-review completed at 19dbe7f. APPROVED; no production-reachable blocking findings.

The latest spill changes preserve row conservation and ownership across the resident-to-spill transition and recursive rebuild: the threshold-crossing input is spilled before retention, retained/pending/unread batches are consumed exactly once, and map-admission recovery is allowed only while HashmapBuilder proves that Dedup has not destructively rewritten its input. Scratch, memory, spill-disk, FD, expression, file, and JoinMap ownership all terminate on success, cancellation, error, Reset/Free, and re-spill paths; recursion and queue growth remain bounded. The resident path adds only constant-time threshold/accounting work and does not pre-admit spill scratch.

The merge with current main also resolves the real protocol collision correctly: structured CHECK remains on MORPC v7, the versioned exact runtime-filter contract advances to v8, all production planner gates use v8, and v7 rollback fails open. Protobuf tags are append-only and preserve both main and PR fields/removals; plan/prepared-plan cache invalidation covers v7 to v8 and v8 to v7.

Focused low-concurrency tests passed for the three new HashBuild threshold/lazy-admission cases, eight rebuild/re-spill headroom, conservation, lifecycle, and Dedup safety cases, and the v7/v8 runtime-filter planner boundary. git diff --check is clean. Current-head CI has no reported failure; UT, coverage, SCA, BVT, and connector jobs are still running and remain merge gates.

Keep speculative spill sizing and reservation off the resident hash-build path. Admit actual scratch lazily when spill starts, expose scratch diagnostics, and convert terminal budget admissions into actionable resource errors without changing internal recovery control flow.
Avoid telling users to make a join spill-eligible when an eligible shuffle join can still reject an oversized per-batch scratch request. Point to build width, query memory, the process limit, and the actual eligibility boundary.
Apply the existing spill threshold to retained state plus the current input before copying it. This preserves lazy scratch admission and the resident fast path while keeping enough budget headroom for autonomous spill recovery.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants