Skip to content

fix(chat): eliminate O(turns) startup double-scan and speculative launchd stall - #9500

Merged
loopx-agent merged 1 commit into
mainfrom
codex/fix-chat-startup-activation-20261127
Nov 26, 2026
Merged

loopx-agent merged 1 commit into
mainfrom
codex/fix-chat-startup-activation-20261127

Conversation

@loopx-agent

Copy link
Copy Markdown
Collaborator

Summary

Fixes deterministic service_runtime_alignment_failed (90s HTTP readiness timeout + rollback) during loopx upgrade / loopx update activate on hosts with multi-thousand historical Chat turns and large attachment payloads.

Root Cause

  1. O(2 * total_turns) full-file JSON double-scan in ChatSessionStore.__init__ before serve_forever():
    • Every ChatSessionStore initialization synchronously executed compact_completed_events() followed by _recover_turn_completions(), opening and json.loads()-parsing every */turns/*.json file twice (e.g., 2,811 turns = 201.8 MiB × 2 = 403.6 MiB / 6.01s CPU) before serve_chat() entered server.serve_forever().
  2. macOS launchd default background throttling (immediate reason = speculative / PRIO_DARWIN_BG):
    • scripts/macos-dashboard-launchagent.sh omitted <key>ProcessType</key><string>Interactive</string> on com.loopx.status and com.loopx.chat. Under launchctl bootstrap, macOS throttled com.loopx.chat startup CPU to ~0.033s/s, stretching ~7.3s of startup CPU to ~218s wall time and deterministically exceeding _SERVICE_READINESS_TIMEOUT_SECONDS = 90.0 in align_managed_runtime().

Changes

  • loopx/chat_store.py:
    • Add _peek_turn_status() using json.decoder.scanstring over the first 1 KB top-level JSON object prefix so _recover_turn_completions() skips multi-MB message/attachments decoding on terminal turns (100% fast-path hit rate on compacted history, with lossless full _read_json() fallback for reordered keys, nested values, or "completing" turns).
    • Add compact_on_init: bool = True to ChatSessionStore.__init__ (preserving synchronous compaction by default for direct store callers while allowing serve_chat() to defer replay-delta compaction off the pre-readiness socket path).
  • loopx/chat/event_cache.py:
    • Use os.scandir and _turn_already_compacted_for_revision() (128-byte top-level ,"event_compaction_revision":[...]} tail check) in compact_completed_events() to skip full JSON reads on already-compacted historical turns (6.01s CPU -> 0.19s CPU across 2,811 turns / 817 MiB).
  • loopx/chat_server.py:
    • Pass compact_on_init=False in serve_chat() so _recover_turn_completions() still completes synchronously before HTTP readiness (~0.05s CPU), and run compact_completed_events() in a background daemon thread once serve_forever() starts.
  • scripts/macos-dashboard-launchagent.sh:
    • Declare <key>ProcessType</key><string>Interactive</string> on com.loopx.status and com.loopx.chat LaunchAgent plists.
  • tests/test_chat_startup_scale.py:
    • Add scale and equivalence regression coverage (compacted turn skip verification, nested-dict suffix lookalike defense, standard/reordered/escaped "completing" recovery, and compact_on_init=False behavior).

Verification

  • pytest -q tests/test_chat_startup_scale.py tests/test_steward_history_scale.py tests/test_chat_runtime_activation.py tests/test_managed_service_runtime.py tests/test_dashboard_command.py
  • python examples/macos-dashboard-launchagent-status-smoke.py
  • ruff check & mypy
  • loopx canary premerge --from-git-diff --git-diff-base origin/main

…nchd stall

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>

@loopx-agent loopx-agent left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer: model_agent · Gemini · Google · self_reported

Approval conclusion (author-owned PR; GitHub blocks formal self-approval)

Reviewed exact head: 1bd68dd2dec89945251974058f4f624adfdab5fc (base ddcfca586a0393ac952a3fa7ca29850d979dc6da).

动机 / Motivation

在长期积累数千条历史对话回合的机器上执行 loopx upgrade 或 loopx update activate 切换托管服务的操作者与本地 Chat 启动路径。 修复前,每次启动或升级重启本地 Chat 服务时,存储初始化都会在进入 HTTP 监听循环前把全部历史回合 JSON 完整读取并解析两遍,叠加 macOS LaunchAgent 缺少交互进程类型导致的后台限流,启动耗时超过 90 秒就绪窗口并触发自动回滚;修复后,终态已压缩回合仅读取首尾极小字节片段即可跳过全量解析,且历史事件压缩移至监听就绪后的后台线程执行,服务可在数秒内通过就绪探针。 已压缩终态回合在重启时不再触发全量 JSON 解析,中断的收尾中回合仍会在对外提供 HTTP 服务前同步完成恢复,且新生成的 macOS LaunchAgent 配置显式声明交互式调度优先级。 本 PR 不改变回合与事件文件的磁盘 JSON 格式、不跳过收尾中回合的启动同步恢复,也不在托管服务对齐逻辑中强行改写用户自定义 LaunchAgent 键。

在真实长周期环境中,随着管家和项目对话积累数千个回合文件(尤其是包含大体积内联图片附件的 turns/*.json,总计可达数百 MiB),ChatSessionStore.__init__ 先后串行执行 compact_completed_events() 与 _recover_turn_completions(),把每一个历史回合完整读入内存并做两次 json.loads()。当 align_managed_runtime 通过 launchctl bootstrap 重启 com.loopx.chat 时,由于默认 plist 未指定 ProcessType,macOS launchd 以 speculative 后台限流模式运行进程(CPU 配额约 3%),6 秒 以上的 JSON 解析 CPU 开销被拉长到 218 秒 真实挂钟时间,必然超过 _verify_services 的 90 秒 就绪探针上限并导致每次升级自动回滚。

改动思路 / Approach

回合状态前缀快速探测、事件压缩尾部版本比对与后台压缩线程均内聚在既有的 ChatSessionStore / ChatEventStreamMixin 存储边界内,LaunchAgent 交互优先级声明落在既有安装脚本边界内,既未引入额外索引文件破坏目录哈希不变量,也未在托管对齐器中越权改写外部 plist 键,因此保持当前边界。 当前 PR 边界限定在 Chat 存储启动恢复与压缩扫描优化、serve_chat 压缩后台化及默认 LaunchAgent 模板的 ProcessType 声明,不修改托管运行时对齐协议或回合持久化 schema。

下表对比了基准提交 ddcfca586a 与当前精确提交 1bd68dd2de 在服务启动与升级切换路径上的行为差异(说明性对比与实测回执):

阶段 / Stage 基准行为 (ddcfca586a) 当前行为 (1bd68dd2de) 关键不变量 / Invariant
收尾回合恢复 (_recover_turn_completions) glob 遍历并对每个 turn.json 全量 _read_json os.scandir + peek_turn_status 仅读前 1,024 字节顶层原语字段;非 completing 直接跳过 遇到前置数组/对象、截断或 status == "completing" 时完整回退 _read_json 并同步恢复
历史事件压缩 (compact_completed_events) 每次全量读取 turn.json 后再比对 event_compaction_revision 同次 scandir 获取 .events.jsonl 的 stat 三元组,读取 turn.json 末尾 128 字节匹配顶层后缀 仅当无内存待刷事件且匹配单右花括号 ]} 根结尾时跳过;嵌套伪造字段仍走全量解析
serve_chat 启动顺序 同步等待全量压缩完成才进入 serve_forever() compact_on_init=False 先同步完成恢复并监听就绪,再由 start_background_compaction 后台压缩 /api/chat/readiness 就绪前所有中断的 completing 回合均已完成收尾发布
macOS LaunchAgent 模板 未设置 ProcessType,bootstrap 落入后台限流 macos-dashboard-launchagent.sh 为 status 与 chat 写入 ProcessType=Interactive 保持 _retarget 对既有外部 plist 非路径键的原样保留契约不变

仓库内无独立书面 RFC 规定存储内部启动扫描实现,行为契约由 tests/test_chat_runtime_activation.py(包括作用域恢复不改动目录内容哈希)与 tests/test_lark_private_conversations.py 约束。

具体改动 / Changes

关键代码讲解

  1. loopx/chat/event_cache.py(peek_turn_status、recover_completing_turns):新增顶层 JSON 前缀扫描函数 peek_turn_status,仅读取文件头部 1,024 字节,通过 _json_string_end 与标准库 json.loads 严格解析顶层原语键值(天然支持 \uXXXX 转义),在触及大体积 message 与 attachments 之前拿到顶层 status。一旦在 status 之前遇到嵌套 { 或 [(如自定义键序)或截断,立即返回 None 并由 recover_completing_turns 回退到完整 _read_json。
  2. loopx/chat/event_cache.py(compact_completed_events、_turn_already_compacted_for_revision、start_background_compaction):使用 os.scandir 在单次目录遍历中收集 *.events.jsonl 的 (st_ino, st_size, st_mtime_ns) 版本三元组与 *.json 大小;当内存 _event_pending 无待刷事件时,读取 turn.json 尾部 128 字节检查是否以 ,"event_compaction_revision":[ino,size,mtime]} 结尾,从而对已压缩历史回合实现零 JSON 反序列化跳过,并提供守护线程包装 start_background_compaction。
  3. loopx/chat_store.py(ChatSessionStore.__init__、_recover_turn_completions)与 loopx/chat_server.py(serve_chat):ChatSessionStore.__init__ 新增关键字参数 compact_on_init: bool = True(直接调用方默认行为完全不变),serve_chat 传入 compact_on_init=False 并在 background_services.start() 后启动后台压缩线程,同时将 chat_store.py 行数从 1706 压降至 1702、chat_server.py 维持 1788 行不变。
  4. scripts/macos-dashboard-launchagent.sh(write_plists)与 tests/test_chat_startup_scale.py:在 status 与 chat 两个 LaunchAgent 模板中补充 <key>ProcessType</key><string>Interactive</string>;新增回归测试覆盖 60 个已压缩回合零全量读取、嵌套同名字段防误判、标准/乱序/Unicode 转义三类 completing 回合恢复以及 compact_on_init=False 行为。

对主干的风险 / Risks

  1. 前缀或尾部快速跳过误判风险:若某个异常格式回合文件被错误跳过,可能导致 completing 回合未恢复或旧流式增量事件未压缩。peek_turn_status 仅在深度为 1 的原语字段链上推进,遇到数组或对象立即回退 _read_json;_turn_already_compacted_for_revision 要求前导逗号与单一根对象右花括号 ]}(任何嵌套字典都会以 ]}} 结尾而返回 False)。回归测试已对上述对抗样本逐一验证。
  2. 后台压缩与在线读取并发竞争风险:serve_chat 启动后后台线程执行 compact_completed_events() 时,可能与客户端 events_after() 并发访问同一回合事件文件。既有实现已通过 exclusive_file_lock(event_path)、exclusive_file_lock(turn_path) 与 self._event_cache.drop 保证并发互斥与缓存一致性。
  3. 存量 plist 未重装时的升级兼容性:存量机器上的 com.loopx.chat.plist 在重新执行安装脚本前仍不含 ProcessType,但由于存储启动预热 CPU 已从 6.01 秒 降至约 0.05 秒,即使在 launchd 后台限流下也能在 90 秒 窗口内完成就绪校验。
  4. 验证矩阵(Validation Matrix):
    • changed_invariant_positive: PASS — pytest -q tests/test_chat_startup_scale.py tests/test_chat_runtime_activation.py tests/test_managed_service_runtime.py(109 passed, 1 skipped),且基线/当前同输入探针(fixture SHA-256 02ec9fcdbd2eec6d...)验证 40 个已压缩回合重开时全量读取次数由 80 降至 0。
    • material_negative_or_failure: PASS — pytest -q tests/test_dashboard_command.py(与规模测试合计 45 passed)及 python examples/macos-dashboard-launchagent-status-smoke.py(ok),确认嵌套字段伪造、乱序键恢复与作用域目录哈希不变性全部保持。
    • repository_required_checks: PASS — ruff check、mypy --follow-imports=silent(0 错误,使用 _RecoverableTurnStore Protocol 零新增 Any)、loopx check(5 个文件 0 错误 0 警告)及 loopx canary premerge --from-git-diff --git-diff-base origin/main(8/8 检查全部通过,wait_for_ci=false)。

我的整体评价 / Verdict

从长程运行(long_horizon)看,本改动消除了历史回合数随时间增长后每次服务重启都要重扫数百 MiB JSON 的线性退化,确保长周期管家会话环境下的自动升级持续可用;从用户体验(user_experience)看,loopx upgrade 与 loopx update activate 不再因 90 秒 就绪探针超时而回滚失败。视觉审查结论:本次改动仅涉及后端 ChatSessionStore 启动扫描、后台事件压缩调度与 macOS LaunchAgent plist 配置脚本(loopx/chat/event_cache.py、loopx/chat_store.py、loopx/chat_server.py、scripts/macos-dashboard-launchagent.sh),未修改任何前端组件、样式或渲染输出。 未覆盖范围:无前端视觉展示变更(none)。 代码体量紧凑且完全复用既有 event_compaction_revision 字段而不引入额外索引文件,未触及任何注册表或公开语义词表,语义对齐判定为 not_applicable。因本 PR 为作者自有分支(GitHub 禁止自批 APPROVE),按仓库策略以 COMMENTED 形式发布等效批准结论。

English verdict: APPROVE at exact head 1bd68dd2dec89945251974058f4f624adfdab5fc; eliminates O(2 * turns) full-file JSON startup scans and speculative launchd throttling while preserving exact completing-turn recovery and event compaction invariants (109 + 45 pytest cases, launchagent smoke, and loopx canary premerge PASS).

@loopx-agent
loopx-agent merged commit 50b4cc9 into main Nov 26, 2026
9 of 11 checks passed
@loopx-agent
loopx-agent deleted the codex/fix-chat-startup-activation-20261127 branch November 26, 2026 17:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant