Skip to content

fix(plan): preserve SQL comparison semantics in index predicates - #31624

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/31619-index-comparison-semantics
Oct 30, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/31619-index-comparison-semantics

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 28, 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:

Fixes #31619

What this PR does / why we need it:

A DATETIME index compared with NOW() can return future rows or omit matching rows because encoded DATETIME and TIMESTAMP values have different type tags. Their SQL comparison also depends on session time zone and TIMESTAMP precision, so casting the bound does not generally preserve the predicate.

Share comparison-domain admission and lossless bound normalization across regular indexes and compound primary/cluster keys. Keep safe key prefixes and original SQL predicates whenever byte-prefix or NULL semantics require an exact recheck, before applying LIMIT. Preserve direct scalar comparison overloads and decline unsafe range coalescing. The same policy covers CHAR padding, decimal overflow/rounding, escaped-NUL string prefixes, OR arms, and nullable cluster-key bounds; redundant decimal-only helpers are removed.

Existing index data and encoding are unchanged. Unsupported cross-domain comparisons use decoded SQL evaluation, which can cost more scan work; proven same-domain access paths remain available.

Validation:

  • Owning planner package in normal mode and focused comparison/residual controls passed. The full owning planner package also passed with the race detector; all 10 new regression tests executed and passed.
  • Source-built SQL results agree across automatic, FORCE INDEX and IGNORE INDEX paths, including flush, prepared reuse, precision and DST cases. The new 105-check BVT passed twice on one service; both runs left no test database.
  • Formatting, vet, pinned molint and repository-configured incremental golangci checks passed for the affected planner package (0 lint issues).
  • Design and overall review: gpt-6.1-terra/max; final independent review: gpt-6-astra/xhigh. No unresolved review findings.

CI follow-up after rebase

Preserve the existing bound overload for folded IN predicates, fall back to the original scan if index-only plan construction fails, and propagate planning cancellation. Update optimizer expectations for the retained residual filter and unsafe CHAR index probe. The CHAR case can scan more rows; no performance equivalence is claimed.

Validated on the rebased head: the complete planner package under race; the three failing CI cases under race; incremental SCA for the planner package (0 issues); and optimizer BVT in_domain.test (40/40) and index.test (119/119). The original head reproduced the invalid folded-IN binding and the corresponding SQL failure before the fix.

CI results are pending.

@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 Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 80cd84e7cfbccb9a3e5f8037963b4fabc651a92b

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: 80cd84e7cfbccb9a3e5f8037963b4fabc651a92b

Assessment: approve

Reviewed the complete delta, affected consumers and discussion. Comparison admission, lossless normalization and residual handling preserve SQL semantics. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • 24 focused tests and 4,405 planner suite top-level cases passed.

  • Single-CN MySQL-entrypoint probe replayed 105 SQL statements and 54 result sets twice, verifying cleanup after each run.

  • go vet, formatting, diff checks and source-cleanliness checks passed.

  • Commands, frozen-source fingerprints, successful exits and retained logs reconciled in attempt-1/validation-summary.json; discussion assessment and native provenance retained.

Limitations:

  • Supplied CI remained pending; author-reported checks were not counted as independent validation.

  • SQL replay used a reviewer test overlay, not mo-tester; JDBC type-width metadata was not checked.

  • No fresh race, multi-CN, restart or released-binary testing was performed.

@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: cffe8909791e92b1fc9ed666caa76fa78219213e

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

Assessment: approve

Comparison-domain admission, lossless normalization and exact residual handling preserve SQL comparison semantics. Complete delta, consumers and discussion reviewed; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Full planner suite passed, including all 13 targeted regression tests: plan-test.log; receipt checks/1793240317739481323-4.json.

  • Frontend replay passed twice for the 105-statement comparison case and 40-statement optimizer case, with expected results and cleanup verified. CHAR-plan and folded-IN controls also passed: public-test.log; receipt checks/1793240580374143446-11.json.

  • Preflight, native build, formatting and git diff --check passed. Source remained unchanged.

  • Evidence audit verified native provenance, command/log receipts and coverage of all four discussion entries. Records: /home/xupeng/.local/state/mo-bot/jobs/146237458662df47b9bc4ca3/attempt-1/validation-index.json and discussion-assessment.json.

Limitations:

  • Supplied CI was pending; author-reported race and lint results were not independently verified.

  • Frontend checks used one embedded CN, not mo-tester; JDBC width metadata and the full large optimizer/index.test were not checked.

  • An initial probe-only EXPLAIN multiline formatting mismatch was corrected; its failed log and successful rerun were retained.

@XuPeng-SH

XuPeng-SH commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 503ac4e96fbae221d2246566c701644282743585

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: 503ac4e96fbae221d2246566c701644282743585

Assessment: approve

Comparison-domain admission, lossless normalization and residual filtering preserve SQL semantics. Prior design conclusions remain supported; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

Validation:

  • Full planner suite passed: 4,468 top-level tests and 17,064 subtests, including all 13 added tests.

  • Frontend replay passed 308 statements across two rounds of comparison, IN-domain and isolated CHAR scenarios; cleanup verified.

  • Formatting, go vet, pinned molint and configured incremental golangci passed with zero issues.

  • Six successful receipts reconciled in validation-evidence.json. All six discussion entries assessed; source unchanged.

Limitations:

  • Two existing unrelated subtests were skipped; no fresh race run.

  • Frontend replay was not mo-tester; JDBC width metadata and the full large optimizer/index.test were not checked.

  • Relevant CI remained pending. Unsafe comparisons may require more scan work, as documented.

@XuPeng-SH
XuPeng-SH merged commit 415068c into matrixorigin:main Oct 30, 2026
20 of 21 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/31619-index-comparison-semantics branch October 30, 2026 04:20
XuPeng-SH added a commit that referenced this pull request Nov 9, 2026
## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [x] Code Refactoring

## Which issue(s) this PR fixes

Closes #32318. This is the standalone successor to #31944; the original
mixed temporal wrong-result fix is #31624.

## What this PR does / why we need it

Mixed `DATETIME`/`TIMESTAMP` comparisons need type-aware necessary
ranges and the complete SQL residual. This integrates their planning,
costing, authorized resolution, filtering and execution into the
existing index owners:

- The comparison owner supplies range classification and bounded numeric
cost ranges. Ordinary integer costing does not depend on the statement
clock or time zone; temporal inversion requires its captured fixed zone
and clock. A BASE decision retains the dependency needed to reconsider
INDEX on a later execution.
- A necessary `CandidateFilter` is independent of the residual and does
not authorize hidden-table access. A physical scan separately records a
captured-execution requirement, which frontend, compile and retry
validate against execution and placement.
- Ordinary authorized relation resolution supplies an explicit nullable
borrowed-result output. It is cleared on failure and denial and does not
acquire relation ownership. The root builder retains its input only
after initial compiler and process admission and rechecks compiler
identity for each borrow; no duplicate admission flag or compatibility
resolver remains. External Go implementations and callers of
`CompilerContext` must migrate to the explicit parameter.
- The existing bounded expression visitor and index selector own
fallback dependency proof and selection. Unknown or exhausted input
stays conservative; no second resolver, metadata cache, execution route
or dependency registry is introduced.
- Shared zone-map operations treat an all-`ff` maximum as potentially
unbounded, including old unmarked summaries. Metadata aggregation clones
cached zone maps before merging, avoiding concurrent cache mutation.

The
[design](https://github.com/XuPeng-SH/matrixone/blob/d033d8faed2cb5647c3ee6ea3bda3e7179362bd6/docs/design/20261107-index-planning-owners.md)
records the separate ownership and reuse contracts. Named-zone
inversion, prepared temporal inversion, joins, LIMIT/OFFSET,
non-covering backfill and distributed candidate scans retain
conservative fallbacks.

The prior Compose/Proxy CI failed while COPY ALTER was acquiring
source/index admission, with a write conflict. A Fulltext2 ISCP task was
active nearby, but the logs do not identify the actual conflicting
holder. The two affected Fulltext2 fixtures now insert their initial
rows before CREATE INDEX, whose existing synchronous build indexes the
populated table and starts CDC from the current point. Their ALTER and
result assertions remain. A new deterministic SQL integration test
freezes the rebuilt generation after a post-rebuild CDC update, verifies
the same-schema gap and result, then forces a schema change and verifies
that the indexed query survives a rejected cross-schema `table_changes`.
The generic ALTER/async-index conflict tracked by #31611 is not fixed by
the fixture change; production conflict and rollback guards remain
intact.

## Validation

- Rebased onto `main` `d7185c9a92` at head `d033d8faed`. Focused
frontend subscription, planner ENUM/snapshot, pagination and
set-membership, and value-scan tests passed. The embedded SQL test for a
cached historical subscription with a replaced alias and
revoked/regranted publication passed. The issues and isolated-issues
packages were compiled without executing their tests; a repository AST
scan checked 800 `BuildPlan` calls.
- The validation below was recorded on pre-rebase revisions and was not
all rerun after the rebase. CI and final-head review must be evaluated
on the updated head.

- Planner and value_scan complete normal and race runs: 4,846 and 20
top-level tests respectively; two existing planner subtests skipped.
Five public SQL roots (temporal EXPLAIN/index parity, hidden-index
access, prepared numeric/temporal behavior, legacy privilege cleanup and
the upstream #31882/#31913 VALUES/UNION regression) passed normal and
race. The new Fulltext gap/fallback integration test passed three normal
and three race runs, including test-owned database and ISCP cleanup.
- Repository AST inventory: 7,623 tracked Go files, 798 `BuildPlan`
calls and 68 resolver implementations checked for explicit output
signatures and clearing; all passed. Incremental gofmt, full-PR diff
check, vet, pinned molint and unfiltered configured golangci passed for
the seven affected planner/consumer packages, with a further check of
the final test-only delta. Earlier full-repository static and other
owner normal/race runs remain source-qualified to the earlier production
revisions.
- Two-CN pessimistic embedded cluster with a real Proxy and strict
result/metadata comparison: `fulltext2_json_probe_alter` 16/16 and
`fulltext2_include_rename` 39/39, each three times; databases and server
were cleaned up. The first strict run also exposed stale boolean-result
metadata in the old expected files, which this PR corrects. The local
cluster is not the Docker Compose CI topology.
- A stopped upgrade from the real 4.2.8 release to the
production-identical candidate passed: temporal INDEX/BASE results
matched, an old non-admin saved result remained readable, revocation
denied it and regrant restored it, and persisted binary data returned
the expected block-filtered row. Both services stopped cleanly and the
isolated containers and volume were removed. The upgrade binary is built
from `929cd5c825`; the subsequent candidate delta only changes test
cleanup order.
- Same-main two-CN performance against the pre-refactor feature: two
old/old controls and six interleaved processes per side, 100 timed
samples per phase after warmup. Shuffled sparse INDEX p50 was
0.52889→0.52382 ms and ordinary shuffled integer 0.25476→0.25277 ms. The
prepared binary phase showed +8.75% process CPU and +4.02% Go bytes in
this short run. A history-preserving follow-up with the previous seven
phases and 1,000 prepared samples measured p50 -0.15%, p95 +5.18% versus
old/old +10.51%, CPU +0.036% and Go bytes +0.071%. These runs do not
explain the earlier mixed-workload +13% p95 signals; the prepared
physical plan and native allocations were not observed, and process-wide
CPU/Go bytes include background work.

SQL syntax and durable table/index formats do not change. The supported
upgrade tested here is a stopped 4.2 upgrade; mixed-version execution
and downgrade are not claimed. The existing mo-bot approval covers
published head `c04627aa32`; final-head review and GitHub CI remain
separate.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH added a commit that referenced this pull request Nov 15, 2026
## Problem

On 4.2-dev, comparisons between DECIMAL operands with different scales
can discard matching rows after flush. Serialized index bounds can also
use the wrong comparison domain. The failure exposed by #32675 exists
independently on 4.2-dev. The original query works on main, which
includes #26815 and #31624.

## Changes

- Compare storage pruning bounds in a compatible decimal domain and fail
open when a bound is not proven safe.
- Admit serialized index predicates only when their bound can preserve
the stored comparison domain; keep decoded SQL residuals when a prefix
lookup can admit extra candidates.
- Preserve SQL NULL and outer-join semantics, remove the unsafe early
constant fold, and use checked common decimal domains and overflow-aware
vector comparisons.
- Rebuild fixed-type parameter wrappers when a source type changes or
requires conversion.
- Preserve CHAR static index access and same-type CHAR JOIN runtime
filters, which use byte comparisons and the same string serialization.
Mixed CHAR/VARCHAR JOIN filters remain conservative.

## CI follow-up and validation

The first CI run exposed four EXPLAIN changes: a necessary composite
VARCHAR prefix residual, an unintended CHAR index fallback, and two
common DECIMAL type widths. The CHAR fallback is fixed; the other
expectations now reflect the proven plans. On the old baseline, a
composite VARCHAR IN query actually returned an extra embedded-NUL peer
before and after flush; the residual removes it.

- Two-CN BVT for the three previously failing files and DECIMAL
coverage: 1,027/1,027 passed, with no failures or skips. Added real
persisted CHAR index/JOIN, NUL-prefix and signed INT32 boundary cases.
- Actual SQL on one and two CNs, before and after flush, covered
FORCE/AUTO/IGNORE, composite DECIMAL bounds, NULL and outer joins, and
overflow. CHAR FORCE/IGNORE comparisons covered trailing spaces, NUL,
NULL, IN, ranges, prepared parameters, covering and backfill. The CHAR
JOIN probe verified the runtime filter was actually present before and
after flush.
- Full normal and race tests for pkg/sql/plan and pkg/sql/plan/function
passed after this follow-up. The earlier six affected package suites
also passed normal and race before the latest unrelated 4.2 base
updates.
- Incremental go vet, golangci-lint and molint passed.

Before this CI follow-up, ABBA microbenchmarks on host 57 against
4.2-dev 296402f measured valid DECIMAL64/128 comparisons and INT64
controls; their vector kernels are unchanged by this follow-up. INT64
one-row batches increased by about 3.5 ns, while larger batches were
essentially unchanged.

A separate pre-existing 4.2 prepared-statement issue remains: reusing an
untyped parameter with different DECIMAL scales can produce an incorrect
comparison even without an index. Explicitly casting the parameter to a
fixed DECIMAL type avoids it; it is outside this change.

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

[Bug]: Secondary-index range query with NOW() returns future DATETIME rows

2 participants