Data Quality Layers (A / B / C / D)
Codified 2026-05-12. Trigger: a data audit on 2026-05-12 found 258 abandoned documents (pending for more than 48 hours), 40 duplicate doctor profiles and 312 chunks of template placeholder text ("Lorem ipsum") sitting silently in the production corpus for weeks. None was caught by the automated tests or by deployment checks. These counts come from the project's own audit.
The project enforces four parallel code-quality gates: a Python linter (style), a Python type checker, a frontend type checker and a frontend linter. Until this sprint the data layer had no equivalent: bad data could land in the corpus and stay there for months without surfacing.
Layers A / B / C / D mirror the four code-side gates at the data layer. Each gate has a single owner, a single failure mode and a clear escalation:
| Layer | Mirror | What | Failure escalation |
|---|---|---|---|
| A | Daily observability | A nightly audit job (30 minutes after the ingest job) produces a Markdown report and exits with a clean, warning or alert status | A structured log entry carries a severity field; the existing log infrastructure alerts on warning and alert levels |
| B | Canonicalisation and de-duplication at ingest | A pre-insert duplicate check using the page's canonical URL, backed by a database rule that forbids two completed documents with the same normalised title per hospital | The database rejects the duplicate; the application receives a duplicate-document error, skips the document and logs it |
| C | Sanitisation and extraction | A sanitiser strips template placeholder text; an extractor turns consultation-schedule tables into structured data | Bad chunks are rejected at ingest; existing chunks were back-filled by an idempotent one-off script |
| D | Post-completion verification | Verification logic inside the Layer A audit: confirms that what landed matches what was crawled | Same as Layer A: report plus log severity |
Layer A: daily observability
A single self-contained audit job (no new dependencies) is scheduled 30 minutes after the nightly ingest. It writes a dated Markdown report with these metrics:
- Pending-age median and 95th percentile (soft threshold above 24 hours, hard threshold above 48 hours). The percentile uses a discrete rather than interpolated method because interpolated timestamps cannot be cast back to a timestamp type in PostgreSQL.
- Failure-reason histogram (soft threshold above 25, hard above 100), split into two classes:
- real failures: threshold-checked ingest failures;
- intentional soft-deletes: informational only, for rows deliberately superseded or marked as broken extractions. The histogram flags these rows with a marker.
- Duplicate-title count: alerts on one or more; it should always be zero given the Layer B rule.
- Per-hospital doctor coverage: share of doctor profiles with a schedule and share containing placeholder text.
- Chunk-quality statistics: short, empty and placeholder chunks.
Layer B: canonicalisation and de-duplication gate
Two complementary mechanisms run at ingest:
- Canonical-URL extraction. The crawler already read the page's canonical-link declaration but discarded it. It is now stored with the document metadata.
- Pre-insert duplicate check. Before a document is inserted, the system looks for an existing completed document whose normalised title (with the site-name suffix stripped) matches. If one exists, the new document is skipped.
A partial unique database rule (a later schema migration) adds schema-level enforcement: even if the application-level check is bypassed by a manual insert, a race condition or a future code path, the database rejects the duplicate. The rule is partial because pending, processing and failed rows pass through transient duplicate states by design.
A companion fix rejects documents whose title normalises to an empty string. This is a common drift mode for very short pages: a page with a single image and no readable text would otherwise normalise to empty and silently de-duplicate against every other empty-normalised page.
Layer C: sanitisation and extraction
Sanitiser
A one-off script walks the existing chunks, detects runs of template placeholder text (the Lorem ipsum phrase over at least ten consecutive tokens) and strips them. It is idempotent, so it is safe to run on an already-sanitised corpus, and it only touches completed chunks.
Layer B's empty-title guard is the prevention side of Layer C's cleanup: future placeholder-only documents are rejected at ingest, so the sanitiser drains a finite backlog.
Schedule-table extractor
The hospital's website publishes consultation schedules as a table with weekday columns and morning/afternoon rows, in which each cell holds a short code for the type of consultation. An extractor parses this table into structured data keyed by weekday and half-day, for example Monday: morning code A, afternoon code B. Empty cells are omitted, an all-empty table yields no result, and new cell codes pass through unchanged, so there is no fixed vocabulary constraint. The extractor runs on every newly ingested document, and existing documents were back-filled by a one-off, idempotent script.
Important pairing: this extractor is the structured-data fallback to a prompt rule described in ADR-0057. The prompt rule teaches the language model to read the Markdown table when consumers have not yet been upgraded; the extractor makes structured data available to any future code path that needs deterministic schedule answers without relying on the model to parse tables.
The extractor is scoped to one hospital's format. A future hospital would get its own extractor, following the same architectural pattern as ADR-0057.
Layer D: post-completion verification
Verification logic inside Layer A's audit confirms that what landed in the documents and chunks stores matches what was crawled: URL-to-chunk counts, status-flow consistency and expected-versus-actual completion rate per ingest run.
Layer D is the what we check dimension; Layer A is the when we check it dimension. They ship together because the verification rules are most expressive in the script that already walks the corpus.
Why four layers, not one
A single monolithic "data quality" script would have three problems:
- Ownership ambiguity: when the de-duplication gate fires, is that a Layer A audit problem or a Layer B ingest problem?
- Latency mixing: Layer B runs synchronously per insert and must be fast; Layer A runs nightly and can be slow; Layer C runs opportunistically per ingest; Layer D runs after Layer A finishes. Bundling them would force one cadence to bend to another.
- Failure isolation: a bug in the Layer C extractor (for example an edge case with empty tables) should not block ingest. Splitting C from B keeps each gate close to its failure mode.
The split mirrors the code-side gates, which also differ in cadence and concern: the linter runs in seconds, the type checker in minutes, the frontend checks only on the frontend tree.
Companion fixes that surfaced during implementation
| Fix | Why it surfaced |
|---|---|
| Use the database column name, not the Python attribute name, in the back-fill query | The back-fill query was reading the object-mapper attribute name instead of the real column |
| Department-overview pages explicitly yield no schedule | These pages have no schedule by design; the extractor must return nothing rather than raise an error |
| Deterministic handling when a canonical URL matches several documents | Layer B's duplicate check needs predictable behaviour when the same canonical URL appears in two ingest passes |
| Discrete percentile for timestamps | Interpolating between two timestamps produces values PostgreSQL cannot cast back to a timestamp |
References
- Related: ADR-0057, Tenant-scoped prompt addendums and doctor-profile boost. Layer C's schedule extractor is the structured-data half of that decision's defence-in-depth pair.
- Implementation details (audit job, migration, extractor, back-fill script) are kept in the project's private repository.