# Warehouse cost protocol

The part after alerts and on-call. The pipeline cost part priced six layouts on one month of 10,000 trips, where fixed
per-run costs dominate. This part asks what happens as history grows: as a daily-loaded table goes from one day to
thirteen months of history, what does each run of the same models read under a full rebuild, an incremental model on a
date key, and an incremental model on a date-partitioned and clustered table; and do the scorecard's checks still run,
and still catch planted faults, once loads are incremental? No model is called and nothing is paid for: every number
comes from local runs of `quality/warehouse.py` on DuckDB. The frozen protocol is `warehouse_cost/protocol.json`,
committed with this file before any data is downloaded or any run is made.

## Overlap test

Nearest published pages: the scorecard (do automatic checks catch a bad daily load, one month) and pipeline cost (what
six layouts cost on one month, and what they gave up on five recovery faults). The new question is growth: work per run
as a function of history length, and whether the scorecard's own checks survive incremental loads. It uses the same
public trip source and the same checks, so it is a new round of this study, on its own page, linked from the entry page.

## Data

- Source: City of Chicago, Transportation Network Providers Trips (2023-2024), dataset n26f-ihde, through its public
  query endpoint. One file per trip day, 2023-01-01 to 2024-01-31 (396 days), so the scorecard's month is the last
  month of the history and its faults can be planted where they were.
- Sample: every trip that started in the first 15-minute slot of every second hour (00:00, 02:00, ..., 22:00). The
  source rounds start times to 15 minutes, so this keeps about one trip in eight, every day, with the same rule. It is a
  time-slot sample, not a random one; it stands in for a feed of about 30,000 rows a day, a hundred times the
  scorecard's 300.
- History length: thirteen months. Full volume (about 240,000 rows a day) would fit the round's download budget of about
  15 GB for only about a year with no room for the work tables, and the query endpoint returned a quarter-day in about
  15 seconds, so full volume would also take hours to fetch. The one-in-eight sample keeps the download near 2 GB and
  the runs inside the machine's budget; the per-row work, not the absolute size, is the subject.
- Columns: trip ID, start and end time, seconds, miles, pickup and dropoff community area, fare, tip, additional
  charges, trip total, shared trip authorized, shared trip match, trips pooled. No census tract, no coordinates. The
  trip ID is replaced on load by `trip_` plus the first 24 hex characters of its SHA-256, as in the scorecard sample.
  A missing community area becomes area 0, as in the scorecard.
- Each file's URL and SHA-256 go in `warehouse_cost/data-files.json`. The downloads stay out of the repo.
- Derived on load, before any fault: `trip_date` (the start date) and `audit_distance_meters` (miles times 1609.344),
  the scorecard's synthetic audit field for the units check.

## Tables

All tables are parquet files read and written by DuckDB (one thread, row groups of 8,192 rows, the same writer
settings everywhere).

- Landing: every delivered file appended as one parquet file under its load date, with `loaded_at` and `batch_id`.
  Never rewritten. The same files feed every arm.
- `trips` (silver): one row per trip ID, typed, the row from the latest load wins (load time, then delivery order).
- `daily_trips` (gold): one row per trip date: trips, fares present, fare sum, missing-fare share, miles sum, seconds
  sum. A small table, one file.

## Arms (materializations)

A run is triggered by every delivered file. The landing step is the same for every arm and counted apart.

1. `full_rebuild`: read every landing file, keep one row per trip ID, rewrite `trips` (unpartitioned), aggregate every
   day, rewrite `daily_trips`.
2. `incremental_date`: the common incremental pattern on a date key, on an unpartitioned table. The watermark is the
   newest trip date already in `trips`; the run reads landing rows with a later trip date (file statistics skip landing
   files whose newest trip date is not later), keeps one row per trip ID, deletes target rows with those trip IDs
   (a delete on an unpartitioned table reads the trip ID column of every `trips` file; any file holding a deleted row is
   rewritten without it), appends the new rows as one file, and recomputes the gold rows of the trip dates it loaded
   (reading `trips` files whose date statistics overlap those dates).
3. `incremental_partitioned`: incremental on a table partitioned by trip date (one folder per day) and clustered by
   pickup community area (rows sorted by area inside each day's file). The run reads the landing batches not yet
   processed (a small manifest of processed batch IDs), finds the trip dates they touch, reads those partitions of
   `trips`, keeps one row per trip ID across the old and new rows, rewrites those partitions, and recomputes those gold
   rows.

Arm 2's filter is on the trip date, so by its definition it never loads rows whose trip date is not newer than the
watermark: a late day, the rest of a day that arrived in parts, a backfill. Arm 3's filter is on the load batch, so it
loads them. These outcomes follow from the definitions; the runs confirm them and measure what the checks see.

## Measures

Per run and per step: rows read (DuckDB's own profile, rows scanned), data bytes read (the compressed parquet bytes of
the columns the step reads, in the files and row groups its filters cannot skip, counted from the files' parquet
metadata: partition folders, then row-group min and max statistics for date and area filters), rows and bytes written
(parquet files its writes add), files touched, and process CPU seconds (`time.process_time`, one DuckDB thread).

The accounting predicts which files and row groups each step opens; the step then hands DuckDB exactly those files. A
step's measured rows scanned is compared with the rows the accounting predicts; mismatches are counted and reported.

Bytes are the warehouse's billable quantity on scan-priced engines; rows are the work. No price is applied: this round
reports rows and bytes, never money. CPU seconds are measured on a shared machine under heavy load and are reported
as such, as a check that work follows rows, not as a timing claim.

Monthly totals: the sum of a calendar month's daily runs, per arm.

## Workloads

Clean: one file per trip day, delivered at 01:00 the next day, 2023-01-01 to 2024-01-31 (396 runs per arm). The clock
is 2024-02-01 06:00, as in the scorecard.

Faults, each on its own copy of January 2024 replayed from the state after the clean run's December 31 file (every arm
copies its own tables at that point). The sizes follow the scorecard's: 90 of 300 fares is 30%, 25 of 300 rows is one
row in twelve.

- `missing_day`: the January 31 file never arrives (the scorecard's `late_partition`).
- `null_spike`: 30% of January 30 fares are blanked (the first 30% of that day's rows with a fare, by trip ID).
- `duplicate_load`: one in twelve January 30 rows (the first by trip ID) is delivered again, unchanged, in a second file
  at 01:30 on January 31.
- `unit_change`: every January 30 mile is multiplied by 1.609344.
- `late_day`: the January 24 file arrives at 01:00 on January 27, with January 26's, instead of on January 25. Clean.
- `late_day_null_spike`: as `late_day`, and 30% of January 24 fares are blanked: a fault in a day the incremental filter
  skips.
- `backfill_unit_change`: at 04:00 on February 1 the January 8 to 14 rows are delivered again, same trip IDs, as one
  backfill file per day, with miles multiplied by 1.609344.
- `partial_day`: January 31 arrives in two halves (the first half of its rows by trip ID at 01:00 on February 1, the
  rest at 05:00). The scorecard's `partial_late_partition`, completed before the clock.

## Checks (the scorecard's version 2, ported to SQL on the landing and model tables)

Source checks, on landing rows:

- `freshness`: the newest `loaded_at` is more than 12 hours before the check time.
- `fare_completeness`: a trip date's missing-fare share is above 0.05.
- `day_volume`: a trip date has fewer than 0.6 times the median row count of the 14 loaded days before it.
- `source_unique`: a trip ID appears more than once.
- `content_duplicates`: two rows share every field except the trip ID.
- `unit_invariant`: miles times 1609.344 differs from the audit metres by more than 0.000001.
- `fare_null_anomaly_v2`: a trip date's missing-fare share is above the median of the 14 loaded days before it plus
  the larger of 0.02 and 6 times 1.4826 times their median absolute deviation.

Model checks, on each arm's tables:

- `unique_trips_trip_id`: a trip ID appears more than once in `trips`.
- `daily_reconciliation`: a date's `trips` row count differs from `daily_trips` (bookkeeping: built from the same rows).
- `landing_reconciliation`: a date's distinct trip IDs in the landing table differ from its `trips` rows or its
  published trips (the daily count check the pipeline cost part recommended).

Each check reports the trip dates it flags (`freshness` flags the clock's day).

Scopes (where and how often the checks run):

- `whole`: every check over every landing row and the whole model tables, at the clock, as the scorecard ran them.
- `batch`: every morning at 06:00, the checks over the landing rows delivered since the previous morning; the 14-day
  baselines of `day_volume` and `fare_null_anomaly_v2` are the 14 loaded days before each date in the landing table;
  `source_unique` compares the batch's trip IDs with each other and with landing rows of the same trip dates loaded
  earlier; model checks over the trip dates the batch touched.
- `new_dates`: every morning at 06:00, the same checks over landing rows whose trip date is after the newest trip date
  the previous morning's check covered, the filter an incremental model on a date key uses. Model checks over those
  dates.

A fault is caught in a scope when a check in that scope flags one of the fault's planted dates on any morning from
January 1 to the clock (or, for `whole`, at the clock). For `missing_day` the planted date is January 31, flagged by
`freshness` (clock's day) or by a model check. A flag on a date the fault did not plant is a false alarm; false alarms
on the clean workload are counted per scope.

Check cost: rows and bytes read per check run, per scope, every morning of the clean workload for `batch` and
`new_dates`, and on the last morning of every month for `whole`.

## Correctness at the clock

Per fault and arm: the dates where `daily_trips` differs from the clean workload's (counts exactly, sums within 0.01),
and the dates where it differs from a full rebuild of the same fault's landing table. A date in the second set is one
the arm's model hid or got wrong on its own; a date only in the first is the source fault itself, loaded faithfully.

## Queries (the query side of partitioning and clustering)

On `trips` of each arm, on the last morning of every month of the clean workload, each run once with its filters
pushed into the file and row-group list:

- `q_day`: trips and average fare by pickup area for the newest trip date.
- `q_area_4w`: trips and fare per mile per day for pickup area 8 over the last 28 trip dates.
- `q_area_all`: total trips and fare sum for pickup area 8 over the whole history.

Every answer is compared across arms; a difference is a method failure.

## Repeats and stopping

Rows, bytes, files and outcomes are deterministic: the January 2024 clean runs are replayed three times from the
December 31 state for every arm, and every row, byte and file count must match across the replays (a mismatch is a
method failure, reported). CPU seconds for January 2024 are reported as the median and range of those three replays;
for the other months, from the one clean run. Every run is made; nothing stops early. A run that raises an error is
run once more and counted.

Development runs that only check the code use the first 20 days of 2023 and the first 3 days of January 2024; their
numbers are not reported.

## Predictions (declared before any run)

1. Rows read per daily run: `full_rebuild` grows in step with history, ending near the whole landing table (about
   12 million rows); `incremental_partitioned` stays flat near one day's rows (about 30,000), so the ratio on the last
   day is in the hundreds.
2. `incremental_date` reads few rows of data but its delete reads the trip ID column of the whole table on every run,
   so its bytes per run grow with history, more slowly than `full_rebuild`'s: between a tenth and a half of
   `full_rebuild`'s bytes on the last day.
3. CPU seconds follow rows read: `full_rebuild`'s grows with history, `incremental_partitioned`'s stays flat.
4. Gold at the clock: `full_rebuild` and `incremental_partitioned` match a full rebuild on every fault (by design).
   `incremental_date` differs from a full rebuild on `late_day` and `late_day_null_spike` (January 24 missing),
   `partial_day` (January 31 short by half) and `backfill_unit_change` (January 8 to 14 not restated), and matches on
   the other four.
5. Checks: `new_dates` misses the faults in a day the date filter skips (`late_day_null_spike`, `backfill_unit_change`)
   in its source checks; `batch` catches them; `whole` catches every value fault but also flags clean days of the
   thirteen months. `duplicate_load` is caught by `source_unique` in `whole` and `batch` and missed by every model check
   (every arm keeps one row per trip). `landing_reconciliation` is the check that catches `incremental_date`'s hidden
   days. `late_day` (clean) is not a value fault; only a reconciliation can see it.
6. Check cost: `whole` reads grow with history like a full rebuild; `batch` and `new_dates` stay flat. An incremental
   model with whole-history checks still pays a full scan every morning.

## Headline rule

The h1 leads with the ratio of `full_rebuild` to `incremental_partitioned` in data bytes read on the last daily run
(thirteen months of history), with the same ratio in rows, and with what the cheaper incremental model on a date key
hid that a check had to catch. If `incremental_partitioned` differs from a full rebuild on any fault, the h1 says so.

## Honesty

A laptop is not a warehouse. Bytes here are parquet bytes on one machine's disk, close to what a scan-priced engine
counts but not a bill. The sample is one trip in eight; rows per run scale with volume, so the ratios between arms, not
the absolute counts, are the result. Fault outcomes that follow from an arm's definition are labelled as by
construction. One author wrote the arms, faults, scopes and predictions, knowing the earlier parts' results.

## Amendment before the measured runs

Decided during the downloads and the development runs (the first 20 days of 2023 only), before any measured run. No
result had been seen; the development runs only showed where the protocol could not be taken as written.

1. **Downloads without server-side ordering, compressed.** Ordering by trip ID made the query endpoint answer a day in
   30 to 45 seconds; without it, and with a compressed transfer, about 12. Row order does not matter: every file is
   sorted by trip ID when it is normalized. A re-download may return the same rows in another order, so its SHA-256 can
   differ; the data notes also record each file's row count. The first few files were fetched with the ordering and
   keep their own URL in the notes.
2. **Rows read come from the parquet metadata, not from DuckDB's counter.** In the development runs DuckDB's rows
   scanned counter counted every row of every file a query opened, even when a filter left a row group out (a one-area
   query on a day file of three row groups reported all three). Rows read are therefore the rows of the row groups the
   accounting cannot skip, the same row groups whose column bytes make the data bytes read. DuckDB's counter is kept in
   the records beside them as the engine's own figure.
3. **Month-end mornings.** The month-end checkpoint for the `whole` scope's cost and for the queries is the 06:00
   morning after the month's last file lands (the first of the next month), so the clock is the last checkpoint.
4. **Freshness flags the day that is due.** `freshness` flags the trip date that should have arrived by that morning
   (the day before it), not the clock's day, so a late day is attributed to itself.
5. **The `new_dates` watermark** is the newest trip date in the landing table at the previous morning's check.
6. **Six months of history, not thirteen.** After 75 of the 396 files, the query endpoint was answering a day in 5 to
   over 75 seconds (one request timed out at 75 seconds with a third of its rows), and parallel requests made it slower,
   so the thirteen months could not be fetched inside the round. The history is January 1 to June 30, 2023 (181 days),
   the files already fetched from the start of 2023 plus the rest of the half year. The faults keep their roles and move
   to June 2023: `missing_day` June 30; `null_spike`, `duplicate_load` (re-sent at 01:30 on June 30) and `unit_change`
   June 29; `late_day` and `late_day_null_spike` June 24, delivered with June 26's file at 01:00 on June 27;
   `backfill_unit_change` June 8 to 14 at 04:00 on July 1; `partial_day` June 30, halves at 01:00 and 05:00 on July 1.
   The clock is July 1, 2023 at 06:00, every fault replays June from the clean run's state after the May 31 file, and the
   three repeat replays are of June. The values are in `warehouse_cost/amendment-1.json`, which the code applies over
   the frozen protocol. The prediction about the last day's ratio now concerns six months of history; its other
   predictions stand as written.
7. **Fifty-four days of history: January 1 to February 23, 2023.** After amendment 6, the query endpoint stopped
   answering for this dataset altogether: a one-row request timed out at 20 to 40 seconds for more than fifteen minutes,
   while the portal and another of its datasets answered in under a second. Transports tried: curl with redirects
   followed, a retry per file, compressed and uncompressed transfers, one to six requests at a time, and the alternate
   `/api/id/` path; the city's 2018 to 2022 trips dataset answers but lacks the shared-trip-match column the checks
   use. Two fetched files were cut short by the server (February 24 and March 10) and were set aside. The history is
   therefore the 54 contiguous days already fetched, about 1.3 million sampled trips. The faults keep their roles:
   `missing_day` February 23; `null_spike`, `duplicate_load` (re-sent at 01:30 on February 23) and `unit_change`
   February 22; `late_day` and `late_day_null_spike` February 17, delivered with February 19's file at 01:00 on
   February 20; `backfill_unit_change` February 2 to 8 at 04:00 on February 24; `partial_day` February 23, halves at
   01:00 and 05:00 on February 24. The clock is February 24, 2023 at 06:00; faults and the three repeat replays start
   from the clean run's state after the January 31 file. With only one month-end, the `whole` scope and the queries
   run every morning of the clean workload (their flags still count at the clock), so their cost has a series. Values:
   `warehouse_cost/amendment-2.json`, applied after amendment 1.

   Disclosure: the code's development runs used this same window and these fault days (they were the days on disk),
   so the fault outcomes and the last day's ratios were seen once, after the predictions were committed and before
   this amendment. The measured run repeats everything from an empty folder. No arm, check, scope, threshold or fault
   was changed after that development run; two summary rules were added: a planted date counts as caught only when
   the clean workload's same check and scope did not flag it as well, and the `whole` scope's flags count at the clock.

## Notes added after the measured run

These notes were written after the results and the page; the text above is unchanged.

1. **Prediction 1 was not met and could not be tested as declared.** It expected about 12 million rows read by the
   last `full_rebuild` run and a last-day ratio in the hundreds, for thirteen months of history. Amendment 6 moved it to
   six months and amendment 7 did not restate it. After 54 days the last `full_rebuild` run read 2,804,428 rows and the
   ratio of data read to `incremental_partitioned` was 48.96. The page reports it as not met; the statement that a
   year would put the ratio in the hundreds is an extrapolation of the measured straight line, not a measurement.
2. **Prediction 5 held in part.** Its last sentence, "`late_day` (clean) is not a value fault; only a reconciliation
   can see it", was missed after amendment 4: `freshness` flags the day that was due, so it flagged February 17 in the
   `batch` and `new_dates` scopes. Its `duplicate_load` clause was too narrow: `new_dates` caught the re-sent rows too.
   Predictions 2, 3, 4 and 6 held: four of the six.
3. **The two summary rules of amendment 7 were added after the development runs had shown the fault outcomes.** The
   first (a planted day counts only when the clean run's same check and scope did not flag it) can only remove catches.
   It removed `content_duplicates` flags on February 4 and 5 from `backfill_unit_change` and on February 23 from
   `partial_day`, in all three scopes; without it, `new_dates` would have counted the backfill as caught from flags
   raised on February 5 and 6 mornings, before the backfill arrived. The second (whole-scope flags count at the clock)
   changed no catch. Both effects are computed from the records by `quality/warehouse_rules.py` into
   `warehouse_cost/rule-effects.json`.
4. **What `incremental_date` reads.** Besides the trip ID column for its delete, each run reads the trip date column
   of the whole cleaned table to find its watermark (`select max(trip_date)`), so its rows read count the whole table
   twice. On the last run: 1,373,504 rows and 10,176 bytes for the watermark, the same rows and 33,819,979 bytes for
   the delete, of 35,599,338 bytes in all. `quality/warehouse_split.py` computes this split for every clean run from
   the run's table files into `warehouse_cost/date-key-split.json`, and checks that the parts add up to each run's
   recorded rows read. This is how the common incremental pattern reads on an engine that bills by data scanned.
