Skip to content

fix(ci): preserve pytest deadline diagnostics and abort slow collection (#8787) - #8878

Open
loopx-agent wants to merge 1 commit into
mainfrom
codex/ci-python-shard-speedup-20261117
Open

loopx-agent wants to merge 1 commit into
mainfrom
codex/ci-python-shard-speedup-20261117

Conversation

@loopx-agent

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

Copy link
Copy Markdown
Collaborator

Refs #8787

Delivery Brief

  • Goal & Source: Respond to @dsyme's feedback in Ideas for making your CI faster #8787 (C1 + C3) to make Python Tests shard timeouts diagnosable, preserve partial JUnit outcomes and live progress/process diagnostics before the 60m runner deadline, and keep failure semantics intact without relaxing Python 3.11 checks, test selection, or the 19.6% coverage floor.
  • Scope Update Following Review:
    • Real CI Run 43929531116 showed -n 4 on 4-vCPU ubuntu-latest runners caused subprocess CPU contention where all 6 shards still hit the 3300s cooperative deadline while uncovering a 512.3s hang in test_profile_without_steerable_binding_keeps_four_ordinary_workers.
    • Per Issue Ideas for making your CI faster #8787 (C2 — isolate hangs and measure durations before raising concurrency), this PR retains -n 2 on test-shard and focuses strictly on C1 + C3 diagnostic observability and cooperative deadline enforcement.
  • What Changed:
    1. Cooperative Session Deadline & Slow-Collection Abort (scripts/ci/pytest_timing.py, .github/workflows/python-tests.yml):
      • Add --ci-session-deadline 3300 (55m inner deadline inside the 60m job timeout) to TimingObserver.
      • Track active collection (_collection_active) and active runtest loop (_loop_active), and guard entry to both pytest_collection and pytest_runtestloop via _abort_if_deadline_exceeded. When the deadline expires during slow collection, between collection and execution, or during test execution, TimingObserver records deadline_exceeded: true, writes ci-shard-diagnostics.json, sets session.shouldstop / dsession.shouldstop, interrupts the main thread when inside an active hook, flushes partial junit.xml, preserves failing exit code (ExitCode.INTERRUPTED = 2), and emits LOOPX_PYTEST_DEADLINE without changing LOOPX_PYTEST_TIMING parsing in scripts/ci/pytest_timing.ts.
      • Guard Upload full-shard outcomes for selection audit with if: ${{ !cancelled() }} so external cancellation avoids misleading missing-JUnit upload errors while genuine failures and inner-deadline stops still upload junit.xml.
    2. Live In-Flight & Child-Process Timeout Diagnostics (scripts/ci/pytest_timing.py, .github/workflows/python-tests.yml):
      • Add --ci-diagnostics-file ci-shard-diagnostics.json (loopx_ci_pytest_diagnostics_v1), atomically updated at collection, every 100 finished cases / 15s, on deadline, and at session finish with in_flight_cases, phase_seconds, longest_cases, and public-safe active_child_processes (pid, ppid, state, sanitized executable basename comm — never argv/paths/env).
      • Enhance --ci-stall-after stack snapshots with [child pid=... ppid=... state=... comm=...] rows for hung child subprocesses.
      • Upload python-diagnostics-${{ matrix.shard }} with if: always() and if-no-files-found: warn.
    3. Retain -n 2 Worker Pool & Conditional bwrap Install (.github/workflows/python-tests.yml):
      • Keep the measured -n 2 pool on test-shard.
      • Guard sudo apt-get update && sudo apt-get install --no-install-recommends -y bubblewrap with if ! command -v bwrap >/dev/null 2>&1.

Verification (Head f2d6fac64bd0c8b1a54d55d15a8166f8ec093c24)

  • uv run --extra test python -m pytest -n 3 -q tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py tests/test_ci_pytest_failure_context.py -> 656 passed in 54.64s
  • uv run --extra test python -m ruff check scripts/ci/pytest_timing.py tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py tests/test_ci_pytest_failure_context.py -> All checks passed
  • uv run --extra test python -m unittest discover -s scripts/ci -p 'test_*.py' -> 23 tests OK
  • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs -> 9 passed, 0 failed
  • Counterfactual (-n 2, pytest_collection_modifyitems 1.5s sleep, --ci-session-deadline 0.4, 5.0s test) -> exits 2 in 2.92s, deadline_exceeded: true, test_slow never runs; default-off (--ci-session-deadline 0, no diagnostics file) exits 0 unchanged.
  • loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main --goal-id personal-loopx-maintenance -> PASS (receipt_id: cqr_f79248c6f3b054fd3a62, public_boundary: ok).

@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 · Google Gemini (self_reported)

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

针对精确头 a971731e532e99752c8317fa743d25f9b55abbd8(base f15ebdd16b5eb8cd01b2d112a3a0fe866b0f3486)的审查结论:暂不建议合入(REQUEST_CHANGES)。本 PR 的协作式截止时间与诊断文件机制在真实 CI 中有效落地并暴露了真实阻塞,但将 test-shard 扩至 -n 4 并未达成 40 分钟绿灯完成的核心目标(全部 6 条分片仍在 55 分钟撞线失败),且 TimingObserver 在慢集合阶段存在定时器永久失效边界问题。

动机 / Motivation

使用 GitHub Actions 运行 Python Tests 全量分片(test-shard 1–6)的维护者与 PR 贡献者,在长程 CI 校验任务触发时受影响。
改前在基线 main 上,test-shard 使用两路并发(-n 2)运行全量测试并受限于 60 分钟硬超时,多条分片在完成约七成多用例时被 Runner 强行取消且难以保留部分 JUnit 结果与阻塞现场;本次 PR 尝试将并发提升到四路并发(-n 4)并加入 55 分钟协作式会话截止时间(--ci-session-deadline 3300)与实时诊断文件,期望在约 40 分钟内完成全量分片并保留部分结果与卡住进程信息。
诊断与部分 JUnit 上传机制在真实 CI 运行中生效(6 条分片均在约 55 分钟优雅中断并上传 194–240 KB 的 junit.xml 与约 3 KB 的 ci-shard-diagnostics.json,并精准捕获 test_profile_without_steerable_binding_keeps_four_ordinary_workers 卡住 512.3 秒),但核心性能目标未能成立:受 4 路并发子进程 CPU 争用影响,全部 6 条分片依然撞上 55 分钟 deadline 失败(仅完成 79.8%–99.7%),且 TimingObserver 在集合阶段超时的反例下会丢失 deadline 中断。
本 PR 不调整 6 分片矩阵数量、不放宽 Python 3.11 或 19.6% 覆盖率门禁,也不直接修复各个具体业务测试内部的逻辑缺陷。

改动思路 / Approach

维度 改动前(基线 -n 2) 本次 PR(-n 4 + 55m 协作截止) 实测结果(Run 43929531116)
并发度与耗时估算 -n 2,单分片约 157.5 worker-min,估算需 78.8 分钟 -n 4,预期利用 4 vCPU 在 ~40 分钟跑完 4 路并发引发 8–16 个子进程争用 4 vCPU,仅完成 79.8%–99.7% 仍全员 55m 超时
超时与产物保留 60m 被 Runner 强杀,cancelled() 时上传缺文件报错 内置 --ci-session-deadline 3300,退出码保留为 2 并上传部分 junit.xml 与 ci-shard-diagnostics.json 6 条分片均成功退出码 2 并上传 junit.xml 与诊断 JSON,暴露出 512.3s 死等测试
bwrap 安装 每次无条件执行 apt-get update && install 先检查 command -v bwrap 再按需 --no-install-recommends 安装 工作流结构与静态检查通过

将协作式会话截止时间、实时进度诊断文件与子进程基名采集保留在 CI 观察插件 scripts/ci/pytest_timing.py 内核中是低耦合且可逆的正确边界,但直接把共享 4 vCPU Runner 上的 test-shard 从 -n 2 扩到 -n 4 绕过了 Issue #8787 先定位并解决长尾阻塞再调并发的顺序,在真实 CI 上反而使单分片 worker CPU 从约 9,451 秒推高到约 12,336 秒(81.8% 进度)并继续全员超时。
当前 PR 应收敛为先修复 TimingObserver 集合阶段 deadline 失效边界并保留诊断/JUnit 保留机制;在解决已暴露的 512 秒死等用例与重型子进程 CPU 争用前,不应把 -n 4 作为解决超时的有效方案直接合入,需回到受控基线对比或先拆解长尾用例。

此外,本次改动对既有主干存在两处关键交互边界:一是 TimingObserver 沿用控制器单点注册(not hasattr(config, "workerinput")),并通过独立子进程 _STACK_POPEN 写入堆栈,保持不改写用例选择与覆盖率统计的观测者边界;二是 Upload full-shard outcomes for selection audit 将 if: always() 收紧为 if: ${{ !cancelled() }},使外部取消不再因缺少 junit.xml 报错,而内部 55 分钟协作中断仍能保留部分结果。

具体改动 / Changes

对照 Issue #8787(参考规范 https://github.com/loopx-project/loopx/issues/8787 ,修订标识 #8787 )提出的改进准则逐条映射如下:

  • ISSUE-8787-C1(在提升并发前先让超时长尾可诊断,输出当前运行测试、有界栈/进程元数据与部分结果,且保留失败退出码):implemented — scripts/ci/pytest_timing.py 新增 --ci-session-deadline、--ci-diagnostics-file 与 _collect_descendant_processes,在真实 CI Run 43929531116 成功保留全部 6 条分片的部分 junit.xml 与 ci-shard-diagnostics.json(退出码 2)。
  • ISSUE-8787-C2(基于全量耗时分布平衡分片或先隔离已证挂起,再改矩阵/并发):not_met — PR 在未先解决挂起用例及未提供持久化 .test_durations 时即把 .github/workflows/python-tests.yml 改为 -n 4;在 Run 43929531116 中 6/6 分片仍在 55 分钟超时(Shard 6 捕获到 test_profile_without_steerable_binding_keeps_four_ordinary_workers 卡住 512.3 秒),未能实现 PR 声明的 ~40 分钟绿灯完成。
  • ISSUE-8787-C3(在协作截止时安全卸载而不吞掉失败或阻塞部分结果上传):not_met — 虽然正常测试循环中 _on_deadline 工作,但经本地反例复现,若集合阶段耗时超过 --ci-session-deadline,_on_deadline 因 _loop_active 为 False 而静默返回且不再重设,导致会话超时完全失效。

关键代码讲解

  1. _collect_descendant_processes(scripts/ci/pytest_timing.py):在 POSIX 环境下优先遍历 /proc/<pid>/stat,在无 /proc 的系统回退调用有界 ps -eo pid=,ppid=,stat=,comm=(超时 0.3 秒并确保 kill/wait),按 BFS 从 root_pid 收集最多 16 个子孙进程的 pid、ppid、state 与经过 _sanitize_comm 清洗的可执行文件基名。刻意不读取命令行参数与环境变量,避免泄露敏感路径或 token;单测 test_stall_snapshot_reports_descendant_child_process_basename_without_argv 已验证不输出 -c 'import time...' 载荷。
  2. TimingObserver._on_deadline 与 pytest_runtestloop(scripts/ci/pytest_timing.py):pytest_sessionstart 启动 daemon 定时器在 deadline_seconds 后触发 _on_deadline,加锁记录 deadline_in_flight、设置 session.shouldstop 与 dsession.shouldstop,落盘原子诊断 JSON 并调用 _thread.interrupt_main() 唤醒阻塞中的控制器事件循环。然而 _on_deadline 在 not self._loop_active 时直接 return,若测试集合阶段耗时超过 deadline_seconds,单次定时器提前触发并作废,后续进入 pytest_runtestloop 时不会补触发或重算剩余预算。
  3. TimingObserver.pytest_runtest_logstart / logreport / pytest_sessionfinish(scripts/ci/pytest_timing.py):分别维护 in_flight 表(上限按运行耗时排序取前 16 条)与 cases/phase_seconds 统计,每完成 100 条或每 15 秒通过临时文件加 os.replace 原子更新诊断 JSON;pytest_sessionfinish 取消并 join 定时器,在 deadline_exceeded 时强制将 session.exitstatus 设为 pytest.ExitCode.INTERRUPTED(2),输出 LOOPX_PYTEST_DEADLINE 事件且不破坏 scripts/ci/pytest_timing.ts 对 LOOPX_PYTEST_TIMING 行格式的解析。
  4. test-shard 工作流配置(.github/workflows/python-tests.yml):为 bwrap 安装增加存在性判断与 --no-install-recommends,将 pytest 命令从 -n 2 改为 -n 4 并挂载 --ci-session-deadline 3300 与 --ci-diagnostics-file ci-shard-diagnostics.json,同时将 junit.xml 上传条件改为 ${{ !cancelled() }} 并新增 always() 的 python-diagnostics-${{ matrix.shard }} 上传步骤。

对主干的风险 / Risks

阻塞问题 1:-n 4 未能兑现“40 分钟绿灯完成”的核心目标,在真实 CI 上因 4 核子进程争用导致 6/6 分片仍全部 55 分钟超时

  • Problem: PR 标题与 Delivery Brief 声称把 -n 2 扩至 -n 4 可将 ~157.5 worker-minutes 压到 ~40 分钟绿灯完成;但实测表明在 4 vCPU 的 GitHub Runner 上开启 4 个 xdist worker 并同时孵化多层 python / node 子进程(诊断文件显示每分片常驻 8–16 个活跃子孙进程),单用例 CPU 开销暴涨约 54%,6 条分片在 55 分钟时无一跑完。
  • Evidence: 检视精确头 a971731e532e99752c8317fa743d25f9b55abbd8 的真实 GitHub Actions Run 43929531116(6 份官方 python-diagnostics-* 产物与作业日志):
    • test-shard (1): 完成 5,577 / 6,662(83.7%),measured_worker_seconds = 12,375.52s,observed_elapsed_seconds = 3,311.11s,deadline_exceeded = true,exit_code = 2(且含 28 条测试失败);
    • test-shard (2): 完成 5,761 / 6,662(86.5%),measured_worker_seconds = 12,266.81s,deadline_exceeded = true;
    • test-shard (3): 完成 5,587 / 6,662(83.9%),measured_worker_seconds = 12,345.68s,deadline_exceeded = true;
    • test-shard (4): 完成 5,449 / 6,662(81.8%),measured_worker_seconds = 12,335.92s,deadline_exceeded = true(折合单用例耗时 ~2.26s,较 -n 2 基线 ~1.47s/用例膨胀 54%);
    • test-shard (5): 完成 6,645 / 6,662(99.7%),measured_worker_seconds = 12,380.08s,deadline_exceeded = true;
    • test-shard (6): 完成 5,317 / 6,661(79.8%),measured_worker_seconds = 11,832.55s,deadline_exceeded = true,其中 tests/extensions/test_lark_realtime_dispatch.py::test_profile_without_steerable_binding_keeps_four_ordinary_workers 在死线前已阻塞 512.31s(源码 L644–L646 存在无超时死等循环 while len(entered) < 4 and not deadline.wait(0.02): pass)。
    • 另据本地实测:Run 43929531116 中的 25–33 条常规用例失败(如 test_cli_program_route.py、test_performance_diagnosis_cli.py)在基线 f15ebdd16b 与精确头本地 -n 0 下同样复现,属于基线既有问题;但 6 条分片全员超时使每条分片继续触发 55m 中断并丢失全部 coverage 归并。
  • Impact: 合入后主干全量 Python Tests 仍将 100% 在 55 分钟撞线失败,同时以更大比例的 4 vCPU 争用继续暴露或放大依赖墙钟超时的脆弱测试,违背 Issue #8787 先止血诊断与修复挂起再调并发的工程原则。
  • Fix: 1)在本次 PR 中聚焦合入经过修复的诊断与协作 deadline 基础设施,或提供基于真实 CI -n 2 / -n 3 / -n 4 及隔离 test_profile_without_steerable_binding_keeps_four_ordinary_workers 之后的实测绿灯证据再切换 -n 4;2)同步修正工作流注释与 PR 说明中“~40 分钟完成”的未证实表述,并审视无持久化 .test_durations 时 --splitting-algorithm least_duration 导致的分片尾差(5317 vs 6645)。重跑命令:gh 工作流 Python Tests 全量 6 分片并校验 ci-shard-diagnostics.json 中 execution_complete == true。

阻塞问题 2:TimingObserver 在集合阶段耗时超过 --ci-session-deadline 时定时器会静默永久失效

  • Problem: pytest_sessionstart(scripts/ci/pytest_timing.py:406-411)在集合阶段前启动单次 threading.Timer,而 _on_deadline(L373)在 not self._loop_active 时直接 return 且不重设定时器。
  • Evidence: 本地反例构造:在 conftest.py 的 pytest_collection_modifyitems 中休眠 1.5s,设置 --ci-session-deadline 0.4,并执行一个耗时 5.0s 的用例。实测返回码为 0(墙钟 6.73s),ci-shard-diagnostics.json 记录 deadline_exceeded: false、execution_complete: true、pytest_exit_code: 0,定时器完全未触发中断。
  • Impact: 一旦某条分片因导入/集合卡顿超过会话预算(或预算设置较紧),协作式截止时间将完全失效,测试进程会一直跑满外部 60 分钟硬限,重新失去诊断与部分 junit.xml 保留能力。
  • Fix: 在 pytest_runtestloop 进入时检查已耗时长(或改在 pytest_runtestloop 入口按 max(0.0, self.deadline_seconds - self._elapsed()) 启动定时器,并在剩余时间 <= 0 时立即触发 _on_deadline;或允许 _on_deadline 直接中断卡在集合阶段的会话),并补充单测覆盖慢集合超时场景。重跑命令:uv run --extra test python -m pytest -q tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py。

非阻塞观察

  1. 本地反例验证 --ci-session-deadline 在 -n 4 下确实在 ~9.8s(deadline 3.0s)内中断阻塞用例并产出完备 junit.xml(保留已完成的 test_pass_1 与 test_fail_1)及可用 scripts/ci/pytest_timing.ts 解析输出;不过 junit.xml 在中断收尾时会附带无 name 属性的空 <testcase time="0.000" /> 占位节点(CI Shard 1 的 5,589 条 <testcase> 中有 4 条此类节点),后续统计脚本若直接读取 case.attrib["name"] 需保留防御性 .get("name")。
  2. scope_fit 与 default_off_isolation 核验:所有新增选项(--ci-session-deadline 0、--ci-diagnostics-file "")在默认关闭状态下均不启动定时器、不写诊断文件,不改变既有测试选择与 LOOPX_PYTEST_TIMING 输出;CI 路径通过 .github/workflows/python-tests.yml 真实调用生效。authority_semantics 与 semantic_alignment 均未引入跨运行时语义词表或虚假 actor 模型(not_applicable)。

我的整体评价 / Verdict

  • 长程与用户体验影响(outcome_impact):long_horizon = not_yet_proven、user_experience = not_yet_proven(visual_review = not_applicable,理由:本 PR 仅涉及 CI 脚本与 GitHub Actions 工作流配置,未修改任何前端渲染页面;unverified_scope = none)。诊断与部分结果保留本身显著提升了长程 CI 排障透明度,但 -n 4 在真实 CI 中仍 6/6 超时且未达到可用绿灯基线,使开发者仍需面对全分片红灯重试。
  • 兼容性、代码体积与工程比例:compatibility_assessment = retain(保留既有 LOOPX_PYTEST_TIMING 行协议供 scripts/ci/pytest_timing.ts 零改动消费),code_volume = partly_avoidable,change_proportionality = disproportionate、architecture_assessment = simplify_now:诊断插件本体结构清晰,但在未经隔离挂起或证明缩减墙钟时长前将 -n 4 与诊断捆绑合入,且存在集合超时定时器失效漏洞,需要先行收口。
  • 本地与 CI 验证汇总:
    • uv run --extra test python -m ruff check scripts/ci/pytest_timing.py tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py:PASS
    • uv run --extra test python -m pytest -q tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py:PASS(627 passed in 85.12s)
    • uv run --extra test python -m unittest discover -s scripts/ci -p 'test_*.py':PASS(23 tests OK)
    • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs:PASS(9 passed, 0 failed)
    • uv run --extra test python -m pytest -q --no-cov tests/test_ci_pytest_failure_context.py:PASS(26 passed in 9.70s)
    • uv run --extra test loopx canary premerge --tier quick --from-git-diff --git-diff-base f15ebdd16b5eb8cd01b2d112a3a0fe866b0f3486:PASS(3 catalog canaries + public boundary passed, failures=0)
    • 合成反例测试(-n 4 中断保留部分成功/失败 JUnit 与 pytest_timing.ts 解析):PASS;慢集合超过 --ci-session-deadline 测试:FAIL(复现定时器静默失效)。
    • 远端 CI test-shard (1)–(6):全部因撞线 3300s deadline 返回退出码 2 并伴随基线既有用例失败;checks 因 chat-bundle-browser (1) 被取消而失败。
  • 语义词表决策:not_applicable(仅本地诊断 schema loopx_ci_pytest_diagnostics_v1,不涉及共享状态词表)。
  • 后续复审所需证据:修复 TimingObserver 在慢集合阶段的定时器边界并补充回归测试;同时拆离或以真实 CI 实测绿灯(或先修复已暴露的 512s 阻塞测试后重测 -n 2 vs -n 4 墙钟对比)来验证并发调整的净收益。

English verdict: REQUEST_CHANGES on a971731: real CI run 43929531116 refutes the 40-minute green completion claim as all 6 test-shard jobs with -n 4 still hit the 3300s deadline under 4-vCPU subprocess contention, and TimingObserver._on_deadline silently drops the session deadline if test collection exceeds --ci-session-deadline.

…on (#8787)

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
@loopx-agent
loopx-agent force-pushed the codex/ci-python-shard-speedup-20261117 branch from a971731 to f2d6fac Compare November 19, 2026 20:01
@loopx-agent loopx-agent changed the title perf(ci): scale python test shards to 4 workers and preserve deadline diagnostics (#8787) fix(ci): preserve pytest deadline diagnostics and abort slow collection (#8787) Nov 19, 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)

针对精确头 f2d6fac64bd0c8b1a54d55d15a8166f8ec093c24(base 45c015ffd9c9065b3af533e0abf103170627d15f)的审查结论:建议合入(APPROVE)。本轮修订已彻底解耦此前在真实 CI 中未获证实的 -n 4 并发改动(恢复 test-shard 为 -n 2),同时修复了 TimingObserver 在集合阶段超出 --ci-session-deadline 时静默丢失超时中断的缺陷,保留了完整的 55 分钟协作式截止时间、部分 JUnit 保留与无敏感信息子进程诊断能力。

动机 / Motivation

运行 GitHub Actions Python Tests 全量分片任务(test-shard 1–6)的维护者与贡献者会直接受分片超时不透明的影响。改动前在基线 main 上,test-shard 以 -n 2 跑全量套件并受限于 60 分钟 Runner 硬限,外部强杀时既丢失部分 junit.xml(触发 upload-artifact 报错)又缺少在飞测试与子进程现场;改动后在保持 -n 2 的基础上增加 55 分钟(3300 秒)协作式软截止时间,并在集合超时、入口超限或执行超时时主动以退出码 2 收尾并原子输出 ci-shard-diagnostics.json。

超时分片(含慢集合阶段)稳定以退出码 2 提前退出,产出包含 deadline_exceeded=true、in_flight_cases 与去敏 active_child_processes 的诊断 JSON 及部分 junit.xml,而默认关闭状态(--ci-session-deadline 0)与基线完全等价。本次改动不调整 6 分片矩阵、Python 3.11 环境、19.6% 覆盖率门禁或 -n 2 并发度,也不直接修改各个具体业务测试内部的逻辑缺陷。剩余缺口在于后续独立隔离已被诊断暴露的 512 秒长尾阻塞用例,并在取得全量耗时基线后再评估分片均衡与并发扩容收益。

改动思路 / Approach

维度 基线 main(45c015ffd9) 本次精确头(f2d6fac64b) 边界与可逆性
分片并发度 -n 2 保持 -n 2(已撤回未证 -n 4) 零并发回归风险,待 hang 隔离后另案评估
超时收尾与产物 60m 被 Runner 强杀,always() 传 JUnit 缺文件报错 --ci-session-deadline 3300 在集合/循环/入口触发退出码 2,!cancelled() 上传部分 junit.xml 默认关闭(0),仅 CI 工作流显式启用
现场诊断与隔离 仅单用例栈打印,无条件 apt-get 装 bwrap 原子写 ci-shard-diagnostics.json(含 sanitized 子进程基名),command -v bwrap 按需安装 纯本地诊断投影,不改 pytest_timing.ts 协议

将协作式超时控制、子进程基名采样与诊断落盘收口在既有控制器观察插件 scripts/ci/pytest_timing.py 内,保持 pytest 与 DSession 对测试选择和执行结果的唯一权威,同时在工作流中保留 -n 2 避免未经隔离阻塞前的 4 核子进程争用。当前 PR 边界严格聚焦 Issue #8787 的 C1+C3 可观测性与协作式截止时间机制,刻意将 C2 并发扩容与业务测试 hang 修复留作后续独立交付。具体实现上,控制器单点 TimingObserver(not hasattr(config, "workerinput"))通过 session.shouldstop / dsession.shouldstop 与 _thread.interrupt_main() 唤醒主循环并在 pytest_sessionfinish 强制保留退出码 2;ci-shard-diagnostics.json(schema loopx_ci_pytest_diagnostics_v1)属于只读本地诊断投影(diagnostic_hint),与 scripts/ci/pytest_timing.ts 消费的 LOOPX_PYTEST_TIMING 流正交。工作流 .github/workflows/python-tests.yml 是该能力的唯一生产调用方。

具体改动 / Changes

对照规范 https://github.com/loopx-project/loopx/issues/8787(修订标识 #8787 )提出的准则逐条核验:

  • ISSUE-8787-C1(先让超时长尾可诊断,输出当前运行测试、有界栈/进程元数据与部分结果且保留失败退出码):implemented — 通过 --ci-session-deadline 3300、--ci-diagnostics-file ci-shard-diagnostics.json 与 _collect_descendant_processes 实现,保留退出码 2 与部分 junit.xml。
  • ISSUE-8787-C2(基于全量耗时分布平衡分片或先隔离挂起,再调整并发):deferred — 已按审查反馈将 .github/workflows/python-tests.yml 恢复为 -n 2,避免在隔离 512 秒死等测试前盲目提高并发,待后续独立 PR 处理。
  • ISSUE-8787-C3(在协作截止时安全卸载而不吞掉失败或阻塞部分结果上传):implemented — 修复了集合阶段超越 --ci-session-deadline 时定时器被丢弃的问题,工作流在 !cancelled() 下上传 junit.xml 并以 always() 上传诊断 JSON。

关键代码讲解

  1. _collect_descendant_processes(scripts/ci/pytest_timing.py):在 POSIX 环境下优先读取 /proc/<pid>/stat(无 /proc 时回退到 0.3s 有界超时的 ps -eo pid=,ppid=,stat=,comm= 并确保异常时 kill/wait),按 BFS 从控制器进程起收集最多 16 个子孙进程的 pid、ppid、state 与经 _sanitize_comm 清洗的可执行文件基名。函数刻意不读取 argv 或环境变量,防止敏感路径或凭据进入公共 CI 产物;单测 test_stall_snapshot_reports_descendant_child_process_basename_without_argv 已验证命令行载荷不会泄露。
  2. TimingObserver._record_deadline 与 _abort_if_deadline_exceeded(scripts/ci/pytest_timing.py):修复了旧版 _on_deadline 在 not self._loop_active 时直接丢弃超时的缺陷。现在 _record_deadline 仅在 _finished、_runtestloop_finished 或已触发 deadline_exceeded 时退出,无论超时发生在集合期还是执行期都会加锁记录 deadline_exceeded = True、采样在飞测试与子进程、设置 session.shouldstop 与 dsession.shouldstop、原子写入诊断 JSON,并在当前处于 pytest_collection 或 pytest_runtestloop 阻塞中时调用 _thread.interrupt_main() 立即唤醒主线程;_abort_if_deadline_exceeded 在 pytest_collection 和 pytest_runtestloop 入口检查 self.deadline_exceeded 或 self._elapsed() >= self.deadline_seconds,直接抛出 pytest.Session.Interrupted 确保测试不会越过截止时间继续执行。
  3. TimingObserver.pytest_collection 与 pytest_runtestloop(scripts/ci/pytest_timing.py):两处均使用 @pytest.hookimpl(wrapper=True, tryfirst=True),并在 self.deadline_seconds <= 0 时直接 return (yield) 实现零开销默认关闭隔离。开启截止时间后,pytest_collection 维护 _collection_active 标志以允许定时器在慢集合期间安全打断主线程;pytest_runtestloop 维护 _loop_active 并在正常无异常返回时原子置位 _runtestloop_finished = True,避免测试全部跑完后收尾瞬间被后台定时器误标记超时。pytest_sessionfinish 负责取消并 join 定时器,保持退出码为 ExitCode.INTERRUPTED(2)。
  4. test-shard 工作流与回归单测(.github/workflows/python-tests.yml):test-shard 维持 -n 2,仅在 command -v bwrap 缺失时安装 bubblewrap(带 --no-install-recommends),传入 --ci-session-deadline 3300 与 --ci-diagnostics-file ci-shard-diagnostics.json,将 junit.xml 上传条件收紧为 ${{ !cancelled() }} 并新增 always() 的诊断上传步骤;配套测试在 tests/test_ci_pytest_timing.py 与 tests/test_python_ci_workflow.py 覆盖了慢集合超时、pytest_runtestloop 入口守卫及工作流配置约束。

对主干的风险 / Risks

对精确头 f2d6fac64b 进行负向路径、默认关闭隔离与主干兼容性核验如下:

  • 慢集合超时与入口竞态:已构造本地反例(conftest.py 在 pytest_collection_modifyitems 中休眠 1.5s,设置 --ci-session-deadline 0.4 并包含 5.0s 用例)。无论在 -n 0 还是 -n 2 下,pytest 均在集合超时后以退出码 2 提前终止(-n 2 实测墙钟 2.92s),5.0s 用例从未执行,ci-shard-diagnostics.json 正确落盘 deadline_exceeded: true、execution_complete: false、pytest_exit_code: 2;单元测试 test_runtestloop_entry_aborts_when_session_deadline_already_elapsed 进一步覆盖了定时器在集合与测试循环间隙触发或计时已超限但回调尚未运行时的入口拦截与 dsession.shouldstop 同步。
  • 默认关闭隔离(default_off_isolation):在相同双用例夹具上对比基线 main(45c015ffd9)与精确头 f2d6fac64b 关闭选项运行(-n 2 --ci-session-deadline 0、无诊断路径),两者均以退出码 1 结束,scripts/ci/pytest_timing.ts 解析出的 execution_complete、selected_cases、observed_cases、finished_cases 与 invalid_duration_count 完全一致;pytest_collection 与 pytest_runtestloop 在 deadline_seconds <= 0 时直接 return (yield),不启动定时器也不落盘任何文件。
  • 非阻塞残余风险:中断收尾时 pytest 原生 junit.xml 仍可能包含无 name 属性的空 <testcase /> 占位节点,现有测试与本轮修改已统一采用防御性 case.attrib.get("name") 过滤;scope_fit 通过 .github/workflows/python-tests.yml 直接落地;authority_semantics 与 semantic_alignment 均未改变共享状态机或引入跨运行时语义词表(not_applicable)。

我的整体评价 / Verdict

  • 长程与用户体验影响(outcome_impact):long_horizon = improved(超长分片可在 55 分钟可控退出并持续沉淀部分 JUnit 与在飞/子进程诊断,避免 60 分钟盲目强杀)、user_experience = improved(visual_review = not_applicable,本 PR 仅修改 CI 观测脚本、单元测试与 GitHub Actions 工作流配置,未触及任何前端渲染页面或用户界面。;unverified_scope = none)。
  • 兼容性、代码体积与工程比例:compatibility_assessment = retain(零改动保留 LOOPX_PYTEST_TIMING 行协议供 scripts/ci/pytest_timing.ts 消费)、code_volume = necessary、change_proportionality = proportionate、architecture_assessment = retain、default_off_isolation = isolated、authority_semantics = not_applicable。上一轮阻塞问题(-n 4 争用未证、集合期超时丢定时器)均已在此头完全解决。
  • 精确头本地验证汇总(Goal 策略 wait_for_ci = false,以本地全量受影响套件与反例验证为决定性依据):
    • uv run --extra test python -m ruff check scripts/ci/pytest_timing.py tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py tests/test_ci_pytest_failure_context.py:PASS
    • uv run --extra test python -m pytest -n 3 -q tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py tests/test_ci_pytest_failure_context.py:PASS(656 passed in 54.64s)
    • uv run --extra test python -m unittest discover -s scripts/ci -p 'test_*.py':PASS(23 tests OK)
    • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs:PASS(9 passed, 0 failed)
    • 慢集合 -n 2 反例与默认关闭(--ci-session-deadline 0)基线/头对比:PASS(慢集合 2.92s 退出码 2 并落盘 deadline_exceeded: true;默认关闭与 main 完全等价)
    • loopx canary premerge --tier quick --from-git-diff --git-diff-base origin/main --goal-id personal-loopx-maintenance:PASS(cqr_f79248c6f3b054fd3a62 有效,public_boundary: ok)
    • 历史诊断记录(旧头 a971731e53):GitHub Run 43929531116(required=false 诊断参考)验证了 -n 4 争用问题,已通过本轮回退至 -n 2 消除。
  • 语义词表决策:not_applicable(仅本地诊断文件 schema loopx_ci_pytest_diagnostics_v1,不涉及共享状态或协议词表)。

English verdict: APPROVE on f2d6fac: decoupled unproven -n 4 scaling back to -n 2, fixed TimingObserver slow-collection and pre-loop deadline handling with regression tests, and all 656 pytest cases, ruff, unittest, node tests, counterfactuals, and CQR premerge passed locally.

This branch has not been deployed

No deployments
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