diff --git a/CLAUDE.md b/CLAUDE.md index efd4789..03e6ca2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ ## 開発進捗 -最新: PLAN_02 のステップ 1-3(送信の除外を,固定の部分と設定に分ける)完了.次はステップ 1-4(回収の一覧と結果の置き場を設定にする) +最新: PLAN_02 のステップ 1-4(回収の一覧と結果の置き場を設定にする)完了.次はステップ 1-5(`run.exclude_groups`) ※ 本欄は**最新ステップ 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 73857da..235eee1 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" @@ -39,11 +39,10 @@ | 直すステップ | 内容 | | --- | --- | | 3-3 | 学習側のコードと git のハッシュの環境変数名を突き合わせるテスト(`test_whitelist.py`)は,名前を `LABREMOTE_GIT_COMMIT` に置き換えたため,TongueSegModel の今のコード(`TSM_GIT_COMMIT`)とは合わない.`project.git_commit_env` は 1-2 で入ったので,利用する側のテスト(3-3)で「設定の `git_commit_env` と,学習側のコードが読む名前が同じ」ことを確かめる形に移す | -| 1-4 | `test_cli.py` の回収のテストは,`split.json`・`predictions.csv` を「回収しない」前提で書かれている.一覧を設定にするときに,前提を設定から与える形に直す | | 1-6・3-3 | LabRemote の中では動かせないテストが 18 件あり,スキップにしてある(学習側の実験 ID の作り方と突き合わせる 15 件,実際の `configs/remote.yaml` を読む 2 件,サブモジュールの 1 件).利用する側のテストへ移す | | 1-7 | 表示・help の使用例・コメントに,TongueSegModel の言葉(「学習データのバンドル」,`tsm-train`・`tsm-export`,`TIAS_DATA_ROOT` の経緯)が残っている.テストの名前にも `tsm` が残っている(`test_markers_use_tsm_prefix`・`TestRunIdOfTsmTrain`) | | 1-7 | コメント・docstring の SPEC の参照(約 36 行)は,移す元の文書を指している.該当のコードを書き換えるステップで,LabRemote の SPEC を指す形に直す | -| 1-4 以降 | `cli.py` は約 1200 行あり,GPU の選択の流れ・git の状態の取得・tar の受け取りを抱えている.設定に出すときに,判定を各モジュールへ分ける(`.claude/rules/project-structure.md`) | +| 1-7 | `cli.py` は約 1200 行あり,GPU の選択の流れ・git の状態の取得・tar の受け取りを抱えている.設定に出すときに,判定を各モジュールへ分ける(`.claude/rules/project-structure.md`) | | 1-7 | コンソールの文字コードが日本語を表せない環境(CI の Windows は cp1252)では,help や表示の書き出しで `UnicodeEncodeError` になり,コマンドが落ちる.手元(cp932)とサーバ(UTF-8)では起きない.入口で「表せない文字は置き換えて出す」設定にする.今は `test_imports.py` の `test_help_runs_without_torch` が,子プロセスに UTF-8 を指定して避けている | | M2 | `test_cli.py` の `test_subcommands_listed_in_help_are_from_spec` は,help の字下げの幅に頼って一覧を読んでいる.`ls`・`clean` を足すときに壊れやすい | @@ -65,12 +64,25 @@ | 直すステップ | 内容 | | --- | --- | -| 1-4 | `config.py` の固定の除外は,結果の置き場を定数の `runs` から作っている.結果の置き場を設定にするときに,送信の固定の除外と,`partial.path` の検証(結果の置き場の中を指す `path` の拒否)が,設定の値を見るように直す | | 1-6 | 固定の除外を名前で判定する処理が,設定の検証(`config.py`)と選別(`files.py`)の 2 か所にある.「当たった部分の位置と種類」を返す関数 1 つにまとめられる.テスト用の関数は,`PushRules.from_push(設定の push).is_excluded(名前)` を包むだけで作れる | | 3-1 | **`data`・`legacy`・重みの拡張子は,もう固定の除外ではない**.TongueSegModel の `labremote.yaml` に `push.exclude_root: [data, legacy]`・`push.exclude_suffixes`・`push.partial`(`external/TIASDataHub`)を必ず書き,3-3 のテストで確かめる.`push` の節が無い設定は,読む時点でエラーになる | | 3-1 | LabRemote 自身のフォルダの場所は,「`labremote` パッケージの 2 つ上」で求めている(`src/` の形を前提にしている).サブモジュールとして編集可能インストールで入れる前提なら合う.別の入れ方にするなら見直す | | 1-7 | テスト(`tests/test_files.py`)に,TongueSegModel の言葉(`original_tongue_seg_dataset.py`・`legacy`)が残っている.サブモジュールのテスト群と `TestPartial` は,確かめている内容が重なっている | +### 1-4 で分かったこと (Findings from Step 1-4) + +1-4 は完了した(2026-11-20).前の表のうち,1-4 に回してあった 2 件は済んだので消した. + +| 直すステップ | 内容 | +| --- | --- | +| 1-6 | プロジェクトの側のテスト用の関数は,`is_pull_allowed(名前, 設定の results, with_checkpoints=...)` を包むだけで作れる | +| 1-7 | 設定の名前の検証は,送信(`push`)と回収(`results`)で前半(空・前後の空白・使えない文字)が同じだが,エラーの文言が少し違うので別の関数のままにしてある.文言をそろえるときに 1 つにまとめる.絶対パスの検査も同じ | +| 1-7 | `__init__.py` の docstring・`run` のコメント・help の使用例に,TongueSegModel の言葉が残っている | +| 2-2 | `discard` は,読み込みと検証だけが入っている.`clean` の判定を書くときは,回収と同じく大文字と小文字を区別して比べる.設定の検証用の「小文字にして比べる」関数を,判定に使わない | +| 2-3 | サーバのコマンドへ結果の置き場を埋め込む前の最後の確認(`commands.py`)は,設定の検証より緩い(引用するので安全ではある).消すコマンドに使うときは,規則をそろえる | +| 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 つ)になっていて,どの組み合わせが何を確かめているかが読み取りにくい.検査の順序(複数の誤りがあるときに,どのエラーが先に出るか)を固定するテストは無い | + ## M2: 新しい機能 (New Features) | ステップ | 内容 | 確かめること | diff --git "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" index 6a2a62f..95b6dbf 100644 --- "a/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" +++ "b/docs/04_SPEC/SPEC_01_\343\202\242\343\203\274\343\202\255\343\203\206\343\202\257\343\203\201\343\203\243\350\250\255\350\250\210.md" @@ -65,7 +65,7 @@ - 次は,設定に関わらず送らない(固定の除外) - どの階層にあっても送らないフォルダ: `.git/`・`.venv/`・`.claude/`・キャッシュ(`__pycache__/`・`.pytest_cache/`・`.ruff_cache/`) - どの階層にあっても送らないファイル: `.env`・`.env.*` - - 結果の置き場(ルートの直下.サーバ側の結果を上書きしないため) + - 結果の置き場(設定の `results.dir`.既定は `runs`.サーバ側の結果を上書きしないため) - 設定ファイル: 読み込んだ設定ファイルと,ルートの直下の `labremote.yaml`(サーバでは使わないため.2026-11-19 のユーザー判断) - LabRemote 自身のフォルダ: 実行中の `labremote` パッケージが入っているリポジトリが,ルートの下にある場合 - シンボリックリンクとジャンクションは,ファイルもフォルダも送らず,中にも入らない(リンク先がデータや原本でも,名前からは分からないため) @@ -93,6 +93,9 @@ 2. 手元で,受け取った tar を展開する前に全件を検査する.一覧に無い名前・外へ出るパス・リンクが 1 つでもあれば,何も展開せずに止まる - 手元のファイル名になる名前は,Windows で別の場所を指しうるもの(`:` 等の文字,末尾の `.` と空白,予約名)を拒否する - 回収しなかったファイルは件数だけを表示し,名前は表示しない +- 名前で回収してよいかを決める処理は,1 つの関数に置く.上の二重の確認は,どちらもその関数を,同じ設定で呼ぶ(片方だけが緩い判定になる形にしない) +- 回収の判定は,大文字と小文字を区別する.設定の検証のうち,重複と重なりの検査だけは小文字にして比べる([SPEC_02](SPEC_02_設定ファイル仕様.md)「`results`」).小文字にして比べる処理を,回収の判定に使わない(使うと,一覧に無い名前まで回収する) +- 回収の一覧が空のときは,サーバに接続せず,0 以外の終了コードで終わる ※ フォルダを丸ごと回収する型(`sm-remote` の型)は,この枠に入っていない.SmTIAS-LightSim を切り替えるときに,この節を先に改訂してから実装する. 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 fec2c07..0f23dde 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`・`run.exclude_groups` は未実装で,今は書くと未知のキーとして拒否される([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 1-4・1-5).結果の置き場は,今は `runs` で固定である. +※ 実装の状況(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). ## 例 (Example) @@ -153,11 +153,41 @@ | `discard.files` | `[]` | 回収せずに消してよい,実験フォルダの直下のファイル名 | | `discard.dirs` | `[]` | 回収せずに消してよいもの.形は `pull.dirs` と同じ | -- 名前は大文字と小文字を区別し,完全一致で比べる -- 名前に書けないもの: ワイルドカード(`*`・`?`・`[`),`/`・`\`(`path` を除く),`..`,絶対パス,Windows で使えない文字・予約名 -- `pull.files`・`pull.dirs` には,`push.exclude_suffixes` に書いた拡張子(重み)を持つ名前を書けない.重みは `checkpoints.files` にだけ書ける -- 同じ名前を `pull` と `discard` の両方に書くとエラーにする -- ジョブのログは `/_remote_logs/` に置く.この名前は固定で,設定では変えられない +`results` の節は省略できる.省略したときは,結果の置き場が `runs`,回収する名前の一覧が空になる.一覧が空のときの `pull` は,サーバに接続せず,設定に書く場所を示して,0 以外の終了コードで終わる(頼まれた回収が 1 件もできないため).`push` と違って省略できるのは,書き忘れても回収するものが増えないためである. + +名前の比べ方. + +- 回収・破棄の名前(`files`・`dirs` の `path` と `suffix`・`checkpoints`)は,**大文字と小文字を区別し,完全一致で比べる**(`config.yaml` と書いて実際が `Config.yaml` なら回収しない.`.png` と書いて実際が `.PNG` なら回収しない).送信の除外とは逆だが,どちらも「迷ったら動かさない側」に倒すための決まりである +- 拡張子や中身では判断しない.一覧に名前が無いものは回収しない + +書き方と,書けないもの(設定を読む時点でエラーにする). + +- `dir` は,ルートからの相対パスで,`/` 区切りで書く(`runs`・`output/runs` 等).`..`・絶対パス・ワイルドカード・`.` や空の部分は書けない.固定の除外のフォルダ(`.git`・`.venv`・`.claude`・キャッシュ)の中も指せない +- `pull.files`・`checkpoints.files`・`discard.files` に書くのは,1 つのファイル名である.`/`・`\`・ワイルドカード(`*`・`?`・`[`)・`.`・`..`・空・前後の空白・NUL は書けない +- `dir`・`path`・名前には,空白や記号(`;`・`$` 等)を含むものも書ける(上に挙げた,書けない文字を除く).サーバのコマンドへは,引用して 1 つの語として渡す +- `pull.dirs`・`discard.dirs` の `path` には,固定の除外のフォルダと同じ名前(`.git` 等)も書ける(固定の除外は送信の決まりであり,`dir` にだけかかる) +- `pull.dirs`・`discard.dirs` は,`path` と `suffix` の両方を必ず書く.`path` は実験フォルダからの相対パス(`/` 区切り.書けないものは `dir` と同じ),`suffix` は `.` と 1 つの拡張子で書く(`.png` 等.ワイルドカードは書けない.`.tar.gz` のように点を 2 つ以上含むもの,`.` だけのものも書けない).対象は `path` の**直下**のファイルだけで,下の階層は対象にしない +- `checkpoints.dir` は,実験フォルダの直下の 1 つの名前で書く +- **手元のファイル名になる名前**(`dir`・`files`・`dirs` の `path`・`checkpoints`)には,Windows で別の場所を指しうるものを書けない: `<`・`>`・`:`・`"`・`|` の文字,末尾が `.` か空白の名前,予約名(`CON`・`NUL`・`COM1` 等.拡張子が付いていても同じ) +- **重みを一覧に紛れ込ませない**: + - `pull.files` に,`push.exclude_suffixes` に書いた拡張子を持つ名前は書けない.`pull.dirs` の `suffix` に,`push.exclude_suffixes` に書いた拡張子は書けない(比べるときは小文字にする) + - `pull.dirs` の `path` に,`checkpoints.dir` と同じ場所・その中の場所は書けない + - 重みは `checkpoints.files` にだけ書け,`--with-checkpoints` を付けたときだけ回収される + - 同じ名前を `pull.files` と `checkpoints.files` の両方に書くことはできない.`pull.files` に `checkpoints.dir` と同じ名前を書くこと,`pull.dirs` の `path` の最初の部分に `pull.files` と同じ名前を書くこともできない + - `pull.dirs` の `suffix` と `push.exclude_suffixes` の拡張子は,一方が他方の末尾に当たる場合も書けない(`.tar.gz` に対する `.gz` 等) +- **回収と破棄を両立させない**: 同じ名前を `pull.files` と `discard.files` の両方に書くこと,同じ `path` と `suffix` の組を `pull.dirs` と `discard.dirs` の両方に書くことはできない.`discard.dirs` の `path` に,`checkpoints.dir` と同じ場所・その中の場所は書けない(重みを捨てるのは,その場で `--discard-checkpoints` を付けたときだけ) +- 一覧の中の重複(同じ名前を 2 回)はエラーにする +- 重複と重なりの検査は,小文字にして比べる.手元の Windows では `a.txt` と `A.txt` が同じファイルになり,回収で上書きし合うためである.回収するかどうかの判定そのものは,大文字と小文字を区別したままである +- 名前に制御文字は書けない +- ジョブのログは `/_remote_logs/` に置く.この名前は固定で,設定では変えられない.`_remote_logs` は実験 ID としても,`files`・`checkpoints.dir` の名前としても,`dir`・`dirs` の `path` のどの部分としても使えない.`dir` に `labremote.yaml` を指す場所も書けない +- 未知のキーは拒否する.「すべて回収する」「検査を飛ばす」ためのキーは設けない + +結果の置き場と送信. + +- 結果の置き場(`<ルート>/`)は,送信の固定の除外である([SPEC_01](SPEC_01_アーキテクチャ設計.md)「安全の枠」).`dir` を変えると,除外される場所も変わる +- `push.partial` の `path` に,結果の置き場と同じ場所・その中の場所は書けない + +※ `discard` は,回収済みの実験フォルダを消す `clean`([SPEC_03](SPEC_03_リモート実行仕様.md).ステップ 2-2)で使う.それまでは,読み込みと検証だけを行う. ## 環境変数での上書き (Overrides) 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 54dffb9..9923088 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" @@ -132,6 +132,7 @@ - 保存先は,手元の `<ルート>/<結果の置き場>//`(同じ名前のファイルは上書きする) - 検査と展開は [SPEC_01](SPEC_01_アーキテクチャ設計.md)「安全の枠」の「回収」のとおり - 回収した件数と,回収しなかった件数(うち `--with-checkpoints` で回収できる件数)を表示する +- 設定の回収の一覧(`results.pull`)が空のときは,サーバに接続せず,設定に書く場所を示して,0 以外の終了コードで終わる.重みの一覧だけが書かれていて `--with-checkpoints` を付けたときは,警告を出して重みを回収する ### ls diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index f1fc087..871a563 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -40,3 +40,9 @@ - 設計判断: 名前は小文字にして比べ(`data` と書けば `Data` も送らない),比べ方は 1 つの関数で決める.`partial.include` だけは大文字小文字を区別する.どちらも,迷ったら送らない側に倒すため - 設計判断: `.claude` は「ルートの直下だけ」から「どの階層でも」送らない,に広げた(サブモジュールの中の `.claude` もサーバに要らない) - 後段: TongueSegModel の切り替え(3-1)で,`push` に `data`・`legacy`・重み・`external/TIASDataHub` を必ず書く.結果の置き場はまだ `runs` で固定(1-4) +- [x] **ステップ 1-4(回収の一覧を設定にする)**: 回収してよい名前の一覧と結果の置き場を,`labremote.yaml` の `results` から取るようにした.一覧に書ける形の検証を入れた. + - 設計判断: 変えたのは「一覧の中身をどこから取るか」だけで,回収の枠(完全一致・3 つの形・重みは明示のときだけ・二重の確認)は変えていない.名前で回収してよいかを決める関数は 1 つで,サーバ側の絞り込みと手元の tar の検査の両方が,同じ設定でそれを呼ぶ + - 設計判断: 回収の判定は大文字と小文字を区別し,設定の重複・重なりの検査だけは小文字にして比べる(Windows で上書きし合う名前を防ぐ).取り違えると回収するものが増えるので,関数を分け,名前と docstring に書いた + - 設計判断: `results` の節は省略できる(書き忘れても回収するものが増えないため).一覧が空の `pull` は,接続せずに 0 以外で終わる + - 設計判断: 結果の置き場は,コマンドを組み立てる関数が省略できない引数で受け取る(渡し忘れたときに,黙って `runs` を見に行かない) + - 後段: TongueSegModel の切り替え(3-1)で,`results.pull` と `results.checkpoints` を書く.`discard` を使う判定は 2-2 diff --git a/src/labremote/cli.py b/src/labremote/cli.py index 857efaf..9fee858 100644 --- a/src/labremote/cli.py +++ b/src/labremote/cli.py @@ -12,10 +12,11 @@ - run : 空き GPU を選び,そのサーバへコードを送って tmux でジョブを起動する - logs : ジョブのログを表示する(ジョブのあるサーバを自動で探す) - kill : ジョブを止める(ジョブのあるサーバを自動で探す) -- pull : 実験結果を回収ホワイトリストに従って持ち帰る +- pull : 実験結果のうち,設定の回収の一覧(`results`)に名前が一致するものだけを持ち帰る ssh を呼ぶ副作用はこのモジュールに集め,コマンド文字列の組み立て・出力の解析・GPU の選択・ -回収ホワイトリストの判定は `labremote` の純関数に任せる. +回収の判定(SPEC_01「安全の枠」の「回収」)は `labremote` の純関数に任せる.結果の置き場と +回収の一覧は,設定の `results`(SPEC_02「`results`」)から各関数へ渡す. 手元で torch を読み込まずに動かすため,`labremote` 以外のモジュールを import しない. 終了コード: 成功 0.ssh・リモートの失敗時はその終了コード(ssh の接続失敗は 255, @@ -52,8 +53,7 @@ EXIT_REMOTE_DIR_MISSING, EXIT_SESSION_EXISTS, EXIT_UNSAFE_PATH, - REMOTE_LOG_DIR, - REMOTE_RUNS_DIR, + REMOTE_LOG_DIR_NAME, build_job_env, build_job_script, build_kill_command, @@ -104,7 +104,7 @@ format_shared_warning, ) from labremote.transfer import copy_stream, extract_pull_archive, write_tar_stream -from labremote.whitelist import parse_find_listing, plan_pull, validate_run_id +from labremote.whitelist import has_pull_names, parse_find_listing, plan_pull, validate_run_id logger = logging.getLogger(__name__) @@ -136,8 +136,8 @@ # GPU なし(ONNX の書き出し) uv run labremote logs train1 -f # ログを追従 uv run labremote kill train1 # ジョブを止める - uv run labremote pull <実験ID> # 回収ホワイトリストのみ持ち帰る - uv run labremote pull <実験ID> --with-checkpoints # best.pth・ResUNet.onnx も持ち帰る + uv run labremote pull <実験ID> # 設定の results.pull の一覧だけ持ち帰る + uv run labremote pull <実験ID> --with-checkpoints # 重み(results.checkpoints.files)も持ち帰る tsm-train の実験 ID は,ジョブのログ(logs)の終了行(=== ... exit 0)の直前の行に出る. tsm-export の成否は終了行の exit の値で判断する(失敗時は PyTorch がグラフを大量に出しうる). @@ -380,6 +380,7 @@ """ command = build_probe_command( server.remote_dir, + results_dir=ctx.config.results.dir, observe_sec=threshold.observe_sec, sample_interval_ms=threshold.sample_interval_ms, ) @@ -570,6 +571,7 @@ ctx.config.push, config_path=ctx.config_path, labremote_dir=ctx.labremote_dir, + results_dir=ctx.config.results.dir, ) if not selection.entries: raise ValueError("送信するファイルが無い") @@ -728,8 +730,11 @@ # 移植元はデータの場所(TIAS_DATA_ROOT)をここで渡していた.TongueSegModel はバンドルだけを # 読み,場所は TIASDATA_BUNDLES(既定 ~/data/tiasdata)で決まるため渡さない(SPEC_03) path_env={}, + results_dir=ctx.config.results.dir, ) - remote_command = build_run_command(server.remote_dir, name, script) + remote_command = build_run_command( + server.remote_dir, name, script, results_dir=ctx.config.results.dir + ) if args.dry_run: _write_stdout( f"選んだ実行先: {_describe_target(server, gpu_index, state)}\n" @@ -759,7 +764,7 @@ _report_remote_failure(result, server) return _as_exit_code(result.rc) - log_path = f"{server.remote_dir}/{job_log_path(name)}" + log_path = f"{server.remote_dir}/{job_log_path(name, results_dir=ctx.config.results.dir)}" _write_stdout( f"ジョブを起動した: {name}({_describe_target(server, gpu_index)})\n" f" 環境変数: {' '.join(f'{k}={v}' for k, v in env.items())}\n" @@ -778,7 +783,12 @@ def _locate_log(ctx: _Context, name: str, server_name: str | None) -> ServerConfig: """ジョブログがあるサーバを探す(複数・0 台ならエラー).""" servers = _target_servers(ctx, server_name) - results = _query_servers(ctx, servers, lambda s: build_log_exists_command(s.remote_dir, name)) + results_dir = ctx.config.results.dir + results = _query_servers( + ctx, + servers, + lambda s: build_log_exists_command(s.remote_dir, name, results_dir=results_dir), + ) found: list[ServerConfig] = [] unreachable = 0 for server, result in zip(servers, results, strict=True): @@ -823,7 +833,13 @@ if args.lines < 0: raise ValueError("--lines は 0 以上を指定する") server = _locate_log(ctx, name, args.server) - command = build_logs_command(server.remote_dir, name, lines=args.lines, follow=args.follow) + command = build_logs_command( + server.remote_dir, + name, + results_dir=ctx.config.results.dir, + lines=args.lines, + follow=args.follow, + ) if args.follow: logger.info("%s のジョブ %s のログを追従する(Ctrl+C で終了)", server.name, name) return _follow(_ssh_argv(ctx, server, command, stdin=True)) @@ -851,7 +867,11 @@ [probe.server for probe in found], what=f"実行中のジョブ {name!r}", unreachable=unreachable ) result = _run_ssh( - _ssh_argv(ctx, server, build_kill_command(server.remote_dir, name)), + _ssh_argv( + ctx, + server, + build_kill_command(server.remote_dir, name, results_dir=ctx.config.results.dir), + ), timeout=ctx.query_timeout_sec, ) if result.rc == EXIT_NO_SESSION: @@ -872,7 +892,12 @@ def _locate_run(ctx: _Context, run_id: str, server_name: str | None) -> tuple[ServerConfig, bytes]: """RUN_ID のディレクトリがあるサーバを探し,そのファイル一覧を返す(複数・0 台ならエラー).""" servers = _target_servers(ctx, server_name) - results = _query_servers(ctx, servers, lambda s: build_pull_list_command(s.remote_dir, run_id)) + results_dir = ctx.config.results.dir + results = _query_servers( + ctx, + servers, + lambda s: build_pull_list_command(s.remote_dir, run_id, results_dir=results_dir), + ) found: list[tuple[ServerConfig, bytes]] = [] unreachable = 0 for server, result in zip(servers, results, strict=True): @@ -880,7 +905,7 @@ found.append((server, result.stdout)) elif result.rc == EXIT_UNSAFE_PATH: raise ValueError( - f"{server.name} の {REMOTE_RUNS_DIR}/{run_id} がリンクであるため回収しない" + f"{server.name} の {results_dir}/{run_id} がリンクであるため回収しない" ) elif result.rc != EXIT_NOT_FOUND: # 一覧の失敗理由(find の標準エラー)はファイル名を含みうるので表示しない @@ -926,20 +951,36 @@ def _cmd_pull(args: argparse.Namespace, ctx: _Context) -> int: - """pull サブコマンド: 実験結果を回収ホワイトリストに従って持ち帰る.""" + """pull サブコマンド: 実験結果のうち,設定の回収の一覧に一致するものだけを持ち帰る.""" run_id = validate_run_id(args.run_id) + results = ctx.config.results + if not has_pull_names(results, with_checkpoints=args.with_checkpoints): + # 一覧が空なら何も回収できない.頼まれた回収が 1 件もできないので,成功(0)にしない + # (スクリプトから呼んだときに気づけるようにする).接続する前に止め,設定を書く場所を示す + logger.error( + "設定の results.pull に回収する名前が書かれていないため,何も回収しない" + "(%s の results.pull.files・results.pull.dirs に書く)", + CONFIG_FILE_NAME, + ) + return 1 + if not results.pull.files and not results.pull.dirs: + logger.warning("設定の results.pull に回収する名前が書かれていない(重みだけを回収する)") server, listing = _locate_run(ctx, run_id, args.server) - plan = plan_pull(parse_find_listing(listing), run_id, with_checkpoints=args.with_checkpoints) + plan = plan_pull( + parse_find_listing(listing), run_id, results, with_checkpoints=args.with_checkpoints + ) if not plan.files: raise ValueError( f"{server.name} の実験 {run_id!r} に回収対象のファイルが無い" f"(回収しなかったファイル {plan.skipped} 件)" ) - dest = ctx.project_root / REMOTE_RUNS_DIR - logger.info("取得: %s の %s/%s → %s", server.name, REMOTE_RUNS_DIR, run_id, dest / run_id) + dest = ctx.project_root / results.dir + logger.info("取得: %s の %s/%s → %s", server.name, results.dir, run_id, dest / run_id) payload = b"".join(path.encode("utf-8", "surrogateescape") + b"\0" for path in plan.files) - argv = _ssh_argv(ctx, server, build_pull_tar_command(server.remote_dir), stdin=True) + argv = _ssh_argv( + ctx, server, build_pull_tar_command(server.remote_dir, results_dir=results.dir), stdin=True + ) start = time.monotonic() with tempfile.TemporaryFile() as archive: result = _receive_tar(argv, payload, archive) @@ -955,7 +996,7 @@ return result.rc try: extracted = extract_pull_archive( - archive, dest, run_id, with_checkpoints=args.with_checkpoints + archive, dest, run_id, results, with_checkpoints=args.with_checkpoints ) except tarfile.TarError as exc: raise ValueError("受け取ったアーカイブが壊れているため,何も展開せず中止した") from exc @@ -967,12 +1008,12 @@ skipped = f"回収しなかったファイル: {plan.skipped} 件" if plan.skipped_checkpoints: skipped += ( - f"(うち checkpoints/best.pth・ResUNet.onnx {plan.skipped_checkpoints} 件は" + f"(うち重み({results.checkpoints.dir}/ の下){plan.skipped_checkpoints} 件は" " --with-checkpoints で回収できる)" ) _write_stdout( f"取得完了: {extracted.files} ファイル / {_format_size(extracted.bytes)}" - f"({time.monotonic() - start:.1f} 秒)→ {REMOTE_RUNS_DIR}/{run_id}/\n{skipped}\n" + f"({time.monotonic() - start:.1f} 秒)→ {results.dir}/{run_id}/\n{skipped}\n" ) return 0 @@ -1042,8 +1083,9 @@ description=( "プロジェクトのルートの下のファイルを tar over ssh でサーバの remote_dir へ" "上書き展開する..git / .venv / .claude / キャッシュ・.env・リンク・" - f"{REMOTE_RUNS_DIR}/(ルートの直下)・設定ファイル・LabRemote 自身のフォルダは" - "常に送らない.ほかに送らないもの(データ・原本・重み等)は設定の push に書く." + "結果の置き場(設定の results.dir.既定は runs)・設定ファイル・LabRemote 自身の" + "フォルダは常に送らない." + "ほかに送らないもの(データ・原本・重み等)は設定の push に書く." ), ) p_push.add_argument( @@ -1058,7 +1100,8 @@ "GPU を選び(data_ready のサーバ全体を通して,まず未使用を,無ければ" "空き(利用者あり)を priority 順・GPU 番号順に探す)," "そのサーバへコードを送ってから remote_dir で `uv run ` を tmux で起動する." - f"出力は remote_dir/{REMOTE_LOG_DIR}/.log に追記され,接続が切れても継続する." + f"出力は remote_dir//{REMOTE_LOG_DIR_NAME}/.log に追記され" + "(results.dir は設定の結果の置き場.既定は runs),接続が切れても継続する." "コマンドは -- の後に書く." ), ) @@ -1145,22 +1188,29 @@ p_pull = sub.add_parser( "pull", parents=[common, server_opt], - help="実験結果を回収ホワイトリストに従って持ち帰る", + help="実験結果のうち,設定の回収の一覧に名前が一致するものだけを持ち帰る", description=( - "サーバの runs// のうち回収ホワイトリスト(config.yaml・history.csv・" - "metrics.json・log.txt・figures/*.png)に一致するファイルだけを" - "手元の runs// へ持ち帰る(同名ファイルは上書き)." - "重み(checkpoints/best.pth・checkpoints/ResUNet.onnx)は --with-checkpoints を" - "付けたときだけ.split.json・predictions.csv 等それ以外は回収しない." + "サーバの /// のうち,設定の results.pull に" + "名前が完全に一致する(大文字小文字も区別する)ファイルだけを,手元の" + "<ルート>/// へ持ち帰る(同名ファイルは上書き.results.dir の" + "既定は runs).results.pull.files は実験フォルダの直下のファイル名," + "results.pull.dirs は path の直下で拡張子が suffix のもの." + "重み(results.checkpoints.dir の直下の results.checkpoints.files)は" + " --with-checkpoints を付けたときだけ.一覧に無いものは回収しない" + "(回収しなかった件数だけを表示する)." ), ) - p_pull.add_argument("run_id", metavar="RUN_ID", help="実験 ID(runs/ 直下のディレクトリ名).") + p_pull.add_argument( + "run_id", + metavar="RUN_ID", + help="実験 ID(結果の置き場 results.dir の直下のディレクトリ名).", + ) p_pull.add_argument( "--with-checkpoints", "--checkpoints", dest="with_checkpoints", action="store_true", - help="重み(checkpoints/best.pth・checkpoints/ResUNet.onnx)も持ち帰る.", + help="重み(設定の results.checkpoints.files)も持ち帰る.", ) return parser.parse_args(argv) diff --git a/src/labremote/commands.py b/src/labremote/commands.py index b149964..709259c 100644 --- a/src/labremote/commands.py +++ b/src/labremote/commands.py @@ -34,8 +34,9 @@ {"CUDA_VISIBLE_DEVICES", "CUDA_DEVICE_ORDER", "PYTHONUNBUFFERED", GIT_COMMIT_ENV_VAR} ) -REMOTE_RUNS_DIR = "runs" -REMOTE_LOG_DIR = f"{REMOTE_RUNS_DIR}/_remote_logs" +# ジョブのログを置くフォルダの名前(結果の置き場 `results.dir` の直下).固定で,設定では変えない +# (SPEC_02「`results`」).設定の検証(`labremote.config`)も,この名前を一覧に書かせない +REMOTE_LOG_DIR_NAME = "_remote_logs" # リモートスクリプトが返す終了コード.ssh 自身の 255・tar の 1/2 と衝突しない値にする EXIT_REMOTE_DIR_MISSING = 90 @@ -380,16 +381,57 @@ ) -def job_log_path(name: str) -> str: +def _checked_results_dir(results_dir: str) -> str: + """結果の置き場(設定の `results.dir`.remote_dir 基準)を確かめて返す(クォート前). + + 設定を読む時点で検証済みの値を受け取る前提だが,サーバのコマンドに埋め込むため, + remote_dir の外を指す形(絶対パス・`~`・`..`・空の部分)でないことをここでも確かめる + (呼び出し側の取り違えで,別の場所でコマンドを実行させないため). + + Raises: + ValueError: 空・絶対パス・`~` 始まり・`.`・`..`・空の部分・バックスラッシュ・NUL を + 含む場合. + """ + parts = results_dir.split("/") + if ( + results_dir.startswith("~") + or "\\" in results_dir + or "\x00" in results_dir + or any(part in ("", ".", "..") for part in parts) + ): + raise ValueError(f"結果の置き場が不正である: {results_dir!r}") + return results_dir + + +def remote_log_dir(results_dir: str) -> str: + """ジョブのログの置き場(remote_dir 基準.クォート前)を返す. + + Args: + results_dir: 検証済みの結果の置き場(設定の `results.dir`). + + Returns: + `/_remote_logs`. + + Raises: + ValueError: 結果の置き場が remote_dir の外を指す形の場合. + """ + return f"{_checked_results_dir(results_dir)}/{REMOTE_LOG_DIR_NAME}" + + +def job_log_path(name: str, *, results_dir: str) -> str: """ジョブログのパス(remote_dir 基準.クォート前)を返す. Args: name: 検証済みのジョブ名(`validate_job_name`). + results_dir: 検証済みの結果の置き場(設定の `results.dir`). Returns: - `runs/_remote_logs/.log`. + `/_remote_logs/.log`. + + Raises: + ValueError: 結果の置き場が remote_dir の外を指す形の場合. """ - return f"{REMOTE_LOG_DIR}/{name}.log" + return f"{remote_log_dir(results_dir)}/{name}.log" def _tmux_target(name: str) -> str: @@ -400,7 +442,9 @@ return shlex.quote(f"={name}") -def build_probe_command(remote_dir: str, *, observe_sec: int, sample_interval_ms: int) -> str: +def build_probe_command( + remote_dir: str, *, results_dir: str, observe_sec: int, sample_interval_ms: int +) -> str: """tmux セッション・GPU の観測・計算プロセスとその所有者を 1 回の ssh で取るコマンドを返す. 出力の形式(`parse_probe_output` が解釈する): @@ -408,7 +452,7 @@ - `@@labremote-user <接続したユーザー名>`(`id -un`.GPU の利用者のうち自分を「自分」と 表示するため.設定にはユーザー名を書かないので,サーバで調べた名前だけで見分ける) - `@@labremote-sessions` の後に,tmux セッション 1 件につき 1 行.このツールのジョブログ - (`remote_dir/runs/_remote_logs/<名前>.log`)があるものは `job <名前>`,無いものは + (`remote_dir//_remote_logs/<名前>.log`)があるものは `job <名前>`,無いものは `other <名前>`(同じユーザーの別用途のセッション) - `@@labremote-gpus` の後に GPU の一覧(`nvidia-smi --query-gpu` の CSV),続けて `@@labremote-gpu-rc <終了コード>`(nvidia-smi が無ければ 127 で,以降の節は出ない) @@ -426,6 +470,7 @@ Args: remote_dir: リモートのプロジェクトルート. + results_dir: 検証済みの結果の置き場(設定の `results.dir`.引用して埋め込む). observe_sec: 観測秒数(0 なら観測せず瞬間値だけを取る). sample_interval_ms: 観測の間隔(ミリ秒). @@ -433,9 +478,9 @@ リモートで実行するシェルコマンド. Raises: - ValueError: 観測秒数が負,または間隔が 1 未満の場合. + ValueError: 観測秒数が負,間隔が 1 未満,または結果の置き場が不正な場合. """ - log_dir = f"{quote_remote_path(remote_dir)}/{REMOTE_LOG_DIR}" + log_dir = f"{quote_remote_path(remote_dir)}/{shlex.quote(remote_log_dir(results_dir))}" sessions = ( "tmux ls -F '#{session_name}' 2>/dev/null | while IFS= read -r s; do " f'if [ -f {log_dir}/"$s".log ]; then echo "{PROBE_JOB_PREFIX}$s"; ' @@ -516,10 +561,11 @@ gpu_index: int | None, env: Mapping[str, str], path_env: Mapping[str, str], + results_dir: str, ) -> str: """tmux セッション内で bash が実行するジョブ本体のスクリプトを返す. - 出力は `runs/_remote_logs/.log` に追記し(前回の同名ジョブのログも残す), + 出力は `/_remote_logs/.log` に追記し(前回の同名ジョブのログも残す), 開始行(サーバ名・GPU・日時)と終了コード行で挟む.標準入力は /dev/null にする (入力待ちで止まらないように).非対話 ssh では `~/.local/bin` が PATH に無いため, uv のディレクトリと `$HOME/.local/bin` を PATH に足す. @@ -535,16 +581,17 @@ env: ジョブに渡す環境変数(値はそのまま渡す). path_env: ジョブに渡す環境変数のうち,値がリモートのパス(`~` を `$HOME` に展開する) であるもの. + results_dir: 検証済みの結果の置き場(設定の `results.dir`). Returns: bash スクリプト(1 行). Raises: - ValueError: コマンドが空,またはジョブ名・環境変数名・パスが不正な場合. + ValueError: コマンドが空,またはジョブ名・環境変数名・パス・結果の置き場が不正な場合. """ if not command: raise ValueError("実行するコマンドが空である") - log = job_log_path(validate_job_name(name)) + log = job_log_path(validate_job_name(name), results_dir=results_dir) for key in [*env, *path_env]: validate_env_key(key) @@ -571,7 +618,7 @@ return "; ".join(statements) -def build_run_command(remote_dir: str, name: str, job_script: str) -> str: +def build_run_command(remote_dir: str, name: str, job_script: str, *, results_dir: str) -> str: """ジョブ本体を tmux の新規セッション(デタッチ状態)で起動するコマンドを返す. 同名セッションが既にあれば起動せず `EXIT_SESSION_EXISTS` で終わる. @@ -582,18 +629,19 @@ remote_dir: リモートのプロジェクトルート. name: ジョブ名(tmux セッション名). job_script: `build_job_script` が返したスクリプト. + results_dir: 検証済みの結果の置き場(設定の `results.dir`.ログの置き場を作る). Returns: リモートで実行するシェルコマンド. Raises: - ValueError: ジョブ名が不正な場合. + ValueError: ジョブ名・結果の置き場が不正な場合. """ name = validate_job_name(name) inner = "bash -c " + shlex.quote(job_script) statements = [ _cd_command(remote_dir), - f"mkdir -p {REMOTE_LOG_DIR} || exit 1", + f"mkdir -p {shlex.quote(remote_log_dir(results_dir))} || exit 1", f"if tmux has-session -t {_tmux_target(name)} 2>/dev/null; then " f"echo 'labremote: tmux session already exists:' {shlex.quote(name)} >&2; " f"exit {EXIT_SESSION_EXISTS}; fi", @@ -602,26 +650,29 @@ return "; ".join(statements) -def build_log_exists_command(remote_dir: str, name: str) -> str: +def build_log_exists_command(remote_dir: str, name: str, *, results_dir: str) -> str: """ジョブログがあれば 0,無ければ `EXIT_NOT_FOUND` で終わるコマンドを返す. Args: remote_dir: リモートのプロジェクトルート. name: ジョブ名. + results_dir: 検証済みの結果の置き場(設定の `results.dir`). Returns: リモートで実行するシェルコマンド. Raises: - ValueError: ジョブ名が不正な場合. + ValueError: ジョブ名・結果の置き場が不正な場合. """ - log = shlex.quote(job_log_path(validate_job_name(name))) + log = shlex.quote(job_log_path(validate_job_name(name), results_dir=results_dir)) return ( f"cd {quote_remote_path(remote_dir)} 2>/dev/null && [ -f {log} ] || exit {EXIT_NOT_FOUND}" ) -def build_logs_command(remote_dir: str, name: str, *, lines: int, follow: bool) -> str: +def build_logs_command( + remote_dir: str, name: str, *, results_dir: str, lines: int, follow: bool +) -> str: """ジョブログの末尾を表示する(follow なら追従する)コマンドを返す. 追従モードでは,ssh の標準入力が閉じたら(手元で Ctrl+C・終了したら)tail を止める. @@ -630,6 +681,7 @@ Args: remote_dir: リモートのプロジェクトルート. name: ジョブ名. + results_dir: 検証済みの結果の置き場(設定の `results.dir`). lines: 表示する末尾の行数(0 以上). follow: True なら追記を追従する. @@ -637,11 +689,11 @@ リモートで実行するシェルコマンド. Raises: - ValueError: ジョブ名が不正,または lines が負の場合. + ValueError: ジョブ名・結果の置き場が不正,または lines が負の場合. """ if lines < 0: raise ValueError(f"表示行数は 0 以上でなければならない({lines})") - log = shlex.quote(job_log_path(validate_job_name(name))) + log = shlex.quote(job_log_path(validate_job_name(name), results_dir=results_dir)) check = ( f"[ -f {log} ] || {{ echo 'labremote: log not found:' {log} >&2; exit {EXIT_NOT_FOUND}; }}" ) @@ -652,7 +704,7 @@ return "; ".join([_cd_command(remote_dir), check, tail]) -def build_kill_command(remote_dir: str, name: str) -> str: +def build_kill_command(remote_dir: str, name: str, *, results_dir: str) -> str: """ジョブの tmux セッションを終了し,ログにその旨を追記するコマンドを返す. tmux がセッションを閉じるとジョブの bash は SIGHUP で終わり,自分では終了行を @@ -661,16 +713,17 @@ Args: remote_dir: リモートのプロジェクトルート. name: ジョブ名. + results_dir: 検証済みの結果の置き場(設定の `results.dir`). Returns: リモートで実行するシェルコマンド. Raises: - ValueError: ジョブ名が不正な場合. + ValueError: ジョブ名・結果の置き場が不正な場合. """ name = validate_job_name(name) target = _tmux_target(name) - log = shlex.quote(job_log_path(name)) + log = shlex.quote(job_log_path(name, results_dir=results_dir)) statements = [ f"tmux has-session -t {target} 2>/dev/null || " f"{{ echo 'labremote: no such tmux session:' {shlex.quote(name)} >&2; " @@ -682,25 +735,30 @@ return "; ".join(statements) -def build_pull_list_command(remote_dir: str, run_id: str) -> str: - """`runs//` 配下のディレクトリ以外のエントリを種類付きで列挙するコマンドを返す. +def build_pull_list_command(remote_dir: str, run_id: str, *, results_dir: str) -> str: + """`//` 配下のディレクトリ以外のエントリを種類付きで列挙するコマンドを返す. - 出力は `<種類> ` を NUL で区切ったもの(GNU find の `-printf '%y %p\\0'`. - 種類は `f` 通常ファイル・`l` シンボリックリンク 等).回収対象の絞り込みは手元の - `plan_pull` が行い,ここでは何も送らない(一覧はファイル名を含むため表示しない). + 出力は `<種類> ` を NUL で区切ったもの + (GNU find の `-printf '%y %p\\0'`.種類は `f` 通常ファイル・`l` シンボリックリンク 等). + 回収対象の絞り込みは手元の `plan_pull` が行い,ここでは何も送らない + (一覧はファイル名を含むため表示しない). RUN_ID のディレクトリが無ければ `EXIT_NOT_FOUND`,リンクなら `EXIT_UNSAFE_PATH` で終わる. Args: remote_dir: リモートのプロジェクトルート. run_id: `validate_run_id` で検証済みの RUN_ID. + results_dir: 検証済みの結果の置き場(設定の `results.dir`.引用して埋め込む). Returns: リモートで実行するシェルコマンド. + + Raises: + ValueError: 結果の置き場が不正な場合. """ run = shlex.quote(run_id) + results = shlex.quote(_checked_results_dir(results_dir)) statements = [ - f"cd {quote_remote_path(remote_dir)}/{REMOTE_RUNS_DIR} 2>/dev/null" - f" || exit {EXIT_NOT_FOUND}", + f"cd {quote_remote_path(remote_dir)}/{results} 2>/dev/null || exit {EXIT_NOT_FOUND}", f"if [ -L {run} ]; then exit {EXIT_UNSAFE_PATH}; fi", f"[ -d {run} ] || exit {EXIT_NOT_FOUND}", f"find {run} -mindepth 1 ! -type d -printf '%y %p\\0'", @@ -708,18 +766,23 @@ return "; ".join(statements) -def build_pull_tar_command(remote_dir: str) -> str: - """標準入力の NUL 区切りのパス(`runs/` 基準)だけを tar ストリームで書き出すコマンドを返す. +def build_pull_tar_command(remote_dir: str, *, results_dir: str) -> str: + """標準入力の NUL 区切りのパス(`results_dir` 基準)だけを tar で書き出すコマンドを返す. `--no-recursion` で指定したパス以外を含めない(ディレクトリを渡されても中身を入れない). Args: remote_dir: リモートのプロジェクトルート. + results_dir: 検証済みの結果の置き場(設定の `results.dir`.引用して埋め込む). Returns: リモートで実行するシェルコマンド. + + Raises: + ValueError: 結果の置き場が不正な場合. """ + results = shlex.quote(_checked_results_dir(results_dir)) return ( - f"cd {quote_remote_path(remote_dir)}/{REMOTE_RUNS_DIR} || exit {EXIT_NOT_FOUND}; " + f"cd {quote_remote_path(remote_dir)}/{results} || exit {EXIT_NOT_FOUND}; " "tar --null --no-recursion -T - -cf -" ) diff --git a/src/labremote/config.py b/src/labremote/config.py index 526da1e..d2d51e4 100644 --- a/src/labremote/config.py +++ b/src/labremote/config.py @@ -6,6 +6,10 @@ 「送信」)は設定のスキーマに入れない.固定の除外の名前は,`push.partial` の検証と `labremote.files` の選別の両方で使うため,このモジュールの定数に置く (`labremote.files` がこのモジュールを import する向きのため). +`results` の節(結果の置き場と,回収・破棄の一覧)は SPEC_02「`results`」に従う.一覧に書けるのは +名前だけで,回収の形と判定(SPEC_01「安全の枠」の「回収」)は `labremote.whitelist` で固定している. +手元のファイル名として安全かの規則は,回収の判定と同じ +`labremote.whitelist.is_safe_local_name` を使う. """ from __future__ import annotations @@ -29,7 +33,7 @@ ) from labremote.commands import ( - REMOTE_RUNS_DIR, + REMOTE_LOG_DIR_NAME, quote_remote_path, reserved_env_vars, validate_env_key, @@ -37,6 +41,7 @@ validate_git_commit_env, validate_ssh_token, ) +from labremote.whitelist import is_safe_local_name # 設定ファイルの名前.このファイルのあるフォルダをプロジェクトのルートとする CONFIG_FILE_NAME = "labremote.yaml" @@ -79,9 +84,15 @@ FIXED_EXCLUDED_DIR_NAMES = frozenset( fold_push_parts((".git", ".venv", ".claude", "__pycache__", ".pytest_cache", ".ruff_cache")) ) -# ルートの直下で送らない名前.結果の置き場はサーバ側の結果を上書きしないため, -# labremote.yaml はサーバでは使わないため(2026-11-19 のユーザー判断) -FIXED_EXCLUDED_ROOT_ENTRIES = frozenset(fold_push_parts((REMOTE_RUNS_DIR, CONFIG_FILE_NAME))) +# ルートの直下で送らない名前.labremote.yaml はサーバでは使わないため(2026-11-19 のユーザー判断). +# 結果の置き場(設定の `results.dir`)も固定の除外だが,設定で場所が決まるため,ここではなく +# `labremote.files.PushRules` が設定の値から除外する(サーバ側の結果を上書きしないため) +FIXED_EXCLUDED_ROOT_ENTRIES = frozenset(fold_push_parts((CONFIG_FILE_NAME,))) + +# 設定の `results` の既定値(SPEC_02「`results`」).結果の置き場はルート・remote_dir からの相対パス +DEFAULT_RESULTS_DIR = "runs" +# 重みを置くフォルダ(実験フォルダの直下) +DEFAULT_CHECKPOINTS_DIR = "checkpoints" # `jump_host` を上書きする.空文字なら直接接続(研究室 LAN 内にいるとき) JUMP_ENV_VAR = "LABREMOTE_JUMP" @@ -95,9 +106,10 @@ _SERVER_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") _PROJECT_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") _TRUE_VALUES = frozenset({"1", "true", "yes"}) -# push の設定に書く名前に使えない文字.パスの区切り(1 つの名前に限るため)・ワイルドカード -# (名前は完全一致で比べるため,書いても効かないことに気づけるよう拒否する)・NUL -_PUSH_NAME_FORBIDDEN_CHARS = frozenset("/\\*?[\0") +# push・results の設定に書く名前に使えない文字.パスの区切り(1 つの名前に限るため)・ワイルドカード +# (名前は完全一致で比べるため,書いても効かないことに気づけるよう拒否する)・NUL. +# 送信の除外と回収の一覧で同じ規則のため,1 つの定数にする(片方だけ直して食い違わないように) +_CONFIG_NAME_FORBIDDEN_CHARS = frozenset("/\\*?[\0") class _StrictModel(BaseModel): @@ -174,7 +186,7 @@ if value != value.strip(): # `data ` のような書き間違いは実際の `data` に一致せず,除外が効かないまま送るため拒否する raise ValueError(f"{where}: 前後に空白のある名前は書けない: {value!r}") - if _PUSH_NAME_FORBIDDEN_CHARS.intersection(value): + if _CONFIG_NAME_FORBIDDEN_CHARS.intersection(value): raise ValueError( f"{where}: / \\ とワイルドカード(* ? [)は書けない(1 つの名前を完全一致で比べる): " f"{value!r}" @@ -295,6 +307,285 @@ return self +def _check_result_name(value: str, *, where: str) -> str: + """回収・破棄の一覧(`results`)に書く 1 つの名前を検証して返す. + + 手元のファイル名になる名前のため,Windows で別の場所を指しうるものは + `labremote.whitelist.is_safe_local_name`(回収の判定と同じ規則)で拒否する. + + Raises: + ValueError: 空・`.`・`..`,前後に空白がある,パスの区切り・ワイルドカード・NUL を含む, + Windows で別の場所を指しうる,またはジョブのログの置き場の名前の場合. + """ + if value in {"", ".", ".."}: + raise ValueError(f"{where}: 空・.・.. は書けない(1 つの名前を書く): {value!r}") + if value != value.strip(): + # `config.yaml ` のような書き間違いは実際の名前に一致せず,気づかないまま回収されないため + raise ValueError(f"{where}: 前後に空白のある名前は書けない: {value!r}") + if _CONFIG_NAME_FORBIDDEN_CHARS.intersection(value): + # 名前は完全一致で比べるため,ワイルドカードは書いても効かない.誤解させないよう拒否する + raise ValueError( + f"{where}: / \\ とワイルドカード(* ? [)・NUL は書けない" + f"(1 つの名前を完全一致で比べる): {value!r}" + ) + if not is_safe_local_name(value): + # 手元(Windows)で見かけと違う場所に書かれる名前は,回収の判定でも必ず拒否されるため + raise ValueError( + f"{where}: Windows で別の場所を指しうる名前は書けない" + f'(< > : " | の文字・制御文字・末尾の . と空白・CON や NUL 等の予約名): {value!r}' + ) + if _fold_result_name(value) == REMOTE_LOG_DIR_NAME: + raise ValueError( + f"{where}: {REMOTE_LOG_DIR_NAME} はジョブのログの置き場の名前のため書けない: {value!r}" + ) + return value + + +def _check_result_path(value: str, *, where: str) -> str: + """`results` に書く相対パス(`/` 区切り)を検証して返す. + + Raises: + ValueError: 絶対パス,または部分のどれかが `_check_result_name` を通らない場合. + """ + # 絶対パス(/x・C:/x・\x)を拒否し,基準のフォルダの下の場所だけを指せるようにする + if value.startswith(("/", "\\")) or (len(value) >= 2 and value[1] == ":"): + raise ValueError(f"{where} に絶対パスは書けない: {value!r}") + for part in value.split("/"): + _check_result_name(part, where=f"{where} {value!r}") + return value + + +def _check_result_names(values: tuple[str, ...], *, where: str) -> tuple[str, ...]: + for value in values: + _check_result_name(value, where=where) + _reject_duplicates(values, where=where) + return values + + +def _reject_duplicates(values: Iterable[Any], *, where: str) -> None: + """一覧の中の重複を拒否する. + + 手元の Windows では大文字小文字だけが違う名前が同じファイルになり,回収で互いに上書きするため, + 小文字にして比べる(書いた名前どうしの比較で,拒否する側に倒す). + """ + seen: set[Any] = set() + for value in values: + key = _fold_result_key(value) + if key in seen: + raise ValueError(f"{where} に同じ名前が 2 回書かれている: {value!r}") + seen.add(key) + + +def _fold_result_name(value: str) -> str: + """`results` の検証(重複・重なり)で比べるために,名前・パスを小文字にそろえる. + + 設定の検証で書いた名前どうしを比べるときだけ使う(手元の Windows では大文字小文字だけが違う + 名前が同じ場所になるため,拒否する側に倒す).回収の判定(`labremote.whitelist.is_pull_allowed`) + は大文字小文字を区別して比べるため,そちらには使わない(使うと回収するものが増える). + """ + return value.lower() + + +def _fold_result_key(value: Any) -> Any: + if isinstance(value, ResultDirPattern): + return (_fold_result_name(value.path), _fold_result_name(value.suffix)) + return _fold_result_name(value) + + +def _is_same_or_inside(path: str, base: str) -> bool: + """path が base と同じ場所かその中か(小文字にして比べる.拒否する側に倒すため).""" + path_parts = _fold_result_name(path).split("/") + base_parts = _fold_result_name(base).split("/") + return path_parts[: len(base_parts)] == base_parts + + +class ResultDirPattern(_StrictModel): + """「`path` の直下で,拡張子が `suffix` のもの」1 件(`results.pull.dirs`・`discard.dirs`). + + Attributes: + path: 実験フォルダからの相対パス(`/` 区切り).下の階層は対象にしない. + suffix: `.` で始まる拡張子(大文字小文字を区別して比べる). + """ + + path: StrictStr + suffix: StrictStr + + @field_validator("path") + @classmethod + def _check_path(cls, value: str) -> str: + return _check_result_path(value, where="results の dirs の path") + + @field_validator("suffix") + @classmethod + def _check_suffix(cls, value: str) -> str: + # `.` だけは全ファイルに当たり,`.tar.gz` のような点を 2 つ以上含む書き方は + # 「拡張子」の範囲を超えるため,どちらも拒否する(迷ったら回収しない側に倒す) + if not value.startswith(".") or value.count(".") != 1 or len(value) < 2: + raise ValueError( + "results の dirs の suffix は,. で始まる 1 つの拡張子で書く" + f"(.png 等.. だけ・.tar.gz のような書き方はできない): {value!r}" + ) + _check_result_name(value, where="results の dirs の suffix") + return value + + +class ResultList(_StrictModel): + """回収(`results.pull`)または破棄(`results.discard`)の一覧. + + Attributes: + files: 実験フォルダの直下のファイル名. + dirs: 「`path` の直下で,拡張子が `suffix` のもの」. + """ + + files: tuple[StrictStr, ...] = () + dirs: tuple[ResultDirPattern, ...] = () + + @field_validator("files") + @classmethod + def _check_files(cls, value: tuple[str, ...]) -> tuple[str, ...]: + return _check_result_names(value, where="results の files") + + @field_validator("dirs") + @classmethod + def _check_dirs(cls, value: tuple[ResultDirPattern, ...]) -> tuple[ResultDirPattern, ...]: + _reject_duplicates(value, where="results の dirs") + return value + + +class CheckpointsConfig(_StrictModel): + """重みの回収の設定(`results.checkpoints`). + + Attributes: + dir: 重みを置くフォルダ(実験フォルダの直下の 1 つの名前). + files: `--with-checkpoints` を付けたときだけ回収する,`dir` の直下のファイル名. + """ + + dir: StrictStr = DEFAULT_CHECKPOINTS_DIR + files: tuple[StrictStr, ...] = () + + @field_validator("dir") + @classmethod + def _check_dir(cls, value: str) -> str: + return _check_result_name(value, where="results.checkpoints.dir") + + @field_validator("files") + @classmethod + def _check_files(cls, value: tuple[str, ...]) -> tuple[str, ...]: + return _check_result_names(value, where="results.checkpoints.files") + + +class ResultsConfig(_StrictModel): + """結果の置き場と,回収・破棄の一覧(SPEC_02「`results`」). + + 一覧に書けるのは名前だけで,回収の形(直下のファイル名・フォルダの直下の拡張子・重み)と + 判定の規則(完全一致・二重の確認)は `labremote.whitelist` で固定している + (SPEC_01「安全の枠」). + 節は省略でき,省略したときは回収の一覧が空になる(何も回収しない). + + Attributes: + dir: 結果の置き場(ルート・remote_dir からの相対パス.`/` 区切り). + pull: 回収する名前の一覧. + checkpoints: 重みの置き場と,明示したときだけ回収する名前. + discard: 回収せずに消してよい名前の一覧(`clean` で使う.今は読み込みと検証だけ). + """ + + dir: StrictStr = DEFAULT_RESULTS_DIR + pull: ResultList = Field(default_factory=ResultList) + checkpoints: CheckpointsConfig = Field(default_factory=CheckpointsConfig) + discard: ResultList = Field(default_factory=ResultList) + + @field_validator("dir") + @classmethod + def _check_dir(cls, value: str) -> str: + _check_result_path(value, where="results.dir") + parts = value.split("/") + # 固定の除外の中は,送信の選別でも入らない場所のため,結果の置き場にさせない + for part in fold_push_parts(parts): + if part in FIXED_EXCLUDED_DIR_NAMES: + raise ValueError( + f"results.dir {value!r} は固定の除外のフォルダ({part!r})の中を指す" + ) + if fold_push_name(parts[0]) in FIXED_EXCLUDED_ROOT_ENTRIES: + raise ValueError(f"results.dir {value!r} は設定ファイルの場所を指す") + return value + + @model_validator(mode="after") + def _check_lists(self) -> ResultsConfig: + # 一覧どうしの重なりの検査.どれも小文字にして比べる(`_fold_result_name`.拒否する側に + # 倒す).最初に見つかった問題で止めるため,検査の順序(=出すエラー)はこの並びで決まる + self._check_pull_dirs() + self._check_pull_files_not_checkpoints_dir() + self._check_checkpoints_files_not_in_pull() + self._check_discard_files_not_in_pull() + self._check_discard_dirs() + return self + + def _folded_pull_files(self) -> set[str]: + return {_fold_result_name(name) for name in self.pull.files} + + def _check_pull_dirs(self) -> None: + checkpoints_dir = self.checkpoints.dir + pull_files = self._folded_pull_files() + for item in self.pull.dirs: + # 重みを pull の一覧に紛れ込ませない(重みは --with-checkpoints のときだけ回収する) + if _is_same_or_inside(item.path, checkpoints_dir): + raise ValueError( + f"results.pull.dirs の path {item.path!r} は,重みの置き場" + f"(results.checkpoints.dir: {checkpoints_dir!r})と同じ場所かその中を指す" + ) + # 直下のファイル名とフォルダの名前が同じだと,どちらとして回収するかが曖昧になる + if _fold_result_name(item.path.split("/")[0]) in pull_files: + raise ValueError( + f"results.pull.dirs の path {item.path!r} は,results.pull.files の名前と重なる" + ) + + def _check_pull_files_not_checkpoints_dir(self) -> None: + # 重みの置き場の名前を直下のファイル名として書かせない(重みと取り違えないため) + checkpoints_dir = _fold_result_name(self.checkpoints.dir) + for name in self.pull.files: + if _fold_result_name(name) == checkpoints_dir: + raise ValueError( + f"results.pull.files の {name!r} は,重みの置き場" + "(results.checkpoints.dir)と同じ名前のため書けない" + ) + + def _check_checkpoints_files_not_in_pull(self) -> None: + # 重みの名前を実験フォルダの直下からも回収できると,--with-checkpoints 無しで持ち帰りうる + pull_files = self._folded_pull_files() + for name in self.checkpoints.files: + if _fold_result_name(name) in pull_files: + raise ValueError( + f"results.checkpoints.files の {name!r} は results.pull.files にも書かれている" + "(重みは checkpoints.files にだけ書く)" + ) + + def _check_discard_files_not_in_pull(self) -> None: + # 回収と破棄を両立させない(どちらとして扱うかが曖昧になり,回収前に消しうるため) + pull_files = self._folded_pull_files() + for name in self.discard.files: + if _fold_result_name(name) in pull_files: + raise ValueError( + f"{name!r} が results.pull.files と results.discard.files の両方に書かれている" + ) + + def _check_discard_dirs(self) -> None: + checkpoints_dir = self.checkpoints.dir + pull_dirs = {_fold_result_key(item) for item in self.pull.dirs} + for item in self.discard.dirs: + # 回収と破棄を両立させない(files と同じ理由) + if _fold_result_key(item) in pull_dirs: + raise ValueError( + f"path {item.path!r}・suffix {item.suffix!r} が results.pull.dirs と" + " results.discard.dirs の両方に書かれている" + ) + # 重みを捨てるのは,その場で --discard-checkpoints を付けたときだけ + if _is_same_or_inside(item.path, checkpoints_dir): + raise ValueError( + f"results.discard.dirs の path {item.path!r} は,重みの置き場" + f"(results.checkpoints.dir: {checkpoints_dir!r})と同じ場所かその中を指す" + ) + + class GpuFreeThreshold(_StrictModel): """GPU を「空き」とみなす閾値と,判定前の観測の設定. @@ -379,11 +670,13 @@ gpu_free: 空き判定の閾値. servers: 計算サーバの一覧(1 件以上.名前は重複不可). push: 送信の設定(固定の除外に足す除外). + results: 結果の置き場と,回収・破棄の一覧(省略時は既定.回収の一覧は空). """ project: ProjectConfig run: RunConfig = Field(default_factory=RunConfig) push: PushConfig + results: ResultsConfig = Field(default_factory=ResultsConfig) jump_host: str | None = None connect_timeout_sec: StrictInt = Field(default=15, ge=1) gpu_free: GpuFreeThreshold = Field(default_factory=GpuFreeThreshold) @@ -422,6 +715,36 @@ return self @model_validator(mode="after") + def _check_results_with_push(self) -> RemoteConfig: + results = self.results + # 重みの拡張子(push.exclude_suffixes.小文字で持つ)を pull の一覧に紛れ込ませない. + # 重みは results.checkpoints.files にだけ書け,--with-checkpoints のときだけ回収する + weight_suffixes = self.push.exclude_suffixes + for name in results.pull.files: + if _fold_result_name(name).endswith(weight_suffixes): + raise ValueError( + f"results.pull.files の {name!r} は push.exclude_suffixes の拡張子を持つ" + "(重みは results.checkpoints.files に書く)" + ) + for item in results.pull.dirs: + suffix = _fold_result_name(item.suffix) + # 一方が他方の末尾なら,その拡張子のファイルを pull.dirs で回収しうる + # (exclude_suffixes の .tar.gz に対する suffix の .gz 等) + if any(suffix.endswith(w) or w.endswith(suffix) for w in weight_suffixes): + raise ValueError( + f"results.pull.dirs の suffix {item.suffix!r} は push.exclude_suffixes の" + "拡張子と重なる(重みは results.checkpoints.files に書く)" + ) + # 結果の置き場は送らないため,その中を partial で指すのは書き間違いとして拒否する + for partial in self.push.partial: + if _is_same_or_inside(partial.path, results.dir): + raise ValueError( + f"push.partial の path {partial.path!r} は結果の置き場" + f"(results.dir: {results.dir!r})と同じ場所かその中を指す(そこは送らない)" + ) + return self + + @model_validator(mode="after") def _check_reserved_env(self) -> RemoteConfig: # GPU の割り当てと実験の記録を設定で上書きさせない(SPEC_01「名前と値の検証」) reserved = self.reserved_env_vars() diff --git a/src/labremote/files.py b/src/labremote/files.py index 762500f..ed46773 100644 --- a/src/labremote/files.py +++ b/src/labremote/files.py @@ -17,7 +17,8 @@ 当たらなかったものだけをリンクかどうか調べる(除外したフォルダの中のリンクは報告しない). 1. 固定の除外(`_is_fixed_excluded`): どの階層でも送らないフォルダ名,ルートの直下で送らない名前, - 場所で決まるもの(設定ファイル・LabRemote 自身のフォルダ),`.env`・`.env.*` + 結果の置き場(設定の `results.dir`.ルートからの相対パス),場所で決まるもの(設定ファイル・ + LabRemote 自身のフォルダ),`.env`・`.env.*` 2. 設定の除外(`_is_config_excluded`): `exclude_root`・`exclude_dirs`・`exclude_suffixes` 3. `partial`(`_is_outside_partial_include`): `path` の直下で `include` に無いもの 4. リンク(`_walk_files`): 1〜3 に当たらなかったシンボリックリンク・ジャンクション @@ -33,6 +34,7 @@ from pathlib import Path, PurePosixPath from labremote.config import ( + DEFAULT_RESULTS_DIR, FIXED_EXCLUDED_DIR_NAMES, FIXED_EXCLUDED_ROOT_ENTRIES, PushConfig, @@ -94,6 +96,8 @@ partial: 一部だけ送るフォルダ(比べる形にした `path` の各部分と,`include` の組). excluded_paths: 固定の除外のうち場所で決まるもの(読み込んだ設定ファイル・LabRemote 自身のフォルダ)の,ルートからの相対パスを比べる形にして分けたもの. + results_dir: 固定の除外の結果の置き場(設定の `results.dir`)を,比べる形にして + 分けたもの.`output/runs` のように複数の部分を持てるため,ルートからの相対パスで持つ. """ exclude_root: frozenset[str] = frozenset() @@ -101,6 +105,7 @@ exclude_suffixes: tuple[str, ...] = () partial: tuple[tuple[tuple[str, ...], frozenset[str]], ...] = () excluded_paths: frozenset[tuple[str, ...]] = frozenset() + results_dir: tuple[str, ...] = fold_push_parts(DEFAULT_RESULTS_DIR.split("/")) @classmethod def from_push( @@ -108,12 +113,14 @@ push: PushConfig | None = None, *, excluded_paths: Iterable[tuple[str, ...]] = (), + results_dir: str = DEFAULT_RESULTS_DIR, ) -> PushRules: """設定の `push` から規則を作る. Args: push: 設定の `push`.None なら設定の除外は無し(固定の除外だけ). excluded_paths: 固定の除外のうち場所で決まるもの(ルートからの相対パスの各部分). + results_dir: 結果の置き場(設定の `results.dir`.ルートからの相対パス). Returns: 規則. @@ -127,6 +134,7 @@ (fold_push_parts(item.parts), frozenset(item.include)) for item in push.partial ), excluded_paths=frozenset(fold_push_parts(parts) for parts in excluded_paths), + results_dir=fold_push_parts(results_dir.split("/")), ) def is_excluded(self, rel_path: str, *, is_dir: bool = False) -> bool: @@ -159,6 +167,9 @@ return True if folded[0] in FIXED_EXCLUDED_ROOT_ENTRIES: return True + # 結果の置き場は,サーバ側の結果を上書きしないため,その場所とその中を送らない + if folded[: len(self.results_dir)] == self.results_dir: + return True # 設定ファイル・LabRemote 自身のフォルダは,その場所とその中を送らない if any(folded[: len(path)] == path for path in self.excluded_paths): return True @@ -208,6 +219,7 @@ *, config_path: Path | None = None, labremote_dir: Path | None = None, + results_dir: str = DEFAULT_RESULTS_DIR, ) -> PushRules: """ルートと設定の `push` から,送らないものの規則を作る. @@ -218,6 +230,8 @@ labremote_dir: LabRemote 自身のフォルダ(実行中の `labremote` パッケージが入っている リポジトリ).ルートの下にあれば,フォルダ全体を送らない.ルートそのもの・ルートの外 なら何もしない. + results_dir: 結果の置き場(設定の `results.dir`.ルートからの相対パス).その場所と + その中を送らない. Returns: 規則. @@ -231,7 +245,7 @@ ) if parts is not None ] - return PushRules.from_push(push, excluded_paths=excluded) + return PushRules.from_push(push, excluded_paths=excluded, results_dir=results_dir) def is_link(path: Path) -> bool: @@ -302,6 +316,7 @@ *, config_path: Path | None = None, labremote_dir: Path | None = None, + results_dir: str = DEFAULT_RESULTS_DIR, ) -> PushSelection: """送信するファイルを選び,送らなかったリンクと合わせて返す. @@ -310,13 +325,18 @@ push: 設定の `push`.None なら設定の除外は無し(固定の除外だけ). config_path: 読み込んだ設定ファイル(`build_push_rules` を参照). labremote_dir: LabRemote 自身のフォルダ(`build_push_rules` を参照). + results_dir: 結果の置き場(設定の `results.dir`.`build_push_rules` を参照). Returns: arcname 順に並べた送信対象と,送らなかったリンク. """ resolved_root = root.resolve() rules = build_push_rules( - resolved_root, push, config_path=config_path, labremote_dir=labremote_dir + resolved_root, + push, + config_path=config_path, + labremote_dir=labremote_dir, + results_dir=results_dir, ) skipped_links: list[str] = [] entries = sorted( @@ -331,6 +351,7 @@ *, config_path: Path | None = None, labremote_dir: Path | None = None, + results_dir: str = DEFAULT_RESULTS_DIR, ) -> list[PushEntry]: """送信するファイルの一覧を作る(リンクは含まない.`select_push_files` を参照). @@ -339,9 +360,16 @@ push: 設定の `push`. config_path: 読み込んだ設定ファイル. labremote_dir: LabRemote 自身のフォルダ. + results_dir: 結果の置き場(設定の `results.dir`). Returns: arcname 順に並べた送信対象. """ - selection = select_push_files(root, push, config_path=config_path, labremote_dir=labremote_dir) + selection = select_push_files( + root, + push, + config_path=config_path, + labremote_dir=labremote_dir, + results_dir=results_dir, + ) return list(selection.entries) diff --git a/src/labremote/transfer.py b/src/labremote/transfer.py index edfd054..01f6754 100644 --- a/src/labremote/transfer.py +++ b/src/labremote/transfer.py @@ -3,7 +3,8 @@ Windows には rsync が無いため,Python の tarfile でストリームを作り `ssh ... 'tar -x ...'` の 標準入力へ流す(push).pull は ssh の標準出力をいったん一時ファイルに受け取り, 全メンバーを検査してから展開する(ストリームのまま展開すると,問題のメンバーに当たる前の -ファイルが展開済みになってしまうため.SPEC_03「pull」の二重の防御). +ファイルが展開済みになってしまうため.SPEC_01「安全の枠」の「回収」の二重の確認).検査は, +サーバの一覧の絞り込み(`labremote.whitelist.plan_pull`)と同じ判定(`is_pull_allowed`)を使う. TIASJudgeModel の `tias_judge_model.remote.transfer` の移植.push の tar はリンクを辿らない (移植元は `dereference=True` でリンク先の中身を送っていた.送信対象の選別でリンクは除いて @@ -16,11 +17,14 @@ from collections.abc import Sequence from dataclasses import dataclass from pathlib import Path -from typing import BinaryIO +from typing import TYPE_CHECKING, BinaryIO from labremote.files import PushEntry, is_link from labremote.whitelist import check_pull_members +if TYPE_CHECKING: + from labremote.config import ResultsConfig + _ENCODING = "utf-8" _COPY_CHUNK = 1024 * 1024 @@ -112,7 +116,12 @@ def extract_pull_archive( - archive: BinaryIO, dest: Path, run_id: str, *, with_checkpoints: bool + archive: BinaryIO, + dest: Path, + run_id: str, + results: ResultsConfig, + *, + with_checkpoints: bool, ) -> ExtractResult: """回収した tar(シーク可能なファイル)の全メンバーを検査し,問題が無ければ dest へ展開する. @@ -122,9 +131,11 @@ Args: archive: tar を書き込んだ一時ファイル(読み出し位置は問わない). - dest: 展開先(手元の `runs/`.`/...` がその下にできる.同名ファイルは上書き). + dest: 展開先(手元の `<ルート>//`.`/...` がその下にできる. + 同名ファイルは上書き). run_id: 検証済みの RUN_ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)を受け入れるか. + results: 検証済みの設定の `results`(回収の一覧). + with_checkpoints: 重み(`results.checkpoints.files`)を受け入れるか. Returns: 展開したファイル数と合計バイト数. @@ -137,7 +148,7 @@ archive.seek(0) with tarfile.open(fileobj=archive, mode="r:", encoding=_ENCODING) as tar: members = tar.getmembers() - check_pull_members(members, run_id, with_checkpoints=with_checkpoints) + check_pull_members(members, run_id, results, with_checkpoints=with_checkpoints) dest.mkdir(parents=True, exist_ok=True) tar.extractall(dest, members=members, filter="data") return ExtractResult(files=len(members), bytes=sum(member.size for member in members)) diff --git a/src/labremote/whitelist.py b/src/labremote/whitelist.py index 21ad9f6..7162136 100644 --- a/src/labremote/whitelist.py +++ b/src/labremote/whitelist.py @@ -1,19 +1,26 @@ -"""pull の回収ホワイトリスト(SPEC_01「回収ホワイトリスト」)の判定と,受け取った tar の検査. +"""回収する名前の判定(SPEC_01「安全の枠」の「回収」)と,受け取った tar の検査. -回収できるのは `runs/<実験ID>/` 配下で名前が一致するファイルのみ.拡張子や中身では判断せず, -列挙外はすべて回収しない.名前は大文字小文字を区別して完全一致で比べる(`Config.yaml`・ -`figures/x.PNG` は回収しない).判定は 2 か所で使う(二重の防御.TIASJudgeModel の -SPEC_03「pull」). +回収できるのは,結果の置き場の `<実験ID>/` の下で,設定の `results`(SPEC_02「`results`」)の +一覧に名前が一致するファイルだけである.拡張子や中身では判断せず,一覧に無いものはすべて回収しない. +名前は大文字小文字を区別して完全一致で比べる(`Config.yaml`・`figures/x.PNG` は回収しない. +送信の除外とは逆).一覧に書ける形は次の 3 つに限る(形はコードで固定し,設定では変えられない). + +- 実験フォルダの直下のファイル名(`results.pull.files`) +- 「このフォルダの直下で,この拡張子のもの」(`results.pull.dirs`.下の階層は対象にしない) +- 重みのファイル名(`results.checkpoints.dir` の直下の `results.checkpoints.files`. + `--with-checkpoints` のときだけ) + +判定は `is_pull_allowed` の 1 か所で行い,二重の確認(SPEC_01「安全の枠」の「回収」)の両方で使う. 1. サーバの一覧(`build_pull_list_command` の出力)から送らせるファイルを絞り込む(`plan_pull`) 2. 手元で受け取った tar を展開前に全メンバー検査する(`check_pull_members`) +手元のファイル名になる名前のうち,Windows で別の場所を指しうるもの(`:` 等の文字・末尾が `.` か +空白・予約名)を拒否する規則(`is_safe_local_name`)も,ここの 1 か所に置く.設定の検証 +(`labremote.config`)も同じ関数を使う. + エラーメッセージ・戻り値の表示用情報には件数だけを載せ,ファイル名は出さない (患者情報を含む名前の可能性があるため). - -TIASJudgeModel の `tias_judge_model.remote.whitelist` の移植.回収するファイル名と重みの名前を -TongueSegModel の SPEC_01 に合わせ,Windows で別の場所を指しうる名前(`:` 等の文字を含む名前・ -末尾が `.` か空白の名前・予約デバイス名)の拒否と,実験 ID の書式の確認(`re.fullmatch`)を足した. """ from __future__ import annotations @@ -22,14 +29,11 @@ import tarfile from collections.abc import Iterable from dataclasses import dataclass +from typing import TYPE_CHECKING -# runs/<実験ID>/ 直下で回収するファイル名 -PULL_ROOT_FILES = frozenset({"config.yaml", "history.csv", "metrics.json", "log.txt"}) -PULL_FIGURES_DIR = "figures" -PULL_FIGURE_SUFFIX = ".png" -PULL_CHECKPOINTS_DIR = "checkpoints" -# checkpoints/ の下で,明示的に指定したとき(--with-checkpoints)だけ回収するファイル名 -PULL_CHECKPOINT_FILES = frozenset({"best.pth", "ResUNet.onnx"}) +if TYPE_CHECKING: + # 実行時には import しない(`labremote.config` がこのモジュールの名前の規則を使うため) + from labremote.config import ResultsConfig # find -printf '%y' の通常ファイル _FIND_TYPE_FILE = "f" @@ -37,9 +41,9 @@ # Windows のファイル名に使えない文字.`:` は NTFS の代替データストリームとして解釈され, # 名前の見かけと違う場所へ書かれうるため拒否する(移植元はドライブ文字だけを見ていた) _WINDOWS_UNSAFE_CHARS = frozenset('<>:"|?*') -# 実験 ID(runs/ 直下のディレクトリ名)に許す文字.`make_run_id` の書式 -# (`YYYYmmdd-HHMMSS_<設定ファイル名>_`)はこの範囲に収まる. -# リモートのシェルとパスに埋め込むため fullmatch で確かめる +# 実験 ID(結果の置き場の直下のディレクトリ名)に許す文字. +# リモートのシェルとパスに埋め込むため fullmatch で確かめる.英数字で始めるため, +# ジョブのログの置き場(`_remote_logs`)は実験 ID にならない _RUN_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,199}") # Windows の予約デバイス名(小文字で比べる).拡張子が付いていても(`nul.png`・`CON.tar.gz`) # ファイルではなくデバイスを指すため,手元に展開すると書き込みが消える・別の動作になる. @@ -55,7 +59,7 @@ """サーバから送らせるファイルの計画. Attributes: - files: 送らせるファイル(`runs/` 基準の POSIX パス.表示しない). + files: 送らせるファイル(結果の置き場を基準にした POSIX パス.表示しない). skipped: 回収しなかったファイルの件数(リンク等の通常ファイル以外を含む). skipped_checkpoints: そのうち `--with-checkpoints` を付ければ回収できた件数. """ @@ -66,7 +70,7 @@ def validate_run_id(run_id: str) -> str: - """実験 ID(`runs/` 直下のディレクトリ名)を検証して返す. + """実験 ID(結果の置き場の直下のディレクトリ名)を検証して返す. Args: run_id: 実験 ID. @@ -80,9 +84,9 @@ 別の実験のフォルダに展開してしまう),または Windows の予約名(`nul`・`con.txt` 等) の場合. """ - if not _RUN_ID_RE.fullmatch(run_id) or ".." in run_id or not _is_safe_part(run_id): + if not _RUN_ID_RE.fullmatch(run_id) or ".." in run_id or not is_safe_local_name(run_id): raise ValueError( - f"実験 ID が不正である: {run_id!r}(runs/ 直下のディレクトリ名を指定する." + f"実験 ID が不正である: {run_id!r}(結果の置き場の直下のディレクトリ名を指定する." "英数字で始まり英数字・.・_・- のみ... と末尾の . は使えない." "Windows の予約名(CON・NUL・COM1 等)は使えない)" ) @@ -97,11 +101,19 @@ return part.split(".", 1)[0].rstrip(" ").lower() in _WINDOWS_RESERVED_NAMES -def _is_safe_part(part: str) -> bool: - """パスの 1 要素が `..`・`.`・空・バックスラッシュ・ドライブ文字・制御文字・Windows で - 使えない文字を含まず,末尾が `.`・空白でなく,Windows の予約名でないか. +def is_safe_local_name(part: str) -> bool: + """パスの 1 要素が,手元(Windows を含む)のファイル名として安全かを返す. - 末尾の `.`・空白は Windows が捨てるため,見かけと違う名前(`abc.` → `abc`)に書かれる. + `..`・`.`・空・バックスラッシュ・ドライブ文字・制御文字・Windows で使えない文字 + (`<>:"|?*`)を含まず,末尾が `.`・空白でなく,Windows の予約名(拡張子付きを含む)でなければ + 安全とする.末尾の `.`・空白は Windows が捨てるため,見かけと違う名前(`abc.` → `abc`)に + 書かれる.回収の判定と,設定(`results`)の名前の検証の両方が,この 1 つの規則を使う. + + Args: + part: パスの 1 要素(`/` を含まない名前). + + Returns: + 安全なら True. """ return ( part not in ("", ".", "..") @@ -115,33 +127,57 @@ def _is_safe_relative(path: str) -> bool: """POSIX 区切りの相対パスとして安全か(絶対パス・パス外へ出る要素を含まない).""" - return not path.startswith("/") and all(_is_safe_part(part) for part in path.split("/")) + return not path.startswith("/") and all(is_safe_local_name(part) for part in path.split("/")) -def is_pull_allowed(rel_path: str, *, with_checkpoints: bool) -> bool: - """`runs/<実験ID>/` 基準の相対パスが回収ホワイトリストに一致するかを返す. +def is_pull_allowed(rel_path: str, results: ResultsConfig, *, with_checkpoints: bool) -> bool: + """実験フォルダを基準にした相対パスが,設定の回収の一覧に一致するかを返す. + + 回収の判定はこの関数だけで行う(`plan_pull` と `check_pull_members` の両方が使う). + 名前は大文字小文字を区別して完全一致で比べる. Args: - rel_path: `runs/<実験ID>/` 基準の POSIX 相対パス. - with_checkpoints: `checkpoints/best.pth`・`checkpoints/ResUNet.onnx` も回収対象に - するか. + rel_path: 実験フォルダ(`<結果の置き場>/<実験ID>/`)を基準にした POSIX 相対パス. + results: 検証済みの設定の `results`. + with_checkpoints: 重み(`results.checkpoints.dir` の直下の `results.checkpoints.files`)も + 回収の対象にするか. Returns: 回収してよければ True. """ + # パス外へ出る名前・手元(Windows)で別の場所を指しうる名前は,一覧に一致しても回収しない if not _is_safe_relative(rel_path): return False - parts = rel_path.split("/") - if len(parts) == 1: - return parts[0] in PULL_ROOT_FILES - if len(parts) != 2: - return False - directory, name = parts - if directory == PULL_FIGURES_DIR: - return name.endswith(PULL_FIGURE_SUFFIX) and len(name) > len(PULL_FIGURE_SUFFIX) - if directory == PULL_CHECKPOINTS_DIR and with_checkpoints: - return name in PULL_CHECKPOINT_FILES - return False + # ここから先は大文字小文字を区別して比べる(設定の検証の重複・重なりの検査とは逆. + # 小文字にそろえると,一覧に無い名前まで回収する) + *directory_parts, name = rel_path.split("/") + if not directory_parts: + return name in results.pull.files + directory = "/".join(directory_parts) + if with_checkpoints and directory == results.checkpoints.dir: + return name in results.checkpoints.files + # pull.dirs は path の直下だけ(下の階層は directory が一致しないので対象にならない). + # 拡張子だけの名前(`.png`)は,その拡張子のファイルとみなさない + return any( + directory == item.path and name.endswith(item.suffix) and len(name) > len(item.suffix) + for item in results.pull.dirs + ) + + +def has_pull_names(results: ResultsConfig, *, with_checkpoints: bool) -> bool: + """設定の一覧に,回収しうる名前が 1 つでもあるかを返す. + + Args: + results: 検証済みの設定の `results`. + with_checkpoints: 重みも回収の対象にするか. + + Returns: + `results.pull` に名前があるか,`with_checkpoints` のときに `results.checkpoints.files` に + 名前があれば True. + """ + if results.pull.files or results.pull.dirs: + return True + return with_checkpoints and bool(results.checkpoints.files) def _strip_run_prefix(path: str, run_id: str) -> str | None: @@ -159,7 +195,7 @@ data: サーバの出力. Returns: - (種類, `runs/` 基準のパス) の一覧. + (種類, 結果の置き場を基準にしたパス) の一覧. Raises: ValueError: 書式が崩れている場合(件数のみ示す). @@ -174,14 +210,21 @@ def plan_pull( - listing: Iterable[tuple[str, str]], run_id: str, *, with_checkpoints: bool + listing: Iterable[tuple[str, str]], + run_id: str, + results: ResultsConfig, + *, + with_checkpoints: bool, ) -> PullPlan: - """サーバのファイル一覧から,送らせるファイル(ホワイトリストに一致する通常ファイル)を選ぶ. + """サーバのファイル一覧から,送らせるファイル(一覧に一致する通常ファイル)を選ぶ. + + 一覧との照合は `check_pull_members` と同じ `is_pull_allowed` で行う. Args: listing: `parse_find_listing` の結果. run_id: 検証済みの実験 ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)も回収するか. + results: 検証済みの設定の `results`. + with_checkpoints: 重み(`results.checkpoints.files`)も回収するか. Returns: 送らせるファイルと,回収しなかった件数. @@ -191,37 +234,44 @@ skipped_checkpoints = 0 for kind, path in listing: rel = _strip_run_prefix(path, run_id) + # 通常ファイル以外(リンク等)と実験 ID の外のものは,名前に関わらず送らせない. + # 名前で回収してよいかを決めるのは is_pull_allowed だけ if kind == _FIND_TYPE_FILE and rel is not None: - if is_pull_allowed(rel, with_checkpoints=with_checkpoints): + if is_pull_allowed(rel, results, with_checkpoints=with_checkpoints): files.append(path) continue - if not with_checkpoints and is_pull_allowed(rel, with_checkpoints=True): + if not with_checkpoints and is_pull_allowed(rel, results, with_checkpoints=True): skipped_checkpoints += 1 skipped += 1 return PullPlan(tuple(sorted(files)), skipped, skipped_checkpoints) def check_pull_members( - members: Iterable[tarfile.TarInfo], run_id: str, *, with_checkpoints: bool + members: Iterable[tarfile.TarInfo], + run_id: str, + results: ResultsConfig, + *, + with_checkpoints: bool, ) -> int: """受け取った tar の全メンバーを展開前に検査する. 1 つでも問題があれば例外を送出する(呼び出し側は何も展開しない).受け入れるのは - `<実験ID>/<ホワイトリストに一致する名前>` の通常ファイルのみで,ディレクトリ・リンク + `<実験ID>/<一覧に一致する名前>` の通常ファイルのみで,ディレクトリ・リンク (シンボリック・ハード)・特殊ファイルは拒否する(サーバはファイル名だけを tar に渡すため, - 正常な応答にディレクトリのメンバーは含まれない). + 正常な応答にディレクトリのメンバーは含まれない).一覧との照合は `plan_pull` と同じ + `is_pull_allowed` で行う. Args: members: tar のメンバー(`TarFile.getmembers()`). run_id: 検証済みの実験 ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)を - 受け入れるか. + results: 検証済みの設定の `results`. + with_checkpoints: 重み(`results.checkpoints.files`)を受け入れるか. Returns: 受け入れたメンバーの件数. Raises: - ValueError: ホワイトリスト外の名前・パス外に出る名前(`..`・絶対パス・ドライブ文字・ + ValueError: 一覧に無い名前・パス外に出る名前(`..`・絶対パス・ドライブ文字・ バックスラッシュ・Windows で使えない文字)・リンク・通常ファイル以外が含まれる場合 (件数のみを示す). """ @@ -239,7 +289,7 @@ not_regular += 1 else: rel = _strip_run_prefix(member.name, run_id) - if rel is None or not is_pull_allowed(rel, with_checkpoints=with_checkpoints): + if rel is None or not is_pull_allowed(rel, results, with_checkpoints=with_checkpoints): not_allowed += 1 else: accepted += 1 diff --git a/tests/results_helpers.py b/tests/results_helpers.py new file mode 100644 index 0000000..8380103 --- /dev/null +++ b/tests/results_helpers.py @@ -0,0 +1,73 @@ +"""テストで使い回す,設定の `results`(回収の一覧). + +回収の判定のテストは,一覧を設定から与える(SPEC_02「`results`」).LabRemote の移植元の +テストが前提にしていた一覧(実験フォルダの直下の 4 つのファイル・`figures/` の直下の `.png`・ +`--with-checkpoints` のときだけの 2 つの重み)を,ここ 1 か所に書く.`split.json`・ +`predictions.csv` 等は,わざと一覧に入れない(「一覧に無い名前は回収しない」ことを確かめるため). +""" + +from labremote.config import ResultsConfig + +SAMPLE_RESULTS_DICT = { + "pull": { + "files": ["config.yaml", "history.csv", "metrics.json", "log.txt"], + "dirs": [{"path": "figures", "suffix": ".png"}], + }, + "checkpoints": {"dir": "checkpoints", "files": ["best.pth", "ResUNet.onnx"]}, +} + +SAMPLE_RESULTS = ResultsConfig.model_validate(SAMPLE_RESULTS_DICT) + +# labremote.yaml に書く形(トップレベルの `results:` の節) +SAMPLE_RESULTS_YAML = """\ +results: + pull: + files: [config.yaml, history.csv, metrics.json, log.txt] + dirs: + - path: figures + suffix: .png + checkpoints: + dir: checkpoints + files: [best.pth, ResUNet.onnx] +""" + +# 上とは別の一覧(判定が設定を見ていて,上の一覧や古い定数が残っていないことを確かめるため). +# 名前・フォルダ・拡張子・重みの置き場と名前・結果の置き場を,すべて上と違うものにする. +# `discard` の名前は,回収の対象にならないことを確かめるために書く +OTHER_RESULTS_DICT = { + "dir": "output/runs", + "pull": { + "files": ["summary.txt", "scores.tsv"], + "dirs": [ + {"path": "out/plots", "suffix": ".svg"}, + {"path": "curves", "suffix": ".csv"}, + ], + }, + "checkpoints": {"dir": "weights", "files": ["final.ckpt"]}, + "discard": { + "files": ["trace.bin"], + "dirs": [{"path": "debug", "suffix": ".png"}], + }, +} + +OTHER_RESULTS = ResultsConfig.model_validate(OTHER_RESULTS_DICT) + +OTHER_RESULTS_YAML = """\ +results: + dir: output/runs + pull: + files: [summary.txt, scores.tsv] + dirs: + - path: out/plots + suffix: .svg + - path: curves + suffix: .csv + checkpoints: + dir: weights + files: [final.ckpt] + discard: + files: [trace.bin] + dirs: + - path: debug + suffix: .png +""" diff --git a/tests/test_cli.py b/tests/test_cli.py index 4b686cb..6a884af 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -11,7 +11,8 @@ TIASJudgeModel の tests/cli/test_remote.py の移植.設定(labremote.yaml)にアドレス・ユーザー名を 書くキーは無く,ssh の接続先はサーバ名(~/.ssh/config の Host 名)になる. -回収ホワイトリストはTongueSegModel の SPEC_01 に合わせた. +回収の一覧は,テスト用の設定の `results`(tests/results_helpers.py の SAMPLE_RESULTS_YAML)で +与える(SPEC_02「`results`」). """ from __future__ import annotations @@ -30,6 +31,7 @@ import pytest import yaml +from results_helpers import OTHER_RESULTS_YAML, SAMPLE_RESULTS_YAML import labremote.cli as cli from labremote.commands import ( @@ -51,7 +53,8 @@ ARCHIMEDES_ADDR = "Archimedes" RUN_ID = "20261119-120000_resunet_abc1234" -CONFIG_YAML = """\ +CONFIG_YAML = ( + """\ project: name: DemoProject push: {} @@ -74,6 +77,8 @@ uv: ~/.local/bin/uv data_ready: true """ + + SAMPLE_RESULTS_YAML +) def _probe_stdout(gpus: list[tuple[int, int, int]], apps: list[str] | None = None) -> bytes: @@ -1958,3 +1963,272 @@ monkeypatch.setattr(cli, "_run_ssh", fake) assert cli.main(["push"]) == 1 assert fake.calls == [] + + +# --------------------------------------------------------------------------- +# 設定の results を変えたとき(SPEC_02「`results`」,SPEC_03「pull」「run」) +# --------------------------------------------------------------------------- + +# 結果の置き場と回収の一覧を書かない設定(results を省略) +CONFIG_YAML_WITHOUT_RESULTS = CONFIG_YAML.replace(SAMPLE_RESULTS_YAML, "") + +# OTHER_RESULTS_YAML(dir: output/runs)の一覧で回収するもの・回収しないもの +OTHER_LISTING_ALLOWED = ["summary.txt", "scores.tsv", "out/plots/a.svg", "curves/train.csv"] +OTHER_LISTING_WEIGHTS = ["weights/final.ckpt"] +OTHER_LISTING_NOT_ALLOWED = [ + # SAMPLE_RESULTS の一覧にあった名前 + "config.yaml", + "metrics.json", + "figures/loss.png", + "checkpoints/best.pth", + # discard の名前・一覧に無い名前・下の階層・大文字小文字の違い + "trace.bin", + "debug/secret_case07.png", + "secret_case08.csv", + "out/plots/sub/secret_case09.svg", + "Summary.txt", + "weights/secret_case10.ckpt", +] +OTHER_SECRETS = ["trace.bin", "secret_case07", "secret_case08", "secret_case09", "secret_case10"] + + +def _use_config(project: Path, results_yaml: str) -> None: + (project / "labremote.yaml").write_text( + CONFIG_YAML_WITHOUT_RESULTS + results_yaml, encoding="utf-8" + ) + + +def _other_listing() -> bytes: + names = OTHER_LISTING_ALLOWED + OTHER_LISTING_WEIGHTS + OTHER_LISTING_NOT_ALLOWED + return b"".join(f"f {RUN_ID}/{name}\0".encode() for name in names) + + +class RecordingReceive(FakeReceive): + """`_receive_tar` の代わり(FakeReceive に加えて,tar を作らせるコマンドを記録する).""" + + def __init__(self) -> None: + super().__init__() + self.argv: list[str] = [] + + def __call__(self, argv: list[str], payload: bytes, destination) -> cli._SshResult: + self.argv = list(argv) + return super().__call__(argv, payload, destination) + + +def _files_under(base: Path) -> list[str]: + if not base.exists(): + return [] + return sorted(p.relative_to(base).as_posix() for p in base.rglob("*") if p.is_file()) + + +def _setup_other_pull(monkeypatch: pytest.MonkeyPatch) -> tuple[FakeSsh, RecordingReceive]: + receive = RecordingReceive() + fake = FakeSsh( + { + NEWTON_ADDR: _ok(_other_listing()), + ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b""), + } + ) + monkeypatch.setattr(cli, "_run_ssh", fake) + monkeypatch.setattr(cli, "_receive_tar", receive) + return fake, receive + + +def _probe_with_sessions(sessions: list[str]) -> bytes: + lines = [PROBE_SESSIONS_MARKER, *sessions, PROBE_GPUS_MARKER, f"{PROBE_GPU_RC_PREFIX}127"] + return ("\n".join([*lines, PROBE_END_MARKER]) + "\n").encode() + + +class TestResultsFromCli: + def test_other_list_pulls_only_its_names_into_results_dir( + self, + project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + ) -> None: + """SPEC_03「pull」: 設定の一覧の名前だけを,<ルート>/// に保存する.""" + caplog.set_level(logging.DEBUG) + _use_config(project, OTHER_RESULTS_YAML) + _, receive = _setup_other_pull(monkeypatch) + assert cli.main(["pull", RUN_ID]) == 0 + assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in OTHER_LISTING_ALLOWED) + assert _files_under(project / "output" / "runs" / RUN_ID) == sorted(OTHER_LISTING_ALLOWED) + # 既定の置き場(runs)には何も作らない + assert not (project / "runs").exists() + # 回収しなかったファイル(一覧に無い 10 件と重み 1 件)は件数だけ.名前は出さない + captured = capsys.readouterr() + output = captured.out + captured.err + caplog.text + for secret in OTHER_SECRETS: + assert secret not in output + assert "11 件" in output + assert "1 件は --with-checkpoints で回収できる" in output + + def test_other_list_with_checkpoints_pulls_listed_weights_only( + self, project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SPEC_02「`results`」. + + --with-checkpoints で checkpoints.files の名前だけを足して回収する. + """ + _use_config(project, OTHER_RESULTS_YAML) + _, receive = _setup_other_pull(monkeypatch) + assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0 + expected = OTHER_LISTING_ALLOWED + OTHER_LISTING_WEIGHTS + assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in expected) + assert _files_under(project / "output" / "runs" / RUN_ID) == sorted(expected) + + def test_pull_commands_use_results_dir( + self, project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SPEC_03「pull」. + + サーバの /// を一覧し,そこで tar を作る. + """ + _use_config(project, OTHER_RESULTS_YAML) + fake, receive = _setup_other_pull(monkeypatch) + assert cli.main(["pull", RUN_ID]) == 0 + list_commands = [argv[-1] for argv in fake.calls] + assert list_commands + for command in [*list_commands, receive.argv[-1]]: + assert shlex.split(command)[:2] == ["cd", "$HOME/work/TongueSegModel/output/runs"] + + @pytest.mark.parametrize( + "extra", + [ + f"{RUN_ID}/config.yaml", + f"{RUN_ID}/trace.bin", + f"{RUN_ID}/weights/final.ckpt", + f"{RUN_ID}/out/plots/sub/a.svg", + f"{RUN_ID}/../evil.txt", + ], + ) + def test_other_list_bad_archive_extracts_nothing( + self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: str + ) -> None: + """SPEC_01「回収」: 別の一覧でも,受け取った tar に一覧に無い名前があれば何も展開しない.""" + _use_config(project, OTHER_RESULTS_YAML) + fake = FakeSsh( + {NEWTON_ADDR: _ok(_other_listing()), ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)} + ) + monkeypatch.setattr(cli, "_run_ssh", fake) + monkeypatch.setattr(cli, "_receive_tar", FakeReceive(extra=[extra])) + assert cli.main(["pull", RUN_ID]) != 0 + assert _files_under(project / "output") == [] + assert not (project / "runs").exists() + assert not (project / "evil.txt").exists() + + @pytest.mark.parametrize("flag", [[], ["--with-checkpoints"]]) + def test_pull_without_results_stops_before_ssh( + self, + project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + flag: list[str], + ) -> None: + """SPEC_02「`results`」. + + 一覧が空の pull は接続せず,設定に書く場所を示して 0 以外で終わる. + """ + caplog.set_level(logging.DEBUG) + _use_config(project, "") + fake = FakeSsh({}) + receive = FakeReceive() + monkeypatch.setattr(cli, "_run_ssh", fake) + monkeypatch.setattr(cli, "_receive_tar", receive) + assert cli.main(["pull", RUN_ID, *flag]) != 0 + assert fake.calls == [] + assert receive.requested == [] + assert not (project / "runs").exists() + captured = capsys.readouterr() + assert "results.pull" in captured.out + captured.err + caplog.text + + def test_pull_with_only_weights_needs_flag( + self, project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SPEC_02「`results`」. + + 重みだけが書かれた設定は,--with-checkpoints のときだけ回収に進む. + """ + _use_config(project, "results:\n checkpoints:\n files: [best.pth]\n") + fake = FakeSsh({NEWTON_ADDR: _ok(_listing()), ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)}) + receive = FakeReceive() + monkeypatch.setattr(cli, "_run_ssh", fake) + monkeypatch.setattr(cli, "_receive_tar", receive) + assert cli.main(["pull", RUN_ID]) != 0 + assert fake.calls == [] + + assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0 + assert receive.requested == [f"{RUN_ID}/checkpoints/best.pth"] + assert _local_files(project) == ["checkpoints/best.pth"] + + def test_logs_use_results_dir(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """SPEC_03「run」: ログの表示は /_remote_logs/<ジョブ名>.log を読む.""" + _use_config(project, OTHER_RESULTS_YAML) + + def newton(argv: list[str]) -> cli._SshResult: + return cli._SshResult(0, b"epoch 1\n" if "tail" in argv[-1] else b"", b"") + + fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND)}) + monkeypatch.setattr(cli, "_run_ssh", fake) + assert cli.main(["logs", "train1", "-n", "5"]) == 0 + assert fake.calls + for argv in fake.calls: + assert "output/runs/_remote_logs/train1.log" in argv[-1] + assert " runs/_remote_logs" not in argv[-1] + + def test_kill_uses_results_dir(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """SPEC_03「run」: probe と kill は /_remote_logs/ のログを見る・書く.""" + _use_config(project, OTHER_RESULTS_YAML) + + def newton(argv: list[str]) -> cli._SshResult: + if "kill-session" in argv[-1]: + return cli._SshResult(0, b"", b"") + return cli._SshResult(0, _probe_with_sessions(["job train1"]), b"") + + fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _ok(_probe_with_sessions([]))}) + monkeypatch.setattr(cli, "_run_ssh", fake) + assert cli.main(["kill", "train1"]) == 0 + kills = [argv[-1] for argv in fake.calls if "kill-session" in argv[-1]] + assert len(kills) == 1 + assert "output/runs/_remote_logs/train1.log" in kills[0] + for argv in fake.calls: + assert "output/runs/_remote_logs" in argv[-1] + + def test_run_dry_run_uses_results_dir( + self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_03「run」: ログの置き場は //_remote_logs/ になる.""" + _use_config(project, OTHER_RESULTS_YAML) + fake = _free_everywhere(monkeypatch) + assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0 + out = capsys.readouterr().out + assert "output/runs/_remote_logs" in out + assert "exp1.log" in out + for argv in fake.calls: + assert "output/runs/_remote_logs" in argv[-1] + + def test_push_excludes_changed_results_dir( + self, project: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「結果の置き場と送信」: dir を変えると,送らない場所もその場所に変わる.""" + _use_config(project, OTHER_RESULTS_YAML) + for rel in ["output/runs/r1/summary.txt", "output/note.txt", "runs/x.txt"]: + (project / rel).parent.mkdir(parents=True, exist_ok=True) + (project / rel).write_bytes(b"x") + names = _push_dry_run_names([], capsys) + assert "output/note.txt" in names + assert "runs/x.txt" in names + assert not any(name.startswith("output/runs") for name in names) + + def test_push_excludes_default_results_dir( + self, project: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """SPEC_02「`results`」: results を省略したとき,ルートの直下の runs/ は送らない.""" + _use_config(project, "") + (project / "runs" / "r1").mkdir(parents=True) + (project / "runs" / "r1" / "metrics.json").write_bytes(b"x") + names = _push_dry_run_names([], capsys) + assert names + assert not any(name.startswith("runs") for name in names) diff --git a/tests/test_commands.py b/tests/test_commands.py index 64ca4bf..edbc231 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -10,6 +10,7 @@ from __future__ import annotations import shlex +from collections.abc import Callable import pytest @@ -175,43 +176,57 @@ class TestBuildProbeCommand: def test_queries_listed_in_spec(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500 + ) assert "--query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" in command assert "--query-compute-apps=gpu_uuid,pid,used_memory" in command assert "--format=csv,noheader,nounits" in command def test_observation_uses_interval_and_duration(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500 + ) assert "-lms 500" in command assert "timeout 10" in command assert "pmon -s u" in command def test_observe_zero_does_not_observe(self) -> None: - command = build_probe_command("~/work/x", observe_sec=0, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500 + ) assert "-lms" not in command assert "pmon" not in command assert "--query-gpu=index,uuid,name" in command def test_is_single_line(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=10, sample_interval_ms=500 + ) assert "\n" not in command def test_reports_own_user_before_sessions(self) -> None: # 自分の利用者名を id -un で取る(設定の user を省略できるため.移植元との違い) - command = build_probe_command("~/work/x", observe_sec=0, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=0, sample_interval_ms=500 + ) assert f"{PROBE_USER_PREFIX}$(id -un" in command assert command.index(PROBE_USER_PREFIX) < command.index(PROBE_SESSIONS_MARKER) assert command.rstrip().endswith(f"echo '{PROBE_END_MARKER}'") def test_markers_use_tsm_prefix(self) -> None: - command = build_probe_command("~/work/x", observe_sec=3, sample_interval_ms=500) + command = build_probe_command( + "~/work/x", results_dir="runs", observe_sec=3, sample_interval_ms=500 + ) assert "@@tias" not in command assert "@@labremote-" in command @pytest.mark.parametrize(("observe", "interval"), [(-1, 500), (0, 0)]) def test_rejects_bad_observation(self, observe: int, interval: int) -> None: with pytest.raises(ValueError): - build_probe_command("~/work/x", observe_sec=observe, sample_interval_ms=interval) + build_probe_command( + "~/work/x", results_dir="runs", observe_sec=observe, sample_interval_ms=interval + ) class TestJobSettings: @@ -402,6 +417,7 @@ gpu_index=gpu_index, env=build_job_env(gpu_index, extra or [], git_commit="abc1234"), path_env={}, + results_dir="runs", ) @@ -500,6 +516,7 @@ gpu_index=0, env={}, path_env={}, + results_dir="runs", ) @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", "-j"]) @@ -514,6 +531,7 @@ gpu_index=0, env={}, path_env={}, + results_dir="runs", ) @pytest.mark.parametrize("key", ["A B", "A;id", "1A", "A\n"]) @@ -528,6 +546,7 @@ gpu_index=0, env={key: "v"}, path_env={}, + results_dir="runs", ) @@ -535,7 +554,7 @@ def test_job_script_round_trips_through_tmux_and_bash_c(self) -> None: """tmux → `bash -c` の 2 段の引用を外すと,元のジョブ本体に戻る.""" script = _script(0, ["tsm-train", *NASTY_ARGS]) - command = build_run_command("~/work/TongueSegModel", "train1", script) + command = build_run_command("~/work/TongueSegModel", "train1", script, results_dir="runs") tokens = shlex.split(command) i = tokens.index("new-session") assert tokens[i : i + 7] == [ @@ -551,7 +570,7 @@ assert inner == ["bash", "-c", script] def test_refuses_existing_session_with_exact_match(self) -> None: - command = build_run_command("~/w", "train1", "true") + command = build_run_command("~/w", "train1", "true", results_dir="runs") # = を前置して完全一致(前方一致で別のジョブを選ばない) assert "tmux has-session -t =train1 " in command assert "exit 91" in command @@ -559,7 +578,7 @@ @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", ""]) def test_bad_name_is_rejected(self, name: str) -> None: with pytest.raises(ValueError): - build_run_command("~/w", name, "true") + build_run_command("~/w", name, "true", results_dir="runs") class TestOtherCommands: @@ -583,33 +602,37 @@ ] def test_logs_command(self) -> None: - command = build_logs_command("~/w", "train1", lines=50, follow=False) + command = build_logs_command("~/w", "train1", results_dir="runs", lines=50, follow=False) assert "tail -n 50 runs/_remote_logs/train1.log" in command - follow = build_logs_command("~/w", "train1", lines=10, follow=True) + follow = build_logs_command("~/w", "train1", results_dir="runs", lines=10, follow=True) assert "-F" in follow and "cat >/dev/null" in follow def test_logs_rejects_negative_lines_and_bad_name(self) -> None: with pytest.raises(ValueError): - build_logs_command("~/w", "train1", lines=-1, follow=False) + build_logs_command("~/w", "train1", results_dir="runs", lines=-1, follow=False) with pytest.raises(ValueError): - build_logs_command("~/w", "a;b", lines=1, follow=False) + build_logs_command("~/w", "a;b", results_dir="runs", lines=1, follow=False) def test_log_exists_and_kill_validate_name(self) -> None: for build in (build_log_exists_command, build_kill_command): with pytest.raises(ValueError): - build("~/w", "x$(id)") - assert "tmux kill-session -t =train1" in build_kill_command("~/w", "train1") - assert job_log_path("train1") == "runs/_remote_logs/train1.log" + build("~/w", "x$(id)", results_dir="runs") + assert "tmux kill-session -t =train1" in build_kill_command( + "~/w", "train1", results_dir="runs" + ) + assert job_log_path("train1", results_dir="runs") == "runs/_remote_logs/train1.log" def test_pull_list_command_quotes_run_id_and_refuses_links(self) -> None: - command = build_pull_list_command("~/work/TongueSegModel", "20261119-120000_x_abc1234") + command = build_pull_list_command( + "~/work/TongueSegModel", "20261119-120000_x_abc1234", results_dir="runs" + ) assert 'cd "$HOME"/work/TongueSegModel/runs' in command assert "[ -L 20261119-120000_x_abc1234 ]" in command assert "exit 94" in command assert "! -type d -printf '%y %p\\0'" in command def test_pull_tar_reads_only_given_names(self) -> None: - command = build_pull_tar_command("~/work/TongueSegModel") + command = build_pull_tar_command("~/work/TongueSegModel", results_dir="runs") assert "tar --null --no-recursion -T - -cf -" in command @@ -633,17 +656,22 @@ gpu_index=0, env=build_job_env(0, [], git_commit="abc1234"), path_env={}, + results_dir="runs", ) return { - "probe": build_probe_command(remote_dir, observe_sec=3, sample_interval_ms=500), + "probe": build_probe_command( + remote_dir, results_dir="runs", observe_sec=3, sample_interval_ms=500 + ), "push": build_push_command(remote_dir), "job_script": script, - "run": build_run_command(remote_dir, "train1", script), - "log_exists": build_log_exists_command(remote_dir, "train1"), - "logs": build_logs_command(remote_dir, "train1", lines=50, follow=True), - "kill": build_kill_command(remote_dir, "train1"), - "pull_list": build_pull_list_command(remote_dir, "20261119-120000_x_abc1234"), - "pull_tar": build_pull_tar_command(remote_dir), + "run": build_run_command(remote_dir, "train1", script, results_dir="runs"), + "log_exists": build_log_exists_command(remote_dir, "train1", results_dir="runs"), + "logs": build_logs_command(remote_dir, "train1", results_dir="runs", lines=50, follow=True), + "kill": build_kill_command(remote_dir, "train1", results_dir="runs"), + "pull_list": build_pull_list_command( + remote_dir, "20261119-120000_x_abc1234", results_dir="runs" + ), + "pull_tar": build_pull_tar_command(remote_dir, results_dir="runs"), } @@ -782,6 +810,7 @@ gpu_index=1, env=env, path_env={}, + results_dir="runs", ) exports = _exports(script) assert exports["LABREMOTE_GIT_COMMIT"] == "abc1234" @@ -860,6 +889,7 @@ gpu_index=0, env=env, path_env={}, + results_dir="runs", ) @pytest.mark.parametrize(("key", "value"), list(NASTY_VALUES.items())) @@ -872,7 +902,7 @@ """SPEC_01「名前と値の検証」: tmux → bash -c の 2 段を経ても値が 1 語のまま戻る.""" env = build_job_env(0, ["CLI=$(id); x"], git_commit="abc1234", base_env=NASTY_VALUES) script = self._script(env) - command = build_run_command("~/work/x", "train1", script) + command = build_run_command("~/work/x", "train1", script, results_dir="runs") tokens = shlex.split(command) inner = shlex.split(tokens[tokens.index("new-session") + 6]) assert inner[:2] == ["bash", "-c"] @@ -882,3 +912,129 @@ assert exports["CLI"] == "$(id); x" # 特殊文字が値の外に漏れて,余分なコマンドが増えていない assert "touch" not in shlex.split(inner[2]) + + +# --------------------------------------------------------------------------- +# 結果の置き場(SPEC_02「`results`」の `dir`・SPEC_03「pull」「run」のログの置き場) +# --------------------------------------------------------------------------- + + +def _builders_with_results_dir(results_dir: str) -> dict[str, Callable[[], str]]: + """結果の置き場を results_dir にして,その場所を使うコマンドを組み立てる関数を返す.""" + remote_dir = "~/work/proj" + + def job_script() -> str: + return build_job_script( + remote_dir, + "train1", + ["python", "-m", "train"], + uv_path="~/.local/bin/uv", + server_name="Newton", + gpu_index=0, + env=build_job_env(0, [], git_commit="abc1234"), + path_env={}, + results_dir=results_dir, + ) + + return { + "probe": lambda: build_probe_command( + remote_dir, results_dir=results_dir, observe_sec=3, sample_interval_ms=500 + ), + "job_script": job_script, + # run には検証済みのスクリプトを渡す(結果の置き場は run の側でも確かめる) + "run": lambda: build_run_command(remote_dir, "train1", "true", results_dir=results_dir), + "log_exists": lambda: build_log_exists_command( + remote_dir, "train1", results_dir=results_dir + ), + "logs": lambda: build_logs_command( + remote_dir, "train1", results_dir=results_dir, lines=50, follow=False + ), + "kill": lambda: build_kill_command(remote_dir, "train1", results_dir=results_dir), + "pull_list": lambda: build_pull_list_command( + remote_dir, "20261119-120000_x_abc1234", results_dir=results_dir + ), + "pull_tar": lambda: build_pull_tar_command(remote_dir, results_dir=results_dir), + } + + +def _commands_with_results_dir(results_dir: str) -> dict[str, str]: + """結果の置き場を results_dir にして,その場所を使うコマンドを一通り組み立てる.""" + return {kind: build() for kind, build in _builders_with_results_dir(results_dir).items()} + + +# ログの場所を含むコマンドと,結果の置き場(の下の実験 ID)へ移動するコマンド +_LOG_KINDS = ["probe", "job_script", "run", "log_exists", "logs", "kill"] +_PULL_KINDS = ["pull_list", "pull_tar"] + + +class TestResultsDirInCommands: + @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS) + def test_changed_results_dir_leaves_no_runs(self, kind: str) -> None: + """SPEC_02「`results`」: dir を変えると,サーバのコマンドに runs の決め打ちが残らない.""" + command = _commands_with_results_dir("zzout/store")[kind] + assert "runs" not in command + assert "zzout/store" in command + + @pytest.mark.parametrize("kind", _LOG_KINDS) + def test_log_dir_is_under_results_dir(self, kind: str) -> None: + """SPEC_03「run」: ログは /<結果の置き場>/_remote_logs/ に置く.""" + command = _commands_with_results_dir("output/runs")[kind] + assert "output/runs/_remote_logs" in command + + def test_job_log_path_follows_results_dir(self) -> None: + """SPEC_02「`results`」: ジョブのログは /_remote_logs/<ジョブ名>.log.""" + assert ( + job_log_path("train1", results_dir="output/runs") + == "output/runs/_remote_logs/train1.log" + ) + + def test_pull_commands_cd_into_results_dir(self) -> None: + """SPEC_03「pull」: 対象はサーバの /<結果の置き場>// の下.""" + commands = _commands_with_results_dir("output/runs") + for kind in _PULL_KINDS: + tokens = shlex.split(commands[kind]) + assert tokens[:2] == ["cd", "$HOME/work/proj/output/runs"], kind + + @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"]) + def test_results_dir_is_one_word_in_pull_commands(self, results_dir: str) -> None: + """SPEC_01「名前と値の検証」. + + 結果の置き場は引用され,空白や特殊文字を含んでも 1 語で渡る. + """ + commands = _commands_with_results_dir(results_dir) + for kind in _PULL_KINDS: + tokens = shlex.split(commands[kind]) + assert tokens[:2] == ["cd", f"$HOME/work/proj/{results_dir}"], kind + + @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`"]) + def test_results_dir_is_one_word_in_log_commands(self, results_dir: str) -> None: + """SPEC_01「名前と値の検証」: ログの場所も引用され,1 語のまま渡る.""" + commands = _commands_with_results_dir(results_dir) + log = f"{results_dir}/_remote_logs/train1.log" + run_tokens = shlex.split(commands["run"]) + mkdir = run_tokens.index("mkdir") + assert run_tokens[mkdir : mkdir + 3] == ["mkdir", "-p", f"{results_dir}/_remote_logs"] + assert log in shlex.split(commands["log_exists"]) + assert log in shlex.split(commands["logs"]) + assert log in shlex.split(commands["kill"]) + # ジョブのスクリプトは,ログの場所を 1 語の変数に入れてから使う + # (shlex.split は区切りの ; を語に付けたまま返すため,末尾の ; を除いて比べる) + script_tokens = [t.removesuffix(";") for t in shlex.split(commands["job_script"])] + assert f"log={log}" in script_tokens + probe_tokens = shlex.split(commands["probe"]) + assert any( + t.startswith(f"$HOME/work/proj/{results_dir}/_remote_logs/") for t in probe_tokens + ) + + @pytest.mark.parametrize( + "results_dir", + ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b"], + ) + @pytest.mark.parametrize("kind", _LOG_KINDS + _PULL_KINDS) + def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str, kind: str) -> None: + """SPEC_01「安全の枠」. + + remote_dir の外を指す結果の置き場では,サーバのコマンドを組み立てない. + """ + with pytest.raises(ValueError): + _builders_with_results_dir(results_dir)[kind]() diff --git a/tests/test_config.py b/tests/test_config.py index 2e6e251..f374746 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1047,3 +1047,633 @@ ] push = load_remote_config(_write(tmp_path, _push_data({"partial": partial}))).push assert [p.path for p in push.partial] == ["ext/a", "ext/ab", "vendor"] + + +# --------------------------------------------------------------------------- +# results(SPEC_02「`results`」の「書き方と,書けないもの」) +# --------------------------------------------------------------------------- + + +def _results_data(results: object, *, push: object | None = None) -> dict: + data = _base() + data["results"] = results + if push is not None: + data["push"] = push + return data + + +def _load_results(tmp_path: Path, results: object, *, push: object | None = None): + return load_remote_config(_write(tmp_path, _results_data(results, push=push))).results + + +# Windows で別の場所を指しうる名前(dir・files・dirs の path・checkpoints で共通) +WINDOWS_UNSAFE_NAMES: list[str] = [ + "ab", + "a:b", + 'a"b', + "a|b", + "a.", + "a. ", + "CON", + "con", + "nul", + "Nul", + "PRN", + "AUX", + "COM1", + "com9", + "LPT1", + "LPT9", + "con.txt", + "NUL.png", + "lpt9.tar.gz", +] + +# 1 つの名前として書けないもの(pull.files・checkpoints.files・discard.files・checkpoints.dir) +BAD_RESULT_NAMES: list[object] = [ + "a/b", + "a\\b", + "/a", + "*", + "*.png", + "a*", + "a?", + "[a]", + ".", + "..", + "", + " a", + "a ", + "a\t", + "a\n", + "a\x00b", + "a\x01b", + "a\x1bb", + "a\x7fb", + "a\nb", + "_remote_logs", + *WINDOWS_UNSAFE_NAMES, + 1, + True, + None, + ["a"], + {"name": "a"}, +] + +# 相対パスとして書けないもの(dir・dirs の path で共通) +BAD_RESULT_PATHS: list[object] = [ + "..", + "../x", + "a/..", + "a/../b", + "/x", + "/", + "C:/x", + "C:\\x", + "c:x", + "\\x", + "a\\b", + "*", + "ru*ns", + "run?", + "[r]uns", + "a/*", + "./a", + "a/./b", + "a//b", + "a/", + ".", + "", + " a", + "a /b", + "a\x00b", + "a\nb", + "_remote_logs", + "_remote_logs/x", + *WINDOWS_UNSAFE_NAMES, + *(f"x/{name}" for name in WINDOWS_UNSAFE_NAMES), + 1, + None, + ["runs"], +] + + +class TestResultsDefaults: + def test_omitted_results_uses_defaults(self, tmp_path: Path) -> None: + """SPEC_02「`results`」. + + 省略したとき dir は runs,checkpoints.dir は checkpoints,一覧は空. + """ + results = load_remote_config(_write(tmp_path, _base())).results + assert results.dir == "runs" + assert results.checkpoints.dir == "checkpoints" + assert results.pull.files == () + assert results.pull.dirs == () + assert results.checkpoints.files == () + assert results.discard.files == () + assert results.discard.dirs == () + + def test_empty_results_uses_defaults(self, tmp_path: Path) -> None: + """SPEC_02「`results`」: results: {} も省略と同じ既定になる.""" + results = _load_results(tmp_path, {}) + assert results.dir == "runs" + assert results.checkpoints.dir == "checkpoints" + assert (results.pull.files, results.pull.dirs, results.checkpoints.files) == ((), (), ()) + + def test_values_are_loaded(self, tmp_path: Path) -> None: + """SPEC_02「`results`」: 各キーを書いたとおりに読む(名前はそのまま.小文字にしない).""" + results = _load_results( + tmp_path, + { + "dir": "output/runs", + "pull": { + "files": ["Summary.TXT", "a b.csv"], + "dirs": [{"path": "out/Plots", "suffix": ".SVG"}], + }, + "checkpoints": {"dir": "Weights", "files": ["Final.ckpt"]}, + "discard": {"files": ["trace.bin"], "dirs": [{"path": "debug", "suffix": ".png"}]}, + }, + ) + assert results.dir == "output/runs" + assert results.pull.files == ("Summary.TXT", "a b.csv") + assert [(d.path, d.suffix) for d in results.pull.dirs] == [("out/Plots", ".SVG")] + assert results.checkpoints.dir == "Weights" + assert results.checkpoints.files == ("Final.ckpt",) + assert results.discard.files == ("trace.bin",) + assert [(d.path, d.suffix) for d in results.discard.dirs] == [("debug", ".png")] + + +class TestResultsDir: + @pytest.mark.parametrize("value", ["runs", "output/runs", "a/b/c", "out-put/run_s", "my runs"]) + def test_good_dir_is_accepted(self, tmp_path: Path, value: str) -> None: + """SPEC_02「`results`」: dir はルートからの相対パスで / 区切りで書く.""" + assert _load_results(tmp_path, {"dir": value}).dir == value + + @pytest.mark.parametrize("value", BAD_RESULT_PATHS) + def test_bad_dir_is_rejected(self, tmp_path: Path, value: object) -> None: + """SPEC_02「`results`」. + + dir に ..・絶対パス・ワイルドカード・. や空の部分・Windows の名前は書けない. + """ + _invalid(tmp_path, _results_data({"dir": value})) + + @pytest.mark.parametrize( + "value", + [ + ".git", + ".git/x", + "a/.venv", + ".venv/runs", + ".claude/x", + "a/__pycache__", + ".pytest_cache/x", + "a/b/.ruff_cache", + ".GIT/x", + "a/.Venv", + ], + ) + def test_dir_inside_fixed_exclusion_is_rejected(self, tmp_path: Path, value: str) -> None: + """SPEC_02「`results`」. + + dir は固定の除外のフォルダ(.git・.venv・.claude・キャッシュ)の中を指せない. + """ + _invalid(tmp_path, _results_data({"dir": value})) + + @pytest.mark.parametrize( + "value", + ["_remote_logs", "runs/_remote_logs", "_remote_logs/x", "a/_remote_logs/b", "_REMOTE_LOGS"], + ) + def test_dir_with_remote_logs_is_rejected(self, tmp_path: Path, value: str) -> None: + """SPEC_02「`results`」: _remote_logs は dir の部分として使えない.""" + _invalid(tmp_path, _results_data({"dir": value})) + + @pytest.mark.parametrize("value", ["labremote.yaml", "labremote.yaml/x", "LabRemote.YAML"]) + def test_dir_pointing_at_config_file_is_rejected(self, tmp_path: Path, value: str) -> None: + """SPEC_02「`results`」: dir に labremote.yaml を指す場所は書けない.""" + _invalid(tmp_path, _results_data({"dir": value})) + + +_FILE_LIST_LOCATIONS = ["pull", "checkpoints", "discard"] + + +def _with_files(where: str, files: list[object]) -> dict: + return {where: {"files": files}} + + +class TestResultsNames: + @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS) + @pytest.mark.parametrize("name", BAD_RESULT_NAMES, ids=repr) + def test_bad_file_name_is_rejected(self, tmp_path: Path, where: str, name: object) -> None: + """SPEC_02「`results`」. + + files に書けるのは 1 つのファイル名(/・\\・ワイルドカード・.・..・空・空白・NUL・ + 制御文字・Windows の名前・_remote_logs・文字列でない値は不可). + """ + _invalid(tmp_path, _results_data(_with_files(where, [name]))) + + @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS) + @pytest.mark.parametrize( + "name", + ["a.txt", "a b.txt", ".hidden", "CONSOLE.txt", "COM10", "nul_", "a.b.c", "日本語.txt"], + ) + def test_good_file_name_is_accepted(self, tmp_path: Path, where: str, name: str) -> None: + """SPEC_02「`results`」: 1 つのファイル名として書けるもの(予約名に似た名前を含む).""" + results = _load_results(tmp_path, _with_files(where, [name])) + assert getattr(results, where).files == (name,) + + @pytest.mark.parametrize("name", BAD_RESULT_NAMES, ids=repr) + def test_bad_checkpoints_dir_is_rejected(self, tmp_path: Path, name: object) -> None: + """SPEC_02「`results`」: checkpoints.dir は実験フォルダの直下の 1 つの名前で書く.""" + _invalid(tmp_path, _results_data({"checkpoints": {"dir": name}})) + + @pytest.mark.parametrize("name", ["weights", "ckpt", "model_out"]) + def test_good_checkpoints_dir_is_accepted(self, tmp_path: Path, name: str) -> None: + """SPEC_02「`results`」: checkpoints.dir に 1 つの名前を書ける.""" + assert _load_results(tmp_path, {"checkpoints": {"dir": name}}).checkpoints.dir == name + + @pytest.mark.parametrize("where", _FILE_LIST_LOCATIONS) + @pytest.mark.parametrize( + "files", [["a.txt", "a.txt"], ["a.txt", "A.TXT"], ["x", "y", "X"]], ids=repr + ) + def test_duplicate_names_are_rejected( + self, tmp_path: Path, where: str, files: list[str] + ) -> None: + """SPEC_02「`results`」: 一覧の中の重複はエラー(小文字にして比べる).""" + _invalid(tmp_path, _results_data(_with_files(where, files))) + + +_DIRS_LOCATIONS = ["pull", "discard"] + + +def _with_dirs(where: str, dirs: list[object]) -> dict: + return {where: {"dirs": dirs}} + + +class TestResultsDirPatterns: + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize("item", [{"path": "figs"}, {"suffix": ".png"}, {}], ids=repr) + def test_path_and_suffix_are_required(self, tmp_path: Path, where: str, item: dict) -> None: + """SPEC_02「`results`」: dirs は path と suffix の両方を必ず書く.""" + _invalid(tmp_path, _results_data(_with_dirs(where, [item]))) + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize( + "suffix", + [ + ".tar.gz", + "..png", + ".png.", + ".", + "png", + "", + ".*", + "*.png", + ".p?g", + ".[p]ng", + " .png", + ".png ", + ".p/g", + ".p\\g", + ".p:g", + ".p\x00g", + ".p\ng", + 1, + None, + [".png"], + ], + ids=repr, + ) + def test_bad_suffix_is_rejected(self, tmp_path: Path, where: str, suffix: object) -> None: + """SPEC_02「`results`」: suffix は . と 1 つの拡張子(.tar.gz・.・ワイルドカードは不可).""" + _invalid(tmp_path, _results_data(_with_dirs(where, [{"path": "figs", "suffix": suffix}]))) + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize("suffix", [".png", ".PNG", ".csv", ".x1", ".jpeg"]) + def test_good_suffix_is_accepted(self, tmp_path: Path, where: str, suffix: str) -> None: + """SPEC_02「`results`」: suffix は . で始まる 1 つの拡張子で書く.""" + results = _load_results(tmp_path, _with_dirs(where, [{"path": "figs", "suffix": suffix}])) + assert getattr(results, where).dirs[0].suffix == suffix + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize("path", BAD_RESULT_PATHS, ids=repr) + def test_bad_path_is_rejected(self, tmp_path: Path, where: str, path: object) -> None: + """SPEC_02「`results`」. + + dirs の path に書けないものは dir と同じ(Windows の名前・_remote_logs を含む). + """ + _invalid(tmp_path, _results_data(_with_dirs(where, [{"path": path, "suffix": ".png"}]))) + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize("path", ["figs", "out/plots", "a/b/c", "my figs"]) + def test_good_path_is_accepted(self, tmp_path: Path, where: str, path: str) -> None: + """SPEC_02「`results`」: dirs の path は実験フォルダからの相対パス(/ 区切り).""" + results = _load_results(tmp_path, _with_dirs(where, [{"path": path, "suffix": ".png"}])) + assert getattr(results, where).dirs[0].path == path + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize( + "pair", + [ + [("figs", ".png"), ("figs", ".png")], + [("figs", ".png"), ("Figs", ".png")], + [("figs", ".png"), ("figs", ".PNG")], + ], + ids=repr, + ) + def test_duplicate_dirs_are_rejected( + self, tmp_path: Path, where: str, pair: list[tuple[str, str]] + ) -> None: + """SPEC_02「`results`」: dirs の中の重複はエラー(小文字にして比べる).""" + dirs = [{"path": p, "suffix": s} for p, s in pair] + _invalid(tmp_path, _results_data(_with_dirs(where, dirs))) + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + def test_same_path_with_other_suffix_is_accepted(self, tmp_path: Path, where: str) -> None: + """SPEC_02「`results`」: path が同じでも suffix が違えば重複ではない.""" + dirs = [{"path": "figs", "suffix": ".png"}, {"path": "figs", "suffix": ".svg"}] + results = _load_results(tmp_path, _with_dirs(where, dirs)) + assert len(getattr(results, where).dirs) == 2 + + +# 重みの拡張子(push.exclude_suffixes に書いたもの) +WEIGHT_PUSH = {"exclude_suffixes": [".pth", ".onnx", ".tar.gz"]} + + +class TestResultsWeightsNotInPull: + @pytest.mark.parametrize( + "name", ["best.pth", "BEST.PTH", "best.Pth", "ResUNet.onnx", "model.tar.gz", "m.TAR.GZ"] + ) + def test_pull_file_with_weight_suffix_is_rejected(self, tmp_path: Path, name: str) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + pull.files に push.exclude_suffixes の拡張子は書けない. + """ + _invalid(tmp_path, _results_data({"pull": {"files": [name]}}, push=WEIGHT_PUSH)) + + @pytest.mark.parametrize("name", ["best.pth.txt", "onnx_notes.md", "a.gz", "a.tar"]) + def test_pull_file_without_weight_suffix_is_accepted(self, tmp_path: Path, name: str) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」: 拡張子が重みでない名前は書ける.""" + results = _load_results(tmp_path, {"pull": {"files": [name]}}, push=WEIGHT_PUSH) + assert results.pull.files == (name,) + + @pytest.mark.parametrize("suffix", [".pth", ".PTH", ".onnx", ".gz", ".GZ"]) + def test_pull_dir_suffix_with_weight_suffix_is_rejected( + self, tmp_path: Path, suffix: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + suffix に重みの拡張子(一方が他方の末尾も)は書けない. + """ + results = {"pull": {"dirs": [{"path": "figs", "suffix": suffix}]}} + _invalid(tmp_path, _results_data(results, push=WEIGHT_PUSH)) + + @pytest.mark.parametrize("suffix", [".png", ".tar", ".pt"]) + def test_pull_dir_suffix_not_overlapping_is_accepted(self, tmp_path: Path, suffix: str) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + 重なりの無い拡張子は書ける(.pth に対する .pt も). + """ + results = {"pull": {"dirs": [{"path": "figs", "suffix": suffix}]}} + assert _load_results(tmp_path, results, push=WEIGHT_PUSH).pull.dirs[0].suffix == suffix + + @pytest.mark.parametrize( + ("checkpoints", "path"), + [ + (None, "checkpoints"), + (None, "checkpoints/sub"), + (None, "Checkpoints"), + ({"dir": "weights"}, "weights"), + ({"dir": "weights"}, "weights/a/b"), + ({"dir": "weights"}, "WEIGHTS/a"), + ], + ) + def test_pull_dir_path_in_checkpoints_dir_is_rejected( + self, tmp_path: Path, checkpoints: dict | None, path: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + pull.dirs の path に checkpoints.dir と同じ場所・その中は書けない. + """ + results: dict = {"pull": {"dirs": [{"path": path, "suffix": ".png"}]}} + if checkpoints is not None: + results["checkpoints"] = checkpoints + _invalid(tmp_path, _results_data(results)) + + @pytest.mark.parametrize("path", ["checkpoints2", "a/checkpoints", "figs"]) + def test_pull_dir_path_outside_checkpoints_dir_is_accepted( + self, tmp_path: Path, path: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」: checkpoints.dir の外の path は書ける.""" + results = {"pull": {"dirs": [{"path": path, "suffix": ".png"}]}} + assert _load_results(tmp_path, results).pull.dirs[0].path == path + + def test_checkpoints_dir_changed_frees_default_name(self, tmp_path: Path) -> None: + """SPEC_02「`results`」. + + checkpoints.dir を変えれば,既定の名前 checkpoints は重みの置き場でない. + """ + results = { + "pull": {"dirs": [{"path": "checkpoints", "suffix": ".png"}]}, + "checkpoints": {"dir": "weights"}, + } + assert _load_results(tmp_path, results).pull.dirs[0].path == "checkpoints" + + @pytest.mark.parametrize( + ("pull", "ckpt"), [("best.onnx", "best.onnx"), ("Best.onnx", "best.onnx")] + ) + def test_same_name_in_pull_and_checkpoints_is_rejected( + self, tmp_path: Path, pull: str, ckpt: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + 同じ名前を pull.files と checkpoints.files に書けない. + """ + results = {"pull": {"files": [pull]}, "checkpoints": {"files": [ckpt]}} + _invalid(tmp_path, _results_data(results)) + + @pytest.mark.parametrize( + ("checkpoints", "name"), + [(None, "checkpoints"), (None, "Checkpoints"), ({"dir": "weights"}, "weights")], + ) + def test_pull_file_named_like_checkpoints_dir_is_rejected( + self, tmp_path: Path, checkpoints: dict | None, name: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + pull.files に checkpoints.dir と同じ名前は書けない. + """ + results: dict = {"pull": {"files": [name]}} + if checkpoints is not None: + results["checkpoints"] = checkpoints + _invalid(tmp_path, _results_data(results)) + + @pytest.mark.parametrize("path", ["figs", "figs/x", "Figs", "FIGS/a/b"]) + def test_pull_dir_path_starting_with_pull_file_name_is_rejected( + self, tmp_path: Path, path: str + ) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + pull.dirs の path の最初の部分に pull.files の名前は書けない. + """ + results = {"pull": {"files": ["figs"], "dirs": [{"path": path, "suffix": ".png"}]}} + _invalid(tmp_path, _results_data(results)) + + def test_pull_dir_path_with_pull_file_name_later_is_accepted(self, tmp_path: Path) -> None: + """SPEC_02「重みを一覧に紛れ込ませない」. + + 最初の部分でなければ,pull.files と同じ名前を path に書ける. + """ + results = {"pull": {"files": ["figs"], "dirs": [{"path": "out/figs", "suffix": ".png"}]}} + assert _load_results(tmp_path, results).pull.dirs[0].path == "out/figs" + + +class TestResultsPullAndDiscard: + @pytest.mark.parametrize(("pull", "discard"), [("a.txt", "a.txt"), ("a.txt", "A.TXT")]) + def test_same_file_in_pull_and_discard_is_rejected( + self, tmp_path: Path, pull: str, discard: str + ) -> None: + """SPEC_02「回収と破棄を両立させない」. + + 同じ名前を pull.files と discard.files に書けない. + """ + results = {"pull": {"files": [pull]}, "discard": {"files": [discard]}} + _invalid(tmp_path, _results_data(results)) + + @pytest.mark.parametrize( + "discard", [("figs", ".png"), ("Figs", ".png"), ("figs", ".PNG")], ids=repr + ) + def test_same_dir_pattern_in_pull_and_discard_is_rejected( + self, tmp_path: Path, discard: tuple[str, str] + ) -> None: + """SPEC_02「回収と破棄を両立させない」. + + 同じ path と suffix の組を pull.dirs と discard.dirs に書けない. + """ + results = { + "pull": {"dirs": [{"path": "figs", "suffix": ".png"}]}, + "discard": {"dirs": [{"path": discard[0], "suffix": discard[1]}]}, + } + _invalid(tmp_path, _results_data(results)) + + def test_different_dir_patterns_in_pull_and_discard_are_accepted(self, tmp_path: Path) -> None: + """SPEC_02「回収と破棄を両立させない」: 組が違えば,pull.dirs と discard.dirs に書ける.""" + results = { + "pull": {"files": ["a.txt"], "dirs": [{"path": "figs", "suffix": ".png"}]}, + "discard": {"files": ["b.txt"], "dirs": [{"path": "figs", "suffix": ".svg"}]}, + } + loaded = _load_results(tmp_path, results) + assert loaded.discard.files == ("b.txt",) + assert loaded.discard.dirs[0].suffix == ".svg" + + @pytest.mark.parametrize( + ("checkpoints", "path"), + [ + (None, "checkpoints"), + (None, "checkpoints/sub"), + (None, "CHECKPOINTS"), + ({"dir": "weights"}, "weights"), + ({"dir": "weights"}, "weights/x"), + ], + ) + def test_discard_dir_path_in_checkpoints_dir_is_rejected( + self, tmp_path: Path, checkpoints: dict | None, path: str + ) -> None: + """SPEC_02「回収と破棄を両立させない」. + + discard.dirs の path に checkpoints.dir と同じ場所・その中は書けない. + """ + results: dict = {"discard": {"dirs": [{"path": path, "suffix": ".pth"}]}} + if checkpoints is not None: + results["checkpoints"] = checkpoints + _invalid(tmp_path, _results_data(results)) + + +# 「すべて回収する」「検査を飛ばす」ようなキー.どれも未知のキーとして拒否される +LOOSENING_KEYS = [ + "all", + "include_all", + "allow", + "allow_all", + "skip_check", + "no_check", + "pattern", + "patterns", + "glob", + "regex", + "recursive", + "suffixes", + "extra", + "unsafe", + "force", +] + + +class TestResultsUnknownKeys: + @pytest.mark.parametrize("key", LOOSENING_KEYS) + @pytest.mark.parametrize("value", [True, "*", ["*"]], ids=repr) + def test_unknown_key_under_results_is_rejected( + self, tmp_path: Path, key: str, value: object + ) -> None: + """SPEC_02「`results`」: 未知のキーは拒否する(回収を広げるキーは無い).""" + _invalid(tmp_path, _results_data({key: value})) + + @pytest.mark.parametrize("where", ["pull", "checkpoints", "discard"]) + @pytest.mark.parametrize("key", LOOSENING_KEYS) + def test_unknown_key_under_lists_is_rejected( + self, tmp_path: Path, where: str, key: str + ) -> None: + """SPEC_02「`results`」: pull・checkpoints・discard の下の未知のキーは拒否する.""" + _invalid(tmp_path, _results_data({where: {key: True}})) + + @pytest.mark.parametrize("where", _DIRS_LOCATIONS) + @pytest.mark.parametrize("key", [*LOOSENING_KEYS, "depth", "include"]) + def test_unknown_key_in_dirs_item_is_rejected( + self, tmp_path: Path, where: str, key: str + ) -> None: + """SPEC_02「`results`」. + + dirs の要素の下の未知のキーは拒否する(下の階層を対象にするキーは無い). + """ + item = {"path": "figs", "suffix": ".png", key: True} + _invalid(tmp_path, _results_data(_with_dirs(where, [item]))) + + @pytest.mark.parametrize("value", ["runs", ["a"], 1, True]) + def test_results_must_be_mapping(self, tmp_path: Path, value: object) -> None: + """SPEC_02「`results`」: results は節(キーと値の対応)として書く.""" + _invalid(tmp_path, _results_data(value)) + + +class TestResultsDirAndPartial: + @pytest.mark.parametrize( + ("results_dir", "path"), + [ + (None, "runs"), + (None, "runs/x"), + (None, "Runs/x"), + ("output/runs", "output/runs"), + ("output/runs", "output/runs/x"), + ("output/runs", "Output/RUNS/x"), + ], + ) + def test_partial_in_results_dir_is_rejected( + self, tmp_path: Path, results_dir: str | None, path: str + ) -> None: + """SPEC_02「結果の置き場と送信」. + + push.partial の path に結果の置き場と同じ場所・その中は書けない. + """ + results = {} if results_dir is None else {"dir": results_dir} + push = {"partial": [{"path": path, "include": ["src"]}]} + _invalid(tmp_path, _results_data(results, push=push)) + + @pytest.mark.parametrize("path", ["runs", "runs/x", "output/other", "outputs/runs"]) + def test_partial_outside_changed_results_dir_is_accepted( + self, tmp_path: Path, path: str + ) -> None: + """SPEC_02「結果の置き場と送信」: dir を変えれば,既定の runs は結果の置き場でない.""" + push = {"partial": [{"path": path, "include": ["src"]}]} + config = load_remote_config( + _write(tmp_path, _results_data({"dir": "output/runs"}, push=push)) + ) + assert config.push.partial[0].path == path diff --git a/tests/test_files.py b/tests/test_files.py index d1e6445..ea602ec 100644 --- a/tests/test_files.py +++ b/tests/test_files.py @@ -912,3 +912,63 @@ selection = select_push_files(repo, push) assert [e.arcname for e in selection.entries] == REPO_CODE assert selection.skipped_links == ("ext/Sub/README.md",) + + +# --------------------------------------------------------------------------- +# 結果の置き場(設定の results.dir)は送信の固定の除外(SPEC_02「結果の置き場と送信」) +# --------------------------------------------------------------------------- + + +class TestResultsDirExclusion: + def test_changed_results_dir_is_not_sent(self, tmp_path: Path) -> None: + """SPEC_02「結果の置き場と送信」: dir を変えると,除外される場所もその場所に変わる.""" + _make_tree( + tmp_path, + [ + "output/runs/r1/metrics.json", + "output/runs/_remote_logs/a.log", + "output/other.txt", + "runs/x.txt", + "src/a.py", + ], + ) + arcnames = [ + e.arcname + for e in collect_push_entries(tmp_path, PushConfig(), results_dir="output/runs") + ] + # 既定の runs はもう結果の置き場ではないので送る(大文字小文字の違いは下の is_excluded で. + # 大文字小文字だけが違う 2 つのフォルダは Windows で同じものになるため,ここでは作らない) + assert sorted(arcnames) == ["output/other.txt", "runs/x.txt", "src/a.py"] + + def test_default_results_dir_is_not_sent(self, tmp_path: Path) -> None: + """SPEC_02「`results`」: dir の既定は runs で,ルートの直下の runs/ は送らない.""" + _make_tree(tmp_path, ["runs/x.txt", "src/runs/z.py", "src/a.py"]) + arcnames = [e.arcname for e in collect_push_entries(tmp_path, PushConfig())] + assert sorted(arcnames) == ["src/a.py", "src/runs/z.py"] + + @pytest.mark.parametrize( + ("rel", "excluded"), + [ + ("output/runs", True), + ("output/runs/x", True), + ("OUTPUT/runs/x", True), + ("output/RUNS/x/y", True), + ("output", False), + ("output/runs2/x", False), + ("output/x/runs/y", False), + ("runs/x", False), + ("a/output/runs/x", False), + ], + ) + def test_is_excluded_follows_results_dir(self, rel: str, excluded: bool) -> None: + """SPEC_02「結果の置き場と送信」. + + <ルート>/ とその中だけを送らない(小文字で比べる). + """ + rules = PushRules.from_push(PushConfig(), results_dir="output/runs") + assert is_excluded(rel, rules=rules) is excluded + + @pytest.mark.parametrize("rel", ["runs", "runs/x", "Runs/x", "RUNS/a/b"]) + def test_default_results_dir_ignores_case(self, rel: str) -> None: + """SPEC_02「`push`」の名前の比べ方: 結果の置き場は小文字にして比べる(Runs も送らない).""" + assert is_excluded(rel, rules=PushRules.from_push(PushConfig())) diff --git a/tests/test_transfer.py b/tests/test_transfer.py index ab72194..d67721c 100644 --- a/tests/test_transfer.py +++ b/tests/test_transfer.py @@ -15,6 +15,7 @@ import pytest from link_helpers import LinkFactory +from results_helpers import OTHER_RESULTS, SAMPLE_RESULTS from labremote.files import PushEntry from labremote.transfer import extract_pull_archive, write_tar_stream @@ -61,7 +62,9 @@ _add_file(tar, f"{RUN_ID}/figures/loss.png", b"png") dest = tmp_path / "runs" - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) + result = extract_pull_archive( + _archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False + ) assert result.files == 3 assert (dest / RUN_ID / "config.yaml").read_bytes() == b"seed: 0\n" assert (dest / RUN_ID / "figures" / "loss.png").read_bytes() == b"png" @@ -72,7 +75,7 @@ (dest / RUN_ID).mkdir(parents=True) (dest / RUN_ID / "metrics.json").write_bytes(b"old") archive = _archive(lambda tar: _add_file(tar, f"{RUN_ID}/metrics.json", b"new")) - extract_pull_archive(archive, dest, RUN_ID, with_checkpoints=False) + extract_pull_archive(archive, dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False) assert (dest / RUN_ID / "metrics.json").read_bytes() == b"new" @@ -84,10 +87,12 @@ dest = tmp_path / "runs" with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) + extract_pull_archive(_archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False) assert _all_files(dest) == [] - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True) + result = extract_pull_archive( + _archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=True + ) assert result.files == 3 assert (dest / RUN_ID / "checkpoints" / "best.pth").read_bytes() == b"weights" assert (dest / RUN_ID / "checkpoints" / "ResUNet.onnx").read_bytes() == b"onnx" @@ -159,7 +164,7 @@ work = tmp_path / "work" dest = work / "runs" with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True) + extract_pull_archive(_archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=True) # 展開先にも,その外側(パス外に出る名前の行き先)にも何も作られない assert _all_files(dest) == [] assert not (dest / RUN_ID / "config.yaml").exists() @@ -179,7 +184,9 @@ _add_dir(tar, f"{RUN_ID}/{secret}") with pytest.raises(ValueError) as excinfo: - extract_pull_archive(_archive(build), tmp_path / "runs", RUN_ID, with_checkpoints=False) + extract_pull_archive( + _archive(build), tmp_path / "runs", RUN_ID, SAMPLE_RESULTS, with_checkpoints=False + ) assert secret not in str(excinfo.value) assert "yamada" not in str(excinfo.value) @@ -187,13 +194,19 @@ def test_broken_archive_extracts_nothing(tmp_path: Path) -> None: dest = tmp_path / "runs" with pytest.raises(tarfile.TarError): - extract_pull_archive(io.BytesIO(b"not a tar" * 100), dest, RUN_ID, with_checkpoints=False) + extract_pull_archive( + io.BytesIO(b"not a tar" * 100), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False + ) assert _all_files(dest) == [] def test_empty_archive_extracts_nothing(tmp_path: Path) -> None: result = extract_pull_archive( - _archive(lambda tar: None), tmp_path / "runs", RUN_ID, with_checkpoints=False + _archive(lambda tar: None), + tmp_path / "runs", + RUN_ID, + SAMPLE_RESULTS, + with_checkpoints=False, ) assert result.files == 0 @@ -329,7 +342,7 @@ dest = tmp_path / "runs" with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) + extract_pull_archive(_archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False) assert _all_files(dest) == [] @@ -339,10 +352,98 @@ _add_file(tar, f"{RUN_ID}/figures/{name}") dest = tmp_path / "runs" - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) + result = extract_pull_archive( + _archive(build), dest, RUN_ID, SAMPLE_RESULTS, with_checkpoints=False + ) assert result.files == 3 assert sorted(p.name for p in (dest / RUN_ID / "figures").iterdir()) == [ "COM10.png", "CONSOLE.png", "nul_.png", ] + + +# --------------------------------------------------------------------------- +# 別の一覧(tests/results_helpers.py の OTHER_RESULTS)での展開(SPEC_02「`results`」) +# --------------------------------------------------------------------------- + +OTHER_ALLOWED = ["summary.txt", "scores.tsv", "out/plots/a.svg", "curves/train.csv"] + + +def _relative_files(root: Path) -> list[str]: + return sorted(p.relative_to(root).as_posix() for p in _all_files(root) if p.is_file()) + + +def test_other_list_extracts_only_its_names(tmp_path: Path) -> None: + """SPEC_02「`results`」: 一覧を変えると,その一覧の名前が展開される(空で通らない).""" + + def build(tar: tarfile.TarFile) -> None: + for name in OTHER_ALLOWED: + _add_file(tar, f"{RUN_ID}/{name}", name.encode()) + + dest = tmp_path / "output" / "runs" + result = extract_pull_archive( + _archive(build), dest, RUN_ID, OTHER_RESULTS, with_checkpoints=False + ) + assert result.files == len(OTHER_ALLOWED) + assert _relative_files(dest) == sorted(f"{RUN_ID}/{name}" for name in OTHER_ALLOWED) + + +def test_other_list_extracts_weights_only_with_flag(tmp_path: Path) -> None: + """SPEC_02「`results`」: checkpoints.files の名前は --with-checkpoints のときだけ展開する.""" + + def build(tar: tarfile.TarFile) -> None: + _add_file(tar, f"{RUN_ID}/summary.txt") + _add_file(tar, f"{RUN_ID}/weights/final.ckpt", b"w") + + dest = tmp_path / "output" / "runs" + with pytest.raises(ValueError): + extract_pull_archive(_archive(build), dest, RUN_ID, OTHER_RESULTS, with_checkpoints=False) + assert _all_files(dest) == [] + extract_pull_archive(_archive(build), dest, RUN_ID, OTHER_RESULTS, with_checkpoints=True) + assert _relative_files(dest) == [f"{RUN_ID}/summary.txt", f"{RUN_ID}/weights/final.ckpt"] + + +OTHER_BAD_MEMBERS = { + # SAMPLE_RESULTS の一覧の名前(OTHER_RESULTS には無い) + "sample_root_file": lambda tar: _add_file(tar, f"{RUN_ID}/config.yaml"), + "sample_figure": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a.png"), + "sample_weight": lambda tar: _add_file(tar, f"{RUN_ID}/checkpoints/best.pth"), + # discard の名前(回収の一覧ではない) + "discard_file": lambda tar: _add_file(tar, f"{RUN_ID}/trace.bin"), + "discard_dir": lambda tar: _add_file(tar, f"{RUN_ID}/debug/a.png"), + # 下の階層・大文字小文字・一覧に無い重み + "nested": lambda tar: _add_file(tar, f"{RUN_ID}/out/plots/sub/a.svg"), + "case": lambda tar: _add_file(tar, f"{RUN_ID}/Summary.txt"), + "other_weight": lambda tar: _add_file(tar, f"{RUN_ID}/weights/other.ckpt"), + # 外へ出るパス・リンク・Windows で別の場所を指す名前 + "parent": lambda tar: _add_file(tar, f"{RUN_ID}/../evil.txt"), + "symlink": lambda tar: _add_link(tar, f"{RUN_ID}/summary.txt", "/etc/passwd", tarfile.SYMTYPE), + "hardlink": lambda tar: _add_link( + tar, f"{RUN_ID}/scores.tsv", f"{RUN_ID}/trace.bin", tarfile.LNKTYPE + ), + "stream": lambda tar: _add_file(tar, f"{RUN_ID}/summary.txt:x"), + "reserved": lambda tar: _add_file(tar, f"{RUN_ID}/out/plots/con.svg"), +} + + +@pytest.mark.parametrize("bad", list(OTHER_BAD_MEMBERS), ids=list(OTHER_BAD_MEMBERS)) +@pytest.mark.parametrize("with_checkpoints", [False, True]) +def test_other_list_bad_member_aborts_without_extracting_anything( + tmp_path: Path, bad: str, with_checkpoints: bool +) -> None: + """SPEC_01「回収」: 別の一覧でも,一覧に無い名前が 1 つでもあれば何も展開しない.""" + + def build(tar: tarfile.TarFile) -> None: + _add_file(tar, f"{RUN_ID}/summary.txt") + OTHER_BAD_MEMBERS[bad](tar) + _add_file(tar, f"{RUN_ID}/out/plots/a.svg") + _add_file(tar, f"{RUN_ID}/weights/final.ckpt") + + work = tmp_path / "work" + dest = work / "output" / "runs" + with pytest.raises(ValueError): + extract_pull_archive( + _archive(build), dest, RUN_ID, OTHER_RESULTS, with_checkpoints=with_checkpoints + ) + assert [p for p in _all_files(tmp_path) if p.is_file()] == [] diff --git a/tests/test_whitelist.py b/tests/test_whitelist.py index 4693502..d329e9f 100644 --- a/tests/test_whitelist.py +++ b/tests/test_whitelist.py @@ -1,12 +1,13 @@ -"""回収ホワイトリストの判定のテスト(SPEC_01「回収ホワイトリスト」・SPEC_03「pull」). +"""回収の判定のテスト(SPEC_01「安全の枠」の「回収」・SPEC_02「`results`」・SPEC_03「pull」). 最重要(testing ルールの必須対象 1): 名前が一致するファイルだけが回収対象になり,分割結果・ 画像ごとの予測・画像・manifest・指定の無い重みは回収されないこと.破れるとファイル名を含む結果や 画像が手元に流れる. -回収する(`runs/<実験ID>/` 配下): `config.yaml`・`history.csv`・`metrics.json`・`log.txt`・ -`figures/*.png`(直下のみ).`--with-checkpoints` のときだけ `checkpoints/best.pth`・ -`checkpoints/ResUNet.onnx`(名前の完全一致).それ以外はすべて回収しない. +テスト用の設定の一覧(`tests/results_helpers.py`)で回収する(`runs/<実験ID>/` 配下): +`config.yaml`・`history.csv`・`metrics.json`・`log.txt`・`figures/*.png`(直下のみ). +`--with-checkpoints` のときだけ `checkpoints/best.pth`・`checkpoints/ResUNet.onnx` +(名前の完全一致).それ以外はすべて回収しない. TIASJudgeModel の tests/remote/test_whitelist.py の移植.回収するファイル名と重みの名前を TongueSegModel の SPEC_01 に合わせ,抜け道(`:`・末尾の `.` や空白・大文字小文字・制御文字・ @@ -18,11 +19,12 @@ from datetime import datetime import pytest +from results_helpers import OTHER_RESULTS, SAMPLE_RESULTS +from labremote.config import ResultsConfig from labremote.whitelist import ( - PULL_CHECKPOINT_FILES, - PULL_ROOT_FILES, check_pull_members, + has_pull_names, is_pull_allowed, parse_find_listing, plan_pull, @@ -30,8 +32,10 @@ ) RUN_ID = "20261119-120000_resunet_abc1234" +# 回収の一覧は設定から与える(tests/results_helpers.py.下の ROOT_FILES・FIGURES・CHECKPOINTS) +RESULTS = SAMPLE_RESULTS -# SPEC_01「回収ホワイトリスト」の表 +# テスト用の設定(RESULTS)の一覧 ROOT_FILES = ["config.yaml", "history.csv", "metrics.json", "log.txt"] FIGURES = ["figures/loss.png", "figures/iou.png", "figures/learning_curve.png", "figures/a b.png"] CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.onnx"] @@ -151,20 +155,24 @@ ] -def test_root_files_are_exactly_the_spec_list() -> None: - # 回収対象を増やすときは SPEC_01 とこのテストを同時に変える - assert PULL_ROOT_FILES == frozenset(ROOT_FILES) +def test_test_results_list_is_exactly_the_names_above() -> None: + # テストの前提(RESULTS の一覧)と,上の ROOT_FILES・CHECKPOINTS の食い違いを防ぐ + assert RESULTS.pull.files == tuple(ROOT_FILES) + assert RESULTS.checkpoints.files == ("best.pth", "ResUNet.onnx") -def test_checkpoint_files_are_exactly_the_spec_list() -> None: - assert PULL_CHECKPOINT_FILES == frozenset({"best.pth", "ResUNet.onnx"}) +def test_default_results_pull_nothing() -> None: + # results を省略した設定では,回収の一覧が空になり何も回収しない(SPEC_02「`results`」) + empty = ResultsConfig() + for name in ALLOWED + CHECKPOINTS: + assert not is_pull_allowed(name, empty, with_checkpoints=True) class TestIsPullAllowed: @pytest.mark.parametrize("name", ALLOWED) @pytest.mark.parametrize("with_checkpoints", [False, True]) def test_allowed_names(self, name: str, with_checkpoints: bool) -> None: - assert is_pull_allowed(name, with_checkpoints=with_checkpoints) + assert is_pull_allowed(name, RESULTS, with_checkpoints=with_checkpoints) @pytest.mark.parametrize("name", NOT_ALLOWED) @pytest.mark.parametrize("with_checkpoints", [False, True]) @@ -172,20 +180,20 @@ self, name: str, with_checkpoints: bool ) -> None: # --with-checkpoints は checkpoints/best.pth・ResUNet.onnx 以外の判定を変えない - assert not is_pull_allowed(name, with_checkpoints=with_checkpoints) + assert not is_pull_allowed(name, RESULTS, with_checkpoints=with_checkpoints) @pytest.mark.parametrize("name", ["split.json", "predictions.csv", "manifest.csv"]) def test_per_image_results_never_pulled_even_with_checkpoints(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=True) + assert not is_pull_allowed(name, RESULTS, with_checkpoints=True) @pytest.mark.parametrize("name", CHECKPOINTS) def test_checkpoints_only_with_flag(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=False) - assert is_pull_allowed(name, with_checkpoints=True) + assert not is_pull_allowed(name, RESULTS, with_checkpoints=False) + assert is_pull_allowed(name, RESULTS, with_checkpoints=True) @pytest.mark.parametrize("name", UNSAFE_PATHS) def test_unsafe_paths_are_not_allowed(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=True) + assert not is_pull_allowed(name, RESULTS, with_checkpoints=True) class TestValidateRunId: @@ -308,7 +316,7 @@ def test_selects_only_whitelisted_files(self) -> None: listing = self._listing(ALLOWED + NOT_ALLOWED + CHECKPOINTS) - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) + plan = plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=False) assert sorted(plan.files) == sorted(f"{RUN_ID}/{name}" for name in ALLOWED) assert plan.skipped == len(NOT_ALLOWED) + len(CHECKPOINTS) assert plan.skipped_checkpoints == len(CHECKPOINTS) @@ -317,7 +325,7 @@ listing = self._listing( ["config.yaml", *CHECKPOINTS, "checkpoints/epoch3.pth", "split.json", "predictions.csv"] ) - plan = plan_pull(listing, RUN_ID, with_checkpoints=True) + plan = plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=True) assert sorted(plan.files) == sorted( [f"{RUN_ID}/config.yaml", *(f"{RUN_ID}/{name}" for name in CHECKPOINTS)] ) @@ -329,7 +337,7 @@ self, kind: str ) -> None: listing = self._listing(["config.yaml", "figures/a.png", "checkpoints/best.pth"], kind) - plan = plan_pull(listing, RUN_ID, with_checkpoints=True) + plan = plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=True) assert plan.files == () assert plan.skipped == 3 @@ -346,7 +354,7 @@ ], ) def test_files_outside_the_run_are_not_selected(self, path: str) -> None: - plan = plan_pull([("f", path)], RUN_ID, with_checkpoints=True) + plan = plan_pull([("f", path)], RUN_ID, RESULTS, with_checkpoints=True) assert plan.files == () assert plan.skipped == 1 @@ -363,12 +371,12 @@ data = f"f {RUN_ID}/split.json\nf {RUN_ID}/config.yaml\0".encode() listing = parse_find_listing(data) assert len(listing) == 1 - assert plan_pull(listing, RUN_ID, with_checkpoints=False).files == () + assert plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=False).files == () def test_non_utf8_names_are_not_selected(self) -> None: data = b"f " + RUN_ID.encode() + b"/figures/\xff\xfe.png\0" listing = parse_find_listing(data) - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) + plan = plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=False) # 名前としては figures/*.png に一致する.選ばれたなら tar の側でも同じ名前で検査される assert len(plan.files) + plan.skipped == 1 @@ -421,14 +429,14 @@ class TestCheckPullMembers: def test_accepts_only_whitelisted_regular_files(self) -> None: members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED] - assert check_pull_members(members, RUN_ID, with_checkpoints=False) == len(members) + assert check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False) == len(members) def test_accepts_checkpoints_with_flag(self) -> None: members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED + CHECKPOINTS] - assert check_pull_members(members, RUN_ID, with_checkpoints=True) == len(members) + assert check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=True) == len(members) def test_empty_archive_is_accepted_as_zero(self) -> None: - assert check_pull_members([], RUN_ID, with_checkpoints=False) == 0 + assert check_pull_members([], RUN_ID, RESULTS, with_checkpoints=False) == 0 @pytest.mark.parametrize("bad", BAD_MEMBERS, ids=lambda info: repr(info.name)[:60]) @pytest.mark.parametrize("with_checkpoints", [False, True]) @@ -437,13 +445,13 @@ ) -> None: members = [_regular(f"{RUN_ID}/config.yaml"), bad, _regular(f"{RUN_ID}/log.txt")] with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=with_checkpoints) @pytest.mark.parametrize("name", CHECKPOINTS) def test_checkpoints_rejected_without_flag(self, name: str) -> None: members = [_regular(f"{RUN_ID}/config.yaml"), _regular(f"{RUN_ID}/{name}")] with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=False) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False) def test_error_message_does_not_contain_member_names(self) -> None: secret = "P0001_yamada_tongue" @@ -456,7 +464,7 @@ _regular(f"{RUN_ID}/checkpoints/{secret}.pth"), ] with pytest.raises(ValueError) as excinfo: - check_pull_members(members, RUN_ID, with_checkpoints=False) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False) message = str(excinfo.value) assert secret not in message assert "yamada" not in message @@ -471,7 +479,7 @@ tar.addfile(_typed(f"{RUN_ID}/log.txt", tarfile.SYMTYPE, "/etc/shadow")) buffer.seek(0) with tarfile.open(fileobj=buffer, mode="r") as tar, pytest.raises(ValueError): - check_pull_members(tar.getmembers(), RUN_ID, with_checkpoints=False) + check_pull_members(tar.getmembers(), RUN_ID, RESULTS, with_checkpoints=False) def test_pax_path_override_is_checked(self) -> None: """PAX ヘッダの path で名前を差し替えたメンバーも,差し替え後の名前で検査する.""" @@ -485,7 +493,7 @@ members = tar.getmembers() assert members[0].name == f"{RUN_ID}/split.json" with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=True) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=True) # --------------------------------------------------------------------------- @@ -588,7 +596,7 @@ def test_reserved_or_trailing_dot_names_are_not_pulled( self, name: str, with_checkpoints: bool ) -> None: - assert not is_pull_allowed(name, with_checkpoints=with_checkpoints) + assert not is_pull_allowed(name, RESULTS, with_checkpoints=with_checkpoints) @pytest.mark.parametrize( "name", @@ -602,15 +610,15 @@ ], ) def test_names_similar_to_reserved_are_pulled(self, name: str) -> None: - assert is_pull_allowed(name, with_checkpoints=False) + assert is_pull_allowed(name, RESULTS, with_checkpoints=False) @pytest.mark.parametrize("base", RESERVED_BASES) def test_every_reserved_base_is_rejected(self, base: str) -> None: - assert not is_pull_allowed(f"figures/{base}.png", with_checkpoints=True) + assert not is_pull_allowed(f"figures/{base}.png", RESULTS, with_checkpoints=True) @pytest.mark.parametrize("base", NOT_RESERVED_BASES) def test_every_not_reserved_base_is_accepted(self, base: str) -> None: - assert is_pull_allowed(f"figures/{base}.png", with_checkpoints=False) + assert is_pull_allowed(f"figures/{base}.png", RESULTS, with_checkpoints=False) def test_plan_pull_skips_reserved_names(self) -> None: listing = [ @@ -619,7 +627,7 @@ ("f", f"{RUN_ID}/figures/nul .png"), ("f", f"{RUN_ID}/figures/CONSOLE.png"), ] - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) + plan = plan_pull(listing, RUN_ID, RESULTS, with_checkpoints=False) assert plan.files == (f"{RUN_ID}/config.yaml", f"{RUN_ID}/figures/CONSOLE.png") assert plan.skipped == 2 @@ -645,7 +653,7 @@ def test_whole_archive_is_rejected(self, name: str, with_checkpoints: bool) -> None: members = [_regular(f"{RUN_ID}/config.yaml"), _regular(name), _regular(f"{RUN_ID}/log.txt")] with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=with_checkpoints) def test_names_similar_to_reserved_are_accepted(self) -> None: members = [ @@ -653,11 +661,283 @@ _regular(f"{RUN_ID}/figures/COM10.png"), _regular(f"{RUN_ID}/figures/nul_.png"), ] - assert check_pull_members(members, RUN_ID, with_checkpoints=False) == 3 + assert check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False) == 3 def test_error_message_does_not_contain_reserved_member_names(self) -> None: members = [_regular(f"{RUN_ID}/figures/P0001_yamada.png."), _regular(f"{RUN_ID}/nul.txt")] with pytest.raises(ValueError) as excinfo: - check_pull_members(members, RUN_ID, with_checkpoints=False) + check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False) assert "yamada" not in str(excinfo.value) assert "nul" not in str(excinfo.value) + + +# --------------------------------------------------------------------------- +# 一覧を設定で変えたときの判定(SPEC_02「`results`」・SPEC_01「安全の枠」の「回収」) +# --------------------------------------------------------------------------- + +# tests/results_helpers.py の OTHER_RESULTS(SAMPLE_RESULTS とは別の一覧)で回収するもの +OTHER_ALLOWED = [ + "summary.txt", + "scores.tsv", + "out/plots/a.svg", + "out/plots/loss curve.svg", + "curves/train.csv", +] +OTHER_CHECKPOINTS = ["weights/final.ckpt"] + +# OTHER_RESULTS で回収しないもの(--with-checkpoints を付けても) +OTHER_NOT_ALLOWED = [ + # pull.dirs は path の直下だけ(path が複数の部分でも) + "out/plots/sub/a.svg", + "out/plots/a/b/c.svg", + "out/a.svg", + "plots/a.svg", + "a.svg", + "x/out/plots/a.svg", + "curves/sub/train.csv", + "out/plots/.svg", + # 大文字と小文字を区別した完全一致 + "Summary.txt", + "SUMMARY.TXT", + "summary.TXT", + "out/plots/a.SVG", + "out/plots/a.Svg", + "Out/plots/a.svg", + "out/Plots/a.svg", + "Curves/train.csv", + "curves/train.CSV", + # 拡張子・中身では判断しない(一覧に無い .png・.csv・.json 等) + "summary.csv", + "metrics.csv", + "result.json", + "a.png", + "out/plots/a.png", + "out/plots/a.csv", + "curves/a.svg", + "curves/a.json", + "summary.txt.bak", + "summary.txt.", + "summary.txt ", + # discard に書いた名前は回収の一覧ではない + "trace.bin", + "debug/a.png", + "debug/sub/a.png", + # 重み: checkpoints.files に無い名前・下の階層・置き場の外・既定の置き場の名前 + "weights/other.ckpt", + "weights/Final.ckpt", + "weights/final.CKPT", + "weights/final.ckpt.bak", + "weights/sub/final.ckpt", + "Weights/final.ckpt", + "final.ckpt", + "out/plots/final.ckpt", + "checkpoints/final.ckpt", + "checkpoints/best.pth", + "weights/summary.txt", + "weights/a.svg", +] + +# SAMPLE_RESULTS の一覧にあった名前.OTHER_RESULTS では対象にならない(古い一覧が残っていない) +SAMPLE_NAMES = ALLOWED + CHECKPOINTS + + +class TestOtherResultsList: + """一覧を設定で変えると,回収の対象がその一覧のとおりに変わる(SPEC_02「`results`」).""" + + @pytest.mark.parametrize("name", OTHER_ALLOWED) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_names_in_other_list_are_allowed(self, name: str, with_checkpoints: bool) -> None: + """SPEC_01「回収」: 設定の一覧に名前が完全に一致するファイルを回収する.""" + assert is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints) + + @pytest.mark.parametrize("name", SAMPLE_NAMES) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_names_of_sample_list_are_not_allowed(self, name: str, with_checkpoints: bool) -> None: + """SPEC_02「`results`」. + + 判定は設定の一覧だけを見る(別の一覧の名前・古い定数は効かない). + """ + assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints) + + @pytest.mark.parametrize("name", OTHER_NOT_ALLOWED) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_names_outside_other_list_are_not_allowed( + self, name: str, with_checkpoints: bool + ) -> None: + """SPEC_02「名前の比べ方」: 直下だけ・大文字小文字を区別した完全一致・拡張子で判断しない.""" + assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints) + + @pytest.mark.parametrize("name", OTHER_CHECKPOINTS) + def test_other_checkpoints_only_with_flag(self, name: str) -> None: + """SPEC_02「`results`」. + + checkpoints.files の名前は --with-checkpoints のときだけ回収する. + """ + assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=False) + assert is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=True) + + @pytest.mark.parametrize("name", ["trace.bin", "debug/a.png"]) + def test_discard_names_are_not_pull_names(self, name: str) -> None: + """SPEC_02「`results`」: discard は回収の一覧ではない(名前を書いても回収しない).""" + assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=True) + + def test_pull_dir_with_one_part_is_also_direct_only(self) -> None: + """SPEC_02「`results`」. + + pull.dirs の対象は path の直下だけ(SAMPLE の figures でも同じ). + """ + assert is_pull_allowed("figures/a.png", RESULTS, with_checkpoints=False) + assert not is_pull_allowed("figures/sub/a.png", RESULTS, with_checkpoints=True) + + +class TestEmptyResultsList: + """一覧が空(`results` を省略)のとき,何も対象にならない(SPEC_02「`results`」の冒頭).""" + + @pytest.mark.parametrize( + "name", + SAMPLE_NAMES + OTHER_ALLOWED + OTHER_CHECKPOINTS + ["checkpoints/x.pth", "runs/x"], + ) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_nothing_is_allowed(self, name: str, with_checkpoints: bool) -> None: + """SPEC_02「`results`」: 省略したときは回収する名前の一覧が空になる.""" + assert not is_pull_allowed(name, ResultsConfig(), with_checkpoints=with_checkpoints) + + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_plan_selects_nothing(self, with_checkpoints: bool) -> None: + """SPEC_02「`results`」: 一覧が空なら,サーバの一覧から何も選ばない(重みも).""" + names = SAMPLE_NAMES + OTHER_ALLOWED + OTHER_CHECKPOINTS + listing = [("f", f"{RUN_ID}/{name}") for name in names] + plan = plan_pull(listing, RUN_ID, ResultsConfig(), with_checkpoints=with_checkpoints) + assert plan.files == () + assert plan.skipped == len(names) + + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_has_no_pull_names(self, with_checkpoints: bool) -> None: + """SPEC_02「`results`」: 一覧が空のときは回収しうる名前が無い.""" + assert not has_pull_names(ResultsConfig(), with_checkpoints=with_checkpoints) + + def test_checkpoints_only_has_names_only_with_flag(self) -> None: + """SPEC_02「`results`」. + + 重みだけが書かれていれば,--with-checkpoints のときだけ名前がある. + """ + only_weights = ResultsConfig.model_validate({"checkpoints": {"files": ["best.pth"]}}) + assert not has_pull_names(only_weights, with_checkpoints=False) + assert has_pull_names(only_weights, with_checkpoints=True) + assert has_pull_names(OTHER_RESULTS, with_checkpoints=False) + + +def _accepted_by_tar_check( + names: list[str], results: ResultsConfig, *, with_checkpoints: bool +) -> set[str]: + """tar の全件検査(check_pull_members)が,1 件だけの tar として受け入れる名前の集合.""" + accepted = set() + for name in names: + try: + count = check_pull_members( + [_regular(f"{RUN_ID}/{name}")], RUN_ID, results, with_checkpoints=with_checkpoints + ) + except ValueError: + continue + assert count == 1 + accepted.add(name) + return accepted + + +# 二重の確認の両方に与える名前(両方の一覧の名前・一覧に無い名前・外へ出る名前) +CANDIDATES = ( + SAMPLE_NAMES + + NOT_ALLOWED + + UNSAFE_PATHS + + OTHER_ALLOWED + + OTHER_CHECKPOINTS + + OTHER_NOT_ALLOWED +) + + +class TestDoubleCheckAgrees: + """二重の確認の両方が,同じ設定で同じ判定をする(SPEC_01「安全の枠」の「回収」).""" + + @pytest.mark.parametrize( + ("results", "expected_without", "expected_with"), + [ + (RESULTS, ALLOWED, ALLOWED + CHECKPOINTS), + (OTHER_RESULTS, OTHER_ALLOWED, OTHER_ALLOWED + OTHER_CHECKPOINTS), + (ResultsConfig(), [], []), + ], + ids=["sample", "other", "empty"], + ) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_plan_and_tar_check_select_the_same_names( + self, + results: ResultsConfig, + expected_without: list[str], + expected_with: list[str], + with_checkpoints: bool, + ) -> None: + """SPEC_01「回収」: サーバの一覧の絞り込みと tar の全件検査が,同じ名前を対象とする.""" + listing = [("f", f"{RUN_ID}/{name}") for name in CANDIDATES] + plan = plan_pull(listing, RUN_ID, results, with_checkpoints=with_checkpoints) + planned = {path.removeprefix(f"{RUN_ID}/") for path in plan.files} + by_tar = _accepted_by_tar_check(CANDIDATES, results, with_checkpoints=with_checkpoints) + expected = set(expected_with if with_checkpoints else expected_without) + assert planned == expected + assert by_tar == expected + + @pytest.mark.parametrize( + "bad", + [ + "summary.txt.bak", + "config.yaml", + "figures/a.png", + "trace.bin", + "weights/other.ckpt", + "out/plots/sub/a.svg", + "../summary.txt", + ], + ) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_other_list_rejects_whole_archive_if_any_member_is_bad( + self, bad: str, with_checkpoints: bool + ) -> None: + """SPEC_01「回収」: 別の一覧でも,一覧に無い名前が 1 つでもあれば tar 全体を拒否する.""" + members = [_regular(f"{RUN_ID}/summary.txt"), _regular(f"{RUN_ID}/{bad}")] + with pytest.raises(ValueError): + check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=with_checkpoints) + + def test_other_list_rejects_weights_without_flag(self) -> None: + """SPEC_01「回収」: 別の一覧でも,重みは --with-checkpoints 無しでは tar ごと拒否する.""" + members = [_regular(f"{RUN_ID}/summary.txt"), _regular(f"{RUN_ID}/weights/final.ckpt")] + with pytest.raises(ValueError): + check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=False) + assert check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=True) == 2 + + @pytest.mark.parametrize( + "bad", + [ + _typed(f"{RUN_ID}/summary.txt", tarfile.SYMTYPE, "/etc/passwd"), + _typed(f"{RUN_ID}/scores.tsv", tarfile.LNKTYPE, f"{RUN_ID}/trace.bin"), + _regular(f"{RUN_ID}/summary.txt:stream"), + _regular(f"{RUN_ID}/out/plots/nul.svg"), + _regular(f"{RUN_ID}/../summary.txt"), + _regular(f"/{RUN_ID}/summary.txt"), + ], + ids=lambda info: repr(info.name)[:60], + ) + def test_other_list_rejects_links_and_unsafe_names(self, bad: tarfile.TarInfo) -> None: + """SPEC_01「回収」. + + 別の一覧でも,リンク・外へ出るパス・Windows で別の場所を指す名前は拒否. + """ + members = [_regular(f"{RUN_ID}/summary.txt"), bad] + with pytest.raises(ValueError): + check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=True) + + def test_plan_counts_skipped_without_names(self) -> None: + """SPEC_01「回収」: 回収しなかったものは件数で数え,計画の対象に名前を含めない.""" + names = OTHER_ALLOWED + ["trace.bin", "secret_case07.png"] + OTHER_CHECKPOINTS + listing = [("f", f"{RUN_ID}/{name}") for name in names] + plan = plan_pull(listing, RUN_ID, OTHER_RESULTS, with_checkpoints=False) + assert plan.skipped == 3 + assert plan.skipped_checkpoints == 1 + assert not any("secret_case07" in path or "trace.bin" in path for path in plan.files)