Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(context): index Decision objects passed to add_decision (#1954) (#1955)
Kaif746dc6354439
diff --git a/docs/guides/decision-intelligence.md b/docs/guides/decision-intelligence.mdindex c923947a..21da97de 100644--- a/docs/guides/decision-intelligence.md+++ b/docs/guides/decision-intelligence.md@@ -135,9 +135,9 @@ decision_id = graph.add_decision()```-<Warning>-Only pass keyword arguments to `add_decision()`, not a pre-built `Decision` object. `add_decision(Decision(...))` stores the node directly and skips the indexing step that `record_decision()` performs, so the decision becomes invisible to `find_precedents()`, `get_causal_chain()`, and `get_decision_insights()`, and `trace_decision_causality()` raises `ValueError` if you call it on one. The keyword-argument form above does not have this problem — it delegates to `record_decision()` internally. Note that, like `record_decision()`, it always generates its own `decision_id` (returned from the call); there is no way to force a specific ID.-</Warning>+<Info>+`add_decision()` also accepts a pre-built `Decision` object: `graph.add_decision(Decision(...))`. Both forms are indexed the same way, so the decision is visible to `find_precedents()`, `get_decision_insights()`, `analyze_decision_influence()` and `trace_decision_causality()` as soon as it is added. The object form keeps the `decision_id` you set on it. The keyword form, like `record_decision()`, generates its own `decision_id` and returns it. Entries in `Decision.metadata` are stored on the node but cannot override the decision's own fields such as `category` or `confidence`.+</Info>## Searching Precedents Before Deciding@@ -281,12 +281,7 @@ d = Decision()if engine.check_compliance(d, "cti_confidence_gate"):- # Pass fields as kwargs, not the Decision object itself — see the- # warning above. add_decision() generates its own decision_id.- decision_id = graph.add_decision(- category=d.category, scenario=d.scenario, reasoning=d.reasoning,- outcome=d.outcome, confidence=d.confidence, decision_maker=d.decision_maker,- )+ decision_id = graph.add_decision(d)engine.record_policy_application(decision_id, "cti_confidence_gate", "1.0")print("Decision recorded — policy compliant.")else:diff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.pyindex 54d0c5e4..941ef5e2 100644--- a/semantica/context/agent_context.py+++ b/semantica/context/agent_context.py@@ -1803,6 +1803,21 @@ class AgentContext:if not self._decision_backend:raise RuntimeError("Decision tracking is not enabled")+ def _safe_parse_timestamp(value: Any) -> datetime:+ if isinstance(value, datetime):+ return value+ if not value:+ return datetime.now()+ if isinstance(value, (int, float)):+ try:+ return datetime.fromtimestamp(value)+ except (OverflowError, OSError, ValueError):+ return datetime.now()+ try:+ return datetime.fromisoformat(str(value))+ except Exception:+ return datetime.now()+# Delegate to ContextGraph if availableif self._decision_backend == "context_graph" and hasattr(self.knowledge_graph, "find_precedents_by_scenario"):try:@@ -1829,7 +1844,7 @@ class AgentContext:reasoning=decision_data["reasoning"],outcome=decision_data["outcome"],confidence=decision_data["confidence"],- timestamp=datetime.fromtimestamp(decision_data["timestamp"]),+ timestamp=_safe_parse_timestamp(decision_data["timestamp"]),decision_maker=decision_data.get("decision_maker"),valid_from=decision_data.get("valid_from"),valid_until=decision_data.get("valid_until"),@@ -1856,16 +1871,6 @@ class AgentContext:results: List[Decision] = []- def _safe_parse_timestamp(value: Any) -> datetime:- if isinstance(value, datetime):- return value- if not value:- return datetime.now()- try:- return datetime.fromisoformat(str(value))- except Exception:- return datetime.now()-if use_hybrid_search and hasattr(self.vector_store, "search_decisions"):filters = {"category": category} if category else Nonevector_results = self.vector_store.search_decisions(diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex ec8bbc73..bb6633af 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -3873,15 +3873,42 @@ class ContextGraph:# Handle None metadatametadata = decision.metadata or {}+ # Validate the values the decision indexes need before touching graph+ # state, so a bad value can't leave a stored but unindexed node.+ try:+ hash(decision.category)+ float(decision.confidence)+ except (TypeError, ValueError) as e:+ raise ValueError(+ f"Decision {node_id!r} has an invalid category or confidence: {e}"+ ) from e+ meta_entities = metadata.get("entities")+ if meta_entities is not None:+ if not isinstance(meta_entities, list):+ raise ValueError("Decision metadata 'entities' must be a list")+ try:+ for entity in meta_entities:+ hash(entity)+ except TypeError as e:+ raise ValueError(+ "Decision metadata 'entities' must contain hashable values"+ ) from e+# Normalize timestamp to ensure consistent storage format- normalized_timestamp = self._normalize_timestamp(decision.timestamp)+ raw_timestamp = decision.timestamp+ if isinstance(raw_timestamp, str) and raw_timestamp.strip().endswith(("Z", "z")):+ raw_timestamp = raw_timestamp.strip()[:-1] + "+00:00"+ normalized_timestamp = self._normalize_timestamp(raw_timestamp)node = ContextNode(node_id=node_id,node_type="Decision",content=decision.scenario,properties={+ # Metadata first so it can't override the Decision's own fields.+ **metadata,"category": decision.category,+ "scenario": decision.scenario,"reasoning": decision.reasoning,"outcome": decision.outcome,"confidence": decision.confidence,@@ -3889,12 +3916,15 @@ class ContextGraph:"decision_maker": decision.decision_maker,"reasoning_embedding": decision.reasoning_embedding,"node2vec_embedding": decision.node2vec_embedding,- **metadata},valid_from=decision.valid_from,valid_until=decision.valid_until,)- self._add_internal_node(node)+ with self._lock:+ if self._add_internal_node(node):+ # Register in the decision indexes so precedent search,+ # influence, causality and insights can see this decision.+ self._sync_decision_from_node(node_id)return node_iddef add_causal_relationship(@@ -4862,7 +4892,7 @@ class ContextGraph:for other_decision_id in self._entity_index.get(entity, set()):if other_decision_id != current_id and other_decision_id not in explicit_cause_ids:other_decision = self._decisions[other_decision_id]- if other_decision["timestamp"] < current_decision["timestamp"]:+ if self._decision_sort_ts(other_decision["timestamp"]) < self._decision_sort_ts(current_decision["timestamp"]):potential_causes[other_decision_id] = Nonefor cause_id in potential_causes:@@ -5133,6 +5163,31 @@ class ContextGraph:"valid_from", "valid_until", "content",})+ @staticmethod+ def _decision_sort_ts(raw_ts: Any) -> float:+ """Epoch seconds for ``_temporal_index`` ordering.++ Accepts epoch numbers (``record_decision``) and ISO strings+ (``add_decision`` with a ``Decision`` object); anything unparseable+ sorts as ``0.0``. A trailing ``Z`` is read as UTC; other naive values+ use local time, matching ``record_decision``'s ``datetime.now()``.+ """+ if isinstance(raw_ts, datetime):+ return raw_ts.timestamp()+ try:+ return float(raw_ts)+ except (TypeError, ValueError):+ pass+ if isinstance(raw_ts, str):+ try:+ text = raw_ts.strip()+ if text.endswith(("Z", "z")):+ text = text[:-1] + "+00:00"+ return datetime.fromisoformat(text).timestamp()+ except ValueError:+ pass+ return 0.0+def _rebuild_decision_indexes(self) -> None:"""Rebuild all derived decision indexes from the current node store.@@ -5171,10 +5226,7 @@ class ContextGraph:# The temporal index uses it for sorting; downstream code handles# both types via _normalize_timestamp.raw_ts = meta.get("timestamp", 0.0)- try:- sort_ts = float(raw_ts)- except (TypeError, ValueError):- sort_ts = 0.0+ sort_ts = self._decision_sort_ts(raw_ts)# Entities may be stored as a list in meta or inferred from# outgoing "involves" edges if the list field is absent/empty.@@ -5273,10 +5325,7 @@ class ContextGraph:meta.update(getattr(node, "properties", {}) or {})raw_ts = meta.get("timestamp", 0.0)- try:- sort_ts = float(raw_ts)- except (TypeError, ValueError):- sort_ts = 0.0+ sort_ts = self._decision_sort_ts(raw_ts)entities = meta.get("entities") or []if not isinstance(entities, list):@@ -5557,7 +5606,12 @@ class ContextGraph:category_score = 1.0 if source_decision["category"] == target_decision["category"] else 0.0# Temporal proximity (more recent decisions have higher influence)- time_diff = abs(source_decision["timestamp"] - target_decision["timestamp"])+ # Timestamps may be epoch floats (record_decision) or ISO strings+ # (add_decision with a Decision object); compare as epoch seconds.+ time_diff = abs(+ self._decision_sort_ts(source_decision["timestamp"])+ - self._decision_sort_ts(target_decision["timestamp"])+ )time_score = max(0.0, 1.0 - time_diff / (30 * 24 * 3600)) # 30 days window# Combined scorediff --git a/tests/context/test_add_decision_object_indexing.py b/tests/context/test_add_decision_object_indexing.pynew file mode 100644index 00000000..7f0ed075--- /dev/null+++ b/tests/context/test_add_decision_object_indexing.py@@ -0,0 +1,204 @@+"""Regression tests for issue #1954.++``ContextGraph.add_decision(Decision(...))`` stored a ``Decision`` node but+never registered it in the decision indexes, so precedent search, influence+analysis, causality tracing and insights all behaved as if the decision did+not exist until the graph was round-tripped through ``to_dict``/``from_dict``.+"""++from datetime import datetime, timezone++import pytest++from semantica.context import ContextGraph+from semantica.context.decision_models import Decision++SCENARIO = "extend payment terms for expansion"+++def _decision(decision_id="D1", ts=datetime(2026, 4, 1), category="terms"):+ return Decision(+ decision_id=decision_id,+ category=category,+ scenario=SCENARIO,+ reasoning="r",+ outcome="o",+ confidence=1.0,+ timestamp=ts,+ decision_maker="cfo",+ )+++def _precedent_ids(graph):+ results = graph.find_precedents_by_scenario(SCENARIO, similarity_threshold=0.0)+ return {r["decision"]["id"] for r in results}+++def test_decision_object_visible_to_precedent_search():+ g = ContextGraph()+ g.add_decision(_decision())+ assert "D1" in _precedent_ids(g)+++def test_decision_object_counted_by_insights():+ g = ContextGraph()+ g.add_decision(_decision())+ insights = g.get_decision_insights()+ assert insights.get("message") != "No decisions recorded yet"+ assert insights["total_decisions"] == 1+++def test_decision_object_accepted_by_influence_and_causality():+ g = ContextGraph()+ g.add_decision(_decision())+ g.analyze_decision_influence("D1")+ g.trace_decision_causality("D1")+++def test_decision_object_category_index():+ g = ContextGraph()+ g.add_decision(_decision())+ assert "D1" in g._decision_index["terms"]+++def test_iso_timestamps_ordered_in_temporal_index():+ g = ContextGraph()+ g.add_decision(_decision("OLD", ts=datetime(2025, 1, 1)))+ g.add_decision(_decision("NEW", ts=datetime(2026, 1, 1)))+ ordered = [nid for nid, _ in g._temporal_index]+ assert ordered == ["NEW", "OLD"]+ assert all(ts > 0 for _, ts in g._temporal_index)+++def test_readding_same_id_does_not_duplicate_index_entries():+ g = ContextGraph()+ g.add_decision(_decision())+ g.add_decision(_decision(category="pricing"))+ assert [nid for nid, _ in g._temporal_index] == ["D1"]+ assert "D1" not in g._decision_index["terms"]+ assert "D1" in g._decision_index["pricing"]++[email protected]("path", ["object", "kwargs"])+def test_every_public_add_path_is_searchable(path):+ g = ContextGraph()+ if path == "object":+ did = g.add_decision(_decision())+ else:+ did = g.add_decision(+ category="terms", scenario=SCENARIO, reasoning="r",+ outcome="o", confidence=1.0,+ )+ assert did in _precedent_ids(g)+++def test_indexes_match_round_trip():+ g = ContextGraph()+ g.add_decision(_decision())+ before = _precedent_ids(g)+ g2 = ContextGraph()+ g2.from_dict(g.to_dict())+ assert before == _precedent_ids(g2)+++# --- Review follow-ups -------------------------------------------------------+++def test_influence_score_with_two_object_decisions():+ g = ContextGraph()+ g.add_decision(_decision("A", ts=datetime(2026, 4, 1)))+ g.add_decision(_decision("B", ts=datetime(2026, 4, 2)))+ score = g._calculate_decision_influence_score("A", "B")+ assert score["category_score"] == 1.0+ assert score["time_score"] == pytest.approx(1.0 - 1 / 30)+ assert score["score"] > 0+++def test_influence_score_with_mixed_add_paths():+ g = ContextGraph()+ g.add_decision(_decision("A", ts=datetime.now()))+ kw_id = g.add_decision(+ category="terms", scenario=SCENARIO, reasoning="r",+ outcome="o", confidence=1.0,+ )+ score = g._calculate_decision_influence_score("A", kw_id)+ assert score["category_score"] == 1.0+ assert score["time_score"] > 0.9+++def test_causality_compares_iso_and_epoch_timestamps():+ g = ContextGraph()+ old = _decision("OLD", ts=datetime(2025, 1, 1))+ old.metadata = {"entities": ["acme"]}+ g.add_decision(old)+ new_id = g.add_decision(+ category="terms", scenario=SCENARIO, reasoning="r",+ outcome="o", confidence=1.0, entities=["acme"],+ )+ g.trace_decision_causality(new_id)+++def test_metadata_cannot_override_core_fields():+ g = ContextGraph()+ d = _decision()+ d.metadata = {"confidence": "high", "category": ["x"], "note": "kept"}+ g.add_decision(d)+ props = g.nodes["D1"].properties+ assert props["confidence"] == 1.0+ assert props["category"] == "terms"+ assert props["note"] == "kept"+ assert "D1" in g._decision_index["terms"]+++def test_invalid_values_rejected_before_graph_mutation():+ g = ContextGraph()+ d = _decision()+ d.metadata = {"entities": [["unhashable"]]}+ with pytest.raises(ValueError):+ g.add_decision(d)+ assert "D1" not in g.nodes+ assert "D1" not in getattr(g, "_decisions", {})++ d = _decision()+ d.category = ["unhashable"]+ with pytest.raises(ValueError):+ g.add_decision(d)+ assert "D1" not in g.nodes+++def test_utc_marker_is_timezone_independent():+ utc = ContextGraph._decision_sort_ts("2026-04-01T00:00:00Z")+ offset = ContextGraph._decision_sort_ts("2026-04-01T00:00:00+00:00")+ expected = datetime(2026, 4, 1, tzinfo=timezone.utc).timestamp()+ assert utc == offset == expected+++def test_agent_context_precedents_with_mixed_add_paths():+ from unittest.mock import Mock++ from semantica.context.agent_context import AgentContext++ g = ContextGraph()+ g.add_decision(_decision("OBJ", ts=datetime(2026, 4, 1)))+ kw_id = g.add_decision(+ category="terms", scenario=SCENARIO, reasoning="r",+ outcome="o", confidence=1.0,+ )+ ctx = AgentContext(+ vector_store=Mock(), knowledge_graph=g, decision_tracking=True+ )+ precedents = ctx.find_precedents(SCENARIO, use_hybrid_search=False)+ by_id = {d.decision_id: d for d in precedents}+ assert set(by_id) == {"OBJ", kw_id}+ assert by_id["OBJ"].timestamp == datetime(2026, 4, 1)+ assert by_id[kw_id].timestamp == datetime.fromtimestamp(+ g._decisions[kw_id]["timestamp"]+ )+++def test_utc_marker_kept_on_add_decision_path():+ g = ContextGraph()+ g.add_decision(_decision("Z1", ts="2026-04-01T00:00:00Z"))+ expected = datetime(2026, 4, 1, tzinfo=timezone.utc).timestamp()+ assert g.nodes["Z1"].properties["timestamp"] == "2026-04-01T00:00:00+00:00"+ assert g._temporal_index == [("Z1", expected)]