Skip to content

[4.2-dev] Optimize wide scans for MARK joins under OR - #32608

Merged
XuPeng-SH merged 5 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/issue-32552-42
Nov 12, 2026
Merged

XuPeng-SH merged 5 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/issue-32552-42

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #32552

What this PR does / why we need it:

For a conservative local MARK-join shape, a bounded optional (probe IN keys) OR alternative row guard lets the existing late-materialization reader defer wide columns. The original MARK join, OR filter and lock operator remain authoritative. Empty builds retain the alternative; unsupported, failed or oversized filters fall back to the original plan. No wire or storage format is changed.

The follow-up separates side-effect-free eligibility and lineage checks from final producer/consumer attachment, and omits the guard when conflicting terminal messages are already visible in the same receive batch. Exactly-once complete publication remains a producer requirement; this check cannot detect a message arriving later. The shared exact-filter constructor also resolves planner dependencies lazily at the original short-circuit points, avoiding new allocations and process access for rejected candidates.

Design and review

The reviewed design revision is the versioned design document (SHA-256 3d8e73a63d1e352475c47cb937380b936409be96ac7fa56d55060aa79a888fca). GPT-6.1 Terra/max independently reviewed and approved this exact revision and the subsequent implementation, including ownership, fallback, bounds, protocol gates and the broad-match cost trade-off. The initial design was reviewed locally before the first implementation; this publicly versioned revision and its review were added later and do not independently timestamp that earlier local phase.

The 128-key and 512-byte-per-key bounds cap live key bytes at 64 KiB for the guarded shape, not total peak memory; vector capacity, metadata, serialization and per-worker state add bounded overhead.

Validation

Tested on host 57 at e15d724cf7eee843c60d1d8ef5b4c78aca9015ae, rebased onto 4.2-dev 51c0af67a207f7a30dddb4bc385c3466ae5696de:

  • Full affected hashbuild, table_scan, compile and plan packages under Go 1.27.1 race; real single-CN SQL under race and same-version two-CN SQL. SQL cases cover IN-only/B-only/overlap, NULL and duplicate keys, empty and oversized builds, prepared execution, lock wait and rollback.
  • Conflicting-message, eligibility/lineage and cancellation/producer-failure tests each passed 100 race repetitions. Planner tests compare old and new protocol, missing protocol, incompatible types, nil process and dependency evaluation order; the old PR version fails the new order check while the base and final version pass.
  • The repository-pinned Go 1.26.4, golangci-lint 2.6.2 and molint were used. Golangci reported zero incremental issues. The legacy molint reported the same nine pre-existing findings on a base overlay and this head, with zero new findings.

Performance and limitations

Warm local single-CN measurements used 61k rows with two 512-byte payloads and eight interleaved executions per mode. The representative EXPLAIN in each shape confirmed guard installation; measured SQL differed only in a comment marker. Row counts and the physical operator sequences were checked and matched within each off/on pair (MARK + INDEX). Times include result delivery:

Predicate shape Guard off Guard on
Selective, FOR UPDATE 142.159 ms 2.935 ms
10% alternative matches 149.741 ms 97.685 ms
50% alternative matches 166.913 ms 127.131 ms
100% alternative matches 179.824 ms 179.588 ms

A separate planner microbenchmark on main measured the unsupported scaled-FLOAT32 path at about 4.3 ns / zero allocations on the base, 46 ns / two allocations after the original extraction, and 5.8 ns / zero allocations with the follow-up. A same-binary interleaved comparison of supported cases retained the original allocation counts and had overlapping timing ranges; this is not an end-to-end latency claim.

The independent 4.2 QA report measured a repeatable +22.1% base-to-head regression when the alternative matched every row, with different INDEX-join plans. The reason for that plan difference and full regression remains unresolved; the same-plan samples here do not disprove it or guarantee a general latency bound. Existing estimates do not reliably capture tenant-specific alternative selectivity, so this PR records the trade-off rather than adding an unverified hard gate. A same-version two-CN test is not a live mixed-version upgrade or production workload replay.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 12, 2026 06:43
@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 12, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: b8784a73876a976d3e0c09ffc08768839d5e19c6

Review linked issue or PR description changed before publication; a fresh contextual review is queued.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: b8784a73876a976d3e0c09ffc08768839d5e19c6

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: b8784a73876a976d3e0c09ffc08768839d5e19c6

Assessment: approve

The bounded local guard coherently reuses exact runtime-filter production and late materialization. Its OR-aware consumer preserves alternative matches and existing ownership/fallback semantics. No actionable findings remain.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Completed the 14-file delta and owner/consumer review; verified current source, applicable rules and all four discussion entries.

  • Current audit passed, verifying 14 same-head execution receipts, source/native fingerprints and 69 retained artifacts. Provenance is recorded in evidence-reuse.json.

  • Retained race evidence: all 10 new unit tests and 100 cancellation/failure repetitions passed. Hashbuild, table_scan and plan passed; compile had 847 passes and three failures reproduced identically on the frozen base.

  • Retained one-CN SQL regression passed under race with a fixture-only socket adjustment. The base control confirmed filter input of 16000 rows versus candidate 1.

  • Retained affected-package build/vet, formatting and diff checks passed. Discussion coverage and receipt/log correlations passed final audit.

Limitations:

  • Compile retains three baseline Parquet failures; plan has three existing subcase skips.

  • Execution evidence was reused after exact-input verification. It used Go1.26.6; SQL required a fixture-only short Unix socket.

  • The added Go1.26.4/linter claim matches branch configuration but remains author-reported. Frozen CI remains in progress.

  • Historical QA replay, two-CN execution, production latency and total-process peak memory were not independently validated.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

独立 QA:正确性 / 生命周期 / 性能 / 方案评审

测试版本:base 51c0af67a207f7a30dddb4bc385c3466ae5696de,head b8784a73876a976d3e0c09ffc08768839d5e19c6。

结论:#32552 的 selective wide 目标问题已解决,SELECT 与 FOR UPDATE 均获得约 9.2× 加速;已测正确性和生命周期通过。但不能签署“无副作用”:100% alternative 匹配存在可重复的 +22.1% 回退。

原始问题:修复成立

61,000 行、两个 512B payload、真实单 CN 服务,精确 base/head、AB/BA 交错测量:

指标 Base Head
selective wide SELECT 21.251ms 2.315ms(9.18×)
selective wide FOR UPDATE 21.484ms 2.323ms(9.25×)
executions scan 61,000→61,000 61,000→1
scan InputSize 68.18 MiB 5.82 MiB
scan MemorySize 18.37 MiB 860.72 KiB
INDEX join 85,576→61,000 24,577→1

收益有直接物理资源证据,并非仅客户端计时变化。单次 cold selective FOR UPDATE 为 34.788ms→6.212ms,但单样本不作为稳定比例。

正确性:PASS(已测范围)

  • Base/head 黑盒、head guard race、head hashbuild race 四项最终退出码均为 0。
  • Base/head 共 30 组结果记录无差异。
  • 覆盖 SELECT/FOR UPDATE、IN-only、alternative-only、overlap、NULL/mixed-NULL、重复键、empty build、prepared、128/129 fallback、锁等待、rollback/delete 和并发。
  • 物理证据确认 guard 真正安装:宽投影 Filter 16000→3、empty build 2、128 unique keys 128;129 unique keys 正确回退为 16000。
  • 两组 -race -count=10 均通过,无 DATA RACE。
  • 中间失败均已分类为探针编译/fixture 断言或环境问题并保留日志,未作为产品缺陷;已测范围未发现真实正确性缺陷。

生命周期与故障注入:PASS(已测范围)

已验证 IN/DROP/PASS、payload release、producer failure/retry、empty-build reuse、25 次 blocked-cancel、Reset/reuse、多 terminal-message 边界、重复/超限 keys 和 payload/mpool 释放。

Compile/hashbuild targeted -race -count=3 两包通过。30 秒 cleanup warning 已证明来自独立 probe 对未运行 merge 的额外 Reset,修正探针后即时通过且无 warning,不计为产品缺陷。

未发现可达的等待环、泄漏、double-free 或阻塞合并的生命周期缺陷。核心 ownership/wait-for 边界合理:唯一本地 producer、单 waiter,原 MARK/OR 保持 authoritative,失败/取消/超限 fail-open 到原计划。

性能副作用:broad 回退真实存在

Alternative 匹配 Base median Head median 变化
约 10% 39.450ms 9.052ms -77.1%
约 50% 37.429ms 26.785ms -28.4%
100% 41.769ms 50.985ms +22.1%

100% 匹配时,两端 scan 都是 61,000→61,000,没有减行;base 无 INDEX join,而 head 出现 85,576→61,000 INDEX join,并增加窄列扫描、key map 和 IN 判断。因此回退有明确机制,不是测量噪声。

其他边界:

  • narrow 未安装 guard,基本持平(-1.0%)。
  • 短 payload wide 仍改善 82.1%。
  • binary-protocol prepared FOR UPDATE 未测得收益(-1.4%)。
  • unique keys 128 安装、129 回退;129 个重复输入仍能安装,符合 unique-key 预算定义。
  • oversized alternative fallback 小样本 +7.2%,只能视为可能开销/波动。

所有性能测量两端行数与返回字节一致。

方案与 Clean Code

合理部分:复用既有 exact runtime-filter producer 与 late-materialization;原 MARK join、OR residual 和锁保持 authoritative;本地、单 MARK、单 producer、同 message board、wide projection 等门控保守;empty build 保留 alternative,unsupported/failed/oversized 均回退原计划。

建议:

  1. 当前固定 minRows/wide-type/key 限制不是完整的 alternative-selectivity 成本门控,无法避免 100% 匹配回退。建议补充 broad/selectivity 门控,或明确接受并记录该 trade-off。
  2. 拆分约 166 行的安装函数,分离只读 eligibility/lineage 与最终 mutation。
  3. 将单 producer / exactly-once terminal-message 不变量靠近消费端集中声明或防御。
  4. 澄清 optional 配置、命名和注释,补全组合测试。

最终建议:支持核心优化方向,但不能宣称普遍加速或零副作用。如果验收要求 broad 场景不得回退,当前实现不通过;否则应明确记录并管理 broad trade-off。

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: b8784a73876a976d3e0c09ffc08768839d5e19c6

New discussion was assessed; the previous review remains unchanged.

@XuPeng-SH

XuPeng-SH commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: e15d724cf7eee843c60d1d8ef5b4c78aca9015ae

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: e15d724cf7eee843c60d1d8ef5b4c78aca9015ae

Assessment: approve

The bounded local MARK-under-OR guard preserves the original MARK/filter and coherently reuses exact runtime-filter production and scan late materialization. Complete-key publication, conservative eligibility, row-only placement and existing cleanup owners keep the added state proportionate. The accepted design explicitly records broad-alternative overhead and the unresolved differing-INDEX-plan QA result. No actionable correctness or applicable design-contract finding remains.

Model: gpt-6.1-sol / max

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

Validation:

  • Completed the full 16-file delta, relevant producer/consumer, SQL NULL/locking, wait, ownership, bounds, clone and reuse review. Read all eight chronological discussion entries and linked issue 32552; discussion-assessment.json has exact key coverage.

  • Verified the current design document SHA256 3d8e73a63d1e352475c47cb937380b936409be96ac7fa56d55060aa79a888fca matches the accepted revision identified in the supplied PR evidence.

  • Local check-run isolation preflight passed (checks/1794477871456166285-2.json; preflight.log). Frozen-head, clean-source, complete change-map, diff whitespace, Go formatting, design-hash and discussion-coverage checks passed (checks/1794478171553835005-4.json; static-check.log; reviewed-inputs.json). Receipts and retained logs were reconciled.

  • The supplied PR body reports current-head hashbuild/table_scan/compile/plan race suites, focused 100-repeat cancellation/failure and eligibility tests, one-CN SQL race and same-version two-CN SQL checks. It also reports pinned Go1.26.4 incremental lint and equal-plan interleaved guard-off/on performance experiments. These are author-reported execution evidence, not locally rerun tests.

  • Reconciled old-head review 5871067251 and independent QA: retained their tested behavior and broad-B regression as historical evidence; did not relabel their executions as current-head local passes.

Limitations:

  • No Go package, SQL, race or benchmark execution was independently rerun in this review. This task has no retained local_validation runs or native prerequisites; runtime validation relies on the detailed current-head report in the supplied evidence.

  • Frozen CI remains in progress. Pending and skipped jobs are not treated as passes.

  • The independent QA +22.1% broad-B base/head result used differing INDEX plans and remains unexplained. Reported same-plan guard-on/off results do not disprove it or establish a general production latency/peak-memory bound; bounded broad-B overhead is an explicit accepted tradeoff.

@XuPeng-SH
XuPeng-SH merged commit 6785b4b into matrixorigin:4.2-dev Nov 12, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/issue-32552-42 branch November 12, 2026 12:37
XuPeng-SH added a commit that referenced this pull request Nov 13, 2026
## What type of PR is this?

- [x] Improvement
- [x] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes:

Related to #32552

Related to #28742 (restore regression test deadline ownership)

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

For a conservative local MARK-join shape, a bounded optional `(probe IN
complete_exact_keys) OR alternative` row guard lets the existing
late-materialization reader defer wide columns. The original MARK join,
OR filter, tenant residual and lock operator remain authoritative. Empty
builds retain the alternative; unsupported, failed or oversized filters
use the original plan. No wire or storage format changes.

Eligibility and lineage checks are separate from final producer/consumer
attachment. Conflicting terminal messages already visible in one receive
batch decline the guard; exactly-once complete publication remains a
producer requirement, and later duplicates cannot be detected by that
check. The shared exact-filter constructor resolves planner dependencies
lazily at the original short-circuit points, preserving
rejected-candidate allocations and process-access behavior.

The restore regression also gives its metadata probe the restore
operation's existing deadline. Previously, the probe had its own
120-second deadline while deliberately waiting behind a restore allowed
180 seconds. It now inherits the bounded operation context and retains
separate cancellation. The 180-second operation and 300-second test
budgets, deterministic lock/barrier checks, rollback checks and restored
subscription/privilege assertions remain in place.

### Design and bounds

The [reviewed design
revision](https://github.com/matrixorigin/matrixone/blob/093153760b1eb98f7372ccc364fde27b1d57a2d9/docs/design/20261112-mark-join-scan-guard.md)
has SHA-256
`3d8e73a63d1e352475c47cb937380b936409be96ac7fa56d55060aa79a888fca`.
Initial design review was local before implementation; the public
revision was added later and does not independently timestamp that
earlier phase. GPT-6.1 Terra/max reviewed this revision and the complete
implementation. The follow-up corrects validation wording and has a
separate design and overall review for the deadline correction.

The guard requires proven local independent build ownership, safe direct
column lineage and bounded exact VARCHAR equality. Limits are 128 keys,
512 actual bytes per key, 128 KiB serialized payload and eight scan
workers. The 64 KiB live-key bound excludes vector capacity, metadata,
serialization and per-worker overhead.

### Validation

- Completed CI on feature head `ee530ac9`, based on main `b9c06b27`:
SCA, x86 Coverage, PROXY BVT and pessimistic multi-CN BVT passed. Full
race owning-package runs passed for `hashbuild`, `table_scan`,
`compile`, `plan` and `sqlintegration`.
- The checked-in SQL regression covers IN-only/B-only/overlap, NULL and
duplicate keys, empty/oversized builds, prepared reuse, lock wait and
rollback. It runs on one CN. The author separately reported a
same-version two-CN run and a negative control where removing `FOR
UPDATE` fails the waiter assertion. Those manual runs were not
independently repeated in this follow-up. Producer, eligibility,
conflicting-message and cancellation tests passed in the exact-head race
CI; earlier author evidence also reports bounded repetitions.
Exact-filter tests preserve dependency evaluation order and
protocol/type rejection.
- Deadline repair: the actual two-CN restore root passed under Go
1.27.1, CGO, `-race -short -tags matrixone_test -p=2 -parallel=2`. A
temporary assertion in the real helper distinguishes the old prematurely
shortened probe deadline from the corrected inherited deadline. Existing
context-ownership race tests also cover bounded/unbounded callers,
cancellation and original executor errors.
- Incremental `make static-check-selected` for
`pkg/tests/issues/isolated` passed: repository-pinned molint and
golangci-lint 2.14.0, including govet and formatting, with zero issues.
Unchanged feature static analysis is covered by the completed exact-head
CI.

The [completed full race
UT](https://github.com/matrixorigin/matrixone/actions/runs/43229521162/job/131220915150)
had one failing root:
`TestIssue26640ClusterRestoreRebindsSubscriptionPrivileges`, whose
restore exceeded its 180-second operation deadline. Its trace confirms
the probe expired at 120 seconds while restore still progressed. The
correction addresses that premature probe expiry; it does **not**
establish the cause or resolution of the separate 180-second restore
timeout. Both original and corrected roots pass locally, which does not
reproduce loaded CI. CI for the follow-up commit is pending.

### Performance and limitations

Earlier warm single-CN measurements on `2365d779` used 61k rows, two
512-byte payloads and eight interleaved executions per mode. Guard
installation, result cardinalities and matching physical operator
sequences were checked. Complete-result times were:

| Alternative matches | Guard off | Guard on |
| --- | ---: | ---: |
| Selective, FOR UPDATE | 130.152 ms | 3.528 ms |
| 10% | 136.598 ms | 103.303 ms |
| 50% | 150.281 ms | 137.218 ms |
| 100% | 167.010 ms | 170.117 ms |

These historical samples are not a production latency bound. The
independent [4.2 QA
report](#32608 (comment))
measured a repeatable +22.1% broad-match base/head regression with
different INDEX-join plans. Its cause remains unresolved; same-plan
local comparisons do not disprove it. Existing estimates do not reliably
capture tenant-specific alternative selectivity, so no unverified
selectivity gate is added. The lazy planner follow-up restores zero
allocations for the rejected scaled-FLOAT32 path; no end-to-end gain is
claimed for that extraction. Production workload replay remains
outstanding.

This branch was previously deployed

1 inactive deployment
ci — e15d724c Deployed Nov 12, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement kind/refactor Code refactor size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants