{"record":{"id":"137e17f3559795bd","repo":"mem0ai/mem0","slug":"insert-failed-for-document-doc-get-id-doc","errorCode":null,"errorMessage":"Insert failed for document {doc.get('id')}: {doc}","messagePattern":"Insert failed for document (.+?): (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"mem0/vector_stores/azure_ai_search.py","lineNumber":189,"sourceCode":"\n    # Note: Explicit \"insert\" calls may later be decoupled from memory management decisions.\n    def insert(self, vectors, payloads=None, ids=None):\n        \"\"\"\n        Insert vectors into the index.\n\n        Args:\n            vectors (List[List[float]]): List of vectors to insert.\n            payloads (List[Dict], optional): List of payloads corresponding to vectors.\n            ids (List[str], optional): List of IDs corresponding to vectors.\n        \"\"\"\n        logger.info(f\"Inserting {len(vectors)} vectors into index {self.index_name}\")\n        documents = [\n            self._generate_document(vector, payload, id) for id, vector, payload in zip(ids, vectors, payloads)\n        ]\n        response = self.search_client.upload_documents(documents)\n        for doc in response:\n            if not hasattr(doc, \"status_code\") and doc.get(\"status_code\") != 201:\n                raise Exception(f\"Insert failed for document {doc.get('id')}: {doc}\")\n        return response\n\n    def _sanitize_key(self, key: str) -> str:\n        return re.sub(r\"[^\\w]\", \"\", key)\n\n    def _build_filter_expression(self, filters):\n        filter_conditions = []\n        for key, value in filters.items():\n            safe_key = self._sanitize_key(key)\n            if isinstance(value, str):\n                safe_value = value.replace(\"'\", \"''\")\n                condition = f\"{safe_key} eq '{safe_value}'\"\n            elif isinstance(value, bool):\n                condition = f\"{safe_key} eq {str(value).lower()}\"\n            elif isinstance(value, (int, float)):\n                condition = f\"{safe_key} eq {value}\"\n            else:\n                raise ValueError(","sourceCodeStart":171,"sourceCodeEnd":207,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/vector_stores/azure_ai_search.py#L171-L207","documentation":"Raised by AzureAISearch.insert after search_client.upload_documents returns: the code inspects each IndexedDocument and raises when the response indicates the document was not uploaded with status 201. Typical causes are stale index schema (dimension/field mismatch), throttling (207/429), auth issues, or a payload field that violates the index definition. Note the guard 'not hasattr(doc, \"status_code\") and doc.get(...) != 201' only fires for dict-like responses lacking the attribute, so some real failures can be silently swallowed — treat any raise here as a genuine server-side rejection.","triggerScenarios":"Calling memory.add() with azure_ai_search configured after switching embedding models so vector dimensions no longer match the existing index's vector field; uploading documents whose payload JSON exceeds field constraints; hitting Azure throttling limits on bulk adds; index deleted/recreated with different schema while the client cached the old one.","commonSituations":"Changing embedder model (e.g. text-embedding-3-small 1536 → another dim) without recreating the Azure index; bursty workloads exceeding the service's QPS; service name/api key misconfigured; index field 'payload' redefined as non-collection(Edm.String).","solutions":["Inspect the doc dict in the exception: status_code 400 → schema mismatch, 429 → throttling, 403 → auth","If dimensions changed, delete and recreate the index (drop the collection_name or create a new one) so create_col rebuilds it","For 429: reduce batch size / add retry with exponential backoff around memory.add()","Verify service_name and api_key in vector_store config and that the index exists in the portal"],"exampleFix":"# before\nmemory.add(\"...\", user_id=\"u1\")  # Insert failed for document ...\n\n# after (dimension changed): recreate index with the new dims\ncfg = {\n  \"vector_store\": {\"provider\": \"azure_ai_search\", \"config\": {\n    \"service_name\": \"svc\", \"collection_name\": \"mem0_idx_v2\",\n    \"api_key\": key, \"embedding_model_dims\": 1536}}\n}\nmemory = Memory.from_config(cfg)","handlingStrategy":"retry","validationCode":"# before add(): confirm index dims match the embedder\nemb_dims = 1536  # from your embedder\n# AzureAISearch stores embedding_model_dims at init; recreate index if it differs\nif existing_index_dim is not None and existing_index_dim != emb_dims:\n    raise ConfigError(f'dimension drift: index={existing_index_dim}, embedder={emb_dims}; recreate index')","typeGuard":null,"tryCatchPattern":"import time\nfor attempt in range(5):\n    try:\n        memory.add(msg, user_id=uid)\n        break\n    except Exception as e:\n        if 'Insert failed for document' in str(e) and attempt < 4:\n            time.sleep(2 ** attempt)\n            continue\n        raise","preventionTips":["Recreate the Azure index whenever you change embedding model/dimension (use a new collection_name and bump a suffix)","Batch adds modestly to stay under QPS limits","Log the full doc dict from the exception — status codes map to distinct fixes","Monitor index schema drift in integration tests"],"tags":["azure","vector-store","insert","schema-mismatch","throttling"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}