microsoft/semantic-kernel · error · ServiceResourceNotFoundError

Key not found

Error message

Key not found

What it means

Raised by PostgresMemoryStore.get() after the SELECT returns no row for the supplied key (cur.fetchone() is None). It is a ServiceResourceNotFoundError distinct from the collection-missing case: the collection is fine, but the specific row is absent. The message is the literal string 'Key not found' with no interpolation.

Solutions

  1. Catch ServiceResourceNotFoundError around get() and treat as a cache miss.
  2. Prefer get_batch() if partial misses are acceptable; it returns only found rows rather than throwing.
  3. Normalize the key before get (strip, lowercase) to match what was stored.
  4. Verify the row exists with a direct check or by re-upserting before read.

Example fix

// before
rec = await store.get('mycol', key)
// after
from semantic_kernel.exceptions import ServiceResourceNotFoundError
try:
    rec = await store.get('mycol', key)
except ServiceResourceNotFoundError:
    rec = None
Defensive patterns

Strategy: try-catch

Try / catch

from semantic_kernel.exceptions import ServiceResourceNotFoundError
try:
    record = await store.get(collection_name, key)
except ServiceResourceNotFoundError as e:
    if str(e) == 'Key not found':
        record = None
    else:
        raise

Prevention

When it happens

Trigger: Awaiting `store.get(collection_name, key)` against an existing collection where no row has `key = <key>`. Common when the record was never upserted, was removed, or the key string differs (whitespace, case, type).

Common situations: Reading a key right after upsert that silently failed; key generated client-side differs from stored id; record deleted by remove()/remove_batch(); concurrent writer deleted the row between operations.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/7fdf993ec7626085. Report an issue: GitHub.

Appendix: source

Thrown at python/semantic_kernel/connectors/memory_stores/postgres/postgres_memory_store.py:278

        with self._connection_pool.connection() as conn, conn.cursor() as cur:
            if not await self.__does_collection_exist(cur, collection_name):
                raise ServiceResourceNotFoundError(f"Collection '{collection_name}' does not exist")
            cur.execute(
                SQL(
                    """
                        SELECT key, embedding, metadata, timestamp
                        FROM {scm}.{tbl}
                        WHERE key = %s
                        """
                ).format(
                    scm=Identifier(self._schema),
                    tbl=Identifier(collection_name),
                ),
                (key,),
            )
            result = cur.fetchone()
            if result is None:
                raise ServiceResourceNotFoundError("Key not found")
            return MemoryRecord.local_record(
                id=result[0],
                embedding=(
                    np.fromstring(result[1].strip("[]"), dtype=float, sep=",") if with_embedding else np.array([])
                ),
                text=result[2]["text"],
                description=result[2]["description"],
                additional_metadata=result[2]["additional_metadata"],
                timestamp=result[3],
            )

    async def get_batch(
        self, collection_name: str, keys: list[str], with_embeddings: bool = False
    ) -> list[MemoryRecord]:
        """Gets a batch of records.

        Args:
            collection_name: The name of the collection to get the records from.

View on GitHub (pinned to c028a0c7dc)