Skip to content

fix(vector): restore safe distributed filtered PRE scans - #29538

Merged
XuPeng-SH merged 11 commits into
mainfrom
perf/29531-filtered-pre-read-cost
Oct 1, 2026
Merged

XuPeng-SH merged 11 commits into
mainfrom
perf/29531-filtered-pre-read-cost

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement

Which issue(s) this PR fixes:

Fixes #29531

What this PR does / why we need it:

Root cause and design

A required-membership IVF PRE scan on main is forced onto one CN. When the decoded entries exceed that CN's memory cache, repeated queries read and convert the same objects from disk. The 4.2 distributed path uses both CN caches. A controlled 40k × 128D, eight-object fixture reproduces the reported class of regression without the full nightly dataset. Increasing main's cache or restricting 4.2 to one CN independently reverses the result.

Restore distributed execution for the proven scalar, synchronous, single-round integer-PK PRE shape. Reuse the existing complete broadcast SEMI build, runtime-filter MessageBoard, object sharding and downstream Top merge. Validate complete producer/consumer coverage and reject partial, duplicate, shuffle or disconnected sources. Preserve CN identity and coordinator ownership of workspace rows. Use a private CPU centroid route within the existing cache/admission lifecycle.

Reuse the existing reader policy to suppress full data-object preloads for filtered entry scans, preserving inherited policy, tombstones and ordinary scans. No production insert, flush, merge, writer, encoding or persistent data-layout changes.

The final-plan qualifier is shared by exec-type selection and compilation. It also recognizes the generated optional root PK filter for plain row fetches (including CAST and ABS predicates), validating exact build/probe ownership and pruned PK lineage. Existing HashBuild optional-filter admission and PASS fallback remain the owners; no second filter state machine is introduced. Regular INDEX scans keep their scan-local ForceOneCN flags; only the proven generated access tree is exempt from the query-wide veto. Unknown work/shapes, fewer than two objects, GPU centroid dispatch, incompatible or unknown worker versions remain local for the entire query.

Capability 103 is enforced at placement, fragment encoding, actual destination, same stream and decoding. Existing admission may advance its persisted authoring floor after running a newer binary: restarting an old 102 binary is not a supported rollback after that floor has advanced. Do not edit that floor to downgrade. Reverting placement while retaining a compatible binary restores local execution.

Validation

Current rebased base: 6d4957b395df919d201cc84ae60e40bb7b637657. Current head: a4a51b2e766275983158e73160824ac5118270bb.

Fresh review/QA on the current source (Go 1.26.4, Darwin arm64 CPU):

  • Full plan, compile, ivfflat UT PASS (7.517s / 7.111s / 0.771s); exact-source binary build PASS.
  • Focused generation, admission/failure, topology and protocol race checks, count=2, PASS. Explicitly reject protocol 101 and 102; accept 103.
  • Test-owned two-CN black-box challenge: 35 checks PASS against independent source ID/distance oracles. Both ingress CNs, CAST/ABS/NULL-IN, offset, empty/small domains, regular INDEX, persisted and memory rows/deletes, prepared NULL/rebind, transaction rollback and concurrent distinct domains. Eligible plans assert actual readers=2; database/catalog cleanup verified; services stopped.
  • License-eye: all 29 changed Go files valid. Rebase preserves the original patch series apart from protocol 102 → 103, with its boundary test and documentation updated.

Earlier broad validation below was recorded on main base 9990e0e7155aa63bc74b697b5d605efce70e2460, source b1cb1b9a4f0940ff12857287a46d1e3aa7932ca4; it is retained as historical/reused evidence, not a fresh head-wide run. Earlier timing/4.2/GPU/nightly limits remain as described below.

  • Final merged full plan/compile normal UT: PASS (7.317s/4.078s); full race UT: PASS (40.744s/5.867s). Build driver is GOMAXPROCS=2 -p 2; test runtime is 4 to preserve existing compile fanout contracts.
  • Final merged frontend selection ^(TestViewMetadataCache.*|TestCheckModifyValidatesCatalogDependencies)$: six nonempty top-level tests PASS, covering retained snapshots, dependency deduplication, missing/version/identity changes and publisher remapping.
  • Incremental SCA: gofmt clean; pinned golangci-lint 2.6.2, --new-from-rev origin/main, 0 issues, exit 0; repository molint, exit 0, with 11 diagnostics in eight files byte-identical to tested main (zero changed-file diagnostics). Closure: defines, sql/plan, sql/compile, vectorindex/ivfflat, vectorindex/sqlexec, disttae, readutil, blockio.
  • Final Go 1.26.4 / CPU / GOAMD64=v3 / GOEXPERIMENT=simd binary build: PASS, embeds the final source SHA above.
  • Final two-CN public smoke: PASS on a regenerated 40k-row fixture, without rerunning comparative timing; earlier same-object performance evidence below is reused. Ten query vectors pass the source oracle; twenty ordinary INDEX queries on one connection return identical corresponding results. CAST, ABS, NULL-containing IN and query-vector CAST each repeat three times on the same connection with consistent results and EXPLAIN readers=2; empty domain returns no rows.
  • Existing ten vector BVT cases run twice on the final binary in the same owned instance, with unchanged cases/expected output, normal CI-compatible comparison (nometa ignore pprof): each 414 total, 413 success, 1 existing script-marked ignore, 0 failures, 0 abnormal. Includes IVF PRE/POST/include/DML synchronization, f64, quantization/upcast, distance ranges and TopK consumers. Test-owned services are stopped after validation.
  • Earlier complete Q1 normal/race UT: sqlexec, disttae, readutil, blockio, ivfflat. Placement/protocol/reader gates include owning plan, compile, ivfflat and defines packages. Unchanged closures reuse their completed evidence.
  • Deterministic QA covers required versus optional PASS, cancel/error/empty completion, broadcast merger and complete domain, duplicate/missing/disconnected edges, nonzero coordinator and real nonempty reader ownership, protocol 103/102/101/unknown and decode checks, regular INDEX remapping, CPU centroid routing/cache isolation, pruned PK slots and unsupported shapes.
  • Public SQL checks use independent source membership, ID uniqueness and distance order. Repeated INDEX, CAST, ABS, NULL-containing IN, query-vector CAST and empty-domain queries validate results and distributed eligibility.

Local gate commands (repo CGo wrapper controls matching native artifacts):

GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -p 2 \
  -exec 'env GOMAXPROCS=4' -count=1 -timeout=300s ./pkg/sql/plan ./pkg/sql/compile
GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -race -p 2 \
  -exec 'env GOMAXPROCS=4' -count=1 -timeout=300s ./pkg/sql/plan ./pkg/sql/compile
GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -p 2 -v \
  -exec 'env GOMAXPROCS=4' -count=1 -timeout=300s \
  -run '^(TestViewMetadataCache.*|TestCheckModifyValidatesCatalogDependencies)$' ./pkg/frontend
# Incremental package list is the eight-package closure above.
golangci-lint run --concurrency 2 --timeout 10m -c .golangci.yml \
  --new-from-rev origin/main <incremental-packages>
go vet -mod=readonly -p 2 -vettool=<repo-molint> <incremental-packages>
GOMAXPROCS=2 make build-with-prebuilt-native GOBUILD_OPT=-p=2

Reproduction recipe: two CPU CNs, shared memory cache 16 MiB each, query sessions with ivf_preload_entries=0 and probe_limit=5. Create wiki_domain(id BIGINT PRIMARY KEY, file_id BIGINT, embedding VECF32(128)), insert 40k deterministic vectors in eight batches of 5k, assign file_id = 20000000 + id % 50, create the ordinary file_id index and synchronous IVF flat index (lists=64, vector_l2_ops), and flush the entries table between batches. Run ten changing query vectors with WHERE file_id=20000000 ORDER BY l2_distance(embedding, <vector>) LIMIT 10 BY RANK WITH OPTION 'mode=pre'. EXPLAIN ANALYZE must show two entry readers with complete required membership. Use CAST(file_id AS BIGINT)=20000000 and ABS(file_id)=20000000 as non-index access controls. Within each binary comparison preserve the exact objects; use 64 MiB and one eligible CN as independent cache/placement counterfactuals. Cross-version objects are separate and only logical source data is shared.

Performance and limits

The following sequential local experiments retain probe, domain, query vectors and budgets within each comparison:

Control Baseline QPS Candidate/control QPS Observation
Causal fixture: main vs 4.2, 16 MiB, two eligible CNs 32.63 main 191.09 4.2 5.86× gap; main readers=1
Same main objects, cache 16 → 64 MiB 32.63 206.20 Repeated disk-cache reads 1464 → 0; entry time 33.47 → 1.75 ms
Same 4.2 objects, one → two eligible CNs 27.52 191.09 6.94×; second CN has real entry-cache activity
Placement fix, original main objects, 16 MiB 32.63 146.36 4.49×; readers=2; entry time 1.90 ms
CAST predicate, same regenerated objects before/after outer-PK qualification 31.07 124.60 4.01×; readers 1 → 2; entry time 26.05 → 1.66 ms
ABS predicate, same regenerated objects before/after outer-PK qualification 29.58 144.15 4.87×; readers 1 → 2; entry time 29.14 → 1.57 ms

All ten Top10 sets match in the original placement comparison; all twenty CAST/ABS sets match their corresponding before/after comparison. Independent source checks verify membership, uniqueness and distance order. The small fixture's recall is equal across versions; it is not the original nightly recall. CAST/ABS candidate runs measure zero disk-cache/S3 reads on both CNs. The original final indexed run has coordinator disk-cache reads=0 and remote=27 including background activity; an earlier placement candidate separately has zero on both. FileService logical extent size is not physical I/O, and conversion counters are not a decompression profile.

The ordinary indexed control around the CAST/ABS fix is 175.41 → 167.22 median QPS, with overlapping round ranges (167.41–176.66 versus 155.51–173.76). This shared-machine result does not establish a stable change for that control. Original-object indexed performance above uses the earlier finalized placement binary; the latest merged binary revalidates the same unchanged placement path through public smoke, rather than rerunning the entire comparative matrix.

A same-candidate, same-object hot-cache control measures 246.01 QPS with one eligible CN versus 183.49 with two: 25.4% lower throughput and about 1.385 ms additional time per SQL. The fixed distributed compilation, broadcast and RPC overhead is material for this small fully cached workload. This change does not promise a universal speedup.

Broadcast retains complete keys per CN and each shard's full candidate budget B, yielding a union bounded by P×B before the existing Top merge. Residual predicates may see more candidates than a single local B window. Centroid metadata is replicated. These costs use existing admission and cleanup owners.

Versions run sequentially with bounded resources. The machine has unrelated workloads, so results are causal local evidence, not an isolated capacity claim. The original 10M × 768D nightly and physical GPU execution are not verified by this local run. See docs/design/ivf_filtered_pre_read_cost.md for contracts, qualification and counterexamples.

Design: GPT-6-astra xhigh. Independent source/QA review: GPT-6.1-sol xhigh. CI status is separate from local validation.

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

Commit review: a4a51b2

Base/merge-base: 6d4957b395df919d201cc84ae60e40bb7b637657. Complete 31-file diff, related planner/compiler/reader/cache/protocol ownership and PR comments reviewed; no subagents used.

Conclusion: no newly verified merge blocker. This is a self/delivery commit review, not a second person's approval.

Design and engineering

  • Reader policy uses existing FileService flags and request/context ownership. The scanner ORs inherited flags without changing the session context; readutil retains the existing threshold; both scalar loader branches receive policy; data prefetch is suppressed while remote tombstone prefetch/cursor behavior remains intact.
  • Required PRE uses the existing complete broadcast SEMI build, MessageBoard, stable object partitioning and downstream Top. The final plan qualifier is shared by execution selection and compilation. It proves PK lineage/source identity and the generated INDEX/optional outer PK dependencies instead of introducing another filter state machine.
  • Generation construction seals domain/snapshot/centroid route before publication. Existing admission, references, Close and failure unwind remain owners. Remote/coordinator ownership is retained when the initiating CN's stable ordinal is nonzero.
  • Protocol requirement is now 103 after rebase, with maximum nested requirement, selected-worker check, actual-destination check, same-stream handshake and receiver validation. Required membership never silently becomes PASS. Old/unknown workers fall back for the whole query before construction; a later capability change rejects the execution.
  • CPU centroid routing uses the existing constructor/cache/admission lifecycle and an immutable cache discriminator. GPU-selected routes remain local. Physical GPU execution was not locally exercised.
  • Production delta +759/-73 (net +686); tests +907/-126 (net +781); docs +308. Most production growth is the plan qualification and physical topology proof. The breadth is justified by admitting distributed required membership, but these two validators should remain the common owners; future extensions should not add parallel scheduling/filter state. Tests reuse existing fixtures and add distinct negative, ownership, protocol and policy oracles.

Fresh QA on this exact source

  • Go 1.26.4, Darwin arm64 CPU, matching verified native inputs: full pkg/sql/plan (7.517s), pkg/sql/compile (7.111s), pkg/vectorindex/ivfflat (0.771s), exit 0. Linked binary build succeeds and embeds this commit.
  • Focused race challenge, count=2: distributed reader identity/memory ownership, shared generation, admission/construction failure, required topology/broadcast/remote fragment, protocol 101/102 rejection and 103 support, whole-query old/unknown/canceled fallback, and outer PK build merging; both owning packages exit 0 (3.090s / 3.089s). Existing required-PASS/cancellation tests also pass in the full compile run.
  • New test-owned two-CN public SQL challenge: 35 checks pass, with a 2,000-row fixture, eight persisted entry objects, lists=1/probe=1 and an independent Python source-distance/ID oracle. Includes both ingress CNs, direct/CAST/ABS/NULL-IN predicates, LIMIT/OFFSET, small/empty domains, L2/squared units, ordinary secondary INDEX, committed memory rows plus deletes, prepared NULL followed by valid rebind, own uncommitted row/rollback, and 12 concurrent requests with different domains. Major eligible plans assert actual readers=2; results assert exact IDs, uniqueness, distance values and ordering. Database/catalog teardown verified.
  • Previously recorded same-object performance evidence is reused for the unchanged placement/read mechanism, not claimed as a new timing result on this head. No CI waiting.

Remaining non-blocking delivery note and limits

At intake, the PR body still said capability 102, old rollback floor 101, and final source b1cb1b9. Delivery metadata has now been corrected to capability 103, pre-capability 102, and current source/base; fresh QA is separated from historical/reused evidence. Committed design text also reflects 103. This delivery note is closed.

The acknowledged fully cached small-query control was 25.4% slower with two CNs. This is an accepted placement tradeoff, not universal acceleration. Broadcast duplicates domain/centroid state per CN, and candidates are bounded by P×B; mixed workloads and the original 10M×768D nightly/GPU deployment are not newly benchmarked here. Cold/expired planning also gains the existing hidden-table Stats lookup when the local-DOP hint is absent.

Comment status

At review intake there are 0 inline comments and 0 review threads, hence no unaddressed code-comment requests. The sole general bot comment says its review subscription is paused; the existing human approval is on the previous head. This review is bound to the current commit.

@XuPeng-SH
XuPeng-SH merged commit ec7a5b1 into main Oct 1, 2026
26 of 27 checks passed
@XuPeng-SH
XuPeng-SH deleted the perf/29531-filtered-pre-read-cost branch October 1, 2026 00:51

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Main IVF filtered PRE is 4-7x slower than 4.2 at comparable recall (Wiki 10M)

3 participants