microsoft/semantic-kernel · error · ValueError

Upsert failed

Error message

Upsert failed

What it means

Raised as a ValueError in MongoDBAtlasMemoryStore.upsert when update_result.acknowledged is False. MongoDB write operations are 'acknowledged' when the server confirms the write per the write concern; an unacknowledged result (write concern w=0) means the driver did not wait for confirmation. The store treats this as a failure.

Source

Thrown at python/semantic_kernel/connectors/memory_stores/mongodb_atlas/mongodb_atlas_memory_store.py:161

        Does not guarantee that the collection exists.
            If the record already exists, it will be updated.
            If the record does not exist, it will be created.

        Args:
            collection_name (str): The name associated with a collection of embeddings.
            record (MemoryRecord): The memory record to upsert.

        Returns:
            str: The unique identifier for the memory record.
        """
        document: Mapping[str, Any] = memory_record_to_mongo_document(record)

        update_result: results.UpdateResult = await self.database[collection_name].update_one(
            document, {"$set": document}, upsert=True
        )

        if not update_result.acknowledged:
            raise ValueError("Upsert failed")
        return record._id

    async def upsert_batch(self, collection_name: str, records: list[MemoryRecord]) -> list[str]:
        """Upserts a group of memory records into the data store.

        Does not guarantee that the collection exists.
            If the record already exists, it will be updated.
            If the record does not exist, it will be created.

        Args:
            collection_name (str): The name associated with a collection of embeddings.
            records (MemoryRecord): The memory records to upsert.

        Returns:
            List[str]: The unique identifiers for the memory records.
        """
        upserts: list[UpdateOne] = []
        for record in records:

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Ensure the write concern is acknowledged (default w=majority or w=1); remove ?w=0 from the connection string.
  2. If you intentionally use unacknowledged writes, note this store rejects them — switch to acknowledged.
  3. Verify the motor AsyncIOMotorClient is constructed with default or majority write concern.
  4. Check that update_one is not being called with explicit unacknowledged options.

Example fix

// before
# connection string has w=0 -> unacknowledged
store = MongoDBAtlasMemoryStore(connection_string='mongodb+srv://...?w=0')
await store.upsert('docs', record)  # ValueError: Upsert failed
// after
# remove w=0 so writes are acknowledged
store = MongoDBAtlasMemoryStore(connection_string='mongodb+srv://...?w=majority')
await store.upsert('docs', record)
Defensive patterns

Strategy: validation

Validate before calling

def is_acknowledged_write_concern(conn_str: str) -> bool:
    s = conn_str.lower()
    if 'w=0' in s:
        return False
    return True

if not is_acknowledged_write_concern(connection_string):
    raise ValueError('Connection string uses unacknowledged write concern (w=0)')

Try / catch

try:
    await store.upsert('docs', record)
except ValueError as e:
    if 'Upsert failed' in str(e):
        logging.error('Write was unacknowledged; check write concern')
    raise

Prevention

When it happens

Trigger: The MongoDB client is configured with an unacknowledged write concern (w=0). This can happen if the connection string or client options set w=0, or if a server/driver edge case returns unacknowledged.

Common situations: Connection string includes ?w=0 for low-latency fire-and-forget writes. Client configured with WriteConcern(w=0) for throughput. Misconfigured motor client options passed through from settings.

Related errors


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