# Shift material consumption The read-only layer uses stored cumulative machine quantities. It does not use ERP bookings or infer material labels for B1/K7. ## API `PostgresShiftMaterialRepository` and `PostgresShiftChannelMaterialRepository` (in `service.postgres_shift_material`) expose `get_snapshots(machine_id=..., calculation_ids=(...), start=..., end=...)`. Each call executes one parameterized query: one latest valid baseline at or before start per calculation/channel, followed by all raw rows strictly after start and before end. Valid baselines have finite, non-negative counters. Missing baselines do not suppress in-window rows. In-window invalid counters remain visible to aggregation for run-boundary and reset validation. Compose these readers with `ShiftMaterialService` or `ShiftChannelMaterialService` (in `service.shift_material`) and call: ```python summary = service.summarize( machine_id="K7", calculation_ids=("k7-fiber-consumption",), start=start, end=end, include_zero=False, ) ``` The same keyword arguments apply to the pure functions `aggregate_shift_material` and `aggregate_shift_channel_material` in `calculations.shift_material`, with an iterable of snapshots as their first argument. Results are frozen `ShiftMaterialSummary` objects containing a tuple of frozen `ShiftMaterialItem` objects. Items retain source, calculation, machine, production order, run, quantity, observed baseline/end timestamps, and optional channel/material/quality metadata. Results have deterministic ordering. `include_zero=True` preserves diagnostic zero items; false omits them. ## Boundaries and runs All timestamps must be timezone aware. Validation, ordering, and comparisons use UTC instants, including DST folds. The window is `[start, end)` and must have positive elapsed duration. No interpolation or extrapolation is performed. Each calculation stream is segmented by observed run transitions. Channel streams additionally separate extruder and doser channel. Within the active run, the baseline is the last valid cumulative sample at or before shift start; the end is the last valid sample strictly before shift end or the next observed run transition. A run without a pre-window baseline uses its first valid sample and flags `baseline_missing=True`. Its initial counter is not counted. There is no differencing across runs. A lone valid sample yields a diagnostic zero item; no valid samples yield an empty summary. Neither implies source freshness. Null and non-finite counters are skipped as quantity samples, but their rows still establish run boundaries. Every selected consecutive valid counter pair is checked: decreases/resets raise `ValueError`, even if the final value later recovers. Negative counters, duplicate stream timestamps, reappearing runs, and production-order changes within a run also raise rather than guessing. ## E1 materials For consecutive valid samples A → B, attribute `B.counter - A.counter` to the material number, name, and mapping status stored on **B**. Consecutive intervals with the same identity form a segment. A → null → A remains separate segments. Blank labels become null; historical null names remain null even if a material number is present. There is no last-known name carry-forward or ERP lookup. When both number and name are absent, the segment status is `UNAVAILABLE`. Otherwise the stored mapping status is retained. Percentage validity is the logical AND of the ending samples' flags in that segment. If a counter is invalid between valid samples, the quantity interval bridges those valid samples and uses the ending valid sample's identity; no intermediate material allocation is fabricated. Run boundaries still interrupt that bridge. Repository tests use mocked PostgreSQL connections; they do not validate query plans or execute queries against a live database. ## PostgreSQL read performance Machine reads use `unnest` plus a lateral `ORDER BY timestamp DESC LIMIT 1` lookup per requested calculation ID. Equality on calculation and machine allows the existing `(calculation_id, machine_id, timestamp)` index to seek backward from shift start. A separate `UNION ALL` branch reads only the bounded window, with the same calculation/machine predicates. Both branches run in one statement and retain the existing 10-second timeout. Final ordering is deterministic. Channel reads use `DISTINCT ON (calculation_id, extruder, doser_channel)` ordered by descending timestamp for the baseline, plus a bounded-window branch. This performs one filtered baseline pass for the requested calculations/machine, instead of correlated history checks per source row or per channel. The existing unique index can restrict calculation/machine, but its intervening `production_order` prevents it from delivering channel timestamp ordering without additional work. Channel baseline selection may still scan substantial history and sort it; its live latency has not been measured here. If E1 remains slow, inspect `EXPLAIN (ANALYZE, BUFFERS)` for each branch first. A `(calculation_id, machine_id, timestamp)` index would help the bounded window; a `(calculation_id, machine_id, extruder, doser_channel, timestamp DESC)` index would help channel baseline ordering. Neither is added by this change. Choose based on the measured plan and account for snapshot-write/storage overhead. The supplied K7 live measurement (0.022 seconds for 2580 rows) supports the baseline-plus-window strategy. This change was tested locally with mocked PostgreSQL connections, without claiming a new live benchmark.