diff --git a/adapters/vllm_omni/manifest.yaml b/adapters/vllm_omni/manifest.yaml index 33f4dde7..b6224054 100644 --- a/adapters/vllm_omni/manifest.yaml +++ b/adapters/vllm_omni/manifest.yaml @@ -25,12 +25,12 @@ upstream: kind: fork_tracking repo_path: ${VLLM_UPSTREAM_REPO} remote: origin - # v0.33.0 alignment campaign (2026-10-28): vLLM cut releases/v0.33.0 on - # 2026-10-26 (tip 4135590ffe = v0.33.0rc0, cu130 wheel published), so the - # wheel pick and commit assignment target the release branch, not main. - # Pinned to the rc0 commit by the launcher's force_upstream_commit; re-pin - # to the tag commit once v0.33.0 final is tagged. - target_branch: releases/v0.33.0 + # v0.35.0 preparation campaign (2026-11-23): vLLM has not cut a + # releases/v0.35.0 branch yet, so the wheel pick and commit assignment + # target main (tip eff4de9be3c, 2026-11-23). vllm-omni main 9b753874d is + # aligned to vLLM v0.34.0 final (62d4bc3c7e). Flip to the release branch + # once vLLM cuts it, as the v0.33.0 and v0.34.0 campaigns did. + target_branch: main # Repo-specific slice of the SHARED, human-curated knowledge base (the vendored # community docs at the repo-root `knowledge/` = settings.knowledge_dir; @@ -232,7 +232,15 @@ rebase: wheel: package: vllm index_url_template: "https://wheels.vllm.ai/{commit}/{variant}/{package}/" - variant: cu130 + # vLLM main moved its default CUDA build from 13.0 to 13.2 in 3996083d37 + # (#55387, 2026-11-10): wheels for main commits are published under cu132 + # only ("the cu129 and cu130 subdirectories no longer get new builds"). + # PyPI's torch==2.14.0 stays +cu130; only vLLM's own kernels are built + # with 13.2. Release branches up to v0.34.0 publish cu130. + variant: cu132 + # The baseline runtime (test loop) installs the wheel vllm-omni main was + # last aligned to, vLLM v0.34.0 final, which is published under cu130 only. + baseline_variant: cu130 arch: x86_64 import_check_modules: [vllm._C_stable_libtorch, vllm._C] ops_namespace: _C diff --git a/adapters/vllm_omni/rebase/api_drift_guard.py b/adapters/vllm_omni/rebase/api_drift_guard.py index 55cb11ab..e3758412 100755 --- a/adapters/vllm_omni/rebase/api_drift_guard.py +++ b/adapters/vllm_omni/rebase/api_drift_guard.py @@ -56,6 +56,9 @@ def find_spec(fullname, path, target=None): ("vllm.v1.worker.gpu_model_runner", "GPUModelRunner", "vllm_omni.worker.gpu_ar_model_runner", "GPUARModelRunner"), ("vllm.v1.core.sched.scheduler", "Scheduler", "vllm_omni.core.sched.omni_ar_scheduler", "OmniARScheduler"), ("vllm.v1.core.sched.scheduler", "Scheduler", "vllm_omni.core.sched.omni_generation_scheduler", "OmniGenerationScheduler"), + ("vllm.v1.engine.output_processor", "RequestState", "vllm_omni.outputs.output_processor", "OmniRequestState"), + ("vllm.v1.engine.output_processor", "OutputProcessor", "vllm_omni.outputs.output_processor", "MultimodalOutputProcessor"), + ("vllm.profiler.wrapper", "WorkerProfiler", "vllm_omni.profiler.omni_torch_profiler", "OmniTorchProfilerWrapper"), ] @@ -276,9 +279,17 @@ def _check_inheritance() -> list[str]: ): continue missing.append(pname) - if missing: + positional_kinds = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) + base_positional = [p.name for p in base_sig.parameters.values() if p.kind in positional_kinds] + omni_positional = [p.name for p in omni_sig.parameters.values() if p.kind in positional_kinds] + omni_has_var_positional = any( + p.kind == inspect.Parameter.VAR_POSITIONAL for p in omni_sig.parameters.values() + ) + lost_positional = [] if omni_has_var_positional else base_positional[len(omni_positional):] + if missing or lost_positional: msg = ( - f"MISMATCH {omni_cls_name}.{name}(): missing params {missing}\n" + f"MISMATCH {omni_cls_name}.{name}(): missing params {missing}; " + f"incompatible positional params {lost_positional}\n" f" Base : {base_sig}\n" f" Omni : {omni_sig}" ) diff --git a/doc/architecture/SPEC/engine/steps/rebase_v3.md b/doc/architecture/SPEC/engine/steps/rebase_v3.md index 4946c2c3..18638823 100644 --- a/doc/architecture/SPEC/engine/steps/rebase_v3.md +++ b/doc/architecture/SPEC/engine/steps/rebase_v3.md @@ -1,8 +1,8 @@ # engine/steps/rebase_v3.py —— 规范 - + -`LOC ~2204 · step 库(v3 rebase 装配层) · refactor-status: oversized` +`LOC ~2660 · step 库(v3 rebase 装配层) · refactor-status: oversized` ## 职责 把 `rebase_engine` 包接进 executor:locked playbook `repo-rebase-v3` 的全部 @@ -132,7 +132,9 @@ harness 会话通过 MCP tool bridge 拿到同一套工具面,plan gate 在派 `upstream_commit` 重新确保 scratch。 - baseline venv(`ensure_baseline_venv`):硬链接克隆 campaign venv 并换入 baseline commit 的 wheel,让"omni main 对上次对齐的 wheel 是否也失败"可问; - 任何失败返回 None,保留保守的回归判定。 + 使用发布 wheel(若配置 URL)或非 editable 安装,删除临时源码后再验证导入; + 克隆的 console/activation 脚本通过原子替换改为 baseline 路径,不能写穿硬链接 + 修改 campaign。缓存复用也必须通过导入检查。任何失败返回 None,保留保守的回归判定。 ## 操作者重跑与本地超时预算(2026-10-29) @@ -142,9 +144,14 @@ harness 会话通过 MCP tool bridge 拿到同一套工具面,plan gate 在派 `run_test_loop`:记录过的 timeout/watchdog infra 再跑一次,已通过的 job 不重跑。 普通 resume 下 infra 仍然粘滞。 - `rebase.testing.local_timeout_multiplier`(默认 1,须为 >= 1 的数,否则 BLOCKED) - 只放大本地 `TestJob.timeout_sec`;构建出的 manifest 保留 CI 的 + 放大本地 `TestJob.timeout_sec` 和命令行首的直接 `timeout DURATION`;构建出的 manifest 保留 CI 的 `timeout_in_minutes`(shell golden 不变)。vllm-omni 取 3:Ready 的 20 分钟 CPU Simple step 在共享 rebase 主机上通过 53–88% 用例、零失败时就被杀。 +- 本地已配置虚拟环境时,将行首 `uv pip install --system` 改为 + `uv pip install --python "$VIRTUAL_ENV/bin/python"`。候选与基线各自使用 + `_target_test_env` 选定的虚拟环境;不修改 CI manifest,也不向系统 Python 安装依赖。 +- API drift guard 覆盖输出处理器、请求状态及 profiler 基类;除参数名外还检查位置参数容量, + 防止将上游可按位置传递的可选参数改成仅关键字参数后仍误报兼容。 ## 信号中断的模块:BLOCKED 收口、resume 重跑(2026-10-28) @@ -158,3 +165,16 @@ done;`_v3_wave_gate` 把 interrupted 与 failed 同等视为"wave-1 未完成" rebase 的模块不是 wave 2 的基础)。测试:`test_assembly.py:: test_v3_module_rebase_reruns_interrupted_and_blocks_on_interrupt`、 `test_run_shutdown.py::test_wave_gate_treats_interrupted_as_not_done`。 + +## agent 测试工具的卡数与会话卡数(2026-11-25) + +campaign 改为按命令向调度器取卡之后(`testing` 规范的"按命令向调度器申请 GPU"), +经本文件启动的 GPU 命令各自声明要几张: + +- `run_pytest`/`reproduce`(`_run_tests`)以 `TestJob(min_gpus=0, gpu_lock=True, + gpus=1)` 运行,向调度器要 1 张卡。返回值新增 `skipped` 与 `skip_reason`; + `passed` 只在 `rc == 0 and not skipped` 时为真——调度器没给卡的运行没有通过。 +- `run_precommit` 以 `gpus=0` 运行,不申请。 +- 两处 `ModuleRunConfig` 的 `cuda_devices` 改取 `testing.gpu_demand.session_devices()`: + 有 `CUDA_VISIBLE_DEVICES` 就用它,否则保留历史缺省 `0,1`;按需模式下会话不持有 + 卡,取空串,不再把 `0,1` 写进桥的环境。 diff --git a/doc/architecture/SPEC/providers/zcode.md b/doc/architecture/SPEC/providers/zcode.md index 000ba997..654b1d18 100644 --- a/doc/architecture/SPEC/providers/zcode.md +++ b/doc/architecture/SPEC/providers/zcode.md @@ -1,6 +1,6 @@ # providers/zcode.py —— 规范 - + `harness transport(Z.AI / GLM 订阅) · refactor-status: ok` @@ -12,11 +12,12 @@ `ZCodeFailure`;额度、限流、认证和暂时不可用分别表达。未知失败保留现有 RuntimeError 行为;分类器不把提示、原始事件或提供方错误正文暴露给 RFC 服务。 -headless `zcode --prompt=... --output-format stream-json --mode plan --cwd <临时目录> +headless `zcode --prompt=... --output-format stream-json --mode --cwd <临时目录> --disallowed-tools=<非读工具>`;工具桥写进临时目录的 `.zcode/config.json`;从事件流解析 `result.response`、`result.usage`、`session.updated.modelId` 和 `tool.updated`(`kind: scheduled`)。prompt 超过 100,000 字节时写成文件并 `--attach`(zcode 没有 stdin 通道, -argv 单参数上限 128KiB)。 +argv 单参数上限 128KiB)。`--mode` 按调用选:一次性调用用 `plan`(不带桥);agent 会话里 +只读作用域用 `guarded`、会改动的作用域用 `yolo`(0.18 起,见下文)。 ## 公开契约 `ZCodeTransport`(`auth_gap`、`run_session`、`complete`)、`spec = PROVIDERS["zcode"]`。 @@ -84,3 +85,33 @@ stdlib + `.base` + `..agent_loop.AgentOutcome` + `..llm` 的类型与 `ModelMism `subscription_billing` 仅在实际选中的 provider 为已知 OAuth coding plan 时为 True;自定义 provider 或 settings 中的 API provider override 返回 False。它描述计费模式,不声称调用花费为零。 `kb init --subscription-generator` 通过此声明显式使用订阅生成器,保留未报告的 USD 与 token 用量。 + +## zcode 0.17 与 0.18(2026-11-11、2026-11-24) + +- **项目级 MCP server 的信任登记(0.17)。** 0.17 给项目作用域的 MCP server 加了 + 工作区信任门(`createWorkspaceMcpTrust`),无头 prompt 过不去:工具桥被静默留成 + 未连接,每个模块 agent 都只能读、随后阻塞(run-20261111-160314)。`_write_mcp_config` + 写完会话配置后调用 `_seed_workspace_mcp_trust`,把本会话的信任记录追加进宿主的 + `~/.zcode/security/workspace-mcp-trust-v1.json`(flock 串行、幂等,并清掉会话目录 + 已不存在的记录)。记录的 `declarationDigest` 是对规范化后的 + `{version, workspaceIdentity, workingDirectory, serverName, sourcePaths, config}` + 做 sha256——键排序、紧凑分隔符、非 ASCII 原样;其中 `config` 是该 server 去掉 + `enabled`/`source` 后的执行字段,`env` 缺省为 `{}`、`cwd` 缺省为工作目录。摘要 + 的算法若在将来的版本里变化,就**失败关闭**:桥保持未连接,引擎的桥存活检查拦住 + 该模块。0.17.1 上实测过(桥被拉起、工具调用往返)。 +- **只读作用域跑 `--mode guarded`,不再是 `plan`(0.18)。** 0.18 的 plan 模式要求 + 每个 MCP 工具都经审批,而无头会话无人审批:只读作用域经工具桥的读取被拒 + ("Plan mode requires approval for MCP tools that are not read-only")。拒绝列表 + 剥掉之后,plan 与 guarded 留下同一批原生工具(全是读),guarded 只对危险命令 + 保留询问。给桥工具标 `readOnlyHint` 在 plan 模式下不起作用:那里的 MCP 能力一律 + 是 `needsApproval`。一次性调用(`complete()`)仍用 plan,它不带桥。 +- **会话管理工具加入 `_DISALLOWED`(0.18)。** `CreateSession`、`ForkSession`、 + `InterruptSession`、`ListSessions`、`ReadSession`、`RenameSession`、`SendToSession`、 + `WaitSessions` 能触达宿主的其他会话。宿主安装的插件 server(`mcp__plugin_*`)在 + 每种模式下都列在工具清单里,仍留在审计白名单之外,与之前相同。 +- **桥进程的环境带上 `IMX_GPU_MODE` 与 `IMX_GPU_WAIT`。** 桥自己会启动 GPU 命令 + (agent 的 shell 与测试工具),campaign 按命令向调度器取卡时它需要知情。 + `IMX_GPU_HELD` 有意不传:它只在已持有卡的命令树内部为真。 + +0.18.0 上的实测(2026-11-24):一次性调用服务于钉住的模型;只读会话经桥读文件; + 会改动的作用域经桥写文件。信任登记沿用 0.17 的算法,0.18 仍然连得上桥。 diff --git a/doc/architecture/SPEC/rebase_engine.md b/doc/architecture/SPEC/rebase_engine.md index d329f167..b5f93706 100644 --- a/doc/architecture/SPEC/rebase_engine.md +++ b/doc/architecture/SPEC/rebase_engine.md @@ -1,8 +1,8 @@ # rebase_engine/ —— 规范 - + -`LOC ~7500(26 个模块) · repo-rebase-v3 的原生 rebase 引擎 · refactor-status: ok` +`LOC ~9530(30 个模块) · repo-rebase-v3 的原生 rebase 引擎 · refactor-status: ok` ## 职责 父级 rebase agent 机制的仓库中立移植(PR0..PR7 分片落地):repo-rebase-v3 @@ -88,6 +88,9 @@ runner/LLM/CI client 全部可注入 —— 每个模块都能离线测试。 取锁(父级 parity)。 - wheel:每个 uv 调用 `--python` 显式指向**声明的目标 venv** —— 启动 shell 的 venv 状态绝不影响装到哪;只有 import 验证失败才重试。 +- baseline venv:克隆后的 launcher/activation 路径必须独立且重复修复幂等; + baseline 包优先安装冻结 wheel,否则非 editable 安装源码。临时 worktree + 删除后须再次从 venv 目录验证 import;缓存也须验证实际 import,不能只信版本元数据。 - CI 创建受守卫:durable op 记录先于 API 调用,恢复按 op id 精确匹配, **不确定时绝不重复创建**。 - 每个被 monitor 的 CI round 持久化实际 monitor 时长,供 run metrics 从 durable @@ -256,3 +259,39 @@ GPU 进程执行 SIGINT→SIGTERM→SIGKILL 阶梯。`module_pytest.py` 现在 收口而不是推进到下一个兄弟;substate 短路**只**接受 done/skipped,所以 `--resume` 重跑 interrupted 模块、跳过 done;`_v3_wave_gate` 把 interrupted 与 failed 同等视为未完成。 + +## 按需 GPU:agent shell、测试包装器与提示词(2026-11-25) + +campaign 不再从头到尾持有一份外层预约,每条 GPU 命令向调度器申请自己需要的卡 +(`testing` 规范的"按命令向调度器申请 GPU")。本包里三处与之相接: + +- **`run_shell`。** `handle_run_shell` 先决定这条命令要不要卡,再把执行交给 + `_run_shell`(原有的 Popen、后代快照与超时逻辑未变)。按需模式(读本进程环境的 + `IMX_GPU_MODE`)下,它把模式写进子进程环境,使命令启动的 `imx-omni-pytest` + 自己去申请;`testing.gpu_demand.shell_needs_gpu` 判定会起测试或 CUDA 代码的命令, + 用 `scheduler_wrap` 向调度器要 1 张卡(等待上限是工具超时的一半),并给子进程设 + `IMX_GPU_HELD=1`,命令启动的东西不再申请。等待到期时返回 + `{"exit_code": 1, "gpu_unavailable": true, "stderr": "Not run: …"}`;其余失败 + 在 stderr 前附上调度器的错误文本。2026-11-24/25 的 campaign 里,agent 的 1039 次 + 工具调用有 882 次走 `run_shell`(计划评审之前 `run_pytest` 是锁住的),其中绝大多数 + 是 `git`、`grep` 与读取,不受影响。 +- **`module_pytest.py`。** 包装器的 `TestJob` 带 `gpus=1`:测试可能用到卡,如同它 + 过去在外层预约下运行时那样。包装器仍返回结果自己的 rc(既有契约,由 + `test_module_pytest_outcomes.py` 钉住),所以跳过时把 + `imx-omni-pytest: skipped — <原因>` 同时写到 stdout 和 stderr。 +- **提示词。** `build_module_prompt(..., cuda_devices=prompt_devices(config.cuda_devices))`: + 按需模式下 `CUDA_DEVICES` 替换成"由调度器按命令设置(本会话不持有卡)"。模板里的 + "Use only env from this prompt: `CUDA_VISIBLE_DEVICES={CUDA_DEVICES}`" 不再让 + agent 以为自己握有 0、1 两张卡。 + +测试在 `test_gpu_demand.py`(agent shell、模块测试包装器)。 + +## 基线运行时的 wheel variant(2026-11-23) + +`wheel.ensure_baseline_venv` 装基线 commit 的 wheel 时,variant 改为 +`spec.baseline_variant or spec.variant`;`WheelSpec.from_manifest` 读可选的 +`rebase.wheel.baseline_variant`,未声明时行为不变。vLLM 在 3996083d37 把 main 的 +默认 CUDA 构建从 13.0 换到 13.2:main 只发布 `cu132` wheel,而作为基线的 v0.34.0 +final 只有 `cu130`。按目标的 variant 去取,测试循环用来区分既有失败与回归的基线 +运行时就建不出来,退回到让基线也跑在 campaign 的 venv 上。vllm-omni adapter 把 +`baseline_variant` 设为 `cu130`。测试:`test_rebase_release_target.py`。 diff --git a/doc/architecture/SPEC/testing.md b/doc/architecture/SPEC/testing.md index e35ea229..6473e79a 100644 --- a/doc/architecture/SPEC/testing.md +++ b/doc/architecture/SPEC/testing.md @@ -1,8 +1,8 @@ # testing/ —— 规范 - + -`LOC ~1760(6 个文件) · 测试执行底座(rebase agent shell 测试层的 Python 移植) · refactor-status: ok` +`LOC ~2190(9 个文件) · 测试执行底座(rebase agent shell 测试层的 Python 移植) · refactor-status: ok` ## 职责 仓库中立的测试执行底座:gpu_lock.sh / kill_test_tree.sh / test_watchdog.sh / @@ -22,6 +22,10 @@ test_runner.sh 的 Python 移植。仓库专属数据(watchdog 模式、artifa 廉价 reviewer 裁决(KILL/CONTINUE)。 - `watchdog_learn.py` —— Tier-2 裁决的记录/收割/晋升:一贯良性的模式 自动晋升进噪声 overlay YAML(数据,而非 shell 时代的改代码)。 +- `cpu_ci_resources.py` —— 目标仓库 Simple CPU job 的单卡对齐:pytest 的 marker + 表达式恰为 `core_model and cpu` 时,把 `CUDA_VISIBLE_DEVICES` 收到第一张。 +- `gpu_demand.py` —— 按需 GPU:向 canhazgpu 调度器**按命令**申请卡的模式开关、 + 一条命令的卡数、`gpu run` 包装程序,以及交给会话配置与提示词的卡数。 ## 公开契约 - `env_plan`:`build_subprocess_env(...)`、`scrub_agent_shell_env(env, keep_hf_token, extra_safe_prefixes)`, @@ -32,8 +36,14 @@ test_runner.sh 的 Python 移植。仓库专属数据(watchdog 模式、artifa - `runner`:`TestRunner.run(job, env, baseline, dry_run) -> TestOutcome`、 `TestRunner.terminate_active() -> bool`(对正在跑的 attempt 的进程组 + 快照 后代 TERM→宽限→KILL;无 attempt 在跑返回 False;可自信号处理器/他线程调用, - `_spawn` 的 `proc.wait()` 随后返回子进程的信号 rc)、`TestJob`、`RunPlan`、`TestOutcome`、`strip_cov_flags`、`cleanup_test_artifacts`、 + `_spawn` 的 `proc.wait()` 随后返回子进程的信号 rc)、`TestJob`(含 `gpus`)、 + `RunPlan`、`TestOutcome`、`strip_cov_flags`、`cleanup_test_artifacts`、 `log_file_for`/`pass_marker_for`、`TIMEOUT_RC=124`、`PY_TIMEOUT_MARGIN_SEC`。 +- `gpu_demand`:`GpuDemand`(`.from_env`)、`command_gpus`、`shell_needs_gpu`、 + `scheduler_wrap`、`idle_timeout`、`granted_gpus`、`scheduler_error`、 + `duration_seconds`、`session_devices`、`prompt_devices`;常量 `MODE_ENV`、 + `HELD_ENV`、`WAIT_ENV`、`NO_GPU_RC`、`SCHEDULER_TIMEOUT_MARGIN_SEC`、 + `IDLE_MAX_SEC`。 - `watchdog`:`WatchdogPatterns(.from_yaml)`、`LogWatchdog(.start/.stop/.check_once/.result)`、`WatchdogResult`。 - `watchdog_learn`:`record`、`harvest`、`eligible_patterns`、`promote`、 `read_decisions`、`normalize_pattern`、`repair_tail`。 @@ -86,7 +96,10 @@ env 前缀 → `scrub_agent_shell_env(extra_safe_prefixes=…)`(manifest 数 (TestRunner 对 shell 的 command-echo 金样)、`test_module_pytest_signals.py` (经包装器:`terminate_active` 停树、stdin=/dev/null);`watchdog_learn` 另由 `test_curator.py`(harvest exactly-once)与 `test_knowledge_foundation.py` -(record 身份字段、撕尾修复)钉住。 +(record 身份字段、撕尾修复)钉住。`test_gpu_demand.py`(64 个)以一个替身 `gpu` +可执行文件覆盖按需模式:卡数、shell 命令的判定、包装程序的输出路由与等待到期、 +空闲回收的单位与上限、调度器拒绝请求时的日志行、`TestRunner` 的 skip,以及 agent +shell 与模块测试包装器。 ## 重构备注 `runner.py`(643L)是包内最重的一块:`_spawn` 把快照线程、双定时器、watchdog @@ -104,3 +117,64 @@ env 前缀 → `scrub_agent_shell_env(extra_safe_prefixes=…)`(manifest 数 KeyboardInterrupt/SystemExit 展开)打断时先刷新快照、杀树,再让异常传播—— 包装器被展开时测试树不得继续占 GPU。消费方是 `rebase_engine/module_pytest.py::WrapperProcess` 的 SIGTERM/SIGINT 处理器。 + +## 按命令向调度器申请 GPU(2026-11-25) + +在此之前,一次 rebase 从头到尾持有一份外层 `gpu run` 预约,每条 GPU 命令继承 +它的 `CUDA_VISIBLE_DEVICES`。v0.35.0 campaign 在 2026-11-25 连续五小时占着 4 张 +卡,其中最多只有 130 MB 在用;manifest 的 71 个 job 全部声明 `min_gpus=1`,在 +GPU 锁下一次只跑一个,52 个只用 1 张卡。负责人决定:不再有任何预约横跨整个 +campaign,改为每条 GPU 命令向调度器申请自己需要的卡、只在运行期间持有。 + +- **开关。** `IMX_GPU_MODE=demand` 选择按需模式;未设置时行为不变(调用方已 + 持有卡,命令继承)。`IMX_GPU_WAIT`(缺省 `30m`)是命令在调度器队列里的等待 + 上限。`IMX_GPU_HELD=1` 表示所在命令树已持有卡,其下任何 `TestRunner` 都不再 + 申请。`TestRunner` 缺省从环境读取(`GpuDemand.from_env`),测试可显式传 + `gpu_demand=`。 +- **卡数。** `TestJob.gpus` 显式给出;缺省取三者最大值:`min_gpus`、命令里最大 + 的 `cards_N` pytest marker(manifest 的每个 job 都是 `hw: any`,卡数只在 marker + 里)、以及"取 GPU 锁的运行算 1 张"。0 表示不申请(`run_precommit`)。agent 的 + `run_pytest`/`reproduce` 与 `imx-omni-pytest` 包装器各要 1 张。 +- **包装程序。** `scheduler_wrap(command, gpus, timeout_sec, wait, note, side_log)` + 返回一段给 `bash --norc -c` 的 shell:命令的 stdout/stderr 留在调用方给的描述符 + (fd 3/4),调度器自己的输出写进 `<日志>.scheduler`。实测调度器把进度打到 + stdout、把 `Error: wait timeout exceeded` 打到 stderr,等待到期时退出码为 1; + 包装程序把它换成 `NO_GPU_RC`(97),其余失败保留调度器的退出码。调度器的超时设为 + `timeout_sec + SCHEDULER_TIMEOUT_MARGIN_SEC`(秒),让运行器自己的定时器先触发。 + 空闲回收由 `idle_timeout()` 给出:同一个时长向上取整到**单一单位**(秒、分或小时), + 且不超过 `IDLE_MAX_SEC`(3 小时)。实测(2026-11-25)调度器只解析单一单位的空闲 + 时长:给 `1h30m` 直接拒绝;给 `8100s` 它接受,再把 `2h15m` 交给自己的 supervisor, + 那个进程读不了(卡照给、照释放,只是不会因空闲回收);超过 3 小时也直接拒绝。 + v0.35.0 campaign 最初把整个超时按秒传给它,超时 6 小时的模块测试因此一次都没跑成。 + 命令的超时用秒则没有限制。 +- **调度器的输出绝不进测试日志。** 本机的 `gpu run` 会打印一条 "failed to + activate booking" 警告,命中看门狗 Tier-2 的 `failed to`,会让每个 job 多一次 + LLM 评审。日志里只留运行器自己写的一行 `[gpu] …`(拿到的卡,或没跑成的原因); + 命令失败且调度器报了错时才附上它的错误文本。日志里没有 `Reserved …` 可依时写 + `[gpu] not run: the scheduler named no card(s) and said: …`——没有卡,命令就没跑; + 错误文本在它随后的 `Usage:` 处截断。 +- **排队到期是一次显式 skip。** `TestRunner.run` 返回 `rc=0, skipped=True`, + `skip_reason` 写明要几张、等了多久;命令没有运行,也不写 pass marker。等待 + 上限不超过 `timeout_sec` 的一半:运行器的定时器从 spawn 起算,排队时间也在内。 +- **按需模式下由调度器决定有没有卡**:不做硬件门槛,丢掉继承的 + `CUDA_VISIBLE_DEVICES`(调度器授权时自己命名),并给子进程设 `IMX_GPU_HELD=1`。 +- **命令结束后不在已释放的卡上清理进程。** 外层预约时代 + `cleanup_orphan_gpu_procs`/`wait_gpu_memory_idle` 是安全的,卡始终是自己的; + 调度器授予的卡在命令结束时已经释放,可能已经分给了别人。逃逸的后代由调度器 + 自己的 guard 负责杀。 +- **agent 在 shell 里起的测试。** `shell_needs_gpu(command)` 把命令按引号之外的 + 列表分隔符与括号拆成简单命令,剥掉可能位于命令字之前的东西(`then`/`do`/ + `else`、`env`、`VAR=value`、`sudo`、`timeout`、`nohup`、`uv run`),再看命令字: + `pytest` 或 `python -m pytest` 算测试;`python` 且同一条简单命令里有 CUDA 用法 + (`torch.cuda`、`cuda.is_available(`、`device="cuda"`、`--device cuda`)算 GPU + 代码;`python -` 从 stdin 读脚本时,脚本就是命令的其余部分。只在命令字上判断: + 对整行用一个正则时,`grep -rn pytest`、`echo pytest` 也会命中。提到 + `imx-<仓库>-pytest` 形式的模块测试包装器或 `gpu run` 的命令原样放过,它们自己申请 + (包装器的名字由 adapter 侧决定,这里不写死任何一个仓库)。 +- **交给会话配置与提示词的卡数。** `session_devices(env)`:有 + `CUDA_VISIBLE_DEVICES` 就用它,否则是外层预约时代的历史缺省 `0,1`;按需模式 + 下会话不持有卡,取空串。`prompt_devices("")` 在按需模式下返回一句"由调度器按 + 命令设置",提示词不再把 `0,1` 当作会话持有的卡交给 agent。 + +实测(2026-11-25):一条 `TestRunner` 命令在真实调度器下恰好持有 1 张卡 35 秒, +前后都是 0;torch 看到 1 张卡;import vllm 及其编译扩展不建立 CUDA 上下文。 diff --git a/src/infermatrix_copilot/engine/steps/rebase_v3.py b/src/infermatrix_copilot/engine/steps/rebase_v3.py index f29fa06a..6c45079a 100644 --- a/src/infermatrix_copilot/engine/steps/rebase_v3.py +++ b/src/infermatrix_copilot/engine/steps/rebase_v3.py @@ -32,6 +32,7 @@ from ...rebase_engine.test_manifest import ManifestSpec, build_manifest from ...rebase_engine.remote_ci_owner import RemoteOwnerResolver from ...rebase_engine.testing_env import scrubbed_agent_env +from ...testing.gpu_demand import session_devices from ...scopes import PathScope, ToolScope from ..step import FailureKind, StepContext, StepResult from ._common import require_repo, step @@ -102,6 +103,29 @@ def _local_timeout_multiplier(testing: Mapping) -> float | StepResult: return factor +def _local_test_job(job, *, timeout_multiplier: float, virtualenv: bool): + """Adapt container commands to the selected local runtime and budget. + + VIRTUAL_ENV is supplied by _target_test_env for both candidate and + baseline runs. The CI manifest itself remains unchanged. + """ + command = job.command + if virtualenv: + command = re.sub( + r'(?m)^([ \t]*uv[ \t]+pip[ \t]+install[ \t]+)--system(?=[ \t]|$)', + r'\1--python "$VIRTUAL_ENV/bin/python"', command) + if timeout_multiplier != 1: + # Ready jobs also put direct timeout commands around individual + # pytest invocations. Scaling only the outer runner leaves those + # inner CI budgets unchanged and still kills valid local runs. + command = re.sub( + r'(?m)^([ \t]*timeout[ \t]+)(\d+(?:\.\d+)?)([smhd]?)(?=[ \t])', + lambda m: (f'{m[1]}{float(m[2]) * timeout_multiplier:g}{m[3]}'), + command) + return _dc_replace(job, command=command, + timeout_sec=job.timeout_sec * timeout_multiplier) + + def _tier_client(ctx: StepContext): """The run's agent backend via `Settings.tier_target` — the ONLY place a tier's model may pair with an endpoint and credential. Returns @@ -330,7 +354,7 @@ def _run_tests(kw: Mapping, key: str) -> dict: outcome = runner.run( TestJob(key=f"{key}_{abs(hash(cmd)) % 10 ** 8}", command=cmd, timeout_sec=float(kw.get("timeout") or 1800), - min_gpus=0, gpu_lock=True), + min_gpus=0, gpu_lock=True, gpus=1), _target_test_env(settings, manifest, host_env=host_env)) tail = "" try: @@ -341,7 +365,11 @@ def _run_tests(kw: Mapping, key: str) -> dict: .splitlines()[-120:]) except OSError: pass - return {"exit_code": outcome.rc, "passed": outcome.rc == 0, + # A run the scheduler gave no card to did not pass (rc is 0 for a skip). + return {"exit_code": outcome.rc, + "passed": outcome.rc == 0 and not outcome.skipped, + "skipped": outcome.skipped, + "skip_reason": outcome.skip_reason, "timed_out": outcome.timed_out, "output": tail, "log_file": outcome.log_file} @@ -373,7 +401,7 @@ def run_precommit(**kw) -> dict: outcome = runner.run( TestJob(key="agent_precommit", command=command, timeout_sec=float(pc.get("timeout_sec") or 600), - min_gpus=0, gpu_lock=False), + min_gpus=0, gpu_lock=False, gpus=0), _target_test_env(settings, manifest, host_env=host_env)) return {"exit_code": outcome.rc, "passed": outcome.rc == 0, "log_file": outcome.log_file} @@ -1314,7 +1342,7 @@ async def _run_debug_agent(ctx: StepContext, manifest: dict, module: str, # the same host facts and budgets a module attempt gets: the # bridge forwards CUDA/HF from here and the debug prompt's # budget note must not fall back to the dataclass defaults - cuda_devices=_os.environ.get("CUDA_VISIBLE_DEVICES", "0,1"), + cuda_devices=session_devices(_os.environ), hf_home=_os.environ.get("HF_HOME", "/model"), harness_timeout_s=float(getattr( ctx.settings, "rebase_harness_timeout_sec", 7200)), @@ -1546,9 +1574,10 @@ def notify_download(key: str, repo_id: str) -> None: def _job(slug: str) -> TestJob: job = manifest_job_to_test_job(jobs_by_slug[slug]) - if timeout_multiplier != 1: - job = _dc_replace(job, timeout_sec=job.timeout_sec * timeout_multiplier) - return job + return _local_test_job( + job, timeout_multiplier=timeout_multiplier, + virtualenv=bool(_target_venv( + manifest, extra=ctx.settings.expansion_env()))) def _to_result(outcome) -> tl.TestRunResult: infra = "timeout" if outcome.timed_out else \ @@ -2082,7 +2111,7 @@ async def _v3_module_rebase(ctx: StepContext) -> StepResult: ""), # the prompt's CUDA/HF facts must describe THIS host, not the # dataclass defaults - cuda_devices=os.environ.get("CUDA_VISIBLE_DEVICES", "0,1"), + cuda_devices=session_devices(os.environ), hf_home=os.environ.get("HF_HOME", "/model"), model_aliases=ctx.settings.model_aliases, model_mismatch_policy=ctx.settings.model_mismatch_policy, diff --git a/src/infermatrix_copilot/providers/zcode.py b/src/infermatrix_copilot/providers/zcode.py index 5cc79a58..90800b90 100644 --- a/src/infermatrix_copilot/providers/zcode.py +++ b/src/infermatrix_copilot/providers/zcode.py @@ -22,13 +22,25 @@ - **The session cwd is a scratch dir WE own, never the PR worktree.** zcode loads ``.env`` from its cwd and discovers ``zcode.json`` / ``.zcode/config.json`` from the cwd up to the git root — project config - can declare stdio MCP servers (i.e. commands) and zcode connects them - without a trust prompt. Running inside a PR checkout would let the PR - under review configure the reviewer. The worktree is read by absolute - path instead; the prompt names it. -- The MCP tool bridge rides that scratch dir's ``.zcode/config.json`` + can declare stdio MCP servers (i.e. commands). Running inside a PR + checkout would let the PR under review configure the reviewer. The + worktree is read by absolute path instead; the prompt names it. +- **The MCP tool bridge rides that scratch dir's ``.zcode/config.json`` (measured live: ``mcp__infermatrix-tools__read_file`` called, bridge trace recorded), so scoped reads still pass ``tools.dispatch``. + zcode 0.17 added a workspace trust gate for project-scope servers that + headless prompts cannot grant; the provider pre-seeds the host trust + store's matching record (``_seed_workspace_mcp_trust``) so the bridge + still connects — verified live on 0.17.1 (bridge spawned, tool call + round-trip). A future digest change fails CLOSED: the bridge stays + unconnected and the engine's lifecycle check blocks the module. +- **A read-only scope runs ``--mode guarded``, not ``plan`` (zcode 0.18).** + Plan mode asks for every MCP tool there, so a headless prompt gets the + bridge denied ("Plan mode requires approval for MCP tools that are not + read-only"; probed live on 0.18.0, 2026-11-24). After the denylist both + modes leave the same native tools, all reads; ``guarded`` keeps the ask for + dangerous commands. The host's plugin servers (``mcp__plugin_*``) are listed + in every mode and stay outside the audit allowlist. Model selection: zcode has no ``--model`` flag; a session takes the *configured default* of its personal provider config, and only when that @@ -52,6 +64,8 @@ from __future__ import annotations +import fcntl +import hashlib import json import logging import os @@ -83,7 +97,19 @@ _BRIDGE_SERVER = "infermatrix-tools" _BRIDGE_PREFIX = f"mcp__{_BRIDGE_SERVER}__" -# Everything zcode 0.16.9 exposes in plan mode that is not a pure read. +# zcode 0.17 gates project-scope MCP servers behind a workspace trust review +# (createWorkspaceMcpTrust) that headless `--prompt` sessions cannot grant — +# the server is silently left unconnected ("bridge never started"). The +# trust record lives in `/.zcode/security/workspace-mcp-trust-v1.json` +# and matches on (workspaceIdentity, serverName, declarationDigest); we +# pre-seed it after writing the session's project config. User-scope +# declaration (kind "user" skips the gate) would need HOME redirection, +# which measurably breaks the CLI's model-selection bootstrap (0.17.1) and +# runs retention cleanup against symlinked host dirs — rejected. +_TRUST_STORE_REL = (".zcode", "security", "workspace-mcp-trust-v1.json") + +# Everything zcode exposes that is not a pure read: 0.16.9's set, plus the +# session management zcode 0.18 added, which reaches the host's other sessions. _DISALLOWED = ( "Bash", "Edit", "Write", "MultiEdit", "NotebookEdit", "Agent", "Skill", "ExitPlanMode", "EnterPlanMode", "AskUserQuestion", "SendMessage", @@ -91,6 +117,8 @@ "SaveWorkflow", "EvalWorkflowSnippet", "ResumeWorkflowRun", "ResolveWorkflowQuestion", "TaskStop", "mcp__node_repl__js", "mcp__web_reader__webReader", "mcp__4_5v_mcp__analyze_image", + "CreateSession", "ForkSession", "InterruptSession", "ListSessions", + "ReadSession", "RenameSession", "SendToSession", "WaitSessions", ) # What remains after the denylist — the audit's allowlist. _READ_TOOLS = frozenset({ @@ -200,7 +228,87 @@ def auth_gap(self) -> str | None: # -- process plumbing ---------------------------------------------------- @staticmethod - def _write_mcp_config(session: Path, spec_path: Path, *, + def _zcode_canon(value) -> str: + """zcode's hash2 pre-image: JSON.stringify with a replacer that + sorts the keys of every object (arrays untouched), compact + separators, raw non-ASCII — json.dumps(sort_keys=True) matches it + exactly (golden-verified against a live 0.17.1 session).""" + return json.dumps(value, sort_keys=True, separators=(",", ":"), + ensure_ascii=False) + + @classmethod + def _trust_declaration_digest(cls, session: Path, server: str, + server_config: dict) -> str: + """The declarationDigest zcode 0.17 computes over a project-scope + server: sha256 over the canonical form of + ``{version, workspaceIdentity, workingDirectory, serverName, + sourcePaths, config}`` where config is the server entry's execution + fields (enabled/source stripped, env defaulted to {}, cwd defaulted + to the working directory) and workspaceIdentity defaults to the + working directory. sourcePaths is the project config file list — + here exactly the one file we write.""" + execution = {k: v for k, v in server_config.items() + if k not in ("enabled", "source")} + execution["env"] = server_config.get("env") or {} + execution["cwd"] = server_config.get("cwd") or str(session) + value = { + "version": 1, + "workspaceIdentity": str(session), + "workingDirectory": str(session), + "serverName": server, + "sourcePaths": [str(session / ".zcode" / "config.json")], + "config": execution, + } + canonical = cls._zcode_canon(value) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + @classmethod + def _seed_workspace_mcp_trust(cls, session: Path, server: str, + server_config: dict) -> None: + """Append the session's trust record (idempotent, flock-serialized) + to the host's workspace MCP trust store. Best effort: on failure the + bridge stays untrusted and the engine's bridge-lifecycle check + surfaces it — never a silent pass.""" + home = Path(sanitized_env().get("HOME") or Path.home()) + store = home.joinpath(*_TRUST_STORE_REL) + record = { + "workspaceIdentity": str(session), + "serverName": server, + "declarationDigest": cls._trust_declaration_digest( + session, server, server_config), + "grantedAt": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()) + + f".{int(time.time() * 1000) % 1000:03d}Z", + } + store.parent.mkdir(parents=True, exist_ok=True) + with open(store, "a+", encoding="utf-8") as fh: + fcntl.flock(fh, fcntl.LOCK_EX) + try: + fh.seek(0) + try: + data = json.loads(fh.read() or "{}") + except ValueError: + data = {} + records = data.get("records") if isinstance(data, dict) else None + if not isinstance(records, list): + records = [] + key = (record["serverName"], record["declarationDigest"]) + if not any((r.get("serverName"), r.get("declarationDigest")) + == key for r in records): + records.append(record) + # prune OUR records whose session dir is gone — the store is + # host-global and every dispatch session adds one record + records = [r for r in records + if r.get("serverName") != _BRIDGE_SERVER + or Path(str(r.get("workspaceIdentity", ""))).is_dir()] + fh.seek(0) + fh.truncate() + fh.write(json.dumps({"schemaVersion": 1, "records": records}, + indent=2)) + finally: + fcntl.flock(fh, fcntl.LOCK_UN) + + @classmethod + def _write_mcp_config(cls, session: Path, spec_path: Path, *, timeout_s: float = 30.0) -> None: package_root = Path(__file__).resolve().parents[2] # The harness stays credential-free; its scoped bridge also needs @@ -210,12 +318,14 @@ def _write_mcp_config(session: Path, spec_path: Path, *, "OMP_NUM_THREADS", "MKL_NUM_THREADS", "ZCODE_DATA_BASE_DIR", "STRICT_BACKEND", "STRICT_BACKEND_MODEL", "STRICT_BACKEND_CLI", "ZCODE_PROVIDER_ID", "ZCODE_REASONING_LEVEL", - "REBASE_REVIEWER_MODEL", "NOTIFY_EMAIL") if k in os.environ} + "REBASE_REVIEWER_MODEL", "NOTIFY_EMAIL", + # The bridge starts GPU commands itself (the agents' shell and + # test tools): it asks the scheduler for their cards when the + # campaign does. IMX_GPU_HELD is deliberately not passed: it is + # only ever true inside a command tree that already holds them. + "IMX_GPU_MODE", "IMX_GPU_WAIT") if k in os.environ} bridge_env["PYTHONPATH"] = str(package_root) - config = session / ".zcode" / "config.json" - config.parent.mkdir() - config.write_text(json.dumps({"features": {"memory": False}, "memory": {"use": False}, - "mcp": {"servers": {_BRIDGE_SERVER: { + server = { "type": "stdio", # ZCode otherwise abandons tools after 30s, even while a valid # test or nested plan review is still running in the bridge. @@ -225,7 +335,17 @@ def _write_mcp_config(session: Path, spec_path: Path, *, "args": ["-m", "infermatrix_copilot.tool_bridge", "--spec", str(spec_path)], "env": bridge_env, - }}}}, indent=2), encoding="utf-8") + } + config = session / ".zcode" / "config.json" + config.parent.mkdir() + config.write_text(json.dumps({"features": {"memory": False}, "memory": {"use": False}, + "mcp": {"servers": {_BRIDGE_SERVER: server}}}, + indent=2), encoding="utf-8") + try: + cls._seed_workspace_mcp_trust(session, _BRIDGE_SERVER, server) + except OSError as exc: + logger.warning("zcode workspace MCP trust seed failed " + "(bridge will stay untrusted): %s", exc) @staticmethod def _write_oneshot_config(session: Path) -> None: @@ -643,7 +763,12 @@ def run_session(self, req: AgentSessionRequest) -> AgentOutcome: model=req.model or self.settings.strict_backend_model, # Mutating workflows write only through the scoped bridge; # native writes/shell/subagents retain the same denylist. - mode="plan" if req.scope.read_only else "yolo") + # A read-only scope takes `guarded`, not `plan`: zcode 0.18 + # asks for every MCP tool in plan mode, so a headless prompt + # gets the bridge denied. After the denylist both modes leave + # the same native tools; `guarded` keeps asking for dangerous + # commands, which headless turns into a denial. + mode="guarded" if req.scope.read_only else "yolo") finally: shutil.rmtree(session, ignore_errors=True) usage = self._usage(events) diff --git a/src/infermatrix_copilot/rebase_engine/module_pytest.py b/src/infermatrix_copilot/rebase_engine/module_pytest.py index cc442a6f..6d6c3aa3 100644 --- a/src/infermatrix_copilot/rebase_engine/module_pytest.py +++ b/src/infermatrix_copilot/rebase_engine/module_pytest.py @@ -458,7 +458,10 @@ def review_fn(test_name: str, snippet: str) -> str: # so a GPU-less box still RUNS the command (a skip would be a false # pass), while gpu_lock=True holds the lock for the run job = TestJob(key=_job_key(args), command=command, timeout_sec=timeout, - min_gpus=0, gpu_lock=_needs_gpu_lock(args), index=0) + min_gpus=0, gpu_lock=_needs_gpu_lock(args), index=0, + # the tests may use a card, as they could under the + # campaign-wide reservation this wrapper used to run in + gpus=1) if process_setup: process.install_signal_handlers(runner) outcome = runner.run(job, dict(os.environ)) @@ -472,8 +475,12 @@ def review_fn(test_name: str, snippet: str) -> str: platform_marker=platform_marker, process=process) try: if outcome.skipped: - print(f"imx-omni-pytest: skipped — {outcome.skip_reason}", - file=sys.stderr) + notice = f"imx-omni-pytest: skipped — {outcome.skip_reason}" + # On stdout as well as stderr: the rc is the outcome's own (0 + # here), so a reader of the output alone must see that nothing + # ran and why (in demand mode: the scheduler granted no card). + print(notice) + print(notice, file=sys.stderr) if verdict["signal_diagnosis"]: print(f"module test wrapper: {verdict['signal_diagnosis']}", file=sys.stderr) diff --git a/src/infermatrix_copilot/rebase_engine/module_rebase.py b/src/infermatrix_copilot/rebase_engine/module_rebase.py index 00b9fd99..65bd2763 100644 --- a/src/infermatrix_copilot/rebase_engine/module_rebase.py +++ b/src/infermatrix_copilot/rebase_engine/module_rebase.py @@ -24,6 +24,7 @@ from .prompt_builder import (ModulePromptData, build_debug_prompt, build_module_prompt) from .substate import Substate +from ..testing.gpu_demand import prompt_devices @dataclass(frozen=True) @@ -484,7 +485,7 @@ async def rebase_module( vllm_path=config.vllm_path, omni_path=config.omni_path, script_dir=config.script_dir, last_rebase_vllm_commit=assignment_baseline, - cuda_devices=config.cuda_devices, hf_home=config.hf_home, + cuda_devices=prompt_devices(config.cuda_devices), hf_home=config.hf_home, log_dir=config.log_dir, signal_dir=config.signal_dir, rebase_run_id=substate.run_id, max_debug_retries=config.max_debug_retries, diff --git a/src/infermatrix_copilot/rebase_engine/rebase_tools.py b/src/infermatrix_copilot/rebase_engine/rebase_tools.py index 66109549..c979c6e0 100644 --- a/src/infermatrix_copilot/rebase_engine/rebase_tools.py +++ b/src/infermatrix_copilot/rebase_engine/rebase_tools.py @@ -178,6 +178,50 @@ def handle_grep(pattern: str, path: str = "", include: str = "*.py", def handle_run_shell(command: str, workdir: str | None = None, timeout: int = 600, **_: Any) -> dict: + import tempfile + + from ..testing.gpu_demand import ( + HELD_ENV, MODE_ENV, NO_GPU_RC, GpuDemand, scheduler_error, + scheduler_wrap, shell_needs_gpu) + + env, side_log, wait = (dict(paths.env) or None), None, "" + if GpuDemand.from_env(os.environ).enabled: + # The mode is this process's (a bridge learns it from its env) + # and must reach what the command starts: the test wrapper asks + # for its own cards. + env = dict(env or os.environ) + env[MODE_ENV] = "demand" + if shell_needs_gpu(command): + # Agents start tests from the shell (`run_pytest` is gated + # behind the decision file): such a command gets its cards + # the way the wrapper does, and what it starts must not ask + # for them a second time. + env[HELD_ENV] = "1" + fd, name = tempfile.mkstemp(prefix="imx-gpu-", suffix=".log") + os.close(fd) + side_log, wait = Path(name), f"{max(int(timeout / 2), 1)}s" + command = scheduler_wrap( + command, gpus=1, timeout_sec=timeout + 60, wait=wait, + note=f"imx agent shell {os.getpid()}", side_log=side_log) + try: + result = _run_shell(command, workdir, timeout, env) + finally: + scheduler = scheduler_error(side_log) if side_log else "" + if side_log: + side_log.unlink(missing_ok=True) + if result.get("exit_code") == NO_GPU_RC: + return {"exit_code": 1, "stdout": result.get("stdout", ""), + "stderr": "Not run: the scheduler granted no GPU within " + f"{wait}. Retry later, or continue with work " + "that needs no GPU.", + "gpu_unavailable": True} + if scheduler and result.get("exit_code", 0) != 0: + result["stderr"] = (f"[gpu] scheduler: {scheduler}\n" + + result.get("stderr", ""))[-5000:] + return result + + def _run_shell(command: str, workdir: str | None, timeout: int, + env: dict[str, str] | None) -> dict: from ..testing.process_tree import collect_descendants, kill_tree from ..testing.runner import TestRunner, _record_walk @@ -189,7 +233,7 @@ def handle_run_shell(command: str, workdir: str | None = None, # and replace the target venv's PATH before verification. ["bash", "--norc", "-c", command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace", - cwd=cwd, env=dict(paths.env) or None, + cwd=cwd, env=env, start_new_session=True) as proc: # Killing only bash leaves pytest and setsid'd model workers # alive. Reuse the test runner's identity-checked snapshots so diff --git a/src/infermatrix_copilot/rebase_engine/wheel.py b/src/infermatrix_copilot/rebase_engine/wheel.py index bc221084..9bd39048 100644 --- a/src/infermatrix_copilot/rebase_engine/wheel.py +++ b/src/infermatrix_copilot/rebase_engine/wheel.py @@ -77,6 +77,10 @@ class WheelSpec: # Complete published wheels avoid editable installs tied to a disposable # source checkout. Optional: existing adapters retain editable installs. install_url_template: str = "" + # Variant of the LAST-RELEASE wheel the baseline venv installs, when it + # differs from `variant` (a main target built with a newer CUDA than the + # release the target repo is aligned to). "" keeps `variant`. + baseline_variant: str = "" @classmethod def from_manifest(cls, data: Mapping) -> "WheelSpec": @@ -91,6 +95,7 @@ def from_manifest(cls, data: Mapping) -> "WheelSpec": install_env=dict(data.get("install_env", {})), reinstall_retries=int(data.get("reinstall_retries", 3)), install_url_template=str(data.get("install_url_template", "")), + baseline_variant=str(data.get("baseline_variant", "")), ) @@ -749,6 +754,31 @@ def import_ok() -> bool: # -- baseline runtime ---------------------------------------------------------- +def _relocate_venv_scripts(src: Path, dst: Path) -> None: + """Point cloned launchers/activation scripts at the clone, without writing + through hardlinks into the campaign runtime.""" + import stat + + source = os.fsencode(str(src)) + destination = os.fsencode(str(dst)) + # The baseline directory name starts with the campaign name. Match the + # complete path so a healthy cloned launcher is not relocated twice. + source_path = re.compile(re.escape(source) + rb"(?=[/\x22\x27\s]|$)") + for script in (dst / "bin").iterdir(): + if script.is_symlink() or not script.is_file(): + continue + data = script.read_bytes() + if b"\0" in data or not source_path.search(data): + continue + replacement = script.with_name(f".{script.name}.relocate-{os.getpid()}") + try: + replacement.write_bytes(source_path.sub(lambda _: destination, data)) + replacement.chmod(stat.S_IMODE(script.stat().st_mode)) + os.replace(replacement, script) + finally: + replacement.unlink(missing_ok=True) + + def _clone_tree_hardlinked(src: Path, dst: Path) -> bool: """Hardlink clone (near-zero disk, same filesystem). uv replaces files by rename, which breaks the links — the campaign venv is never modified @@ -757,6 +787,7 @@ def _clone_tree_hardlinked(src: Path, dst: Path) -> bool: if rc != 0: _log(f"baseline-venv clone failed: {err.strip()}") return False + _relocate_venv_scripts(src, dst) return True @@ -778,7 +809,8 @@ def ensure_baseline_venv( against the wheel main was LAST aligned to"; this builds exactly that runtime: hardlink-clone the campaign venv (identical deps), swap in the baseline wheel from a throwaway worktree of the upstream at the - baseline commit. Returns None on any failure — a missing baseline + baseline commit. Installs are non-editable so cleanup cannot remove code + the runtime needs; console scripts are relocated to the clone. Returns None on any failure — a missing baseline runtime keeps the loop's regression-preserving default and must never read as pre-existing.""" import shutil @@ -791,9 +823,16 @@ def ensure_baseline_venv( python = str(bv / "bin" / "python") if (bv / "pyvenv.cfg").is_file(): installed = read_installed_version(spec, python=python, run=run) - if installed and version_matches_commit(installed, baseline_commit): - log(f"baseline venv already healthy at {bv}") - return bv + matches = (installed_wheel_matches( + spec, baseline_commit, installed, python=python, run=run) + if spec.install_url_template else + bool(installed and version_matches_commit(installed, baseline_commit))) + if matches: + rc, _, _ = run([python, "-c", build_import_check_snippet(spec)], cwd=bv) + if rc == 0: + _relocate_venv_scripts(target_venv, bv) + log(f"baseline venv already healthy at {bv}") + return bv if not (Path(upstream) / ".git").exists(): log(f"baseline venv: upstream {upstream} is not a git checkout") return None @@ -813,12 +852,22 @@ def ensure_baseline_venv( try: run([uv, "pip", "uninstall", "--python", python, spec.package], cwd=wt) + # The baseline is the last release the target repo was aligned to, and + # that release can be published under another variant than a main + # target (a release line may ship cu130 only while main builds cu132). + baseline_variant = spec.baseline_variant or spec.variant env = dict(os.environ) env.update({key: value.replace("{commit}", baseline_commit) - .replace("{variant}", spec.variant) + .replace("{variant}", baseline_variant) for key, value in spec.install_env.items()}) + # The worktree is deleted below. An editable install would retain a + # finder pointing into that deleted tree and pass only the import check + # run from inside it. Prefer the frozen published wheel when available. + requirement = (spec.install_url_template.format( + commit=baseline_commit, variant=baseline_variant, arch=spec.arch, + package=spec.package) if spec.install_url_template else ".") rc, _, err = run([uv, "pip", "install", "--python", python, - "-e", "."], cwd=wt, env=env, timeout=3600) + requirement], cwd=wt, env=env, timeout=3600) if rc != 0: log(f"baseline wheel install failed: {err.strip()[-300:]}") shutil.rmtree(bv, ignore_errors=True) @@ -832,6 +881,13 @@ def ensure_baseline_venv( finally: run(["git", "-C", str(upstream), "worktree", "remove", "--force", str(wt)], timeout=600) + # Probe after removal, away from both source trees: cwd must not rescue a + # broken install. This also protects baseline classification on later reuse. + rc, _, err = run([python, "-c", build_import_check_snippet(spec)], cwd=bv) + if rc != 0: + log(f"baseline venv import failed after source cleanup: {err.strip()[-200:]}") + shutil.rmtree(bv, ignore_errors=True) + return None log(f"baseline venv ready at {bv} (wheel {baseline_commit[:12]})") return bv diff --git a/src/infermatrix_copilot/testing/gpu_demand.py b/src/infermatrix_copilot/testing/gpu_demand.py new file mode 100644 index 00000000..b549898b --- /dev/null +++ b/src/infermatrix_copilot/testing/gpu_demand.py @@ -0,0 +1,249 @@ +"""GPUs on demand from the canhazgpu scheduler (owner decision, 2026-11-25). + +A campaign used to hold one `gpu run` reservation, four cards, for its whole +run, and every GPU command inherited CUDA_VISIBLE_DEVICES from it. In demand +mode nothing is held between commands: each GPU command asks the scheduler for +the cards it needs and holds them exactly as long as it runs. + + IMX_GPU_MODE=demand opt in. Unset, or any other value: the caller already + holds the cards and commands inherit them. + IMX_GPU_HELD=1 set inside a command tree that already holds its cards; + nothing below asks the scheduler again. + IMX_GPU_WAIT=30m how long a command waits in the scheduler's queue + before it is reported as not run. + +Measured on the scheduler (2026-11-25): `gpu run` prints its progress to stdout +and its errors to stderr ("Error: wait timeout exceeded"), exits 1 when it gave +up, names the granted cards as "Reserved N GPU(s): [a b]" and sets +CUDA_VISIBLE_DEVICES to them. Its own output is kept out of test logs: on this +machine it carries a "failed to activate booking" warning, which matches the +watchdog's `failed to` pattern and would start an LLM review of every job. +Its idle release takes one unit and at most three hours (`idle_timeout`); its +command timeout takes any duration in seconds. +""" +from __future__ import annotations + +import os +import re +import shlex +from dataclasses import dataclass +from pathlib import Path +from typing import Mapping + +MODE_ENV = "IMX_GPU_MODE" +HELD_ENV = "IMX_GPU_HELD" +WAIT_ENV = "IMX_GPU_WAIT" +DEFAULT_WAIT = "30m" +#: The scheduler stops a command this long after the runner's own timers +#: would have, so the runner's timeout stays the one that fires. +SCHEDULER_TIMEOUT_MARGIN_SEC = 900 +#: The longest idle release the scheduler accepts; it refuses the request +#: outright above this ("idle timeout cannot exceed 3h"). +IDLE_MAX_SEC = 3 * 3600 +#: The wrapper's own status for "the scheduler granted no cards in time". +NO_GPU_RC = 97 + +_CARDS = re.compile(r"\bcards_(\d{1,2})\b") +_WAIT_EXPIRED = "wait timeout exceeded" +_GRANTED = re.compile(r"Reserved \d+ GPU\(s\): \[([0-9 ]+)\]") +_DURATION = re.compile(r"^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?(?:(\d+(?:\.\d+)?)s)?$") + +# A test run an agent typed in a shell is found per simple command: split +# where a new simple command starts (outside quotes), strip what may precede +# the command word, then look at the command word itself. One pattern over +# the whole line kept matching `pytest` as an argument (`grep -rn pytest`, +# `echo pytest`). +_LEAD = re.compile( + r"^(?:[\s(]+|\b(?:then|do|else|nohup|time|exec)\b\s+" + r"|\btimeout\s+\S+\s+|\benv\s+(?:-\S+\s+)*|\bsudo\s+(?:-\S+\s+)*" + r"|\buv\s+run\s+(?:--\S+\s+)*" + r"|[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|\"[^\"]*\"|[^\s;&|()]+)\s+)+") +_EXE = re.compile(r"(?:\S*/)?(?Ppytest|python[0-9.]*)(?=[\s)&|;]|$)") +_PYTEST_MODULE = re.compile(r"\s+-m\s+pytest(?=[\s)&|;]|$)") +# Python running CUDA code. The token alone is not enough: agents grep and +# read this text far more often than they run it. +_CUDA_CODE = re.compile( + r"torch\.cuda\b|cuda\.is_available\(|device\s*=\s*['\"]cuda|--device[=\s]+['\"]?cuda") +_PYTHON_STDIN = re.compile(r"\bpython[0-9.]*\s+-\s*(?:<<|<)") +# Commands that already handle the cards themselves: the scheduler, and the +# repository's module test wrapper (named per repository by rebase_engine). +_SELF_SERVED = re.compile(r"\bgpu\s+run\b|\bimx-[a-z0-9]+-pytest\b") +# Outside quotes, each of these characters starts a new simple command. +_COMMAND_START = ";|&()\n" + + +@dataclass(frozen=True) +class GpuDemand: + """Whether to ask the scheduler per command, and how long to wait for it.""" + enabled: bool = False + wait: str = DEFAULT_WAIT + + @classmethod + def from_env(cls, env: Mapping[str, str] | None = None) -> "GpuDemand": + env = os.environ if env is None else env + return cls(enabled=env.get(MODE_ENV, "") == "demand" + and not env.get(HELD_ENV), + wait=env.get(WAIT_ENV) or DEFAULT_WAIT) + + +def duration_seconds(text: str, default: float = 0.0) -> float: + """`30m`, `2h`, `90s`, `1h30m` -> seconds; `default` for anything else.""" + m = _DURATION.match((text or "").strip()) + if not m or not any(m.groups()): + return default + h, minute, s = (float(g) if g else 0.0 for g in m.groups()) + return h * 3600 + minute * 60 + s + + +def command_gpus(command: str, minimum: int = 0) -> int: + """Cards a test command needs: the largest `cards_N` pytest marker it + selects (every job of the manifest says `hw: any`), else `minimum`.""" + found = [int(n) for n in _CARDS.findall(command or "") if 1 <= int(n) <= 16] + return max([minimum, *found]) + + +def shell_needs_gpu(command: str) -> bool: + """Whether a shell command an agent typed starts a test run, or Python + that touches CUDA, without the gated wrapper (which asks for its cards + itself). A command that already names `gpu run` or the wrapper is left + alone.""" + if _SELF_SERVED.search(command or ""): + return False + # a script read from stdin: its text is the rest of the command + if _PYTHON_STDIN.search(command) and _CUDA_CODE.search(command): + return True + return any(_simple_command_needs_gpu(part) + for part in _simple_commands(command)) + + +def _simple_commands(command: str) -> list[str]: + """The simple commands of a shell line: split where the next one starts, + at a list separator or a parenthesis that is not inside quotes.""" + out: list[str] = [] + buf: list[str] = [] + quote = "" + i = 0 + while i < len(command): + ch = command[i] + if quote: + if ch == "\\" and quote == '"' and i + 1 < len(command): + buf.append(command[i:i + 2]) + i += 2 + continue + if ch == quote: + quote = "" + buf.append(ch) + elif ch in "'\"": + quote = ch + buf.append(ch) + elif ch in _COMMAND_START: + out.append("".join(buf)) + buf = [] + else: + buf.append(ch) + i += 1 + out.append("".join(buf)) + return out + + +def _simple_command_needs_gpu(segment: str) -> bool: + """`pytest` or `python -m pytest` as the command word, or `python` with + CUDA code in the same simple command.""" + body = _LEAD.sub("", segment, count=1) + found = _EXE.match(body) + if not found: + return False + rest = body[found.end():] + if found["exe"] == "pytest" or _PYTEST_MODULE.match(rest): + return True + return bool(_CUDA_CODE.search(body)) + + +def scheduler_wrap(command: str, *, gpus: int, timeout_sec: float, wait: str, + note: str, side_log: Path) -> str: + """A shell program (for `bash --norc -c`) that runs `command` under the + scheduler. The command's stdout and stderr stay where the caller put them + and the scheduler's own output goes to `side_log`. The program exits with + the command's status once the cards were granted, with NO_GPU_RC when the + wait expired, and with the scheduler's status for its other failures.""" + ask = shlex.join([ + "gpu", "run", "--gpus", str(gpus), + "--timeout", f"{int(timeout_sec)}s", + # the scheduler releases an idle card after 30 min by default; a test + # may take longer before its first kernel (a model download), and the + # timeout already bounds this reservation + "--idle-timeout", idle_timeout(timeout_sec), + "--wait", wait, "--note", note, "--", + "bash", "--norc", "-c", "exec >&3 2>&4\n" + command]) + side = shlex.quote(str(side_log)) + return "\n".join([ + "exec 3>&1 4>&2", + f"{ask} > {side} 2>&1", + "rc=$?", + f'if [ "$rc" -ne 0 ] && grep -q {shlex.quote(_WAIT_EXPIRED)} {side}; ' + f"then exit {NO_GPU_RC}; fi", + 'exit "$rc"', + ]) + + +def idle_timeout(seconds: float) -> str: + """`seconds` as an idle release the scheduler takes: one unit (seconds, + minutes or hours), rounded up so the reservation outlives the command's + own timers, and never above IDLE_MAX_SEC. It parses one unit only. Given + `2h15m` it refuses the request; given `8100s` it accepts, then hands its + supervisor `"2h15m"`, which that process cannot read (the card is still + granted and released, but never for idleness).""" + seconds = min(int(seconds), IDLE_MAX_SEC) + if seconds < 60: + return f"{max(seconds, 1)}s" + minutes = -(-seconds // 60) + if minutes < 60: + return f"{minutes}m" + return f"{-(-seconds // 3600)}h" + + +def granted_gpus(side_log: Path) -> list[str]: + """The physical cards the scheduler named for one command.""" + try: + found = _GRANTED.search(Path(side_log).read_text(errors="replace")) + except OSError: + return [] + return found.group(1).split() if found else [] + + +def scheduler_error(side_log: Path) -> str: + """The scheduler's own failure text of one command, for a log the command + failed anyway; "" when it has none.""" + try: + text = Path(side_log).read_text(errors="replace") + except OSError: + return "" + hit = text.find("Error:") + if hit < 0: + return "" + error = text[hit:] + usage = error.find("\nUsage:") # the flag list that follows is not the error + return (error if usage < 0 else error[:usage]).strip()[:300] + + +INHERITED_DEFAULT = "0,1" +ON_DEMAND_TEXT = "set per command by the scheduler (none held by this session)" + + +def session_devices(env: Mapping[str, str] | None = None) -> str: + """The cards a session may hand to its commands: CUDA_VISIBLE_DEVICES + when it holds them, else the historical default `0,1`. A session whose + commands each ask the scheduler holds none and says so with "".""" + env = os.environ if env is None else env + if "CUDA_VISIBLE_DEVICES" in env: + return env["CUDA_VISIBLE_DEVICES"] + return "" if GpuDemand.from_env(env).enabled else INHERITED_DEFAULT + + +def prompt_devices(devices: str, env: Mapping[str, str] | None = None) -> str: + """What a prompt names as the session's cards. A session whose commands + each ask the scheduler holds none: the prompt says so instead of offering + a selection the agent would then use on cards it does not hold.""" + if devices or not GpuDemand.from_env(env).enabled: + return devices + return ON_DEMAND_TEXT diff --git a/src/infermatrix_copilot/testing/runner.py b/src/infermatrix_copilot/testing/runner.py index 01894d98..278b7187 100644 --- a/src/infermatrix_copilot/testing/runner.py +++ b/src/infermatrix_copilot/testing/runner.py @@ -26,6 +26,9 @@ from pathlib import Path from typing import Callable +from .gpu_demand import ( + HELD_ENV, NO_GPU_RC, SCHEDULER_TIMEOUT_MARGIN_SEC, GpuDemand, command_gpus, + duration_seconds, granted_gpus, scheduler_error, scheduler_wrap) from .gpu_lock import (GpuLock, cleanup_orphan_gpu_procs, visible_devices, wait_gpu_memory_idle) from .watchdog import LogWatchdog, WatchdogPatterns @@ -67,6 +70,10 @@ class TestJob: setup: str = "" index: int = 0 hw: str = "" # informational only — never enforced (shell parity) + # Cards to ask the scheduler for, when the runner is in demand mode. + # None derives them: min_gpus, the command's `cards_N` markers, and one + # card for a run that takes the GPU lock; 0 asks for none. + gpus: int | None = None @dataclass @@ -309,7 +316,8 @@ def __init__(self, *, repo_root: Path, tests_dir: Path, cuda_visible_devices: str = "", available_gpus: Callable[[], int] | None = None, watchdog_interval: float = 10.0, - notify_download: Callable[[str, str], None] | None = None): + notify_download: Callable[[str, str], None] | None = None, + gpu_demand: GpuDemand | None = None): self.repo_root = Path(repo_root) self.tests_dir = Path(tests_dir) self.patterns = patterns @@ -319,6 +327,8 @@ def __init__(self, *, repo_root: Path, tests_dir: Path, self.artifact_globs = artifact_globs or [] self.gpu_lock_dir = gpu_lock_dir self.cuda = cuda_visible_devices + self.gpu_demand = (gpu_demand if gpu_demand is not None + else GpuDemand.from_env()) self.available_gpus = available_gpus or ( lambda: len(visible_devices(self.cuda))) self.watchdog_interval = watchdog_interval @@ -344,8 +354,14 @@ def terminate_active(self) -> bool: def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, dry_run: bool = False) -> TestOutcome: log_file = log_file_for(self.tests_dir, job, baseline=baseline) + # In demand mode the command asks the scheduler for its cards, and + # the scheduler's own output goes beside the log, never into it. + gpus = self._job_gpus(job) if self.gpu_demand.enabled else 0 + side_log = (log_file.with_name(log_file.name + ".scheduler") + if gpus else None) plan = RunPlan( - argv=["bash", "--norc", "-c", _exec_wrap(job.command)], + argv=["bash", "--norc", "-c", + self._command(job, job.command, side_log)], env_overlay=dict(job.env), timeout_sec=job.timeout_sec, needs_gpu_lock=(job.gpu_lock if job.gpu_lock is not None else job.min_gpus > 0), @@ -365,7 +381,14 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, # effective env is {**env, **job.env}, and either layer may redirect # CUDA_VISIBLE_DEVICES away from the runner's own view run_env = {**env, **job.env} - if "CUDA_VISIBLE_DEVICES" in run_env: + if gpus: + # The scheduler names the cards when it grants them; an inherited + # selection would name cards this command does not hold. Anything + # the command starts must not ask for cards a second time. + run_env.pop("CUDA_VISIBLE_DEVICES", None) + run_env[HELD_ENV] = "1" + job_cuda, avail = "", gpus + elif "CUDA_VISIBLE_DEVICES" in run_env: job_cuda = run_env["CUDA_VISIBLE_DEVICES"] avail = len(visible_devices(job_cuda)) else: @@ -419,7 +442,18 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, except OSError: primary_offset = 0 rc, wd_hit, timed_out = self._spawn( - _exec_wrap(job.command), job, run_env, log_file, append=True) + self._command(job, job.command, side_log), job, run_env, + log_file, append=True) + if gpus: + self._note_scheduler(job, side_log, rc, log_file) + if rc == NO_GPU_RC: + # The queue outlasted the wait. An explicit skip, like the + # hardware gate: never a failure, never a silent pass. + return TestOutcome(rc=0, skipped=True, log_file=str(log_file), + plan=plan, skip_reason=( + f"needs {self._job_gpus(job)} GPU(s); the " + f"scheduler granted none within " + f"{self._wait(job)}")) append_silent_log_footer(log_file, rc, "primary") if wd_hit: rc = rc or 1 @@ -439,15 +473,19 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, f.write("\n[coverage-fallback] Retrying without --cov " f"flags:\n{fallback}\n") rc, wd_hit, timed_out = self._spawn( - _exec_wrap(fallback), job, run_env, log_file, - append=True) + self._command(job, fallback, side_log), job, run_env, + log_file, append=True) append_silent_log_footer(log_file, rc, "cov-fallback") if wd_hit: rc = rc or 1 finally: if lock is not None: - cleanup_orphan_gpu_procs(job_cuda) - wait_gpu_memory_idle(job_cuda) + if not gpus: + # Under a reservation of our own anything on these cards + # is our orphan. A card the scheduler granted is released + # by now and may already be someone else's. + cleanup_orphan_gpu_procs(job_cuda) + wait_gpu_memory_idle(job_cuda) lock.release() cleanup_test_artifacts(self.repo_root, self.artifact_globs) @@ -457,6 +495,63 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, timed_out=timed_out, log_file=str(log_file), plan=plan) + # -- cards on demand ------------------------------------------------------ + def _job_gpus(self, job: TestJob) -> int: + """What one job asks the scheduler for (TestJob.gpus).""" + if job.gpus is not None: + return job.gpus + takes_gpu = (job.gpu_lock if job.gpu_lock is not None + else job.min_gpus > 0) + return command_gpus(job.command, + max(job.min_gpus, 1 if takes_gpu else 0)) + + def _wait(self, job: TestJob) -> str: + """The queue wait: the configured one, but never more than half of the + job's timeout, because the runner's own timer starts at the spawn.""" + seconds = min(duration_seconds(self.gpu_demand.wait, 1800.0), + job.timeout_sec / 2) + return f"{max(int(seconds), 1)}s" + + def _command(self, job: TestJob, command: str, + side_log: Path | None) -> str: + wrapped = _exec_wrap(command) + if side_log is None: + return wrapped + return scheduler_wrap( + wrapped, gpus=self._job_gpus(job), + timeout_sec=job.timeout_sec + SCHEDULER_TIMEOUT_MARGIN_SEC, + wait=self._wait(job), + note=f"imx {self.tests_dir.parent.name} {job.key}"[:100], + side_log=side_log) + + def _note_scheduler(self, job: TestJob, side_log: Path, rc: int, + log_file: Path) -> None: + """One or two lines for whoever reads the log: the cards a command + ran on, or why it did not run. The scheduler's own text stays in the + side log unless the command failed anyway.""" + gpus = self._job_gpus(job) + granted = granted_gpus(side_log) + if rc == NO_GPU_RC: + lines = [f"[gpu] not run: the scheduler granted no {gpus} card(s) " + f"within {self._wait(job)}."] + elif granted: + lines = [f"[gpu] {gpus} card(s) from the scheduler: " + f"[{' '.join(granted)}]"] + if rc not in (0, TIMEOUT_RC): + error = scheduler_error(side_log) + if error: + lines.append(f"[gpu] scheduler: {error}") + else: + # no card was ever named, so nothing ran under the scheduler + error = scheduler_error(side_log) + lines = ["[gpu] not run: the scheduler named no card(s)" + + (f" and said: {error}" if error else ".")] + try: + with open(log_file, "a", encoding="utf-8") as lf: + lf.write("\n" + "\n".join(lines) + "\n") + except OSError: + pass + # -- internals ------------------------------------------------------------ def _run_setup(self, job: TestJob, env: dict[str, str], log_file: Path) -> None: diff --git a/test/test_api_drift_guard.py b/test/test_api_drift_guard.py index 0800ce43..1d8a966b 100644 --- a/test/test_api_drift_guard.py +++ b/test/test_api_drift_guard.py @@ -88,3 +88,28 @@ async def release_kv_cache_memory(self): assert "release_kv_cache_memory" in findings[0] guard.__globals__["import_class"] = lambda module, name: EngineClient if module == "upstream" else CurrentAPI assert guard() == [] + + +@pytest.mark.parametrize("keyword_only", [False, True]) +def test_guard_preserves_optional_positional_parameters(guard, keyword_only): + class Base: + def make_request_output(self, tokens, error=None): + pass + + class KeywordOnly(Base): + def make_request_output(self, tokens, *, error=None): + pass + + class Compatible(Base): + def make_request_output(self, tokens, error=None): + pass + + guard.__globals__["INHERITANCE_MAP"] = [("upstream", "Base", "omni", "Omni")] + child = KeywordOnly if keyword_only else Compatible + guard.__globals__["import_class"] = lambda module, name: Base if module == "upstream" else child + findings = guard() + if keyword_only: + assert len(findings) == 1 + assert "positional" in findings[0] and "error" in findings[0] + else: + assert findings == [] diff --git a/test/test_assembly.py b/test/test_assembly.py index cf913922..fe6e384b 100644 --- a/test/test_assembly.py +++ b/test/test_assembly.py @@ -2815,3 +2815,43 @@ def test_local_timeout_multiplier_rejects_invalid_factor(factor): result = _local_timeout_multiplier({"local_timeout_multiplier": factor}) assert isinstance(result, StepResult) assert result.failure == FailureKind.BLOCKED + + +def test_local_test_job_targets_each_runtime_without_system_install(tmp_path): + """The same job must install into the candidate or baseline it is running.""" + import os + + from infermatrix_copilot.engine.steps.rebase_v3 import _local_test_job + from infermatrix_copilot.testing.runner import TestJob + + binary = tmp_path / "bin" + binary.mkdir() + uv = binary / "uv" + uv.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n') + uv.chmod(0o755) + original = TestJob(key="attention", command="uv pip install --system --no-deps fastvideo-kernel==0.3.4", + timeout_sec=1200, min_gpus=1) + local = _local_test_job(original, timeout_multiplier=1, virtualenv=True) + for runtime in ("candidate runtime", "baseline runtime"): + env = dict(os.environ, PATH=str(binary) + os.pathsep + os.environ["PATH"], + VIRTUAL_ENV=str(tmp_path / runtime)) + result = subprocess.run(["bash", "--norc", "-c", local.command], + env=env, capture_output=True, text=True, check=True) + assert result.stdout.splitlines() == [ + "pip", "install", "--python", str(tmp_path / runtime / "bin/python"), + "--no-deps", "fastvideo-kernel==0.3.4"] + assert "--system" in original.command + assert _local_test_job(original, timeout_multiplier=1, virtualenv=False) == original + + +def test_local_timeout_budget_reaches_inner_commands(tmp_path): + from infermatrix_copilot.engine.steps.rebase_v3 import _local_test_job + from infermatrix_copilot.testing.runner import TestJob + + original = TestJob(key="distributed", command="timeout 0.05s sleep 0.15\ntimeout 0.05s sleep 0.15", + timeout_sec=10, min_gpus=0) + assert subprocess.run(["bash", "--norc", "-ec", original.command]).returncode == 124 + local = _local_test_job(original, timeout_multiplier=10, virtualenv=True) + assert subprocess.run(["bash", "--norc", "-ec", local.command]).returncode == 0 + assert local.timeout_sec == 100 + assert original.timeout_sec == 10 diff --git a/test/test_gpu_demand.py b/test/test_gpu_demand.py new file mode 100644 index 00000000..7cced2b3 --- /dev/null +++ b/test/test_gpu_demand.py @@ -0,0 +1,409 @@ +"""GPUs on demand from the scheduler: `testing/gpu_demand.py`, `TestRunner` and +the agents' shell in demand mode, and the module test wrapper. + +The scheduler is a stand-in `gpu` executable. It records the request, prints +what the real one prints on this machine (including the booking warning that +matches the watchdog's `failed to` pattern), sets CUDA_VISIBLE_DEVICES and runs +the command, or reports an expired wait. No card is involved. +""" + +import json +import os +import re +import subprocess +from pathlib import Path + +import pytest + +from infermatrix_copilot.rebase_engine import module_pytest +from infermatrix_copilot.rebase_engine.rebase_tools import ( + RebasePaths, + build_rebase_tools, +) +from infermatrix_copilot.testing import gpu_demand +from infermatrix_copilot.testing.gpu_demand import ( + DEFAULT_WAIT, + IDLE_MAX_SEC, + NO_GPU_RC, + SCHEDULER_TIMEOUT_MARGIN_SEC, + GpuDemand, + command_gpus, + duration_seconds, + granted_gpus, + idle_timeout, + prompt_devices, + scheduler_error, + scheduler_wrap, + session_devices, + shell_needs_gpu, +) +from infermatrix_copilot.testing.runner import TestJob, TestRunner + +_STUB = r"""#!/bin/sh +# A stand-in for canhazgpu `run`. +gpus="" +while [ $# -gt 0 ]; do + case "$1" in + --gpus) gpus="$2"; shift 2 ;; + --) shift; break ;; + *) shift ;; + esac +done +printf 'gpus=%s\n' "$gpus" >> "$IMX_GPU_STUB_LOG" +if [ -f "$(dirname "$IMX_GPU_STUB_REFUSE")/deny" ]; then + printf 'Error: invalid idle timeout: idle timeout cannot exceed 3h\nUsage:\n canhazgpu run\nFlags:\n --gpus int Number of GPUs\n' >&2 + printf 'Error: invalid idle timeout: idle timeout cannot exceed 3h\n' >&2 + exit 1 +fi +if [ -f "$IMX_GPU_STUB_REFUSE" ]; then + printf 'Waiting for GPUs... (queue position: 3)\n' + printf 'Error: wait timeout exceeded\nUsage:\n canhazgpu run\n' >&2 + printf 'Error: wait timeout exceeded\n' >&2 + exit 1 +fi +printf 'Waiting for GPUs... (queue position: 2)\n' +printf 'Reserved %s GPU(s): [7] for command execution (timeout: 1h 0m 0s)\n' "$gpus" +printf 'Warning: failed to activate booking abc: failed to stop run task x\n' >&2 +CUDA_VISIBLE_DEVICES=7 exec "$@" +""" +_PYTEST_STUB = """#!/bin/sh +printf 'STUB-PYTEST cards=%s\\n' "$CUDA_VISIBLE_DEVICES" +""" +_DEMAND = GpuDemand(enabled=True, wait="5s") +_PROBE = ("printf 'hello\\n'\n" + "printf 'cards=%s\\n' \"$CUDA_VISIBLE_DEVICES\"\n" + "printf 'held=%s\\n' \"$IMX_GPU_HELD\"") + + +@pytest.fixture +def scheduler(tmp_path, monkeypatch): + """Puts the stand-in `gpu` (and a stand-in `pytest`) first on PATH.""" + stubs = tmp_path / "stubs" + stubs.mkdir() + for name, text in (("gpu", _STUB), ("pytest", _PYTEST_STUB)): + path = stubs / name + path.write_text(text) + path.chmod(0o755) + calls = tmp_path / "scheduler.log" + refuse = tmp_path / "refuse" + env = {"PATH": str(stubs) + os.pathsep + os.environ["PATH"], + "IMX_GPU_STUB_LOG": str(calls), + "IMX_GPU_STUB_REFUSE": str(refuse)} + for key in ("IMX_GPU_MODE", "IMX_GPU_HELD", "IMX_GPU_WAIT"): + monkeypatch.delenv(key, raising=False) + return env, calls, refuse + + +def _requests(calls: Path) -> list[str]: + return calls.read_text().split() if calls.exists() else [] + + +def _runner(tmp_path, demand=_DEMAND): + return TestRunner(repo_root=tmp_path, tests_dir=tmp_path / "tests", + gpu_demand=demand) + + +# -- pure helpers --------------------------------------------------------------- + +def test_command_gpus_is_the_largest_cards_marker(): + assert command_gpus('pytest -m "core_model and (cards_1 or cards_4)"') == 4 + assert command_gpus("pytest tests/x -m cards_2") == 2 + assert command_gpus("pytest tests/x") == 0 + assert command_gpus("pytest tests/x", 1) == 1 + assert command_gpus("pytest -m cards_99") == 0 # not a card count + + +@pytest.mark.parametrize("command, needs", [ + ("pytest -x tests/a", True), + ("python -m pytest tests/a", True), + ("python3.12 -m pytest tests/a", True), + ("cd tests && pytest b", True), + ("(cd x && pytest)", True), + ("(pytest a)", True), + ("FOO=1 pytest -k foo", True), + ("VLLM_X=1 python -m pytest a", True), + ("env FOO=bar pytest", True), + ("if true; then pytest a; fi", True), + ("timeout 600 pytest a", True), + ("uv run pytest a", True), + ("nohup pytest a > x.log &", True), + ('pytest -m "core_model and (cards_1 or cards_4)"', True), + ('python -c "import torch; print(torch.cuda.device_count())"', True), + ("CUDA_VISIBLE_DEVICES=0 python x.py --device cuda", True), + ("python - <<\"PY\"\nimport torch\ntorch.cuda.synchronize()\nPY", True), + ("imx-omni-pytest tests/worker", False), + ("imx-other-pytest tests/worker", False), # named per repository + ("gpu run --gpus 1 -- pytest a", False), + ("cat pytest.ini", False), + ('git commit -m "fix pytest"', False), + ("grep -rn pytest tests/", False), + ("grep -rn torch.cuda vllm_omni/", False), + ("python script.py", False), + ("echo pytest", False), + ("echo \"run pytest now\"", False), + ("git status", False), + ("python check.py; echo torch.cuda", False), + ("python a.py | grep -n cuda.is_available", False), + ("cat conftest.py | grep -n cuda.is_available", False), + ("sed -i s/torch.cuda// a.py", False), + ("", False), +]) +def test_shell_needs_gpu(command, needs): + assert shell_needs_gpu(command) is needs + + +def test_duration_seconds_reads_the_scheduler_formats(): + assert DEFAULT_WAIT == "30m" and duration_seconds(DEFAULT_WAIT) == 1800 + assert duration_seconds("2h") == 7200 + assert duration_seconds("90s") == 90 + assert duration_seconds("1h30m") == 5400 + assert duration_seconds("later", -1) == -1 + + +@pytest.mark.parametrize("seconds, text", [ + (0, "1s"), (59, "59s"), (60, "1m"), (1040, "18m"), (1500, "25m"), + (1501, "26m"), (3599, "1h"), (3600, "1h"), (7200, "2h"), (7201, "3h"), + (8100, "3h"), (IDLE_MAX_SEC, "3h"), + (21600 + SCHEDULER_TIMEOUT_MARGIN_SEC, "3h"), +]) +def test_idle_timeout_is_one_unit_within_the_schedulers_cap(seconds, text): + assert idle_timeout(seconds) == text + # measured on the scheduler (2026-11-25): it reads one unit only (given + # `1h30m` it refuses the request) and at most three hours + assert re.fullmatch(r"\d+[smh]", text) + assert duration_seconds(text) <= IDLE_MAX_SEC + + +def test_mode_comes_from_the_environment(monkeypatch): + assert GpuDemand.from_env({}) == GpuDemand(enabled=False, wait="30m") + demand = {gpu_demand.MODE_ENV: "demand", gpu_demand.WAIT_ENV: "2m"} + assert GpuDemand.from_env(demand) == GpuDemand(enabled=True, wait="2m") + assert GpuDemand.from_env({gpu_demand.MODE_ENV: "reserved"}).enabled is False + # inside a command tree that already holds the cards nothing asks again + assert GpuDemand.from_env( + {**demand, gpu_demand.HELD_ENV: "1"}).enabled is False + monkeypatch.setenv(gpu_demand.MODE_ENV, "demand") + assert TestRunner(repo_root=Path("."), tests_dir=Path(".")).gpu_demand.enabled + + +def test_session_and_prompt_name_no_cards_on_demand(): + # under a campaign-wide reservation the historical default is kept + assert session_devices({}) == "0,1" + assert session_devices({"CUDA_VISIBLE_DEVICES": "4,5"}) == "4,5" + demand = {gpu_demand.MODE_ENV: "demand"} + assert session_devices(demand) == "" + assert session_devices({**demand, "CUDA_VISIBLE_DEVICES": "4,5"}) == "4,5" + # the prompt offers no selection an agent would use on cards it lacks + text = gpu_demand.ON_DEMAND_TEXT + assert prompt_devices("", demand) == text + assert prompt_devices("", {}) == "" + assert prompt_devices("4,5", {}) == "4,5" + + +# -- the wrapper program, run by a real bash ------------------------------------ + +def test_wrapper_routes_the_schedulers_output_and_the_commands(scheduler, tmp_path): + env, _, _ = scheduler + side = tmp_path / "side.log" + program = scheduler_wrap( + "printf 'out\\n'\nprintf 'err\\n' >&2\nprintf 'cards=%s\\n' \"$CUDA_VISIBLE_DEVICES\"\nexit 3", + gpus=2, timeout_sec=600, wait="30m", note="a test", side_log=side) + done = subprocess.run(["bash", "--norc", "-c", program], env=env, + capture_output=True, text=True) + assert done.returncode == 3 + assert done.stdout.splitlines() == ["out", "cards=7"] + assert done.stderr.splitlines() == ["err"] + spoken = side.read_text() + assert "Reserved 2 GPU(s): [7]" in spoken + assert "failed to activate booking" in spoken # never in the command's streams + assert granted_gpus(side) == ["7"] and scheduler_error(side) == "" + + +def test_wrapper_reports_an_expired_wait_with_its_own_status(scheduler, tmp_path): + env, _, refuse = scheduler + refuse.touch() + side = tmp_path / "side.log" + program = scheduler_wrap("printf 'ran\\n'", gpus=4, timeout_sec=600, + wait="30m", note="a test", side_log=side) + done = subprocess.run(["bash", "--norc", "-c", program], env=env, + capture_output=True, text=True) + assert done.returncode == NO_GPU_RC and done.stdout == "" + assert "wait timeout exceeded" in scheduler_error(side) + + +# -- TestRunner ------------------------------------------------------------------- + +def test_runner_in_demand_mode_runs_on_the_granted_cards(scheduler, tmp_path): + env, calls, _ = scheduler + outcome = _runner(tmp_path).run( + TestJob(key="probe", command=_PROBE, timeout_sec=120), dict(env)) + assert outcome.rc == 0 and not outcome.skipped + assert _requests(calls) == ["gpus=1"] + log = Path(outcome.log_file).read_text() + assert "hello" in log and "cards=7" in log and "held=1" in log + assert "[gpu] 1 card(s) from the scheduler: [7]" in log + # the scheduler's warning would match the watchdog's `failed to` pattern + assert "failed to activate booking" not in log + side = Path(outcome.log_file + ".scheduler") + assert "failed to activate booking" in side.read_text() + assert Path(outcome.log_file).with_name(".passed_probe").exists() + + +def test_runner_asks_for_the_jobs_cards_and_bounds_the_wait(scheduler, tmp_path): + env, calls, _ = scheduler + command = _PROBE + "\nprintf '%s\\n' pytest -m 'cards_1 or cards_2'" + job = TestJob(key="two", command=command, timeout_sec=100, min_gpus=1) + outcome = _runner(tmp_path, GpuDemand(enabled=True, wait="30m")).run( + job, dict(env)) + assert outcome.rc == 0 and _requests(calls) == ["gpus=2"] + program = outcome.plan.argv[-1] + assert "--gpus 2" in program + # the runner's own timer starts at the spawn: the wait is at most half of it + assert "--wait 50s" in program + assert f"--timeout {int(100 + SCHEDULER_TIMEOUT_MARGIN_SEC)}s" in program + assert "--idle-timeout 17m" in program + + +def test_runner_caps_the_idle_release_of_a_long_job(scheduler, tmp_path): + env, _, _ = scheduler + job = TestJob(key="long", command="printf 'ran\\n'", timeout_sec=21600) + outcome = _runner(tmp_path).run(job, dict(env)) + assert outcome.rc == 0 + program = outcome.plan.argv[-1] + assert f"--timeout {21600 + SCHEDULER_TIMEOUT_MARGIN_SEC}s" in program + assert "--idle-timeout 3h" in program + + +def test_runner_says_so_when_the_scheduler_refuses_the_request(scheduler, tmp_path): + env, _, _ = scheduler + (tmp_path / "deny").touch() + job = TestJob(key="probe", command="printf 'ran\\n'", timeout_sec=600) + outcome = _runner(tmp_path).run(job, dict(env)) + assert outcome.rc == 1 and not outcome.skipped # the scheduler's own status + log = Path(outcome.log_file).read_text() + assert ("[gpu] not run: the scheduler named no card(s) and said: " + "Error: invalid idle timeout: idle timeout cannot exceed 3h\n") in log + assert "Usage:" not in log and "\nran\n" not in log + + +def test_runner_leaves_a_command_that_asks_for_no_cards_alone(scheduler, tmp_path): + env, calls, _ = scheduler + job = TestJob(key="cpu", command="printf 'cpu\\n'", timeout_sec=60, + min_gpus=0, gpu_lock=False, gpus=0) + outcome = _runner(tmp_path).run(job, dict(env)) + assert outcome.rc == 0 and _requests(calls) == [] + assert "gpu run" not in outcome.plan.argv[-1] + + +def test_runner_an_expired_wait_is_a_skip_not_a_failure(scheduler, tmp_path): + env, calls, refuse = scheduler + refuse.touch() + job = TestJob(key="probe", command="printf 'ran\\n'", timeout_sec=600) + outcome = _runner(tmp_path).run(job, dict(env)) + assert outcome.skipped and outcome.rc == 0 and not outcome.timed_out + assert "scheduler granted none within" in outcome.skip_reason + log = Path(outcome.log_file).read_text() + assert "[gpu] not run" in log and "\nran\n" not in log # the command never ran + assert not Path(outcome.log_file).with_name(".passed_probe").exists() + + +def test_runner_in_demand_mode_ignores_an_inherited_selection(scheduler, tmp_path): + env, calls, _ = scheduler + outcome = _runner(tmp_path).run( + TestJob(key="probe", command=_PROBE, timeout_sec=120), + dict(env, CUDA_VISIBLE_DEVICES="0,1,2,3")) + assert "cards=7" in Path(outcome.log_file).read_text() + assert _requests(calls) == ["gpus=1"] + + +def test_runner_outside_demand_mode_keeps_the_hardware_gate(scheduler, tmp_path): + env, calls, _ = scheduler + job = TestJob(key="probe", command="printf 'ran\\n'", timeout_sec=60) + gated = _runner(tmp_path, GpuDemand(enabled=False)).run(job, dict(env)) + assert gated.skipped and "1 GPU(s), 0 available" in gated.skip_reason + assert _runner(tmp_path).run(job, dict(env)).skipped is False + assert _requests(calls) == ["gpus=1"] + + +# -- the agents' shell ------------------------------------------------------------- + +def _shell(env): + tools = build_rebase_tools( + [{"name": "run_shell", "description": "Run a command", + "input_schema": {"type": "object"}}], + RebasePaths(omni_path="/", vllm_path="/", env=env)) + return lambda command, timeout=60: json.loads( + tools["run_shell"].handler(command=command, timeout=timeout)) + + +def test_shell_runs_a_test_under_the_scheduler_and_leaves_the_rest_alone( + scheduler, tmp_path, monkeypatch): + env, calls, _ = scheduler + monkeypatch.setenv(gpu_demand.MODE_ENV, "demand") + monkeypatch.delenv(gpu_demand.HELD_ENV, raising=False) + run = _shell(env) + plain = run("printf 'plain cards=%s\\n' \"$CUDA_VISIBLE_DEVICES\"") + assert plain["exit_code"] == 0 and plain["stdout"].strip() == "plain cards=" + assert _requests(calls) == [] + test = run("cd /tmp && FOO=1 pytest -k x") + assert test["exit_code"] == 0, test + assert test["stdout"].strip() == "STUB-PYTEST cards=7" + assert "failed to activate booking" not in test["stderr"] + assert _requests(calls) == ["gpus=1"] + # a command that names the wrapper is left to it: the wrapper asks for + # its own cards + assert run("printf '%s\\n' imx-omni-pytest")["exit_code"] == 0 + assert _requests(calls) == ["gpus=1"] + + +def test_shell_tells_the_agent_when_no_card_was_granted(scheduler, monkeypatch): + env, calls, refuse = scheduler + monkeypatch.setenv(gpu_demand.MODE_ENV, "demand") + refuse.touch() + result = _shell(env)("pytest -k x", timeout=60) + assert result["gpu_unavailable"] is True and result["exit_code"] == 1 + assert "granted no GPU within 30s" in result["stderr"] + assert _requests(calls) == ["gpus=1"] + + +def test_shell_outside_demand_mode_never_asks(scheduler, tmp_path): + env, calls, _ = scheduler + result = _shell(env)("pytest -k x") + assert result["exit_code"] == 0 + assert result["stdout"].strip() == "STUB-PYTEST cards=" + assert _requests(calls) == [] + + +# -- the module test wrapper -------------------------------------------------------- + +def test_module_wrapper_asks_for_one_card_and_says_so_when_nothing_ran( + tmp_path, monkeypatch, capsys): + repo = tmp_path / "repo" + repo.mkdir() + for name in ("IMX_ADAPTER_REBASE", "IMX_WATCHDOG_OVERLAY"): + monkeypatch.delenv(name, raising=False) + for key, value in {"IMX_TARGET_REPO": str(repo), + "IMX_LOG_DIR": str(tmp_path / "logs"), + "IMX_RUN_ID": "run-20200101-000000-abcdef", + "IMX_GPU_MUTEX": "0", "CUDA_VISIBLE_DEVICES": "", + "TEST_TIMEOUT_SEC": "10"}.items(): + monkeypatch.setenv(key, value) + seen = {} + + class CapturingRunner: + def __init__(self, **kwargs): + seen["options"] = kwargs + + def run(self, job, env): + seen["job"] = job + return module_pytest.TestOutcome( + rc=0, skipped=True, log_file="", skip_reason="needs 1 GPU(s)") + + monkeypatch.setattr(module_pytest, "TestRunner", CapturingRunner) + # The wrapper keeps the outcome's own rc (its contract); a run that did + # not happen is said on both streams, so no reader takes it for a pass. + assert module_pytest.main(["-vv", "-s", "tests/worker/"]) == 0 + assert seen["job"].gpus == 1 + captured = capsys.readouterr() + for stream in (captured.out, captured.err): + assert "skipped — needs 1 GPU(s)" in stream diff --git a/test/test_provider_zcode.py b/test/test_provider_zcode.py index b9c9276b..4df5c43f 100644 --- a/test/test_provider_zcode.py +++ b/test/test_provider_zcode.py @@ -102,14 +102,14 @@ def _transport(tmp_path: Path, **settings) -> ZCodeTransport: def _request(tmp_path: Path, with_bridge: bool = True, - prompt: str = "PROMPT") -> AgentSessionRequest: + prompt: str = "PROMPT", read_only: bool = True) -> AgentSessionRequest: worktree = tmp_path / "worktree" worktree.mkdir() run_dir = tmp_path / "run" run_dir.mkdir() scope = read_only_scope() scope = type(scope)(name=scope.name, allowed_tools=scope.allowed_tools, - read_only=True, root=str(worktree)) + read_only=read_only, root=str(worktree)) bridge = write_bridge_spec(run_dir=run_dir, step_name="agent.review_diff", scope=scope, repo="vllm-omni") \ if with_bridge else None @@ -125,7 +125,7 @@ def _capture(tmp_path: Path) -> dict: (tmp_path / "bin" / "capture.json").read_text(encoding="utf-8")) -def test_run_session_plan_mode_bridge_and_parse(tmp_path, monkeypatch): +def test_run_session_read_only_guarded_bridge_and_parse(tmp_path, monkeypatch): monkeypatch.setenv("ANTHROPIC_API_KEY", "should-not-leak") transport = _transport(tmp_path) req = _request(tmp_path) @@ -139,11 +139,14 @@ def test_run_session_plan_mode_bridge_and_parse(tmp_path, monkeypatch): capture = _capture(tmp_path) argv = capture["argv"] - assert argv[argv.index("--mode") + 1] == "plan" + # zcode 0.18 asks for every MCP tool in plan mode: a read-only scope that + # needs the bridge runs guarded. + assert argv[argv.index("--mode") + 1] == "guarded" assert argv[argv.index("--output-format") + 1] == "stream-json" denied = next(a for a in argv if a.startswith("--disallowed-tools=")) for tool in ("Bash", "Edit", "Write", "Agent", "WebFetch", - "mcp__node_repl__js"): + "mcp__node_repl__js", "CreateSession", "InterruptSession", + "SendToSession", "ReadSession"): assert tool in denied.split("=", 1)[1].split(",") prompt = next(a for a in argv if a.startswith("--prompt=")) assert "SYS\n\nPROMPT" in prompt and str(req.scope.root) in prompt @@ -166,6 +169,14 @@ def test_run_session_plan_mode_bridge_and_parse(tmp_path, monkeypatch): assert session["served_model"] == "GLM-5.3-Flash" +def test_run_session_mutating_scope_runs_yolo(tmp_path): + transport = _transport(tmp_path) + transport.run_session(_request(tmp_path, read_only=False)) + + argv = _capture(tmp_path)["argv"] + assert argv[argv.index("--mode") + 1] == "yolo" + + def test_bridge_timeout_covers_long_running_module_tools(tmp_path): transport = _transport(tmp_path) req = _request(tmp_path) @@ -451,3 +462,51 @@ def test_known_failure_events_have_typed_safe_recovery_without_raw_text(tmp_path transport.complete(system="PRIVATE_SYSTEM_PROMPT", messages=[]) assert exc.value.code == code and exc.value.retryable is retryable assert "PRIVATE" not in str(exc.value) and "SECRET" not in str(exc.value) + + +def test_workspace_mcp_trust_digest_golden(): + """The pre-seeded trust record's declarationDigest must equal what + zcode 0.17.1 computes over the project-scope server declaration + (golden measured live: echo-tools session, tool-call round-trip).""" + session = Path("/tmp/zcode-trust-test") + server = {"type": "stdio", "timeoutMs": 600000, + "command": "/usr/bin/python3", + "args": ["/tmp/zcode-trust-test/echo_mcp.py"]} + digest = ZCodeTransport._trust_declaration_digest(session, "echo-tools", + server) + assert digest == ("f5f218c5e9d36908b100ef3a0bb57f3be12b19d4" + "fc3f271d5a27e0e82f3ba633") + + +def test_workspace_mcp_trust_seed_is_idempotent_and_prunes_dead_sessions( + tmp_path, monkeypatch): + """One record per (server, digest); sessions whose dir vanished are + pruned so the host-global store cannot grow without bound.""" + monkeypatch.setenv("HOME", str(tmp_path)) + session = tmp_path / "imc-zcode-session-x" + (session / ".zcode").mkdir(parents=True) + server = {"type": "stdio", "timeoutMs": 7200000, "command": "/usr/bin/x", + "args": ["-m", "infermatrix_copilot.tool_bridge"], + "env": {"A": "1"}} + ZCodeTransport._seed_workspace_mcp_trust(session, "infermatrix-tools", + server) + ZCodeTransport._seed_workspace_mcp_trust(session, "infermatrix-tools", + server) + store = json.loads((tmp_path / ".zcode" / "security" + / "workspace-mcp-trust-v1.json").read_text()) + assert store["schemaVersion"] == 1 + assert len(store["records"]) == 1 + rec = store["records"][0] + assert rec["serverName"] == "infermatrix-tools" + assert rec["declarationDigest"] == \ + ZCodeTransport._trust_declaration_digest(session, "infermatrix-tools", + server) + # a dead session's record is pruned on the next seed, others survive + dead = tmp_path / "imc-zcode-session-dead" # never created on disk + ZCodeTransport._seed_workspace_mcp_trust(dead, "infermatrix-tools", server) + store = json.loads((tmp_path / ".zcode" / "security" + / "workspace-mcp-trust-v1.json").read_text()) + names = [(r["serverName"], r["workspaceIdentity"]) + for r in store["records"]] + assert ("infermatrix-tools", str(dead)) not in names + assert ("infermatrix-tools", str(session)) in names diff --git a/test/test_rebase_release_target.py b/test/test_rebase_release_target.py index 079397a6..342a715d 100644 --- a/test/test_rebase_release_target.py +++ b/test/test_rebase_release_target.py @@ -437,3 +437,133 @@ def clone(src, dst): run=run, clone=clone) assert out == tmp_path / ("venv-baseline-" + "a" * 12) assert any("worktree" in c and "remove" in c for c in calls) + + +def test_baseline_venv_installs_with_the_baseline_variant(tmp_path): + """The baseline is the last release the target repo was aligned to, which + can be published under another variant than a main target (vLLM: v0.34.0 + ships cu130 only, main builds cu132): fetch it with the baseline's variant, + and keep `variant` when the adapter declares none.""" + from infermatrix_copilot.rebase_engine.wheel import ensure_baseline_venv + url = "https://example.invalid/{commit}/{variant}/fixture/fix-{arch}.whl" + + def spec(**extra): + return WheelSpec( + package="fixture", variant="cu132", arch="x86_64", + index_url_template="https://example.invalid/{commit}/{variant}/{package}/", + install_env={"VLLM_PRECOMPILED_WHEEL_COMMIT": "{commit}", + "VLLM_PRECOMPILED_WHEEL_VARIANT": "{variant}"}, + install_url_template=url, **extra) + + seen = [] + + def run(cmd, *, cwd=None, env=None, timeout=600.0): + if " ".join(cmd).startswith("uv pip install"): + seen.append((env["VLLM_PRECOMPILED_WHEEL_VARIANT"], cmd[-1])) + return 0, "0.1\n", "" # version mismatch -> build; every probe ok + + def clone(src, dst): + (dst / "bin").mkdir(parents=True) + (dst / "pyvenv.cfg").write_text("home=/usr\n", encoding="utf-8") + return True + + target = tmp_path / "venv" + target.mkdir() + (tmp_path / ".git").mkdir() + assert ensure_baseline_venv(target, spec(baseline_variant="cu130"), tmp_path, + "a" * 40, run=run, clone=clone) + assert ensure_baseline_venv(target, spec(), tmp_path, "b" * 40, + run=run, clone=clone) + assert seen == [("cu130", url.format(commit="a" * 40, variant="cu130", + arch="x86_64")), + ("cu132", url.format(commit="b" * 40, variant="cu132", + arch="x86_64"))] + + +def test_hardlinked_baseline_launchers_use_clone_without_modifying_target(tmp_path): + import venv + + from infermatrix_copilot.rebase_engine.wheel import _clone_tree_hardlinked, _relocate_venv_scripts + + target, baseline = tmp_path / "venv", tmp_path / "venv-baseline" + venv.EnvBuilder(with_pip=False).create(target) + launcher = target / "bin" / "runtime-probe" + original = f"#!{target}/bin/python\nimport sys\nprint(sys.prefix)\n" + launcher.write_text(original) + launcher.chmod(0o755) + assert _clone_tree_hardlinked(target, baseline) + _relocate_venv_scripts(target, baseline) # Cached reuse must be idempotent. + result = subprocess.run([str(baseline / "bin" / launcher.name)], + capture_output=True, text=True, check=True) + assert result.stdout.strip() == str(baseline) + assert launcher.read_text() == original + assert str(target) in (target / "bin" / "activate").read_text() + assert str(baseline) in (baseline / "bin" / "activate").read_text() + + +def test_baseline_package_survives_temporary_source_removal(tmp_path): + import shutil + import venv + + from infermatrix_copilot.rebase_engine import wheel + + target = tmp_path / "target" + venv.EnvBuilder(with_pip=False).create(target) + (tmp_path / ".git").mkdir() + + def run(cmd, *, cwd=None, env=None, timeout=600): + if cmd[0] == "git": + source = tmp_path / ("target-baseline-" + "a" * 12 + "-src") + if "add" in cmd: + (source / "fixture").mkdir(parents=True) + (source / "fixture" / "__init__.py").write_text("VALUE = 'baseline'\n") + else: + shutil.rmtree(source) + return 0, "", "" + if cmd[:3] == ["fixture-uv", "pip", "uninstall"]: + return 0, "", "" + if cmd[:3] == ["fixture-uv", "pip", "install"]: + python = cmd[cmd.index("--python") + 1] + site = subprocess.check_output( + [python, "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], + text=True).strip() + # Simulate editable/non-editable installation without network or a + # build backend. The former becomes unimportable after git cleanup. + from pathlib import Path + if "-e" in cmd: + (Path(site) / "fixture.pth").write_text(str(cwd) + "\n") + else: + shutil.copytree(cwd / "fixture", Path(site) / "fixture") + return 0, "", "" + return wheel._run(cmd, cwd=cwd, env=env, timeout=timeout) + + spec = WheelSpec(package="fixture", variant="cpu", arch="x86_64", + index_url_template="https://example.invalid/{commit}") + baseline = wheel.ensure_baseline_venv(target, spec, tmp_path, "a" * 40, + uv="fixture-uv", run=run) + assert baseline is not None + assert not (tmp_path / (baseline.name + "-src")).exists() + result = subprocess.run([str(baseline / "bin/python"), "-c", + "import fixture; print(fixture.VALUE)"], + cwd=tmp_path, capture_output=True, text=True, check=True) + assert result.stdout.strip() == "baseline" + + +def test_cached_baseline_with_matching_metadata_but_missing_code_is_rejected(tmp_path): + from infermatrix_copilot.rebase_engine import wheel + + target = tmp_path / "target" + baseline = tmp_path / ("target-baseline-" + "a" * 12) + baseline.mkdir() + (baseline / "pyvenv.cfg").write_text("home=/usr\n") + (tmp_path / ".git").mkdir() + + def run(cmd, **kwargs): + if len(cmd) > 3 and cmd[-1] == "fixture": + return 0, "1.0+gaaaaaaaaa\n", "" + return 1, "", "missing fixture source" + + result = wheel.ensure_baseline_venv(target, _install_spec(), tmp_path, + "a" * 40, run=run, + clone=lambda src, dst: False) + assert result is None