Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat: add validation checks

Tiberiu Sabău14b3b6b19b62
diff --git a/semantica/export/__init__.py b/semantica/export/__init__.py
index 27aee7b8..51e304ac 100644
--- a/semantica/export/__init__.py
+++ b/semantica/export/__init__.py
@@ -126,11 +126,10 @@ Convenience Functions:
- export_lpg: LPG export wrapper
- generate_report: Report generation wrapper
-Example Usage:, export_parquet
+Example Usage:
>>> # Using convenience function
>>> export_lpg(kg, "output.cypher", method="cypher")
- >>> export_parquet(entities, "output.parquet", compression="snappy
- >>> export_lpg(kg, "output.cypher", method="cypher")
+ >>> export_parquet(entities, "output.parquet", compression="snappy")
>>> # Using classes directly
>>> json_exporter = JSONExporter()
>>> json_exporter.export_knowledge_graph(kg, "output.json")
@@ -201,7 +200,6 @@ __all__ = [
"NamespaceManager",
"JSONExporter",
"CSVExporter",
- "ArrowExporter",
"ParquetExporter",
"GraphExporter",
"SemanticNetworkYAMLExporter",
diff --git a/semantica/export/parquet_exporter.py b/semantica/export/parquet_exporter.py
index 2e698765..b2d6911e 100644
--- a/semantica/export/parquet_exporter.py
+++ b/semantica/export/parquet_exporter.py
@@ -255,7 +255,13 @@ class ParquetExporter:
)
# If no schema provided, try to auto-detect from data structure
- if schema is None and data:
+ if schema is None:
+ if not data:
+ raise ValidationError(
+ "Cannot export empty list without explicit schema. "
+ "Provide a schema or use "
+ "export_entities/export_relationships."
+ )
sample = data[0]
has_source = any(
k in sample for k in ["source_id", "source", "from_id", "from"]
@@ -344,15 +350,55 @@ class ParquetExporter:
self.logger.warning(f"Entity {i} missing ID, skipping")
continue
+ # Normalize confidence to float, with validation
+ raw_confidence = entity.get("confidence")
+ confidence_value = None
+ if raw_confidence is not None:
+ try:
+ confidence_value = float(raw_confidence)
+ except (TypeError, ValueError):
+ self.logger.warning(
+ f"Entity {i} has non-numeric confidence {raw_confidence!r}; "
+ "setting to None"
+ )
+ confidence_value = None
+
+ # Normalize start/end to int, with validation
+ start_value = entity.get("start")
+ if start_value is None:
+ start_value = entity.get("start_offset")
+ if start_value is not None:
+ try:
+ start_value = int(start_value)
+ except (TypeError, ValueError):
+ self.logger.warning(
+ f"Entity {i} has non-integer start {start_value!r}; "
+ "setting to None"
+ )
+ start_value = None
+
+ end_value = entity.get("end")
+ if end_value is None:
+ end_value = entity.get("end_offset")
+ if end_value is not None:
+ try:
+ end_value = int(end_value)
+ except (TypeError, ValueError):
+ self.logger.warning(
+ f"Entity {i} has non-integer end {end_value!r}; "
+ "setting to None"
+ )
+ end_value = None
+
normalized = {
"id": str(entity_id),
"text": (
entity.get("text") or entity.get("label") or entity.get("name")
),
"type": entity.get("type") or entity.get("entity_type"),
- "confidence": entity.get("confidence"),
- "start": entity.get("start") or entity.get("start_offset"),
- "end": entity.get("end") or entity.get("end_offset"),
+ "confidence": confidence_value,
+ "start": start_value,
+ "end": end_value,
}
# Convert metadata to struct format (keys and values lists)
@@ -374,6 +420,12 @@ class ParquetExporter:
f"Normalized {len(normalized_entities)} entity(ies) for Parquet export"
)
+ if not normalized_entities:
+ raise ValidationError(
+ "No valid entities to export after normalization. "
+ "All entities were skipped due to missing IDs or invalid format."
+ )
+
self._write_parquet(
normalized_entities, file_path, schema=ENTITY_SCHEMA, **options
)
@@ -451,6 +503,19 @@ class ParquetExporter:
# Generate ID if missing
rel_id = rel.get("id") or rel.get("relationship_id") or f"rel_{i}"
+ # Normalize confidence to float, with validation
+ raw_confidence = rel.get("confidence")
+ confidence_value = None
+ if raw_confidence is not None:
+ try:
+ confidence_value = float(raw_confidence)
+ except (TypeError, ValueError):
+ self.logger.warning(
+ f"Relationship {i} has non-numeric confidence "
+ f"{raw_confidence!r}; setting to None"
+ )
+ confidence_value = None
+
normalized = {
"id": str(rel_id),
"source_id": str(source_id),
@@ -460,7 +525,7 @@ class ParquetExporter:
or rel.get("relationship_type")
or rel.get("relation_type")
),
- "confidence": rel.get("confidence"),
+ "confidence": confidence_value,
}
# Convert metadata to struct format (keys and values lists)
@@ -482,6 +547,13 @@ class ParquetExporter:
f"Normalized {len(normalized_rels)} relationship(s) for Parquet export"
)
+ if not normalized_rels:
+ raise ValidationError(
+ "No valid relationships to export after normalization. "
+ "Ensure each relationship is a dictionary and includes valid "
+ "'source'/'source_id' and 'target'/'target_id' fields."
+ )
+
self._write_parquet(
normalized_rels, file_path, schema=RELATIONSHIP_SCHEMA, **options
)
diff --git a/tests/test_parquet_exporter.py b/tests/test_parquet_exporter.py
index 0ae37bf8..83ca3a35 100644
--- a/tests/test_parquet_exporter.py
+++ b/tests/test_parquet_exporter.py
@@ -150,17 +150,41 @@ class TestParquetExporter(unittest.TestCase):
def test_export_entities_with_compression(self):
"""Test entity export with different compression codecs."""
+ import pyarrow.parquet as pq_module
+
for compression in ["snappy", "gzip", "brotli", "zstd", "lz4", "none"]:
with self.subTest(compression=compression):
- exporter = ParquetExporter(compression=compression)
- output_path = Path(self.test_dir) / f"entities_{compression}.parquet"
-
- exporter.export_entities(self.entities, str(output_path))
- self.assertTrue(output_path.exists())
-
- # Verify file can be read
- table = pq.read_table(str(output_path))
- self.assertEqual(table.num_rows, 2)
+ # Check if codec is available in this pyarrow build
+ try:
+ # Test codec availability by checking compression opts
+ if compression != "none":
+ codec_available = compression.upper() in dir(
+ pq_module.lib.Codec
+ )
+ if not codec_available:
+ self.skipTest(
+ f"Codec {compression} not available in " "pyarrow build"
+ )
+ except AttributeError:
+ # If we can't check, just try and skip on error
+ pass
+
+ try:
+ exporter = ParquetExporter(compression=compression)
+ output_path = (
+ Path(self.test_dir) / f"entities_{compression}.parquet"
+ )
+
+ exporter.export_entities(self.entities, str(output_path))
+ self.assertTrue(output_path.exists())
+
+ # Verify file can be read
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 2)
+ except (ImportError, RuntimeError, OSError) as e:
+ if "codec" in str(e).lower() or "compression" in str(e).lower():
+ self.skipTest(f"Codec {compression} not available: {e}")
+ raise
def test_export_entities_empty(self):
"""Test exporting empty entities list raises ValidationError."""
@@ -436,6 +460,87 @@ class TestParquetExporter(unittest.TestCase):
table = pq.read_table(str(output_path))
self.assertEqual(table.num_rows, 2)
+ def test_all_entities_skipped_raises_error(self):
+ """Test that exporting entities with all skipped raises ValidationError."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "all_skipped.parquet"
+
+ # All entities missing IDs
+ bad_entities = [
+ {"text": "No ID 1"},
+ {"text": "No ID 2"},
+ "not a dict",
+ ]
+
+ with self.assertRaises(ValidationError) as cm:
+ exporter.export_entities(bad_entities, str(output_path))
+
+ self.assertIn("No valid entities", str(cm.exception))
+
+ def test_all_relationships_skipped_raises_error(self):
+ """Test that exporting relationships with all skipped raises ValidationError."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "all_rels_skipped.parquet"
+
+ # All relationships missing source or target
+ bad_rels = [
+ {"id": "r1", "source_id": "e1"}, # Missing target
+ {"id": "r2", "target_id": "e2"}, # Missing source
+ "not a dict",
+ ]
+
+ with self.assertRaises(ValidationError) as cm:
+ exporter.export_relationships(bad_rels, str(output_path))
+
+ self.assertIn("No valid relationships", str(cm.exception))
+
+ def test_invalid_confidence_values_handled(self):
+ """Test that invalid confidence values are handled gracefully."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "invalid_confidence.parquet"
+
+ entities_with_invalid_conf = [
+ {"id": "e1", "text": "Valid", "confidence": 0.9},
+ {"id": "e2", "text": "String conf", "confidence": "invalid"},
+ {"id": "e3", "text": "None conf", "confidence": None},
+ ]
+
+ exporter.export_entities(entities_with_invalid_conf, str(output_path))
+
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 3)
+ # First entity has valid confidence
+ self.assertEqual(table.column("confidence")[0].as_py(), 0.9)
+ # Second entity has invalid confidence (should be None)
+ self.assertIsNone(table.column("confidence")[1].as_py())
+ # Third entity has None confidence
+ self.assertIsNone(table.column("confidence")[2].as_py())
+
+ def test_invalid_start_end_values_handled(self):
+ """Test that invalid start/end offset values are handled gracefully."""
+ exporter = ParquetExporter()
+ output_path = Path(self.test_dir) / "invalid_offsets.parquet"
+
+ entities_with_invalid_offsets = [
+ {"id": "e1", "text": "Valid", "start": 0, "end": 10},
+ {"id": "e2", "text": "String offsets", "start": "abc", "end": "def"},
+ {"id": "e3", "text": "None offsets", "start": None, "end": None},
+ ]
+
+ exporter.export_entities(entities_with_invalid_offsets, str(output_path))
+
+ table = pq.read_table(str(output_path))
+ self.assertEqual(table.num_rows, 3)
+ # First entity has valid offsets
+ self.assertEqual(table.column("start")[0].as_py(), 0)
+ self.assertEqual(table.column("end")[0].as_py(), 10)
+ # Second entity has invalid offsets (should be None)
+ self.assertIsNone(table.column("start")[1].as_py())
+ self.assertIsNone(table.column("end")[1].as_py())
+ # Third entity has None offsets
+ self.assertIsNone(table.column("start")[2].as_py())
+ self.assertIsNone(table.column("end")[2].as_py())
+
if __name__ == "__main__":
unittest.main()