Repository navigation
Conversation
Signed-off-by: lusendong.6789 <lusendong.6789@bytedance.com>
loopx-agent
left a comment
There was a problem hiding this comment.
Reviewer: model_agent, Gemini (Google), self_reported
动机 / Motivation
在本地、Worktree 或 CI Runner 上运行 LoopX 完整 pytest 套件的开发者与自动化流程,都会在执行测试时为每个用例创建独立的临时工作区与隔离的 HOME 目录。
改动前 pytest 默认使用 tmp_path_retention_policy=all,且自动隔离 HOME 使用 tmp_path_factory.mktemp,导致上千个已通过用例的临时目录在整场测试结束前持续堆积;改动后在每个通过用例的 teardown 报告阶段立即回收其登记的 tmp_path、case_mktemp 与隔离 HOME,同时在 setup 前校验临时目录剩余空间并在不足阈值时提前中止会话。
在 macOS 上实测已验证:通过用例的 tmp_path、case_mktemp 与隔离 HOME 会在下一条测试运行前被回收,setup/call/teardown 失败仍保留现场,多进程并发与 xdist 仅清理各自用例目录,低磁盘保护会在启动夹具前以 ExitCode.INTERRUPTED 中止;但当前 _remove_temp_dir 直接调用 shutil.rmtree 并在出错时在 pytest_runtest_makereport 内发出 PytestWarning,一旦通过用例留下只读目录(0o555)或 Windows Git 只读对象(0o444),清理会失败并可能在 -W error 下引发 INTERNALERROR 崩溃。
本 PR 不改动 LoopX 生产控制面或运行时的临时目录生命周期,也不跨越会话全局扫除其他并发 pytest 进程拥有的 pytest-of-/pytest-* 目录。
改动思路 / Approach
本次改动在 tests/conftest.py 内通过统一的 case_mktemp 夹具替代分散的 tmp_path_factory.mktemp 调用来登记单用例临时目录,而不是简单地在 pyproject.toml 中设置 tmp_path_retention_policy = "failed":一方面内置 tmp_path 不会回收 _isolated_default_runtime_routes(home)和短路径 case_mktemp 目录,另一方面 pytest 内置 tmp_path 最终清理器仅查看 call 阶段结果,容易在 teardown 失败时误删目录(具体机制详见下文)。
整体生命周期由三个点协同控制:
- 策略解析(
pytest_configure):检查--loopx-min-free-tmp-mib非负,并通过config.inicfg与-o覆盖判断用户是否显式配置了tmp_path_retention_policy;未显式配置时默认采用"failed"策略,且在config.stash[_CASE_SEQUENCE]维护进程内单调序号。 - 目录登记与按用例回收(
case_mktemp/tmp_path/pytest_runtest_makereport):case_mktemp创建tmp_path_factory.mktemp(f"{name}-{serial}", numbered=False)并记录在request.node.stash[_CASE_TEMP_DIRS];tmp_path、_isolated_default_runtime_routes以及 3 个短路径测试均委托给它。pytest_runtest_makereport先汇总setup/call/teardown任意阶段的失败标记到item.stash[_CASE_FAILED],在report.when == "teardown"时按策略删除当前用例登记目录(与内置tmp_path的最终清理解耦,从而确保所有 fixture finalizer 与pytest_runtest_teardown中的stop_disposable_effect_runtimes执行完后再删目录)。会话结束时若无默认路由泄漏、策略非"all"且exitstatus == OK,pytest_sessionfinish再回收 worker 级_WORKER_TEMP(effect-runtime*)。 - 预启动磁盘保护(
pytest_runtest_setup):在tryfirst=True阶段按--basetemp->PYTEST_DEBUG_TEMPROOT->tempfile.gettempdir()解析所在已存在挂载点,可用空间低于--loopx-min-free-tmp-mib(默认 2048 MiB)时设置item.session.shouldstop并立即pytest.fail(..., pytrace=False),在会话和用例 fixture 初始化前中断串行或 xdist 会话。
具体改动 / Changes
本次 PR 共修改 5 个测试文件(+202/-9),均处于 tests/ 范围内,仓库未就测试套件临时目录回收制定专门 RFC 或书面规范(spec_basis: no_spec),以下按改动文件逐一核查:
- tests/conftest.py:新增
case_mktemp、重写tmp_path、新增_remove_temp_dir、pytest_configure、扩展pytest_runtest_makereport与pytest_runtest_setup、扩展pytest_sessionfinish与pytest_addoption(--loopx-min-free-tmp-mib),并将_isolated_default_runtime_routes切换至case_mktemp("home")。 - tests/test_managed_effect_runtime_fixture.py:新增
test_pytest_reclaims_finished_cases_and_keeps_failed_phases(校验 setup/call/teardown 失败保留与通过用例即时回收,及 finalizer 执行顺序)与test_pytest_stops_before_fixtures_on_low_disk(串行与-n 2xdist 低磁盘中止)。 - tests/control_plane/test_monitor_gate_handoff.py、tests/control_plane/test_user_gate_resume_cli.py、tests/test_collaboration_sidecar_scan.py:将原函数级短路径
tmp_path_factory.mktemp(...)迁移为case_mktemp(...),使短路径目录也能随用例结束而回收;同时仓库内剩余的两处tmp_path_factory.mktemp(test_pr_review_git_file_inventory.py与test_runtime_stdio_host_utf8.py)均为scope="module",未受误伤。
对主干的风险 / Risks
[P1 / Blocking] _remove_temp_dir 缺少只读权限恢复,且在 pytest_runtest_makereport 内发出 PytestWarning 会在 -W error 下触发 INTERNALERROR 崩溃
- 触发路径:
tests/conftest.py的_remove_temp_dir(temporary)在pytest_runtest_makereport(teardown报告后)和pytest_sessionfinish中直接调用shutil.rmtree(temporary),并在捕获OSError时调用warnings.warn(pytest.PytestWarning(...))。 - 实测证据(macOS):
- 当通过用例在
tmp_path下留下0o555只读目录时,默认清理触发PermissionError: [Errno 13],目录未被回收,且输出PytestWarning。 - 在
pytest -W error与单测标记@pytest.mark.filterwarnings("error")两种场景下实测,该warnings.warn(pytest.PytestWarning(...))在pytest_runtest_makereport钩子内被转换为未捕获异常,导致 pytest 以ExitCode.INTERNAL_ERROR(返回码3)直接崩溃并中止后续测试,即便被测用例本身已经通过。
- 当通过用例在
- Windows 主干风险(基于仓库配置与现有修复记录分析,本地未运行 Windows 原生环境):
.github/workflows/python-tests.yml的windows-powershell任务会执行在tmp_path中运行git init/git commit的测试(如tests/test_doctor_git_encoding.py、tests/control_plane/test_cli_output_differential.py)。如loopx/extensions/process_runtime.py(remove_owned_tree)及该工作流注释所记录,Windows 上git会将 loose object 写为只读(0o444),裸shutil.rmtree会以PermissionError [WinError 5]失败;由于本 PR 将默认回收策略从"all"改为"failed",Windows CI 上相关通过用例将无法回收.git临时目录并产生清理警告(若带-W error则直接INTERNALERROR)。 - 最小修复:
- 在
_remove_temp_dir删除树前或onexc回调中,仅针对temporary内部拥有的非符号链接/非 junction 目录与单硬链接文件(st_nlink == 1)补充写/执行权限后重试删除(可复用loopx.extensions.process_runtime.remove_owned_tree的只读清理思路并补充 POSIX 只读目录处理,或参考_pytest.pathlib.rm_rf的on_rm_rf_error),绝不跟随符号链接或修改硬链接外部文件权限。 - 在
pytest_runtest_makereport/pytest_sessionfinish清理钩子内避免发出可被-W error升级为INTERNALERROR的PytestWarning(对齐上游_pytest/tmpdir.py的 best-effort 静默忽略或仅在安全通道处理不可删除目录)。 - 在
tests/test_managed_effect_runtime_fixture.py补充对0o444/0o555只读树与@pytest.mark.filterwarnings("error")组合场景的回归测试。
- 在
其他已验证的并发、符号链接与边界项(均已通过,无额外阻塞)
- 并发与兄弟运行安全性(PASS):未扫描或清理全局
pytest-of-<user>/pytest-*目录,所有清理严格限定在当前进程的item.stash[_CASE_TEMP_DIRS]与session.config.stash[_WORKER_TEMP]。实测两个进程共享同一PYTEST_DEBUG_TEMPROOT/TMPDIR(无--basetemp)并发运行,以及两组pytest -n 2在各自--basetemp下并发运行,均互相隔离、无误删且失败用例目录完整保留。 - 符号链接与跨作用域 fixture(PASS):
tmp_path内部指向外部目录/文件的 symlink、悬空 symlink 以及tmp_path本身被替换为 symlink,均不会删除外部目标;scope="session"与scope="module"的tmp_path_factory.mktemp不受按用例清理影响。 - 次要非阻塞观察:当
-o tmp_path_retention_policy=none且某 worker 有用例失败(exitstatus != 0)时,pytest_sessionfinish仍保留该 worker 的_WORKER_TEMP(effect-runtime*);另外pytest_runtest_setup若遇到前置测试泄露os.chdir且运行命令使用相对--basetemp,会按当前工作目录解析路径,建议后续顺手以invocation_params.dir锚定。
我的整体评价 / Verdict
本 PR 针对长耗时 pytest 会话的磁盘膨胀问题切中要害,且在单进程与 xdist 并发隔离、三阶段失败保留、fixture finalizer 与 effect-runtime 停机顺序、tmp_path_factory 模块级目录隔离以及低磁盘中断等方面设计清晰、在 macOS 本地实测表现稳健。但 _remove_temp_dir 使用无只读恢复的裸 shutil.rmtree 并在 pytest_runtest_makereport 中发出 PytestWarning,已实测导致留有只读目录的通过用例在 -W error 或 @pytest.mark.filterwarnings("error") 下引发 INTERNALERROR 会话崩溃,且与仓库已有的 Windows Git 只读对象清理经验冲突,因此当前 head f62c1f760e3274a2ee441e3cf0116937c9026df9 需补齐只读清理与钩子警告安全后再合入。
本地验证摘要(exact head f62c1f760e3274a2ee441e3cf0116937c9026df9,未等待远程 CI):
- PR 目标测试集(
-n 2 --dist loadfile):PASS(86 passed in 164.69s,覆盖tests/test_managed_effect_runtime_fixture.py、tests/test_collaboration_sidecar_scan.py、tests/control_plane/test_monitor_gate_handoff.py、tests/control_plane/test_user_gate_resume_cli.py)。 - 相关仓库回归集(含 git、只读清理、
filterwarnings、module级tmp_path_factory):PASS(94 passed in 28.55s)。 - 基线
036a95fb1aacvs Headf62c1f760e32对比与并发/策略/符号链接探针:PASS(基线保留通过用例tmp_path与home;Head 即时回收通过用例目录并保留失败用例;并发与xdist互不干扰;symlink 外指安全)。 - 只读
0o555目录 +-W error/@pytest.mark.filterwarnings("error")探针:FAIL(复现ExitCode.INTERNAL_ERROR,rc=3)。 - 静态检查与门禁:
ruff check(5 个变更文件)PASS、mypy(17 个严格类型文件)PASS、git diff --checkPASS、scripts/check_rfc_bilingual.pyPASS、loopx check --scan-path(公私边界零告警)PASS、loopx canary premerge --tier quick(5 项直接检查 + 3 项 canary 全通过)PASS。 - 视觉审查与未验证范围:
visual_review为not_applicable(仅修改tests/下测试夹具与测试文件,无前端 UI 渲染变化);unverified_scope为 Windows 原生宿主机实际执行及全量完整测试套件(-W error下另有 4 项既有用例因独立Popen.__del__ResourceWarning失败,非本 PR 引入)。
English verdict: REQUEST_CHANGES at head f62c1f7 — _remove_temp_dir in tests/conftest.py lacks read-only permission recovery (0o555 dirs / Windows 0o444 git objects) and emits PytestWarning inside pytest_runtest_makereport, which crashes -W error and @pytest.mark.filterwarnings("error") runs with INTERNALERROR; PR touched suites (86 passed) and static/canary checks passed locally on macOS.
Goal And Delivered Outcome
Long LoopX pytest sessions could retain temporary directories for completed cases until the session ended. The suite now reclaims case-owned scratch space after the final teardown report whenever the case completed without a failure. Setup, call, and teardown failures retain their evidence under the default policy.
tmp_path, per-case isolated HOME, and named case-owned directories.--loopx-min-free-tmp-mib.loopx-project/loopx:main.Author Declaration
tests/conftest.pycase ownership and teardown reportingScope And Continuation
Complete within the main pytest suite. The change also checks that the touched runtime, sidecar, and short-path fixtures still work with the new lifecycle.
Validation
f62c1f760e3274a2ee441e3cf0116937c9026df9finishedsyntheticintegrationpassedstaticpassedgit diff --check origin/main...HEAD, and the RFC bilingual diff check.integrationnot_runpython -B -m pytest -q -n 2 --dist loadfile \ tests/test_managed_effect_runtime_fixture.py \ tests/test_collaboration_sidecar_scan.py \ tests/control_plane/test_monitor_gate_handoff.py \ 'tests/control_plane/test_user_gate_resume_cli.py::test_gate_first_link_rejects_invalid_target_without_consuming_link[missing-preview-sqlite]'Frontend / Visual Evidence
UI impact is
none.Type of Change
LoopX Area
Shared-authority RFC fixture impact
N/A. This changes pytest scratch-space lifecycle.
Boundary Checklist