Skip to content

Fix primary-key runtime filter for index join backfill - #29466

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-29322-first-phase-20260929
Oct 4, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-29322-first-phase-20260929

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • BUG
  • Improvement

Which issue(s) this PR fixes:

Related to #29322. This is a partial performance repair; keep the issue open and this PR Draft until workload acceptance is met.

What this PR does / why we need it:

Secondary-index rewrites must keep column names aligned with their physical relation and column positions. Fix the five missing index/base primary-key names so runtime filters classify ordinary and hidden No-PK backfill keys correctly.

Rebased onto main f1137a6cac72852be2ab2e5078b684b98f23d96c, preserving main's prepared binding, scalar/DML contracts and diagnostic ownership. For multi-item SELECT IN/NOT IN, a wider signed integer parameter that fits a signed column of at most 32 bits can enter the existing typed IN list. Save its immutable full cast in the existing diagnostic candidates before optimization, then probe that cast for each cache hit. Unsafe bindings use the wider fallback without evicting the valid narrow generation; safe rebinding recovers the same Plan/Compile.

Reject nonsigned marker types and unsupported target domains before searching source bindings. This avoids the added per-item linear lookup for text, floating-point and unsigned IN inputs. Authoritative binding checks still own positive narrowing admission; immutable full cast guards are retained. No new lookup cache or state is introduced.

Remove this PR's minimal-width integer classifier, global range-key suffix, four propagated range flags and dedicated bucket tests. Changes such as 127 -> 128, or an unrelated projection value, now reuse the same valid INT plan. Shared cast rules and unsigned DML behavior remain those of main. Compile publication, failure/cancellation and delayed retirement keep their existing owner.

Route all subscription scenario teardown, including main's newly added legacy snapshot, through fresh bounded cleanup contexts. Retain deliberate scenario cancellation and resource-absence assertions. Consolidate prefix-IN coverage into the existing parameter/warning fixture; extend existing cache and planner guard fixtures instead of adding duplicate setup.

Validation

Validated content: ae56c83b622be3b4f8de52195d216f2f6c5f3bd4, directly based on f1137a6. On the rebased delivery content, macOS arm64 / Go 1.26.4 with locally built native artifacts:

  • PASS: complete pkg/sql/plan, pkg/frontend, pkg/sql/compile packages.
  • PASS: real MySQL prepared rebinding with mixed IN ordinals, INT32 boundaries/overflow/recovery, NULL, fractions, safe unsigned control, scalar comparisons and BIGINT arithmetic; result and warning oracles retained.
  • PASS: cancelled TestViewDescriptionSubscription, including legacy snapshot cleanup and teardown absence checks.
  • PASS: cache identity across irrelevant width boundaries, each ordinal's guard miss/recovery, projected IN and actual unused-consumer removal with retained guards, unsigned category miss, preservation of prior dependencies and diagnostic generation on Compile error/cancellation.
  • PASS: compact rejection/authority table (10 cases), including unsupported source/target domains, a signed-looking marker backed by an unsigned/same-width source and an unbound position.
  • PASS: real SQL with 2,048 text, floating-point and unsigned parameters; independent SUM and warning assertions before/after the prefilter.
  • PASS: incremental golangci-lint across affected packages and diff checks.
  • gpt-6.1-sol / xhigh solution design and complete final review performed through explicitly selected read-only CLI sessions; previous E1/E2/E3 findings and the rejected-domain P2 reconciled.
  • Existing physical-name and index-filter evidence reused where relevant source inputs are unchanged. External CI for the pushed revision remains pending; no new-base full BVT/topology pass is claimed.

Performance and remaining limits

The local admission benchmark checks Plan/Compile reuse on every iteration. Guarded IN measured about 16.36 us/op, 18,274 B/op and 142 allocations with three candidates; full-cast probing has measurable cost. This is not a full workload recovery claim.

Earlier exact-source A/B/A testing isolated the rejected-domain scan: for 2,048 text parameters, the original/early-rejection/restored SQL medians were 111.87/109.04/111.16 ms with identical results and warnings. The current before/after SQL correctness checks pass, but their timing is excluded because unrelated compilation caused large variance. No fresh quantitative speedup or full TPCC recovery is claimed.

Historical frozen-harness runs: baseline 36686381733 was 3,601.12 steady TPS; old head 36692316433 was 5,839.21 TPS. Both semantic/cleanup families passed. This partial improvement predates the current main integration and remains below #29322's 25,228.42 TPS acceptance.

A separate UINT64-overflow/negative-INT comparison error reproduces on both exact main and the candidate; this change preserves main's mixed-sign behavior and does not claim that limitation fixed.

@mergify mergify Bot added the kind/bug Something isn't working label Sep 29, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 29, 2026

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

Reviewed 80477ec1f3aec3d146ef15196cd3a58de36f9926 against freshly verified main f1137a6cac72852be2ab2e5078b684b98f23d96c. No remaining material code blocker found. This review was performed without subagents.

All three previous requested changes are resolved:

  • 4174506833 — cache identity: the global minimal-width classifier/range suffix and propagated flags are removed. Admission is owned by the actual IN consumer; frontend tests prove reuse of the same Plan/Compile across irrelevant integer boundaries and unrelated projection changes, plus per-ordinal overflow fallback and recovery.
  • 4174506836 — main integration: shared checkNoNeedCast, scalar and unsigned DML contracts match main. The existing unsigned DML oracle remains unchanged and passes.
  • 4174506843 — cancelled cleanup: the legacy snapshot and other scenario teardown use fresh bounded cleanup contexts. Deliberate cancellation and absence checks pass.

Design and failure-path assessment:

  • The narrow SELECT IN/NOT IN admission uses the existing source-binding and diagnostic-candidate owner. Full target casts are captured before optimization; projected and actually removed consumers retain their safety proof. Rejected witnesses retain value dependence; successful admission does not clear an unrelated dependency.
  • Cache publication remains after successful Compile. Failure/cancellation preserves the installed generation; unsafe rebinding cannot evict it. Existing isolated probes release results, suppress probe-only SQL warnings, and propagate cancellation/resource errors. No new cache, lifecycle state machine or asynchronous owner is introduced.
  • The five physical column-name repairs agree with their relation/column positions and the existing runtime-filter primary-key classification, including hidden No-PK backfill keys.
  • Tests were reviewed by contract, including their setup and negative assertions. The complete PR delta is implementation +49/-4 (net +45), tests/results +506/-75 (net +431), documentation 0. Planner, frontend cache identity, compile proof, public protocol and teardown cases exercise distinct boundaries; obsolete range-bucket tests are removed and existing fixtures are extended/consolidated.

Validation: reused the recorded final-content plan/frontend/compile package passes, public prepared rebinding, cancelled subscription teardown, actual consumer-removal oracle and incremental lint. This review additionally ran an independent real-MySQL challenge for TINYINT/SMALLINT projected IN/NOT IN with NULL rows, mixed/all-NULL parameters, both overflow directions and recovery. Expected three-valued results were computed independently in Go; all executions and zero-warning assertions passed (test 8.38s, package 10.195s). The temporary challenge is retained as a review artifact, with the worktree restored clean.

Approval covers the code repair, not completed workload acceptance. Full-cast probing has measured cost: the existing two-parameter guarded-IN benchmark reports approximately 16.36 us/op, 18,274 B/op and 142 allocations, with three candidates. No current-head full TPCC recovery is established. Keep the PR Draft and #29322 open until workload acceptance is met. At review time Shared Build and Connector/J Pool Reset passed; UT, SCA, coverage and BVT remain in progress. No new-base full BVT pass is claimed.

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

Senior-QA follow-up on 80477ec1f3aec3d146ef15196cd3a58de36f9926, without subagents. The challenge did not reproduce a new correctness blocker, but quantified the existing guard-work duplication at larger parameter counts.

Independent public-path challenge: 567 binary prepared executions across TINYINT/SMALLINT/INT and ordinary/composite/no-primary-key tables. Seven-parameter lists mix fitting values, both overflow directions, INT64 extrema, duplicates, NULL/all-NULL, and safe recovery. Projected IN/NOT IN truth and filtered row IDs are calculated by an independent Go three-valued model. Forced-index and ignored-index results agree with that model, including non-indexed payload columns. EXPLAIN verifies INDEX JOIN, runtime-filter build/probe, and the ordinary/composite/hidden physical PK in all nine forced-index cases. PASS: 8.90s test / 11.126s package; zero warnings checked immediately after each of the 567 executions.

Measured performance concern, not an established regression against main: an admission-only benchmark verifies the same Plan and Compile on every iteration. Wider signed bindings expose N individually captured full-cast guards plus the existing maximal list candidate. The retained trees contain 2N cast sites and the normal probe path evaluates those conversions in the individual guards and again in the list.

IN parameters Guarded hit time Bytes/op Allocs/op Candidates Retained cast sites
8 38.3 us 67,776 492 9 16
64 295.3 us 535,108 3,747 65 128
512 2.467 ms 4,340,217 30,013 513 1,024

Same-width 512-parameter control: 0.956 ms, 1,644,747 bytes/op, 11,569 allocations, one candidate and no cast sites. These controls isolate source-domain/admission costs within this head; they are not a before/after main comparison or a TPCC result. The same-width path also has substantial baseline cost.

This is a concrete performance optimization opportunity within the accepted partial-repair scope. Any consolidation must retain proof after actual consumer removal, projected-IN coverage, target/position identity, warning isolation and failure/recovery behavior; simply deleting the individual guards would lose those invariants. This result does not justify a new cache or parallel guard state machine.

Existing code approval remains unchanged. Full workload acceptance remains open and the PR remains Draft. Current-head UT, SCA, coverage, Connector/J and both active BVT modes now report success. Temporary challenge/benchmark files were retained as local review artifacts and removed from the clean worktree; no production or committed test changes were made.

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

Main-baseline verification on exact PR head 80477ec1f3aec3d146ef15196cd3a58de36f9926 versus its exact main base f1137a6cac72852be2ab2e5078b684b98f23d96c. This closes the before/after uncertainty in the preceding QA challenge. No subagents were used.

Both isolated worktrees ran byte-identical benchmark sources on Apple M4 / macOS arm64 / Go 1.26.4. Native source fingerprints and CPU/release/SIMSIMD=0 profiles match; main native artifacts were built through make -j8 cgo and both were validated by the repository wrapper. Runs were serial, with three 300ms samples per case and excluded fixture setup/warmup. Admission ran main then PR; real SQL ran PR then main. Figures below are medians, not statistical confidence intervals.

EXECUTE binding/admission: signed BIGINT parameters against an INT column. Main rebuilds with 0% runtime-cache hits; the PR reuses the same Plan and Compile with 100% hits.

IN parameters Main PR Latency reduction Main bytes/op PR bytes/op
2 65.37 us 11.22 us 82.8% 60,708 18,275
8 137.13 us 64.36 us 53.1% 119,157 67,776
64 790.34 us 313.51 us 60.3% 695,804 535,149
512 7.169 ms 2.561 ms 64.3% 5,496,696 4,337,421

Same-width controls retain 100% hits on both revisions and essentially equal allocation counts/bytes; their timing varies between samples. The admission seam deliberately excludes executing/compiling the database query, so the second layer is needed.

Real MySQL prepared SQL: a seven-row indexed table, SUM(payload) requiring a non-indexed payload column, distinct BIGINT arguments and repeated EXECUTE on one server statement. Every measured call verifies the aggregate against an independently computed expected sum.

IN parameters Main query latency PR query latency Reduction
2 0.465 ms 0.312 ms 33.0%
8 0.700 ms 0.380 ms 45.6%
64 2.806 ms 0.986 ms 64.9%
512 21.492 ms 6.733 ms 68.7%

All four benchmark invocations terminated with PASS. Sources, complete logs, raw samples, native provenance and median calculations are retained as local review artifacts; the temporary files were removed and both worktrees verified clean.

Decision: retain code APPROVE; the measured guard duplication does not establish a regression and does not justify REQUEST_CHANGES on that basis. The PR trades main's repeated value-dependent binding/planning for bounded diagnostic probing, with a demonstrated net benefit in both measured layers. Duplicate individual/list cast probing remains a real optimization opportunity with the previously documented safety constraints. These are single-client, small-data microbenchmarks, not a full TPCC/TPS acceptance result; keep the Draft/open performance issue until that acceptance is independently met.

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

Follow-up regression challenge on 80477ec1f3aec3d146ef15196cd3a58de36f9926 against exact main f1137a6cac72852be2ab2e5078b684b98f23d96c: REQUEST_CHANGES for one verified P2 performance finding in the newly added IN admission helper.

The previous positive result for eligible signed narrowing remains valid. This round deliberately exercised rejected/low-benefit paths: removed consumers, TRUE short-circuit, continuous overflow at different positions, safe/unsafe oscillation, one-shot prepare, fractional sources, and large nonsigned source lists.

The new blocker is avoidable additional binding scans for source domains that cannot enter the optimization. The inline finding includes the main comparison and original/diagnostic-overlay/restored-original causal control. It does not ask to remove the safety guards or introduce another stateful mechanism.

Other observations are non-blocking:

  • Two-parameter continuous overflow adds admission overhead and allocations. Whole-query reverse-order seven-sample checks differed by about 1%, with overlapping samples; that is not sufficient to call a material end-to-end regression.
  • A last-position overflow in a 128-item list increases admission bytes by about 22% and measured whole-query allocation by about 8%, while whole-query latency is about 20% lower than main. Process-wide SQL allocation figures include server/background work and are not a precise capacity bound.
  • Removed consumers, TRUE short-circuit, safe/unsafe oscillation, and one-shot prepare did not show a convincing whole-query regression in the measured two-/128-item cases.
  • Every selected execution/result/warning oracle passed. No new wrong-result or warning-publication failure was reproduced.

Measurements were serial with identical test source per comparison, setup/warmup excluded, same source/native profiles, and explicit case/sample-count validation. Empty-selection trial logs were excluded. Temporary test files and the diagnostic overlay were not committed; both worktrees are restored clean. This review used no subagents.

Local evidence: regression-challenge-80477ec/ under the existing PR evidence directory contains full logs, raw samples, summaries, source fingerprints and the diagnostic overlay. These are small-data, single-client measurements, not full TPCC acceptance. Keep the PR Draft/open performance issue; after removing the demonstrated non-admitted-path overhead, preserve the existing correctness and positive cache-reuse evidence.

Comment thread pkg/sql/plan/prepared_binding.go Resolved

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

Reviewed ae56c83; the P2 rejected-domain scan is fixed and its thread resolved. gpt-6.1-sol / xhigh complete overall review found no material blocker (session01a104a2-ede3-7050-94c5-153287c774ee; reviewed delta810bb7732eb20867d03ed882651bd1db29b95b9611818664222d5d99241f7b15). Source-type rejection precedes lookup; authoritative positive binding checks, projected/eliminated full-cast diagnostics, unsafe fallback and cached Plan/Compile recovery remain intact. Owning plan/frontend/compile packages, real protocol regression, all 10 rejection/authority cases and incremental SCA pass. 2048-parameter unsupported-domain SQL results/warnings pass; recent timing samples are excluded due unrelated compilation. Approval is for the current implementation scope; PR remains Draft and full #29322 TPCC acceptance and current CI remain outstanding.

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

Deep review of ae56c83b622be3b4f8de52195d216f2f6c5f3bd4 against verified base/merge-base f1137a6cac72852be2ab2e5078b684b98f23d96c: APPROVE for the current implementation scope; no new blocking regression found. All 11 changed files and all four review threads were covered. No subagents or external model sessions were used in this review.

One verified non-blocking inherited gap remains: buildHintedIndexBackfillJoin still constructs its base-PK reference without Name, unlike the repaired applyIndexJoin path. A focused counterexample on BOTH exact main and this head produces physical PK=id, Name="", ColPos=0, NotOnPk=true. Thus a complete primary key is classified as an ordinary-column runtime filter. Real SQL SELECT id FROM t FORCE INDEX(idx) WHERE payload='a' ORDER BY id on a three-row No-PK table reaches an INDEX join/runtime probe and returns the correct independently expected rows, including a NULL indexed key, with both forced and ignored index access. This is a demonstrated metadata/classification gap, not a reproduced wrong result or measured regression introduced by this PR. The hinted constructor is a follow-up target; the mechanism should not be described as completely cleaned up.

The four existing findings are resolved in code and evidence:

  • Cache reuse follows actual full target-cast consumers; the global minimal-width classifier/range key and obsolete tests are gone. Unrelated value changes do not evict a valid plan.
  • Shared scalar/unsigned DML conversion remains main's contract; SELECT multi-IN admission is local to its consumer.
  • All changed subscription SQL teardown, including the legacy snapshot, uses independent bounded contexts after scenario cancellation.
  • Nonsigned markers/unsupported targets return before the new linear binding lookup. Positive admission still checks authoritative source identity and width; guards remain intact.

Design/lifecycle audit:

Closure Verified owner and terminal behavior
Guards and allocations (Q1/Q3) Immutable copies enter the existing per-plan diagnostic list; evaluation results are freed, failed candidates discarded, replaced/closed generations release their references. Retention scales with statement expression size; no new global cache/worker/state machine.
Failure and reuse (Q1/Q2) Full target casts remain before rewrites, including projected/eliminated consumers. Widening-only binary shortcuts cannot approve narrowing overflow. Compile errors/cancellation preserve the installed generation; displaced Compile release remains deferred to wrapper cleanup.
Subscription teardown (Q2) Fresh 30-second contexts outlive the cancelled scenario; SQL cleanup precedes registered DB close, and account/database absence is asserted.

Independent additional QA: TestQA29466PreparedIndexWorkspaceLifecycle passed in 9.89s (package11.193s). One shared cluster, No-PK and composite-PK tables, five rows initially: warm prepared IN -> transaction insert/key-update/delete -> rollback -> repeat/commit -> flush. 100 result checks combine forced/ignored index, signed overflow at either ordinal, NULL, and safe recovery. Expected IDs/keys/payloads come from an independent model; warnings remain zero. Actual INDEX-join reachability is asserted. The first diagnostic attempt used the wrong EXPLAIN label; it was corrected to the actual Join Type: INDEX field and excluded from pass evidence. The separate forced-backfill public reachability/control passed in9.48s.

Valid owning-package, real-protocol, projected/eliminated guard, Compile failure/cancellation, subscription cleanup and static evidence from the delivered content is reused; no equivalent broad suites were repeated. Temporary challenges are retained as review artifacts and removed from both worktrees. No production code changed.

Change cost versus base: production +53/-4 (net+49), tests/results +544/-74 (net+470), documentation0. Tests cover distinct planner identity, cache lifecycle, storage diagnostic ownership, protocol semantics and teardown contracts, with reused lightweight fixtures and small SQL data. Remaining individual/list diagnostic probe duplication has measured net benefit versus main in eligible cases; current host-contended timings do not support a new speedup claim.

Build and Connector/J E2E have passed; other CI gates remain pending at review time. Keep Draft and #29322 open for full workload acceptance. This approval neither asserts full TPCC recovery nor closes the inherited hinted-backfill classification gap or previously recorded main UINT64 limitation.

@XuPeng-SH
XuPeng-SH marked this pull request as ready for review October 4, 2026 04:10
@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 →

This branch was previously deployed

1 inactive deployment
ci — bd03dc0f Deployed Oct 4, 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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants