Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(context): stop record_decision returning an id for a decision it dropped (#1871)

Shubham Srivastava8fec65d518f0
diff --git a/semantica/cli.py b/semantica/cli.py
index c5840b77..9d4af98c 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -3394,11 +3394,8 @@ def decision_record(cli_ctx: CLIContext, title: str, tags: Optional[str],
# ContextGraph tracks node validity itself, so pass the
# dates as validity rather than leaving them in
# metadata, where they would not bound the node.
- # They must also be REMOVED from the metadata: it is
- # splatted into add_node() alongside these arguments,
- # and a duplicate key raises a TypeError that
- # record_decision logs and swallows, leaving an empty
- # graph behind a successful exit code.
+ # They are kept out of the metadata as well, since the
+ # graph ignores metadata keys that name node fields.
metadata={
k: v for k, v in cross_ctx.items()
if k not in ("valid_from", "valid_until")
diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.py
index 6159d447..f81fedb8 100644
--- a/semantica/context/context_graph.py
+++ b/semantica/context/context_graph.py
@@ -4441,6 +4441,11 @@ class ContextGraph:
for key, value in kwargs.items():
if not isinstance(key, str) or not key.strip():
raise ValueError("Additional field names must be non-empty strings")
+ if key == "id":
+ # kwargs are merged last into the decision mapping, so an "id"
+ # would replace the generated one and the returned id would no
+ # longer name the stored node.
+ raise ValueError("'id' is reserved; the decision id is generated")
if len(key.strip()) > 100:
raise ValueError("Additional field names must be 100 characters or less")
if len(str(value)) > 1000:
@@ -4938,111 +4943,136 @@ class ContextGraph:
# --- Private helper methods for decision management ---
def _add_decision_to_graph(self, decision: Dict[str, Any]) -> None:
- """Add decision to context graph."""
- try:
- protected_properties = {
- "category",
- "scenario",
- "reasoning",
- "outcome",
- "confidence",
- "timestamp",
- "decision_maker",
- }
- safe_metadata = {
- key: value
- for key, value in (decision.get("metadata") or {}).items()
- if key not in protected_properties
- }
- extra_properties = {
- key: value
- for key, value in decision.items()
- if key not in {
- "id",
- "category",
- "scenario",
- "reasoning",
- "outcome",
- "confidence",
- "entities",
- "decision_maker",
- "timestamp",
- "recorded_at",
- "valid_from",
- "valid_until",
- "metadata",
- }
- }
- # Add decision node
- self.add_node(
- decision["id"],
- "decision",
- content=decision["scenario"],
- valid_from=decision.get("valid_from"),
- valid_until=decision.get("valid_until"),
- category=decision["category"],
- outcome=decision["outcome"],
- confidence=decision["confidence"],
- timestamp=decision["timestamp"],
- scenario=decision["scenario"],
- decision_maker=decision.get("decision_maker", ""),
- reasoning=decision["reasoning"],
- recorded_at=decision.get("recorded_at", ""),
- **safe_metadata,
- **extra_properties,
- )
-
- # Add entity nodes and relationships
- for entity in decision["entities"]:
- # Add entity node if not exists
- if not self.find_node(entity):
- self.add_node(
+ """Add decision to context graph.
+
+ All-or-nothing: on any failure the nodes and edges created by this call
+ are removed again and the exception is re-raised, so a decision is
+ never left half-stored and ``record_decision`` never reports success
+ for one that is not in the graph.
+ """
+ # Every name add_node() receives other than through **properties, plus
+ # the keywords passed explicitly below. A metadata key or **kwargs
+ # entry under one of these names would arrive twice and raise
+ # TypeError, so both mappings are filtered by the same set. "self" is
+ # included because a bound method rejects it as a keyword too.
+ node_properties = {
+ "self",
+ "node_id",
+ "node_type",
+ "content",
+ "category",
+ "scenario",
+ "reasoning",
+ "outcome",
+ "confidence",
+ "timestamp",
+ "decision_maker",
+ "recorded_at",
+ "valid_from",
+ "valid_until",
+ }
+ # Keys of the decision mapping handled structurally, not as node
+ # properties.
+ structural_keys = {"id", "entities", "metadata"}
+ safe_metadata = {
+ key: value
+ for key, value in (decision.get("metadata") or {}).items()
+ if key not in node_properties
+ }
+ extra_properties = {
+ key: value
+ for key, value in decision.items()
+ if key not in node_properties and key not in structural_keys
+ }
+
+ with self._lock:
+ nodes_before = set(self.nodes)
+ edges_before = len(self.edges)
+ try:
+ # Add decision node
+ if not self.add_node(
+ decision["id"],
+ "decision",
+ content=decision["scenario"],
+ valid_from=decision.get("valid_from"),
+ valid_until=decision.get("valid_until"),
+ category=decision["category"],
+ outcome=decision["outcome"],
+ confidence=decision["confidence"],
+ timestamp=decision["timestamp"],
+ scenario=decision["scenario"],
+ decision_maker=decision.get("decision_maker", ""),
+ reasoning=decision["reasoning"],
+ recorded_at=decision.get("recorded_at", ""),
+ **safe_metadata,
+ **extra_properties,
+ ):
+ raise ValueError(
+ f"Decision node {decision['id']!r} was rejected by the graph"
+ )
+
+ # Add entity nodes and relationships
+ for entity in decision["entities"]:
+ # Add entity node if not exists
+ if not self.find_node(entity):
+ self.add_node(
+ entity,
+ "entity",
+ name=entity
+ )
+
+ # Add relationship
+ self.add_edge(
+ decision["id"],
entity,
- "entity",
- name=entity
+ "involves",
+ confidence=decision["confidence"]
)
-
- # Add relationship
+
+ # Add category node and relationship
+ category_id = f"category_{decision['category']}"
+ if not self.find_node(category_id):
+ self.add_node(
+ category_id,
+ "category",
+ name=decision["category"]
+ )
+
self.add_edge(
decision["id"],
- entity,
- "involves",
- confidence=decision["confidence"]
- )
-
- # Add category node and relationship
- category_id = f"category_{decision['category']}"
- if not self.find_node(category_id):
- self.add_node(
category_id,
- "category",
- name=decision["category"]
+ "belongs_to"
)
-
- self.add_edge(
- decision["id"],
- category_id,
- "belongs_to"
- )
-
- # Add decision maker node if provided
- if decision.get("decision_maker"):
- maker_id = f"maker_{decision['decision_maker']}"
- if not self.find_node(maker_id):
- self.add_node(
+
+ # Add decision maker node if provided
+ if decision.get("decision_maker"):
+ maker_id = f"maker_{decision['decision_maker']}"
+ if not self.find_node(maker_id):
+ self.add_node(
+ maker_id,
+ "decision_maker",
+ name=decision["decision_maker"]
+ )
+
+ self.add_edge(
+ decision["id"],
maker_id,
- "decision_maker",
- name=decision["decision_maker"]
+ "made_by"
)
-
- self.add_edge(
- decision["id"],
- maker_id,
- "made_by"
- )
-
- except Exception as e:
- self.logger.exception("Failed to add decision to graph")
+
+ except Exception:
+ # Do not swallow this. record_decision() has already generated
+ # the id it is about to return, so a silent failure here hands
+ # the caller a plausible identifier for a decision that is not
+ # in the graph. Undo the partial write first so a retry does
+ # not stack a second decision on top of orphaned nodes/edges.
+ self.logger.exception("Failed to add decision to graph")
+ for edge in list(self.edges[edges_before:]):
+ self._drop_edge_from_indexes(edge)
+ self._edge_index.pop(edge.edge_id, None)
+ for node_id in set(self.nodes) - nodes_before:
+ self._drop_node_from_indexes(node_id)
+ raise
def _decision_matches_temporal_filters(
self,
diff --git a/tests/context/test_context_graph_decisions.py b/tests/context/test_context_graph_decisions.py
index f8dc9b4e..6cf110f9 100644
--- a/tests/context/test_context_graph_decisions.py
+++ b/tests/context/test_context_graph_decisions.py
@@ -938,3 +938,117 @@ class TestContextGraphDecisionsEdgeCases:
if __name__ == "__main__":
pytest.main([__file__])
+
+
+class TestRecordDecisionReservedKeys:
+ """record_decision() must never return an id for a decision it dropped.
+
+ `_add_decision_to_graph` passes a fixed set of keywords to `add_node()` and
+ splats the caller's metadata and **kwargs alongside them. A key under one of
+ those names arrived twice and raised TypeError, which the surrounding
+ handler logged and swallowed — so the caller got a plausible UUID for a
+ decision that was never in the graph, and nothing surfaced until a read.
+ """
+
+ @pytest.fixture
+ def graph(self):
+ return ContextGraph()
+
+ def _record(self, graph, **extra):
+ return graph.record_decision(
+ category="pilot", scenario="Trial", reasoning="because",
+ outcome="recorded", confidence=1.0, **extra
+ )
+
+ @pytest.mark.parametrize("key", [
+ "valid_from", "valid_until", "content", "recorded_at",
+ "category", "scenario", "reasoning", "outcome", "confidence",
+ "timestamp", "decision_maker",
+ "node_id", "node_type", "self",
+ ])
+ def test_metadata_may_shadow_any_node_property(self, graph, key):
+ """A metadata key matching an add_node argument must not drop the node."""
+ decision_id = self._record(graph, metadata={key: "2026-01-01T00:00:00"})
+
+ stored = graph.get_nodes_by_label("decision")
+ assert len(stored) == 1, f"metadata key {key!r} lost the decision"
+ assert stored[0]["id"] == decision_id
+
+ def test_validity_arguments_alongside_matching_metadata(self, graph):
+ """The reported case: validity passed explicitly *and* in metadata."""
+ decision_id = self._record(
+ graph,
+ metadata={"valid_from": "2026-01-01T00:00:00"},
+ valid_from="2026-02-01T00:00:00",
+ valid_until="2026-03-01T00:00:00",
+ )
+
+ stored = graph.get_nodes_by_label("decision")
+ assert len(stored) == 1
+ assert stored[0]["id"] == decision_id
+
+ @pytest.mark.parametrize("key", ["content", "node_id", "node_type"])
+ def test_kwargs_may_shadow_a_node_property(self, graph, key):
+ """**kwargs lands in the decision mapping and was filtered separately."""
+ decision_id = self._record(graph, **{key: "some other value"})
+
+ stored = graph.get_nodes_by_label("decision")
+ assert len(stored) == 1
+ assert stored[0]["id"] == decision_id
+
+ def test_kwargs_cannot_replace_the_generated_id(self, graph):
+ """An "id" kwarg would make the returned id differ from the stored one."""
+ with pytest.raises(ValueError, match="reserved"):
+ self._record(graph, id="custom-id")
+ assert graph.get_nodes_by_label("decision") == []
+
+ def test_a_recorded_id_is_always_present_in_the_graph(self, graph):
+ """The invariant the bug violated: returned id => node exists."""
+ decision_id = self._record(graph, metadata={"risk": "low"})
+ assert graph.find_node(decision_id) is not None
+
+ def test_failure_to_add_is_raised_not_swallowed(self, graph, monkeypatch):
+ """A genuine add failure must reach the caller, not log and return an id."""
+ def boom(*args, **kwargs):
+ raise RuntimeError("storage is down")
+
+ monkeypatch.setattr(graph, "add_node", boom)
+ with pytest.raises(RuntimeError, match="storage is down"):
+ self._record(graph)
+
+ def test_partial_failure_leaves_no_orphans_and_retry_is_clean(self, graph, monkeypatch):
+ """A failure after the decision node is written must roll it back."""
+ real_add_edge = graph.add_edge
+ calls = {"n": 0}
+
+ def flaky_add_edge(*args, **kwargs):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("edge store failed")
+ return real_add_edge(*args, **kwargs)
+
+ monkeypatch.setattr(graph, "add_edge", flaky_add_edge)
+ with pytest.raises(RuntimeError, match="edge store failed"):
+ self._record(graph, entities=["acme"], decision_maker="alice")
+
+ assert len(graph.nodes) == 0
+ assert len(graph.edges) == 0
+ assert graph.get_nodes_by_label("decision") == []
+
+ # The retry succeeds and is the only decision in the graph.
+ decision_id = self._record(graph, entities=["acme"], decision_maker="alice")
+ stored = graph.get_nodes_by_label("decision")
+ assert [n["id"] for n in stored] == [decision_id]
+ assert graph.find_node(decision_id) is not None
+
+ def test_rollback_keeps_pre_existing_nodes(self, graph, monkeypatch):
+ """Rollback removes only what this call created."""
+ graph.add_node("acme", "entity", name="acme")
+ monkeypatch.setattr(
+ graph, "add_edge",
+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")),
+ )
+ with pytest.raises(RuntimeError):
+ self._record(graph, entities=["acme"])
+
+ assert set(graph.nodes) == {"acme"}