Skip to content

refactor(chat): slim chat_runtime below 1,500 lines, fix entry-point project_contexts guard, and retire ceiling - #8920

Merged
loopx-agent merged 2 commits into
mainfrom
codex/chat-runtime-slim-20261117
Nov 19, 2026
Merged

loopx-agent merged 2 commits into
mainfrom
codex/chat-runtime-slim-20261117

Conversation

@loopx-agent

@loopx-agent loopx-agent commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Goal / Gap: Retire the 2,524-line baseline exception on loopx/chat_runtime.py (currently 2,497 lines on main, any_count=38) and bring it cleanly below 1,500 lines while tightening its any_count ratchet and reducing net lines across the Chat runtime/lifecycle boundary. Also fix an entry-point AttributeError in open_chat_session on minimal HTTP test/entry controllers that do not define project_contexts, and fix the [P2] Thread.start() failure concurrent-retry race in _start_accepted_turn_worker / submit_turn.
  • Changes:
    • Extract ChatSessionLifecycleMixin (_resolve_manager_channel, _start_acp_adapter, _start_adapter, open_session, _ensure_adapter, _ensure_adapter_locked, close_session, resume_session) into internal module loopx/chat/session_open.py (240 -> 1,249 lines), adding internal deduplication helper _supports_live_model_id while routing operator_credential_resolution, operator_credential_pair, DshChatAdapter, manager_session_model_allocation, manager_session_quota_route, and _steward_dsh_model_config through loopx.chat_runtime so test monkeypatch hooks and production manager_model_config(..., machine_defaults=...) caller checks remain intact.
    • Guard getattr(controller, "project_contexts", None) in open_chat_session (loopx/chat/session_open.py) so minimal entry-point controllers without project_contexts route through open_manager_session instead of failing with AttributeError.
    • Have ChatRuntimeController inherit ChatSessionLifecycleMixin in loopx/chat_runtime.py (2,497 -> 1,465 lines, any_count: 38 -> 29, dict_any_count=0), deduplicating _load_open_session, _validate_project_session, _drop_owned_adapter, _release_done_event, and _steer_active_turn's local fail_ingress helper while preserving all main fixes (commit_steward_memory_after_turn, record_owner_resume, steward model adoption/resume).
    • Fix _start_accepted_turn_worker to pass drop_before_notify=True to _release_done_event on worker.start() failure (removing (session_id, turn_id) from turn_done_events under self.lock before calling done_event.set() / turn_release_wakeup.notify()), guard _drop_owned_adapter in submit_turn when a concurrent retry already owns a live worker, and add deterministic interleaving test test_thread_start_failure_drops_done_event_before_notifying_concurrent_retry in tests/test_chat_session_active_turn.py.
    • Update loopx/canary/module_metric_baseline.json to remove "lines": 2524 from "loopx/chat_runtime.py" and tighten "any_count" from 38 to 29.
  • Owning Boundary & Rollback: Python Chat runtime/session-lifecycle internal organization (loopx/chat_runtime.py + loopx/chat/session_open.py + baseline ledger + unit regression test); no public API shim added and no TypeScript control-plane contract changed.

Verification

Exact rebased HEAD 9a88b14bd2b618f162ab3a86a21454dc6cccfae2 (on origin/main 6e1a0bd9e7):

  • ruff check loopx/chat_runtime.py loopx/chat/session_open.py tests/test_chat_session_active_turn.py -> All checks passed!
  • mypy (repo [tool.mypy], 17 files): fails identically to origin/main (6e1a0bd9e7) solely on untouched pre-existing loopx/control_plane/work_items/interaction_contract.py:1004 (exit_code=1); mypy --strict --follow-imports=silent on changed .py files introduces 0 errors in moved close_session/resume_session (pre-existing mixin/test strict annotations remain).
  • npm run -s typecheck:control-plane -> passed
  • Targeted pytest across 22 Chat, session lifecycle, maintainability ratchet, and top-level budget suites (tests/test_chat_session_active_turn.py, tests/canary/test_maintainability_ratchet.py, tests/architecture/test_top_level_module_budget.py, tests/test_chat_internal_module_layout.py, tests/test_chat_executor_profile.py, tests/test_manager_channel_binding.py, tests/test_chat_manager_model_adoption.py, tests/test_chat_codex_history.py, tests/test_chat_turn_wait.py, tests/test_chat_process_recovery.py, tests/test_chat_turn_steering.py, tests/test_chat_ordinary_project.py, tests/test_chat_codex_defaults.py, tests/test_chat_codex_goal.py, tests/test_chat_runtime_preparation_recovery.py, tests/test_chat_queue_preparation.py, tests/test_chat_agent.py, tests/control_plane/test_goal_create_session.py, tests/control_plane/test_new_goal_storage_defaults.py, tests/control_plane/test_chat_task_start_recovery.py, tests/test_native_steward_monitor.py, tests/test_antigravity_steward_adapter.py) -> 1,444 passed in 1038.52s (0 failed, 0 skipped).
  • pytest tests/test_chat_session_active_turn.py -q -> 63 passed in 15.02s; test_thread_start_failure_drops_done_event_before_notifying_concurrent_retry -v -> 1 passed in 1.04s.
  • scripts/check_rfc_bilingual.py --base origin/main --head HEAD -> passed
  • git diff --check origin/main...HEAD -> passed
  • loopx check --scan-path on all 4 changed files -> errors: 0, warnings: 0
  • loopx change-quality verify -> receipt_valid: true (cqr_d2839ea1cd63e1077df9)
  • loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main --goal-id personal-loopx-maintenance -> merge_gate_passed: true, direct_failure_count: 0, failure_count: 0 (control-plane-maintainability-ratchet-smoke.py, semantic-vocabulary-drift-smoke.py, catalog-planner-smoke.py all passed); examples/loopx-chat-runtime-smoke.py -> ok

@mergify

mergify Bot commented Nov 18, 2026

Copy link
Copy Markdown

This pull request has merge conflicts with main and cannot be merged
until they are resolved. Please rebase or merge the base branch, @loopx-agent.

Choose the remote for the base repository, not an out-of-date fork.
For a fork clone, first inspect git remote -v; upstream must point
to https://github.com/loopx-project/loopx.git. If it is absent, add it
with git remote add upstream https://github.com/loopx-project/loopx.git.
Then run:

git fetch upstream
git rebase upstream/main
# Resolve each conflict, git add the resolved files, then git rebase --continue.
git push --force-with-lease origin HEAD

For a same-repository clone whose origin points to
https://github.com/loopx-project/loopx.git, use origin instead of
upstream for fetch/rebase. If you prefer merging the base, use
git merge <base-remote>/main and push normally.

Keep the DCO Signed-off-by trailer on every commit when you rebase.
https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify Bot added the needs-rebase Mergify: the pull request has merge conflicts with its base branch label Nov 18, 2026

@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 · gpt-6.2-sol · OpenAI (runtime_reported, max)

Request changes conclusion (author-owned PR; GitHub blocks formal self-review)

[P2] 工作线程启动失败后,并发重试可能让消息滞留在队列。 _start_accepted_turn_worker 把 turn_done_events 中的条目视为已有 worker。异常分支现在先设置完成事件并通知,再删除条目。第二次提交在此期间会返回同一 Turn,却跳过启动。在 Thread.start() 异常分支持锁移除该线程自己的 Event,再唤醒等待者。增加覆盖通知与清理交错的重试测试,断言重试完成原 Turn 且 transport 仅调用一次。 异常分支

动机 / Motivation

通过聊天入口发送消息后遭遇本地线程启动失败的用户,需要用同一请求标识重试既有消息。
旧提交在通知完成之前释放失败的工作线程占位,重试可以接手已入队的消息并生成回复。当前提交把这两步的顺序倒转,同一条消息可能停留在排队状态。
此次重构应缩小聊天运行时和会话生命周期的维护范围,同时保留同一请求可重试且只执行一次的行为。
评审范围是现有会话、适配器和消息投递的重构,发布或调整聊天界面属于另一个交付范围。

改动思路 / Approach

ChatRuntimeController 仍接纳请求并拥有本地 worker。持久化会话存储保留已接纳的 Turn,同进程的事件表负责避免重复调度。PR 把会话创建、适配器初始化及 owner 恢复搬到 ChatSessionLifecycleMixin,复用已有 session store 与适配器锁。把相同会话决策放在一个模块能减轻主控制器的维护压力。启动失败时,释放本地派发占位和通知等待者的先后顺序属于同一个恢复约束,适合保留在派发边界。

具体改动 / Changes

关键代码讲解

  • ChatSessionLifecycleMixin.open_session 汇集主控制器原有的会话入口。项目上下文、会话范围和选择运行适配器仍沿用原路径,独立 HTTP 入口测试在当前提交验证了默认客户端无法选择 steward executor。
  • ChatSessionLifecycleMixin._ensure_adapter_locked 接管启动和恢复时的适配器决策。它沿用现有适配器缓存、锁和会话状态,普通聊天、托管会话和已有会话的路由仍在这个边界内判断。
  • ChatRuntimeController._start_accepted_turn_worker 注册完成事件后启动线程。_release_done_event 统一终结及唤醒动作。正常终态清理和线程尚未启动时的错误恢复需要各自满足调用方时序。
  • 主控制器另收敛了打开已有会话、检查项目会话以及移除当前 owner 对应适配器的分支。模块预算同步移除了旧的 chat_runtime.py 行数例外。三文件净减 64 行,主要变动是生命周期提取。

验收依据为基础提交 6bbdeb58715bafaa0eb54fedcbcc7fa51324bd93 上的 docs/development/testing-and-quality.md。其中“真实路径等价”未满足,线程启动失败时已接纳消息无法靠一次并发重试继续。“有意行为变更的验证”在 HTTP 会话入口上有覆盖,基线上的旧最小 controller 走到 HTTP 400,当前提交通过同一测试。该测试约束了默认请求方的 executor 选择。 重构真实路径要求

对主干的风险 / Risks

语义与 CI 对齐

已接纳的 Turn 依靠同一 client_turn_id 实现重试和去重。用真实会话存储、普通聊天入口和可控的启动故障验证了两个线程交错的边界。重跑方法是在临时 File 存储里注入一次 Thread.start() 异常,将首个调用停在发出完成通知之后,再并发重放同一请求。只有启动故障和时间点由测试控制,transport 用计数替身读取调用次数。

重试时机 基线 当前提交
失败清理仍在进行 原 Turn 完成,transport 调用 1 次 原 Turn 保持 queued,仅见 turn.queued,transport 调用 0 次
失败清理完成后 原 Turn 完成,transport 调用 1 次 原 Turn 完成,transport 调用 1 次

最小修复是让启动异常先在锁内移除该 worker 的占位,再发通知。回归测试应将第二次提交放在上述时机,同时校验普通同键重试的去重结果。HTTP 路由测试和两个同进程去重测试通过,Ruff、mypy 和模块预算检查通过。完整 premerge 缺少可确认的终态。基于主干 4a0188c1ca1b6e33a11a7e31ddb56315bc1cdd46 的合并模拟还在 loopx/chat_runtime.py 发生冲突。

我的整体评价 / Verdict

生命周期提取复用了既有的会话和权限边界,历史状态无需迁移。已验证的失败窗口会让一个已接纳 Turn 失去持续推进的 worker,且调用方重试后仍只看到排队。正向路径中的维护收益可以保留,恢复分支需要局部修复并在新提交复核。此次检查覆盖本地 HTTP 和持久化聊天状态,实时模型、打包环境及完整 CI 留待验证。

English verdict: REQUEST_CHANGES at 3bf4f93. Concurrent replay can strand an accepted turn after thread startup fails. Release its reservation before waking waiters, then verify recovery and exactly-once dispatch.

Comment thread loopx/chat_runtime.py Resolved
@loopx-agent
loopx-agent force-pushed the codex/chat-runtime-slim-20261117 branch from 3bf4f93 to 5ef9f48 Compare November 18, 2026 18:41
@mergify mergify Bot removed the needs-rebase Mergify: the pull request has merge conflicts with its base branch label Nov 18, 2026

@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: 8920@5ef9f48fdd44f12036c9ce87abe4e327a67d3053

动机 / Motivation

负责发起与恢复本地对话的 Chat 运行时维护者,以及在工作线程启动失败后用同一请求标识重试发送的调用方。
此前 loopx/chat_runtime.py 体积达 2,415 行且依赖 2,524 行基线例外,最小入口 controller 缺少 project_contexts 属性时会在 open_chat_session 触发 AttributeError,且重构稿将 _start_accepted_turn_worker 的启动异常并入先通知再删占位的释放顺序会导致并发同键重试停留在 queued。当前提交把会话生命周期抽取到 loopx/chat/session_open.py,将 chat_runtime.py 压到 1,541 行并移除行数例外,同时修正最小入口守卫与启动失败的先删占位后唤醒顺序。
会话创建、适配器恢复与并发重试维持原有对外语义:最小 HTTP 入口可安全路由到 steward 会话;Thread.start() 失败时同键并发重试能接管并完成原 Turn 且 transport 仅执行一次;loopx/chat_runtime.py 无需行数例外且 any_count 从 38 降至 30。
本 PR 不修改前端聊天界面、TypeScript 控制面协议或持久化的 Session/Turn 存储格式,也不顺带处理主干已有的两个决策函数复杂度未审条目。

改动思路 / Approach

将 ChatSessionLifecycleMixin 独立到内部模块 loopx/chat/session_open.py,复用既有 ChatSessionStore、适配器锁与 loopx.chat_runtime monkeypatch 解析点;同时保留 Turn 状态持久化与同进程 turn_done_events 单飞控制,在 _release_done_event 中通过 drop_before_notify 区分线程已退出终态清理与线程未启动时的占位回退。
仅限 Python Chat 会话生命周期组织、并发派发异常恢复与 module_metric_baseline.json 指标收敛,不改变公共接口或控制面跨语言边界。

从调用链路来看,open_chat_session 与 ChatSessionLifecycleMixin 继续承担会话打开与适配器恢复,但不再把近千行生命周期细节堆叠在 loopx/chat_runtime.py 顶层控制类内;ChatRuntimeController 通过继承 ChatSessionLifecycleMixin 保持对外方法签名与既有测试 monkeypatch 入口不变,并将 _start_adapter 内托管执行所需的 operator_credential_resolution、operator_credential_pair、DshChatAdapter 等符号路由回 loopx.chat_runtime 模块,保证外部替身与配置钩子继续生效。针对先前评审指出的 [P2] 竞态,_start_accepted_turn_worker 在 worker.start() 失败时改用 drop_before_notify=True,先在 self.lock 下移除本线程的 done_event 占位再执行 done_event.set() 与 turn_release_wakeup.notify(),并在 submit_turn 的异常清理分支检查是否已有并发重试启动的活跃 worker,避免把重试线程正在使用的健康适配器关闭。

具体改动 / Changes

关键代码讲解

  1. open_chat_session(loopx/chat/session_open.py:204):将原来的直接属性访问改为 getattr(controller, "project_contexts", None),使不定义 project_contexts 的最小 HTTP 测试或入口 controller 在 context_kind="manager" 时可回落到 open_manager_session 而不再抛 AttributeError。
  2. ChatSessionLifecycleMixin._ensure_adapter_locked(loopx/chat/session_open.py:732):接收原 chat_runtime.py 的适配器复用、恢复、上下文迁移与故障回写逻辑,并合入 origin/main(41ea75e89892ed88d0ae543e97e31aad0a181c47)近期对 steward 模型默认配置继承(executor_model / agent_config / expected_model)与工作线程续接(resume_working_model)的修复;通过 _resolve_manager_channel、_start_acp_adapter 与 _supports_live_model_id 消除了重复逻辑。
  3. ChatRuntimeController._release_done_event(loopx/chat_runtime.py:372):统一收口完成事件清理,并新增 drop_before_notify: bool = False 参数;_run_turn 与 _fail_queue_preparation 维持先 set()/notify() 后删占位的既有终态语义,而线程未曾启动的场景先持锁删占位再唤醒等待者。
  4. ChatRuntimeController._start_accepted_turn_worker 与 submit_turn(loopx/chat_runtime.py:493, 403):worker.start() 异常分支传入 drop_before_notify=True,解决并发同键重试在唤醒窗口观测到陈旧占位并跳过派发的问题;submit_turn 异常回退先检查 turn_done_events 中同会话是否已有活跃 worker,若已被并发重试接管则保留适配器。
  5. test_thread_start_failure_drops_done_event_before_notifying_concurrent_retry(tests/test_chat_session_active_turn.py:2292):在真实 File ChatSessionStore 上注入首次 worker.start() 异常,于 turn_release_wakeup.notify 内阻塞首次提交并并发重放同一 client_turn_id,验证修复前稳态复现滞留,修复后原 Turn 完成且 start_calls == 1;同时保留主干 record_owner_resume 逻辑并将 loopx/canary/module_metric_baseline.json 中 loopx/chat_runtime.py 的行数例外移除、any_count 降至 30。

本变更属于已有内部模块拆分与并发竞态修复,仓库中不存在独立于源码与既有文档的外部书面规格(spec_basis: no_spec),以主干 origin/main(41ea75e89892ed88d0ae543e97e31aad0a181c47)的原有调用契约与可观察行为作为对齐基准。

对主干的风险 / Risks

以真实本地验证替代远端 CI(wait_for_ci: false):

  • 核心与架构回归:ruff check 全过;mypy(17 个 strict 文件)全过;npm run typecheck:control-plane 通过;loopx check --scan-path 对全部 4 个变更文件 errors: 0;scripts/check_rfc_bilingual.py --base origin/main --head HEAD 通过;canary premerge --from-git-diff --git-diff-base origin/main --tier quick 结果 merge_gate_passed: true(direct_failure_count: 0、failure_count: 0)。
  • Chat 与预算测试:16 个核心 Chat/架构测试文件共 633 passed(含新增交错回归测试与 test_content_digest_single_owner.py、test_top_level_module_budget.py);symlink loopx/web/chat 前端产物后 test_chat_cold_source_import.py 与 test_chat_goal_storage.py 83 passed;全量 tests/*chat* 其余用例 2,530 passed, 6 skipped,出现的 5 个失败(test_chat_external_todo_confirmation.py::test_other_app_cannot_confirm_a_known_todo_preview 与 test_chat_operation_actions.py 4 个旧 activation_state 用例)以及 control-plane-maintainability-ratchet-smoke.py 的 2 个 unreviewed 决策函数均已在同方法下于主干 origin/main(41ea75e89892ed88d0ae543e97e31aad0a181c47)独立复核,属于与本 PR 无关的主干既有基线问题;examples/loopx-chat-runtime-smoke.py、examples/loopx-chat-acp-adapter-smoke.py 与 examples/loopx-steward-channel-binding-smoke.py 均通过(loopx-steward-managed-chat-smoke.py 因本地 venv 未安装可选 deepseek-harness-sdk 而跳过)。
  • 残余边界:经由主干合入的 record_owner_resume 逻辑使 loopx/chat_runtime.py 当前为 1,541 行(any_count=30, dict_any_count=0),仍大幅低于仓库 2,000 行默认硬限制且无 module_metric_budget 回归;真机模型端到端执行未在本轮触发。

我的整体评价 / Verdict

本次重基完整保留了主干合入的 steward 模型默认配置解析、原线程恢复及显式 Goal owner resume 语义,同时高质量完成了 chat_runtime.py 的瘦身与基线例外退役,并彻底修复了线程启动失败窗口里的并发重试滞留竞态与并发卸载适配器风险。未涉及任何前端界面渲染改动(视觉评审 not_applicable:loopx/chat_runtime.py、loopx/chat/session_open.py、loopx/canary/module_metric_baseline.json 与 tests/test_chat_session_active_turn.py 仅覆盖 Python 运行时、预算配置与单测),无未覆盖的 UI 范围(none)。

English Verdict: APPROVE at 5ef9f48. Rebased cleanly onto origin/main, retired the chat_runtime.py line ceiling, fixed the Thread.start() failure cleanup-before-notify race with a deterministic interleaving regression test, and passed local typecheck, lint, canary premerge, and Chat test suites with zero PR-attributable regressions.

…cate runtime helpers, and retire ceiling

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

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent
loopx-agent force-pushed the codex/chat-runtime-slim-20261117 branch from 5ef9f48 to 9a88b14 Compare November 19, 2026 17:27

@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: 8920@9a88b14bd2b618f162ab3a86a21454dc6cccfae2

动机 / Motivation

负责维护与调用本地 Chat 运行时的开发者,在最小 HTTP 入口(缺少 project_contexts 属性的 controller)打开 steward 会话的调用方,以及在工作线程启动失败后以相同 client_turn_id 并发重试发送消息的对话用户。
此前在 main(6e1a0bd9e7)上,loopx/chat_runtime.py 体积达 2,497 行(any_count=38)并依赖 module_metric_baseline.json 中 2,524 行的历史例外;同时 open_chat_session 直接读取 controller.project_contexts 会在最小入口 controller 上抛出 AttributeError;此外初版拆分后 _start_accepted_turn_worker 在 Thread.start() 失败时先 notify 再清理 turn_done_events,并发重试会看到陈旧占位而跳过派发并滞留在 queued。合入后,ChatSessionLifecycleMixin 迁入 loopx/chat/session_open.py,chat_runtime.py 降至 1,465 行并退役行数例外(any_count 降至 29),最小入口路由安全回落至 open_manager_session,且启动线程失败先持锁删占位再唤醒并保护同会话活跃重试的适配器不被误关。
会话打开、适配器复用与恢复、关闭/重连和并发同键重试保持既有外部行为;最小入口不再因缺少 project_contexts 报错;worker.start() 失败窗口下的同键并发重试可正常完成原 Turn 且 transport 仅调用一次;chat_runtime.py 降至 1,465 行(低于 1,500)且退役 2,524 行基线例外。
本 PR 不改变前端聊天界面、TypeScript 控制面协议、Session/Turn 持久化格式或任何公共 API 契约,也不处理主干既有 interaction_contract.py:1004 的 unrelated mypy 类型报错。

改动思路 / Approach

将同属会话打开、适配器复用/恢复、关闭与重连的生命周期方法集中到内部模块 ChatSessionLifecycleMixin(loopx/chat/session_open.py),通过继承保留 ChatRuntimeController 既有方法签名与测试 monkeypatch 入口;在 _release_done_event 中用单一布尔参数 drop_before_notify 区分终态清理与未启动回滚,避免复制清理逻辑或引入额外兼容层。
仅限于 Python Chat 内部模块组织(loopx/chat_runtime.py 与 loopx/chat/session_open.py)、并发启动失败恢复、module_metric_baseline.json 指标收敛以及对应的单元回归测试,不包含前端 UI 或跨语言控制面协议改动。

从控制流与所有权边界来看,open_chat_session 与 ChatSessionLifecycleMixin(loopx/chat/session_open.py)承接会话打开(open_session)、适配器按需创建/复用(_ensure_adapter、_ensure_adapter_locked、_start_adapter)以及会话关闭和恢复(close_session、resume_session);ChatRuntimeController(loopx/chat_runtime.py)保留 Turn 受理、执行缓冲(_TurnEventBuffer)、并发单飞事件表(turn_done_events)及中断/排队调度。两者仍复用同一个 ChatSessionStore、self.lock、self._session_adapter_lock 与 loopx.chat_runtime 模块级调度解析点(operator_credential_resolution、operator_credential_pair、DshChatAdapter、manager_session_model_allocation、manager_session_quota_route、_steward_dsh_model_config),不引入任何并行状态存储或顶层兼容垫片。针对之前评审指出的 [P2] 窗口期滞留问题,_release_done_event 统一封装“设完成事件 + 唤醒等待者 + 移除占位”,正常终态保留先唤醒再删占位,而 worker.start() 尚未启动线程的异常路径通过 drop_before_notify=True 先持锁删除本线程占位再唤醒等待者;同时 submit_turn 异常处理检查 turn_done_events 是否已存在同会话活跃 worker,防止在并发重试已接管适配器后将其误关。

具体改动 / Changes

关键代码讲解

  1. open_chat_session(loopx/chat/session_open.py:208):将原本直接访问 controller.project_contexts 改为 getattr(controller, "project_contexts", None),使未定义 project_contexts 属性的最小 HTTP 测试/入口 controller 在 context_kind="manager" 时可安全回落至 open_manager_session,不再抛出 AttributeError。
  2. ChatSessionLifecycleMixin._ensure_adapter_locked、close_session 与 resume_session(loopx/chat/session_open.py:752, 1168, 1198):完整承接会话生命周期方法(open_session、close_session、resume_session 及适配器创建/恢复),保留主干既有的 steward 模型分配、working continuation、配额路由切换与测试 monkeypatch 解析钩子,并通过 _resolve_manager_channel、_start_acp_adapter 与 _supports_live_model_id 消除重复逻辑;经此拆分,loopx/chat_runtime.py 从主干 2,497 行降至 1,465 行(低于 1,500 行),且保留主干合入的 commit_steward_memory_after_turn 与 record_owner_resume。
  3. ChatRuntimeController._release_done_event、submit_turn 与 _start_accepted_turn_worker(loopx/chat_runtime.py:371, 402, 492):新增 drop_before_notify: bool = False,在 worker.start() 抛错回退时先于 self.lock 下移除 (session_id, turn_id) 的 done_event 占位,再执行 done_event.set() 与 turn_release_wakeup.notify();并在 submit_turn 的异常分支检查同会话是否已有其他活跃 worker,避免并发重试已经启动工作线程时误调用 _drop_owned_adapter。
  4. test_thread_start_failure_drops_done_event_before_notifying_concurrent_retry 与 module_metric_baseline.json(tests/test_chat_session_active_turn.py:2292, loopx/canary/module_metric_baseline.json:73):在真实文件存储 ChatSessionStore 上注入首次 worker.start() 异常并在 turn_release_wakeup.notify 处拦截以构造并发同键重试,验证原 Turn 最终 completed 且 adapter.start_calls == 1、adapter.closed is False;同时移除 loopx/chat_runtime.py 的 2524 行基线例外并将 any_count 从 38 收紧至 29(dict_any_count=0),保留主干 origin/main 其他模块的基线更新。

spec_basis: no_spec(spec_source: none):本次变更为已有 Python 内部模块的生命周期拆解与线程启动异常竞态修复,仓库中不存在独立于源码与 AGENTS.md/module_metric_baseline.json 的外部规格文档,因此以主干 origin/main(6e1a0bd9e722ee2d287371c5586559d1b466a1b8)的既有调用契约及不变量作为验收基准。

对主干的风险 / Risks

  • 负向与异常交错验证:已针对强回归场景“首次 Thread.start() 失败后并发同键重试恰在 notify() 窗口进入 submit_turn”进行实测(test_thread_start_failure_drops_done_event_before_notifying_concurrent_retry),确认不会出现陈旧 turn_done_events 占位导致跳过派发或并发误关适配器;对于合法同键重试与 open_chat_session 最小入口路径亦由既有单测覆盖。
  • 本地全量/专项验证(不等待远端 CI,wait_for_ci: false):
    • pytest(22 个 Chat / 生命周期 / 维持性棘轮 / 顶层模块预算测试集):PASS(1,444 passed, 0 failed, 0 skipped;其中 tests/test_chat_session_active_turn.py 63 passed,并发重试回归用例 1 passed)。
    • ruff check(全部 3 个变更 .py 文件):PASS。
    • scripts/check_rfc_bilingual.py --base origin/main --head HEAD & git diff --check origin/main...HEAD:PASS。
    • loopx check --scan-path(全部 4 个变更文件):PASS(errors: 0, warnings: 0)。
    • loopx change-quality verify --goal-id personal-loopx-maintenance --base-ref origin/main:PASS(receipt_valid: true,receipt_id: cqr_d2839ea1cd63e1077df9)。
    • loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main --goal-id personal-loopx-maintenance:PASS(merge_gate_passed: true,6 项直接检查与 3 项目录 canary 全过)。
    • npm run -s typecheck:control-plane & examples/loopx-chat-runtime-smoke.py:PASS。
    • mypy(仓库 pyproject.toml#tool.mypy 17 个 strict 文件):FAIL(pre_existing_unrelated) — 在 origin/main(6e1a0bd9e722ee2d287371c5586559d1b466a1b8)与当前 HEAD(9a88b14bd2b618f162ab3a86a21454dc6cccfae2)均以完全相同的错误 loopx/control_plane/work_items/interaction_contract.py:1004 退出码 1 失败,本 PR 未改动上述 17 个文件中的任何文件。mypy --strict --follow-imports=silent 在新增/搬迁的 close_session、resume_session 方法体引入 0 个新错(既有测试和 ChatSessionLifecycleMixin 原生注解保持现状)。
  • 其他维度审查结论:本 PR 为内部纯代码重构与并发竞态修复,不新增开关或默认路径变更(default_off_isolation: not_applicable),不改变顶层模块数量(124 个)或公共协议/角色权限命名(authority_semantics: not_applicable),未修改共享状态枚举或自然语言契约文本(semantic_alignment: not_applicable,decision_text_assessment: not_applicable),生产调用链通过 ChatRuntimeController 继承 ChatSessionLifecycleMixin 与 open_chat_session 全部直连(scope_fit: shipped)。

我的整体评价 / Verdict

从整体交付效果评估:long_horizon 为 preserved(沿 submit_turn -> _start_accepted_turn_worker -> _release_done_event(drop_before_notify=True) -> 同键并发重试 -> wait_for_turn 与 resume_session / close_session 完整链路核验,持久化状态与适配器单飞约束在失败回退与重连后均保持一致,并完整保留主干 commit_steward_memory_after_turn 与 record_owner_resume 逻辑。);user_experience 为 improved(最小 HTTP 入口缺失 project_contexts 时不再抛出 AttributeError,且工作线程启动失败后的同键重试可完成原 Turn 而非永久卡在 queued,同时不增加额外用户交互或配置步骤。)。视觉评审 visual_review 为 not_applicable(原因:本次变更仅涉及 Python Chat 内部运行时(loopx/chat_runtime.py、loopx/chat/session_open.py)、指标基线配置(loopx/canary/module_metric_baseline.json)与后端单元测试(tests/test_chat_session_active_turn.py),未改动任何前端或渲染界面。;未覆盖范围:none)。

架构与代码体积方面,change_proportionality 评估为 proportionate,架构处置为 retain(将同属会话打开、适配器复用/恢复、关闭与重连的生命周期方法集中到内部模块 ChatSessionLifecycleMixin(loopx/chat/session_open.py),通过继承保留 ChatRuntimeController 既有方法签名与测试 monkeypatch 入口;在 _release_done_event 中用单一布尔参数 drop_before_notify 区分终态清理与未启动回滚,避免复制清理逻辑或引入额外兼容层。;仅限于 Python Chat 内部模块组织(loopx/chat_runtime.py 与 loopx/chat/session_open.py)、并发启动失败恢复、module_metric_baseline.json 指标收敛以及对应的单元回归测试,不包含前端 UI 或跨语言控制面协议改动。);code_volume 评估为 necessary,保留 ChatRuntimeController 继承边界避免破坏外部调用方与测试钩子。精确头 8920@9a88b14bd2b618f162ab3a86a21454dc6cccfae2 已与当前远端一致,本地测试、lint、公私边界扫描、CQR 与 canary premerge 全部通过,不存在未解决阻塞项;残余边界仅为主干既有未关联 interaction_contract.py:1004 mypy 报错及真实外部模型进程端到端调用未在本轮本地单测中触发。

English Verdict: APPROVE at 9a88b14. Cleanly rebased onto latest origin/main preserving commit_steward_memory_after_turn, record_owner_resume, and baseline entries; slimmed loopx/chat_runtime.py to 1,465 lines (<1,500) with any_count tightened to 29, preserved the Thread.start() failure cleanup-before-notify fix and minimal entry-point guard, and passed 1,444 targeted tests, ruff, public-boundary scan, CQR receipt, and canary premerge.

@loopx-agent
loopx-agent merged commit b927e20 into main Nov 19, 2026
31 of 38 checks passed
@loopx-agent
loopx-agent deleted the codex/chat-runtime-slim-20261117 branch November 19, 2026 17:36
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