Skip to content

fix(vector_store): return stored metadata in MilvusCollection.search() (#1330) - #1343

Merged
ZohaibHassan16 merged 5 commits into
semantica-agi:mainfrom
mhaye9545:fix/issue-1330-milvus-search-metadata
Sep 19, 2026
Merged

ZohaibHassan16 merged 5 commits into
semantica-agi:mainfrom
mhaye9545:fix/issue-1330-milvus-search-metadata

Conversation

@mhaye9545

Copy link
Copy Markdown
Contributor

Closes #1330.

Summary

MilvusCollection.search() contained a stale comment claiming the collection schema only stores id and vector with no metadata field. That description was accurate once, but create_collection() has long defined a FieldSchema(name="metadata", dtype=DataType.JSON) at line 393.

As a result of the stale comment, search() hardcoded "metadata": {} in every result, silently discarding metadata that was actually stored — making it inconsistent with get_metadata() and filter_by_metadata(), which both request and return metadata correctly.

Changes

semantica/vector_store/milvus_store.py

MilvusCollection.search()

  1. Added output_fields=["metadata"] to the self.collection.search() call so the Milvus SDK returns the stored metadata field alongside each hit.
  2. Changed "metadata": {} → "metadata": hit.entity.get("metadata") or {} so callers receive the actual stored value. Falls back to {} for legacy records where the field is absent.
  3. Updated the comment to accurately describe the current schema.

tests/vector_store/test_milvus_store_search_metadata.py [new]

Four focused unit tests (no real Milvus connection needed — all collection calls are mocked):

Test What it checks
test_search_returns_stored_metadata Result dict contains the metadata that was stored
test_search_requests_metadata_output_field output_fields=["metadata"] is passed to the SDK
test_search_falls_back_to_empty_dict_when_metadata_is_none None entity value yields {}, not None
test_search_score_calculation Score formula and distance field are preserved unchanged

Verification

pytest tests/vector_store/test_milvus_store_search_metadata.py -v
4 passed in 11.59s

@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Return stored metadata from Milvus collection searches

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Return stored JSON metadata with Milvus vector search results.
• Preserve empty metadata fallback for legacy records.
• Add mocked regression coverage for metadata retrieval, SDK fields, and score behavior.
Diagram

sequenceDiagram
    actor Caller
    participant Wrapper as MilvusCollection
    participant Milvus as Milvus SDK
    participant Hit as Search Hit
    Caller->>Wrapper: Search vectors
    Wrapper->>Milvus: Request metadata field
    Milvus-->>Wrapper: Return entity hits
    Wrapper->>Hit: Read metadata
    Hit-->>Wrapper: Stored metadata
    Wrapper-->>Caller: Results with metadata
Loading
High-Level Assessment

Requesting the existing JSON field as part of the vector search is the most direct and efficient approach. A separate metadata lookup was considered but would add extra queries, latency, and consistency risk without benefit.

Files changed (2) +145 / -5

Bug fix (1) +6 / -5
milvus_store.pyReturn metadata from Milvus search hits +6/-5

Return metadata from Milvus search hits

• Requests the schema's 'metadata' field from the Milvus SDK and returns its stored value for each result. Missing or null metadata falls back to an empty dictionary while distance and score behavior remain unchanged.

semantica/vector_store/milvus_store.py

Tests (1) +139 / -0
test_milvus_store_search_metadata.pyAdd regression tests for Milvus search metadata +139/-0

Add regression tests for Milvus search metadata

• Adds mocked tests confirming stored metadata is returned, the SDK receives 'output_fields=["metadata"]', and null metadata falls back safely. Also protects existing score and distance calculations from regression.

tests/vector_store/test_milvus_store_search_metadata.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Canonical schema test fails ✓ Resolved 🐞 Bug ☼ Reliability
Description
The new hit.entity.get("metadata") access makes the existing Milvus canonical-schema test return a
truthy child MagicMock as metadata because that fixture never defines entity. Its required
dict assertion and subsequent {} equality assertion now fail, so the repository test suite
regresses despite the newly added focused tests passing.
Code

semantica/vector_store/milvus_store.py[212]

+                            "metadata": hit.entity.get("metadata") or {},
Evidence
The changed line returns the mock's truthy nested value unchanged. The existing fixture only sets
id and distance, while the shared schema assertion requires metadata to be a real dict and the
test explicitly expects {}.

semantica/vector_store/milvus_store.py[202-215]
tests/vector_store/test_search_result_schema.py[24-37]
tests/vector_store/test_search_result_schema.py[219-245]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Update the existing Milvus canonical-schema test fixture to model the entity returned when metadata is requested.
## Issue Context
A bare `MagicMock` produces a truthy `MagicMock` from `hit.entity.get("metadata")`, whereas the test intends to represent a hit with no metadata and expects `{}`.
## Fix Focus Areas
- tests/vector_store/test_search_result_schema.py[225-244]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Duplicate output_fields crashes search ✓ Resolved 🐞 Bug ≡ Correctness
Description
MilvusCollection.search() now passes output_fields explicitly and also expands caller-supplied
**options, so any existing call such as search_vectors(..., output_fields=["vector"]) raises a
duplicate-keyword TypeError instead of searching. The public Milvus search layers document and
forward arbitrary options, making this a regression for a previously valid SDK option.
Code

semantica/vector_store/milvus_store.py[R195-196]

+                output_fields=["metadata"],
             **options,
Evidence
The changed call supplies output_fields before expanding options, while both higher-level public
search methods forward arbitrary options unchanged; Python rejects the resulting duplicate keyword
before the SDK is called.

semantica/vector_store/milvus_store.py[175-197]
semantica/vector_store/milvus_store.py[253-286]
semantica/vector_store/milvus_store.py[529-576]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Avoid passing `output_fields` both explicitly and through `**options`; preserve caller-requested fields while always requesting metadata.
## Issue Context
`MilvusStore.search_vectors()` and `MilvusSearch.similarity_search()` forward arbitrary options to `MilvusCollection.search()`. Pop `output_fields` from options, add `metadata` if absent, and pass the merged list once.
## Fix Focus Areas
- semantica/vector_store/milvus_store.py[175-197]
- semantica/vector_store/milvus_store.py[253-286]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can describe a rule in plain language on the Rules page and Qodo drafts it for you

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread semantica/vector_store/milvus_store.py Resolved
Comment thread semantica/vector_store/milvus_store.py Resolved
@mhaye9545
mhaye9545 force-pushed the fix/issue-1330-milvus-search-metadata branch from 447430c to a64bc80 Compare August 31, 2026 13:01
@mhaye9545

Copy link
Copy Markdown
Contributor Author

Fixed both issues flagged by the Qodo review:

1. Duplicate output_fields crash — Instead of passing output_fields=["metadata"] as a separate keyword while also expanding **options (which could contain output_fields), the code now pops output_fields from options first and merges them: list({"metadata", *caller_fields}). This means any caller-supplied output_fields are preserved alongside metadata with no duplicate-keyword risk.

2. Canonical schema test — Added mock_hit.entity.get.return_value = None to the existing TestMilvusSearchSchema fixture. A bare MagicMock was returning a truthy child mock from .get("metadata"), which bypassed the or {} fallback. Now it correctly returns None, so the fallback yields {} as the test asserts.

All 16 tests pass (4 new focused tests + 12 existing schema tests).

@ZohaibHassan16 ZohaibHassan16 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core fix looks right.

There's one thing this broke though. TestVectorStoreDeepDive::test_milvus_store in tests/vector_store/test_vector_store_deepdive.py builds a Milvus mock hit with only .id and .distance set, no entity.get stub, same pattern that broke TestMilvusSearchSchema in test_search_result_schema.py. That one got the mock_hit.entity.get.return_value = None fix but this one didn't. Ran it: passes on main, fails on this branch with

AssertionError: <MagicMock name='mock.entity.get()' id=...> is not an instance of <class 'dict'>

Since MagicMock auto-attributes are truthy, hit.entity.get("metadata") or {} returns the mock itself instead of falling through to {}..

@zeekay zeekay left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The premise checks out, and the comment this replaces was the actually-wrong part. MilvusStore.create_collection defines the schema at milvus_store.py:388-394:

FieldSchema(name="id", dtype=DataType.VARCHAR, is_primary=True, ...),
FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=dimension),
FieldSchema(name="metadata", dtype=DataType.JSON),

So the comment at line 211 — "Milvus collection schema stores only id+vector; no metadata field is defined in create_collection()" — has been false for as long as that schema has existed, and search() was returning {} on the strength of it. The rest of the file already reads the field (output_fields at lines 656, 715, 773), which is what makes search() the odd one out: get_metadata() and filter_by_metadata() returned real values while search() returned nothing.

Popping output_fields out of **options before merging is the right call rather than an afterthought — collection.search(output_fields=..., **options) with a caller-supplied output_fields would have been a TypeError, and that's exactly the sort of thing that only shows up for the one user who passes it.

Test runs against current main (merged, the branch is behind): pytest tests/vector_store/ -m "not integration" — 345 passed, 84 skipped, 7 xfailed, against 341 passed on main. The four new tests are the difference.

Two small things I checked rather than assumed:

  • list({"metadata", *caller_fields}) has nondeterministic order, but the test asserts "metadata" in output_fields rather than list equality, so it won't flake. Worth keeping that assertion as-is if anyone edits it later.
  • The or {} fallback and the corresponding one-line update to test_milvus_search_canonical_schema keep the "legacy record with no metadata" path returning {} rather than None, so the result schema stays stable for existing callers.

I don't have write access on this repo, so I can't merge it — approving so a maintainer can.

@zeekay zeekay left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correcting my own approval above — @ZohaibHassan16 is right, and I missed it because of how I ran the suite. Reproduced on this branch merged onto current main:

tests/vector_store/test_vector_store_deepdive.py::TestVectorStoreDeepDive::test_milvus_store
>       self.assertIsInstance(results[0]["metadata"], dict)
E       AssertionError: <MagicMock name='mock.entity.get()' ...> is not an instance of <class 'dict'>
1 failed, 10 deselected

Passes on main, fails here. The cause is the one they gave: the mock hit in that test sets only .id and .distance, so hit.entity.get("metadata") returns an auto-created MagicMock, which is truthy, so or {} never fires and the mock itself lands in the result dict. It's the same underspecified mock you already fixed in test_search_result_schema.py — this file just needs the same mock_hit.entity.get.return_value = None.

Worth knowing why I didn't catch it: tests/vector_store/test_vector_store_deepdive.py:19 sets pytestmark = pytest.mark.integration for the whole module, so pytest -m "not integration" skips it — that's the "11 deselected" in the 345-passed run I quoted. The file only uses mocks and needs no Milvus server, so the marker is wrong, but until someone fixes that this failure is invisible to the standard local command and CI doesn't run pytest at all. If you're touching it anyway, dropping the module-level marker would stop the next person from hitting the same blind spot.

Everything else in my earlier review stands: the schema really does define FieldSchema(name="metadata", dtype=DataType.JSON), the comment you're replacing was false, and popping output_fields out of **options is the right way to avoid the duplicate-keyword TypeError. This is a one-line test fix away from being ready.

@ZohaibHassan16 ZohaibHassan16 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed the 1-line mock fix for TestVectorStoreDeepDive::test_milvus_store and synced with main. All Milvus and vector store tests are now green. Ready to merge.

@ZohaibHassan16
ZohaibHassan16 merged commit 2d053c9 into semantica-agi:main Sep 19, 2026
1 check passed
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] Stale comment in milvus_store says the schema has no metadata field

3 participants