from datetime import UTC, datetime, timedelta from pathlib import Path from unittest.mock import Mock import pytest from production_analytics.calculations.channel_config import load_channel_material_calculation from production_analytics.calculations.channel_material import ( MATERIAL_AMBIGUOUS, MATERIAL_UNAVAILABLE, DosingChannelSample, channel_rates, validate_active_percentage_sum, ) from production_analytics.enlyze.gateway import EnlyzeApiGateway, EnlyzeProductionRun from production_analytics.service.channel_material import ( ChannelDefinition, ChannelMaterialPollingService, ) from production_analytics.service.channel_material_state_store import JsonChannelMaterialStateStore NOW = datetime(2026, 9, 1, tzinfo=UTC) E1_CONFIG = ( Path(__file__).resolve().parents[1] / "config/e1-channel-material-consumption.example.yaml" ) def sample(*, on=True, percent=100, material=None, timestamp=NOW): return DosingChannelSample(timestamp, 120, on, percent, 10, material) def test_off_channel_with_nonzero_displayed_percentage_contributes_zero(): assert channel_rates((sample(on=False, percent=40),))[0].sample.material_rate_kg_per_hour == 0 def test_e1_config_dry_run_resolves_every_signal_through_gateway_without_sampling(): config = load_channel_material_calculation(E1_CONFIG) origins = { reference for channel in config.channels for reference in ( channel.total_rate_signal_ref, channel.status_signal_ref, channel.percentage_signal_ref, channel.screw_speed_signal_ref, ) } client = Mock() client.get.return_value.body = { "data": [ { "uuid": f"variable-{index}", "details": {"origin_identifier": {"code": origin}}, } for index, origin in enumerate(sorted(origins)) ] + [ {"uuid": channel.material_name_signal_ref[5:], "details": {"origin_identifier": None}} for channel in config.channels ] } resolved = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs( machine_id=config.machine_ref, channels=config.channels, ) assert config.machine_ref == "8302e3d1-b1e5-42f1-8540-615eb6c73e08" assert len(config.channels) == 14 assert len(origins) == 44 assert len(resolved) == 14 for channel in config.channels: refs = resolved[channel.channel + "\0" + channel.extruder] assert len(refs) == 6 and refs[-2] is None assert refs[-1] == channel.material_name_signal_ref[5:] assert config.channels[1].material_name_signal_ref == ( "uuid:b8be6b5a-0ce7-40ed-9754-107175468c8d" ) client.get.assert_called_once_with("/v2/variables", {"machine": config.machine_ref}) client.post_json.assert_not_called() def test_active_percentages_sum_to_100_and_deviation_is_reported_not_normalized(): active = (sample(percent=40), sample(percent=60)) assert validate_active_percentage_sum(active, tolerance=0.1) assert not validate_active_percentage_sum( (sample(percent=40), sample(percent=50)), tolerance=0.1 ) assert [x.sample.material_rate_kg_per_hour for x in channel_rates(active)] == [48, 72] def test_null_and_duplicate_material_assignments_are_not_inferred(): assert ( channel_rates((sample(material=None),))[0].material_mapping_status == MATERIAL_UNAVAILABLE ) rates = channel_rates((sample(material="123"), sample(material="123"))) assert all(rate.material_mapping_status == MATERIAL_AMBIGUOUS for rate in rates) assert all(rate.material_number is None and rate.material_name is None for rate in rates) def test_run_change_and_json_restart_preserve_channel_total(tmp_path): channels = (ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm"),) store, gateway = JsonChannelMaterialStateStore(tmp_path), Mock() gateway.get_production_runs.return_value = [] gateway.get_open_production_run.return_value = EnlyzeProductionRun( "r1", "m", None, "order", NOW, None ) key = "C1\0Ex1" gateway.get_dosing_channel_samples.return_value = { key: [sample(timestamp=NOW), sample(timestamp=NOW + timedelta(seconds=10))] } first = ChannelMaterialPollingService( gateway=gateway, state_store=store, machine_id="m", channels=channels, max_sample_gap_seconds=20, ) assert first.poll_once(now=NOW + timedelta(seconds=10))[ 0 ].state.cumulative_consumption_kg == pytest.approx(10 / 30) gateway.get_open_production_run.return_value = EnlyzeProductionRun( "r2", "m", None, "order", NOW + timedelta(seconds=20), None ) gateway.get_dosing_channel_samples.return_value = { key: [ sample(timestamp=NOW + timedelta(seconds=20)), sample(timestamp=NOW + timedelta(seconds=30)), ] } restarted = ChannelMaterialPollingService( gateway=gateway, state_store=store, machine_id="m", channels=channels, max_sample_gap_seconds=20, ) assert restarted.poll_once(now=NOW + timedelta(seconds=30))[ 0 ].state.cumulative_consumption_kg == pytest.approx(20 / 30) def test_bootstrap_replays_closed_runs_without_integrating_the_inter_run_gap(tmp_path): channels = (ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm"),) closed = EnlyzeProductionRun("r1", "m", None, "order", NOW, NOW + timedelta(seconds=10)) current = EnlyzeProductionRun("r2", "m", None, "order", NOW + timedelta(seconds=20), None) gateway = Mock() gateway.get_open_production_run.return_value = current gateway.get_production_runs.return_value = [closed, current] key = "C1\0Ex1" gateway.get_dosing_channel_samples.side_effect = [ {key: [sample(timestamp=NOW), sample(timestamp=NOW + timedelta(seconds=10))]}, { key: [ sample(timestamp=NOW + timedelta(seconds=20)), sample(timestamp=NOW + timedelta(seconds=30)), ] }, ] result = ChannelMaterialPollingService( gateway=gateway, state_store=JsonChannelMaterialStateStore(tmp_path), machine_id="m", channels=channels, max_sample_gap_seconds=20, ).poll_once(now=NOW + timedelta(seconds=30)) assert result is not None assert result[0].state.cumulative_consumption_kg == pytest.approx(20 / 30) @pytest.mark.parametrize("name", ["TR 131", None, "", " "]) def test_direct_name_samples_and_assignment(name): columns = ["rate", "on", "pct", "rpm", "name"] value = EnlyzeApiGateway._dosing_sample( [120, True, 100, 10, name], columns, NOW, "rate", "on", "pct", "rpm", None, "name" ) assert value is not None expected = name if name and name.strip() else None assert value.material_name == expected assert value.material_number is None rate = channel_rates((value,), material_names={"123": "Other"})[0] assert rate.material_name == expected assert rate.material_number is None assert rate.material_mapping_status == ("ASSIGNED" if expected else "UNAVAILABLE") def test_duplicate_direct_names_remain_assigned(): value = DosingChannelSample(NOW, 120, True, 50, 10, material_name="TR 131") assert all(rate.material_mapping_status == "ASSIGNED" for rate in channel_rates((value, value))) @pytest.mark.parametrize("value", [123, True, [], {}]) def test_direct_name_rejects_non_string(value): with pytest.raises(ValueError, match="material name must be a string or null"): EnlyzeApiGateway._dosing_sample( [120, True, 100, 10, value], ["rate", "on", "pct", "rpm", "name"], NOW, "rate", "on", "pct", "rpm", None, "name", ) def test_numeric_material_mapping_is_unchanged(): value = EnlyzeApiGateway._dosing_sample( [120, True, 100, 10, 123], ["rate", "on", "pct", "rpm", "number"], NOW, "rate", "on", "pct", "rpm", "number", ) assert value.material_number == "123" mapped = channel_rates((value,), material_names={"123": "Mapped"})[0] assert (mapped.material_number, mapped.material_name, mapped.material_mapping_status) == ( "123", "Mapped", "ASSIGNED", ) assert channel_rates((value,), material_names={"456": "Other"})[0].material_mapping_status == ( "UNMAPPED" ) @pytest.mark.parametrize("ref", ["exa_c1_material", "uuid:bad", "", 123]) def test_config_rejects_invalid_direct_name_ref(tmp_path, ref): import yaml from production_analytics.calculations.config import CalculationConfigError document = yaml.safe_load(E1_CONFIG.read_text()) document["calculations"][0]["extruders"][0]["channels"][0]["material_name_signal_ref"] = ref path = tmp_path / "config.yaml" path.write_text(yaml.safe_dump(document)) with pytest.raises(CalculationConfigError, match="material_name_signal_ref"): load_channel_material_calculation(path) def test_config_preserves_number_mode_and_rejects_both_modes(tmp_path): import yaml from production_analytics.calculations.config import CalculationConfigError document = yaml.safe_load(E1_CONFIG.read_text()) row = document["calculations"][0]["extruders"][0]["channels"][0] row["material_number_signal_ref"] = "DB107:100" path = tmp_path / "config.yaml" path.write_text(yaml.safe_dump(document)) with pytest.raises(CalculationConfigError, match="mutually exclusive"): load_channel_material_calculation(path) del row["material_name_signal_ref"] path.write_text(yaml.safe_dump(document)) channel = load_channel_material_calculation(path).channels[0] assert channel.material_number_signal_ref == "DB107:100" assert channel.material_name_signal_ref is None def dosing_client(*, include_name=True): name_id = "b8be6b5a-0ce7-40ed-9754-107175468c8d" client = Mock() client.get.return_value.body = { "data": [ {"uuid": ref, "details": {"origin_identifier": {"code": ref}}} for ref in ("rate", "on", "pct", "rpm", "number") ] + ([{"uuid": name_id, "details": {"origin_identifier": None}}] if include_name else []) } return client, name_id @pytest.mark.parametrize("problem", ["missing_name", "missing_origin", "duplicate_origin"]) def test_resolver_preserves_availability_and_origin_uniqueness(problem): client, name_id = dosing_client(include_name=problem != "missing_name") items = client.get.return_value.body["data"] if problem == "missing_origin": items.pop(0) elif problem == "duplicate_origin": items.append({"uuid": "duplicate", "details": {"origin_identifier": {"code": "rate"}}}) channel = ChannelDefinition( "Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}" ) with pytest.raises(ValueError, match="unavailable|ambiguous"): EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs( machine_id="m", channels=(channel,) ) def test_number_signal_still_resolves_by_origin(): client, _ = dosing_client() channel = ChannelDefinition("Ex1", "C1", "rate", "on", "pct", "rpm", "number") refs = EnlyzeApiGateway(client).resolve_dosing_channel_signal_refs( machine_id="m", channels=(channel,) ) assert refs["C1\0Ex1"] == ("rate", "on", "pct", "rpm", "number", None) def test_direct_name_changes_and_null_reach_postgres_without_carry_forward(tmp_path): import io from unittest.mock import patch from production_analytics.service.channel_material_runner import ChannelMaterialPollingRunner from production_analytics.service.postgres_channel_material import ( PostgresChannelMaterialSnapshotWriter, ) from production_analytics.service.postgres_material import PostgresSettings client, name_id = dosing_client() gateway = EnlyzeApiGateway(client) gateway.get_open_production_run = Mock( return_value=EnlyzeProductionRun("run", "m", None, "order", NOW, None) ) gateway.get_production_runs = Mock(return_value=[]) channel = ChannelDefinition( "Ex1", "C2", "rate", "on", "pct", "rpm", material_name_signal_ref=f"uuid:{name_id}" ) service = ChannelMaterialPollingService( gateway=gateway, state_store=JsonChannelMaterialStateStore(tmp_path), machine_id="m", channels=(channel,), max_sample_gap_seconds=20, ) writer = PostgresChannelMaterialSnapshotWriter( PostgresSettings("localhost", 5432, "db", "user", "pw") ) runner = ChannelMaterialPollingRunner( service, machine_id="m", calculation_id="calc", snapshot_writer=writer, poll_interval_seconds=10, stdout=io.StringIO(), clock=lambda: NOW, ) with patch("psycopg.connect") as connect: connection = connect.return_value.__enter__.return_value for index, name in enumerate(("TR 131", "New material", None)): timestamp = NOW + timedelta(seconds=index * 10) client.post_json.return_value.body = { "data": { "columns": ["time", "rate", "on", "pct", "rpm", name_id], "records": [[timestamp.isoformat(), 120, True, 100, 10, name]], } } runner.clock = lambda: timestamp assert runner.run_once() parameters = connection.execute.call_args.args[1] assert parameters[8:11] == (None, name, "ASSIGNED" if name else "UNAVAILABLE") assert parameters[7] == pytest.approx(index / 3) request = client.post_json.call_args.args assert request[0] == "/v2/timeseries" assert request[1]["variables"] == [ {"uuid": ref} for ref in ("rate", "on", "pct", "rpm", name_id) ]