Skip to content

fix(plan): prune correlated composite primary-key points (4.2-dev) - #32371

Merged
XuPeng-SH merged 4 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/issue-32365-composite-points-42
Nov 9, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:4.2-devfrom
XuPeng-SH:codex/issue-32365-composite-points-42

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement

Which issue(s) this PR fixes:

Fixes #32365

What this PR does / why we need it:

For a composite primary key, a shared equality combined with a disjunction of complete, correlated key points previously used only the shared prefix for scanning. For example, tenant = ? AND ((session = ? AND request = ?) OR (session = ? AND request = ?)) read the whole tenant even when only two keys matched.

Derive a bounded set of complete serialized key points from safe conjunctions and disjunctions, retain the original predicates as the authority for SQL semantics, and reuse the existing primary-key reader. Publish the implied filter before index rewrites; if join planning invalidates a deferred candidate, restore the ordinary prefix path. The reader prefers exact points over a prefix only when every point is contained in that prefix.

Collect directly nested OR points without repeatedly copying preceding results. Decide early deferral while collecting composite-key block filters, so a scan that will not be lowered does not deep-copy snapshots that would immediately be discarded. Existing compound filters still retain their required snapshots.

EXPLAIN escapes control or invalid UTF-8 bytes when displaying literal or folded-vector values, including encoded keys copied to a secondary index. The affected existing EXPLAIN result snapshots are updated to match this text representation.

Composite-key lowering also stops at floating-point components: physical encoding distinguishes -0 and +0, while SQL equality does not. The original SQL predicate and any preceding safe key prefix are preserved.

Performance comparison

Compared clean 4.2-dev base 0351bc89, the original PR head 20671cd4, and current head 6e7afae2 on the same AMD Ryzen 9 7900X host, Linux/amd64, Go 1.26.4, GOMAXPROCS=4. Planner results are medians of six interleaved 1-second runs per revision.

BuildPlan workload Clean base Original PR Current PR
50 correlated OR points 423 µs; 506,176 B; 9,871 allocs 602 µs; 923,756 B; 14,064 allocs 485 µs; 619,860 B; 11,510 allocs
Ordinary single key 39.2 µs; 49,425 B; 741 allocs 38.5 µs; 49,425 B; 741 allocs 36.6 µs; 49,425 B; 741 allocs

For the 50-point microbenchmark, the current version reduces planning time by about 19%, allocated bytes by 33%, and allocations by 18% versus the original PR. It still costs about 62 µs and 111 KiB more per plan than clean base. A 50-arm query with an unsupported range residual retained the old fallback, with the same 508,263 B and 9,906 allocations; its local median was 427.5 µs before and 430.8 µs after. An isolated 128-point candidate analysis used 17,032 B versus 272,344 B before; 129 points still fall back.

On 100,001 persisted rows with 50 scattered matching keys, EXPLAIN ANALYZE scan input changed from 100,001 rows and 14 blocks to 50 rows and 13 blocks. Total ReadSize was 2.46 MiB versus 2.43 MiB; the DiskReadSize component was 10.2 KiB versus 1.35 MiB. Ten warm prepared SELECTs took a median 464.7 ms on clean base and 7.35 ms on the current code, across three fresh 1-CN cluster runs per revision. Both returned 50 rows and the prepared UPDATE affected exactly 50. These local samples do not establish a proportional reduction in storage I/O or a production latency guarantee.

Counterexample checks

  • Incomplete OR arms, independent ORs that would require a cross-product, foreign-column equalities, range residuals, and dynamic folded literals use the existing path; original predicates remain intact.
  • A failed or oversized OR alternative cannot contaminate a later candidate. The 128-point and encoded-byte limits have admission/fallback tests, including an underdeclared large literal.
  • Join-derived equalities that invalidate an earlier candidate retain the previous primary-key prefix. Existing compound block filters survive deferral; disabled block filtering, forced/ignored secondary indexes, and IVF INCLUDE are covered.
  • The reader retains its prior fallback when an exact point set only partially overlaps a prefix. Floating-point signed zero, NULL and duplicate points, embedded NUL and oversized parameters, wrong arity, throwing residual predicates, and transaction rollback were challenged.

Validation

  • Full pkg/sql/plan tests, normal and -race; existing normal/race evidence for the unchanged explain and reader packages remains applicable.
  • Shared-cluster binary prepared-statement test, normal and -race, including actual two-point and 50-point scan-row assertions, parameter reuse, errors, rollback, and CASE updates.
  • Optimizer SQL BVT: 49/49. The CI failure was reproduced as three stale raw-byte EXPLAIN expectations in blockfilter.test. After refreshing the affected snapshots, blockfilter.test (55/55), explain_index.sql (69/69), and secondary_index_range.sql (171/171) each passed twice on the same isolated instance, with database teardown checked after each run.
  • Offline replay using the CI coverage parser, historical profiles for unchanged files, and local planner UT coverage for changed files estimated changed-code coverage at 86.1% against the 75% threshold. The official coverage job must still run on the new head.
  • Formatting, scoped vet, pinned diff lint, and license checks passed; molint reported only the same three diagnostics as clean base.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 8, 2026 14:22
@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 →

@XuPeng-SH

XuPeng-SH commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 20671cd40898b307b63d338f9fcbaf7cf593882f

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

@XuPeng-SH XuPeng-SH changed the title fix(plan): prune correlated composite primary-key points fix(plan): prune correlated composite primary-key points (4.2-dev) Nov 8, 2026
@XuPeng-SH

XuPeng-SH commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 20671cd40898b307b63d338f9fcbaf7cf593882f

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: 20671cd40898b307b63d338f9fcbaf7cf593882f

Assessment: approve

Bounded point derivation reuses existing serialization, index and reader owners with safe fallback. The reported planning overhead is justified by the scoped execution gains. No actionable findings remain.

Model: gpt-6.1-sol / max

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

Validation:

  • Verified complete 14-file coverage against identical frozen inputs; assessed all three current discussion entries and linked issue.

  • Current preflight and source, formatting, discussion and evidence-identity audit passed; receipts and logs are reconciled in validation-ledger.json.

  • Reused matching logical-core and formatter tests; assessed author-reported normal/race suites, 49/49 optimizer BVT and updated performance comparisons.

Limitations:

  • Full application/BVT execution was not independently repeated; native prerequisites and raw author logs were unavailable.

  • Reused model tests exclude production guards, encoding and SQL integration.

  • Four CI checks remain pending. Planning overhead and execution gains are workload-specific; storage-I/O improvement is not established.

@XuPeng-SH

XuPeng-SH commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 6e7afae2ae59e86733fc2957db1ae7ec8689ad9e

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: 6e7afae2ae59e86733fc2957db1ae7ec8689ad9e

Assessment: approve

Bounded point derivation reuses existing serialization, index and reader owners with conservative fallback. Phase-local deferral, linear OR collection and float guards preserve SQL semantics; the reported scoped execution gains justify the remaining planning cost. No actionable findings remain.

Model: gpt-6.1-sol / max

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

Validation:

  • Reviewed all 17 changed files, affected owners and consumers, linked issue and five discussion items; assessment records are retained.

  • Isolation preflight and frozen-source native prerequisite build passed.

  • Source-derived collector and formatter probes passed: 2949 admitted candidates, 238869 row valuations, boundary controls and byte escaping. All three snapshot oracles passed.

  • Static audit passed for frozen inputs, clean source, formatting, 49 SQL/result statement echoes, discussion coverage and artifact provenance. Receipts and logs are reconciled in validation-ledger.json.

  • Assessed current author-reported normal/race tests, SQL BVT runs and controlled performance comparisons.

Limitations:

  • Production package tests timed out during Go module downloads before selected tests executed. Full application/BVT execution was not independently repeated; raw author logs were unavailable.

  • Standalone collector probes exclude production admission guards, physical encoding, reader and SQL integration.

  • Four CI checks remain pending. Performance results are workload-specific and do not establish reduced storage I/O.

XuPeng-SH added a commit that referenced this pull request Nov 9, 2026
## What type of PR is this?

- [x] BUG
- [x] Improvement

## Which issue(s) this PR fixes:

issue #32365

Related 4.2-dev implementation: #32371.

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

A predicate like `tenant = ? AND ((session = ? AND request = ?) OR ...)`
describes a small set of complete composite primary keys, but previously
scanned the entire tenant prefix. Derive a bounded set of correlated
keys as a necessary scan filter and retain the full original predicates.

- Reuse existing composite-key encoding, index and join selection, and
reader filtering. Publish points only if the same scan, key, snapshot
and predicate witnesses survive the existing rewrites. Unsafe
comparisons or residuals, unsupported shapes, and exhausted query-wide
admission budgets keep the existing access path.
- Defer execution-value inspection until a point candidate actually
survives access selection. This preserves the existing prepared-plan
cache for index plans that discard the candidate; surviving or
value-dependently rejected candidates use the existing value-dependent
replanning policy. A reused ordinary plan can miss an optimization that
a fresh plan might find; it remains correct under the existing cache
policy.
- Avoid temporary numeric-prefix bookkeeping for functions that the
existing shared binder already rejects, without bypassing their normal
conversions or diagnostics. Prefer exact point membership over a
compatible prefix in the existing reader; redact serialized key lists in
text EXPLAIN.

The [versioned
design](https://github.com/XuPeng-SH/matrixone/blob/bb859e839fd1d4c8ec5ba7d5ce136daba9503aa4/docs/design/20261109-correlated-composite-primary-key-points.md)
covers ownership, cache semantics, bounded resource charges,
cancellation and performance. Its amended revision received an
independent `gpt-6.1-terra` / `max` design PASS (session
`01a1bc7a-177e-7950-b176-bd33aabe982f`). The original implementation
preceded the versioned document; the deferred-admission correction was
designed and approved before implementation.

### Validation

- Full planner package normal and race tests; existing full
`plan/explain` and `readutil` normal/race results remain applicable to
their unchanged code. Focused frontend cache/retry and binary prepared
SELECT/UPDATE tests under race, including index cache reuse,
large/small/NULL rebinding, error/warning and rollback controls.
- Two runs each on the same isolated instance: composite-point BVT 64/64
and existing block-filter BVT 56/56. Existing prepared numeric and
warning BVT 299/299; SQL and binary common-value tests include numeric
overflow.
- Incremental `gofmt`, `go vet`, repository-pinned `molint` and
`golangci-lint` for the changed packages and affected consumers, license
headers, and `git diff --check`.

### Local performance

On a Ryzen 9 7900X with Go 1.27.1, one local CN and a persisted
100,001-row table, three fresh-cluster samples of ten warmed
binary-prepared COUNT executions over 50 scattered keys had medians of
**615.7 ms on the main baseline and 78.2 ms with this change**. Scan
input was 100,001 versus 50 rows; blocks touched were 14 versus 13. The
two-point case read two rows, and binary SELECT and UPDATE returned or
changed the expected rows. These separate local batches are
illustrative, not a general latency guarantee or evidence of
proportional block-I/O savings.

The planning work is not free. In three paired local microbenchmark
samples, 50-point planning went from **1.27 to 1.53 ms**, **831 KB to
1,038 KB**, and **16,209 to 18,096 allocations** per plan;
value-dependent point plans are replanned. The shared numeric-prefix
change reduced the updated 50-point case by 22.4 KB and 400 allocations
compared with the same deferred-admission code before that change; these
short timing samples do not establish a CPU speedup from that particular
reduction.

---------

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

This branch was successfully deployed

No deployments
ci — a0ae768e Deployed Nov 9, 2026 by XuPeng-SH
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 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