Add unified shift reporting
This commit is contained in:
1 parent
1b060377aa
commit
41a5ae7a63
30 files changed
+3751
-9
No files matched your search
@@ -0,0 +1,105 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Unified shift-report composition
|
||||
|
||||
`ShiftReportService` composes the existing production, downtime, material, and
|
||||
speed services sequentially. It performs no database or HTTP reads itself and
|
||||
adds no quantity or interval aggregation. Its frozen `ShiftReport` reuses all
|
||||
four immutable summary models directly, preserving source metadata and items
|
||||
for later PDF or SSR rendering. Neither renderer is implemented here.
|
||||
|
||||
## Configuration and API
|
||||
|
||||
`config/shift-report-machines.yaml` is self-contained for composition:
|
||||
|
||||
```yaml
|
||||
machines:
|
||||
B1:
|
||||
machine_id: 5f42a4f6-9ca0-4f6f-9786-40d50a35b230
|
||||
erp_workplace: BENTO 1
|
||||
material:
|
||||
mode: cumulative
|
||||
calculation_ids:
|
||||
- bento1-fresh-bentonite-consumption
|
||||
- bento1-spreader3-consumption
|
||||
speed:
|
||||
signal_ref: fef41976-1103-4090-b780-eaeecc02fdfa
|
||||
signal: Transport Auszug Geschwindigkeit Istwert
|
||||
unit: m/min
|
||||
production_gate_m_min: 0.3
|
||||
```
|
||||
|
||||
The loader returns `ShiftReportMachineConfig` values with frozen material and
|
||||
speed configurations. Speed-only consumers now use `machines[name].speed`.
|
||||
Missing/unknown fields, duplicate YAML keys or machine IDs, unsupported material
|
||||
modes, empty/duplicate calculation IDs, and invalid speed metadata are rejected.
|
||||
No unrelated YAML configuration is loaded at runtime.
|
||||
|
||||
Inject already constructed services:
|
||||
|
||||
```python
|
||||
machines = load_shift_report_machines("config/shift-report-machines.yaml")
|
||||
service = ShiftReportService(
|
||||
machines=machines,
|
||||
production=production_service,
|
||||
downtime=downtime_service,
|
||||
materials=material_service,
|
||||
channel_materials=channel_material_service,
|
||||
speed=speed_service,
|
||||
)
|
||||
start, end = shift_report_window(day, "early")
|
||||
report = service.build(machine_name="B1", start=start, end=end)
|
||||
```
|
||||
|
||||
`shift_report_window` lives in `calculations.shift_report`; the loader and
|
||||
service live in `service.shift_report_config` and `service.shift_report`.
|
||||
The day is the shift's start date in Europe/Berlin. Early is 06:00–14:00, late is
|
||||
14:00–22:00, and night is 22:00–06:00 on the following day. Night shifts can have
|
||||
seven or nine elapsed hours at DST transitions. Explicit windows are validated
|
||||
as aware, positive-duration instants and normalized to Berlin for all service
|
||||
calls. All source services retain their `[start, end)` semantics.
|
||||
|
||||
## Source semantics
|
||||
|
||||
Production uses the existing finished-goods ERP service with workplaces B1:
|
||||
`BENTO 1`, E1: `1568705`, and K7: `K7`. Its order/article groups, m², roll counts,
|
||||
and first/last confirmation timestamps remain available in `report.production`.
|
||||
|
||||
`report.downtime.non_downtime_seconds` is the elapsed shift duration minus the
|
||||
union of downtime intervals. It is a time complement and does not measure actual
|
||||
production time. It is never named `production_time_seconds`. The report exposes
|
||||
`downtime_event_count`, all `downtime_reasons`, and `top_downtime_reasons` (at most
|
||||
three). Reason views retain the original immutable reason, including duration
|
||||
and metadata; null/blank names get `Ohne Stillstandsgrund`. The existing summary
|
||||
provides ranking and tie ordering. Overlapping reasons can have durations whose
|
||||
sum exceeds total downtime.
|
||||
|
||||
B1 uses cumulative fresh-bentonite and spreader3 snapshot streams; K7 uses the
|
||||
cumulative fiber stream. E1 uses channel snapshots, preserving extruder/channel,
|
||||
material number/name/status, calculation ID, and source in each item. Existing
|
||||
counter differencing, reset failure behavior, and sample-to-sample attribution
|
||||
remain unchanged. Null material names remain null; no carry-forward or report
|
||||
label invents an identity. ERP raw-material booking quantities are excluded
|
||||
because their timing is not synchronized with physical shift consumption.
|
||||
|
||||
Speed is the arithmetic sample mean strictly above the configured production
|
||||
gate: average speed while running, not average speed over the full shift.
|
||||
Counts, gate, and active min/max are preserved in `report.speed`.
|
||||
|
||||
Every source is mandatory. Exceptions propagate immediately and later services
|
||||
are not called. An empty successful summary remains an empty summary; a failed
|
||||
read is never replaced with zeros. No cross-source matching of runs or orders is
|
||||
introduced, and sequential reads are not a transactionally consistent snapshot
|
||||
across ERP, PostgreSQL, and ENLYZE.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Shift running-speed KPI
|
||||
|
||||
`average_line_speed_m_min` is the arithmetic mean of finite speed samples
|
||||
strictly above the configured production gate within `[start, end)`. Samples
|
||||
have equal weight regardless of spacing. Inactive time does not contribute to
|
||||
this KPI. No interpolation, carry-forward, or time weighting is applied.
|
||||
|
||||
The immutable summary includes signal, unit, gate, window, finite sample count,
|
||||
active/inactive counts, active average/minimum/maximum, and invalid sample count.
|
||||
`sample_count` counts finite numeric in-window values and equals active plus
|
||||
inactive counts. Zero, negative, and values equal to or below the gate are
|
||||
inactive. Null, non-numeric, boolean, NaN, and infinite values are invalid and
|
||||
excluded from all finite/active statistics. Invalid/missing timestamps are also
|
||||
counted separately as unavailable because window membership cannot be verified.
|
||||
Absent source rows are not synthesized or counted. Without active samples,
|
||||
average, minimum, and maximum are all `None`.
|
||||
|
||||
Window timestamps must be timezone aware and have positive elapsed duration.
|
||||
All boundary comparisons use UTC instants, including DST folds.
|
||||
|
||||
## Configuration and service API
|
||||
|
||||
Machine-specific UUIDs, signal labels, units, and gates live in
|
||||
`config/shift-report-machines.yaml`. It also contains the ERP workplace and material source references needed for
|
||||
report composition; existing material-calculation definitions are not duplicated. The configured gates are
|
||||
B1: 0.3 m/min; E1: 0.5 m/min; K7: 0.5 m/min. The config loader validates required
|
||||
fields, non-empty identifiers, unique machine IDs, m/min units, and finite
|
||||
non-negative gates. It returns frozen report machine configurations by name, each with a nested
|
||||
`ShiftSpeedConfig` in `.speed`.
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from production_analytics.enlyze.gateway import EnlyzeApiGateway
|
||||
from production_analytics.service.shift_report_config import load_shift_report_machines
|
||||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||
|
||||
machines = load_shift_report_machines("config/shift-report-machines.yaml")
|
||||
service = ShiftSpeedService(EnlyzeApiGateway(client)) # Existing ExplorationClient
|
||||
summary = service.summarize(
|
||||
config=machines["K7"].speed,
|
||||
start=datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin")),
|
||||
end=datetime(2026, 10, 7, 14, tzinfo=ZoneInfo("Europe/Berlin")),
|
||||
)
|
||||
```
|
||||
|
||||
`aggregate_shift_speed(samples, config=..., start=..., end=...)` is the pure
|
||||
calculation API, accepting `ShiftSpeedSample(timestamp, value)` objects.
|
||||
`EnlyzeApiGateway.get_speed_samples(machine_id=..., speed_signal_ref=...,
|
||||
start=..., end=...)` requests just the configured signal from `/v2/timeseries`,
|
||||
using the existing client and cursor semantics. It tolerates unavailable sample
|
||||
values/timestamps; structural response and pagination errors fail the read,
|
||||
preventing a partial successful summary. No snapshots are persisted.
|
||||
|
||||
## Supplied live reference
|
||||
|
||||
For 2026-10-07 06:00–14:00 Europe/Berlin:
|
||||
|
||||
| Machine | Samples | Active samples | Active average (m/min) |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| B1 | 2880 | 1603 | 2.3139663284001912 |
|
||||
| E1 | 2880 | 2782 | 7.933009468249328 |
|
||||
| K7 | 2880 | 2667 | 10.078945039942955 |
|
||||
|
||||
These are the supplied validation values, not a new live read performed during
|
||||
implementation. Tests cover filtering, statistics, boundary/DST behavior,
|
||||
configuration, service composition, and gateway pagination with mocked responses.
|
||||
Reference in new issue
Block a user