# Pipeline cost protocol

The next part after pipeline recovery. It asks what each pipeline layout costs to run and to query on the study's public
trip month, and how much freshness or recovery safety the cheaper layouts give up. No model is called. Every number comes
from local runs of the code in `quality/cost.py`; the frozen protocol is `pipeline_cost/protocol.json`, committed with this
file before the measured runs. Development runs that only check the code (one repeat, a subset of jobs) come before the
measured runs; their numbers are not reported.

## Data, tables and clock

The same 10,000 licensed January 2024 trips, the same conform step (`Lake.conform` from `quality/recovery.py`: strict,
a missing column or an unparseable value parks the whole file), the same registered schema versions, fault schedules and
clock (2024-02-01 06:00) as pipeline recovery. Bronze is the recovery round's landing table: every delivered file appended as
text with its batch ID, load time, source file and schema version, unpartitioned. Silver holds one row per trip, typed;
gold holds the six daily metrics (trips, fare sum, fares present, miles sum, seconds sum, shared trips matched). Only the
layout of silver and gold, and the work each run does, change between arms. All tables are Delta tables written by the
deltalake package; DuckDB (one thread) computes every conform, deduplication and aggregate.

A run is triggered by every file that lands. Each run first appends the file to bronze (the landing step, the same in every
arm and timed apart), then does the arm's transform.

## Arms (layouts)

1. `full_rebuild`: read the whole landing table, conform every file under the registered schemas, keep one row per trip ID
   from its latest load (load time, then delivery order), overwrite silver; aggregate every day, overwrite gold. Silver and
   gold partitioned by trip date.
2. `window_3`: incremental by partition with a declared late-data window of 3 days. D is the latest trip date in the
   landing table after the file lands; the window is D-2 to D. Read the landing rows whose trip date is in the window (file
   statistics prune the rest), conform them per file, keep one row per trip ID from its latest load, replace those silver
   partitions, aggregate them and replace those gold partitions. Rows for days before the window are not applied by a
   normal run. Partitioned by trip date.
3. `merge_key`: incremental with merge on a key. Read the new file from the landing table, conform it, MERGE it into
   silver on trip ID (the recovery round's merge), with the file's trip dates added to the merge condition so only those
   partitions are scanned; then read those silver partitions, aggregate them and replace those gold partitions.
   Partitioned by trip date.
4. `merge_add`: silver as `merge_key`; gold instead adds the new file's per-day totals to the published days (a MERGE that
   adds matched days and inserts new ones), the recovery round's published-table design without its watermark gate.
   Silver is not re-read. Partitioned by trip date.
5. `merge_key_flat`: `merge_key` with silver and gold unpartitioned (storage choice 1: partitioned by date against
   unpartitioned). Only Delta file statistics can skip files.
6. `merge_key_compacted`: `merge_key`, plus, when a file carries a day's end-of-day marker, that day's silver partition is
   compacted into one file (storage choice 2: many small files against compacted files). Compaction is timed and counted in
   the run.

Secondary, labelled as a sweep: `window_1` and `window_7` (the same as `window_3` with windows of 1 and 7 days), on the
`daily` and `late` workloads only.

## Workloads

Clean cost workloads (cost and query measures):

- `daily`: the recovery round's clean schedule, one file per trip day at 01:00 the next day (31 runs).
- `three_a_day`: the recovery round's micro-batch schedule, each day as three files of a third at 01:00, 01:10 and
  01:20, the end-of-day marker on the last (93 runs). This is the many-small-files case.

Fault workloads (safety measures, plus the cost of each run and of the recovery), the recovery round's own declared faults
on the daily schedule, unchanged:

- `late`: late rows past the watermark (the last 60 January 24 rows arrive at 01:30 on January 27).
- `replay`: replay after an outage (two January 30 micro-batches delivered again, out of order, before the day closes).
- `backfill`: backfill counted twice (the stream re-run for January 8 to 14 at 04:00 on February 1; the backfill start
  and end markers do nothing in these layouts, the re-delivered files load like any file).
- `schema`: renamed column (from the January 26 file the fare column arrives as `fare_amount`; those files park).
- `restore`: partial restore (at 09:00 on January 28 silver is restored to its version right after the January 25 file's
  run; gold is left as it was).

The blind faults of the recovery round are not used.

## Queries (declared set, run at the clock on the final tables of `daily` and `three_a_day`)

Dashboard, on gold:

- `q1_week`: trips and fare sum per day for January 25 to 31.
- `q2_month`: month totals of trips, fare sum and miles sum.

Analyst, on silver:

- `q3_day`: trips and average fare by pickup community area on January 24.
- `q4_week`: fare per mile by pickup community area for January 15 to 21.
- `q5_month`: share of trips with no fare, per day, over the month.
- `q6_lookup`: one trip by trip ID (a fixed January 24 trip).

Each query opens its table fresh (a new Delta table object and dataset, so no file footer is cached), runs through DuckDB
over the table's pyarrow dataset with the filter pushed down, five times per job. Every answer is checked against the same
query on the clean month's truth; a wrong answer is a failure of the arm, not a cost.

## Measures

Per run (landing and transform timed apart): wall seconds (`time.perf_counter`), process CPU seconds (`time.process_time`),
bytes read and bytes written by the process (`rchar` and `wchar` from `/proc/self/io`, which count every read and write
call, Delta logs included, whether or not the operating system had the bytes cached), and files touched (parquet files
added and removed in the Delta commits the run made, plus files opened by the run's own reads and the files a MERGE
reports scanning). Per query: wall seconds, bytes read, files opened after pruning. Per job: storage at the clock (bytes of
the live silver and gold files, and bytes on disk including files a later commit replaced, since no vacuum runs).

Freshness: the publish lag of each file is the wall time of its run (landing plus transform), the time from a file landing
to its rows in gold. Reported as the median and the maximum per arm on `daily`, and as the trend over the month.

Correctness and recovery safety, as the recovery round scores them, per fault workload:

- At the clock, with no manual step: the days where gold differs from the clean month (counts exactly, sums within 0.01),
  and the days where silver aggregated the same way differs from the clean month; parked files.
- Recovery, run when a control-totals comparison against the landing table (the landing table rebuilt as in
  `full_rebuild`, per day, against silver and against gold) finds a day that differs, or after the schema fault, whose
  declared first step is to register schema version 2 in every arm. `full_rebuild` recovers by its normal run.
  Every other arm rebuilds the differing days from the landing table: replace those silver partitions (one row per trip
  ID from its latest load) and those gold partitions. Detection and recovery are timed apart.
- After recovery: the days where gold or silver still differ from the clean month.

A layout is called safe on this set when, at the clock and with no manual step, gold equals the clean month on `late`,
`replay`, `backfill` and `restore`. The `schema` fault parks files in every layout by design, so it does not enter the
safe test; its recovery cost is reported.

## Repeats, order and stopping rule

Five repeats of every arm on every workload (six arms on seven workloads, plus the sweep: two arms on two workloads), each
job a fresh process in a fresh folder, run one at a time on one machine. Within a repeat the workloads run in the order
above and the arms in an order rotated by one each repeat. Outcomes (days wrong, parked files, query answers, bytes
written by data files) must be identical across repeats; times and byte counts are reported as the median with the range
of the five. A job that raises an error is a method failure: it is run once more, and the count of re-runs is reported.
All 5 repeats of every job are run; nothing stops early.

## Money (declared assumption, labelled on the page)

- Compute: US$4.00 per compute-hour (US$0.00111 per second), charged on wall seconds.
- Scan: US$5.00 per terabyte (10^12 bytes) read.
- Query frequency: each dashboard query 24 times a day, each analyst query 10 times a day, for the 31 days.
- Monthly cost per arm on `daily`: transform wall seconds and bytes read over the month, plus every query at its median
  wall seconds and bytes read times its frequency, priced under three models: compute only, scan only, and both.
- Ranking check: the cost ranking of the six arms is recomputed with the scan price multiplied by every power of ten
  from 10^-4 to 10^4 against the compute price; the page reports the ranking at the declared prices and any multiplier
  where it changes.

## Headline rule

The h1 leads with the ratio of `full_rebuild` to the cheapest safe incremental arm (arms 2 to 6) in transform wall
seconds over the `daily` month, with the same ratio in bytes read beside it, and with what that arm gave up on the fault
set. If no incremental arm is safe, the h1 says so and leads with the cheapest incremental arm and what it gave up.

## Honesty

A laptop is not a warehouse. The page states the hardware, shows results as ratios between layouts, and says which ratios
are expected to hold at scale and which are not, as expectations, not measurements. Safety outcomes that follow from a
layout's definition (a window drops rows older than the window) are labelled as by construction, confirmed by the run.

## Amendment before the measured runs

Decided during the development runs, before any measured run, and committed with the code. No result had been seen;
the development runs only showed where the measures above could not be taken as written.

1. **Queries read the live files through DuckDB's own parquet reader.** The query step lists the table's live files from
   its Delta log and gives them to DuckDB's `read_parquet` (partitioned tables through their trip-date folders, so a date
   filter skips whole folders; flat tables through file statistics only). The reason: a MERGE writes text columns as
   string views while an append writes plain strings, and a text filter pushed through a pyarrow dataset failed on the
   mixed files; declaring string views on the dataset made it run but stopped partition pruning. Listing the files is
   timed apart from the scan. The bytes a query scans are the bytes read during the scan; the files it opened come from
   DuckDB's own query profile, in one extra untimed run per query and job.
2. **Every table checkpoints its commit log every 10 commits** (the library default is 100), so a reader replays at most
   10 commit files, as on most engines.
3. **Compute is measured in CPU seconds.** In the development runs the shared machine's load average ran from about 48 to
   70 on 16 threads, so wall seconds include time spent waiting for a processor. The process's CPU seconds (all threads)
   are the compute measure, the money's compute charge and the h1 ratio; wall seconds are reported beside them, and the
   load average is recorded at the start and end of every job.
4. **Bytes are the parquet bytes each step opens.** Data bytes read: the parquet bytes of the files each step opens after
   partition and file-statistics pruning (its reads, the target files a MERGE scans, the files a predicate rewrite of a
   flat table reads, and a compaction's inputs). Data bytes written: the parquet bytes its commits add. These are the
   byte measures on the page and the ones the scan price charges. The operating system's counters, which also count
   commit logs and checkpoints, are reported beside them.
5. **The landing step hands the manifest to the transform in memory** (the same rows it appends to the manifest table),
   so a run does not re-read the manifest table.
6. **Measurement bookkeeping is taken out.** Counting the files a step opens is timed and counted apart and subtracted
   from the run. The files a MERGE reports scanning are compared with the files pruning predicts; mismatches are counted.
7. **Each call of the runner starts with one unrecorded warm-up job** (`merge_key` on `daily`).
8. **The five repeats run side by side**, one runner process per repeat, each running its own jobs one at a time in the
   declared order. Run one after another on this loaded machine they would take about two and a half hours; the
   machine is shared with other work either way, every arm meets the same conditions inside each repeat, and the
   byte, file and outcome measures do not depend on timing.

The headline rule therefore reads: the ratio of `full_rebuild` to the cheapest safe incremental arm in transform CPU
seconds over the `daily` month, with the ratio in data bytes read beside it, and what that arm gave up.
