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: address ingestion review findings
Sameer Kadamb97b3ab1eff4
diff --git a/semantica/ingest/file_ingestor.py b/semantica/ingest/file_ingestor.pyindex 480ba757..84373387 100644--- a/semantica/ingest/file_ingestor.py+++ b/semantica/ingest/file_ingestor.py@@ -27,7 +27,7 @@ import warningsfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import Any, Dict, List, Optional, Tuple, Union+from typing import Any, Dict, List, Optional, Unionfrom ..utils.constants import (FILE_SIZE_LIMITS,@@ -522,7 +522,10 @@ class FileIngestor:# Process each filefile_objects: List[FileObject] = []- failed_files: List[Tuple[str, Exception]] = []+ # Only paths are stored — retaining exception objects would pin+ # their tracebacks (and all referenced frame locals) for the entire+ # duration of the directory scan (Finding 2 fix).+ failed_paths_list: List[str] = []total_files = len(files)self.progress_tracker.update_tracking(@@ -530,10 +533,28 @@ class FileIngestor:)for idx, file_info in enumerate(files, 1):+ file_path_str = file_info["path"]++ # --- per-file ingestion (inner try) ---+ # Only ingest_file() is inside this scope. Post-success+ # side-effects (progress, callback, logging) are separated so+ # that a callback or display error cannot mis-classify a+ # successfully returned FileObject as a failure (Finding 1 fix).try:- file_obj = self.ingest_file(file_info["path"], **file_info)- file_objects.append(file_obj)+ file_obj = self.ingest_file(file_path_str, **file_info)+ except Exception as e:+ self.logger.error(f"Failed to ingest file {file_path_str}: {e}")+ if self.config.get("fail_fast", False):+ raise ProcessingError(f"Failed to ingest file: {e}") from e+ failed_paths_list.append(file_path_str)+ continue++ # ingest_file() succeeded — record the result first, then run+ # optional side-effects. Errors here are logged but do not+ # count the file as an ingestion failure.+ file_objects.append(file_obj)+ try:# Track progress with ETAself.progress_tracker.update_progress(tracking_id,@@ -541,7 +562,7 @@ class FileIngestor:total=total_files,message=(f"Processing file {idx}/{total_files}: "- f"{Path(file_info['path']).name}"+ f"{Path(file_path_str).name}"),)@@ -550,21 +571,25 @@ class FileIngestor:self._progress_callback(idx, total_files, file_obj)self.logger.debug(- f"Ingested file {idx}/{total_files}: {file_info['path']}"+ f"Ingested file {idx}/{total_files}: {file_path_str}"+ )+ except Exception as side_e:+ # The file was successfully ingested and is already in+ # file_objects — do NOT add its path to failed_paths_list.+ self.logger.error(+ f"Post-ingestion side-effect failed for {file_path_str}: {side_e}")-- 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}") from e- failed_files.append((file_info["path"], e))+ raise ProcessingError(+ f"Post-ingestion operation failed for {file_path_str}: {side_e}"+ ) from side_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)+ if failed_paths_list:+ failed_paths = ", ".join(failed_paths_list)warnings.warn(- f"{len(failed_files)} of {total_files} file(s) could not be "+ f"{len(failed_paths_list)} 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}",@@ -574,7 +599,7 @@ class FileIngestor:status_message = (f"Ingested {len(file_objects)}/{total_files} files"- if failed_files+ if failed_paths_listelse f"Ingested {len(file_objects)} files")self.progress_tracker.stop_tracking(diff --git a/tests/ingest/test_file_ingestor.py b/tests/ingest/test_file_ingestor.pyindex 1ab36a18..21c6ac96 100644--- a/tests/ingest/test_file_ingestor.py+++ b/tests/ingest/test_file_ingestor.py@@ -481,3 +481,88 @@ def test_ingest_directory_fail_fast_true_raises_and_no_warning(tmp_path: Path) -"No PartialIngestionWarning should be emitted when fail_fast=True; "f"got {partial_warnings}")++def test_ingest_directory_callback_error_fail_fast_false_does_not_count_as_ingestion_failure(+ tmp_path: Path,+) -> None:+ """+ Regression test for Qodo Finding 1 — fail_fast=False path.++ A successfully ingested file must NOT appear in failed_paths_list /+ PartialIngestionWarning merely because the post-ingestion callback raises.+ With fail_fast=False the error is logged and processing continues; the+ file stays in the returned results.+ """+ (tmp_path / "good.txt").write_text("content", encoding="utf-8")++ ingestor = FileIngestor() # fail_fast defaults to False++ def exploding_callback(idx, total, file_obj):+ raise RuntimeError("callback exploded")++ ingestor.set_progress_callback(exploding_callback)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ results = ingestor.ingest_directory(tmp_path)++ # File was successfully ingested — must be in results.+ assert len(results) == 1, (+ f"Expected 1 result; got {len(results)}. "+ "A callback error must not remove the file from the result."+ )+ assert results[0].name == "good.txt"++ # No ingestion failure → no PartialIngestionWarning.+ partial_warnings = [w for w in caught if issubclass(w.category, PartialIngestionWarning)]+ assert partial_warnings == [], (+ "A callback error must not trigger PartialIngestionWarning; "+ f"got: {[str(w.message) for w in partial_warnings]}"+ )+++def test_ingest_directory_callback_error_fail_fast_true_raises_processing_error(+ tmp_path: Path,+) -> None:+ """+ Regression test for Qodo Finding 1 — fail_fast=True path.++ When fail_fast=True, a post-ingestion callback failure must raise+ ProcessingError (preserving fail_fast semantics), but the successfully+ ingested file must NOT be added to failed_paths_list — i.e. the error+ must not be labelled as an ingestion failure.++ The ProcessingError message must NOT say "Failed to ingest file" (that+ wording is reserved for actual ingest_file() failures).+ """+ (tmp_path / "good.txt").write_text("content", encoding="utf-8")++ ingestor = FileIngestor(fail_fast=True)++ def exploding_callback(idx, total, file_obj):+ raise RuntimeError("callback exploded")++ ingestor.set_progress_callback(exploding_callback)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always", PartialIngestionWarning)+ with pytest.raises(ProcessingError) as exc_info:+ ingestor.ingest_directory(tmp_path)++ # The error must be chained from the original callback exception.+ assert exc_info.value.__cause__ is not None+ assert "callback exploded" in str(exc_info.value.__cause__)++ # The ProcessingError must distinguish a side-effect failure from an+ # ingestion failure — it must NOT say "Failed to ingest file".+ assert "Failed to ingest file" not in str(exc_info.value), (+ "fail_fast side-effect error must not be labelled as an ingestion failure"+ )++ # No PartialIngestionWarning should be emitted — the failure was not+ # an ingestion failure, and fail_fast raised before the warning point.+ partial_warnings = [w for w in caught if issubclass(w.category, PartialIngestionWarning)]+ assert partial_warnings == [], (+ "No PartialIngestionWarning should be emitted for a callback failure; "+ f"got: {[str(w.message) for w in partial_warnings]}"+ )