diff --git a/doc/architecture/SPEC/engine/steps/rebase_v3.md b/doc/architecture/SPEC/engine/steps/rebase_v3.md index 18638823..d7339cd9 100644 --- a/doc/architecture/SPEC/engine/steps/rebase_v3.md +++ b/doc/architecture/SPEC/engine/steps/rebase_v3.md @@ -1,6 +1,6 @@ # engine/steps/rebase_v3.py —— 规范 - + `LOC ~2660 · step 库(v3 rebase 装配层) · refactor-status: oversized` @@ -172,7 +172,9 @@ campaign 改为按命令向调度器取卡之后(`testing` 规范的"按命令 经本文件启动的 GPU 命令各自声明要几张: - `run_pytest`/`reproduce`(`_run_tests`)以 `TestJob(min_gpus=0, gpu_lock=True, - gpus=1)` 运行,向调度器要 1 张卡。返回值新增 `skipped` 与 `skip_reason`; + gpus=None)` 运行:卡数由 `TestRunner` 按 `command_gpus` 从命令及其测试的声明推导, + 至少 1 张(2026-11-26 起"按需要申请",此前固定 1 张)。返回值新增 `skipped` 与 + `skip_reason`; `passed` 只在 `rc == 0 and not skipped` 时为真——调度器没给卡的运行没有通过。 - `run_precommit` 以 `gpus=0` 运行,不申请。 - 两处 `ModuleRunConfig` 的 `cuda_devices` 改取 `testing.gpu_demand.session_devices()`: diff --git a/doc/architecture/SPEC/rebase_engine.md b/doc/architecture/SPEC/rebase_engine.md index b5f93706..5bbe62e8 100644 --- a/doc/architecture/SPEC/rebase_engine.md +++ b/doc/architecture/SPEC/rebase_engine.md @@ -1,6 +1,6 @@ # rebase_engine/ —— 规范 - + `LOC ~9530(30 个模块) · repo-rebase-v3 的原生 rebase 引擎 · refactor-status: ok` @@ -269,14 +269,17 @@ campaign 不再从头到尾持有一份外层预约,每条 GPU 命令向调度 `_run_shell`(原有的 Popen、后代快照与超时逻辑未变)。按需模式(读本进程环境的 `IMX_GPU_MODE`)下,它把模式写进子进程环境,使命令启动的 `imx-omni-pytest` 自己去申请;`testing.gpu_demand.shell_needs_gpu` 判定会起测试或 CUDA 代码的命令, - 用 `scheduler_wrap` 向调度器要 1 张卡(等待上限是工具超时的一半),并给子进程设 + 用 `scheduler_wrap` 向调度器要卡,张数取 `command_gpus(command, 1, root)`—— + 命令的实际 cwd,缺省是目标仓库;至少 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(既有契约,由 +- **`module_pytest.py`。** 包装器的 `TestJob` 带 + `gpus=command_gpus(command, 1, root=repo, maximum=…)`:以它所选测试声明的需要 + 为准(`testing` 规范的"卡数 = 需要"),至少 1 张——测试可能用到卡,如同它过去在 + 外层预约下运行时那样。包装器仍返回结果自己的 rc(既有契约,由 `test_module_pytest_outcomes.py` 钉住),所以跳过时把 `imx-omni-pytest: skipped — <原因>` 同时写到 stdout 和 stderr。 - **提示词。** `build_module_prompt(..., cuda_devices=prompt_devices(config.cuda_devices))`: @@ -295,3 +298,9 @@ campaign 不再从头到尾持有一份外层预约,每条 GPU 命令向调度 final 只有 `cu130`。按目标的 variant 去取,测试循环用来区分既有失败与回归的基线 运行时就建不出来,退回到让基线也跑在 campaign 的 venv 上。vllm-omni adapter 把 `baseline_variant` 设为 `cu130`。测试:`test_rebase_release_target.py`。 + +2026-11-26:负责人定了"一直等到有卡、按需要申请、不做 reserve"。两处的卡数从固定 +1 张改为按需要推导:此前模块测试只申请 1 张,而外层预约时代每个模块的测试都看得到 +4 张卡,需要多张卡的测试因此失败(`tests/diffusion/models/hy_nomas/ +test_pixelumm_parallel.py`)。等待不再有缺省上限(`run_shell` 里同步起的测试除外, +见 `testing` 规范)。 diff --git a/doc/architecture/SPEC/testing.md b/doc/architecture/SPEC/testing.md index 6473e79a..95253054 100644 --- a/doc/architecture/SPEC/testing.md +++ b/doc/architecture/SPEC/testing.md @@ -1,8 +1,8 @@ # testing/ —— 规范 - + -`LOC ~2190(9 个文件) · 测试执行底座(rebase agent shell 测试层的 Python 移植) · refactor-status: ok` +`LOC ~2450(9 个文件) · 测试执行底座(rebase agent shell 测试层的 Python 移植) · refactor-status: ok` ## 职责 仓库中立的测试执行底座:gpu_lock.sh / kill_test_tree.sh / test_watchdog.sh / @@ -42,8 +42,8 @@ test_runner.sh 的 Python 移植。仓库专属数据(watchdog 模式、artifa - `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`。 + `HELD_ENV`、`WAIT_ENV`、`MAX_ENV`、`NO_GPU_RC`、`SCHEDULER_TIMEOUT_MARGIN_SEC`、 + `IDLE_MAX_SEC`、`RUN_LEVEL_OPTION`、`RUN_LEVELS`、`DEFAULT_RUN_LEVEL`。 - `watchdog`:`WatchdogPatterns(.from_yaml)`、`LogWatchdog(.start/.stop/.check_once/.result)`、`WatchdogResult`。 - `watchdog_learn`:`record`、`harvest`、`eligible_patterns`、`promote`、 `read_decisions`、`normalize_pattern`、`repair_tail`。 @@ -96,10 +96,11 @@ 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 身份字段、撕尾修复)钉住。`test_gpu_demand.py`(64 个)以一个替身 `gpu` -可执行文件覆盖按需模式:卡数、shell 命令的判定、包装程序的输出路由与等待到期、 -空闲回收的单位与上限、调度器拒绝请求时的日志行、`TestRunner` 的 skip,以及 agent -shell 与模块测试包装器。 +(record 身份字段、撕尾修复)钉住。`test_gpu_demand.py`(74 个)以一个替身 `gpu` +可执行文件覆盖按需模式:卡数(含测试声明的读取与上限)、shell 命令的判定、 +包装程序的输出路由、不限等待与有界等待到期、给卡后才计时、锁仍有界、 +空闲回收的单位与上限、调度器拒绝请求时的日志行、`TestRunner` 的 skip,以及 +agent shell 与模块测试包装器。 ## 重构备注 `runner.py`(643L)是包内最重的一块:`_spawn` 把快照线程、双定时器、watchdog @@ -127,19 +128,29 @@ GPU 锁下一次只跑一个,52 个只用 1 张卡。负责人决定:不再 campaign,改为每条 GPU 命令向调度器申请自己需要的卡、只在运行期间持有。 - **开关。** `IMX_GPU_MODE=demand` 选择按需模式;未设置时行为不变(调用方已 - 持有卡,命令继承)。`IMX_GPU_WAIT`(缺省 `30m`)是命令在调度器队列里的等待 + 持有卡,命令继承)。`IMX_GPU_WAIT` 给命令在调度器队列里的等待设上限;不设则 + 一直等到拿到卡(2026-11-26 起,见下文)。`IMX_GPU_MAX` 是一条命令申请卡数的 上限。`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 张。 +- **卡数 = 需要。** `TestJob.gpus` 显式给出;否则 `command_gpus(command, minimum, + root, maximum)`:命令自己的 `-m` 表达式选中的 `cards_N` 以其中最大者为准 + (manifest 的每个 job 都是 `hw: any`,卡数只在 marker 里);被 `not` 否定的是 + **排除**,不是需要——目标仓库自己的 CPU job 写的就是 + `core_model and cpu and not (cards_2 or … or cards_8)`。没有选中任何 `cards_N` + 时读取命令所指定的测试文件,取其中**与命令同属一个运行级别**(`--run-level`, + 缺省 `core_model`)的测试所声明的最大卡数——`cards_N` 标记,或装饰器的 + `num_cards=`。其它级别的、以及被表达式排除的卡数的测试不计:卡不够时它们按 + 自己的保护跳过,不会失败。没有声明算 1 张。 + 结果不低于 `minimum`(取 GPU 锁的运行至少 1 张,`run_precommit` 为 0、不申请), + 不高于 `maximum`。agent 的 `run_pytest`/`reproduce`、`imx-<仓库>-pytest` 包装器 + 与 agent 在 shell 里起的测试走同一套算法。 - **包装程序。** `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),其余失败保留调度器的退出码。调度器的超时设为 + stdout、把 `Error: wait timeout exceeded` 打到 stderr,有界等待到期时退出码为 1; + 包装程序把它换成 `NO_GPU_RC`(97),其余失败保留调度器的退出码。`wait` 为空时 + 不传 `--wait`,调度器一直排队。调度器的超时设为 `timeout_sec + SCHEDULER_TIMEOUT_MARGIN_SEC`(秒),让运行器自己的定时器先触发。 空闲回收由 `idle_timeout()` 给出:同一个时长向上取整到**单一单位**(秒、分或小时), 且不超过 `IDLE_MAX_SEC`(3 小时)。实测(2026-11-25)调度器只解析单一单位的空闲 @@ -153,9 +164,10 @@ campaign,改为每条 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 起算,排队时间也在内。 +- **有界等待到期是一次显式 skip**(只在设了 `IMX_GPU_WAIT` 时)。`TestRunner.run` + 返回 `rc=0, skipped=True`,`skip_reason` 写明要几张、等了多久;命令没有运行, + 也不写 pass marker。上限不超过 `timeout_sec` 的一半:那时运行器的定时器从 + spawn 起算,排队时间也在内。 - **按需模式下由调度器决定有没有卡**:不做硬件门槛,丢掉继承的 `CUDA_VISIBLE_DEVICES`(调度器授权时自己命名),并给子进程设 `IMX_GPU_HELD=1`。 - **命令结束后不在已释放的卡上清理进程。** 外层预约时代 @@ -178,3 +190,45 @@ campaign,改为每条 GPU 命令向调度器申请自己需要的卡、只在 实测(2026-11-25):一条 `TestRunner` 命令在真实调度器下恰好持有 1 张卡 35 秒, 前后都是 0;torch 看到 1 张卡;import vllm 及其编译扩展不建立 CUDA 上下文。 + +## 一直等到有卡、按需要申请(2026-11-26) + +负责人在 2026-11-26 定了三条:排不到卡就一直等,不放弃也不跳过;不指定要哪几张 +卡,申请的数量与需要的一致;不做任何 reserve,只走调度器的队列。 + +- **一直等。** `IMX_GPU_WAIT` 不再设缺省值:`gpu run` 不带 `--wait`。运行器的 + 定时器与看门狗改为在调度器给卡之后才启动——`_await_grant` 每秒读一次旁路文件, + 直到出现 `Reserved …` 或进程退出。排队时间因此不计入测试的超时;此前定时器从 + spawn 起算,一条排了两小时的命令会在队列里被自己的超时杀掉。旁路文件在启动前 + 清空:上一次运行留下的给卡记录不能让这一次的等待提前结束。日志里写两行: + `[gpu] queued for the scheduler's cards at …` 与 `[gpu] granted after N s in the + queue: [..]`——空了几小时的日志在读的人看来是挂死。调度器**拒绝**请求不是等待: + 进程退出,日志照旧写 `not run`。GPU 锁保持它一小时的有界等待,没有跟着放开: + 持锁的那个运行自己可能在队列里排几个小时,后面等锁的若不设上限,agent 的会话 + 就会无声地卡住;锁超时是它能据以行动的反馈。"一直等"说的是卡,锁是自己的串行。 +- **按需要。** 模块测试此前固定申请 1 张,而以前外层预约时代每个模块的测试都能 + 看到 4 张卡:`tests/diffusion/models/hy_nomas/test_pixelumm_parallel.py` 按 + 2、4 个进程 `mp.spawn`,没有 `cards_N` 标记也没有保护,1 张卡下必然失败。 + 卡数于是改为读测试自己的声明:`command_gpus` 的规则见上文"卡数 = 需要"。读取 + 用 AST,不认字符串里的名字——目标仓库自己的测试会引用写着 `cards_8` 的 CI 命令。 + 只扫仓库根目录之内、路径名以 `test` 开头的目录,至多 4000 个文件;命令里出现的 + 别的目录一律不碰(一个以 `/` 为根的测试里,命令说了 `cd /tmp`)。结果缓存 5 分钟: + agent 一边工作一边改测试。 +- **上限。** `tests/e2e --run-level advanced_model` 声明的需求是 8 张,也就是整台 + 机器;配上"一直等",这样一条命令可能永远排不上。`IMX_GPU_MAX` 封顶,launcher + 里取 4——以往每个 campaign 的配置,也是 `core_model` 级别上声明的最大需求。 + 超出部分的测试按它们自己的保护跳过,和以前只看得到 4 张卡时一样。 +- **仍然有界的一处。** agent 在 `run_shell` 里同步起的测试,等待不超过该次工具 + 调用超时的一半:工具调用的期限是 harness 定的,超了它等不下去;到期时返回 + `gpu_unavailable`,提示词本就要求长验证走包装器的分离运行。 + +实测(2026-11-25/26):`tests/` 全树在 `core_model` 级别上声明 1 张的 196 个文件、 +2 张的 14 个、4 张的 6 个;按模块,worker_runner / input_output / online_serving / +model_config 需要 1 张(后者无声明),model_executor / scheduler / platform 的 +全量运行需要 4 张。AST 解析全树约 6 秒,单个模块目录 1–2 秒。 + +2026-11-26,实机上发现并补上:`-m` 表达式里被 `not` 否定的 `cards_N` 曾被当成需要 +——卡数是对整条命令做正则取最大值。campaign 自己的 agent 跑 +`tests/distributed/ -m 'core_model and cuda and L4 and not cards_2'` 时因此申请了 +两张卡,而 manifest 里 CPU job 的排除表达式会申请八张。现在按表达式解析 +(`_expression_cards`):`not` 作用于紧随其后的那一项,或一个括号组。 diff --git a/src/infermatrix_copilot/engine/steps/rebase_v3.py b/src/infermatrix_copilot/engine/steps/rebase_v3.py index 6c45079a..2f7dcf6e 100644 --- a/src/infermatrix_copilot/engine/steps/rebase_v3.py +++ b/src/infermatrix_copilot/engine/steps/rebase_v3.py @@ -354,7 +354,8 @@ 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, gpus=1), + # as many cards as the command's tests declare, one at least + min_gpus=0, gpu_lock=True, gpus=None), _target_test_env(settings, manifest, host_env=host_env)) tail = "" try: diff --git a/src/infermatrix_copilot/rebase_engine/module_pytest.py b/src/infermatrix_copilot/rebase_engine/module_pytest.py index 6d6c3aa3..aa6d9c1e 100644 --- a/src/infermatrix_copilot/rebase_engine/module_pytest.py +++ b/src/infermatrix_copilot/rebase_engine/module_pytest.py @@ -54,6 +54,7 @@ import time from pathlib import Path +from ..testing.gpu_demand import GpuDemand, command_gpus from ..testing.runner import TestJob, TestOutcome, TestRunner from ..testing.watchdog import WatchdogPatterns @@ -459,9 +460,11 @@ def review_fn(test_name: str, snippet: str) -> str: # 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, - # the tests may use a card, as they could under the + # as many cards as the tests it runs declare, and one at + # least: they may use a card, as they could under the # campaign-wide reservation this wrapper used to run in - gpus=1) + gpus=command_gpus(command, 1, root=repo, + maximum=GpuDemand.from_env().maximum)) if process_setup: process.install_signal_handlers(runner) outcome = runner.run(job, dict(os.environ)) diff --git a/src/infermatrix_copilot/rebase_engine/rebase_tools.py b/src/infermatrix_copilot/rebase_engine/rebase_tools.py index c979c6e0..a2c01b27 100644 --- a/src/infermatrix_copilot/rebase_engine/rebase_tools.py +++ b/src/infermatrix_copilot/rebase_engine/rebase_tools.py @@ -181,11 +181,13 @@ def handle_run_shell(command: str, workdir: str | None = None, import tempfile from ..testing.gpu_demand import ( - HELD_ENV, MODE_ENV, NO_GPU_RC, GpuDemand, scheduler_error, - scheduler_wrap, shell_needs_gpu) + HELD_ENV, MODE_ENV, NO_GPU_RC, GpuDemand, command_gpus, + scheduler_error, scheduler_wrap, shell_needs_gpu) env, side_log, wait = (dict(paths.env) or None), None, "" - if GpuDemand.from_env(os.environ).enabled: + root = workdir or paths.omni_path # where the command runs + demand = GpuDemand.from_env(os.environ) + if demand.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. @@ -201,10 +203,12 @@ def handle_run_shell(command: str, workdir: str | None = None, 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, + command, gpus=command_gpus(command, 1, root=root, + maximum=demand.maximum), + 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) + result = _run_shell(command, root, timeout, env) finally: scheduler = scheduler_error(side_log) if side_log else "" if side_log: @@ -225,7 +229,7 @@ def _run_shell(command: str, workdir: str | None, timeout: int, from ..testing.process_tree import collect_descendants, kill_tree from ..testing.runner import TestRunner, _record_walk - cwd = workdir or paths.omni_path + cwd = workdir # resolved by the caller try: with subprocess.Popen( # Match TestRunner's runtime protection: inherited SSH diff --git a/src/infermatrix_copilot/testing/gpu_demand.py b/src/infermatrix_copilot/testing/gpu_demand.py index b549898b..0e33cb0d 100644 --- a/src/infermatrix_copilot/testing/gpu_demand.py +++ b/src/infermatrix_copilot/testing/gpu_demand.py @@ -9,8 +9,14 @@ 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. + IMX_GPU_WAIT=30m bounds the time a command waits in the scheduler's + queue before it is reported as not run. Unset, it + waits until the cards are granted (owner decision, + 2026-11-26: nothing gives up on cards). + +How many cards a command asks for is what it needs (the same decision: never +which cards, only how many): `command_gpus`. `IMX_GPU_MAX` caps it; a test that +declares more skips by its own guard, as it did whenever fewer cards were visible. 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 @@ -23,9 +29,11 @@ """ from __future__ import annotations +import ast import os import re import shlex +import time from dataclasses import dataclass from pathlib import Path from typing import Mapping @@ -33,7 +41,9 @@ MODE_ENV = "IMX_GPU_MODE" HELD_ENV = "IMX_GPU_HELD" WAIT_ENV = "IMX_GPU_WAIT" -DEFAULT_WAIT = "30m" +MAX_ENV = "IMX_GPU_MAX" +#: No bound: a command waits in the scheduler's queue until it gets its cards. +DEFAULT_WAIT = "" #: 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 @@ -42,6 +52,14 @@ IDLE_MAX_SEC = 3 * 3600 #: The wrapper's own status for "the scheduler granted no cards in time". NO_GPU_RC = 97 +#: The run level a test command selects, and the levels there are. A test of +#: another level skips by its own guard when the cards are not there. +RUN_LEVEL_OPTION = "--run-level" +RUN_LEVELS = ("core_model", "advanced_model", "full_model") +DEFAULT_RUN_LEVEL = "core_model" +#: A declared need is read from the test files' source; agents edit tests while +#: they work, so it is kept only briefly. +_NEED_TTL_SEC = 300.0 _CARDS = re.compile(r"\bcards_(\d{1,2})\b") _WAIT_EXPIRED = "wait timeout exceeded" @@ -74,16 +92,22 @@ @dataclass(frozen=True) class GpuDemand: - """Whether to ask the scheduler per command, and how long to wait for it.""" + """Whether to ask the scheduler per command, how long to wait for it, and + the most cards one command asks for.""" enabled: bool = False wait: str = DEFAULT_WAIT + maximum: int | None = None @classmethod def from_env(cls, env: Mapping[str, str] | None = None) -> "GpuDemand": env = os.environ if env is None else env + try: + maximum = int(env.get(MAX_ENV, "") or 0) or None + except ValueError: + maximum = None return cls(enabled=env.get(MODE_ENV, "") == "demand" and not env.get(HELD_ENV), - wait=env.get(WAIT_ENV) or DEFAULT_WAIT) + wait=(env.get(WAIT_ENV) or "").strip(), maximum=maximum) def duration_seconds(text: str, default: float = 0.0) -> float: @@ -95,11 +119,218 @@ def duration_seconds(text: str, default: float = 0.0) -> float: 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 command_gpus(command: str, minimum: int = 0, + root: Path | str | None = None, + maximum: int | None = None) -> int: + """The cards one test command needs. + + A `cards_N` that the command's `-m` expression selects is the selection + itself (every job of the manifest says `hw: any`): its largest. One the + expression negates (`not cards_2`) is an exclusion, not a need: the + repository's own jobs say `core_model and cpu and not (cards_2 or ... or + cards_8)`. Otherwise, and given the `root` the command runs in, the tests + it names are read: the largest number of cards that a test of the command's + run level declares in those files, with a `cards_N` mark or with a + decorator's `num_cards=`. Tests of other levels and of excluded counts do + not count: they skip by their own guard when the cards are not there. A + test that declares nothing needs one (`minimum`). `maximum` caps what the + command and its tests say, never the caller's `minimum`. + """ + command = command or "" + selected, excluded = _expression_cards(_option(_words(command), "-m") or "") + if selected or root is None: + return max(minimum, _capped(max(selected, default=0), maximum)) + level = _run_level(command) + key = (str(root), tuple(_test_paths(command, Path(root))), level, tuple(excluded)) + now = time.monotonic() + hit = _NEEDS.get(key) + if hit is None or hit[0] < now: + need = max([_file_need(path, level, excluded) for path in key[1]] or [0]) + for stale in [k for k, v in _NEEDS.items() if v[0] < now]: + del _NEEDS[stale] + _NEEDS[key] = hit = (now + _NEED_TTL_SEC, need) + return max(minimum, _capped(hit[1], maximum)) + + +def _capped(need: int, maximum: int | None) -> int: + return min(need, maximum) if maximum and need else need + + +_NEEDS: dict[tuple, tuple[float, int]] = {} + + +def _words(command: str) -> list[str]: + try: + return shlex.split(command, posix=True) + except ValueError: # an unclosed quote + return command.split() + + +_TOKEN = re.compile(r"\(|\)|\bnot\b|[A-Za-z_][\w.]*") + + +def _expression_cards(expression: str) -> tuple[set[int], set[int]]: + """What a `-m` expression says about cards: the counts it selects and the + counts it negates. `not` applies to the one term that follows it, or to a + bracketed group.""" + selected: set[int] = set() + excluded: set[int] = set() + negated = [False] # per bracket level + after_not = False + for token in _TOKEN.findall(expression): + if token == "not": + after_not = True + elif token == "(": + negated.append(after_not or negated[-1]) + after_not = False + elif token == ")": + if len(negated) > 1: + negated.pop() + after_not = False + else: + if _CARDS.fullmatch(token) and 1 <= int(token[6:]) <= 16: + (excluded if after_not or negated[-1] else selected).add(int(token[6:])) + after_not = False + return selected, excluded + + +def _option(words: list[str], name: str) -> str | None: + for index, word in enumerate(words): + if word == name and index + 1 < len(words): + return words[index + 1] + if word.startswith(name + "="): + return word.split("=", 1)[1] + return None + + +def _run_level(command: str) -> str: + """What a test command selects: its `--run-level`, else the one level its + `-m` expression names, else the default.""" + words = _words(command) + level = _option(words, RUN_LEVEL_OPTION) + if level: + return level + expression = _option(words, "-m") or "" + named = [name for name in RUN_LEVELS if re.search(rf"\b{name}\b", expression)] + return named[0] if len(named) == 1 else DEFAULT_RUN_LEVEL + + +def _test_paths(command: str, root: Path) -> list[Path]: + """The test files a command names: a file itself, or the test files under + a directory it names that lies inside `root`, below it, and is named like + a test directory (`tests`, `testing`, `test_*`). A node id counts as its + file. Nothing else is walked: a command may say `cd /tmp`.""" + out: list[Path] = [] + for word in _words(command): + if word.startswith("-"): + continue + path = root / re.split(r"::|\[", word, maxsplit=1)[0] + try: + inside = path.resolve().is_relative_to(root.resolve()) and path.resolve() != root.resolve() + except OSError: + continue + if not inside: + continue + if path.is_file() and path.suffix == ".py": + out.append(path) + elif path.is_dir() and any(part.startswith("test") + for part in path.relative_to(root).parts): + out.extend(_test_files(path)) + return out + + +#: Never read more test files than this for one command, nor walk these. +_MAX_TEST_FILES = 4000 +_SKIP_DIRS = {".git", ".hg", ".venv", "venv", "node_modules", "__pycache__", ".tox", "build"} + + +def _test_files(directory: Path) -> list[Path]: + out: list[Path] = [] + for here, dirs, files in os.walk(directory): + dirs[:] = sorted(d for d in dirs if d not in _SKIP_DIRS and not d.startswith(".")) + for name in sorted(files): + if (name.startswith("test_") or name.endswith("_test.py")) and name.endswith(".py"): + out.append(Path(here) / name) + if len(out) >= _MAX_TEST_FILES: + return out + return out + + +def _file_need(path: Path, level: str, excluded: frozenset[int] = frozenset()) -> int: + """The largest number of cards that a test of `level` in one test file + declares, other than the counts a command excludes. Read from the source: names inside strings are not needs (the + repository's own tests quote CI commands that say `cards_8`).""" + try: + tree = ast.parse(path.read_text(encoding="utf-8", errors="replace")) + except (OSError, ValueError, SyntaxError, RecursionError): + return 0 + need = 0 + module_marks = _pytestmark(tree) + for fn, inherited in _tests(tree, module_marks): + declared = _test_need(fn, inherited, level) + if declared not in excluded: + need = max(need, declared) + return need + + +def _tests(tree: ast.Module, module_marks: list[str]): + """Every test function of one file with the marks it inherits.""" + for node in tree.body: + if isinstance(node, ast.ClassDef): + own = module_marks + _pytestmark(node) + for fn in node.body: + if isinstance(fn, ast.FunctionDef): + yield fn, own + elif isinstance(node, ast.FunctionDef): + yield node, module_marks + + +def _pytestmark(scope: ast.Module | ast.ClassDef) -> list[str]: + """The marks a module or a class applies through `pytestmark`.""" + return [name for stmt in scope.body + if isinstance(stmt, ast.Assign) and any( + isinstance(target, ast.Name) and target.id == "pytestmark" + for target in stmt.targets) + for name in _mark_names(stmt.value)] + + +def _mark_names(node: ast.expr) -> list[str]: + """`pytest.mark.cards_2` is `cards_2`; a list of marks is each of them; a + mark called with arguments is the mark's own name.""" + if isinstance(node, (ast.List, ast.Tuple)): + return [name for item in node.elts for name in _mark_names(item)] + if isinstance(node, ast.Call): + return _mark_names(node.func) + if isinstance(node, ast.Attribute): + return [node.attr] + return [] + + +def _test_need(fn: ast.FunctionDef, inherited: list[str], level: str) -> int: + own = [name for d in fn.decorator_list for name in _mark_names(d)] + if not fn.name.startswith("test") or level not in inherited + own: + return 0 + need = max((int(name[6:]) for name in inherited + own if _CARDS.fullmatch(name)), + default=0) + for decorator in fn.decorator_list: + if isinstance(decorator, ast.Call): + for keyword in decorator.keywords: + if keyword.arg == "num_cards": + need = max(need, _num_cards(keyword.value)) + return need + + +def _num_cards(node: ast.expr) -> int: + """A decorator's `num_cards=`: one number for every platform, or the one + for CUDA.""" + if isinstance(node, ast.Constant) and type(node.value) is int: + return node.value + if isinstance(node, ast.Dict): + for key, value in zip(node.keys, node.values): + if (isinstance(key, ast.Constant) and key.value == "cuda" + and isinstance(value, ast.Constant) and type(value.value) is int): + return value.value + return 0 def shell_needs_gpu(command: str) -> bool: @@ -164,8 +395,9 @@ def scheduler_wrap(command: str, *, gpus: int, timeout_sec: float, wait: 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.""" + the command's status once the cards were granted, with NO_GPU_RC when a + bounded `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", @@ -173,7 +405,9 @@ def scheduler_wrap(command: str, *, gpus: int, timeout_sec: float, wait: str, # 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, "--", + # no bound: the scheduler queues the command until it gets its cards + *(["--wait", wait] if wait else []), + "--note", note, "--", "bash", "--norc", "-c", "exec >&3 2>&4\n" + command]) side = shlex.quote(str(side_log)) return "\n".join([ diff --git a/src/infermatrix_copilot/testing/runner.py b/src/infermatrix_copilot/testing/runner.py index 278b7187..e4138719 100644 --- a/src/infermatrix_copilot/testing/runner.py +++ b/src/infermatrix_copilot/testing/runner.py @@ -22,6 +22,7 @@ import signal import subprocess import threading +import time from dataclasses import dataclass, field from pathlib import Path from typing import Callable @@ -359,6 +360,9 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, 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) + # unbounded queue wait: the command's timers start when the scheduler + # grants its cards, so time in the queue is not time off the test + queue = side_log if gpus and self._waits_for_cards() else None plan = RunPlan( argv=["bash", "--norc", "-c", self._command(job, job.command, side_log)], @@ -432,6 +436,9 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, # before touching the GPU and the fallback does the real workload. lock: GpuLock | None = None if plan.needs_gpu_lock and self.gpu_lock_dir is not None: + # the lock keeps its bounded wait: a run holding it may sit in the + # scheduler's queue for hours, and a silent wait behind it would + # stall the agent's session; a lock timeout is feedback it can act on lock = GpuLock(self.gpu_lock_dir).acquire() try: # append: backup_prev_log already truncated this attempt's log, @@ -443,12 +450,12 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, primary_offset = 0 rc, wd_hit, timed_out = self._spawn( self._command(job, job.command, side_log), job, run_env, - log_file, append=True) + log_file, append=True, queue=queue) 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. + # A bounded wait (IMX_GPU_WAIT) expired. 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 " @@ -495,6 +502,28 @@ def run(self, job: TestJob, env: dict[str, str], *, baseline: bool = False, timed_out=timed_out, log_file=str(log_file), plan=plan) + def _await_grant(self, proc: subprocess.Popen, side_log: Path, + log_file: Path, stop: threading.Event) -> None: + """Wait, for as long as it takes, for the scheduler to grant the cards + (owner decision, 2026-11-26: nothing gives up on cards). The attempt's + timers and watchdog start after this. The log says the command is + queued: an empty log for hours reads as a hang to whoever polls it.""" + queued = time.time() + with open(log_file, "a", encoding="utf-8") as lf: + lf.write(f"\n[gpu] queued for the scheduler's cards at " + f"{time.strftime('%H:%M:%S', time.localtime(queued))}; " + "the test's own timeout starts when they are granted.\n") + granted: list[str] = [] + while proc.poll() is None and not granted: + granted = granted_gpus(side_log) + if not granted: + stop.wait(1.0) + granted = granted or granted_gpus(side_log) # it may have run and gone + if granted: + with open(log_file, "a", encoding="utf-8") as lf: + lf.write(f"[gpu] granted after {int(time.time() - queued)} s in the queue: " + f"[{' '.join(granted)}]\n") + # -- cards on demand ------------------------------------------------------ def _job_gpus(self, job: TestJob) -> int: """What one job asks the scheduler for (TestJob.gpus).""" @@ -503,11 +532,20 @@ def _job_gpus(self, job: TestJob) -> int: 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)) + max(job.min_gpus, 1 if takes_gpu else 0), + root=self.repo_root, maximum=self.gpu_demand.maximum) + + def _waits_for_cards(self) -> bool: + """Demand mode with no bound on the queue: a command waits for its + cards until it gets them.""" + return self.gpu_demand.enabled and not self.gpu_demand.wait 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.""" + """The queue wait as the scheduler takes it: "" when nothing bounds + it. A bound is capped at half of the job's timeout, because the + runner's own timer starts at the spawn then.""" + if not self.gpu_demand.wait: + return "" seconds = min(duration_seconds(self.gpu_demand.wait, 1800.0), job.timeout_sec / 2) return f"{max(int(seconds), 1)}s" @@ -599,7 +637,8 @@ def _run_setup(self, job: TestJob, env: dict[str, str], pass def _spawn(self, exec_cmd: str, job: TestJob, env: dict[str, str], - log_file: Path, *, append: bool) -> tuple[int, bool, bool]: + log_file: Path, *, append: bool, + queue: Path | None = None) -> tuple[int, bool, bool]: timed_out = threading.Event() # scope this attempt's watchdog to bytes IT produces — setup output # and previous-attempt tails are not this attempt's evidence @@ -607,6 +646,10 @@ def _spawn(self, exec_cmd: str, job: TestJob, env: dict[str, str], attempt_offset = log_file.stat().st_size if append else 0 except OSError: attempt_offset = 0 + if queue is not None: + # the side log is reused between attempts: a grant recorded by the + # previous one would end this attempt's wait before it began + queue.write_text("") with open(log_file, "a" if append else "w", encoding="utf-8") as lf: # Bash can source ~/.bashrc for a noninteractive SSH-launched # shell at SHLVL=0. That can put a foreign CLI ahead of the @@ -671,28 +714,37 @@ def _kill_snapshot(): self._active_kill = _kill_snapshot watchdog = None - if self.patterns is not None: - watchdog = LogWatchdog( - self.patterns, log_file, proc.pid, job.key, - check_interval=self.watchdog_interval, - review_fn=self.review_fn, record_fn=self.record_fn, - report_fn=self.report_fn, start_offset=attempt_offset, - kill_fn=lambda pid: _kill_snapshot()).start() - - def primary(): - timed_out.set() - _snapshot() # leader still alive here: refresh before killing - self._terminate_tree(proc.pid, pgid, snapshot=tree["idmap"]) + timers: list[threading.Timer] = [] + try: + if queue is not None: + self._await_grant(proc, queue, log_file, stop_snap) + # the queue lines are the runner's, not this attempt's evidence + try: + attempt_offset = log_file.stat().st_size + except OSError: + pass + if self.patterns is not None: + watchdog = LogWatchdog( + self.patterns, log_file, proc.pid, job.key, + check_interval=self.watchdog_interval, + review_fn=self.review_fn, record_fn=self.record_fn, + report_fn=self.report_fn, start_offset=attempt_offset, + kill_fn=lambda pid: _kill_snapshot()).start() + + def primary(): + timed_out.set() + _snapshot() # leader still alive here: refresh before killing + self._terminate_tree(proc.pid, pgid, snapshot=tree["idmap"]) - def safety(): # only matters if the primary path wedged - _kill_group(pgid, signal.SIGKILL) + def safety(): # only matters if the primary path wedged + _kill_group(pgid, signal.SIGKILL) - t_primary = threading.Timer(job.timeout_sec, primary) - t_safety = threading.Timer(job.timeout_sec + PY_TIMEOUT_MARGIN_SEC, - safety) - t_primary.start() - t_safety.start() - try: + t_primary = threading.Timer(job.timeout_sec, primary) + t_safety = threading.Timer( + job.timeout_sec + PY_TIMEOUT_MARGIN_SEC, safety) + timers = [t_primary, t_safety] + t_primary.start() + t_safety.start() try: rc = proc.wait() except BaseException: @@ -702,6 +754,12 @@ def safety(): # only matters if the primary path wedged _snapshot() self._terminate_tree(proc.pid, pgid, snapshot=tree["idmap"]) raise + except BaseException: + # unwound before the wait above, while still queued for cards: + # the same rule — the tree must not outlive it + _snapshot() + self._terminate_tree(proc.pid, pgid, snapshot=tree["idmap"]) + raise finally: with self._active_lock: self._active_kill = None @@ -710,10 +768,10 @@ def safety(): # only matters if the primary path wedged # cancel then JOIN: a fired primary timer is mid-escalation in # its own thread — returning before it finishes would let the # next job start while own-pgroup descendants still hold GPUs - t_primary.cancel() - t_safety.cancel() - t_primary.join() - t_safety.join() + for timer in timers: + timer.cancel() + for timer in timers: + timer.join() if watchdog is not None: watchdog.stop() # final scan: a job shorter than the poll interval (or a diff --git a/test/test_gpu_demand.py b/test/test_gpu_demand.py index 7cced2b3..3105c2a3 100644 --- a/test/test_gpu_demand.py +++ b/test/test_gpu_demand.py @@ -61,6 +61,10 @@ printf 'Error: wait timeout exceeded\n' >&2 exit 1 fi +if [ -f "$(dirname "$IMX_GPU_STUB_REFUSE")/slow" ]; then + printf 'Waiting for GPUs... (queue position: 2)\n' + sleep "${IMX_GPU_STUB_DELAY:-4}" +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 @@ -69,7 +73,8 @@ _PYTEST_STUB = """#!/bin/sh printf 'STUB-PYTEST cards=%s\\n' "$CUDA_VISIBLE_DEVICES" """ -_DEMAND = GpuDemand(enabled=True, wait="5s") +_DEMAND = GpuDemand(enabled=True, wait="5s") # a bounded wait: the opt-in +_UNBOUNDED = GpuDemand(enabled=True) # the rule since 2026-11-26 _PROBE = ("printf 'hello\\n'\n" "printf 'cards=%s\\n' \"$CUDA_VISIBLE_DEVICES\"\n" "printf 'held=%s\\n' \"$IMX_GPU_HELD\"") @@ -89,7 +94,7 @@ def scheduler(tmp_path, monkeypatch): 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"): + for key in ("IMX_GPU_MODE", "IMX_GPU_HELD", "IMX_GPU_WAIT", "IMX_GPU_MAX"): monkeypatch.delenv(key, raising=False) return env, calls, refuse @@ -113,6 +118,20 @@ def test_command_gpus_is_the_largest_cards_marker(): assert command_gpus("pytest -m cards_99") == 0 # not a card count +@pytest.mark.parametrize("expression, need", [ + ("core_model and (cards_1 or cards_4)", 4), + ("cards_2", 2), + # an exclusion is not a need: the repository's own CPU job says so + ("core_model and cuda and L4 and not cards_2", 0), + ("core_model and cpu and not (cards_2 or cards_3 or cards_8)", 0), + ("full_model and cards_4 and not cards_2", 4), + ("not cards_4 and cards_2", 2), + ("cards_99", 0), # not a card count +]) +def test_a_negated_cards_marker_is_not_a_need(expression, need): + assert command_gpus(f"pytest -m '{expression}'") == need + + @pytest.mark.parametrize("command, needs", [ ("pytest -x tests/a", True), ("python -m pytest tests/a", True), @@ -153,7 +172,8 @@ def test_shell_needs_gpu(command, needs): def test_duration_seconds_reads_the_scheduler_formats(): - assert DEFAULT_WAIT == "30m" and duration_seconds(DEFAULT_WAIT) == 1800 + assert DEFAULT_WAIT == "" # no bound (owner decision, 2026-11-26) + assert duration_seconds("30m") == 1800 assert duration_seconds("2h") == 7200 assert duration_seconds("90s") == 90 assert duration_seconds("1h30m") == 5400 @@ -175,9 +195,14 @@ def test_idle_timeout_is_one_unit_within_the_schedulers_cap(seconds, text): def test_mode_comes_from_the_environment(monkeypatch): - assert GpuDemand.from_env({}) == GpuDemand(enabled=False, wait="30m") + assert GpuDemand.from_env({}) == GpuDemand(enabled=False) demand = {gpu_demand.MODE_ENV: "demand", gpu_demand.WAIT_ENV: "2m"} assert GpuDemand.from_env(demand) == GpuDemand(enabled=True, wait="2m") + # a wait is a bound someone sets; the cap on cards is the same kind of knob + assert GpuDemand.from_env({gpu_demand.MODE_ENV: "demand"}).wait == "" + assert GpuDemand.from_env({gpu_demand.MAX_ENV: "4"}).maximum == 4 + assert GpuDemand.from_env({gpu_demand.MAX_ENV: "four"}).maximum is None + assert GpuDemand.from_env({gpu_demand.MAX_ENV: "0"}).maximum is None 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( @@ -219,6 +244,19 @@ def test_wrapper_routes_the_schedulers_output_and_the_commands(scheduler, tmp_pa assert granted_gpus(side) == ["7"] and scheduler_error(side) == "" +def test_wrapper_without_a_bound_waits_for_the_cards(scheduler, tmp_path): + env, _, refuse = scheduler + (tmp_path / "slow").touch() + env = dict(env, IMX_GPU_STUB_DELAY="3") + side = tmp_path / "side.log" + program = scheduler_wrap("printf 'ran\\n'", gpus=1, timeout_sec=600, + wait="", note="a test", side_log=side) + assert "--wait" not in program + done = subprocess.run(["bash", "--norc", "-c", program], env=env, + capture_output=True, text=True, timeout=60) + assert done.returncode == 0 and done.stdout == "ran\n" + + def test_wrapper_reports_an_expired_wait_with_its_own_status(scheduler, tmp_path): env, _, refuse = scheduler refuse.touch() @@ -264,6 +302,74 @@ def test_runner_asks_for_the_jobs_cards_and_bounds_the_wait(scheduler, tmp_path) assert "--idle-timeout 17m" in program +def test_runner_waits_for_cards_and_times_the_test_from_the_grant(scheduler, tmp_path): + env, calls, refuse = scheduler + (tmp_path / "slow").touch() + # 4 s in the queue, a test allowed 2 s: timed from the spawn it would be + # killed in the queue; timed from the grant it runs to its end + job = TestJob(key="queued", command="printf 'ran\\n'", timeout_sec=2) + outcome = _runner(tmp_path, _UNBOUNDED).run(job, dict(env)) + assert outcome.rc == 0 and not outcome.timed_out, outcome + program = outcome.plan.argv[-1] + assert "--wait" not in program # nothing gives up on cards + log = Path(outcome.log_file).read_text() + assert "[gpu] queued for the scheduler's cards" in log + assert "[gpu] granted after" in log and "[gpu] 1 card(s) from the scheduler: [7]" in log + assert "\nran\n" in log + + +def test_runner_a_refusal_is_not_a_wait(scheduler, tmp_path): + env, _, _ = scheduler + (tmp_path / "deny").touch() + job = TestJob(key="probe", command="printf 'ran\\n'", timeout_sec=600) + outcome = _runner(tmp_path, _UNBOUNDED).run(job, dict(env)) + assert outcome.rc == 1 and not outcome.skipped and not outcome.timed_out + log = Path(outcome.log_file).read_text() + assert "[gpu] not run: the scheduler named no card(s) and said:" in log + assert "\nran\n" not in log + + +def test_runner_lock_keeps_its_bounded_wait_whatever_the_queue(scheduler, tmp_path, monkeypatch): + import infermatrix_copilot.testing.runner as module + + seen = [] + + class FakeLock: + def __init__(self, lock_dir, **kwargs): + seen.append(kwargs) + + def acquire(self): + return self + + def release(self): + pass + + monkeypatch.setattr(module, "GpuLock", FakeLock) + job = TestJob(key="cpu", command="printf 'cpu\\n'", timeout_sec=30, + min_gpus=0, gpu_lock=True, gpus=0) + locked = lambda demand: TestRunner( # noqa: E731 + repo_root=tmp_path, tests_dir=tmp_path / "tests", + gpu_lock_dir=tmp_path / "gpu_lock", gpu_demand=demand) + locked(_UNBOUNDED).run(job, dict(scheduler[0])) + locked(_DEMAND).run(job, dict(scheduler[0])) + # a run holding the lock may itself be queued for cards without a bound: + # the next one still gives up on the lock after its hour, as feedback + assert seen == [{}, {}] + + +def test_runner_asks_for_what_the_jobs_tests_declare(scheduler, tmp_path): + env, calls, _ = scheduler + (tmp_path / "tests_x").mkdir() + (tmp_path / "tests_x" / "test_need.py").write_text( + "import pytest\npytestmark = [pytest.mark.core_model, pytest.mark.cards_4]\n" + "def test_a():\n pass\n") + command = _PROBE + "\nprintf '%s\\n' pytest tests_x/test_need.py" + job = TestJob(key="need", command=command, timeout_sec=60, min_gpus=0, gpu_lock=True) + outcome = _runner(tmp_path).run(job, dict(env)) + assert outcome.rc == 0 and _requests(calls) == ["gpus=4"] + assert "--gpus 4" in outcome.plan.argv[-1] + + 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) @@ -366,6 +472,25 @@ def test_shell_tells_the_agent_when_no_card_was_granted(scheduler, monkeypatch): assert _requests(calls) == ["gpus=1"] +def test_shell_asks_for_what_the_test_declares(scheduler, tmp_path, monkeypatch): + env, calls, _ = scheduler + monkeypatch.setenv(gpu_demand.MODE_ENV, "demand") + (tmp_path / "tests").mkdir() + (tmp_path / "tests" / "test_need.py").write_text( + "import pytest\n" + "@pytest.mark.core_model\n" + "@hardware_test(res={\"cuda\": \"L20\"}, num_cards=2)\n" + "def test_a():\n pass\n") + tools = build_rebase_tools( + [{"name": "run_shell", "description": "Run a command", + "input_schema": {"type": "object"}}], + RebasePaths(omni_path=str(tmp_path), vllm_path="/", env=env)) + result = json.loads(tools["run_shell"].handler(command="pytest tests/test_need.py", + timeout=60)) + assert result["exit_code"] == 0, result + assert _requests(calls) == ["gpus=2"] + + def test_shell_outside_demand_mode_never_asks(scheduler, tmp_path): env, calls, _ = scheduler result = _shell(env)("pytest -k x") @@ -374,11 +499,95 @@ def test_shell_outside_demand_mode_never_asks(scheduler, tmp_path): assert _requests(calls) == [] +# -- what the selected tests declare --------------------------------------------- + +_TREE = { + "test_decorator.py": ( + "import pytest\n" + "@pytest.mark.core_model\n" + "@hardware_test(res={\"cuda\": \"L20\"}, num_cards=2)\n" + "def test_a():\n pass\n"), + "test_module.py": ( + "import pytest\n" + "pytestmark = [pytest.mark.core_model, pytest.mark.cards_4]\n" + "def test_b():\n pass\n"), + "test_class.py": ( + "import pytest\n" + "class TestGroup:\n" + " pytestmark = pytest.mark.core_model\n" + " @hardware_marks(res={\"cuda\": \"L20\"}, num_cards={\"cuda\": 3, \"rocm\": 1})\n" + " def test_c(self):\n pass\n"), + "test_other_level.py": ( + "import pytest\n" + "@pytest.mark.advanced_model\n" + "@hardware_test(res={\"cuda\": \"H100\"}, num_cards=8)\n" + "def test_d():\n pass\n"), + "test_strings.py": ( + "def test_quote():\n" + " assert '-m \"cards_8\"' in buildkite()\n"), + "test_undeclared.py": "def test_e():\n pass\n", +} + + +@pytest.fixture +def tree(tmp_path): + (tmp_path / "tests").mkdir() + for name, text in _TREE.items(): + (tmp_path / "tests" / name).write_text(text) + gpu_demand._NEEDS.clear() + return tmp_path + + +def test_command_gpus_reads_what_the_selected_tests_declare(tree): + need = lambda command, **kw: command_gpus(command, 1, tree, **kw) # noqa: E731 + # the command's own expression is the selection + assert command_gpus("pytest -m 'core_model and cards_2'", 1, tree) == 2 + # decorators, module marks, class marks, a per-platform number + assert need("pytest tests/test_decorator.py") == 2 + assert need("pytest tests/test_module.py") == 4 + assert need("pytest tests/test_class.py::TestGroup::test_c") == 3 + # a test of another run level does not count at the default level + assert need("pytest tests/test_other_level.py") == 1 + assert need("pytest tests/test_other_level.py --run-level advanced_model") == 8 + # names inside strings are not needs, and a directory is all of its files + assert need("pytest tests/test_strings.py") == 1 + assert need("pytest tests/ --run-level core_model") == 4 + assert need("pytest tests/ --run-level advanced_model") == 8 + # the level the command selects: its option, else the one level it names + assert need("pytest tests/test_other_level.py -m 'advanced_model and cuda'") == 8 + # nothing declared: one card + assert need("pytest tests/test_undeclared.py") == 1 + assert need("pytest tests/missing.py") == 1 + assert need("python -c 'import torch'") == 1 + + +def test_command_gpus_does_not_count_what_the_expression_excludes(tree): + cpu_job = "core_model and cpu and not (cards_2 or cards_3 or cards_4 or cards_8)" + assert command_gpus(f"pytest tests/ -m '{cpu_job}'", 1, tree) == 1 + # the module's four and the class's three; four is excluded + assert command_gpus("pytest tests/ -m 'core_model and not cards_4'", 1, tree) == 3 + + +def test_command_gpus_cap_never_dips_below_a_callers_minimum(tree): + assert command_gpus("pytest tests/ --run-level advanced_model", 1, tree, 4) == 4 + assert command_gpus("pytest tests/", 6, tree, 4) == 6 + assert command_gpus("pytest -m 'full_model and cards_8'", 1, None, 4) == 4 + assert command_gpus("pytest tests/", 0, tree, 4) == 4 + + +def test_command_gpus_rereads_edited_tests(tree): + assert command_gpus("pytest tests/test_undeclared.py", 1, tree) == 1 + (tree / "tests" / "test_undeclared.py").write_text( + "import pytest\npytestmark = pytest.mark.core_model\n" + "@pytest.mark.cards_2\ndef test_e():\n pass\n") + assert command_gpus("pytest tests/test_undeclared.py", 1, tree) == 1 # kept briefly + gpu_demand._NEEDS.clear() + assert command_gpus("pytest tests/test_undeclared.py", 1, tree) == 2 + + # -- 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" +def _wrapper_env(repo, tmp_path, monkeypatch): repo.mkdir() for name in ("IMX_ADAPTER_REBASE", "IMX_WATCHDOG_OVERLAY"): monkeypatch.delenv(name, raising=False) @@ -388,6 +597,10 @@ def test_module_wrapper_asks_for_one_card_and_says_so_when_nothing_ran( "IMX_GPU_MUTEX": "0", "CUDA_VISIBLE_DEVICES": "", "TEST_TIMEOUT_SEC": "10"}.items(): monkeypatch.setenv(key, value) + gpu_demand._NEEDS.clear() + + +def _capturing_wrapper(monkeypatch): seen = {} class CapturingRunner: @@ -400,6 +613,13 @@ def run(self, job, env): rc=0, skipped=True, log_file="", skip_reason="needs 1 GPU(s)") monkeypatch.setattr(module_pytest, "TestRunner", CapturingRunner) + return seen + + +def test_module_wrapper_asks_for_one_card_and_says_so_when_nothing_ran( + tmp_path, monkeypatch, capsys): + _wrapper_env(tmp_path / "repo", tmp_path, monkeypatch) + seen = _capturing_wrapper(monkeypatch) # 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 @@ -407,3 +627,16 @@ def run(self, job, env): captured = capsys.readouterr() for stream in (captured.out, captured.err): assert "skipped — needs 1 GPU(s)" in stream + + +def test_module_wrapper_asks_for_what_its_tests_declare(tmp_path, monkeypatch): + repo = tmp_path / "repo" + _wrapper_env(repo, tmp_path, monkeypatch) + (repo / "tests" / "worker").mkdir(parents=True) + # the wrapper selects core_model by default: the test says it needs two + (repo / "tests" / "worker" / "test_need.py").write_text( + "import pytest\npytestmark = pytest.mark.core_model\n" + "@pytest.mark.cards_2\ndef test_a():\n pass\n") + seen = _capturing_wrapper(monkeypatch) + assert module_pytest.main(["-vv", "-s", "tests/worker/"]) == 0 + assert seen["job"].gpus == 2