aiml

Lesson 7 of 37Module 3

Handle ingestion failures

Continue loading valid documents when another source fails. Keep accepted text and failure reasons together, and mark incomplete batches.

Prerequisites

Load Developer Documentation and Track Passage Sources.

By the end, you can

  • Retain per-source failures without reporting partial ingestion as complete.
  • Separate batch-level manifest errors from per-source load failures.
  • Use a nonzero CLI exit to signal incomplete ingestion.
Runtime
Python 3.11+; local files only
Dependencies
Python standard library; no model or third-party packages

Lab code, tests and fixtures (ZIP, 671 KB)Quiz check your understanding

Progress is saved in this browser.

One bad source should be visible in an ingestion report. Otherwise a corpus can look complete while quietly missing documents. A batch loader tries each listed source and keeps accepted documents beside explicit failure records.

There are two boundaries. A malformed manifest leaves the batch without a reliable list of what to load, so the batch stops before it reads any file. A valid manifest can still name individual bad files; the batch records each of those failures and tries the remaining sources. The result must still show that the load was partial, not complete.

When you need this. The strict loader in the preceding lesson stops at the first bad source, so one bad file blocks every other document in the batch.

Follow one example. The supplied exercise changes a temporary source file without changing its pinned hash. That source fails with hash_mismatch. The batch records the source ID, path and reason, then continues with the other listed files. Accepted documents go into documents, rejected attempts go into failures, and a nonzero exit tells shell automation that ingestion is incomplete.

You will add per-source handling around the existing strict loader. The exercise changes temporary copies of the original Python summaries and writes its report to a local file; it does not index a partial corpus or call a model.

Keep accepted documents and explain each refusal

Source manifestListed local filesAttempt eachsourceValidate one itemat a timeAccepted recordsRetain validdocumentsRejected itemKeep its failurereasonBatch reportAccepted andrefused itemsSource manifestListed local filesAttempt eachsourceValidate one itemat a timeAccepted recordsRetain validdocumentsRejected itemKeep its failurereasonBatch reportAccepted andrefused items
The batch report distinguishes accepted records from rejected items. A failed source does not become a successful document merely because the batch finishes. Dashed arrows show conditional paths.
  1. Attempt each listed file.
  2. Retain an accepted source.
  3. Record the reason for refusal.
  4. Include accepted records.
  5. Include refused items without pretending success.

Inspect the controlled batch. The supplied failure exercise loads 1 document and records 3 failures. The result below keeps the accepted document and the rejected attempts in one file.

Decide what stops the batch

An invalid manifest stops the batch before it tries any source. The manifest entries define the source identities and paths, so a batch that continued with an ambiguous manifest would produce a report that is hard to interpret.

A valid manifest can still name an unreadable or changed file. The batch catches the loader’s IngestionError for that source, records its ID, path and error, and continues to the next listed entry. It catches no other exception type, so a programming error still stops the run instead of appearing as bad input. When you add a new source check, raise IngestionError with a new reason string; do not widen the except clause.

Invalid manifest. Repair duplicate source identities or malformed manifest content, then rerun the batch. Per-file quarantine covers sources that the manifest lists validly but that fail to load; it does not guess what the manifest author intended.

Keep rejected attempts in the result

The result contains both documents and failures. Its status is complete when every source loads, partial when accepted and failed records coexist, and failed when no listed source loads. This status describes file ingestion, not whether a future answer will be correct.

Changed source. The exercise edits one temporary source without changing its expected hash. The loader reports hash_mismatch. The exercise deletes another source, which produces unreadable_source.

Invalid UTF-8. The exercise writes invalid UTF-8 into a different temporary file and pins the hash of those new bytes in its temporary manifest. The byte-hash check then passes, so the UTF-8 decode runs and fails with invalid_utf8. The original snapshot stays unchanged.

The report is the local quarantine record: the lab has no queue, persistent quarantine service, retry scheduler or vector-store write. Repair the named inputs and run another batch with a new output path; ingest.py overwrites an existing output file, and the earlier report is your record of what failed. Resume and incremental index updates belong to later modules.

Execute the controlled failure batch

Download the complete lab. The copied loader is identical to the preceding lesson’s implementation. The failure driver first validates the supplied snapshot, then changes temporary copies only.

ingest.pySource · pythonDownload
"""Quarantine bad local sources; explicitly report partial ingestion."""
import argparse
import hashlib
import json
from pathlib import Path
import tempfile
from load_documents import IngestionError, load_source, read_manifest

def ingest(manifest: Path) -> dict:
    # An invalid manifest fails the whole batch before any source is loaded.
    sources = read_manifest(manifest)
    documents, failures = [], []
    for source in sources:
        try:
            documents.append(load_source(manifest.parent, source))
        except IngestionError as error:
            failures.append({'source_id': source['source_id'], 'path': source['path'], 'error': str(error)})
    return {'schema_version': 1, 'execution_mode': 'offline-local-files',
            'status': 'partial' if failures and documents else 'failed' if failures else 'complete',
            'documents': documents, 'failures': failures}

def failure_exercise(manifest: Path) -> dict:
    """Mutate temporary copies only; leave the pinned source snapshot untouched."""
    sources = read_manifest(manifest)
    if len(sources) < 4:
        raise IngestionError('exercise_requires_four_sources')
    # Validate the entire snapshot before staging; never copy unchecked paths.
    for source in sources:
        load_source(manifest.parent, source)
    with tempfile.TemporaryDirectory() as directory:
        root = Path(directory)
        for source in sources:
            target = root / source['path']; target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes((manifest.parent / source['path']).read_bytes())
        # Changed bytes are rejected before decoding, preserving the pinned contract.
        (root / sources[1]['path']).write_bytes(b'changed after snapshot')
        (root / sources[2]['path']).unlink()
        invalid = b'\xff'
        (root / sources[3]['path']).write_bytes(invalid)
        sources[3] = dict(sources[3], sha256=hashlib.sha256(invalid).hexdigest())
        copy = root / 'manifest.json'
        copy.write_text(json.dumps({'schema_version': 1, 'sources': sources}))
        return ingest(copy)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--manifest', type=Path, default=Path(__file__).parent / 'fixtures/source-manifest.json')
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--exercise-failures', action='store_true')
    args = parser.parse_args()
    result = failure_exercise(args.manifest) if args.exercise_failures else ingest(args.manifest)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps({'status': result['status'], 'loaded': len(result['documents']), 'failures': result['failures']}, sort_keys=True))
    # Partial completion is never advertised as full success to shell automation.
    raise SystemExit(0 if result['status'] == 'complete' else 2)

if __name__ == '__main__': main()
Execute complete and partial batchesTerminal · bash
python3 ingest.py --output /tmp/ingestion-complete.json
python3 ingest.py --exercise-failures --output /tmp/ingestion-partial.json
python3 -m unittest -v test_load_documents.py test_ingest.py
Saved CLI outputRecorded output · jsonDownload
{
  "failures": [
    {
      "error": "hash_mismatch",
      "path": "docs/path-read.md",
      "source_id": "path-read"
    },
    {
      "error": "unreadable_source",
      "path": "docs/json-text.md",
      "source_id": "json-text"
    },
    {
      "error": "invalid_utf8",
      "path": "docs/path-read-3-13.md",
      "source_id": "path-read-3-13"
    }
  ],
  "loaded": 1,
  "status": "partial"
}

The first command loads the unmodified fixture and exits successfully. The controlled failure command exits with status 2 on purpose. Run the tests as a separate command, so a script that stops on a nonzero exit still runs them.

Inspect the complete saved result
Actual controlled failure resultRecorded output · jsonDownload
{
  "schema_version": 1,
  "execution_mode": "offline-local-files",
  "status": "partial",
  "documents": [
    {
      "source_id": "path-write",
      "path": "docs/path-write.md",
      "title": "path-write",
      "sha256": "a48b4b9f763cd6309ebe32af19c5a814adcf810c2259683da9f328ccee46948e",
      "version": "3.12",
      "url": "https://docs.python.org/3.12/library/pathlib.html#pathlib.Path.write_text",
      "fact_status": "original summary; primary docs checked",
      "text": "Path.write_text(data, encoding=None, errors=None, newline=None) writes text to a file and closes it. Set encoding=\"utf-8\" to select UTF-8. An existing file is overwritten. The method returns the number of characters written."
    }
  ],
  "failures": [
    {
      "source_id": "path-read",
      "path": "docs/path-read.md",
      "error": "hash_mismatch"
    },
    {
      "source_id": "json-text",
      "path": "docs/json-text.md",
      "error": "unreadable_source"
    },
    {
      "source_id": "path-read-3-13",
      "path": "docs/path-read-3-13.md",
      "error": "invalid_utf8"
    }
  ]
}

This output comes from a deterministic local run. It calls no model and measures no retrieval quality.

Refuse to promote incomplete ingestion

Partial batch. The CLI writes its result and returns exit 2 whenever the status is not complete. A caller must inspect that status before treating the accepted subset as the intended corpus. The output file exists after a partial batch too, so gate the next pipeline step on exit 0 or on status equal to complete, not on the file being present.

Try running once without --exercise-failures and once with it, using different output paths. Compare the status, source IDs in failures and process exit codes. Then read the test where every source fails, test_all_sources_fail: its status must be failed, and its failures must remain visible.

The lab has no atomic corpus-promotion operation or load benchmark. It reads small local files one at a time. Protecting concurrent writes and measuring large-corpus throughput require separate work.

The loader writes a result with accepted documents and failed sources. May the caller treat the batch as complete?

Choose one answer, then check your reasoning.

Read the explanation

A successful artifact write and complete ingestion are separate outcomes.

What’s next

Continue with Version documents and chunks.

References

Implementation APIs were checked on 23 October 2026 against official Python pathlib, JSON and temporary-file documentation. Source summaries retain their original version-specific links. The implementation uses only the Python standard library.

Written by Arjun Prabhulal.

Module 3

Document ingestion