diff --git a/docs/site/model-validation.md b/docs/site/model-validation.md index 14b26c6..807cbfa 100644 --- a/docs/site/model-validation.md +++ b/docs/site/model-validation.md @@ -106,8 +106,8 @@ change read-only/reserved bits; a writable bit sharing a register with read-only bits can be changed while preserving those bits. Reads that would expose a write-only field are rejected, while FC5/6 write echoes remain supported. Model read-only measurements may be changed internally but cannot be written by clients. -`hold` stops a generator for a property after a valid client write until restart; -`overwrite` permits the next tick to replace it. Scripts define their own write +`hold` stops a generator or binding for a property after a valid client write until +restart; `overwrite` permits the next tick to replace it. Scripts define their own write response and may deliberately overwrite values. ## Local Python behaviors diff --git a/modsim/manifest.py b/modsim/manifest.py index 63c1eea..6598e10 100644 --- a/modsim/manifest.py +++ b/modsim/manifest.py @@ -250,6 +250,9 @@ def load_deployment(path: Path, *, include_data: bool = True) -> Deployment: ).data if include_data and item.get("script"): script_path = local_path(root, item["script"]) + # Scripts execute with the simulator's rights; keep them with the deployment. + if not Path(script_path).is_relative_to(root.resolve()): + raise ValueError(f"{key}: script must stay inside {root}") with Path(script_path).open("rb") as stream: script_source = stream.read(MAX_BYTES + 1) if len(script_source) > MAX_BYTES: diff --git a/modsim/runtime.py b/modsim/runtime.py index 4d6472c..dda5730 100644 --- a/modsim/runtime.py +++ b/modsim/runtime.py @@ -1,7 +1,6 @@ """Independent device state, local behavior hooks and atomic protocol access.""" import asyncio -import copy import importlib.util import inspect import logging @@ -48,6 +47,9 @@ def __init__(self, model: Any, cells: Any, schemas: Any, access: Any) -> None: self.bindings: dict[str, str] = {} self.write_policy = "hold" self.held: set[str] = set() + # Previous raw values of cells changed by the write in progress, so a + # rejected write restores only what it touched. + self.journal: dict[tuple[str, int], Any] | None = None def get(self, name: str) -> Any: """Read the current property value, including previous client writes.""" @@ -91,6 +93,9 @@ def set_many(self, values: dict[str, Any], *, initializing: bool = False) -> Non old = { (table, address): self.cells[table][address] for table, address in updates } + if self.journal is not None: + for key, raw in old.items(): + self.journal.setdefault(key, raw) try: for (table, address), (raw, mask) in updates.items(): value = (int(self.cells[table][address]) & ~mask) | (raw & mask) @@ -164,8 +169,17 @@ def advance(self, elapsed: float, dt: float) -> None: values[name] = value self.set_many(values) self.hook("tick", elapsed, dt) + self.apply_bindings() + + def apply_bindings(self) -> None: + """Copy sources to targets; under hold a client-written target stays put.""" + hold = self.write_policy == "hold" self.set_many( - {target: self.get(source) for target, source in self.bindings.items()} + { + target: self.get(source) + for target, source in self.bindings.items() + if not (hold and target in self.held) + } ) async def run(self) -> None: @@ -219,7 +233,8 @@ async def async_setValues( if error := device.access(func_code, address, len(values), True): return error table = FUNCTIONS[func_code] - old = copy.deepcopy(device.cells) + journal: dict[tuple[str, int], Any] = {} + device.journal = journal held = device.held.copy() try: full_mask = 1 if table in ("coil", "discrete_input") else 65535 @@ -229,6 +244,9 @@ async def async_setValues( current = int(device.cells[table][current_address]) if (current ^ int(value)) & (full_mask ^ allowed): raise ValueError("write changes read-only or unconfigured bits") + journal.setdefault( + (table, current_address), device.cells[table][current_address] + ) device.cells[table][current_address] = value touched = {(table, item) for item in range(address, address + len(values))} changes = device.validate_cells(touched) @@ -237,15 +255,13 @@ async def async_setValues( name for name in changes if device.codecs[name].member.writable ) device.hook("on_write", changes) - device.set_many( - { - target: device.get(source) - for target, source in device.bindings.items() - } - ) + device.apply_bindings() except Exception: - device.cells = old + for (name, address), raw in journal.items(): + device.cells[name][address] = raw device.held = held _LOG.exception("Write rejected by device %s", device.name) return ExcCodes.ILLEGAL_VALUE + finally: + device.journal = None return None diff --git a/tests/test_codec.py b/tests/test_codec.py index 32c5a18..8e2a001 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -6,6 +6,8 @@ import pytest +from pymodbus.constants import ExcCodes + from modsim.runtime import RuntimeContext from modsim.utils import get_parser from modsim.wot import configure @@ -239,7 +241,7 @@ def test_readonly_bits_and_writeonly_property(tmp_path): instance = configure_properties(tmp_path, {"a": a, "b": b}) context = RuntimeContext([instance]) assert asyncio.run(context.async_setValues(1, 6, 0, [2])) is None - assert asyncio.run(context.async_setValues(1, 6, 0, [3])) is not None + assert asyncio.run(context.async_setValues(1, 6, 0, [3])) == ExcCodes.ILLEGAL_VALUE assert instance.get("a") is False assert instance.get("b") is True instance = configure_properties(tmp_path, {"value": prop(writeOnly=True)}) @@ -269,12 +271,15 @@ def test_partial_float_write_validates_full_span_and_rolls_back(tmp_path): tmp_path, {"value": prop("float", 2, "number", maximum=1.5)}, {"value": 1.5} ) context = RuntimeContext([instance]) - assert asyncio.run(context.async_setValues(1, 6, 1, [1])) is not None + assert asyncio.run(context.async_setValues(1, 6, 1, [1])) == ExcCodes.ILLEGAL_VALUE assert instance.get("value") == 1.5 assert asyncio.run(context.async_setValues(1, 6, 0, [0x3F80])) is None assert instance.get("value") == 1.0 assert instance.held == {"value"} - assert asyncio.run(context.async_setValues(1, 6, 0, [0x7F80])) is not None + assert ( + asyncio.run(context.async_setValues(1, 6, 0, [0x7F80])) + == ExcCodes.ILLEGAL_VALUE + ) assert instance.get("value") == 1.0 @@ -295,7 +300,9 @@ def test_legacy_bool16_full_span_write_preserves_padding(tmp_path): context = RuntimeContext([instance]) assert asyncio.run(context.async_setValues(1, 16, 0, [0x8101, 0])) is None assert instance.get("value") == [True] + [False] * 6 + [True, True] + [False] * 7 - assert asyncio.run(context.async_setValues(1, 16, 0, [0, 1])) is not None + assert ( + asyncio.run(context.async_setValues(1, 16, 0, [0, 1])) == ExcCodes.ILLEGAL_VALUE + ) assert instance.cells["holding_register"] == {0: 0x8101, 1: 0} @@ -463,3 +470,94 @@ def test_float_initial_multipleof_intersects_declared_bounds(tmp_path, raw, quan }, ) assert instance.get("value") == 105 + + +def test_bound_target_keeps_a_client_write_under_hold_and_follows_under_overwrite( + tmp_path, +): + source = prop("unsignedShort", 1, address=0) + target = prop("unsignedShort", 1, address=1) + for policy, expected in (("hold", 999), ("overwrite", 10)): + instance = configure_properties( + tmp_path, {"src": source, "tgt": target}, {"src": 10} + ) + instance.bindings = {"tgt": "src"} + instance.write_policy = policy + instance.apply_bindings() + context = RuntimeContext([instance]) + assert asyncio.run(context.async_setValues(1, 6, 1, [999])) is None + instance.advance(0, 1) + assert instance.get("src") == 10 + assert instance.get("tgt") == expected, policy + + +def test_rejected_write_restores_only_touched_cells_in_place(tmp_path): + flag = prop("unsignedShort", 1, address=0) + other = prop("unsignedShort", 1, address=1) + instance = configure_properties(tmp_path, {"a": flag, "b": other}, {"a": 1, "b": 2}) + cells = instance.cells + context = RuntimeContext([instance]) + + def fail(name, *args): + if name == "on_write": + instance.set("b", 77) + raise ValueError("script refused") + + instance.hook = fail + assert asyncio.run(context.async_setValues(1, 6, 0, [5])) == ExcCodes.ILLEGAL_VALUE + assert instance.get("a") == 1 and instance.get("b") == 2 + assert instance.cells is cells + assert instance.journal is None + + +def bit_prop(): + value = prop("unsignedShort", 1, "boolean") + value["forms"][0]["modpoll:bit"] = 0 + return value + + +@pytest.mark.parametrize( + "properties, name, value, match", + [ + ({"v": prop("unsignedShort", 1)}, "v", "text", "violates|expected"), + ({"v": prop("unsignedShort", 1)}, "v", True, "violates|expected"), + ({"v": prop("unsignedShort", 1)}, "v", 70000, "violates|cannot be encoded"), + ({"v": prop("float", 2, "number")}, "v", float("nan"), "violates|non-finite"), + ({"v": bit_prop()}, "v", 1, "violates"), + ({"v": bit_prop()}, "v", "yes", "violates"), + ], +) +def test_encoder_rejects_wrong_types_without_touching_the_register( + tmp_path, properties, name, value, match +): + instance = configure_properties(tmp_path, properties) + before = instance.get(name) + with pytest.raises(ValueError, match=match): + instance.set(name, value) + assert instance.get(name) == before + + +def test_script_hooks_must_be_synchronous(tmp_path): + from types import SimpleNamespace + + instance = configure_properties(tmp_path, {"v": prop("unsignedShort", 1)}) + + async def coroutine_hook(device, *args): + return None + + instance.script = SimpleNamespace(on_write=coroutine_hook) + with pytest.raises(ValueError, match="synchronous"): + instance.hook("on_write", {}) + instance.script = SimpleNamespace(on_write=lambda device, *args: asyncio.sleep(0)) + with pytest.raises(ValueError, match="synchronous"): + instance.hook("on_write", {}) + instance.script = SimpleNamespace(on_write=lambda device, *args: object()) + assert instance.hook("on_write", {}) is None + + +def test_async_hook_is_rejected_when_the_script_loads(tmp_path): + instance = configure_properties(tmp_path, {"v": prop("unsignedShort", 1)}) + script = tmp_path / "behavior.py" + script.write_text("async def tick(device, elapsed, dt):\n pass\n") + with pytest.raises(ValueError, match="must be a synchronous function"): + instance.load_script(str(script)) diff --git a/tests/test_deployment.py b/tests/test_deployment.py index 43b5ad3..d2b1d4b 100644 --- a/tests/test_deployment.py +++ b/tests/test_deployment.py @@ -318,6 +318,8 @@ def test_explicit_thing_id_for_model_without_id(tmp_path): def test_root_adam_deployment(): + if not (ROOT / "examples/models").is_dir(): + pytest.skip("run tools/fetch-models.py to populate examples/models") deployment = load_deployment(ROOT / "examples/deployment.yaml") assert deployment.bind == "0.0.0.0" assert [item.model.unit_id for item in deployment.instances.values()] == [1, 2] @@ -337,3 +339,41 @@ def test_removed_deployment_cli_option(tmp_path): ) assert result.returncode != 0 assert b"unrecognized arguments: --deployment" in result.stderr + + +def test_script_path_cannot_leave_the_deployment_directory(tmp_path): + project = tmp_path / "project" + project.mkdir() + (tmp_path / "evil.py").write_text('raise AssertionError("must not execute")') + (project / "link.py").symlink_to(tmp_path / "evil.py") + for script in ("../evil.py", str(tmp_path / "evil.py"), "link.py"): + with pytest.raises(ValueError, match="script must stay inside"): + build(project, [device(script=script)]) + + +def test_noise_sequences_follow_the_seed_and_differ_between_seeds(tmp_path): + for name, seed in (("a", 73), ("b", 74)): + (tmp_path / f"{name}.json").write_text( + json.dumps( + { + "version": "1", + "seed": seed, + "generators": { + "AO0_RAW": {"kind": "noise", "minimum": 1, "maximum": 100} + }, + } + ) + ) + args = build( + tmp_path, + [device(1, data="a.json"), device(2, data="a.json"), device(3, data="b.json")], + ) + sequences = [] + for runtime in args.runtimes: + values = [] + for tick in range(1, 9): + runtime.advance(tick, 1) + values.append(runtime.get("AO0_RAW")) + sequences.append(values) + assert sequences[0] == sequences[1] + assert sequences[0] != sequences[2] diff --git a/tests/test_modsim.py b/tests/test_modsim.py index ebe2197..09d7249 100644 --- a/tests/test_modsim.py +++ b/tests/test_modsim.py @@ -478,3 +478,25 @@ def test_tls_without_certificates_explains_what_is_missing(tmp_path): ) assert result.returncode == 2 assert "certificates/pymodbus.crt" in result.stderr + result.stdout + + +def test_serial_transport_passes_port_framer_and_datastore(monkeypatch): + import asyncio + + from modsim import main + from modsim.utils import get_parser + + calls = {} + + async def fake_serial_server(**kwargs): + calls.update(kwargs) + + monkeypatch.setattr(main, "StartAsyncSerialServer", fake_serial_server) + args = get_parser().parse_args( + ["--comm", "serial", "--port", "/dev/modsim-test", "--framer", "rtu"] + ) + main.setup_server(args) + assert asyncio.run(main.run_async_server(args)) is None + assert calls["port"] == "/dev/modsim-test" + assert calls["framer"] == args.framer + assert calls["context"] is args.context