Skip to content

fix: restore prepared TPCC filter selectivity with per-binding proof - #29462

Merged
XuPeng-SH merged 12 commits into
mainfrom
fix/29429-block-filter-perf
Sep 29, 2026
Merged

XuPeng-SH merged 12 commits into
mainfrom
fix/29429-block-filter-perf

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #29429
Fixes #29463
Fixes #29464
Fixes #29465
Fixes #29469
Fixes #29470
Fixes #29473

Related: #28907 (existing JSON CONCAT report), #29471 (separate global JSON CAST/assignment behavior) and #29476 (transient clean-startup IVF placement failure). The latter two are not fixed here.

What this PR does / why we need it:

Root cause

#28851 (a99db843c7b4630a86883addc9424433d93fc2d2) protected conversion diagnostics, but treated a prepared conversion that might diagnose as unsafe for every execution. Integer parameters travel through TEXT vectors and implicit CASTs. Excluding their predicates before binding removed reader/block selectivity and prevented JOIN rewrites. Extra execution work extended lock holding time; the reported lock waits were a consequence.

The initial fix restored binding-specific proof, but retained late parameter specialization and two execution templates. Review exposed an existing correctness defect: specializing after composite-key lowering can coerce the serialized key itself to DOUBLE and return unrelated rows. Disabling key rewrites selectively was neither complete nor fast enough.

One execution route

Bind the original parameter ordinal and SQL source type before overload selection, comparisons and key/index lowering. Keep parameter references throughout optimization. Each builder captures immutable diagnostic candidates before rewrites; every execution and retry proves its own binding. Only after SQL optimization are non-string parameters lowered to the existing TEXT transport CAST representation. String source metadata remains intact.

Each prepared generation owns one bounded runtime plan/compile entry keyed by source metadata. Value-dependent configuration is excluded. Compile success gates publication; displaced compiles are freed after statement cleanup. Normal execution and retry use the same typed binding route. Reusable source nodes remain immutable, while current raw block filters are renewed and folded at their execution destination.

Delete dual templates, the QUERY late-Fill/prepare-compile fallback, duplicate proof state, value/parser-specific cache traits and unused admission helpers. Shared function admission handles actual source domains, including temporal/FLOAT/string arithmetic, full UINT64 multiplication, JSON arithmetic, opaque binary aggregate states and runtime REGEXP domains. Bare NULL retains ANY; typed NULL retains its source type. JSON CONCAT and binary JSON_DEPTH input contracts use the existing MORPC capability mechanism at version 101, including placement, send recheck, receive and persisted-expression floor.

Design and complete review map: design, review record.

Review disposition and engineering scope

Accepted aptend's review. The old composite-key golden was wrong. The corrected oracle agrees with an independent scalar comparison for valid → invalid text → NULL → valid, including an actual zero key, warnings, ranges and both SQL/binary protocols. No wrong rows or internal-key conversion warnings are accepted.

Staged GPT-6 Astra/xhigh review approved the single-route design, reviewed the complete change map and the affected increments, and closed all code findings. Physical string metadata and opaque-state admission findings were fixed in their common owners and retested. The same reviewer independently audited the final source hashes, repeat BVT, race/static gates, six benchmark runs and corresponding profiles: final PASS, zero unresolved blockers.

Against merge base a543410f766d2f41237519ed7cc1376c31e03d99, production code is +1,597/-1,284 (net +313); tests are reported separately. Against the previously published PR head, this rewrite removes a net 331 production lines (+1,330/-1,661). The remaining increase over the base covers the common binding owner and consumer contracts.

Validation

Delivered head: 74d6811d3ddae92e1841efab3892bf841588e16f; Go source hashes match the tested binary and final review.

  • Full frontend/plan/function/compile package tests passed after the binding and consumer changes; pb/plan, colexec and parser/tree package tests also passed.
  • Final temporal string/NULL changes: full plan/function tests, real TIME protocol rebinding and actual frontend execution of a migrated legacy TEXT NULL passed.
  • Real two-CN SQL/binary composite-key correctness, specialized domains, JSON_DEPTH and prepared binary EXPLAIN passed. Large opaque-state valid/error/NULL/valid recovery and typed NULL controls passed.
  • Focused race tests passed for cache replacement, fresh retry proof, AP plan reuse and reader/remote filter ownership.
  • Incremental vet and golangci-lint passed across ten changed/consumer packages (local lint 2.5.0 built with Go 1.26.4; CI installs its pinned 2.6.2); the final affected-package rerun also passed, zero issues. Formatting and diff checks passed.
  • Fresh two-CN BVT: issue case 61/61 and vector prepared-range case 64/64, twice on each CN, 500/500 total. The readiness precondition actively refreshes inventory with SHOW BACKEND SERVERS and confirms both expected CNs as Working. The first attempt used only SELECT 1 readiness and encountered one ordinary IVF placement failure during startup; original failure and clean-parent controls are preserved in [Bug]: First ordinary IVF query can fail during clean 2-CN startup despite SQL readiness #29476, not counted as a pass.

Performance acceptance

Three formal pairs passed, with zero transaction errors in all six runs:

Pair / order Parent tpmC Current tpmC Parent/current NVMe read GiB
1 / parent then current 5831.75 5900.37 46.04 / 46.05
2 / current then parent 5611.58 5785.63 44.41 / 46.30
3 / parent then current 5563.75 5761.17 45.51 / 44.82
Mean 5669.03 5815.72

Mean current/parent: 102.59%; all three pairs reached the parent level. This supports recovery for this workload, not a universal speedup claim. Current binary SHA256: ac124dedc8d664daeb506bce35501540f0a3cdd6225774b3f8c2f91260a03c01.

Merged three 120-second profiles per version, aligned within one second of all terminals starting: parent/current 76,620/78,660 transactions, 2173.69/2030.66 sampled CPU seconds. Approximate CPU per transaction fell 28.370 → 25.816 ms (-9.00%). Parameter initialization fell 2.912 → 0.686 ms/transaction, and Compile 3.545 → 1.261 ms/transaction. Cumulative stacks overlap and must not be added. The deleted QUERY late-Fill previously consumed 84.37 CPU seconds; current binding proof and planning consume only 0.95 and 0.63 CPU seconds. This supports the single reusable binding route and closes the performance gate.

Baseline is the regression's direct parent 1575e70c3db676d3ed00abc080aadc029b0e1435. Each run uses a fresh service and version-compatible initial snapshot on NVMe, sync and own-data cache eviction, 10 warehouses, 10 clients and two minutes. Same fixed-seed BenchmarkSQL JAR on both sides; alternating run order and CPU profiles. Version-compatible snapshots were independently loaded; their row values have not been proven identical. The previous binary's 100.44% result and the initial pilot are excluded from this acceptance. The host has other services; this task's build, UT, lint and BVT had finished before performance runs. NVMe numbers are device-level I/O, not exclusively this process.

Compatibility and delivery scope

The tested base is a543410f76; main was rechecked at d8152cb08d7e73316034c33aaf0e7bc01c176f91. Its intervening changes do not overlap the modified files, and MORPC 101 remains available. This does not claim validation of an unbuilt merge result. Local two-CN validation uses separate CN services within one process; independent-process multi-CN throughput is outside the single-CN regression benchmark. Reverting restores the conservative diagnostic behavior and its regression. CI for the new head will be reported separately from local evidence.

2026-09-29 CI repair on rebased head

Rebased onto main at e5f70bedc4; current head 968b2ca863. The prior CI run at 65c129b9b6 had three UT failures, seven static-analysis findings, 31 pessimistic BVT mismatches and 12 proxy BVT mismatches. The new issue #29429 BVT itself had passed 61/61. The failures came from prepared source-domain binding reaching adjacent consumers and from an ordinary SQL comparison rule that changed existing coercion/index plans.

The repair keeps source identity at the prepared consumer, removes the generic text/numeric comparison override for ordinary SQL, preserves exact UINT/BIT and DECIMAL comparisons, and makes value-sensitive numeric spelling plans ineligible for the type-only cache. It also repairs NULL user-variable aliasing, REGEXP marker provenance through scalar/derived projections, unsigned generate_series bounds, numeric aggregates, NTILE NULL errors, and the geometry test's UINT32 vector read. Four uncalled numeric-prefix helpers were removed. Three existing BVT expected-result files were updated only where direct SQL behavior or the runtime charset error supports the changed expectation.

A GPT-6 Astra xhigh independent review challenged same-type cache reuse, ternary BETWEEN coercion, exact comparison above 2^53, volatile left evaluation, diagnostic warning count and BIT/UINT boundaries. Confirmed findings were fixed and the final exact BIT challenge passed. Local validation after rebase: complete pkg/sql/plan, pkg/sql/plan/function, pkg/frontend, and pkg/sql/compile package tests; the full TestPreparedSpecializedDomains embedded suite; focused pkg/tests/issues tests for #27088, #27294 and #29463; CGo-aware golangci-lint; go build; go vet; gofmt and git diff --check all passed. Full distributed BVT and the prior TPCC throughput experiment were not rerun on this exact head; earlier performance measurements remain evidence for the preceding implementation, not a new throughput claim. CI is running independently and was not awaited. The latest rebase resolved the single baseBindVar conflict by applying NULL-to-TEXT normalization before the new mainline user-variable string-domain binding; focused planner/frontend and embedded protocol regressions passed.

2026-09-29 follow-up repair on f520258274

The Ubuntu/x86 coverage job for 386c143 found two real failures in pkg/tests/issues: the CHAR string source case expected 41 but produced the independently confirmed MySQL result 40, and an existing binary prepared BETWEEN DML case rejected text "foo" via a strict integer cast. The latter passed on exact base b06ff850d4 and failed on the previous PR head. The fix routes prepared text parameters with numeric BETWEEN bounds through the existing binary comparison conversion, preserving warning 1292 and the DML result. No parallel prepared execution path or new state was added.

#29500 and #29502 are fixed and closed. #29500 also removed the remaining production-unused applyBinaryDirectResultDecimalTypes and runtimeParamTypesContainText helpers, write-only directResultParamPositionsSet and parameterizedGenerateSeries fields, self-only tests/benchmark, one duplicate direct-result metadata scan, and the superseded dual-template text in docs/design/temporal-compatibility.md. #29501 (cross-query-boundary ABS/SUM) and #29499 (YEAR→BIT mixed-version capability) are fixed in 95e565b528.

Local validation on the repaired source, using the repository CGo-aware wrapper: full TestIssue25408PreparedPaginationParameters and TestIssue27443BinaryPreparedDMLAndAggregate families passed with no skips; full pkg/sql/plan and pkg/frontend packages passed; git diff --check passed. The prior 74d6811 performance experiment and 386c143 coverage job are revision-specific evidence; neither is an exact-head benchmark or CI pass for f520258. CI is running separately and was not awaited.

2026-09-29 follow-up repair on 95e565b528

#29501: the prepared numeric consumer binder now converts non-direct string expressions for SUM, AVG, ABS, SIGN and SLEEP in the same DOUBLE domain already used for direct string parameters. This covers scalar-subquery and derived-column boundaries, including binary NULL rebinding, without another prepared execution path or state machine. Embedded SQL PREPARE and binary protocol cases exercised two values, NULL and recovery; the neighboring #25408 and #27443 families also passed.

#29499: CAST(YEAR AS BIT) uses the existing MORPC v101 expression capability gate. Placement chooses one CN if a worker only supports v100; send and receive recheck reject old workers; persisted expressions record a v101 floor. The combined protocol test covers v100/v101 and a non-YEAR CAST control. Full local pkg/sql/plan, pkg/sql/compile, pkg/pb/plan and pkg/sql/plan/function tests passed. Formatting and diff checks passed. These are local checks on the delivered commit; CI and an actual mixed-version cluster were not awaited or rerun.

@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 added kind/bug Something isn't working kind/enhancement kind/test-ci labels Sep 28, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Sep 28, 2026

@aptend aptend 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 exact head f5b8e9f, including the complete changed-file map, prepared execution/proof/template and remote filter paths, the design review record, and the newly added SQL oracle. There are no earlier human GitHub reviews or inline threads to close. Required CI is green but the new BVT currently records an incorrect SQL result.

[P1 correctness / regression-oracle blocker] test/distributed/cases/prepare/issue_29429_prepared_filter.result:73-86 expects rows two and three for k1=1 AND k2=\x27invalid\x27 on a composite INT primary key with only (1,2) and (1,3), and expects two warnings for a NULL second binding. Neither row has k2 equal to the text\x27s numeric value (0), and k2=NULL must not match or convert an internal key. The equivalent scalar control k2+0=? returns no rows. This is the serialized-composite-key-to-DOUBLE coercion path documented by #29463; the current PR adds a passing test oracle for the wrong result rather than closing it. Repro: run the added SQL at lines 42-58, bind @first=1, then @second=\x27invalid\x27, NULL and 3 on the same prepared handle; the committed result shows two false-positive rows and internal-key warnings before the safe binding. This can silently return incorrect query results in prepared composite-key lookups, including application paths using server-side prepares. Please keep the original scalar comparison when the current binding changes the serialized key domain, correct this SQL/result oracle (including warnings), and rerun the safe/unsafe/NULL/safe sequence through SQL and binary protocol before re-review. The pre-PR issue being inherited does not make a newly committed incorrect expected result acceptable.

Use one typed prepared execution route and one bounded runtime cache. Preserve parameter ordinals and source metadata before overload and key lowering, renew diagnostic proof for every execution and retry, and remove the dual templates and QUERY late-Fill fallback.

Repair shared arithmetic, JSON and opaque-state consumer contracts exposed by actual source types. Validate SQL and binary protocol recovery, two-CN BVT, race and incremental static checks. Three clean NVMe TPCC pairs reach 102.59% of the direct parent throughput with zero errors; sampled CPU per transaction falls about 9%.
@XuPeng-SH
XuPeng-SH force-pushed the fix/29429-block-filter-perf branch from cd145e1 to 968b2ca Compare September 29, 2026 14:47

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 kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

4 participants