From a71f8739d8ba3a5da3680700cf84eda223133b1a Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 14:40:19 +0800 Subject: [PATCH 1/4] fix: hold only writable properties after a client write (SIM-06) A write re-decodes every property sharing the written cells. Recording all of them in held froze the generators of read-only aliases the client never wrote. Co-Authored-By: Claude Sonnet 5.5 --- modsim/runtime.py | 5 ++++- tests/test_codec.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/modsim/runtime.py b/modsim/runtime.py index 55853a3..4d6472c 100644 --- a/modsim/runtime.py +++ b/modsim/runtime.py @@ -232,7 +232,10 @@ async def async_setValues( device.cells[table][current_address] = value touched = {(table, item) for item in range(address, address + len(values))} changes = device.validate_cells(touched) - device.held.update(changes) + # Read-only aliases are re-decoded but not written, so their generators keep running. + device.held.update( + name for name in changes if device.codecs[name].member.writable + ) device.hook("on_write", changes) device.set_many( { diff --git a/tests/test_codec.py b/tests/test_codec.py index 4d1484a..32c5a18 100644 --- a/tests/test_codec.py +++ b/tests/test_codec.py @@ -249,6 +249,21 @@ def test_readonly_bits_and_writeonly_property(tmp_path): assert instance.get("value") == 0x12345678 +def test_client_write_holds_only_writable_properties(tmp_path): + a = prop("unsignedShort", 1, "boolean", readOnly=True) + a["forms"][0]["modpoll:bit"] = 0 + b = prop("unsignedShort", 1, "boolean") + b["forms"][0]["modpoll:bit"] = 1 + instance = configure_properties(tmp_path, {"a": a, "b": b}) + instance.generators = {"a": {"kind": "constant", "value": True}} + context = RuntimeContext([instance]) + assert asyncio.run(context.async_setValues(1, 6, 0, [2])) is None + assert instance.held == {"b"} + instance.advance(0, 1) + assert instance.get("a") is True + assert instance.get("b") is True + + def test_partial_float_write_validates_full_span_and_rolls_back(tmp_path): instance = configure_properties( tmp_path, {"value": prop("float", 2, "number", maximum=1.5)}, {"value": 1.5} From 7e7452c5d756b088a91c7bf4c9c6bf4a01f526c5 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 14:51:08 +0800 Subject: [PATCH 2/4] fix: read management requests before locking and build devices off the event loop (SIM-06) An idle control connection held the manager lock for up to 5 seconds while it waited for a request line, delaying every other command including down. Build validates schemas and executes behavior scripts, which stalled Modbus service for all devices while it ran on the event loop. Co-Authored-By: Claude Sonnet 5.5 --- modsim/management.py | 17 ++++++++----- tests/test_management.py | 55 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/modsim/management.py b/modsim/management.py index 39cedcf..43f84a4 100644 --- a/modsim/management.py +++ b/modsim/management.py @@ -84,8 +84,12 @@ def plan(self, desired: Deployment) -> dict: async def apply(self, desired: Deployment, dry_run: bool = False) -> dict: plan = self.plan(desired) # Only changed candidates initialize; repeated up cannot rerun live hooks. + # Building validates schemas and executes behavior scripts; keep it off the + # event loop so Modbus clients of the running devices are still served. candidates = { - key: desired.instances[key].build(self.allow_scripts, preview=dry_run) + key: await asyncio.to_thread( + desired.instances[key].build, self.allow_scripts, preview=dry_run + ) for key in plan["added"] + plan["replaced"] } if dry_run: @@ -227,12 +231,13 @@ async def handle( if task is not None: handlers.add(task) try: + # Read before locking so an idle connection cannot stall other commands. + payload = await asyncio.wait_for(reader.readline(), 5) + message = json.loads(payload) + if message.get("source") != str(desired.path): + raise ValueError("deployment name belongs to a different file") + action = message.get("action") async with manager.lock: - payload = await asyncio.wait_for(reader.readline(), 5) - message = json.loads(payload) - if message.get("source") != str(desired.path): - raise ValueError("deployment name belongs to a different file") - action = message.get("action") if action == "up": if message.get("allow_scripts") and not manager.allow_scripts: raise ValueError( diff --git a/tests/test_management.py b/tests/test_management.py index 9634d7a..85a6895 100644 --- a/tests/test_management.py +++ b/tests/test_management.py @@ -422,3 +422,58 @@ def test_attached_up_and_follow_logs_detach_without_stopping(tmp_path): assert json.loads(cli(path, "ps").stdout)["running"] is True finally: cli(path, "down") + + +def test_apply_builds_devices_off_the_event_loop(tmp_path, monkeypatch): + import threading + + path, _, _ = fixture(tmp_path) + desired = load_deployment(path) + instance_type = type(desired.instances["io-1"]) + original = instance_type.build + threads = [] + + def build(self, *args, **kwargs): + threads.append(threading.current_thread()) + return original(self, *args, **kwargs) + + monkeypatch.setattr(instance_type, "build", build) + + async def exercise(): + manager = RuntimeManager() + try: + await manager.apply(desired) + finally: + await manager.close() + + asyncio.run(exercise()) + assert threads and all(t is not threading.main_thread() for t in threads) + + +def test_idle_management_connection_does_not_block_other_commands(tmp_path): + import time + + from modsim.management import paths + + path, spec, _ = fixture(tmp_path) + process = subprocess.Popen( + [sys.executable, "-m", "modsim", "up"], + cwd=tmp_path, + env={**os.environ, "PYTHONPATH": str(ROOT)}, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + deadline = time.monotonic() + 10 + while not json.loads(cli(path, "ps").stdout)["running"]: + assert time.monotonic() < deadline and process.poll() is None + time.sleep(0.05) + with socket.socket(socket.AF_UNIX) as idle: + idle.connect(str(paths(spec["name"])[0])) + started = time.monotonic() + assert json.loads(cli(path, "ps").stdout)["running"] + # The server drops an idle client after 5 seconds. + assert time.monotonic() - started < 3 + finally: + process.terminate() + process.wait(timeout=10) From d2534af0fef9054e86efd183ce77a02a1d69b233 Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 14:51:08 +0800 Subject: [PATCH 3/4] fix: name the missing TLS files and enable asyncio debug only with --log debug (SIM-06) Co-Authored-By: Claude Sonnet 5.5 --- modsim/main.py | 16 +++++++++++----- tests/test_modsim.py | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/modsim/main.py b/modsim/main.py index 37718de..e228e70 100644 --- a/modsim/main.py +++ b/modsim/main.py @@ -201,10 +201,16 @@ async def run_async_server(args: Any) -> Any: require_bindable(address[0], args.port) # Create SSL context from cert and key files sslctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) - sslctx.load_cert_chain( - certfile="certificates/pymodbus.crt", - keyfile="certificates/pymodbus.key", - ) + try: + sslctx.load_cert_chain( + certfile="certificates/pymodbus.crt", + keyfile="certificates/pymodbus.key", + ) + except OSError as exc: + raise OSError( + "TLS needs certificates/pymodbus.crt and certificates/pymodbus.key " + f"in the working directory: {exc}" + ) from exc server = ModbusTlsServer( context=args.context, @@ -244,7 +250,7 @@ def app() -> None: _logger.error("Invalid model configuration: %s", exc) raise SystemExit(2) from exc try: - asyncio.run(_run_server_with_signals(run_args), debug=True) + asyncio.run(_run_server_with_signals(run_args), debug=args.log == "debug") except OSError as exc: _logger.error("%s", exc) raise SystemExit(2) from exc diff --git a/tests/test_modsim.py b/tests/test_modsim.py index 7635fde..ebe2197 100644 --- a/tests/test_modsim.py +++ b/tests/test_modsim.py @@ -461,3 +461,20 @@ def test_default_port_without_rights_fails_with_hint(): ) assert result.returncode == 2 assert "Port 502 needs administrator rights" in result.stderr + + +def test_tls_without_certificates_explains_what_is_missing(tmp_path): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + source = os.path.dirname(os.path.dirname(modsim.__file__)) + result = subprocess.run( + [sys.executable, "-m", "modsim", "--comm", "tls", "--port", str(port)], + cwd=tmp_path, + env={**os.environ, "PYTHONPATH": source}, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 2 + assert "certificates/pymodbus.crt" in result.stderr + result.stdout From 1fe1ad63a7583611ddef9cc5ac3c1d0aa2ca173e Mon Sep 17 00:00:00 2001 From: Gavin Ying Date: Thu, 12 Nov 2026 14:51:08 +0800 Subject: [PATCH 4/4] docs: use the mounted deployment path in the Compose update command (SIM-06) The control socket only accepts the path the deployment started with, so the README command with /app/examples/deployment.yaml was rejected. The Compose example also no longer passes --allow-scripts: its deployment uses no scripts. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +++-- examples/docker-compose.yaml | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b6a9f7d..042daba 100644 --- a/README.md +++ b/README.md @@ -90,10 +90,11 @@ again just to start it. After editing the mounted deployment file, apply the updated configuration to the running simulator with: ```bash -docker compose exec modsim python -m modsim up -f /app/examples/deployment.yaml -d +docker compose exec modsim python -m modsim up -f /app/deployment.yaml -d ``` -An unchanged device keeps its state; a changed device is replaced. Listener +Use the mounted path Compose started (`/app/deployment.yaml`); the control +socket rejects any other path. An unchanged device keeps its state; a changed device is replaced. Listener changes require a container restart. If you replace the deployment file itself, run `docker compose up -d --force-recreate` to refresh its bind mount. Export all running TDs directly into the host's `examples/td/` directory. The Compose diff --git a/examples/docker-compose.yaml b/examples/docker-compose.yaml index dd021b1..350722a 100644 --- a/examples/docker-compose.yaml +++ b/examples/docker-compose.yaml @@ -3,7 +3,7 @@ services: modsim: build: .. restart: unless-stopped - command: ["python", "-m", "modsim", "up", "-f", "/app/deployment.yaml", "--allow-scripts"] + command: ["python", "-m", "modsim", "up", "-f", "/app/deployment.yaml"] ports: - "127.0.0.1:5020:5020" volumes: