Skip to content

Your lightweight open-source personal agent.

fix(gateway): reuse Windows-safe atomic lease I/O

chengyongru1c28b20c7e11
diff --git a/nanobot/gateway/runtime.py b/nanobot/gateway/runtime.py
index 0538dd54f..1e6dd9e32 100644
--- a/nanobot/gateway/runtime.py
+++ b/nanobot/gateway/runtime.py
@@ -35,6 +35,7 @@ from nanobot.process_runtime import (
process_identity_record,
process_is_running,
)
+from nanobot.utils.atomic_file import read_atomic_bytes, replace_atomic
@dataclass(frozen=True)
@@ -772,7 +773,7 @@ class GatewayClientLease:
def _read_state(self) -> dict[str, object]:
try:
- payload: object = json.loads(self.state_path.read_text(encoding="utf-8"))
+ payload: object = json.loads(read_atomic_bytes(self.state_path).decode("utf-8"))
except (OSError, json.JSONDecodeError, ValueError):
return {"auto_stop": False, "clients": {}}
if isinstance(payload, dict):
@@ -800,7 +801,7 @@ class GatewayClientLease:
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
- temporary.replace(self.state_path)
+ replace_atomic(temporary, self.state_path)
finally:
temporary.unlink(missing_ok=True)
diff --git a/tests/gateway/test_runtime.py b/tests/gateway/test_runtime.py
index 09ae44e3a..4a1108c92 100644
--- a/tests/gateway/test_runtime.py
+++ b/tests/gateway/test_runtime.py
@@ -553,6 +553,32 @@ def test_restart_stops_then_starts_the_background_gateway(tmp_path, monkeypatch)
assert result.ok is True
+def test_client_lease_reader_keeps_snapshot_during_replacement(tmp_path, monkeypatch):
+ """A real lease read retains its contents while a writer publishes the next state."""
+ from contextlib import contextmanager
+
+ from nanobot.utils import atomic_file
+
+ runtime = GatewayRuntime(paths=_paths(tmp_path))
+ client = GatewayClientLease(runtime, kind="tui", token="client")
+ client.acquire()
+ previous = client._read_state()
+ current = {**previous, "auto_stop": True}
+ open_snapshot = atomic_file._open_snapshot
+
+ @contextmanager
+ def publish_while_reading(path):
+ with open_snapshot(path) as snapshot:
+ client._write_state(current)
+ yield snapshot
+
+ with monkeypatch.context() as patch:
+ patch.setattr(atomic_file, "_open_snapshot", publish_while_reading)
+ assert client._read_state() == previous
+ assert client._read_state() == current
+ assert list(runtime.paths.run_dir.glob("*.tmp")) == []
+
+
def test_last_interactive_client_stops_an_on_demand_gateway(tmp_path, monkeypatch):
runtime = GatewayRuntime(paths=_paths(tmp_path), platform_name="Linux")
monkeypatch.setattr(runtime, "_process_identity", lambda pid: pid)