Skip to content

[core][python] Fix filtered PK vector search when part of a level is pruned - #11669

Open
liangjie3138 wants to merge 1 commit into
apache:masterfrom
liangjie3138:fix/pk-vector-search-pruned-level
Open

liangjie3138 wants to merge 1 commit into
apache:masterfrom
liangjie3138:fix/pk-vector-search-pruned-level

Conversation

@liangjie3138

Copy link
Copy Markdown
Contributor

Purpose

Linked issue: close #11668

In a primary-key table, multiple data files in the same LSM level share one ANN segment. When a filter prunes part of a level, the remaining files no longer exactly match the segment's full file list, so the valid ANN segment was dropped as stale—skipping matching rows in fast mode and falling back to raw scans in full/detail mode.

This PR fixes both Java and Python read paths:

  • Allow reusing an ANN segment when a filter is present and the remaining files in that level are a valid subset of the segment's sources (still strict for writes and unfiltered reads, and rejecting cross-level or conflicting segments).
  • In Python, skip rows from pruned files when building ANN include_row_ids and reading candidates.

Tests

  • PkVectorBucketIndexStateTest (Java unit tests for subset matching, cross-level upgrades, and overlap rejection)
  • PrimaryKeyVectorSearchTest#testFilteredVectorSearchWhenMultiFileLevelIsPruned (Java E2E with PK stats, BTree pruning, batch search, and DV)
  • primary_key_index_definitions_test.py (Python unit tests for subset matching, pruned-source exclusion, and cross-level rejection)

@liangjie3138
liangjie3138 force-pushed the fix/pk-vector-search-pruned-level branch from 017f0c6 to e4a6269 Compare December 3, 2026 09:13
}
Set<PrimaryKeyIndexSourceFile> available = new HashSet<>(sourceFiles);
return available.containsAll(desired);
}

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.

Nit: Because exactMatch (desired.equals(sourceMeta.sourceFiles())) is already false when containsAll is called, and both sourceFiles and desired are ordered by fileName with unique file names:

  1. A pruned subset match must have sourceFiles.size() > desired.size() (if sourceFiles.size() == desired.size() and !exactMatch, sourceFiles could only match desired as a HashSet if sourceFiles had out-of-order metadata, which should be rejected just like in the unfiltered path).
  2. We can validate that sourceFiles is strictly ordered by fileName and contains desired in a single linear two-pointer pass (matching PkSortedBucketIndexState#activeIntersection) without allocating a HashSet:
    private static boolean containsAll(
            List<PrimaryKeyIndexSourceFile> sourceFiles, List<PrimaryKeyIndexSourceFile> desired) {
        if (sourceFiles.size() <= desired.size()) {
            return false;
        }
        int desiredIndex = 0;
        for (int i = 0; i < sourceFiles.size(); i++) {
            PrimaryKeyIndexSourceFile source = sourceFiles.get(i);
            if (i > 0 && sourceFiles.get(i - 1).fileName().compareTo(source.fileName()) >= 0) {
                return false;
            }
            if (desiredIndex < desired.size() && desired.get(desiredIndex).equals(source)) {
                desiredIndex++;
            }
        }
        return desiredIndex == desired.size();
    }

for name, _ in sources)
subset_match = (not has_cross_level_active
and len(sources) >= len(desired)
and set(desired).issubset(sources))

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.

Nit: Similar to the Java side, when not exact_match, a pruned subset match must have strictly more source files than desired (len(sources) > len(desired)), and sources should be in strictly increasing file_name order (otherwise an out-of-order sources list of the same size is rejected when allow_pruned_sources=False but accepted as a subset_match when allow_pruned_sources=True):

                is_ordered = all(
                    sources[i - 1][0] < sources[i][0]
                    for i in range(1, len(sources)))
                subset_match = (not has_cross_level_active
                                and is_ordered
                                and len(sources) > len(desired)
                                and set(desired).issubset(sources))

if (allowPrunedSources) {
activeLevelByFile.put(dataFile.fileName(), dataFile.level());
}
if (PrimaryKeyIndexSourcePolicy.shouldRead(dataFile)) {

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.

Nit: In PrimaryKeyVectorRead, searchParameters passes split.dataSplit().dataFiles() (unfiltered) into fromActiveDataFiles, whereas searchBatchAsync passes activeFiles (pre-filtered by PrimaryKeyIndexSourcePolicy::shouldRead). Moving activeLevelByFile.put(...) inside if (PrimaryKeyIndexSourcePolicy.shouldRead(dataFile)) ensures activeLevelByFile is populated identically regardless of whether the caller pre-filtered activeDataFiles.

continue
if not _allowed(context[0], source.file_name, row_position):
if not _allowed(context[0], source.file_name, row_position,
active_files=context[2]):

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.

Nit: This loop is now identical to _localized_candidates in primary_key_vector_read.py and can be simplified to:

        for future, context in zip(futures, contexts):
            candidates.extend(_localized_candidates(
                future.result(), context[0], context[1], deleted_positions,
                active_files=context[2]))

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

I ran the 39 focused Core tests, 24 Python tests, and four Native PK interoperability cases on e4a6269a3b. They passed.

[P1] Preserve raw fallback when Native reads a transported Python plan. For an ANN payload covering files A and B, when a predicate prunes A, the Python planner now keeps that payload, sends only B in the data split, and omits B from uncovered_data_files. The supported Python-to-Native plan path then revalidates the ANN with Rust 0.5.0's exact-source check. Rust drops that payload, and its transport validation also drops B because B is neither covered by a surviving ANN nor listed for raw fallback. A DETAIL read can therefore omit B entirely. I reproduced this with the Java golden fixture and one synthetic pruned source metadata entry. After pickling the plan, Python DETAIL returned [3] and Native DETAIL returned []. Native also returned [3] when the same surviving file was explicitly marked uncovered, as the pre-PR planner does. The same exact-match rule also leaves the original FAST behavior on the default Native single-vector path for REST tables. Please make the Native planner and transported reader understand the subset, or keep these plans on a reader that preserves their coverage. Python planner · Native transport validation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Primary-key vector search drops ANN segment when filters prune part of a level

3 participants