# Table layers protocol

The part after warehouse cost. The same public trip feed lands in three layers stored as Delta tables: raw, cleaned
and modeled (often called bronze, silver and gold). Batches arrive four times a day. The question: when the scorecard's
existing checks run on each layer, at which layer does each planted fault get caught, if at all, and how fresh is each
layer after each batch? Nothing is paid for: every number comes from local runs of `quality/layers.py`, with tables
written by the open-source `deltalake` package and read by DuckDB. The frozen protocol is `table_layers/protocol.json`,
committed with this file before any table is built from the feed and before any check runs on it.

## Overlap test

Nearest published pages:

- Pipeline recovery: bronze, silver and gold Delta tables on one month of 300 trips a day; question: do layer-to-layer
  checks catch pipeline faults (late data, schema changes, backfills, replays, restores) that the day-level checks miss,
  and does a recovery put the published numbers back. It ran the day-level checks on the cleaned layer only.
- Warehouse cost: the same public ride-hail feed and the same checks ported to SQL; question: what each run of three
  materializations reads as history grows, and which check scope (whole history, each morning's load batches, new trip
  dates only) still catches faults once loads are incremental. It had one landing table and one model, no layers.

The new question is placement: the same checks run on every layer, so the result is a fault-by-layer map of what each
layer can and cannot see, plus how far behind each layer is after each batch. Neither page answers it. It is a new
round of this study, on its own page, linked from the entry page.

## Why Delta and not Iceberg

Both are open table formats that DuckDB reads. Delta is used here because the pipeline recovery part already wrote its
layers as Delta tables with the pinned open-source `deltalake` package, so the two parts read the same way and the
study gains no dependency; a local Iceberg table written from Python needs a catalog (a SQL catalog on a local file)
for every commit, one more moving part for a laptop test. What this round uses from the format is common to both:
an atomic commit per batch (a reader never sees half a batch), metadata on each commit (the batch ID), partitions,
MERGE on a key, a replace of chosen partitions, and table versions. The question does not depend on which of the two
formats is used.

## Data

- The 54 daily files of warehouse cost: City of Chicago, Transportation Network Providers Trips, every trip that
  started in the first 15-minute slot of every second hour, January 1 to February 23, 2023 (1,402,214 trips). Each
  file's URL and SHA-256 are in `warehouse_cost/data-files.json`; this round checks every file against that list before
  use and downloads nothing.
- Normalized exactly as in warehouse cost (`quality/warehouse_data.py`, `normalize_sql`): trip ID hashed, area 0 for a
  missing area, the derived distance field in metres (miles times 1609.344), the trip date from the start time.

## Batches (simulated; no streaming system is built or run)

Each trip day is cut into four batches by start time: 00:00 to 05:59, 06:00 to 11:59, 12:00 to 17:59 and 18:00 to
23:59 (three sample slots each). A window's batch lands one hour after the window closes: 07:00, 13:00, 19:00, and 01:00
the next day. 216 batches for the clean feed. These are simulated arrival times inside the data period; freshness is
measured in batches and in the feed's own event time, never in run time.

## Layers (all Delta tables; every transform computed by DuckDB, one thread)

- Raw: every delivered batch appended as one commit, rows as delivered plus `loaded_at`, `batch_id` and `batch_seq`
  (delivery order), partitioned by load date. Never rewritten.
- Cleaned: one row per trip ID, the row from the latest load wins (`loaded_at`, then `batch_seq`), partitioned by trip
  date. Each batch is merged when it lands: the batch is first reduced to one row per trip ID, then a MERGE on trip ID,
  limited to the trip-date partitions the batch touches, updates every column when matched and inserts otherwise.
  Rows carry the `loaded_at`, `batch_id` and `batch_seq` of the batch that last wrote them.
- Modeled: one row per trip date: trips, fares present, fare sum, missing-fare share, miles sum, seconds sum (the
  published daily table of warehouse cost), plus `built_at` and `built_through_seq`. Built once a day at 05:00: every
  trip date with a cleaned row written since the last build is recomputed from the cleaned layer and replaces its row
  (a replace of those dates in one commit). It does not carry the trip ID or the distance in metres.
- Each commit carries the batch ID (raw and cleaned) or the build time (modeled) in its commit metadata.
- DuckDB reads every layer through its Delta extension (`delta_scan`). At the clock, every layer of every workload is
  also read through the `deltalake` package's own reader, and row counts and sums must match; a mismatch is a method
  failure, reported.

## Checks (the scorecard's version 2 as ported to SQL in warehouse cost, same thresholds)

Every morning at 06:00, each layer is checked over what it received since the previous morning (the scope the
warehouse cost part recommended): raw rows loaded since then; cleaned rows written since then (a row a later batch
re-wrote counts); modeled rows built since then. The scoped trip dates are the dates of those rows.

- `freshness`: the layer's newest `loaded_at` (raw, cleaned) or `built_at` (modeled) is more than 12 hours before the
  check; flags the day that was due (the day before the morning).
- `fare_completeness`: a scoped date's missing-fare share above 0.05, over the scoped rows (modeled: the published
  share).
- `day_volume`: a scoped date with fewer than 0.6 times the median row count (modeled: published trips) of the 14
  dates before it present in the layer.
- `source_unique`: a trip ID appears more than once among the layer's rows of the scoped dates (on the cleaned layer
  this is the model check `unique_trips_trip_id`).
- `content_duplicates`: two rows of the scoped dates share every field except the trip ID.
- `unit_invariant`: a scoped row whose miles times 1609.344 differs from its distance in metres by more than 0.000001,
  or with either missing.
- `fare_null_anomaly_v2`: a scoped date's missing-fare share above the median of the 14 dates before it plus the
  larger of 0.02 and 6 times 1.4826 times their median absolute deviation.

On the modeled layer `source_unique`, `content_duplicates` and `unit_invariant` cannot run: the trip ID, the row grain
and the distance in metres are gone. They are reported as "cannot run", never as passed.

Across layers, every morning, over the trip dates of the raw rows loaded since the previous morning (the warehouse cost
part's model checks): `landing_reconciliation` (distinct trip IDs in raw against cleaned rows and modeled trips) and
`daily_reconciliation` (cleaned rows against modeled trips).

A fault is caught at a layer when a check at that layer flags one of the fault's planted dates on any morning from
February 2 to the clock, and the clean workload's same check at the same layer did not flag that date on any of those
mornings. Both rules are declared here, before any run (warehouse cost added them after its development runs).

## Freshness (measured after every batch and every build)

- Batches behind: delivered batches whose rows the layer does not reflect yet (modeled: delivered batches after its
  `built_through_seq`). This is what a pipeline can see about itself.
- Complete through: the newest 6-hour window such that every window up to it holds, in that layer, exactly the clean
  feed's trip IDs (modeled: a day's four windows count when its published trips equal the clean feed's count for that
  day). Windows behind = windows the clean schedule has delivered by then minus windows complete; reported in windows
  and in hours of event time (6 hours a window). This is measured against the full clean feed, which a pipeline does
  not have.
- A hole: the layer holds rows of a window newer than its complete-through window.

Per workload and layer: the largest windows behind, the number of events with a hole, and the batches-behind range.

## Workloads

- Clean: all 216 batches, January 1 to February 23. The clock is February 24, 2023 at 06:00.
- Seven faults, each replaying February on its own copy of the three tables, from the clean run's state after the
  06:00 checks on February 1. The sizes follow the scorecard's and warehouse cost's (30% of fares, miles times
  1.609344).
  1. `missing_day`: none of February 23's four batches arrives.
  2. `null_spike`: 30% of February 22's fares arrive blank (the first 30% of that day's rows with a fare, by trip ID).
  3. `unit_change`: every February 22 mile arrives multiplied by 1.609344.
  4. `replayed_batch`: February 22's 06:00 to 11:59 batch is delivered a second time, unchanged, under a new batch ID,
     20 minutes after the first.
  5. `late_batch`: February 17's 18:00 to 23:59 batch arrives at 01:00 on February 19, after February 18's last batch,
     instead of at 01:00 on February 18. Its rows are fine.
  6. `late_batch_null_spike`: as `late_batch`, and 30% of that batch's fares arrive blank (the first 30% of its rows
     with a fare, by trip ID).
  7. `backfill_unit_change`: at 04:00 on February 24, February 2 to 8 are delivered again, same trips, one batch per
     day, with miles multiplied by 1.609344.
  Planted dates: February 23 (1); February 22 (2, 3, 4); February 17 (5, 6); February 2 to 8 (7).
- One repeat: the clean February replayed from the same state. Rows, flags, freshness and the modeled table must match
  the clean run exactly; a mismatch is a method failure, reported.

Per fault and layer at the clock, also: the dates where the modeled table differs from the clean run's (counts
exactly, sums within 0.01), and the count of cleaned rows that differ from the clean run's cleaned layer.

Descriptive, not predicted: commits, data files and bytes per layer at the clock of the clean run.

## Development runs

Code is tested on small synthetic tables (tests) and run on the clean feed of January 1 to 5 only, with no fault.
No development run touches February or any fault, so no outcome is seen before the measured run.

## Predictions (declared before any run; band in brackets)

1. Faults caught (of 7): raw 6 [6]; cleaned 5 [5]; modeled 3 [2 to 3]. Raw misses only `late_batch`; cleaned also
   misses `replayed_batch`; modeled catches `missing_day`, `null_spike` and possibly `late_batch_null_spike`.
2. `late_batch` (clean rows, one window a day late) is caught at no layer: freshness passes because other batches keep
   arriving, and the day short by one window stays above 0.6 times the median day.
3. `replayed_batch` is caught only at raw, by `source_unique`; the cleaned layer's one-row-per-trip rule absorbs it, so
   no check on cleaned or modeled sees it, and the modeled table equals the clean run's.
4. `unit_change` and `backfill_unit_change` are caught at raw and cleaned by `unit_invariant` and missed at modeled,
   where no check can read the distance; both change the modeled table's miles.
5. The two across-layer checks catch 0 of 7: each layer is built from the one below, so a fault reaches every layer
   or is absorbed by the cleaned layer's key.
6. Freshness, clean: raw and cleaned 0 batches behind after every batch; modeled 0 to 4 batches behind (24 hours of
   event time at most) [0 to 4]. `late_batch`: raw and cleaned show a hole while the late batch is missing, with
   complete-through 4 to 5 windows behind at the worst point [4 to 5], while their batches behind stay 0; modeled
   publishes February 17 short at the February 18 build and restates it at the February 19 build.
7. Clean false alarms on the February mornings: `content_duplicates` flags the same clean dates at raw and cleaned
   (as in warehouse cost, about two days in five) [5 to 15 of the 23 February dates]; modeled flags no clean date [0].

## Headline rule

The h1 states, with exact counts, how many of the 7 faults each layer's checks caught (raw, cleaned, modeled) and how
many no layer caught. Every prediction is reported on the page with its band, as held, missed or untestable, with
how many held.

## Honesty

One author wrote the layers, batches, faults and predictions, knowing the earlier parts' results: every catch is a
self-test of these checks on these faults, and many outcomes follow from each layer's definition (labelled so). The
batches are simulated from a daily public feed; no streaming system is built or run. A laptop is not a lakehouse:
tables are local files. Any change to this protocol after this commit is written as "Change N to the protocol",
committed before it is used, and shown on the page.

## Notes added after the measured run

The text above is unchanged since it was committed before the measured run. What followed:

- Results: faults caught raw 6, cleaned 5, modeled 3, across layers 0; caught at no layer: `late_batch`. All 7
  predictions held (`table_layers/results.json`, `predictions`). Prediction 3 named `source_unique`; `content_duplicates`
  also flagged the replayed batch at raw, which the prediction did not name.
- Speed change, no change to any measure: after the clean run, `missing_day`, `null_spike`, `unit_change` and part of
  `replayed_batch` had run, the freshness bookkeeping in `quality/layers.py` was changed to keep per-window counts and
  recount only the dates a batch carries (commit ba1a4c016). The remaining runs and the repeat used the new code. The
  repeat (new code) matched the clean run (old code) on all 644 check and freshness records. Every stretch of every run
  records the SHA-256 of the code that ran it (`provenance.jsonl` in `table_layers/records.zip`).
- Change 1 to the protocol, made after the results: the protocol asked the repeat's modeled table to match the clean
  run exactly. Counts matched exactly; sums differed on 6 dates by at most 7.3e-10, from the order of floating-point
  addition. The repeat is judged on sums within 0.01 (the tolerance this protocol set for comparing fault runs with the
  clean run), and `repeat.modeled_differs_exactly` and `repeat.modeled_max_sum_difference` report the exact comparison
  beside it. Read strictly, the protocol as first written calls this a method failure; it is reported on the page.
- "Cleaned rows that differ from the clean run" compares the normalized trip columns, not the lineage columns
  (`loaded_at`, `batch_id`, `batch_seq`), as the code committed before the run does. A replayed batch therefore
  counts 0 differing rows although its rows carry the replay's batch ID.
- Computed after the results, descriptive only: the late window's trips and its day's total, the short day against
  the median of the 14 days before, the clean windows' smallest and largest trip counts, and the published
  missing-fare shares on the planted days (`figures_after_results`). The cleaned-row differences are saved with the
  records so the summary rebuilds from `table_layers/records.zip` alone.
- The page's suggestion of a completeness check per event-time window is not tested in this round.
- Added after the results: a unit test, `test_incremental_freshness_equals_full_recount_out_of_order`,
  and a full recount. The repeat replays the clean feed in order, so it never exercised the incremental freshness
  bookkeeping on out-of-order batches; the late batch and backfill runs used only the new code. The unit test compares
  the incremental and the full count after every delivery of a late batch, a replay and a whole-day backfill on
  synthetic days. The recount read the raw and cleaned tables of the `late_batch`, `late_batch_null_spike` and
  `backfill_unit_change` runs at the table version each February delivery wrote, counted every window and compared
  complete-through, newest window, windows behind and hole with the recorded freshness: 283 deliveries, 0 mismatches
  (`table_layers/fresh-recount.json`). Batches behind was not recounted; it is covered by the unit test only. The docstring of `freshness()` in `quality/layers.py`, written with the speed
  change, already said a test checked both ways; that test did not exist until this point.
- Known before the run: the warehouse cost part had run the same checks on the same 54 files. There, duplicate content
  flagged the same 12 clean February dates, the same four backfill days and the same two clean ones, and caught rows
  sent twice. Predictions 6 and 7, the replay's duplicate-content flag and the backfill's duplicate-content days were
  therefore foreseeable; prediction 6's band follows from the batch schedule.
- The late batch's miss is narrow: February 17 was published at 18,479 trips, 0.6955 times the 14-day median of 26,568.5,
  2,538 trips above the 0.6 bound taken from the warehouse cost part; the freshness check saw a newest load 11 hours old
  against its 12-hour limit.
- "Up to 30 hours" is complete-through: at worst 5 windows were not complete in order, while the rows missing were one
  6-hour window (13,644 trips).
