From 1bd68dd2dec89945251974058f4f624adfdab5fc Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:08:51 +0800 Subject: [PATCH] fix(chat): eliminate O(turns) startup double-scan and speculative launchd stall Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/chat/event_cache.py | 252 ++++++++++++++++++++++--- loopx/chat_server.py | 6 +- loopx/chat_store.py | 16 +- scripts/macos-dashboard-launchagent.sh | 4 + tests/test_chat_startup_scale.py | 170 +++++++++++++++++ 5 files changed, 410 insertions(+), 38 deletions(-) create mode 100644 tests/test_chat_startup_scale.py diff --git a/loopx/chat/event_cache.py b/loopx/chat/event_cache.py index a9ec95a1d0..ad064b1829 100644 --- a/loopx/chat/event_cache.py +++ b/loopx/chat/event_cache.py @@ -2,10 +2,13 @@ from __future__ import annotations from bisect import bisect_right +from contextlib import suppress from datetime import datetime, timedelta, timezone +import json +import os from pathlib import Path import threading -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Protocol import uuid from ..file_lock import exclusive_file_lock @@ -232,31 +235,230 @@ def compact_completed_events(self, *, older_than_hours: float = 24.0) -> int: cutoff = datetime.now(timezone.utc) - timedelta(hours=max(0.0, older_than_hours)) compacted = 0 - for turn_path in self.sessions_root.glob("*/turns/*.json"): - turn = _store._read_json(turn_path) - if turn.get("status") not in _store.TERMINAL_TURN_STATES: + try: + session_entries = list(os.scandir(self.sessions_root)) + except OSError: + return 0 + for session_entry in session_entries: + if not session_entry.is_dir(follow_symlinks=False): continue - completed = _store._instant(turn.get("completed_at")) - if completed is None or completed > cutoff: + session_id = session_entry.name + turns_dir = Path(session_entry.path) / "turns" + try: + entries = list(os.scandir(turns_dir)) + except OSError: continue - session_id = turn_path.parent.parent.name - turn_id = turn_path.stem - self.flush_events(session_id, turn_id) - event_path = turn_path.with_name(f"{turn_path.stem}.events.jsonl") - revision = self._event_revision(event_path) - if turn.get("event_compaction_revision") == list(revision or ()): - continue - with exclusive_file_lock(event_path, agent_id="loopx-chat", operation="compact_chat_events"): - rows = self._event_rows_locked(session_id, turn_id) - retained = [row for row in rows if row.get("kind") not in _store.REPLAY_ONLY_EVENT_KINDS] - if len(retained) != len(rows): - _store._replace_jsonl(event_path, retained) - compacted += 1 + event_revisions: dict[str, EventRevision] = {} + turn_entries: list[tuple[Path, int]] = [] + for entry in entries: + name = entry.name + if name.endswith(".events.jsonl"): + with suppress(OSError): + st = entry.stat(follow_symlinks=False) + event_revisions[name[: -len(".events.jsonl")]] = ( + st.st_ino, + st.st_size, + st.st_mtime_ns, + ) + elif name.endswith(".json"): + with suppress(OSError): + st = entry.stat(follow_symlinks=False) + turn_entries.append((Path(entry.path), st.st_size)) + for turn_path, turn_size in turn_entries: + turn_id = turn_path.stem + with self._event_lock: + has_pending = bool(self._event_pending.get((session_id, turn_id))) + if not has_pending and _turn_already_compacted_for_revision( + turn_path, turn_size, event_revisions.get(turn_id) + ): + continue + turn = _store._read_json(turn_path) + if turn.get("status") not in _store.TERMINAL_TURN_STATES: + continue + completed = _store._instant(turn.get("completed_at")) + if completed is None or completed > cutoff: + continue + self.flush_events(session_id, turn_id) + event_path = turn_path.with_name(f"{turn_id}.events.jsonl") revision = self._event_revision(event_path) - self._event_cache.drop((session_id, turn_id)) - with exclusive_file_lock(turn_path, agent_id="loopx-chat", operation="mark_chat_events_compacted"): - current = _store._read_json(turn_path) - if current.get("status") in _store.TERMINAL_TURN_STATES: - current["event_compaction_revision"] = list(revision or ()) - _store._atomic_write_json(turn_path, current, preserve_mode=True) + if turn.get("event_compaction_revision") == list(revision or ()): + continue + with exclusive_file_lock(event_path, agent_id="loopx-chat", operation="compact_chat_events"): + rows = self._event_rows_locked(session_id, turn_id) + retained = [row for row in rows if row.get("kind") not in _store.REPLAY_ONLY_EVENT_KINDS] + if len(retained) != len(rows): + _store._replace_jsonl(event_path, retained) + compacted += 1 + revision = self._event_revision(event_path) + self._event_cache.drop((session_id, turn_id)) + with exclusive_file_lock(turn_path, agent_id="loopx-chat", operation="mark_chat_events_compacted"): + current = _store._read_json(turn_path) + if current.get("status") in _store.TERMINAL_TURN_STATES: + current["event_compaction_revision"] = list(revision or ()) + _store._atomic_write_json(turn_path, current, preserve_mode=True) return compacted + + def start_background_compaction(self) -> None: + """Run startup replay-delta compaction off the critical HTTP readiness path.""" + + def _worker() -> None: + with suppress(OSError): + self.compact_completed_events() + + threading.Thread( + target=_worker, + name="loopx-chat-startup-compaction", + daemon=True, + ).start() + + +class _RecoverableTurnStore(Protocol): + sessions_root: Path + + def finalize_turn_completion(self, session_id: str, turn_id: str) -> object: ... + + +def recover_completing_turns(store: _RecoverableTurnStore) -> None: + """Finalize interrupted ``completing`` turns while skipping terminal payloads.""" + from .. import chat_store as _store + + try: + session_entries = list(os.scandir(store.sessions_root)) + except OSError: + return + for session_entry in session_entries: + if not session_entry.is_dir(follow_symlinks=False): + continue + turns_dir = Path(session_entry.path) / "turns" + try: + turn_entries = list(os.scandir(turns_dir)) + except OSError: + continue + for turn_entry in turn_entries: + if not turn_entry.name.endswith(".json") or turn_entry.name.endswith(".events.jsonl"): + continue + path = Path(turn_entry.path) + peeked = peek_turn_status(path) + if peeked is not None and peeked != "completing": + continue + turn = _store._read_json(path) + if ( + turn.get("schema_version") == _store.CHAT_TURN_SCHEMA_VERSION + and turn.get("status") == "completing" + ): + store.finalize_turn_completion(str(turn["session_id"]), str(turn["turn_id"])) + + +def _json_string_end(text: str, quote_index: int) -> int: + index = quote_index + 1 + length = len(text) + while index < length: + char = text[index] + if char == "\\": + index += 2 + elif char == '"': + return index + 1 + else: + index += 1 + return -1 + + +def peek_turn_status(path: Path, *, max_bytes: int = 1024) -> str | None: + """Decode top-level ``status`` from the JSON prefix without reading multi-MB attachments.""" + try: + fd = os.open(path, os.O_RDONLY) + except OSError: + return None + try: + raw = os.read(fd, max_bytes) + except OSError: + return None + finally: + with suppress(OSError): + os.close(fd) + text = raw.decode("utf-8", errors="ignore") + length = len(text) + index = 0 + while index < length and text[index] in " \t\r\n": + index += 1 + if index >= length or text[index] != "{": + return None + index += 1 + while index < length: + while index < length and text[index] in " \t\r\n": + index += 1 + if index >= length or text[index] != '"': + return None + key_end = _json_string_end(text, index) + if key_end < 0: + return None + try: + key = json.loads(text[index:key_end]) + except json.JSONDecodeError: + return None + index = key_end + while index < length and text[index] in " \t\r\n": + index += 1 + if index >= length or text[index] != ":": + return None + index += 1 + while index < length and text[index] in " \t\r\n": + index += 1 + if index >= length: + return None + char = text[index] + if char == '"': + val_end = _json_string_end(text, index) + if val_end < 0: + return None + try: + value = json.loads(text[index:val_end]) + except json.JSONDecodeError: + return None + index = val_end + if key == "status" and isinstance(value, str): + while index < length and text[index] in " \t\r\n": + index += 1 + return value if index < length and text[index] in ",}" else None + elif text.startswith("null", index) or text.startswith("true", index): + index += 4 + elif text.startswith("false", index): + index += 5 + elif char in "-0123456789": + while index < length and text[index] in "-+0123456789.eE": + index += 1 + if index >= length: + return None + else: + return None + while index < length and text[index] in " \t\r\n": + index += 1 + if index < length and text[index] == ",": + index += 1 + else: + return None + return None + + +def _turn_already_compacted_for_revision( + turn_path: Path, turn_size: int, revision: EventRevision +) -> bool: + """Fast tail check matching compact top-level ``event_compaction_revision``.""" + rev_text = f"{revision[0]},{revision[1]},{revision[2]}" if revision is not None else "" + expected_suffix = f',"event_compaction_revision":[{rev_text}]}}'.encode("ascii") + if turn_size < len(expected_suffix) + 2: + return False + read_len = min(turn_size, max(128, len(expected_suffix) + 16)) + try: + fd = os.open(turn_path, os.O_RDONLY) + except OSError: + return False + try: + os.lseek(fd, max(0, turn_size - read_len), os.SEEK_SET) + tail = os.read(fd, read_len) + except OSError: + return False + finally: + with suppress(OSError): + os.close(fd) + return tail.rstrip().endswith(expected_suffix) diff --git a/loopx/chat_server.py b/loopx/chat_server.py index e75d9e8e2e..753b453b56 100644 --- a/loopx/chat_server.py +++ b/loopx/chat_server.py @@ -1683,7 +1683,7 @@ def serve_chat( for app in list_lark_apps(runner=server.lark_runner, cli_bin=lark_cli_cmd) ), ) - server.chat_store = ChatSessionStore(runtime_root) + server.chat_store = ChatSessionStore(runtime_root, compact_on_init=False) server.action_store = ChatActionStore(runtime_root / "chat" / "actions") from .presentation.request_control_api import bound_steward_inventory_scope from .chat.lark_api import manager_source_scope_resolver @@ -1762,8 +1762,7 @@ def _wake_goal_context(session: dict[str, object]) -> dict[str, object]: server.delegation_wake_service = DelegationWakeService( server.runtime_controller, goal_context=_wake_goal_context ).start() - # Resume only retained, explicitly confirmed creation requests through the - # existing Session queue. Its owner rechecks source, native work and gates. + # Resume confirmed creation requests via Session queue (rechecking gates). server.runtime_controller.resume_creation_requests() url = f"http://{host}:{port}{DEFAULT_CHAT_PATH}" print(f"Serving LoopX Chat at {url}", flush=True) @@ -1781,6 +1780,7 @@ def _wake_goal_context(session: dict[str, object]) -> dict[str, object]: server.conversation_transports.start(server) background_api.register_chat_background_services(server) server.background_services.start() + server.chat_store.start_background_compaction() server.serve_forever() except KeyboardInterrupt: print("Stopping LoopX Chat", flush=True) diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 9caedfc0ff..4530e44993 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -25,7 +25,7 @@ MODEL_SELECTION_UNSET as _MODEL_SELECTION_UNSET, normalize_agent_model_id as normalize_agent_model_id, normalize_session_model_settings, session_model_settings_supported, normalize_session_model_changes, ) -from .chat.event_cache import ChatEventCache, ChatEventStreamMixin +from .chat.event_cache import ChatEventCache, ChatEventStreamMixin, recover_completing_turns from .chat.journal import CachedJournalRows, decode_chat_journal from .chat.ingress import ( ChatIngressStore, @@ -201,7 +201,7 @@ def _replace_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: class ChatSessionStore(ChatEventStreamMixin, ChatIngressStore): """Filesystem store kept outside project and public LoopX run history.""" - def __init__(self, runtime_root: Path, *, startup_maintenance: bool = True) -> None: + def __init__(self, runtime_root: Path, *, startup_maintenance: bool = True, compact_on_init: bool = True) -> None: self.root = runtime_root.expanduser().resolve() / "chat" self.sessions_root = self.root / "sessions" self._session_lock_guard = threading.Lock() @@ -215,10 +215,10 @@ def __init__(self, runtime_root: Path, *, startup_maintenance: bool = True) -> N self.sessions_root.mkdir(parents=True, exist_ok=True, mode=0o700) os.chmod(self.root, 0o700) os.chmod(self.sessions_root, 0o700) - # A scoped lifecycle repair must not compact unrelated history or finish - # other pending completions merely by opening their data owner. + # Scoped repairs open the data owner without mutating unrelated history. if startup_maintenance: - self.compact_completed_events() + if compact_on_init: + self.compact_completed_events() self._recover_turn_completions() def _session_dir(self, session_id: str) -> Path: @@ -1466,11 +1466,7 @@ def finalize_turn_completion( return self.finalize_managed_turn_completion(session_id, turn_id) def _recover_turn_completions(self) -> None: - # ponytail: owner-local startup scan; add an index only if history makes it measurable. - for path in self.sessions_root.glob("*/turns/*.json"): - turn = _read_json(path) - if turn.get("schema_version") == CHAT_TURN_SCHEMA_VERSION and turn.get("status") == "completing": - self.finalize_turn_completion(str(turn["session_id"]), str(turn["turn_id"])) + recover_completing_turns(self) def finalize_attached_turn_completion( self, diff --git a/scripts/macos-dashboard-launchagent.sh b/scripts/macos-dashboard-launchagent.sh index 01a83a92d5..51085e8006 100755 --- a/scripts/macos-dashboard-launchagent.sh +++ b/scripts/macos-dashboard-launchagent.sh @@ -482,6 +482,8 @@ write_plists() { KeepAlive + ProcessType + Interactive ThrottleInterval 10 StandardOutPath @@ -529,6 +531,8 @@ EOF KeepAlive + ProcessType + Interactive ThrottleInterval 10 StandardOutPath diff --git a/tests/test_chat_startup_scale.py b/tests/test_chat_startup_scale.py new file mode 100644 index 0000000000..d08dc15cd9 --- /dev/null +++ b/tests/test_chat_startup_scale.py @@ -0,0 +1,170 @@ +"""Scale and equivalence regression tests for ChatSessionStore startup maintenance.""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +import json +from pathlib import Path +from unittest import mock + +import loopx.chat_store as chat_store_mod +from loopx.chat.event_cache import peek_turn_status as _peek_turn_status +from loopx.chat_store import ( + CHAT_TURN_SCHEMA_VERSION, + ChatSessionStore, + _atomic_write_json, +) + + +def _old_iso(hours: float = 48.0) -> str: + return (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat().replace("+00:00", "Z") + + +def test_startup_maintenance_skips_full_reads_on_compacted_terminal_turns(tmp_path: Path) -> None: + store = ChatSessionStore(tmp_path) + session = store.create_session( + goal_id="loopx-manager", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id="thread-scale", + channel_id="manager", + ) + sid = session["session_id"] + old_completed_at = _old_iso(48.0) + large_blob = "x" * 16384 + + compacted_ids: list[str] = [] + for idx in range(60): + turn, _ = store.create_turn(sid, client_turn_id=f"c-{idx}", message=large_blob) + tid = turn["turn_id"] + compacted_ids.append(tid) + store.append_event(sid, tid, kind="assistant.delta", payload={"text": "chunk"}) + store.append_event(sid, tid, kind="turn.completed", payload={"ok": True}) + store.release_active_turn(sid, tid, last_activity_at=old_completed_at, last_error_code=None) + turn_path = store.sessions_root / sid / "turns" / f"{tid}.json" + doc = json.loads(turn_path.read_text(encoding="utf-8")) + doc["status"] = "completed" + doc["completed_at"] = old_completed_at + _atomic_write_json(turn_path, doc, preserve_mode=True) + + assert store.compact_completed_events(older_than_hours=24.0) == 60 + + # Add 1) an uncompacted old turn, 2) a nested-dict lookalike tail, + # 3) a standard completing turn, 4) a custom-key-order completing turn, + # and 5) a unicode-escaped completing turn. + uncompacted, _ = store.create_turn(sid, client_turn_id="uncomp", message=large_blob) + uncomp_id = uncompacted["turn_id"] + store.append_event(sid, uncomp_id, kind="assistant.delta", payload={"text": "delta"}) + store.append_event(sid, uncomp_id, kind="turn.completed", payload={"ok": True}) + store.release_active_turn(sid, uncomp_id, last_activity_at=old_completed_at, last_error_code=None) + uncomp_path = store.sessions_root / sid / "turns" / f"{uncomp_id}.json" + uncomp_doc = json.loads(uncomp_path.read_text(encoding="utf-8")) + uncomp_doc["status"] = "completed" + uncomp_doc["completed_at"] = old_completed_at + _atomic_write_json(uncomp_path, uncomp_doc, preserve_mode=True) + + nested, _ = store.create_turn(sid, client_turn_id="nested", message=large_blob) + nested_id = nested["turn_id"] + store.append_event(sid, nested_id, kind="assistant.delta", payload={"text": "delta"}) + store.append_event(sid, nested_id, kind="turn.completed", payload={"ok": True}) + store.release_active_turn(sid, nested_id, last_activity_at=old_completed_at, last_error_code=None) + nested_path = store.sessions_root / sid / "turns" / f"{nested_id}.json" + nested_event_stat = nested_path.with_name(f"{nested_id}.events.jsonl").stat() + nested_doc = json.loads(nested_path.read_text(encoding="utf-8")) + nested_doc["status"] = "completed" + nested_doc["completed_at"] = old_completed_at + nested_doc.pop("event_compaction_revision", None) + nested_doc["nested_lookalike"] = { + "x": 1, + "event_compaction_revision": [ + nested_event_stat.st_ino, + nested_event_stat.st_size, + nested_event_stat.st_mtime_ns, + ], + } + _atomic_write_json(nested_path, nested_doc, preserve_mode=True) + + completing_std, _ = store.create_turn(sid, client_turn_id="comp-std", message="hi") + comp_std_id = completing_std["turn_id"] + store.release_active_turn(sid, comp_std_id, last_activity_at=old_completed_at, last_error_code=None) + comp_std_path = store.sessions_root / sid / "turns" / f"{comp_std_id}.json" + comp_std_doc = json.loads(comp_std_path.read_text(encoding="utf-8")) + comp_std_doc["status"] = "completing" + comp_std_doc["response"] = {"message": "recovered-standard"} + _atomic_write_json(comp_std_path, comp_std_doc, preserve_mode=True) + + completing_reordered, _ = store.create_turn(sid, client_turn_id="comp-reord", message="hi") + comp_reord_id = completing_reordered["turn_id"] + store.release_active_turn(sid, comp_reord_id, last_activity_at=old_completed_at, last_error_code=None) + comp_reord_path = store.sessions_root / sid / "turns" / f"{comp_reord_id}.json" + reord_doc = { + "attachments": [{"data": large_blob}], + "schema_version": CHAT_TURN_SCHEMA_VERSION, + "turn_id": comp_reord_id, + "session_id": sid, + "status": "completing", + "response": {"message": "recovered-reordered"}, + "completed_at": old_completed_at, + } + _atomic_write_json(comp_reord_path, reord_doc, preserve_mode=True) + assert _peek_turn_status(comp_reord_path) is None + + completing_escaped, _ = store.create_turn(sid, client_turn_id="comp-esc", message="hi") + comp_esc_id = completing_escaped["turn_id"] + store.release_active_turn(sid, comp_esc_id, last_activity_at=old_completed_at, last_error_code=None) + comp_esc_path = store.sessions_root / sid / "turns" / f"{comp_esc_id}.json" + esc_doc = json.loads(comp_esc_path.read_text(encoding="utf-8")) + esc_doc["status"] = "completing" + esc_doc["response"] = {"message": "recovered-escaped"} + raw_esc = json.dumps(esc_doc, separators=(",", ":")).replace('"completing"', '"\\u0063ompleting"') + comp_esc_path.write_text(raw_esc, encoding="utf-8") + assert _peek_turn_status(comp_esc_path) == "completing" + + read_paths: list[str] = [] + original_read_json = chat_store_mod._read_json + + def tracking_read_json(path: Path) -> dict[str, object]: + read_paths.append(path.stem) + return original_read_json(path) + + with mock.patch.object(chat_store_mod, "_read_json", side_effect=tracking_read_json): + reopened = ChatSessionStore(tmp_path) + + compacted_set = set(compacted_ids) + assert compacted_set.isdisjoint(read_paths), f"expected 0 full JSON reads on compacted turns, got {compacted_set & set(read_paths)}" + assert (reopened.load_turn(sid, comp_std_id) or {}).get("status") == "completed" + assert (reopened.load_turn(sid, comp_reord_id) or {}).get("status") == "completed" + assert (reopened.load_turn(sid, comp_esc_id) or {}).get("status") == "completed" + messages_text = [m["text"] for m in reopened.messages(sid) if m["role"] == "agent"] + assert {"recovered-standard", "recovered-reordered", "recovered-escaped"} <= set(messages_text) + assert all( + row["kind"] != "assistant.delta" + for tid in (uncomp_id, nested_id) + for row in reopened.events_after(sid, tid, None) + ) + + +def test_compact_on_init_false_recovers_completions_without_blocking_on_compaction(tmp_path: Path) -> None: + store = ChatSessionStore(tmp_path) + session = store.create_session( + goal_id="loopx-manager", + agent_id="codex", + adapter_kind="codex_app_server", + upstream_thread_id="thread-defer", + channel_id="manager", + ) + sid = session["session_id"] + turn, _ = store.create_turn(sid, client_turn_id="c-1", message="hello") + tid = turn["turn_id"] + old_completed_at = _old_iso(48.0) + store.release_active_turn(sid, tid, last_activity_at=old_completed_at, last_error_code=None) + turn_path = store.sessions_root / sid / "turns" / f"{tid}.json" + doc = json.loads(turn_path.read_text(encoding="utf-8")) + doc["status"] = "completing" + doc["response"] = {"message": "done-fast"} + _atomic_write_json(turn_path, doc, preserve_mode=True) + + with mock.patch.object(ChatSessionStore, "compact_completed_events", side_effect=AssertionError("must not run synchronously")): + fast_store = ChatSessionStore(tmp_path, compact_on_init=False) + + assert (fast_store.load_turn(sid, tid) or {}).get("status") == "completed"