From 2c50ec69df6ac87998ccc885f5e1e0f499a4279e Mon Sep 17 00:00:00 2001 From: Keath Mueller Date: Sat, 24 Oct 2026 15:28:17 -0600 Subject: [PATCH] fix(dashboard): write the status and config files atomically, one writer at a time The dashboard server threads, the provider probe worker, the swarm pipeline thread and council.py all read-modify-write specs/swarm-status.json and specs/swarm-config.json. They shared one ".tmp" scratch file with no lock. What goes wrong (each is reproduced by a test in this change): * two concurrent writers tear the JSON ("Extra data" on the next read) and lose each other's updates; * on Windows os.replace onto a file a reader still has open raises PermissionError, which was swallowed, so the update was dropped silently; * the provider probe worker wrote back the whole config it had read before probing (sockets, and HTTP for rate-limited cloud providers), reverting anything saved in the meantime; * a failed replace left a stray swarm-config.json.tmp behind. * dashboard/statefile.py: atomic_write_json writes a unique temp file in the same directory and replaces the target, retrying briefly while a Windows reader holds it; an existing file keeps its permissions and a symlink is followed rather than replaced. update_json_file does the read-modify-write under a lock that belongs to that one file, so a writer waiting for a reader of the status file never delays writers of the config (no code path holds two of these locks). A UTF-8 byte-order mark is accepted when reading. * serve.py, swarm_pipeline.py and council.py go through it (stream.py, a separate process, uses the atomic replace so readers never see a partial file). The duplicate safe_write_json definition is removed. * The probe worker now merges only the status fields into a fresh read of the file. * POST /api/config writes atomically and reports a failed write instead of claiming success. * Latent, not reproducible on Windows today: GET /api/config probed local providers and wrote back the copy it had just stripped of provider keys. The old code did that from inside "with open(cfg_file)", where the replace is refused on Windows and the error was swallowed, so the keys survived by accident; wherever the replace succeeds every stored key would be deleted. It now refreshes the statuses through the same merge and serves what is on disk. Tests: tests/test_statefile.py (helpers) and tests/test_dashboard_state.py (the real serve.py against a temporary tree; skipped off Windows, where serve.py cannot be imported). Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 +- council.py | 29 ++- dashboard/serve.py | 374 +++++++++++++++++----------------- dashboard/statefile.py | 119 +++++++++++ stream.py | 6 +- swarm_pipeline.py | 19 +- tests/test_dashboard_state.py | 300 +++++++++++++++++++++++++++ tests/test_statefile.py | 186 +++++++++++++++++ 8 files changed, 818 insertions(+), 217 deletions(-) create mode 100644 dashboard/statefile.py create mode 100644 tests/test_dashboard_state.py create mode 100644 tests/test_statefile.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b4b8f6..c780611 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: - name: Verify TenAgent Scripts & Engines run: | - python -m py_compile council.py stream.py swarm_pipeline.py dashboard/serve.py setup_project.py + python -m py_compile council.py stream.py swarm_pipeline.py dashboard/serve.py dashboard/statefile.py setup_project.py - name: Validate Swarm State & Specification Integrity run: | diff --git a/council.py b/council.py index 53d0dc6..30b2ab8 100644 --- a/council.py +++ b/council.py @@ -20,6 +20,9 @@ pass ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) +if ROOT_DIR not in sys.path: + sys.path.insert(0, ROOT_DIR) +from dashboard.statefile import update_json_file # one lock and atomic replace for every writer SPECS_DIR = os.path.join(ROOT_DIR, "specs") CONFIG_FILE = os.path.join(SPECS_DIR, "swarm-config.json") STATUS_FILE = os.path.join(SPECS_DIR, "swarm-status.json") @@ -138,15 +141,10 @@ def log_council_message(tag: str, message: str, root_dir: str = None): pass def update_provider_runtime_status(provider_id: str, status: str, status_detail: str, valid: bool = None, root_dir: str = None): - try: - base = root_dir or ROOT_DIR - cfg_path = os.path.join(base, "specs", "swarm-config.json") - if not os.path.exists(cfg_path): - return - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) - changed = False - p_target = provider_id.lower().strip() + cfg_path = os.path.join(root_dir or ROOT_DIR, "specs", "swarm-config.json") + p_target = provider_id.lower().strip() + + def apply(cfg): for p in cfg.get("providers", []): cur_p = (p.get("provider") or "").lower().strip() if cur_p == p_target or (cur_p in p_target) or (p_target in cur_p): @@ -155,13 +153,12 @@ def update_provider_runtime_status(provider_id: str, status: str, status_detail: p["statusDetail"] = status_detail if valid is not None: p["valid"] = valid - changed = True - break - if changed: - tmp = cfg_path + ".tmp" - with open(tmp, "w", encoding="utf-8") as f: - json.dump(cfg, f, indent=2) - os.replace(tmp, cfg_path) + return True + return False + return False + + try: + update_json_file(cfg_path, apply) except Exception: pass diff --git a/dashboard/serve.py b/dashboard/serve.py index 8c54caa..d6fe2c7 100644 --- a/dashboard/serve.py +++ b/dashboard/serve.py @@ -21,6 +21,8 @@ if DIRECTORY not in sys.path: sys.path.insert(0, DIRECTORY) +from dashboard.statefile import atomic_write_json, update_json_file + import json import datetime import threading @@ -69,34 +71,23 @@ def append_to_terminal_log(agent: str, text: str): with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(f"[{ts}] [{agent}] {clean}\n") -def safe_write_json(filepath: str, data: dict): - try: - tmp_path = filepath + ".tmp" - with open(tmp_path, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) - os.replace(tmp_path, filepath) - except Exception: - pass +def safe_write_json(filepath: str, data: dict) -> bool: + """Atomic replace (see dashboard.statefile); returns False if it did not land.""" + return atomic_write_json(filepath, data) def set_agent_status_direct(agent_id: str, status: str, process_detail: str, progress: int = None): - try: - if os.path.exists(STATUS_FILE): - with open(STATUS_FILE, "r", encoding="utf-8") as f: - data = json.load(f) - updated = False - for a in data.get("agents", []): - if a.get("id") == agent_id: - a["status"] = status - if process_detail: - a["processDetail"] = process_detail - if progress is not None: - a["progress"] = progress - updated = True - break - if updated: - safe_write_json(STATUS_FILE, data) - except Exception: - pass + def apply(data): + for a in data.get("agents", []): + if a.get("id") == agent_id: + a["status"] = status + if process_detail: + a["processDetail"] = process_detail + if progress is not None: + a["progress"] = progress + return True + return False + + update_json_file(STATUS_FILE, apply) def run_powershell_subprocess(cmd: str, root_dir: str): def worker(): @@ -591,14 +582,9 @@ def get_cached_cli_status(root_dir: str) -> dict: return data def update_provider_runtime_status(provider_id: str, status: str, status_detail: str, valid: bool = None): - try: - cfg_file = os.path.join(SPECS_DIR, "swarm-config.json") - if not os.path.exists(cfg_file): - return - with open(cfg_file, "r", encoding="utf-8") as f: - cfg = json.load(f) - changed = False - p_target = provider_id.lower().strip() + p_target = provider_id.lower().strip() + + def apply(cfg): for p in cfg.get("providers", []): cur_p = (p.get("provider") or "").lower().strip() if cur_p == p_target or (cur_p in p_target) or (p_target in cur_p): @@ -607,12 +593,11 @@ def update_provider_runtime_status(provider_id: str, status: str, status_detail: p["statusDetail"] = status_detail if valid is not None: p["valid"] = valid - changed = True - break - if changed: - safe_write_json(cfg_file, cfg) - except Exception: - pass + return True + return False + return False + + update_json_file(os.path.join(SPECS_DIR, "swarm-config.json"), apply) def probe_and_update_local_provider(p: dict) -> bool: """Probes a local provider (e.g. 9Router or Ollama) via TCP socket and syncs status. Returns True if changed.""" @@ -684,6 +669,52 @@ def probe_rate_limited_provider(p: dict) -> bool: pass return False +PROBE_FIELDS = ("status", "statusDetail", "valid") + +def _provider_identity(p: dict): + return (p.get("provider"), p.get("baseUrl") or p.get("base_url")) + +def refresh_provider_statuses(cfg_file: str, check_cloud_ratelimit: bool = False) -> bool: + """Probe providers and merge only the status fields into the live file. + + Probing does socket and HTTP I/O, so it runs on a snapshot outside the lock; + the results are then applied to a fresh read of the file. Writing the + snapshot back (the old behaviour) reverted anything saved while the probe ran. + """ + try: + with open(cfg_file, "r", encoding="utf-8-sig") as f: + snapshot = json.load(f).get("providers", []) + except (OSError, ValueError, AttributeError): + return False + results = [] + for original in snapshot if isinstance(snapshot, list) else []: + if not isinstance(original, dict): + continue + probed = dict(original) + changed = probe_and_update_local_provider(probed) + if check_cloud_ratelimit and probe_rate_limited_provider(probed): + changed = True + if changed: + results.append((_provider_identity(original), + {k: probed[k] for k in PROBE_FIELDS if k in probed})) + if not results: + return False + + def apply(cfg): + changed = False + for p in cfg.get("providers", []): + if not isinstance(p, dict): + continue + for identity, fields in results: + if _provider_identity(p) == identity: + for name, value in fields.items(): + if p.get(name) != value: + p[name] = value + changed = True + return changed + + return update_json_file(cfg_file, apply) + def local_providers_probe_worker(root_dir: str): cfg_file = os.path.join(root_dir, "specs", "swarm-config.json") last_cloud_probe = 0 @@ -692,25 +723,11 @@ def local_providers_probe_worker(root_dir: str): time.sleep(2.5) if not os.path.exists(cfg_file): continue - with open(cfg_file, "r", encoding="utf-8") as f: - cfg = json.load(f) - - providers = cfg.get("providers", []) - changed = False now = time.time() check_cloud_ratelimit = (now - last_cloud_probe >= 15.0) - - for p in providers: - if probe_and_update_local_provider(p): - changed = True - if check_cloud_ratelimit and probe_rate_limited_provider(p): - changed = True - + refresh_provider_statuses(cfg_file, check_cloud_ratelimit) if check_cloud_ratelimit: last_cloud_probe = now - - if changed: - safe_write_json(cfg_file, cfg) except Exception: pass @@ -843,15 +860,6 @@ def worker(): AUTO_GENERATED_FILES = set() -def safe_write_json(filepath: str, data: dict): - try: - tmp_path = filepath + ".tmp" - with open(tmp_path, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) - os.replace(tmp_path, filepath) - except Exception: - pass - def detect_agent_from_file_path(rel_path: str) -> str: norm = rel_path.replace("\\", "/").lower() @@ -986,47 +994,46 @@ def handle_task_completion(agent_id: str, root_dir: str): log_file = os.path.join(root_dir, "specs", "terminal.log") status_file = os.path.join(root_dir, "specs", "swarm-status.json") - try: - if os.path.exists(status_file): - with open(status_file, "r", encoding="utf-8") as f: - data = json.load(f) - updated = False + msg = f"Task completed (100%). Status set to REVIEWING." + + def apply(data): + for a in data.get("agents", []): + if a.get("id") == agent_id and a.get("status") == "WORKING": + a["status"] = "REVIEWING" + a["progress"] = 100 + a["processDetail"] = get_role_stage_message(agent_id, 100) + break + else: + return False + if "logs" not in data: + data["logs"] = [] + data["logs"].append({ + "timestamp": ts, + "agent": agent_id, + "message": f"[{agent_id}] {msg}" + }) + data["logs"] = data["logs"][-50:] + + # Natural dependency notification (Honest state without fake execution) + if agent_id in ("05_backend", "06_client"): for a in data.get("agents", []): - if a.get("id") == agent_id and a.get("status") == "WORKING": - a["status"] = "REVIEWING" - a["progress"] = 100 - a["processDetail"] = get_role_stage_message(agent_id, 100) - updated = True - break - if updated: - msg = f"Task completed (100%). Status set to REVIEWING." - if "logs" not in data: - data["logs"] = [] - data["logs"].append({ - "timestamp": ts, - "agent": agent_id, - "message": f"[{agent_id}] {msg}" - }) - data["logs"] = data["logs"][-50:] - - # Natural dependency notification (Honest state without fake execution) - if agent_id in ("05_backend", "06_client"): - for a in data.get("agents", []): - if a.get("id") == "07_qa" and a.get("status") in ("IDLE", "WAITING"): - a["status"] = "WAITING" - a["currentTask"] = "Pending test verification for latest backend/client changes." - a["processDetail"] = "Standby: Waiting for automated test execution or QA suite run." - - with open(log_file, "a", encoding="utf-8") as f: - f.write(f"[{ts}] [{agent_id}] {msg}\n") + if a.get("id") == "07_qa" and a.get("status") in ("IDLE", "WAITING"): + a["status"] = "WAITING" + a["currentTask"] = "Pending test verification for latest backend/client changes." + a["processDetail"] = "Standby: Waiting for automated test execution or QA suite run." + + try: + with open(log_file, "a", encoding="utf-8") as f: + f.write(f"[{ts}] [{agent_id}] {msg}\n") + except OSError: + pass - if "project" in data and "agents" in data: - total_p = sum(ag.get("progress", 0) for ag in data["agents"]) - data["project"]["overallProgress"] = int(total_p / len(data["agents"])) + if "project" in data and "agents" in data: + total_p = sum(ag.get("progress", 0) for ag in data["agents"]) + data["project"]["overallProgress"] = int(total_p / len(data["agents"])) + return True - safe_write_json(status_file, data) - except Exception: - pass + update_json_file(status_file, apply) def handle_file_event(agent_id: str, action_desc: str, root_dir: str): ts = datetime.datetime.now().strftime("%H:%M:%S") @@ -1046,64 +1053,60 @@ def handle_file_event(agent_id: str, action_desc: str, root_dir: str): pass # 2. Update swarm-status.json with dynamic progress - try: - if os.path.exists(status_file): - with open(status_file, "r", encoding="utf-8") as f: - data = json.load(f) - updated = False - cur_phase = str(data.get("project", {}).get("phase", "")) - is_pipeline_active = cur_phase.startswith("Phase ") or cur_phase == "Completed: Production Ready" + def apply(data): + cur_phase = str(data.get("project", {}).get("phase", "")) + is_pipeline_active = cur_phase.startswith("Phase ") or cur_phase == "Completed: Production Ready" + + for a in data.get("agents", []): + if a.get("id") == agent_id: + # Do not revert an agent that just completed its deliverable during an automated pipeline run + if is_pipeline_active and a.get("status") == "REVIEWING" and a.get("progress", 0) == 100 and action_desc.startswith("Created "): + return False + + a["processDetail"] = action_desc + a["status"] = "WORKING" + # Invalidate prior completion on file modifications + if a.get("progress", 0) >= 100 or a.get("status") in ("REVIEWING", "COMPLETED"): + a["progress"] = 25 + elif a.get("progress", 0) == 0: + a["progress"] = 25 + break + else: + return False - for a in data.get("agents", []): - if a.get("id") == agent_id: - # Do not revert an agent that just completed its deliverable during an automated pipeline run - if is_pipeline_active and a.get("status") == "REVIEWING" and a.get("progress", 0) == 100 and action_desc.startswith("Created "): - break - - a["processDetail"] = action_desc - a["status"] = "WORKING" - # Invalidate prior completion on file modifications - if a.get("progress", 0) >= 100 or a.get("status") in ("REVIEWING", "COMPLETED"): - a["progress"] = 25 - elif a.get("progress", 0) == 0: - a["progress"] = 25 - updated = True - break - if updated: - if "logs" not in data: - data["logs"] = [] - data["logs"].append({ - "timestamp": ts, - "agent": agent_id, - "message": f"[{agent_id}] {action_desc}" - }) - data["logs"] = data["logs"][-50:] - - # Update overall project progress - if "project" in data and "agents" in data: - total_p = sum(ag.get("progress", 0) for ag in data["agents"]) - data["project"]["overallProgress"] = int(total_p / len(data["agents"])) - - # Clear stuck FAILED phase when agent resumes active work - cur_phase = str(data["project"].get("phase", "")) - if "FAILED:" in cur_phase: - role_phase_map = { - "01_pm": "Phase 1: PRD & Requirements", - "02_arch": "Phase 2: Architecture & ADR", - "03_designer": "Phase 3: Design Tokens & UI/UX", - "04_dba": "Phase 4: Database & API Contract", - "05_backend": "Phase 5: Backend Domain Implementation", - "06_client": "Phase 6: Client UI Implementation", - "07_qa": "Phase 7: QA Test Engineering", - "08_security": "Phase 8: Security Vulnerability Audit", - "09_devops": "Phase 9: DevOps & Containerization", - "10_tech_lead": "Phase 10: Final Quality Gate Audit" - } - data["project"]["phase"] = role_phase_map.get(agent_id, "In Progress") - - safe_write_json(status_file, data) - except Exception: - pass + if "logs" not in data: + data["logs"] = [] + data["logs"].append({ + "timestamp": ts, + "agent": agent_id, + "message": f"[{agent_id}] {action_desc}" + }) + data["logs"] = data["logs"][-50:] + + # Update overall project progress + if "project" in data and "agents" in data: + total_p = sum(ag.get("progress", 0) for ag in data["agents"]) + data["project"]["overallProgress"] = int(total_p / len(data["agents"])) + + # Clear stuck FAILED phase when agent resumes active work + cur_phase = str(data["project"].get("phase", "")) + if "FAILED:" in cur_phase: + role_phase_map = { + "01_pm": "Phase 1: PRD & Requirements", + "02_arch": "Phase 2: Architecture & ADR", + "03_designer": "Phase 3: Design Tokens & UI/UX", + "04_dba": "Phase 4: Database & API Contract", + "05_backend": "Phase 5: Backend Domain Implementation", + "06_client": "Phase 6: Client UI Implementation", + "07_qa": "Phase 7: QA Test Engineering", + "08_security": "Phase 8: Security Vulnerability Audit", + "09_devops": "Phase 9: DevOps & Containerization", + "10_tech_lead": "Phase 10: Final Quality Gate Audit" + } + data["project"]["phase"] = role_phase_map.get(agent_id, "In Progress") + return True + + update_json_file(status_file, apply) def start_workspace_watcher(root_dir: str): def watcher_loop(): @@ -1175,20 +1178,19 @@ def watcher_loop(): # If an agent was in WORKING state for over 120 seconds with no tool activity, return to IDLE without fake 100% if elapsed >= 120.0: del last_activity_time[aid] - if os.path.exists(status_file): + def go_idle(sdata, aid=aid): + changed = False + for a in sdata.get("agents", []): + if a.get("id") == aid and a.get("status") == "WORKING": + a["status"] = "IDLE" + a["processDetail"] = "Standing by for founder instructions." + changed = True + return changed + + if update_json_file(status_file, go_idle): try: - with open(status_file, "r", encoding="utf-8") as f: - sdata = json.load(f) - changed = False - for a in sdata.get("agents", []): - if a.get("id") == aid and a.get("status") == "WORKING": - a["status"] = "IDLE" - a["processDetail"] = "Standing by for founder instructions." - changed = True - if changed: - safe_write_json(status_file, sdata) - prev_status_mtime = os.path.getmtime(status_file) - except Exception: + prev_status_mtime = os.path.getmtime(status_file) + except OSError: pass # 3. Workspace filesystem watcher for all project code and specs @@ -1404,14 +1406,13 @@ def do_GET(self): if os.path.exists(cfg_file): try: + # Merge probe results into the file (credentials untouched), then serve what is on disk. + refresh_provider_statuses(cfg_file) with open(cfg_file, "r", encoding="utf-8") as f: saved = json.load(f) cfg.update(saved) if "providers" in cfg: - probe_changed = False for p in cfg["providers"]: - if probe_and_update_local_provider(p): - probe_changed = True k = p.get("key", "") p["has_key"] = bool(k and k.strip()) if k: @@ -1419,8 +1420,6 @@ def do_GET(self): else: p["key_masked"] = "" p.pop("key", None) - if probe_changed: - safe_write_json(cfg_file, cfg) except Exception: pass cfg["cli"] = get_cached_cli_status(DIRECTORY) @@ -1564,9 +1563,10 @@ def validate_single_provider(p_entry): with concurrent.futures.ThreadPoolExecutor(max_workers=min(len(providers), 5)) as executor: list(executor.map(validate_single_provider, providers)) - os.makedirs(SPECS_DIR, exist_ok=True) - with open(cfg_file, "w", encoding="utf-8") as f: - json.dump(payload, f, indent=2) + saved = atomic_write_json(cfg_file, payload) + if not saved: + self.send_json_response({"error": "Could not save configuration"}, 500) + return # CRITICAL SECURITY: Never return raw plaintext keys to client! safe_payload = json.loads(json.dumps(payload)) @@ -1715,10 +1715,8 @@ def validate_single_provider(p_entry): with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(f"[{ts}] [{agent_id}] {message}\n") - if os.path.exists(STATUS_FILE) and (status or progress is not None or message): - try: - with open(STATUS_FILE, "r", encoding="utf-8") as f: - data = json.load(f) + if status or progress is not None or message: + def apply(data): for a in data.get("agents", []): if a.get("id") == agent_id: if message: @@ -1727,10 +1725,10 @@ def validate_single_provider(p_entry): a["status"] = status if progress is not None: a["progress"] = max(0, min(100, int(progress))) - break - safe_write_json(STATUS_FILE, data) - except Exception: - pass + return True + return False + + update_json_file(STATUS_FILE, apply) self.send_json_response({"ok": True}) return diff --git a/dashboard/statefile.py b/dashboard/statefile.py new file mode 100644 index 0000000..d32977a --- /dev/null +++ b/dashboard/statefile.py @@ -0,0 +1,119 @@ +"""Atomic, serialised JSON state files for the dashboard process. + +The dashboard's server threads, its background workers and the swarm pipeline +thread all read-modify-write ``specs/swarm-status.json`` and +``specs/swarm-config.json``. Writing through one shared ``.tmp`` file +with no lock tore the JSON when two threads wrote at once, lost updates, and +(on Windows) silently dropped an update whenever a reader still had the target +open, because ``os.replace`` onto an open file raises PermissionError. + +Writers in *other* processes (``stream.py``, agents editing the file directly) +are not covered by the in-process lock; atomic replacement still guarantees +they can never expose a half-written file to readers. + +There is one re-entrant lock per file, so a writer waiting for a reader to let +go of one file never delays writers of another. No code path holds the lock of +two files at once (``update_json_file`` callbacks must not update other state +files), so the locks cannot deadlock. +""" + +import json +import os +import stat +import tempfile +import threading +import time + +_REPLACE_ATTEMPTS = 60 +_REPLACE_DELAY = 0.025 +_NEW_FILE_MODE = 0o644 # what ``open(path, "w")`` gave under the usual umask + +_locks = {} +_locks_guard = threading.Lock() + + +def _resolve(path) -> str: + """The file that really gets replaced: a symlink is followed, not overwritten.""" + return os.path.realpath(os.path.abspath(path)) + + +def path_lock(path): + """The re-entrant lock that serialises every read-modify-write of ``path``.""" + key = os.path.normcase(_resolve(path)) + with _locks_guard: + lock = _locks.get(key) + if lock is None: + lock = _locks[key] = threading.RLock() + return lock + + +def atomic_write_json(path, data) -> bool: + """Write ``data`` to ``path`` atomically; return False if it could not land. + + The data is written to a unique temporary file in the same directory, then + moved over the target. A busy target (a reader on Windows) is retried for + about 1.5 seconds before giving up. The previous file is never left + truncated and no temporary file is left behind; an existing file keeps its + permissions and a symlink keeps pointing at the file that is updated. + """ + target = _resolve(path) + directory = os.path.dirname(target) + tmp_path = None + with path_lock(target): + try: + os.makedirs(directory, exist_ok=True) + try: + mode = stat.S_IMODE(os.stat(target).st_mode) + except OSError: + mode = _NEW_FILE_MODE + handle, tmp_path = tempfile.mkstemp( + prefix=os.path.basename(target) + ".", suffix=".tmp", dir=directory + ) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump(data, stream, indent=2) + stream.flush() + os.fsync(stream.fileno()) + if os.name != "nt": # mkstemp creates 0600; Windows only has a read-only bit + os.chmod(tmp_path, mode) + for attempt in range(_REPLACE_ATTEMPTS): + try: + os.replace(tmp_path, target) + tmp_path = None + return True + except PermissionError: + if attempt == _REPLACE_ATTEMPTS - 1: + return False + time.sleep(_REPLACE_DELAY) + return False + except (OSError, TypeError, ValueError): + return False + finally: + if tmp_path is not None: + try: + os.remove(tmp_path) + except OSError: + pass + + +def update_json_file(path, mutate) -> bool: + """Atomically read-modify-write ``path`` under that file's lock. + + ``mutate(data)`` edits the parsed document in place and returns True when it + changed something; only then is the file rewritten. Returns True when a new + version was written. A missing or unparseable file is left alone, and so is + a file whose document ``mutate`` cannot handle (it raised): the callers are + background threads that must not die over a hand-edited state file. A + leading byte-order mark (an editor's "UTF-8 with BOM") is accepted. + """ + with path_lock(path): + try: + with open(_resolve(path), "r", encoding="utf-8-sig") as stream: + data = json.load(stream) + except (OSError, ValueError): + return False + try: + if not mutate(data): + return False + except Exception: + return False # document does not have the expected shape (or the update itself failed) + return atomic_write_json(path, data) diff --git a/stream.py b/stream.py index 828e835..0074215 100644 --- a/stream.py +++ b/stream.py @@ -33,6 +33,9 @@ import argparse ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) +if ROOT_DIR not in sys.path: + sys.path.insert(0, ROOT_DIR) +from dashboard.statefile import atomic_write_json # readers never see a half-written file SPECS_DIR = os.path.join(ROOT_DIR, "specs") LOG_FILE = os.path.join(SPECS_DIR, "terminal.log") STATUS_FILE = os.path.join(SPECS_DIR, "swarm-status.json") @@ -130,8 +133,7 @@ def update_agent_status(agent_id: str, process_detail: str, status: str = None, # Keep swarm logs to last 50 entries data["logs"] = data["logs"][-50:] - with open(STATUS_FILE, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) + atomic_write_json(STATUS_FILE, data) except Exception: pass diff --git a/swarm_pipeline.py b/swarm_pipeline.py index 9b565b8..33c740b 100644 --- a/swarm_pipeline.py +++ b/swarm_pipeline.py @@ -18,6 +18,11 @@ import council ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) +if ROOT_DIR not in sys.path: + sys.path.insert(0, ROOT_DIR) +# Same lock and atomic replace as dashboard/serve.py, which runs this pipeline +# on a thread of its own process. +from dashboard.statefile import update_json_file SPECS_DIR = os.path.join(ROOT_DIR, "specs") LOG_FILE = os.path.join(SPECS_DIR, "terminal.log") STATUS_FILE = os.path.join(SPECS_DIR, "swarm-status.json") @@ -48,13 +53,8 @@ def log_swarm_message(agent_id: str, message: str, root_dir: str = None): def update_swarm_status(agent_id: str, status: str, process_detail: str, progress: int = None, root_dir: str = None, overall_progress: int = None, phase: str = None): target_status = os.path.join(root_dir or ROOT_DIR, "specs", "swarm-status.json") - if not os.path.exists(target_status): - return - - try: - with open(target_status, "r", encoding="utf-8") as f: - data = json.load(f) + def apply(data): if overall_progress is not None and "project" in data: data["project"]["overallProgress"] = max(0, min(100, int(overall_progress))) if phase and "project" in data: @@ -78,11 +78,10 @@ def update_swarm_status(agent_id: str, status: str, process_detail: str, progres "message": f"[{agent_id}] {process_detail[:140]}" }) data["logs"] = data["logs"][-50:] + return True - tmp_path = target_status + ".tmp" - with open(tmp_path, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2) - os.replace(tmp_path, target_status) + try: + update_json_file(target_status, apply) except Exception: pass diff --git a/tests/test_dashboard_state.py b/tests/test_dashboard_state.py new file mode 100644 index 0000000..b1828f2 --- /dev/null +++ b/tests/test_dashboard_state.py @@ -0,0 +1,300 @@ +"""The dashboard's threads share swarm-status.json and swarm-config.json. + +These tests drive the real ``dashboard/serve.py`` module (and the swarm +pipeline) against a throw-away directory tree: no repository file is written, +no provider is contacted and no subprocess is started. The module is +Windows-only (it exits at import elsewhere), so the whole file is skipped on +other platforms. +""" + +import http.client +import importlib.util +import json +import shutil +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path + +if sys.platform != "win32": + raise unittest.SkipTest("dashboard/serve.py is a Windows-only server") + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +_SERVE = None + + +def load_serve(): + global _SERVE + if _SERVE is None: + spec = importlib.util.spec_from_file_location( + "tenagent_serve_state_tests", ROOT / "dashboard" / "serve.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + _SERVE = module + return _SERVE + + +class StateCase(unittest.TestCase): + def setUp(self): + self.serve = load_serve() + self.tmp = tempfile.TemporaryDirectory(prefix="tenagent-state-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.specs = self.root / "specs" + self.specs.mkdir() + shutil.copy2(ROOT / "specs" / "swarm-status.json", self.specs / "swarm-status.json") + serve = self.serve + for name, value in ( + ("DIRECTORY", str(self.root)), + ("SPECS_DIR", str(self.specs)), + ("LOG_FILE", str(self.specs / "terminal.log")), + ("STATUS_FILE", str(self.specs / "swarm-status.json")), + ): + self.addCleanup(setattr, serve, name, getattr(serve, name)) + setattr(serve, name, value) + + def read_status(self): + return json.loads((self.specs / "swarm-status.json").read_text(encoding="utf-8")) + + def agent_ids(self, count): + return [a["id"] for a in self.read_status()["agents"]][:count] + + def leftovers(self): + return sorted(p.name for p in self.specs.glob("*.tmp")) + + def write_config(self, config): + (self.specs / "swarm-config.json").write_text(json.dumps(config), encoding="utf-8") + + def read_config(self): + return json.loads((self.specs / "swarm-config.json").read_text(encoding="utf-8")) + + def run_threads(self, targets): + threads = [threading.Thread(target=t) for t in targets] + for thread in threads: + thread.start() + for thread in threads: + thread.join(60) + self.assertFalse(any(t.is_alive() for t in threads), "a worker thread hung") + + +class StatusFileTests(StateCase): + def test_concurrent_status_updates_are_neither_lost_nor_corrupted(self): + ids = self.agent_ids(8) + barrier = threading.Barrier(len(ids)) + + def work(agent_id): + barrier.wait() + for step in range(1, 26): + self.serve.set_agent_status_direct(agent_id, "WORKING", f"step {step}", step) + + self.run_threads([lambda i=i: work(i) for i in ids]) + final = {a["id"]: a["progress"] for a in self.read_status()["agents"]} + self.assertEqual([final[i] for i in ids], [25] * len(ids)) + self.assertEqual(self.leftovers(), []) + + def test_file_events_and_task_completions_share_the_same_lock(self): + ids = self.agent_ids(4) + barrier = threading.Barrier(len(ids) * 2) + serve = self.serve + + def events(agent_id): + barrier.wait() + for step in range(15): + serve.handle_file_event(agent_id, f"Modified file {step}", str(self.root)) + + def statuses(agent_id): + barrier.wait() + for step in range(1, 16): + serve.set_agent_status_direct(agent_id, "WORKING", f"direct {step}", step) + + self.run_threads([lambda i=i: events(i) for i in ids] + [lambda i=i: statuses(i) for i in ids]) + status = self.read_status() + self.assertEqual(len(status["agents"]), 10) # parseable and complete + self.assertEqual(self.leftovers(), []) + # every agent kept the last value written by *its* writers + self.assertTrue(all(a["progress"] == 15 for a in status["agents"] if a["id"] in ids)) + + def test_the_swarm_pipeline_writes_through_the_same_lock(self): + import swarm_pipeline + a, b = self.agent_ids(2) + barrier = threading.Barrier(2) + + def pipeline(): + barrier.wait() + for step in range(1, 21): + swarm_pipeline.update_swarm_status(a, "WORKING", f"pipeline {step}", step, str(self.root)) + + def dashboard(): + barrier.wait() + for step in range(1, 21): + self.serve.set_agent_status_direct(b, "WORKING", f"dashboard {step}", step) + + self.run_threads([pipeline, dashboard]) + final = {x["id"]: x["progress"] for x in self.read_status()["agents"]} + self.assertEqual((final[a], final[b]), (20, 20)) + self.assertEqual(self.leftovers(), []) + + def test_an_update_waits_for_a_reader_instead_of_being_dropped(self): + # SimpleHTTPRequestHandler keeps the file open while it streams it; on + # Windows os.replace onto an open file fails, and the update used to be + # swallowed silently. + agent_id = self.agent_ids(1)[0] + reader = open(self.specs / "swarm-status.json", "rb") + self.addCleanup(reader.close) + worker = threading.Thread( + target=self.serve.set_agent_status_direct, + args=(agent_id, "WORKING", "after-reader", 77)) + worker.start() + time.sleep(0.3) + reader.close() + worker.join(10) + agent = next(a for a in self.read_status()["agents"] if a["id"] == agent_id) + self.assertEqual((agent["progress"], agent["processDetail"]), (77, "after-reader")) + self.assertEqual(self.leftovers(), []) + + def test_a_started_completed_agent_is_not_reverted_by_a_created_file(self): + # behaviour that must survive the move to the shared writer: during an + # automated run an agent that just finished stays finished + serve = self.serve + agent_id = self.agent_ids(1)[0] + data = self.read_status() + data["project"]["phase"] = "Phase 5: Backend Domain Implementation" + for agent in data["agents"]: + if agent["id"] == agent_id: + agent.update(status="REVIEWING", progress=100) + (self.specs / "swarm-status.json").write_text(json.dumps(data), encoding="utf-8") + serve.handle_file_event(agent_id, "Created backend/src/main.py", str(self.root)) + agent = next(a for a in self.read_status()["agents"] if a["id"] == agent_id) + self.assertEqual((agent["status"], agent["progress"]), ("REVIEWING", 100)) + serve.handle_file_event(agent_id, "Modified backend/src/main.py", str(self.root)) + agent = next(a for a in self.read_status()["agents"] if a["id"] == agent_id) + self.assertEqual((agent["status"], agent["progress"]), ("WORKING", 25)) + + +class ConfigFileTests(StateCase): + KEY = "sk-test-FAKE-KEEP-333333" + + def one_probe_pass(self, slow_probe): + """Run local_providers_probe_worker for a single pass with ``slow_probe``.""" + serve = self.serve + calls = [] + worker = threading.Thread(target=serve.local_providers_probe_worker, args=(str(self.root),)) + + class OnePassTime: + """serve.py's own view of ``time``: only the worker thread's sleep is intercepted.""" + + def __getattr__(self, name): + return getattr(time, name) + + def sleep(self, seconds): + if threading.current_thread() is not worker: + return time.sleep(seconds) + calls.append(seconds) + if len(calls) > 1: + raise SystemExit # end the worker thread after a single pass + + for owner, name, value in ( + (serve, "probe_and_update_local_provider", slow_probe), + (serve, "time", OnePassTime()), + ): + self.addCleanup(setattr, owner, name, getattr(owner, name)) + setattr(owner, name, value) + worker.start() + return worker + + def make_slow_probe(self, probing, release): + def slow_probe(provider): + probing.set() + release.wait(10) + provider["status"] = "connection_error" + provider["statusDetail"] = "Offline" + provider["valid"] = False + return True + return slow_probe + + def test_a_config_saved_while_the_probe_runs_is_not_reverted(self): + self.write_config({"engine": "custom", "providers": [ + {"provider": "9router", "key": self.KEY, "baseUrl": "http://127.0.0.1:9/v1"}]}) + probing, release = threading.Event(), threading.Event() + worker = self.one_probe_pass(self.make_slow_probe(probing, release)) + self.assertTrue(probing.wait(10)) + # the operator saves a different provider list while the probe is in flight + self.write_config({"engine": "custom", "providers": [ + {"provider": "gemini", "key": "sk-test-FAKE-NEW-222222"}]}) + release.set() + worker.join(10) + self.assertEqual([p["provider"] for p in self.read_config()["providers"]], ["gemini"]) + + def test_probe_results_are_merged_into_the_current_config(self): + self.write_config({"engine": "custom", "providers": [ + {"provider": "9router", "key": self.KEY, "baseUrl": "http://127.0.0.1:9/v1"}]}) + probing, release = threading.Event(), threading.Event() + worker = self.one_probe_pass(self.make_slow_probe(probing, release)) + self.assertTrue(probing.wait(10)) + current = self.read_config() + current["note"] = "edited-meanwhile" # an unrelated edit lands during the probe + self.write_config(current) + release.set() + worker.join(10) + stored = self.read_config() + self.assertEqual(stored.get("note"), "edited-meanwhile") + self.assertEqual(stored["providers"][0]["status"], "connection_error") + self.assertEqual(stored["providers"][0]["key"], self.KEY) + + def test_runtime_status_updates_keep_the_rest_of_the_file(self): + self.write_config({"engine": "custom", "providers": [ + {"provider": "groq", "key": self.KEY, "status": "active"}]}) + self.serve.update_provider_runtime_status("groq", "rate_limited", "Rate Limited", False) + stored = self.read_config()["providers"][0] + self.assertEqual((stored["status"], stored["valid"], stored["key"]), + ("rate_limited", False, self.KEY)) + self.assertEqual(self.leftovers(), []) + + def test_council_status_updates_use_the_same_writer(self): + import council + self.write_config({"engine": "custom", "providers": [ + {"provider": "groq", "key": self.KEY, "status": "active"}]}) + council.update_provider_runtime_status("groq", "rate_limited", "Rate Limited", False, str(self.root)) + stored = self.read_config()["providers"][0] + self.assertEqual((stored["status"], stored["key"]), ("rate_limited", self.KEY)) + self.assertEqual(self.leftovers(), []) + + +class ConfigReadTests(StateCase): + """GET /api/config shows a redacted view; it must not write that view back.""" + + def test_reading_the_config_never_strips_the_stored_keys(self): + # Pins a latent defect. The old handler wrote the key-stripped view back from inside + # ``with open(cfg_file)``; on Windows that replace is refused while the handle is open + # (the error was swallowed and the keys survived by accident). Anywhere the replace + # succeeds - or if the handle were closed first - every stored key would be deleted. + key = "sk-test-FAKE-STORED-444444" + # nothing listens on port 1, so the local-provider probe flips the status + self.write_config({"engine": "custom", "providers": [ + {"provider": "ollama", "key": key, "baseUrl": "http://127.0.0.1:1/v1", "status": "active"}]}) + httpd = self.serve.ThreadedSwarmServer(("127.0.0.1", 0), self.serve.SwarmHandler) + thread = threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True) + thread.start() + self.addCleanup(thread.join, 5) + self.addCleanup(httpd.server_close) + self.addCleanup(httpd.shutdown) + conn = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=10) + try: + conn.request("GET", "/api/config") + reply = conn.getresponse() + body = reply.read().decode("utf-8") + finally: + conn.close() + self.assertEqual(reply.status, 200) + self.assertNotIn(key, body) # the browser never sees it + stored = self.read_config()["providers"][0] + self.assertEqual(stored.get("key"), key) # and the file still has it + self.assertEqual(stored["status"], "connection_error") # the probe result was kept + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_statefile.py b/tests/test_statefile.py new file mode 100644 index 0000000..7bb9fb2 --- /dev/null +++ b/tests/test_statefile.py @@ -0,0 +1,186 @@ +"""Unit tests for the atomic, serialised JSON state-file helpers.""" + +import json +import os +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from dashboard import statefile # noqa: E402 + + +class StateFileTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="tenagent-state-") + self.addCleanup(self.tmp.cleanup) + self.path = os.path.join(self.tmp.name, "state.json") + self.write({"counters": {f"c{i}": 0 for i in range(8)}}) + + def write(self, data): + with open(self.path, "w", encoding="utf-8") as stream: + json.dump(data, stream) + + def read(self): + with open(self.path, "r", encoding="utf-8") as stream: + return json.load(stream) + + def leftovers(self): + return [n for n in os.listdir(self.tmp.name) if n != "state.json"] + + def test_concurrent_updates_are_serialised_and_atomic(self): + barrier = threading.Barrier(8) + + def work(name): + barrier.wait() + for _ in range(30): + statefile.update_json_file( + self.path, + lambda d, n=name: d["counters"].__setitem__(n, d["counters"][n] + 1) or True, + ) + + threads = [threading.Thread(target=work, args=(f"c{i}",)) for i in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(60) + self.assertEqual(set(self.read()["counters"].values()), {30}) + self.assertEqual(self.leftovers(), []) + + def test_unchanged_document_is_not_rewritten(self): + before = self.read() + with mock.patch("os.replace", wraps=os.replace) as replace: + self.assertFalse(statefile.update_json_file(self.path, lambda d: False)) + self.assertEqual(replace.call_count, 0) # nothing was moved over the file + self.assertEqual(self.read(), before) + self.assertEqual(self.leftovers(), []) + + def test_missing_or_corrupt_files_are_left_alone(self): + missing = os.path.join(self.tmp.name, "absent.json") + self.assertFalse(statefile.update_json_file(missing, lambda d: True)) + self.assertFalse(os.path.exists(missing)) + with open(self.path, "w", encoding="utf-8") as stream: + stream.write("{not json") + self.assertFalse(statefile.update_json_file(self.path, lambda d: True)) + with open(self.path, "r", encoding="utf-8") as stream: + self.assertEqual(stream.read(), "{not json") + + def test_wrongly_shaped_documents_do_not_raise(self): + self.write([1, 2, 3]) + self.assertFalse(statefile.update_json_file(self.path, lambda d: d["counters"])) + + def test_an_update_that_raises_leaves_the_file_alone(self): + original = self.read() + + def broken(document): + document["counters"]["c0"] = 99 + raise ValueError("bad progress value") + + self.assertFalse(statefile.update_json_file(self.path, broken)) + self.assertEqual(self.read(), original) + self.assertEqual(self.leftovers(), []) + + def test_failed_replace_keeps_the_old_file_and_cleans_up(self): + original = self.read() + with mock.patch.object(statefile, "_REPLACE_ATTEMPTS", 3), \ + mock.patch.object(statefile, "_REPLACE_DELAY", 0), \ + mock.patch("os.replace", side_effect=PermissionError): + self.assertFalse(statefile.atomic_write_json(self.path, {"new": True})) + self.assertEqual(self.read(), original) + self.assertEqual(self.leftovers(), []) + + def test_unserialisable_data_keeps_the_old_file(self): + original = self.read() + self.assertFalse(statefile.atomic_write_json(self.path, {"bad": {1, 2}})) + self.assertEqual(self.read(), original) + self.assertEqual(self.leftovers(), []) + + def test_directory_is_created_on_demand(self): + nested = os.path.join(self.tmp.name, "a", "b", "state.json") + self.assertTrue(statefile.atomic_write_json(nested, {"ok": 1})) + with open(nested, "r", encoding="utf-8") as stream: + self.assertEqual(json.load(stream), {"ok": 1}) + + def test_files_do_not_wait_for_each_other(self): + # one file whose replace is stuck (a reader holds it on Windows) must not stall + # the writers of any other file + other = os.path.join(self.tmp.name, "other.json") + with open(other, "w", encoding="utf-8") as stream: + json.dump({"n": 0}, stream) + stuck, release = threading.Event(), threading.Event() + real_replace = os.replace + + def replace(src, dst): + if os.path.basename(dst) == "state.json": + stuck.set() + release.wait(10) + return real_replace(src, dst) + + slow = threading.Thread(target=statefile.update_json_file, + args=(self.path, lambda d: d["counters"].__setitem__("c0", 1) or True)) + with mock.patch("os.replace", side_effect=replace): + slow.start() + self.assertTrue(stuck.wait(5)) + started = time.monotonic() + done = [] + fast = threading.Thread(target=lambda: done.append(statefile.update_json_file( + other, lambda d: d.__setitem__("n", 1) or True))) + fast.start() + fast.join(3) + elapsed = time.monotonic() - started + release.set() + slow.join(10) + self.assertEqual(done, [True], "the other file's update waited for the stuck one") + self.assertLess(elapsed, 3) + self.assertEqual(self.read()["counters"]["c0"], 1) + + def test_the_same_file_is_still_serialised_through_symlinks_and_relative_paths(self): + alias = os.path.join(self.tmp.name, ".", "state.json") + self.assertIs(statefile.path_lock(self.path), statefile.path_lock(alias)) + self.assertIsNot(statefile.path_lock(self.path), + statefile.path_lock(os.path.join(self.tmp.name, "other.json"))) + + def test_a_byte_order_mark_does_not_stop_updates(self): + with open(self.path, "w", encoding="utf-8-sig") as stream: # "UTF-8 with BOM", as some editors save it + json.dump({"counters": {"c0": 1}}, stream) + self.assertTrue(statefile.update_json_file(self.path, lambda d: d["counters"].__setitem__("c0", 2) or True)) + self.assertEqual(self.read(), {"counters": {"c0": 2}}) + + @unittest.skipUnless(os.name == "posix", "file modes and symlinks are a POSIX matter here") + def test_an_updated_file_keeps_its_permissions(self): + os.chmod(self.path, 0o644) + self.assertTrue(statefile.update_json_file(self.path, lambda d: d["counters"].__setitem__("c0", 1) or True)) + self.assertEqual(oct(os.stat(self.path).st_mode & 0o777), oct(0o644)) + os.chmod(self.path, 0o664) + self.assertTrue(statefile.atomic_write_json(self.path, {"counters": {}})) + self.assertEqual(oct(os.stat(self.path).st_mode & 0o777), oct(0o664)) + fresh = os.path.join(self.tmp.name, "fresh.json") + self.assertTrue(statefile.atomic_write_json(fresh, {"new": 1})) + self.assertEqual(oct(os.stat(fresh).st_mode & 0o777), oct(0o644)) + + @unittest.skipUnless(os.name == "posix", "file modes and symlinks are a POSIX matter here") + def test_a_symlinked_state_file_stays_a_symlink(self): + link = os.path.join(self.tmp.name, "link.json") + os.symlink(self.path, link) + self.assertTrue(statefile.update_json_file(link, lambda d: d["counters"].__setitem__("c0", 7) or True)) + self.assertTrue(os.path.islink(link)) + self.assertEqual(self.read()["counters"]["c0"], 7) + self.assertEqual(self.leftovers(), ["link.json"]) + + @unittest.skipUnless(sys.platform == "win32", "os.replace onto an open file only fails on Windows") + def test_replace_waits_for_a_reader_to_let_go(self): + reader = open(self.path, "rb") + self.addCleanup(reader.close) + threading.Timer(0.2, reader.close).start() + self.assertTrue(statefile.atomic_write_json(self.path, {"after": "reader"})) + self.assertEqual(self.read(), {"after": "reader"}) + self.assertEqual(self.leftovers(), []) + + +if __name__ == "__main__": + unittest.main()