Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions hindsight-api-slim/hindsight_api/engine/response_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,20 @@ class MemoryFact(BaseModel):
@field_validator("metadata", mode="before")
@classmethod
def parse_metadata(cls, v: Any) -> dict[str, str] | None:
"""Parse metadata from JSON string if needed (asyncpg may return JSONB as str)."""
"""Parse metadata from JSON string if needed (asyncpg may return JSONB as str).

Also coerces non-string dict values (e.g., integer IDs stored in JSONB)
to strings, preventing ValidationError when consolidation encounters
metadata like {"original_id": 348} instead of {"original_id": "348"}.
"""
if v is None:
return None
if isinstance(v, str):
import json

return json.loads(v)
v = json.loads(v)
if isinstance(v, dict):
return {str(k): str(val) for k, val in v.items()}
return v

chunk_id: str | None = Field(
Expand Down
31 changes: 31 additions & 0 deletions hindsight-api-slim/tests/test_response_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Tests for MemoryFact response-model validation."""

from hindsight_api.engine.response_models import MemoryFact

_BASE = {"id": "u1", "text": "hi", "fact_type": "observation"}


class TestMemoryFactMetadataCoercion:
"""metadata values may arrive as non-strings from JSONB; they must coerce to str.

Regression for #2622: an integer ``original_id`` stored in ``metadata`` raised
``ValidationError`` (``string_type``) and blocked consolidation, because
``metadata`` is typed ``dict[str, str]`` and the raw dict passed straight
through to Pydantic.
"""

def test_integer_value_is_coerced_to_string(self):
fact = MemoryFact(**_BASE, metadata={"original_id": 12345})
assert fact.metadata == {"original_id": "12345"}

def test_jsonb_string_with_integer_value_is_coerced(self):
# asyncpg may hand back JSONB as a raw string; ints inside must still coerce.
fact = MemoryFact(**_BASE, metadata='{"original_id": 12345, "n": 3}')
assert fact.metadata == {"original_id": "12345", "n": "3"}

def test_string_values_pass_through_unchanged(self):
fact = MemoryFact(**_BASE, metadata={"source": "slack", "channel": "eng"})
assert fact.metadata == {"source": "slack", "channel": "eng"}

def test_none_metadata_stays_none(self):
assert MemoryFact(**_BASE, metadata=None).metadata is None