Skip to content

Python: VolatileMemoryStore.get_nearest_matches raises ValueError on an empty collection #14534

Description

What happens

VolatileMemoryStore.get_nearest_matches raises ValueError: cannot reshape array of size 0 into shape (0,newaxis) when the collection exists but has no records. It should return [], as it already does when the collection does not exist.

Where

python/semantic_kernel/memory/volatile_memory_store.py, get_nearest_matches (checked against current main, 9974625):

memory_records = list(self._store[collection_name].values())

# Convert the collection of embeddings into a numpy array (stacked)
embeddings = array([x._embedding for x in memory_records], dtype=float)
embeddings = embeddings.reshape(embeddings.shape[0], -1)

With no records, array([]) has shape (0,) and the reshape to (0, -1) is ambiguous, so numpy raises. Even without the reshape, compute_similarity_scores would raise its own ValueError for "zero vectors" because valid_indices.any() is False for an empty array.

Steps to reproduce

import asyncio, numpy as np
from semantic_kernel.memory.volatile_memory_store import VolatileMemoryStore

async def main():
    s = VolatileMemoryStore()
    await s.create_collection("c")
    print(await s.get_nearest_matches("c", np.array([1.0, 2.0]), limit=3))

asyncio.run(main())

Actual:

  File ".../semantic_kernel/memory/volatile_memory_store.py", line 256, in get_nearest_matches
    embeddings = embeddings.reshape(embeddings.shape[0], -1)
ValueError: cannot reshape array of size 0 into shape (0,newaxis)

Expected: [].

Impact

SemanticTextMemory.search and TextMemoryPlugin.recall call this method. A freshly created collection, or one whose records were all removed, makes a normal search crash instead of returning no results.

I have a fix ready (early return when the collection has no records) with tests.

No activity

Activity on this issue will appear here.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    pythonPull requests for the Python Semantic Kerneltriage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions