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: surface partial directory ingestion failures
Sameer Kadamf8a560fb943a
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.pyindex e1018462..a0bc9e34 100644--- a/semantica/ingest/__init__.py+++ b/semantica/ingest/__init__.py@@ -161,6 +161,7 @@ from .file_ingestor import (FileObject,FileTypeDetector,)+from ..utils.exceptions import PartialIngestionWarningfrom .methods import (get_ingest_method,ingest,@@ -452,6 +453,7 @@ __all__ = ["FileObject","FileTypeDetector","CloudStorageIngestor",+ "PartialIngestionWarning",# Web ingestion"WebIngestor","WebContent",diff --git a/semantica/ingest/file_ingestor.py b/semantica/ingest/file_ingestor.pyindex f2a4ca41..480ba757 100644--- a/semantica/ingest/file_ingestor.py+++ b/semantica/ingest/file_ingestor.py@@ -23,10 +23,11 @@ License: MIT"""import mimetypes+import warningsfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional, Union+from typing import Any, Dict, List, Optional, Tuple, Unionfrom ..utils.constants import (FILE_SIZE_LIMITS,@@ -35,7 +36,7 @@ from ..utils.constants import (SUPPORTED_IMAGE_FORMATS,SUPPORTED_VIDEO_FORMATS,)-from ..utils.exceptions import ProcessingError, ValidationError+from ..utils.exceptions import PartialIngestionWarning, ProcessingError, ValidationErrorfrom ..utils.logging import get_loggerfrom ..utils.progress_tracker import get_progress_tracker@@ -473,13 +474,30 @@ class FileIngestor:"""Ingest all files from a directory.+ When ``fail_fast=False`` (the default) and one or more files cannot be+ processed, the successfully ingested files are still returned and a+ :class:`~semantica.utils.exceptions.PartialIngestionWarning` is emitted+ so callers are not silently handed an incomplete result. Use+ ``warnings.catch_warnings()`` to capture or suppress it programmatically.++ When ``fail_fast=True``, the first per-file failure raises a+ :class:`~semantica.utils.exceptions.ProcessingError` immediately.+Args:directory_path: Path to directory- recursive: Whether to scan subdirectories- **filters: File filtering criteria+ recursive: Whether to scan subdirectories (default: True)+ **filters: File filtering criteria (see :meth:`scan_directory`)Returns:- list: List of ingested file objects+ list: List of successfully ingested file objects. May be a subset+ of the discovered files if some failed and ``fail_fast=False``.++ Raises:+ ValidationError: If *directory_path* does not exist or is not a directory.+ ProcessingError: If a per-file failure occurs and ``fail_fast=True``.++ Warns:+ PartialIngestionWarning: If any files failed and ``fail_fast=False``."""directory_path = Path(directory_path)@@ -503,7 +521,8 @@ class FileIngestor:files = self.scan_directory(directory_path, recursive=recursive, **filters)# Process each file- file_objects = []+ file_objects: List[FileObject] = []+ failed_files: List[Tuple[str, Exception]] = []total_files = len(files)self.progress_tracker.update_tracking(@@ -537,12 +556,31 @@ class FileIngestor:except Exception as e:self.logger.error(f"Failed to ingest file {file_info['path']}: {e}")if self.config.get("fail_fast", False):- raise ProcessingError(f"Failed to ingest file: {e}")+ raise ProcessingError(f"Failed to ingest file: {e}") from e+ failed_files.append((file_info["path"], e))++ # Surface partial failures to the caller via a warning so that+ # downstream consumers are not silently handed an incomplete result.+ if failed_files:+ failed_paths = ", ".join(p for p, _ in failed_files)+ warnings.warn(+ f"{len(failed_files)} of {total_files} file(s) could not be "+ f"ingested from '{directory_path}' and were skipped. "+ f"Successfully ingested: {len(file_objects)}. "+ f"Failed paths: {failed_paths}",+ PartialIngestionWarning,+ stacklevel=2,+ )+ status_message = (+ f"Ingested {len(file_objects)}/{total_files} files"+ if failed_files+ else f"Ingested {len(file_objects)} files"+ )self.progress_tracker.stop_tracking(tracking_id,status="completed",- message=f"Ingested {len(file_objects)} files",+ message=status_message,)return file_objectsdiff --git a/semantica/utils/exceptions.py b/semantica/utils/exceptions.pyindex 234756cf..f7f9316e 100644--- a/semantica/utils/exceptions.py+++ b/semantica/utils/exceptions.py@@ -179,6 +179,32 @@ class TemporalAmbiguityWarning(UserWarning):pass+class PartialIngestionWarning(UserWarning):+ """+ Warning raised when a directory ingestion completes but one or more files+ could not be processed.++ The successfully ingested files are still returned by+ ``FileIngestor.ingest_directory()``. This warning carries the count of+ failures and the list of failed paths so callers can decide whether the+ partial result is acceptable.++ Example::++ import warnings+ from semantica.ingest import FileIngestor+ from semantica.utils.exceptions import PartialIngestionWarning++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ files = FileIngestor().ingest_directory("./docs")+ if caught:+ print(caught[0].message)+ """++ pass++class ProcessingError(SemanticaError):"""Exception raised for data processing errors.diff --git a/tests/ingest/test_file_ingestor.py b/tests/ingest/test_file_ingestor.pyindex de7d6592..1ab36a18 100644--- a/tests/ingest/test_file_ingestor.py+++ b/tests/ingest/test_file_ingestor.py@@ -1,5 +1,6 @@import sysimport types+import warningsfrom unittest.mock import MagicMock# --- Mock missing cloud modules ---@@ -40,6 +41,7 @@ from semantica.ingest.file_ingestor import ( # noqa: E402ProcessingError,ValidationError,)+from semantica.utils.exceptions import PartialIngestionWarning # noqa: E402# --- Fixtures ---@@ -356,3 +358,126 @@ def test_scan_directory_filters(temp_files: Path) -> None:assert len(res_max) == 1 # Expect latin.txtassert len(res_min) >= 3+++# ---------------------------------------------------------------------------+# Regression tests: partial-failure signalling in ingest_directory+# (covers the fix for silent per-file data loss — Hotspot 6)+# ---------------------------------------------------------------------------++def test_ingest_directory_partial_failure_emits_warning(tmp_path: Path) -> None:+ """+ When fail_fast=False (default) and one file fails, ingest_directory must+ emit a PartialIngestionWarning so the caller is not silently given an+ incomplete result.+ """+ (tmp_path / "good1.txt").write_text("ok", encoding="utf-8")+ (tmp_path / "bad.txt").write_text("will fail", encoding="utf-8")+ (tmp_path / "good2.txt").write_text("ok", encoding="utf-8")++ ingestor = FileIngestor()+ original_ingest_file = ingestor.ingest_file++ def selective_fail(*args, **opts):+ # ingest_file receives path as the first positional argument+ path = args[0] if args else opts.get("path", "")+ if "bad" in str(path):+ raise RuntimeError("Simulated per-file failure")+ return original_ingest_file(*args, **opts)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ with patch.object(ingestor, "ingest_file", side_effect=selective_fail):+ results = ingestor.ingest_directory(tmp_path)++ # Exactly one PartialIngestionWarning must have been emitted.+ partial_warnings = [w for w in caught if issubclass(w.category, PartialIngestionWarning)]+ assert len(partial_warnings) == 1, (+ "Expected exactly one PartialIngestionWarning; "+ f"got {len(partial_warnings)}"+ )+++def test_ingest_directory_partial_failure_warning_content(tmp_path: Path) -> None:+ """+ The emitted PartialIngestionWarning message must contain:+ - the failed-file count+ - the total-file count+ - the path of the failed file+ """+ (tmp_path / "a.txt").write_text("ok", encoding="utf-8")+ (tmp_path / "broken.txt").write_text("boom", encoding="utf-8")++ ingestor = FileIngestor()+ original_ingest_file = ingestor.ingest_file++ def fail_broken(*args, **opts):+ # ingest_file receives path as the first positional argument+ path = args[0] if args else opts.get("path", "")+ if "broken" in str(path):+ raise OSError("permission denied")+ return original_ingest_file(*args, **opts)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ with patch.object(ingestor, "ingest_file", side_effect=fail_broken):+ ingestor.ingest_directory(tmp_path)++ assert caught, "No PartialIngestionWarning was emitted"+ msg = str(caught[0].message)+ assert "1 of 2" in msg, f"Expected '1 of 2' in warning message; got: {msg!r}"+ assert "broken.txt" in msg, f"Expected failed path in warning message; got: {msg!r}"+++def test_ingest_directory_partial_failure_successes_still_returned(tmp_path: Path) -> None:+ """+ When fail_fast=False and one file fails, the successfully ingested files+ are still present in the return value.+ """+ (tmp_path / "good1.txt").write_text("hello", encoding="utf-8")+ (tmp_path / "bad.txt").write_text("will fail", encoding="utf-8")+ (tmp_path / "good2.txt").write_text("world", encoding="utf-8")++ ingestor = FileIngestor()+ original_ingest_file = ingestor.ingest_file++ def selective_fail(*args, **opts):+ # ingest_file receives path as the first positional argument+ path = args[0] if args else opts.get("path", "")+ if "bad" in str(path):+ raise RuntimeError("Simulated per-file failure")+ return original_ingest_file(*args, **opts)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always", PartialIngestionWarning)+ with patch.object(ingestor, "ingest_file", side_effect=selective_fail):+ results = ingestor.ingest_directory(tmp_path)++ result_names = {r.name for r in results}+ assert "good1.txt" in result_names, "good1.txt should be in results"+ assert "good2.txt" in result_names, "good2.txt should be in results"+ assert "bad.txt" not in result_names, "bad.txt must not appear in results"+ assert len(results) == 2+++def test_ingest_directory_fail_fast_true_raises_and_no_warning(tmp_path: Path) -> None:+ """+ When fail_fast=True, the first per-file failure must raise ProcessingError+ immediately without emitting a PartialIngestionWarning.+ """+ (tmp_path / "good.txt").write_text("ok", encoding="utf-8")+ (tmp_path / "bad.txt").write_text("boom", encoding="utf-8")++ ingestor = FileIngestor(fail_fast=True)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ with patch.object(ingestor, "ingest_file", side_effect=Exception("Boom")):+ with pytest.raises(ProcessingError):+ ingestor.ingest_directory(tmp_path)++ partial_warnings = [w for w in caught if issubclass(w.category, PartialIngestionWarning)]+ assert partial_warnings == [], (+ "No PartialIngestionWarning should be emitted when fail_fast=True; "+ f"got {partial_warnings}"+ )