aiml

Lesson 5 of 21Module 3

Validate incoming events before preparing training data

Preserve original events, quarantine invalid records and block the entire training batch when field, identity or temporal checks fail.

Prerequisites

Complete the preceding course lessons in the shared user-return lab; keep their work/ outputs. Python functions and local CLI commands.

Preparation and term definitions

By the end, you can

  • Separate parsing, contract checks and training authorization.
  • Preserve rejected events and reasons for repair.
  • Block a partially accepted batch from training.
Runtime
Python 3.12+; local CPU
Dependencies
Python standard library and SQLite

Lab code, tests and fixtures (ZIP, 1.6 MB)Quiz check your understanding

Progress is saved in this browser.

Keep the original input, quarantine invalid records and block the entire batch when its data contract fails.

Problem

When you need this. The manual workflow starts from a valid fixture. A recurring data feed needs a decision before training: can this batch be used at all? Quietly dropping broken rows would change the dataset without telling the training job what was lost.

This adaptation applies the existing JSON Lines validator to the same return-application events. It runs a clean batch and a second batch with one deliberately malformed event. Both runs keep their original input and write a manifest that says whether training may proceed.

Concepts

JSON Lines stores one JSON value on each line; this feed requires each value to be an event object. A data contract specifies the fields and value rules the application can interpret. Each event needs a bounded ID, a user identity, an event time and an arrival time. Correct JSON syntax alone does not satisfy that contract.

Quarantine keeps each invalid line with its source line number and rejection reasons. Use it to investigate and repair the input; it does not permit training on the remaining rows. This exercise chooses a strict batch policy: any rejected record blocks the batch.

The validator also refuses duplicate event identities. It quarantines every row that shares an event ID, because keeping the first or last row would silently pick one version of the event.

The validator writes the manifest after the staged files, so a partly written directory has no manifest and does not look ready. A ready manifest names the training file; a blocked manifest leaves that field empty. The handoff is a set of local files, with no distributed transaction or recovery service.

Architecture

Raw JSON Linesoriginal input bytesValidate eventsfields, times, identityAccepted rowsvalid event recordsQuarantineraw bytes + reasonsBatch manifestready or blockedRaw JSON Linesoriginal input bytesValidate eventsfields, times, identityAccepted rowspreserved for inspectionQuarantineraw bytes + reasonsBatch manifestready or blocked
Both outputs retain records for inspection. The batch manifest, rather than the existence of accepted rows, determines whether preparation may continue.

Working code

Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. This workshop uses the standard library.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate

On PowerShell, activate with .venv\Scripts\Activate.ps1.

Validate a clean and a deliberately broken batch

Use a fresh work directory. The wrapper writes the current fixture’s events as JSON Lines, passes those bytes to the existing validator and saves each batch’s source bytes. The broken example adds one object missing the required fields.

Source excerpt: validate_sourceSource · pythonDownload
def validate_source(source, destination, inject_bad=False):
    fixture=w.strict_json(source)
    w.availability.validate(fixture['observations'], [], fixture['labels'])
    if not isinstance(fixture.get('events'), list):raise ValueError('events must be a list')
    raw=b''.join(encoded(e)+b'\n' for e in fixture['events'])
    if inject_bad: raw+=b'{"id":"broken"}\n'
    batch=quarantine.validate_batch(raw)
    manifest=quarantine.write_batch(batch,destination)
    return {'status':manifest['status'],'accepted':manifest['accepted'],'quarantined':manifest['quarantined'],
            'reason_counts':manifest['reason_counts'],'training_file':manifest['training_file'],
            'source_sha256':manifest['source_sha256']}
Validate a clean and a deliberately broken batchTerminal · bash
python adapt.py validation --work work/adaptations
Actual local application outputRecorded output · jsonDownload
{
  "clean_batch": {
    "status": "ready",
    "accepted": 1193,
    "quarantined": 0,
    "reason_counts": {},
    "training_file": "accepted.jsonl",
    "source_sha256": "2a4d21ec1a2934bfe78e57054f2ee5904809dbad1338b6b8aa6452f39c40a168"
  },
  "deliberately_invalid_batch": {
    "status": "blocked",
    "accepted": 1193,
    "quarantined": 1,
    "reason_counts": {
      "event_contract": 1
    },
    "training_file": null,
    "source_sha256": "5467a40341eee85f3994740b346a34662ad14cf2add2bc285dec5928b1e4d2a4"
  }
}

Compare status and training_file for the two results. The blocked batch still keeps its accepted rows for inspection, but its training_file is null. Have the next stage read status and training_file from the manifest; do not treat the presence of accepted.jsonl as permission to train.

This output is from a saved local Python run with no remote calls; its files are in recorded-adaptations/, and your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt.

Failure cases

Run test_quarantine_blocks_partial_training, test_malformed_source_event_reaches_quarantine, test_clean_validation_keeps_every_original_event and test_duplicate_identity_quarantines_both_occurrences. They check the whole-batch decision and that the original records are kept, including an invalid event already present in the source fixture.

The validator checks supported fields and temporal relationships. It cannot tell whether a syntactically valid event was collected correctly, whether consent exists or whether the observed population represents the intended users. The owners of the source and the application must review those questions.

Run the application failure checksTerminal · bash
python -m unittest -v test_workflow.py test_foundations.py

Running and scaling the workshop

The deployment unit is a local staging directory. The validator refuses an existing directory, so a second attempt cannot mix its files with an earlier manifest.

A larger feed needs bounded streaming and storage retention policies. When you replace the in-memory reader with a streaming one, keep the same rejection reasons and batch decision.

Key takeaways

  • Parsing, contract validation and training authorization are separate checks.
  • Quarantine preserves rejected records for repair.
  • A batch can contain accepted rows and still be blocked from training.

Best practices

Make the batch policy explicit before selecting or dropping records.

Pass the manifest status and source identity to the next stage, not only a path to a cleaned file.

Read reason_counts in the manifest before you open quarantine.jsonl: its reason codes separate format failures, such as malformed_json, from event_contract and duplicate_event_id failures.

Check your understanding

Can the pipeline train on accepted.jsonl when the manifest is blocked?

Show the explanation

No. Accepted rows are retained for investigation, but this application’s strict batch policy permits training only when every record passes and the ready manifest names the training file.

Some events pass validation, but the batch contains an invalid record. May training use the accepted subset?

Choose one answer, then check your reasoning.

Read the explanation

The accepted rows are staging output. The whole batch must pass its validation manifest before the pipeline permits training.

References

Written by Arjun Prabhulal.

Module 3

Make the workflow reproducible