{"record":{"id":"c7c38a3d87a3ba3e","repo":"microsoft/semantic-kernel","slug":"upsert-failed-c7c38a","errorCode":null,"errorMessage":"Upsert failed","messagePattern":"Upsert failed","errorType":"exception","errorClass":"ServiceResponseException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/memory_stores/postgres/postgres_memory_store.py","lineNumber":197,"sourceCode":"                        SET embedding = EXCLUDED.embedding,\n                            metadata = EXCLUDED.metadata,\n                            timestamp = EXCLUDED.timestamp\n                        RETURNING key\n                        \"\"\"\n                ).format(\n                    scm=Identifier(self._schema),\n                    tbl=Identifier(collection_name),\n                ),\n                (\n                    record._id,\n                    record.embedding.tolist(),\n                    self.__serialize_metadata(record),\n                    record._timestamp,\n                ),\n            )\n            result = cur.fetchone()\n            if result is None:\n                raise ServiceResponseException(\"Upsert failed\")\n            return result[0]\n\n    async def upsert_batch(self, collection_name: str, records: list[MemoryRecord]) -> list[str]:\n        \"\"\"Upserts a batch of records.\n\n        Args:\n            collection_name: The name of the collection to upsert the records into.\n            records: The records to upsert.\n\n        Returns:\n            List[str]: The unique database keys of the records.\n        \"\"\"\n        with self._connection_pool.connection() as conn, conn.cursor() as cur:\n            if not await self.__does_collection_exist(cur, collection_name):\n                raise ServiceResourceNotFoundError(f\"Collection '{collection_name}' does not exist\")\n            cur.nextset()\n            cur.executemany(\n                SQL(","sourceCodeStart":179,"sourceCodeEnd":215,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/memory_stores/postgres/postgres_memory_store.py#L179-L215","documentation":"Raised in PostgresMemoryStore.upsert() when cur.fetchone() returns None after an INSERT ... RETURNING key. ServiceResponseException('Upsert failed') indicates the row was not returned despite the ON CONFLICT DO UPDATE ... RETURNING clause expecting a row. This is an unexpected DB response, not a normal not-found case.","triggerScenarios":"The RETURNING clause produced no row — e.g., a DB-side rule rewrote the statement, a trigger suppressed the row, the connection was in a broken state, or a pgvector/serialization error left the statement non-returning. Most commonly a symptom of an underlying DB error surfacing as a missing return.","commonSituations":"Corrupt/timed-out connection from the pool; metadata serialization produced an invalid JSONB value; pgvector extension missing or dimension mismatch causing a silent statement failure; a BEFORE trigger returning NULL.","solutions":["Check DB logs for the actual statement error around the upsert timestamp.","Verify the pgvector extension is installed and the embedding dimension matches the table's vector(N) column.","Validate record.embedding length and that __serialize_metadata returns valid JSON before upsert.","Recreate the connection pool if connections are stale; increase pool health checks."],"exampleFix":"// before\nawait store.upsert(\"my_table\", record)\n\n// after\n# validate before upsert\nassert record.embedding.shape[0] == expected_dim\nawait store.upsert(\"my_table\", record)","handlingStrategy":"try-catch","validationCode":"assert record.embedding is not None and record.embedding.shape[0] == expected_dim\nimport json\njson.loads(json.dumps(record.__dict__))  # ensure metadata is JSON-serializable\nawait store.upsert(collection_name, record)","typeGuard":"def is_valid_pg_record(record: MemoryRecord, dim: int) -> bool:\n    return record.embedding is not None and record.embedding.shape[0] == dim","tryCatchPattern":"from semantic_kernel.exceptions import ServiceResponseException\ntry:\n    await store.upsert(collection_name, record)\nexcept ServiceResponseException as e:\n    # 'Upsert failed' — check DB logs for the underlying statement error\n    logger.error(\"postgres upsert returned no row: %s\", e)\n    raise","preventionTips":["Ensure pgvector is installed and the table vector(N) matches the embedding dim.","Validate metadata serializes to valid JSONB before upsert.","Recycle stale pool connections; monitor pool health."],"tags":["postgres","memory-store","deprecated","upsert","pgvector","server-error","data-integrity"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}