import sqlite3 import traceback from dataclasses import FrozenInstanceError, replace from datetime import UTC, datetime, timedelta from unittest.mock import MagicMock, Mock from zoneinfo import ZoneInfo import pytest from production_analytics.calculations.shift_downtime import ( ShiftDowntimeEvent, aggregate_shift_downtime, ) from production_analytics.service.postgres_downtime import ( DowntimeReadError, PostgresDowntimeRepository, ) from production_analytics.service.postgres_material import PostgresSettings from production_analytics.service.shift_downtime import ShiftDowntimeService BERLIN = ZoneInfo("Europe/Berlin") START = datetime(2026, 10, 7, 6, tzinfo=BERLIN) END = START + timedelta(hours=8) def event(identifier="event", *, start=START, end=END, reason="Reason", **changes): return replace( ShiftDowntimeEvent( identifier, "machine", start, end, "reason-id", reason, "Description", "Group", "PLANNED", "Comment", ), **changes, ) def summarize(events, **changes): return aggregate_shift_downtime( events, **{ "machine_id": "machine", "start": START, "end": END, **changes, }, ) def test_clip_both_boundaries_preserve_source_and_immutable_results(): source = event(start=START - timedelta(hours=1), end=END + timedelta(hours=1)) summary = summarize([source]) assert summary.shift_duration_seconds == summary.total_downtime_seconds == 480 * 60 assert summary.non_downtime_seconds == 0 clipped = summary.events[0] assert clipped.source is source assert clipped.start is START and clipped.end is END assert clipped.duration_seconds == 480 * 60 assert summary.reasons[0].duration_seconds == 480 * 60 assert summary.reasons[0].event_count == 1 assert summary.reasons[0].reason_description == "Description" assert clipped.source.comment == "Comment" for value, field in ( (source, "comment"), (summary, "machine_id"), (clipped, "start"), (summary.reasons[0], "reason_name"), ): with pytest.raises(FrozenInstanceError): setattr(value, field, None) def test_open_event_clipped_to_shift_end(): summary = summarize([event(start=START + timedelta(hours=7), end=None)]) assert summary.total_downtime_seconds == 3600 assert summary.non_downtime_seconds == 7 * 3600 assert summary.events[0].end is END assert summary.events[0].source.source_end is None def test_raw_closed_event_without_attribution(): source = event(start=START + timedelta(hours=1), end=START + timedelta(hours=2)) summary = summarize([source]) assert source.attributed_start is source.attributed_end is None assert summary.events[0].start == source.source_start assert summary.events[0].end == source.source_end assert summary.total_downtime_seconds == 3600 def test_attributed_end_closes_raw_open_event(): attributed_end = START + timedelta(hours=2) source = event(end=None, attributed_end=attributed_end) summary = summarize([source]) assert summary.events[0].start == START assert summary.events[0].end is attributed_end assert summary.events[0].source.source_end is None assert summary.total_downtime_seconds == 2 * 3600 def test_attributed_start_with_no_end_remains_open(): summary = summarize([event(end=None, attributed_start=START + timedelta(hours=7))]) assert summary.total_downtime_seconds == 3600 assert summary.events[0].end is END def test_attribution_overrides_conflicting_raw_interval(): attributed_start = START + timedelta(hours=1) attributed_end = START + timedelta(hours=2) source = event( start=END, end=END + timedelta(hours=2), attributed_start=attributed_start, attributed_end=attributed_end, ) summary = summarize([source]) assert summary.events[0].start is attributed_start assert summary.events[0].end is attributed_end assert summary.total_downtime_seconds == 3600 assert source.source_start == END assert source.source_end == END + timedelta(hours=2) def test_attributed_interval_clips_both_shift_boundaries(): source = event( start=END, end=END, attributed_start=START - timedelta(hours=1), attributed_end=END + timedelta(hours=1), ) summary = summarize([source]) assert summary.events[0].start is START assert summary.events[0].end is END assert summary.total_downtime_seconds == 8 * 3600 def test_production_reconciled_no_data_event_does_not_overlap_later_shift(): source_start = datetime(2026, 10, 12, 8, 56, 30, tzinfo=UTC) source = event( start=source_start, end=None, attributed_start=source_start, attributed_end=datetime(2026, 10, 12, 12, 36, 2, tzinfo=UTC), ) summary = summarize( [source], start=datetime(2026, 10, 13, 12, tzinfo=UTC), end=datetime(2026, 10, 13, 20, tzinfo=UTC), ) assert summary.events == summary.reasons == () assert summary.total_downtime_seconds == 0 assert summary.non_downtime_seconds == 8 * 3600 def test_attributed_intervals_preserve_union_and_reason_aggregation(): sources = [ event( identifier, end=None, reason=reason, attributed_start=START + timedelta(hours=lower), attributed_end=START + timedelta(hours=upper), ) for identifier, reason, lower, upper in [ ("a", "A", 0, 2), ("b", "A", 1, 3), ("c", "B", 2, 4), ] ] summary = summarize(sources) assert summary.total_downtime_seconds == 4 * 3600 assert summary.non_downtime_seconds == 4 * 3600 assert [ (reason.reason_name, reason.duration_seconds, reason.event_count) for reason in summary.reasons ] == [("A", 3 * 3600, 2), ("B", 2 * 3600, 1)] def test_overlap_nested_duplicates_and_adjacent_intervals_are_not_double_counted(): events = [ event("a", end=START + timedelta(hours=2)), event("b", start=START + timedelta(hours=1), end=START + timedelta(hours=3)), event("c", start=START + timedelta(minutes=30), end=START + timedelta(hours=1)), event("d", start=START + timedelta(hours=3), end=START + timedelta(hours=4)), ] summary = summarize([*events, events[0]]) assert summary.total_downtime_seconds == 4 * 3600 assert summary.non_downtime_seconds == 4 * 3600 assert summary.reasons[0].duration_seconds == 4 * 3600 def test_overlapping_different_reasons_do_not_inflate_total(): summary = summarize( [ event("a", end=START + timedelta(hours=2), reason="A"), event( "b", start=START + timedelta(hours=1), end=START + timedelta(hours=3), reason="B" ), ] ) assert summary.total_downtime_seconds == 3 * 3600 assert sum(reason.duration_seconds for reason in summary.reasons) == 4 * 3600 assert summary.non_downtime_seconds == 5 * 3600 def test_half_open_window_excludes_touching_zero_length_and_other_machine_events(): summary = summarize( [ event("before", start=START - timedelta(hours=1), end=START), event("after", start=END, end=END + timedelta(hours=1)), event("zero", start=START, end=START), event("other", machine_id="other"), event("future-open", start=END, end=None), ] ) assert summary.events == summary.reasons == () assert summary.total_downtime_seconds == 0 assert summary.non_downtime_seconds == 480 * 60 def test_empty_shift(): summary = summarize([]) assert summary.total_downtime_seconds == 0 assert summary.non_downtime_seconds == summary.shift_duration_seconds == 480 * 60 def test_example_reason_totals_using_synthetic_intervals_matching_supplied_approximations(): # Exact synthetic durations chosen within the supplied rounded real-data examples. intervals = [ ("clean", "Reinigung", -10, 50.84), ("setup1", "Rüstzeit Auftragsbeginn", 60, 91.34), ("mechanical", "212 - Hülsenzuführung mechanisch", 180, 59.22), ("setup2", "Rüstzeit Auftragsbeginn", 469.2, 10.8), ] events = [ event( identifier, reason=reason, start=START + timedelta(minutes=minute), end=START + timedelta(minutes=max(0, minute) + duration), ) for identifier, reason, minute, duration in intervals ] summary = summarize(events) assert summary.total_downtime_seconds / 60 == pytest.approx(212.2) assert summary.non_downtime_seconds / 60 == pytest.approx(267.8) assert [ (value.reason_name, round(value.duration_seconds / 60, 1)) for value in summary.reasons ] == [ ("Rüstzeit Auftragsbeginn", 102.1), ("212 - Hülsenzuführung mechanisch", 59.2), ("Reinigung", 50.8), ] assert summary.reasons[0].event_count == 2 def test_nullable_reasons_and_deterministic_order(): events = [ event( "z", reason=None, reason_id=None, reason_description=None, reason_group=None, category=None, comment=None, end=START + timedelta(minutes=1), ), event("a", reason="A", end=START + timedelta(minutes=1)), ] summary = summarize(events) assert summary == summarize(reversed(events)) assert [value.source.external_id for value in summary.events] == ["a", "z"] assert any(reason.reason_id is None for reason in summary.reasons) @pytest.mark.parametrize("date,hours", [(datetime(2026, 3, 29), 7), (datetime(2026, 10, 25), 9)]) def test_dst_uses_elapsed_time_not_wall_clock_duration(date, hours): start = date.replace(tzinfo=BERLIN) end = start + timedelta(hours=8) summary = summarize([event(start=start, end=end)], start=start, end=end) assert summary.total_downtime_seconds == summary.shift_duration_seconds == hours * 3600 assert summary.start is start and summary.end is end @pytest.fixture def db(monkeypatch): connect = MagicMock() monkeypatch.setattr("psycopg.connect", connect) connection = connect.return_value.__enter__.return_value connection.execute.return_value.fetchall.return_value = [ ( "id", "machine", START.astimezone(UTC), None, None, None, None, None, "UNKNOWN", None, START.astimezone(UTC), END.astimezone(UTC), ) ] repository = PostgresDowntimeRepository(PostgresSettings("localhost", 5432, "db", "user", "pw")) return repository, connect, connection def test_repository_sql_parameters_mapping_and_lifecycle(db): repository, connect, connection = db values = repository.get_events(machine_id="machine", start=START, end=END) sql, params = connection.execute.call_args.args assert params == ("machine", END, START) assert "WHERE machine_id = %s AND COALESCE(attributed_start, source_start) < %s" in sql assert "COALESCE(attributed_end, source_end) IS NULL" in sql assert "OR COALESCE(attributed_end, source_end) > %s" in sql assert "ORDER BY COALESCE(attributed_start, source_start), external_id" in sql assert "category, comment, attributed_start, attributed_end" in sql assert "production_order" not in sql assert values[0].attributed_start == START.astimezone(UTC) assert values[0].attributed_end == END.astimezone(UTC) assert len(values) == 1 and values[0].source_end is None assert values[0].source_start.tzinfo is UTC connect.assert_called_once_with( host="localhost", port=5432, dbname="db", user="user", password="pw", connect_timeout=10, options="-c statement_timeout=10000", ) connect.return_value.__exit__.assert_called_once() connection.commit.assert_not_called() def test_machine_id_is_parameterized(db): machine_id = "id'; DELETE FROM anything; --" db[0].get_events(machine_id=machine_id, start=START, end=END) sql, params = db[2].execute.call_args.args assert machine_id not in sql assert params[0] == machine_id def test_repository_excludes_production_reconciled_event_from_later_shift(db): repository, _, connection = db # Execute the repository's overlap predicate, translating only driver placeholders. with sqlite3.connect(":memory:") as database: database.execute( """CREATE TABLE production_downtime_events ( external_id, machine_id, source_start, source_end, reason_id, reason_name, reason_description, reason_group, category, comment, attributed_start, attributed_end)""" ) database.execute( """INSERT INTO production_downtime_events (external_id, machine_id, source_start, attributed_start, attributed_end) VALUES (?, ?, ?, ?, ?)""", ( "reconciled-no-data", "machine", "2026-10-12T08:56:30+00:00", "2026-10-12T08:56:30+00:00", "2026-10-12T12:36:02+00:00", ), ) def execute(sql, params): return database.execute( sql.replace("%s", "?"), tuple( value.isoformat() if isinstance(value, datetime) else value for value in params ), ) connection.execute.side_effect = execute assert repository.get_events( machine_id="machine", start=datetime(2026, 10, 13, 12, tzinfo=UTC), end=datetime(2026, 10, 13, 20, tzinfo=UTC), ) == [] @pytest.mark.parametrize( "changes", [ {"machine_id": ""}, {"machine_id": " "}, {"machine_id": "bad\x00"}, {"start": START.replace(tzinfo=None)}, {"end": END.replace(tzinfo=None)}, {"start": None}, {"end": START}, {"end": START - timedelta(seconds=1)}, ], ) def test_invalid_window_before_database_read(db, changes): inputs = {"machine_id": "machine", "start": START, "end": END, **changes} with pytest.raises(ValueError): db[0].get_events(**inputs) db[1].assert_not_called() with pytest.raises(ValueError): aggregate_shift_downtime([], **inputs) reader = Mock() with pytest.raises(ValueError): ShiftDowntimeService(reader).summarize(**inputs) reader.get_events.assert_not_called() @pytest.mark.parametrize("stage", ["connect", "execute", "fetch", "close"]) def test_repository_errors_are_safe(db, stage): repository, connect, connection = db target = { "connect": connect, "execute": connection.execute, "fetch": connection.execute.return_value.fetchall, "close": connect.return_value.__exit__, }[stage] target.side_effect = RuntimeError("private-password") with pytest.raises(DowntimeReadError, match="read failed") as error: repository.get_events(machine_id="machine", start=START, end=END) assert "private-password" not in "".join(traceback.format_exception(error.value)) @pytest.mark.parametrize( "changes", [ {"source_start": START.replace(tzinfo=None)}, {"source_end": END.replace(tzinfo=None)}, {"attributed_start": START.replace(tzinfo=None)}, {"attributed_end": END.replace(tzinfo=None)}, {"attributed_start": "invalid"}, {"attributed_end": "invalid"}, {"source_end": START - timedelta(seconds=1)}, {"reason_name": 123}, ], ) def test_invalid_source_model(changes): with pytest.raises(ValueError): event(**changes) def test_repository_invalid_row_is_wrapped(db): db[2].execute.return_value.fetchall.return_value = [("invalid-row",)] with pytest.raises(DowntimeReadError, match="invalid row"): db[0].get_events(machine_id="machine", start=START, end=END) def test_service_reads_once_and_propagates_errors(): reader = Mock() reader.get_events.return_value = [event()] summary = ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END) assert summary == summarize([event()]) reader.get_events.assert_called_once_with(machine_id="machine", start=START, end=END) reader.get_events.side_effect = DowntimeReadError("read failed") with pytest.raises(DowntimeReadError): ShiftDowntimeService(reader).summarize(machine_id="machine", start=START, end=END)