Files
f929d68ba6 test: clear the ruff baseline in tests/ so the lint gate reflects the PR under review (#52115)
issue: #52114

Makes `ruff check` and `ruff format --check` pass over all of `tests/`,
so the `Ruff (changed files only)` job stops failing PRs for violations
they did not introduce (most recently #51903, which got 69 errors from
an 8-line change).

Almost all of this is mechanical. The behavioural changes are called out
individually below: one `NameError` fix, three shadowed duplicate
definitions, 13 assertion gaps, and two undefined names that only became
visible once star imports were expanded.

### Layout

Seven reviewable commits:

| commit | what | files |
|---|---|---|
| 1 | `ruff format` | 170 |
| 2 | `ruff check --fix` (safe fixes only, no `--unsafe-fixes`) | 156 |
| 3 | F821 fix + `tests/ruff.toml` | 4 |
| 4 | three shadowed duplicate definitions | 4 |
| 5 | close 13 assertion gaps behind F841 | 7 |
| 6 | expand star imports, re-enable F403/F405/F821 | 33 |
| 7 | enable E402, E712, E722 | 16 |

1745 violations → 0. Only `tests/` is touched.

### The undefined-name bug

`chaos/test_chaos_memory_stress.py`:
`TestMemoryStressReplica.prepare_collection` referenced bare `nb` and
`dim`. Those are class attributes, never module-level names, so the
fixture raised `NameError` the moment it ran — and the line directly
above it already used `self.dim`. Changed to `self.nb` / `self.dim`.
This was the only F821 in `tests/`; **the rule stays enabled**.

### Three shadowed duplicate definitions

Three places define the same name twice in the same scope. Python keeps
the later one, so the earlier definition is dead while still reading as
live code — a test that looks like it exists and never runs.

**`restful_client/testcases/test_vector_operations.py` —
`TestDeleteVector`**

```python
@pytest.mark.L0
class TestDeleteVector(TestBase):          # line 778 — shadowed, never ran
    def test_delete_vector_default(...)    # 2x2 parametrized

@pytest.mark.L1
class TestDeleteVector(TestBase):          # line 838 — wins
    def test_delete_vector_with_invalid_api_key(...)
    def test_delete_vector_with_invalid_collection_name(...)
    def test_delete_vector_with_non_primary_key(...)
```

The second holds only negative cases, and the file already uses
`TestInsertVectorNegative` / `TestSearchVectorNegative`, so this is a
copy whose class name was never updated. Renamed it to
`TestDeleteVectorNegative`.

**This is the one to look at:** it brings back an `L0` case, so 4
parametrizations of `test_delete_vector_default` start running in PR CI.
They have never executed, so if the restful delete path has drifted
since they were written, this is where it surfaces.

**`python_client/testcases/test_compaction.py` —
`test_compact_after_delete`**

Defined twice in `TestCompactionParams`, covering different things: the
shadowed one (L3, `@parametrize("delete_pos", [1, tmp_nb // 2])`) covers
*partial* deletes plus a compaction-plan check; the surviving one (L2)
deletes everything. There is already a separate
`test_compact_after_delete_all`, so partial-delete coverage existed only
in the shadowed case and was not running. Renamed it to
`test_compact_after_delete_partial`; the surviving definition is
untouched.

**`python_client/utils/util_pymilvus.py` — `add_vector_field`**

Defined twice with different signatures:

```python
def add_vector_field(entities, is_normal=False):     # line 455 — shadowed
    ...
    entities.append(field)
    return entities

def add_vector_field(nb, dimension=default_dim):     # line 527 — wins
    field_name = gen_unique_str()
    field = {...}          # built, then discarded
    return field_name      # returns only the name
```

Removed the second — both the broken one and the one that was winning.
Grepped the whole repo: **neither definition has a caller**; every
`add_vector_field` hit is something else
(`test_milvus_client_add_vector_field` test methods, the
`Op.add_vector_field` enum member in `chaos/checker.py`, a `Checker`
method of the same name). Dead-code removal, not an API change.

**Net effect on what executes:** `test_delete_vector_default` ×4
(**L0**) and `test_compact_after_delete_partial` ×2 (L3) start running;
nothing stops running; the 3 negative cases keep running under the new
class name. Computed by parsing each file before and after and resolving
shadowing the way Python does, not by reading the diff.

F811 is now clean across `tests/` with no per-file suppressions.

### Star imports expanded, F403/F405/F821 re-enabled

33 of 307 files used `from utils.util_pymilvus import *` and friends.
Inside those, pyflakes cannot tell a typo from a star-imported name — it
downgrades everything unresolved to F405, and **F821 never fires**. The
`NameError` fixed in commit 3 was only catchable because that file
happens not to use a star import.

The 379 F405 hits were only **58 distinct names**. All are now explicit,
resolved by walking the star modules in source order (later import wins,
matching Python). Names that `util_pymilvus` merely re-exports come from
their real source now — `DataType` from `pymilvus`, `np` from `numpy`,
`log` from `utils.util_log` — rather than being laundered through it.

Turning F821 on immediately caught **two real undefined names**, both in
`rate_limit/test_rate_limit.py` (L3, so it has never run in CI):

```python
for collection_num in range(collectionRateLimit):   # no such name
#                          ^ the parametrize arg is `collection_rate_limit`, and it is
#                            a string ("10"/"500"), so range() needs int().
#                            The same test uses the correct name 30 lines below.

mil.uninstall(release_name, namespace=NAMESPACE)    # no such name
#  ^ MilvusOperator.uninstall has exactly this signature, and other suites do the
#    same under `mic`/`milvus_op` — the instantiation was just missing.
```

Both fixed. `test_milvus_client_data_integrity_new.py` needed 15 `noqa`
markers instead: its `prepare_data` fixture injects those names via
`globals()[field] = ...`, which no static analysis can follow. That
block has other problems — a `float is None` check against the builtin,
an always-true `if "is null" or "IS NULL" in expression`, leftover
`binbin_debug1` logging — but rewriting fixture logic does not belong
here; noted in #52116.

### 13 assertion gaps closed

Of ~80 F841 hits, most are harmless scratch values. 13 were a call whose
result was bound and then never checked. Highlights:

- `test_milvus_client_database.py`: two tests apply a non-existent
property key (`data.replica.number`, note `data.` not `database.`),
describe the database, and drop it without checking anything. Their
docstrings say `actual: run successfully` / `nothing changed` — the
intent was to prove nothing changed. Now asserted.
- `test_milvus_client_alias.py`: two assertions were commented out,
**and they were commented out for a reason** — `list_aliases()[0]`
returns a dict, so `assert alias in aliases` would have tested dict
keys. Rewritten against `[0]["aliases"]` (how the rest of the file does
it) and re-enabled. In the skipped `alias_default` test the calls were
also missing the required `collection_name` argument.

The remaining ~65 F841 stay, and the rule stays off.

### E402, E712, E722 also enabled

**E722** (37 sites): mechanical `except:` → `except Exception:`. Checked
the two ways this could change behaviour, both empty: no bare-except
try-block can raise `SystemExit`/`KeyboardInterrupt`, and **none calls
`pytest.skip`/`fail`/`xfail`**. That second one matters — pytest's
`Skipped` derives from `BaseException`, so a bare except silently eats
it while `except Exception` would not. 0 of 37, so behaviour is
unchanged.

**E402** (5 sites): imports that were just in the wrong place — `import
re` sat 70 lines into `check/param_check.py`, and the two
`resource_group` modules imported `rich` after their module-level
constants. Nothing to do with `sys.path`, which is what an earlier
version of this description wrongly claimed.

**E712** (5 sites), gone through one at a time rather than
bulk-rewritten:

| site | value | change |
|---|---|---|
| `test_milvus_client_partition.py` | `has_partition()` | → `is False` —
stricter than `not result`, which would pass on `None` |
| `test_restart.py` | JSON status flag | → `is True` |
| `test_restart.py` | local `break_flag` | → plain truth test, it is a
real bool |
| `test_query.py` | wrapper `check_result` | → `is True` |
| `test_milvus_client_ttl.py` | `hit.get(bool_field)` | **kept as `==
False` + noqa** |

That last one is the reason this rule cannot be bulk-fixed: `.get()`
returns `None` for a missing field, so `not ...` would pass exactly
where the assertion should fail, and `is False` would break on a numpy
bool.

### What ruff.toml still disables

| rule | n | reason |
|---|---|---|
| F841 | ~65 | tests deliberately keep call results; the 13 that were
genuine assertion gaps are fixed above |
| UP031 | 95 | pure style rewrite that catches no bugs, and 27 sites use
`% (...)` tuples where it is not equivalent |

Everything else pyflakes/pycodestyle checks is on, including `F401`,
`F811` and `F821`, so new code cannot introduce dead, duplicate or
undefined names. Tracked in #52116.

### Verification

Not just "ruff is green" — the mechanical passes were checked for
semantic drift:

- **Format pass:** parsed all 307 files before and after and compared
ASTs with string constants normalized away → **zero structural
differences**. The only AST-visible deltas are 146 string-constant
changes, every one whitespace-only (docstring indentation / trailing
whitespace); zero non-whitespace string changes.
- **Import removals:** 142 imports were dropped. For each, checked
whether the bound name still appears anywhere in its file. 115 have no
remaining reference at all. The 27 that still matched textually were
each read by hand and are all comments (`# pdb.set_trace()`, the
commented-out checker dict in `test_load_with_checker.py`), docstring
prose (`"input random collection name"`, `"Tuple[List[Dict]]"`), string
literals (`"Collection ID"`, the `"config"` dict key), a different
binding (`from time import sleep`), or attribute access through another
module (`ct.CaseLabel`, `np.random`). **No real reference was removed.**
- **Python version:** the pyupgrade rewrites emit `datetime.UTC` (3.11+)
and `X | None` (3.10+). `tests/.python-version` is 3.12,
`tests/scripts/python-env.sh` defaults to 3.12, and
`tests/docker/Dockerfile` is `python:3.12-bullseye`.
- **`compileall`** over all 307 files under Python 3.12 passes.
- No external reference to `TestDeleteVector`,
`test_compact_after_delete`, or `add_vector_field` exists anywhere in
the repo (`*.py`, `*.sh`, `*.yaml`, `*.json`).

### Conflict surface

Of the 100 currently-open PRs, 9 touch `tests/*.py` and only **2**
overlap with this change: #51903 (3 of its 5 files) and #51856 (1 file).
The other 7 touch files that were already format-clean. Worth merging
promptly to keep that number small.

`.pre-commit-config.yaml` needs no change — it already runs with
`--config=tests/ruff.toml`, so local hooks and CI stay in sync.

---------

Signed-off-by: xiaofanluan <xf@hjjaq.com>
Co-authored-by: xiaofanluan <xf@hjjaq.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 14:54:18 +08:00

401 lines
17 KiB
Python

import time
import pandas as pd
import pytest
from base.client_base import TestcaseBase
from common import common_func as cf
from common.common_type import CaseLabel, CheckTasks
from common.phrase_match_generator import PhraseMatchTestGenerator
from pymilvus import CollectionSchema, DataType, FieldSchema
from utils.util_log import test_log as log
prefix = "phrase_match"
def init_collection_schema(dim: int, tokenizer: str, enable_partition_key: bool) -> CollectionSchema:
"""Initialize collection schema with specified parameters"""
analyzer_params = {"tokenizer": tokenizer}
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(
name="text",
dtype=DataType.VARCHAR,
max_length=65535,
enable_analyzer=True,
enable_match=True,
is_partition_key=enable_partition_key,
analyzer_params=analyzer_params,
),
FieldSchema(name="emb", dtype=DataType.FLOAT_VECTOR, dim=dim),
]
return CollectionSchema(fields=fields, description="phrase match test collection")
@pytest.mark.tags(CaseLabel.L0)
class TestQueryPhraseMatch(TestcaseBase):
"""
Test cases for phrase match functionality in Milvus using PhraseMatchTestGenerator.
This class verifies the phrase matching capabilities with different configurations
including various tokenizers, partition keys, and index settings.
"""
@pytest.mark.parametrize("enable_partition_key", [True])
@pytest.mark.parametrize("enable_inverted_index", [True])
@pytest.mark.parametrize("tokenizer", ["standard", "jieba", "icu"])
def test_query_phrase_match_with_different_tokenizer(self, tokenizer, enable_inverted_index, enable_partition_key):
"""
target: Verify phrase match functionality with different tokenizers (standard, jieba)
method: 1. Generate test data using PhraseMatchTestGenerator with language-specific content
2. Create collection with appropriate schema (primary key, text field with analyzer, vector field)
3. Build both vector (IVF_SQ8) and inverted indexes
4. Execute phrase match queries with various slop values
5. Compare results against Tantivy reference implementation
expected: Milvus phrase match results should exactly match the reference implementation
results for all queries and slop values
note: Test is marked to xfail for jieba tokenizer due to known issues
"""
# Initialize parameters
dim = 128
data_size = 3000
num_queries = 10
analyzer_params = {"tokenizer": tokenizer}
# Initialize generator based on tokenizer
language = "zh" if tokenizer == "jieba" else "en"
generator = PhraseMatchTestGenerator(language=language)
# Create collection
collection_w = self.init_collection_wrap(
name=cf.gen_unique_str(prefix),
schema=init_collection_schema(dim, tokenizer, enable_partition_key),
consistency_level="Strong",
)
# Generate test data
test_data = generator.generate_test_data(data_size, dim)
df = pd.DataFrame(test_data)
log.info(f"Test data: \n{df['text']}")
# Insert data into collection
insert_data = [{"id": d["id"], "text": d["text"], "emb": d["emb"]} for d in test_data]
collection_w.insert(insert_data)
collection_w.flush()
# Create indexes
collection_w.create_index(
"emb",
{"index_type": "IVF_SQ8", "metric_type": "L2", "params": {"nlist": 64}},
)
if enable_inverted_index:
collection_w.create_index("text", {"index_type": "INVERTED", "params": {"tokenizer": tokenizer}})
collection_w.load()
# Generate and execute test queries
test_queries = generator.generate_test_queries(num_queries)
for query in test_queries:
expr = f"phrase_match(text, '{query['query']}', {query['slop']})"
log.info(f"Testing query: {expr}")
# Execute query
results, _ = collection_w.query(expr=expr, output_fields=["id", "text"])
if tokenizer == "standard":
# Get expected matches using Tantivy
expected_matches = generator.get_query_results(query["query"], query["slop"])
# Get actual matches from Milvus
actual_matches = [r["id"] for r in results]
if set(actual_matches) != set(expected_matches):
log.info(f"collection schema: {collection_w.schema}")
for match_id in expected_matches:
# query by id to get text
res, _ = collection_w.query(expr=f"id == {match_id}", output_fields=["text"])
text = res[0]["text"]
log.info(f"Expected match: {match_id}, text: {text}")
for match_id in actual_matches:
# query by id to get text
res, _ = collection_w.query(expr=f"id == {match_id}", output_fields=["text"])
text = res[0]["text"]
log.info(f"Matched document: {match_id}, text: {text}")
# Assert results match
assert set(actual_matches) == set(expected_matches), (
f"Mismatch in results for query '{query['query']}' with slop {query['slop']}"
)
else:
log.info(
"Tokenizer is not standard, verify phrase match results by checking all query tokens in result"
)
for result in results:
text = result["text"]
tokens = self.get_tokens_by_analyzer(query["query"], analyzer_params)
for token in tokens:
if token not in text:
log.info(f"Token {token} not in text {text}")
assert False
@pytest.mark.parametrize("enable_partition_key", [True])
@pytest.mark.parametrize("enable_inverted_index", [True])
@pytest.mark.parametrize("tokenizer", ["standard"])
def test_phrase_match_as_filter_in_vector_search(self, tokenizer, enable_inverted_index, enable_partition_key):
"""
target: Verify phrase match functionality when used as a filter in vector search
method: 1. Generate test data with both text content and vector embeddings
2. Create collection with vector field (128d) and text field
3. Build both vector index (IVF_SQ8) and text inverted index
4. Perform vector search with phrase match as a filter condition
5. Verify the combined search results maintain accuracy
expected: The system should correctly combine vector search with phrase match filtering
while maintaining both search accuracy and performance
"""
# Initialize parameters
dim = 128
data_size = 3000
num_queries = 10
# Initialize generator based on tokenizer
language = "zh" if tokenizer == "jieba" else "en"
generator = PhraseMatchTestGenerator(language=language)
# Create collection
collection_w = self.init_collection_wrap(
name=cf.gen_unique_str(prefix),
schema=init_collection_schema(dim, tokenizer, enable_partition_key),
consistency_level="Strong",
)
# Generate test data
test_data = generator.generate_test_data(data_size, dim)
df = pd.DataFrame(test_data)
log.info(f"Test data: \n{df['text']}")
# Insert data into collection
insert_data = [{"id": d["id"], "text": d["text"], "emb": d["emb"]} for d in test_data]
collection_w.insert(insert_data)
collection_w.flush()
# Create indexes
collection_w.create_index(
"emb",
{"index_type": "IVF_SQ8", "metric_type": "L2", "params": {"nlist": 64}},
)
if enable_inverted_index:
collection_w.create_index("text", {"index_type": "INVERTED", "params": {"tokenizer": tokenizer}})
collection_w.load()
# Generate and execute test queries
test_queries = generator.generate_test_queries(num_queries)
for query in test_queries:
expr = f"phrase_match(text, '{query['query']}', {query['slop']})"
log.info(f"Testing query: {expr}")
# Execute filter search
data = [generator.generate_embedding(dim) for _ in range(10)]
results, _ = collection_w.search(
data,
anns_field="emb",
param={},
limit=10,
expr=expr,
output_fields=["id", "text"],
)
# Get expected matches using Tantivy
expected_matches = generator.get_query_results(query["query"], query["slop"])
# assert results satisfy the filter
for hits in results:
for hit in hits:
assert hit.id in expected_matches
@pytest.mark.parametrize("slop_value", [0, 1, 2, 5, 10])
def test_slop_parameter(self, slop_value):
"""
target: Verify phrase matching behavior with varying slop values
method: 1. Create collection with standard tokenizer
2. Generate and insert data with controlled word gaps between terms
3. Test phrase matching with specific slop values (0, 1, 2, etc.)
4. Verify matches at different word distances
5. Compare results with Tantivy reference implementation
expected: Results should only match phrases where words are within the specified
slop distance, validating the slop parameter's distance control
"""
dim = 128
data_size = 3000
num_queries = 2
tokenizer = "standard"
enable_partition_key = True
# Initialize generator based on tokenizer
language = "zh" if tokenizer == "jieba" else "en"
generator = PhraseMatchTestGenerator(language=language)
# Create collection
collection_w = self.init_collection_wrap(
name=cf.gen_unique_str(prefix),
schema=init_collection_schema(dim, tokenizer, enable_partition_key),
consistency_level="Strong",
)
# Generate test data
test_data = generator.generate_test_data(data_size, dim)
df = pd.DataFrame(test_data)
log.info(f"Test data: {df['text']}")
# Insert data into collection
insert_data = [{"id": d["id"], "text": d["text"], "emb": d["emb"]} for d in test_data]
collection_w.insert(insert_data)
collection_w.flush()
# Create indexes
collection_w.create_index(
"emb",
{"index_type": "IVF_SQ8", "metric_type": "L2", "params": {"nlist": 64}},
)
collection_w.create_index("text", {"index_type": "INVERTED"})
collection_w.load()
# Generate and execute test queries
test_queries = generator.generate_test_queries(num_queries)
for query in test_queries:
expr = f"phrase_match(text, '{query['query']}', {slop_value})"
log.info(f"Testing query: {expr}")
# Execute query
results, _ = collection_w.query(expr=expr, output_fields=["id", "text"])
# Get expected matches using Tantivy
expected_matches = generator.get_query_results(query["query"], slop_value)
# Get actual matches from Milvus
actual_matches = [r["id"] for r in results]
if set(actual_matches) != set(expected_matches):
log.info(f"collection schema: {collection_w.schema}")
for match_id in expected_matches:
# query by id to get text
res, _ = collection_w.query(expr=f"id == {match_id}", output_fields=["text"])
text = res[0]["text"]
log.info(f"Expected match: {match_id}, text: {text}")
for match_id in actual_matches:
# query by id to get text
res, _ = collection_w.query(expr=f"id == {match_id}", output_fields=["text"])
text = res[0]["text"]
log.info(f"Matched document: {match_id}, text: {text}")
# Assert results match
assert set(actual_matches) == set(expected_matches), (
f"Mismatch in results for query '{query['query']}' with slop {slop_value}"
)
def test_query_phrase_match_with_different_patterns(self):
"""
target: Verify phrase matching with various text patterns and complexities
method: 1. Create collection with standard tokenizer
2. Generate and insert data with diverse phrase patterns:
- Exact phrases ("love swimming and running")
- Phrases with gaps ("enjoy very basketball")
- Complex phrases ("practice tennis seriously often")
- Multiple term phrases ("swimming running cycling")
3. Test each pattern with appropriate slop values
4. Verify minimum match count for each pattern
expected: System should correctly identify and match each pattern type
with the specified number of matches per pattern
"""
dim = 128
collection_name = f"{prefix}_patterns"
schema = init_collection_schema(dim, "standard", False)
collection = self.init_collection_wrap(name=collection_name, schema=schema, consistency_level="Strong")
# Generate data with various patterns
generator = PhraseMatchTestGenerator(language="en")
data = generator.generate_test_data(3000, dim)
collection.insert(data)
# Test various patterns
test_patterns = [
("love swimming and running", 0), # Exact phrase
("enjoy very basketball", 1), # Phrase with gap
("practice tennis seriously often", 2), # Complex phrase
("swimming running cycling", 5), # Multiple activities
]
# Generate and insert documents that match the patterns
num_docs_per_pattern = 100
pattern_documents = generator.generate_pattern_documents(
test_patterns, dim, num_docs_per_pattern=num_docs_per_pattern
)
collection.insert(pattern_documents)
df = pd.DataFrame(pattern_documents)[["id", "text"]]
log.info(f"Test data:\n {df}")
collection.flush()
collection.create_index(field_name="text", index_params={"index_type": "INVERTED"})
collection.create_index(
field_name="emb",
index_params={
"index_type": "IVF_SQ8",
"metric_type": "L2",
"params": {"nlist": 64},
},
)
collection.load()
time.sleep(1)
for pattern, slop in test_patterns:
results, _ = collection.query(
expr=f'phrase_match(text, "{pattern}", {slop})',
output_fields=["text"],
)
log.info(f"Pattern '{pattern}' with slop {slop} found {len(results)} matches")
assert len(results) >= num_docs_per_pattern
@pytest.mark.tags(CaseLabel.L1)
class TestQueryPhraseMatchNegative(TestcaseBase):
def test_query_phrase_match_with_invalid_slop(self):
"""
target: Verify error handling for invalid slop values in phrase matching
method: 1. Create collection with standard test data
2. Test phrase matching with invalid slop values:
- Negative slop values (-1)
- Extremely large slop values (10^31)
3. Verify error handling and response
expected: System should:
1. Reject queries with invalid slop values
2. Return appropriate error responses
3. Maintain system stability after invalid queries
"""
dim = 128
collection_name = f"{prefix}_invalid_slop"
schema = init_collection_schema(dim, "standard", False)
collection = self.init_collection_wrap(name=collection_name, schema=schema, consistency_level="Strong")
# Insert some test data
generator = PhraseMatchTestGenerator(language="en")
data = generator.generate_test_data(100, dim)
collection.insert(data)
collection.create_index(field_name="text", index_params={"index_type": "INVERTED"})
collection.create_index(
field_name="emb",
index_params={
"index_type": "IVF_SQ8",
"metric_type": "L2",
"params": {"nlist": 64},
},
)
collection.load()
# Test invalid inputs
invalid_cases = [
("valid query", -1), # Negative slop
("valid query", 10**31), # Very large slop
]
for query, slop in invalid_cases:
res, result = collection.query(
expr=f'phrase_match(text, "{query}", {slop})',
output_fields=["text"],
check_task=CheckTasks.check_nothing,
)
log.info(f"Query: '{query[:10]}' with slop {slop} returned {res}")
assert result is False