Skip to content

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

Merged
huangruiteng merged 7 commits into
mainfrom
codex/ci-python-shard-speedup-20261117
Nov 25, 2026
Merged

huangruiteng merged 7 commits 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) and address the [P2] blocker from PRR_kwDOStEbEs8AAAABZs7Z1g so Python Tests shard timeouts preserve partial JUnit outcomes and live progress/process diagnostics within the 60m outer job budget regardless of setup duration, while keeping Python 3.11 checks, -n 2, 6-shard selection, and the 19.6% coverage floor unchanged.
  • What Changed:
    1. Dynamic Job-Budget Calculation & Pre-Shard Fail-Fast (scripts/ci/shard_budget.py, .github/workflows/python-tests.yml):
      • Record LOOPX_SHARD_JOB_START_EPOCH=$(date -u +%s) into $GITHUB_ENV in a dedicated Record job start time step at the very start of test-shard (before actions/checkout, artifact download, dependency installation, and bwrap setup).
      • Introduce scripts/ci/shard_budget.py (282 LOC, 0 Any, 0 # type: ignore) as the single shard launcher entrypoint (python -m scripts.ci.shard_budget --job-budget-seconds 3600 --upload-reserve-seconds 300 --min-session-seconds 300 --diagnostics-file ci-shard-diagnostics.json -- ...):
        • Computes remaining_session_seconds = job_budget_seconds - elapsed_prep_seconds - upload_reserve_seconds (clamping clock skew so elapsed_prep_seconds >= 0, failing closed when LOOPX_SHARD_JOB_START_EPOCH is missing/malformed under GITHUB_ACTIONS=true, and rejecting duplicate --ci-session-deadline).
        • When remaining_session_seconds < min_session_seconds, refuses to start pytest (exit code 2), emits a clear human-readable budget diagnostic (job_budget, elapsed_prep, upload_reserve, remaining vs min_session), and atomically writes ci-shard-diagnostics.json (pre_shard_budget_exhausted: true, deadline_exceeded: true) for the always() diagnostics upload step.
        • Otherwise invokes pytest with --ci-session-deadline={remaining_session_seconds:.3f} so cooperative abort + partial JUnit flush + upload reserve always occur before the 60m runner deadline.
      • Share atomic_write_text and DIAGNOSTICS_SCHEMA_VERSION from scripts/ci/shard_budget.py with scripts/ci/pytest_timing.py.
    2. Cooperative Session Deadline, Early Partial JUnit & Serialized Diagnostics (scripts/ci/pytest_timing.py, .github/workflows/python-tests.yml):
      • Track active collection and runtest loop phases via _abort_if_deadline_exceeded, interrupt blocked execution via signal.pthread_kill(..., SIGINT) (falling back to _thread.interrupt_main()), flush partial junit.xml atomically before DSession teardown waits on blocked workers (_DeadlineSessionHook, _flush_partial_junit, _JUnitSummaryHook), bound xdist teardown (EXIT_TIMEOUT <= 1.0s, _bound_xdist_teardown), and serialize ci-shard-diagnostics.json writes so lagging progress snapshots never corrupt or overwrite deadline_exceeded=true.
      • Guard Upload full-shard outcomes for selection audit with if: ${{ !cancelled() }}, upload python-diagnostics-${{ matrix.shard }} with if: always(), retain -n 2, and install bubblewrap only if command -v bwrap is absent.
    3. Regression & Workflow Contract Coverage (tests/test_ci_pytest_timing.py, tests/test_python_ci_workflow.py):
      • Added unit validation (test_shard_budget_computation_and_fail_closed_validation) covering normal/boundary budget arithmetic, clock skew clamping, malformed/missing CI epoch fail-closed checks, and duplicate deadline rejection.
      • Added real subprocess -n 2 fast-vs-slow prep reproduction (test_shard_budget_preserves_reserve_across_fast_and_slow_prep) exercising 0.2s prep (5.0s budget, 2.6s reserve -> exit=2, partial junit.xml + deadline_exceeded=true before 5.0s), 3.6s prep exceeding viable floor (5.0s budget -> fast pre-shard exit=2 with readable budget error + diagnostics before 5.0s, zero tests started), and 3.6s tight-but-viable prep (9.0s budget, 3.0s reserve -> shortened dynamic deadline preserving the reserve).
      • Updated test_python_shards_preserve_two_workers_and_deadline_diagnostics and workflow execution isolation in tests/test_python_ci_workflow.py (0 stale hardcoded --ci-session-deadline 3300).

Verification (Head 7e13cd7d5b, merged with latest origin/main f37e1c6589)

  • Before vs After Fast/Slow Prep Reproducer (scripts.ci.shard_budget, real -n 2 + pytest_timing, blocked 10s test):
    • Baseline fixed --ci-session-deadline 2.2 under 5.0s outer limit: prep=0.2s -> rc=2, junit=True (2.78s); prep=3.6s -> killed at 5.0s outer timeout (junit=False).
    • Current python -m scripts.ci.shard_budget:
      • prep=0.2s (budget=5.0s, reserve=2.6s) -> rc=2 in 3.00s/5.0s, deadline_seconds=2.166, junit=True (test_fast), deadline_exceeded=True.
      • prep=3.6s (budget=5.0s, reserve=2.6s) -> pre-shard fail-fast rc=2 in 3.65s/5.0s, junit=False, pre_shard_budget_exhausted=True, deadline_exceeded=True.
      • prep=3.6s (budget=9.0s, reserve=3.0s) -> rc=2 in 6.63s/9.0s, deadline_seconds=2.357, junit=True (test_fast), deadline_exceeded=True.
  • 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 tests/test_stage2c_dependency_lock.py tests/architecture/test_top_level_module_budget.py tests/test_codeowners.py tests/canary/test_maintainability_ratchet.py -> 687 passed, 1 skipped in 57.32s.
  • uv run --extra test python -m unittest discover -s scripts/ci -p 'test_*.py' -> Ran 23 tests, OK.
  • uv run --extra test python -m ruff check scripts/ci/shard_budget.py scripts/ci/pytest_timing.py tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py -> All checks passed!.
  • uv run --extra test python -m mypy --explicit-package-bases --strict scripts/ci/shard_budget.py -> Success: no issues found in 1 source file (0 Any, 0 # type: ignore).
  • uv run --extra test python -m mypy (17 kernel files) -> Success: no issues found in 17 source files.
  • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs -> 9 passed, 0 failed; npm run typecheck:control-plane -> passed.
  • uv run --extra test python scripts/check_rfc_bilingual.py --base origin/main --head HEAD -> RFC bilingual diff check passed..
  • loopx canary premerge --from-git-diff --git-diff-base origin/main (clean worktree on 7e13cd7d5b) -> status: passed, merge_gate_passed: true, selected=7, failures=0 (6/6 catalog canaries incl. semantic-vocabulary-drift-smoke.py, 1/1 public boundary, manual_holds=0).

@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.

@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, xhigh)

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

P2,阻塞。截止已记账,部分 JUnit 仍等阻塞用例返回。 在实际 pytest 命令加载 scripts.ci.pytest_timing,设置 --ci-session-deadline=1.3 和 --junitxml=out.xml,运行一个快测试和一个阻塞 6 秒的测试。进程启动 3 秒时已可读到 deadline JSON,pytest 仍在运行,JUnit 尚未生成。-n 0 和 -n 2 均约 6.4 秒才退出 2、写出部分 JUnit。 建议在外层上传窗口内做有界收尾,或让结果在此之前独立可读。 截止处理

P2,阻塞。并发写诊断会发布损坏的 JSON。 在真实 -n 2 CLI 中让进度写入打开暂存文件,再让截止线程写入并 rename。恢复进度写入后,目标 JSON 无法解析。会话退出时最后一次写入恢复了文件。 当前快照锁不覆盖写入,两个线程按同一 PID 命名暂存文件。应序列化发布,并防止较旧进度覆盖截止快照。 诊断发布

动机 / Motivation

维护 Python Tests 分片的人,需要在 runner 杀作业前读到正在阻塞的用例和已完成的测试结果。 长尾分片在外层作业限时被取消,完成结果可能还没写成 JUnit,维护者缺少定位依据。 候选在现有 pytest 插件内增加会话截止时间和诊断,保留两 worker。实测截止时可记录阻塞用例,部分 JUnit 仍等阻塞调用返回后才生成。 本次是本地 pytest 与 xdist 的验证。GitHub 托管 runner 的整分片耗时、上传和 Linux 进程读回未实测。

改动思路 / Approach

pytest 与 xdist 保持测试执行及结果所有权,现有 TimingObserver 提供诊断;工作流拥有外部作业预算和上传。 保留现有插件和工作流的责任分界。在现有结果所有者处缩小修复范围,避免扩大并发或放松失败门。 主要决策路径位于 scripts/ci/pytest_timing.py。评审以 https://github.com/loopx-project/loopx/issues/8787 在 #8787 的要求为依据。 验收来源

具体改动 / Changes

精确头 f2d6fac64bd0c8b1a54d55d15a8166f8ec093c24,基线 45c015ffd9c9065b3af533e0abf103170627d15f。共 4 个文件,新增 679 行,删除 12 行。与当前主干 f0018b1b19 干净整合。

  • ISSUE-8787-C1。截止时能记录正在运行的 test_stalled 并保留失败退出,进度与截止写盘交错时丢失有效 JSON。
  • ISSUE-8787-C2。撤回此前四 worker 的方案,保留两 worker、六分片与原覆盖门;继续隔离真实 hang 并收集全量耗时分布后再评估。
  • ISSUE-8787-C3。短集合反例能带失败退出并保留诊断。遇到持续阻塞的运行,内层会话截止到外层 runner 之间能否留下 JUnit 仍没有保证。正常结束时,工作流以 !cancelled() 上传 JUnit,并用 always() 尝试上传诊断。bubblewrap 仅在缺失时安装,实际 user namespace 探测仍执行。 工作流

关键代码讲解

  • _record_deadline。在控制器写入超时快照并请求停止。阻塞 worker 的退出仍由 xdist 收尾决定。 源码
  • _write_diagnostics。锁只保护快照组装,进度与定时器共用 PID 命名的临时文件。 源码
  • test-shard。沿用两 worker、六分片与覆盖门,提早配置截止时间并上传 JUnit 与诊断。 源码

对主干的风险 / Risks

同一 -n 2 通过及失败用例在未启用的基线、精确头、整合树均退出 1,包含相同 JUnit 用例和规范化 timing 事件,均无诊断文件。 精确头相关源码测试 655 项通过、1 项跳过。 精确头 quick premerge 的 5 项直接和 4 项选中检查通过。 Ruff、diff whitespace 与 DCO 通过。 合成阻塞与并发对照复现两个缺口。真实托管环境的完整作业、产物上传和 Python 3.11 Linux 行为仍待验证。

我的整体评价 / Verdict

REQUEST_CHANGES。 为 pytest 及 worker 收尾设定有界退场,或由现有结果 owner 在阻塞结束前持久化可上传的部分结果。把诊断快照到发布的写入串行化,避免复用暂存文件并保证截止快照不会倒退。 未查询托管 CI。验证使用 macOS 本地进程和合成测试。

English verdict: REQUEST_CHANGES at f2d6fac. A recorded deadline leaves JUnit unavailable while pytest/xdist waits for a blocked test, and concurrent progress and deadline writes can corrupt the published JSON. The default-off baseline comparison and eventual timeout exit code both hold.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
…s on deadline (#8787)

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)

针对精确头 b9a1f81c7aa40ba086e3eaa33d7040799662a58c(base bbd26838366cf03b371f5a2308833e03d1e1229b)的独立复审结论:建议合入(APPROVE)。

本轮提交(b9a1f81c7a)已逐项彻底修复上一轮 gpt-6.2-sol 提出的全部两项 [P2] 阻塞意见,同时完整保留此前针对 #8787(C1 + C3)收敛后的安全边界(保持 -n 2 并发、慢集合与循环入口超限拦截):

  1. 已解决 [P2-1](截止已记账但部分 JUnit 仍等阻塞用例返回):在 scripts/ci/pytest_timing.py 新增 _interrupt_main_locked()(POSIX 且激活默认 SIGINT 处理器时直接调用 signal.pthread_kill(..., signal.SIGINT) 打断阻塞中的 C 睡眠或系统等待,否则回退 _thread.interrupt_main())、TimingObserver.pytest_runtest_protocol 入口/出口守卫,以及仅在 deadline_seconds > 0 时注册的 _DeadlineSessionHook(@pytest.hookimpl(tryfirst=True))。超时触发结束阶段时调用 prepare_deadline_sessionfinish():率先通过 _flush_partial_junit -> _render_junit_xml + _atomic_write_text 抢在 DSession.pytest_sessionfinish() 等待阻塞 worker 前原子写盘部分 junit.xml(同步卸载 LogXML、在 POSIX 重定向 xml.logfile 至空设备并挂入 _JUnitSummaryHook 保留终端摘要输出,杜绝后续 teardown 再次覆盖截断),随后向本地活跃 xdist worker 发送 SIGINT 并将 nodemanager.EXIT_TIMEOUT 封顶为 1.0s(_bound_xdist_teardown)。对照复现(test_fast + time.sleep(6.0)、--ci-session-deadline=1.3)下,-n 0 于 2.082s、-n 2 于 2.137s 均以退出码 2 完成并生成包含 test_fast 的 out.xml;针对无视 SIGINT 休眠 20s 的不可中断 worker 回归测试更实测进程退场途中即可无 ParseError 地读回 out.xml,整轮运行于 < 7s 收敛结束。
  2. 已解决 [P2-2](并发写诊断会发布损坏 JSON 或被较旧进度覆盖):在 TimingObserver.__init__ 将 self.diagnostics_path 固定为启动目录的绝对路径,新增 self._write_lock 串行化快照组装、计数推进与落盘全流程,并以同目录唯一临时文件加 os.replace 的 _atomic_write_text(异常时在 finally 清理残留 .tmp)替代按 PID 复用的临时路径;为 _write_diagnostics 增加 kind: Literal["progress", "deadline", "final"] 保护,当 _finished 或 deadline_exceeded 已成立时在锁内直接忽略滞后抵达的 "progress" 刷盘。真实 -n 2 并发延迟写盘压力测试与单元直测均证明零 JSONDecodeError 且 deadline_exceeded=true 永不回退。

动机 / Motivation

受影响方与触发场景:使用 GitHub Actions 运行全量 Python Tests 6 分片作业的维护者与贡献者在长尾分片接近 60 分钟 Runner 超限时直接受影响。

改前与改后变化:改前在基线 main 上,test-shard 以 -n 2 跑全量套件并受限于 60 分钟硬限,超限被强杀时既丢失部分 junit.xml 又缺少正在阻塞用例与子进程现场;先前的 f2d6fac 候选虽加了 55 分钟软超时与诊断文件,但阻塞测试或 xdist 10 秒退场仍会拖延 JUnit 落盘,且并发刷新会损坏 JSON。改后精确头通过 pthread_kill 即时唤醒、抢在 worker 退场前原子刷写部分 JUnit、限制 xdist 收尾为 1 秒并串行写盘防倒退,在 60 分钟强杀前稳定交出可读 JUnit 与完整诊断。

可观测输出:超时分片(含慢集合与阻塞用例)稳定以退出码 2 收尾,及时生成合法可读的部分 junit.xml、含 deadline_exceeded=true、in_flight_cases、longest_cases 与去敏子进程基名 active_child_processes 的 ci-shard-diagnostics.json,且默认关闭路径与基线完全等价。

非目标范围:本 PR 不调整 6 分片矩阵、不恢复 -n 4 并发扩容、不放宽 Python 3.11 检查或 19.6% 覆盖率门禁,也不直接修复单个业务测试内部死等缺陷。

分阶段剩余缺口:在取得全量用例真实耗时分布后隔离已暴露的 512 秒死等用例并按耗时均衡分片(对应 Issue 8787 第二条准则)留待后续独立 PR 交付。

改动思路 / Approach

维度 基线 main(bbd2683836) 上一轮审查头(f2d6fac64b) 本次精确头(b9a1f81c7a) 机制角色与归属边界
分片并发与门禁 -n 2,6 分片,60m 硬限 保持 -n 2(已撤回 -n 4),--ci-session-deadline 3300 保持 -n 2,6 分片,19.6% 覆盖门不变 policy(.github/workflows/python-tests.yml)
阻塞中断与早写 JUnit 强杀后缺 JUnit,always() 报错 _thread.interrupt_main() 不破 POSIX sleep;JUnit 等阻塞返回 pthread_kill(SIGINT) + _DeadlineSessionHook 先原子写 JUnit 再限 EXIT_TIMEOUT=1.0s invariant(scripts/ci/pytest_timing.py)
诊断文件一致性 无 ci-shard-diagnostics.json _lock 不包写盘,共用 .pid.tmp 造成损坏/倒退 固定绝对路径 + _write_lock + mkstemp/os.replace + 拒绝对齐过期 progress invariant + projection(loopx_ci_pytest_diagnostics_v1)
默认隔离与兼容 仅输出 LOOPX_PYTEST_TIMING 保留行协议,按需安装 bwrap 仅在 deadline_seconds > 0 注册收尾 hook,既有调用方零增量开销 local_helper + 默认关闭隔离

架构合理性与设计对照(architecture_assessment = retain):将协作超时中断、部分 JUnit 原子早写、xdist 1 秒退场封顶与诊断 JSON 串行防倒退写盘收口在既有插件 scripts/ci/pytest_timing.py 内,保持 pytest、DSession 与 LogXML 对测试选择、执行和结果格式的唯一权威,可逆且不新增控制面状态机。 当前 PR 交付 Issue 8787 第一与第三条所要求的可观测诊断、慢集合截断、早写部分 JUnit 与有界收尾契约并维持 -n 2,将基于耗时分布的分片均衡与个别挂起测试修复安全隔离到后续独立 PR。 之所以不在 pytest 外再包装超时外壳或强行把 -n 4 扩回本次 PR,是因为外部进程超时会彻底丢弃内存态的 LogXML 已完结用例报告与阻塞堆栈,而真实 CI Run 43929531116 已证实未先隔离长尾挂起用例前的 4 worker 争用反而会加重全部 6 条分片的超时;在单一控制器观察插件内新增上述串行发布与有界收尾逻辑,改动高度局部、零控制面耦合且随时可通过删除两条工作流参数完整回退。

具体改动 / Changes

精确头 b9a1f81c7aa40ba086e3eaa33d7040799662a58c 相对基线 bbd26838366cf03b371f5a2308833e03d1e1229b 共修改 4 个文件(+1108 / -14 行:生产代码 scripts/ci/pytest_timing.py +594/-7、工作流 .github/workflows/python-tests.yml +20/-6、测试/夹具 tests/test_ci_pytest_timing.py +471/0、tests/test_python_ci_workflow.py +23/-1)。

对照参考规范 #8787 (修订标识 #8787 )提出的各准则映射如下:

  • ISSUE-8787-C1(在调整并发前先让超时长尾可诊断,输出当前运行测试、有界栈/子进程元数据与部分结果并保持失败退出码):implemented — scripts/ci/pytest_timing.py 实现 --ci-session-deadline、--ci-diagnostics-file、--ci-stall-after 子进程基名抓取与 LOOPX_PYTEST_DEADLINE 事件,强制保留退出码 2 并串行保护 JSON 一致性。
  • ISSUE-8787-C2(基于全量耗时分布均衡分片或先隔离 hang 再改变并发或矩阵):deferred — .github/workflows/python-tests.yml 保持 -n 2 与 6 分片矩阵不变,待诊断积累完整耗时分布并解决个体 hang 后在独立 PR 推进。
  • ISSUE-8787-C3(在协作截止或取消发生时及时保留可上传的部分结果并预留有界收尾窗口):implemented — 通过 pthread_kill(SIGINT)、_DeadlineSessionHook 抢先原子落盘部分 JUnit、屏蔽后续 LogXML 截断并将 EXIT_TIMEOUT 上限压至 1.0s 实现;工作流收紧 JUnit 上传为 ${ !cancelled() } 并增加 always() 诊断上传。

关键代码讲解

  1. TimingObserver._write_diagnostics 与 _atomic_write_text(scripts/ci/pytest_timing.py 及 L503-L531):在 __init__ 将 diagnostics_path 固定为启动 cwd 绝对路径后,_write_diagnostics 用 self._write_lock 全程包住快照装配、self._last_diag_flush_* 刷新和磁盘写入。写入前在锁内校验 kind: Literal["progress", "deadline", "final"]:一旦 _finished 或 deadline_exceeded 为真,后到的 "progress" 立即短路退出。写盘调用 _atomic_write_text 通过 tempfile.mkstemp 在目标同目录创建唯一临时文件并 os.replace 发布,消除同 PID 临时文件名碰撞。
  2. _DeadlineSessionHook.prepare_deadline_sessionfinish、_flush_partial_junit 与 _bound_xdist_teardown(scripts/ci/pytest_timing.py 及 L550-L559):pytest_configure 仅当 observer.deadline_seconds > 0 时注册 loopx-ci-deadline-shutdown;触发中断或结束钩子(tryfirst=True)时通过 _deadline_teardown_prepared 幂等执⾏收尾前准备。_flush_partial_junit 读取 _pytest.junitxml.xml_key 渲染当前已完成节点并以 _atomic_write_text 立即写出 XML,同时注销 LogXML、将 POSIX xml.logfile 指向空设备(防止 pluggy 已缓存当前阶段列表后再次写空覆盖)并挂回 _JUnitSummaryHook;接着 _bound_xdist_teardown 向活跃本地 xdist worker 发送 SIGINT 并把 nodemanager.EXIT_TIMEOUT 封顶为 1.0s。
  3. TimingObserver._interrupt_main_locked、_record_deadline 与 pytest_runtest_protocol(scripts/ci/pytest_timing.py):_record_deadline 先采集最多 16 个去敏子孙进程基名,加锁记录超限快照与 shouldstop 后写出 kind="deadline" 诊断。若此时主线程仍处在集合或测试循环中,调用 _interrupt_main_locked():在 POSIX 且 SIGINT 仍为 default_int_handler 时用 signal.pthread_kill(main_ident, signal.SIGINT) 立即唤醒阻塞中的 time.sleep 或系统调用,否则回退 _thread.interrupt_main()。同时 pytest_collection、pytest_runtestloop 与 pytest_runtest_protocol 在超限后立即抛出 pytest.Session.Interrupted 并保证退出码为 ExitCode.INTERRUPTED(2)。
  4. test-shard 工作流配置与新增回归测试(.github/workflows/python-tests.yml、tests/test_ci_pytest_timing.py、tests/test_python_ci_workflow.py):工作流保持 -n 2 与 --ci-stall-after 120,启用 --ci-session-deadline 3300 与 --ci-diagnostics-file ci-shard-diagnostics.json,按需安装 bubblewrap;配套回归测试以真实 -n 0/-n 2 子进程校验阻塞打断与早期 JUnit 读回、不可中断 SIG_IGN worker 的 out.xml 途中可读性与 < 7s 收尾、并发延迟刷盘下的零 JSON 解析错误与单调性,以及工作流静态参数契约。

对主干的风险 / Risks

  • 负向与阻塞反例验证:
    • 阻塞用例即时退场与早写 JUnit(对应 [P2-1]):在 --ci-session-deadline=1.3 下运行包含 test_fast 与 time.sleep(6.0) 的夹具,-n 0 实测 2.082s、-n 2 实测 2.137s 均以退出码 2 终止并产含 test_fast 的 out.xml 与完整 diag.json(deadline_exceeded=true、in_flight_cases=['test_repro.py::test_blocked']);test_session_deadline_flushes_junit_early_and_bounds_uninterruptible_worker 针对忽略 SIGINT 且休眠 20 秒的 worker 验证了退场完成前即可无 ParseError 解析 out.xml,且整体运行被 1.0s EXIT_TIMEOUT 约束在 < 7s 完成。
    • 并发写盘一致性与状态单调性(对应 [P2-2]):test_concurrent_progress_and_deadline_diagnostics_never_corrupt_or_regress 在 -n 2 真实运行中对首次 "progress" 写入注入 0.45s 延迟,并由 5ms 轮询线程持续解析目标文件,验证零 JSONDecodeError 且 deadline_exceeded=true 后永不回退;同时以单元直测覆盖逾期 "progress" 刷盘被跳过。
    • 慢集合期超限中断:-n 2 下集合钩子休眠 1.5s、--ci-session-deadline=0.4,pytest 在 1.47s 以退出码 2 退出,未运行任何测试(execution_complete=false、deadline_exceeded=true)。
  • 默认关闭隔离(default_off_isolation = isolated):在同一 -n 2 双用例(一过一败)夹具上对比基线 origin/main(bbd2683836)、精确头未传新增参数与精确头传入 --ci-session-deadline=0 三组实测:三者全部退出码为 1,产出完全一致的 9 条 LOOPX_PYTEST_TIMING 事件(start、collection、6 条 phase、end),out.xml 均仅包含 ['test_fail', 'test_pass'] 且均不生成诊断文件;此外,既有未传新参数的调用方 scripts/qualify_release_commit.py 不触发任何新 hook 或定时器。
  • scope_fit、authority_semantics 与 semantic_alignment:scope_fit 由 .github/workflows/python-tests.yml 直接激活;authority_semantics 为 not_applicable(无多 Agent 租约或权限控制面改动);semantic_alignment 为 not_applicable(loopx_ci_pytest_diagnostics_v1 为独立局部诊断 JSON 格式,未改动共享状态词表,下游 scripts/ci/pytest_timing.ts 解析兼容未破坏)。
  • 诚实残余边界:_flush_partial_junit 读取 pytest 内部 _pytest.junitxml.xml_key 与 LogXML 成员并已包裹容错回退,若未来 pytest 大版本变更内部私有属性名则会安全返回 False 交由原 LogXML 收尾;同时本次验证基于本地 macOS(Python 3.14.8)与合成并发夹具,GitHub 托管 Ubuntu Python 3.11 Runner 全量 6 分片真实耗时、/proc 遍历与产物上传在 Goal wait_for_ci: false 策略下未实测远端 CI,仅通过工作流语法测试与本地仿真等价替代。

我的整体评价 / Verdict

  • 长程与用户体验影响(outcome_impact):
    • long_horizon = improved:为长达一小时的 CI 校验建立可控软超时、即时部分结果沉淀和无破坏去敏现场快照,使后续分片优化与 hang 修复直接建立在实证基础上。
    • user_experience = improved(visual_review = not_applicable,理由:已检查全部 4 个改动文件 .github/workflows/python-tests.yml、scripts/ci/pytest_timing.py、tests/test_ci_pytest_timing.py 与 tests/test_python_ci_workflow.py,仅涵盖 CI 观测脚本与工作流配置,不触及任何前端或 UI 渲染画面;unverified_scope = none)。
  • 兼容性、代码体积与工程比例:observable_semantics = intentional_change_validated(默认关闭与基线 origin/main 逐事件完全一致;启用时按设计引入可控协同中断与原子诊断)、compatibility_assessment = retain(LOOPX_PYTEST_TIMING 行协议零破坏兼容 scripts/ci/pytest_timing.ts 与 scripts/qualify_release_commit.py)、code_volume = necessary、change_proportionality = proportionate、architecture_assessment = retain、default_off_isolation = isolated、authority_semantics = not_applicable。
  • 语义词表决策:not_applicable(仅新增单向本地诊断格式 loopx_ci_pytest_diagnostics_v1,不引入或扩展跨模块共享语义词表,双语 RFC 差检无需修改且已通过)。
  • 精确头 b9a1f81c7aa40ba086e3eaa33d7040799662a58c 本地验证汇总(依据 Goal 策略 wait_for_ci = false,远端 CI 未列为必需阻断项):
    • 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(660 passed in 56.12s)
    • uv run --extra test python -m pytest -q --no-cov tests/test_stage2c_dependency_lock.py tests/architecture/test_top_level_module_budget.py:PASS(7 passed in 0.39s)
    • uv run --extra test python -m ruff check(4 个相关文件及核心包 tests loopx/canary loopx/control_plane loopx/domain_packs loopx/presentation):PASS(All checks passed!)
    • uv run --extra test python -m mypy:PASS(Success: no issues found in 17 source files)
    • uv run --extra test python -m unittest discover -s scripts/ci -p 'test_*.py':PASS(Ran 23 tests in 5.886s, OK)
    • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs 与 npm run typecheck:control-plane:PASS(9 passed, 0 failed / TS exit 0)
    • python3 scripts/check_rfc_bilingual.py --base origin/main --head HEAD & loopx check:PASS(ok=True, errors=0,仅既有 test_ci_pytest_timing.py:560 测试夹具字符串提示)
    • loopx canary premerge --from-git-diff --git-diff-base origin/main --goal-id personal-loopx-maintenance:PASS(status=passed, merge_gate_passed=true, 6/6 catalog canaries, 1/1 public boundary, CQR cqr_7c2fd74e068ee5a7965d valid)
    • 合成阻塞反例(-n 0 2.082s / -n 2 2.137s 均退出 2 并生成包含 test_fast 的 out.xml 与完整 JSON)、慢集合 -n 2(1.47s 退出 2)及三方默认关闭对照等价实测:PASS

English verdict: APPROVE on b9a1f81: resolved both [P2] blockers via pthread_kill SIGINT wakeup, early atomic partial JUnit flush with bounded 1.0s xdist worker teardown, and serialized unique-tempfile diagnostics publishing rejecting stale progress updates; all 660 targeted pytest cases, ruff, mypy, unittest, node tests, counterfactual/default-off parity checks, and standard canary premerge passed locally.

@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 · xhigh

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

动机 / Motivation

负责 Python Tests 分片的人需要在作业被终止前看到阻塞的用例和已经完成的测试结果。 旧提交能标记截止,却要等阻塞调用结束才写出部分 JUnit。进度和截止同时写入时也可能破坏诊断。 给现有 pytest 分片提早写出诊断和部分结果的时间,同时保留两 worker、六分片、完整选择审计与现有覆盖门。

使用 Linux Python 3.11 的真实 pytest,运行一个快用例和一个 7 秒阻塞用例,然后比较旧提交和当前提交的截止、JUnit 与退出。 在 -n 0 和 -n 2 下,新头 4 秒时均已有截止快照和有名的已完成测试,退出 2。旧头在同一时点尚无 JUnit 且进程仍在运行。新写入锁和每次唯一暂存文件防止旧进度覆盖已发布的截止快照。 Linux 验证使用本地 Python 3.11 容器和缩短的真实进程时限。GitHub 托管作业的完整安装、上传和调度未执行,失败门未标为通过。

[P2] 作业准备耗时可能吃完截止与上传的预留时间

候选工作流在 checkout、下载、依赖安装和 bwrap 准备后才启动 3300 秒计时。这些步骤共用同一个 60 分钟 job 预算。用 5 秒外层期限、2.2 秒内层期限运行同一 -n 2 CLI。准备耗时 0.2 秒时退出 2 并保留 JUnit。准备耗时 3.6 秒时已有测试完成,外层终止仍先发生,没有截止快照或 JUnit。 按作业已用时间计算 pytest 可用预算,为输出和上传显式留出余量。余量不足时在启动分片前给出可读失败,并用两种准备耗时的同一入口核验。 当前提交

改动思路 / Approach

pytest 和 xdist 仍拥有测试结果。TimingObserver 负责记录和写出本地诊断,工作流负责外层时钟、产物路径与上传条件。 保留两 worker 和修复的插件收尾。在现有工作流按剩余时间取内层期限,无需并行报告体系或扩大 runner 期限。 真实 pytest -n 0/-n 2 修复旧头提前导出和串行发布的两项问题。

具体改动 / Changes

精确头 b9a1f81c7aa40ba086e3eaa33d7040799662a58c,对比基线 bbd26838366cf03b371f5a2308833e03d1e1229b。4 个文件,+1108/−14。 验收依据

  • C1 截止诊断保留失败语义(implemented)。在 -n 0 和 -n 2 下,新头 4 秒时均已有截止快照和有名的已完成测试,退出 2。旧头在同一时点尚无 JUnit 且进程仍在运行。新写入锁和每次唯一暂存文件防止旧进度覆盖已发布的截止快照。
  • C3 外层期限前保留可上传结果(not_met)。安装、下载和沙箱准备占用外层作业时间,超过 60 分钟与 3300 秒内层期限之间的 5 分钟差。 影响路径

关键代码讲解

  • test-shard。外层 60 分钟覆盖准备、pytest 和上传。pytest 另从自身启动后计时。 代码
  • _flush_partial_junit。在阻塞收尾前原子发布部分 XML。实际样例保留了已完成用例。 代码
  • _write_diagnostics。用发布锁和独立暂存文件保护截止快照。 代码
  • _record_deadline。记录运行中用例及子进程状态,并请求停止。 代码
  • pytest_sessionstart。以观察者自己的会话计时启动定时器,接收的期限不含 job 准备耗时。 代码

对主干的风险 / Risks

相同 macOS 定向 suite 在 base 644 项通过、head 659 项通过。两端同一六分片 smoke 因短用例未输出预期 stack 行失败。Linux 独立入口通过了实际截止与 JUnit 对照。 标准 premerge 的 5 项直接和 7 项选中检查通过。 本地 Linux 证据另见已有基线和候选的普通 pytest 路径。内层期限由工作流启用,默认插件入口没有额外计时。部分 XML 仍可能包含 pytest 自己留下的未命名节点,两版退出后的 XML 均能观察到。这一轮只核对可归属的已完成用例,未把空节点记为测试结果。

语义与 CI 对齐

保持 pytest 原退出语义与原诊断开关,工作流内应校验新期限是否真实早于外层截止。 用 Python 3.11 的真实 pytest -n 2,模拟短作业期限并改变准备耗时。核对已完成用例、截止 JSON、JUnit 和退出。 未查询远端 CI。

我的整体评价 / Verdict

当前提交需要修改。按作业已用时间计算 pytest 可用预算,为输出和上传显式留出余量。余量不足时在启动分片前给出可读失败,并用两种准备耗时的同一入口核验。 Linux 验证使用本地 Python 3.11 容器和缩短的真实进程时限。GitHub 托管作业的完整安装、上传和调度未执行,失败门未标为通过。

English verdict: REQUEST_CHANGES at b9a1f81c7aa4. The plugin now writes partial JUnit promptly, but the fixed pytest deadline can still fall after the runner stops a shard because setup consumes the same job budget.

Record the test-shard start epoch before checkout/setup and launch shards
through scripts.ci.shard_budget so pytest receives the remaining job budget
minus setup elapsed time and the 300s upload reserve, failing fast with
pre-shard diagnostics when remaining time drops below the 300s viable floor.

Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
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)

本次基于精确提交 62950d87f36229c6daf64ba896924457c8fdeab8(PR #8878,分支 codex/ci-python-shard-speedup-20261117 -> main,基线 e5d5945f6dfa7bca340c7f9473432d9f1ba6b1f6)在独立干净临时 worktree 中完成全量复审与门禁复核。上一轮审阅 6019799510 在 .github/workflows/python-tests.yml 指出的阻塞性 P2(checkout/下载/安装与 bwrap 准备耗时可能挤占固定 --ci-session-deadline 3300 导致外层 60 分钟超时强杀)已通过 Record job start time 与动态预算入口 scripts/ci/shard_budget.py 修复落地,且行内未解决线程数为 0。

动机 / Motivation

在 #8787(基线版本 issue-8787)中,定时 Python Tests 分片在逼近作业超时时会出现作业级强杀,既没有正在卡死用例的栈与子进程诊断,也无法及时落盘已完成用例的部分 junit.xml,导致上传步骤失败并迫使维护者与调度系统盲目重跑。

改前无论准备阶段耗时多久,工作流都在所有 setup 完成后才开始固定 3300 秒计时;若准备耗时超出预留窗口(如 5.0s 外层预算中准备 3.6s),外层 runner 会在导出 junit.xml 与截止快照前直接终止进程。改后工作流在作业最前端记录 LOOPX_SHARD_JOB_START_EPOCH,通过 scripts/ci/shard_budget.py 在扣减已耗准备时间与 300 秒上传预留后计算真实剩余会话期限;若剩余预算低于 300 秒最低阈值,则启动前即以退出码 2 快速失败并落盘 ci-shard-diagnostics.json,同时由 pytest_timing.py 在合作式超时触发时先原子写出部分 JUnit 与诊断快照并收紧 xdist 清理等待。如果不改,慢准备或阻塞用例仍会以静默取消收场。

本 PR 针对 #8787(issue-8787)的交付边界为:完成 C1(超时前保留可诊断栈/子进程/部分结果与 INTERRUPTED 退出语义)与 C3(按全作业剩余预算动态留出结果刷新与上传窗口);将 C2(在收集稳定单测耗时分布后重平衡 6 分片矩阵)延后至拿到完整调度计时数据后的独立 PR 处理,本轮保持 Python 3.11、-n 2、6 分片与 19.6% 覆盖率基线不变。

改动思路 / Approach

整体将外层作业预算控制与内层合作式会话中断解耦为两层清晰边界,共用统一的原子落盘与诊断 Schema(DIAGNOSTICS_SCHEMA_VERSION = "loopx_ci_pytest_diagnostics_v1"):

  1. 外层作业起始打点与启动前预算门禁(scripts/ci/shard_budget.py、.github/workflows/python-tests.yml):在 test-shard 第 0 步(actions/checkout@v7 之前)写入 LOOPX_SHARD_JOB_START_EPOCH;Run test shard 经 python -m scripts.ci.shard_budget 计算 remaining_session_seconds = job_budget_seconds - elapsed_prep_seconds - upload_reserve_seconds,对负时钟偏移做 >= 0 钳位、在 GITHUB_ACTIONS=true 下缺失/非法 epoch 及重复传入 --ci-session-deadline 时 fail-closed 报错(退出码 4);低于 min_session_seconds 时拒绝拉起 pytest(退出码 2)并写出 pre_shard_budget_exhausted: true 诊断。
  2. 内层合作式期限、早期 JUnit 原子刷新与诊断串行化(scripts/ci/pytest_timing.py):TimingObserver 监控 collection 与 runtestloop 阶段,超时后经 pthread_kill(..., SIGINT) 或 _thread.interrupt_main() 唤醒主线程,在 _DeadlineSessionHook 中优先调用 _flush_partial_junit 原子写出已完成用例 XML(注销原 LogXML 并用 _JUnitSummaryHook 保留终端路径输出)并经 _bound_xdist_teardown 将 xdist EXIT_TIMEOUT 压至 <= 1.0s 通知 worker 退出;_write_diagnostics 通过 _write_lock 串行化写入,禁止较慢的进度快照回退覆盖 deadline_exceeded=true。
  3. 架构评估与边界收敛:shard_budget.py(282 LOC、0 Any、0 # type: ignore)单向为 pytest_timing.py 提供 atomic_write_text 与 DIAGNOSTICS_SCHEMA_VERSION,不改动测试筛选逻辑、6 分片策略或正常完成时的退出码;对既有未加类型注解的 pytest_failure_context.py 与 C2 分片重平衡均不在本 PR 扩大修改范围。
test-shard Step 0: Record job start time (LOOPX_SHARD_JOB_START_EPOCH)
   └─▶ setup (checkout / download / pip / npm / bwrap)
         └─▶ python -m scripts.ci.shard_budget (3600s - elapsed_prep - 300s reserve)
               ├─ remaining < 300s ─▶ pre-shard fail-fast (rc=2) + ci-shard-diagnostics.json
               └─ remaining >= 300s ─▶ pytest -n 2 --ci-session-deadline=<remaining>
                                         └─ timeout ─▶ _flush_partial_junit + _bound_xdist_teardown + always() diag upload

说明:上图为按当前精确提交整理的执行路径概览,实际运行行为以正文与下方实测证据为准。

具体改动 / Changes

全量涉及 5 个文件(+1,596 / -17):.github/workflows/python-tests.yml(+29 / -7)、scripts/ci/shard_budget.py(282 LOC,0 Any)、scripts/ci/pytest_timing.py(775 LOC,+572 / -7)、tests/test_ci_pytest_timing.py(1,246 LOC,+666)、tests/test_python_ci_workflow.py(655 LOC,+47 / -3)。

  • 验收标准 C1(implemented):scripts/ci/pytest_timing.py 实现阶段级期限检查、pthread_kill 中断、无命令参数的后代进程基名采样(_collect_descendant_processes)、先于 xdist 阻塞等待的部分 JUnit 原子导出(_flush_partial_junit)及串行化诊断落盘,并强制保留 pytest.ExitCode.INTERRUPTED(退出码 2);由 tests/test_ci_pytest_timing.py 多项真进程测试验证。
  • 验收标准 C2(deferred):#8787 明确建议先为慢分片插桩并在超时前保留诊断与部分结果,待积累可靠单测耗时分布后再重新平衡 6 分片矩阵;当前 PR 保留既有 -n 2 与 6 分片配置,将分片权重调整留待后续独立 PR。
  • 验收标准 C3(implemented):针对上轮 [P2] 修复 .github/workflows/python-tests.yml#L627-L707 与 scripts/ci/shard_budget.py,在作业起点捕获 LOOPX_SHARD_JOB_START_EPOCH,按真实剩余预算下发 --ci-session-deadline 或在预算不足时启动前快速失败,并以 if: ${{ !cancelled() }}(JUnit)及 if: always()(python-diagnostics-${{ matrix.shard }})保留产物上传能力;由 test_shard_budget_computation_and_fail_closed_validation、test_shard_budget_preserves_reserve_across_fast_and_slow_prep 及独立 0.2s/3.6s 准备耗时对比复现验证。

关键代码讲解

  1. .github/workflows/python-tests.yml:627-707(test-shard):
    第 0 步记录 LOOPX_SHARD_JOB_START_EPOCH;Prepare native shell isolation 在已有 bwrap 时跳过重复 apt 安装;Run test shard 通过 python -m scripts.ci.shard_budget 传入 3600 秒总预算、300 秒上传预留及 300 秒最小可执行下限,禁止硬编码 --ci-session-deadline;Upload shard timeout and progress diagnostics 使用 if: always() 保证即便 pre-shard 退出或 pytest 超时也能上传诊断 JSON。
  2. scripts/ci/shard_budget.py:72-282(parse_job_start_epoch、compute_shard_budget、build_pre_shard_budget_diagnostics、main):
    校验有限正数/非负数输入并做负时钟差钳位;GITHUB_ACTIONS=true 下缺少或畸形 LOOPX_SHARD_JOB_START_EPOCH、或参数中重复指定 --ci-session-deadline 均返回退出码 4;剩余不足 min_session_seconds 时写出带 pre_shard_budget_exhausted: true 的 JSON 并返回 2;否则执行子进程 pytest 并附带 --ci-session-deadline={remaining_session_seconds:.3f}。
  3. scripts/ci/pytest_timing.py:53-178, 481-591, 607-768(_render_junit_xml、_flush_partial_junit、_bound_xdist_teardown、TimingObserver):
    在不改动 LogXML 内部状态的前提下提前生成完整 XML 并原子替换写入 junit.xml,同时注销原 LogXML 避免正常 teardown 用空文件覆盖已刷出的部分结果;_bound_xdist_teardown 将 worker 退出宽限钳制到 <= 1.0s;_write_diagnostics 通过 _write_lock 阻止进度写回退覆盖终态或超时快照。
  4. tests/test_ci_pytest_timing.py:1077-1246 与 tests/test_python_ci_workflow.py:404-592:
    覆盖无效 deadline 拒绝、collection 超时中止、SIG_IGN worker 有界清理、并发写入无损坏/无回退、负时钟与缺失 env 校验、0.2s/3.6s 真实 -n 2 准备耗时对照,以及嵌套测试子进程剥离 LOOPX_SHARD_JOB_START_EPOCH 与 GITHUB_ACTIONS 环境变量的隔离修复。

对主干的风险 / Risks

  • 未发现阻塞性缺陷:上轮 P2 已闭环且无未解决审阅线程;shard_budget.py 为工作流直接生产入口且共享原子写/Schema 常量给 pytest_timing.py,无悬空模块(scope_fit 对齐);工作流与插件保持原有退出码、19.6% 覆盖率要求与 -n 2/6 分片行为不变(default_off_isolation 不适用);未引入新控制面状态词表(semantic_alignment 为 not_applicable)。
  • 精确提交 62950d87f36229c6daf64ba896924457c8fdeab8 独立验证矩阵(干净临时 detached worktree 实测,按 Goal 策略不等待远端 GitHub Actions CI):
    • 独立快/慢准备耗时复现对照(真实 python -m scripts.ci.shard_budget + -n 2 + scripts.ci.pytest_timing,10 秒阻塞用例):
      • fast_prep_0.2s(budget=5.0s, reserve=2.6s, min=0.5s):rc=2,总耗时 2.91s / 5.0s,junit.xml 保留 test_fast,deadline_exceeded=True, deadline_s=2.165。
      • slow_prep_3.6s_fail_fast(budget=5.0s, reserve=2.6s, min=0.5s):rc=2,总耗时 3.65s / 5.0s(未等到 5.0s 强杀即在启动 pytest 前可读退出),junit=False, pre_shard_budget_exhausted=True, deadline_exceeded=True, deadline_s=0.0。
      • slow_prep_3.6s_tight_viable(budget=9.0s, reserve=3.0s, min=0.5s):rc=2,总耗时 6.51s / 9.0s(动态缩短内层截止至 2.365s,完整保留约 2.49s 上传窗口),junit.xml 保留 test_fast,deadline_exceeded=True。
    • Pytest 与脚本单测(总计 2,740 项 pytest + 23 项 unittest + 9 项 node 全过):
      • pytest -v(test_ci_pytest_timing.py, test_python_ci_workflow.py, test_ci_pytest_failure_context.py, test_ci_resource_policy.py, test_stage2c_dependency_lock.py, test_codeowners.py):822 passed in 93.04s(0 failed, 0 skipped)。
      • pytest -n 3 -q tests/canary/test_maintainability_ratchet.py tests/architecture/:1918 passed in 98.49s(0 failed, 0 skipped)。
      • python -m unittest discover -s scripts/ci -p 'test_*.py':Ran 23 tests in 2.555s, OK。
      • node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs:9 passed, 0 failed;npm run typecheck:control-plane PASS。
    • 静态检查、类型与门禁:
      • ruff check(4 个 PR .py 文件)PASS;mypy --strict scripts/ci/shard_budget.py PASS(0 errors,282 LOC,0 Any,0 # type: ignore);仓库配置 mypy(17 个文件)PASS(0 errors);pytest_timing.py 经基线 origin/main 对比确认 0 新增 mypy 错误(仅行 338, 687 调用既有未注解 pytest_failure_context.py 的两处旧 no-untyped-call)。
      • check_rfc_bilingual.py PASS;generate_semantic_inventory.py --changed-from origin/main 为 0 候选词表;Goal 绑定 loopx check(5 个 PR 路径)ok: true, errors: 0, warnings: 1(test_ci_pytest_timing.py:563 既有脱敏测试夹具非字面量告警);全补丁泄露扫描 PASS(0 hits);loopx canary premerge --from-git-diff --git-diff-base origin/main PASS(status=passed, merge_gate_passed=true,5/5 直接检查 + 7/7 选中门禁含 6/6 目录金丝雀及 1/1 公共边界,manual_hold_count=0)。

我的整体评价 / Verdict

  • 长程与用户体验影响(outcome_impact):long_horizon=preserved(不改变正常分片测试选择、覆盖率统计、-n 2 并发与失败退出语义,并在慢准备/阻塞场景下将原本无诊断强杀转化为带部分 JUnit 与进程快照的可恢复诊断);user_experience=preserved(visual_review 为仅涉及 CI 工作流、Python 计时插件与测试脚本的纯运维链路改动,未修改任何产品前端界面或交互控件,unverified_scope 为 none)。
  • 语义兼容性、代码体积与变更比例:observable_semantics=equivalent(正常执行与失败码不变,仅在期限溢出时提前原子导出已运行结果与诊断,并在预算不足前可读 fail-fast);code_volume=necessary(shard_budget.py 282 LOC 零 Any 与 pytest_timing.py 复用共享常量,无冗余包装);change_proportionality=proportionate(5 个文件精准关闭原 P2 阻塞)。
  • 残留风险:本次只在本地 macOS 环境以缩短预算模拟真实 python -m scripts.ci.shard_budget + -n 2 过程;Linux bwrap 与 GitHub 托管 runner 完整端到端执行按仓库不等待远端 CI 策略未在本审阅中等待跑完,但工作流 YAML、env 传递与全部 2,740 项回归/架构门禁已实测通过。

English verdict: APPROVE — Exact head 62950d87f36229c6daf64ba896924457c8fdeab8 resolves the prior P2 at .github/workflows/python-tests.yml via Record job start time and scripts/ci/shard_budget.py (282 LOC, 0 Any, mypy --strict clean), verified by independent 0.2s/3.6s fast-and-slow prep reproducers, 2,740/2,740 pytest tests, 23/23 CI unittests, 9/9 Node tests, typecheck:control-plane, ruff, zero new mypy regressions, loopx check, and 7/7 canary premerge gates.

@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 · reasoning_effort=xhigh

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

动机 / Motivation

维护者需要在定时 Python 测试分片卡住时,拿到已完成用例的结果和最后的运行诊断。当前提交按准备耗时缩短测试窗口,为写报告和上传留出时间。真实两工作进程的对照显示,慢收集能够主动退出,但收尾钩子卡住时,外层截止仍会先到,已通过的用例没有留下 JUnit 结果。这个切片的范围是分片诊断和上传预留。

改动思路 / Approach

当前只调整定时 Python 分片的截止控制、已有证据及上传预留。

工作流开头记录时间,shard_budget 负责判断是否还能启动 pytest,pytest_timing 负责会话内的进度、截止和诊断落盘。上传仍由工作流执行,JUnit 格式仍来自 pytest 报告。这样分工适合保留,当前 PR 应在同一个测试会话截止边界内覆盖已有测试结果到报告可交付之间的空档。给每个钩子分别加超时会复制截止逻辑,优先让同一个截止处理在控制器收尾也能落盘。

具体改动 / Changes

按 #8787 的公开反馈快照 issue-8787 对照 C1 和 C3。对 C1,收集或用例执行期间能收到结构化截止诊断。本地慢收集触发退出码 2。对 C3,正常路径有可解析 JUnit,准备预算不足会保留明确诊断。控制器收尾卡住这一分支未兑现保留部分输出的要求。完整差异含五路径,生产工作流及两个脚本 +883/-14,两个测试文件 +713/-3。

关键代码讲解

  • compute_shard_budget 从外层时限扣掉准备耗时和上传预留,低于最短窗口时由 main 拒绝启动且写诊断。工作流的两进程、六分片和覆盖率步骤仍由原工作流负责。
  • TimingObserver.pytest_runtestloop 在运行循环正常返回后设置 _runtestloop_finished。进入控制器的 pytest_sessionfinish 时,测试已经完成,正常 JUnit 写入仍可能尚未发生。
  • TimingObserver._record_deadline 见到循环已结束就直接返回。即使测试在收尾前已经通过,超时也不会到达 prepare_deadline_sessionfinish 的提前写入路径。
  • 新测试覆盖启动预算、慢收集、阻塞用例、worker 清理、诊断并发,以及工作流接线。本次独立对照额外覆盖控制器外层收尾钩子。

对主干的风险 / Risks

P2 [阻塞] 会话截止在运行循环结束后提前失效。用真实 scripts.ci.shard_budget、pytest 和 -n 2 运行一个必过用例,外层预算 10 秒、上传预留 3 秒。只让控制器的 pytest_sessionfinish wrapper 在进入时暂停。控制组退出 0,产生 1 条 JUnit 用例。暂停组已进入该钩子,第 10 秒达到外层截止,仍没有 JUnit,已有 JSON 中 deadline_exceeded 还是 false。慢收集对照在外层截止前退出 2 并记录 deadline。请让截止持续覆盖报告可交付前的控制器收尾,添加同样的两工作进程回归用例,并验证部分结果先落盘再退出。 见当前头的提前返回

我的整体评价 / Verdict

动态预算与慢收集的实测改善成立。对于已跑完用例却卡在控制器收尾的分片,仍会失去用例结果,维护者需要再跑一次才能定位。建议修复同一个截止处理的收尾边界,保留失败退出与现有工作流选择。审阅头为 62950d87f36229c6daf64ba896924457c8fdeab8,基线为 e5d5945f6dfa7bca340c7f9473432d9f1ba6b1f6。源码定向全量一轮通过 633 项,3 项并行失败在同头串行复跑均通过。标准 premerge 的语义词汇检查已超时,不能据此判定改动归因。诊断只影响工作流和 CLI 路径,未涉及渲染。独立精简实验未运行托管 runner 或执行实际 artifact upload,远端 CI 未查询。

English verdict: REQUEST_CHANGES — 62950d8. A stalled controller session-finish hook can exhaust the outer budget without JUnit or deadline diagnostics, even after a passing test. Two-worker positive, collection-timeout and budget controls were verified.

Comment thread scripts/ci/pytest_timing.py Resolved
…nfinish

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 · gpt-6.2-sol · OpenAI · runtime_reported · xhigh

动机 / Motivation

从同一 runner 预算中留出诊断和上传时间,在慢收集、阻塞用例或控制器结束钩子停滞时保留部分成果。 目标是维护者能从超时的 Python 分片得到部分结果,定位慢收集与收尾停滞。

同一条两 worker 测试通过后卡在 controller pytest_sessionfinish。上一头在外层期限被停止,当前头保留结果和截止原因。 当前头在完整控制器退场前保留同一个 deadline。两 worker 的结束钩子暂停时,会在外层期限前发布可读 JUnit 与 deadline 诊断并退出 2。 范围是 Python 分片入口与诊断投递,沿用两 worker、六分片与现有覆盖率门槛。

改动思路 / Approach

工作流先记录开始时刻,shard_budget 计算剩余时间,pytest_cmdline_main 包装 controller 直到会话结束。deadline 时提前写部分 JUnit,并对本地 xdist worker 有界收尾。 runner 的 60 分钟仍是外层限制。shard launcher 从作业开始时间和准备耗时计算内层预算,TimingObserver 负责该进程的截止与诊断,pytest 原退出语义由原入口处理。 预算入口只算可用时间,pytest plugin 负责诊断、原报告与测试进程生命周期。上传仍由 workflow 管理。

具体改动 / Changes

关键代码讲解

  • compute_shard_budget 从可用预算减准备耗时及报告预留。 源码
  • pytest_cmdline_main 保留 controller cutoff 并在结束中断后最终发布。 源码
  • _flush_partial_junit 原子保存已完成用例的部分报告。 源码
  • _bound_xdist_teardown 约束本次本地 worker 的退出。 源码
  • Run test shard 继续两 worker 和六分片,把原入口接到预算计算。 源码

5 文件,+1828/−17。工作流接入、预算计算、pytest hook 和回归夹具共五个文件。保留一个剩余预算和一个 session cutoff,诊断由原 pytest 入口保存。 默认无 --ci-session-deadline 的常规执行保持退出码、JUnit 与结束事件。诊断文件发布先后复用同一写锁。分片与覆盖选择沿现有策略。 验收依据

  • C1 慢收集和正在执行或收尾的试验可以及时诊断。 以 Python 3.11 双 worker 停在 controller 结束前后,退出 2 并记录截止。
  • C3 给诊断和部分结果留有界的 job 时间,并保持失败退出。 动态准备预算、拒绝无余量的启动,18 秒外层下保留可读 JUnit。
  • PYTEST-NATIVE-PARITY 常规 pytest 和测试选择保持原有语义。 main/head 无 deadline 结果一致,本地正常双 worker 有完整 JUnit。

对主干的风险 / Risks

准备耗尽预算的实跑在 pytest 收集前退出 2,保存诊断,无 JUnit。运行进入结束钩子并逾期时则保留已有用例,诊断明确该轮未完整执行。

同一短预算对照中,两种暂停均在原外层截止前保留全部已完成用例。 变更来源 #8787

语义与 CI 对齐

git diff --check 与静态合并通过。Python 3.11 本机复跑四项关键回归通过,独立收尾前后对照和默认入口对照通过。 真实 -n 2 的正常对照退出 0。暂停结束钩子进入或退出时,当前头约 16.4 秒退出 2,两个用例都保留可解析的 JUnit 和 deadline_exceeded=true。 对当前 main c0bf1a5f68 的变更路径无交集,静态合并成功。几次短预算套件在本机负载下超时,上一提交也遇到。隔离非必要插件的同一 9 秒对照,两端均保存 JUnit 后退出 2,当前头 6.91 秒,上一头 8.57 秒。实际 GitHub runner 的上传与全量 Linux 分片耗时未测。

我的整体评价 / Verdict

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

工作流和终端诊断改动。 当前证据覆盖 #8787 的 C1 与 C3,以及先前评审的报告收尾阻塞。Linux runner 使用实际分片时的成本和成功率仍有单独验证价值。

English verdict: APPROVE at 90d83d8. Under Python 3.11 and real two-worker pytest, the deadline now survives controller session-finish stalls and preserves partial JUnit and deadline diagnostics. Normal and no-deadline controls preserve the native result.

@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 · effort_unavailable
Approval conclusion (author-owned PR; GitHub blocks formal self-approval)

本次复审基于 PR #8878 精确提交 90d83d88a72916e396bb501dc991167864ff32f2(分支 codex/ci-python-shard-speedup-20261117 -> main,基线 e5d5945f6dfa7bca340c7f9473432d9f1ba6b1f6)在干净临时 detached worktree 中完成全量复验。上轮评审 6042342045 指出的阻塞性 [P2](控制器 pytest_sessionfinish 阻塞时因 _runtestloop_finished 守卫使截止机制提前失效,导致外层 10 秒预算耗尽且丢失已完成用例 JUnit 与 deadline_exceeded 诊断)已在 90d83d88a7 修复,行内线程 PRRT_kwDOStEbEs67ceCW 已标记解决。

动机 / Motivation

依赖 GitHub Actions Python Tests 分片稳定产出的贡献者与维护者,以及在分片逼近超时时依靠 junit.xml 和诊断文件定位卡死用例与残留子进程的调度系统。 此前主干固定在 setup 结束后使用单一 --ci-session-deadline,若检出或依赖安装阶段耗时拉长,runner 会在会话超时刷新和上传前强杀整条作业;同时上轮审查提交 62950d8 在 TimingObserver.pytest_runtestloop 正常结束后设置 _runtestloop_finished 导致 _record_deadline 提前失效,一旦控制器的 pytest_sessionfinish 钩子阻塞,10 秒外层预算会直接耗尽且既无 junit.xml 也停留在 deadline_exceeded=false。本次精确提交 90d83d8 将单一会话截止期保持至可交付报告完成并经由 pytest_cmdline_main 捕获超时中断,使控制组正常退出 0 且卡死对照组在 10 秒前以退出码 2 原子写出已完成用例的 junit.xml 与 deadline_exceeded=true 诊断。 外层 shard_budget 按作业启动时间戳扣除准备耗时与上传预留动态计算剩余会话时限(不足时以退出码 2 拒绝启动并写出 pre_shard_budget_exhausted 诊断);当收集、用例循环或控制器 pytest_sessionfinish 阶段触发截止超时,单一计时器仍会唤醒并安全清理 xdist worker、原子落盘已完成用例的 junit.xml 并以退出码 2 结束。 本次交付仅完成超时可诊断性与预算/上传窗口预留(C1 与 C3),基于稳定长周期分片实测耗时重新均衡 6 分片矩阵(C2)仍留待收集完新计时样本后的后续独立 PR 完成。 本 PR 不重平衡 6 分片测试矩阵(C2),不更改 Python 3.11、-n 2 worker 池与 19.6% 覆盖率基线,也不替代远端 GitHub Actions 真实托管 runner 的实际 artifact upload 演练。 如果不修理控制器收尾阶段这一截止盲区,任何测试全部通过却卡在会话收尾插件的分片仍会被 GitHub Actions 强杀并丢失诊断与部分报告,迫使维护者再次盲目重试。

改动思路 / Approach

整体按“外层作业剩余预算计算 -> 内层全周期单一会话截止 -> 外层命令包装统一中断清尾”三段串联:

  1. 作业起始打点与动态预算准入(.github/workflows/python-tests.yml、scripts/ci/shard_budget.py):在 test-shard 首步记录 LOOPX_SHARD_JOB_START_EPOCH,由 compute_shard_budget 扣除准备耗时与 300s 上传预留;若剩余有效窗口低于 300s(min_session_seconds)或在 GITHUB_ACTIONS=true 下缺少/传入非法 epoch 或重复 --ci-session-deadline,则 fail-closed 拒绝拉起 pytest(退出码 2/4)并写出 pre_shard_budget_exhausted 诊断 JSON。
  2. 修复控制器 pytest_sessionfinish 截止失效(scripts/ci/pytest_timing.py):最新提交移除 _runtestloop_finished 对 _record_deadline 的提前屏蔽,改用 _post_loop_active 标记循环结束后的收尾阶段;在 prepare_deadline_sessionfinish() 中不再提前置 _finished = True,而是保留单一 _deadline_timer 直至报告可交付的 pytest_cmdline_main 外层包装完成时统一 disarm_deadline()。一旦在控制器 pytest_sessionfinish(包含外层 conftest.py wrapper yield 前/后及普通钩子)发生超时,SIGINT 将唤醒并跳出 wrap_session 进入 finalize_interrupted_session():原子刷新已完成用例 XML(_flush_partial_junit 并注销原 LogXML 避免重入/截断)、终止并等待 xdist worker(_bound_xdist_teardown(..., terminate=True) + kill/wait 兜底)、输出 LOOPX_PYTEST_DEADLINE 与单次 end(退出码 2),并写入 deadline_exceeded: true / execution_complete: false 终态诊断。
  3. 架构评估与边界:维持外层工作流预算准入(scripts/ci/shard_budget.py)与内层测试会话进度/截止中断控制(scripts/ci/pytest_timing.py)的清晰边界:双方仅共享统一的原子落盘原语 atomic_write_text 与诊断 Schema 版本 DIAGNOSTICS_SCHEMA_VERSION,并在 pytest_cmdline_main 外层统一兜底收尾中断、部分 JUnit 原子刷新、xdist 进程清理与单次最终诊断落盘,避免给单个钩子重复拼装多套计时器。 当前 PR 范围收敛在作业启动打点、动态预算启动前门禁、收集/执行/控制器 sessionfinish 全链路单一截止控制、部分 JUnit 与诊断落盘,以及配套工作流与回归测试;6 分片耗时重平衡留给下一阶段独立 PR。
shard_budget (记录 prep 耗时与 300s 预留)
  ├─ remaining < min_session ──> exit 2 + pre_shard_budget_exhausted 诊断 (不拉起 pytest)
  └─ remaining >= min_session ─> pytest -p scripts.ci.pytest_timing --ci-session-deadline=R
       ├─ pytest_cmdline_main (outer wrapper)
       │    ├─ 正常收尾完成 ──> finalize_completed_session() -> disarm_deadline() -> exit 0
       │    └─ 收集 / 循环 / 控制器 sessionfinish 超时 (SIGINT -> KeyboardInterrupt)
       │         └─> finalize_interrupted_session() -> _flush_partial_junit() + kill workers + diag(deadline_exceeded=true) -> exit 2

说明:上图按精确提交 90d83d88a72916e396bb501dc991167864ff32f2 源码梳理分支关系,仅作说明辅助,不替代下方实测执行证据。

具体改动 / Changes

关键代码讲解

  1. scripts/ci/pytest_timing.py:399-428(pytest_cmdline_main):以 @pytest.hookimpl(wrapper=True, tryfirst=True) 包裹 wrap_session,仅在 observer.deadline_exceeded 为真时拦截 KeyboardInterrupt 并调用 _suspend_capture_safely、observer.finalize_interrupted_session() 与 _ensure_unconfigure_safely;真实用户 Ctrl-C(deadline_exceeded=False)仍会先关闭计时器并原样抛出 KeyboardInterrupt。
  2. scripts/ci/pytest_timing.py:620-660, 717-730(prepare_deadline_sessionfinish、_record_deadline、pytest_runtestloop):pytest_runtestloop 的 finally 改为设置 _post_loop_active = True 而非阻塞截止检测,_record_deadline 在 _collection_active or _loop_active or _post_loop_active 任一阶段超期均触发 _interrupt_main_locked(),从而把控制器的 pytest_sessionfinish(含 wrapper 前后两段)纳入同一截止边界。
  3. scripts/ci/pytest_timing.py:109-190, 832-906(_flush_partial_junit、_bound_xdist_teardown、finalize_completed_session、finalize_interrupted_session、pytest_sessionfinish):在退出清理前原子写出已完成测试用例 JUnit 并重定向/注销 LogXML 防止二次写空,随后终止/强杀失联 xdist worker 并保证终态诊断(deadline_exceeded: true, pytest_exit_code: 2)与单次 end 事件幂等落盘,同时兼容无 pytest_cmdline_main 包装的独立单元测试路径。
  4. scripts/ci/shard_budget.py:93-278 & .github/workflows/python-tests.yml:615-715:保持 compute_shard_budget 的零偏差时钟钳位、CI epoch fail-closed 检验与禁止硬编码 --ci-session-deadline 守卫,保留 -n 2、6 分片与 19.6% 覆盖率基线不变。
  5. tests/test_ci_pytest_timing.py:1249-1347(test_shard_budget_enforces_deadline_during_stalled_controller_sessionfinish[none|before_yield|after_yield]):以真实 scripts.ci.shard_budget + pytest -n 2 覆盖正常控制组(退出 0,1 条 testcase)与控制器 pytest_sessionfinish 在 yield 前/后卡死两组(在 10s/6s 外层预算到达前退出 2,产出含 test_pass 的可解析 junit.xml 与 deadline_exceeded: true 诊断)。

规范对照(spec_basis)

对照公开议题 issue #8787(修订标记 issue-8787)需求项逐一核验:

  • C1:implemented — 收集、执行与控制器 pytest_sessionfinish 阶段均受单一会话截止保护,触发后保留堆栈/子进程/部分结果并以 INTERRUPTED(退出码 2)退出(scripts/ci/pytest_timing.py:399-428, 620-660, 832-906;test_ci_pytest_timing.py 88 项 + 独立控制/阻塞对照 probe PASS)。
  • C3:implemented — scripts/ci/shard_budget.py:93-278 与 .github/workflows/python-tests.yml 根据实际 LOOPX_SHARD_JOB_START_EPOCH 动态扣除准备耗时与 300s 上传预留,_flush_partial_junit 在清理阻塞前原子写出 junit.xml(test_shard_budget_* 与 test_python_ci_workflow.py PASS)。
  • C2:deferred — 基于稳定长周期运行样本重平衡 6 分片矩阵按 PR 边界延后,待取得新计时数据后在独立后续 PR 实施。

对主干的风险 / Risks

  • 未发现阻塞性缺陷(No blocking findings):上轮 6042342045 指出的 [P2] 控制器收尾截止失灵已在精确提交 90d83d88a72916e396bb501dc991167864ff32f2 彻底修复,行内审阅线程 PRRT_kwDOStEbEs67ceCW 已解决(unresolved_count: 0)。
  • 独立复现与边界验证(observable_semantics / scope_fit):在干净临时 worktree 内以真实 scripts.ci.shard_budget + pytest -n 2(10s 预算 / 3s 上传预留)除了运行新增 before_yield/after_yield 包装钩子测试外,还额外构造了普通非 wrapper def pytest_sessionfinish(session) 卡死 20s 对照试验:控制组 rc=0(耗时 2.33s,junit_cases=['test_ok'],deadline_exceeded=False),卡死组 rc=2(耗时 7.60s < 10s,junit_cases=['test_ok'],deadline_exceeded=True,execution_complete=False,pytest_exit_code=2)。scripts/ci/pytest_timing.py 与 shard_budget.py 均由 .github/workflows/python-tests.yml 现网分片步骤直接拉起,无悬空或未接入路径(scope_fit 对齐);无共享语义词表变化(generate_semantic_inventory.py 显示 NativeGoalStatus 来自主干基线提交、本 PR 触及 0 字节;semantic_alignment 为 not_applicable)。
  • 精确提交 90d83d88a72916e396bb501dc991167864ff32f2 全量本地实测矩阵(不等待远端 CI):
    • 定向与回归 Pytest(PASS):pytest -v tests/test_ci_pytest_timing.py -k stalled_controller_sessionfinish 3 passed, 85 deselected in 18.71s;合并套件 pytest -q tests/test_ci_pytest_timing.py tests/test_python_ci_workflow.py tests/test_ci_pytest_failure_context.py tests/canary/test_maintainability_ratchet.py tests/architecture/test_control_plane_import_boundaries.py 711 passed in 231.39s(0 failed, 0 skipped);pytest -q tests/test_stage2c_dependency_lock.py tests/architecture/test_top_level_module_budget.py tests/test_codeowners.py 9 passed in 1.14s。
    • CI Unit 与 TypeScript/JS(PASS):python -m unittest discover -v -s scripts/ci -p 'test_*.py' 23 tests in 11.502s OK;npm run typecheck:control-plane PASS;node --test scripts/ci/qualification_summary.test.ts scripts/ci/merge-dashboard-coverage.test.mjs 9 passed, 0 failed。
    • 静态与门禁(PASS):ruff check(4 .py 文件)PASS;mypy(17 严格核心文件)0 issues(shard_budget.py 独立 --strict --follow-imports=silent 为 0 issues,pytest_timing.py:364, 781 仅保留既有未标注 exception_type_name/failure_context 调用提示);check_rfc_bilingual.py PASS;module_metric_baseline.json 与 oversized_in_pr 均无修改/无超长决策函数;loopx check(5 PR 文件)ok: true(errors: 0,warnings: 1 为 test_ci_pytest_timing.py:563 既有用例构造的抗 Bearer $TOKEN 泄露脱敏测试字面量,非真实凭证);diff 泄露扫描 0 命中;6/6 提交带 DCO Signed-off-by;loopx canary premerge --from-git-diff --git-diff-base origin/main PASS(5/5 direct checks、6/6 catalog canaries、1/1 public boundary check,merge_gate_passed: true,manual_hold_count: 0)。
  • 残留风险与未核验边界:本地无法实际运行 GitHub Actions 托管 Ubuntu runner 60 分钟整作业、actions/upload-artifact 真实上传步骤或云端环境计时抖动;远端 CI 依据 Goal 策略未查询/等待(wait_for_ci: false)。

我的整体评价 / Verdict

  • 长程与用户体验影响(outcome_impact):long_horizon=improved(测试全部通过但收尾卡死时也能保留 junit.xml 与 deadline_exceeded=true 诊断而非整批重跑,缩短长分片故障恢复环路);user_experience=preserved(visual_review 为 not_applicable:本 PR 仅涉及 CI 工作流配置与 Python 测试分片计时/预算脚本(inspected path: .github/workflows/python-tests.yml, scripts/ci/shard_budget.py, scripts/ci/pytest_timing.py),未更改任何前端界面、Web 面板组件或用户交互渲染页面。,unverified_scope 为 none)。
  • 可观察语义、体积与比例:observable_semantics=intentional_change_validated(修复了控制器 pytest_sessionfinish 阻塞与动态准备时间扣除边界,同时正常 0 退出与现有 -n 2/6 分片语义不变);code_volume=necessary(shard_budget.py 282 LOC / 0 Any、pytest_timing.py 906 LOC,无冗余包装或重复逻辑);change_proportionality=proportionate(5 个文件精准解决 #8787 C1+C3 与收尾截止边界)。
  • 精确头新鲜度:本评审直接在精确提交 90d83d88a72916e396bb501dc991167864ff32f2(OPEN / MERGEABLE / 非 Draft / 未解决线程 0)上验证并完成全部门禁,建议批准(COMMENTED 作者自有 PR 形式回执)。

English verdict: APPROVE — Exact head 90d83d88a72916e396bb501dc991167864ff32f2 resolves review 6042342045's [P2] stalled controller pytest_sessionfinish deadline gap in scripts/ci/pytest_timing.py (399-428, 620-660, 832-906), passes independent scripts.ci.shard_budget + pytest -n 2 control/stalled probes (both wrapper pre/post-yield and plain non-wrapper hooks exiting 2 with partial junit.xml and deadline_exceeded=true before outer budget expiry), 711 + 9 pytest tests, 23 scripts/ci unittests, 9/9 CI TS tests, ruff, mypy, loopx check, and 7/7 canary premerge gates.

Signed-off-by: huangruiteng <huangrt01@163.com>

@huangruiteng huangruiteng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewer: model_agent · GPT-5 · OpenAI · self_reported

动机 / Motivation

维护 Python Tests 分片的贡献者和维护者需要区分“测试失败”和“runner 到点强杀”。旧工作流使用与准备耗时脱节的固定内部 deadline;准备阶段变慢时会挤压报告和上传窗口,而 controller 已经完成用例循环、却卡在 pytest_sessionfinish 时,外层 60 分钟限制可能直接杀死进程,留下零 JUnit、零截止诊断,只能盲重跑。

本 head 处理的是 linked issue #8787 的 C1 和 C3:一次通过用例后 controller 在 sessionfinish 前后各阻塞 20 秒的真实 pytest -n 2 子进程中,新实现会在外层预算前退出 2,保留 test_pass 的 junit.xml,并写入 deadline_exceeded=true、execution_complete=false。准备已经吃掉过多预算时,则在 pytest 启动前退出 2,写 pre_shard_budget_exhausted=true 而不启动任何用例。

可观察结果是维护者能直接看到剩余预算、已完成的测试和阻塞阶段,不再用整个分片重跑来换取低质量诊断。边界保持不变:仍有 Python 3.11、-n 2、六个分片和 19.6% coverage floor;C2 的分片耗时再平衡被明确留给拿到稳定 timing 样本后的独立变更。

改动思路 / Approach

外层 .github/workflows/python-tests.yml 在 checkout 前记录真实作业起始时间,并把 pytest 交给 scripts/ci/shard_budget.py。launcher 从 3600 秒作业预算扣除准备耗时和 300 秒报告/上传预留,只在剩余时间达到最低可用阈值时启动 pytest;pytest 内仍由既有的 scripts/ci/pytest_timing.py 观察阶段并负责结果,不新增测试调度器。

关键收口是把“测试循环结束”和“controller 收尾完成”分开。TimingObserver 在 loop 结束后进入 _post_loop_active,保持同一个 deadline 武装到 pytest_cmdline_main 的完整 wrapper 返回;超时后只由外层 wrapper 执行一次原子 JUnit 保存、xdist 有界收尾、诊断落盘和退出码 2。普通未设置 --ci-session-deadline 的 pytest 路径仍走原 finalization。

ci-shard-diagnostics.json 是单次尝试的派生投影。pre-shard launcher 与 pytest observer 共用 schema version 和原子写入函数;写入锁保证落后的 progress 快照不能把 deadline 状态覆盖回 false。这个职责拆在 launcher 和 pytest 两侧,是因为前者必须在 pytest 进程存在之前完成预算准入,后者才持有 collection/report 与 worker 生命周期。

当前 PR 边界是:仍有 Python 3.11、-n 2、六个分片和 19.6% coverage floor;C2 的分片耗时再平衡被明确留给拿到稳定 timing 样本后的独立变更。

具体改动 / Changes

相对最新 main f37e1c6589dd43cc80049c0d187fb86abdc9f33c,精确 head 共 5 个文件、+1828/-17:3 个 production 文件和 2 个 tests。验收依据是 issue #8787,修订标记 issue-8787;C1 和 C3 已实现,C2 明确 deferred。

关键代码讲解

  1. scripts/ci/shard_budget.py:93 的 compute_shard_budget 将 job budget、实际准备耗时和上传预留转换为 typed ShardBudgetDecision。时钟倒退被钳为 0;CI 环境缺少或损坏 start epoch 时 fail closed;显式重复 deadline 被拒绝;预算不足时不导入或启动 pytest,只原子写 pre-shard 诊断。
  2. scripts/ci/pytest_timing.py:400 的 pytest_cmdline_main 成为 controller 生命周期的统一 finalization owner。deadline 触发的 KeyboardInterrupt 被转换为诊断退出 2;真实用户 Ctrl-C 没有 deadline_exceeded 时仍原样抛出,不能被误报成 CI timeout。
  3. scripts/ci/pytest_timing.py:636 的 _record_deadline 保证 deadline 状态只写入一次,并只在 collection、runtest 或 post-loop 阶段用 pthread_kill/_thread.interrupt_main 唤醒主线程。sessionfinish 前后阻塞仍属于同一个 deadline,不再被 “runtest loop finished” 提前解除。
  4. scripts/ci/pytest_timing.py:109 的 _flush_partial_junit 从 pytest 的现有 LogXML 数据原子生成已完成用例,随后注销原 XML writer,避免 card 或 worker teardown 再次截断报告;_bound_xdist_teardown 把现有 xdist 退出等待限制在 1 秒并最终清理本地 worker。
  5. .github/workflows/python-tests.yml 的 Run test shard 只替换外层 launcher,pytest 参数仍为原测试集合、-n 2、六分片选择与至少 19.6% coverage。JUnit 上传继续在普通失败时运行,diagnostics 使用 always() 上传;bubblewrap 仅在镜像缺少命令时安装。

对主干的风险 / Risks

最强回归场景是 timer 在正常收尾阶段误触发,或在保存 JUnit 后重入已经阻塞的 pytest_sessionfinish。当前实现用单次 deadline 状态、outer cmdline wrapper、LogXML 注销和幂等 final reporting 控制这条路径;无停滞 control 明确退出 0,pre-yield、post-yield 和普通非 wrapper 阻塞都必须在原外层预算之前退出 2。

第二个风险是外层预算计算错误,导致本可运行的 shard 被提前拒绝。实现只接受有限正数,开始时间早于当前时钳为零偏移,边界恰好等于最低 session 时允许启动;慢准备、紧但可用准备和缺失 CI epoch 都有独立反例。错误使 shard 明确失败,而不是把 pytest 改成通过。

本 head 相对上一审查头只合入最新 main 并补 DCO merge commit,PR 差分仍只有原五个文件。验证结果为:定向 CI/timing 套件 687 passed, 1 skipped;scripts/ci 单测 23 tests OK;Ruff、strict shard_budget.py mypy、17 个 kernel mypy 文件、RFC bilingual 和 diff hygiene 全部通过;standard premerge 完成 4 项 direct checks、6/6 catalog canaries、1/1 public boundary,零失败。首次 premerge 因审查 worktree 未安装 npm dev dependencies 触发 scanner 环境错误,执行 npm ci --ignore-scripts 后同一 exact head 全绿,未改代码。

没有阻塞 finding。没有私有状态、凭证、原始日志或生成物进入 diff;未验证范围保留为真实 hosted runner 的排队、60 分钟完整分片和 artifact upload 行为,这些不由本地 mock 冒充成功。

我的整体评价 / Verdict

long_horizon 判定 improved:长分片在准备超时或 controller 收尾阻塞时保留已完成测试和阶段证据,减少昂贵盲重跑。user_experience 判定 improved:维护者会看到明确 exit 2、预算算术、deadline 和 execution completeness;visual_review 为 not_applicable,因为五个文件都只影响 CI/pytest 执行与 artifacts,没有渲染页面。

整体架构 assessed as retain:outer budget、pytest lifecycle 和 artifact upload 分别留在 workflow、timing plugin 与现有 upload owner;没有新增持久状态、第二套测试调度或通用 control-plane 词汇。兼容性 assessed as not_applicable:这些都是同一次 workflow 部署内的 ephemeral diagnostics,普通无 deadline pytest 保持原路径。最小可行后续仍是用本 PR 产生的稳定 timing 样本完成 C2 六分片再平衡。

可以合入。结论基于精确 head 7e13cd7d5b4802f1dafac21caf04eab883fe018b 的真实 pytest/xdist 子进程、合并后的生产 workflow 路径和当前 main 上的完整验证;远端 hosted-runner 计时与上传是明确披露的集成残余风险,不是本地已通过项。

English verdict: APPROVE at 7e13cd7. The latest main is merged, the five-file CI diff remains intact, and real -n 2 fixtures prove setup-budget fail-fast plus partial JUnit/diagnostic preservation through controller sessionfinish stalls; 687 selected tests, 23 CI script tests, static checks and standard premerge pass.

@huangruiteng
huangruiteng merged commit 8de9f97 into main Nov 25, 2026
5 of 9 checks passed
@huangruiteng
huangruiteng deleted the codex/ci-python-shard-speedup-20261117 branch November 25, 2026 07:21
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.

2 participants