Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cache): resolve codec ambiguity between dataclass envelopes and user metadata dicts

Sameer Kadam2224d1082748
diff --git a/semantica/semantic_extract/cache.py b/semantica/semantic_extract/cache.py
index 23283a1e..9b05c213 100644
--- a/semantica/semantic_extract/cache.py
+++ b/semantica/semantic_extract/cache.py
@@ -52,64 +52,87 @@ NAMESPACES = ("entities", "relations", "triplets")
# The codec handles the three concrete value types stored by ExtractionCache:
# List[Entity], List[Relation], List[Triplet]
#
-# Each dataclass is encoded as a plain JSON object tagged with a ``__type__``
-# key so the decoder can reconstruct the correct Python type unambiguously.
+# Dataclass instances are encoded as:
+# {"__dc__": "<ClassName>", "fields": {<field>: <encoded-value>, ...}}
+#
+# The ``__dc__`` key is a codec-internal marker that is never present in user
+# data (metadata dicts are arbitrary and may carry any key, including
+# ``__type__``, so that key must not be treated as a dispatch signal).
+# Plain dicts are encoded by recursing into their values without adding any
+# wrapper, so their keys are never mistaken for envelope markers.
+#
# All field values (str, int, float, bool, None, dict-of-primitives) are
# JSON-native, so no Python-specific serialisation is required.
-#
-# Values that are not one of the known tagged types (e.g. raw dicts or
-# primitives stored by tests) are round-tripped as-is. Unknown ``__type__``
-# tags are returned as plain dicts so forward-compatibility is preserved.
# ---------------------------------------------------------------------------
def _encode_value(value: Any) -> Any:
"""Recursively encode *value* to a JSON-safe representation.
- Dataclass instances are represented as ``{"__type__": "<ClassName>",
- **fields}``. Lists are encoded element-wise. Everything else is
- returned unchanged (it must already be JSON-serialisable; callers that
- pass non-serialisable values will get a ``TypeError`` from
- ``json.dumps``, which ``SqliteCacheBackend.set`` already handles).
+ Dataclass instances are represented as
+ ``{"__dc__": "<ClassName>", "fields": {…}}``.
+ Lists are encoded element-wise.
+ Plain dicts are encoded by recursing into their values — no wrapper is
+ added, so user metadata keys (including ``__type__``) are never
+ reinterpreted by the decoder.
+ Everything else is returned unchanged (it must already be
+ JSON-serialisable; non-serialisable values surface as a ``TypeError``
+ from ``json.dumps``, which ``SqliteCacheBackend.set`` already handles).
"""
if isinstance(value, list):
return [_encode_value(item) for item in value]
if dataclasses.is_dataclass(value) and not isinstance(value, type):
- # Build the tagged envelope manually (rather than dataclasses.asdict)
- # so that nested dataclasses are also tagged, which the decoder needs.
- encoded: Dict[str, Any] = {"__type__": type(value).__name__}
- for f in dataclasses.fields(value):
- encoded[f.name] = _encode_value(getattr(value, f.name))
- return encoded
- # Primitive or dict — returned as-is; json.dumps will catch anything
- # non-serialisable and SqliteCacheBackend.set treats that as a skip.
+ # Encode as a two-key envelope: the marker ``__dc__`` identifies this
+ # as a codec-managed dataclass, and ``fields`` carries the encoded
+ # field values. Nesting is handled by recursing into each field.
+ return {
+ "__dc__": type(value).__name__,
+ "fields": {
+ f.name: _encode_value(getattr(value, f.name))
+ for f in dataclasses.fields(value)
+ },
+ }
+ if isinstance(value, dict):
+ # Recurse into dict values so nested dataclasses inside metadata are
+ # also encoded. Do NOT add any wrapper: the dict's own keys must be
+ # preserved exactly and must never be confused with envelope markers.
+ return {k: _encode_value(v) for k, v in value.items()}
+ # Primitive — returned as-is.
return value
def _decode_value(raw: Any) -> Any:
"""Reconstruct Python objects from the JSON-decoded representation.
- Tagged dicts (``__type__`` key) are converted back to the corresponding
- dataclass. Lists are decoded element-wise. Everything else is returned
- unchanged.
+ Dicts carrying the ``__dc__`` key are dataclass envelopes written by
+ :func:`_encode_value` and are reconstructed as the corresponding type.
+ Lists are decoded element-wise.
+ Everything else — including plain dicts with any user-defined keys such
+ as ``__type__`` — is returned unchanged.
"""
# Import here to avoid a circular import; types.py has no deps on cache.py.
from .types import Entity, Relation, Triplet # noqa: PLC0415
if isinstance(raw, list):
return [_decode_value(item) for item in raw]
- if isinstance(raw, dict) and "__type__" in raw:
- type_tag = raw["__type__"]
- fields = {k: _decode_value(v) for k, v in raw.items() if k != "__type__"}
+ if isinstance(raw, dict) and "__dc__" in raw:
+ # This dict was produced by the encoder; reconstruct the dataclass.
+ type_tag = raw["__dc__"]
+ fields = {k: _decode_value(v) for k, v in raw.get("fields", {}).items()}
if type_tag == "Entity":
return Entity(**fields)
if type_tag == "Relation":
return Relation(**fields)
if type_tag == "Triplet":
return Triplet(**fields)
- # Unknown tag — return the original dict unchanged (forward-compat).
- # Do NOT return fields: that would silently drop the ``__type__`` key.
- return raw
- # Primitive, plain dict without a type tag, etc.
+ # Unknown tag from a future version — return the decoded fields dict
+ # so callers get the data rather than an opaque envelope.
+ return fields
+ if isinstance(raw, dict):
+ # Plain dict (e.g. user metadata): recurse into values so any
+ # dataclass envelopes nested inside are decoded, but preserve all
+ # keys including ``__type__`` unchanged.
+ return {k: _decode_value(v) for k, v in raw.items()}
+ # Primitive (str, int, float, bool, None) — returned as-is.
return raw
diff --git a/tests/semantic_extract/test_cache_backends.py b/tests/semantic_extract/test_cache_backends.py
index 8d797120..96ef0528 100644
--- a/tests/semantic_extract/test_cache_backends.py
+++ b/tests/semantic_extract/test_cache_backends.py
@@ -697,50 +697,135 @@ def test_custom_pickle_serializer_escape_hatch(tmp_path):
backend.close()
-def test_metadata_dict_with_dunder_type_key_is_not_misreconstructed(tmp_path):
- """A metadata dict that happens to contain a ``__type__`` key must NOT be
- reconstructed as an Entity, Relation, or Triplet — it must round-trip as
- a plain dict.
- This guards against the codec accidentally treating user-supplied metadata
- values as tagged envelopes.
+def test_metadata_dict_with_dunder_type_key_is_not_misreconstructed(tmp_path):
+ """Metadata dicts whose ``__type__`` value matches a recognised dataclass
+ name (``Entity``, ``Relation``, ``Triplet``) must NOT be reconstructed as
+ a dataclass — they must round-trip as plain dicts. The containing cache
+ row must NOT be evicted (i.e. the result must not be a miss).
+
+ This is the primary regression test for the codec-ambiguity fix: the
+ encoder must use a private marker key (``__dc__``) for its own envelopes
+ so that user-controlled ``__type__`` values in metadata are never
+ interpreted as dispatch signals.
"""
- backend = SqliteCacheBackend(_db(tmp_path))
-
- # An Entity whose metadata dict contains a "__type__" key with an unknown
- # tag name. The metadata must survive unchanged as a plain dict.
- entities = [
- _make_entity(
- text="TestOrg",
- label="ORG",
- start_char=0,
- end_char=7,
- confidence=0.8,
- metadata={
- # Unknown __type__ tag inside metadata.
- # Must NOT cause metadata to be reconstructed as a dataclass.
- "__type__": "SomeExternalModel",
- "schema_version": 2,
- },
- )
- ]
-
- backend.set("entities", "k", entities, ttl=None)
- result = backend.get("entities", "k")
- backend.close()
-
- assert result is not None
- assert len(result) == 1
-
- e = result[0]
- # The outer value must be reconstructed correctly as an Entity.
- assert isinstance(e, Entity), "outer value must be reconstructed as Entity"
- assert e.text == "TestOrg"
+ # Three independent backends, one per namespace, so each case is
+ # isolated and size assertions are unambiguous.
+
+ # --- entities namespace: metadata.__type__ == "Entity" ---
+ b_ent = SqliteCacheBackend(_db(tmp_path) + ".ent")
+ b_ent.set(
+ "entities",
+ "k",
+ [
+ _make_entity(
+ text="Collision",
+ label="ORG",
+ start_char=0,
+ end_char=9,
+ confidence=0.7,
+ metadata={
+ "__type__": "Entity", # recognised name — must stay a dict
+ "text": "inner",
+ "label": "FAKE",
+ "start_char": 0,
+ "end_char": 5,
+ "confidence": 0.5,
+ "metadata": {},
+ "extra": "should survive",
+ },
+ )
+ ],
+ ttl=None,
+ )
+ result_ent = b_ent.get("entities", "k")
+ # Row must NOT have been evicted.
+ assert b_ent.size("entities") == 1, (
+ "row was evicted — Entity __type__ in metadata caused deserialization failure"
+ )
+ b_ent.close()
- # The metadata dict must come back as a plain dict, not a dataclass.
+ assert result_ent is not None, "__type__=Entity in metadata must not cause a miss"
+ assert len(result_ent) == 1
+ e = result_ent[0]
+ assert isinstance(e, Entity), "outer item must be an Entity"
+ assert e.text == "Collision"
assert isinstance(e.metadata, dict), "metadata must remain a plain dict"
- # The __type__ key inside metadata must be preserved exactly — not stripped.
- assert e.metadata["__type__"] == "SomeExternalModel", (
- "__type__ key inside metadata must be preserved, not stripped"
+ assert e.metadata["__type__"] == "Entity", "__type__ key must be preserved"
+ assert e.metadata["extra"] == "should survive"
+
+ # --- relations namespace: metadata.__type__ == "Relation" ---
+ b_rel = SqliteCacheBackend(_db(tmp_path) + ".rel")
+ subj = _make_entity("A", "ORG", 0, 1, 0.9)
+ obj = _make_entity("B", "ORG", 2, 3, 0.8)
+ b_rel.set(
+ "relations",
+ "k",
+ [
+ Relation(
+ subject=subj,
+ predicate="knows",
+ object=obj,
+ confidence=0.9,
+ context="ctx",
+ metadata={
+ "__type__": "Relation", # recognised name — must stay a dict
+ "subject": "not a real subject",
+ "predicate": "collision",
+ "note": "plain value",
+ },
+ )
+ ],
+ ttl=None,
+ )
+ result_rel = b_rel.get("relations", "k")
+ assert b_rel.size("relations") == 1, (
+ "row was evicted — Relation __type__ in metadata caused deserialization failure"
+ )
+ b_rel.close()
+
+ assert result_rel is not None, "__type__=Relation in metadata must not cause a miss"
+ assert len(result_rel) == 1
+ r = result_rel[0]
+ assert isinstance(r, Relation), "outer item must be a Relation"
+ assert r.predicate == "knows"
+ assert isinstance(r.metadata, dict), "metadata must remain a plain dict"
+ assert r.metadata["__type__"] == "Relation", "__type__ key must be preserved"
+ assert r.metadata["note"] == "plain value"
+
+ # --- triplets namespace: metadata.__type__ == "Triplet" ---
+ b_tri = SqliteCacheBackend(_db(tmp_path) + ".tri")
+ b_tri.set(
+ "triplets",
+ "k",
+ [
+ Triplet(
+ subject="S",
+ predicate="P",
+ object="O",
+ confidence=0.95,
+ metadata={
+ "__type__": "Triplet", # recognised name — must stay a dict
+ "subject": "collision",
+ "predicate": "collision",
+ "object": "collision",
+ "note": "plain value",
+ },
+ )
+ ],
+ ttl=None,
+ )
+ result_tri = b_tri.get("triplets", "k")
+ assert b_tri.size("triplets") == 1, (
+ "row was evicted — Triplet __type__ in metadata caused deserialization failure"
)
- assert e.metadata["schema_version"] == 2
+ b_tri.close()
+
+ assert result_tri is not None, "__type__=Triplet in metadata must not cause a miss"
+ assert len(result_tri) == 1
+ t = result_tri[0]
+ assert isinstance(t, Triplet), "outer item must be a Triplet"
+ assert t.predicate == "P"
+ assert isinstance(t.metadata, dict), "metadata must remain a plain dict"
+ assert t.metadata["__type__"] == "Triplet", "__type__ key must be preserved"
+ assert t.metadata["note"] == "plain value"