{"record":{"id":"98b4a028aed78f00","repo":"mem0ai/mem0","slug":"invalid-filter-key-key-r-98b4a0","errorCode":null,"errorMessage":"Invalid filter key: {key!r}","messagePattern":"Invalid filter key: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mem0/vector_stores/upstash_vector.py","lineNumber":22,"sourceCode":"\nfrom pydantic import BaseModel\n\nfrom mem0.vector_stores.base import VectorStoreBase\n\ntry:\n    from upstash_vector import Index\nexcept ImportError:\n    raise ImportError(\"The 'upstash_vector' library is required. Please install it using 'pip install upstash_vector'.\")\n\n\nlogger = logging.getLogger(__name__)\n\n_SAFE_FILTER_KEY = re.compile(r\"[a-zA-Z_][a-zA-Z0-9_]*\\Z\")\n\n\ndef _validate_filter(key: str, value: Any) -> None:\n    if not isinstance(key, str) or not _SAFE_FILTER_KEY.fullmatch(key):\n        raise ValueError(f\"Invalid filter key: {key!r}\")\n    if not isinstance(value, (str, int, float, bool)):\n        raise ValueError(\n            f\"Filter value for {key!r} must be str, int, float, or bool, \"\n            f\"got {type(value).__name__}\"\n        )\n    if isinstance(value, str) and ('\"' in value or \"\\\\\" in value):\n        raise ValueError(\n            f\"Filter value for {key!r} contains prohibited characters \"\n            f\"(double quote or backslash): {value!r}\"\n        )\n\n\nclass OutputData(BaseModel):\n    id: Optional[str]  # memory id\n    score: Optional[float]  # is None for `get` method\n    payload: Optional[Dict]  # metadata\n\n","sourceCodeStart":4,"sourceCodeEnd":40,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/vector_stores/upstash_vector.py#L4-L40","documentation":"Raised by the module-level `_validate_filter` helper when a metadata filter key is not a string or does not match the identifier regex `[a-zA-Z_][a-zA-Z0-9_]*`. Upstash Vector filters are serialized into a string query, so unsanitized keys are an injection surface — this strict allowlist blocks quotes, operators, whitespace, dots, hyphens, and unicode before they reach the API.","triggerScenarios":"Insert/search filters with keys like `\"user-id\"`, `\"data.created_at\"`, `\"1st_flag\"`, `\"memory type\"`, or a non-string key (int from JSON with int keys); any key containing quotes or backslashes.","commonSituations":"Using arbitrary metadata field names straight from user input or external systems; carrying over field naming conventions (kebab-case, dotted paths) from other schemas; filters generated by an LLM that quotes or decorates key names.","solutions":["Rename metadata fields at write time to snake_case identifiers: `user_id` not `user-id`.","Sanitize or reject keys before calling the API with a mirror of the same regex.","For dotted paths, flatten to a single underscore-joined key when writing payloads, since Upstash metadata is flat."],"exampleFix":"# before\nresults = memory.search(\"q\", filters={\"user-id\": \"u1\", \"data.score\": 5})\n\n# after\nresults = memory.search(\"q\", filters={\"user_id\": \"u1\", \"data_score\": 5})","handlingStrategy":"validation","validationCode":"import re\n\nSAFE_KEY = re.compile(r\"[a-zA-Z_][a-zA-Z0-9_]*\\Z\")\n\ndef sanitize_filter_keys(filters: dict) -> dict:\n    bad = [k for k in filters if not isinstance(k, str) or not SAFE_KEY.fullmatch(k)]\n    if bad:\n        raise ValueError(f\"Unsafe/non-identifier filter keys: {bad!r}\")\n    return filters","typeGuard":"import re\n\ndef is_safe_filter_key(key) -> bool:\n    return isinstance(key, str) and re.fullmatch(r\"[a-zA-Z_][a-zA-Z0-9_]*\", key) is not None","tryCatchPattern":"try:\n    results = memory.search(\"q\", filters=filters)\nexcept ValueError as e:\n    if \"Invalid filter key\" in str(e):\n        raise BadRequest(f\"Filter keys must be snake_case identifiers: {filters}\") from e\n    raise","preventionTips":["Constrain metadata field names to snake_case identifiers at write time — it is the only safe shape for Upstash.","Map external/dotted keys to flattened underscore names in one normalization function.","Treat filter-key validation as a security control, not a convenience: reject, don't escape."],"tags":["filters","upstash","validation","security","injection-prevention","vector-store"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}