diff --git a/CLAUDE.md b/CLAUDE.md index 03e6ca2..b066f77 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ ## 開発進捗 -最新: PLAN_02 のステップ 1-4(回収の一覧と結果の置き場を設定にする)完了.次はステップ 1-5(`run.exclude_groups`) +最新: PLAN_02 のステップ 1-5(`run.exclude_groups`)完了.次はステップ 1-6(プロジェクトの側のテストを短く書くための関数) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" index 235eee1..c33227b 100644 --- "a/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" +++ "b/docs/03_PLAN/PLAN_02_\351\226\213\347\231\272\343\202\271\343\203\206\343\203\203\343\203\227.md" @@ -83,6 +83,16 @@ | 3-1 | **回収の一覧は,もうコードに無い**.TongueSegModel の `labremote.yaml` に `results.pull`(`config.yaml`・`history.csv`・`metrics.json`・`log.txt`・`predictions.csv`・`split.json`,`figures` の `.png`)と `results.checkpoints`(`best.pth`・`ResUNet.onnx`)を書く.書かなければ,`pull` は何も回収せずに止まる | | テスト | 設定の検証のテストは,大きな組み合わせ(200 件以上のクラスが 2 つ)になっていて,どの組み合わせが何を確かめているかが読み取りにくい.検査の順序(複数の誤りがあるときに,どのエラーが先に出るか)を固定するテストは無い | +### 1-5 で分かったこと (Findings from Step 1-5) + +1-5 は完了した(2026-11-20). + +| 直すステップ | 内容 | +| --- | --- | +| 3-1 | TongueSegModel の `pyproject.toml` で,LabRemote を専用の依存グループ(`remote`)に入れ,`labremote.yaml` に `run.exclude_groups: [remote]` を書く | +| 3-2 | サーバに LabRemote のフォルダが無い状態で,`uv run --no-group remote` がロックファイルの確認を通るかは,まだ確かめていない(実サーバとサブモジュールが要る).通らなければ,`--frozen` を足すか,導入に要るものだけを送る形に仕様を直す.今の実装が `uv run` へ渡せるのは `--no-group <名前>` だけである | +| 1-7 | 依存グループの名前の検証は,`a.`・`a-` のように末尾が記号の名前も通す.依存グループの名前の決まり(末尾は英数字)より緩い.害は無い(uv が拒否する)が,そろえるなら仕様を先に直す | + ## M2: 新しい機能 (New Features) | ステップ | 内容 | 確かめること | diff --git "a/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" "b/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" index 0f23dde..005e421 100644 --- "a/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" +++ "b/docs/04_SPEC/SPEC_02_\350\250\255\345\256\232\343\203\225\343\202\241\343\202\244\343\203\253\344\273\225\346\247\230.md" @@ -3,7 +3,7 @@ 各プロジェクトのルートに置く `labremote.yaml` の項目を定める.pydantic で検証し,未知のキーは拒否する. 設定で変えられない規則(安全の枠)は [SPEC_01](SPEC_01_アーキテクチャ設計.md) にある. -※ 実装の状況(2026-11-20): `project`・接続と GPU の基準・`servers`・`run.env`・`push`・`results` は実装済み(`results.discard` は読み込みと検証だけで,使うのはステップ 2-2 の `clean`).`run.exclude_groups` は未実装で,今は書くと未知のキーとして拒否される([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 1-5). +※ 実装の状況(2026-11-20): この文書の項目は,すべて実装済みである.ただし `results.discard` は読み込みと検証だけで,使うのは `clean`([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 2-2)である. ## 例 (Example) @@ -133,6 +133,17 @@ | `env` | `{}` | ジョブに既定で渡す環境変数.`--env` で同じ名前を指定すると,`--env` が優先される | | `exclude_groups` | `[]` | サーバの `uv run` で外す依存グループの名前.グループごとに `--no-group <名前>` を付ける.名前は英数字で始まり,英数字・`_`・`-`・`.` だけ | +`exclude_groups` の書き方. + +- 名前の一覧で書く(`exclude_groups: [remote]`.1 つの文字列 `exclude_groups: remote` はエラーにする) +- 名前は文字列で書く.英数字で始まり,英数字・`_`・`-`・`.` だけ(依存グループの名前に使える文字).それ以外(空・空白・`/`・`=`・先頭の `-` 等)はエラーにする +- 同じ名前を 2 回書くとエラーにする.比べ方は,Python のパッケージの名前の正規化(PEP 503)と同じにする: 小文字にし,`_`・`-`・`.` が続いた部分を 1 つの `-` にして比べる(`remote` と `Remote`,`a_b` と `a.-b` は同じ名前.`ab` と `a-b` は別の名前).uv がそう扱うためである.サーバへ渡すのは,設定に書いたままの名前である +- サーバのコマンドでは,` run --no-group <名前> ... <コマンド>` の形で,書いた順に,コマンドより前に付ける.値は引用して埋め込む +- `--cpu` のジョブにも,`--dry-run` の表示にも,同じように付く.ジョブのログの開始行に出るコマンドの表示にも付ける(実際に動くコマンドと,表示を食い違わせない) +- 一覧が空のときは,何も付かない +- `uv run` へ渡せるのは `--no-group <名前>` だけである.任意の引数を渡す設定は設けない +- 手元の環境には関わらない(手元で LabRemote を入れるかどうかは,利用する側の `pyproject.toml` で決める) + 優先の順は,`run.env` → `servers[].env` → `--env`(後のものが勝つ).予約の環境変数([SPEC_01](SPEC_01_アーキテクチャ設計.md)「環境変数」)は,どこにも書けない. `run.env`・`servers[].env` の書き方. diff --git "a/docs/04_SPEC/SPEC_03_\343\203\252\343\203\242\343\203\274\343\203\210\345\256\237\350\241\214\344\273\225\346\247\230.md" "b/docs/04_SPEC/SPEC_03_\343\203\252\343\203\242\343\203\274\343\203\210\345\256\237\350\241\214\344\273\225\346\247\230.md" index 9923088..c27d26a 100644 --- "a/docs/04_SPEC/SPEC_03_\343\203\252\343\203\242\343\203\274\343\203\210\345\256\237\350\241\214\344\273\225\346\247\230.md" +++ "b/docs/04_SPEC/SPEC_03_\343\203\252\343\203\242\343\203\274\343\203\210\345\256\237\350\241\214\344\273\225\346\247\230.md" @@ -111,7 +111,7 @@ - ジョブ名は,英数字で始まり,英数字・`_`・`-` だけ,1〜64 文字 - いずれかのサーバで同じ名前のジョブが実行中ならエラーにする -- tmux のセッション名をジョブ名とし,サーバの `remote_dir` で ` run ` を実行する.設定の `run.exclude_groups` に書いた依存グループは,`--no-group` で外す(LabRemote をサーバの環境に入れないため) +- tmux のセッション名をジョブ名とし,サーバの `remote_dir` で ` run ` を実行する.設定の `run.exclude_groups` に書いた依存グループは,` run --no-group <名前> ... ` の形で外す(LabRemote をサーバの環境に入れないため.[SPEC_02](SPEC_02_設定ファイル仕様.md)「`run`」).ログの開始行のコマンドの表示にも,同じ形で出す - ジョブに渡す環境変数は [SPEC_01](SPEC_01_アーキテクチャ設計.md)「環境変数」のとおり - ログは `/<結果の置き場>/_remote_logs/<ジョブ名>.log` に,開始の行(サーバ名・GPU・日時)と終了コードの行を付けて追記する - `--dry-run` を付けると,GPU の選択までを行い,送信・起動はしない diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 871a563..2fb21d3 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -46,3 +46,6 @@ - 設計判断: `results` の節は省略できる(書き忘れても回収するものが増えないため).一覧が空の `pull` は,接続せずに 0 以外で終わる - 設計判断: 結果の置き場は,コマンドを組み立てる関数が省略できない引数で受け取る(渡し忘れたときに,黙って `runs` を見に行かない) - 後段: TongueSegModel の切り替え(3-1)で,`results.pull` と `results.checkpoints` を書く.`discard` を使う判定は 2-2 +- [x] **ステップ 1-5(`run.exclude_groups`)**: 設定に書いた依存グループを,サーバの `uv run` で `--no-group <名前>` として外すようにした(LabRemote をサーバの環境に入れないため). + - 設計判断: `uv run` へ渡せるのは `--no-group <名前>` だけにし,任意の引数を渡す設定は作らなかった.名前は検証と引用を通してから埋め込む + - 後段: LabRemote のフォルダが無いサーバで,実際に `uv run --no-group` が通るかは未検証(3-2 で実サーバで確かめる) diff --git a/src/labremote/cli.py b/src/labremote/cli.py index 9fee858..e5a1a75 100644 --- a/src/labremote/cli.py +++ b/src/labremote/cli.py @@ -731,6 +731,7 @@ # 読み,場所は TIASDATA_BUNDLES(既定 ~/data/tiasdata)で決まるため渡さない(SPEC_03) path_env={}, results_dir=ctx.config.results.dir, + exclude_groups=ctx.config.run.exclude_groups, ) remote_command = build_run_command( server.remote_dir, name, script, results_dir=ctx.config.results.dir @@ -1099,7 +1100,9 @@ description=( "GPU を選び(data_ready のサーバ全体を通して,まず未使用を,無ければ" "空き(利用者あり)を priority 順・GPU 番号順に探す)," - "そのサーバへコードを送ってから remote_dir で `uv run ` を tmux で起動する." + "そのサーバへコードを送ってから remote_dir で `uv run ` を tmux で起動する" + "(設定の run.exclude_groups の各グループは `--no-group <名前>` として" + "uv run の直後に付く)." f"出力は remote_dir//{REMOTE_LOG_DIR_NAME}/.log に追記され" "(results.dir は設定の結果の置き場.既定は runs),接続が切れても継続する." "コマンドは -- の後に書く." @@ -1166,7 +1169,7 @@ "command", nargs=argparse.REMAINDER, metavar="-- COMMAND", - help="サーバで実行するコマンド(uv run の後ろに付く部分).", + help="サーバで実行するコマンド(uv run と --no-group <名前> の後ろに付く部分).", ) p_logs = sub.add_parser( diff --git a/src/labremote/commands.py b/src/labremote/commands.py index 709259c..9123037 100644 --- a/src/labremote/commands.py +++ b/src/labremote/commands.py @@ -77,6 +77,12 @@ # tmux のセッション名に使えない "." ":" を避け,ログのファイル名にもそのまま使える文字に限る _JOB_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}") _ENV_KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +# サーバの `uv run` で外す依存グループの名前(設定の `run.exclude_groups`.SPEC_02「`run`」). +# 英数字で始める(`-` 始まりで uv のオプションとして解釈されないようにする). +# 設定の検証(`labremote.config`)とコマンドの組み立ての両方がこの規則を使う +_DEPENDENCY_GROUP_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*") +# 依存グループの名前を比べる形にするときに,1 つの `-` にまとめる文字の連なり(PEP 503 と同じ) +_DEPENDENCY_GROUP_SEPARATORS_RE = re.compile(r"[-_.]+") # ssh の接続先(Host 名・踏み台)に許す文字.空白や `-` 始まりでオプションとして # 解釈されるのを防ぐ _SSH_TOKEN_RE = re.compile(r"[A-Za-z0-9_.][A-Za-z0-9_.@:%-]*") @@ -211,6 +217,43 @@ return name +def validate_dependency_group(name: str) -> str: + """サーバの `uv run` で外す依存グループの名前(設定の `run.exclude_groups`)を検証して返す. + + Args: + name: 依存グループの名前. + + Returns: + 検証済みの名前(書いたまま.比べる形には `normalize_dependency_group` を使う). + + Raises: + ValueError: 文字列でない,または英数字で始まり英数字・`_`・`-`・`.` のみでない場合. + """ + # YAML が数値等に変えた値を,気づかないまま渡さないため + if not isinstance(name, str): + raise ValueError(f"依存グループの名前は文字列で書く: {name!r}") + if not _DEPENDENCY_GROUP_RE.fullmatch(name): + raise ValueError( + f"依存グループの名前が不正である: {name!r}(英数字で始まり,英数字・_・-・. のみ)" + ) + return name + + +def normalize_dependency_group(name: str) -> str: + """依存グループの名前を,重複を比べる形にそろえる(PEP 503 の正規化と同じ). + + uv は大文字小文字と `_`・`-`・`.` の違いだけの名前を同じグループとして扱うため,比べるときに + 使う.サーバへ渡す値には使わない(書いたままの名前を渡す). + + Args: + name: 検証済みの依存グループの名前. + + Returns: + 小文字にし,`_`・`-`・`.` の連なりを 1 つの `-` にした名前. + """ + return _DEPENDENCY_GROUP_SEPARATORS_RE.sub("-", name).lower() + + def reserved_env_vars(git_commit_env: str | None) -> frozenset[str]: """設定でも `--env` でも指定できない環境変数名を返す. @@ -562,6 +605,7 @@ env: Mapping[str, str], path_env: Mapping[str, str], results_dir: str, + exclude_groups: Sequence[str] = (), ) -> str: """tmux セッション内で bash が実行するジョブ本体のスクリプトを返す. @@ -569,11 +613,13 @@ 開始行(サーバ名・GPU・日時)と終了コード行で挟む.標準入力は /dev/null にする (入力待ちで止まらないように).非対話 ssh では `~/.local/bin` が PATH に無いため, uv のディレクトリと `$HOME/.local/bin` を PATH に足す. + `exclude_groups` の各名前は,` run` の直後(コマンドより前)に `--no-group <名前>` として + 渡した順に付ける(LabRemote を入れた依存グループをサーバの環境に入れないため). Args: remote_dir: リモートのプロジェクトルート. name: ジョブ名. - command: `uv run` の後ろに付けて実行するコマンドと引数. + command: `uv run`(と `--no-group <名前>`)の後ろに付けて実行するコマンドと引数. uv_path: リモートの uv 実行ファイル. server_name: ログの開始行に書くサーバ名. gpu_index: ログの開始行に書く GPU 番号.None なら GPU を使わないジョブ(`--cpu`)として @@ -582,23 +628,40 @@ path_env: ジョブに渡す環境変数のうち,値がリモートのパス(`~` を `$HOME` に展開する) であるもの. results_dir: 検証済みの結果の置き場(設定の `results.dir`). + exclude_groups: サーバの `uv run` で外す依存グループの名前(設定の `run.exclude_groups`). + 設定で検証済みでも,ここで `validate_dependency_group` を通してから引用して埋め込む. + 空なら何も付けない. Returns: bash スクリプト(1 行). Raises: - ValueError: コマンドが空,またはジョブ名・環境変数名・パス・結果の置き場が不正な場合. + ValueError: コマンドが空,またはジョブ名・環境変数名・パス・結果の置き場・依存グループの + 名前が不正な場合. """ if not command: raise ValueError("実行するコマンドが空である") log = job_log_path(validate_job_name(name), results_dir=results_dir) for key in [*env, *path_env]: validate_env_key(key) + # 設定の検証との二重の確認(`-` 始まりの名前で uv のオプションを差し込まれないように) + if isinstance(exclude_groups, str): + # 文字列を渡すと 1 文字ずつのグループとして扱ってしまうため + raise ValueError(f"依存グループは名前の一覧で渡す: {exclude_groups!r}") + uv_options: list[str] = [] + for group in exclude_groups: + uv_options += ["--no-group", validate_dependency_group(group)] uv_quoted = quote_remote_path(uv_path) - run_argv = [uv_quoted, "run", *(shlex.quote(arg) for arg in command)] + run_argv = [ + uv_quoted, + "run", + *(shlex.quote(arg) for arg in uv_options), + *(shlex.quote(arg) for arg in command), + ] display = shlex.join( - [f"{k}={v}" for k, v in [*env.items(), *path_env.items()]] + ["uv", "run", *command] + [f"{k}={v}" for k, v in [*env.items(), *path_env.items()]] + + ["uv", "run", *uv_options, *command] ) gpu_label = NO_GPU_LABEL if gpu_index is None else str(gpu_index) header = f"server={server_name} gpu={gpu_label}" diff --git a/src/labremote/config.py b/src/labremote/config.py index d2d51e4..967dc64 100644 --- a/src/labremote/config.py +++ b/src/labremote/config.py @@ -34,8 +34,10 @@ from labremote.commands import ( REMOTE_LOG_DIR_NAME, + normalize_dependency_group, quote_remote_path, reserved_env_vars, + validate_dependency_group, validate_env_key, validate_env_value, validate_git_commit_env, @@ -163,9 +165,12 @@ Attributes: env: ジョブに既定で渡す環境変数(`servers[].env`・`--env` に同じ名前があれば後者が 勝つ).値はそのまま引用して渡す(`~` は展開しない). + exclude_groups: サーバの `uv run` で外す依存グループの名前(書いた順.書いたままの名前で + `--no-group <名前>` として渡す). """ env: dict[StrictStr, StrictStr] = Field(default_factory=dict) + exclude_groups: tuple[StrictStr, ...] = () @field_validator("env") @classmethod @@ -173,6 +178,23 @@ _check_env_mapping(value, where="run.env") return value + @field_validator("exclude_groups") + @classmethod + def _check_exclude_groups(cls, value: tuple[str, ...]) -> tuple[str, ...]: + # 名前の規則は `labremote.commands.validate_dependency_group` の 1 か所で決める + seen: set[str] = set() + for group in value: + try: + validate_dependency_group(group) + except ValueError as exc: + raise ValueError(f"run.exclude_groups: {exc}") from exc + # uv は大文字小文字と _ - . の違いだけの名前を同じグループとして扱うため,そろえて比べる + key = normalize_dependency_group(group) + if key in seen: + raise ValueError(f"run.exclude_groups に同じ名前が 2 回書かれている: {group!r}") + seen.add(key) + return value + def _check_push_name(value: str, *, where: str) -> str: """push の設定に書く 1 つの名前(フォルダ・ファイルの名前)を検証して返す. diff --git a/tests/test_cli.py b/tests/test_cli.py index 6a884af..8ddad54 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2232,3 +2232,86 @@ names = _push_dry_run_names([], capsys) assert names assert not any(name.startswith("runs") for name in names) + + +# --------------------------------------------------------------------------- +# run.exclude_groups(SPEC_02「`exclude_groups` の書き方」,SPEC_03「run」) +# --------------------------------------------------------------------------- + + +def _remote_command_of_dry_run(out: str) -> str: + """`run --dry-run` の出力から,表示された「実行するリモートコマンド」を取り出す.""" + lines = out.splitlines() + return lines[lines.index("実行するリモートコマンド:") + 1] + + +class TestExcludeGroupsFromCli: + def _with_groups(self, project: Path, groups: object) -> None: + def mutate(data: dict) -> None: + data["run"] = {"exclude_groups": groups} + + _write_config_data(project, mutate) + + def test_dry_run_shows_no_group_options( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: `--dry-run` の表示にも書いた順に付く.""" + self._with_groups(project, ["remote", "dev.tools"]) + _free_everywhere(monkeypatch) + captured = _spy_job_script(monkeypatch) + assert cli.main(_run_dry([])) == 0 + assert tuple(captured[0]["exclude_groups"]) == ("remote", "dev.tools") + remote_command = _remote_command_of_dry_run(capsys.readouterr().out) + assert _uv_run_args_of_launch(remote_command) == [ + "--no-group", + "remote", + "--no-group", + "dev.tools", + "python", + ] + + def test_dry_run_without_groups_has_no_option( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: 書いていなければ何も付かない.""" + _free_everywhere(monkeypatch) + assert cli.main(_run_dry([])) == 0 + remote_command = _remote_command_of_dry_run(capsys.readouterr().out) + assert _uv_run_args_of_launch(remote_command) == ["python"] + + def test_cpu_dry_run_also_has_options( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: `--cpu` のジョブにも同じように付く.""" + self._with_groups(project, ["remote"]) + fake = FakeSsh( + { + NEWTON_ADDR: _ok(_probe_stdout_instant()), + ARCHIMEDES_ADDR: _ok(_probe_stdout_instant()), + } + ) + monkeypatch.setattr(cli, "_run_ssh", fake) + assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 + remote_command = _remote_command_of_dry_run(capsys.readouterr().out) + assert _uv_run_args_of_launch(remote_command) == ["--no-group", "remote", "x"] + + def test_launch_passes_options(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """SPEC_03「run」: 起動のコマンドでも,`--no-group` がコマンド本体より前に付く.""" + self._with_groups(project, ["remote"]) + fake = _free_everywhere(monkeypatch) + assert cli.main(["run", "--name", "train1", "--no-push", "--", "tsm-train"]) == 0 + assert _uv_run_args_of_launch(fake.calls[-1][-1]) == ["--no-group", "remote", "tsm-train"] + + @pytest.mark.parametrize( + "groups", [["-x"], ["--frozen"], ["a b"], ["remote", "Remote"], "remote"] + ) + @pytest.mark.parametrize("subcommand", [["gpus"], ["run", "--name", "t", "--", "x"]]) + def test_invalid_config_stops_before_ssh( + self, project: Path, monkeypatch: pytest.MonkeyPatch, groups: object, subcommand: list[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: 不正な設定は読む時点でエラー(ssh を呼ばない).""" + self._with_groups(project, groups) + fake = FakeSsh({}) + monkeypatch.setattr(cli, "_run_ssh", fake) + assert cli.main(subcommand) == 1 + assert fake.calls == [] diff --git a/tests/test_commands.py b/tests/test_commands.py index edbc231..d79b980 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1038,3 +1038,85 @@ """ with pytest.raises(ValueError): _builders_with_results_dir(results_dir)[kind]() + + +# --------------------------------------------------------------------------- +# run.exclude_groups の組み立て(SPEC_02「`exclude_groups` の書き方」,SPEC_03「run」) +# --------------------------------------------------------------------------- + + +def _script_with_groups( + groups: object, *, gpu_index: int | None = 0, command: list[str] | None = None +) -> str: + return build_job_script( + "~/work/TongueSegModel", + "train1", + command or ["tsm-train", "--config", "c.yaml"], + uv_path="~/.local/bin/uv", + server_name="Newton", + gpu_index=gpu_index, + env=build_job_env(gpu_index, [], git_commit="abc1234"), + path_env={}, + results_dir="runs", + exclude_groups=groups, # type: ignore[arg-type] + ) + + +def _log_display_words(script: str) -> list[str]: + """ジョブのログの開始行に出るコマンドの表示を,語に分けて返す(`uv` 以降).""" + tokens = shlex.split(script) + display = tokens[tokens.index("$(hostname)") + 1] + words = shlex.split(display) + return words[words.index("uv") :] + + +class TestExcludeGroupsInJobScript: + @pytest.mark.parametrize( + ("groups", "options"), + [ + (["remote"], ["--no-group", "remote"]), + (["remote", "dev.tools"], ["--no-group", "remote", "--no-group", "dev.tools"]), + (["dev.tools", "remote"], ["--no-group", "dev.tools", "--no-group", "remote"]), + ], + ) + def test_no_group_options_come_right_after_uv_run_in_order( + self, groups: list[str], options: list[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: uv run の直後・コマンドより前に書いた順で付く.""" + command = ["tsm-train", "--config", "c.yaml"] + assert _uv_run_args(_script_with_groups(groups, command=command)) == [*options, *command] + + @pytest.mark.parametrize("groups", [(), []]) + def test_empty_list_adds_nothing(self, groups: object) -> None: + """SPEC_02「`exclude_groups` の書き方」: 空なら何も付かない(引数無しと同じ).""" + assert _script_with_groups(groups) == _script(0, ["tsm-train", "--config", "c.yaml"]) + assert "--no-group" not in shlex.split(_script_with_groups(groups)) + + def test_no_group_in_user_command_stays_in_command(self) -> None: + """SPEC_02「`exclude_groups` の書き方」: コマンド本体の `--no-group` は本体の側に残る.""" + command = ["tsm-train", "--no-group", "x"] + args = _uv_run_args(_script_with_groups(["remote"], command=command)) + assert args == ["--no-group", "remote", *command] + + @pytest.mark.parametrize("gpu_index", [0, None]) + def test_added_for_gpu_and_cpu_jobs(self, gpu_index: int | None) -> None: + """SPEC_02「`exclude_groups` の書き方」: `--cpu` のジョブにも同じように付く.""" + args = _uv_run_args(_script_with_groups(["remote"], gpu_index=gpu_index)) + assert args[:2] == ["--no-group", "remote"] + + @pytest.mark.parametrize("groups", [["remote"], ["remote", "dev.tools"], []]) + def test_log_header_display_matches_actual_command(self, groups: list[str]) -> None: + """SPEC_02「`exclude_groups` の書き方」: ログの開始行の表示も実際と同じ.""" + script = _script_with_groups(groups) + assert _log_display_words(script) == ["uv", "run", *_uv_run_args(script)] + + @pytest.mark.parametrize("name", ["-x", "--frozen", "a b", "x;rm", "$(id)", "remote\n", "", 1]) + def test_invalid_name_is_rejected_by_builder(self, name: object) -> None: + """SPEC_02「`exclude_groups` の書き方」: 組み立ての側でも名前を確かめる.""" + with pytest.raises(ValueError): + _script_with_groups(["remote", name]) + + def test_single_string_instead_of_list_is_rejected(self) -> None: + """SPEC_02「`run`」: 一覧の代わりに 1 つの文字列を渡すと組み立てない.""" + with pytest.raises(ValueError): + _script_with_groups("remote") diff --git a/tests/test_config.py b/tests/test_config.py index f374746..58d866a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1677,3 +1677,109 @@ _write(tmp_path, _results_data({"dir": "output/runs"}, push=push)) ) assert config.push.partial[0].path == path + + +# --------------------------------------------------------------------------- +# run.exclude_groups(SPEC_02「`run`」「`exclude_groups` の書き方」) +# --------------------------------------------------------------------------- + + +def _groups_data(groups: object) -> dict: + data = _base() + data["run"] = {"exclude_groups": groups} + return data + + +class TestRunExcludeGroups: + def test_default_is_empty(self, tmp_path: Path) -> None: + """SPEC_02「`run`」: `exclude_groups` の既定は `[]`(`run` を省いても,書いても).""" + assert tuple(load_remote_config(_write(tmp_path, _base())).run.exclude_groups) == () + data = _base() + data["run"] = {} + assert tuple(load_remote_config(_write(tmp_path, data)).run.exclude_groups) == () + + @pytest.mark.parametrize( + "groups", + [["remote"], ["remote", "dev.tools"], ["a_b-c.d", "X1"], ["dev.tools", "remote"]], + ) + def test_valid_names_are_kept_in_order(self, tmp_path: Path, groups: list[str]) -> None: + """SPEC_02「`exclude_groups` の書き方」: 書ける名前は書いた順に持つ.""" + config = load_remote_config(_write(tmp_path, _groups_data(groups))) + assert tuple(config.run.exclude_groups) == tuple(groups) + + @pytest.mark.parametrize( + "name", + [ + "", + " remote", + "remote ", + "re mote", + "a/b", + "a\b", + "a=b", + "a;b", + "$a", + "a$b", + "'a'", + '"a"', + "-x", + "_x", + ".x", + "remote\n", + "re\x00mote", + "リモート", + "remoté", + "--frozen", + "-p", + "--with x", + "--no-group=x", + ], + ) + def test_invalid_names_are_rejected(self, tmp_path: Path, name: str) -> None: + """SPEC_02「`exclude_groups` の書き方」: 書けない名前・uv の別の引数はエラー.""" + _invalid(tmp_path, _groups_data(["ok", name])) + + @pytest.mark.parametrize("value", [1, 1.5, True, None, ["remote"]]) + def test_non_string_names_are_rejected(self, tmp_path: Path, value: object) -> None: + """SPEC_02「`exclude_groups` の書き方」: 文字列でない名前はエラー.""" + _invalid(tmp_path, _groups_data([value])) + + @pytest.mark.parametrize("groups", ["remote", {"remote": True}, 1]) + def test_must_be_a_list(self, tmp_path: Path, groups: object) -> None: + """SPEC_02「`run`」: `exclude_groups` は名前の一覧(1 つの文字列を書くとエラー).""" + _invalid(tmp_path, _groups_data(groups)) + + @pytest.mark.parametrize( + "groups", + [ + ["remote", "remote"], + ["remote", "Remote"], + ["a_b", "a-b"], + ["a_b", "a.b"], + ["a-b", "A.-B"], + ["x", "remote", "x"], + ], + ) + def test_duplicate_names_are_rejected(self, tmp_path: Path, groups: list[str]) -> None: + """SPEC_02「`exclude_groups` の書き方」: 大小・_ - . だけ違う名前も重複.""" + _invalid(tmp_path, _groups_data(groups)) + + @pytest.mark.parametrize("groups", [["remote", "remote2"], ["ab", "a-b"], ["a-b", "a-b-c"]]) + def test_similar_but_different_names_are_accepted( + self, tmp_path: Path, groups: list[str] + ) -> None: + """SPEC_02「`exclude_groups` の書き方」: 重複でない似た名前は通る.""" + config = load_remote_config(_write(tmp_path, _groups_data(groups))) + assert tuple(config.run.exclude_groups) == tuple(groups) + + def test_value_is_kept_as_written(self, tmp_path: Path) -> None: + """SPEC_02「`exclude_groups` の書き方」: 比べ方をそろえても,持つ値は書いたまま.""" + config = load_remote_config(_write(tmp_path, _groups_data(["Remote_X", "Dev..Tools"]))) + assert tuple(config.run.exclude_groups) == ("Remote_X", "Dev..Tools") + + @pytest.mark.parametrize("key", ["uv_args", "no_group", "groups", "uv_options", "extra_args"]) + def test_no_key_for_arbitrary_uv_arguments(self, tmp_path: Path, key: str) -> None: + """SPEC_02「`exclude_groups` の書き方」: 任意の引数を渡すキーは無い.""" + data = _base() + data["run"] = {key: ["--frozen"]} + _invalid(tmp_path, data)