Skip to content

fix(compile): preserve JOIN and scan ownership on remote indexed updates (4.2-dev) - #33155

Merged
mergify[bot] merged 8 commits into
matrixorigin:4.2-devfrom
LeftHandCold:fix/4.2-dev-33150-join-locality
Nov 25, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:4.2-devfrom
LeftHandCold:fix/4.2-dev-33150-join-locality

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Fixes #33150. Branch-adapted backport of the applicable execution-placement fixes from #29452 (main merge a97f9c940bba).

What this PR does / why we need it:

A SINK_SCAN reads a process-local producer register; a hash join consumes a process-local JoinMap. Nesting these under a sole remote probe does not transport those dependencies. On a synchronous indexed UPDATE the remote hash build can end up waiting on a register for which no producer was shipped. Increasing a timeout does not create that producer.

Keep the owner of local-only operators; when the inputs cross the ownership boundary, transfer batches through the normal merge/connector before constructing the JOIN. A remotely eligible scan can remain remote. No timeout, JoinMap cleanup behavior, index format or transaction semantics are changed.

When the coordinator is one of several probe CNs, it can host either a SINK_SCAN or a WINDOW build. It broadcasts the resulting batches through the existing receivers, and each peer probes with its own HashBuild and JoinMap. A topology without a coordinator host, a forced-single join, and a shuffle involving WINDOW retain their coordinator fallback.

Backport boundary

The numeric-CAST string-domain inference and physical ASOF build-left entry points from the upstream change do not exist on this branch. Do not introduce those main-only features to backport their guards.

The updated 4.2 base includes #33169, the backport of the singleton reader fix from #27796 for #27755. With the JOIN placement fix alone, a one-remote-worker UPDATE could commit the new base row and full-text postings but leave zero IVF entries for that PK. The physical index failure was independently observed from both CNs after a writer-commit fence. The write uses the current IVF version and centroids; when those source rows were still in memory a singleton remote block reader silently skipped them. Flushing just those sources changed this control from FAIL to PASS. This is why the companion reader fix is needed here; flushing production tables is not the fix.

The singleton remote worker now uses the relation it opened at the statement snapshot to read the complete input. Distributed remote workers retain the persisted-block reader and its original partitioning. The branch's account context, membership filters and cancellation path are preserved.

Validation

  • Compiler/wire control: old 4.2-dev fails the three misplaced-owner cases; local parallelism and legal remote transport are controls, not things to disable. Check forced single-probe and WINDOW placement as well as empty input and cancellation.
  • Public SQL: an isolated two-CN MO cluster, one eligible peer, query_max_workers=1, synchronous full-text + IVFFLAT indexes. Check the actual peer for the windowed reads, selected remote worker and index operations for UPDATE, and the ordinary control on the coordinator. Exercise zero matches, ROLLBACK, then COMMIT. Fence both observers at the writer commit timestamp and independently check base text/vector, physical IVF entry count and stored vector, and old/new full-text postings.
  • Negative/positive controls: the base remote indexed UPDATE times out on empty input; JOIN-only returns, but the committed PK has 0 matching physical IVF rows on both observers. Flushing just the metadata and centroids hides the reader defect. The committed regression instead deliberately leaves these two tables unflushed. A separate one-row table also checks the same remote SELECT before and after its own flush.
  • Review regression: With the exact d227e96 production files and the final regression tests, the coordinator-first, coordinator-last, and mixed-source build cases all lost the peer join (1 probe stage instead of 2). All three pass on 69e6e21. The tests round-trip the peer pipeline, verify its HashJoin and colocated HashBuild, matching JoinMap tag and remote receiver UUID/address, and verify the original producer register. No-host and forced-single controls still gather safely.
  • Standalone (69e6e21, Linux/amd64, Go 1.26.4): full compiler package passed (34.408s); four focused compiler controls including all 11 placement cases passed five repetitions with -race -short -tags matrixone_test; scoped go vet passed. Isolated two-CN SQL fixture passed (16.68s). The peer read row 42 before and after flush. Both observers saw IVF total/exact 1/1, and old/new full-text postings 1/0 after rollback and 0/1 after commit, with the correct base text and vector.
  • Combined integration, not a PR dependency merge: locally merged exactly 69e6e21 and fix(ivfflat): keep flushed appendable entries on the replay owner (4.2-dev) #33153 at e746fb5 with no conflicts. The IVF replay/wire, JOIN placement, singleton reader and writable-workspace placement regressions passed together; the isolated two-CN public SQL fixture passed again (16.66s). That validation used the explicit-transaction scheduling guard from fix(ivfflat): keep flushed appendable entries on the replay owner (4.2-dev) #33153. The current PR also carries that same scheduling commit, independently of the IVF changes.

These results establish correctness and plan placement, not a production throughput benchmark. The local race result above is targeted, not a full compiler race result.

Follow-up to review 6043625892

The writable workspace belongs to the ingress CN. AP statements after a write now require that owner to be eligible and included in the selected worker set. With a one-worker cap the owner executes the scan. When the owner is draining or excluded by placement, the statement returns an explicit scheduling error. Read-only transactions can still use a sole remote worker. The shared scheduling change comes from commit fa605a7846 of #33153.

On the reviewed head 69e6e2109b, an ordinary unflushed table contained committed key 42. A transaction deleted 42, inserted 43, and a remote SELECT succeeded with key 42. On the revised head, the draining ingress rejects that query with current-cn-draining. The eligible owner returns just key 43. In the WINDOW regression, the reviewed head collapsed three valid two-probe broadcasts to one stage. The revised head retains both JOINs with the coordinator listed first, last, or with a mixed build. The tests also check the coordinator WINDOW, the decoded peer HashJoin/HashBuild and its dispatch registration, and the no-host, forced-single and shuffle cases.

Tested revision: bd998a2ed0 against 4.2 base bb197e5118. The complete compiler, scheduler, and isolated two-CN SQL packages passed. The SQL fixture also checked FULLTEXT postings and physical IVF entries after both rollback and commit.

  • A separate public SQL comparison used two Working CNs and 131,072 probe rows. Both revisions returned 131,072 rows and a sum of 327,680. The executed plan on 69e6e2109b had the WINDOW and hash join on the coordinator and no hash join or hash build on the peer. On bd998a2ed0 the WINDOW stayed on the coordinator, and both CNs had their own hash join and hash build. This checks operator placement; no throughput comparison was made.
  • A three-CN SQL fixture with 8,600,005 rows exercised read-your-writes and downstream materialization. A Working owner with a cap of one or two workers returned the replacement key and all three observers read the correct committed summary. A draining owner received an explicit error on both SELECT and INSERT … SELECT and wrote no summary. Prepared SELECTs passed for both owner states. The first run timed out at a preliminary EXPLAIN ANALYZE scheduling check in the two prepared cases, before executing them. Their successful rerun used EXPLAIN VERBOSE for that preliminary check and executed the prepared queries and materializations against the full dataset.
  • The JOIN placement, compiler workspace, and worker-selection regressions passed three repetitions with -race -short -tags matrixone_test. Scoped go vet passed and incremental lint reported zero issues.

LeftHandCold and others added 2 commits November 24, 2026 17:24
Backport matrixorigin#27796 (52e3079) to 4.2-dev as a prerequisite for matrixorigin#33150. Keep the existing distributed block reader and carry 4.2 cancellation and IVF/fulltext membership context on the singleton relation reader.

Co-authored-by: Cao Kai <[email protected]>
Backport JOIN and WINDOW locality from matrixorigin#29452 (a97f9c9) for matrixorigin#33150. Use existing batch-transfer edges before installing process-local JOIN state. Cover shared SINK_SCAN registers and an actual two-CN fulltext/IVF indexed UPDATE with fenced physical index checks.

Co-authored-by: Cao Kai <[email protected]>
@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 →

@mergify

mergify Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Queue requested — the merge queue status continues in this comment ↓.

The race UT passed all SQL and index assertions but failed when its private cluster cleanup had to acknowledge a HAKeeper Working-state write in three seconds. Start the ingress as draining and verify both heartbeat states instead of changing and restoring them through debug RPCs. Cluster shutdown still owns the fixture.
@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/XL Denotes a PR that changes [1000, 1999] lines label Nov 24, 2026
@XuPeng-SH

XuPeng-SH commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 69e6e2109b7b34a0439616549f91a2c75d0a7d42

Review completed. Read the assessment.

XuPeng-SH pushed a commit that referenced this pull request Nov 24, 2026
#33169)

## What type of PR is this?

- [x] BUG
- [x] Test and CI

## Which issue(s) this PR fixes:

Fixes #33168 on `4.2-dev`.

## What this PR does / why we need it:

An AP scan assigned entirely to one remote CN can miss a committed
insert or count a deleted row. An `INSERT … SELECT` can then commit the
wrong aggregate to another table.

The sole executing CN already opens the relation and collects its full
ranges, including its in-memory data. This change retains that relation
handle on the worker and builds the readers at the transaction snapshot
with all tombstone checks. Remote workers that share a distributed scan
keep using the block reader for their assigned ranges. The single-worker
path retains the account context and serialized membership filters used
by published and index tables.

## Relationship to earlier changes

Main addressed the same reader ownership issue in #27796 for #27755. The
two files in this backport match the corresponding files in #33155 at
`d227e967f2`. A local three-way merge of the two PR heads on base
`9ed1645371` produced exactly the tree of #33155. The JOIN placement
changes remain reviewable there.

## Validation

- Added focused coverage for local, distributed remote and single remote
scans, including decoded remote scopes, the in-memory range marker,
cluster and published table identity, and full-text/IVF membership
filters. On the unmodified base, the decoded single-worker cases fail
because they never call the relation reader.
- The complete `pkg/sql/compile` unit suite passed. Focused reader and
cancellation tests passed three repetitions under the race detector.
Targeted combined-table reader tests, `go vet`, and the repository's
incremental lint also passed.
- On real local MatrixOne services with three CNs and 8,600,005
generated seed rows, the base missed a committed insert in both a
single-remote aggregate and the committed destination table. All three
observers confirmed the wrong total after reaching the writer's commit
timestamp. A baseline delete probe also counted a deleted key.
- On the candidate, the same public SQL with uninstrumented production
code returned 8,600,006 after insert and 8,600,005 after delete, both
before and after a flush. All three CNs read back the correct committed
summaries.
- In an independent two-CN snapshot-isolation case, a held snapshot
continued to return three rows totaling 83 after a different CN
committed changes and after a flush. A fresh snapshot returned four rows
totaling 131. The run also checked rolled-back mutations, empty input
and the pure `COUNT(*)` path. Test-only plan selection and diagnostic
traces confirmed execution on the peer.
- After publication we fetched GitHub's PR head and repeated the
snapshot suite. All 11 scans executed on the intended peer and passed.
Three adjacent SQL regressions (delete/select, remote insert-ignore with
conversion, and distributed DISTINCT) passed. Six reader and
cancellation tests also passed ten shuffled repetitions.
- On published head `453131d68b`, we repeated the large fixture with
three Working CNs, worker cap one, and a real label selector with one
eligible peer. Diagnostic hooks recorded the reader actually built by
each statement. All eight aggregate and materialization scans executed
there. All 12 fenced destination reads and all 12 source primary-key
checks passed.

Repeating that exact labeled configuration against `9ed1645371` selected
the block reader for all eight statements. The aggregate and the
committed summaries on every CN were wrong in three of the four phases.

| State of source | Expected total | Base query and stored summary | PR
query and stored summary |
| --- | ---: | ---: | ---: |
| Insert committed, before flush | 8,600,006 | 8,600,005 | 8,600,006 |
| After insert flush | 8,600,006 | 8,600,006 | 8,600,006 |
| Delete committed, before flush | 8,600,005 | 8,600,006 | 8,600,005 |
| After delete flush | 8,600,005 | 8,600,006 | 8,600,005 |

A separate tiny-table test with forced distributed planning hit
`unexpected operator: Output` during remote-plan encoding on both the
base and the PR. The snapshot tests described above kept the output
operator on the coordinator, traced which peer actually read the table,
and checked each result. This backport applies to future scans.
Previously materialized incorrect summaries need to be recomputed from
the source.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: 69e6e2109b7b34a0439616549f91a2c75d0a7d42

Assessment: request_changes

The coordinator-hosted SINK_SCAN broadcast path reuses the existing dispatch mechanism and resolves the prior placement concern. Two issues remain: the new singleton remote reader can expose rows deleted by the current transaction, and the WINDOW guard unnecessarily gathers a viable distributed broadcast join.

Model: gpt-6.1-terra / max

Session: 01a20de6-4798-7d33-92a8-6fabbca9bb9d · slot 3 · generation 1

  • P1 pkg/sql/compile/scope.go:1819: An explicit transaction deletes a committed but still in-memory row, then runs an AP scan whose sole eligible worker is a different CN.
    Impact: The newly selected relation reader can return the deleted row, violating read-your-writes and potentially feeding it into later DML.
    Evidence: The remote CN creates its own workspace in remoterunServer.go:506-515. The singleton range expansion at scope.go:1004-1018 replaces the coordinator's attached relation data, and the new relation-reader path uses the remote workspace to apply transaction deletes (local_disttae_datasource.go:844-850, 1003-1023). The old block-only reader skipped these in-memory rows; the new reader makes them visible without the coordinator's delete. The PR describes a separate writable-workspace guard, but that guard is not present in this checkout. Preserve the transaction's writes and deletes on the peer, or keep scans with a writable workspace on their owner.

  • P2 pkg/sql/compile/compile.go:4434: A broadcast join has coordinator and peer probe scopes, and its WINDOW build subtree is already hosted on the coordinator.
    Impact: The guard gathers all probe rows to one coordinator join. For a selective join with a small build, the peer sends its entire probe input and loses its local join work.
    Evidence: joinNeedsLocalWindow returns true for any WINDOW subtree whenever an input is off the coordinator. The unchanged broadcast builder at compile.go:4898-4956 can instead attach the WINDOW build to the coordinator probe and dispatch its build batches to a peer HashBuild, as it did on the merge base. Preserve that distributed path when the WINDOW remains on its owner, and gather only when placement would otherwise move the WINDOW across the serialization boundary. This is a source-based placement finding; throughput was not measured.

Validation:

  • Private /tmp and loopback preflight passed: preflight.log and checks/1795536876433622019-3.json.

  • Native prerequisites built from the assigned head, with inputs verified against Git blobs: native-build.log, native-inputs-ledger.json, and checks/1795536956515424061-2.json and checks/1795537028951250633-2.json.

  • The frozen CI snapshot reports successful x86 unit tests and multi-CN BVT on the assigned head.

  • The PR body reports focused race and two-CN SQL validation on the assigned head. The prior review reports a passing two-CN regression for the unchanged singleton-reader code.

Limitations:

  • The user reports that 15 focused race tests and the targeted two-CN SQL regression completed, but matching local logs and receipts were not present in this job's supplied evidence.

  • This review's focused Go attempts timed out before test execution; the transaction probe was interrupted while linking. No result is claimed for those probes.

  • The broad eight-package race suite did not complete; no pass is claimed.

  • The transaction and WINDOW findings are based on source analysis. The targeted counterexamples and a production throughput comparison did not complete.

A remote scan reconstructs the committed snapshot, not the ingress CN's pending writes. Prove membership of the actual owner in the resolved pool and reserve a worker slot for it before enforcing the cap. Fail closed if it cannot participate. Leave read-only and local queries unchanged.

(cherry picked from commit fa605a7)
@XuPeng-SH

XuPeng-SH commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: bd998a2ed0f82abafeb5104c96d6cdd706c498a9

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: bd998a2ed0f82abafeb5104c96d6cdd706c498a9

Assessment: approve

The join fix keeps process-local build inputs on their owner and reuses existing merge and broadcast dispatch; eligible multi-probe broadcasts remain distributed. The workspace constraint closes the prior singleton remote-read issue while preserving existing remote tombstone transport for multi-worker scans. Prior SINK_SCAN, WINDOW, transaction-visibility and PR-heading concerns are addressed. The coordinator fallback for shuffle involving WINDOW retains a conservative execution path and no new long-lived state.

Model: gpt-6.1-terra / max

Session: 01a2110f-4081-7e00-8415-e36a337ad118 · slot 0 · generation 12

Validation:

  • Private /tmp and loopback preflight passed: preflight.log and checks/1795582785127548273-2.json.

  • Full pkg/sql/schedule package passed at the assigned head with -count=1 and the supplied test executor: schedule-test.log and checks/1795582804430332469-2.json.

  • The frozen head's CI snapshot reports successful x86 unit tests and multi-CN BVT. The PR reports passing current-head compiler, scheduler and isolated two-CN SQL packages, focused races, and a three-CN read-your-writes comparison; the reported public SQL cases check rollback/commit and physical indexes.

  • Reviewed the compiler scope/dispatch and scheduler-to-scan/transaction-tombstone paths, all changed tests, linked issue requirements and complete indexed discussion.

Limitations:

  • No matching local author logs or receipts were supplied for the reported compiler, topology, or race checks; their individual executions were not independently reproduced in this review.

  • No production throughput comparison was supplied for the conservative WINDOW shuffle fallback; the author reports plan placement and result comparisons rather than a benchmark.

@mergify mergify Bot added the queued label Nov 25, 2026
@mergify
mergify Bot merged commit 1b41ffa into matrixorigin:4.2-dev Nov 25, 2026
@mergify

mergify Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into 4.2-dev as 1b41ffa at 05:02 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 25 Nov, 05:02 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 05:02 · 1b41ffa · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify mergify Bot removed the queued label Nov 25, 2026
XuPeng-SH pushed a commit that referenced this pull request Nov 25, 2026
…2-dev) (#33153)

## What type of PR is this?

- [x] BUG
- [x] Test and CI

## Which issue(s) this PR fixes

Refs #33149 (`4.2-dev`).

## What this PR does / why we need it

In the 4.2 SQL-based IVF search, an inner entries scan can be *locally
executed* on more than one CN. Only one of those readers owns the
committed in-memory rows. An appendable file and its pre-flush memory
representation must have that **same logical owner** at an identical
logical snapshot. Otherwise opposing CN replay orders produce a
duplicate or an omission, even when each CN's own view is correct.

Do not change how immutable objects are distributed and do not hide the
error with a DISTINCT. No index rebuild, catalog/data migration, or
change to score calculation.

**Upgrade (4.2):** stop the entire cluster (CN, TN, LogService and
proxy), replace all binaries, then restart. Rolling upgrades,
mixed-version service and downgrade are not supported. All workers apply
one rule using the existing scan identity and partition ordinal. No new
pipeline opcode, capability negotiation, legacy fallback, or change to
persisted data is involved.

### IVF validation

- A real appendable snapshot file and two TN logtail replay states model
all four before/after combinations at one logical snapshot. On both the
nested table-function path and the filtered remote-scan path, only the
replay owner returns the committed key, exactly once. A one-CN control
returns it once; 64 immutable ObjectIDs retain their original hash
partitions.
- The planner counterexample deliberately separates the replay partition
from the hash partition for the same ObjectID. It failed on the previous
head and passes with one unconditional ownership rule. Compiled
distributed IVF table functions and entries scans encode as the native
`TableFunction` and `TableScan` operators. The remote codec is identical
to the 4.2-dev base.
- The four-CN frontend SQL test for ordered IVF results and strict
query-pool behavior passed (22.54s). No mixed-version, upgrade
rehearsal, recall or throughput claim.

### 4.2 safeguard: read your own writes on AP scans

A second, independent wrong-result case is covered here without taking
#33155 or the main scheduling refactor. After an explicit transaction
inserts one key and deletes another, a remote-only AP scan can see the
previous committed snapshot. An `INSERT … SELECT` can then successfully
commit the wrong summary. A correct source table and an unchanged total
row count are not sufficient checks.

At execution, only an AP query whose transaction has already written
must include the workspace-owning CN among the eligible workers. If a
worker cap applies, that CN gets a slot; a Draining/Drained, excluded or
out-of-pool owner cannot be silently replaced by a peer. Other workers
can still participate. Read-only transactions keep the existing routing.
AP prepares don't cache a physical pipeline on 4.2; the check runs when
the statement executes. This additional fix does not change JOIN, index
algorithms, storage, or the wire format. It cannot repair previously
materialized results.

On `fa605a784`, the four-CN frontend IVF test passed (17.72s), as did
the full compile and schedule packages, the new scheduling test under
race (100 repetitions), scoped vet and incremental golangci-lint (0
findings).

Two-CN SQL witness (8,600,001 rows, flushed source, no optimizer hint or
forced routing, `query_max_workers=1`): on the original PR head
`42713c6a` the dirty copy committed successfully: both observers saw
source key 43 but persisted summary `(marker=42, old=1, new=0,
total=8600001)`. The identical business oracle failed on that build. On
`fa605a784` the read-only control used the actual remote worker. On the
Draining ingress, both dirty operations failed with
`current-cn-draining`; after committing the previous INSERT/DELETE, two
fresh observers saw source key 43 and no summary row. On the Working
ingress the same transaction and materialization succeeded; both
observers saw key 43 and the exact summary `(marker=43, old=0, new=1,
total=8600001)`. The public SQL witness passed in 17.67s. This is not a
fix for the indexed UPDATE JOIN wait in #33150.

After removing the mixed-version path in `e746fb523`, the same
8,600,001-row public SQL witness passed again (33.84s), including both
post-commit observers. The compile, plan, schedule, engine and readutil
packages, the disttae uncommitted-ownership control, scoped vet and
incremental lint passed on this revision.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — bd998a2e Deployed Nov 25, 2026 by LeftHandCold
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/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants