from dataclasses import replace from datetime import UTC, datetime from types import SimpleNamespace from unittest.mock import MagicMock import pytest from production_analytics.enlyze.gateway import EnlyzeProductionRun from production_analytics.service.historical_reconcile import ( Decision, HistoricalRecord, decide, reconcile_machine, reconciliation_window, ) from production_analytics.service.postgres_historical_reconcile import PostgresHistoricalRepository def at(hour=12): return datetime(2026, 10, 13, hour, tzinfo=UTC) def record(order="old", machine="generic"): return HistoricalRecord("material_consumption_snapshots", ("calc", machine, at()), machine, at(), order, "retained-counter-run") def run(order="Machine-123", machine="generic"): return EnlyzeProductionRun("source-run", machine, None, order, at(10), at(14)) def confirmation(order="123", hour=12): return SimpleNamespace(production_order=order, workplace="workplace", timestamp=at(hour), is_finished_goods=True) def decision(r=None, runs=None, confirmations=None): return decide(r or record(), runs if runs is not None else [run()], confirmations if confirmations is not None else [confirmation()], "workplace", "Machine-{production_order}") def test_correct_and_stale_assignments(): assert decision(record("Machine-123")).order == "Machine-123" d = decision() assert d.order == "Machine-123" assert d.record.run_id == "retained-counter-run" @pytest.mark.parametrize("machine", ["arbitrary-machine", "another-machine"]) def test_machine_independent(machine): assert decision(record(machine=machine), [run(machine=machine)]).order == "Machine-123" @pytest.mark.parametrize("runs, confirmations", [ ([run(), run("Machine-456")], [confirmation()]), ([run()], [confirmation(), confirmation("456")]), ([], [confirmation()]), ([replace(run(), end=None)], [confirmation()]), ([run(), replace(run(), end=None)], [confirmation()]), ([run()], []), ]) def test_ambiguous_or_missing_evidence(runs, confirmations): assert decision(runs=runs, confirmations=confirmations).order is None def test_previous_order_at_start_is_ignored_when_current_order_is_inside(): start = confirmation("1030", 10) current = confirmation("12026001032") d = decide(record("K 7-12026001030", "reference-machine"), [replace(run("K 7-12026001032", "reference-machine"), start=at(10), end=at(14))], [start, current], "workplace", "K 7-{production_order}") assert d.order == "K 7-12026001032" def test_interior_conflicting_order_remains_unresolved(): assert decision(confirmations=[confirmation("123"), confirmation("456", 13)]).order is None def test_correct_order_at_start_without_interior_evidence_is_unresolved(): boundary = confirmation("123", 10) assert decision(confirmations=[boundary]).order is None def test_correct_order_strictly_inside_run_reconciles(): assert decision(confirmations=[confirmation("123", 11)]).order == "Machine-123" def test_confirmation_at_run_end_is_ignored(): end = confirmation("123", 14) assert decision(confirmations=[end]).order is None def test_shared_boundary_confirmation_corroborates_neither_adjacent_run(): left = replace(run("Machine-123"), start=at(10), end=at(12)) right = replace(run("Machine-456"), uuid="right", start=at(12), end=at(14)) boundary = confirmation("123", 12) left_record = replace(record(), timestamp=at(11)) right_record = replace(record(), timestamp=at(13)) assert decide(left_record, [left, right], [boundary], "workplace", "Machine-{production_order}").order is None assert decide(right_record, [left, right], [boundary], "workplace", "Machine-{production_order}").order is None def test_k7_repaired_1030_to_1032_boundary_case_is_correctable(): r = record("K 7-12026001030", "reference-machine") run_start = at(11) k7_run = replace(run("K 7-12026001032", "reference-machine"), start=run_start, end=at(17)) previous = confirmation("12026001030", 11) d = decide(r, [k7_run], [previous, confirmation("12026001032", 12)], "workplace", "K 7-{production_order}") assert d.order == "K 7-12026001032" d = decide(r, [k7_run], [confirmation("12026001032"), confirmation("12026001037", 13)], "workplace", "K 7-{production_order}") assert d.order is None def test_calendar_days_and_berlin_dst(): start, end = reconciliation_window(datetime(2026, 10, 15, 2, 30, tzinfo=UTC)) assert start.isoformat() == "2026-10-12T00:00:00+02:00" assert end.isoformat() == "2026-10-15T00:00:00+02:00" start, end = reconciliation_window(datetime(2026, 10, 27, tzinfo=UTC)) assert (end.timestamp() - start.timestamp()) / 3600 == 73 # UTC date still previous day; use Berlin's date. assert reconciliation_window(datetime(2026, 10, 14, 23, tzinfo=UTC))[1].day == 15 @pytest.mark.parametrize("days", [0, -1, True]) def test_invalid_window(days): with pytest.raises(ValueError): reconciliation_window(at(), days) def test_dry_run_and_source_failure(): repository = MagicMock() repository.read.return_value = [record()] repository.guard_runs.side_effect = lambda decisions: decisions source = MagicMock() source.get_production_runs.return_value = [run()] erp = MagicMock() erp.get_confirmations.return_value = [confirmation()] config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") decisions, applied = reconcile_machine(repository, source, erp, config, "Machine-{production_order}", at(11), at(13), True) assert decisions[0].order == "Machine-123" and applied == 0 repository.apply.assert_not_called() assert erp.get_confirmations.call_args.kwargs["start"] == at(10) assert erp.get_confirmations.call_args.kwargs["end"] == at(14) source.get_production_runs.side_effect = RuntimeError("source unavailable") with pytest.raises(RuntimeError, match="source unavailable"): reconcile_machine(repository, source, erp, config, "Machine-{production_order}", at(11), at(13)) repository.apply.assert_not_called() def repository_with_connection(): repository = PostgresHistoricalRepository(None) connection = MagicMock() repository.connect = MagicMock() repository.connect.return_value.__enter__.return_value = connection return repository, connection def test_atomic_update_audit_and_repeated_run(): repository, connection = repository_with_connection() connection.execute.return_value.fetchone.side_effect = [(1,), (at(),)] assert repository.apply([decision()]) == 1 calls = connection.execute.call_args_list assert len(calls) == 5 # isolation, lock, run guard, update, audit update_args = calls[3].args[1] assert update_args == ("Machine-123", "calc", "generic", at(), "old", "retained-counter-run") audit_args = calls[4].args[1] assert audit_args[0] == "generic" assert audit_args[3:6] == ("old", "Machine-123", "retained-counter-run") connection.reset_mock() assert repository.apply([decision(record("Machine-123"))]) == 0 assert connection.execute.call_count == 2 # no update or audit def test_concurrent_change_fails_without_audit(): repository, connection = repository_with_connection() connection.execute.return_value.fetchone.side_effect = [(1,), None] with pytest.raises(RuntimeError, match="concurrently"): repository.apply([decision()]) assert connection.execute.call_count == 4 assert repository.connect.return_value.__exit__.call_args.args[0] is RuntimeError def test_partial_and_split_run_guard(): repository, connection = repository_with_connection() connection.execute.return_value.fetchone.return_value = (2,) assert repository.guard_runs([decision()])[0].order is None d = decision() other = replace(d, record=replace(d.record, timestamp=at(13)), order="Machine-456") assert repository.guard_runs([d, other]) == [d, other] assert all(d.order is None for d in repository.guard_runs([d, replace(other, order=None)])) connection.execute.return_value.fetchone.return_value = (1,) assert repository.guard_runs([decision()])[0].order == "Machine-123" def test_database_failure_propagates(): repository = PostgresHistoricalRepository(None) repository.connect = MagicMock(side_effect=RuntimeError("database unavailable")) with pytest.raises(RuntimeError, match="database unavailable"): repository.read("machine", at(10), at(14)) def test_cli_defaults(): from production_analytics.cli.__main__ import _parser args = _parser().parse_args(["historical-reconcile", "--dry-run"]) assert args.lookback_days == 3 and args.dry_run and not args.verbose assert _parser().parse_args(["historical-reconcile", "--verbose"]).verbose assert _parser().parse_args(["historical-reconcile", "--dry-run", "--verbose"]).verbose @pytest.mark.parametrize("split", [False, True]) def test_end_to_end_dry_run_idempotency_and_physical_values(sqlite_schema, split): import sqlite3 database = sqlite3.connect(":memory:") database.executescript(sqlite_schema) database.execute( "INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)", (at().isoformat(), "calc", "generic", "old", "retained-counter-run", 1234.5), ) if split: database.execute("DELETE FROM material_consumption_snapshots") database.executemany( "INSERT INTO material_consumption_snapshots VALUES (?, ?, ?, ?, ?, ?)", [(at(hour).isoformat(), "calc", "generic", "OLD", "R1", value) for hour, value in zip([10, 11, 12, 13], [1000, 1010, 1025, 1040])], ) class Connection: def __enter__(self): return self def __exit__(self, exc_type, *_): database.rollback() if exc_type else database.commit() def execute(self, statement, parameters=()): statement = statement if isinstance(statement, str) else statement.as_string() if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")): return None parameters = tuple( str(p.obj) if hasattr(p, "obj") else p.isoformat() if isinstance(p, datetime) else p for p in parameters ) return database.execute(statement.replace("%s", "?"), parameters) class Repository(PostgresHistoricalRepository): def connect(self): return Connection() def read(self, machine_id, start, end): return [replace(r, timestamp=datetime.fromisoformat(r.timestamp), identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2]))) for r in super().read(machine_id, start, end)] repository = Repository(None) source = SimpleNamespace(get_production_runs=lambda machine: [run()]) erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()]) config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") if split: source = SimpleNamespace(get_production_runs=lambda machine: [ replace(run("1032"), start=at(10), end=at(12)), replace(run("1037"), uuid="second", start=at(12), end=at(14)), ]) erp = SimpleNamespace(get_confirmations=lambda **kwargs: [ confirmation("1032", 11), confirmation("1037", 13)]) template = "{production_order}" if split else "Machine-{production_order}" args = (repository, source, erp, config, template, at(10), at(14)) decisions, count = reconcile_machine(*args, dry_run=True) assert count == 0 and decisions[0].order == ("1032" if split else "Machine-123") assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) assert database.execute( "SELECT production_order FROM material_consumption_snapshots" ).fetchone() == (("OLD",) if split else ("old",)) assert reconcile_machine(*args)[1] == (4 if split else 1) assert reconcile_machine(*args)[1] == 0 assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == ( 4 if split else 1,) if split: from production_analytics.calculations.shift_material import ( ShiftMaterialSnapshot, aggregate_shift_material, ) from production_analytics.service.historical_reconcile import grouped_counts assert grouped_counts(decisions) == (1, 1, 2, 0, 0) rows = database.execute( "SELECT timestamp, calculation_id, machine_id, production_order, run_id, " "consumption_kg FROM material_consumption_snapshots ORDER BY timestamp" ).fetchall() snapshots = [ShiftMaterialSnapshot(datetime.fromisoformat(r[0]), *r[1:]) for r in rows] assert [(r.timestamp.hour, r.run_id, r.consumption_kg) for r in snapshots] == [ (10, "R1", 1000), (11, "R1", 1010), (12, "R1", 1025), (13, "R1", 1040)] summary = aggregate_shift_material(snapshots, machine_id="generic", calculation_ids=("calc",), start=at(10), end=at(14)) assert [(i.production_order, i.consumption_kg) for i in summary.items] == [ ("1032", 10), ("1037", 30)] assert summary.total_consumption_kg == 40 return assert database.execute( "SELECT timestamp, run_id, consumption_kg, production_order " "FROM material_consumption_snapshots" ).fetchone() == (at().isoformat(), "retained-counter-run", 1234.5, "Machine-123") def test_erp_failure_never_becomes_no_changes(): repository = MagicMock() repository.read.return_value = [record()] source = SimpleNamespace(get_production_runs=lambda machine: [run()]) erp = MagicMock() erp.get_confirmations.side_effect = RuntimeError("ERP offline") with pytest.raises(RuntimeError, match="ERP offline"): reconcile_machine(repository, source, erp, SimpleNamespace(machine_id="generic", erp_workplace="workplace"), "Machine-{production_order}", at(10), at(14)) repository.apply.assert_not_called() def test_runtime_reports_machine_failures_and_continues(monkeypatch, capsys): from pathlib import Path from production_analytics.service import historical_runtime for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway", "ExplorationClient", "ErpProductionConfirmationGateway"): monkeypatch.setattr(historical_runtime, factory, MagicMock()) for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings, historical_runtime.ExplorationSettings): monkeypatch.setattr(settings, "from_environment", MagicMock()) reconcile = MagicMock(side_effect=[RuntimeError("source offline"), ([], 0), ([], 0)]) monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile) args = SimpleNamespace(lookback_days=3, dry_run=True, config=Path("config/shift-report-machines.yaml"), order_formats=Path("config/historical-order-formats.yaml")) assert historical_runtime.run(args, {}) == 1 assert reconcile.call_count == 3 output = capsys.readouterr().out assert "Physical runs inspected:" in output and "Unresolved segments:" in output assert "Order segments proposed:" in output assert "DRY RUN" in output and "FAILED B1" in output and "Failures: 1" in output assert "source offline" in output @pytest.mark.parametrize("dry_run", [True, False]) @pytest.mark.parametrize("verbose", [True, False]) def test_runtime_groups_record_output_and_preserves_totals(monkeypatch, capsys, dry_run, verbose): from datetime import timedelta from pathlib import Path from production_analytics.service import historical_runtime for factory in ("PostgresHistoricalRepository", "EnlyzeApiGateway", "ExplorationClient", "ErpProductionConfirmationGateway"): monkeypatch.setattr(historical_runtime, factory, MagicMock()) for settings in (historical_runtime.PostgresSettings, historical_runtime.ErpSettings, historical_runtime.ExplorationSettings): monkeypatch.setattr(settings, "from_environment", MagicMock()) start = at(10) correction_reason = ("closed ENLYZE run e0f474e0-1234 " "[2026-10-13T10:00:00+00:00, 2026-10-13T14:00:00+00:00) " "corroborated by ERP order K 7-12026001032") corrections = [ Decision(HistoricalRecord( "material_consumption_snapshots", ("calc", "machine", start + timedelta(seconds=i)), "machine", start + timedelta(seconds=i), "K 7-12026001030", "counter-run", ), "K 7-12026001032", correction_reason) for i in range(1964) ] unresolved = [ Decision(HistoricalRecord( "material_application_snapshots", ("application", "machine", start + timedelta(seconds=i)), "machine", start + timedelta(seconds=i), "B 1-42", "application-run", ), None, "unresolved: missing or overlapping closed ENLYZE runs") for i in range(8421) ] reconcile = MagicMock(side_effect=[(corrections, 1964 if not dry_run else 0), (unresolved, 0), ([], 0)]) monkeypatch.setattr(historical_runtime, "reconcile_machine", reconcile) args = SimpleNamespace(lookback_days=3, dry_run=dry_run, verbose=verbose, config=Path("config/shift-report-machines.yaml"), order_formats=Path("config/historical-order-formats.yaml")) assert historical_runtime.run(args, {}) == 0 output = capsys.readouterr().out correction_action = "proposed" if dry_run else "corrected" assert (f"B1 | {correction_action}: K 7-12026001030 -> K 7-12026001032 | " "ENLYZE run e0f474e0-1234 | 1964 records") in output assert ("E1 | unresolved: missing or overlapping closed ENLYZE runs | " "physical run application-run | source material_application_snapshots/application | " "8421 records | 2026-10-13T10:00:00+00:00 -> " "2026-10-13T12:20:20+00:00") in output assert output.count("1964 records") == 1 assert output.count("8421 records") == 1 if verbose: assert output.count("Proposed B1 " if dry_run else "Corrected B1 ") == 1964 assert output.count("Unresolved E1 ") == 8421 else: assert "Proposed B1 " not in output assert "Corrected B1 " not in output assert "Unresolved E1 " not in output assert "('calc', 'machine'" not in output assert len(output.splitlines()) == 15 assert "Machines checked: 3\nRecords inspected: 10385" in output assert f"Corrections {'proposed' if dry_run else 'applied'}: 1964" in output assert "Ambiguous/unresolved: 8421\nUnchanged: 0\nFailures: 0" in output assert "Physical runs inspected: 2\nRuns with proposed corrections: 1" in output assert f"Order segments {correction_action}: 1" in output assert "Unresolved runs: 1\nUnresolved segments: 1" in output def test_grouped_counts_distinguish_rows_runs_and_segments(): from production_analytics.service.historical_reconcile import grouped_counts d = decision() decisions = [replace(d, record=replace(d.record, timestamp=at(hour)), order=order) for hour, order in [(10, "A"), (11, "A"), (12, "B"), (13, None)]] assert grouped_counts(decisions) == (1, 1, 2, 1, 1) assert grouped_counts([]) == (0, 0, 0, 0, 0) @pytest.mark.parametrize("calculation", [ "bento1-fresh-bentonite-application", "bento1-spreader3-application", ]) def test_application_collision_deduplicates_audits_and_is_idempotent( sqlite_schema, calculation, ): database, repository = application_repository(sqlite_schema) for hour in (11, 12, 13): insert_application(database, calculation, hour, "old", "old-run", 4730.169159683733) insert_application(database, calculation, hour, "Machine-123", "source-run", 4730.169159683733) args = application_reconcile_args(repository) decisions, count = reconcile_machine(*args, dry_run=True) assert count == 0 and len([d for d in decisions if d.order != d.record.production_order]) == 3 assert application_rows(database, calculation) == 6 assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) assert reconcile_machine(*args)[1] == 3 assert application_rows(database, calculation) == 3 assert database.execute( "SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots " "WHERE calculation_id = ? ORDER BY timestamp", (calculation,) ).fetchall() == [("Machine-123", "source-run", 4730.169159683733)] * 3 assert database.execute( "SELECT previous_order, new_order, run_id, retained_run_id, action, reason, " "record_identity FROM historical_assignment_audit ORDER BY id" ).fetchall() == [ ("old", "Machine-123", "old-run", "source-run", "deduplicated", decisions[0].reason, str({"calculation_id": calculation, "machine_id": "generic", "timestamp": str(at(hour))})) for hour in (11, 12, 13) ] assert reconcile_machine(*args)[1] == 0 def test_application_without_target_updates_normally(sqlite_schema): database, repository = application_repository(sqlite_schema) insert_application(database, "calc", 12, "old", "old-run", 42.5) assert reconcile_machine(*application_reconcile_args(repository))[1] == 1 assert database.execute( "SELECT production_order, run_id, application_g_m2 FROM material_application_snapshots" ).fetchone() == ("Machine-123", "old-run", 42.5) assert database.execute( "SELECT action, retained_run_id FROM historical_assignment_audit" ).fetchone() == ("updated", None) @pytest.mark.parametrize("target_value,target_run", [ (99.0, "source-run"), (42.5, "unexpected-run"), ]) def test_application_collision_rolls_back_whole_machine( sqlite_schema, target_value, target_run, ): database, repository = application_repository(sqlite_schema) for hour in (11, 12): insert_application(database, "calc", hour, "old", "old-run", 42.5) insert_application(database, "calc", hour, "Machine-123", "source-run" if hour == 11 else target_run, 42.5 if hour == 11 else target_value) with pytest.raises(RuntimeError, match="conflicting measurement|unexpected target run"): reconcile_machine(*application_reconcile_args(repository)) assert application_rows(database, "calc") == 4 assert database.execute("SELECT count(*) FROM historical_assignment_audit").fetchone() == (0,) def application_repository(sqlite_schema): import sqlite3 database = sqlite3.connect(":memory:") database.executescript(sqlite_schema) class Connection: def __enter__(self): return self def __exit__(self, exc_type, *_): database.rollback() if exc_type else database.commit() def execute(self, statement, parameters=()): statement = statement if isinstance(statement, str) else statement.as_string() if statement.startswith(("SET TRANSACTION", "SELECT pg_advisory")): return None parameters = tuple( str(p.obj) if hasattr(p, "obj") else p.isoformat() if isinstance(p, datetime) else p for p in parameters ) return database.execute(statement.replace(" FOR UPDATE", "").replace("%s", "?"), parameters) class Repository(PostgresHistoricalRepository): def connect(self): return Connection() def read(self, machine_id, start, end): return [replace(r, timestamp=datetime.fromisoformat(r.timestamp), identity=(*r.identity[:2], datetime.fromisoformat(r.identity[2]))) for r in super().read(machine_id, start, end)] return database, Repository(None) def insert_application(database, calculation, hour, order, run_id, value): database.execute("INSERT INTO material_application_snapshots VALUES (?, ?, ?, ?, ?, ?)", (at(hour).isoformat(), calculation, "generic", order, run_id, value)) database.commit() def application_rows(database, calculation): return database.execute( "SELECT count(*) FROM material_application_snapshots WHERE calculation_id = ?", (calculation,), ).fetchone()[0] def application_reconcile_args(repository): source = SimpleNamespace(get_production_runs=lambda machine: [run()]) erp = SimpleNamespace(get_confirmations=lambda **kwargs: [confirmation()]) config = SimpleNamespace(machine_id="generic", erp_workplace="workplace") return repository, source, erp, config, "Machine-{production_order}", at(10), at(14)