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,407 @@
|
||||
from dataclasses import FrozenInstanceError, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import Mock
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from production_analytics.calculations.shift_material import (
|
||||
ShiftChannelMaterialSnapshot,
|
||||
ShiftMaterialSnapshot,
|
||||
aggregate_shift_channel_material,
|
||||
aggregate_shift_material,
|
||||
)
|
||||
from production_analytics.service.shift_material import (
|
||||
ShiftChannelMaterialService,
|
||||
ShiftMaterialService,
|
||||
)
|
||||
|
||||
START = datetime(2026, 10, 7, 6, tzinfo=ZoneInfo("Europe/Berlin"))
|
||||
END = START + timedelta(hours=8)
|
||||
|
||||
|
||||
def machine_sample(minutes=0, value=100.0, *, run="r1", calculation="calc", order="order"):
|
||||
return ShiftMaterialSnapshot(
|
||||
START + timedelta(minutes=minutes), calculation, "machine", order, run, value
|
||||
)
|
||||
|
||||
|
||||
def channel_sample(
|
||||
minutes=0,
|
||||
value=100.0,
|
||||
*,
|
||||
name="Material A",
|
||||
number=None,
|
||||
status="ASSIGNED",
|
||||
run="r1",
|
||||
extruder="Ex1",
|
||||
channel="C1",
|
||||
order="order",
|
||||
quality=True,
|
||||
):
|
||||
return ShiftChannelMaterialSnapshot(
|
||||
START + timedelta(minutes=minutes),
|
||||
"calc",
|
||||
"machine",
|
||||
extruder,
|
||||
channel,
|
||||
order,
|
||||
run,
|
||||
value,
|
||||
number,
|
||||
name,
|
||||
status,
|
||||
quality,
|
||||
)
|
||||
|
||||
|
||||
def aggregate(rows, *, channel=False, **changes):
|
||||
function = aggregate_shift_channel_material if channel else aggregate_shift_material
|
||||
return function(
|
||||
rows,
|
||||
**{
|
||||
"machine_id": "machine",
|
||||
"calculation_ids": ("calc",),
|
||||
"start": START,
|
||||
"end": END,
|
||||
**changes,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_single_run_boundary_baseline_and_end_are_latest_not_min_max():
|
||||
summary = aggregate(
|
||||
[
|
||||
machine_sample(-20, 1),
|
||||
machine_sample(-1, 100),
|
||||
machine_sample(10, 110),
|
||||
machine_sample(479, 120),
|
||||
machine_sample(480, 500),
|
||||
machine_sample(500, 600),
|
||||
]
|
||||
)
|
||||
assert summary.total_consumption_kg == 20
|
||||
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=1)
|
||||
assert summary.items[0].end_timestamp == END - timedelta(minutes=1)
|
||||
assert not summary.items[0].baseline_missing
|
||||
assert summary.items[0].material_name is None
|
||||
assert summary.items[0].production_order == "order"
|
||||
assert summary.items[0].run_id == "r1"
|
||||
assert isinstance(summary.items, tuple)
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
summary.total_consumption_kg = 0
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
summary.items[0].consumption_kg = 0
|
||||
|
||||
|
||||
def test_exact_start_baseline_and_end_exclusion():
|
||||
summary = aggregate(
|
||||
[
|
||||
machine_sample(-1, 90),
|
||||
machine_sample(0, 100),
|
||||
machine_sample(479, 125),
|
||||
machine_sample(480, 500),
|
||||
]
|
||||
)
|
||||
assert summary.total_consumption_kg == 25
|
||||
assert summary.items[0].baseline_timestamp is not None
|
||||
assert summary.items[0].baseline_timestamp == START
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_run_change_never_differences_counters_across_runs(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
summary = aggregate(
|
||||
[
|
||||
sample(-1, 100),
|
||||
sample(120, 120),
|
||||
sample(121, 10, run="r2", order="order-2"),
|
||||
sample(479, 45, run="r2", order="order-2"),
|
||||
],
|
||||
channel=channel,
|
||||
)
|
||||
assert [item.consumption_kg for item in summary.items] == [20, 35]
|
||||
assert summary.total_consumption_kg == 55
|
||||
assert summary.items[1].baseline_missing
|
||||
assert summary.items[1].production_order == "order-2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_missing_baseline_uses_first_sample_without_fabricating_consumption(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
summary = aggregate([sample(10, 1000), sample(20, 1005)], channel=channel)
|
||||
assert summary.total_consumption_kg == 5
|
||||
assert all(item.baseline_missing for item in summary.items)
|
||||
assert aggregate([sample(10, 1000)], channel=channel).total_consumption_kg == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_no_samples_and_zero_items_filter(channel):
|
||||
assert aggregate([], channel=channel).items == ()
|
||||
sample = channel_sample if channel else machine_sample
|
||||
rows = [sample(0, 100), sample(10, 100)]
|
||||
summary = aggregate(rows, channel=channel)
|
||||
assert len(summary.items) == 1 and summary.total_consumption_kg == 0
|
||||
assert aggregate(rows, channel=channel, include_zero=False).items == ()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
@pytest.mark.parametrize("values", [(100, 90), (100, 90, 150)])
|
||||
def test_counter_reset_rejected_even_when_final_value_recovers(channel, values):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
with pytest.raises(ValueError, match="decreased/reset"):
|
||||
aggregate(
|
||||
[sample(index * 10, value) for index, value in enumerate(values)], channel=channel
|
||||
)
|
||||
|
||||
|
||||
def test_last_valid_baseline_and_end_skip_null_and_nonfinite_counters():
|
||||
summary = aggregate(
|
||||
[
|
||||
machine_sample(-2, 100),
|
||||
machine_sample(-1, None),
|
||||
machine_sample(0, float("nan")),
|
||||
machine_sample(10, 105),
|
||||
machine_sample(479, float("inf")),
|
||||
]
|
||||
)
|
||||
assert summary.total_consumption_kg == 5
|
||||
assert summary.items[0].baseline_timestamp == START - timedelta(minutes=2)
|
||||
assert summary.items[0].end_timestamp == START + timedelta(minutes=10)
|
||||
|
||||
|
||||
def test_multiple_calculations_and_supplied_k7_b1_examples():
|
||||
examples = {
|
||||
"k7-fiber-consumption": (12083.537, 15552.303, 3468.766),
|
||||
"bento1-fresh-bentonite-consumption": (34604.833, 47320.628, 12715.795),
|
||||
"bento1-spreader3-consumption": (9540.429, 11303.167, 1762.738),
|
||||
}
|
||||
rows = [
|
||||
machine_sample(minutes, value, calculation=calculation)
|
||||
for calculation, (baseline, end, _) in examples.items()
|
||||
for minutes, value in ((-1, baseline), (479, end))
|
||||
]
|
||||
summary = aggregate(rows, calculation_ids=tuple(examples))
|
||||
assert {item.calculation_id: item.consumption_kg for item in summary.items} == pytest.approx(
|
||||
{calculation: values[2] for calculation, values in examples.items()}
|
||||
)
|
||||
assert summary.total_consumption_kg == pytest.approx(
|
||||
sum(values[2] for values in examples.values())
|
||||
)
|
||||
|
||||
|
||||
def test_channel_b_identity_attribution_and_no_null_carry_forward():
|
||||
rows = [
|
||||
channel_sample(-1, 100, name="Old"),
|
||||
channel_sample(10, 110, name="Material A"),
|
||||
channel_sample(20, 130, name="Material A"),
|
||||
channel_sample(30, 135, name=None),
|
||||
channel_sample(40, 140, name=" "),
|
||||
channel_sample(50, 155, name="Material A"),
|
||||
channel_sample(60, 165, name="Material B"),
|
||||
]
|
||||
summary = aggregate(rows, channel=True)
|
||||
assert [(item.material_name, item.consumption_kg) for item in summary.items] == [
|
||||
("Material A", 30),
|
||||
(None, 10),
|
||||
("Material A", 15),
|
||||
("Material B", 10),
|
||||
]
|
||||
assert summary.items[1].material_mapping_status == "UNAVAILABLE"
|
||||
assert all(item.material_number is None for item in summary.items)
|
||||
assert summary.total_consumption_kg == 65
|
||||
assert all(item.material_name != "Old" for item in summary.items)
|
||||
|
||||
|
||||
def test_material_number_metadata_and_quality_are_preserved():
|
||||
summary = aggregate(
|
||||
[
|
||||
channel_sample(0, 100, number="123", name=None),
|
||||
channel_sample(10, 105, number="123", name=None, quality=False),
|
||||
channel_sample(20, 110, number="123", name=None, quality=True),
|
||||
],
|
||||
channel=True,
|
||||
)
|
||||
item = summary.items[0]
|
||||
assert item.material_number == "123" and item.material_name is None
|
||||
assert item.material_mapping_status == "ASSIGNED"
|
||||
assert not item.percentage_sum_valid
|
||||
assert item.consumption_kg == 10
|
||||
|
||||
|
||||
def test_e1_historical_null_channel_fixtures():
|
||||
expected = {
|
||||
"Ex1": [0, 4890.271, 4890.271, 1772.723, 0, 0, 672.412],
|
||||
"Ex2": [7596.677, 822.973, 2481.581, 1266.113, 0, 0, 493.784],
|
||||
}
|
||||
rows = [
|
||||
channel_sample(
|
||||
minutes, value, extruder=extruder, channel=f"C{index}", name=None, status="UNAVAILABLE"
|
||||
)
|
||||
for extruder, deltas in expected.items()
|
||||
for index, delta in enumerate(deltas, 1)
|
||||
for minutes, value in ((-1, 5000), (479, 5000 + delta))
|
||||
]
|
||||
summary = aggregate(rows, channel=True)
|
||||
assert len(summary.items) == 14
|
||||
assert {(item.extruder, item.doser_channel): item.consumption_kg for item in summary.items} == (
|
||||
pytest.approx(
|
||||
{
|
||||
(extruder, f"C{index}"): delta
|
||||
for extruder, deltas in expected.items()
|
||||
for index, delta in enumerate(deltas, 1)
|
||||
}
|
||||
)
|
||||
)
|
||||
assert all(item.material_name is None for item in summary.items)
|
||||
assert all(item.material_mapping_status == "UNAVAILABLE" for item in summary.items)
|
||||
assert summary == aggregate(reversed(rows), channel=True)
|
||||
assert len(aggregate(rows, channel=True, include_zero=False).items) == 9
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_dst_fold_boundaries_use_instants(channel):
|
||||
berlin = ZoneInfo("Europe/Berlin")
|
||||
start = datetime(2026, 10, 25, 2, 30, tzinfo=berlin, fold=0)
|
||||
end = start.replace(fold=1)
|
||||
sample = channel_sample if channel else machine_sample
|
||||
rows = [
|
||||
replace(sample(value=value), timestamp=timestamp)
|
||||
for timestamp, value in (
|
||||
(start, 100),
|
||||
(datetime(2026, 10, 25, 1, 20, tzinfo=UTC), 110),
|
||||
(end, 500),
|
||||
)
|
||||
]
|
||||
summary = aggregate(rows, channel=channel, start=start, end=end)
|
||||
assert summary.total_consumption_kg == 10
|
||||
assert summary.start is start and summary.end is end
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_invalid_windows_precede_reader_call(channel):
|
||||
reader = Mock()
|
||||
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
|
||||
for changes in (
|
||||
{"start": START.replace(tzinfo=None)},
|
||||
{"end": END.replace(tzinfo=None)},
|
||||
{"end": START},
|
||||
{"end": START - timedelta(hours=1)},
|
||||
{"machine_id": ""},
|
||||
{"calculation_ids": ()},
|
||||
{"calculation_ids": ("calc", "calc")},
|
||||
):
|
||||
inputs = {
|
||||
"machine_id": "machine",
|
||||
"calculation_ids": ("calc",),
|
||||
"start": START,
|
||||
"end": END,
|
||||
**changes,
|
||||
}
|
||||
with pytest.raises(ValueError):
|
||||
service.summarize(**inputs)
|
||||
with pytest.raises(ValueError):
|
||||
aggregate([], channel=channel, **changes)
|
||||
reader.get_snapshots.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_service_composes_once_and_propagates_errors(channel):
|
||||
reader = Mock()
|
||||
reader.get_snapshots.return_value = [channel_sample() if channel else machine_sample()]
|
||||
service = ShiftChannelMaterialService(reader) if channel else ShiftMaterialService(reader)
|
||||
inputs = {"machine_id": "machine", "calculation_ids": ("calc",), "start": START, "end": END}
|
||||
assert service.summarize(**inputs) == aggregate(
|
||||
reader.get_snapshots.return_value, channel=channel
|
||||
)
|
||||
reader.get_snapshots.assert_called_once_with(**inputs)
|
||||
reader.get_snapshots.side_effect = RuntimeError("reader failed")
|
||||
with pytest.raises(RuntimeError, match="reader failed"):
|
||||
service.summarize(**inputs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_ambiguous_stream_timestamps_and_reappearing_runs_rejected(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
with pytest.raises(ValueError, match="same stream timestamp"):
|
||||
aggregate([sample(0, 100), sample(0, 100)], channel=channel)
|
||||
with pytest.raises(ValueError, match="reappeared"):
|
||||
aggregate([sample(0, 100), sample(10, 10, run="r2"), sample(20, 200)], channel=channel)
|
||||
with pytest.raises(ValueError, match="Production order"):
|
||||
aggregate([sample(0, 100), sample(10, 110, order="different")], channel=channel)
|
||||
|
||||
|
||||
def test_machine_and_calculation_scoping():
|
||||
summary = aggregate(
|
||||
[
|
||||
machine_sample(),
|
||||
machine_sample(10, 110),
|
||||
replace(machine_sample(20, 1000), machine_id="other"),
|
||||
machine_sample(20, 1000, calculation="other"),
|
||||
]
|
||||
)
|
||||
assert summary.total_consumption_kg == 10
|
||||
|
||||
|
||||
def test_channel_invalid_numeric_samples_are_not_used_as_baseline_or_end():
|
||||
summary = aggregate(
|
||||
[
|
||||
channel_sample(-2, 100),
|
||||
channel_sample(-1, None),
|
||||
channel_sample(10, 120, name=None),
|
||||
channel_sample(479, float("nan")),
|
||||
],
|
||||
channel=True,
|
||||
)
|
||||
assert summary.total_consumption_kg == 20
|
||||
assert summary.items[0].material_name is None
|
||||
assert summary.items[0].material_mapping_status == "UNAVAILABLE"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_new_run_exactly_at_shift_start_is_its_own_baseline(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
summary = aggregate(
|
||||
[sample(-1, 10000, run="old"), sample(0, 50, run="new"), sample(10, 60, run="new")],
|
||||
channel=channel,
|
||||
)
|
||||
assert len(summary.items) == 1
|
||||
assert summary.items[0].run_id == "new"
|
||||
assert not summary.items[0].baseline_missing
|
||||
assert summary.total_consumption_kg == 10
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_invalid_counters_do_not_hide_run_boundaries(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
summary = aggregate(
|
||||
[sample(-2, 1000), sample(-1, None, run="r2"),
|
||||
sample(10, 50, run="r2"), sample(20, 60, run="r2")],
|
||||
channel=channel,
|
||||
)
|
||||
assert summary.total_consumption_kg == 10
|
||||
assert len(summary.items) == 1
|
||||
assert summary.items[0].run_id == "r2"
|
||||
assert summary.items[0].baseline_missing
|
||||
with pytest.raises(ValueError, match="reappeared"):
|
||||
aggregate([sample(0, 100), sample(10, None, run="r2"), sample(20, 120)],
|
||||
channel=channel)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_negative_counter_is_rejected(channel):
|
||||
sample = channel_sample if channel else machine_sample
|
||||
with pytest.raises(ValueError, match="non-negative"):
|
||||
aggregate([sample(0, 100), sample(10, -1)], channel=channel)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("channel", [False, True])
|
||||
def test_spring_dst_window_uses_elapsed_instants(channel):
|
||||
berlin = ZoneInfo("Europe/Berlin")
|
||||
start = datetime(2026, 3, 29, 1, 30, tzinfo=berlin)
|
||||
end = datetime(2026, 3, 29, 3, 30, tzinfo=berlin)
|
||||
sample = channel_sample if channel else machine_sample
|
||||
rows = [replace(sample(value=value), timestamp=timestamp) for timestamp, value in
|
||||
[(start, 100), (datetime(2026, 3, 29, 1, 20, tzinfo=UTC), 110), (end, 999)]]
|
||||
assert (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() == 3600
|
||||
assert aggregate(rows, channel=channel, start=start, end=end).total_consumption_kg == 10
|
||||
Reference in new issue
Block a user