Skip to content

perf(plan): cut proto text marshalling from filter rewrite; normalize filter domain before composite-key folding - #24261

Merged
4 commits merged into
matrixorigin:3.0-devfrom
ck89119:bigsql-perf-fix
Apr 30, 2026
Merged

4 commits merged into
matrixorigin:3.0-devfrom
ck89119:bigsql-perf-fix

Conversation

@ck89119

@ck89119 ck89119 commented Apr 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:

issue #24227

What this PR does / why we need it:

Two independent changes on top of #24229:

1. perf(plan): avoid proto text marshalling in hot paths

Large IN/OR queries (e.g. an outer IN with ~450 varchar values
combined with a nested cast(col AS BIGINT) IN/NOT IN list of
similar size) were spending ~95% CPU in
proto.(*TextMarshaler).writeStruct, driven by Expr.String()
being used as a map key inside applyDistributivity and inside
constLiteralKey (PR #24229). Both paths reflected over the full
expression tree on every call.

  • applyDistributivity now uses a structural FNV-64 hash
    (exprStructuralHash) over the Expr's ColRef / Literal /
    Function / List shapes, and falls back to a structural equality
    check only on hash collision. Right conjuncts are bucketed once
    so the left scan performs a single hash per cond.
  • constLiteralKey packs the literal's proto binary form plus
    the Type fields directly into the key, avoiding the
    TextMarshaler in the per-literal hot loop of the domain
    rewrite.

Measured on a BPC-style reproducer (MatrixOne container cluster, 10-core host, 19.5M-row scan):

Version Query latency (steady) CPU top
baseline (pre-PR) 2.7 - 2.9 s proto.TextMarshaler 96%
after Marshal-as-key 2.9 - 3.2 s proto.ProtoSize 56%
this PR (structural hash + constLiteralKey fix) 0.52 s doPrefixIn / mallocgc / scanobject (real work)

2. fix(plan): normalize filter domains before composite-key folding

optimizeFilters used to run mergeFiltersOnCompositeKey before
rewriteInDomainNotInFilters. When the outer IN sits on the first
column of a composite primary key, the composite-key pass folds
that IN into prefix_in(__mo_cpkey_col) and the IN disappears
from the scan's FilterList. The domain normalizer then has no
outer IN to propagate, so nested NOT IN / <> / cast(col)
conjuncts (typically introduced by the binder when a varchar PK is
compared against an integer list) survive unrewritten. This
reproduces on BPC-style reports where the same column appears as
both an outer varchar IN and an inner cast(col AS BIGINT)
IN/NOT IN list — the exact scenario that motivated PR #24229.

Swapping the order lets the domain rewrite run against the
still-bare IN, collapse matching conjuncts into a single IN /
FALSE / equality, and only then hand the narrowed IN to the
composite-key folder (which gets a smaller point set for the
prefix_in seek).

The existing in_domain BVT cases on int primary keys now report
a single collapsed IN where they used to show two conjuncts; the
expected output is updated accordingly. Behavior on non-PK tables
is identical to before.

Test plan

  • UT: go test ./pkg/sql/plan/ -run TestRewriteInDomain -count=1 — 29/29 pass
  • BVT: optimizer/in_domain — 36/36 pass
  • make && make static-check clean
  • End-to-end check with the BPC reproducer — correct result, ~5× latency improvement, pprof top now shows real data-path work

ck89119 and others added 2 commits April 30, 2026 15:27
Large IN/OR queries (e.g. outer IN of 400+ values + nested
NOT IN/<> list) were spending ~95% CPU in
proto.(*TextMarshaler).writeStruct, driven by Expr.String() being
used as a map key in applyDistributivity and as part of
constLiteralKey in the domain rewriter. Both paths reflected over
the full expression tree on every call.

- Replace the String()-based map key in applyDistributivity with a
  structural FNV-64 hash over the expr's ColRef / Literal /
  Function / List shapes, and fall back to a structural equality
  check on collision. Right conjuncts are bucketed once so the
  left scan performs a single hash per cond.
- constLiteralKey now packs the literal's proto binary form plus
  the Type fields directly into the key, avoiding the
  TextMarshaler in the per-literal hot loop of the domain rewrite.

On the reproducer (BPC-style query, ~450-entry outer IN + nested
cast IN/NOT IN), end-to-end latency drops from 2.7s to 0.52s and
the pprof top goes from "TextMarshaler 96%" to "scan / prefix_in /
mallocgc" — i.e. real work.

Fixes: matrixorigin#24227

Co-Authored-By: Claude Opus 4.7 <[email protected]>
optimizeFilters used to run mergeFiltersOnCompositeKey before
rewriteInDomainNotInFilters. When the outer IN sits on a composite
primary key's first column, the composite-key pass folds it into
prefix_in(__mo_cpkey_col) and the IN disappears from the scan's
FilterList. The domain normalizer then has no outer IN to
propagate, so nested NOT IN / <> / cast(col) (typically from a
varchar PK compared against an integer list after the binder's
IN expansion) survive unrewritten. This reproduces on BPC-style
reports where the same column appears as an outer varchar IN and
as an inner cast(col AS BIGINT) IN/NOT IN list.

Swapping the order lets the domain rewrite run against the
still-bare IN, collapse matching conjuncts into a single IN /
FALSE / equality, and only then hands the narrowed IN to the
composite-key folder (which now gets a smaller point set for the
prefix_in seek).

The existing in_domain BVT cases on int primary keys now report
a single collapsed IN where they used to show two conjuncts; the
expected output is updated accordingly. Behavior on non-PK tables
is identical to before.

Fixes: matrixorigin#24227

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@ck89119
ck89119 requested a review from a user April 30, 2026 07:30
@qodo-code-review

Copy link
Copy Markdown
ⓘ You've reached your Qodo monthly free-tier limit. Reviews pause until next month — upgrade your plan to continue now, or link your paid account if you already have one.

@Ariznawlll

Copy link
Copy Markdown
Collaborator

/auto-test-pr

@Ariznawlll

Copy link
Copy Markdown
Collaborator

PR #24261 测试覆盖分析

变更摘要

本 PR 针对 SQL 计划优化器(pkg/sql/plan/)的性能瓶颈进行了修复和优化,主要包括:

  1. 在 filter rewrite/composite-key folding 等热路径中,避免 proto text marshalling,改用结构化 FNV-64 hash 和结构化等价性判定,提升大规模 IN/OR 查询的 CPU 性能。
  2. 优化 filter domain 的归一化处理,减少重复表达式判定的开销。
    涉及文件包括:expr_hash.go(新增)、expr_opt.go、opt_misc.go、utils.go,以及 BVT 测试结果文件 test/distributed/cases/optimizer/in_domain.result。

6 类测试覆盖情况

测试类型 覆盖状态 说明
BVT ✅ 已有 optimizer 相关 BVT case(in_domain.result 被更新),覆盖 filter rewrite/IN/OR 优化场景。
稳定性 ⚠️ 涉及复杂 filter rewrite 和大规模 IN/OR 查询,需在 TPCH 等长时间运行场景验证无性能回退或稳定性问题。
Chaos ➖ 仅计划层优化,无故障注入相关影响。
大数据 ⚠️ 涉及大规模 IN/OR 查询、filter rewrite,需补充大数据量下的查询计划选择和性能验证(如 1亿行表上复杂 IN/OR 查询)。
PITR ➖ 与备份恢复无关。
Snapshot ➖ 与快照功能无关。

图例: ✅ 已覆盖 ⚠️ 需补充 ➖ 不相关

建议

  • 稳定性测试:建议在 TPCH、Sysbench 等场景下,增加包含大规模 IN/OR 条件的 SQL,验证 filter rewrite 优化后长时间运行的性能和稳定性。

    • 示例 SQL:
      SELECT * FROM lineitem WHERE l_orderkey IN (10001,10002,...,10450) OR l_partkey IN (20001,20002,...,20450);
      (可用脚本生成大批量 IN 条件)
  • 大数据测试:建议在 mo-nightly-regression 的 big_data 分支补充大数据量下的复杂 filter rewrite 场景,针对 1亿行以上表,构造大批量 IN/OR 查询,验证计划优化和性能。

    • 示例 SQL:
      -- tools/mo-regression-test/cases/tpch_10g/q_in_or.sql
      SELECT * FROM lineitem WHERE l_orderkey IN (1000001,1000002,...,1000450) OR l_partkey IN (2000001,2000002,...,2000450);
  • BVT 已覆盖,无需补充。

🤖 自动生成的测试 PR

✅ 稳定性 PR 已提交:https://github.com/Ariznawlll/mo-nightly-regression/pull/6
✅ 大数据 PR 已提交:https://github.com/Ariznawlll/mo-nightly-regression/pull/7


由 AI Test Analyzer 自动生成 · workflow run

…composite-pk cast

Addresses two review items on the filter-rewrite stack:

1. exprStructuralHash / exprStructuralEqual used to only consider
   Function.Func.ObjName. Two distinct ObjectRef identities
   (different schema / obj id / overload) sharing a name would
   hash and compare equal, letting applyDistributivity factor them
   as a common subexpression. Feed the full ObjectRef proto bytes
   into the hash and compare ObjectRef byte-for-byte on equality,
   restoring the invariant the old String()-as-key path had. A
   regression test (TestExprStructuralHashDistinguishesObjectRef)
   locks this down.

2. The existing BVT cases covered only single-column int primary
   keys. The motivating composite-varchar-pk scenario (outer
   varchar IN + inner cast(col AS BIGINT) IN / NOT IN) had no
   checked-in case exercising the full optimizeFilters pipeline.
   Add an in_domain.test case over a composite varchar PK that
   asserts both the result rows and that the scan filter collapses
   into prefix_in / prefix_eq — confirming the order-swap
   rewrite-then-fold path keeps working end-to-end.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Apr 30, 2026
Extend expr_hash_test.go with coverage for paths the first UT didn't
reach:
- every Literal variant enumerated by hashLitInto / literalEqual
  (i8/i16/i32/u8/u16/u32/double/fval/date/time/datetime/timestamp/
  enum/jsonval/defaultval/updateval/vecval), plus cross-variant
  inequality (i64 vs u64)
- null literal vs non-null, nil expr arguments
- column relpos / colpos distinctness and column-vs-literal kind
  mismatch
- Typ width distinctness for strings
- Expr_F arg recursion and list arity differences
- Expr_Sub fallback through the default Marshal-bytes branch
- objectRefEqual nil handling

Covers >=80% of every function in expr_hash.go; residual lines are
unreachable Marshal-error fallbacks.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

@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.

LGTM — thorough performance fix with solid test coverage.

Perf: Structural FNV-64a hash replacing proto TextMarshaler in applyDistributivity and binary-marshal key in constLiteralKey — measured 5x improvement on the BPC reproducer. Sound design with tag bytes preventing cross-variant collisions and marshal fallback for uncommon expr types.

Correctness: optimizeFilters ordering swap is well-reasoned — domain rewrite must see the raw IN before composite-key folding absorbs it into prefix_in. BVT updates confirm strictly better filter plans.

Minor nits (non-blocking):

  • Manual byte loops could use bytes.Equal
  • writeUint64 loops while writeUint32 is unrolled (inconsistency)
  • String hashing uses null terminator rather than length prefix (safe due to equality fallback, but length prefix would be collision-proof)

@ghost
ghost merged commit 6a0394c into matrixorigin:3.0-dev Apr 30, 2026
23 checks passed
@ck89119
ck89119 deleted the bigsql-perf-fix branch April 30, 2026 16:04
mergify Bot pushed a commit that referenced this pull request May 7, 2026
… filter domain before composite-key folding (#24280)

Cherry-pick of #24229 and #24261 from 3.0-dev to main.

1. **Normalize per-column IN/NOT IN/=/<> domains in scan filters** (#24229): Generalizes the single-table scan filter rewrite into `normalizeColumnDomain`. For each column referenced by a scan's FilterList, collects constant-domain predicates and merges them into one canonical expression (IN intersections, IN \ NOT IN differences, = + IN collapse, empty → FALSE, etc.).

2. **Cut proto text marshalling from filter rewrite; normalize filter domain before composite-key folding** (#24261): Replaces `Expr.String()` map keys with structural FNV-64 hash + equality check in `applyDistributivity`, and packs literal proto binary form directly into `constLiteralKey`. Also reorders `optimizeFilters` so domain normalization runs before composite-key folding, allowing nested NOT IN / <> conjuncts to be collapsed before the outer IN is folded into `prefix_in`.

Measured ~5× latency improvement on BPC-style reproducer (2.9s → 0.52s).

Approved by: @heni02, @aunjgr
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
… filter domain before composite-key folding (matrixorigin#24280)

Cherry-pick of matrixorigin#24229 and matrixorigin#24261 from 3.0-dev to main.

1. **Normalize per-column IN/NOT IN/=/<> domains in scan filters** (matrixorigin#24229): Generalizes the single-table scan filter rewrite into `normalizeColumnDomain`. For each column referenced by a scan's FilterList, collects constant-domain predicates and merges them into one canonical expression (IN intersections, IN \ NOT IN differences, = + IN collapse, empty → FALSE, etc.).

2. **Cut proto text marshalling from filter rewrite; normalize filter domain before composite-key folding** (matrixorigin#24261): Replaces `Expr.String()` map keys with structural FNV-64 hash + equality check in `applyDistributivity`, and packs literal proto binary form directly into `constLiteralKey`. Also reorders `optimizeFilters` so domain normalization runs before composite-key folding, allowing nested NOT IN / <> conjuncts to be collapsed before the outer IN is folded into `prefix_in`.

Measured ~5× latency improvement on BPC-style reproducer (2.9s → 0.52s).

Approved by: @heni02, @aunjgr
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
… filter domain before composite-key folding (matrixorigin#24280)

Cherry-pick of matrixorigin#24229 and matrixorigin#24261 from 3.0-dev to main.

1. **Normalize per-column IN/NOT IN/=/<> domains in scan filters** (matrixorigin#24229): Generalizes the single-table scan filter rewrite into `normalizeColumnDomain`. For each column referenced by a scan's FilterList, collects constant-domain predicates and merges them into one canonical expression (IN intersections, IN \ NOT IN differences, = + IN collapse, empty → FALSE, etc.).

2. **Cut proto text marshalling from filter rewrite; normalize filter domain before composite-key folding** (matrixorigin#24261): Replaces `Expr.String()` map keys with structural FNV-64 hash + equality check in `applyDistributivity`, and packs literal proto binary form directly into `constLiteralKey`. Also reorders `optimizeFilters` so domain normalization runs before composite-key folding, allowing nested NOT IN / <> conjuncts to be collapsed before the outer IN is folded into `prefix_in`.

Measured ~5× latency improvement on BPC-style reproducer (2.9s → 0.52s).

Approved by: @heni02, @aunjgr
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
… filter domain before composite-key folding (matrixorigin#24280)

Cherry-pick of matrixorigin#24229 and matrixorigin#24261 from 3.0-dev to main.

1. **Normalize per-column IN/NOT IN/=/<> domains in scan filters** (matrixorigin#24229): Generalizes the single-table scan filter rewrite into `normalizeColumnDomain`. For each column referenced by a scan's FilterList, collects constant-domain predicates and merges them into one canonical expression (IN intersections, IN \ NOT IN differences, = + IN collapse, empty → FALSE, etc.).

2. **Cut proto text marshalling from filter rewrite; normalize filter domain before composite-key folding** (matrixorigin#24261): Replaces `Expr.String()` map keys with structural FNV-64 hash + equality check in `applyDistributivity`, and packs literal proto binary form directly into `constLiteralKey`. Also reorders `optimizeFilters` so domain normalization runs before composite-key folding, allowing nested NOT IN / <> conjuncts to be collapsed before the outer IN is folded into `prefix_in`.

Measured ~5× latency improvement on BPC-style reproducer (2.9s → 0.52s).

Approved by: @heni02, @aunjgr
This pull request was closed.

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 size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants