diff --git a/CLAUDE.md b/CLAUDE.md index 1f656af..dcd97a8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ ## 開発進捗 -最新: PLAN_02 のステップ 2-1(`ls`: サーバに残っているものの一覧)完了.次はステップ 2-2(`clean` の判定) +最新: PLAN_02 のステップ 2-2(`clean` の判定と `--dry-run`.削除はまだ無い)完了.次はステップ 2-3(`clean` の削除) ※ 本欄は**最新ステップ 1 行のみ上書き更新**.詳細な進捗履歴(動機・設計判断・失敗パターン)は [docs/PROGRESS.md](docs/PROGRESS.md) に追記する.運用ルールは `.claude/rules/progress-log.md` を参照(該当ファイル編集時に自動ロードされる). ## 必須ルール(コード実装時) diff --git "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" index 3444bf4..c58fe31 100644 --- "a/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" +++ "b/docs/02_ENV/ENV_04_\351\226\213\347\231\272\343\202\263\343\203\236\343\203\263\343\203\211.md" @@ -36,5 +36,5 @@ - `uv run ruff format .` は Markdown の中の Python のコードブロックも整形する.`.claude/` は対象から外してある(`pyproject.toml`) - `labremote` のサブコマンド(`push`・`run`・`pull` 等)は,`labremote.yaml` のあるフォルダ(またはその下)で実行するものである.LabRemote 自身のリポジトリには `labremote.yaml` を置かないので,ここで実行できるのは `--help` と単体テストだけである - 別のフォルダに置いた設定で試すときは,そのフォルダで `uv run --project labremote <サブコマンド>` を実行する.`push --dry-run` は,サーバに接続せずに,設定の読み込みと送るファイルの一覧までを確かめられる -- 手元(権限の無い Windows)では,スキップされるテストが 44 件ある.25 件はシンボリックリンクを作れないため(CI では実行される),1 件は Windows のファイル名に使えない文字を使うため,1 件は権限で読めないフォルダを作れないため(どちらも CI の Linux では実行される),17 件は TongueSegModel の側にしか無いものに頼るため([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md)「1-1 で分かったこと」) +- 手元(権限の無い Windows)では,スキップされるテストが 56 件ある.32 件はシンボリックリンクを作れないため(CI では実行される),7 件は Windows では作れないもの(ファイル名に使えない文字,権限で読めないファイル・フォルダ,UTF-8 として読めない名前,FIFO)を使うため(CI の Linux では実行される),17 件は TongueSegModel の側にしか無いものに頼るため([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md)「1-1 で分かったこと」) - 実サーバを使う確認の手順は,仕様が決まった時点で別に書く.単体テストは実サーバに接続しない 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 da571c3..ce6b327 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" @@ -162,6 +162,22 @@ | 3-5 | `ls` を実サーバで動かしていない.GNU の `find`(`-printf`)が前提である.リンクをたどらないことは,リンクを作れる CI の Linux のテストで確かめている.`.venv` の大きさの取得にかかる時間(応答を 90 秒長く待つ)が足りるかは,実サーバで確かめる | | 未定 | 実験フォルダの件数は,サーバのシェルの中で,ファイルの数だけの長さの文字列を作って数えている.ファイルが非常に多い実験フォルダで遅い・失敗する場合は,数え方を変える | +### 2-2 で分かったこと (Findings from Step 2-2) + +2-2 は完了した(2026-11-23).`clean RUN_ID` は,判定と `--dry-run` まで入った.サーバのものを消すコードは,まだ 1 行も無い.`--dry-run` の無い `clean RUN_ID` は,判定を表示した後,削除がまだ無いことを示して 0 以外で終わる.判定の細部は [SPEC_03](../04_SPEC/SPEC_03_リモート実行仕様.md)「clean」の「判定の細部」に書いた. + +| 直すステップ | 内容 | +| --- | --- | +| 2-3 | **消す直前の照合で,種類も照らし合わせる**.判定の段階では,サーバで「リンクでない通常のファイル」と確かめてからハッシュを取るまでの間に,ファイルを差し替えられると見逃す.一覧の途中で実験フォルダを差し替えて戻された場合も同じである.手順 4(サーバ側でもう一度照合してから消す)が,この穴を塞ぐ役目を持つ | +| 2-3 | サーバへ送る一覧(相対パス・種類・大きさ・ハッシュ)は,判定の結果(`CleanJudgement.entries`)に残してある.相対パスはサーバから来た生の名前なので,コマンドの文字列に埋め込まず,標準入力で NUL 区切りで渡す(`pull` の tar に渡す一覧と同じ形) | +| 2-3 | **`remote_dir` の検証を先に決める**.仕様は「`~/...` か絶対パス」だが,設定の検証は相対パス(`proj` 等)も通す.相対パスだと,サーバの `CDPATH` しだいで別の場所に入りうる.消すコマンドを入れる前に,相対パスを設定の時点で拒否するか(動作が変わる.仕様の文には合う),全部のスクリプトで `CDPATH` を外すかを決める | +| 2-3 | **結果の置き場そのものがリンクの場合を決める**.今は,手元の `<ルート>/<結果の置き場>` も,サーバの `/<結果の置き場>` も,リンクなら先をたどる(実験フォルダと,その下のリンクはたどらない).中身の照合は保たれるが,消す対象の場所が設定の文字どおりでなくなる.消す前に,拒否するか認めるかを仕様に書く | +| 2-3 | 消すコマンドのテストは,2-1・2-2 と同じく,偽のフォルダを置いた bash で実際に動かして,「対象の外が変わっていないこと」を確かめる.`clean` のテストは今,「サーバへ送るどのコマンドにも消すコマンドが含まれない」ことを確かめている.2-3 では,これを「判定が消せると答えたときだけ,その実験フォルダ 1 つを消すコマンドが送られる」に書き直す | +| 2-4 | `clean --logs` の引数は,まだ無い(argparse のエラーになることをテストで確かめている).入れるときに,そのテストを書き直す | +| 3-5 | ハッシュの待ち時間(600 秒長く待つ)が,大きな重みが複数ある実験で足りるかは,実サーバで確かめる.サーバのスクリプトは `find`(GNU)・`stat`・`sha256sum`・`bash` を使う | +| 未定 | 安全な名前の検査が拒否する制御文字は,`\x00`〜`\x1f` と `\x7f` である.`\x80`〜`\x9f` は通る(回収と同じ規則).名前は表示しないので,判定は緩まない.仕様の「制御文字」の範囲を書くなら,回収の側とあわせて決める | +| 未定 | `ls` の `CDPATH` のテスト(bash で動かすもの)は,`unset CDPATH` を消しても通るという報告がある.今,効いているのは「`unset CDPATH` が `cd` より前にあること」を文字列で確かめるテストである.動かすテストの側を見直す | + ## M3: TongueSegModel の切り替え (Switch TongueSegModel) TongueSegModel のリポジトリでの作業である.LabRemote の側で直すものが出たら,LabRemote の PR を先に取り込む. 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 005e421..a30e2b3 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): この文書の項目は,すべて実装済みである.ただし `results.discard` は読み込みと検証だけで,使うのは `clean`([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 2-2)である. +※ 実装の状況(2026-11-23): この文書の項目は,すべて実装済みである.`results.discard` は,`clean` の判定([SPEC_03](SPEC_03_リモート実行仕様.md)「clean」)で使う. ## 例 (Example) @@ -198,7 +198,7 @@ - 結果の置き場(`<ルート>/`)は,送信の固定の除外である([SPEC_01](SPEC_01_アーキテクチャ設計.md)「安全の枠」).`dir` を変えると,除外される場所も変わる - `push.partial` の `path` に,結果の置き場と同じ場所・その中の場所は書けない -※ `discard` は,回収済みの実験フォルダを消す `clean`([SPEC_03](SPEC_03_リモート実行仕様.md).ステップ 2-2)で使う.それまでは,読み込みと検証だけを行う. +※ `discard` は,回収済みの実験フォルダを消す `clean`([SPEC_03](SPEC_03_リモート実行仕様.md))の判定で使う.比べ方は回収と同じで,大文字と小文字を区別する. ## 環境変数での上書き (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 f080fd8..20af8f7 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" @@ -225,6 +225,31 @@ - そのサーバでジョブが実行中なら,警告を出す(手順 4 の照合があるため,書き込み中のフォルダは消えない) - 重みを回収していない実験は,`--with-checkpoints` で回収するか,`--discard-checkpoints` を付けるまで消えない +判定の細部(手順 1〜3). + +- **サーバから取るもの**: 実験フォルダの下の,フォルダ以外のもの全部について,相対パス・種類(通常のファイルか,それ以外か)・大きさ・ハッシュ.リンクの先はたどらない.通常のファイル以外(リンク・特殊なファイル)は,ハッシュを取らず,種類だけを取る.フォルダは判定の対象にしない(空のフォルダは,説明の要るものとして数えない) +- **分ける順**: 一致 → 捨ててよい → 重み(捨てる)→ 説明がつかない,の順に当てはめ,最初に当たった区分にする +- **一致**: 手元の `<ルート>/<結果の置き場>//<相対パス>` が,リンクでない通常のファイルで,大きさとハッシュ(SHA-256)の両方がサーバと同じであること.手元に無い・内容が違う・手元の側がリンクやフォルダである場合は,一致としない + - 手元の名前は,大文字と小文字まで同じものだけを同じファイルとみなす.Windows は大文字と小文字を区別せず,短い名前でもファイルを開けるので,開く前に,フォルダの中の実際の名前と完全一致で比べる(サーバの `A.csv` と `a.csv` を,手元の 1 つのファイルで両方「一致」にしないため) + - 途中のフォルダ・手元の実験フォルダそのものが,リンクやジャンクションである場合は,一致としない +- **捨ててよい**: 相対パスが,設定の `results.discard` の形([SPEC_02](SPEC_02_設定ファイル仕様.md))に,大文字と小文字を区別して一致すること.回収の判定と同じ比べ方をする(小文字にして比べる処理を使わない) +- **重み(捨てる)**: 相対パスが `results.checkpoints.dir` の下にあり,`--discard-checkpoints` が付いていること.付いていないときは,この区分に入れない(一致しなければ「説明がつかない」になる) +- **説明がつかない**: 上のどれでもないもの.次も,ここに入れる + - 通常のファイル以外(リンク等).手元と一致するか・捨ててよい一覧に名前があるかを見ない + - 相対パスが安全でないもの(空,絶対パス,`..`・`.` の部分,`\`,NUL・制御文字を含む,Windows で別の場所を指しうる名前,UTF-8 として読めない名前).手元のパスを組み立てる前に確かめる.規則は,回収のときの名前の検査と同じものを使う +- 実験フォルダが空(フォルダ以外のものが 0 件)のときは,説明がつかないものが無いので,消してよいと判定する +- **表示**: 区分ごとの件数と大きさだけを出す.相対パス・ファイル名は,表示・ログ・エラーのどこにも出さない +- **終了コード**: 「説明がつかない」が 0 件なら 0,1 件でもあれば 0 以外.`--dry-run` でも同じにする(消せるかどうかを,終了コードで確かめられるようにする) +- **サーバの出力の扱い**: `ls` と同じ形にする.目印で囲み,NUL で区切り,目印が 2 つ以上ある出力を拒否する.解釈できない出力(途中で切れている,ハッシュの形でない,数として読めない,同じ相対パスが 2 回出る)は,「説明がつく」と見なさず,何も消さずに 0 以外の終了コードで終わる.サーバでハッシュを取れなかったファイル(権限が無い等)が 1 件でもあれば,同じく止まる +- **サーバで実行するコマンド**: 埋め込むのは,設定の `remote_dir`・結果の置き場と,検証済みの `RUN_ID` だけである.判定の段階では,一覧とハッシュの取得だけを行い,書き込み・削除をしない +- 実験フォルダそのものがリンクである・フォルダでない・無い場合は,判定に進まず,0 以外の終了コードで終わる.一覧を取った後にもう一度確かめ,その間にリンク等へ変わっていた場合も,同じく止まる.一覧の取得(`find`)が失敗した場合(読めないフォルダがある等)も止まる +- **サーバを探すとき**(`--server` を省いたとき): 接続できないサーバは,`pull` と同じく警告して続ける.接続できたのに出力を解釈できないサーバ,実験フォルダがリンク・フォルダでない・読めないサーバが 1 台でもあれば,他のサーバに実験があっても止まる(`pull` より厳しくする) +- ハッシュの計算には時間がかかることがある.`clean` は,他のサブコマンドより 600 秒長く応答を待つ +- サーバのスクリプトは,相対の `cd` が別の場所へ行かないように,`CDPATH` を外してから動かす(`ls` も同じ) +- サーバで使うコマンドは,`find`(GNU)・`stat`・`sha256sum`・`bash` である.ファイルの名前は,`sha256sum` の出力からは読まない(名前に `\` や改行があると,出力の形が変わるため) + +※ 実装の状況(2026-11-23): 判定と `--dry-run` まで([PLAN_02](../03_PLAN/PLAN_02_開発ステップ.md) のステップ 2-2).削除(手順 4・5)は 2-3 で入れる.それまでは,`--dry-run` の無い `clean RUN_ID` は,判定の結果を表示した後,「削除はまだ実装していない」ことを示して,何も消さずに 0 以外の終了コードで終わる. + `clean --logs [NAME ...] [--server NAME] [--dry-run]` - ジョブのログを消す.`NAME` を省いたときは,実行中でない全ジョブのログを対象にする diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0548f54..9645651 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -72,3 +72,8 @@ - 設計判断: サーバから受け取った名前は,手元で実験 ID・ジョブ名の規則で検証してから表示する.合わない名前と,結果の置き場の直下のリンクは,名前を出さずに「その他」の件数に数える - 失敗パターン: ① 最初に見つかった始まりの目印から読む → ログインの挨拶に完結した偽の一覧があると,それを本物として読み「何も残っていない」になる / ② 始まり・終わりの目印が 2 つ以上ある出力を拒否する形で解決(テストで見つかった) - 後段: 実サーバでは動かしていない(3-5).リンクの扱いのテストは,手元では飛ばされ,CI の Linux で実行される +- [x] **ステップ 2-2(`clean` の判定)**: `clean RUN_ID` の判定と `--dry-run` を足した.サーバの実験フォルダの全ファイルの種類・大きさ・ハッシュを取り,一致・捨ててよい・重み(捨てる)・説明がつかない,に分ける.サーバのものを消すコードは,まだ入れていない. + - 設計判断: 判定と削除を別のステップに分けた.判定だけの段階で,「説明がつかないものを,説明がつくと判定する入力」をテストで探してから,削除を足す + - 設計判断: 手元の照合は,名前を大文字と小文字まで完全一致で比べる.Windows は区別せずにファイルを開けるので,そのままだと,サーバの名前違いの 2 つのファイルを,手元の 1 つのファイルで両方「一致」にしてしまう + - 設計判断: リンク等の通常のファイル以外と,安全でない相対パスは,他のどの条件に当たっても「説明がつかない」にする.サーバでハッシュを取れなかったファイル・読めないフォルダがあれば,判定せずに止まる + - 後段: 判定の段階には,確認とハッシュの取得の間にファイルを差し替えられる穴が残る.消す直前のサーバ側の照合(2-3)で塞ぐ.`remote_dir` の相対パスと,結果の置き場がリンクの場合の扱いも,2-3 の前に決める(PLAN_02) diff --git a/src/labremote/cleanup.py b/src/labremote/cleanup.py index f6505d0..02c8ac2 100644 --- a/src/labremote/cleanup.py +++ b/src/labremote/cleanup.py @@ -8,15 +8,36 @@ 手元に同じ実験 ID のフォルダがあるかは,ファイルの読み書きにあたるため `labremote.cli` が調べ, 結果(実験 ID の集合)を表示の側(`labremote.report`)へ渡す. + +`clean RUN_ID` の判定(SPEC_03「clean」の手順 1〜3)も置く.サーバの出力 +(`build_clean_list_command`)を `parse_clean_output` で読み,`classify_clean` で各ファイルを +一致・捨ててよい・重み(捨てる)・説明がつかない,に分ける.判定できないものは「説明がつかない」, +出力を解釈できないときは `ValueError`(止まる)の側に倒す.手元のファイルの大きさとハッシュは +`labremote.cli` が調べて渡す(調べてよい相対パスかは `is_safe_clean_path` で先に確かめる). """ from __future__ import annotations +import enum import re -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass +from typing import TYPE_CHECKING from labremote.commands import ( + CLEAN_AFTER_PREFIX, + CLEAN_BEGIN_MARKER, + CLEAN_END_MARKER, + CLEAN_FILE_PREFIX, + CLEAN_FIND_RC_PREFIX, + CLEAN_NOHASH_PREFIX, + CLEAN_OTHER_PREFIX, + CLEAN_RUN_PREFIX, + CLEAN_STATE_LINK, + CLEAN_STATE_MISSING, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_PRESENT, + CLEAN_STATE_UNREADABLE, LS_BEGIN_MARKER, LS_DIR_PREFIX, LS_END_MARKER, @@ -36,10 +57,15 @@ LS_VENV_PREFIX, validate_job_name, ) -from labremote.whitelist import validate_run_id +from labremote.whitelist import is_discard_allowed, is_safe_relative_path, validate_run_id + +if TYPE_CHECKING: + from labremote.config import ResultsConfig # du -k の単位 _KIB = 1024 +# ls の出力のエラーの主語(clean の側は _CLEAN_WHAT) +_LS_WHAT = "サーバに残っているもの" # ジョブのログのファイル名の末尾 _LOG_SUFFIX = ".log" # サーバが出す数(件数・大きさ・終了コード).符号・空白・空を通さない @@ -151,9 +177,12 @@ all_unreachable: bool -def _malformed(detail: str) -> ValueError: - """出力の形が決まりと違うときのエラー(サーバから受け取った名前は入れない).""" - return ValueError(f"サーバに残っているものの出力を解釈できない({detail})") +def _malformed(detail: str, what: str = _LS_WHAT) -> ValueError: + """出力の形が決まりと違うときのエラー(サーバから受け取った名前は入れない). + + what は,何の出力か(メッセージの主語.`ls` と `clean` で違う). + """ + return ValueError(f"{what}の出力を解釈できない({detail})") def _unreadable(where: str) -> ValueError: @@ -164,28 +193,30 @@ class _Reader: """NUL 区切りの記録を 1 件ずつ読む(読み終わりを ValueError にする).""" - def __init__(self, records: Sequence[str]) -> None: + def __init__(self, records: Sequence[str], what: str = _LS_WHAT) -> None: self._records = records self._pos = 0 + self._what = what def next(self) -> str: if self._pos >= len(self._records): - raise ValueError("サーバに残っているものの出力が途中で切れている(目印が欠けている)") + raise ValueError(f"{self._what}の出力が途中で切れている(目印が欠けている)") record = self._records[self._pos] self._pos += 1 return record -def _parse_number(text: str, what: str) -> int: +def _parse_number(text: str, name: str, what: str = _LS_WHAT) -> int: + """サーバが出した数(name は項目の名前)を読む(符号・空白・空は通さない).""" if not _NUMBER_RE.fullmatch(text): - raise ValueError(f"サーバに残っているものの出力の{what}を数として読めない") + raise ValueError(f"{what}の出力の{name}を数として読めない") return int(text) -def _expect_prefixed(record: str, prefix: str) -> str: +def _expect_prefixed(record: str, prefix: str, what: str = _LS_WHAT) -> str: """記録が prefix で始まることを確かめ,残りを返す.""" if not record.startswith(prefix): - raise _malformed("目印の順が違う") + raise _malformed("目印の順が違う", what) return record[len(prefix) :] @@ -299,17 +330,20 @@ return jobs -def _records_after_begin(data: bytes) -> list[str]: +def _records_after_begin( + data: bytes, begin: str = LS_BEGIN_MARKER, end: str = LS_END_MARKER, what: str = _LS_WHAT +) -> list[str]: """出力を記録に分け,始まりの目印の次からの記録を返す(目印の数を先に確かめる).""" records = data.decode("utf-8", "surrogateescape").split("\0") # 挨拶等に完結した偽の一覧が混ざると,どれが本物かを決められない(偽の側を読むと, - # 残っているものを「無い」と見誤る).読み始める前に,目印が 1 つずつであることを確かめる. - # 名前を含む記録は `dir `・`log `・`job ` で始まるので,目印に完全一致することは無い - if records.count(LS_BEGIN_MARKER) > 1 or records.count(LS_END_MARKER) > 1: - raise _malformed("始まりか終端の目印が 2 つ以上ある") - if LS_BEGIN_MARKER not in records: - raise _malformed("始まりの目印が無い") - return records[records.index(LS_BEGIN_MARKER) + 1 :] + # 残っているものを「無い」「説明がつく」と見誤る).読み始める前に,目印が 1 つずつである + # ことを確かめる.名前を含む記録は,種類を表す語(`dir `・`file ` 等)で始まるので, + # 目印に完全一致することは無い + if records.count(begin) > 1 or records.count(end) > 1: + raise _malformed("始まりか終端の目印が 2 つ以上ある", what) + if begin not in records: + raise _malformed("始まりの目印が無い", what) + return records[records.index(begin) + 1 :] def parse_ls_output(data: bytes) -> RemoteListing: @@ -400,3 +434,369 @@ ), all_unreachable=bool(results) and all(r.unreachable for r in results), ) + + +# --------------------------------------------------------------------------- +# clean RUN_ID の判定(SPEC_03「clean」の手順 1〜3) +# --------------------------------------------------------------------------- + +# サーバが出す SHA-256(sha256sum の 16 進.小文字) +_SHA256_RE = re.compile(r"[0-9a-f]{64}") +# 実験フォルダの状態として受け付ける値 +_CLEAN_STATES = frozenset( + { + CLEAN_STATE_PRESENT, + CLEAN_STATE_MISSING, + CLEAN_STATE_LINK, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_UNREADABLE, + } +) +_CLEAN_WHAT = "実験フォルダのファイルの一覧" +# 目印の先頭(ファイルの記録の位置に目印が来たら,順が違う出力として扱う) +_MARKER_HEAD = "@@labremote" + + +@dataclass(frozen=True) +class RemoteFile: + """サーバの実験フォルダの下の,フォルダ以外のもの 1 件. + + Attributes: + rel_path: 実験フォルダを基準にした POSIX 相対パス(サーバから受け取ったまま.未検証. + 表示・ログ・エラーに出さない). + regular: リンクでない通常のファイルか(False ならリンク・FIFO 等.大きさとハッシュは無い). + size_bytes: 大きさ(バイト.`regular` が False なら 0). + sha256: SHA-256 の 16 進(小文字 64 桁.`regular` が False なら空). + """ + + rel_path: str + regular: bool + size_bytes: int = 0 + sha256: str = "" + + +@dataclass(frozen=True) +class RemoteRunListing: + """`parse_clean_output` の結果(サーバ 1 台の実験フォルダ). + + Attributes: + state: 実験フォルダの状態(`labremote.commands` の `CLEAN_STATE_*`). + files: `state` が `present` のときの,フォルダ以外のもの全部(サーバの出力の順). + """ + + state: str + files: tuple[RemoteFile, ...] = () + + +@dataclass(frozen=True) +class LocalFile: + """手元の `<ルート>/<結果の置き場>//<相対パス>` の通常のファイルの情報. + + Attributes: + size_bytes: 大きさ(バイト). + sha256: SHA-256 の 16 進(小文字 64 桁).大きさがサーバと違うために読まなかったときは空 + (空はサーバのハッシュと一致しえないので,一致にならない). + """ + + size_bytes: int + sha256: str + + +class CleanCategory(enum.Enum): + """clean の判定の区分(SPEC_03「clean」.分ける順もこの順).""" + + MATCHED = "matched" + DISCARDABLE = "discardable" + CHECKPOINT = "checkpoint" + UNEXPLAINED = "unexplained" + + +@dataclass(frozen=True) +class CategoryTotal: + """区分 1 つの件数と大きさ. + + Attributes: + count: 件数. + size_bytes: 大きさの合計(通常のファイル以外は 0 として足す). + """ + + count: int = 0 + size_bytes: int = 0 + + +@dataclass(frozen=True) +class ClassifiedFile: + """判定したファイル 1 件(2-3 の「消す直前の照合」でサーバへ送る一覧の元). + + Attributes: + file: サーバのファイル. + category: 区分. + """ + + file: RemoteFile + category: CleanCategory + + +@dataclass(frozen=True) +class CleanJudgement: + """`classify_clean` の結果. + + Attributes: + entries: 判定した全ファイル(サーバの出力の順). + matched: 一致(手元の同じ相対パスに,大きさとハッシュが同じ通常のファイルがある). + discardable: 捨ててよい(設定の `results.discard` に一致). + checkpoints: 重み(捨てる)(`results.checkpoints.dir` の下で,`--discard-checkpoints`). + unexplained: 説明がつかない. + unexplained_checkpoints: 説明がつかないもののうち,`results.checkpoints.dir` の下の + 通常のファイル(`--with-checkpoints` で回収するか,`--discard-checkpoints` で + 説明がつく). + unexplained_not_regular: 説明がつかないもののうち,通常のファイル以外(リンク等). + unexplained_unsafe: 説明がつかないもののうち,相対パスが安全でない(手元のパスにできない) + 通常のファイル. + """ + + entries: tuple[ClassifiedFile, ...] + matched: CategoryTotal + discardable: CategoryTotal + checkpoints: CategoryTotal + unexplained: CategoryTotal + unexplained_checkpoints: int + unexplained_not_regular: int + unexplained_unsafe: int + + @property + def total(self) -> CategoryTotal: + """全ファイルの件数と大きさ.""" + parts = (self.matched, self.discardable, self.checkpoints, self.unexplained) + return CategoryTotal(sum(p.count for p in parts), sum(p.size_bytes for p in parts)) + + @property + def deletable(self) -> bool: + """説明がつかないものが 0 件か(空の実験フォルダも True).""" + return self.unexplained.count == 0 + + +def _clean_malformed(detail: str) -> ValueError: + """clean の一覧の出力の形が決まりと違うときのエラー(サーバから受け取った名前は入れない).""" + return _malformed(detail, _CLEAN_WHAT) + + +def _clean_state(record: str, prefix: str) -> str: + state = _expect_prefixed(record, prefix, _CLEAN_WHAT) + if state not in _CLEAN_STATES: + raise _clean_malformed("実験フォルダの状態が不明") + return state + + +def _strip_run_dir(path: str, run_id: str) -> str: + """`.//<相対パス>` から相対パスを取り出す(形が違えば ValueError).""" + prefix = f"./{run_id}/" + if not path.startswith(prefix) or len(path) == len(prefix): + raise _clean_malformed("パスが実験フォルダの下を指していない") + return path[len(prefix) :] + + +def _parse_clean_entry(record: str, run_id: str) -> RemoteFile: + """実験フォルダの中の 1 件の記録を読む.""" + if record.startswith(CLEAN_NOHASH_PREFIX): + # 飛ばして続けると,取れなかったファイルを判定から漏らす(消してよいと見誤る) + raise ValueError( + "サーバでハッシュを取れなかったファイルがある(権限が無い等).何も消さない" + ) + if record.startswith(CLEAN_OTHER_PREFIX): + return RemoteFile(_strip_run_dir(record[len(CLEAN_OTHER_PREFIX) :], run_id), False) + if record.startswith(CLEAN_FILE_PREFIX): + parts = record[len(CLEAN_FILE_PREFIX) :].split(" ", 2) + if len(parts) != 3: + raise _clean_malformed("ファイルの行の欄が足りない") + size_text, digest, path = parts + size = _parse_number(size_text, "大きさ", _CLEAN_WHAT) + if not _SHA256_RE.fullmatch(digest): + raise _clean_malformed("ハッシュが 64 桁の 16 進でない") + return RemoteFile(_strip_run_dir(path, run_id), True, size, digest) + raise _clean_malformed("ファイルの行の種類が不明") + + +def parse_clean_output(data: bytes, run_id: str) -> RemoteRunListing: + """`build_clean_list_command` の標準出力を解釈する. + + 始まりの目印より前(ログインシェルの挨拶等)と終端の目印より後は無視する.ただし,始まりか + 終端の目印が 2 つ以上ある出力は,どれが本物かを決められないので `ValueError` にする. + 解釈できない出力を「説明がつく」と見なさない(SPEC_03「clean」の「サーバの出力の扱い」). + + Args: + data: サーバの標準出力(NUL 区切りの記録). + run_id: 一覧を取った実験 ID(ここでも `validate_run_id` を通す.パスの先頭と比べる). + + Returns: + 実験フォルダの状態と,`present` ならフォルダ以外のもの全部. + + Raises: + ValueError: 目印が欠けている・2 つ以上ある・順が違う・途中で切れている,数として読めない, + ハッシュが 64 桁の 16 進でない,同じ相対パスが 2 回出る,ハッシュを取れなかった + ファイルがある,サーバの `find` が失敗した(読めないフォルダがある),一覧の後に + 実験フォルダがリンク等に変わっていた,または実験 ID が不正な場合.メッセージに + サーバから受け取った名前は含めない. + """ + run_id = validate_run_id(run_id) + records = _records_after_begin(data, CLEAN_BEGIN_MARKER, CLEAN_END_MARKER, _CLEAN_WHAT) + reader = _Reader(records, _CLEAN_WHAT) + state = _clean_state(reader.next(), CLEAN_RUN_PREFIX) + if state != CLEAN_STATE_PRESENT: + if reader.next() != CLEAN_END_MARKER: + raise _clean_malformed("終端の目印が無い") + return RemoteRunListing(state) + + files: list[RemoteFile] = [] + seen: set[str] = set() + while not (record := reader.next()).startswith(CLEAN_FIND_RC_PREFIX): + if record.startswith(_MARKER_HEAD): + raise _clean_malformed("目印の順が違う") + entry = _parse_clean_entry(record, run_id) + # 同じ相対パスが 2 回あると,どちらの内容で判定したかが決まらない + if entry.rel_path in seen: + raise _clean_malformed("同じ相対パスが 2 回出ている") + seen.add(entry.rel_path) + files.append(entry) + find_rc = _parse_number(record[len(CLEAN_FIND_RC_PREFIX) :], "find の終了コード", _CLEAN_WHAT) + after = _clean_state(reader.next(), CLEAN_AFTER_PREFIX) + if reader.next() != CLEAN_END_MARKER: + raise _clean_malformed("終端の目印が無い") + if find_rc != 0: + # 読めないフォルダの中のファイルは一覧に出ていない(数え漏れたまま判定しない) + raise ValueError( + "サーバの実験フォルダの中に読めない場所がある(一覧を最後まで取れなかった)." + "何も消さない" + ) + if after != CLEAN_STATE_PRESENT: + raise ValueError( + "一覧を取っている間に,サーバの実験フォルダがリンク等に変わった.何も消さない" + ) + return RemoteRunListing(state, tuple(files)) + + +def is_safe_clean_path(rel_path: str) -> bool: + """サーバから受け取った相対パスを,手元のパスにして調べてよいかを返す. + + SPEC_03「clean」の「説明がつかない」の 2 つ目.手元のパスを組み立てる前に確かめる. + 規則は回収と同じ(`labremote.whitelist.is_safe_relative_path`.空・絶対パス・`..`・`.`・ + 空の部分・`\\`・NUL・制御文字・Windows で別の場所を指しうる名前を拒否する).加えて, + UTF-8 として読めない名前(サーバのバイト列を surrogateescape で読んだもの)も拒否する + (手元のファイル名に正しく直せないため). + + Args: + rel_path: 実験フォルダを基準にした POSIX 相対パス. + + Returns: + 安全なら True. + """ + try: + rel_path.encode("utf-8") + except UnicodeEncodeError: + return False + return is_safe_relative_path(rel_path) + + +def local_paths_to_check(files: Iterable[RemoteFile]) -> tuple[RemoteFile, ...]: + """手元のファイルを調べる対象(通常のファイルで,相対パスが安全なもの)を返す. + + 通常のファイル以外と,安全でない相対パスは,手元を調べずに「説明がつかない」にするので + 含めない(サーバから来たパスで手元の実験フォルダの外を開かないため). + + Args: + files: サーバのファイル(`parse_clean_output` の結果). + + Returns: + 調べる対象. + """ + return tuple(f for f in files if f.regular and is_safe_clean_path(f.rel_path)) + + +def _is_under_checkpoints(rel_path: str, results: ResultsConfig) -> bool: + """相対パスの先頭の部分が `checkpoints.dir` と(大文字小文字を区別して)一致し,その下にあるか. + + `checkpoints.dir` そのものの名前のファイルは含めない(フォルダの下ではないため). + """ + first, sep, rest = rel_path.partition("/") + return bool(sep) and bool(rest) and first == results.checkpoints.dir + + +def _classify_one( + file: RemoteFile, + local: Mapping[str, LocalFile], + results: ResultsConfig, + *, + discard_checkpoints: bool, +) -> CleanCategory: + # 通常のファイル以外(リンク等)は,手元・一覧を見ずに説明がつかないとする + if not file.regular: + return CleanCategory.UNEXPLAINED + # 安全でない相対パスは,手元のファイル・一覧のどれとも結び付けない + if not is_safe_clean_path(file.rel_path): + return CleanCategory.UNEXPLAINED + found = local.get(file.rel_path) + if ( + found is not None + and _SHA256_RE.fullmatch(file.sha256) + and found.size_bytes == file.size_bytes + and found.sha256 == file.sha256 + ): + return CleanCategory.MATCHED + if is_discard_allowed(file.rel_path, results): + return CleanCategory.DISCARDABLE + if discard_checkpoints and _is_under_checkpoints(file.rel_path, results): + return CleanCategory.CHECKPOINT + return CleanCategory.UNEXPLAINED + + +def _total(entries: Iterable[ClassifiedFile], category: CleanCategory) -> CategoryTotal: + chosen = [e.file for e in entries if e.category is category] + return CategoryTotal(len(chosen), sum(f.size_bytes for f in chosen)) + + +def classify_clean( + files: Sequence[RemoteFile], + local: Mapping[str, LocalFile], + results: ResultsConfig, + *, + discard_checkpoints: bool, +) -> CleanJudgement: + """サーバの実験フォルダの各ファイルを,一致・捨ててよい・重み(捨てる)・説明がつかないに分ける. + + SPEC_03「clean」の「分ける順」.一致 → 捨ててよい → 重み(捨てる)→ 説明がつかない,の順に + 当てはめ,最初に当たった区分にする.通常のファイル以外と,相対パスが安全でないものは, + 手元・一覧を見ずに説明がつかないとする.名前は大文字小文字を区別して比べる. + + Args: + files: サーバのファイル(`parse_clean_output` の結果の `files`). + local: 手元の情報(相対パス → 大きさとハッシュ).手元にリンクでない通常のファイルが + あったものだけを入れる(無い・リンク・フォルダは入れない). + results: 検証済みの設定の `results`. + discard_checkpoints: `--discard-checkpoints` が付いているか. + + Returns: + 判定の結果. + """ + entries = tuple( + ClassifiedFile(f, _classify_one(f, local, results, discard_checkpoints=discard_checkpoints)) + for f in files + ) + unexplained = [e.file for e in entries if e.category is CleanCategory.UNEXPLAINED] + return CleanJudgement( + entries=entries, + matched=_total(entries, CleanCategory.MATCHED), + discardable=_total(entries, CleanCategory.DISCARDABLE), + checkpoints=_total(entries, CleanCategory.CHECKPOINT), + unexplained=_total(entries, CleanCategory.UNEXPLAINED), + unexplained_checkpoints=sum( + 1 + for f in unexplained + if f.regular + and is_safe_clean_path(f.rel_path) + and _is_under_checkpoints(f.rel_path, results) + ), + unexplained_not_regular=sum(1 for f in unexplained if not f.regular), + unexplained_unsafe=sum( + 1 for f in unexplained if f.regular and not is_safe_clean_path(f.rel_path) + ), + ) diff --git a/src/labremote/cli.py b/src/labremote/cli.py index 0ad94cb..9852b62 100644 --- a/src/labremote/cli.py +++ b/src/labremote/cli.py @@ -13,6 +13,8 @@ - kill : ジョブを止める(ジョブのあるサーバを自動で探す) - pull : 実験結果のうち,設定の回収の一覧(`results`)に名前が一致するものだけを持ち帰る - ls : サーバに残っているもの(実験フォルダ・ジョブのログ・大きさ)を一覧する(何も消さない) +- clean : サーバの実験フォルダの全ファイルを手元・設定と照らして,消せるかを判定する + (削除はまだ実装していない.何も消さない) ssh を呼ぶ副作用はこのモジュールに集め,コマンド文字列の組み立て・出力の解析・GPU の選択・ 回収の判定(SPEC_01「安全の枠」の「回収」)・表示の文の組み立て(`labremote.report`)は @@ -30,9 +32,11 @@ import argparse import codecs import contextlib +import hashlib import logging import os import socket +import stat import subprocess import sys import tarfile @@ -48,8 +52,23 @@ from pydantic import ValidationError import labremote -from labremote.cleanup import ServerLeftovers, listed_run_ids, parse_ls_output, summarize_ls +from labremote.cleanup import ( + LocalFile, + RemoteFile, + RemoteRunListing, + ServerLeftovers, + classify_clean, + listed_run_ids, + local_paths_to_check, + parse_clean_output, + parse_ls_output, + summarize_ls, +) from labremote.commands import ( + CLEAN_STATE_LINK, + CLEAN_STATE_MISSING, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_PRESENT, EXIT_NO_SESSION, EXIT_NOT_FOUND, EXIT_NOT_JOB, @@ -60,6 +79,7 @@ REMOTE_LOG_DIR_NAME, RESERVED_ENV_VARS, SSH_FAILURE_RC, + build_clean_list_command, build_job_env, build_job_script, build_kill_command, @@ -112,6 +132,7 @@ describe_skipped_links, describe_ssh_failure, describe_target, + format_clean_report, format_forced_warning, format_ls_incomplete_warning, format_ls_report, @@ -145,6 +166,12 @@ # ls はサーバで大きさを数える(du..venv 等で時間がかかる)ため,短い問い合わせの上限に # これを足して待つ.超えたサーバは接続不可と同じに扱う(SPEC_03「ls」) _LS_EXTRA_TIMEOUT_SEC = 90 +# clean はサーバで実験フォルダの全ファイルのハッシュ(SHA-256)を計算する(重み等の大きな +# ファイルで時間がかかる)ため,短い問い合わせの上限にこれを足して待つ.超えたサーバは +# 確かめられなかったものとして扱う(SPEC_03「clean」) +_CLEAN_EXTRA_TIMEOUT_SEC = 600 +# 手元のファイルのハッシュを計算するときに 1 回に読む大きさ +_HASH_CHUNK_BYTES = 1024 * 1024 _EPILOG = """\ 使用例: @@ -163,6 +190,7 @@ uv run labremote pull <実験ID> # 設定の results.pull の一覧だけ持ち帰る uv run labremote pull <実験ID> --with-checkpoints # 重み(results.checkpoints.files)も持ち帰る uv run labremote ls # サーバに残っている実験フォルダ・ログ・大きさ + uv run labremote clean <実験ID> --dry-run # サーバの実験フォルダを消せるかを確かめる ジョブの成否は,ジョブのログ(logs)の終了行(=== ... exit <終了コード>)で判断する. 実験 ID は,ジョブが出力したもの(ログ等)で確かめる. @@ -1087,6 +1115,225 @@ # --------------------------------------------------------------------------- +# clean +# --------------------------------------------------------------------------- + + +def _remote_check_failure(result: _SshResult) -> str: + """一覧を取れなかった理由(サーバの標準エラーはファイル名を含みうるので出さない).""" + if result.rc == _TIMEOUT_RC: + return "応答がタイムアウトした" + if result.rc == SSH_FAILURE_RC: + return f"ssh 接続できなかった: {last_stderr_line(result.stderr)}" + return f"終了コード {result.rc}" + + +def _locate_clean_run( + ctx: _Context, run_id: str, server_name: str | None +) -> tuple[ServerConfig, RemoteRunListing]: + """実験フォルダのあるサーバを探し,そのファイルの一覧と大きさ・ハッシュを返す. + + 探し方は `pull` と同じ(`--server` を省けば全サーバを探し,1 台で見つかればそこ.複数台・ + 0 台ならエラー.接続できないサーバは警告して続ける).接続できたのに出力を解釈できない, + 実験フォルダがリンク・フォルダでない・入れない,のどれかのサーバがあれば,判定に進まずに + 止まる(どこを消すかを確かめられないため). + """ + servers = _target_servers(ctx, server_name) + results_dir = ctx.config.results.dir + raw = _query_servers( + ctx, + servers, + lambda s: build_clean_list_command(s.remote_dir, results_dir=results_dir, run_id=run_id), + timeout=ctx.query_timeout_sec + _CLEAN_EXTRA_TIMEOUT_SEC, + ) + found: list[tuple[ServerConfig, RemoteRunListing]] = [] + unreachable = 0 + where = f"{results_dir}/{run_id}" + for server, result in zip(servers, raw, strict=True): + if result.rc != 0: + unreachable += 1 + logger.warning( + "%s で実験フォルダを確かめられなかった(%s)", + server.name, + _remote_check_failure(result), + ) + continue + try: + listing = parse_clean_output(result.stdout, run_id) + except ValueError as exc: + raise ValueError(f"{server.name} の {where} を確かめられない: {exc}") from exc + if listing.state == CLEAN_STATE_MISSING: + continue + if listing.state == CLEAN_STATE_LINK: + raise ValueError(f"{server.name} の {where} がリンクであるため消さない") + if listing.state == CLEAN_STATE_NOT_DIR: + raise ValueError(f"{server.name} の {where} がフォルダでないため消さない") + if listing.state != CLEAN_STATE_PRESENT: + raise ValueError(f"{server.name} の {where} を読めない(権限が無い等).何も消さない") + found.append((server, listing)) + server = pick_single_server( + [s for s, _ in found], what=f"実験 {run_id!r}", unreachable=unreachable + ) + return server, next(listing for s, listing in found if s.name == server.name) + + +def _warn_running_jobs(ctx: _Context, server: ServerConfig) -> None: + """そのサーバでジョブが実行中なら警告する(確かめられなければ,その旨を警告する).""" + probe = _probe_servers(ctx, [server])[0] + if probe.output is None: + logger.warning("%s で実行中のジョブを確かめられなかった(%s)", server.name, probe.error) + elif probe.output.jobs: + logger.warning( + "%s では実行中のジョブがある(%s).書き込み中の実験フォルダは,判定と内容が変わりうる", + server.name, + ", ".join(probe.output.jobs), + ) + + +def _exact_child(parent: Path, name: str, cache: dict[Path, frozenset[str] | None]) -> bool: + """parent の直下に,name と(大文字小文字まで)同じ名前があるか. + + Windows は名前の大文字小文字を区別せず,短い名前(`ABCDEF~1.TXT`)でも開けるため, + 開く前に,フォルダの中の実際の名前と完全一致で比べる(サーバの別の名前のファイルを, + 手元の別のファイルと結び付けないため). + """ + if parent not in cache: + try: + cache[parent] = frozenset(os.listdir(parent)) + except OSError: + cache[parent] = None + names = cache[parent] + return names is not None and name in names + + +def _is_real_dir(path: Path) -> bool: + """リンク・ジャンクションでないフォルダか(先をたどらずに確かめる).""" + try: + info = os.lstat(path) + except OSError: + return False + return stat.S_ISDIR(info.st_mode) and not path.is_junction() + + +def _local_run_dir( + ctx: _Context, run_id: str, cache: dict[Path, frozenset[str] | None] +) -> Path | None: + """手元の実験フォルダ(`<ルート>/<結果の置き場>/`)を返す(リンク等なら None).""" + results_root = ctx.project_root / ctx.config.results.dir + run_dir = results_root / run_id + if not _exact_child(results_root, run_id, cache) or not _is_real_dir(run_dir): + return None + return run_dir + + +def _hash_local_file(path: Path, info: os.stat_result) -> LocalFile | None: + """lstat で確かめた通常のファイルを開き,同じファイルであることを確かめてからハッシュを取る.""" + try: + with path.open("rb") as handle: + opened = os.fstat(handle.fileno()) + # 確かめた後にリンク等へ差し替えられていたら,開いたものを一致の根拠にしない + if not stat.S_ISREG(opened.st_mode) or (opened.st_ino, opened.st_dev) != ( + info.st_ino, + info.st_dev, + ): + return None + digest = hashlib.sha256() + size = 0 + while chunk := handle.read(_HASH_CHUNK_BYTES): + digest.update(chunk) + size += len(chunk) + except OSError: + return None + return LocalFile(size, digest.hexdigest()) + + +def _local_file_info( + run_dir: Path, file: RemoteFile, cache: dict[Path, frozenset[str] | None] +) -> LocalFile | None: + """手元の同じ相対パスの通常のファイルの大きさとハッシュを返す(無い・リンク等なら None). + + `file.rel_path` は `is_safe_clean_path` を通したものに限る(`local_paths_to_check`). + 途中のフォルダも含めて,リンク・ジャンクションをたどらない(手元の実験フォルダの外を開かない). + 大きさがサーバと違うときは,読まずに空のハッシュで返す(一致にならない). + """ + *dirs, name = file.rel_path.split("/") + current = run_dir + for part in dirs: + if not _exact_child(current, part, cache): + return None + current = current / part + if not _is_real_dir(current): + return None + if not _exact_child(current, name, cache): + return None + path = current / name + try: + info = os.lstat(path) + except OSError: + return None + # リンク(lstat は先をたどらない)・フォルダ・特殊なファイルは一致としない + if not stat.S_ISREG(info.st_mode) or path.is_junction(): + return None + if info.st_size != file.size_bytes: + return LocalFile(info.st_size, "") + return _hash_local_file(path, info) + + +def _local_files(ctx: _Context, run_id: str, files: Sequence[RemoteFile]) -> dict[str, LocalFile]: + """手元の実験フォルダで,サーバと同じ相対パスの通常のファイルの情報を集める.""" + cache: dict[Path, frozenset[str] | None] = {} + run_dir = _local_run_dir(ctx, run_id, cache) + if run_dir is None: + return {} + local: dict[str, LocalFile] = {} + for file in files: + info = _local_file_info(run_dir, file, cache) + if info is not None: + local[file.rel_path] = info + return local + + +def _cmd_clean(args: argparse.Namespace, ctx: _Context) -> int: + """clean サブコマンド: 実験フォルダの全ファイルを判定し,区分ごとの件数を表示する. + + SPEC_03「clean」の手順 1〜3.削除(手順 4・5)はまだ無い(PLAN_02 のステップ 2-3)ので, + 何も消さない. + """ + run_id = validate_run_id(args.run_id) + results = ctx.config.results + server, listing = _locate_clean_run(ctx, run_id, args.server) + _warn_running_jobs(ctx, server) + local = _local_files(ctx, run_id, local_paths_to_check(listing.files)) + judgement = classify_clean( + listing.files, local, results, discard_checkpoints=args.discard_checkpoints + ) + _write_stdout( + format_clean_report( + server.name, + run_id, + judgement, + checkpoints_dir=results.checkpoints.dir, + ) + ) + if not judgement.deletable: + logger.error( + "%s の実験 %s に説明がつかないファイルが %d 件あるため,何も消さない", + server.name, + run_id, + judgement.unexplained.count, + ) + return 1 + if args.dry_run: + _write_stdout("(--dry-run のため消していない)\n") + return 0 + logger.error( + "削除はまだ実装していない(ステップ 2-3).何も消していない(消せるかどうかは --dry-run で" + "確かめられる)" + ) + return 1 + + +# --------------------------------------------------------------------------- # 引数 # --------------------------------------------------------------------------- @@ -1300,6 +1547,37 @@ "--server", default=None, metavar="NAME", help="対象のサーバ(既定: 全サーバ)." ) + p_clean = sub.add_parser( + "clean", + parents=[common, server_opt], + help="サーバの実験フォルダを消せるかを判定する(削除はまだ実装していない)", + description=( + "サーバの /// の下の全ファイルの大きさとハッシュ" + "(SHA-256)を取り,一致(手元の同じ相対パスに同じ内容のファイルがある)・" + "捨ててよい(設定の results.discard に名前が一致する)・" + "重み(捨てる.results.checkpoints.dir の下で --discard-checkpoints を付けたとき)・" + "説明がつかない,に分けて件数と大きさを表示する.名前は大文字小文字を区別して比べる." + "説明がつかないものが 1 件でもあれば消さずに 0 以外で終わる." + "ファイル名は表示しない.削除はまだ実装していないので,何も消さない" + "(--dry-run を付けると,消せるときに 0 で終わる)." + ), + ) + p_clean.add_argument( + "run_id", + metavar="RUN_ID", + help="実験 ID(結果の置き場 results.dir の直下のディレクトリ名).", + ) + p_clean.add_argument( + "--discard-checkpoints", + action="store_true", + help="重み(設定の results.checkpoints.dir の下)を,回収していなくても捨ててよいとする.", + ) + p_clean.add_argument( + "--dry-run", + action="store_true", + help="判定して区分ごとの件数を表示するだけで,何も消さない.", + ) + return parser.parse_args(argv) @@ -1312,6 +1590,7 @@ "kill": _cmd_kill, "pull": _cmd_pull, "ls": _cmd_ls, + "clean": _cmd_clean, } diff --git a/src/labremote/commands.py b/src/labremote/commands.py index ddbb568..1eedfe1 100644 --- a/src/labremote/commands.py +++ b/src/labremote/commands.py @@ -22,6 +22,9 @@ import shlex from collections.abc import Mapping, Sequence +# whitelist は実行時に labremote の他のモジュールを import しないので,循環しない +from labremote.whitelist import validate_run_id + # 実験 ID に入れる git の短縮ハッシュをジョブへ渡す環境変数.サーバには .git を送らないため # 手元で求めて渡す(SPEC_01「環境変数」).利用する側のコードが別の名前で読む場合は, # 設定の `project.git_commit_env` で同じ値を追加の名前でも渡す @@ -85,6 +88,24 @@ LS_OTHER_RECORD = "other" LS_JOB_PREFIX = "job " +# clean の判定のための一覧(`build_clean_list_command`)の出力の目印.ls と同じく NUL で区切る. +# 各記録の形は `build_clean_list_command` の docstring にある +CLEAN_BEGIN_MARKER = "@@labremote-clean-begin" +CLEAN_RUN_PREFIX = "@@labremote-clean-run " +CLEAN_FIND_RC_PREFIX = "@@labremote-clean-find-rc " +CLEAN_AFTER_PREFIX = "@@labremote-clean-after " +CLEAN_END_MARKER = "@@labremote-clean-end" +# 実験フォルダの状態 +CLEAN_STATE_PRESENT = "present" +CLEAN_STATE_MISSING = "missing" +CLEAN_STATE_LINK = "link" +CLEAN_STATE_NOT_DIR = "notdir" +CLEAN_STATE_UNREADABLE = "unreadable" +# 実験フォルダの中の 1 件の記録の先頭 +CLEAN_FILE_PREFIX = "file " +CLEAN_OTHER_PREFIX = "other " +CLEAN_NOHASH_PREFIX = "nohash " + NVIDIA_SMI_QUERY = ( "nvidia-smi --query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" " --format=csv,noheader,nounits" @@ -784,6 +805,9 @@ [ # 名前の並び・文字数の数え方を,サーバの言語の設定に左右させない "export LC_ALL=C", + # 結果の置き場・ログの置き場へは相対の cd で入る.CDPATH が設定されたサーバで, + # 別の場所の同じ名前のフォルダへ入らないようにする + "unset CDPATH", f"printf '\\0'; {_ls_record(LS_BEGIN_MARKER)}", f"if {_ls_absent_test(remote)}; then " f"{_ls_record(LS_REMOTE_DIR_PREFIX + LS_STATE_MISSING)}; " @@ -1059,6 +1083,108 @@ return "; ".join(statements) +# clean の一覧で,実験フォルダの下のフォルダ以外のもの(find が引数で渡す `$@`)を 1 件ずつ +# 記録にする bash のスクリプト.名前はコマンドの引数で受け取り,記録の最後の欄に `%s` で出す +# (名前をコマンドの文字列にも,sha256sum の出力にも入れない.sha256sum は名前に `\`・改行が +# あると出力の形を変えるため,標準入力から読ませて名前を渡さない).リンク・通常のファイル以外は +# 開かない(FIFO を開いて止まる・リンクの先を読むことを避ける).大きさとハッシュのどちらかを +# 取れなければ `nohash` を出す(飛ばさない.手元はこれを見て止まる) +_CLEAN_ENTRY_SCRIPT = ( + "for p do " + 'if [ -L "$p" ] || [ ! -f "$p" ]; then ' + f"printf '{CLEAN_OTHER_PREFIX}%s\\0' \"$p\"; " + 'elif s=$(stat -c %s -- "$p") && h=$(sha256sum < "$p"); then ' + f'printf \'{CLEAN_FILE_PREFIX}%s %s %s\\0\' "$s" "${{h%% *}}" "$p"; ' + f"else printf '{CLEAN_NOHASH_PREFIX}%s\\0' \"$p\"; fi; " + "done" +) + + +def build_clean_list_command(remote_dir: str, *, results_dir: str, run_id: str) -> str: + """`clean` の判定のため,実験フォルダの下のファイルの一覧と大きさ・ハッシュを取るコマンド. + + SPEC_03「clean」の手順 1.一覧と大きさ・ハッシュ(SHA-256)の取得だけを行い,書き込まない・ + 消さない.埋め込むのは設定の `remote_dir`・結果の置き場と,ここでも `validate_run_id` を通した + `RUN_ID` だけである(どれも引用して埋め込む).`find` はリンクをたどらない既定のまま使う + (`-L`・`-H` を付けない.実験フォルダそのものがリンクなら,その先へ入らない). + + 前提にするサーバのコマンド: GNU findutils の `find`(`-mindepth`・`-exec ... {} +`), + GNU coreutils の `stat -c %s`・`sha256sum`(標準入力から読むので,名前の書き方の違いに + 左右されない),bash(記録を出すため.ジョブの実行にも使っている). + + 出力は NUL で区切った記録の並び(`labremote.cleanup.parse_clean_output` が解釈する). + 先頭に空の記録を置く(ログインシェルの挨拶が目印と同じ記録に混ざらないようにするため). + + - `@@labremote-clean-begin` + - `@@labremote-clean-run <状態>`.状態は `present`(リンクでないフォルダで,中に入れる)・ + `missing`(`remote_dir`・結果の置き場・実験フォルダのどれかが無い)・`link`(実験フォルダが + リンク)・`notdir`(フォルダでない)・`unreadable`(`remote_dir`・結果の置き場に入れない, + 実験フォルダを読めない).`present` 以外なら次は終端 + - `present` なら,実験フォルダの下のフォルダ以外のもの 1 件ごとに次のどれか(パスは + `.//...` の形) + - `file <バイト数> <パス>`(リンクでない通常のファイル) + - `other <パス>`(リンク・FIFO 等の通常のファイル以外.開かない) + - `nohash <パス>`(通常のファイルだが,大きさかハッシュを取れなかった) + - `@@labremote-clean-find-rc `(読めないフォルダがあれば 0 以外) + - `@@labremote-clean-after <状態>`(一覧の後にもう一度確かめた実験フォルダの状態.一覧の + 途中でリンク等に差し替えられていないことの確認用) + - `@@labremote-clean-end`(出力が途中で切れていないことの確認用) + + `find` と bash の標準エラーは捨てる(ファイル名を含みうるため.失敗は終了コードで分かる). + + 終了コード: 実験フォルダが無くても 0 で終わる(状態は出力で区別する). + + Args: + remote_dir: リモートのプロジェクトルート(引用して埋め込む). + results_dir: 結果の置き場(設定の `results.dir`.ここでも検証して引用する). + run_id: 実験 ID(ここでも `validate_run_id` で検証して引用する). + + Returns: + リモートで実行するシェルコマンド. + + Raises: + ValueError: リモートパス・結果の置き場・実験 ID が不正な場合. + """ + remote = quote_remote_path(remote_dir) + results = "./" + shlex.quote(_checked_results_dir(results_dir)) + run = "./" + shlex.quote(validate_run_id(run_id)) + + def state(value: str) -> str: + return _ls_record(CLEAN_RUN_PREFIX + value) + + def after(value: str) -> str: + return _ls_record(CLEAN_AFTER_PREFIX + value) + + listing = ( + f"{state(CLEAN_STATE_PRESENT)}; " + f"find {run} -mindepth 1 ! -type d -exec bash -c {shlex.quote(_CLEAN_ENTRY_SCRIPT)} " + "bash {} + 2>/dev/null; " + f"printf '{CLEAN_FIND_RC_PREFIX}%s\\0' \"$?\"; " + f"if [ -L {run} ] || [ ! -d {run} ]; then {after(CLEAN_STATE_LINK)}; " + f"else {after(CLEAN_STATE_PRESENT)}; fi" + ) + return "; ".join( + [ + # 名前の扱いをサーバの言語の設定に左右させない.相対の cd が CDPATH で別の場所へ + # 行かないようにする + "export LC_ALL=C", + "unset CDPATH", + f"printf '\\0'; {_ls_record(CLEAN_BEGIN_MARKER)}", + f"if {_ls_absent_test(remote)}; then {state(CLEAN_STATE_MISSING)}; " + f"elif ! cd -- {remote} 2>/dev/null; then {state(CLEAN_STATE_UNREADABLE)}; " + f"elif {_ls_absent_test(results)}; then {state(CLEAN_STATE_MISSING)}; " + f"elif ! cd -- {results} 2>/dev/null; then {state(CLEAN_STATE_UNREADABLE)}; " + # リンクかを先に確かめる([ -e ]・[ -d ] はリンクの先を見るため) + f"elif [ -L {run} ]; then {state(CLEAN_STATE_LINK)}; " + f"elif [ ! -e {run} ]; then {state(CLEAN_STATE_MISSING)}; " + f"elif [ ! -d {run} ]; then {state(CLEAN_STATE_NOT_DIR)}; " + f"elif [ ! -r {run} ] || [ ! -x {run} ]; then {state(CLEAN_STATE_UNREADABLE)}; " + f"else {listing}; fi", + _ls_record(CLEAN_END_MARKER), + ] + ) + + def build_pull_tar_command(remote_dir: str, *, results_dir: str) -> str: """標準入力の NUL 区切りのパス(`results_dir` 基準)だけを tar で書き出すコマンドを返す. diff --git a/src/labremote/report.py b/src/labremote/report.py index 6cbc241..31b146e 100644 --- a/src/labremote/report.py +++ b/src/labremote/report.py @@ -8,7 +8,13 @@ from collections.abc import Sequence -from labremote.cleanup import LsSummary, RemoteListing, ServerLeftovers +from labremote.cleanup import ( + CategoryTotal, + CleanJudgement, + LsSummary, + RemoteListing, + ServerLeftovers, +) from labremote.commands import SSH_FAILURE_RC from labremote.gpu import ( GpuInfo, @@ -504,6 +510,86 @@ ) +# --------------------------------------------------------------------------- +# clean の表示 +# --------------------------------------------------------------------------- + + +def _format_clean_line(label: str, total: CategoryTotal, width: int) -> str: + return f" {label:<{width}} {total.count:>6} 件 {format_size(total.size_bytes):>10}" + + +def format_clean_report( + server_name: str, + run_id: str, + judgement: CleanJudgement, + *, + checkpoints_dir: str, +) -> str: + """`clean RUN_ID` の判定の結果(区分ごとの件数と大きさ,結論,次にすること)を返す. + + 相対パス・ファイル名は出さない(件数と大きさだけ.SPEC_03「clean」の「表示」). + + Args: + server_name: サーバ名. + run_id: 検証済みの実験 ID. + judgement: 判定の結果. + checkpoints_dir: 重みを置くフォルダ(設定の `results.checkpoints.dir`). + + Returns: + 末尾に改行を含む複数行の文字列. + """ + total = judgement.total + labels = [ + ("一致(手元と同じ内容)", judgement.matched), + ("捨ててよい(results.discard)", judgement.discardable), + (f"重み(捨てる.{checkpoints_dir}/ の下)", judgement.checkpoints), + ("説明がつかない", judgement.unexplained), + ] + width = max(len(label) for label, _ in labels) + lines = [ + f"[{server_name}] 実験 {run_id}: {total.count} ファイル / {format_size(total.size_bytes)}", + *(_format_clean_line(label, value, width) for label, value in labels), + ] + if judgement.deletable: + note = "(ファイルが無い)" if total.count == 0 else "" + lines.append(f"結論: 消せる(説明がつかないものは無い){note}") + return "\n".join(lines) + "\n" + + lines.append(f"結論: 消せない(説明がつかないものが {judgement.unexplained.count} 件ある)") + hints: list[str] = [] + others = ( + judgement.unexplained.count + - judgement.unexplained_checkpoints + - judgement.unexplained_not_regular + - judgement.unexplained_unsafe + ) + if others: + hints.append( + f"手元に無い・内容が違うもの {others} 件: labremote pull {run_id} で回収する." + "回収しないで消してよいものは,設定の results.discard に書く" + ) + if judgement.unexplained_checkpoints: + hints.append( + f"重み({checkpoints_dir}/ の下){judgement.unexplained_checkpoints} 件: " + f"labremote pull {run_id} --with-checkpoints で回収する" + "(回収できるのは results.checkpoints.files に書いた名前だけ)か," + "捨てるなら --discard-checkpoints を付ける" + ) + if judgement.unexplained_not_regular: + hints.append( + f"リンク等の通常のファイル以外 {judgement.unexplained_not_regular} 件: " + "labremote では消さない.サーバで確かめる" + ) + if judgement.unexplained_unsafe: + hints.append( + f"手元のファイル名にできない名前 {judgement.unexplained_unsafe} 件: " + "labremote では消さない.サーバで確かめる" + ) + lines.extend(f" - {hint}" for hint in hints) + return "\n".join(lines) + "\n" + + def describe_skipped_links(links: Sequence[str]) -> str: """送らなかったリンクの件数と名前の 1 行を返す. diff --git a/src/labremote/whitelist.py b/src/labremote/whitelist.py index 5a0cf5b..ce17577 100644 --- a/src/labremote/whitelist.py +++ b/src/labremote/whitelist.py @@ -33,7 +33,7 @@ if TYPE_CHECKING: # 実行時には import しない(`labremote.config` がこのモジュールの名前の規則を使うため) - from labremote.config import ResultsConfig + from labremote.config import ResultList, ResultsConfig # find -printf '%y' の通常ファイル _FIND_TYPE_FILE = "f" @@ -130,6 +130,38 @@ return not path.startswith("/") and all(is_safe_local_name(part) for part in path.split("/")) +def is_safe_relative_path(path: str) -> bool: + """実験フォルダを基準にした POSIX 相対パスが,手元のパスにしてよい形かを返す. + + 回収の判定(`is_pull_allowed`・`check_pull_members`)と同じ規則である.空・絶対パス・ + `..`・`.`・空の部分・バックスラッシュ・NUL・制御文字・Windows で別の場所を指しうる名前を + 含むものは False.`clean` の判定(`labremote.cleanup`)が,手元のパスを組み立てる前に使う. + + Args: + path: `/` 区切りの相対パス. + + Returns: + 安全なら True. + """ + return _is_safe_relative(path) + + +def _matches_result_list(directory_parts: list[str], name: str, items: ResultList) -> bool: + """`files`(実験フォルダの直下)か `dirs`(path の直下で拡張子が suffix)の形に一致するか. + + 大文字小文字を区別して完全一致で比べる(回収・破棄の両方の判定がこの比べ方を使う). + """ + if not directory_parts: + return name in items.files + directory = "/".join(directory_parts) + # dirs は path の直下だけ(下の階層は directory が一致しないので対象にならない). + # 拡張子だけの名前(`.png`)は,その拡張子のファイルとみなさない + return any( + directory == item.path and name.endswith(item.suffix) and len(name) > len(item.suffix) + for item in items.dirs + ) + + def is_pull_allowed(rel_path: str, results: ResultsConfig, *, with_checkpoints: bool) -> bool: """実験フォルダを基準にした相対パスが,設定の回収の一覧に一致するかを返す. @@ -151,17 +183,35 @@ # ここから先は大文字小文字を区別して比べる(設定の検証の重複・重なりの検査とは逆. # 小文字にそろえると,一覧に無い名前まで回収する) *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: + if ( + directory_parts + and with_checkpoints + and "/".join(directory_parts) == 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 - ) + return _matches_result_list(directory_parts, name, results.pull) + + +def is_discard_allowed(rel_path: str, results: ResultsConfig) -> bool: + """実験フォルダを基準にした相対パスが,設定の「捨ててよい一覧」に一致するかを返す. + + SPEC_03「clean」の「捨ててよい」.`results.discard` の `files`・`dirs` の形に,回収の判定 + (`is_pull_allowed`)と同じ比べ方(大文字小文字を区別した完全一致)で当てはめる. + 設定の検証用の「小文字にして比べる」処理は使わない(使うと,一覧に無い名前まで捨ててよいと + 判定する). + + Args: + rel_path: 実験フォルダ(`<結果の置き場>/<実験ID>/`)を基準にした POSIX 相対パス. + results: 検証済みの設定の `results`. + + Returns: + 捨ててよければ True.パスが安全でない形なら,一覧に一致しても False. + """ + # パス外へ出る名前・手元(Windows)で別の場所を指しうる名前は,一覧に一致しても認めない + if not _is_safe_relative(rel_path): + return False + *directory_parts, name = rel_path.split("/") + return _matches_result_list(directory_parts, name, results.discard) def has_pull_names(results: ResultsConfig, *, with_checkpoints: bool) -> bool: diff --git a/tests/clean_helpers.py b/tests/clean_helpers.py new file mode 100644 index 0000000..4d3653d --- /dev/null +++ b/tests/clean_helpers.py @@ -0,0 +1,118 @@ +"""`clean RUN_ID` のサーバの出力(NUL 区切りの記録)と判定の入力を組み立てる補助. + +SPEC_03「clean」. + +`build_clean_list_command` がサーバで出す形を,目印の定数から組み立てる.`tests/test_cleanup.py` +(解析・判定)と `tests/test_cli.py`(サブコマンドの流れ)が使う.名前は架空のものだけを使う. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Sequence + +from ls_helpers import Record, encode_records + +from labremote.commands import ( + CLEAN_AFTER_PREFIX, + CLEAN_BEGIN_MARKER, + CLEAN_END_MARKER, + CLEAN_FILE_PREFIX, + CLEAN_FIND_RC_PREFIX, + CLEAN_NOHASH_PREFIX, + CLEAN_OTHER_PREFIX, + CLEAN_RUN_PREFIX, + CLEAN_STATE_PRESENT, +) +from labremote.config import ResultsConfig + +CLEAN_RUN_ID = "20261119-120000_demo_abc1234" + +# clean の判定のテストで使う設定の results(discard を含む) +CLEAN_RESULTS_DICT = { + "pull": { + "files": ["config.yaml", "metrics.json"], + "dirs": [{"path": "figures", "suffix": ".png"}], + }, + "checkpoints": {"dir": "checkpoints", "files": ["best.pth"]}, + "discard": { + "files": ["cache.bin", "nohup.out"], + "dirs": [ + {"path": "debug", "suffix": ".png"}, + {"path": "tmp/vis", "suffix": ".jpg"}, + ], + }, +} +CLEAN_RESULTS = ResultsConfig.model_validate(CLEAN_RESULTS_DICT) + +CLEAN_RESULTS_YAML = """\ +results: + pull: + files: [config.yaml, metrics.json] + dirs: + - path: figures + suffix: .png + checkpoints: + dir: checkpoints + files: [best.pth] + discard: + files: [cache.bin, nohup.out] + dirs: + - path: debug + suffix: .png + - path: tmp/vis + suffix: .jpg +""" + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _b(value: Record) -> bytes: + return value if isinstance(value, bytes) else value.encode("utf-8") + + +def file_record(rel: Record, data: bytes = b"x", *, run_id: str = CLEAN_RUN_ID) -> bytes: + """`file <バイト数> .//` の記録(大きさとハッシュは data から).""" + head = f"{CLEAN_FILE_PREFIX}{len(data)} {sha(data)} ./{run_id}/".encode() + return head + _b(rel) + + +def raw_file_record(size: str, digest: str, path: Record) -> bytes: + """欄を自由に書いた file の記録(path は `.//...` を含めて書く).""" + return f"{CLEAN_FILE_PREFIX}{size} {digest} ".encode() + _b(path) + + +def other_record(rel: Record, *, run_id: str = CLEAN_RUN_ID) -> bytes: + return f"{CLEAN_OTHER_PREFIX}./{run_id}/".encode() + _b(rel) + + +def nohash_record(rel: Record, *, run_id: str = CLEAN_RUN_ID) -> bytes: + return f"{CLEAN_NOHASH_PREFIX}./{run_id}/".encode() + _b(rel) + + +def clean_records( + entries: Sequence[Record] = (), + *, + find_rc: int | str = 0, + after: str = CLEAN_STATE_PRESENT, +) -> list[Record]: + """実験フォルダが present のときの記録の並び.""" + return [ + CLEAN_BEGIN_MARKER, + CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT, + *entries, + f"{CLEAN_FIND_RC_PREFIX}{find_rc}", + CLEAN_AFTER_PREFIX + after, + CLEAN_END_MARKER, + ] + + +def clean_output(entries: Sequence[Record] = (), **kwargs: object) -> bytes: + return encode_records(clean_records(entries, **kwargs)) # type: ignore[arg-type] + + +def clean_state_output(state: str) -> bytes: + """実験フォルダが present でないときの出力.""" + return encode_records([CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + state, CLEAN_END_MARKER]) diff --git a/tests/test_cleanup.py b/tests/test_cleanup.py index 6c90982..9278fed 100644 --- a/tests/test_cleanup.py +++ b/tests/test_cleanup.py @@ -7,11 +7,29 @@ - `du`・`find` が失敗した記録を「数え切れなかった」とすること サーバの出力はテストの中で組み立てる(`tests/ls_helpers.py`).実サーバには接続しない. + +後半は `clean RUN_ID` の判定(SPEC_03「clean」の手順 1〜3.testing ルールの必須対象 2「削除の +判定」): `classify_clean` が「説明がつかないもの」を 1 件でも見つけたら消せないとすること, +手元と内容が違う・手元に無いファイルを一致としないこと,`parse_clean_output` が解釈できない +出力を拒否すること.出力は `tests/clean_helpers.py` で組み立てる. """ from __future__ import annotations import pytest +from clean_helpers import ( + CLEAN_RESULTS, + CLEAN_RESULTS_DICT, + CLEAN_RUN_ID, + clean_output, + clean_records, + clean_state_output, + file_record, + nohash_record, + other_record, + raw_file_record, + sha, +) from ls_helpers import ( dir_record, encode_records, @@ -23,16 +41,36 @@ ) from labremote.cleanup import ( + CategoryTotal, + CleanCategory, + CleanJudgement, JobLogEntry, + LocalFile, LsSummary, + RemoteFile, RemoteListing, + RemoteRunListing, RunDirEntry, ServerLeftovers, + classify_clean, + is_safe_clean_path, listed_run_ids, + local_paths_to_check, + parse_clean_output, parse_ls_output, summarize_ls, ) from labremote.commands import ( + CLEAN_AFTER_PREFIX, + CLEAN_BEGIN_MARKER, + CLEAN_END_MARKER, + CLEAN_FIND_RC_PREFIX, + CLEAN_RUN_PREFIX, + CLEAN_STATE_LINK, + CLEAN_STATE_MISSING, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_PRESENT, + CLEAN_STATE_UNREADABLE, LS_BEGIN_MARKER, LS_END_MARKER, LS_LOGS_END_MARKER, @@ -44,6 +82,7 @@ LS_TMUX_RC_PREFIX, LS_VENV_PREFIX, ) +from labremote.config import ResultsConfig RUN_A = "20261119-120000_demo_abc1234" RUN_B = "20261120-090000_demo_def5678" @@ -633,3 +672,929 @@ ServerLeftovers("Curie", None, "x", unreachable=True), ] assert listed_run_ids(results) == frozenset({RUN_A, RUN_B}) + + +# =========================================================================== +# clean RUN_ID の判定(SPEC_03「clean」の手順 2・3 と「判定の細部」) +# =========================================================================== + + +def _rf(path: str, data: bytes = b"x") -> RemoteFile: + """サーバの通常のファイル(大きさとハッシュは data から).""" + return RemoteFile(path, True, len(data), sha(data)) + + +def _lf(data: bytes = b"x") -> LocalFile: + return LocalFile(len(data), sha(data)) + + +def _judge( + files: list[RemoteFile], + local: dict[str, LocalFile] | None = None, + *, + results: ResultsConfig = CLEAN_RESULTS, + discard_checkpoints: bool = False, +) -> CleanJudgement: + return classify_clean(files, local or {}, results, discard_checkpoints=discard_checkpoints) + + +def _category( + file: RemoteFile, + local: dict[str, LocalFile] | None = None, + *, + results: ResultsConfig = CLEAN_RESULTS, + discard_checkpoints: bool = False, +) -> CleanCategory: + judgement = _judge([file], local, results=results, discard_checkpoints=discard_checkpoints) + (entry,) = judgement.entries + assert entry.file is file + return entry.category + + +# 設定の一覧(CLEAN_RESULTS)のどれにも当たらない名前 +PLAIN = "result.txt" +NESTED = "sub/dir/result.txt" +_X = sha(b"x") +_Y = sha(b"y") + +# 一致としない組(サーバのファイル,手元の情報) +NOT_MATCHED_CASES = { + "not_in_local": (RemoteFile(PLAIN, True, 1, _X), {}), + "hash_differs": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, _Y)}), + "size_larger_same_hash": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(2, _X)}), + "size_smaller_same_hash": (RemoteFile(PLAIN, True, 2, _X), {PLAIN: LocalFile(1, _X)}), + "size_zero_same_hash": (RemoteFile(PLAIN, True, 0, _X), {PLAIN: LocalFile(1, _X)}), + "local_hash_empty": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, "")}), + "both_hash_empty": (RemoteFile(PLAIN, True, 1, ""), {PLAIN: LocalFile(1, "")}), + "both_hash_empty_size0": (RemoteFile(PLAIN, True, 0, ""), {PLAIN: LocalFile(0, "")}), + "local_upper": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, _X.upper())}), + "remote_upper": (RemoteFile(PLAIN, True, 1, _X.upper()), {PLAIN: LocalFile(1, _X)}), + "both_upper": (RemoteFile(PLAIN, True, 1, _X.upper()), {PLAIN: LocalFile(1, _X.upper())}), + "local_leading_space": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, f" {_X}")}), + "local_trailing_newline": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, f"{_X}\n")}), + "both_trailing_space": ( + RemoteFile(PLAIN, True, 1, f"{_X} "), + {PLAIN: LocalFile(1, f"{_X} ")}, + ), + "both_63_digits": (RemoteFile(PLAIN, True, 1, _X[:-1]), {PLAIN: LocalFile(1, _X[:-1])}), + "both_65_digits": (RemoteFile(PLAIN, True, 1, _X + "0"), {PLAIN: LocalFile(1, _X + "0")}), + "both_1_digit": (RemoteFile(PLAIN, True, 1, "0"), {PLAIN: LocalFile(1, "0")}), + "both_not_hex": (RemoteFile(PLAIN, True, 1, "g" * 64), {PLAIN: LocalFile(1, "g" * 64)}), + # 手元の辞書に別の相対パスでしか無い + "key_case_first": (_rf(PLAIN), {"Result.txt": _lf()}), + "key_case_all": (_rf(PLAIN), {"RESULT.TXT": _lf()}), + "key_dot_slash": (_rf(PLAIN), {"./result.txt": _lf()}), + "key_trailing_slash": (_rf(PLAIN), {"result.txt/": _lf()}), + "key_absolute": (_rf(PLAIN), {"/result.txt": _lf()}), + "key_trailing_space": (_rf(PLAIN), {"result.txt ": _lf()}), + "nested_key_case_dir1": (_rf(NESTED), {"Sub/dir/result.txt": _lf()}), + "nested_key_case_dir2": (_rf(NESTED), {"sub/Dir/result.txt": _lf()}), + "nested_key_dot_slash": (_rf(NESTED), {"./sub/dir/result.txt": _lf()}), + "nested_key_backslash": (_rf(NESTED), {"sub\\dir\\result.txt": _lf()}), + "nested_key_mixed_sep": (_rf(NESTED), {"sub/dir\\result.txt": _lf()}), + "nested_key_trailing_slash": (_rf(NESTED), {"sub/dir/result.txt/": _lf()}), + "nested_key_double_slash": (_rf(NESTED), {"sub//dir/result.txt": _lf()}), + "nested_key_basename_only": (_rf(NESTED), {"result.txt": _lf()}), + "nested_key_partial": (_rf(NESTED), {"dir/result.txt": _lf()}), +} + + +class TestCleanMatch: + @pytest.mark.parametrize("path", [PLAIN, NESTED, "config.yaml", "figures/a.png"]) + def test_same_size_and_hash_is_matched(self, path: str) -> None: + """SPEC_03「clean」: 手元の同じ相対パスに,大きさとハッシュが同じファイルがあれば一致.""" + assert _category(_rf(path, b"abc"), {path: _lf(b"abc")}) is CleanCategory.MATCHED + + def test_empty_file_matches_empty_file(self) -> None: + assert _category(_rf(PLAIN, b""), {PLAIN: _lf(b"")}) is CleanCategory.MATCHED + + @pytest.mark.parametrize("case", sorted(NOT_MATCHED_CASES)) + @pytest.mark.parametrize("flag", [False, True]) + def test_not_matched(self, case: str, flag: bool) -> None: + """SPEC_03「clean」: 大きさとハッシュの両方が同じで,同じ相対パスのときだけ一致. + + 一覧のどれにも当たらない名前なので,一致でなければ説明がつかない. + """ + remote, local = NOT_MATCHED_CASES[case] + judgement = _judge([remote], local, discard_checkpoints=flag) + assert judgement.entries[0].category is CleanCategory.UNEXPLAINED + assert judgement.matched == CategoryTotal(0, 0) + assert not judgement.deletable + + def test_matched_only_by_own_path_among_many(self) -> None: + """他のファイルの手元の情報で一致にならない(同じ内容の別のファイルがあっても).""" + files = [_rf("a.txt", b"same"), _rf("b.txt", b"same")] + judgement = _judge(files, {"a.txt": _lf(b"same")}) + assert [e.category for e in judgement.entries] == [ + CleanCategory.MATCHED, + CleanCategory.UNEXPLAINED, + ] + + def test_case_variants_on_server_each_need_own_local(self) -> None: + """サーバの A.csv と a.csv を,手元の 1 つで両方一致にしない.""" + files = [_rf("A.csv", b"v"), _rf("a.csv", b"v")] + judgement = _judge(files, {"a.csv": _lf(b"v")}) + assert judgement.matched.count == 1 + assert judgement.unexplained.count == 1 + assert not judgement.deletable + + +# 説明がつかないもの 1 件の種類(SPEC_03「clean」の手順 2 の「説明がつかない」) +UNEXPLAINED_KINDS: dict[str, tuple[RemoteFile, dict[str, LocalFile]]] = { + "not_in_local": (_rf("extra.txt", b"e"), {}), + "content_differs": (_rf("extra.txt", b"e"), {"extra.txt": _lf(b"E")}), + "size_differs": (_rf("extra.txt", b"e"), {"extra.txt": LocalFile(2, sha(b"e"))}), + "link": (RemoteFile("extra.txt", False), {"extra.txt": LocalFile(0, "")}), + "link_with_matching_local": ( + RemoteFile("extra.txt", False, 1, sha(b"e")), + {"extra.txt": _lf(b"e")}, + ), + "unsafe_path": (_rf("a/../extra.txt", b"e"), {"a/../extra.txt": _lf(b"e")}), + "checkpoint_without_flag": (_rf("checkpoints/best.pth", b"w"), {}), + "checkpoint_not_in_files": (_rf("checkpoints/other.pt", b"w"), {}), + "case_of_discard_name": (_rf("Cache.bin", b"c"), {}), +} + + +def _explained() -> tuple[list[RemoteFile], dict[str, LocalFile]]: + """説明がつくものだけの一覧(一致 5 件・捨ててよい 3 件).""" + matched = [_rf(f"m{i}/f{i}.txt", bytes([65 + i]) * (i + 1)) for i in range(5)] + local = {f.rel_path: LocalFile(f.size_bytes, f.sha256) for f in matched} + discard = [_rf("cache.bin", b"c"), _rf("debug/a.png", b"d"), _rf("tmp/vis/b.jpg", b"v")] + return matched + discard, local + + +class TestCleanDeletable: + def test_all_explained_is_deletable(self) -> None: + files, local = _explained() + judgement = _judge(files, local) + assert judgement.deletable + assert judgement.unexplained == CategoryTotal(0, 0) + assert judgement.matched.count == 5 and judgement.discardable.count == 3 + + @pytest.mark.parametrize("kind", sorted(UNEXPLAINED_KINDS)) + @pytest.mark.parametrize("position", ["first", "middle", "last"]) + def test_one_unexplained_makes_it_not_deletable(self, kind: str, position: str) -> None: + """SPEC_03「clean」の手順 3: 説明がつかないものが 1 件でもあれば消せない.""" + files, local = _explained() + extra, extra_local = UNEXPLAINED_KINDS[kind] + index = {"first": 0, "middle": len(files) // 2, "last": len(files)}[position] + files.insert(index, extra) + judgement = _judge(files, {**local, **extra_local}) + assert not judgement.deletable + assert judgement.unexplained.count == 1 + assert judgement.entries[index].category is CleanCategory.UNEXPLAINED + assert judgement.matched.count == 5 and judgement.discardable.count == 3 + + def test_all_kinds_together_are_counted(self) -> None: + files, local = _explained() + for i, (extra, extra_local) in enumerate(UNEXPLAINED_KINDS.values()): + # 同じ相対パスが重ならないよう,種類ごとにフォルダを分ける + path = extra.rel_path if extra.rel_path != "extra.txt" else f"k{i}/extra.txt" + files.append(RemoteFile(path, extra.regular, extra.size_bytes, extra.sha256)) + for value in extra_local.values(): + local[path] = value + judgement = _judge(files, local) + assert not judgement.deletable + assert judgement.unexplained.count == len(UNEXPLAINED_KINDS) + + def test_empty_run_dir_is_deletable(self) -> None: + """SPEC_03「clean」: フォルダ以外のものが 0 件なら,消してよい.""" + judgement = _judge([]) + assert judgement.deletable + assert judgement.total == CategoryTotal(0, 0) + assert judgement.entries == () + + +# 通常のファイル以外が当たりうる条件(どれに当たっても説明がつかない) +NON_REGULAR_PATHS = [ + "result.txt", # 手元に同じ相対パスの一致するファイルがある(下で手元の情報を渡す) + "cache.bin", # discard.files + "debug/a.png", # discard.dirs + "tmp/vis/a.jpg", + "checkpoints/best.pth", # 重み(--discard-checkpoints を付ける) + "checkpoints/sub/x.bin", +] + + +class TestCleanNonRegular: + @pytest.mark.parametrize("path", NON_REGULAR_PATHS) + @pytest.mark.parametrize("filled", [True, False], ids=["with_hash", "without_hash"]) + @pytest.mark.parametrize("flag", [False, True]) + def test_non_regular_is_always_unexplained(self, path: str, filled: bool, flag: bool) -> None: + """SPEC_03「clean」: リンク等は,手元・一覧・重みのフラグを見ずに説明がつかない.""" + remote = RemoteFile(path, False, 1, sha(b"x")) if filled else RemoteFile(path, False) + local = {path: _lf(b"x") if filled else LocalFile(0, "")} + assert _category(remote, local, discard_checkpoints=flag) is CleanCategory.UNEXPLAINED + + def test_non_regular_is_counted_and_not_deletable(self) -> None: + judgement = _judge( + [_rf("a.txt"), RemoteFile("cache.bin", False)], + {"a.txt": _lf()}, + discard_checkpoints=True, + ) + assert not judgement.deletable + assert judgement.unexplained_not_regular == 1 + assert judgement.unexplained.count == 1 + + +# 安全でない相対パス(SPEC_03「clean」・回収の名前の検査と同じ規則). +# 多くは,一覧・重みのフォルダ・手元の辞書のどれかに当たりうる形にしてある +UNSAFE_CLEAN_PATHS = [ + "", + "/abs", + "/cache.bin", + "/checkpoints/best.pth", + "a/../b", + "checkpoints/../cache.bin", + "..", + "../cache.bin", + ".", + "./a", + "./cache.bin", + "checkpoints/./best.pth", + "a//b", + "debug//a.png", + "checkpoints//best.pth", + "a\\b", + "debug\\a.png", + "checkpoints\\best.pth", + "C:x", + "c:cache.bin", + "checkpoints/C:best.pth", + "a:b", + "nul", + "NUL", + "CON.txt", + "con.png", + "debug/nul.png", + "checkpoints/CON", + "com1.bin", + "LPT9", + "nul .png", + "cache.bin.", + "cache.bin ", + "debug/a.png.", + "debug./a.png", + "checkpoints /best.pth", + "checkpoints./best.pth", + "a\x00b", + "cache.bin\x00", + "a\nb", + "cache.bin\n", + "a\rb", + "a\tb", + "a\x1b[31mb", + "a\x7fb", + "a/", + "checkpoints/", + "debug/", + "a\udcffb", + "checkpoints/\udcff", + "debug/\udc80.png", + "ab", + 'a"b', + "a|b", + "a?b", + "a*b", + "debug/*.png", +] + + +class TestCleanUnsafePath: + @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS) + def test_is_not_safe(self, path: str) -> None: + assert not is_safe_clean_path(path) + + @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS) + @pytest.mark.parametrize("flag", [False, True]) + def test_unsafe_path_is_unexplained_even_with_matching_local( + self, path: str, flag: bool + ) -> None: + """SPEC_03「clean」: 安全でない相対パスは,他のどの条件に当たっても説明がつかない.""" + remote = _rf(path, b"z") + judgement = _judge([remote], {path: _lf(b"z")}, discard_checkpoints=flag) + assert judgement.entries[0].category is CleanCategory.UNEXPLAINED + assert not judgement.deletable + assert judgement.unexplained_unsafe == 1 + + @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS) + def test_local_paths_to_check_skips_unsafe(self, path: str) -> None: + """手元を調べる対象に,安全でない相対パスを入れない(手元の外を開かない).""" + safe = _rf("ok.txt") + assert local_paths_to_check([_rf(path), safe, _rf(path)]) == (safe,) + + def test_local_paths_to_check_skips_non_regular(self) -> None: + safe = _rf("ok.txt") + files = [RemoteFile("link.txt", False), safe, RemoteFile("x", False, 1, sha(b"x"))] + assert local_paths_to_check(files) == (safe,) + + @pytest.mark.parametrize( + "path", ["a", "a b.txt", "sub/dir/x.bin", ".hidden", "-dash", "日本語.txt", "a..b"] + ) + def test_safe_paths_are_checked(self, path: str) -> None: + assert is_safe_clean_path(path) + assert local_paths_to_check([_rf(path)]) == (_rf(path),) + + +class TestCleanDiscardable: + @pytest.mark.parametrize( + "path", ["cache.bin", "nohup.out", "debug/a.png", "debug/x y.png", "tmp/vis/b.jpg"] + ) + def test_discard_names_are_discardable(self, path: str) -> None: + """SPEC_03「clean」: results.discard の形に一致すれば捨ててよい(手元に無くても).""" + assert _category(_rf(path)) is CleanCategory.DISCARDABLE + + @pytest.mark.parametrize( + "path", + [ + # files は実験フォルダの直下だけ + "sub/cache.bin", + "debug/cache.bin", + "checkpoints2/nohup.out", + # 大文字小文字が違う + "Cache.bin", + "CACHE.BIN", + "cache.BIN", + "Nohup.out", + "Debug/a.png", + "debug/a.PNG", + "debug/a.Png", + "tmp/Vis/b.jpg", + "TMP/vis/b.jpg", + # 名前の一部だけが一致する + "cache.bin.bak", + "xcache.bin", + "cache.binx", + "nohup.out2", + # dirs は path の直下で suffix のものだけ + "debug/sub/a.png", + "debug/sub/deep/a.png", + "x/debug/a.png", + "tmp/a.jpg", + "tmp/vis/sub/b.jpg", + "vis/b.jpg", + "debug2/a.png", + "debu/a.png", + "debug/a.jpg", + "tmp/vis/b.png", + "debug/a.png.txt", + "debug/apng", + # 拡張子だけの名前 + "debug/.png", + "tmp/vis/.jpg", + # dirs の path そのもの + "debug", + "tmp/vis", + # pull の一覧の名前(回収の一覧は捨ててよいにならない) + "config.yaml", + "metrics.json", + "figures/a.png", + ], + ) + def test_other_names_are_not_discardable(self, path: str) -> None: + assert _category(_rf(path)) is CleanCategory.UNEXPLAINED + assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.UNEXPLAINED + + +class TestCleanCheckpoints: + @pytest.mark.parametrize( + "path", + [ + "checkpoints/best.pth", # checkpoints.files の名前 + "checkpoints/last.pth", # checkpoints.files に無い名前 + "checkpoints/sub/epoch1.pth", # 下の階層 + "checkpoints/a/b/c/d.bin", + "checkpoints/.hidden", + "checkpoints/config.yaml", + "checkpoints/cache.bin", + ], + ) + def test_under_checkpoints_dir_only_with_flag(self, path: str) -> None: + """SPEC_03「clean」: checkpoints.dir の下の全部.--discard-checkpoints のときだけ.""" + assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.CHECKPOINT + assert _category(_rf(path), discard_checkpoints=False) is CleanCategory.UNEXPLAINED + + @pytest.mark.parametrize( + "path", + [ + "checkpoints", # その名前のファイル + "checkpoints2/x", + "checkpointsX/x", + "checkpoints.bak/x", + "checkpoint/x", + "Checkpoints/x", + "CHECKPOINTS/best.pth", + "sub/checkpoints/x", + "a/b/checkpoints/best.pth", + "xcheckpoints/x", + "best.pth", + ], + ) + def test_not_under_checkpoints_dir(self, path: str) -> None: + assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.UNEXPLAINED + + def test_configured_checkpoints_dir_is_used(self) -> None: + """SPEC_02「`results`」: checkpoints.dir を別の名前にしたときは,その名前の下だけ.""" + data = {**CLEAN_RESULTS_DICT, "checkpoints": {"dir": "weights", "files": ["final.ckpt"]}} + results = ResultsConfig.model_validate(data) + for path in ["weights/final.ckpt", "weights/other.pt", "weights/sub/x"]: + got = _category(_rf(path), results=results, discard_checkpoints=True) + assert got is CleanCategory.CHECKPOINT, path + for path in ["checkpoints/best.pth", "weights", "Weights/x", "weights2/x", "a/weights/x"]: + got = _category(_rf(path), results=results, discard_checkpoints=True) + assert got is CleanCategory.UNEXPLAINED, path + + def test_unexplained_checkpoints_are_counted_for_hint(self) -> None: + judgement = _judge( + [_rf("checkpoints/best.pth"), _rf("checkpoints/sub/x"), _rf("extra.txt")] + ) + assert judgement.unexplained.count == 3 + assert judgement.unexplained_checkpoints == 2 + + +class TestCleanOrder: + @pytest.mark.parametrize("path", ["cache.bin", "debug/a.png"]) + def test_matched_wins_over_discardable(self, path: str) -> None: + """SPEC_03「clean」の「分ける順」: 一致 → 捨ててよい.""" + assert _category(_rf(path, b"q"), {path: _lf(b"q")}) is CleanCategory.MATCHED + + @pytest.mark.parametrize("flag", [False, True]) + def test_matched_wins_over_checkpoint(self, flag: bool) -> None: + path = "checkpoints/best.pth" + got = _category(_rf(path, b"w"), {path: _lf(b"w")}, discard_checkpoints=flag) + assert got is CleanCategory.MATCHED + + def test_discardable_when_local_differs(self) -> None: + """手元と内容が違っても,捨ててよい一覧に当たれば捨ててよい(次の区分へ進む).""" + got = _category(_rf("cache.bin", b"a"), {"cache.bin": _lf(b"b")}) + assert got is CleanCategory.DISCARDABLE + + def test_checkpoint_when_local_differs(self) -> None: + path = "checkpoints/best.pth" + got = _category(_rf(path, b"a"), {path: _lf(b"b")}, discard_checkpoints=True) + assert got is CleanCategory.CHECKPOINT + + +class TestCleanTotals: + def test_category_totals_and_overall_total(self) -> None: + files = [ + _rf("a.txt", b"1"), # 一致 1 + _rf("sub/b.txt", b"22"), # 一致 2 + _rf("cache.bin", b"333"), # 捨ててよい 3 + _rf("debug/x.png", b"4444"), # 捨ててよい 4 + _rf("checkpoints/best.pth", b"5" * 50), # 重み 50 + _rf("checkpoints/s/x", b"6" * 60), # 重み 60 + _rf("other.txt", b"7" * 7), # 説明がつかない 7 + RemoteFile("link", False), # 説明がつかない 0 + _rf("c.txt", b"8" * 8), # 手元と違う 8 + ] + local = {"a.txt": _lf(b"1"), "sub/b.txt": _lf(b"22"), "c.txt": _lf(b"9" * 8)} + judgement = _judge(files, local, discard_checkpoints=True) + assert judgement.matched == CategoryTotal(2, 3) + assert judgement.discardable == CategoryTotal(2, 7) + assert judgement.checkpoints == CategoryTotal(2, 110) + assert judgement.unexplained == CategoryTotal(3, 15) + assert judgement.total == CategoryTotal(9, 135) + assert not judgement.deletable + assert [e.file for e in judgement.entries] == files + + def test_large_sizes_are_summed(self) -> None: + big = 5 * 1024**4 + files = [RemoteFile(f"f{i}", True, big, sha(b"x")) for i in range(3)] + local = {f.rel_path: LocalFile(big, sha(b"x")) for f in files} + judgement = _judge(files, local) + assert judgement.matched == CategoryTotal(3, 3 * big) + assert judgement.total == CategoryTotal(3, 3 * big) + + +class TestDiscardCheckpointsLoosensOnlyWeights: + def test_flag_changes_only_files_under_checkpoints_dir(self) -> None: + """SPEC_03「clean」: --discard-checkpoints で変わるのは,重みのフォルダの下の区分だけ.""" + files = [ + _rf("a.txt", b"1"), + _rf("cache.bin"), + _rf("debug/x.png"), + _rf("checkpoints/best.pth", b"w"), + _rf("checkpoints/sub/x", b"w2"), + _rf("checkpoints/m.pth", b"m"), # 手元と一致 + _rf("checkpoints"), + _rf("Checkpoints/x"), + _rf("sub/checkpoints/x"), + _rf("extra.txt"), + RemoteFile("checkpoints/link", False), + _rf("checkpoints/../x"), + _rf("checkpoints//x"), + _rf("checkpoints/\udcff"), + ] + local = {"a.txt": _lf(b"1"), "checkpoints/m.pth": _lf(b"m")} + off = _judge(files, local, discard_checkpoints=False) + on = _judge(files, local, discard_checkpoints=True) + changed = [ + (a.file.rel_path, a.category, b.category) + for a, b in zip(off.entries, on.entries, strict=True) + if a.category is not b.category + ] + assert changed == [ + ("checkpoints/best.pth", CleanCategory.UNEXPLAINED, CleanCategory.CHECKPOINT), + ("checkpoints/sub/x", CleanCategory.UNEXPLAINED, CleanCategory.CHECKPOINT), + ] + assert off.checkpoints == CategoryTotal(0, 0) + assert not on.deletable # 他の説明がつかないものは残る + + +# --------------------------------------------------------------------------- +# clean の一覧の出力の解析(SPEC_03「clean」の「サーバの出力の扱い」) +# --------------------------------------------------------------------------- + +CLEAN_ENTRIES = [ + file_record("metrics.json", b"{}"), + file_record("sub dir/a b.txt", b"hello"), + other_record("link"), + file_record("empty.bin", b""), + other_record("sub dir/fifo"), + file_record("checkpoints/best.pth", b"w" * 1000), +] +CLEAN_NORMAL_RECORDS = clean_records(CLEAN_ENTRIES) +CLEAN_NORMAL = clean_output(CLEAN_ENTRIES) +CLEAN_EMPTY = clean_output([]) +_H = sha(b"x") +_RUN_PREFIX = f"./{CLEAN_RUN_ID}/" +_CLEAN_SECRET = "secretcleanname_z3" + + +def _parse(data: bytes) -> RemoteRunListing: + return parse_clean_output(data, CLEAN_RUN_ID) + + +class TestParseCleanNormal: + def test_reads_files_and_others_in_order(self) -> None: + listing = _parse(CLEAN_NORMAL) + assert listing.state == CLEAN_STATE_PRESENT + assert listing.files == ( + RemoteFile("metrics.json", True, 2, sha(b"{}")), + RemoteFile("sub dir/a b.txt", True, 5, sha(b"hello")), + RemoteFile("link", False), + RemoteFile("empty.bin", True, 0, sha(b"")), + RemoteFile("sub dir/fifo", False), + RemoteFile("checkpoints/best.pth", True, 1000, sha(b"w" * 1000)), + ) + + def test_empty_run_dir(self) -> None: + assert _parse(CLEAN_EMPTY) == RemoteRunListing(CLEAN_STATE_PRESENT, ()) + + @pytest.mark.parametrize( + "state", + [CLEAN_STATE_MISSING, CLEAN_STATE_LINK, CLEAN_STATE_NOT_DIR, CLEAN_STATE_UNREADABLE], + ) + def test_other_states(self, state: str) -> None: + listing = _parse(clean_state_output(state)) + assert listing == RemoteRunListing(state) + assert listing.files == () + + def test_output_without_last_nul_is_still_complete(self) -> None: + """ls と同じく,最後の NUL だけを落としたもの(終端の目印まで届いている)は読める.""" + assert _parse(CLEAN_NORMAL[:-1]) == _parse(CLEAN_NORMAL) + assert _parse(CLEAN_EMPTY[:-1]) == _parse(CLEAN_EMPTY) + + @pytest.mark.parametrize( + "name", + ["a b", " lead", "trail ", "x\ny", "back\\slash", "q'uote", "$(touch PWNED)", "-rf"], + ) + def test_names_with_spaces_and_specials_are_kept_whole(self, name: str) -> None: + """名前の空白で欄がずれない(パスは最後の欄で,空白を含んだまま読む).""" + listing = _parse(clean_output([file_record(name, b"abc")])) + assert listing.files == (RemoteFile(name, True, 3, sha(b"abc")),) + + def test_name_that_is_not_utf8_is_read_but_unsafe(self) -> None: + """UTF-8 として読めない名前は,解析では読み,判定で安全でないとする.""" + listing = _parse(clean_output([file_record(b"bad\xff.bin")])) + (found,) = listing.files + assert not is_safe_clean_path(found.rel_path) + judgement = classify_clean( + listing.files, {found.rel_path: LocalFile(1, sha(b"x"))}, CLEAN_RESULTS, + discard_checkpoints=True, + ) # fmt: skip + assert not judgement.deletable + + def test_path_with_dot_dot_under_run_dir_is_parsed_then_unexplained(self) -> None: + listing = _parse(clean_output([raw_file_record("1", _H, f"{_RUN_PREFIX}../escape")])) + judgement = classify_clean( + listing.files, {"../escape": LocalFile(1, _H)}, CLEAN_RESULTS, + discard_checkpoints=True, + ) # fmt: skip + assert not judgement.deletable + + def test_large_size(self) -> None: + size = 123 * 1024**4 + listing = _parse(clean_output([raw_file_record(str(size), _H, f"{_RUN_PREFIX}big")])) + assert listing.files[0].size_bytes == size + + @pytest.mark.parametrize("banner", [b"Welcome\nLast login: Mon\n", b"motd\0nul\0", b"\xff\0"]) + def test_banner_before_begin_is_ignored(self, banner: bytes) -> None: + assert _parse(banner + CLEAN_NORMAL) == _parse(CLEAN_NORMAL) + + @pytest.mark.parametrize("trailer", [b"bye\n", b"\0garbage\0", b"\xff\0"]) + def test_garbage_after_end_is_ignored(self, trailer: bytes) -> None: + assert _parse(CLEAN_NORMAL + trailer) == _parse(CLEAN_NORMAL) + + +def _without(records: list, prefix: str) -> list: + return [r for r in records if not (isinstance(r, str) and r.startswith(prefix))] + + +def _swap(records: list, i: int, j: int) -> list: + out = list(records) + out[i], out[j] = out[j], out[i] + return out + + +_FIND_RC_INDEX = len(CLEAN_NORMAL_RECORDS) - 3 +_AFTER_INDEX = len(CLEAN_NORMAL_RECORDS) - 2 + +BROKEN_CLEAN_OUTPUTS: dict[str, bytes] = { + "empty": b"", + "only_nul": b"\0", + "garbage": b"Welcome to the server\n", + "newline_separated": b"\n".join( + r if isinstance(r, bytes) else r.encode() for r in CLEAN_NORMAL_RECORDS + ), + # 目印が欠けている + "no_begin": encode_records(CLEAN_NORMAL_RECORDS[1:]), + "no_end": encode_records(CLEAN_NORMAL_RECORDS[:-1]), + "no_run_state": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_RUN_PREFIX)), + "no_find_rc": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_FIND_RC_PREFIX)), + "no_after": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_AFTER_PREFIX)), + "empty_no_find_rc": encode_records(_without(clean_records([]), CLEAN_FIND_RC_PREFIX)), + "present_then_end": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT, CLEAN_END_MARKER] + ), + "missing_without_end": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING] + ), + "missing_then_records": encode_records( + [ + CLEAN_BEGIN_MARKER, + CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING, + file_record("a"), + CLEAN_END_MARKER, + ] + ), + "missing_then_find_rc": encode_records( + [ + CLEAN_BEGIN_MARKER, + CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING, + f"{CLEAN_FIND_RC_PREFIX}0", + CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT, + CLEAN_END_MARKER, + ] + ), + # 目印の順が違う + "find_rc_before_entries": encode_records( + [ + CLEAN_BEGIN_MARKER, + CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT, + f"{CLEAN_FIND_RC_PREFIX}0", + *CLEAN_ENTRIES, + CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT, + CLEAN_END_MARKER, + ] + ), + "after_before_find_rc": encode_records( + _swap(CLEAN_NORMAL_RECORDS, _FIND_RC_INDEX, _AFTER_INDEX) + ), + "end_before_after": encode_records( + _swap(CLEAN_NORMAL_RECORDS, _AFTER_INDEX, len(CLEAN_NORMAL_RECORDS) - 1) + ), + "run_state_after_entries": encode_records( + [ + CLEAN_BEGIN_MARKER, + *CLEAN_ENTRIES, + CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT, + f"{CLEAN_FIND_RC_PREFIX}0", + CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT, + CLEAN_END_MARKER, + ] + ), + "run_marker_in_entries": clean_output([CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT]), + "after_marker_in_entries": clean_output([CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT]), + "two_find_rc": encode_records( + [ + *CLEAN_NORMAL_RECORDS[:_FIND_RC_INDEX], + f"{CLEAN_FIND_RC_PREFIX}0", + *CLEAN_NORMAL_RECORDS[_FIND_RC_INDEX:], + ] + ), + "entry_after_find_rc": encode_records( + [ + *CLEAN_NORMAL_RECORDS[: _FIND_RC_INDEX + 1], + file_record("late.txt"), + *CLEAN_NORMAL_RECORDS[_AFTER_INDEX:], + ] + ), + "entry_after_after": encode_records( + [*CLEAN_NORMAL_RECORDS[:-1], file_record("late.txt"), CLEAN_END_MARKER] + ), + # 大きさ + "size_word": clean_output([raw_file_record("big", _H, f"{_RUN_PREFIX}a")]), + "size_negative": clean_output([raw_file_record("-1", _H, f"{_RUN_PREFIX}a")]), + "size_empty": clean_output([raw_file_record("", _H, f"{_RUN_PREFIX}a")]), + "size_plus": clean_output([raw_file_record("+1", _H, f"{_RUN_PREFIX}a")]), + "size_decimal": clean_output([raw_file_record("1.5", _H, f"{_RUN_PREFIX}a")]), + "size_exponent": clean_output([raw_file_record("1e3", _H, f"{_RUN_PREFIX}a")]), + "size_hex": clean_output([raw_file_record("0x10", _H, f"{_RUN_PREFIX}a")]), + "size_fullwidth": clean_output([raw_file_record("1", _H, f"{_RUN_PREFIX}a")]), + "size_underscore": clean_output([raw_file_record("1_000", _H, f"{_RUN_PREFIX}a")]), + # ハッシュ + "hash_63": clean_output([raw_file_record("1", _H[:-1], f"{_RUN_PREFIX}a")]), + "hash_65": clean_output([raw_file_record("1", _H + "0", f"{_RUN_PREFIX}a")]), + "hash_upper": clean_output([raw_file_record("1", _H.upper(), f"{_RUN_PREFIX}a")]), + "hash_not_hex": clean_output([raw_file_record("1", "g" * 64, f"{_RUN_PREFIX}a")]), + "hash_empty": clean_output([raw_file_record("1", "", f"{_RUN_PREFIX}a")]), + "hash_dash": clean_output([raw_file_record("1", "-", f"{_RUN_PREFIX}a")]), + "hash_fullwidth": clean_output([raw_file_record("1", "a" + _H[1:], f"{_RUN_PREFIX}a")]), + # 欄が足りない + "file_without_path": clean_output([f"file 1 {_H}"]), + "file_without_hash": clean_output(["file 1"]), + "file_bare": clean_output(["file "]), + "file_word_only": clean_output(["file"]), + "other_bare": clean_output(["other "]), + "other_word_only": clean_output(["other"]), + # 同じ相対パスが 2 回 + "duplicate_file_file": clean_output([file_record("a.txt"), file_record("a.txt")]), + "duplicate_file_file_other_hash": clean_output( + [file_record("a.txt", b"1"), file_record("a.txt", b"2")] + ), + "duplicate_file_other": clean_output([file_record("a.txt"), other_record("a.txt")]), + "duplicate_other_file": clean_output([other_record("a.txt"), file_record("a.txt")]), + "duplicate_other_other": clean_output([other_record("a.txt"), other_record("a.txt")]), + "duplicate_apart": clean_output( + [file_record("sub/a"), file_record("b"), file_record("c"), file_record("sub/a")] + ), + # ハッシュを取れなかった + "nohash": clean_output([nohash_record("a.txt")]), + "nohash_among_files": clean_output([file_record("a"), nohash_record("b"), file_record("c")]), + "nohash_bare": clean_output(["nohash "]), + # パスが .// の下でない + "path_other_run": clean_output([file_record("a", run_id="20261120-090000_demo_def5678")]), + "path_run_itself": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID}")]), + "path_run_itself_slash": clean_output([raw_file_record("1", _H, _RUN_PREFIX)]), + "path_run_prefix_x": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID}x/a")]), + "path_run_shorter": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID[:-1]}/a")]), + "path_parent": clean_output([raw_file_record("1", _H, "../a")]), + "path_parent_run": clean_output([raw_file_record("1", _H, f"../{CLEAN_RUN_ID}/a")]), + "path_without_dot": clean_output([raw_file_record("1", _H, f"{CLEAN_RUN_ID}/a")]), + "path_absolute": clean_output([raw_file_record("1", _H, f"/{CLEAN_RUN_ID}/a")]), + "path_dot": clean_output([raw_file_record("1", _H, "./a")]), + "path_case": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID.upper()}/a")]), + "other_path_other_run": clean_output( + [other_record("a", run_id="20261120-090000_demo_def5678")] + ), + "other_path_run_itself": clean_output([f"other ./{CLEAN_RUN_ID}"]), + # find の終了コード + "find_rc_1": clean_output(CLEAN_ENTRIES, find_rc=1), + "find_rc_2": clean_output(CLEAN_ENTRIES, find_rc=2), + "find_rc_1_empty": clean_output([], find_rc=1), + "find_rc_word": clean_output(CLEAN_ENTRIES, find_rc="x"), + "find_rc_empty": clean_output(CLEAN_ENTRIES, find_rc=""), + "find_rc_negative": clean_output(CLEAN_ENTRIES, find_rc="-1"), + # 一覧の後の状態 + "after_link": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_LINK), + "after_notdir": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_NOT_DIR), + "after_missing": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_MISSING), + "after_unreadable": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_UNREADABLE), + "after_link_empty": clean_output([], after=CLEAN_STATE_LINK), + "after_unknown": clean_output(CLEAN_ENTRIES, after="ok"), + "after_upper": clean_output(CLEAN_ENTRIES, after="PRESENT"), + "after_empty": clean_output(CLEAN_ENTRIES, after=""), + # 知らない種類の記録 + "unknown_dir_record": clean_output([f"dir {_RUN_PREFIX}a"]), + "unknown_upper_file": clean_output([f"FILE 1 {_H} {_RUN_PREFIX}a"]), + "unknown_link_record": clean_output([f"link {_RUN_PREFIX}a"]), + "unknown_empty_record": clean_output([""]), + "unknown_bare_path": clean_output([f"{_RUN_PREFIX}a"]), + "unknown_file_tab": clean_output([f"file\t1\t{_H}\t{_RUN_PREFIX}a"]), + # 状態が知らない値 + "state_unknown": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "exists", CLEAN_END_MARKER] + ), + "state_upper": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "MISSING", CLEAN_END_MARKER] + ), + "state_trailing_space": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "missing ", CLEAN_END_MARKER] + ), + "state_empty": encode_records([CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX, CLEAN_END_MARKER]), + "present_upper": encode_records( + [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "PRESENT", *CLEAN_NORMAL_RECORDS[2:]] + ), +} + + +class TestParseCleanBroken: + @pytest.mark.parametrize("case", sorted(BROKEN_CLEAN_OUTPUTS)) + def test_unparsable_output_is_value_error(self, case: str) -> None: + """SPEC_03「clean」: 解釈できない出力は「説明がつく」と見なさず ValueError にする.""" + with pytest.raises(ValueError): + _parse(BROKEN_CLEAN_OUTPUTS[case]) + + @pytest.mark.parametrize("cut", range(len(CLEAN_NORMAL) - 1)) + def test_truncated_output_is_value_error(self, cut: int) -> None: + """正常な出力を各バイト位置で切ったものは ValueError(最後の NUL だけを落としたものは除く). + + ls と同じ扱い. + """ + with pytest.raises(ValueError): + _parse(CLEAN_NORMAL[:cut]) + + @pytest.mark.parametrize("cut", range(len(CLEAN_EMPTY) - 1)) + def test_truncated_empty_output_is_value_error(self, cut: int) -> None: + """「空の実験フォルダ」の出力も,途中で切れていれば消せると読まない.""" + with pytest.raises(ValueError): + _parse(CLEAN_EMPTY[:cut]) + + @pytest.mark.parametrize("state", [CLEAN_STATE_MISSING, CLEAN_STATE_LINK]) + def test_truncated_state_output_is_value_error(self, state: str) -> None: + data = clean_state_output(state) + for cut in range(len(data) - 1): + with pytest.raises(ValueError): + _parse(data[:cut]) + + @pytest.mark.parametrize( + "run_id", ["", "..", "a/b", "-rf", "a;b", "$(x)", f"{CLEAN_RUN_ID}\n", "x.", "nul"] + ) + def test_bad_run_id_is_value_error(self, run_id: str) -> None: + with pytest.raises(ValueError): + parse_clean_output(CLEAN_EMPTY, run_id) + + def test_run_id_must_match_output(self) -> None: + """別の実験 ID で取った出力を,この実験 ID の一覧として読まない.""" + with pytest.raises(ValueError): + parse_clean_output(CLEAN_NORMAL, "20261120-090000_demo_def5678") + + @pytest.mark.parametrize( + "entries", + [ + [file_record(_CLEAN_SECRET), file_record(_CLEAN_SECRET)], + [file_record(_CLEAN_SECRET), other_record(_CLEAN_SECRET)], + [raw_file_record("big", _H, f"{_RUN_PREFIX}{_CLEAN_SECRET}")], + [raw_file_record("1", "XYZ", f"{_RUN_PREFIX}{_CLEAN_SECRET}")], + [raw_file_record("1", _H, f"./other/{_CLEAN_SECRET}")], + [nohash_record(_CLEAN_SECRET)], + [f"weird {_RUN_PREFIX}{_CLEAN_SECRET}"], + [f"file 1 {_CLEAN_SECRET}"], + [_CLEAN_SECRET], + ], + ids=[ + "dup", "dup_other", "size", "hash", "outside", "nohash", "kind", "fields", "bare", + ], + ) # fmt: skip + def test_error_message_does_not_contain_server_names(self, entries: list) -> None: + """SPEC_03「clean」: 相対パス・ファイル名は,エラーのどこにも出さない.""" + with pytest.raises(ValueError) as excinfo: + _parse(clean_output([file_record(f"ok_{_CLEAN_SECRET}"), *entries])) + assert _CLEAN_SECRET not in str(excinfo.value) + assert "secretclean" not in repr(excinfo.value) + + @pytest.mark.parametrize("find_rc", [1]) + def test_find_failure_message_has_no_names(self, find_rc: int) -> None: + with pytest.raises(ValueError) as excinfo: + _parse(clean_output([file_record(_CLEAN_SECRET)], find_rc=find_rc)) + assert _CLEAN_SECRET not in str(excinfo.value) + + +class TestParseCleanFakeListing: + # 挨拶に紛れた偽の一覧(空の実験フォルダ = 消せる)を本物として読まない + @pytest.mark.parametrize( + "fake", + [CLEAN_EMPTY, clean_state_output(CLEAN_STATE_MISSING), CLEAN_NORMAL], + ids=["empty_run_dir", "missing", "normal"], + ) + def test_fake_listing_before_real_one_is_rejected(self, fake: bytes) -> None: + with pytest.raises(ValueError, match="解釈できない"): + _parse(fake + CLEAN_NORMAL) + + @pytest.mark.parametrize( + "fake", [CLEAN_EMPTY, clean_state_output(CLEAN_STATE_MISSING)], ids=["empty", "missing"] + ) + def test_fake_listing_after_end_is_rejected(self, fake: bytes) -> None: + with pytest.raises(ValueError, match="解釈できない"): + _parse(CLEAN_NORMAL + fake) + + def test_fake_empty_listing_before_failing_real_one_is_rejected(self) -> None: + """本物が find の失敗でも,前の偽の「空」を読んで消せるとしない.""" + with pytest.raises(ValueError): + _parse(CLEAN_EMPTY + clean_output(CLEAN_ENTRIES, find_rc=1)) + + @pytest.mark.parametrize("marker", [CLEAN_BEGIN_MARKER, CLEAN_END_MARKER]) + @pytest.mark.parametrize("position", ["before", "after"]) + def test_duplicated_marker_is_rejected(self, marker: str, position: str) -> None: + extra = b"\0" + marker.encode() + b"\0" + data = extra + CLEAN_NORMAL if position == "before" else CLEAN_NORMAL + extra + with pytest.raises(ValueError, match="解釈できない"): + _parse(data) + + def test_marker_text_inside_a_name_is_not_a_marker(self) -> None: + listing = _parse(clean_output([file_record(CLEAN_END_MARKER), other_record("x")])) + assert [f.rel_path for f in listing.files] == [CLEAN_END_MARKER, "x"] diff --git a/tests/test_cli.py b/tests/test_cli.py index 63c3d6a..276ea31 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -20,6 +20,7 @@ import io import logging import os +import re import shlex import subprocess import sys @@ -31,6 +32,17 @@ import pytest import yaml +from clean_helpers import ( + CLEAN_RESULTS_YAML, + CLEAN_RUN_ID, + clean_output, + clean_state_output, + file_record, + nohash_record, + other_record, + raw_file_record, + sha, +) from ls_helpers import ( dir_record, encode_records, @@ -42,7 +54,13 @@ from results_helpers import OTHER_RESULTS_YAML, SAMPLE_RESULTS_YAML import labremote.cli as cli +from labremote.cleanup import CleanCategory from labremote.commands import ( + CLEAN_BEGIN_MARKER, + CLEAN_STATE_LINK, + CLEAN_STATE_MISSING, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_UNREADABLE, EXIT_NOT_FOUND, EXIT_NOT_JOB, EXIT_REMOTE_DIR_MISSING, @@ -56,6 +74,7 @@ PROBE_SESSIONS_MARKER, PROBE_USER_PREFIX, RESERVED_ENV_VARS, + build_clean_list_command, build_ls_command, ) from labremote.gpu import GpuState @@ -1345,8 +1364,8 @@ # 名前(SPEC_01「全体像」「環境変数」・SPEC_03「サブコマンド」) # --------------------------------------------------------------------------- -# 今のステップで動くサブコマンド(clean は後のステップで足す) -SUBCOMMANDS = ["gpus", "status", "push", "run", "logs", "kill", "pull", "ls"] +# 今のステップで動くサブコマンド(clean は判定と --dry-run まで.--logs は 2-4 で足す) +SUBCOMMANDS = ["gpus", "status", "push", "run", "logs", "kill", "pull", "ls", "clean"] # SPEC_03「サブコマンド」に書かれた全部 SPEC_SUBCOMMANDS = {*SUBCOMMANDS, "ls", "clean"} @@ -2976,3 +2995,644 @@ def test_ls_help_has_server_option(self, capsys: pytest.CaptureFixture[str]) -> None: out = _help_text(["ls", "--help"], capsys) assert "--server" in out + + +# --------------------------------------------------------------------------- +# clean RUN_ID(SPEC_03「clean」の手順 1〜3.削除は 2-3 で入る) +# --------------------------------------------------------------------------- + +# サーバの出力に入れる,表示・ログ・エラーに出てはならない名前 +CLEAN_SECRET = "secretcleanfile_p8" +_DELETE_WORDS = [ + "rm", "rmdir", "unlink", "shred", "mv", "truncate", "tee", "dd", "touch", "cp", "xargs", +] # fmt: skip + + +class _CleanServer: + """1 台のサーバの応答(clean の一覧のコマンドには clean_stdout,probe には probe_stdout).""" + + def __init__( + self, + clean_stdout: bytes, + *, + probe_stdout: bytes | None = None, + rc: int = 0, + probe_rc: int = 0, + ) -> None: + self.clean_stdout = clean_stdout + self.probe_stdout = _probe_with_sessions([]) if probe_stdout is None else probe_stdout + self.rc = rc + self.probe_rc = probe_rc + + def __call__(self, argv: list[str]) -> cli._SshResult: + if CLEAN_BEGIN_MARKER in argv[-1]: + return cli._SshResult(self.rc, self.clean_stdout if self.rc == 0 else b"", b"") + return cli._SshResult(self.probe_rc, self.probe_stdout, b"") + + +_MISSING = clean_state_output(CLEAN_STATE_MISSING) + + +def _clean_fake( + monkeypatch: pytest.MonkeyPatch, + newton: bytes | _CleanServer, + archimedes: bytes | _CleanServer = _MISSING, +) -> FakeSsh: + servers = { + NEWTON_ADDR: newton if isinstance(newton, _CleanServer) else _CleanServer(newton), + ARCHIMEDES_ADDR: ( + archimedes if isinstance(archimedes, _CleanServer) else _CleanServer(archimedes) + ), + } + fake = _TimeoutSpy(servers) # type: ignore[arg-type] + monkeypatch.setattr(cli, "_run_ssh", fake) + return fake + + +@pytest.fixture +def clean_project(project: Path) -> Path: + """discard を含む設定(tests/clean_helpers.py の CLEAN_RESULTS_YAML)のプロジェクト.""" + _use_config(project, CLEAN_RESULTS_YAML) + return project + + +def _local_run(project: Path) -> Path: + return project / "runs" / CLEAN_RUN_ID + + +def _put_local(project: Path, rel: str, data: bytes) -> Path: + path = _local_run(project) / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path + + +def _spy_judgement(monkeypatch: pytest.MonkeyPatch) -> list: + judged: list = [] + original = cli.classify_clean + + def spy(*args, **kwargs): + result = original(*args, **kwargs) + judged.append(result) + return result + + monkeypatch.setattr(cli, "classify_clean", spy) + return judged + + +def _categories(judgement) -> dict[str, CleanCategory]: + return {e.file.rel_path: e.category for e in judgement.entries} + + +def _assert_no_delete_commands(fake: FakeSsh) -> None: + """サーバへ送ったのは,一覧のコマンドと probe だけで,どれにも消すコマンドが無い.""" + expected = build_clean_list_command( + "~/work/DemoProject", results_dir="runs", run_id=CLEAN_RUN_ID + ) + assert fake.calls + for argv in fake.calls: + command = argv[-1] + if CLEAN_BEGIN_MARKER in command: + assert command == expected + else: + assert PROBE_END_MARKER in command + for word in _DELETE_WORDS: + assert not re.search(rf"(^|[\s;(|&'\"]){word}(\s|$)", command), word + assert "-delete" not in command + # 書き込むリダイレクトは /dev/null へのものだけ(一覧のコマンドは 2>/dev/null だけ) + assert ">" not in re.sub(r"[12]?>\s*/dev/null|2>&1", "", command) + if CLEAN_BEGIN_MARKER in command: + assert ">" not in command.replace("2>/dev/null", "") + + +# 手元と一致する 3 件と,捨ててよい 2 件 +_MATCHED = {"metrics.json": b"{}", "sub/a b.txt": b"hello", "figures/loss.png": b"png" * 100} + + +def _matched_output(extra: list | None = None) -> bytes: + entries = [file_record(rel, data) for rel, data in _MATCHED.items()] + entries += [file_record("cache.bin", b"c" * 10), file_record("debug/x.png", b"d")] + return clean_output(entries + (extra or [])) + + +def _put_matched(project: Path) -> None: + for rel, data in _MATCHED.items(): + _put_local(project, rel, data) + + +class TestClean: + def test_all_explained_with_dry_run_is_zero( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + ) -> None: + _put_matched(clean_project) + fake = _clean_fake(monkeypatch, _matched_output()) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0 + (judgement,) = judged + assert judgement.deletable + assert judgement.matched.count == 3 and judgement.discardable.count == 2 + out = capsys.readouterr().out + assert "消せる" in out and "[Newton]" in out + _assert_no_delete_commands(fake) + + def test_all_explained_without_dry_run_is_error_not_implemented( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + ) -> None: + """SPEC_03「clean」(実装の状況): 削除はまだ無いので,示して 0 以外で終わる.""" + caplog.set_level(logging.DEBUG) + _put_matched(clean_project) + before = sorted(p.relative_to(clean_project).as_posix() for p in clean_project.rglob("*")) + fake = _clean_fake(monkeypatch, _matched_output()) + assert cli.main(["clean", CLEAN_RUN_ID]) != 0 + assert "まだ実装していない" in _all_output(capsys, caplog) + _assert_no_delete_commands(fake) + after = sorted(p.relative_to(clean_project).as_posix() for p in clean_project.rglob("*")) + assert after == before + + @pytest.mark.parametrize("dry_run", [False, True]) + @pytest.mark.parametrize( + "extra", + [ + file_record("extra.txt", b"e"), + other_record("link"), + file_record("checkpoints/best.pth", b"w"), + raw_file_record("1", sha(b"x"), f"./{CLEAN_RUN_ID}/../outside.txt"), + ], + ids=["not_local", "link", "checkpoint", "unsafe"], + ) + def test_unexplained_is_error_with_and_without_dry_run( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + dry_run: bool, + extra: bytes, + ) -> None: + """SPEC_03「clean」の手順 3: 説明がつかないものがあれば 0 以外(--dry-run でも).""" + _put_matched(clean_project) + fake = _clean_fake(monkeypatch, _matched_output([extra])) + args = ["clean", CLEAN_RUN_ID] + (["--dry-run"] if dry_run else []) + assert cli.main(args) != 0 + out = capsys.readouterr().out + assert "消せない" in out + assert "結論: 消せる" not in out + _assert_no_delete_commands(fake) + + def test_discard_checkpoints_flag( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _put_matched(clean_project) + output = _matched_output([file_record("checkpoints/sub/e1.pth", b"w")]) + _clean_fake(monkeypatch, output) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + _clean_fake(monkeypatch, output) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run", "--discard-checkpoints"]) == 0 + + def test_empty_run_dir_is_deletable( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _clean_fake(monkeypatch, clean_output([])) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0 + + def test_sends_only_list_command_built_from_config( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _put_matched(clean_project) + fake = _clean_fake(monkeypatch, _matched_output()) + cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"]) + lists = [argv for argv in fake.calls if CLEAN_BEGIN_MARKER in argv[-1]] + assert [argv[-2] for argv in lists] == ["Newton"] + _assert_no_delete_commands(fake) + + def test_waits_600_seconds_longer( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SPEC_03「clean」: 他のサブコマンドより 600 秒長く応答を待つ.""" + fake = _clean_fake(monkeypatch, clean_output([])) + cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"]) + list_timeouts = [ + t for argv, t in zip(fake.calls, fake.timeouts, strict=True) + if CLEAN_BEGIN_MARKER in argv[-1] + ] # fmt: skip + missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"") + other = _TimeoutSpy({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing}) + monkeypatch.setattr(cli, "_run_ssh", other) + cli.main(["logs", "train1"]) + assert list_timeouts == [other.timeouts[0] + 600] + + # --- 手元の照合(tmp_path の実際のファイル) --- + + @pytest.mark.parametrize( + ("local", "expected"), + [ + (b"same content", CleanCategory.MATCHED), + (b"SAME CONTENT", CleanCategory.UNEXPLAINED), # 内容が違う(大きさは同じ) + (b"same content!", CleanCategory.UNEXPLAINED), # 大きさが違う + (b"", CleanCategory.UNEXPLAINED), + (None, CleanCategory.UNEXPLAINED), # 手元に無い + ("dir", CleanCategory.UNEXPLAINED), # 手元の側がフォルダ + ], + ids=["same", "content_differs", "size_differs", "empty", "missing", "folder"], + ) + @pytest.mark.parametrize("rel", ["result.txt", "deep/er/result.txt"]) + def test_local_comparison( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + local: bytes | str | None, + expected: CleanCategory, + rel: str, + ) -> None: + _local_run(clean_project).mkdir(parents=True) + if isinstance(local, bytes): + _put_local(clean_project, rel, local) + elif local == "dir": + (_local_run(clean_project) / rel).mkdir(parents=True) + _put_local(clean_project, f"{rel}/inner", b"same content") + _clean_fake(monkeypatch, clean_output([file_record(rel, b"same content")])) + judged = _spy_judgement(monkeypatch) + rc = cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) + assert _categories(judged[0]) == {rel: expected} + assert (rc == 0) == (expected is CleanCategory.MATCHED) + + @pytest.mark.parametrize( + ("server_rel", "local_rel"), + [ + ("Config.yaml", "config.yaml"), + ("config.yaml", "Config.yaml"), + ("RESULT.TXT", "result.txt"), + ("Sub/a.txt", "sub/a.txt"), + ("sub/Deep/a.txt", "sub/deep/a.txt"), + ("sub/a.TXT", "sub/a.txt"), + ], + ) + def test_case_of_local_name_must_match( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + server_rel: str, + local_rel: str, + ) -> None: + """SPEC_03「clean」: 手元の名前は,大文字と小文字まで同じものだけ(Windows でも).""" + _put_local(clean_project, local_rel, b"v") + _clean_fake(monkeypatch, clean_output([file_record(server_rel, b"v")])) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert _categories(judged[0]) == {server_rel: CleanCategory.UNEXPLAINED} + + def test_case_of_local_run_dir_must_match( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """手元の実験フォルダの名前の大文字小文字が違うときも,一致としない.""" + other = clean_project / "runs" / CLEAN_RUN_ID.upper() + other.mkdir(parents=True) + (other / "a.txt").write_bytes(b"v") + _clean_fake(monkeypatch, clean_output([file_record("a.txt", b"v")])) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert _categories(judged[0]) == {"a.txt": CleanCategory.UNEXPLAINED} + + def test_two_server_names_differing_in_case_match_only_once( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """サーバの A.csv と a.csv を,手元の 1 つのファイルで両方一致にしない.""" + _put_local(clean_project, "a.csv", b"v") + output = clean_output([file_record("A.csv", b"v"), file_record("a.csv", b"v")]) + _clean_fake(monkeypatch, output) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert judged[0].matched.count == 1 + assert _categories(judged[0]) == { + "A.csv": CleanCategory.UNEXPLAINED, + "a.csv": CleanCategory.MATCHED, + } + + def test_windows_short_name_is_not_matched( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Windows の短い名前(8.3)でファイルを開けても,実際の名前でなければ一致としない.""" + if sys.platform != "win32": + pytest.skip("短い名前は Windows だけ") + import ctypes + + path = _put_local(clean_project, "averylongfilename_example.txt", b"v") + buffer = ctypes.create_unicode_buffer(1024) + length = ctypes.windll.kernel32.GetShortPathNameW(str(path), buffer, 1024) + short = Path(buffer.value).name if length else "" + if not short or short == path.name: + pytest.skip("この環境では短い名前が作られない") + _clean_fake(monkeypatch, clean_output([file_record(short, b"v")])) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert _categories(judged[0]) == {short: CleanCategory.UNEXPLAINED} + + def test_local_file_link_is_not_matched( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + target = tmp_path / "elsewhere.txt" + target.write_bytes(b"v") + _local_run(clean_project).mkdir(parents=True) + _symlink_or_skip(_local_run(clean_project) / "a.txt", target) + _clean_fake(monkeypatch, clean_output([file_record("a.txt", b"v")])) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert _categories(judged[0]) == {"a.txt": CleanCategory.UNEXPLAINED} + + @pytest.mark.parametrize("kind", ["symlink", "junction"]) + @pytest.mark.parametrize("where", ["middle", "run_dir"]) + def test_local_folder_link_is_not_matched( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + junction_or_skip: Callable[[Path, Path], None], + kind: str, + where: str, + ) -> None: + """SPEC_03「clean」: 途中のフォルダ・手元の実験フォルダがリンク等なら一致としない.""" + target = tmp_path / "elsewhere" + (target / "sub").mkdir(parents=True) + (target / "sub" / "a.txt").write_bytes(b"v") + (target / "a.txt").write_bytes(b"v") + if where == "middle": + _local_run(clean_project).mkdir(parents=True) + link, rel = _local_run(clean_project) / "sub", "sub/a.txt" + target = target / "sub" + else: + (clean_project / "runs").mkdir(parents=True) + link, rel = _local_run(clean_project), "a.txt" + if kind == "symlink": + _symlink_or_skip(link, target) + else: + junction_or_skip(link, target) + _clean_fake(monkeypatch, clean_output([file_record(rel, b"v")])) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert _categories(judged[0]) == {rel: CleanCategory.UNEXPLAINED} + + def test_server_paths_never_open_files_outside_local_run_dir( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """サーバから来た相対パスで,手元の実験フォルダの外のファイルを開かない・一致にしない.""" + data = b"outside content" + (clean_project / "runs").mkdir(parents=True) + (clean_project / "runs" / "outside.txt").write_bytes(data) + (clean_project / "top.txt").write_bytes(data) + absolute = tmp_path / "abs.txt" + absolute.write_bytes(data) + _put_local(clean_project, "ok.txt", data) + prefix = f"./{CLEAN_RUN_ID}/" + size, digest = str(len(data)), sha(data) + bad = [ + "../outside.txt", + "../../top.txt", + "sub/../../outside.txt", + "./../outside.txt", + "..\\outside.txt", + "..\\..\\top.txt", + absolute.as_posix(), + "/" + absolute.as_posix().lstrip("/"), + str(absolute), + "C:" + "../outside.txt", + "ok.txt/", + "ok.txt.", + "ok.txt ", + "ok.txt:stream", + ] + # Linux では,絶対パスの 3 つの書き方が同じ文字列になる.同じ相対パスが 2 回出る出力は + # 解析が拒否するので(別のテストで確かめている),重なりを除いてから並べる + bad = list(dict.fromkeys(bad)) + entries = [raw_file_record(size, digest, prefix + rel) for rel in bad] + _clean_fake(monkeypatch, clean_output(entries)) + opened: list[Path] = [] + original = cli._hash_local_file + + def spy(path: Path, info): + opened.append(Path(path)) + return original(path, info) + + monkeypatch.setattr(cli, "_hash_local_file", spy) + judged = _spy_judgement(monkeypatch) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert judged[0].matched.count == 0 + assert judged[0].unexplained.count == len(bad) + run_dir = _local_run(clean_project).resolve() + for path in opened: + assert path.resolve().is_relative_to(run_dir) + + # --- 実験 ID・サーバの探し方 --- + + @pytest.mark.parametrize( + "run_id", + ["", "..", "a/b", "-rf", "a;b", "$(x)", f"{CLEAN_RUN_ID}\n", "x.", "nul", "_x", "a b"], + ) + def test_bad_run_id_is_error_without_connecting( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str + ) -> None: + """SPEC_03「clean」: 不正な RUN_ID は,サーバに接続せずにエラー. + + `-` で始まるものは `--` の後に置く(置かなければ argparse のエラーになる). + """ + fake = _clean_fake(monkeypatch, clean_output([])) + try: + rc = cli.main(["clean", "--dry-run", "--", run_id]) + except SystemExit as exc: + rc = exc.code + assert rc not in (0, None) + assert fake.calls == [] + + def test_found_on_one_server( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + ) -> None: + _clean_fake(monkeypatch, _MISSING, clean_output([])) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0 + out = capsys.readouterr().out + assert "[Archimedes]" in out and "[Newton]" not in out + + def test_found_on_two_servers_is_error( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _clean_fake(monkeypatch, clean_output([]), clean_output([])) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + + def test_found_nowhere_is_error( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _clean_fake(monkeypatch, _MISSING, _MISSING) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + + @pytest.mark.parametrize("rc", [255, cli._TIMEOUT_RC]) + def test_unreachable_server_warns_and_continues( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + rc: int, + ) -> None: + caplog.set_level(logging.DEBUG) + _clean_fake(monkeypatch, _CleanServer(b"", rc=rc), clean_output([])) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert any("Newton" in w for w in warnings) + + def test_all_unreachable_is_error( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + _clean_fake(monkeypatch, _CleanServer(b"", rc=255), _CleanServer(b"", rc=255)) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + + @pytest.mark.parametrize( + "bad", + [ + b"", + b"garbage\n", + clean_output([])[:-10], + clean_output([], find_rc=1), + clean_output([], after=CLEAN_STATE_LINK), + clean_output([nohash_record("x")]), + clean_state_output(CLEAN_STATE_LINK), + clean_state_output(CLEAN_STATE_NOT_DIR), + clean_state_output(CLEAN_STATE_UNREADABLE), + clean_output([]) + clean_output([]), + ], + ids=[ + "empty", "garbage", "truncated", "find_failed", "after_link", "nohash", "link", + "notdir", "unreadable", "twice", + ], + ) # fmt: skip + @pytest.mark.parametrize("bad_on", ["Newton", "Archimedes"]) + def test_bad_server_stops_even_if_other_has_it( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + bad: bytes, + bad_on: str, + ) -> None: + """SPEC_03「clean」: 解釈できない・リンク等のサーバが 1 台でもあれば止まる.""" + caplog.set_level(logging.DEBUG) + good = clean_output([]) + newton, archimedes = (bad, good) if bad_on == "Newton" else (good, bad) + judged = _spy_judgement(monkeypatch) + _clean_fake(monkeypatch, newton, archimedes) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) != 0 + assert judged == [] + output = _all_output(capsys, caplog) + assert "消せる" not in output + assert bad_on in output + + @pytest.mark.parametrize( + "bad", + [b"", clean_output([])[:-10], clean_state_output(CLEAN_STATE_LINK)], + ids=["empty", "truncated", "link"], + ) + def test_bad_output_with_server_option_is_error( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + bad: bytes, + ) -> None: + _clean_fake(monkeypatch, bad) + assert cli.main(["clean", CLEAN_RUN_ID, "--server", "Newton", "--dry-run"]) != 0 + assert "消せる" not in capsys.readouterr().out + + def test_running_job_warns( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + """SPEC_03「clean」: そのサーバでジョブが実行中なら,警告を出す.""" + caplog.set_level(logging.DEBUG) + server = _CleanServer(clean_output([]), probe_stdout=_probe_with_sessions(["job train1"])) + _clean_fake(monkeypatch, server) + cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert any("実行中" in w and "Newton" in w for w in warnings) + + def test_no_running_job_no_warning( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + ) -> None: + caplog.set_level(logging.DEBUG) + _clean_fake(monkeypatch, clean_output([])) + assert cli.main(["clean", CLEAN_RUN_ID, "--dry-run"]) == 0 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert not any("実行中" in w for w in warnings) + + # --- 名前を出さない --- + + @pytest.mark.parametrize( + "entries", + [ + [file_record(f"{CLEAN_SECRET}.txt", b"v")], # 一致 + [file_record(f"{CLEAN_SECRET}_x.txt", b"v")], # 手元に無い + [other_record(f"{CLEAN_SECRET}_link")], + [file_record(f"{CLEAN_SECRET}/../e", b"v")], + [file_record(f"checkpoints/{CLEAN_SECRET}", b"v")], + [file_record(f"{CLEAN_SECRET}.txt"), file_record(f"{CLEAN_SECRET}.txt")], # 解釈不可 + [nohash_record(CLEAN_SECRET)], + [raw_file_record("x", "y", f"./{CLEAN_RUN_ID}/{CLEAN_SECRET}")], + [raw_file_record("1", sha(b"x"), f"./other/{CLEAN_SECRET}")], + ], + ids=[ + "matched", "unexplained", "link", "unsafe", "checkpoint", "duplicate", "nohash", + "malformed", "outside", + ], + ) # fmt: skip + @pytest.mark.parametrize("dry_run", [False, True]) + def test_server_names_never_appear( + self, + clean_project: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + entries: list, + dry_run: bool, + ) -> None: + """SPEC_03「clean」: 相対パス・ファイル名は,表示・ログ・エラーのどこにも出さない.""" + caplog.set_level(logging.DEBUG) + _put_local(clean_project, f"{CLEAN_SECRET}.txt", b"v") + _clean_fake(monkeypatch, clean_output(entries)) + cli.main(["clean", CLEAN_RUN_ID] + (["--dry-run"] if dry_run else [])) + output = _all_output(capsys, caplog) + assert CLEAN_SECRET not in output + assert "secretclean" not in output + + # --- 引数 --- + + def test_logs_option_does_not_exist_yet( + self, clean_project: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """clean --logs は 2-4 で入る.今は argparse のエラー(何も接続しない).""" + fake = _clean_fake(monkeypatch, clean_output([])) + for args in (["clean", "--logs"], ["clean", "--logs", "train1"]): + with pytest.raises(SystemExit) as excinfo: + cli.main(args) + assert excinfo.value.code == 2 + assert fake.calls == [] + + def test_run_id_is_required(self, clean_project: Path) -> None: + with pytest.raises(SystemExit) as excinfo: + cli.main(["clean"]) + assert excinfo.value.code == 2 + + def test_help_has_options(self, capsys: pytest.CaptureFixture[str]) -> None: + out = _help_text(["clean", "--help"], capsys) + for option in ["--server", "--discard-checkpoints", "--dry-run"]: + assert option in out + assert "--logs" not in out diff --git a/tests/test_commands.py b/tests/test_commands.py index 470187a..fd8fe9b 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -11,6 +11,7 @@ from __future__ import annotations +import hashlib import os import re import shlex @@ -24,8 +25,19 @@ from link_helpers import LinkFactory import labremote.commands as commands_module -from labremote.cleanup import RemoteListing, RunDirEntry, parse_ls_output +from labremote.cleanup import ( + RemoteListing, + RemoteRunListing, + RunDirEntry, + parse_clean_output, + parse_ls_output, +) from labremote.commands import ( + CLEAN_STATE_LINK, + CLEAN_STATE_MISSING, + CLEAN_STATE_NOT_DIR, + CLEAN_STATE_PRESENT, + CLEAN_STATE_UNREADABLE, EXIT_NO_SESSION, EXIT_NOT_JOB, EXIT_REMOTE_DIR_MISSING, @@ -34,6 +46,7 @@ PROBE_END_MARKER, PROBE_SESSIONS_MARKER, PROBE_USER_PREFIX, + build_clean_list_command, build_job_env, build_job_script, build_kill_command, @@ -1902,3 +1915,492 @@ links.symlink(ls_sandbox.remote / "runs" / "_remote_logs", target, is_dir=True) with pytest.raises(ValueError): ls_sandbox.run() + + +# --------------------------------------------------------------------------- +# clean: 実験フォルダのファイルの一覧と大きさ・ハッシュ(SPEC_03「clean」の手順 1) +# --------------------------------------------------------------------------- + +CLEAN_RUN = "20261119-120000_demo_abc1234" + +BAD_CLEAN_RUN_IDS = [ + "", + "..", + ".", + "a/b", + "../x", + "-rf", + "a;b", + "$(x)", + "`x`", + "a b", + f"{CLEAN_RUN}\n", + "\nx", + "x.", + "x..y", + "nul", + "CON", + "con.txt", + "COM1", + "a\x00b", + "a\\b", + "_remote_logs", + "x" * 201, +] + + +def _cd_dash_targets(command: str) -> list[str]: + """シェルが解釈した後の,`cd -- <引数>` の引数(1 語)の一覧.""" + words = shlex.split(command) + return [words[i + 2] for i, w in enumerate(words[:-2]) if w == "cd" and words[i + 1] == "--"] + + +class TestBuildCleanListCommandString: + @pytest.mark.parametrize("run_id", BAD_CLEAN_RUN_IDS) + def test_bad_run_id_is_rejected_before_building(self, run_id: str) -> None: + """SPEC_03「clean」: 埋め込むのは検証済みの RUN_ID だけ(組み立ての前に ValueError).""" + with pytest.raises(ValueError): + build_clean_list_command("~/work/proj", results_dir="runs", run_id=run_id) + + @pytest.mark.parametrize( + "remote_dir", + ["~/work/proj", "/srv/a b/proj", "/srv/x;y $(id)/p", "/srv/it's/p", "/srv/`id`|&/p"], + ) + def test_remote_dir_is_quoted_as_one_word(self, remote_dir: str) -> None: + command = build_clean_list_command(remote_dir, results_dir="runs", run_id=CLEAN_RUN) + assert remote_dir.replace("~", "$HOME", 1) in _cd_dash_targets(command) + + @pytest.mark.parametrize("results_dir", ["my res/out", "a;b $(id)", "x'y/`id`", "o|p&q"]) + def test_results_dir_is_quoted_as_one_word(self, results_dir: str) -> None: + command = build_clean_list_command("~/w/p", results_dir=results_dir, run_id=CLEAN_RUN) + assert f"./{results_dir}" in _cd_dash_targets(command) + + @pytest.mark.parametrize( + "results_dir", + ["", "~", "~/x", "/x", "../x", "a/../b", "a//b", "a/", "./a", "a\\b", "a\x00b", ".."], + ) + def test_results_dir_outside_remote_dir_is_rejected(self, results_dir: str) -> None: + with pytest.raises(ValueError): + build_clean_list_command("~/w/p", results_dir=results_dir, run_id=CLEAN_RUN) + + @pytest.mark.parametrize("run_id", [CLEAN_RUN, "r1", "A.b_c-d"]) + def test_run_id_is_one_word_under_results_dir(self, run_id: str) -> None: + command = build_clean_list_command("~/w/p", results_dir="runs", run_id=run_id) + words = shlex.split(command) + assert f"./{run_id}" in words + # find の起点は実験フォルダだけ + starts = [words[i + 1] for i, w in enumerate(words) if w == "find"] + assert starts == [f"./{run_id}"] + + @pytest.mark.parametrize("results_dir", ["runs", "output/runs"]) + @pytest.mark.parametrize("remote_dir", ["~/work/proj", "/srv/a b/proj"]) + def test_does_not_delete_or_write(self, remote_dir: str, results_dir: str) -> None: + """SPEC_03「clean」: 判定の段階では,一覧とハッシュの取得だけ.書き込み・削除をしない.""" + command = build_clean_list_command(remote_dir, results_dir=results_dir, run_id=CLEAN_RUN) + forbidden_words = [ + "rm", "rmdir", "mv", "cp", "touch", "truncate", "tee", "dd", "ln", "mkdir", + "chmod", "chown", "install", "unlink", "shred", "eval", "source", "xargs", "tar", + ] # fmt: skip + for word in forbidden_words: + assert not re.search(rf"(^|[\s;(|&'\"]){word}(\s|$)", command), word + for option in ["-delete", "-execdir", "-ok", "-okdir", "-fprint", "-fls", "-fprintf"]: + assert option not in command + # 書き込むリダイレクトは,標準エラーを捨てる 2>/dev/null だけ + assert ">" not in command.replace("2>/dev/null", "") + + def test_find_does_not_follow_links(self) -> None: + command = build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN) + assert "-follow" not in command + assert not re.search(r"\bfind\s+-[LH]\b", command) + assert not re.search(r"\b(stat|sha256sum)\s+-L\b", command) + assert "--dereference" not in command + + def test_hash_is_read_from_stdin_not_from_name(self) -> None: + """名前を sha256sum の引数にしない(出力の形が名前で変わるため).""" + command = build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN) + assert re.search(r"sha256sum\s*<", command) + assert not re.search(r"sha256sum\s+[^<\s]", command) + + @pytest.mark.parametrize( + "build", + [ + lambda: build_clean_list_command("~/w/p", results_dir="runs", run_id=CLEAN_RUN), + lambda: build_ls_command("~/w/p", results_dir="runs"), + ], + ids=["clean", "ls"], + ) + def test_unsets_cdpath_before_cd(self, build: Callable[[], str]) -> None: + """SPEC_03「clean」: 相対の cd が別の場所へ行かないよう,CDPATH を外してから動かす.""" + command = build() + assert "unset CDPATH" in command + assert command.index("unset CDPATH") < command.index("cd ") + + +class _CleanSandbox: + """`tmp_path` の中の偽のサーバのフォルダで,clean の一覧のコマンドを bash で実際に動かす.""" + + def __init__(self, tmp_path: Path) -> None: + tmp_path.mkdir(parents=True, exist_ok=True) + self.bash = _bash_or_skip(tmp_path) + self.root = tmp_path + self.outside = tmp_path / "outside" + self.outside.mkdir() + self.remote = tmp_path / "srv" / "proj" + self.last_stdout = b"" + + def run_dir(self, run_id: str = CLEAN_RUN, results_dir: str = "runs") -> Path: + return self.remote / results_dir / run_id + + def write(self, rel: str, data: bytes = b"x", *, base: Path | None = None) -> Path: + path = (base or self.run_dir()) / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path + + def run_raw( + self, + run_id: str = CLEAN_RUN, + *, + remote: str | None = None, + results_dir: str = "runs", + env: dict[str, str] | None = None, + ) -> bytes: + remote_dir = self.remote.as_posix() if remote is None else remote + command = build_clean_list_command(remote_dir, results_dir=results_dir, run_id=run_id) + result = subprocess.run( + [self.bash, "-c", command], + cwd=self.root, + capture_output=True, + # FIFO 等で止まったときに,pytest の制限時間に頼らずに失敗させる + timeout=60, + check=False, + env={**os.environ, **(env or {})}, + ) + # 実験フォルダが無くても 0 で終わる(状態は出力で区別する) + assert result.returncode == 0, result.stderr + self.last_stdout = result.stdout + return result.stdout + + def run(self, run_id: str = CLEAN_RUN, **kwargs: object) -> RemoteRunListing: + return parse_clean_output(self.run_raw(run_id, **kwargs), run_id) # type: ignore[arg-type] + + +@pytest.fixture +def clean_sandbox(tmp_path: Path) -> _CleanSandbox: + return _CleanSandbox(tmp_path) + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _files_of(listing: RemoteRunListing) -> dict[str, tuple[bool, int, str]]: + return {f.rel_path: (f.regular, f.size_bytes, f.sha256) for f in listing.files} + + +class TestCleanListCommandInShell: + def test_lists_nested_files_with_size_and_hash(self, clean_sandbox: _CleanSandbox) -> None: + """SPEC_03「clean」の手順 1: 全ファイルの相対パス・大きさ・SHA-256(入れ子の中も).""" + contents = { + "empty.bin": b"", + "one.txt": b"a", + "sub/two.txt": b"bc", + "sub/deep/er/big.bin": bytes(range(256)) * (3 * 4096 + 7), + ".hidden": b"h", + } + for rel, data in contents.items(): + clean_sandbox.write(rel, data) + listing = clean_sandbox.run() + assert listing.state == CLEAN_STATE_PRESENT + assert _files_of(listing) == { + rel: (True, len(data), _sha(data)) for rel, data in contents.items() + } + + def test_empty_run_dir_and_only_empty_dirs(self, clean_sandbox: _CleanSandbox) -> None: + """SPEC_03「clean」: フォルダは判定の対象にしない(空のフォルダだけなら 0 件).""" + clean_sandbox.run_dir().mkdir(parents=True) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_PRESENT, ()) + (clean_sandbox.run_dir() / "a" / "b").mkdir(parents=True) + (clean_sandbox.run_dir() / "c").mkdir() + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_PRESENT, ()) + + def test_nasty_names_are_listed_one_by_one_and_nothing_is_created( + self, clean_sandbox: _CleanSandbox + ) -> None: + names = [ + "a b.txt", + " lead and trail x", + "it's.txt", + "$(touch PWNED).txt", + "`touch PWNED2`", + "a;b.txt", + "a&&touch PWNED3", + "-rf", + "-dash.txt", + "--help", + ] + if sys.platform != "win32": + names += ['q"d.txt', "star*.txt", "nl\nname.txt", "back\\slash.txt", "x\ty", "?"] + contents = {} + for i, name in enumerate(names): + contents[name] = f"content {i}".encode() + contents[f"nested dir/{name}"] = f"nested {i}".encode() * 3 + for rel, data in contents.items(): + clean_sandbox.write(rel, data) + before = _snapshot(clean_sandbox.root) + listing = clean_sandbox.run() + assert _files_of(listing) == { + rel: (True, len(data), _sha(data)) for rel, data in contents.items() + } + # 名前の中のコマンドが実行されていない(cwd を含め,どこにも何も作られていない) + assert not [p for p in clean_sandbox.root.rglob("PWNED*") if p.name.startswith("PWNED")] + assert _snapshot(clean_sandbox.root) == before + + def test_not_utf8_name_is_listed(self, clean_sandbox: _CleanSandbox) -> None: + if sys.platform == "win32": + pytest.skip("Windows では UTF-8 として読めない名前を作れない") + run_dir = clean_sandbox.run_dir() + run_dir.mkdir(parents=True) + bad = os.path.join(os.fsencode(run_dir), b"bad\xff.bin") + with open(bad, "wb") as handle: + handle.write(b"q") + (found,) = clean_sandbox.run().files + assert found.regular and found.sha256 == _sha(b"q") + assert found.rel_path == os.fsdecode(b"bad\xff.bin") + + def test_run_id_prefix_of_other_run_lists_only_its_own( + self, clean_sandbox: _CleanSandbox + ) -> None: + """RUN_ID が別の実験フォルダの名前の前半と同じでも,その実験フォルダの下だけ.""" + clean_sandbox.write("a.txt", b"1", base=clean_sandbox.run_dir("r1")) + clean_sandbox.write("b.txt", b"2", base=clean_sandbox.run_dir("r10")) + clean_sandbox.write("c.txt", b"3", base=clean_sandbox.run_dir("r1x")) + if sys.platform != "win32": # Windows では大文字小文字だけが違う名前は同じフォルダ + clean_sandbox.write("d.txt", b"4", base=clean_sandbox.run_dir("R1")) + assert list(_files_of(clean_sandbox.run("r1"))) == ["a.txt"] + assert list(_files_of(clean_sandbox.run("r10"))) == ["b.txt"] + + def test_missing_run_dir(self, clean_sandbox: _CleanSandbox) -> None: + clean_sandbox.write("a.txt", base=clean_sandbox.run_dir("other1")) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING) + + def test_missing_remote_dir(self, clean_sandbox: _CleanSandbox) -> None: + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING) + assert not os.path.lexists(clean_sandbox.remote) + + def test_missing_results_dir(self, clean_sandbox: _CleanSandbox) -> None: + clean_sandbox.remote.mkdir(parents=True) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_MISSING) + assert not os.path.lexists(clean_sandbox.remote / "runs") + + def test_run_dir_that_is_a_file(self, clean_sandbox: _CleanSandbox) -> None: + clean_sandbox.write("", b"file", base=clean_sandbox.run_dir()) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_NOT_DIR) + + @pytest.mark.parametrize("what", ["remote_dir", "results_dir"]) + def test_place_that_is_a_file_is_not_present( + self, clean_sandbox: _CleanSandbox, what: str + ) -> None: + target = clean_sandbox.remote if what == "remote_dir" else clean_sandbox.remote / "runs" + clean_sandbox.write("", b"file", base=target) + assert clean_sandbox.run().state != CLEAN_STATE_PRESENT + + def test_other_results_dir_is_used(self, clean_sandbox: _CleanSandbox) -> None: + clean_sandbox.write("a.txt", b"1") + clean_sandbox.write("b.txt", b"2", base=clean_sandbox.run_dir(results_dir="out/runs")) + listing = clean_sandbox.run(results_dir="out/runs") + assert list(_files_of(listing)) == ["b.txt"] + + @pytest.mark.parametrize("dir_name", ["a b", "x;y $(touch PWNED)", "it's", "`touch PWNED`"]) + def test_remote_dir_with_special_characters( + self, clean_sandbox: _CleanSandbox, dir_name: str + ) -> None: + remote = clean_sandbox.root / "srv" / dir_name + clean_sandbox.write("a.txt", b"1", base=remote / "runs" / CLEAN_RUN) + listing = clean_sandbox.run(remote=remote.as_posix()) + assert list(_files_of(listing)) == ["a.txt"] + assert not list(clean_sandbox.root.rglob("PWNED")) + + def test_remote_dir_under_home(self, clean_sandbox: _CleanSandbox) -> None: + """`~/...` の remote_dir は,サーバの $HOME の下を見る.""" + home = clean_sandbox.root / "home" + clean_sandbox.write("a.txt", b"1", base=home / "work" / "p" / "runs" / CLEAN_RUN) + listing = clean_sandbox.run(remote="~/work/p", env={"HOME": home.as_posix()}) + assert list(_files_of(listing)) == ["a.txt"] + + def test_nothing_changes(self, clean_sandbox: _CleanSandbox) -> None: + """SPEC_03「clean」: 判定では何も消さない・書き込まない(一覧・内容・mtime が同じ).""" + clean_sandbox.write("metrics.json", b"{}") + clean_sandbox.write("sub/x.bin", b"\0\1\2") + clean_sandbox.write("checkpoints/best.pth", b"w" * 5000) + (clean_sandbox.run_dir() / "emptydir").mkdir() + clean_sandbox.write("a.txt", base=clean_sandbox.run_dir("20261120-090000_demo_def5678")) + clean_sandbox.write("_remote_logs/t.log", base=clean_sandbox.remote / "runs") + clean_sandbox.write("src/main.py", base=clean_sandbox.remote) + before = _snapshot(clean_sandbox.root) + clean_sandbox.run() + assert _snapshot(clean_sandbox.root) == before + + @pytest.mark.parametrize("command", ["clean", "ls"]) + def test_cdpath_does_not_redirect_cd(self, clean_sandbox: _CleanSandbox, command: str) -> None: + """SPEC_03「clean」: CDPATH が設定されていても,remote_dir の下の結果の置き場を見る.""" + decoy = clean_sandbox.root / "decoy" + clean_sandbox.write("decoy.txt", b"d", base=decoy / "runs" / CLEAN_RUN) + clean_sandbox.write("real.txt", b"r") + env = {"CDPATH": decoy.as_posix()} + if command == "clean": + listing = clean_sandbox.run(env=env) + assert list(_files_of(listing)) == ["real.txt"] + # 結果の置き場が remote_dir に無いときも,CDPATH の先へ行かない + (clean_sandbox.run_dir() / "real.txt").unlink() + clean_sandbox.run_dir().rmdir() + (clean_sandbox.remote / "runs").rmdir() + assert clean_sandbox.run(env=env) == RemoteRunListing(CLEAN_STATE_MISSING) + else: + ls_command = build_ls_command(clean_sandbox.remote.as_posix(), results_dir="runs") + result = subprocess.run( + [clean_sandbox.bash, "-c", ls_command], + cwd=clean_sandbox.root, + capture_output=True, + timeout=60, + check=False, + env={**os.environ, **env}, + ) + listing = parse_ls_output(result.stdout) + (entry,) = listing.run_dirs + assert entry.file_count == 1 + (clean_sandbox.run_dir() / "real.txt").unlink() + clean_sandbox.run_dir().rmdir() + (clean_sandbox.remote / "runs").rmdir() + result = subprocess.run( + [clean_sandbox.bash, "-c", ls_command], + cwd=clean_sandbox.root, + capture_output=True, + timeout=60, + check=False, + env={**os.environ, **env}, + ) + listing = parse_ls_output(result.stdout) + assert not listing.results_dir_exists and listing.run_dirs == () + + # --- 権限・特殊なファイル(Linux だけ) --- + + def test_unreadable_file_is_nohash_and_rejected(self, clean_sandbox: _CleanSandbox) -> None: + """SPEC_03「clean」: ハッシュを取れなかったファイルが 1 件でもあれば止まる.""" + clean_sandbox.write("ok.txt", b"1") + locked = clean_sandbox.write("locked.txt", b"secret") + locked.chmod(0) + try: + if os.access(locked, os.R_OK): + pytest.skip("この環境では権限で読めないファイルを作れない(Windows・root)") + raw = clean_sandbox.run_raw() + finally: + locked.chmod(0o644) + assert b"nohash ./" + CLEAN_RUN.encode() + b"/locked.txt" in raw + with pytest.raises(ValueError): + parse_clean_output(raw, CLEAN_RUN) + + def test_unreadable_folder_inside_is_rejected(self, clean_sandbox: _CleanSandbox) -> None: + """SPEC_03「clean」: 一覧の取得(find)が失敗した(読めないフォルダがある)なら止まる.""" + clean_sandbox.write("ok.txt", b"1") + locked = clean_sandbox.run_dir() / "locked" + clean_sandbox.write("hidden.txt", base=locked) + locked.chmod(0) + try: + if os.access(locked, os.R_OK | os.X_OK): + pytest.skip("この環境では権限で読めないフォルダを作れない(Windows・root)") + raw = clean_sandbox.run_raw() + finally: + locked.chmod(0o755) + with pytest.raises(ValueError): + parse_clean_output(raw, CLEAN_RUN) + + def test_unreadable_run_dir_is_unreadable(self, clean_sandbox: _CleanSandbox) -> None: + clean_sandbox.write("a.txt") + run_dir = clean_sandbox.run_dir() + run_dir.chmod(0) + try: + if os.access(run_dir, os.R_OK | os.X_OK): + pytest.skip("この環境では権限で読めないフォルダを作れない(Windows・root)") + listing = clean_sandbox.run() + finally: + run_dir.chmod(0o755) + assert listing == RemoteRunListing(CLEAN_STATE_UNREADABLE) + + def test_fifo_is_other_and_not_opened(self, clean_sandbox: _CleanSandbox) -> None: + """FIFO は開かずに「通常のファイル以外」とする(開いて止まらない).""" + if not hasattr(os, "mkfifo"): + pytest.skip("FIFO を作れない環境(Windows)") + clean_sandbox.write("a.txt", b"1") + os.mkfifo(clean_sandbox.run_dir() / "pipe") + listing = clean_sandbox.run() + assert _files_of(listing) == {"a.txt": (True, 1, _sha(b"1")), "pipe": (False, 0, "")} + + # --- リンク(作れない環境では飛ばす.CI の Linux で実行される) --- + + def test_run_dir_that_is_a_link_is_not_entered( + self, clean_sandbox: _CleanSandbox, links: LinkFactory + ) -> None: + """SPEC_03「clean」: 実験フォルダそのものがリンクなら link(中に入らない).""" + target = clean_sandbox.outside / "real" + clean_sandbox.write("a.txt", base=target) + (clean_sandbox.remote / "runs").mkdir(parents=True) + links.symlink(clean_sandbox.run_dir(), target, is_dir=True) + raw = clean_sandbox.run_raw() + assert parse_clean_output(raw, CLEAN_RUN) == RemoteRunListing(CLEAN_STATE_LINK) + assert b"a.txt" not in raw + + def test_run_dir_that_is_a_link_to_a_file( + self, clean_sandbox: _CleanSandbox, links: LinkFactory + ) -> None: + target = clean_sandbox.write("f", b"x", base=clean_sandbox.outside) + (clean_sandbox.remote / "runs").mkdir(parents=True) + links.symlink(clean_sandbox.run_dir(), target, is_dir=False) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_LINK) + + def test_broken_link_as_run_dir_is_link( + self, clean_sandbox: _CleanSandbox, links: LinkFactory + ) -> None: + (clean_sandbox.remote / "runs").mkdir(parents=True) + links.symlink(clean_sandbox.run_dir(), clean_sandbox.outside / "nowhere", is_dir=True) + assert clean_sandbox.run() == RemoteRunListing(CLEAN_STATE_LINK) + + def test_links_inside_are_other_and_not_followed( + self, clean_sandbox: _CleanSandbox, links: LinkFactory + ) -> None: + """SPEC_03「clean」: 中のリンクは,先をたどらずに「通常のファイル以外」として 1 件ずつ.""" + target_file = clean_sandbox.write("t.txt", b"target", base=clean_sandbox.outside) + target_dir = clean_sandbox.outside / "tdir" + clean_sandbox.write("inner1.txt", b"i1", base=target_dir) + clean_sandbox.write("inner2.txt", b"i2", base=target_dir) + clean_sandbox.write("a.txt", b"1") + run_dir = clean_sandbox.run_dir() + links.symlink(run_dir / "file_link", target_file, is_dir=False) + links.symlink(run_dir / "sub" / "dir_link", target_dir, is_dir=True) + links.symlink(run_dir / "broken", clean_sandbox.outside / "nowhere", is_dir=False) + links.symlink(run_dir / "inner_link", run_dir / "a.txt", is_dir=False) + raw = clean_sandbox.run_raw() + listing = parse_clean_output(raw, CLEAN_RUN) + assert _files_of(listing) == { + "a.txt": (True, 1, _sha(b"1")), + "file_link": (False, 0, ""), + "sub/dir_link": (False, 0, ""), + "broken": (False, 0, ""), + "inner_link": (False, 0, ""), + } + assert b"inner1" not in raw and b"inner2" not in raw + assert _sha(b"target").encode() not in raw + + def test_junction_inside_is_not_followed( + self, clean_sandbox: _CleanSandbox, links: LinkFactory + ) -> None: + """Windows のジャンクションも,中に入らない(Windows だけ).""" + target_dir = clean_sandbox.outside / "tdir" + clean_sandbox.write("inner1.txt", b"i1", base=target_dir) + clean_sandbox.write("a.txt", b"1") + links.junction(clean_sandbox.run_dir() / "junc", target_dir) + raw = clean_sandbox.run_raw() + assert b"inner1" not in raw + listing = parse_clean_output(raw, CLEAN_RUN) + assert "a.txt" in _files_of(listing) + assert not any("inner1" in f.rel_path for f in listing.files) diff --git a/tests/test_report.py b/tests/test_report.py index 80aaaa5..e447ba4 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -10,18 +10,30 @@ from __future__ import annotations from collections.abc import Sequence +from hashlib import sha256 import pytest from probe_helpers import PMON_HEADER, gpu_line, probe_text, sample_lines -from labremote.cleanup import JobLogEntry, LsSummary, RemoteListing, RunDirEntry, ServerLeftovers +from labremote.cleanup import ( + CleanJudgement, + JobLogEntry, + LocalFile, + LsSummary, + RemoteFile, + RemoteListing, + RunDirEntry, + ServerLeftovers, + classify_clean, +) from labremote.commands import SSH_FAILURE_RC -from labremote.config import GpuFreeThreshold, ServerConfig +from labremote.config import GpuFreeThreshold, ResultsConfig, ServerConfig from labremote.gpu import GpuSelection, GpuState, ServerProbe, parse_probe_output, select_gpu from labremote.report import ( describe_skipped_links, describe_ssh_failure, describe_target, + format_clean_report, format_forced_warning, format_ls_incomplete_warning, format_ls_report, @@ -585,3 +597,133 @@ def test_unreachable_does_not_make_incomplete_warning(self) -> None: assert format_ls_incomplete_warning(_summary(unreachable=("Newton",))) is None + + +# --------------------------------------------------------------------------- +# clean RUN_ID の表示(SPEC_03「clean」の「表示」) +# --------------------------------------------------------------------------- + +CLEAN_RUN = "20261119-120000_demo_abc1234" +# 表示に出てはならない,サーバから来た名前の目印 +_SECRET = "secretfile_w4" +_CLEAN_PROJECT_WORDS = [*_PROJECT_WORDS, "tsm", "tongueseg", "tias", "resunet"] + + +def _remote(path: str, data: bytes) -> RemoteFile: + return RemoteFile(path, True, len(data), sha256(data).hexdigest()) + + +def _local(data: bytes) -> LocalFile: + return LocalFile(len(data), sha256(data).hexdigest()) + + +def _judgement( + *, unexplained: bool, checkpoints: bool = False, flag: bool = False +) -> CleanJudgement: + files = [ + _remote(f"{_SECRET}_m.txt", b"a" * 1000), + _remote(f"sub_{_SECRET}/x.txt", b"b" * 2000), + _remote("cache.bin", b"c" * 3000), + ] + local = {files[0].rel_path: _local(b"a" * 1000), files[1].rel_path: _local(b"b" * 2000)} + if checkpoints: + files.append(_remote(f"checkpoints/{_SECRET}.pth", b"w" * 5000)) + if unexplained: + files += [ + _remote(f"{_SECRET}_extra.txt", b"e" * 700), + RemoteFile(f"{_SECRET}_link", False), + _remote(f"{_SECRET}/../escape", b"u"), + ] + results = ResultsConfig.model_validate( + { + "checkpoints": {"dir": "checkpoints", "files": []}, + "discard": {"files": ["cache.bin"]}, + } + ) + return classify_clean(files, local, results, discard_checkpoints=flag) + + +def _clean_report(judgement: CleanJudgement) -> str: + return format_clean_report("Newton", CLEAN_RUN, judgement, checkpoints_dir="checkpoints") + + +class TestFormatCleanReport: + def test_deletable_shows_counts_sizes_and_conclusion(self) -> None: + judgement = _judgement(unexplained=False) + out = _clean_report(judgement) + assert "Newton" in out and CLEAN_RUN in out + assert judgement.deletable + lines = out.splitlines() + (matched,) = [line for line in lines if line.strip().startswith("一致")] + assert "2 件" in matched and format_size(3000) in matched + (discard,) = [line for line in lines if line.strip().startswith("捨ててよい")] + assert "1 件" in discard and format_size(3000) in discard + (unexp,) = [line for line in lines if line.strip().startswith("説明がつかない")] + assert "0 件" in unexp + assert "消せる" in out and "消せない" not in out + assert format_size(6000) in lines[0] and "3" in lines[0] + + def test_checkpoints_line_with_flag(self) -> None: + judgement = _judgement(unexplained=False, checkpoints=True, flag=True) + out = _clean_report(judgement) + (weights,) = [line for line in out.splitlines() if line.strip().startswith("重み")] + assert "1 件" in weights and format_size(5000) in weights + assert "消せる" in out + + def test_not_deletable_shows_conclusion_and_next_steps(self) -> None: + judgement = _judgement(unexplained=True) + out = _clean_report(judgement) + assert not judgement.deletable + assert "消せない" in out + assert f"{judgement.unexplained.count} 件" in out + (unexp,) = [line for line in out.splitlines() if line.strip().startswith("説明がつかない")] + assert f"{judgement.unexplained.count} 件" in unexp + # 次に何をすればよいか(回収する・discard に書く・サーバで確かめる) + assert f"labremote pull {CLEAN_RUN}" in out + assert "results.discard" in out + assert "結論: 消せる" not in out + + def test_unexplained_checkpoints_show_both_options(self) -> None: + judgement = _judgement(unexplained=False, checkpoints=True, flag=False) + out = _clean_report(judgement) + assert not judgement.deletable + assert "--with-checkpoints" in out + assert "--discard-checkpoints" in out + + def test_no_checkpoint_hint_without_checkpoints(self) -> None: + out = _clean_report(_judgement(unexplained=True)) + assert "--discard-checkpoints" not in out + + def test_empty_run_dir_is_deletable(self) -> None: + judgement = classify_clean([], {}, ResultsConfig(), discard_checkpoints=False) + out = _clean_report(judgement) + assert "消せる" in out and "消せない" not in out + + @pytest.mark.parametrize( + "kwargs", + [ + {"unexplained": False}, + {"unexplained": True}, + {"unexplained": True, "checkpoints": True}, + {"unexplained": False, "checkpoints": True, "flag": True}, + ], + ) + def test_no_file_names_and_no_project_words(self, kwargs: dict) -> None: + """SPEC_03「clean」: 相対パス・ファイル名は表示に出さない.プロジェクトの言葉も出さない.""" + out = _clean_report(_judgement(**kwargs)) + assert _SECRET not in out + assert "secretfile" not in out + assert "escape" not in out and "cache.bin" not in out + for word in _CLEAN_PROJECT_WORDS: + assert word not in out.lower() + + def test_checkpoints_dir_from_config_is_shown(self) -> None: + judgement = classify_clean( + [_remote("weights/a", b"x")], + {}, + ResultsConfig.model_validate({"checkpoints": {"dir": "weights", "files": []}}), + discard_checkpoints=False, + ) + out = format_clean_report("Newton", CLEAN_RUN, judgement, checkpoints_dir="weights") + assert "weights/" in out + assert "--discard-checkpoints" in out diff --git a/tests/test_whitelist.py b/tests/test_whitelist.py index 1069f5f..77a87c4 100644 --- a/tests/test_whitelist.py +++ b/tests/test_whitelist.py @@ -24,7 +24,9 @@ from labremote.whitelist import ( check_pull_members, has_pull_names, + is_discard_allowed, is_pull_allowed, + is_safe_relative_path, parse_find_listing, plan_pull, validate_run_id, @@ -940,3 +942,184 @@ 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) + + +# --------------------------------------------------------------------------- +# 破棄の判定(SPEC_03「clean」の「捨ててよい」・SPEC_02「`results`」の `discard`) +# --------------------------------------------------------------------------- + +DISCARD_RESULTS_DICT = { + "pull": { + "files": ["config.yaml", "metrics.json"], + "dirs": [{"path": "figures", "suffix": ".png"}], + }, + "checkpoints": {"dir": "checkpoints", "files": ["best.pth"]}, + "discard": { + "files": ["cache.bin", "nohup.out"], + "dirs": [{"path": "debug", "suffix": ".png"}, {"path": "tmp/vis", "suffix": ".jpg"}], + }, +} +DISCARD_RESULTS = ResultsConfig.model_validate(DISCARD_RESULTS_DICT) + +DISCARD_ALLOWED = ["cache.bin", "nohup.out", "debug/a.png", "debug/a b.png", "tmp/vis/x.jpg"] +DISCARD_NOT_ALLOWED = [ + # files は実験フォルダの直下だけ + "sub/cache.bin", + "debug/cache.bin", + "tmp/nohup.out", + # 大文字小文字が違う + "Cache.bin", + "CACHE.BIN", + "cache.Bin", + "NOHUP.OUT", + "Debug/a.png", + "DEBUG/a.png", + "debug/a.PNG", + "debug/a.pnG", + "tmp/VIS/x.jpg", + "Tmp/vis/x.jpg", + "tmp/vis/x.JPG", + # 名前の一部 + "cache.bin.old", + "old.cache.bin", + "cache", + # dirs は path の直下で suffix のものだけ + "debug/sub/a.png", + "debug/a/b/c.png", + "a/debug/x.png", + "tmp/x.jpg", + "vis/x.jpg", + "tmp/vis/sub/x.jpg", + "debug2/a.png", + "debugx/a.png", + "debug/a.jpg", + "debug/apng", + "debug/a.png.bak", + # 拡張子だけの名前・path そのもの + "debug/.png", + "tmp/vis/.jpg", + "debug", + "tmp/vis", + "tmp", + # 回収の一覧・重みの名前 + "config.yaml", + "metrics.json", + "figures/a.png", + "checkpoints/best.pth", + "checkpoints/x.png", + "best.pth", +] +DISCARD_UNSAFE = [ + "", + "/cache.bin", + "./cache.bin", + "../cache.bin", + "x/../cache.bin", + "debug/../cache.bin", + "debug//a.png", + "debug/./a.png", + "debug\\a.png", + "C:cache.bin", + "debug/C:a.png", + "cache.bin.", + "cache.bin ", + "debug /a.png", + "debug/a.png.", + "debug/nul.png", + "debug/CON.png", + "cache.bin\n", + "cache.bin\x00", + "debug/a\x1b.png", + "debug/", + "/", +] + + +class TestIsDiscardAllowed: + @pytest.mark.parametrize("name", DISCARD_ALLOWED) + def test_allowed(self, name: str) -> None: + assert is_discard_allowed(name, DISCARD_RESULTS) + + @pytest.mark.parametrize("name", DISCARD_NOT_ALLOWED) + def test_not_allowed(self, name: str) -> None: + assert not is_discard_allowed(name, DISCARD_RESULTS) + + @pytest.mark.parametrize("name", DISCARD_UNSAFE) + def test_unsafe_paths_are_not_allowed(self, name: str) -> None: + assert not is_discard_allowed(name, DISCARD_RESULTS) + + @pytest.mark.parametrize("name", UNSAFE_PATHS) + def test_pull_unsafe_paths_are_not_allowed(self, name: str) -> None: + assert not is_discard_allowed(name, DISCARD_RESULTS) + + def test_default_results_discard_nothing(self) -> None: + for name in DISCARD_ALLOWED + ALLOWED + CHECKPOINTS: + assert not is_discard_allowed(name, ResultsConfig()) + + @pytest.mark.parametrize("name", [*ALLOWED, *CHECKPOINTS]) + def test_pull_names_are_not_discardable(self, name: str) -> None: + """回収の一覧(RESULTS)に discard が無ければ,回収の名前は捨ててよいにならない.""" + assert not is_discard_allowed(name, RESULTS) + + def test_safe_relative_path_matches_pull_rule(self) -> None: + for name in UNSAFE_PATHS + DISCARD_UNSAFE: + assert not is_safe_relative_path(name) + for name in ALLOWED + DISCARD_ALLOWED: + assert is_safe_relative_path(name) + + +def _with(**sections: object) -> ResultsConfig: + data = {**DISCARD_RESULTS_DICT, **sections} + return ResultsConfig.model_validate(data) + + +# 判定に使う全ての名前 +_ALL_NAMES = sorted( + {*DISCARD_ALLOWED, *DISCARD_NOT_ALLOWED, *ALLOWED, *CHECKPOINTS, "summary.txt", "out/a.svg"} +) + + +class TestPullAndDiscardAreIndependent: + """回収の判定は pull の一覧だけ,破棄の判定は discard の一覧だけを見る.""" + + @pytest.mark.parametrize( + "pull", + [ + {"files": [], "dirs": []}, + {"files": ["summary.txt"], "dirs": [{"path": "out", "suffix": ".svg"}]}, + {"files": ["config.yaml", "metrics.json", "history.csv"], "dirs": []}, + ], + ) + def test_changing_pull_does_not_change_discard(self, pull: dict) -> None: + changed = _with(pull=pull) + for name in _ALL_NAMES: + assert is_discard_allowed(name, changed) == is_discard_allowed(name, DISCARD_RESULTS), ( + name + ) + + @pytest.mark.parametrize( + "discard", + [ + {"files": [], "dirs": []}, + {"files": ["summary.txt"], "dirs": [{"path": "out", "suffix": ".svg"}]}, + {"files": ["history.csv"], "dirs": [{"path": "figures", "suffix": ".jpg"}]}, + ], + ) + @pytest.mark.parametrize("with_checkpoints", [False, True]) + def test_changing_discard_does_not_change_pull( + self, discard: dict, with_checkpoints: bool + ) -> None: + changed = _with(discard=discard) + for name in _ALL_NAMES: + assert is_pull_allowed( + name, changed, with_checkpoints=with_checkpoints + ) == is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=with_checkpoints), name + + def test_discard_names_are_not_pulled(self) -> None: + for name in DISCARD_ALLOWED: + assert not is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=True) + + def test_pull_names_are_not_discarded(self) -> None: + for name in ["config.yaml", "metrics.json", "figures/a.png", "checkpoints/best.pth"]: + assert is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=True) + assert not is_discard_allowed(name, DISCARD_RESULTS)