Skip to content

The import_traces() method will crash with an unhandled KeyError if a JSON file contains trace data with missing required fields like trace_id\, state\, input\, or output\. #7

@toolate28

Description

@toolate28

The import_traces() method will crash with an unhandled KeyError if a JSON file contains trace data with missing required fields like trace_id, state, input, or output.

View Details
📝 Patch Details
diff --git a/bridges/saif_npc/teleprompter.py b/bridges/saif_npc/teleprompter.py
index 0289d31..35087d0 100644
--- a/bridges/saif_npc/teleprompter.py
+++ b/bridges/saif_npc/teleprompter.py
@@ -71,7 +71,26 @@ class NpcTrace:
 
     @classmethod
     def from_dict(cls, data: Dict[str, Any]) -> 'NpcTrace':
-        """Create NpcTrace from dictionary."""
+        """Create NpcTrace from dictionary.
+        
+        Args:
+            data: Dictionary containing trace data
+            
+        Returns:
+            NpcTrace instance
+            
+        Raises:
+            ValueError: If any required field (trace_id, state, input, output) is missing
+        """
+        # Validate required fields
+        required_fields = ['trace_id', 'state', 'input', 'output']
+        missing_fields = [field for field in required_fields if field not in data]
+        if missing_fields:
+            raise ValueError(
+                f"Missing required fields in trace data: {missing_fields}. "
+                f"Trace data: {data}"
+            )
+        
         timestamp = data.get("timestamp")
         if timestamp and isinstance(timestamp, str):
             timestamp = datetime.fromisoformat(timestamp)
@@ -221,13 +240,41 @@ class NpcTeleprompter:
             json.dump(data, f, indent=2)
 
     def import_traces(self, filepath: str):
-        """Import traces from JSON file."""
+        """Import traces from JSON file.
+        
+        Args:
+            filepath: Path to JSON file containing traces
+            
+        Raises:
+            IOError: If file cannot be read
+            ValueError: If no valid traces can be loaded from the file
+        """
         with open(filepath, 'r', encoding='utf-8') as f:
             data = json.load(f)
 
-        for trace_data in data.get("traces", []):
-            trace = NpcTrace.from_dict(trace_data)
-            self.traces.append(trace)
+        traces_loaded = 0
+        errors = []
+        
+        for i, trace_data in enumerate(data.get("traces", [])):
+            try:
+                trace = NpcTrace.from_dict(trace_data)
+                self.traces.append(trace)
+                traces_loaded += 1
+            except (KeyError, ValueError) as e:
+                error_msg = f"Trace {i}: {str(e)}"
+                errors.append(error_msg)
+
+        if errors:
+            error_summary = "; ".join(errors)
+            raise ValueError(
+                f"Failed to import {len(errors)} trace(s) from {filepath}. "
+                f"Errors: {error_summary}"
+            )
+        
+        if traces_loaded == 0:
+            raise ValueError(
+                f"No valid traces found in {filepath}"
+            )
 
         # Trim to max_traces
         if len(self.traces) > self.max_traces:

Analysis

Unhandled KeyError when importing trace data with missing required fields

What fails: NpcTeleprompter.import_traces() raises unhandled KeyError if a JSON file contains trace data missing required fields (trace_id, state, input, or output)

How to reproduce:

import json
import tempfile
from bridges.saif_npc.teleprompter import NpcTeleprompter

# Create JSON with missing trace_id
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
    data = {
        "traces": [
            {
                "state": {"location": "town"},
                "input": "hello",
                "output": "response"
                # Missing trace_id
            }
        ]
    }
    json.dump(data, f)
    temp_file = f.name

teleprompter = NpcTeleprompter()
teleprompter.import_traces(temp_file)  # Raises unhandled KeyError: 'trace_id'

Result: Unhandled KeyError: 'trace_id' with no context about which trace caused the problem or what fields were missing. Entire import operation fails without loading any traces.

Expected: Should provide clear error message indicating which trace failed and what fields were missing, helping users fix corrupted or third-party generated JSON files.

Fix implemented:

  • Added validation in NpcTrace.from_dict() to check all required fields and raise descriptive ValueError with field names and trace data
  • Added try-except error handling in import_traces() to catch KeyError and ValueError exceptions and report all failures with trace index and error details

Originally posted by @vercel[bot] in toolate28/SpiralSafe#115 (comment)

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions