diff --git a/configs/remote.yaml b/configs/remote.yaml deleted file mode 100644 index eb17b27..0000000 --- a/configs/remote.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# リモート実行ツール tsm-remote のサーバ設定(SPEC_03「サーバ設定」.形は TIASJudgeModel と同じ). -# 学習データのバンドルは各サーバの ~/data/tiasdata/ に事前配置する(ツールはデータを転送しない.ENV_03). -# 接続先は ~/.ssh/config の Host 名(servers の name)で,アドレス・ユーザー名・鍵は手元の -# ~/.ssh/config から決まる(リポジトリに書かない).address・user を書くとそれを使う. -# 環境変数での上書き: -# TSM_REMOTE_JUMP 踏み台(jump_host)を上書き.空文字なら直接接続(研究室 LAN 内) -# TSM_REMOTE_SSH 手元の ssh 実行ファイル -# TSM_REMOTE_ALLOW_SELF 1 でサーバ上実行の検出を無効化 -jump_host: labpc # 踏み台(~/.ssh/config の Host 名).null なら直接接続 -connect_timeout_sec: 15 -gpu_free: - max_memory_used_mib: 1024 # 使用中メモリがこれ未満 - max_utilization_percent: 10 # かつ使用率がこれ未満なら「空き」(いずれも観測中の最大値で判定) - observe_sec: 10 # この秒数だけ観測してから判定する(0 なら瞬間値のみ.0〜120) - sample_interval_ms: 500 # 観測の間隔(100〜5000) -servers: - - name: Newton - priority: 1 # 小さいほど優先 - remote_dir: ~/work/TongueSegModel - uv: ~/.local/bin/uv - data_ready: true # バンドル tongue_segmentation v1 を配置済み(PLAN_02 のステップ 2-2) - - name: Archimedes - priority: 2 - remote_dir: ~/work/TongueSegModel - uv: ~/.local/bin/uv - data_ready: true # 同上 diff --git a/pyproject.toml b/pyproject.toml index 0c8bf79..f41fef8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,7 +20,6 @@ [project.scripts] tsm-train = "tongue_seg_model.cli.train:main" tsm-export = "tongue_seg_model.cli.export:main" -tsm-remote = "tongue_seg_model.cli.remote:main" [dependency-groups] dev = [ diff --git a/src/tongue_seg_model/cli/remote.py b/src/tongue_seg_model/cli/remote.py deleted file mode 100644 index 2f6a485..0000000 --- a/src/tongue_seg_model/cli/remote.py +++ /dev/null @@ -1,1214 +0,0 @@ -"""tsm-remote: 研究室の GPU サーバでの実行を手元から操作する CLI(SPEC_03). - -TIASJudgeModel の `tias-remote`(`tias_judge_model.cli.remote`)の移植. -手元(Windows の PowerShell / Git Bash)から 1 コマンドで以下を行う.サーバは -`configs/remote.yaml` の一覧(Newton・Archimedes 等)で,空いている GPU を自動で選ぶ. - -- gpus : 全サーバの GPU 一覧と,run が選ぶ GPU を表示する -- status : 全サーバの実行中ジョブと GPU の状況を表示する -- push : コードをサーバへ送る(tar over ssh.rsync 不要) -- run : 空き GPU を選び,そのサーバへコードを送って tmux でジョブを起動する -- logs : ジョブのログを表示する(ジョブのあるサーバを自動で探す) -- kill : ジョブを止める(ジョブのあるサーバを自動で探す) -- pull : 実験結果を回収ホワイトリストに従って持ち帰る - -ssh を呼ぶ副作用はこのモジュールに集め,コマンド文字列の組み立て・出力の解析・GPU の選択・ -回収ホワイトリストの判定は `tongue_seg_model.remote` の純関数に任せる. -手元で torch を読み込まずに動かすため,`tongue_seg_model.remote` 以外のモジュールを import しない. - -終了コード: 成功 0.ssh・リモートの失敗時はその終了コード(ssh の接続失敗は 255, -リモートスクリプトの 90〜94 は `tongue_seg_model.remote.commands` の `EXIT_*`). -入力エラー・空き GPU 無し・接続できるサーバが無い等は 1.引数の誤りは 2.中断は 130. -""" - -from __future__ import annotations - -import argparse -import codecs -import contextlib -import logging -import os -import socket -import subprocess -import sys -import tarfile -import tempfile -import threading -import time -from collections.abc import Callable, Sequence -from concurrent.futures import ThreadPoolExecutor -from dataclasses import dataclass -from pathlib import Path -from typing import BinaryIO - -from pydantic import ValidationError - -from tongue_seg_model.remote.commands import ( - EXIT_NO_SESSION, - EXIT_NOT_FOUND, - EXIT_REMOTE_DIR_MISSING, - EXIT_SESSION_EXISTS, - EXIT_UNSAFE_PATH, - REMOTE_LOG_DIR, - REMOTE_RUNS_DIR, - build_job_env, - build_job_script, - build_kill_command, - build_log_exists_command, - build_logs_command, - build_probe_command, - build_pull_list_command, - build_pull_tar_command, - build_push_command, - build_run_command, - build_ssh_argv, - format_git_commit, - job_log_path, - validate_job_name, -) -from tongue_seg_model.remote.config import ( - ALLOW_SELF_ENV_VAR, - DEFAULT_CONFIG_PATH, - JUMP_ENV_VAR, - SSH_ENV_VAR, - GpuFreeThreshold, - RemoteConfig, - ServerConfig, - detect_self_server, - is_self_check_disabled, - load_remote_config, - resolve_jump_host, - resolve_ssh_executable, -) -from tongue_seg_model.remote.files import ( - PushEntry, - PushSelection, - find_project_root, - select_push_files, -) -from tongue_seg_model.remote.gpu import ( - ServerProbe, - check_cpu_options, - check_selection_options, - parse_probe_output, - select_cpu_server, - select_gpu, - servers_with_session, -) -from tongue_seg_model.remote.report import ( - format_selection, - format_server_report, - format_shared_warning, -) -from tongue_seg_model.remote.transfer import copy_stream, extract_pull_archive, write_tar_stream -from tongue_seg_model.remote.whitelist import parse_find_listing, plan_pull, validate_run_id - -logger = logging.getLogger(__name__) - -# ssh 自身の失敗(接続できない・認証失敗等)の終了コード -_SSH_FAILURE_RC = 255 -# 応答待ちを打ち切ったことを表す内部の終了コード(ssh の終了コードと衝突しない負値) -_TIMEOUT_RC = -1 -# GNU tar の終了コード 1 は「読み取り中にファイルが変化した」等の警告 -_TAR_WARNING_RC = 1 -# 短い問い合わせ(probe・ログの有無・一覧)の応答待ちの上限は接続タイムアウトにこれを足す. -# 踏み台経由では ConnectTimeout が踏み台側の接続に効かないため,全体の上限も設ける -_QUERY_TIMEOUT_MARGIN_SEC = 30 -_MAX_STDERR_CHARS = 160 -_HOST_KEY_FAILURE = b"Host key verification failed" -# 手元の git(rev-parse・status)の応答待ちの上限 -_GIT_TIMEOUT_SEC = 30 - -_EPILOG = """\ -使用例: - uv run tsm-remote gpus # 全サーバの GPU と run が選ぶ GPU - uv run tsm-remote status # 実行中ジョブと GPU - uv run tsm-remote push --dry-run # 送るファイルの一覧(送信しない) - uv run tsm-remote push # 接続できる全サーバへコードを送る - uv run tsm-remote run --name train1 -- tsm-train --config configs/resunet.yaml - # 空き GPU を自動で選んで学習 - uv run tsm-remote run --name train2 --server Newton --gpu 1 -- tsm-train --config ... - # GPU を指定 - uv run tsm-remote run --name export1 --cpu --server Newton -- tsm-export --run <実験ID> - # GPU なし(ONNX の書き出し) - uv run tsm-remote logs train1 -f # ログを追従 - uv run tsm-remote kill train1 # ジョブを止める - uv run tsm-remote pull <実験ID> # 回収ホワイトリストのみ持ち帰る - uv run tsm-remote pull <実験ID> --with-checkpoints # best.pth・ResUNet.onnx も持ち帰る - -tsm-train の実験 ID は,ジョブのログ(logs)の終了行(=== ... exit 0)の直前の行に出る. -tsm-export の成否は終了行の exit の値で判断する(失敗時は PyTorch がグラフを大量に出しうる). - -環境変数: - TSM_REMOTE_JUMP 踏み台を上書き(空文字なら直接接続.研究室 LAN 内にいるとき) - TSM_REMOTE_SSH 手元の ssh 実行ファイル - TSM_REMOTE_ALLOW_SELF 1 でサーバ上実行の検出を無効化 -""" - - -@dataclass(frozen=True) -class _Context: - """サブコマンドが使う実行環境. - - Attributes: - config: サーバ設定. - ssh: 手元の ssh 実行ファイル. - jump_host: 踏み台(None なら直接接続). - project_root: 手元のプロジェクトルート. - """ - - config: RemoteConfig - ssh: str - jump_host: str | None - project_root: Path - - @property - def query_timeout_sec(self) -> int: - """短い問い合わせの応答待ちの上限(秒).""" - return self.config.connect_timeout_sec + _QUERY_TIMEOUT_MARGIN_SEC - - -@dataclass(frozen=True) -class _SshResult: - """ssh の実行結果. - - Attributes: - rc: 終了コード(応答待ちを打ち切ったら `_TIMEOUT_RC`). - stdout: 標準出力. - stderr: 標準エラー. - """ - - rc: int - stdout: bytes - stderr: bytes - - -class _CliFormatter(logging.Formatter): - """警告・エラーに日本語の接頭辞を付ける(CLI の利用者向けの表示).""" - - _PREFIXES = {logging.WARNING: "警告: ", logging.ERROR: "エラー: ", logging.CRITICAL: "エラー: "} - - def format(self, record: logging.LogRecord) -> str: - return self._PREFIXES.get(record.levelno, "") + super().format(record) - - -def _configure_logging() -> None: - """標準エラーへ日本語の接頭辞付きでログを出す(既に設定済みなら何もしない).""" - handler = logging.StreamHandler(sys.stderr) - handler.setFormatter(_CliFormatter("%(message)s")) - logging.basicConfig(level=logging.INFO, handlers=[handler]) - - -def _write_stdout(text: str) -> None: - """標準出力へ書く(出力先の文字コードで表せない文字は置換する). - - リモートの出力は UTF-8 で届くが,リダイレクト時の Windows の標準出力は cp932 のことがある. - """ - try: - sys.stdout.write(text) - except UnicodeEncodeError: - encoding = sys.stdout.encoding or "utf-8" - sys.stdout.write(text.encode(encoding, errors="replace").decode(encoding, errors="replace")) - sys.stdout.flush() - - -def _format_size(num_bytes: float) -> str: - """バイト数を読みやすい単位で返す.""" - for unit in ("B", "KB", "MB"): - if num_bytes < 1024: - return f"{num_bytes:.0f} {unit}" if unit == "B" else f"{num_bytes:.1f} {unit}" - num_bytes /= 1024 - return f"{num_bytes:.1f} GB" - - -def _last_stderr_line(stderr: bytes) -> str: - """ssh の標準エラーの最後の空でない行を返す(接続不可の理由の表示用).""" - lines = [line.strip() for line in stderr.decode("utf-8", errors="replace").splitlines()] - lines = [line for line in lines if line] - return lines[-1][:_MAX_STDERR_CHARS] if lines else "" - - -def _describe_failure(result: _SshResult) -> str: - """ssh が失敗した理由を短く返す.""" - if result.rc == _TIMEOUT_RC: - return "応答がタイムアウトした" - detail = _last_stderr_line(result.stderr) if result.rc == _SSH_FAILURE_RC else "" - return f"終了コード {result.rc}" + (f": {detail}" if detail else "") - - -# --------------------------------------------------------------------------- -# ssh の実行(副作用) -# --------------------------------------------------------------------------- - - -def _ssh_argv( - ctx: _Context, server: ServerConfig, command: str, *, stdin: bool = False -) -> list[str]: - """サーバでリモートコマンドを実行する ssh の引数リストを返す.""" - return build_ssh_argv( - ctx.ssh, - host=server.ssh_host, - user=server.user, - jump_host=ctx.jump_host, - connect_timeout_sec=ctx.config.connect_timeout_sec, - remote_command=command, - stdin=stdin, - ) - - -def _popen(argv: list[str], **kwargs: object) -> subprocess.Popen[bytes]: - """ssh を起動する(見つからなければ対処を添えて ValueError にする).""" - try: - return subprocess.Popen(argv, **kwargs) # noqa: S603 - except FileNotFoundError as exc: - raise ValueError( - f"ssh が見つからない: {argv[0]}(環境変数 {SSH_ENV_VAR} で実行ファイルを指定できる)" - ) from exc - - -def _run_ssh( - argv: list[str], *, input_bytes: bytes | None = None, timeout: float | None = None -) -> _SshResult: - """ssh を実行して終了を待ち,標準出力・標準エラーを受け取る. - - Args: - argv: ssh の引数リスト. - input_bytes: 標準入力へ渡すバイト列(None なら何も渡さない). - timeout: 応答待ちの上限(秒).超えたら ssh を止めて `_TIMEOUT_RC` を返す. - - Returns: - 実行結果. - """ - stdin = subprocess.PIPE if input_bytes is not None else subprocess.DEVNULL - proc = _popen(argv, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - try: - out, err = proc.communicate(input=input_bytes, timeout=timeout) - except subprocess.TimeoutExpired: - proc.kill() - out, err = proc.communicate() - return _SshResult(_TIMEOUT_RC, out or b"", err or b"") - return _SshResult(proc.returncode, out or b"", err or b"") - - -def _map_servers[T](servers: Sequence[ServerConfig], func: Callable[[ServerConfig], T]) -> list[T]: - """サーバごとの処理を並列に実行し,servers の順で結果を返す. - - 接続できないサーバの接続タイムアウトを待つ間,他のサーバの処理を止めないため並列にする. - """ - if not servers: - return [] - with ThreadPoolExecutor(max_workers=len(servers)) as executor: - return list(executor.map(func, servers)) - - -def _query_servers( - ctx: _Context, servers: Sequence[ServerConfig], build_command: Callable[[ServerConfig], str] -) -> list[_SshResult]: - """短い問い合わせを各サーバで並列に実行し,servers の順で結果を返す. - - コマンドは ssh を起動する前にすべて組み立てる(引数の検証エラーで一部のサーバにだけ - 問い合わせた状態にしないため). - """ - commands = {server.name: build_command(server) for server in servers} - return _map_servers( - servers, - lambda s: _run_ssh(_ssh_argv(ctx, s, commands[s.name]), timeout=ctx.query_timeout_sec), - ) - - -def _run_git(project_root: Path, *git_args: str) -> str | None: - """手元で git を実行して標準出力を返す(git が無い・失敗したら None).""" - try: - completed = subprocess.run( # noqa: S603 - ["git", *git_args], - cwd=project_root, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=_GIT_TIMEOUT_SEC, - check=False, - ) - except (OSError, subprocess.TimeoutExpired): - return None - if completed.returncode != 0: - return None - return completed.stdout - - -def _local_git_commit(project_root: Path) -> str | None: - """ジョブに `TSM_GIT_COMMIT` として渡す手元の git の短縮ハッシュを求める. - - 未コミットの変更(未追跡のファイルを含む)があれば末尾に `-dirty` を付ける.git が - 使えない・リポジトリでない場合は None(渡さない.ジョブ側は `nogit` とする). - """ - head = _run_git(project_root, "rev-parse", "--short", "HEAD") - if head is None: - logger.warning("git のコミットハッシュを取得できなかった(実験 ID は nogit になる)") - return None - status = _run_git(project_root, "status", "--porcelain") - if status is None: - logger.warning("git の変更状況を取得できなかった(実験 ID は nogit になる)") - return None - return format_git_commit(head, dirty=bool(status.strip())) - - -def _as_exit_code(rc: int) -> int: - """ssh の結果の終了コードを CLI の終了コードにする(応答待ちの打ち切り等の負値は 1).""" - return rc if rc >= 0 else 1 - - -def _ssh_hint(ctx: _Context, server: ServerConfig, result: _SshResult) -> str: - """よくある ssh の失敗に対処の案内を返す(該当しなければ空文字).""" - if result.rc != _SSH_FAILURE_RC or _HOST_KEY_FAILURE not in result.stderr: - return "" - # BatchMode ではホスト鍵の確認に答えられないため,初回だけ手で登録してもらう - jump = f"-J {ctx.jump_host} " if ctx.jump_host else "" - return f" → ホスト鍵が未登録: 手元で一度 ssh {jump}{server.destination} exit を実行して登録する" - - -def _probe_server(ctx: _Context, server: ServerConfig, threshold: GpuFreeThreshold) -> ServerProbe: - """サーバ 1 台の tmux セッションと GPU の状況を取得する(接続できなければその旨を返す). - - GPU の観測はサーバ側で `threshold.observe_sec` 秒かかるため,応答待ちの上限をそのぶん延ばす. - """ - command = build_probe_command( - server.remote_dir, - observe_sec=threshold.observe_sec, - sample_interval_ms=threshold.sample_interval_ms, - ) - argv = _ssh_argv(ctx, server, command) - result = _run_ssh(argv, timeout=ctx.query_timeout_sec + threshold.observe_sec) - if result.rc != 0: - return ServerProbe(server, None, _describe_failure(result) + _ssh_hint(ctx, server, result)) - try: - output = parse_probe_output(result.stdout.decode("utf-8", errors="replace"), threshold) - except ValueError as exc: - return ServerProbe(server, None, str(exc)) - return ServerProbe(server, output) - - -def _probe_servers( - ctx: _Context, servers: Sequence[ServerConfig], threshold: GpuFreeThreshold | None = None -) -> list[ServerProbe]: - """複数サーバの状況を並列に取得する(servers の順で返す). - - Args: - ctx: 実行環境. - servers: 対象のサーバ. - threshold: 判定と観測の設定.None なら観測しない(ジョブの有無だけが要る push・kill - 用.瞬間値で判定する). - """ - if threshold is None: - threshold = ctx.config.gpu_free.with_observe_sec(0) - elif threshold.observe_sec > 0: - logger.info( - "GPU を %d 秒観測している(%d ミリ秒間隔.全サーバ並行)", - threshold.observe_sec, - threshold.sample_interval_ms, - ) - return _map_servers(servers, lambda server: _probe_server(ctx, server, threshold)) - - -def _threshold_for(ctx: _Context, observe_sec: int | None) -> GpuFreeThreshold: - """`--observe` があれば観測秒数を差し替えた判定の設定を返す(範囲外は ValueError).""" - threshold = ctx.config.gpu_free - if observe_sec is None: - return threshold - try: - return threshold.with_observe_sec(observe_sec) - except ValidationError as exc: - # 設定ファイルではなくコマンドライン引数の誤りとして伝える - raise ValueError(f"--observe は 0〜120 の整数で指定する(指定 {observe_sec})") from exc - - -def _target_servers(ctx: _Context, server_name: str | None) -> list[ServerConfig]: - """`--server` の指定があればそのサーバ,無ければ全サーバ(優先順)を返す.""" - if server_name is not None: - return [ctx.config.find_server(server_name)] - return ctx.config.ordered_servers() - - -def _warn_unreachable(probes: Sequence[ServerProbe]) -> None: - """接続できなかったサーバを警告し,すべて接続できなければ ValueError にする.""" - reachable = [probe for probe in probes if probe.reachable] - if not reachable: - details = "; ".join(f"{p.server.name}: {p.error}" for p in probes) - raise ValueError(f"どのサーバにも接続できない({details})") - for probe in probes: - if not probe.reachable: - logger.warning( - "%s に接続できない(%s).他のサーバで続行する", probe.server.name, probe.error - ) - - -def _report_remote_failure(result: _SshResult, server: ServerConfig) -> None: - """ssh・リモートスクリプトに共通の失敗理由をログに出す.""" - if result.rc == EXIT_REMOTE_DIR_MISSING: - logger.error("%s に %s が無い.先に tsm-remote push する", server.name, server.remote_dir) - elif result.rc == _SSH_FAILURE_RC: - logger.error( - "%s へ ssh 接続できなかった(%s)", server.name, _last_stderr_line(result.stderr) - ) - else: - logger.error( - "%s でリモートコマンドが失敗した(%s)", server.name, _describe_failure(result) - ) - - -def _pick_single(found: Sequence[ServerConfig], *, what: str, unreachable: int) -> ServerConfig: - """探索で見つかったサーバが 1 台であることを確かめて返す.""" - if len(found) > 1: - names = ", ".join(server.name for server in found) - raise ValueError(f"{what}が複数のサーバ({names})にある.--server で指定する") - if not found: - note = f"(接続できないサーバが {unreachable} 台ある)" if unreachable else "" - raise ValueError(f"{what}がどのサーバにも見つからない{note}") - return found[0] - - -# --------------------------------------------------------------------------- -# gpus / status -# --------------------------------------------------------------------------- - - -def _cmd_gpus(args: argparse.Namespace, ctx: _Context) -> int: - """gpus サブコマンド: 全サーバの GPU 一覧と run が選ぶ GPU を表示する.""" - threshold = _threshold_for(ctx, args.observe) - probes = _probe_servers(ctx, ctx.config.ordered_servers(), threshold) - _write_stdout(format_server_report(probes, show_jobs=False)) - if not any(probe.reachable for probe in probes): - raise ValueError("どのサーバにも接続できない") - selection = select_gpu(probes, include_not_ready=args.no_data) - _write_stdout(format_selection(selection) + "\n") - if selection is None and not args.no_data: - alternative = select_gpu(probes, include_not_ready=True) - if alternative is not None: - _write_stdout( - f" (データ未配置のサーバも含めると {alternative.server.name} の GPU " - f"{alternative.gpu_index}.データを使わないジョブなら --no-data で選べる)\n" - ) - return 0 - - -def _cmd_status(args: argparse.Namespace, ctx: _Context) -> int: - """status サブコマンド: 全サーバの実行中ジョブと GPU の状況を表示する.""" - probes = _probe_servers(ctx, ctx.config.ordered_servers(), ctx.config.gpu_free) - _write_stdout(format_server_report(probes, show_jobs=True)) - if not any(probe.reachable for probe in probes): - raise ValueError("どのサーバにも接続できない") - return 0 - - -# --------------------------------------------------------------------------- -# push -# --------------------------------------------------------------------------- - - -def _stream_push(argv: list[str], entries: Sequence[PushEntry]) -> int: - """tar ストリームを ssh の標準入力へ流し,ssh の終了コードを返す.""" - proc = _popen(argv, stdin=subprocess.PIPE) - stdin = proc.stdin - if stdin is None: - raise RuntimeError("ssh の標準入力を開けなかった") - try: - write_tar_stream(entries, stdin) - except OSError as exc: - # ssh が先に終了してパイプが閉じている.後始末の close 失敗は原因ではないので無視する - with contextlib.suppress(OSError): - stdin.close() - rc = proc.wait() - logger.error("送信が中断された(ssh 終了コード %d): %s", rc, exc) - return rc or 1 - except ValueError: - # 送信対象がリンク等に差し替えられていた.壊れた tar を最後まで送らず ssh を止める - proc.kill() - proc.wait() - raise - stdin.close() - return proc.wait() - - -def _push_to(ctx: _Context, probe: ServerProbe, entries: Sequence[PushEntry]) -> int: - """サーバ 1 台へコードを送り,終了コードを返す.""" - server = probe.server - if probe.output is not None and probe.output.jobs: - logger.warning( - "%s では実行中のジョブがある(%s).上書き展開のため,実行中のジョブが" - "新旧のコードを混ぜて読むおそれがある", - server.name, - ", ".join(probe.output.jobs), - ) - total = sum(entry.size for entry in entries) - logger.info( - "送信: %d ファイル / %s → %s:%s", - len(entries), - _format_size(total), - server.name, - server.remote_dir, - ) - start = time.monotonic() - argv = _ssh_argv(ctx, server, build_push_command(server.remote_dir), stdin=True) - rc = _stream_push(argv, entries) - if rc != 0: - logger.error("%s への送信に失敗した(終了コード %d)", server.name, rc) - return rc - logger.info("送信完了: %s(%.1f 秒)", server.name, time.monotonic() - start) - return 0 - - -def _collect_entries(ctx: _Context) -> PushSelection: - """送信対象を集める(空ならエラー).""" - selection = select_push_files(ctx.project_root) - if not selection.entries: - raise ValueError("送信するファイルが無い") - return selection - - -def _describe_skipped_links(selection: PushSelection) -> str: - """送らなかったリンクの件数と名前(リポジトリ内のコードの名前なので出してよい)の 1 行.""" - links = selection.skipped_links - names = f"({', '.join(links)})" if links else "" - return f"送らなかったリンク: {len(links)} 件{names}" - - -def _cmd_push(args: argparse.Namespace, ctx: _Context) -> int: - """push サブコマンド: コードをサーバへ送る(省略時は接続できる全サーバ).""" - selection = _collect_entries(ctx) - entries = selection.entries - servers = _target_servers(ctx, args.server) - if args.dry_run: - for entry in entries: - _write_stdout(f" {_format_size(entry.size):>10} {entry.arcname}\n") - names = ", ".join(server.name for server in servers) - _write_stdout( - f"送信対象: {len(entries)} ファイル / " - f"{_format_size(sum(e.size for e in entries))}(送信先の候補: {names})\n" - f"{_describe_skipped_links(selection)}\n" - "(--dry-run のため送信していない)\n" - ) - return 0 - logger.info("%s", _describe_skipped_links(selection)) - - probes = _probe_servers(ctx, servers) - _warn_unreachable(probes) - rc_total = 0 - for probe in probes: - if probe.reachable: - rc = _push_to(ctx, probe, entries) - rc_total = rc_total or rc - return rc_total - - -# --------------------------------------------------------------------------- -# run -# --------------------------------------------------------------------------- - - -def _select_gpu_target( - args: argparse.Namespace, probes: Sequence[ServerProbe] -) -> tuple[ServerConfig, int, str] | None: - """GPU ジョブの実行先(サーバ・GPU・GPU の状態)を選び,警告を出す. - - 選べなければ状況を表示して None を返す. - """ - selection = select_gpu( - probes, - server_name=args.server, - gpu_index=args.gpu, - force=args.force, - include_not_ready=args.no_data, - ) - if selection is None: - _write_stdout(format_server_report(probes, show_jobs=True)) - scope = "全サーバ" if args.no_data else "データ配置済みのサーバ" - logger.error( - "%s(%s)に未使用・空き(利用者あり)の GPU が無いため,ジョブを起動しなかった", - args.server or scope, - "--no-data 指定" if args.no_data else "data_ready: true", - ) - return None - if selection.forced: - logger.warning( - "%s の GPU %d は%sだが,--force により使う(他のユーザーの計算と競合しうる)", - selection.server.name, - selection.gpu_index, - selection.state, - ) - shared_warning = format_shared_warning(selection) - if shared_warning is not None: - logger.warning("%s", shared_warning) - return selection.server, selection.gpu_index, selection.state.value - - -def _select_cpu_target( - args: argparse.Namespace, probes: Sequence[ServerProbe] -) -> tuple[ServerConfig, None, str] | None: - """CPU ジョブ(--cpu)の実行先サーバを選ぶ(選べなければエラーを出して None).""" - server = select_cpu_server(probes, server_name=args.server, include_not_ready=args.no_data) - if server is None: - logger.error( - "接続できる%sが無いため,ジョブを起動しなかった", - "サーバ" if args.no_data else "データ配置済み(data_ready: true)のサーバ", - ) - return None - return server, None, "" - - -def _describe_target(server: ServerConfig, gpu_index: int | None, state: str = "") -> str: - """実行先の表示(例: `Newton の GPU 1(未使用)`・`Newton(GPU なし・CPU のみ)`).""" - if gpu_index is None: - return f"{server.name}(GPU なし・CPU のみ)" - return f"{server.name} の GPU {gpu_index}" + (f"({state})" if state else "") - - -def _cmd_run(args: argparse.Namespace, ctx: _Context) -> int: - """run サブコマンド: 空き GPU(--cpu なら GPU なし)を選び,コードを送って tmux で起動する.""" - command = list(args.command) - if command and command[0] == "--": - command = command[1:] - if not command: - raise ValueError( - "実行するコマンドを -- の後に指定する(例: tsm-remote run --name x -- python ...)" - ) - name = validate_job_name(args.name) - if args.cpu: - check_cpu_options(gpu_index=args.gpu, force=args.force, observe_sec=args.observe) - # GPU を選ばないため観測しない(同名ジョブの確認と接続可否だけを見る) - threshold = None - else: - check_selection_options(server_name=args.server, gpu_index=args.gpu, force=args.force) - threshold = _threshold_for(ctx, args.observe) - if args.server is not None: - ctx.config.find_server(args.server) - - probes = _probe_servers(ctx, ctx.config.ordered_servers(), threshold) - _warn_unreachable(probes) - running = servers_with_session(probes, name, jobs_only=False) - if running: - names = ", ".join(probe.server.name for probe in running) - raise ValueError( - f"ジョブ名 {name!r} の tmux セッションが {names} で実行中である" - "(--name で別名を付けるか,終了を待つ)" - ) - if any(not probe.reachable for probe in probes): - logger.warning("接続できないサーバでは同名ジョブの有無を確認していない") - - target = _select_cpu_target(args, probes) if args.cpu else _select_gpu_target(args, probes) - if target is None: - return 1 - server, gpu_index, state = target - - env = build_job_env(gpu_index, args.env, git_commit=_local_git_commit(ctx.project_root)) - script = build_job_script( - server.remote_dir, - name, - command, - uv_path=server.uv, - server_name=server.name, - gpu_index=gpu_index, - env=env, - # 移植元はデータの場所(TIAS_DATA_ROOT)をここで渡していた.本リポジトリはバンドルだけを - # 読み,場所は TIASDATA_BUNDLES(既定 ~/data/tiasdata)で決まるため渡さない(SPEC_03) - path_env={}, - ) - remote_command = build_run_command(server.remote_dir, name, script) - if args.dry_run: - _write_stdout( - f"選んだ実行先: {_describe_target(server, gpu_index, state)}\n" - f"実行するリモートコマンド:\n{remote_command}\n" - "(--dry-run のため送信・起動していない)\n" - ) - return 0 - - if not args.no_push: - probe = next(p for p in probes if p.server.name == server.name) - selection = _collect_entries(ctx) - if selection.skipped_links: - logger.info("%s", _describe_skipped_links(selection)) - rc = _push_to(ctx, probe, selection.entries) - if rc != 0: - return rc - - result = _run_ssh(_ssh_argv(ctx, server, remote_command), timeout=ctx.query_timeout_sec) - if result.rc == EXIT_SESSION_EXISTS: - logger.error( - "%s で同名のジョブ(tmux セッション)%r が実行中である(--name で別名を付ける)", - server.name, - name, - ) - return result.rc - if result.rc != 0: - _report_remote_failure(result, server) - return _as_exit_code(result.rc) - - log_path = f"{server.remote_dir}/{job_log_path(name)}" - _write_stdout( - f"ジョブを起動した: {name}({_describe_target(server, gpu_index)})\n" - f" 環境変数: {' '.join(f'{k}={v}' for k, v in env.items())}\n" - f" ログ : {server.name}:{log_path}\n" - " 状態確認: uv run tsm-remote status\n" - f" ログ追従: uv run tsm-remote logs {name} -f\n" - ) - return 0 - - -# --------------------------------------------------------------------------- -# logs / kill -# --------------------------------------------------------------------------- - - -def _locate_log(ctx: _Context, name: str, server_name: str | None) -> ServerConfig: - """ジョブログがあるサーバを探す(複数・0 台ならエラー).""" - servers = _target_servers(ctx, server_name) - results = _query_servers(ctx, servers, lambda s: build_log_exists_command(s.remote_dir, name)) - found: list[ServerConfig] = [] - unreachable = 0 - for server, result in zip(servers, results, strict=True): - if result.rc == 0: - found.append(server) - elif result.rc != EXIT_NOT_FOUND: - unreachable += 1 - logger.warning("%s に接続できない(%s)", server.name, _describe_failure(result)) - return _pick_single(found, what=f"ジョブ {name!r} のログ", unreachable=unreachable) - - -def _follow(argv: list[str]) -> int: - """ssh の出力を逐次表示し続ける(Ctrl+C で終了). - - 進捗バーは改行せず \\r で上書きすることがあるため,行単位ではなく受け取った分から表示する. - ssh の標準入力はパイプにして開いたままにし,終了時に閉じてリモートの tail を止める. - """ - proc = _popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE) - if proc.stdin is None or proc.stdout is None: - raise RuntimeError("ssh の標準入出力を開けなかった") - decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") - interrupted = False - try: - while chunk := proc.stdout.read1(65536): - _write_stdout(decoder.decode(chunk)) - except KeyboardInterrupt: - interrupted = True - logger.info("(追従を終了した.ジョブは継続している)") - finally: - # stdin を閉じるとリモートの cat が EOF を受けて tail を止める.既に ssh が - # 終了していれば close は失敗しうるが,後始末なので無視する - with contextlib.suppress(OSError): - proc.stdin.close() - rc = proc.wait() - # Ctrl+C は追従の正常な終わらせ方(Windows では ssh も同時に止まり非 0 を返す) - return 0 if interrupted else rc - - -def _cmd_logs(args: argparse.Namespace, ctx: _Context) -> int: - """logs サブコマンド: ジョブのログを表示する(ジョブのあるサーバを自動で探す).""" - name = validate_job_name(args.name) - if args.lines < 0: - raise ValueError("--lines は 0 以上を指定する") - server = _locate_log(ctx, name, args.server) - command = build_logs_command(server.remote_dir, name, lines=args.lines, follow=args.follow) - if args.follow: - logger.info("%s のジョブ %s のログを追従する(Ctrl+C で終了)", server.name, name) - return _follow(_ssh_argv(ctx, server, command, stdin=True)) - result = _run_ssh(_ssh_argv(ctx, server, command)) - _write_stdout(result.stdout.decode("utf-8", errors="replace")) - if result.rc == EXIT_NOT_FOUND: - logger.error("%s にジョブ %r のログが無い", server.name, name) - elif result.rc != 0: - _report_remote_failure(result, server) - return _as_exit_code(result.rc) - - -def _cmd_kill(args: argparse.Namespace, ctx: _Context) -> int: - """kill サブコマンド: ジョブを止める(ジョブのあるサーバを自動で探す).""" - name = validate_job_name(args.name) - probes = _probe_servers(ctx, _target_servers(ctx, args.server)) - _warn_unreachable(probes) - found = servers_with_session(probes, name, jobs_only=True) - if not found and servers_with_session(probes, name, jobs_only=False): - raise ValueError( - f"{name!r} は tsm-remote のジョブではない tmux セッションである(止めない)" - ) - unreachable = sum(1 for probe in probes if not probe.reachable) - server = _pick_single( - [probe.server for probe in found], what=f"実行中のジョブ {name!r}", unreachable=unreachable - ) - result = _run_ssh( - _ssh_argv(ctx, server, build_kill_command(server.remote_dir, name)), - timeout=ctx.query_timeout_sec, - ) - if result.rc == EXIT_NO_SESSION: - logger.error("%s のジョブ %r は実行中ではない(既に終了した可能性)", server.name, name) - return result.rc - if result.rc != 0: - _report_remote_failure(result, server) - return _as_exit_code(result.rc) - _write_stdout(f"ジョブ {name} を終了した({server.name})\n") - return 0 - - -# --------------------------------------------------------------------------- -# pull -# --------------------------------------------------------------------------- - - -def _locate_run(ctx: _Context, run_id: str, server_name: str | None) -> tuple[ServerConfig, bytes]: - """RUN_ID のディレクトリがあるサーバを探し,そのファイル一覧を返す(複数・0 台ならエラー).""" - servers = _target_servers(ctx, server_name) - results = _query_servers(ctx, servers, lambda s: build_pull_list_command(s.remote_dir, run_id)) - found: list[tuple[ServerConfig, bytes]] = [] - unreachable = 0 - for server, result in zip(servers, results, strict=True): - if result.rc == 0: - found.append((server, result.stdout)) - elif result.rc == EXIT_UNSAFE_PATH: - raise ValueError( - f"{server.name} の {REMOTE_RUNS_DIR}/{run_id} がリンクであるため回収しない" - ) - elif result.rc != EXIT_NOT_FOUND: - # 一覧の失敗理由(find の標準エラー)はファイル名を含みうるので表示しない - unreachable += 1 - reason = ( - "応答がタイムアウトした" if result.rc == _TIMEOUT_RC else f"終了コード {result.rc}" - ) - logger.warning("%s で実験結果を探せなかった(%s)", server.name, reason) - server = _pick_single([s for s, _ in found], what=f"実験 {run_id!r}", unreachable=unreachable) - listing = next(out for s, out in found if s.name == server.name) - return server, listing - - -def _receive_tar(argv: list[str], payload: bytes, destination: BinaryIO) -> _SshResult: - """ssh の標準入力へ payload を送り,標準出力(tar)を destination へ書き写す. - - 書き込みと読み出しを別スレッドにする(送る一覧が大きいとき,リモートの tar の出力で - パイプが詰まって互いに待つのを避けるため).標準エラーは表示しない(リモートの tar の - メッセージはファイル名を含みうるため). - """ - proc = _popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if proc.stdin is None or proc.stdout is None or proc.stderr is None: - raise RuntimeError("ssh の標準入出力を開けなかった") - stdin, stderr_pipe = proc.stdin, proc.stderr - stderr_chunks: list[bytes] = [] - - def _write_payload() -> None: - # ssh が先に終了していれば書き込みは失敗する.終了コードで失敗を報告するので無視する - with contextlib.suppress(OSError): - stdin.write(payload) - with contextlib.suppress(OSError): - stdin.close() - - writer = threading.Thread(target=_write_payload, daemon=True) - reader = threading.Thread(target=lambda: stderr_chunks.append(stderr_pipe.read()), daemon=True) - writer.start() - reader.start() - copy_stream(proc.stdout, destination) - writer.join() - reader.join() - rc = proc.wait() - return _SshResult(rc, b"", b"".join(stderr_chunks)) - - -def _cmd_pull(args: argparse.Namespace, ctx: _Context) -> int: - """pull サブコマンド: 実験結果を回収ホワイトリストに従って持ち帰る.""" - run_id = validate_run_id(args.run_id) - server, listing = _locate_run(ctx, run_id, args.server) - plan = plan_pull(parse_find_listing(listing), run_id, with_checkpoints=args.with_checkpoints) - if not plan.files: - raise ValueError( - f"{server.name} の実験 {run_id!r} に回収対象のファイルが無い" - f"(回収しなかったファイル {plan.skipped} 件)" - ) - - dest = ctx.project_root / REMOTE_RUNS_DIR - logger.info("取得: %s の %s/%s → %s", server.name, REMOTE_RUNS_DIR, run_id, dest / run_id) - payload = b"".join(path.encode("utf-8", "surrogateescape") + b"\0" for path in plan.files) - argv = _ssh_argv(ctx, server, build_pull_tar_command(server.remote_dir), stdin=True) - start = time.monotonic() - with tempfile.TemporaryFile() as archive: - result = _receive_tar(argv, payload, archive) - if result.rc == _TAR_WARNING_RC: - logger.warning("一部のファイルが読み取り中に変化した(ジョブが実行中の可能性)") - elif result.rc == _SSH_FAILURE_RC: - logger.error( - "%s へ ssh 接続できなかった(%s)", server.name, _last_stderr_line(result.stderr) - ) - return result.rc - elif result.rc != 0: - logger.error("%s で結果の書き出しに失敗した(終了コード %d)", server.name, result.rc) - return result.rc - try: - extracted = extract_pull_archive( - archive, dest, run_id, with_checkpoints=args.with_checkpoints - ) - except tarfile.TarError as exc: - raise ValueError("受け取ったアーカイブが壊れているため,何も展開せず中止した") from exc - - if extracted.files != len(plan.files): - logger.warning( - "回収予定 %d 件のうち %d 件しか届かなかった", len(plan.files), extracted.files - ) - skipped = f"回収しなかったファイル: {plan.skipped} 件" - if plan.skipped_checkpoints: - skipped += ( - f"(うち checkpoints/best.pth・ResUNet.onnx {plan.skipped_checkpoints} 件は" - " --with-checkpoints で回収できる)" - ) - _write_stdout( - f"取得完了: {extracted.files} ファイル / {_format_size(extracted.bytes)}" - f"({time.monotonic() - start:.1f} 秒)→ {REMOTE_RUNS_DIR}/{run_id}/\n{skipped}\n" - ) - return 0 - - -# --------------------------------------------------------------------------- -# 引数 -# --------------------------------------------------------------------------- - - -def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace: - """コマンドライン引数をパースして返す.""" - parser = argparse.ArgumentParser( - prog="tsm-remote", - description=( - "研究室の GPU サーバ(configs/remote.yaml)で空いている GPU を選んで実行する" - "(コード送信・ジョブ起動・状態確認・結果回収)." - ), - epilog=_EPILOG, - formatter_class=argparse.RawDescriptionHelpFormatter, - ) - common = argparse.ArgumentParser(add_help=False) - common.add_argument( - "--config", - type=Path, - default=None, - metavar="PATH", - help=f"サーバ設定 YAML(既定: プロジェクトルートの {DEFAULT_CONFIG_PATH.as_posix()}).", - ) - server_opt = argparse.ArgumentParser(add_help=False) - server_opt.add_argument( - "--server", default=None, metavar="NAME", help="対象のサーバ(既定: 全サーバから探す)." - ) - sub = parser.add_subparsers(dest="subcommand", required=True, metavar="SUBCOMMAND") - - p_gpus = sub.add_parser( - "gpus", - parents=[common], - help="全サーバの GPU 一覧(状態・使い方の型・利用者)と run が選ぶ GPU を表示する", - description=( - "各 GPU を一定時間観測し,観測中の最大値で 未使用(閾値内・計算プロセス無し)/" - "空き(利用者あり)/使用中/状態不明 に分けて表示する.run は全候補サーバを通して" - "まず未使用を,無ければ空き(利用者あり)を選ぶ." - ), - ) - p_gpus.add_argument( - "--observe", - type=int, - default=None, - metavar="SEC", - help="観測秒数(設定の observe_sec を上書き.0 で瞬間値のみ.0〜120).", - ) - p_gpus.add_argument( - "--no-data", - action="store_true", - help="データ未配置(data_ready: false)のサーバも run の候補として選ぶ.", - ) - - sub.add_parser("status", parents=[common], help="全サーバの実行中ジョブと GPU の状況を表示する") - - p_push = sub.add_parser( - "push", - parents=[common, server_opt], - help="コードをサーバへ送る(省略時は接続できる全サーバ)", - description=( - "リポジトリを tar over ssh でサーバの remote_dir へ上書き展開する." - ".git / .venv / キャッシュ / data / runs / legacy / .claude・重み(.pt .pth .ckpt " - ".pb .onnx)・.env は送らない." - ), - ) - p_push.add_argument( - "--dry-run", action="store_true", help="送信せず,対象ファイルの一覧だけ表示する." - ) - - p_run = sub.add_parser( - "run", - parents=[common, server_opt], - help="GPU を選び(未使用を最優先),コードを送って tmux でジョブを起動する", - description=( - "GPU を選び(data_ready のサーバ全体を通して,まず未使用を,無ければ" - "空き(利用者あり)を priority 順・GPU 番号順に探す)," - "そのサーバへコードを送ってから remote_dir で `uv run ` を tmux で起動する." - f"出力は remote_dir/{REMOTE_LOG_DIR}/.log に追記され,接続が切れても継続する." - "コマンドは -- の後に書く." - ), - ) - p_run.add_argument( - "--name", - required=True, - metavar="NAME", - help="ジョブ名(tmux セッション名・ログ名).英数字で始まり英数字・_・-,64 文字以内.", - ) - p_run.add_argument( - "--gpu", - type=int, - default=None, - metavar="I", - help="使う GPU 番号(--server が必須.使用中・状態不明ならエラー).", - ) - p_run.add_argument( - "--force", - action="store_true", - help="--gpu で指定した GPU が使用中・状態不明でも使う.", - ) - p_run.add_argument( - "--cpu", - action="store_true", - help=( - "GPU を使わないジョブ(ONNX の書き出し・合成データの生成等)として起動する." - "GPU を観測・選択せず,CUDA_VISIBLE_DEVICES を空にする.サーバは --server," - "省略時は候補サーバを priority 順に見て最初に接続できたもの." - "--gpu・--force・--observe とは同時に指定できない." - ), - ) - p_run.add_argument( - "--no-data", - action="store_true", - help="データ未配置(data_ready: false)のサーバも候補にする.", - ) - p_run.add_argument("--no-push", action="store_true", help="起動前にコードを送らない.") - p_run.add_argument( - "--observe", - type=int, - default=None, - metavar="SEC", - help="GPU を選ぶ前の観測秒数(設定の observe_sec を上書き.0 で瞬間値のみ).", - ) - p_run.add_argument( - "--env", - action="append", - default=[], - metavar="KEY=VALUE", - help=( - "ジョブに追加で渡す環境変数.複数指定可(tsm-remote が設定する CUDA_VISIBLE_DEVICES・" - "TSM_GIT_COMMIT 等は指定できない)." - ), - ) - p_run.add_argument( - "--dry-run", - action="store_true", - help="GPU を選ぶところまで行い,送信・起動せずにリモートコマンドを表示する.", - ) - p_run.add_argument( - "command", - nargs=argparse.REMAINDER, - metavar="-- COMMAND", - help="サーバで実行するコマンド(uv run の後ろに付く部分).", - ) - - p_logs = sub.add_parser( - "logs", parents=[common, server_opt], help="ジョブのログを表示する(サーバを自動で探す)" - ) - p_logs.add_argument("name", metavar="NAME", help="ジョブ名.") - p_logs.add_argument( - "--lines", "-n", type=int, default=40, metavar="N", help="表示する末尾の行数(既定 40)." - ) - p_logs.add_argument( - "--follow", "-f", action="store_true", help="追記を追従表示する(Ctrl+C で終了)." - ) - - p_kill = sub.add_parser( - "kill", parents=[common, server_opt], help="ジョブを止める(サーバを自動で探す)" - ) - p_kill.add_argument("name", metavar="NAME", help="ジョブ名.") - - p_pull = sub.add_parser( - "pull", - parents=[common, server_opt], - help="実験結果を回収ホワイトリストに従って持ち帰る", - description=( - "サーバの runs// のうち回収ホワイトリスト(config.yaml・history.csv・" - "metrics.json・log.txt・figures/*.png)に一致するファイルだけを" - "手元の runs// へ持ち帰る(同名ファイルは上書き)." - "重み(checkpoints/best.pth・checkpoints/ResUNet.onnx)は --with-checkpoints を" - "付けたときだけ.split.json・predictions.csv 等それ以外は回収しない." - ), - ) - p_pull.add_argument("run_id", metavar="RUN_ID", help="実験 ID(runs/ 直下のディレクトリ名).") - p_pull.add_argument( - "--with-checkpoints", - "--checkpoints", - dest="with_checkpoints", - action="store_true", - help="重み(checkpoints/best.pth・checkpoints/ResUNet.onnx)も持ち帰る.", - ) - - return parser.parse_args(argv) - - -_HANDLERS: dict[str, Callable[[argparse.Namespace, _Context], int]] = { - "gpus": _cmd_gpus, - "status": _cmd_status, - "push": _cmd_push, - "run": _cmd_run, - "logs": _cmd_logs, - "kill": _cmd_kill, - "pull": _cmd_pull, -} - - -def _build_context(args: argparse.Namespace) -> _Context: - """設定を読み込み,実行環境を組み立てる.""" - project_root = find_project_root(Path.cwd()) - config_path = args.config if args.config is not None else project_root / DEFAULT_CONFIG_PATH - config = load_remote_config(config_path) - return _Context( - config=config, - ssh=resolve_ssh_executable(os.environ), - jump_host=resolve_jump_host(config, os.environ), - project_root=project_root, - ) - - -def main(argv: Sequence[str] | None = None) -> int: - """tsm-remote コマンドのメインエントリポイント. - - Args: - argv: 引数リスト.None のとき sys.argv[1:] を使用. - - Returns: - 終了コード(成功時 0.ssh・リモートの失敗時はその終了コード, - 入力エラー・空き GPU 無しは 1). - """ - args = _parse_args(argv) - _configure_logging() - try: - ctx = _build_context(args) - if not is_self_check_disabled(os.environ): - self_server = detect_self_server(ctx.config, socket.gethostname()) - if self_server is not None: - logger.error( - "ここはサーバ %s である(ホスト名が一致)." - "tsm-remote は手元の PC から実行する." - "サーバ上で直接回すなら tmux の中で uv run ... を実行する." - "判定が誤りなら環境変数 %s=1 で無効にできる", - self_server.name, - ALLOW_SELF_ENV_VAR, - ) - return 1 - if ctx.jump_host is None and JUMP_ENV_VAR in os.environ: - logger.info("%s が空のため,踏み台を使わず直接接続する", JUMP_ENV_VAR) - return _HANDLERS[args.subcommand](args, ctx) - except ValidationError as exc: - logger.error("サーバ設定が不正である:\n%s", exc) - return 1 - except ValueError as exc: - logger.error("%s", exc) - return 1 - except KeyboardInterrupt: - logger.error("中断した") - return 130 - - -if __name__ == "__main__": - # uv の生成するランチャ(tsm-remote.exe)が Windows の Smart App Control に - # ブロックされた場合の代替として `uv run python -m tongue_seg_model.cli.remote` を使える - sys.exit(main()) diff --git a/src/tongue_seg_model/remote/__init__.py b/src/tongue_seg_model/remote/__init__.py deleted file mode 100644 index a19486b..0000000 --- a/src/tongue_seg_model/remote/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -"""リモート実行: 研究室の GPU サーバへのコード送信・空き GPU の選択・ジョブ実行・結果回収. - -TIASJudgeModel の `tias_judge_model.remote` を移植したもの(SPEC_03).ssh を呼ぶ副作用は -`tongue_seg_model.cli.remote` に置き,このパッケージは設定の検証・コマンド文字列の組み立て・ -出力の解析・選択・回収ホワイトリストの判定などを担う. - -手元で GPU 用の重い依存を読み込まずに動かすため,`torch`・`cv2` と `tongue_seg_model` の -他のモジュールを import しない(`.claude/rules/project-structure.md`). -""" diff --git a/src/tongue_seg_model/remote/commands.py b/src/tongue_seg_model/remote/commands.py deleted file mode 100644 index eb02c65..0000000 --- a/src/tongue_seg_model/remote/commands.py +++ /dev/null @@ -1,651 +0,0 @@ -"""サーバ上で実行するシェルコマンド文字列と ssh 引数を組み立てる純関数群. - -`ssh [@] ''` で送る文字列を作る.リモートのログインシェル(Ubuntu では -bash)が解釈する前提で POSIX sh の範囲で書き,ジョブ本体だけは `${PIPESTATUS[0]}` を使うため -`bash -c` で包む.ユーザー由来の値(パス・コマンド引数)はすべて `shlex.quote` でクォートし, -ジョブ名・環境変数名・RUN_ID は書式を検証してから埋め込む. - -複数の文は `; ` で 1 行につなぐ.書式を検証して埋め込む値(ジョブ名・環境変数名・RUN_ID・ -ssh の接続先)は改行を通さない.一方,ジョブのコマンドの引数と `--env` の値は `shlex.quote` で -引用して渡すため改行を含みうる(`python -c` に複数行のコードを渡す使い方があるため拒否しない. -引用の中の改行はリモートのシェルでも値の一部として扱われる).`--env` の値の NUL は ssh へ -渡せないため拒否する. -リモート側が出すメッセージは ASCII に限る(ssh の stderr は Windows コンソールへ素通しされ, -コードページによっては日本語が化けるため.日本語の説明は呼び出し側の CLI が出す). - -TIASJudgeModel の `tias_judge_model.remote.commands` の移植(SPEC_03).書式の検証は -`re.fullmatch` で行う(`match` と `$` の組み合わせは末尾の改行を通すため). -""" - -from __future__ import annotations - -import re -import shlex -from collections.abc import Mapping, Sequence - -# 実験 ID に入れる git の短縮ハッシュをジョブへ渡す環境変数.サーバには .git を送らないため -# 手元で求めて渡す(SPEC_01「実験の出力」).`remote` は他のモジュールを import しない決まりの -# ため,`training/run_artifacts.py` の `GIT_COMMIT_ENV_VAR` と同じ値をここにも置く -# (変えるときは両方) -GIT_COMMIT_ENV_VAR = "TSM_GIT_COMMIT" - -REMOTE_RUNS_DIR = "runs" -REMOTE_LOG_DIR = f"{REMOTE_RUNS_DIR}/_remote_logs" - -# リモートスクリプトが返す終了コード.ssh 自身の 255・tar の 1/2 と衝突しない値にする -EXIT_REMOTE_DIR_MISSING = 90 -EXIT_SESSION_EXISTS = 91 -EXIT_NOT_FOUND = 92 -EXIT_NO_SESSION = 93 -EXIT_UNSAFE_PATH = 94 - -# probe コマンドの出力を区切る目印(ログインシェルが余計な出力をしても区切りで読み分ける) -PROBE_USER_PREFIX = "@@tsm-user " -PROBE_SESSIONS_MARKER = "@@tsm-sessions" -PROBE_GPUS_MARKER = "@@tsm-gpus" -PROBE_GPU_RC_PREFIX = "@@tsm-gpu-rc " -PROBE_SAMPLES_MARKER = "@@tsm-samples" -PROBE_PMON_MARKER = "@@tsm-pmon" -PROBE_APPS_MARKER = "@@tsm-apps" -PROBE_APPS_RC_PREFIX = "@@tsm-apps-rc " -PROBE_OWNERS_MARKER = "@@tsm-owners" -PROBE_END_MARKER = "@@tsm-end" -PROBE_JOB_PREFIX = "job " -PROBE_OTHER_PREFIX = "other " - -NVIDIA_SMI_QUERY = ( - "nvidia-smi --query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" - " --format=csv,noheader,nounits" -) -# 観測用のサンプリング(-lms <間隔> を付けて繰り返し出力させ,timeout で打ち切る) -NVIDIA_SMI_SAMPLE_QUERY = ( - "nvidia-smi --query-gpu=index,utilization.gpu,memory.used --format=csv,noheader,nounits" -) -# プロセス別の SM 使用率(1 秒間隔.-c <回数> を付けて観測秒数ぶん取る) -NVIDIA_SMI_PMON_COMMAND = "nvidia-smi pmon -s u -d 1" -# 計算プロセスのみ(画面描画の Xorg 等は含まない).gpu_uuid で上の GPU と対応付ける -NVIDIA_SMI_APPS_QUERY = ( - "nvidia-smi --query-compute-apps=gpu_uuid,pid,used_memory --format=csv,noheader,nounits" -) - -# tmux のセッション名に使えない "." ":" を避け,ログのファイル名にもそのまま使える文字に限る -_JOB_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}") -_ENV_KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") -# ssh の接続先(ユーザー名・アドレス・踏み台)に許す文字.空白や `-` 始まりでオプションとして -# 解釈されるのを防ぐ -_SSH_TOKEN_RE = re.compile(r"[A-Za-z0-9_.][A-Za-z0-9_.@:%-]*") -# git rev-parse --short HEAD の出力(16 進).実験 ID に埋め込むため,これ以外は渡さない -_GIT_SHORT_HASH_RE = re.compile(r"[0-9a-f]{4,40}") -GIT_DIRTY_SUFFIX = "-dirty" - -_NOW = "\"$(date '+%Y-%m-%d %H:%M:%S')\"" - -# GPU を使わないジョブ(run --cpu)のログの開始行に書く GPU 欄(SPEC_03「run」) -NO_GPU_LABEL = "なし(CPU)" - - -def quote_remote_path(path: str) -> str: - """リモートのパスをシェル用にクォートする. - - 先頭の `~` はリモートの `$HOME` に展開させる必要があるため,`~/...` は - `"$HOME"/'...'` の形に変換する(丸ごとクォートするとチルダ展開が起きない). - - Args: - path: リモートのパス(`~/...`・絶対パス・ホーム基準の相対パス). - - Returns: - シェルにそのまま埋め込める文字列. - - Raises: - ValueError: 空文字,または `~ユーザー名/...` 形式の場合. - """ - if not path or not path.strip(): - raise ValueError("リモートパスが空である") - if path == "~": - return '"$HOME"' - if path.startswith("~/"): - rest = path[2:] - return f'"$HOME"/{shlex.quote(rest)}' if rest else '"$HOME"' - if path.startswith("~"): - raise ValueError( - f"~ユーザー名 形式のリモートパスには対応していない: {path!r}(~/... か絶対パスを指定)" - ) - return shlex.quote(path) - - -def validate_ssh_token(value: str, *, what: str) -> str: - """ssh の接続先に使う文字列(ユーザー名・アドレス・踏み台)を検証して返す. - - Args: - value: 検証する文字列. - what: エラーメッセージに出す項目名. - - Returns: - 検証済みの文字列. - - Raises: - ValueError: 空・`-` 始まり・空白や記号を含む場合. - """ - if not _SSH_TOKEN_RE.fullmatch(value): - raise ValueError(f"{what} が不正である: {value!r}(英数字・. _ - @ : % のみ)") - return value - - -def validate_job_name(name: str) -> str: - """ジョブ名(tmux セッション名・ログのファイル名)を検証して返す. - - Args: - name: ジョブ名. - - Returns: - 検証済みのジョブ名. - - Raises: - ValueError: 英数字で始まり英数字・`_`・`-` のみ(1〜64 文字)でない場合. - """ - if not _JOB_NAME_RE.fullmatch(name): - raise ValueError( - f"ジョブ名が不正である: {name!r}(英数字で始まり,英数字・_・- のみ,64 文字以内)" - ) - return name - - -def validate_env_key(key: str) -> str: - """環境変数名を検証して返す. - - Args: - key: 環境変数名. - - Returns: - 検証済みの環境変数名. - - Raises: - ValueError: 環境変数名として不正な場合. - """ - if not _ENV_KEY_RE.fullmatch(key): - raise ValueError(f"環境変数名が不正である: {key!r}") - return key - - -def parse_env_assignment(text: str) -> tuple[str, str]: - """`KEY=VALUE` 形式の環境変数指定を分解する. - - Args: - text: `KEY=VALUE` 形式の文字列(VALUE は空でもよい). - - Returns: - (KEY, VALUE). - - Raises: - ValueError: `=` が無い,KEY が環境変数名として不正,または VALUE に NUL を含む場合 - (NUL は ssh へ渡すコマンドに入れられず,環境変数の値にもできないため). - """ - key, sep, value = text.partition("=") - if not sep or not _ENV_KEY_RE.fullmatch(key): - raise ValueError(f"環境変数の指定が不正である: {text!r}(KEY=VALUE 形式)") - if "\x00" in value: - raise ValueError(f"環境変数 {key} の値に NUL 文字は使えない") - return key, value - - -def format_git_commit(short_hash: str, *, dirty: bool) -> str | None: - """`TSM_GIT_COMMIT` に渡す値(git の短縮ハッシュ,未コミットの変更があれば `-dirty` 付き). - - Args: - short_hash: `git rev-parse --short HEAD` の出力(前後の空白は無視する). - dirty: 未コミットの変更があるか(`git status --porcelain` の出力が空でないか). - - Returns: - 渡す値.`short_hash` が短縮ハッシュの形式でなければ None(渡さない). - """ - value = short_hash.strip() - if not _GIT_SHORT_HASH_RE.fullmatch(value): - return None - return value + GIT_DIRTY_SUFFIX if dirty else value - - -def build_job_env( - gpu_index: int | None, extra: Sequence[str], *, git_commit: str | None = None -) -> dict[str, str]: - """ジョブに渡す環境変数(値をそのまま渡すもの)を組み立てる. - - `CUDA_DEVICE_ORDER=PCI_BUS_ID` を付けるのは,CUDA の既定の番号付け(速い順)が - nvidia-smi の index(PCI バス順)と異なりうるため(異なると空きと判定した GPU とは別の - GPU を使ってしまう).`TSM_GIT_COMMIT` はサーバに `.git` を送らないため手元で求めて渡す - (実験 ID に使う.SPEC_01「実験の出力」).GPU の割り当てと実験の記録を迂回させないため, - `--env` で予約済みの変数は上書きできない(`TSM_GIT_COMMIT` は git が使えず渡さない - ときも予約済み). - GPU を使わないジョブ(`run --cpu`)では `CUDA_VISIBLE_DEVICES` を空文字で渡し, - CUDA から GPU が見えないようにする(誤って GPU を掴まないため). - - Args: - gpu_index: 選んだ GPU の番号(nvidia-smi の index).None なら GPU を使わない(`--cpu`). - extra: `--env` で指定された `KEY=VALUE`(後勝ち). - git_commit: `TSM_GIT_COMMIT` に渡す値(`format_git_commit` の結果).None なら渡さない. - - Returns: - 環境変数の辞書(挿入順=ログに表示する順). - - Raises: - ValueError: GPU 番号が負,`KEY=VALUE` が不正,または予約済みの変数を指定した場合. - """ - if gpu_index is not None and gpu_index < 0: - raise ValueError(f"GPU 番号は 0 以上: {gpu_index}") - env = { - "CUDA_DEVICE_ORDER": "PCI_BUS_ID", - "CUDA_VISIBLE_DEVICES": "" if gpu_index is None else str(gpu_index), - # パイプ越しでも Python の出力がすぐログに出るようにする(既定はブロックバッファ) - "PYTHONUNBUFFERED": "1", - } - if git_commit is not None: - env[GIT_COMMIT_ENV_VAR] = git_commit - reserved = {*env, GIT_COMMIT_ENV_VAR} - for item in extra: - key, value = parse_env_assignment(item) - if key in reserved: - raise ValueError(f"{key} は tsm-remote が設定するため --env では指定できない") - env[key] = value - return env - - -def build_ssh_argv( - ssh: str, - *, - host: str, - user: str | None, - jump_host: str | None, - connect_timeout_sec: int, - remote_command: str, - stdin: bool = False, -) -> list[str]: - """ssh を起動する引数リストを返す. - - 常に `BatchMode=yes`(パスワード入力を求めず失敗させる)と `ConnectTimeout` を付ける. - 標準入力を使わないコマンドには `-n` を付ける(標準入力が開いたままだと応答せず止まる - ことがあるため.ENV_02 トラブルシューティング). - - 接続先は ``(`user` が None のとき)か `@`.`host` に `~/.ssh/config` の - Host 名を渡せば,アドレス・ユーザー名・鍵は手元の ssh の設定から決まる(リポジトリに - 書かないため.移植元はアドレスとユーザー名を必須にしていた). - - Args: - ssh: ssh 実行ファイル. - host: 接続先(`~/.ssh/config` の Host 名かアドレス). - user: 接続ユーザー.None なら付けない(ssh の設定に任せる). - jump_host: 踏み台(`-J` に渡す).None なら直接接続. - connect_timeout_sec: 接続タイムアウト(秒). - remote_command: リモートで実行するシェルコマンド(1 引数として渡す). - stdin: True なら標準入力をリモートへ渡す(`-n` を付けない). - - Returns: - subprocess に渡す引数リスト. - - Raises: - ValueError: 接続先の書式が不正,またはタイムアウトが 1 未満の場合. - """ - if connect_timeout_sec < 1: - raise ValueError(f"接続タイムアウトは 1 以上でなければならない({connect_timeout_sec})") - destination = validate_ssh_token(host, what="接続先") - if user is not None: - destination = f"{validate_ssh_token(user, what='ユーザー名')}@{destination}" - argv = [ssh, "-o", "BatchMode=yes", "-o", f"ConnectTimeout={connect_timeout_sec}"] - if jump_host is not None: - argv += ["-J", validate_ssh_token(jump_host, what="踏み台")] - if not stdin: - argv.append("-n") - argv += [destination, remote_command] - return argv - - -def _cd_command(remote_dir: str) -> str: - """リモートディレクトリへ移動し,無ければ専用の終了コードで抜ける文を返す.""" - quoted = quote_remote_path(remote_dir) - return ( - f"cd {quoted} || {{ echo 'tsm-remote: remote directory not found:' {quoted} >&2; " - f"exit {EXIT_REMOTE_DIR_MISSING}; }}" - ) - - -def job_log_path(name: str) -> str: - """ジョブログのパス(remote_dir 基準.クォート前)を返す. - - Args: - name: 検証済みのジョブ名(`validate_job_name`). - - Returns: - `runs/_remote_logs/.log`. - """ - return f"{REMOTE_LOG_DIR}/{name}.log" - - -def _tmux_target(name: str) -> str: - """tmux の `-t` に渡すセッション指定をクォートして返す.name は検証済みとする. - - `=` を前置して完全一致にする(付けないと tmux は前方一致で別のジョブを選びうる). - """ - return shlex.quote(f"={name}") - - -def build_probe_command(remote_dir: str, *, observe_sec: int, sample_interval_ms: int) -> str: - """tmux セッション・GPU の観測・計算プロセスとその所有者を 1 回の ssh で取るコマンドを返す. - - 出力の形式(`parse_probe_output` が解釈する): - - - `@@tsm-user <接続したユーザー名>`(`id -un`.GPU の利用者のうち自分を「自分」と - 表示するため.移植元は設定の `user` を使っていたが,本リポジトリでは省略できるため) - - `@@tsm-sessions` の後に,tmux セッション 1 件につき 1 行.このツールのジョブログ - (`remote_dir/runs/_remote_logs/<名前>.log`)があるものは `job <名前>`,無いものは - `other <名前>`(同じユーザーの別用途のセッション) - - `@@tsm-gpus` の後に GPU の一覧(`nvidia-smi --query-gpu` の CSV),続けて - `@@tsm-gpu-rc <終了コード>`(nvidia-smi が無ければ 127 で,以降の節は出ない) - - `observe_sec > 0` のとき,`@@tsm-samples` の後に観測中のサンプル(`index, 使用率, - 使用中メモリ` の CSV.`sample_interval_ms` 間隔),`@@tsm-pmon` の後に - `nvidia-smi pmon -s u` の出力(1 秒間隔.失敗・未対応なら空) - - `@@tsm-apps` の後に計算プロセス(`nvidia-smi --query-compute-apps` の CSV),続けて - `@@tsm-apps-rc <終了コード>` - - `@@tsm-owners` の後に,計算プロセス 1 件につき ` <所有ユーザー> <経過秒>` - (ps で取れなければ pid だけ) - - 最後に `@@tsm-end`(出力が途中で切れていないことの確認用) - - remote_dir が無くても失敗しない(まだ push していないサーバも GPU 一覧に出すため). - 所要時間はおよそ observe_sec 秒(観測はサーバ側で行う). - - Args: - remote_dir: リモートのプロジェクトルート. - observe_sec: 観測秒数(0 なら観測せず瞬間値だけを取る). - sample_interval_ms: 観測の間隔(ミリ秒). - - Returns: - リモートで実行するシェルコマンド. - - Raises: - ValueError: 観測秒数が負,または間隔が 1 未満の場合. - """ - log_dir = f"{quote_remote_path(remote_dir)}/{REMOTE_LOG_DIR}" - sessions = ( - "tmux ls -F '#{session_name}' 2>/dev/null | while IFS= read -r s; do " - f'if [ -f {log_dir}/"$s".log ]; then echo "{PROBE_JOB_PREFIX}$s"; ' - f'else echo "{PROBE_OTHER_PREFIX}$s"; fi; done' - ) - if observe_sec < 0 or sample_interval_ms < 1: - raise ValueError( - f"観測の設定が不正である(observe_sec={observe_sec}, " - f"sample_interval_ms={sample_interval_ms})" - ) - # 所有者は ps の user 列を広げて取る(既定幅では長いユーザー名が UID 表記・切り詰めになる). - # etimes は起動からの経過秒数(他ユーザーのプロセスでも取れる) - owners = ( - "printf '%s\\n' \"$apps\" | while IFS=, read -r _u p _m; do " - "p=$(printf '%s' \"$p\" | tr -d ' '); " - "case \"$p\" in ''|*[!0-9]*) continue;; esac; " - 'echo "$p $(ps -o user:64=,etimes= -p "$p" 2>/dev/null | tr -s \' \')"; done' - ) - observe = "" - if observe_sec > 0: - # GPU ごとのサンプリングと pmon(プロセス別 SM 使用率)を並行して走らせる.出力が - # 混ざらないよう一時ディレクトリのファイルに分けて書き,終わってから順に出す. - # timeout で打ち切った nvidia-smi -lms は 124 で終わるが,出力は有効なので終了コードは - # 見ない(サンプルが 0 件の GPU を状態不明にする).pmon が止まらない場合に備えて - # pmon にも余裕を持たせた timeout を付ける - observe = ( - 't=$(mktemp -d 2>/dev/null); if [ -n "$t" ]; then ' - f"timeout {observe_sec + 5} {NVIDIA_SMI_PMON_COMMAND} -c {observe_sec}" - ' > "$t/pmon" 2>/dev/null & pp=$!; ' - f"timeout {observe_sec} {NVIDIA_SMI_SAMPLE_QUERY} -lms {sample_interval_ms}" - ' > "$t/samples" 2>/dev/null; wait "$pp"; ' - f"echo '{PROBE_SAMPLES_MARKER}'; cat \"$t/samples\"; " - f"echo '{PROBE_PMON_MARKER}'; cat \"$t/pmon\"; " - 'rm -rf "$t"; fi; ' - ) - gpus = ( - "if command -v nvidia-smi >/dev/null 2>&1; then " - f'{NVIDIA_SMI_QUERY} 2>/dev/null; echo "{PROBE_GPU_RC_PREFIX}$?"; ' - f"{observe}" - f"apps=$({NVIDIA_SMI_APPS_QUERY} 2>/dev/null); arc=$?; " - f"echo '{PROBE_APPS_MARKER}'; if [ -n \"$apps\" ]; then printf '%s\\n' \"$apps\"; fi; " - f'echo "{PROBE_APPS_RC_PREFIX}$arc"; ' - f"echo '{PROBE_OWNERS_MARKER}'; {owners}; " - f"else echo '{PROBE_GPU_RC_PREFIX}127'; fi" - ) - return "; ".join( - [ - f'echo "{PROBE_USER_PREFIX}$(id -un 2>/dev/null)"', - f"echo '{PROBE_SESSIONS_MARKER}'", - sessions, - f"echo '{PROBE_GPUS_MARKER}'", - gpus, - f"echo '{PROBE_END_MARKER}'", - ] - ) - - -def build_push_command(remote_dir: str) -> str: - """標準入力の tar ストリームをリモートディレクトリへ展開するコマンドを返す. - - Args: - remote_dir: 展開先(リモートのプロジェクトルート). - - Returns: - リモートで実行するシェルコマンド. - """ - quoted = quote_remote_path(remote_dir) - return f"mkdir -p {quoted} && tar -xf - -C {quoted}" - - -def build_job_script( - remote_dir: str, - name: str, - command: Sequence[str], - *, - uv_path: str, - server_name: str, - gpu_index: int | None, - env: Mapping[str, str], - path_env: Mapping[str, str], -) -> str: - """tmux セッション内で bash が実行するジョブ本体のスクリプトを返す. - - 出力は `runs/_remote_logs/.log` に追記し(前回の同名ジョブのログも残す), - 開始行(サーバ名・GPU・日時)と終了コード行で挟む.標準入力は /dev/null にする - (入力待ちで止まらないように).非対話 ssh では `~/.local/bin` が PATH に無いため, - uv のディレクトリと `$HOME/.local/bin` を PATH に足す. - - Args: - remote_dir: リモートのプロジェクトルート. - name: ジョブ名. - command: `uv run` の後ろに付けて実行するコマンドと引数. - uv_path: リモートの uv 実行ファイル. - server_name: ログの開始行に書くサーバ名. - gpu_index: ログの開始行に書く GPU 番号.None なら GPU を使わないジョブ(`--cpu`)として - `NO_GPU_LABEL` を書く. - env: ジョブに渡す環境変数(値はそのまま渡す). - path_env: ジョブに渡す環境変数のうち,値がリモートのパス(`~` を `$HOME` に展開する) - であるもの. - - Returns: - bash スクリプト(1 行). - - Raises: - ValueError: コマンドが空,またはジョブ名・環境変数名・パスが不正な場合. - """ - if not command: - raise ValueError("実行するコマンドが空である") - log = job_log_path(validate_job_name(name)) - for key in [*env, *path_env]: - validate_env_key(key) - - uv_quoted = quote_remote_path(uv_path) - run_argv = [uv_quoted, "run", *(shlex.quote(arg) for arg in command)] - display = shlex.join( - [f"{k}={v}" for k, v in [*env.items(), *path_env.items()]] + ["uv", "run", *command] - ) - gpu_label = NO_GPU_LABEL if gpu_index is None else str(gpu_index) - header = f"server={server_name} gpu={gpu_label}" - statements = [ - _cd_command(remote_dir), - f"log={shlex.quote(log)}", - f"printf '=== [%s] start %s host=%s: %s\\n' {_NOW} {shlex.quote(header)} " - f'"$(hostname)" {shlex.quote(display)} >> "$log"', - f'export PATH="$(dirname -- {uv_quoted})":"$HOME/.local/bin:$PATH"', - *[f"export {k}={shlex.quote(v)}" for k, v in env.items()], - *[f"export {k}={quote_remote_path(v)}" for k, v in path_env.items()], - f'{" ".join(run_argv)} < /dev/null 2>&1 | tee -a "$log"', - "rc=${PIPESTATUS[0]}", - f'printf \'=== [%s] exit %s\\n\' {_NOW} "$rc" >> "$log"', - 'exit "$rc"', - ] - return "; ".join(statements) - - -def build_run_command(remote_dir: str, name: str, job_script: str) -> str: - """ジョブ本体を tmux の新規セッション(デタッチ状態)で起動するコマンドを返す. - - 同名セッションが既にあれば起動せず `EXIT_SESSION_EXISTS` で終わる. - tmux のサーバはデーモン化して ssh の入出力を閉じるため,ssh はすぐ戻り, - 接続が切れてもジョブは継続する. - - Args: - remote_dir: リモートのプロジェクトルート. - name: ジョブ名(tmux セッション名). - job_script: `build_job_script` が返したスクリプト. - - Returns: - リモートで実行するシェルコマンド. - - Raises: - ValueError: ジョブ名が不正な場合. - """ - name = validate_job_name(name) - inner = "bash -c " + shlex.quote(job_script) - statements = [ - _cd_command(remote_dir), - f"mkdir -p {REMOTE_LOG_DIR} || exit 1", - f"if tmux has-session -t {_tmux_target(name)} 2>/dev/null; then " - f"echo 'tsm-remote: tmux session already exists:' {shlex.quote(name)} >&2; " - f"exit {EXIT_SESSION_EXISTS}; fi", - f'tmux new-session -d -s {shlex.quote(name)} -c "$PWD" {shlex.quote(inner)}', - ] - return "; ".join(statements) - - -def build_log_exists_command(remote_dir: str, name: str) -> str: - """ジョブログがあれば 0,無ければ `EXIT_NOT_FOUND` で終わるコマンドを返す. - - Args: - remote_dir: リモートのプロジェクトルート. - name: ジョブ名. - - Returns: - リモートで実行するシェルコマンド. - - Raises: - ValueError: ジョブ名が不正な場合. - """ - log = shlex.quote(job_log_path(validate_job_name(name))) - return ( - f"cd {quote_remote_path(remote_dir)} 2>/dev/null && [ -f {log} ] || exit {EXIT_NOT_FOUND}" - ) - - -def build_logs_command(remote_dir: str, name: str, *, lines: int, follow: bool) -> str: - """ジョブログの末尾を表示する(follow なら追従する)コマンドを返す. - - 追従モードでは,ssh の標準入力が閉じたら(手元で Ctrl+C・終了したら)tail を止める. - 疑似端末なしの ssh では切断しても tail に SIGHUP が届かず,リモートに残り続けるため. - - Args: - remote_dir: リモートのプロジェクトルート. - name: ジョブ名. - lines: 表示する末尾の行数(0 以上). - follow: True なら追記を追従する. - - Returns: - リモートで実行するシェルコマンド. - - Raises: - ValueError: ジョブ名が不正,または lines が負の場合. - """ - if lines < 0: - raise ValueError(f"表示行数は 0 以上でなければならない({lines})") - log = shlex.quote(job_log_path(validate_job_name(name))) - check = ( - f"[ -f {log} ] || {{ echo 'tsm-remote: log not found:' {log} >&2; exit {EXIT_NOT_FOUND}; }}" - ) - if follow: - tail = f'tail -n {lines} -F {log} & t=$!; cat >/dev/null; kill "$t" 2>/dev/null' - else: - tail = f"tail -n {lines} {log}" - return "; ".join([_cd_command(remote_dir), check, tail]) - - -def build_kill_command(remote_dir: str, name: str) -> str: - """ジョブの tmux セッションを終了し,ログにその旨を追記するコマンドを返す. - - tmux がセッションを閉じるとジョブの bash は SIGHUP で終わり,自分では終了行を - 書けないため,終了前にここで追記する. - - Args: - remote_dir: リモートのプロジェクトルート. - name: ジョブ名. - - Returns: - リモートで実行するシェルコマンド. - - Raises: - ValueError: ジョブ名が不正な場合. - """ - name = validate_job_name(name) - target = _tmux_target(name) - log = shlex.quote(job_log_path(name)) - statements = [ - f"tmux has-session -t {target} 2>/dev/null || " - f"{{ echo 'tsm-remote: no such tmux session:' {shlex.quote(name)} >&2; " - f"exit {EXIT_NO_SESSION}; }}", - f"if cd {quote_remote_path(remote_dir)} 2>/dev/null && [ -f {log} ]; then " - f"printf '=== [%s] killed by tsm-remote kill\\n' {_NOW} >> {log}; fi", - f"tmux kill-session -t {target}", - ] - return "; ".join(statements) - - -def build_pull_list_command(remote_dir: str, run_id: str) -> str: - """`runs//` 配下のディレクトリ以外のエントリを種類付きで列挙するコマンドを返す. - - 出力は `<種類> ` を NUL で区切ったもの(GNU find の `-printf '%y %p\\0'`. - 種類は `f` 通常ファイル・`l` シンボリックリンク 等).回収対象の絞り込みは手元の - `plan_pull` が行い,ここでは何も送らない(一覧はファイル名を含むため表示しない). - RUN_ID のディレクトリが無ければ `EXIT_NOT_FOUND`,リンクなら `EXIT_UNSAFE_PATH` で終わる. - - Args: - remote_dir: リモートのプロジェクトルート. - run_id: `validate_run_id` で検証済みの RUN_ID. - - Returns: - リモートで実行するシェルコマンド. - """ - run = shlex.quote(run_id) - statements = [ - f"cd {quote_remote_path(remote_dir)}/{REMOTE_RUNS_DIR} 2>/dev/null" - f" || exit {EXIT_NOT_FOUND}", - f"if [ -L {run} ]; then exit {EXIT_UNSAFE_PATH}; fi", - f"[ -d {run} ] || exit {EXIT_NOT_FOUND}", - f"find {run} -mindepth 1 ! -type d -printf '%y %p\\0'", - ] - return "; ".join(statements) - - -def build_pull_tar_command(remote_dir: str) -> str: - """標準入力の NUL 区切りのパス(`runs/` 基準)だけを tar ストリームで書き出すコマンドを返す. - - `--no-recursion` で指定したパス以外を含めない(ディレクトリを渡されても中身を入れない). - - Args: - remote_dir: リモートのプロジェクトルート. - - Returns: - リモートで実行するシェルコマンド. - """ - return ( - f"cd {quote_remote_path(remote_dir)}/{REMOTE_RUNS_DIR} || exit {EXIT_NOT_FOUND}; " - "tar --null --no-recursion -T - -cf -" - ) diff --git a/src/tongue_seg_model/remote/config.py b/src/tongue_seg_model/remote/config.py deleted file mode 100644 index ff2a879..0000000 --- a/src/tongue_seg_model/remote/config.py +++ /dev/null @@ -1,295 +0,0 @@ -"""リモート実行のサーバ設定(`configs/remote.yaml`)の読み込み・検証と環境変数による上書き. - -TIASJudgeModel の `tias_judge_model.remote.config` の移植(SPEC_03「サーバ設定」). -""" - -from __future__ import annotations - -import os -import re -from collections.abc import Mapping -from pathlib import Path -from typing import Any - -import yaml -from pydantic import ( - BaseModel, - ConfigDict, - Field, - StrictBool, - StrictInt, - field_validator, - model_validator, -) - -from tongue_seg_model.remote.commands import quote_remote_path, validate_ssh_token - -# 手元のプロジェクトルートからの設定ファイルの相対パス -DEFAULT_CONFIG_PATH = Path("configs") / "remote.yaml" - -# `jump_host` を上書きする.空文字なら直接接続(研究室 LAN 内にいるとき) -JUMP_ENV_VAR = "TSM_REMOTE_JUMP" -# 手元の ssh 実行ファイル -SSH_ENV_VAR = "TSM_REMOTE_SSH" -# `1` でサーバ上実行の検出を無効化する(誤検出時の逃げ道) -ALLOW_SELF_ENV_VAR = "TSM_REMOTE_ALLOW_SELF" - -# 英数字で始める(`address` を省略するとサーバ名がそのまま ssh の接続先になるため,`-` 始まりで -# オプションとして解釈されないようにする.移植元は `-` 始まりも許していた) -_SERVER_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]*") -_TRUE_VALUES = frozenset({"1", "true", "yes"}) - - -class _StrictModel(BaseModel): - """未知のキー(綴り間違い)を拒否し,生成後の変更を禁止する基底モデル.""" - - model_config = ConfigDict(extra="forbid", frozen=True) - - -class GpuFreeThreshold(_StrictModel): - """GPU を「空き」とみなす閾値と,判定前の観測の設定. - - Attributes: - max_memory_used_mib: 観測中の使用中メモリ(MiB)の最大がこれ未満. - max_utilization_percent: かつ観測中の使用率(%)の最大がこれ未満なら空き. - observe_sec: この秒数だけ観測してから判定する(0 なら瞬間値のみ).瞬間値だけでは - 起動と停止を繰り返す GPU を空きと誤認するため(TIASJudgeModel の SPEC_03「判定」). - sample_interval_ms: 観測の間隔(ミリ秒). - """ - - max_memory_used_mib: StrictInt = Field(default=1024, ge=0) - max_utilization_percent: StrictInt = Field(default=10, ge=0, le=100) - observe_sec: StrictInt = Field(default=10, ge=0, le=120) - sample_interval_ms: StrictInt = Field(default=500, ge=100, le=5000) - - def with_observe_sec(self, observe_sec: int) -> GpuFreeThreshold: - """観測秒数だけを差し替えた設定を返す(`--observe` 用.範囲の検証も行う). - - Args: - observe_sec: 観測秒数. - - Returns: - 差し替えた設定. - - Raises: - pydantic.ValidationError: 範囲外(0〜120 以外)の場合. - """ - return GpuFreeThreshold.model_validate({**self.model_dump(), "observe_sec": observe_sec}) - - -class ServerConfig(_StrictModel): - """計算サーバ 1 台の設定. - - Attributes: - name: サーバ名(英数字で始まり英数字・`_`・`-` のみ.`--server` の指定と表示に使う). - `address` を省略したときは ssh の接続先(`~/.ssh/config` の Host 名)にもなる. - address: ssh の接続先.None ならサーバ名を使う(アドレスをリポジトリに書かないため. - 移植元では必須). - user: ssh の接続ユーザー.None なら付けない(`~/.ssh/config` の `User` に任せる. - 移植元では必須). - priority: GPU 選択の優先度(小さいほど優先.同値は記載順). - remote_dir: サーバ上のプロジェクトルート(`~/...` か絶対パス). - uv: サーバ上の uv 実行ファイル(非対話 ssh では PATH に無いため絶対パスで呼ぶ). - data_ready: 学習データのバンドルが配置済みか(False のサーバは `--no-data` 無しでは - 選ばない). - """ - - name: str - address: str | None = None - user: str | None = None - priority: StrictInt - remote_dir: str - uv: str = "~/.local/bin/uv" - data_ready: StrictBool = False - - @field_validator("name") - @classmethod - def _check_name(cls, value: str) -> str: - if not _SERVER_NAME_RE.fullmatch(value): - raise ValueError(f"サーバ名は英数字で始まり英数字・_・- のみ: {value!r}") - return value - - @field_validator("address", "user") - @classmethod - def _check_ssh_token(cls, value: str | None) -> str | None: - return None if value is None else validate_ssh_token(value, what="接続先") - - @field_validator("remote_dir", "uv") - @classmethod - def _check_remote_path(cls, value: str) -> str: - quote_remote_path(value) - return value - - @property - def ssh_host(self) -> str: - """ssh の接続先(`address`.省略時はサーバ名).""" - return self.address if self.address is not None else self.name - - @property - def destination(self) -> str: - """表示用の接続先(`[user@]host`).""" - return f"{self.user}@{self.ssh_host}" if self.user is not None else self.ssh_host - - -class RemoteConfig(_StrictModel): - """リモート実行の設定のルート. - - Attributes: - jump_host: 踏み台(`~/.ssh/config` の Host 名等.`-J` に渡す).None なら直接接続. - connect_timeout_sec: ssh の接続タイムアウト(秒). - gpu_free: 空き判定の閾値. - servers: 計算サーバの一覧(1 件以上.名前は重複不可). - """ - - jump_host: str | None = "labpc" - connect_timeout_sec: StrictInt = Field(default=15, ge=1) - gpu_free: GpuFreeThreshold = Field(default_factory=GpuFreeThreshold) - servers: tuple[ServerConfig, ...] = Field(min_length=1) - - @field_validator("jump_host") - @classmethod - def _check_jump_host(cls, value: str | None) -> str | None: - return None if value is None else validate_ssh_token(value, what="踏み台") - - @model_validator(mode="after") - def _check_unique_names(self) -> RemoteConfig: - # --server の指定は大文字小文字を区別せず照合するため,重複も同じ基準で判定する - seen: set[str] = set() - for server in self.servers: - key = server.name.lower() - if key in seen: - raise ValueError(f"サーバ名が重複している: {server.name!r}") - seen.add(key) - return self - - def ordered_servers(self) -> list[ServerConfig]: - """サーバを優先順(priority 昇順.同値は記載順)に並べて返す. - - Returns: - 並べ替えたサーバの一覧. - """ - return sorted(self.servers, key=lambda server: server.priority) - - def find_server(self, name: str) -> ServerConfig: - """名前(大文字小文字を区別しない)でサーバを探す. - - Args: - name: サーバ名. - - Returns: - 該当するサーバの設定. - - Raises: - ValueError: 該当するサーバが無い場合. - """ - for server in self.servers: - if server.name.lower() == name.lower(): - return server - known = ", ".join(server.name for server in self.servers) - raise ValueError(f"サーバ {name!r} は設定に無い(設定済み: {known})") - - -def load_remote_config(path: Path) -> RemoteConfig: - """サーバ設定 YAML を読み込み,検証済みの設定を返す. - - Args: - path: 設定 YAML のパス. - - Returns: - 検証済みの設定. - - Raises: - ValueError: ファイルが無い,YAML として読めない,またはトップレベルがマッピングで - ない場合. - pydantic.ValidationError: 設定値が不正な場合. - """ - if not path.is_file(): - raise ValueError(f"サーバ設定ファイルが無い: {path}") - try: - with path.open(encoding="utf-8") as f: - raw: Any = yaml.safe_load(f) - except yaml.YAMLError as exc: - raise ValueError(f"サーバ設定ファイルを YAML として読めない: {path}") from exc - if not isinstance(raw, dict): - raise ValueError(f"サーバ設定 YAML のトップレベルはマッピングでなければならない: {path}") - return RemoteConfig.model_validate(raw) - - -def resolve_jump_host(config: RemoteConfig, environ: Mapping[str, str]) -> str | None: - """環境変数 `TSM_REMOTE_JUMP` を考慮して踏み台を決める. - - Args: - config: サーバ設定. - environ: 参照する環境変数. - - Returns: - 踏み台.None なら直接接続.環境変数が設定されていれば(空文字を含め)それを優先し, - 空文字(空白のみを含む)なら直接接続とする. - - Raises: - ValueError: 環境変数の値が踏み台として不正な場合. - """ - if JUMP_ENV_VAR not in environ: - return config.jump_host - value = environ[JUMP_ENV_VAR].strip() - return validate_ssh_token(value, what=JUMP_ENV_VAR) if value else None - - -def resolve_ssh_executable(environ: Mapping[str, str], os_name: str = os.name) -> str: - """手元の ssh 実行ファイルを決める. - - `TSM_REMOTE_SSH` があればそれを使う.無ければ Windows では System32 の OpenSSH を優先する - (Git Bash から起動すると PATH 上の Git 同梱 ssh(MSYS 版)が先に見つかり, - PowerShell からの起動と挙動が揃わないため). - - Args: - environ: 参照する環境変数. - os_name: `os.name` 相当(テスト用に差し替え可能). - - Returns: - ssh 実行ファイルのパスまたはコマンド名. - """ - override = environ.get(SSH_ENV_VAR, "").strip() - if override: - return override - if os_name == "nt": - system_root = environ.get("SystemRoot") or environ.get("SYSTEMROOT") or r"C:\Windows" - candidate = Path(system_root) / "System32" / "OpenSSH" / "ssh.exe" - if candidate.is_file(): - return str(candidate) - return "ssh" - - -def is_self_check_disabled(environ: Mapping[str, str]) -> bool: - """`TSM_REMOTE_ALLOW_SELF` でサーバ上実行の検出が無効化されているかを返す. - - Args: - environ: 参照する環境変数. - - Returns: - 無効化されていれば True. - """ - return environ.get(ALLOW_SELF_ENV_VAR, "").strip().lower() in _TRUE_VALUES - - -def detect_self_server(config: RemoteConfig, local_hostname: str) -> ServerConfig | None: - """手元のホスト名がいずれかのサーバ名と一致するかを判定する. - - サーバ上(VS Code Remote の端末等)で実行すると ssh で自分自身へつなぎに行くため, - ssh を起動する前に止める目的.大文字小文字とドメイン部(`newton.local` の `.local`)は - 無視して比較する. - - Args: - config: サーバ設定. - local_hostname: 手元のホスト名. - - Returns: - 一致したサーバ.一致しなければ None. - """ - short = local_hostname.strip().lower().split(".", 1)[0] - if not short: - return None - for server in config.servers: - if server.name.lower() == short: - return server - return None diff --git a/src/tongue_seg_model/remote/files.py b/src/tongue_seg_model/remote/files.py deleted file mode 100644 index ca97c19..0000000 --- a/src/tongue_seg_model/remote/files.py +++ /dev/null @@ -1,202 +0,0 @@ -"""push で送るファイルの選別と,手元のプロジェクトルートの探索. - -リポジトリ内のコード一式を送り,キャッシュ・仮想環境・データ・実験結果・原本・重み・ -Claude の設定は送らない(SPEC_03「移植で変える点」).サブモジュール TIASDataHub は -サーバの `uv sync` が tiasdata を導入するのに要るものだけを送る. - -シンボリックリンクとジャンクション(Windows の reparse point)は,ファイル・ディレクトリとも -送らず,リンクのディレクトリの中にも入らない(リンク先がリポジトリの外・`legacy/`・`data/` でも -名前だけでは分からないため.学習データ・原本をサーバへ送る経路を作らない). - -TIASJudgeModel の `tias_judge_model.remote.files` の移植.`legacy/`・重みの拡張子・`.env`・ -リンクの除外を足した(移植元はリンク先の中身を送っていた). -""" - -from __future__ import annotations - -import os -from collections.abc import Iterator -from dataclasses import dataclass -from pathlib import Path, PurePosixPath - -# どの階層にあっても送らないディレクトリ名(.venv は Windows 用でサーバでは使えない) -EXCLUDED_DIR_NAMES = frozenset({".git", ".venv", "__pycache__", ".pytest_cache", ".ruff_cache"}) -# プロジェクト直下でだけ除外するエントリ.data/ は学習データ・合成データの置き場,runs/ は -# サーバ側の実験結果を上書きしないため,.claude/ は手元の Claude Code 設定のため送らない. -# legacy/ は原本で,約 4 GB の重みと画像のファイル名を含む結果があるため送らない(SPEC_03). -# 直下に限るのは src/tongue_seg_model/data/(パッケージ)・tests/data/ を送るため -EXCLUDED_ROOT_ENTRIES = frozenset({"data", "runs", ".claude", "legacy"}) -# どの階層にあっても送らない拡張子(小文字で比べる).重みは data/・runs/・legacy/ の外に -# 置かれていても送らない(.gitignore の重みの拡張子と同じ) -EXCLUDED_SUFFIXES = frozenset({".pt", ".pth", ".ckpt", ".pb", ".onnx"}) -# どの階層にあっても送らないファイル名(環境変数ファイル.秘密を含みうる..gitignore と同じ) -_ENV_FILE_NAME = ".env" - -# サブモジュールのうち,サーバで `uv` が tiasdata を導入するのに要るものだけを送る -# (README.md は uv_build が要求する)..claude/・docs/・tests/・datasets/ 等は送らない -# (実行に要らず,手元の設定や別リポジトリの文書をサーバに広げないため). -_SUBMODULE_PARTS = ("external", "TIASDataHub") -_SUBMODULE_SENT_ENTRIES = frozenset({"pyproject.toml", "README.md", "src"}) - -_PACKAGE_DIR = Path("src") / "tongue_seg_model" - - -@dataclass(frozen=True) -class PushEntry: - """送信するファイル 1 件. - - Attributes: - path: 手元の実ファイル. - arcname: リモートのプロジェクトルート基準の相対パス(POSIX 区切り). - size: バイト数. - """ - - path: Path - arcname: str - size: int - - -@dataclass(frozen=True) -class PushSelection: - """送信対象の選別結果. - - Attributes: - entries: 送信するファイル(arcname 順). - skipped_links: 送らなかったリンク(シンボリックリンク・ジャンクション)の - プロジェクトルート基準の相対パス(POSIX 区切り,順に並べたもの).除外対象の - ディレクトリ(`.venv/` 等)の中のリンクは含まない. - """ - - entries: tuple[PushEntry, ...] - skipped_links: tuple[str, ...] - - -def is_link(path: Path) -> bool: - """path がシンボリックリンクかジャンクション(Windows の reparse point)かを返す. - - `Path.is_symlink()` はジャンクションを見分けないため `os.path.isjunction` も見る. - リンク先が無い(壊れた)リンクも True. - - Args: - path: 調べるパス. - - Returns: - リンクなら True. - """ - return path.is_symlink() or os.path.isjunction(path) - - -def find_project_root(start: Path) -> Path: - """start から上方向にたどり,このリポジトリのルートを探す. - - Args: - start: 探索を始めるディレクトリ(通常はカレントディレクトリ). - - Returns: - `pyproject.toml` と `src/tongue_seg_model/` を持つディレクトリ. - - Raises: - ValueError: 見つからない場合. - """ - start = start.resolve() - for directory in (start, *start.parents): - if (directory / "pyproject.toml").is_file() and (directory / _PACKAGE_DIR).is_dir(): - return directory - raise ValueError( - f"{start} から上にプロジェクトルート(pyproject.toml と src/tongue_seg_model/)が" - "見つからない.リポジトリ内で実行する" - ) - - -def _is_excluded_file_name(name: str) -> bool: - """ファイル名だけで除外が決まるもの(重みの拡張子・環境変数ファイル)か.""" - lowered = name.lower() - if lowered == _ENV_FILE_NAME or lowered.startswith(_ENV_FILE_NAME + "."): - return True - return PurePosixPath(lowered).suffix in EXCLUDED_SUFFIXES - - -def is_excluded(rel_path: str, *, is_dir: bool = False) -> bool: - """プロジェクトルート基準の相対パスが push から除外されるかを返す. - - Args: - rel_path: POSIX 区切りの相対パス. - is_dir: ディレクトリなら True(拡張子・ファイル名による除外を当てはめない). - - Returns: - 除外対象なら True. - """ - parts = PurePosixPath(rel_path).parts - if not parts: - return False - # 大文字小文字を区別せずに比べる(手元の Windows では `Legacy/` も `legacy/` と同じ場所のため) - lowered = [part.lower() for part in parts] - if lowered[0] in EXCLUDED_ROOT_ENTRIES or any(part in EXCLUDED_DIR_NAMES for part in lowered): - return True - if not is_dir and _is_excluded_file_name(parts[-1]): - return True - depth = len(_SUBMODULE_PARTS) - return ( - len(parts) > depth - and parts[:depth] == _SUBMODULE_PARTS - and parts[depth] not in _SUBMODULE_SENT_ENTRIES - ) - - -def _walk_files(root: Path, skipped_links: list[str]) -> Iterator[PushEntry]: - """root 配下のファイルを,除外規則を適用しつつ決定的な順で列挙する. - - リンク(ファイル・ディレクトリとも)は送らず,その相対パスを skipped_links に足す. - os.walk は既定でシンボリックリンクのディレクトリに入らないが,ジャンクションには入りうる - ため,dirnames から明示的に除いて入らないようにする. - """ - for dirpath, dirnames, filenames in os.walk(root): - dir_rel = Path(dirpath).relative_to(root).as_posix() - prefix = "" if dir_rel == "." else f"{dir_rel}/" - kept: list[str] = [] - for dirname in sorted(dirnames): - rel = prefix + dirname - if is_excluded(rel, is_dir=True): - continue - if is_link(Path(dirpath) / dirname): - skipped_links.append(rel) - continue - kept.append(dirname) - dirnames[:] = kept - for filename in sorted(filenames): - rel = prefix + filename - path = Path(dirpath) / filename - if is_excluded(rel): - continue - if is_link(path): - skipped_links.append(rel) - continue - if not path.is_file(): - continue - yield PushEntry(path=path, arcname=rel, size=path.stat().st_size) - - -def select_push_files(root: Path) -> PushSelection: - """送信するファイルを選び,送らなかったリンクと合わせて返す. - - Args: - root: プロジェクトルート. - - Returns: - arcname 順に並べた送信対象と,送らなかったリンク. - """ - skipped_links: list[str] = [] - entries = sorted(_walk_files(root.resolve(), skipped_links), key=lambda entry: entry.arcname) - return PushSelection(tuple(entries), tuple(sorted(skipped_links))) - - -def collect_push_entries(root: Path) -> list[PushEntry]: - """送信するファイルの一覧を作る(リンクは含まない.`select_push_files` を参照). - - Args: - root: プロジェクトルート. - - Returns: - arcname 順に並べた送信対象. - """ - return list(select_push_files(root).entries) diff --git a/src/tongue_seg_model/remote/gpu.py b/src/tongue_seg_model/remote/gpu.py deleted file mode 100644 index fc6f6bd..0000000 --- a/src/tongue_seg_model/remote/gpu.py +++ /dev/null @@ -1,729 +0,0 @@ -"""サーバの状況(tmux セッション・GPU・計算プロセス)の解析と,GPU の選択(純関数). - -ssh を呼ぶ部分は CLI 側にあり,ここは ssh の出力文字列を受け取って解釈するだけにする -(テストで ssh・nvidia-smi をモックせず,出力の文字列で固定できるようにするため). -判定と選択の規則は TIASJudgeModel の SPEC_03「GPU の空き判定と選択」に従う. - -TIASJudgeModel の `tias_judge_model.remote.gpu` の移植.接続したユーザー名を probe の出力から -取るようにした(設定の `user` を省略できるようにしたため.`ProbeOutput.remote_user`). -""" - -from __future__ import annotations - -from collections.abc import Mapping, Sequence -from dataclasses import dataclass -from enum import StrEnum - -from tongue_seg_model.remote.commands import ( - PROBE_APPS_MARKER, - PROBE_APPS_RC_PREFIX, - PROBE_END_MARKER, - PROBE_GPU_RC_PREFIX, - PROBE_GPUS_MARKER, - PROBE_JOB_PREFIX, - PROBE_OTHER_PREFIX, - PROBE_OWNERS_MARKER, - PROBE_PMON_MARKER, - PROBE_SAMPLES_MARKER, - PROBE_SESSIONS_MARKER, - PROBE_USER_PREFIX, -) -from tongue_seg_model.remote.config import GpuFreeThreshold, ServerConfig -from tongue_seg_model.remote.observe import ( - GpuSample, - GpuUsage, - UsagePattern, - classify_usage_pattern, - parse_gpu_samples, - parse_pmon, - summarize_samples, -) - -# nvidia-smi --query-gpu の列数(index,uuid,name,memory.used,memory.total,utilization.gpu) -_GPU_COLUMNS = 6 -# nvidia-smi --query-compute-apps の列数(gpu_uuid,pid,used_memory) -_APP_COLUMNS = 3 - - -class GpuState(StrEnum): - """GPU の状態(選ぶ優先順は UNUSED → SHARED.BUSY・UNKNOWN は選ばない).""" - - UNUSED = "未使用" - SHARED = "空き(利用者あり)" - BUSY = "使用中" - UNKNOWN = "状態不明" - - -# 自動選択で順に探す状態(未使用がサーバの優先順位より優先される) -SELECTABLE_STATES = (GpuState.UNUSED, GpuState.SHARED) - - -@dataclass(frozen=True) -class GpuProcess: - """GPU 上の計算プロセス 1 件. - - Attributes: - pid: プロセス ID. - used_memory_mib: 使用メモリ(MiB).取れなければ None. - user: 所有ユーザー.ps で取れなければ None. - elapsed_sec: 起動からの経過秒数.ps で取れなければ None. - max_sm_percent: 観測中の SM 使用率の最大(pmon).取れなければ None. - """ - - pid: int - used_memory_mib: int | None - user: str | None - elapsed_sec: int | None = None - max_sm_percent: int | None = None - - -@dataclass(frozen=True) -class ProcessOwner: - """ps で取ったプロセスの所有者と経過時間. - - Attributes: - user: 所有ユーザー. - elapsed_sec: 起動からの経過秒数.取れなければ None. - """ - - user: str - elapsed_sec: int | None - - -@dataclass(frozen=True) -class GpuInfo: - """GPU 1 基の状況. - - Attributes: - index: GPU 番号.解釈できなければ None. - uuid: GPU の UUID(計算プロセスとの対応付けに使う).解釈できない行では空文字. - name: GPU の名前(解釈できない行では空文字). - memory_used_mib: 使用中メモリ(MiB.観測前の瞬間値).解釈できなければ None. - memory_total_mib: 総メモリ(MiB).解釈できなければ None. - utilization_percent: 使用率(%.観測前の瞬間値).解釈できなければ None. - state: 判定の結果. - processes: この GPU 上の計算プロセス. - processes_known: 計算プロセスの一覧が取れたか(False なら利用者不明). - usage: 観測の要約(観測しないときは瞬間値 1 つの要約).サンプルが無ければ None. - pattern: 使い方の型(表示専用).決められなければ None. - """ - - index: int | None - uuid: str - name: str - memory_used_mib: int | None - memory_total_mib: int | None - utilization_percent: int | None - state: GpuState - processes: tuple[GpuProcess, ...] = () - processes_known: bool = False - usage: GpuUsage | None = None - pattern: UsagePattern | None = None - - -@dataclass(frozen=True) -class ProbeOutput: - """probe コマンド(`build_probe_command`)の出力を解釈した結果. - - Attributes: - jobs: このツールのジョブ(ジョブログがある tmux セッション)の名前. - other_sessions: それ以外の tmux セッションの名前. - gpu_query_ok: GPU の状態の取得が成功したか.False なら GPU はすべて候補から外す. - processes_query_ok: 計算プロセスの一覧の取得・解釈が成功したか.False なら閾値内の - GPU はすべて「空き(利用者あり)」になる. - gpus: GPU の一覧(GPU の状態の取得が失敗したときは空). - observe_sec: 観測した秒数(0 なら瞬間値のみで判定した). - pmon_ok: プロセス別の観測(pmon)が得られたか(False なら表示を省くだけ). - remote_user: 接続したユーザー名(`id -un`).取れなければ空文字. - """ - - jobs: tuple[str, ...] - other_sessions: tuple[str, ...] - gpu_query_ok: bool - processes_query_ok: bool - gpus: tuple[GpuInfo, ...] - observe_sec: int = 0 - pmon_ok: bool = False - remote_user: str = "" - - @property - def sessions(self) -> tuple[str, ...]: - """すべての tmux セッション名(ジョブとそれ以外).""" - return self.jobs + self.other_sessions - - -@dataclass(frozen=True) -class ServerProbe: - """サーバ 1 台の状況. - - Attributes: - server: サーバの設定. - output: probe の結果.接続できなかったときは None. - error: 接続できなかった理由(表示用.ssh の標準エラーの最終行等). - """ - - server: ServerConfig - output: ProbeOutput | None - error: str = "" - - @property - def reachable(self) -> bool: - """接続できたか.""" - return self.output is not None - - @property - def own_user(self) -> str: - """自分(接続したユーザー)の名前. - - probe で取れなければ設定の `user`,それも無ければ空文字. - """ - if self.output is not None and self.output.remote_user: - return self.output.remote_user - return self.server.user or "" - - -@dataclass(frozen=True) -class GpuSelection: - """run が使う GPU. - - Attributes: - server: 選んだサーバ. - gpu_index: 選んだ GPU 番号. - state: 選んだ時点の GPU の状態. - gpu: 選んだ GPU の状況(利用者の警告表示用.状態を取れなかったときは None). - forced: 使用中・状態不明の GPU を `--force` で選んだか(警告を出す). - own_user: 自分(接続したユーザー)の名前(利用者の表示で「自分」とするため). - """ - - server: ServerConfig - gpu_index: int - state: GpuState - gpu: GpuInfo | None = None - forced: bool = False - own_user: str = "" - - -def classify_gpu( - memory_used_mib: int, - utilization_percent: int, - threshold: GpuFreeThreshold, - process_count: int | None, -) -> GpuState: - """閾値と計算プロセスの数から GPU の状態を判定する. - - 観測するときは,使用中メモリ・使用率に**観測中の最大値**を渡す(一度でも閾値を超えた - GPU を使用中にするため). - - Args: - memory_used_mib: 使用中メモリ(MiB.観測中の最大). - utilization_percent: 使用率(%.観測中の最大). - threshold: 空き判定の閾値. - process_count: 計算プロセスの数(所有者を問わない).一覧が取れなければ None. - - Returns: - 閾値を満たさなければ `BUSY`.閾値内で計算プロセスが 0 なら `UNUSED`, - 1 つ以上または不明(None)なら `SHARED`(未使用と誤認しないため). - """ - within = ( - memory_used_mib < threshold.max_memory_used_mib - and utilization_percent < threshold.max_utilization_percent - ) - if not within: - return GpuState.BUSY - return GpuState.UNUSED if process_count == 0 else GpuState.SHARED - - -def _parse_int(text: str) -> int | None: - """整数として解釈できれば返す(`[N/A]` 等は None).""" - try: - return int(text.strip()) - except ValueError: - return None - - -def _is_valid_uuid(text: str) -> bool: - """nvidia-smi の UUID として使える値か(空・`[N/A]` 等を除く).""" - return bool(text) and not text.startswith("[") and " " not in text - - -def parse_process_owners(text: str) -> dict[int, ProcessOwner]: - """probe の所有者の節(` <ユーザー> <経過秒>` の行)を解釈する. - - ユーザー名が無い行(ps で所有者を取れなかったプロセス)と解釈できない行は含めない - (所有者・経過時間は表示用で,判定には使わないため). - - Args: - text: 所有者の節の出力. - - Returns: - pid から所有者・経過秒数への対応. - """ - owners: dict[int, ProcessOwner] = {} - for line in text.splitlines(): - tokens = line.split() - if len(tokens) < 2: - continue - pid = _parse_int(tokens[0]) - if pid is None: - continue - elapsed = _parse_int(tokens[2]) if len(tokens) >= 3 else None - owners[pid] = ProcessOwner(tokens[1], elapsed) - return owners - - -def parse_compute_apps( - text: str, - owners: Mapping[int, ProcessOwner], - sm_peaks: Mapping[int, int] | None = None, -) -> dict[str, tuple[GpuProcess, ...]] | None: - """`nvidia-smi --query-compute-apps=gpu_uuid,pid,used_memory` の出力を GPU ごとにまとめる. - - Args: - text: nvidia-smi の標準出力(空なら計算プロセスは 0). - owners: pid から所有者・経過秒数への対応(`parse_process_owners`). - sm_peaks: pid から観測中の SM 使用率の最大への対応(`parse_pmon`).無ければ None. - - Returns: - GPU の UUID から計算プロセスへの対応.1 行でも解釈できなければ None - (一覧を信用せず利用者不明として扱うため). - """ - apps: dict[str, list[GpuProcess]] = {} - for line in text.splitlines(): - if not line.strip(): - continue - columns = [column.strip() for column in line.split(",")] - if len(columns) != _APP_COLUMNS or not _is_valid_uuid(columns[0]): - return None - pid = _parse_int(columns[1]) - if pid is None: - return None - owner = owners.get(pid) - process = GpuProcess( - pid=pid, - used_memory_mib=_parse_int(columns[2]), - user=owner.user if owner else None, - elapsed_sec=owner.elapsed_sec if owner else None, - max_sm_percent=sm_peaks.get(pid) if sm_peaks is not None else None, - ) - apps.setdefault(columns[0], []).append(process) - return {uuid: tuple(processes) for uuid, processes in apps.items()} - - -def parse_nvidia_smi_line( - line: str, - threshold: GpuFreeThreshold, - processes: Mapping[str, Sequence[GpuProcess]] | None, - samples: Sequence[GpuSample] | None = None, -) -> GpuInfo: - """`nvidia-smi --query-gpu`(`--format=csv,noheader,nounits`)の 1 行を解釈して判定する. - - 列数不足・数値でない値(`[N/A]` 等)の行は `UNKNOWN` とする.GPU 名にカンマを含む場合に - 備え,先頭 2 列を index・uuid,末尾 3 列を数値として,その間を名前とする. - - 観測したとき(`samples` が None でない)は,観測中の最大値(とこの行の瞬間値の大きい方)で - 閾値を判定し,サンプルが 1 つも無ければ `UNKNOWN` とする.観測しないとき(None)は - この行の瞬間値で判定する. - - Args: - line: nvidia-smi の出力 1 行. - threshold: 空き判定の閾値. - processes: GPU の UUID から計算プロセスへの対応(`parse_compute_apps`). - 計算プロセスの一覧が取れなかったときは None(閾値内なら `SHARED` になる). - samples: この GPU の観測サンプル.観測しないときは None. - - Returns: - GPU の状況. - """ - columns = [column.strip() for column in line.split(",")] - if len(columns) < _GPU_COLUMNS: - index = _parse_int(columns[0]) if columns else None - return GpuInfo(index, "", "", None, None, None, GpuState.UNKNOWN) - index = _parse_int(columns[0]) - uuid = columns[1] - name = ", ".join(columns[2:-3]) - used, total, util = (_parse_int(value) for value in columns[-3:]) - # UUID が取れない GPU は計算プロセスと対応付けられないので,利用者不明として扱う - known = processes is not None and _is_valid_uuid(uuid) - gpu_processes = tuple(processes.get(uuid, ())) if known and processes is not None else () - count = len(gpu_processes) if known else None - - if index is None or used is None or total is None or util is None: - return GpuInfo(index, uuid, name, used, total, util, GpuState.UNKNOWN, gpu_processes, known) - observed = samples is not None - usage = summarize_samples(samples if samples is not None else [GpuSample(util, used)]) - if usage is None: - # 観測したのにサンプルが 1 つも得られない GPU は使わない - state = GpuState.UNKNOWN - pattern = None - else: - max_used = max(usage.max_memory_used_mib, used) if observed else used - max_util = max(usage.max_utilization_percent, util) if observed else util - state = classify_gpu(max_used, max_util, threshold, count) - pattern = classify_usage_pattern(usage, count) - return GpuInfo( - index, uuid, name, used, total, util, state, gpu_processes, known, usage, pattern - ) - - -def parse_nvidia_smi_output( - text: str, - threshold: GpuFreeThreshold, - processes: Mapping[str, Sequence[GpuProcess]] | None, - samples: Mapping[int, Sequence[GpuSample]] | None = None, -) -> list[GpuInfo]: - """`nvidia-smi --query-gpu` の出力全体を 1 行 1 GPU として解釈する(空行は無視する). - - Args: - text: nvidia-smi の標準出力. - threshold: 空き判定の閾値. - processes: GPU の UUID から計算プロセスへの対応.一覧が取れなかったときは None. - samples: GPU 番号から観測サンプルへの対応(`parse_gpu_samples`).観測しないときは - None(瞬間値で判定する).観測したのに該当する GPU のサンプルが無ければ状態不明. - - Returns: - 出力順の GPU の一覧. - """ - gpus: list[GpuInfo] = [] - for line in text.splitlines(): - if not line.strip(): - continue - gpu_samples: Sequence[GpuSample] | None = None - if samples is not None: - index = _parse_int(line.split(",", 1)[0]) - gpu_samples = samples.get(index, []) if index is not None else [] - gpus.append(parse_nvidia_smi_line(line, threshold, processes, gpu_samples)) - return gpus - - -def parse_probe_output(text: str, threshold: GpuFreeThreshold) -> ProbeOutput: - """probe コマンド(`build_probe_command`)の標準出力を解釈する. - - 目印より前の行(ログインシェルが出す挨拶等)は無視する.計算プロセスの節が欠けている・ - 終了コードが 0 でない・解釈できない場合は,計算プロセスの一覧を「取得できない」とする. - `threshold.observe_sec > 0` なら観測したものとして判定し,観測の節が欠けていれば - (サーバで一時ディレクトリを作れなかった等)各 GPU は状態不明になる. - - Args: - text: probe コマンドの標準出力. - threshold: 空き判定の閾値と観測の設定(probe コマンドの組み立てに使ったもの). - - Returns: - 解釈した結果. - - Raises: - ValueError: 必須の目印(セッション・GPU・GPU の終了コード・終端)がそろっていない - (出力が途中で切れた等)場合. - """ - section: str | None = None - jobs: list[str] = [] - others: list[str] = [] - lines: dict[str, list[str]] = { - "gpus": [], - "samples": [], - "pmon": [], - "apps": [], - "owners": [], - } - gpu_rc: int | None = None - apps_rc: int | None = None - remote_user = "" - seen_sessions = ended = False - for line in text.splitlines(): - if line.startswith(PROBE_USER_PREFIX) and section is None and not seen_sessions: - remote_user = line[len(PROBE_USER_PREFIX) :].strip() - elif line == PROBE_SESSIONS_MARKER: - section, seen_sessions = "sessions", True - elif line == PROBE_GPUS_MARKER: - section = "gpus" - elif line.startswith(PROBE_GPU_RC_PREFIX) and section == "gpus": - gpu_rc = _parse_int(line[len(PROBE_GPU_RC_PREFIX) :]) - section = None - elif line == PROBE_SAMPLES_MARKER: - section = "samples" - elif line == PROBE_PMON_MARKER: - section = "pmon" - elif line == PROBE_APPS_MARKER: - section = "apps" - elif line.startswith(PROBE_APPS_RC_PREFIX) and section == "apps": - apps_rc = _parse_int(line[len(PROBE_APPS_RC_PREFIX) :]) - section = None - elif line == PROBE_OWNERS_MARKER: - section = "owners" - elif line == PROBE_END_MARKER: - section, ended = None, True - elif section == "sessions": - if line.startswith(PROBE_JOB_PREFIX): - jobs.append(line[len(PROBE_JOB_PREFIX) :]) - elif line.startswith(PROBE_OTHER_PREFIX): - others.append(line[len(PROBE_OTHER_PREFIX) :]) - elif section in lines: - lines[section].append(line) - if not (seen_sessions and ended) or gpu_rc is None: - raise ValueError("サーバの状況の出力を解釈できない(目印が欠けている)") - - texts = {name: "\n".join(section_lines) for name, section_lines in lines.items()} - gpu_ok = gpu_rc == 0 - observed = threshold.observe_sec > 0 - sm_peaks = parse_pmon(texts["pmon"]) if observed else None - processes = None - if gpu_ok and apps_rc == 0: - owners = parse_process_owners(texts["owners"]) - processes = parse_compute_apps(texts["apps"], owners, sm_peaks) - samples = parse_gpu_samples(texts["samples"]) if observed else None - gpus = ( - tuple(parse_nvidia_smi_output(texts["gpus"], threshold, processes, samples)) - if gpu_ok - else () - ) - return ProbeOutput( - jobs=tuple(jobs), - other_sessions=tuple(others), - gpu_query_ok=gpu_ok, - processes_query_ok=processes is not None, - gpus=gpus, - observe_sec=threshold.observe_sec if observed else 0, - pmon_ok=sm_peaks is not None, - remote_user=remote_user, - ) - - -def _find_probe(probes: Sequence[ServerProbe], name: str) -> ServerProbe: - """名前(大文字小文字を区別しない)でサーバの状況を探す.""" - for probe in probes: - if probe.server.name.lower() == name.lower(): - return probe - known = ", ".join(probe.server.name for probe in probes) - raise ValueError(f"サーバ {name!r} は設定に無い(設定済み: {known})") - - -def _select_explicit(probe: ServerProbe, gpu_index: int, *, force: bool) -> GpuSelection: - """`--server --gpu` で指定された GPU を検証して返す.""" - output = probe.output - if output is None: - raise RuntimeError("接続できないサーバの GPU を検証しようとした") - gpu = next((g for g in output.gpus if g.index == gpu_index), None) - if gpu is None: - # 一覧を正しく取れていて該当が無いなら,存在しない GPU の指定である - if output.gpu_query_ok and all(g.index is not None for g in output.gpus): - raise ValueError(f"{probe.server.name} に GPU {gpu_index} は無い") - state = GpuState.UNKNOWN - else: - state = gpu.state - if state in SELECTABLE_STATES: - return GpuSelection(probe.server, gpu_index, state, gpu, own_user=probe.own_user) - if not force: - raise ValueError( - f"{probe.server.name} の GPU {gpu_index} は{state}である" - "(使うなら --force を付ける.他のユーザーが使用中の可能性がある)" - ) - return GpuSelection(probe.server, gpu_index, state, gpu, forced=True, own_user=probe.own_user) - - -def check_selection_options(*, server_name: str | None, gpu_index: int | None, force: bool) -> None: - """GPU 指定の組み合わせを検証する(サーバへ問い合わせる前に弾けるよう独立させている). - - Args: - server_name: `--server` の値. - gpu_index: `--gpu` の値. - force: `--force` の有無. - - Raises: - ValueError: `--gpu` だけの指定,`--gpu` 無しの `--force`,負の GPU 番号の場合. - """ - if gpu_index is not None and server_name is None: - raise ValueError("--gpu を指定するときは --server も指定する(どのサーバか曖昧になるため)") - if force and gpu_index is None: - raise ValueError("--force は --server と --gpu で GPU を指定したときだけ使える") - if gpu_index is not None and gpu_index < 0: - raise ValueError(f"GPU 番号は 0 以上: {gpu_index}") - - -def check_cpu_options(*, gpu_index: int | None, force: bool, observe_sec: int | None) -> None: - """`--cpu` と GPU 関連のオプションの組み合わせを検証する(ssh より前に弾くため独立させている). - - Args: - gpu_index: `--gpu` の値. - force: `--force` の有無. - observe_sec: `--observe` の値. - - Raises: - ValueError: `--cpu` と `--gpu`・`--force`・`--observe` のいずれかを同時に指定した場合. - """ - conflicts = [ - option - for option, given in ( - ("--gpu", gpu_index is not None), - ("--force", force), - ("--observe", observe_sec is not None), - ) - if given - ] - if conflicts: - raise ValueError( - f"--cpu は {'・'.join(conflicts)} と同時に指定できない" - "(--cpu では GPU を観測・選択しない)" - ) - - -def select_cpu_server( - probes: Sequence[ServerProbe], - *, - server_name: str | None = None, - include_not_ready: bool = False, -) -> ServerConfig | None: - """`run --cpu`(GPU を使わないジョブ)を実行するサーバを選ぶ(SPEC_03「run」). - - `server_name` を指定したらそのサーバ.省略時は候補サーバ(`data_ready` のもの. - `include_not_ready` なら全サーバ)を priority 昇順(同値は `probes` の順)に見て,最初に - 接続できたものを選ぶ.GPU の状態は見ない. - - Args: - probes: 各サーバの状況(設定の記載順で渡す.同じ priority の順位に使う). - server_name: `--server` の値. - include_not_ready: `data_ready: false` のサーバも候補にする(`--no-data`). - - Returns: - 選んだサーバ.自動選択で接続できる候補サーバが無ければ None. - - Raises: - ValueError: 指定したサーバが設定に無い・データ未配置(`include_not_ready` 無し)・ - 接続不可の場合. - """ - if server_name is not None: - probe = _find_probe(probes, server_name) - if not probe.server.data_ready and not include_not_ready: - raise ValueError( - f"{probe.server.name} は学習データのバンドルが未配置(data_ready: false)である" - "(データを使わないジョブなら --no-data を付ける)" - ) - if not probe.reachable: - raise ValueError(f"{probe.server.name} に接続できない({probe.error})") - return probe.server - candidates = sorted( - (p for p in probes if p.reachable and (include_not_ready or p.server.data_ready)), - key=lambda p: p.server.priority, - ) - return candidates[0].server if candidates else None - - -def select_gpu( - probes: Sequence[ServerProbe], - *, - server_name: str | None = None, - gpu_index: int | None = None, - force: bool = False, - include_not_ready: bool = False, -) -> GpuSelection | None: - """run が使う GPU を選ぶ(SPEC_03「GPU の空き判定と選択」). - - 自動選択では,候補サーバ(`data_ready` のもの.`include_not_ready` なら全サーバ. - `server_name` を指定したらそのサーバのみ)全体を通して,まず「未使用」を priority 昇順 - (同値は `probes` の順)→ GPU 番号の昇順で探し,無ければ同じ順で「空き(利用者あり)」を - 探す(未使用がサーバの優先順位より優先される).接続できないサーバと GPU の状態の取得に - 失敗したサーバは候補から外す. - - Args: - probes: 各サーバの状況(設定の記載順で渡す.同じ priority の順位に使う). - server_name: `--server` の値. - gpu_index: `--gpu` の値(`server_name` が必須). - force: 指定した GPU が使用中・状態不明でも選ぶ(`gpu_index` 指定時のみ有効). - include_not_ready: `data_ready: false` のサーバも候補にする(`--no-data`). - - Returns: - 選んだ GPU.自動選択で未使用・空き(利用者あり)のどちらも無ければ None. - - Raises: - ValueError: 指定の組み合わせが不正(`--gpu` だけ・`--force` だけ),指定したサーバが - 設定に無い・データ未配置・接続不可,指定した GPU が無い・使用中・状態不明 - (`force` 無し)の場合. - """ - check_selection_options(server_name=server_name, gpu_index=gpu_index, force=force) - if server_name is not None: - probe = _find_probe(probes, server_name) - if not probe.server.data_ready and not include_not_ready: - raise ValueError( - f"{probe.server.name} は学習データのバンドルが未配置(data_ready: false)である" - "(データを使わないジョブなら --no-data を付ける)" - ) - if not probe.reachable: - raise ValueError(f"{probe.server.name} に接続できない({probe.error})") - if gpu_index is not None: - return _select_explicit(probe, gpu_index, force=force) - candidates = [probe] - else: - candidates = sorted( - (p for p in probes if p.reachable and (include_not_ready or p.server.data_ready)), - key=lambda p: p.server.priority, - ) - - for wanted in SELECTABLE_STATES: - for probe in candidates: - output = probe.output - if output is None or not output.gpu_query_ok: - continue - for gpu in sorted( - (g for g in output.gpus if g.index is not None), key=lambda g: g.index or 0 - ): - if gpu.state is wanted and gpu.index is not None: - return GpuSelection( - probe.server, gpu.index, gpu.state, gpu, own_user=probe.own_user - ) - return None - - -def display_user_name(user: str | None, own_user: str) -> str: - """計算プロセスの所有ユーザーを表示用の名前にする. - - Args: - user: 所有ユーザー.ps で取れなければ None. - own_user: 自分のユーザー名(ssh の接続ユーザー).分からなければ空文字. - - Returns: - 自分なら「自分」,取れなければ「不明」,それ以外はユーザー名. - """ - if user is None: - return "不明" - if own_user and user == own_user: - return "自分" - return user - - -def gpu_users(gpu: GpuInfo, own_user: str) -> list[str]: - """GPU の計算プロセスの所有ユーザーを表示用に並べる(重複は 1 つにまとめ,出現順). - - Args: - gpu: GPU の状況. - own_user: 自分のユーザー名(ssh の接続ユーザー).一致するものは「自分」と表示する. - - Returns: - ユーザー名の一覧(自分は「自分」,所有者を取れなかったものは「不明」). - """ - names: list[str] = [] - for process in gpu.processes: - name = display_user_name(process.user, own_user) - if name not in names: - names.append(name) - return names - - -def servers_with_session( - probes: Sequence[ServerProbe], name: str, *, jobs_only: bool -) -> list[ServerProbe]: - """指定した名前の tmux セッションがあるサーバを返す. - - Args: - probes: 各サーバの状況(接続できなかったサーバは対象外). - name: セッション(ジョブ)名. - jobs_only: True ならこのツールのジョブ(ジョブログがあるもの)だけを見る. - - Returns: - 該当するサーバの状況(`probes` の順). - """ - found: list[ServerProbe] = [] - for probe in probes: - if probe.output is None: - continue - names = probe.output.jobs if jobs_only else probe.output.sessions - if name in names: - found.append(probe) - return found diff --git a/src/tongue_seg_model/remote/observe.py b/src/tongue_seg_model/remote/observe.py deleted file mode 100644 index ec8903e..0000000 --- a/src/tongue_seg_model/remote/observe.py +++ /dev/null @@ -1,191 +0,0 @@ -"""GPU の観測結果(サンプリング・pmon)の解析と,使い方の型の判定(純関数). - -観測は probe コマンドがサーバ側で行い(`build_probe_command`),ここはその出力文字列を -解釈するだけにする.使い方の型は表示専用で,空き判定には使わない(TIASJudgeModel の -SPEC_03「使い方の型」). - -TIASJudgeModel の `tias_judge_model.remote.observe` の移植(変更なし). -""" - -from __future__ import annotations - -from collections.abc import Sequence -from dataclasses import dataclass -from enum import StrEnum - -# 0% を超えたサンプルがこの割合以上なら「常時使用」 -CONSTANT_USE_RATIO = 0.8 -# nvidia-smi --query-gpu=index,utilization.gpu,memory.used の列数 -_SAMPLE_COLUMNS = 3 - - -class UsagePattern(StrEnum): - """観測中の使用率から付ける使い方の型(表示専用).""" - - CONSTANT = "常時使用" - INTERMITTENT = "断続的に使用" - MEMORY_ONLY = "メモリ確保のみ" - IDLE = "未使用" - - -@dataclass(frozen=True) -class GpuSample: - """GPU 1 基の 1 回分のサンプル. - - Attributes: - utilization_percent: 使用率(%). - memory_used_mib: 使用中メモリ(MiB). - """ - - utilization_percent: int - memory_used_mib: int - - -@dataclass(frozen=True) -class GpuUsage: - """観測中のサンプルの要約. - - Attributes: - sample_count: サンプル数(1 以上). - active_count: 使用率が 0% を超えたサンプル数. - mean_utilization_percent: 使用率の平均(%). - max_utilization_percent: 使用率の最大(%). - max_memory_used_mib: 使用中メモリの最大(MiB). - """ - - sample_count: int - active_count: int - mean_utilization_percent: float - max_utilization_percent: int - max_memory_used_mib: int - - -def _parse_int(text: str) -> int | None: - """整数として解釈できれば返す(`[N/A]`・`-` 等は None).""" - try: - return int(text.strip()) - except ValueError: - return None - - -def parse_gpu_samples(text: str) -> dict[int, list[GpuSample]]: - """観測のサンプリング出力(`index, 使用率, 使用中メモリ` の CSV)を GPU ごとにまとめる. - - `timeout` で打ち切った最後の行が途中で切れていることがあるため,解釈できない行は - 読み飛ばす(そのぶんサンプルが減るだけで,サンプルが 0 件の GPU は状態不明になる). - - Args: - text: サンプリングの出力. - - Returns: - GPU 番号からサンプル(出力順)への対応. - """ - samples: dict[int, list[GpuSample]] = {} - for line in text.splitlines(): - columns = line.split(",") - if len(columns) != _SAMPLE_COLUMNS: - continue - index, util, memory = (_parse_int(column) for column in columns) - if index is None or util is None or memory is None: - continue - samples.setdefault(index, []).append(GpuSample(util, memory)) - return samples - - -def summarize_samples(samples: Sequence[GpuSample]) -> GpuUsage | None: - """サンプルを要約する. - - Args: - samples: GPU 1 基のサンプル. - - Returns: - 要約.サンプルが無ければ None. - """ - if not samples: - return None - utils = [sample.utilization_percent for sample in samples] - return GpuUsage( - sample_count=len(samples), - active_count=sum(1 for util in utils if util > 0), - mean_utilization_percent=sum(utils) / len(utils), - max_utilization_percent=max(utils), - max_memory_used_mib=max(sample.memory_used_mib for sample in samples), - ) - - -def classify_usage_pattern(usage: GpuUsage, process_count: int | None) -> UsagePattern | None: - """観測中の使用率から使い方の型を付ける(表示専用). - - Args: - usage: 観測の要約. - process_count: 計算プロセスの数.一覧が取れなければ None. - - Returns: - 使い方の型.0% を超えたサンプルが無く,計算プロセスの有無も分からなければ None. - """ - if usage.active_count > 0: - if usage.active_count >= CONSTANT_USE_RATIO * usage.sample_count: - return UsagePattern.CONSTANT - return UsagePattern.INTERMITTENT - if process_count is None: - return None - return UsagePattern.MEMORY_ONLY if process_count > 0 else UsagePattern.IDLE - - -def parse_pmon(text: str) -> dict[int, int] | None: - """`nvidia-smi pmon -s u` の出力から,計算プロセスごとの SM 使用率の最大を求める. - - `#` で始まる行はヘッダ(1 行目が列名 `# gpu pid type sm ...`,2 行目が単位).列の位置は - ヘッダの列名から決める.種別に `C`(計算)を含む行だけを数え,`G`(描画)だけの行は除く. - 値が `-` の行(その回はプロセスが無い・値が取れない)は読み飛ばす. - - Args: - text: pmon の出力. - - Returns: - pid から SM 使用率の最大(%)への対応.列名のヘッダが無い(pmon が失敗・未対応) - ときは None(表示を省くだけで,判定には影響させない). - """ - columns: list[str] | None = None - peaks: dict[int, int] = {} - for line in text.splitlines(): - stripped = line.strip() - if not stripped: - continue - if stripped.startswith("#"): - names = stripped.lstrip("#").split() - if columns is None and {"pid", "type", "sm"} <= set(names): - columns = names - continue - if columns is None: - continue - values = stripped.split() - if len(values) < len(columns) - 1: - continue - row = dict(zip(columns, values, strict=False)) - pid = _parse_int(row.get("pid", "-")) - sm = _parse_int(row.get("sm", "-")) - if pid is None or sm is None or "C" not in row.get("type", ""): - continue - peaks[pid] = max(peaks.get(pid, 0), sm) - return None if columns is None else peaks - - -def format_elapsed(seconds: int) -> str: - """経過秒数を読みやすい単位で返す(例: `45 秒`・`12.5 分`・`27.7 時間`・`3.2 日`). - - 48 時間までは時間で示す(日単位にすると 1 日前後の違いが読み取りにくいため). - - Args: - seconds: 経過秒数(0 以上). - - Returns: - 表示用の文字列. - """ - if seconds < 60: - return f"{seconds} 秒" - if seconds < 3600: - return f"{seconds / 60:.1f} 分" - if seconds < 48 * 3600: - return f"{seconds / 3600:.1f} 時間" - return f"{seconds / 86400:.1f} 日" diff --git a/src/tongue_seg_model/remote/report.py b/src/tongue_seg_model/remote/report.py deleted file mode 100644 index cd61f6a..0000000 --- a/src/tongue_seg_model/remote/report.py +++ /dev/null @@ -1,197 +0,0 @@ -"""サーバの状況(GPU 一覧・実行中ジョブ)を表示用の文字列に整形する純関数群. - -TIASJudgeModel の `tias_judge_model.remote.report` の移植.接続先の表示を `[user@]host` にし, -「自分」の判定に probe で取ったユーザー名を使うようにした. -""" - -from __future__ import annotations - -from collections.abc import Sequence - -from tongue_seg_model.remote.gpu import ( - GpuInfo, - GpuProcess, - GpuSelection, - GpuState, - ServerProbe, - display_user_name, - gpu_users, -) -from tongue_seg_model.remote.observe import format_elapsed - -# 計算プロセスの一覧が取れなかった GPU の利用者の表示(run の警告と GPU 一覧で共通) -_UNKNOWN_USERS = "利用者不明(計算プロセスの一覧を取得できない)" - - -def _format_value(value: int | None, unit: str) -> str: - return "?" if value is None else f"{value}{unit}" - - -def describe_gpu_users(gpu: GpuInfo, own_user: str) -> str: - """GPU の利用者(計算プロセスの所有ユーザー)を表示用に 1 句で返す. - - Args: - gpu: GPU の状況. - own_user: 自分のユーザー名(ssh の接続ユーザー.一致するものは「自分」). - - Returns: - `利用者: 自分, alice` の形.計算プロセスの一覧が取れなければ `利用者不明`, - 計算プロセスが無ければ空文字. - """ - if not gpu.processes_known: - return _UNKNOWN_USERS - users = gpu_users(gpu, own_user) - return f"利用者: {', '.join(users)}" if users else "" - - -def describe_usage(gpu: GpuInfo, *, observed: bool) -> str: - """GPU の使い方(型と使用率)を表示用に 1 句で返す. - - Args: - gpu: GPU の状況. - observed: 観測したか(False なら瞬間値だけを示し,型は付けない). - - Returns: - 観測したときは `断続的に使用・平均 21%・最大 74%(0% 超 7/20)` の形.観測サンプルが - 無ければ `観測できない`.観測しないときは `使用率 29%(瞬間値)`. - """ - usage = gpu.usage - if not observed: - return f"使用率 {_format_value(gpu.utilization_percent, '%')}(瞬間値)" - if usage is None: - return "観測できない(サンプル無し)" - pattern = gpu.pattern.value if gpu.pattern is not None else "使い方不明" - return ( - f"{pattern}・平均 {usage.mean_utilization_percent:.0f}%" - f"・最大 {usage.max_utilization_percent}%" - f"(0% 超 {usage.active_count}/{usage.sample_count})" - ) - - -def describe_process(process: GpuProcess, own_user: str) -> str: - """計算プロセス 1 件を表示用に 1 句で返す. - - Args: - process: 計算プロセス. - own_user: 自分のユーザー名(ssh の接続ユーザー.一致するものは「自分」). - - Returns: - `ando 経過 27.7 時間 SM 最大 74%` の形(取れない項目は省く.所有者が取れなければ - `不明`). - """ - parts = [display_user_name(process.user, own_user)] - if process.elapsed_sec is not None: - parts.append(f"経過 {format_elapsed(process.elapsed_sec)}") - if process.max_sm_percent is not None: - parts.append(f"SM 最大 {process.max_sm_percent}%") - return " ".join(parts) - - -def _format_gpu_lines(gpu: GpuInfo, own_user: str, *, observed: bool) -> list[str]: - index = "?" if gpu.index is None else str(gpu.index) - memory = f"{_format_value(gpu.memory_used_mib, '')} / {_format_value(gpu.memory_total_mib, '')}" - lines = [ - f" GPU {index:>2} {gpu.name} メモリ {memory} MiB [{gpu.state.value}]" - f" {describe_usage(gpu, observed=observed)}" - ] - if gpu.state is GpuState.UNKNOWN and gpu.usage is None and not gpu.processes: - return lines - if not gpu.processes_known: - lines.append(f" {_UNKNOWN_USERS}") - else: - lines.extend(f" - {describe_process(p, own_user)}" for p in gpu.processes) - return lines - - -def format_server_header(probe: ServerProbe) -> str: - """サーバ 1 台の見出し行を返す. - - Args: - probe: サーバの状況. - - Returns: - `[名前] 接続先 priority=N データ=... 観測 10 秒` の形の 1 行(接続不可なら理由を - 添える). - """ - server = probe.server - data = "配置済み" if server.data_ready else "未配置" - header = f"[{server.name}] {server.destination} priority={server.priority} データ={data}" - if probe.output is None: - reason = f"({probe.error})" if probe.error else "" - return f"{header} 接続不可{reason}" - observe_sec = probe.output.observe_sec - return f"{header} {'観測 ' + str(observe_sec) + ' 秒' if observe_sec else '瞬間値のみ'}" - - -def format_server_report(probes: Sequence[ServerProbe], *, show_jobs: bool) -> str: - """全サーバの GPU 一覧(状態と利用者.と実行中ジョブ)を表示用に整形する. - - Args: - probes: 各サーバの状況(表示順). - show_jobs: 実行中ジョブも表示するか(status 用). - - Returns: - 末尾に改行を含む複数行の文字列. - """ - lines: list[str] = [] - for probe in probes: - lines.append(format_server_header(probe)) - output = probe.output - if output is None: - continue - if show_jobs: - jobs = ", ".join(output.jobs) if output.jobs else "(なし)" - lines.append(f" 実行中のジョブ: {jobs}") - if output.other_sessions: - lines.append( - f" (このツール以外の tmux セッション {len(output.other_sessions)} 件)" - ) - if not output.gpu_query_ok: - lines.append(" GPU: nvidia-smi が失敗した(このサーバの GPU は候補から外す)") - elif not output.gpus: - lines.append(" GPU: なし") - else: - lines.append(" GPU:") - for gpu in output.gpus: - lines.extend( - _format_gpu_lines(gpu, probe.own_user, observed=output.observe_sec > 0) - ) - return "\n".join(lines) + "\n" - - -def format_selection(selection: GpuSelection | None) -> str: - """run が選ぶ GPU の説明を 1 行で返す. - - Args: - selection: `select_gpu` の結果. - - Returns: - 表示用の 1 行(改行なし). - """ - if selection is None: - return "run が選ぶ GPU: なし(未使用・空き(利用者あり)の GPU が無い)" - text = ( - f"run が選ぶ GPU: {selection.server.name} の GPU {selection.gpu_index}" - f"({selection.state.value})" - ) - if selection.state is GpuState.SHARED and selection.gpu is not None: - text += f" {describe_gpu_users(selection.gpu, selection.own_user)}" - return text - - -def format_shared_warning(selection: GpuSelection) -> str | None: - """「空き(利用者あり)」の GPU を選んだときの警告文を返す(それ以外は None). - - Args: - selection: `select_gpu` の結果. - - Returns: - 警告文(改行なし). - """ - if selection.state is not GpuState.SHARED or selection.gpu is None: - return None - users = describe_gpu_users(selection.gpu, selection.own_user) - return ( - f"{selection.server.name} の GPU {selection.gpu_index} には計算プロセスがある" - f"({users}).他の計算とメモリ・計算時間を分け合う" - ) diff --git a/src/tongue_seg_model/remote/transfer.py b/src/tongue_seg_model/remote/transfer.py deleted file mode 100644 index e87fa50..0000000 --- a/src/tongue_seg_model/remote/transfer.py +++ /dev/null @@ -1,143 +0,0 @@ -"""tar ストリームの書き出し(push)と,回収した tar の検査・展開(pull). - -Windows には rsync が無いため,Python の tarfile でストリームを作り `ssh ... 'tar -x ...'` の -標準入力へ流す(push).pull は ssh の標準出力をいったん一時ファイルに受け取り, -全メンバーを検査してから展開する(ストリームのまま展開すると,問題のメンバーに当たる前の -ファイルが展開済みになってしまうため.SPEC_03「pull」の二重の防御). - -TIASJudgeModel の `tias_judge_model.remote.transfer` の移植.push の tar はリンクを辿らない -(移植元は `dereference=True` でリンク先の中身を送っていた.送信対象の選別でリンクは除いて -あるが,学習データ・原本をサーバへ送る経路を作らないよう,ここでも確かめる二重の守りにする). -""" - -from __future__ import annotations - -import tarfile -from collections.abc import Sequence -from dataclasses import dataclass -from pathlib import Path -from typing import BinaryIO - -from tongue_seg_model.remote.files import PushEntry, is_link -from tongue_seg_model.remote.whitelist import check_pull_members - -_ENCODING = "utf-8" -_COPY_CHUNK = 1024 * 1024 - - -@dataclass(frozen=True) -class ExtractResult: - """展開の結果. - - Attributes: - files: 展開したファイル数. - bytes: 展開したファイルの合計バイト数. - """ - - files: int - bytes: int - - -def _normalize_tarinfo(info: tarfile.TarInfo) -> tarfile.TarInfo: - """所有者とパーミッションを送信元 OS に依存しない値にそろえる. - - Windows の stat は所有者を持たず実行ビットも拡張子から推測した値なので, - 展開結果がそれに引きずられないよう固定する(実行ビットが立っているものだけ 755). - """ - info.uid = info.gid = 0 - info.uname = info.gname = "" - info.mode = 0o755 if info.isdir() or info.mode & 0o111 else 0o644 - return info - - -def _reject_non_regular(info: tarfile.TarInfo) -> tarfile.TarInfo: - """通常ファイル以外(確認の後にリンク等へ差し替えられたもの)を送らずに止める.""" - if not info.isreg(): - raise ValueError( - f"送信対象 {info.name} が通常ファイルでなくなったため送信を中止した(再実行する)" - ) - return _normalize_tarinfo(info) - - -def write_tar_stream(entries: Sequence[PushEntry], fileobj: BinaryIO) -> int: - """送信対象を非圧縮の tar ストリームとして fileobj へ書き出す. - - PAX 形式で書く(日本語ファイル名を UTF-8 で確実に運ぶ).fileobj は閉じない - (呼び出し側が ssh の標準入力を閉じて EOF を伝える).リンクは辿らない - (`dereference=False`).書き出す前に全件がリンクでない通常ファイルであることを確かめ, - 1 件でも違えば何も書かずに止める(`select_push_files` がリンクを除いている前提の確認). - - Args: - entries: 送信対象. - fileobj: 書き込み先のバイナリストリーム(ssh の標準入力). - - Returns: - 書き出したファイルの合計バイト数. - - Raises: - ValueError: 送信対象にリンク・通常ファイル以外が含まれる場合(名前はリポジトリ内の - コードのものなので示す). - OSError: 書き込み先が閉じられた(ssh が異常終了した)場合など. - """ - for entry in entries: - if is_link(entry.path) or not entry.path.is_file(): - raise ValueError( - f"送信対象 {entry.arcname} がリンクか通常ファイルでないため送信を中止した" - ) - done = 0 - with tarfile.open( - fileobj=fileobj, mode="w|", format=tarfile.PAX_FORMAT, encoding=_ENCODING, dereference=False - ) as tar: - for entry in entries: - tar.add(entry.path, arcname=entry.arcname, recursive=False, filter=_reject_non_regular) - done += entry.size - return done - - -def copy_stream(source: BinaryIO, destination: BinaryIO) -> int: - """source を終端まで読み,destination へ書き写す. - - Args: - source: 読み出し元(ssh の標準出力). - destination: 書き込み先(一時ファイル). - - Returns: - 書き写したバイト数. - """ - total = 0 - while chunk := source.read(_COPY_CHUNK): - destination.write(chunk) - total += len(chunk) - return total - - -def extract_pull_archive( - archive: BinaryIO, dest: Path, run_id: str, *, with_checkpoints: bool -) -> ExtractResult: - """回収した tar(シーク可能なファイル)の全メンバーを検査し,問題が無ければ dest へ展開する. - - 検査(`check_pull_members`)で 1 つでも問題があれば,何も展開せずに例外を送出する. - 検査を通ったメンバーは相対パスの通常ファイルのみだが,念のため Python 3.12 の - `filter="data"`(展開先の外・特殊ファイル・危険なパーミッションを拒否)も重ねる. - - Args: - archive: tar を書き込んだ一時ファイル(読み出し位置は問わない). - dest: 展開先(手元の `runs/`.`/...` がその下にできる.同名ファイルは上書き). - run_id: 検証済みの RUN_ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)を受け入れるか. - - Returns: - 展開したファイル数と合計バイト数. - - Raises: - ValueError: 回収できないメンバーが含まれる場合(何も展開しない). - tarfile.TarError: アーカイブが壊れている場合(何も展開しない). - OSError: 書き込みに失敗した場合. - """ - archive.seek(0) - with tarfile.open(fileobj=archive, mode="r:", encoding=_ENCODING) as tar: - members = tar.getmembers() - check_pull_members(members, run_id, with_checkpoints=with_checkpoints) - dest.mkdir(parents=True, exist_ok=True) - tar.extractall(dest, members=members, filter="data") - return ExtractResult(files=len(members), bytes=sum(member.size for member in members)) diff --git a/src/tongue_seg_model/remote/whitelist.py b/src/tongue_seg_model/remote/whitelist.py deleted file mode 100644 index 1283430..0000000 --- a/src/tongue_seg_model/remote/whitelist.py +++ /dev/null @@ -1,252 +0,0 @@ -"""pull の回収ホワイトリスト(SPEC_01「回収ホワイトリスト」)の判定と,受け取った tar の検査. - -回収できるのは `runs/<実験ID>/` 配下で名前が一致するファイルのみ.拡張子や中身では判断せず, -列挙外はすべて回収しない.名前は大文字小文字を区別して完全一致で比べる(`Config.yaml`・ -`figures/x.PNG` は回収しない).判定は 2 か所で使う(二重の防御.TIASJudgeModel の -SPEC_03「pull」). - -1. サーバの一覧(`build_pull_list_command` の出力)から送らせるファイルを絞り込む(`plan_pull`) -2. 手元で受け取った tar を展開前に全メンバー検査する(`check_pull_members`) - -エラーメッセージ・戻り値の表示用情報には件数だけを載せ,ファイル名は出さない -(患者情報を含む名前の可能性があるため). - -TIASJudgeModel の `tias_judge_model.remote.whitelist` の移植.回収するファイル名と重みの名前を -本リポジトリの SPEC_01 に合わせ,Windows で別の場所を指しうる名前(`:` 等の文字を含む名前・ -末尾が `.` か空白の名前・予約デバイス名)の拒否と,実験 ID の書式の確認(`re.fullmatch`)を足した. -""" - -from __future__ import annotations - -import re -import tarfile -from collections.abc import Iterable -from dataclasses import dataclass - -# runs/<実験ID>/ 直下で回収するファイル名 -PULL_ROOT_FILES = frozenset({"config.yaml", "history.csv", "metrics.json", "log.txt"}) -PULL_FIGURES_DIR = "figures" -PULL_FIGURE_SUFFIX = ".png" -PULL_CHECKPOINTS_DIR = "checkpoints" -# checkpoints/ の下で,明示的に指定したとき(--with-checkpoints)だけ回収するファイル名 -PULL_CHECKPOINT_FILES = frozenset({"best.pth", "ResUNet.onnx"}) - -# find -printf '%y' の通常ファイル -_FIND_TYPE_FILE = "f" -_WINDOWS_DRIVE_RE = re.compile(r"[A-Za-z]:") -# Windows のファイル名に使えない文字.`:` は NTFS の代替データストリームとして解釈され, -# 名前の見かけと違う場所へ書かれうるため拒否する(移植元はドライブ文字だけを見ていた) -_WINDOWS_UNSAFE_CHARS = frozenset('<>:"|?*') -# 実験 ID(runs/ 直下のディレクトリ名)に許す文字.`make_run_id` の書式 -# (`YYYYmmdd-HHMMSS_<設定ファイル名>_`)はこの範囲に収まる. -# リモートのシェルとパスに埋め込むため fullmatch で確かめる -_RUN_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,199}") -# Windows の予約デバイス名(小文字で比べる).拡張子が付いていても(`nul.png`・`CON.tar.gz`) -# ファイルではなくデバイスを指すため,手元に展開すると書き込みが消える・別の動作になる. -# 上付き数字の `COM¹` 等も新しい Windows では予約名として扱われるため含める -_WINDOWS_RESERVED_NAMES = frozenset( - {"con", "prn", "aux", "nul"} - | {f"{prefix}{digit}" for prefix in ("com", "lpt") for digit in "123456789¹²³"} -) - - -@dataclass(frozen=True) -class PullPlan: - """サーバから送らせるファイルの計画. - - Attributes: - files: 送らせるファイル(`runs/` 基準の POSIX パス.表示しない). - skipped: 回収しなかったファイルの件数(リンク等の通常ファイル以外を含む). - skipped_checkpoints: そのうち `--with-checkpoints` を付ければ回収できた件数. - """ - - files: tuple[str, ...] - skipped: int - skipped_checkpoints: int - - -def validate_run_id(run_id: str) -> str: - """実験 ID(`runs/` 直下のディレクトリ名)を検証して返す. - - Args: - run_id: 実験 ID. - - Returns: - 検証済みの実験 ID. - - Raises: - ValueError: 英数字で始まり英数字・`.`・`_`・`-` のみ(200 文字以内)でない場合, - `..` を含む場合,末尾が `.` の場合(Windows は末尾の `.` を捨てるため,手元の - 別の実験のフォルダに展開してしまう),または Windows の予約名(`nul`・`con.txt` 等) - の場合. - """ - if not _RUN_ID_RE.fullmatch(run_id) or ".." in run_id or not _is_safe_part(run_id): - raise ValueError( - f"実験 ID が不正である: {run_id!r}(runs/ 直下のディレクトリ名を指定する." - "英数字で始まり英数字・.・_・- のみ... と末尾の . は使えない." - "Windows の予約名(CON・NUL・COM1 等)は使えない)" - ) - return run_id - - -def _is_windows_reserved(part: str) -> bool: - """パスの 1 要素が Windows の予約デバイス名か(大文字小文字を問わず,拡張子を除いて比べる). - - Windows は最初の `.` より前を名前として扱い,その末尾の空白も無視する(`nul .png` も予約名). - """ - return part.split(".", 1)[0].rstrip(" ").lower() in _WINDOWS_RESERVED_NAMES - - -def _is_safe_part(part: str) -> bool: - """パスの 1 要素が `..`・`.`・空・バックスラッシュ・ドライブ文字・制御文字・Windows で - 使えない文字を含まず,末尾が `.`・空白でなく,Windows の予約名でないか. - - 末尾の `.`・空白は Windows が捨てるため,見かけと違う名前(`abc.` → `abc`)に書かれる. - """ - return ( - part not in ("", ".", "..") - and "\\" not in part - and not _WINDOWS_DRIVE_RE.match(part) - and not any(c in _WINDOWS_UNSAFE_CHARS or ord(c) < 0x20 or c == "\x7f" for c in part) - and not part.endswith((".", " ")) - and not _is_windows_reserved(part) - ) - - -def _is_safe_relative(path: str) -> bool: - """POSIX 区切りの相対パスとして安全か(絶対パス・パス外へ出る要素を含まない).""" - return not path.startswith("/") and all(_is_safe_part(part) for part in path.split("/")) - - -def is_pull_allowed(rel_path: str, *, with_checkpoints: bool) -> bool: - """`runs/<実験ID>/` 基準の相対パスが回収ホワイトリストに一致するかを返す. - - Args: - rel_path: `runs/<実験ID>/` 基準の POSIX 相対パス. - with_checkpoints: `checkpoints/best.pth`・`checkpoints/ResUNet.onnx` も回収対象に - するか. - - Returns: - 回収してよければ True. - """ - if not _is_safe_relative(rel_path): - return False - parts = rel_path.split("/") - if len(parts) == 1: - return parts[0] in PULL_ROOT_FILES - if len(parts) != 2: - return False - directory, name = parts - if directory == PULL_FIGURES_DIR: - return name.endswith(PULL_FIGURE_SUFFIX) and len(name) > len(PULL_FIGURE_SUFFIX) - if directory == PULL_CHECKPOINTS_DIR and with_checkpoints: - return name in PULL_CHECKPOINT_FILES - return False - - -def _strip_run_prefix(path: str, run_id: str) -> str | None: - """`<実験ID>/` から `` を取り出す(実験 ID 配下でなければ None).""" - prefix = f"{run_id}/" - return path[len(prefix) :] if path.startswith(prefix) else None - - -def parse_find_listing(data: bytes) -> list[tuple[str, str]]: - """`build_pull_list_command` の出力(`<種類> <パス>` の NUL 区切り)を分解する. - - Linux のファイル名は任意のバイト列なので,往復で失われないよう surrogateescape で扱う. - - Args: - data: サーバの出力. - - Returns: - (種類, `runs/` 基準のパス) の一覧. - - Raises: - ValueError: 書式が崩れている場合(件数のみ示す). - """ - entries: list[tuple[str, str]] = [] - for number, record in enumerate((r for r in data.split(b"\0") if r), start=1): - kind, sep, path = record.decode("utf-8", "surrogateescape").partition(" ") - if not sep or not kind or not path: - raise ValueError(f"サーバのファイル一覧の {number} 件目を解釈できない") - entries.append((kind, path)) - return entries - - -def plan_pull( - listing: Iterable[tuple[str, str]], run_id: str, *, with_checkpoints: bool -) -> PullPlan: - """サーバのファイル一覧から,送らせるファイル(ホワイトリストに一致する通常ファイル)を選ぶ. - - Args: - listing: `parse_find_listing` の結果. - run_id: 検証済みの実験 ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)も回収するか. - - Returns: - 送らせるファイルと,回収しなかった件数. - """ - files: list[str] = [] - skipped = 0 - skipped_checkpoints = 0 - for kind, path in listing: - rel = _strip_run_prefix(path, run_id) - if kind == _FIND_TYPE_FILE and rel is not None: - if is_pull_allowed(rel, with_checkpoints=with_checkpoints): - files.append(path) - continue - if not with_checkpoints and is_pull_allowed(rel, with_checkpoints=True): - skipped_checkpoints += 1 - skipped += 1 - return PullPlan(tuple(sorted(files)), skipped, skipped_checkpoints) - - -def check_pull_members( - members: Iterable[tarfile.TarInfo], run_id: str, *, with_checkpoints: bool -) -> int: - """受け取った tar の全メンバーを展開前に検査する. - - 1 つでも問題があれば例外を送出する(呼び出し側は何も展開しない).受け入れるのは - `<実験ID>/<ホワイトリストに一致する名前>` の通常ファイルのみで,ディレクトリ・リンク - (シンボリック・ハード)・特殊ファイルは拒否する(サーバはファイル名だけを tar に渡すため, - 正常な応答にディレクトリのメンバーは含まれない). - - Args: - members: tar のメンバー(`TarFile.getmembers()`). - run_id: 検証済みの実験 ID. - with_checkpoints: 重み(`checkpoints/best.pth`・`checkpoints/ResUNet.onnx`)を - 受け入れるか. - - Returns: - 受け入れたメンバーの件数. - - Raises: - ValueError: ホワイトリスト外の名前・パス外に出る名前(`..`・絶対パス・ドライブ文字・ - バックスラッシュ・Windows で使えない文字)・リンク・通常ファイル以外が含まれる場合 - (件数のみを示す). - """ - accepted = 0 - outside = 0 - links = 0 - not_regular = 0 - not_allowed = 0 - for member in members: - if not _is_safe_relative(member.name): - outside += 1 - elif member.issym() or member.islnk(): - links += 1 - elif not member.isreg(): - not_regular += 1 - else: - rel = _strip_run_prefix(member.name, run_id) - if rel is None or not is_pull_allowed(rel, with_checkpoints=with_checkpoints): - not_allowed += 1 - else: - accepted += 1 - if outside or links or not_regular or not_allowed: - raise ValueError( - "受け取ったアーカイブに回収できないメンバーが含まれるため,何も展開せず中止した" - f"(ホワイトリスト外 {not_allowed} 件・パス外 {outside} 件・リンク {links} 件・" - f"通常ファイル以外 {not_regular} 件)" - ) - return accepted diff --git a/tests/cli/test_remote.py b/tests/cli/test_remote.py deleted file mode 100644 index 486169c..0000000 --- a/tests/cli/test_remote.py +++ /dev/null @@ -1,1248 +0,0 @@ -"""tsm-remote CLI のテスト(SPEC_03).ssh はすべてモックし,実サーバに接続しない. - -- 接続できないサーバがあっても他のサーバで続行する(全台不可ならエラー) -- `TSM_REMOTE_JUMP` が空文字なら踏み台を使わない -- 手元のホスト名がサーバ名と一致したら止まる(`TSM_REMOTE_ALLOW_SELF=1` で無効化) -- pull は回収ホワイトリストに一致するファイルだけを持ち帰り,回収しなかったファイルの名前を - 出さない.受け取った tar に不正なメンバーがあれば何も展開しない -- run はジョブに TSM_GIT_COMMIT(未コミットの変更があれば -dirty 付き)を渡す.手元の git は - subprocess.run をモックする(実プロセスは起動しない) -- run --cpu は GPU を観測・選択せず,CUDA_VISIBLE_DEVICES を空文字で渡す - -TIASJudgeModel の tests/cli/test_remote.py の移植.本リポジトリの configs/remote.yaml と同じく -設定に address・user を書かず,ssh の接続先はサーバ名(~/.ssh/config の Host 名)になる. -回収ホワイトリストは本リポジトリの SPEC_01 に合わせた. -""" - -from __future__ import annotations - -import io -import logging -import os -import shlex -import subprocess -import sys -import tarfile -import threading -from collections.abc import Callable, Iterator -from pathlib import Path - -import pytest - -import tongue_seg_model.cli.remote as cli -from tongue_seg_model.remote.commands import ( - EXIT_NOT_FOUND, - PROBE_APPS_MARKER, - PROBE_APPS_RC_PREFIX, - PROBE_END_MARKER, - PROBE_GPU_RC_PREFIX, - PROBE_GPUS_MARKER, - PROBE_OWNERS_MARKER, - PROBE_SAMPLES_MARKER, - PROBE_SESSIONS_MARKER, - PROBE_USER_PREFIX, -) -from tongue_seg_model.remote.gpu import GpuState - -# 設定に address を書かないため,ssh の接続先はサーバ名になる -NEWTON_ADDR = "Newton" -ARCHIMEDES_ADDR = "Archimedes" -RUN_ID = "20261119-120000_resunet_abc1234" - -CONFIG_YAML = """\ -jump_host: labpc -connect_timeout_sec: 15 -gpu_free: - max_memory_used_mib: 1024 - max_utilization_percent: 10 - observe_sec: 10 - sample_interval_ms: 500 -servers: - - name: Newton - priority: 1 - remote_dir: ~/work/TongueSegModel - uv: ~/.local/bin/uv - data_ready: true - - name: Archimedes - priority: 2 - remote_dir: ~/work/TongueSegModel - uv: ~/.local/bin/uv - data_ready: true -""" - - -def _probe_stdout(gpus: list[tuple[int, int, int]], apps: list[str] | None = None) -> bytes: - """probe の出力(gpus は (index, 使用中メモリ, 使用率) のリスト.観測サンプルも同じ値).""" - lines = [f"{PROBE_USER_PREFIX}hasegawa", PROBE_SESSIONS_MARKER, PROBE_GPUS_MARKER] - lines += [f"{i}, GPU-{i}, NVIDIA RTX A6000, {mem}, 49140, {util}" for i, mem, util in gpus] - lines.append(f"{PROBE_GPU_RC_PREFIX}0") - lines.append(PROBE_SAMPLES_MARKER) - lines += [f"{i}, {util}, {mem}" for i, mem, util in gpus for _ in range(3)] - lines.append(PROBE_APPS_MARKER) - lines += apps or [] - lines += [f"{PROBE_APPS_RC_PREFIX}0", PROBE_OWNERS_MARKER, PROBE_END_MARKER] - return ("\n".join(lines) + "\n").encode() - - -class FakeSsh: - """`_run_ssh` の代わり.接続先(argv の最後から 2 番目)ごとに応答を返し,呼び出しを記録する.""" - - def __init__(self, responses: dict[str, Callable[[list[str]], cli._SshResult]]) -> None: - self.responses = responses - self.calls: list[list[str]] = [] - self._lock = threading.Lock() - - def __call__( - self, argv: list[str], *, input_bytes: bytes | None = None, timeout: float | None = None - ) -> cli._SshResult: - with self._lock: - self.calls.append(list(argv)) - for host, respond in self.responses.items(): - if argv[-2] == host: - return respond(argv) - raise AssertionError("想定外の接続先") - - -def _ok(stdout: bytes) -> Callable[[list[str]], cli._SshResult]: - return lambda argv: cli._SshResult(0, stdout, b"") - - -def _fail(rc: int = 255, stderr: bytes = b"ssh: connect to host: Connection timed out"): - return lambda argv: cli._SshResult(rc, b"", stderr) - - -class FakeGit: - """手元の git(`subprocess.run(["git", ...])`)の代わり.git 以外のコマンドは拒否する. - - Attributes: - head: `git rev-parse --short HEAD` の出力.None なら失敗(リポジトリでない等). - status: `git status --porcelain` の出力.None なら失敗. - missing: True なら git が無い(FileNotFoundError). - """ - - def __init__(self) -> None: - self.head: str | None = "abc1234\n" - self.status: str | None = "" - self.missing = False - self.calls: list[list[str]] = [] - - def __call__(self, argv: list[str], *args: object, **kwargs: object): - argv = list(argv) - if not argv or argv[0] != "git": - raise AssertionError("テストが git 以外の実プロセスを起動しようとした") - self.calls.append(argv) - if self.missing: - raise FileNotFoundError("git") - if "rev-parse" in argv: - out = self.head - elif "status" in argv: - out = self.status - else: - raise AssertionError(f"想定外の git コマンド: {argv}") - if out is None: - return subprocess.CompletedProcess(argv, 128, "", "fatal: not a git repository") - return subprocess.CompletedProcess(argv, 0, out, "") - - -@pytest.fixture -def fake_git(monkeypatch: pytest.MonkeyPatch) -> FakeGit: - """`run` が手元で求める TSM_GIT_COMMIT 用の git をモックする(実プロセスは起動しない).""" - fake = FakeGit() - monkeypatch.setattr(cli.subprocess, "run", fake) - return fake - - -@pytest.fixture -def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fake_git: FakeGit) -> Path: - """手元のプロジェクトルートを模したディレクトリ(ssh は一切起動させない).""" - root = tmp_path / "proj" - (root / "src" / "tongue_seg_model").mkdir(parents=True) - (root / "src" / "tongue_seg_model" / "__init__.py").write_bytes(b"") - (root / "pyproject.toml").write_bytes(b"[project]\nname = 'x'\n") - (root / "configs").mkdir() - (root / "configs" / "remote.yaml").write_text(CONFIG_YAML, encoding="utf-8") - monkeypatch.chdir(root) - for var in ("TSM_REMOTE_JUMP", "TSM_REMOTE_ALLOW_SELF"): - monkeypatch.delenv(var, raising=False) - monkeypatch.setenv("TSM_REMOTE_SSH", "ssh") - monkeypatch.setattr(cli.socket, "gethostname", lambda: "my-laptop") - - def _no_process(*args: object, **kwargs: object) -> None: - raise AssertionError("テストが実プロセス(ssh)を起動しようとした") - - monkeypatch.setattr(cli, "_popen", _no_process) - monkeypatch.setattr(cli.subprocess, "Popen", _no_process) - return root - - -def _spy_selection(monkeypatch: pytest.MonkeyPatch) -> list: - picked: list = [] - original = cli.select_gpu - - def spy(*args, **kwargs): - result = original(*args, **kwargs) - picked.append(result) - return result - - monkeypatch.setattr(cli, "select_gpu", spy) - return picked - - -# --------------------------------------------------------------------------- -# 接続できないサーバ -# --------------------------------------------------------------------------- - - -class TestUnreachableServers: - def test_gpus_continues_with_other_server( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))}) - monkeypatch.setattr(cli, "_run_ssh", fake) - picked = _spy_selection(monkeypatch) - assert cli.main(["gpus"]) == 0 - assert picked[0] is not None - assert (picked[0].server.name, picked[0].gpu_index) == ("Archimedes", 0) - assert len(fake.calls) == 2 - - def test_run_selects_gpu_on_reachable_server( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))}) - monkeypatch.setattr(cli, "_run_ssh", fake) - picked = _spy_selection(monkeypatch) - rc = cli.main(["run", "--name", "exp1", "--dry-run", "--", "python", "-V"]) - assert rc == 0 - assert picked[0].server.name == "Archimedes" - assert picked[0].state is GpuState.UNUSED - - def test_unparsable_probe_is_treated_as_unreachable( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh( - {NEWTON_ADDR: _ok(b"garbage\n"), ARCHIMEDES_ADDR: _ok(_probe_stdout([(1, 5, 0)]))} - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - picked = _spy_selection(monkeypatch) - assert cli.main(["gpus"]) == 0 - assert (picked[0].server.name, picked[0].gpu_index) == ("Archimedes", 1) - - @pytest.mark.parametrize("subcommand", [["gpus"], ["status"], ["push"]]) - def test_all_unreachable_is_error( - self, project: Path, monkeypatch: pytest.MonkeyPatch, subcommand: list[str] - ) -> None: - fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _fail()}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(subcommand) != 0 - - def test_run_all_unreachable_is_error( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh({NEWTON_ADDR: _fail(), ARCHIMEDES_ADDR: _fail()}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) != 0 - - -class TestRunSelection: - def test_unused_on_lower_priority_server_is_chosen( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - newton = _probe_stdout([(0, 300, 0)], apps=["GPU-0, 4321, 300"]) - fake = FakeSsh({NEWTON_ADDR: _ok(newton), ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)]))}) - monkeypatch.setattr(cli, "_run_ssh", fake) - picked = _spy_selection(monkeypatch) - assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0 - assert picked[0].server.name == "Archimedes" - - def test_no_free_gpu_does_not_start_job( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - busy = _probe_stdout([(0, 20000, 95)]) - fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["run", "--name", "exp1", "--", "python"]) != 0 - # probe の 2 回だけで,起動のための ssh は呼ばない - assert len(fake.calls) == 2 - - def test_gpu_without_server_is_rejected_before_ssh( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["run", "--name", "exp1", "--gpu", "0", "--", "python"]) != 0 - assert fake.calls == [] - - def test_explicit_busy_gpu_is_error_without_force( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - busy = _probe_stdout([(0, 20000, 95)]) - fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)}) - monkeypatch.setattr(cli, "_run_ssh", fake) - args = ["run", "--name", "e", "--server", "Newton", "--gpu", "0", "--dry-run", "--", "x"] - assert cli.main(args) != 0 - assert cli.main([*args[:7], "--force", *args[7:]]) == 0 - - -# --------------------------------------------------------------------------- -# 環境変数 -# --------------------------------------------------------------------------- - - -class TestEnvironment: - def _run_gpus(self, monkeypatch: pytest.MonkeyPatch) -> FakeSsh: - fake = FakeSsh( - { - NEWTON_ADDR: _ok(_probe_stdout([(0, 5, 0)])), - ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)])), - } - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["gpus"]) == 0 - return fake - - def test_config_jump_host_is_used(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - fake = self._run_gpus(monkeypatch) - for argv in fake.calls: - assert argv[argv.index("-J") + 1] == "labpc" - assert "BatchMode=yes" in argv - - def test_empty_jump_env_means_direct( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - monkeypatch.setenv("TSM_REMOTE_JUMP", "") - fake = self._run_gpus(monkeypatch) - assert fake.calls - for argv in fake.calls: - assert "-J" not in argv - - def test_self_server_is_detected(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(cli.socket, "gethostname", lambda: "Newton") - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["gpus"]) != 0 - assert fake.calls == [] - - def test_allow_self_disables_detection( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - monkeypatch.setattr(cli.socket, "gethostname", lambda: "Newton") - monkeypatch.setenv("TSM_REMOTE_ALLOW_SELF", "1") - fake = self._run_gpus(monkeypatch) - assert len(fake.calls) == 2 - - -# --------------------------------------------------------------------------- -# pull -# --------------------------------------------------------------------------- - -LISTING_NAMES = [ - "config.yaml", - "history.csv", - "metrics.json", - "log.txt", - "figures/loss.png", - "figures/iou.png", - "split.json", - "predictions.csv", - "P0001_yamada.png", - "manifest.csv", - "figures/sub/P0002_suzuki.png", - "checkpoints/epoch3.pth", - "checkpoints/best.pth", - "checkpoints/ResUNet.onnx", -] -ALLOWED = LISTING_NAMES[:6] -CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.onnx"] -SECRET_NAMES = [ - "split.json", - "predictions.csv", - "P0001_yamada", - "manifest.csv", - "P0002_suzuki", - "epoch3", -] - - -def _listing() -> bytes: - return b"".join(f"f {RUN_ID}/{name}\0".encode() for name in LISTING_NAMES) - - -def _tar_of(names: list[str]) -> bytes: - buffer = io.BytesIO() - with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar: - for name in names: - data = f"content of {name}".encode() - info = tarfile.TarInfo(name) - info.size = len(data) - tar.addfile(info, io.BytesIO(data)) - return buffer.getvalue() - - -class FakeReceive: - """`_receive_tar` の代わり.要求されたパスの tar(と任意の追加メンバー)を返す.""" - - def __init__(self, extra: list[str] | None = None) -> None: - self.extra = extra or [] - self.requested: list[str] = [] - - def __call__(self, argv: list[str], payload: bytes, destination) -> cli._SshResult: - self.requested = [p.decode() for p in payload.split(b"\0") if p] - destination.write(_tar_of(self.requested + self.extra)) - return cli._SshResult(0, b"", b"") - - -def _setup_pull(monkeypatch: pytest.MonkeyPatch, receive: FakeReceive) -> FakeSsh: - fake = FakeSsh( - { - NEWTON_ADDR: _ok(_listing()), - ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b""), - } - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - monkeypatch.setattr(cli, "_receive_tar", receive) - return fake - - -def _local_files(root: Path) -> list[str]: - run = root / "runs" / RUN_ID - if not run.exists(): - return [] - return sorted(p.relative_to(run).as_posix() for p in run.rglob("*") if p.is_file()) - - -class TestPull: - def test_pulls_only_whitelisted_files( - self, - project: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - caplog: pytest.LogCaptureFixture, - ) -> None: - caplog.set_level(logging.DEBUG) - receive = FakeReceive() - _setup_pull(monkeypatch, receive) - assert cli.main(["pull", RUN_ID]) == 0 - assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in ALLOWED) - assert _local_files(project) == sorted(ALLOWED) - captured = capsys.readouterr() - output = captured.out + captured.err + caplog.text - for secret in SECRET_NAMES: - assert secret not in output - # 回収しなかった件数(split・predictions・画像 2・manifest・重み 3 の 8 件)と, - # そのうち --with-checkpoints で回収できる件数(2 件)は示す - assert "8 件" in output - assert "2 件は --with-checkpoints で回収できる" in output - - @pytest.mark.parametrize("flag", ["--with-checkpoints", "--checkpoints"]) - def test_with_checkpoints( - self, project: Path, monkeypatch: pytest.MonkeyPatch, flag: str - ) -> None: - receive = FakeReceive() - _setup_pull(monkeypatch, receive) - assert cli.main(["pull", RUN_ID, flag]) == 0 - # split.json・predictions.csv・指定外の重みは --with-checkpoints でも回収しない - expected = [*ALLOWED, *CHECKPOINTS] - assert _local_files(project) == sorted(expected) - assert sorted(receive.requested) == sorted(f"{RUN_ID}/{n}" for n in expected) - - @pytest.mark.parametrize( - "extra", - [ - f"{RUN_ID}/split.json", - f"{RUN_ID}/predictions.csv", - f"{RUN_ID}/P0001_yamada.png", - f"{RUN_ID}/checkpoints/best.pth", - f"{RUN_ID}/figures/P0001_yamada:x.png", - f"{RUN_ID}/Config.yaml", - f"{RUN_ID}/../evil.txt", - "../evil.txt", - "other_run/config.yaml", - ], - ) - def test_malicious_archive_extracts_nothing( - self, - project: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - caplog: pytest.LogCaptureFixture, - extra: str, - ) -> None: - caplog.set_level(logging.DEBUG) - _setup_pull(monkeypatch, FakeReceive(extra=[extra])) - assert cli.main(["pull", RUN_ID]) != 0 - assert _local_files(project) == [] - assert not (project / "runs" / "evil.txt").exists() - assert not (project / "evil.txt").exists() - captured = capsys.readouterr() - output = captured.out + captured.err + caplog.text - assert "P0001_yamada" not in output - assert "split.json" not in output - assert "predictions.csv" not in output - - @pytest.mark.parametrize( - "run_id", - ["../etc", "a/b", "a\\b", "..", "x..y", ".x", "a;b", "$(id)", "a b", "C:x", "a\n"], - ) - def test_invalid_run_id_is_rejected_before_ssh( - self, project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["pull", run_id]) != 0 - assert fake.calls == [] - - def test_run_on_multiple_servers_is_error( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = FakeSsh({NEWTON_ADDR: _ok(_listing()), ARCHIMEDES_ADDR: _ok(_listing())}) - monkeypatch.setattr(cli, "_run_ssh", fake) - monkeypatch.setattr(cli, "_receive_tar", FakeReceive()) - assert cli.main(["pull", RUN_ID]) != 0 - assert cli.main(["pull", RUN_ID, "--server", "Newton"]) == 0 - - def test_run_not_found_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"") - fake = FakeSsh({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["pull", RUN_ID]) != 0 - - -# --------------------------------------------------------------------------- -# push -# --------------------------------------------------------------------------- - - -class TestPush: - def test_dry_run_lists_code_but_not_excluded( - self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] - ) -> None: - for rel in [ - "data/synthetic/manifest.csv", - "runs/x/metrics.json", - ".claude/a.md", - "legacy/source/main.py", - "src/tongue_seg_model/models/best.pth", - "configs/ResUNet.ONNX", - ".env", - "src/tongue_seg_model/data/bundle.py", - ]: - path = project / rel - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b"x") - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["push", "--dry-run"]) == 0 - out = capsys.readouterr().out - assert "pyproject.toml" in out - assert "configs/remote.yaml" in out - assert "data/synthetic" not in out - assert "runs/x" not in out - assert ".claude" not in out - assert "legacy" not in out - assert "best.pth" not in out - assert "ResUNet.ONNX" not in out - assert ".env" not in out - # data/ の除外は直下だけ(パッケージの data/ は送る) - assert "src/tongue_seg_model/data/bundle.py" in out - assert fake.calls == [] - - -# --------------------------------------------------------------------------- -# run: TSM_GIT_COMMIT(SPEC_03「run」・SPEC_01「実験の出力」) -# --------------------------------------------------------------------------- - - -def _spy_job_script(monkeypatch: pytest.MonkeyPatch) -> list[dict]: - """`build_job_script` に渡された引数(env・gpu_index・server_name)を記録する.""" - captured: list[dict] = [] - original = cli.build_job_script - - def spy(*args, **kwargs): - captured.append(kwargs) - return original(*args, **kwargs) - - monkeypatch.setattr(cli, "build_job_script", spy) - return captured - - -def _free_everywhere(monkeypatch: pytest.MonkeyPatch) -> FakeSsh: - fake = FakeSsh( - { - NEWTON_ADDR: _ok(_probe_stdout([(0, 5, 0)])), - ARCHIMEDES_ADDR: _ok(_probe_stdout([(0, 5, 0)])), - } - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - return fake - - -class TestRunGitCommit: - def test_clean_tree_passes_short_hash( - self, - project: Path, - monkeypatch: pytest.MonkeyPatch, - fake_git: FakeGit, - capsys: pytest.CaptureFixture[str], - ) -> None: - _free_everywhere(monkeypatch) - captured = _spy_job_script(monkeypatch) - assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0 - assert captured[0]["env"]["TSM_GIT_COMMIT"] == "abc1234" - # ジョブのスクリプトに実際に export される - assert "export TSM_GIT_COMMIT=abc1234" in capsys.readouterr().out - assert fake_git.calls - - def test_dirty_tree_appends_suffix( - self, - project: Path, - monkeypatch: pytest.MonkeyPatch, - fake_git: FakeGit, - capsys: pytest.CaptureFixture[str], - ) -> None: - fake_git.status = " M src/tongue_seg_model/schema.py\n" - _free_everywhere(monkeypatch) - captured = _spy_job_script(monkeypatch) - assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0 - assert captured[0]["env"]["TSM_GIT_COMMIT"] == "abc1234-dirty" - assert "export TSM_GIT_COMMIT=abc1234-dirty" in capsys.readouterr().out - - @pytest.mark.parametrize("failure", ["missing", "not_repo", "status_fails"]) - def test_git_unavailable_does_not_set_variable( - self, - project: Path, - monkeypatch: pytest.MonkeyPatch, - fake_git: FakeGit, - capsys: pytest.CaptureFixture[str], - failure: str, - ) -> None: - if failure == "missing": - fake_git.missing = True - elif failure == "not_repo": - fake_git.head = None - else: - fake_git.status = None - _free_everywhere(monkeypatch) - captured = _spy_job_script(monkeypatch) - # git が使えなくてもジョブは起動できる(ジョブ側は nogit になる) - assert cli.main(["run", "--name", "exp1", "--dry-run", "--", "python"]) == 0 - assert "TSM_GIT_COMMIT" not in captured[0]["env"] - assert "TSM_GIT_COMMIT" not in capsys.readouterr().out - - @pytest.mark.parametrize("git_ok", [True, False]) - def test_env_option_cannot_override_git_commit( - self, project: Path, monkeypatch: pytest.MonkeyPatch, fake_git: FakeGit, git_ok: bool - ) -> None: - fake_git.missing = not git_ok - fake = _free_everywhere(monkeypatch) - args = ["run", "--name", "exp1", "--env", "TSM_GIT_COMMIT=fake", "--", "python"] - assert cli.main(args) != 0 - # probe の 2 回だけで,起動のための ssh は呼ばない - assert len(fake.calls) == 2 - - -# --------------------------------------------------------------------------- -# run --cpu(SPEC_03「run」) -# --------------------------------------------------------------------------- - - -def _probe_stdout_instant() -> bytes: - """観測なし(瞬間値のみ)の probe の出力.GPU は使用中.""" - lines = [ - PROBE_SESSIONS_MARKER, - PROBE_GPUS_MARKER, - "0, GPU-0, NVIDIA RTX A6000, 20000, 49140, 95", - f"{PROBE_GPU_RC_PREFIX}0", - PROBE_APPS_MARKER, - "GPU-0, 4321, 20000", - f"{PROBE_APPS_RC_PREFIX}0", - PROBE_OWNERS_MARKER, - PROBE_END_MARKER, - ] - return ("\n".join(lines) + "\n").encode() - - -def _forbid_gpu_selection(monkeypatch: pytest.MonkeyPatch) -> None: - def forbidden(*args: object, **kwargs: object) -> None: - raise AssertionError("--cpu で GPU を選ぼうとした") - - monkeypatch.setattr(cli, "select_gpu", forbidden) - - -def _write_remote_config(project: Path, *, newton_data_ready: bool) -> None: - text = CONFIG_YAML - if not newton_data_ready: - text = text.replace("data_ready: true", "data_ready: false", 1) - (project / "configs" / "remote.yaml").write_text(text, encoding="utf-8") - - -class TestRunCpu: - def _setup( - self, - monkeypatch: pytest.MonkeyPatch, - *, - newton_ok: bool = True, - archimedes_ok: bool = True, - ) -> tuple[FakeSsh, list[dict]]: - # GPU はすべて使用中にしておく(--cpu では GPU の状態に関わらず起動できること) - fake = FakeSsh( - { - NEWTON_ADDR: _ok(_probe_stdout_instant()) if newton_ok else _fail(), - ARCHIMEDES_ADDR: _ok(_probe_stdout_instant()) if archimedes_ok else _fail(), - } - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - _forbid_gpu_selection(monkeypatch) - return fake, _spy_job_script(monkeypatch) - - def test_does_not_observe_or_select_gpu( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake, captured = self._setup(monkeypatch) - args = ["run", "--name", "export1", "--cpu", "--dry-run", "--", "tsm-export", "--run", "x"] - assert cli.main(args) == 0 - assert fake.calls - for argv in fake.calls: - remote_command = argv[-1] - assert PROBE_SAMPLES_MARKER not in remote_command - assert "-lms" not in remote_command - assert "pmon" not in remote_command - assert captured[0]["gpu_index"] is None - - def test_cuda_visible_devices_is_empty_string( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _fake, captured = self._setup(monkeypatch) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 - env = captured[0]["env"] - assert "CUDA_VISIBLE_DEVICES" in env - assert env["CUDA_VISIBLE_DEVICES"] == "" - assert env["TSM_GIT_COMMIT"] == "abc1234" - - def test_log_header_says_no_gpu( - self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] - ) -> None: - self._setup(monkeypatch) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 - assert "gpu=なし(CPU)" in capsys.readouterr().out - - def test_without_server_uses_highest_priority_reachable( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _fake, captured = self._setup(monkeypatch) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 - assert captured[0]["server_name"] == "Newton" - - def test_unreachable_server_is_skipped( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _fake, captured = self._setup(monkeypatch, newton_ok=False) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 - assert captured[0]["server_name"] == "Archimedes" - - def test_all_unreachable_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - _fake, captured = self._setup(monkeypatch, newton_ok=False, archimedes_ok=False) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) != 0 - assert captured == [] - - def test_explicit_server(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - _fake, captured = self._setup(monkeypatch) - args = ["run", "--name", "s", "--cpu", "--server", "Archimedes", "--dry-run", "--", "x"] - assert cli.main(args) == 0 - assert captured[0]["server_name"] == "Archimedes" - - def test_explicit_unreachable_server_is_error( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _fake, captured = self._setup(monkeypatch, archimedes_ok=False) - args = ["run", "--name", "s", "--cpu", "--server", "Archimedes", "--dry-run", "--", "x"] - assert cli.main(args) != 0 - assert captured == [] - - def test_data_not_ready_server_is_skipped_without_no_data( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _write_remote_config(project, newton_data_ready=False) - _fake, captured = self._setup(monkeypatch) - assert cli.main(["run", "--name", "s", "--cpu", "--dry-run", "--", "x"]) == 0 - assert captured[0]["server_name"] == "Archimedes" - - def test_no_data_includes_not_ready_server( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _write_remote_config(project, newton_data_ready=False) - _fake, captured = self._setup(monkeypatch) - args = ["run", "--name", "s", "--cpu", "--no-data", "--dry-run", "--", "x"] - assert cli.main(args) == 0 - assert captured[0]["server_name"] == "Newton" - - @pytest.mark.parametrize( - "extra", - [ - ["--gpu", "0", "--server", "Newton"], - ["--gpu", "0"], - ["--force"], - ["--observe", "0"], - ["--observe", "10"], - ], - ) - def test_gpu_options_are_rejected_before_ssh( - self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: list[str] - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["run", "--name", "s", "--cpu", *extra, "--dry-run", "--", "x"]) != 0 - assert fake.calls == [] - - def test_launch_on_selected_server( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - # --no-push で起動まで進める(起動の ssh もモック) - fake, captured = self._setup(monkeypatch) - assert cli.main(["run", "--name", "s", "--cpu", "--no-push", "--", "x"]) == 0 - launch = fake.calls[-1] - assert launch[-2] == NEWTON_ADDR - assert "tmux" in launch[-1] - assert captured[0]["env"]["CUDA_VISIBLE_DEVICES"] == "" - - -# --------------------------------------------------------------------------- -# 本リポジトリで足した確認 -# --------------------------------------------------------------------------- - -# シェルが特別に解釈する文字を含むコマンド引数 -NASTY_ARGS = ["a b", "it's", 'say "hi"', "x; rm -rf ~", "$(id)", "`id`", "$HOME", "*", ""] - - -def _uv_run_args_of_launch(remote_command: str) -> list[str]: - """起動の ssh に渡したリモートコマンドから,最終的に `uv run` へ渡る引数を取り出す. - - tmux の new-session の引数 → `bash -c` のスクリプト → `uv run` の引数の順に, - POSIX シェルの解釈(shlex)で引用を外す. - """ - tokens = shlex.split(remote_command) - i = tokens.index("new-session") - inner = shlex.split(tokens[i + 6]) - assert inner[:2] == ["bash", "-c"] - script_tokens = shlex.split(inner[2]) - start = script_tokens.index("$HOME/.local/bin/uv") + 1 - assert script_tokens[start] == "run" - return script_tokens[start + 1 : script_tokens.index("<", start)] - - -class TestRunLaunch: - def test_nasty_arguments_reach_uv_run_unchanged( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = _free_everywhere(monkeypatch) - command = ["tsm-train", "--config", *NASTY_ARGS] - assert cli.main(["run", "--name", "train1", "--no-push", "--", *command]) == 0 - launch = fake.calls[-1] - assert launch[-2] == NEWTON_ADDR - assert _uv_run_args_of_launch(launch[-1]) == command - - def test_launch_uses_host_name_without_user( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = _free_everywhere(monkeypatch) - assert cli.main(["run", "--name", "train1", "--no-push", "--", "tsm-train"]) == 0 - for argv in fake.calls: - assert argv[-2] in {NEWTON_ADDR, ARCHIMEDES_ADDR} - assert not any("@" in arg for arg in argv[:-1]) - assert "BatchMode=yes" in argv - - def test_launch_exports_selected_gpu_and_git_commit( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - fake = _free_everywhere(monkeypatch) - args = ["run", "--name", "t", "--no-push", "--env", "TIASDATA_BUNDLES=data/synthetic"] - assert cli.main([*args, "--", "tsm-train"]) == 0 - script = shlex.split(shlex.split(fake.calls[-1][-1])[-1])[2] - for statement in [ - "export CUDA_DEVICE_ORDER=PCI_BUS_ID", - "export CUDA_VISIBLE_DEVICES=0", - "export PYTHONUNBUFFERED=1", - "export TSM_GIT_COMMIT=abc1234", - "export TIASDATA_BUNDLES=data/synthetic", - ]: - assert statement in script - assert "TIAS_DATA_ROOT" not in script - - @pytest.mark.parametrize( - "item", - [ - "CUDA_VISIBLE_DEVICES=1", - "CUDA_DEVICE_ORDER=FASTEST_FIRST", - "PYTHONUNBUFFERED=0", - "TSM_GIT_COMMIT=fake", - "BAD KEY=x", - "1X=y", - "NOEQUALS", - ], - ) - def test_reserved_or_bad_env_is_rejected_without_launch( - self, project: Path, monkeypatch: pytest.MonkeyPatch, item: str - ) -> None: - fake = _free_everywhere(monkeypatch) - assert cli.main(["run", "--name", "t", "--no-push", "--env", item, "--", "x"]) == 1 - # probe だけで,起動の ssh は呼ばない - assert all("new-session" not in argv[-1] for argv in fake.calls) - - def test_busy_gpu_is_not_used_without_force( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - busy = _probe_stdout([(0, 20000, 95)]) - fake = FakeSsh({NEWTON_ADDR: _ok(busy), ARCHIMEDES_ADDR: _ok(busy)}) - monkeypatch.setattr(cli, "_run_ssh", fake) - args = ["run", "--name", "t", "--server", "Newton", "--gpu", "0", "--no-push"] - assert cli.main([*args, "--", "x"]) == 1 - assert all("new-session" not in argv[-1] for argv in fake.calls) - # 自動選択でも使用中の GPU は選ばない - assert cli.main(["run", "--name", "t", "--no-push", "--", "x"]) == 1 - assert all("new-session" not in argv[-1] for argv in fake.calls) - # --force を付けたときだけ使う - assert cli.main([*args, "--force", "--", "x"]) == 0 - assert "new-session" in fake.calls[-1][-1] - - def test_cpu_launch_hides_gpus(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - fake = _free_everywhere(monkeypatch) - assert cli.main(["run", "--name", "t", "--cpu", "--no-push", "--", "tsm-export"]) == 0 - script = shlex.split(shlex.split(fake.calls[-1][-1])[-1])[2] - assert "export CUDA_VISIBLE_DEVICES=''" in script - assert "gpu=なし(CPU)" in script - - @pytest.mark.parametrize("name", ["a b", "x;id", "-x", "_x", "a.b", "a/b", "$(id)"]) - def test_bad_job_name_is_rejected_before_ssh( - self, project: Path, monkeypatch: pytest.MonkeyPatch, name: str - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - try: - rc = cli.main(["run", "--name", name, "--", "x"]) - except SystemExit as exc: # - 始まりは argparse が引数の誤りとして止める - rc = exc.code - assert rc in (1, 2) - assert fake.calls == [] - - def test_session_exists_returns_91( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - probe = _ok(_probe_stdout([(0, 5, 0)])) - - def respond(argv: list[str]) -> cli._SshResult: - if "new-session" in argv[-1]: - return cli._SshResult(91, b"", b"tsm-remote: tmux session already exists: t") - return probe(argv) - - monkeypatch.setattr( - cli, "_run_ssh", FakeSsh({NEWTON_ADDR: respond, ARCHIMEDES_ADDR: probe}) - ) - assert cli.main(["run", "--name", "t", "--no-push", "--", "x"]) == 91 - - -class TestArgumentErrors: - @pytest.mark.parametrize( - "args", - [ - [], - ["unknown"], - ["run", "--", "x"], # --name が無い - ["run", "--name", "t", "--gpu", "x", "--", "x"], - ["pull"], - ["pull", RUN_ID, "--bogus"], - ["logs"], - ], - ) - def test_argument_errors_exit_2( - self, project: Path, monkeypatch: pytest.MonkeyPatch, args: list[str] - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - with pytest.raises(SystemExit) as excinfo: - cli.main(args) - assert excinfo.value.code == 2 - assert fake.calls == [] - - def test_config_option_is_used( - self, project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path - ) -> None: - other = tmp_path / "other.yaml" - other.write_text(CONFIG_YAML.replace("jump_host: labpc", "jump_host: otherjump"), "utf-8") - fake = _free_everywhere(monkeypatch) - assert cli.main(["gpus", "--config", str(other)]) == 0 - for argv in fake.calls: - assert argv[argv.index("-J") + 1] == "otherjump" - - def test_bad_config_is_error_1( - self, project: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path - ) -> None: - bad = tmp_path / "bad.yaml" - bad.write_text("servers: [\n", encoding="utf-8") - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["gpus", "--config", str(bad)]) == 1 - unknown = tmp_path / "unknown.yaml" - unknown.write_text(CONFIG_YAML + "data_dir: x\n", encoding="utf-8") - assert cli.main(["gpus", "--config", str(unknown)]) == 1 - assert fake.calls == [] - - -class TestPullMore: - def test_split_and_predictions_never_pulled_even_with_checkpoints( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - receive = FakeReceive() - _setup_pull(monkeypatch, receive) - assert cli.main(["pull", RUN_ID, "--with-checkpoints"]) == 0 - for name in ["split.json", "predictions.csv", "manifest.csv", "checkpoints/epoch3.pth"]: - assert f"{RUN_ID}/{name}" not in receive.requested - assert not (project / "runs" / RUN_ID / name).exists() - - def test_run_dir_link_on_server_is_refused( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - receive = FakeReceive() - fake = FakeSsh( - {NEWTON_ADDR: _fail(rc=94, stderr=b""), ARCHIMEDES_ADDR: _fail(rc=92, stderr=b"")} - ) - monkeypatch.setattr(cli, "_run_ssh", fake) - monkeypatch.setattr(cli, "_receive_tar", receive) - assert cli.main(["pull", RUN_ID]) != 0 - assert receive.requested == [] - assert _local_files(project) == [] - - def test_nothing_to_pull_is_error(self, project: Path, monkeypatch: pytest.MonkeyPatch) -> None: - listing = f"f {RUN_ID}/split.json\0f {RUN_ID}/predictions.csv\0".encode() - receive = FakeReceive() - fake = FakeSsh({NEWTON_ADDR: _ok(listing), ARCHIMEDES_ADDR: _fail(rc=92, stderr=b"")}) - monkeypatch.setattr(cli, "_run_ssh", fake) - monkeypatch.setattr(cli, "_receive_tar", receive) - assert cli.main(["pull", RUN_ID]) == 1 - assert receive.requested == [] - - def test_make_run_id_is_accepted_by_pull( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """`tsm-train` の実験 ID(-dirty 付き)で pull できる.""" - from datetime import datetime - - from tongue_seg_model.training.run_artifacts import make_run_id - - run_id = make_run_id(datetime(2026, 11, 19, 1, 2, 3), "synthetic-gpu", "abc1234-dirty") - listing = f"f {run_id}/config.yaml\0f {run_id}/split.json\0".encode() - receive = FakeReceive() - fake = FakeSsh({NEWTON_ADDR: _ok(listing), ARCHIMEDES_ADDR: _fail(rc=92, stderr=b"")}) - monkeypatch.setattr(cli, "_run_ssh", fake) - monkeypatch.setattr(cli, "_receive_tar", receive) - assert cli.main(["pull", run_id]) == 0 - assert receive.requested == [f"{run_id}/config.yaml"] - assert (project / "runs" / run_id / "config.yaml").is_file() - assert not (project / "runs" / run_id / "split.json").exists() - - -class TestLogsAndKill: - def test_logs_not_found_anywhere_is_error( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - missing = _fail(rc=EXIT_NOT_FOUND, stderr=b"") - monkeypatch.setattr( - cli, "_run_ssh", FakeSsh({NEWTON_ADDR: missing, ARCHIMEDES_ADDR: missing}) - ) - assert cli.main(["logs", "train1"]) != 0 - - def test_logs_shows_tail_from_the_server_with_the_log( - self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] - ) -> None: - def newton(argv: list[str]) -> cli._SshResult: - if "tail" in argv[-1]: - return cli._SshResult(0, b"epoch 1\n", b"") - return cli._SshResult(0, b"", b"") - - fake = FakeSsh({NEWTON_ADDR: newton, ARCHIMEDES_ADDR: _fail(rc=EXIT_NOT_FOUND, stderr=b"")}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["logs", "train1", "-n", "5"]) == 0 - assert "epoch 1" in capsys.readouterr().out - assert "tail -n 5 runs/_remote_logs/train1.log" in fake.calls[-1][-1] - - def test_kill_refuses_non_job_session( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - lines = [ - PROBE_SESSIONS_MARKER, - "other mywork", - PROBE_GPUS_MARKER, - f"{PROBE_GPU_RC_PREFIX}127", - ] - text = ("\n".join([*lines, PROBE_END_MARKER]) + "\n").encode() - fake = FakeSsh({NEWTON_ADDR: _ok(text), ARCHIMEDES_ADDR: _ok(text)}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["kill", "mywork"]) == 1 - assert all("kill-session" not in argv[-1] for argv in fake.calls) - - -# --------------------------------------------------------------------------- -# 安全策の補強: Windows の予約名・末尾の `.`,送らなかったリンクの表示,--env の NUL -# --------------------------------------------------------------------------- - - -# project が subprocess.run・Popen を差し替える前の本物(ジャンクションを作る mklink だけに使う) -_REAL_POPEN = subprocess.Popen - - -def _symlink_or_skip(link: Path, target: Path) -> None: - """tmp_path の中に link → target のシンボリックリンクを作る(作れなければ skip).""" - try: - os.symlink(target, link, target_is_directory=target.is_dir()) - except (OSError, NotImplementedError) as exc: - code = getattr(exc, "winerror", None) or getattr(exc, "errno", None) - pytest.skip(f"この環境ではシンボリックリンクを作れない({type(exc).__name__} {code})") - - -@pytest.fixture -def junction_or_skip() -> Iterator[Callable[[Path, Path], None]]: - """link → target のジャンクションを作る関数(Windows のみ).後始末でリンクだけを外す.""" - created: list[Path] = [] - - def make(link: Path, target: Path) -> None: - if sys.platform != "win32": - pytest.skip("ジャンクションは Windows のみ") - # project が subprocess.run・Popen を差し替えるため,読み込み時の本物を使う - with _REAL_POPEN( - ["cmd", "/c", "mklink", "/J", str(link), str(target)], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - ) as process: - returncode = process.wait() - if returncode != 0 or not os.path.isjunction(link): - pytest.skip("この環境ではジャンクションを作れない") - created.append(link) - - yield make - for link in reversed(created): - if os.path.isjunction(link): - os.rmdir(link) - - -@pytest.fixture -def outside(tmp_path: Path) -> Path: - """「リポジトリの外」役のフォルダ(tmp_path の中.project とは別のフォルダ).""" - root = tmp_path / "outside" - (root / "patients").mkdir(parents=True) - (root / "patients" / "P0001_yamada.png").write_bytes(b"png") - (root / "secret_code.py").write_bytes(b"x") - return root - - -class TestPushDryRunLinks: - def _dry_run(self, monkeypatch: pytest.MonkeyPatch) -> tuple[FakeSsh, int]: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - return fake, cli.main(["push", "--dry-run"]) - - def test_no_links_reports_zero( - self, project: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] - ) -> None: - fake, rc = self._dry_run(monkeypatch) - assert rc == 0 - assert "送らなかったリンク: 0 件" in capsys.readouterr().out - assert fake.calls == [] - - def test_directory_junction_to_outside_is_reported_and_not_listed( - self, - project: Path, - outside: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - junction_or_skip: Callable[[Path, Path], None], - ) -> None: - junction_or_skip(project / "src" / "ext", outside) - fake, rc = self._dry_run(monkeypatch) - assert rc == 0 - out = capsys.readouterr().out - assert "送らなかったリンク: 1 件" in out - assert "src/ext" in out - assert "P0001_yamada" not in out - assert "secret_code" not in out - assert "pyproject.toml" in out - assert fake.calls == [] - - def test_symlinks_are_counted( - self, - project: Path, - outside: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - ) -> None: - _symlink_or_skip(project / "leak.py", outside / "secret_code.py") - _symlink_or_skip(project / "src" / "data_alias", outside / "patients") - fake, rc = self._dry_run(monkeypatch) - assert rc == 0 - out = capsys.readouterr().out - assert "送らなかったリンク: 2 件" in out - assert "P0001_yamada" not in out - assert "secret_code" not in out - assert fake.calls == [] - - def test_links_in_excluded_directories_are_not_counted( - self, - project: Path, - outside: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - junction_or_skip: Callable[[Path, Path], None], - ) -> None: - (project / ".venv").mkdir() - junction_or_skip(project / ".venv" / "ext", outside) - fake, rc = self._dry_run(monkeypatch) - assert rc == 0 - assert "送らなかったリンク: 0 件" in capsys.readouterr().out - - -class TestWindowsUnsafeNamesInPull: - @pytest.mark.parametrize("run_id", ["abc.", "nul", "NUL", "con.txt", "Com1", "lpt9.x"]) - def test_reserved_or_trailing_dot_run_id_is_rejected_before_ssh( - self, project: Path, monkeypatch: pytest.MonkeyPatch, run_id: str - ) -> None: - fake = FakeSsh({}) - monkeypatch.setattr(cli, "_run_ssh", fake) - assert cli.main(["pull", run_id]) != 0 - assert fake.calls == [] - assert not (project / "runs").exists() - - @pytest.mark.parametrize( - "extra", - [ - f"{RUN_ID}/figures/CON.png", - f"{RUN_ID}/figures/nul.png", - f"{RUN_ID}/figures/COM1.png", - f"{RUN_ID}/figures/LPT9.png", - f"{RUN_ID}/figures/Aux.x.png", - f"{RUN_ID}/figures/nul .png", - f"{RUN_ID}/config.yaml.", - ], - ) - def test_archive_with_reserved_name_extracts_nothing( - self, project: Path, monkeypatch: pytest.MonkeyPatch, extra: str - ) -> None: - _setup_pull(monkeypatch, FakeReceive(extra=[extra])) - assert cli.main(["pull", RUN_ID]) != 0 - assert _local_files(project) == [] - - -class TestEnvNul: - @pytest.mark.parametrize("item", ["A=x\x00y", "TIASDATA_BUNDLES=\x00"]) - def test_nul_in_env_value_is_rejected_without_launch( - self, project: Path, monkeypatch: pytest.MonkeyPatch, item: str - ) -> None: - fake = _free_everywhere(monkeypatch) - assert cli.main(["run", "--name", "t", "--no-push", "--env", item, "--", "x"]) == 1 - assert all("new-session" not in argv[-1] for argv in fake.calls) - - def test_newline_in_env_value_reaches_job( - self, project: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - captured = _spy_job_script(monkeypatch) - _free_everywhere(monkeypatch) - args = ["run", "--name", "t", "--no-push", "--env", "CODE=a\nb", "--", "x"] - assert cli.main(args) == 0 - assert captured - assert captured[-1]["env"]["CODE"] == "a\nb" diff --git a/tests/remote/link_helpers.py b/tests/remote/link_helpers.py deleted file mode 100644 index 1bcc70a..0000000 --- a/tests/remote/link_helpers.py +++ /dev/null @@ -1,60 +0,0 @@ -"""テスト用にシンボリックリンク・ジャンクションを作る補助(push の送信対象からリンクを除くテスト). - -リンクはすべて tmp_path の中に作り,リンク先も tmp_path の中に置く(リポジトリの外の実在の -フォルダ・`legacy/`・`data/` を指さない).作れない環境では pytest.skip する. - -- シンボリックリンク: Windows では権限(開発者モード等)が無いと作れない(WinError 1314) -- ジャンクション: Windows で `cmd /c mklink /J` が使える場合だけ.それ以外の OS では skip -""" - -from __future__ import annotations - -import os -import subprocess -import sys -from pathlib import Path - -import pytest - - -class LinkFactory: - """リンクを作り,後始末でジャンクションのリンクだけを外す(リンク先は消さない).""" - - def __init__(self) -> None: - self._junctions: list[Path] = [] - - def symlink(self, link: Path, target: Path, *, is_dir: bool | None = None) -> Path: - """link → target のシンボリックリンクを作る(作れなければ skip).""" - link.parent.mkdir(parents=True, exist_ok=True) - directory = target.is_dir() if is_dir is None else is_dir - try: - os.symlink(target, link, target_is_directory=directory) - except (OSError, NotImplementedError) as exc: - code = getattr(exc, "winerror", None) or getattr(exc, "errno", None) - pytest.skip(f"この環境ではシンボリックリンクを作れない({type(exc).__name__} {code})") - return link - - def junction(self, link: Path, target: Path) -> Path: - """link → target のジャンクションを作る(Windows で作れなければ skip).""" - if sys.platform != "win32": - pytest.skip("ジャンクションは Windows のみ") - link.parent.mkdir(parents=True, exist_ok=True) - try: - result = subprocess.run( - ["cmd", "/c", "mklink", "/J", str(link), str(target)], - capture_output=True, - check=False, - ) - except OSError as exc: - pytest.skip(f"mklink を実行できない: {exc}") - if result.returncode != 0 or not os.path.isjunction(link): - pytest.skip("この環境ではジャンクションを作れない") - self._junctions.append(link) - return link - - def cleanup(self) -> None: - """ジャンクションを外す(tmp_path の後始末がリンク先をたどって消さないように).""" - for link in reversed(self._junctions): - if os.path.isjunction(link): - os.rmdir(link) - self._junctions.clear() diff --git a/tests/remote/probe_helpers.py b/tests/remote/probe_helpers.py deleted file mode 100644 index da7238c..0000000 --- a/tests/remote/probe_helpers.py +++ /dev/null @@ -1,79 +0,0 @@ -"""テスト用に probe コマンド(SPEC_03「取得」)の出力文字列を組み立てる補助関数. - -実サーバの nvidia-smi・ps を呼ばず,出力の文字列だけで判定を固定するために使う. -""" - -from __future__ import annotations - -from collections.abc import Sequence - -from tongue_seg_model.remote.commands import ( - PROBE_APPS_MARKER, - PROBE_APPS_RC_PREFIX, - PROBE_END_MARKER, - PROBE_GPU_RC_PREFIX, - PROBE_GPUS_MARKER, - PROBE_JOB_PREFIX, - PROBE_OTHER_PREFIX, - PROBE_OWNERS_MARKER, - PROBE_PMON_MARKER, - PROBE_SAMPLES_MARKER, - PROBE_SESSIONS_MARKER, - PROBE_USER_PREFIX, -) - -PMON_HEADER = [ - "# gpu pid type sm mem enc dec jpg ofa command", - "# Idx # C/G % % % % % % name", -] - - -def gpu_line(index: int, uuid: str, used: int, util: int, *, total: int = 49140) -> str: - """`nvidia-smi --query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu` の 1 行.""" - return f"{index}, {uuid}, NVIDIA RTX A6000, {used}, {total}, {util}" - - -def sample_lines(index: int, utils: Sequence[int], memory: int = 10) -> list[str]: - """観測サンプル(`index, 使用率, 使用中メモリ`)の行.""" - return [f"{index}, {util}, {memory}" for util in utils] - - -def probe_text( - gpus: Sequence[str], - *, - gpu_rc: int = 0, - samples: Sequence[str] | None = None, - pmon: Sequence[str] | None = None, - apps: Sequence[str] | None = (), - apps_rc: int = 0, - owners: Sequence[str] = (), - jobs: Sequence[str] = (), - others: Sequence[str] = (), - preamble: Sequence[str] = (), - remote_user: str | None = None, -) -> str: - """probe の出力を組み立てる(samples・pmon が None なら節を出さない.apps が None なら - 計算プロセスの節ごと出さない.remote_user が None なら `@@tsm-user` の行を出さない).""" - lines = [*preamble] - if remote_user is not None: - lines.append(f"{PROBE_USER_PREFIX}{remote_user}") - lines.append(PROBE_SESSIONS_MARKER) - lines += [f"{PROBE_JOB_PREFIX}{name}" for name in jobs] - lines += [f"{PROBE_OTHER_PREFIX}{name}" for name in others] - lines.append(PROBE_GPUS_MARKER) - lines += list(gpus) - lines.append(f"{PROBE_GPU_RC_PREFIX}{gpu_rc}") - if samples is not None: - lines.append(PROBE_SAMPLES_MARKER) - lines += list(samples) - if pmon is not None: - lines.append(PROBE_PMON_MARKER) - lines += list(pmon) - if apps is not None: - lines.append(PROBE_APPS_MARKER) - lines += list(apps) - lines.append(f"{PROBE_APPS_RC_PREFIX}{apps_rc}") - lines.append(PROBE_OWNERS_MARKER) - lines += list(owners) - lines.append(PROBE_END_MARKER) - return "\n".join(lines) + "\n" diff --git a/tests/remote/test_commands.py b/tests/remote/test_commands.py deleted file mode 100644 index 5d1ad61..0000000 --- a/tests/remote/test_commands.py +++ /dev/null @@ -1,618 +0,0 @@ -"""ssh 引数とサーバ上で実行するコマンドの組み立てのテスト(SPEC_03「接続」「取得」「run」). - -TIASJudgeModel の tests/remote/test_commands.py の移植.本リポジトリでの変更(接続先は -`host` と省略できる `user`・probe の `@@tsm-user`・`TIAS_DATA_ROOT` の削除・書式の検証は -`fullmatch`)と,シェルの特殊文字を含む引数の引用の確認を足した. - -シェルでの解釈は `shlex.split`(POSIX)で確かめる(リモートの bash を起動しない). -""" - -from __future__ import annotations - -import shlex - -import pytest - -from tongue_seg_model.remote.commands import ( - GIT_COMMIT_ENV_VAR, - NO_GPU_LABEL, - PROBE_END_MARKER, - PROBE_SESSIONS_MARKER, - PROBE_USER_PREFIX, - build_job_env, - build_job_script, - build_kill_command, - build_log_exists_command, - build_logs_command, - build_probe_command, - build_pull_list_command, - build_pull_tar_command, - build_push_command, - build_run_command, - build_ssh_argv, - format_git_commit, - job_log_path, - parse_env_assignment, - quote_remote_path, - validate_env_key, - validate_job_name, - validate_ssh_token, -) - -# シェルが特別に解釈する文字を含む引数(空白・引用符・; ・$()・バッククォート・改行・グロブ等) -NASTY_ARGS = [ - "a b", - "it's", - 'say "hi"', - "x; rm -rf ~", - "$(id)", - "`id`", - "$HOME", - "a\nb", - "*", - "a|b&c>d list[str]: - return build_ssh_argv( - "ssh", - host="192.168.23.14", - user="hasegawa", - jump_host=jump, - connect_timeout_sec=timeout, - remote_command="echo hi", - ) - - -def _has_option(argv: list[str], value: str) -> bool: - return any(argv[i] == "-o" and argv[i + 1] == value for i in range(len(argv) - 1)) - - -class TestBuildSshArgv: - def test_with_jump_host(self) -> None: - argv = _argv("labpc") - assert argv[0] == "ssh" - j = argv.index("-J") - assert argv[j + 1] == "labpc" - assert "hasegawa@192.168.23.14" in argv - assert argv[-1] == "echo hi" - # 接続先より前にオプションがある - assert j < argv.index("hasegawa@192.168.23.14") - - def test_without_jump_host(self) -> None: - argv = _argv(None) - assert "-J" not in argv - assert "hasegawa@192.168.23.14" in argv - - @pytest.mark.parametrize("jump", ["labpc", None]) - def test_batch_mode_and_timeout_always(self, jump: str | None) -> None: - argv = _argv(jump, timeout=7) - assert _has_option(argv, "BatchMode=yes") - assert _has_option(argv, "ConnectTimeout=7") - - def test_without_user_uses_host_only(self) -> None: - # ~/.ssh/config の Host 名だけを渡す(アドレス・ユーザー名・鍵は手元の ssh の設定) - argv = build_ssh_argv( - "ssh", - host="Newton", - user=None, - jump_host="labpc", - connect_timeout_sec=15, - remote_command="true", - ) - assert argv[-2:] == ["Newton", "true"] - assert not any("@" in arg for arg in argv[:-1]) - - def test_no_stdin_adds_n_and_stdin_omits_it(self) -> None: - kwargs = { - "host": "Newton", - "user": None, - "jump_host": None, - "connect_timeout_sec": 5, - "remote_command": "true", - } - assert "-n" in build_ssh_argv("ssh", **kwargs) - assert "-n" not in build_ssh_argv("ssh", stdin=True, **kwargs) - - def test_remote_command_is_single_argument(self) -> None: - argv = build_ssh_argv( - "ssh", - host="h", - user="u", - jump_host=None, - connect_timeout_sec=5, - remote_command="cd ~/x; echo a b", - ) - assert argv[-1] == "cd ~/x; echo a b" - - @pytest.mark.parametrize( - "bad", ["-oProxyCommand=evil", "a b", "", "h\n", "h;id", "$(id)", "h'", "h/x"] - ) - @pytest.mark.parametrize("field", ["host", "user", "jump_host"]) - def test_rejects_option_like_or_unsafe_destination(self, bad: str, field: str) -> None: - kwargs = {"host": "h", "user": "u", "jump_host": None} - kwargs[field] = bad - with pytest.raises(ValueError): - build_ssh_argv("ssh", connect_timeout_sec=5, remote_command="true", **kwargs) - - def test_timeout_must_be_positive(self) -> None: - with pytest.raises(ValueError): - _argv(None, timeout=0) - - -class TestValidateSshToken: - @pytest.mark.parametrize( - "value", ["Newton", "192.168.23.14", "user_1", "a.b-c", "fe80::1%eth0"] - ) - def test_valid(self, value: str) -> None: - assert validate_ssh_token(value, what="x") == value - - @pytest.mark.parametrize("value", ["", "-J", "a b", "a\n", "a\tb", "a;b", "a$b", "a'b"]) - def test_invalid(self, value: str) -> None: - with pytest.raises(ValueError): - validate_ssh_token(value, what="x") - - -class TestQuoteRemotePath: - def test_tilde_is_expanded_by_remote_shell(self) -> None: - assert quote_remote_path("~/work/TongueSegModel") == '"$HOME"/work/TongueSegModel' - assert quote_remote_path("~") == '"$HOME"' - - def test_special_characters_are_quoted(self) -> None: - quoted = quote_remote_path("~/a b;$(id)") - assert quoted.startswith('"$HOME"/') - assert shlex.split(quoted) == ["$HOME/a b;$(id)"] - - def test_absolute_path(self) -> None: - assert shlex.split(quote_remote_path("/srv/x y")) == ["/srv/x y"] - - @pytest.mark.parametrize("bad", ["", " ", "~root/x"]) - def test_rejects_empty_and_other_users_home(self, bad: str) -> None: - with pytest.raises(ValueError): - quote_remote_path(bad) - - -class TestBuildProbeCommand: - def test_queries_listed_in_spec(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) - assert "--query-gpu=index,uuid,name,memory.used,memory.total,utilization.gpu" in command - assert "--query-compute-apps=gpu_uuid,pid,used_memory" in command - assert "--format=csv,noheader,nounits" in command - - def test_observation_uses_interval_and_duration(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) - assert "-lms 500" in command - assert "timeout 10" in command - assert "pmon -s u" in command - - def test_observe_zero_does_not_observe(self) -> None: - command = build_probe_command("~/work/x", observe_sec=0, sample_interval_ms=500) - assert "-lms" not in command - assert "pmon" not in command - assert "--query-gpu=index,uuid,name" in command - - def test_is_single_line(self) -> None: - command = build_probe_command("~/work/x", observe_sec=10, sample_interval_ms=500) - assert "\n" not in command - - def test_reports_own_user_before_sessions(self) -> None: - # 自分の利用者名を id -un で取る(設定の user を省略できるため.移植元との違い) - command = build_probe_command("~/work/x", observe_sec=0, sample_interval_ms=500) - assert f"{PROBE_USER_PREFIX}$(id -un" in command - assert command.index(PROBE_USER_PREFIX) < command.index(PROBE_SESSIONS_MARKER) - assert command.rstrip().endswith(f"echo '{PROBE_END_MARKER}'") - - def test_markers_use_tsm_prefix(self) -> None: - command = build_probe_command("~/work/x", observe_sec=3, sample_interval_ms=500) - assert "@@tias" not in command - assert "@@tsm-" in command - - @pytest.mark.parametrize(("observe", "interval"), [(-1, 500), (0, 0)]) - def test_rejects_bad_observation(self, observe: int, interval: int) -> None: - with pytest.raises(ValueError): - build_probe_command("~/work/x", observe_sec=observe, sample_interval_ms=interval) - - -class TestJobSettings: - @pytest.mark.parametrize("name", ["a", "exp1", "Exp_1-b", "x" * 64, "0"]) - def test_valid_job_names(self, name: str) -> None: - assert validate_job_name(name) == name - - @pytest.mark.parametrize( - "name", - [ - "", - "_a", - "-a", - "a b", - "a.b", - "a:b", - "x" * 65, - "a/b", - # 末尾の改行(match と $ の組み合わせでは通ってしまう) - "exp1\n", - "..", - "a..b", - "a\\b", - "a'b", - 'a"b', - "a;b", - "a$b", - "$(id)", - "a\tb", - "ジョブ", - ], - ) - def test_invalid_job_names(self, name: str) -> None: - with pytest.raises(ValueError): - validate_job_name(name) - - def test_job_env_contains_selected_gpu_and_extra(self) -> None: - env = build_job_env(2, ["FOO=bar", "EMPTY="]) - assert env["CUDA_VISIBLE_DEVICES"] == "2" - assert env["FOO"] == "bar" - assert env["EMPTY"] == "" - - def test_job_env_value_may_contain_equals_and_specials(self) -> None: - env = build_job_env(0, ["A=x=y", "B=$(id); rm -rf ~"]) - assert env["A"] == "x=y" - assert env["B"] == "$(id); rm -rf ~" - - def test_negative_gpu_index_is_rejected(self) -> None: - with pytest.raises(ValueError): - build_job_env(-1, []) - - @pytest.mark.parametrize("item", ["NOEQUALS", "=x", "1A=x", "A B=x", "A\n=x", "A-B=x", "$A=x"]) - def test_bad_env_assignment_is_rejected(self, item: str) -> None: - with pytest.raises(ValueError): - build_job_env(0, [item]) - - @pytest.mark.parametrize("key", ["A", "_x", "TIASDATA_BUNDLES", "a1_B"]) - def test_valid_env_keys(self, key: str) -> None: - assert validate_env_key(key) == key - assert parse_env_assignment(f"{key}=v") == (key, "v") - - @pytest.mark.parametrize( - "key", ["", "1A", "A\n", "A B", "A-B", "A;B", "A$", "A'", "A.B", "A=B", "AB"] - ) - def test_invalid_env_keys(self, key: str) -> None: - with pytest.raises(ValueError): - validate_env_key(key) - - @pytest.mark.parametrize("item", ["A=x\x00y", "A=\x00", "A=x\x00", "TIASDATA_BUNDLES=a\x00b"]) - def test_nul_in_env_value_is_rejected(self, item: str) -> None: - with pytest.raises(ValueError): - parse_env_assignment(item) - with pytest.raises(ValueError): - build_job_env(0, [item]) - - def test_nul_error_message_names_key(self) -> None: - with pytest.raises(ValueError, match="NUL"): - parse_env_assignment("FOO=x\x00y") - - @pytest.mark.parametrize( - ("item", "expected"), - [ - ("A=x\ny", ("A", "x\ny")), - ("A=x\r\ny", ("A", "x\r\ny")), - ("A=\t", ("A", "\t")), - ("A=\x01", ("A", "\x01")), - ], - ) - def test_newline_and_other_controls_in_value_pass( - self, item: str, expected: tuple[str, str] - ) -> None: - """改行は通る(`python -c` のコードを渡すため.引用して渡す仕様).""" - assert parse_env_assignment(item) == expected - assert build_job_env(0, [item])[expected[0]] == expected[1] - - -class TestGitCommit: - """`TSM_GIT_COMMIT`(SPEC_03「run」・SPEC_01「実験の出力」).""" - - def test_env_var_name(self) -> None: - assert GIT_COMMIT_ENV_VAR == "TSM_GIT_COMMIT" - - def test_clean_tree_passes_short_hash(self) -> None: - # git rev-parse --short HEAD の出力(末尾改行付き) - assert format_git_commit("abc1234\n", dirty=False) == "abc1234" - - def test_dirty_tree_appends_suffix(self) -> None: - assert format_git_commit("abc1234\n", dirty=True) == "abc1234-dirty" - - @pytest.mark.parametrize( - "bad", - [ - "", - "abc", # 短すぎる - "ABC1234", # 大文字は git の出力ではない - "abc1234;id", - "abc 1234", - "abc1234\nxyz", - "$(id)", - "abc1234..", - "fatal: not a git repository", - "a" * 41, - ], - ) - def test_unexpected_git_output_is_not_passed(self, bad: str) -> None: - assert format_git_commit(bad, dirty=False) is None - assert format_git_commit(bad, dirty=True) is None - - def test_job_env_contains_git_commit(self) -> None: - env = build_job_env(0, [], git_commit="abc1234-dirty") - assert env["TSM_GIT_COMMIT"] == "abc1234-dirty" - - def test_job_env_without_git_commit_does_not_set_it(self) -> None: - env = build_job_env(0, []) - assert "TSM_GIT_COMMIT" not in env - - @pytest.mark.parametrize("git_commit", ["abc1234", None]) - def test_env_option_cannot_override_git_commit(self, git_commit: str | None) -> None: - # git が使えず渡さないときも --env で指定させない(実験の記録を迂回させないため) - with pytest.raises(ValueError): - build_job_env(0, ["TSM_GIT_COMMIT=fake"], git_commit=git_commit) - - -class TestReservedEnv: - @pytest.mark.parametrize( - "key", - [ - "CUDA_VISIBLE_DEVICES", - "CUDA_DEVICE_ORDER", - "PYTHONUNBUFFERED", - "TSM_GIT_COMMIT", - ], - ) - @pytest.mark.parametrize("gpu_index", [0, None]) - @pytest.mark.parametrize("git_commit", ["abc1234", None]) - def test_reserved_keys_cannot_be_overridden( - self, key: str, gpu_index: int | None, git_commit: str | None - ) -> None: - with pytest.raises(ValueError): - build_job_env(gpu_index, [f"{key}=x"], git_commit=git_commit) - - def test_reserved_key_rejected_even_after_other_keys(self) -> None: - with pytest.raises(ValueError): - build_job_env(0, ["FOO=1", "CUDA_VISIBLE_DEVICES=0,1"]) - - def test_tias_data_root_is_no_longer_special(self) -> None: - # 移植元の TIAS_DATA_ROOT は外した(本リポジトリはバンドルだけを読む.SPEC_03) - env = build_job_env(0, ["TIASDATA_BUNDLES=data/synthetic"]) - assert env["TIASDATA_BUNDLES"] == "data/synthetic" - assert "TIAS_DATA_ROOT" not in env - - def test_fixed_values(self) -> None: - env = build_job_env(3, [], git_commit="abc1234") - assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID" - assert env["PYTHONUNBUFFERED"] == "1" - assert env["CUDA_VISIBLE_DEVICES"] == "3" - - -def _script( - gpu_index: int | None, command: list[str] | None = None, extra: list[str] | None = None -) -> str: - return build_job_script( - "~/work/TongueSegModel", - "train1", - command or ["tsm-train", "--config", "configs/synthetic-gpu.yaml"], - uv_path="~/.local/bin/uv", - server_name="Newton", - gpu_index=gpu_index, - env=build_job_env(gpu_index, extra or [], git_commit="abc1234"), - path_env={}, - ) - - -class TestCpuJob: - """`run --cpu`(SPEC_03「run」). - - CUDA_VISIBLE_DEVICES を空文字で渡し,ログの開始行の GPU は「なし(CPU)」とする. - """ - - def test_cpu_job_env_hides_gpus(self) -> None: - env = build_job_env(None, ["FOO=bar"], git_commit="abc1234") - assert "CUDA_VISIBLE_DEVICES" in env - assert env["CUDA_VISIBLE_DEVICES"] == "" - assert env["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID" - assert env["TSM_GIT_COMMIT"] == "abc1234" - assert env["FOO"] == "bar" - - def test_cpu_job_log_header_says_no_gpu(self) -> None: - script = _script(None) - assert f"gpu={NO_GPU_LABEL}" in script - assert "gpu=なし(CPU)" in script - assert "gpu=None" not in script - # 空文字として export する(未設定ではなく空にして GPU を見えなくする) - assert "export CUDA_VISIBLE_DEVICES=''" in script - - def test_gpu_job_log_header_has_index(self) -> None: - script = _script(1) - assert "gpu=1" in script - assert "なし(CPU)" not in script - assert "export CUDA_VISIBLE_DEVICES=1" in script - assert "export TSM_GIT_COMMIT=abc1234" in script - - -def _uv_run_args(script: str) -> list[str]: - """ジョブ本体のスクリプトから,`uv run` に渡る引数(シェルが解釈した後)を取り出す.""" - tokens = shlex.split(script) - start = tokens.index("$HOME/.local/bin/uv") + 1 - assert tokens[start] == "run" - end = tokens.index("<", start) - return tokens[start + 1 : end] - - -class TestJobScriptQuoting: - """シェルの特殊文字を含む引数が,そのまま 1 つの引数として `uv run` に渡ること.""" - - def test_plain_command(self) -> None: - script = _script(0) - assert _uv_run_args(script) == ["tsm-train", "--config", "configs/synthetic-gpu.yaml"] - - @pytest.mark.parametrize("arg", NASTY_ARGS) - def test_each_nasty_argument_is_one_word(self, arg: str) -> None: - command = ["tsm-train", "--config", arg] - assert _uv_run_args(_script(0, command)) == command - - def test_all_nasty_arguments_together(self) -> None: - command = ["tsm-train", *NASTY_ARGS] - assert _uv_run_args(_script(0, command)) == command - - def test_env_values_are_quoted(self) -> None: - value = "x'; touch /tmp/pwned; echo '$(id)" - tokens = shlex.split(_script(0, extra=[f"FOO={value}"])) - assert f"FOO={value};" in tokens or f"FOO={value}" in tokens - - def test_script_runs_in_remote_dir_and_logs(self) -> None: - script = _script(0) - assert script.startswith('cd "$HOME"/work/TongueSegModel || ') - assert "runs/_remote_logs/train1.log" in script - assert "rc=${PIPESTATUS[0]}" in script - assert "< /dev/null" in script - assert "\n" not in script - - def test_path_is_extended_with_uv_dir(self) -> None: - script = _script(0) - assert 'export PATH="$(dirname -- "$HOME"/.local/bin/uv)":"$HOME/.local/bin:$PATH"' in ( - script - ) - - def test_exports_required_env(self) -> None: - script = _script(2) - for statement in [ - "export CUDA_DEVICE_ORDER=PCI_BUS_ID", - "export CUDA_VISIBLE_DEVICES=2", - "export PYTHONUNBUFFERED=1", - "export TSM_GIT_COMMIT=abc1234", - ]: - assert statement in script - - def test_empty_command_is_rejected(self) -> None: - with pytest.raises(ValueError): - build_job_script( - "~/w", - "j", - [], - uv_path="~/.local/bin/uv", - server_name="Newton", - gpu_index=0, - env={}, - path_env={}, - ) - - @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", "-j"]) - def test_bad_job_name_is_rejected(self, name: str) -> None: - with pytest.raises(ValueError): - build_job_script( - "~/w", - name, - ["true"], - uv_path="~/.local/bin/uv", - server_name="Newton", - gpu_index=0, - env={}, - path_env={}, - ) - - @pytest.mark.parametrize("key", ["A B", "A;id", "1A", "A\n"]) - def test_bad_env_key_in_mapping_is_rejected(self, key: str) -> None: - with pytest.raises(ValueError): - build_job_script( - "~/w", - "j", - ["true"], - uv_path="~/.local/bin/uv", - server_name="Newton", - gpu_index=0, - env={key: "v"}, - path_env={}, - ) - - -class TestRunCommand: - def test_job_script_round_trips_through_tmux_and_bash_c(self) -> None: - """tmux → `bash -c` の 2 段の引用を外すと,元のジョブ本体に戻る.""" - script = _script(0, ["tsm-train", *NASTY_ARGS]) - command = build_run_command("~/work/TongueSegModel", "train1", script) - tokens = shlex.split(command) - i = tokens.index("new-session") - assert tokens[i : i + 7] == [ - "new-session", - "-d", - "-s", - "train1", - "-c", - "$PWD", - tokens[i + 6], - ] - inner = shlex.split(tokens[i + 6]) - assert inner == ["bash", "-c", script] - - def test_refuses_existing_session_with_exact_match(self) -> None: - command = build_run_command("~/w", "train1", "true") - # = を前置して完全一致(前方一致で別のジョブを選ばない) - assert "tmux has-session -t =train1 " in command - assert "exit 91" in command - - @pytest.mark.parametrize("name", ["a b", "x;id", "j\n", ""]) - def test_bad_name_is_rejected(self, name: str) -> None: - with pytest.raises(ValueError): - build_run_command("~/w", name, "true") - - -class TestOtherCommands: - def test_push_extracts_into_remote_dir(self) -> None: - assert build_push_command("~/work/TongueSegModel") == ( - 'mkdir -p "$HOME"/work/TongueSegModel && tar -xf - -C "$HOME"/work/TongueSegModel' - ) - - def test_push_quotes_remote_dir(self) -> None: - tokens = shlex.split(build_push_command("/srv/a b;id")) - assert tokens == [ - "mkdir", - "-p", - "/srv/a b;id", - "&&", - "tar", - "-xf", - "-", - "-C", - "/srv/a b;id", - ] - - def test_logs_command(self) -> None: - command = build_logs_command("~/w", "train1", lines=50, follow=False) - assert "tail -n 50 runs/_remote_logs/train1.log" in command - follow = build_logs_command("~/w", "train1", lines=10, follow=True) - assert "-F" in follow and "cat >/dev/null" in follow - - def test_logs_rejects_negative_lines_and_bad_name(self) -> None: - with pytest.raises(ValueError): - build_logs_command("~/w", "train1", lines=-1, follow=False) - with pytest.raises(ValueError): - build_logs_command("~/w", "a;b", lines=1, follow=False) - - def test_log_exists_and_kill_validate_name(self) -> None: - for build in (build_log_exists_command, build_kill_command): - with pytest.raises(ValueError): - build("~/w", "x$(id)") - assert "tmux kill-session -t =train1" in build_kill_command("~/w", "train1") - assert job_log_path("train1") == "runs/_remote_logs/train1.log" - - def test_pull_list_command_quotes_run_id_and_refuses_links(self) -> None: - command = build_pull_list_command("~/work/TongueSegModel", "20261119-120000_x_abc1234") - assert 'cd "$HOME"/work/TongueSegModel/runs' in command - assert "[ -L 20261119-120000_x_abc1234 ]" in command - assert "exit 94" in command - assert "! -type d -printf '%y %p\\0'" in command - - def test_pull_tar_reads_only_given_names(self) -> None: - command = build_pull_tar_command("~/work/TongueSegModel") - assert "tar --null --no-recursion -T - -cf -" in command diff --git a/tests/remote/test_config.py b/tests/remote/test_config.py deleted file mode 100644 index b31db16..0000000 --- a/tests/remote/test_config.py +++ /dev/null @@ -1,440 +0,0 @@ -"""サーバ設定の検証と環境変数の上書きのテスト(SPEC_03「サーバ設定」「サーバ上での誤実行の防止」). - -TIASJudgeModel の tests/remote/test_config.py の移植.本リポジトリでの変更(`address`・`user` の -省略・`data_dir` の削除・サーバ名は英数字で始まる・YAML として読めないときの ValueError)を足した. -""" - -from __future__ import annotations - -import re -from pathlib import Path - -import pytest -import yaml -from pydantic import ValidationError - -from tongue_seg_model.remote.config import ( - detect_self_server, - is_self_check_disabled, - load_remote_config, - resolve_jump_host, - resolve_ssh_executable, -) - -REPO_ROOT = Path(__file__).resolve().parents[2] - - -def _base() -> dict: - return { - "jump_host": "labpc", - "connect_timeout_sec": 15, - "gpu_free": { - "max_memory_used_mib": 1024, - "max_utilization_percent": 10, - "observe_sec": 10, - "sample_interval_ms": 500, - }, - "servers": [ - { - "name": "Newton", - "address": "192.168.23.14", - "user": "hasegawa", - "priority": 1, - "remote_dir": "~/work/TongueSegModel", - "uv": "~/.local/bin/uv", - "data_ready": True, - }, - { - "name": "Archimedes", - "address": "192.168.23.15", - "user": "hasegawa", - "priority": 2, - "remote_dir": "~/work/TongueSegModel", - "uv": "~/.local/bin/uv", - "data_ready": False, - }, - ], - } - - -def _write(tmp_path: Path, data: dict) -> Path: - path = tmp_path / "remote.yaml" - path.write_text(yaml.safe_dump(data, allow_unicode=True), encoding="utf-8") - return path - - -def _invalid(tmp_path: Path, data: dict) -> None: - with pytest.raises(ValidationError): - load_remote_config(_write(tmp_path, data)) - - -# --------------------------------------------------------------------------- -# リポジトリの configs/remote.yaml -# --------------------------------------------------------------------------- - - -def test_repository_remote_yaml_loads() -> None: - config = load_remote_config(REPO_ROOT / "configs" / "remote.yaml") - assert [s.name for s in config.ordered_servers()] == ["Newton", "Archimedes"] - assert config.jump_host == "labpc" - for server in config.servers: - assert server.remote_dir == "~/work/TongueSegModel" - assert server.uv == "~/.local/bin/uv" - - -def test_repository_remote_yaml_has_no_address_user_or_key() -> None: - """アドレス・ユーザー名・鍵の場所はリポジトリに書かない(手元の ~/.ssh/config から決める).""" - path = REPO_ROOT / "configs" / "remote.yaml" - config = load_remote_config(path) - for server in config.servers: - assert server.address is None - assert server.user is None - assert server.ssh_host == server.name - text = path.read_text(encoding="utf-8") - raw = yaml.safe_load(text) - for server in raw["servers"]: - assert "address" not in server - assert "user" not in server - # コメントを含めて,IPv4 アドレス・鍵の場所・ユーザー名・アドレスの指定が無いこと - assert not re.search(r"\b\d{1,3}(\.\d{1,3}){3}\b", text) - assert not re.search(r"(?i)identityfile|id_rsa|id_ed25519|id_ecdsa|\.pem\b", text) - assert not re.search(r"(?m)^\s*(-\s*)?(user|address)\s*:", text) - assert "hasegawa" not in text - - -# --------------------------------------------------------------------------- -# 検証 -# --------------------------------------------------------------------------- - - -def test_valid_config_loads(tmp_path: Path) -> None: - config = load_remote_config(_write(tmp_path, _base())) - assert [s.name for s in config.servers] == ["Newton", "Archimedes"] - assert config.jump_host == "labpc" - assert config.gpu_free.observe_sec == 10 - assert config.servers[1].data_ready is False - - -def test_jump_host_null_means_direct(tmp_path: Path) -> None: - data = _base() - data["jump_host"] = None - assert load_remote_config(_write(tmp_path, data)).jump_host is None - - -def test_servers_must_not_be_empty(tmp_path: Path) -> None: - data = _base() - data["servers"] = [] - _invalid(tmp_path, data) - - -def test_servers_are_required(tmp_path: Path) -> None: - data = _base() - del data["servers"] - _invalid(tmp_path, data) - - -def test_duplicate_server_names_are_rejected(tmp_path: Path) -> None: - data = _base() - data["servers"][1]["name"] = "Newton" - _invalid(tmp_path, data) - - -def test_duplicate_server_names_ignore_case(tmp_path: Path) -> None: - # --server は大文字小文字を区別せず照合するため,重複も同じ基準で判定する - data = _base() - data["servers"][1]["name"] = "newton" - _invalid(tmp_path, data) - - -@pytest.mark.parametrize( - "name", - [ - "New ton", - "Newton;rm", - "サーバ", - "a/b", - "", - # address を省略するとサーバ名が ssh の接続先になるため,- 始まり等を拒否する - "-Newton", - "-oProxyCommand=x", - "_Newton", - "Newton\n", - "New.ton", - "$(id)", - "'Newton'", - ], -) -def test_server_name_characters(tmp_path: Path, name: str) -> None: - data = _base() - data["servers"][0]["name"] = name - _invalid(tmp_path, data) - - -@pytest.mark.parametrize("name", ["Newton_2", "gpu-01", "A1", "1gpu"]) -def test_server_name_allowed_characters(tmp_path: Path, name: str) -> None: - data = _base() - data["servers"][0]["name"] = name - assert load_remote_config(_write(tmp_path, data)).servers[0].name == name - - -@pytest.mark.parametrize("priority", ["high", 1.5]) -def test_priority_must_be_integer(tmp_path: Path, priority: object) -> None: - data = _base() - data["servers"][0]["priority"] = priority - _invalid(tmp_path, data) - - -@pytest.mark.parametrize( - ("key", "value", "ok"), - [ - ("max_memory_used_mib", 0, True), - ("max_memory_used_mib", -1, False), - ("max_utilization_percent", 0, True), - ("max_utilization_percent", 100, True), - ("max_utilization_percent", -1, False), - ("max_utilization_percent", 101, False), - ("observe_sec", 0, True), - ("observe_sec", 120, True), - ("observe_sec", -1, False), - ("observe_sec", 121, False), - ("sample_interval_ms", 100, True), - ("sample_interval_ms", 5000, True), - ("sample_interval_ms", 99, False), - ("sample_interval_ms", 5001, False), - ], -) -def test_gpu_free_ranges(tmp_path: Path, key: str, value: int, ok: bool) -> None: - data = _base() - data["gpu_free"][key] = value - if ok: - assert getattr(load_remote_config(_write(tmp_path, data)).gpu_free, key) == value - else: - _invalid(tmp_path, data) - - -@pytest.mark.parametrize(("value", "ok"), [(1, True), (0, False), (-5, False)]) -def test_connect_timeout_at_least_one(tmp_path: Path, value: int, ok: bool) -> None: - data = _base() - data["connect_timeout_sec"] = value - if ok: - assert load_remote_config(_write(tmp_path, data)).connect_timeout_sec == value - else: - _invalid(tmp_path, data) - - -def test_unknown_top_level_key_is_rejected(tmp_path: Path) -> None: - data = _base() - data["jump_hots"] = "labpc" - _invalid(tmp_path, data) - - -def test_unknown_server_key_is_rejected(tmp_path: Path) -> None: - data = _base() - data["servers"][0]["data_redy"] = True - _invalid(tmp_path, data) - - -def test_unknown_gpu_free_key_is_rejected(tmp_path: Path) -> None: - data = _base() - data["gpu_free"]["observe_seconds"] = 5 - _invalid(tmp_path, data) - - -def test_data_dir_of_the_original_is_rejected(tmp_path: Path) -> None: - # 移植元の data_dir(TIAS_DATA_ROOT)は外した.書かれていれば未知のキーとして拒否する - data = _base() - data["servers"][0]["data_dir"] = "~/data/x" - _invalid(tmp_path, data) - - -@pytest.mark.parametrize("key", ["name", "priority", "remote_dir"]) -def test_missing_required_server_field_is_rejected(tmp_path: Path, key: str) -> None: - data = _base() - del data["servers"][0][key] - _invalid(tmp_path, data) - - -def test_defaults_of_optional_fields(tmp_path: Path) -> None: - data = _base() - for key in ("uv", "data_ready", "address", "user"): - del data["servers"][0][key] - for key in ("jump_host", "connect_timeout_sec", "gpu_free"): - del data[key] - config = load_remote_config(_write(tmp_path, data)) - server = config.servers[0] - assert server.uv == "~/.local/bin/uv" - assert server.data_ready is False - assert config.jump_host == "labpc" - assert config.connect_timeout_sec == 15 - assert config.gpu_free.model_dump() == { - "max_memory_used_mib": 1024, - "max_utilization_percent": 10, - "observe_sec": 10, - "sample_interval_ms": 500, - } - - -@pytest.mark.parametrize("value", ["yes", 1, "true"]) -def test_data_ready_must_be_bool(tmp_path: Path, value: object) -> None: - data = _base() - data["servers"][0]["data_ready"] = value - _invalid(tmp_path, data) - - -@pytest.mark.parametrize("key", ["remote_dir", "uv"]) -@pytest.mark.parametrize("bad", ["", " ", "~other/x"]) -def test_bad_remote_paths_are_rejected(tmp_path: Path, key: str, bad: str) -> None: - data = _base() - data["servers"][0][key] = bad - _invalid(tmp_path, data) - - -@pytest.mark.parametrize("bad", ["-oProxyCommand=evil", "a b", "j;id", "j\n", "$(id)", ""]) -def test_bad_jump_host_is_rejected(tmp_path: Path, bad: str) -> None: - data = _base() - data["jump_host"] = bad - _invalid(tmp_path, data) - - -def test_missing_file_is_value_error(tmp_path: Path) -> None: - with pytest.raises(ValueError): - load_remote_config(tmp_path / "missing.yaml") - - -def test_malformed_yaml_is_value_error(tmp_path: Path) -> None: - path = tmp_path / "remote.yaml" - path.write_text("servers: [\n - name: Newton\n", encoding="utf-8") - with pytest.raises(ValueError): - load_remote_config(path) - - -@pytest.mark.parametrize("text", ["- a\n- b\n", "just text\n", ""]) -def test_top_level_must_be_mapping(tmp_path: Path, text: str) -> None: - path = tmp_path / "remote.yaml" - path.write_text(text, encoding="utf-8") - with pytest.raises(ValueError): - load_remote_config(path) - - -def test_ordered_servers_and_find_server(tmp_path: Path) -> None: - data = _base() - data["servers"][0]["priority"] = 5 - config = load_remote_config(_write(tmp_path, data)) - assert [s.name for s in config.ordered_servers()] == ["Archimedes", "Newton"] - assert config.find_server("newton").name == "Newton" - with pytest.raises(ValueError): - config.find_server("Euler") - - -def test_with_observe_sec_validates_range(tmp_path: Path) -> None: - gpu_free = load_remote_config(_write(tmp_path, _base())).gpu_free - assert gpu_free.with_observe_sec(0).observe_sec == 0 - assert gpu_free.with_observe_sec(3).max_memory_used_mib == 1024 - with pytest.raises(ValidationError): - gpu_free.with_observe_sec(121) - - -# --------------------------------------------------------------------------- -# address・user の省略(移植元では必須) -# --------------------------------------------------------------------------- - - -class TestOptionalAddressAndUser: - """`address`・`user` は省略でき,省略時はサーバ名を ssh の Host 名に使う.""" - - def test_address_and_user_can_be_omitted(self, tmp_path: Path) -> None: - data = _base() - for server in data["servers"]: - del server["address"] - del server["user"] - newton = load_remote_config(_write(tmp_path, data)).servers[0] - assert newton.address is None and newton.user is None - assert newton.ssh_host == "Newton" - assert newton.destination == "Newton" - - def test_address_is_used_when_given(self, tmp_path: Path) -> None: - newton = load_remote_config(_write(tmp_path, _base())).servers[0] - assert newton.ssh_host == "192.168.23.14" - assert newton.destination == "hasegawa@192.168.23.14" - - def test_user_without_address(self, tmp_path: Path) -> None: - data = _base() - del data["servers"][0]["address"] - newton = load_remote_config(_write(tmp_path, data)).servers[0] - assert newton.destination == "hasegawa@Newton" - - @pytest.mark.parametrize("key", ["address", "user"]) - @pytest.mark.parametrize( - "bad", ["-oProxyCommand=evil", "a b", "", "h;id", "h\n", "$(id)", "'h'", "h/x"] - ) - def test_bad_address_or_user_is_rejected(self, tmp_path: Path, key: str, bad: str) -> None: - data = _base() - data["servers"][0][key] = bad - _invalid(tmp_path, data) - - -# --------------------------------------------------------------------------- -# 環境変数 -# --------------------------------------------------------------------------- - - -class TestJumpHostEnv: - def _config(self, tmp_path: Path, jump: str | None = "labpc"): - data = _base() - data["jump_host"] = jump - return load_remote_config(_write(tmp_path, data)) - - def test_no_env_uses_config(self, tmp_path: Path) -> None: - assert resolve_jump_host(self._config(tmp_path), {}) == "labpc" - - def test_env_overrides(self, tmp_path: Path) -> None: - env = {"TSM_REMOTE_JUMP": "otherjump"} - assert resolve_jump_host(self._config(tmp_path), env) == "otherjump" - - @pytest.mark.parametrize("value", ["", " "]) - def test_empty_env_means_direct(self, tmp_path: Path, value: str) -> None: - assert resolve_jump_host(self._config(tmp_path), {"TSM_REMOTE_JUMP": value}) is None - - def test_env_sets_jump_when_config_is_null(self, tmp_path: Path) -> None: - config = self._config(tmp_path, None) - assert resolve_jump_host(config, {}) is None - assert resolve_jump_host(config, {"TSM_REMOTE_JUMP": "labpc"}) == "labpc" - - @pytest.mark.parametrize("bad", ["-oProxyCommand=evil", "a b", "j;id"]) - def test_bad_env_value_is_rejected(self, tmp_path: Path, bad: str) -> None: - with pytest.raises(ValueError): - resolve_jump_host(self._config(tmp_path), {"TSM_REMOTE_JUMP": bad}) - - def test_original_env_name_is_not_used(self, tmp_path: Path) -> None: - assert resolve_jump_host(self._config(tmp_path), {"TIAS_REMOTE_JUMP": ""}) == "labpc" - - -class TestSshExecutable: - def test_env_overrides(self) -> None: - assert resolve_ssh_executable({"TSM_REMOTE_SSH": "/opt/ssh"}, "posix") == "/opt/ssh" - - def test_posix_default_is_ssh(self) -> None: - assert resolve_ssh_executable({}, "posix") == "ssh" - - -class TestSelfServer: - def test_hostname_matching_server_name_is_detected(self, tmp_path: Path) -> None: - config = load_remote_config(_write(tmp_path, _base())) - server = detect_self_server(config, "Newton") - assert server is not None and server.name == "Newton" - - def test_hostname_with_domain_and_case_is_detected(self, tmp_path: Path) -> None: - config = load_remote_config(_write(tmp_path, _base())) - server = detect_self_server(config, "newton.local") - assert server is not None and server.name == "Newton" - - def test_other_hostname_is_not_detected(self, tmp_path: Path) -> None: - config = load_remote_config(_write(tmp_path, _base())) - assert detect_self_server(config, "my-laptop") is None - assert detect_self_server(config, "") is None - - def test_allow_self_env(self) -> None: - assert is_self_check_disabled({"TSM_REMOTE_ALLOW_SELF": "1"}) - assert not is_self_check_disabled({}) - assert not is_self_check_disabled({"TSM_REMOTE_ALLOW_SELF": "0"}) - assert not is_self_check_disabled({"TIAS_REMOTE_ALLOW_SELF": "1"}) diff --git a/tests/remote/test_files.py b/tests/remote/test_files.py deleted file mode 100644 index 0b254f0..0000000 --- a/tests/remote/test_files.py +++ /dev/null @@ -1,504 +0,0 @@ -"""push で送るファイルの選別のテスト(SPEC_03「push」). - -`.git/`・`.venv/`・`__pycache__/`・`.pytest_cache/`・`.ruff_cache/` はどこにあっても送らない. -`data/`・`runs/`・`.claude/`・`legacy/` はプロジェクト直下のみ除外する -(`src/tongue_seg_model/data/`・`tests/data/` は送る). -重み(`.pt`・`.pth`・`.ckpt`・`.pb`・`.onnx`.大文字小文字を問わず)と `.env`・`.env.*` は -どの階層でも送らない(SPEC_03「移植で変える点」). - -TIASJudgeModel の tests/remote/test_files.py の移植に,`legacy/`・重み・`.env` の除外と,実際の -リポジトリに対する確認を足した(`legacy/` の中は一覧しない.送信対象の一覧の側から確かめる). -""" - -from __future__ import annotations - -from collections.abc import Iterator -from pathlib import Path - -import pytest -from link_helpers import LinkFactory - -from tongue_seg_model.remote.files import ( - PushEntry, - PushSelection, - collect_push_entries, - is_excluded, - is_link, - select_push_files, -) - -SENT = [ - "pyproject.toml", - "uv.lock", - ".python-version", - "src/tongue_seg_model/__init__.py", - "src/tongue_seg_model/data/manifest.py", - "src/tongue_seg_model/remote/gpu.py", - "tests/data/test_split.py", - "tests/remote/test_gpu.py", - "scripts/make_synthetic_dataset.py", - "configs/remote.yaml", - "configs/synthetic-gpu.yaml", - "src/tongue_seg_model/data/bundle.py", - "tests/data/original_tongue_seg_dataset.py", - # 重みの拡張子に似ているが違うもの・.env に似ているが違うもの - "docs/onnx.md", - "src/tongue_seg_model/export/onnx_export.py", - "scripts/pth_tool.py", - "src/a.pth.py", - ".envrc", - "src/environment.py", - "my.env", - # legacy・data・runs を名前に含むがプロジェクト直下の別名 - "legacy.md", - "src/tongue_seg_model/legacy/x.py", - "docs/legacy/a.md", - "tests/runs/a.py", - # サブモジュール TIASDataHub は導入に要るものだけ - "external/TIASDataHub/pyproject.toml", - "external/TIASDataHub/README.md", - "external/TIASDataHub/src/tiasdata/__init__.py", - "external/TIASDataHub/src/tiasdata/catalog/migrations/catalog/0001_x.sql", -] - -NOT_SENT = [ - ".git/config", - ".git/objects/ab/cdef", - ".venv/Scripts/python.exe", - "__pycache__/x.pyc", - "src/tongue_seg_model/__pycache__/a.cpython-312.pyc", - "tests/data/__pycache__/b.pyc", - ".pytest_cache/v/cache/nodeids", - ".ruff_cache/0.1/x", - "data/synthetic/manifest.csv", - "data/synthetic/synthetic/v1/files/ab.png", - # 原本(重みと,画像のファイル名を含む結果がある) - "legacy/source/main.py", - "legacy/hparams.yaml", - "legacy/result/x.csv", - "legacy/output/bestModel.pth", - "Legacy/source/main.py", - "LEGACY/a.txt", - "DATA/x.png", - "Runs/x/metrics.json", - # 重み(どの階層でも・大文字小文字を問わず) - "model.pt", - "best.pth", - "src/tongue_seg_model/models/best.pth", - "tests/fixtures/ResUNet.onnx", - "scripts/x.ckpt", - "configs/frozen.pb", - "BEST.PTH", - "a/b/c/Model.Onnx", - "x.tar.pt", - # 環境変数ファイル(秘密を含みうる) - ".env", - ".env.local", - "configs/.env", - "src/.ENV", - ".Env.production", - "runs/20260927-120000_x/metrics.json", - "runs/_remote_logs/exp1.log", - ".claude/settings.json", - ".claude/rules/testing.md", - "external/TIASDataHub/.git", - "external/TIASDataHub/.claude/settings.json", - "external/TIASDataHub/.github/dependabot.yml", - "external/TIASDataHub/CLAUDE.md", - "external/TIASDataHub/uv.lock", - "external/TIASDataHub/docs/PROGRESS.md", - "external/TIASDataHub/tests/test_bundle.py", - "external/TIASDataHub/datasets/tongue_color.toml", - "external/TIASDataHub/reviews/r1.md", - "external/TIASDataHub/src/tiasdata/__pycache__/bundle.cpython-312.pyc", -] - - -def _make_tree(root: Path, paths: list[str]) -> None: - for rel in paths: - path = root / rel - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b"x") - - -def test_collect_push_entries_excludes_listed_directories(tmp_path: Path) -> None: - _make_tree(tmp_path, SENT + NOT_SENT) - arcnames = [entry.arcname for entry in collect_push_entries(tmp_path)] - assert sorted(arcnames) == sorted(SENT) - - -def test_arcnames_are_posix_relative(tmp_path: Path) -> None: - _make_tree(tmp_path, ["src/tongue_seg_model/data/manifest.py"]) - entries = collect_push_entries(tmp_path) - assert [e.arcname for e in entries] == ["src/tongue_seg_model/data/manifest.py"] - assert entries[0].size == 1 - - -@pytest.mark.parametrize("rel", NOT_SENT) -def test_is_excluded_for_not_sent(rel: str) -> None: - assert is_excluded(rel) - - -@pytest.mark.parametrize("rel", SENT) -def test_is_not_excluded_for_sent(rel: str) -> None: - assert not is_excluded(rel) - - -@pytest.mark.parametrize( - "rel", ["data", "runs", ".claude", ".git", ".venv", "legacy", "Legacy", "src/__pycache__"] -) -def test_root_directories_themselves_are_excluded(rel: str) -> None: - assert is_excluded(rel) - - -@pytest.mark.parametrize( - "rel", ["src/tongue_seg_model/data", "tests/data", "src/tongue_seg_model/runs_util.py"] -) -def test_nested_data_is_not_excluded(rel: str) -> None: - assert not is_excluded(rel) - - -# --- サブモジュール external/TIASDataHub/ --- - - -@pytest.mark.parametrize("rel", ["external", "external/TIASDataHub"]) -def test_submodule_parent_directories_are_walked(rel: str) -> None: - assert not is_excluded(rel) - - -@pytest.mark.parametrize( - "rel", - [ - "external/TIASDataHub/src", - "external/TIASDataHub/pyproject.toml", - "external/TIASDataHub/README.md", - ], -) -def test_submodule_sent_entries_are_not_excluded(rel: str) -> None: - assert not is_excluded(rel) - - -@pytest.mark.parametrize( - "rel", - [ - "external/TIASDataHub/docs", - "external/TIASDataHub/tests", - "external/TIASDataHub/.claude", - "external/TIASDataHub/datasets", - ], -) -def test_submodule_other_directories_are_excluded(rel: str) -> None: - assert is_excluded(rel) - - -@pytest.mark.parametrize( - "rel", - [ - # 同じ名前でも submodule の直下でなければ規則の対象外 - "external/Other/docs/a.md", - "external/TIASDataHub2/docs/a.md", - "src/external/TIASDataHub/docs/a.md", - # submodule の src の下は名前によらず送る - "external/TIASDataHub/src/tiasdata/docs/a.md", - "external/TIASDataHub/src/tiasdata/tests/a.py", - ], -) -def test_submodule_rule_is_limited_to_its_top_level(rel: str) -> None: - assert not is_excluded(rel) - - -def test_repository_submodule_sends_only_install_files() -> None: - root = Path(__file__).resolve().parents[2] - if not (root / "external" / "TIASDataHub" / "pyproject.toml").is_file(): - pytest.skip("サブモジュールが展開されていない") - prefix = "external/TIASDataHub/" - sent = [e.arcname for e in collect_push_entries(root) if e.arcname.startswith(prefix)] - assert f"{prefix}pyproject.toml" in sent - assert f"{prefix}README.md" in sent - assert f"{prefix}src/tiasdata/bundle.py" in sent - assert {name.removeprefix(prefix).split("/")[0] for name in sent} == { - "pyproject.toml", - "README.md", - "src", - } - - -# --- ディレクトリの扱い --- - - -@pytest.mark.parametrize("rel", ["models.onnx", "src/weights.pth", ".env.d"]) -def test_directory_names_are_not_matched_by_file_rules(rel: str) -> None: - # 拡張子・.env の除外はファイルだけに当てはめる(中のファイルは名前で判断する) - assert not is_excluded(rel, is_dir=True) - - -def test_files_inside_weight_like_directory(tmp_path: Path) -> None: - _make_tree(tmp_path, ["models.onnx/readme.md", "models.onnx/w.ONNX"]) - assert [e.arcname for e in collect_push_entries(tmp_path)] == ["models.onnx/readme.md"] - - -def test_legacy_directory_is_not_walked(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """`legacy/`・`data/`・`runs/` の中は列挙もしない(ファイル名を読まない).""" - import os - - _make_tree(tmp_path, ["legacy/result/x.csv", "data/a.png", "runs/r/log.txt", "src/a.py"]) - visited: list[str] = [] - real_walk = os.walk - - def spy_walk(top, *args, **kwargs): - for dirpath, dirnames, filenames in real_walk(top, *args, **kwargs): - visited.append(Path(dirpath).relative_to(tmp_path).as_posix()) - yield dirpath, dirnames, filenames - - monkeypatch.setattr("tongue_seg_model.remote.files.os.walk", spy_walk) - assert [e.arcname for e in collect_push_entries(tmp_path)] == ["src/a.py"] - assert not any(v.split("/")[0] in {"legacy", "data", "runs"} for v in visited) - - -def test_entries_are_sorted_and_sizes_are_real(tmp_path: Path) -> None: - (tmp_path / "b").mkdir() - (tmp_path / "b" / "z.py").write_bytes(b"12345") - (tmp_path / "a.py").write_bytes(b"") - entries = collect_push_entries(tmp_path) - assert [(e.arcname, e.size) for e in entries] == [("a.py", 0), ("b/z.py", 5)] - - -# --- 実際のリポジトリ --- - -REPO_ROOT = Path(__file__).resolve().parents[2] -WEIGHT_SUFFIXES = (".pt", ".pth", ".ckpt", ".pb", ".onnx") - - -def _repository_entries() -> list[str]: - return [e.arcname for e in collect_push_entries(REPO_ROOT)] - - -def test_repository_push_has_no_legacy_data_runs_or_weights() -> None: - """実際のリポジトリの送信対象に,`legacy/`・`data/`・`runs/`・重み・`.env` が 0 件.""" - sent = _repository_entries() - assert sent, "送信対象が空" - for name in sent: - top = name.split("/")[0].lower() - assert top not in {"legacy", "data", "runs", ".claude", ".git", ".venv"}, name - assert not name.lower().endswith(WEIGHT_SUFFIXES), name - base = name.rsplit("/", 1)[-1].lower() - assert base != ".env" and not base.startswith(".env."), name - assert "__pycache__" not in name.split("/"), name - - -def test_repository_push_contains_code_needed_on_server() -> None: - sent = set(_repository_entries()) - for required in [ - "pyproject.toml", - "uv.lock", - "configs/remote.yaml", - "configs/synthetic-gpu.yaml", - "src/tongue_seg_model/__init__.py", - "src/tongue_seg_model/data/bundle.py", - "src/tongue_seg_model/cli/remote.py", - "scripts/make_synthetic_bundle.py", - ]: - assert required in sent, required - assert any(name.startswith("src/tongue_seg_model/data/") for name in sent) - assert any(name.startswith("tests/data/") for name in sent) - - -# --------------------------------------------------------------------------- -# シンボリックリンク・ジャンクションは送らない(リンクのディレクトリの中にも入らない) -# --------------------------------------------------------------------------- - - -@pytest.fixture -def links() -> Iterator[LinkFactory]: - factory = LinkFactory() - yield factory - factory.cleanup() - - -@pytest.fixture -def repo_and_outside(tmp_path: Path) -> tuple[Path, Path]: - """tmp_path の中に「リポジトリ役」と「外役」の 2 つのフォルダを作る.""" - repo = tmp_path / "repo" - outside = tmp_path / "outside" - _make_tree(repo, ["pyproject.toml", "src/tongue_seg_model/__init__.py"]) - _make_tree(outside, ["secret.py", "patients/P0001.png", "sub/code.py"]) - return repo, outside - - -REPO_CODE = ["pyproject.toml", "src/tongue_seg_model/__init__.py"] - - -def _arcnames(root: Path) -> list[str]: - return [entry.arcname for entry in select_push_files(root).entries] - - -def _nothing_from(outside: Path, entries: tuple[PushEntry, ...]) -> bool: - resolved = outside.resolve() - return all(resolved not in e.path.resolve().parents for e in entries) - - -class TestIsLink: - def test_regular_file_and_directory_are_not_links(self, tmp_path: Path) -> None: - (tmp_path / "d").mkdir() - (tmp_path / "f.py").write_bytes(b"x") - assert not is_link(tmp_path / "d") - assert not is_link(tmp_path / "f.py") - - def test_missing_path_is_not_link(self, tmp_path: Path) -> None: - assert not is_link(tmp_path / "missing") - - def test_file_symlink(self, tmp_path: Path, links: LinkFactory) -> None: - (tmp_path / "t.py").write_bytes(b"x") - assert is_link(links.symlink(tmp_path / "l.py", tmp_path / "t.py")) - - def test_directory_symlink(self, tmp_path: Path, links: LinkFactory) -> None: - (tmp_path / "t").mkdir() - assert is_link(links.symlink(tmp_path / "l", tmp_path / "t")) - - def test_broken_symlink(self, tmp_path: Path, links: LinkFactory) -> None: - assert is_link(links.symlink(tmp_path / "l.py", tmp_path / "gone.py", is_dir=False)) - - def test_junction(self, tmp_path: Path, links: LinkFactory) -> None: - (tmp_path / "t").mkdir() - assert is_link(links.junction(tmp_path / "j", tmp_path / "t")) - - -class TestSelectPushFilesWithoutLinks: - def test_no_links_gives_empty_skipped(self, tmp_path: Path) -> None: - _make_tree(tmp_path, ["a.py", "src/b.py"]) - selection = select_push_files(tmp_path) - assert isinstance(selection, PushSelection) - assert [e.arcname for e in selection.entries] == ["a.py", "src/b.py"] - assert selection.skipped_links == () - - def test_collect_push_entries_is_selection_entries(self, tmp_path: Path) -> None: - _make_tree(tmp_path, SENT + NOT_SENT) - entries = collect_push_entries(tmp_path) - assert isinstance(entries, list) - assert entries == list(select_push_files(tmp_path).entries) - - -class TestFileLinks: - def test_file_symlink_inside_repo_is_skipped( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory - ) -> None: - repo, _ = repo_and_outside - links.symlink(repo / "src" / "alias.py", repo / "pyproject.toml") - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == REPO_CODE - assert selection.skipped_links == ("src/alias.py",) - - def test_file_symlink_to_outside_is_not_sent( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory - ) -> None: - repo, outside = repo_and_outside - links.symlink(repo / "leak.py", outside / "secret.py") - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == REPO_CODE - assert selection.skipped_links == ("leak.py",) - assert _nothing_from(outside, selection.entries) - - def test_broken_file_symlink_is_skipped( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory - ) -> None: - repo, outside = repo_and_outside - links.symlink(repo / "broken.py", outside / "does_not_exist.py", is_dir=False) - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == REPO_CODE - assert selection.skipped_links == ("broken.py",) - - -class TestDirectoryLinks: - @pytest.mark.parametrize("kind", ["symlink", "junction"]) - def test_directory_link_to_outside_is_not_walked( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str - ) -> None: - repo, outside = repo_and_outside - getattr(links, kind)(repo / "src" / "ext", outside) - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == REPO_CODE - assert selection.skipped_links == ("src/ext",) - # リンク先の中身(患者の画像に見立てたもの)は送信対象に一切入らない - assert _nothing_from(outside, selection.entries) - - @pytest.mark.parametrize("kind", ["symlink", "junction"]) - def test_directory_link_inside_repo_is_not_walked( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str - ) -> None: - repo, _ = repo_and_outside - getattr(links, kind)(repo / "mirror", repo / "src") - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == REPO_CODE - assert selection.skipped_links == ("mirror",) - - @pytest.mark.parametrize("kind", ["symlink", "junction"]) - def test_link_to_legacy_or_data_like_folder_is_not_walked( - self, tmp_path: Path, links: LinkFactory, kind: str - ) -> None: - """tmp_path の中の「legacy 役」「data 役」を別名で指すリンクも送らない.""" - repo = tmp_path / "repo" - _make_tree(repo, ["legacy/result/r.csv", "data/a.png", "src/a.py"]) - getattr(links, kind)(repo / "src" / "old", repo / "legacy") - getattr(links, kind)(repo / "src" / "d", repo / "data") - selection = select_push_files(repo) - assert [e.arcname for e in selection.entries] == ["src/a.py"] - assert selection.skipped_links == ("src/d", "src/old") - - @pytest.mark.parametrize("kind", ["symlink", "junction"]) - def test_os_walk_does_not_enter_links( - self, - repo_and_outside: tuple[Path, Path], - links: LinkFactory, - monkeypatch: pytest.MonkeyPatch, - kind: str, - ) -> None: - import os - - repo, outside = repo_and_outside - getattr(links, kind)(repo / "src" / "ext", outside) - visited: list[str] = [] - real_walk = os.walk - - def spy_walk(top, *args, **kwargs): - for dirpath, dirnames, filenames in real_walk(top, *args, **kwargs): - visited.append(Path(dirpath).relative_to(repo.resolve()).as_posix()) - yield dirpath, dirnames, filenames - - monkeypatch.setattr("tongue_seg_model.remote.files.os.walk", spy_walk) - select_push_files(repo) - assert not any(v == "src/ext" or v.startswith("src/ext/") for v in visited) - - -class TestLinksInExcludedDirectories: - @pytest.mark.parametrize("kind", ["symlink", "junction"]) - def test_links_inside_excluded_directories_are_not_counted( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory, kind: str - ) -> None: - repo, outside = repo_and_outside - getattr(links, kind)(repo / ".venv" / "lib" / "ext", outside / "sub") - getattr(links, kind)(repo / "src" / "__pycache__" / "ext", outside / "sub") - getattr(links, kind)(repo / "runs" / "r" / "ext", outside / "sub") - selection = select_push_files(repo) - assert selection.skipped_links == () - assert [e.arcname for e in selection.entries] == REPO_CODE - - def test_file_links_inside_excluded_directories_are_not_counted( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory - ) -> None: - repo, outside = repo_and_outside - links.symlink(repo / ".venv" / "python.py", outside / "secret.py") - selection = select_push_files(repo) - assert selection.skipped_links == () - assert [e.arcname for e in selection.entries] == REPO_CODE - - -class TestSkippedLinksOrder: - def test_skipped_links_are_sorted_posix_paths( - self, repo_and_outside: tuple[Path, Path], links: LinkFactory - ) -> None: - repo, outside = repo_and_outside - links.symlink(repo / "z.py", outside / "secret.py") - links.symlink(repo / "src" / "b" / "a.py", outside / "secret.py") - links.symlink(repo / "a" / "dir", outside / "sub") - selection = select_push_files(repo) - assert selection.skipped_links == ("a/dir", "src/b/a.py", "z.py") diff --git a/tests/remote/test_gpu.py b/tests/remote/test_gpu.py deleted file mode 100644 index fd9e786..0000000 --- a/tests/remote/test_gpu.py +++ /dev/null @@ -1,616 +0,0 @@ -"""GPU の空き判定(4 段階)と選択のテスト(SPEC_03「GPU の空き判定と選択」). - -- 観測中の最大値で閾値を判定する(瞬間値が 0% でも観測中に超えたら使用中) -- 計算プロセスを所有者を問わず数える.一覧が取れなければ閾値内の GPU は「空き(利用者あり)」 -- GPU の行が解釈できない・サンプル 0 件なら「状態不明」 -- 選択では「未使用」をサーバの優先順位より優先する -- 自分の利用者名は probe の `@@tsm-user` から取る(設定の `user` を省略できるため.移植元との違い) - -TIASJudgeModel の tests/remote/test_gpu.py の移植. -""" - -from __future__ import annotations - -import pytest -from probe_helpers import PMON_HEADER, gpu_line, probe_text, sample_lines - -from tongue_seg_model.remote.config import GpuFreeThreshold, ServerConfig -from tongue_seg_model.remote.gpu import ( - GpuInfo, - GpuSelection, - GpuState, - ProbeOutput, - ServerProbe, - check_cpu_options, - check_selection_options, - classify_gpu, - display_user_name, - gpu_users, - parse_probe_output, - select_cpu_server, - select_gpu, -) -from tongue_seg_model.remote.observe import UsagePattern - -OBSERVE = GpuFreeThreshold( - max_memory_used_mib=1024, max_utilization_percent=10, observe_sec=10, sample_interval_ms=500 -) -INSTANT = GpuFreeThreshold( - max_memory_used_mib=1024, max_utilization_percent=10, observe_sec=0, sample_interval_ms=500 -) - -UUID0 = "GPU-00000000-aaaa-bbbb-cccc-000000000000" -UUID1 = "GPU-11111111-aaaa-bbbb-cccc-111111111111" - - -def _states(output: ProbeOutput) -> dict[int | None, GpuState]: - return {gpu.index: gpu.state for gpu in output.gpus} - - -def _gpu(output: ProbeOutput, index: int) -> GpuInfo: - return next(g for g in output.gpus if g.index == index) - - -# --------------------------------------------------------------------------- -# 判定(classify_gpu) -# --------------------------------------------------------------------------- - - -class TestClassifyGpu: - def test_within_threshold_without_processes_is_unused(self) -> None: - assert classify_gpu(0, 0, OBSERVE, 0) is GpuState.UNUSED - - def test_within_threshold_with_processes_is_shared(self) -> None: - assert classify_gpu(500, 5, OBSERVE, 1) is GpuState.SHARED - - def test_unknown_process_list_is_shared_not_unused(self) -> None: - assert classify_gpu(0, 0, OBSERVE, None) is GpuState.SHARED - - @pytest.mark.parametrize( - ("memory", "util", "expected"), - [ - (1023, 9, GpuState.UNUSED), - (1024, 9, GpuState.BUSY), # 「未満」なのでちょうどは超えた扱い - (1023, 10, GpuState.BUSY), - (5000, 0, GpuState.BUSY), - (0, 100, GpuState.BUSY), - ], - ) - def test_threshold_boundaries(self, memory: int, util: int, expected: GpuState) -> None: - assert classify_gpu(memory, util, OBSERVE, 0) is expected - - def test_busy_even_if_process_list_unknown(self) -> None: - assert classify_gpu(0, 50, OBSERVE, None) is GpuState.BUSY - - -# --------------------------------------------------------------------------- -# probe 出力の解析と判定(parse_probe_output) -# --------------------------------------------------------------------------- - - -class TestObservedJudgement: - def test_max_during_observation_is_used_even_if_instant_is_zero(self) -> None: - # 瞬間値は 0% だが,観測中に 74% まで上がった(2026-09-27 Newton の実測を模す) - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], - samples=sample_lines(0, [0, 0, 74, 0, 0, 30, 0, 0, 0, 0]), - ) - output = parse_probe_output(text, OBSERVE) - assert _states(output) == {0: GpuState.BUSY} - - def test_memory_peak_during_observation_makes_busy(self) -> None: - samples = ["0, 0, 10", "0, 0, 2000", "0, 0, 10"] - text = probe_text([gpu_line(0, UUID0, used=10, util=0)], samples=samples) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.BUSY} - - def test_always_within_threshold_without_processes_is_unused(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], samples=sample_lines(0, [0, 3, 9, 0, 1]) - ) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.UNUSED} - - def test_single_sample_over_threshold_is_busy(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], samples=sample_lines(0, [0, 0, 10, 0]) - ) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.BUSY} - - def test_no_samples_for_gpu_is_unknown(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0), gpu_line(1, UUID1, used=5, util=0)], - samples=sample_lines(0, [0, 0, 0]), - ) - assert _states(parse_probe_output(text, OBSERVE)) == { - 0: GpuState.UNUSED, - 1: GpuState.UNKNOWN, - } - - def test_missing_samples_section_makes_all_unknown(self) -> None: - text = probe_text([gpu_line(0, UUID0, used=5, util=0)], samples=None) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.UNKNOWN} - - def test_observe_zero_uses_instant_value(self) -> None: - text = probe_text([gpu_line(0, UUID0, used=5, util=0), gpu_line(1, UUID1, used=5, util=50)]) - output = parse_probe_output(text, INSTANT) - assert _states(output) == {0: GpuState.UNUSED, 1: GpuState.BUSY} - - def test_observe_zero_does_not_require_samples(self) -> None: - text = probe_text([gpu_line(0, UUID0, used=2000, util=0)]) - assert _states(parse_probe_output(text, INSTANT)) == {0: GpuState.BUSY} - - -class TestProcessesAndUnknown: - def test_processes_are_matched_by_gpu_uuid(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=500, util=0), gpu_line(1, UUID1, used=5, util=0)], - samples=sample_lines(0, [0, 0]) + sample_lines(1, [0, 0]), - apps=[f"{UUID0}, 4321, 480"], - owners=["4321 alice 99720"], - ) - output = parse_probe_output(text, OBSERVE) - assert _states(output) == {0: GpuState.SHARED, 1: GpuState.UNUSED} - process = _gpu(output, 0).processes[0] - assert process.pid == 4321 - assert process.user == "alice" - assert process.elapsed_sec == 99720 - assert _gpu(output, 1).processes == () - - def test_own_process_also_counts(self) -> None: - # 自分の別ジョブが載っている GPU にも次のジョブを重ねない(所有者を問わず数える) - text = probe_text( - [gpu_line(0, UUID0, used=300, util=0)], - samples=sample_lines(0, [0, 0]), - apps=[f"{UUID0}, 100, 300"], - owners=["100 hasegawa 10"], - ) - output = parse_probe_output(text, OBSERVE) - gpu = _gpu(output, 0) - assert gpu.state is GpuState.SHARED - assert gpu_users(gpu, "hasegawa") == ["自分"] - assert gpu_users(gpu, "someone_else") == ["hasegawa"] - - def test_process_list_failure_makes_within_threshold_gpus_shared(self) -> None: - text = probe_text( - [ - gpu_line(0, UUID0, used=5, util=0), - gpu_line(1, UUID1, used=5, util=0), - ], - samples=sample_lines(0, [0, 0]) + sample_lines(1, [0, 90]), - apps=[], - apps_rc=9, - ) - output = parse_probe_output(text, OBSERVE) - assert not output.processes_query_ok - # 閾値内は未使用と誤認せず「空き(利用者あり)」,閾値を超えたものは使用中のまま - assert _states(output) == {0: GpuState.SHARED, 1: GpuState.BUSY} - - def test_unparsable_process_list_makes_gpus_shared(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0), gpu_line(1, UUID1, used=5, util=0)], - samples=sample_lines(0, [0]) + sample_lines(1, [0]), - apps=["this is not csv"], - ) - output = parse_probe_output(text, OBSERVE) - assert _states(output) == {0: GpuState.SHARED, 1: GpuState.SHARED} - - def test_missing_process_section_makes_gpus_shared(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], samples=sample_lines(0, [0]), apps=None - ) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.SHARED} - - @pytest.mark.parametrize( - "line", - [ - f"0, {UUID0}, NVIDIA RTX A6000, [N/A], 49140, 0", - f"0, {UUID0}, NVIDIA RTX A6000, 5, 49140, [N/A]", - "0, garbage", - "garbage", - ], - ) - def test_unparsable_gpu_line_is_unknown(self, line: str) -> None: - text = probe_text( - [line, gpu_line(1, UUID1, used=5, util=0)], - samples=sample_lines(0, [0]) + sample_lines(1, [0]), - ) - output = parse_probe_output(text, OBSERVE) - assert output.gpus[0].state is GpuState.UNKNOWN - assert _gpu(output, 1).state is GpuState.UNUSED - - def test_gpu_query_failure_yields_no_candidates(self) -> None: - text = probe_text([], gpu_rc=127, apps=None) - output = parse_probe_output(text, OBSERVE) - assert not output.gpu_query_ok - assert output.gpus == () - - def test_graphics_process_is_not_counted_from_pmon(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=300, util=5)], - samples=sample_lines(0, [5, 0]), - pmon=[ - *PMON_HEADER, - " 0 1234 C 74 10 - - - - python", - " 0 1234 C 3 1 - - - - python", - " 0 999 G 50 2 - - - - Xorg", - " 0 - - - - - - - - -", - ], - apps=[f"{UUID0}, 1234, 280"], - owners=["1234 alice 45"], - ) - output = parse_probe_output(text, OBSERVE) - gpu = _gpu(output, 0) - assert [p.pid for p in gpu.processes] == [1234] - assert gpu.processes[0].max_sm_percent == 74 - - def test_preamble_before_markers_is_ignored(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], - samples=sample_lines(0, [0]), - preamble=["Welcome to Ubuntu", "Last login: Sat Sep 27 10:00:00 2026"], - ) - assert _states(parse_probe_output(text, OBSERVE)) == {0: GpuState.UNUSED} - - def test_truncated_output_is_error(self) -> None: - text = probe_text([gpu_line(0, UUID0, used=5, util=0)], samples=sample_lines(0, [0])) - truncated = text.split("@@tsm-end")[0] - with pytest.raises(ValueError): - parse_probe_output(truncated, OBSERVE) - - def test_jobs_and_other_sessions(self) -> None: - text = probe_text([], jobs=["exp1"], others=["mywork"], samples=[]) - output = parse_probe_output(text, OBSERVE) - assert output.jobs == ("exp1",) - assert output.other_sessions == ("mywork",) - - -class TestPatternDoesNotAffectState: - def test_intermittent_but_within_threshold_is_unused(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], samples=sample_lines(0, [0, 5, 0, 0, 0]) - ) - gpu = _gpu(parse_probe_output(text, OBSERVE), 0) - assert gpu.pattern is UsagePattern.INTERMITTENT - assert gpu.state is GpuState.UNUSED - - def test_constant_but_within_threshold_is_unused(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=5, util=3)], samples=sample_lines(0, [3, 3, 3, 3, 3]) - ) - gpu = _gpu(parse_probe_output(text, OBSERVE), 0) - assert gpu.pattern is UsagePattern.CONSTANT - assert gpu.state is GpuState.UNUSED - - def test_memory_only_pattern_is_shared(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=500, util=0)], - samples=sample_lines(0, [0, 0, 0], memory=500), - apps=[f"{UUID0}, 1, 500"], - owners=["1 bob 100"], - ) - gpu = _gpu(parse_probe_output(text, OBSERVE), 0) - assert gpu.pattern is UsagePattern.MEMORY_ONLY - assert gpu.state is GpuState.SHARED - - def test_idle_pattern_but_memory_over_threshold_is_busy(self) -> None: - text = probe_text( - [gpu_line(0, UUID0, used=2000, util=0)], - samples=sample_lines(0, [0, 0, 0], memory=2000), - ) - gpu = _gpu(parse_probe_output(text, OBSERVE), 0) - assert gpu.pattern is UsagePattern.IDLE - assert gpu.state is GpuState.BUSY - - -# --------------------------------------------------------------------------- -# 選択(select_gpu) -# --------------------------------------------------------------------------- - - -def _server( - name: str, priority: int, *, data_ready: bool = True, user: str | None = None -) -> ServerConfig: - # 本リポジトリの configs/remote.yaml と同じく address・user を書かない(user は省略可) - return ServerConfig( - name=name, - user=user, - priority=priority, - remote_dir="~/work/TongueSegModel", - data_ready=data_ready, - ) - - -def _info(index: int, state: GpuState) -> GpuInfo: - return GpuInfo( - index=index, - uuid=f"GPU-{index}", - name="GPU", - memory_used_mib=0, - memory_total_mib=49140, - utilization_percent=0, - state=state, - processes_known=True, - ) - - -def _probe(server: ServerConfig, *states: GpuState, gpu_query_ok: bool = True) -> ServerProbe: - gpus = tuple(_info(i, s) for i, s in enumerate(states)) - return ServerProbe( - server, - ProbeOutput( - jobs=(), - other_sessions=(), - gpu_query_ok=gpu_query_ok, - processes_query_ok=True, - gpus=gpus if gpu_query_ok else (), - ), - ) - - -def _unreachable(server: ServerConfig) -> ServerProbe: - return ServerProbe(server, None, "Connection timed out") - - -U, S, B, X = GpuState.UNUSED, GpuState.SHARED, GpuState.BUSY, GpuState.UNKNOWN -NEWTON = _server("Newton", 1) -ARCHIMEDES = _server("Archimedes", 2) - - -def _picked(selection: GpuSelection | None) -> tuple[str, int, GpuState] | None: - if selection is None: - return None - return selection.server.name, selection.gpu_index, selection.state - - -class TestSelectGpuAutomatic: - def test_unused_beats_server_priority(self) -> None: - # Newton(優先)は利用者ありのみ,Archimedes に未使用 → Archimedes を選ぶ - probes = [_probe(NEWTON, S, S, B), _probe(ARCHIMEDES, B, U)] - assert _picked(select_gpu(probes)) == ("Archimedes", 1, U) - - def test_priority_order_among_unused(self) -> None: - probes = [_probe(ARCHIMEDES, U), _probe(NEWTON, B, U)] - assert _picked(select_gpu(probes)) == ("Newton", 1, U) - - def test_same_priority_uses_config_order(self) -> None: - first = _server("Alpha", 1) - second = _server("Beta", 1) - assert _picked(select_gpu([_probe(first, U), _probe(second, U)])) == ("Alpha", 0, U) - assert _picked(select_gpu([_probe(second, U), _probe(first, U)])) == ("Beta", 0, U) - - def test_lowest_index_within_server(self) -> None: - probe = _probe(NEWTON, B, U, U) - assert _picked(select_gpu([probe])) == ("Newton", 1, U) - - def test_index_order_even_if_listed_out_of_order(self) -> None: - output = ProbeOutput( - jobs=(), - other_sessions=(), - gpu_query_ok=True, - processes_query_ok=True, - gpus=(_info(3, U), _info(1, U), _info(2, U)), - ) - assert _picked(select_gpu([ServerProbe(NEWTON, output)])) == ("Newton", 1, U) - - def test_shared_when_no_unused_by_priority(self) -> None: - probes = [_probe(NEWTON, B, S), _probe(ARCHIMEDES, S)] - assert _picked(select_gpu(probes)) == ("Newton", 1, S) - - def test_none_when_only_busy_or_unknown(self) -> None: - probes = [_probe(NEWTON, B, X), _probe(ARCHIMEDES, X, B)] - assert select_gpu(probes) is None - - def test_data_not_ready_excluded_by_default(self) -> None: - archimedes = _server("Archimedes", 2, data_ready=False) - probes = [_probe(NEWTON, S), _probe(archimedes, U)] - assert _picked(select_gpu(probes)) == ("Newton", 0, S) - assert _picked(select_gpu(probes, include_not_ready=True)) == ("Archimedes", 0, U) - - def test_only_data_not_ready_has_free_gpu(self) -> None: - archimedes = _server("Archimedes", 2, data_ready=False) - probes = [_probe(NEWTON, B), _probe(archimedes, U)] - assert select_gpu(probes) is None - assert _picked(select_gpu(probes, include_not_ready=True)) == ("Archimedes", 0, U) - - def test_server_option_restricts_candidates(self) -> None: - probes = [_probe(NEWTON, U), _probe(ARCHIMEDES, B, S)] - assert _picked(select_gpu(probes, server_name="Archimedes")) == ("Archimedes", 1, S) - - def test_server_option_none_available(self) -> None: - probes = [_probe(NEWTON, U), _probe(ARCHIMEDES, B)] - assert select_gpu(probes, server_name="Archimedes") is None - - def test_unreachable_server_is_skipped(self) -> None: - probes = [_unreachable(NEWTON), _probe(ARCHIMEDES, S)] - assert _picked(select_gpu(probes)) == ("Archimedes", 0, S) - - def test_server_with_failed_gpu_query_is_skipped(self) -> None: - probes = [_probe(NEWTON, gpu_query_ok=False), _probe(ARCHIMEDES, S)] - assert _picked(select_gpu(probes)) == ("Archimedes", 0, S) - - def test_unknown_server_name_is_error(self) -> None: - with pytest.raises(ValueError): - select_gpu([_probe(NEWTON, U)], server_name="Nowhere") - - -class TestSelectGpuExplicit: - @pytest.mark.parametrize("state", [U, S]) - def test_unused_or_shared_is_accepted(self, state: GpuState) -> None: - probes = [_probe(NEWTON, B, state)] - selection = select_gpu(probes, server_name="Newton", gpu_index=1) - assert _picked(selection) == ("Newton", 1, state) - assert selection is not None and not selection.forced - - @pytest.mark.parametrize("state", [B, X]) - def test_busy_or_unknown_is_error_without_force(self, state: GpuState) -> None: - probes = [_probe(NEWTON, U, state)] - with pytest.raises(ValueError): - select_gpu(probes, server_name="Newton", gpu_index=1) - - @pytest.mark.parametrize("state", [B, X]) - def test_busy_or_unknown_is_allowed_with_force(self, state: GpuState) -> None: - probes = [_probe(NEWTON, U, state)] - selection = select_gpu(probes, server_name="Newton", gpu_index=1, force=True) - assert _picked(selection) == ("Newton", 1, state) - assert selection is not None and selection.forced - - def test_explicit_gpu_even_if_other_server_has_unused(self) -> None: - probes = [_probe(NEWTON, S), _probe(ARCHIMEDES, U)] - assert _picked(select_gpu(probes, server_name="Newton", gpu_index=0)) == ("Newton", 0, S) - - def test_gpu_without_server_is_error(self) -> None: - with pytest.raises(ValueError): - select_gpu([_probe(NEWTON, U)], gpu_index=0) - with pytest.raises(ValueError): - check_selection_options(server_name=None, gpu_index=0, force=False) - - def test_gpu_with_server_passes_option_check(self) -> None: - check_selection_options(server_name="Newton", gpu_index=0, force=False) - check_selection_options(server_name="Newton", gpu_index=0, force=True) - check_selection_options(server_name=None, gpu_index=None, force=False) - - -# --------------------------------------------------------------------------- -# run --cpu(SPEC_03「run」) -# --------------------------------------------------------------------------- - - -class TestCheckCpuOptions: - def test_cpu_alone_is_accepted(self) -> None: - check_cpu_options(gpu_index=None, force=False, observe_sec=None) - - @pytest.mark.parametrize( - ("gpu_index", "force", "observe_sec"), - [(0, False, None), (None, True, None), (None, False, 0), (None, False, 10), (1, True, 5)], - ) - def test_gpu_related_options_conflict( - self, gpu_index: int | None, force: bool, observe_sec: int | None - ) -> None: - with pytest.raises(ValueError): - check_cpu_options(gpu_index=gpu_index, force=force, observe_sec=observe_sec) - - -class TestSelectCpuServer: - def test_gpu_state_is_ignored(self) -> None: - # GPU がすべて使用中・状態不明・一覧取得失敗でも,接続できれば選ぶ - probes = [_probe(NEWTON, B, X), _probe(ARCHIMEDES, U)] - assert select_cpu_server(probes).name == "Newton" - probes = [_probe(NEWTON, gpu_query_ok=False), _probe(ARCHIMEDES, U)] - assert select_cpu_server(probes).name == "Newton" - - def test_priority_order(self) -> None: - # 設定の記載順ではなく priority 順 - probes = [_probe(ARCHIMEDES, U), _probe(NEWTON, B)] - assert select_cpu_server(probes).name == "Newton" - - def test_same_priority_uses_config_order(self) -> None: - a, b = _server("A", 1), _server("B", 1) - assert select_cpu_server([_probe(b, U), _probe(a, U)]).name == "B" - - def test_unreachable_is_skipped(self) -> None: - probes = [_unreachable(NEWTON), _probe(ARCHIMEDES, B)] - assert select_cpu_server(probes).name == "Archimedes" - - def test_all_unreachable_is_none(self) -> None: - assert select_cpu_server([_unreachable(NEWTON), _unreachable(ARCHIMEDES)]) is None - - def test_data_not_ready_is_excluded_by_default(self) -> None: - newton = _server("Newton", 1, data_ready=False) - probes = [_probe(newton, U), _probe(ARCHIMEDES, B)] - assert select_cpu_server(probes).name == "Archimedes" - assert select_cpu_server([_probe(newton, U)]) is None - - def test_no_data_includes_not_ready(self) -> None: - newton = _server("Newton", 1, data_ready=False) - probes = [_probe(newton, U), _probe(ARCHIMEDES, B)] - assert select_cpu_server(probes, include_not_ready=True).name == "Newton" - - def test_explicit_server(self) -> None: - probes = [_probe(NEWTON, U), _probe(ARCHIMEDES, B)] - assert select_cpu_server(probes, server_name="Archimedes").name == "Archimedes" - - def test_explicit_unreachable_server_is_error(self) -> None: - probes = [_probe(NEWTON, U), _unreachable(ARCHIMEDES)] - with pytest.raises(ValueError): - select_cpu_server(probes, server_name="Archimedes") - - def test_explicit_not_ready_server_requires_no_data(self) -> None: - newton = _server("Newton", 1, data_ready=False) - probes = [_probe(newton, U), _probe(ARCHIMEDES, U)] - with pytest.raises(ValueError): - select_cpu_server(probes, server_name="Newton") - assert select_cpu_server(probes, server_name="Newton", include_not_ready=True) is newton - - def test_unknown_server_is_error(self) -> None: - with pytest.raises(ValueError): - select_cpu_server([_probe(NEWTON, U)], server_name="Euler") - - -# --------------------------------------------------------------------------- -# 自分の利用者名(@@tsm-user.移植元との違い) -# --------------------------------------------------------------------------- - - -class TestOwnUser: - def _output(self, remote_user: str | None, **kwargs) -> ProbeOutput: - text = probe_text( - [gpu_line(0, UUID0, used=300, util=0)], - samples=sample_lines(0, [0, 0]), - apps=[f"{UUID0}, 100, 300"], - owners=["100 hasegawa 10"], - remote_user=remote_user, - **kwargs, - ) - return parse_probe_output(text, OBSERVE) - - def test_remote_user_is_parsed(self) -> None: - assert self._output("hasegawa").remote_user == "hasegawa" - - def test_remote_user_after_login_preamble(self) -> None: - output = self._output("hasegawa", preamble=["Welcome to Ubuntu"]) - assert output.remote_user == "hasegawa" - - def test_missing_user_line_is_empty(self) -> None: - assert self._output(None).remote_user == "" - - def test_empty_user_value_is_empty(self) -> None: - # id -un が失敗したとき(`@@tsm-user ` の後が空) - assert self._output("").remote_user == "" - - def test_user_marker_inside_sections_is_ignored(self) -> None: - # セッション名等として紛れた目印で自分の名前を差し替えない - text = probe_text( - [gpu_line(0, UUID0, used=5, util=0)], - samples=sample_lines(0, [0]), - others=["x"], - remote_user="hasegawa", - ).replace("other x", "@@tsm-user mallory") - assert parse_probe_output(text, OBSERVE).remote_user == "hasegawa" - - def test_own_user_prefers_probe_then_config(self) -> None: - with_probe = ServerProbe(_server("Newton", 1, user="cfguser"), self._output("hasegawa")) - assert with_probe.own_user == "hasegawa" - without_probe_user = ServerProbe(_server("Newton", 1, user="cfguser"), self._output(None)) - assert without_probe_user.own_user == "cfguser" - nothing = ServerProbe(_server("Newton", 1), self._output(None)) - assert nothing.own_user == "" - unreachable = ServerProbe(_server("Newton", 1), None, "Connection timed out") - assert unreachable.own_user == "" - - def test_own_process_is_shown_as_self(self) -> None: - gpu = _gpu(self._output("hasegawa"), 0) - assert gpu_users(gpu, "hasegawa") == ["自分"] - - def test_empty_own_user_never_marks_self(self) -> None: - # 自分の名前が分からないときは誰も「自分」にしない(空文字の所有者でも) - assert display_user_name("", "") == "" - assert display_user_name("alice", "") == "alice" - assert display_user_name(None, "") == "不明" - gpu = _gpu(self._output(None), 0) - assert gpu_users(gpu, "") == ["hasegawa"] - - def test_selection_carries_own_user(self) -> None: - probe = ServerProbe(_server("Newton", 1), self._output("hasegawa")) - for kwargs in ({}, {"server_name": "Newton", "gpu_index": 0}): - selection = select_gpu([probe], **kwargs) - assert selection is not None - assert selection.own_user == "hasegawa" diff --git a/tests/remote/test_imports.py b/tests/remote/test_imports.py deleted file mode 100644 index 5ec7997..0000000 --- a/tests/remote/test_imports.py +++ /dev/null @@ -1,85 +0,0 @@ -"""`remote` と `cli/remote.py` が重い依存・他のサブパッケージを読み込まないことのテスト. - -手元で GPU 用の依存を読み込まずに動かすため,`remote` は `torch`・`cv2` と -`tongue_seg_model` の他のサブパッケージ(`data`・`models`・`training`・`export`)を import しない -(`.claude/rules/project-structure.md`).テストの他のモジュールが既に読み込んだものと -混ざらないよう,別プロセスで `sys.modules` を確かめる. -""" - -from __future__ import annotations - -import json -import subprocess -import sys - -import pytest - -FORBIDDEN_TOP_LEVEL = ["torch", "torchvision", "cv2", "onnx", "onnxruntime", "numpy", "tiasdata"] -FORBIDDEN_SUBPACKAGES = [ - "tongue_seg_model.data", - "tongue_seg_model.models", - "tongue_seg_model.training", - "tongue_seg_model.export", - "tongue_seg_model.schema", -] - -_SCRIPT = """ -import importlib, json, sys -for name in sys.argv[1:]: - importlib.import_module(name) -print(json.dumps(sorted(sys.modules))) -""" - - -def _loaded_modules(*modules: str) -> set[str]: - result = subprocess.run( - [sys.executable, "-c", _SCRIPT, *modules], - capture_output=True, - text=True, - timeout=120, - check=True, - ) - return set(json.loads(result.stdout.strip().splitlines()[-1])) - - -@pytest.mark.parametrize( - "module", - [ - "tongue_seg_model.remote", - "tongue_seg_model.remote.commands", - "tongue_seg_model.remote.config", - "tongue_seg_model.remote.files", - "tongue_seg_model.remote.gpu", - "tongue_seg_model.remote.observe", - "tongue_seg_model.remote.report", - "tongue_seg_model.remote.transfer", - "tongue_seg_model.remote.whitelist", - "tongue_seg_model.cli.remote", - ], -) -def test_remote_does_not_import_heavy_dependencies(module: str) -> None: - loaded = _loaded_modules(module) - assert module in loaded - for name in FORBIDDEN_TOP_LEVEL: - assert name not in loaded, f"{module} が {name} を読み込んだ" - for name in FORBIDDEN_SUBPACKAGES: - leaked = sorted(m for m in loaded if m == name or m.startswith(name + ".")) - assert not leaked, f"{module} が {leaked} を読み込んだ" - - -def test_help_runs_without_torch() -> None: - """`tsm-remote --help` が torch を読み込まずに終わる(ENV_04).""" - script = ( - "import sys\n" - "import tongue_seg_model.cli.remote as cli\n" - "try:\n" - " cli.main(['--help'])\n" - "except SystemExit as exc:\n" - " assert exc.code == 0, exc.code\n" - "assert 'torch' not in sys.modules\n" - "print('ok')\n" - ) - result = subprocess.run( - [sys.executable, "-c", script], capture_output=True, text=True, timeout=120, check=True - ) - assert result.stdout.strip().endswith("ok") diff --git a/tests/remote/test_observe.py b/tests/remote/test_observe.py deleted file mode 100644 index b6fe96e..0000000 --- a/tests/remote/test_observe.py +++ /dev/null @@ -1,113 +0,0 @@ -"""観測結果の解析と使い方の型のテスト(SPEC_03「取得」「使い方の型」「表示」).""" - -from __future__ import annotations - -import pytest -from probe_helpers import PMON_HEADER - -from tongue_seg_model.remote.observe import ( - GpuSample, - UsagePattern, - classify_usage_pattern, - format_elapsed, - parse_gpu_samples, - parse_pmon, - summarize_samples, -) - - -def _samples(utils: list[int], memory: int = 10) -> list[GpuSample]: - return [GpuSample(util, memory) for util in utils] - - -def _pattern(utils: list[int], process_count: int | None) -> UsagePattern | None: - usage = summarize_samples(_samples(utils)) - assert usage is not None - return classify_usage_pattern(usage, process_count) - - -class TestParseGpuSamples: - def test_groups_samples_by_gpu_index_in_order(self) -> None: - text = "0, 5, 300\n1, 0, 10\n0, 74, 310\n1, 0, 12\n" - samples = parse_gpu_samples(text) - assert samples[0] == [GpuSample(5, 300), GpuSample(74, 310)] - assert samples[1] == [GpuSample(0, 10), GpuSample(0, 12)] - - def test_empty_output_has_no_samples(self) -> None: - assert parse_gpu_samples("") == {} - - -class TestSummarizeSamples: - def test_mean_and_max(self) -> None: - usage = summarize_samples( - [GpuSample(0, 100), GpuSample(74, 300), GpuSample(10, 200), GpuSample(0, 50)] - ) - assert usage is not None - assert usage.sample_count == 4 - assert usage.active_count == 2 - assert usage.mean_utilization_percent == pytest.approx(21.0) - assert usage.max_utilization_percent == 74 - assert usage.max_memory_used_mib == 300 - - def test_no_samples(self) -> None: - assert summarize_samples([]) is None - - -class TestUsagePattern: - @pytest.mark.parametrize( - ("utils", "expected"), - [ - ([1] * 10, UsagePattern.CONSTANT), - ([1] * 8 + [0] * 2, UsagePattern.CONSTANT), # ちょうど 80% - ([1] * 4 + [0], UsagePattern.CONSTANT), # 4/5 = 80% - ([1] * 7 + [0] * 3, UsagePattern.INTERMITTENT), # 70% - ([1] * 79 + [0] * 21, UsagePattern.INTERMITTENT), # 79% - ([1] + [0] * 9, UsagePattern.INTERMITTENT), # 1 件 - ], - ) - def test_active_ratio_boundaries(self, utils: list[int], expected: UsagePattern) -> None: - # 使用率が 0% を超えたサンプルがあれば,計算プロセスの有無によらず常時/断続的 - assert _pattern(utils, 0) is expected - assert _pattern(utils, 2) is expected - - def test_memory_only(self) -> None: - assert _pattern([0, 0, 0], 1) is UsagePattern.MEMORY_ONLY - - def test_idle(self) -> None: - assert _pattern([0, 0, 0], 0) is UsagePattern.IDLE - - -class TestParsePmon: - def test_max_sm_per_compute_process(self) -> None: - text = "\n".join( - [ - *PMON_HEADER, - " 0 1234 C 10 1 - - - - python", - " 1 5678 C 0 0 - - - - python", - " 0 1234 C 74 9 - - - - python", - " 0 1234 C 3 9 - - - - python", - ] - ) - assert parse_pmon(text) == {1234: 74, 5678: 0} - - def test_header_dash_and_graphics_rows_are_excluded(self) -> None: - text = "\n".join( - [ - *PMON_HEADER, - " 0 - - - - - - - - -", - " 0 999 G 50 2 - - - - Xorg", - " 0 1234 C - - - - - - python", - " 0 1234 C 20 - - - - - python", - ] - ) - peaks = parse_pmon(text) - assert peaks == {1234: 20} - - def test_without_header_is_unavailable(self) -> None: - assert parse_pmon("") is None - - -class TestFormatElapsed: - def test_spec_example_hours(self) -> None: - # SPEC_03「表示」の例: 27.7 時間 - assert format_elapsed(99720) == "27.7 時間" diff --git a/tests/remote/test_report.py b/tests/remote/test_report.py deleted file mode 100644 index d74818a..0000000 --- a/tests/remote/test_report.py +++ /dev/null @@ -1,102 +0,0 @@ -"""GPU 一覧の表示のテスト(SPEC_03「表示」). - -各 GPU の状態・使い方の型と使用率の平均/最大・計算プロセスごとの所有ユーザー(自分は「自分」)・ -経過時間・SM 使用率の最大が表示されること. - -TIASJudgeModel の tests/remote/test_report.py の移植.本リポジトリでは設定に `address`・`user` を -書かないため,接続先の表示は `[user@]host`,「自分」は probe の `@@tsm-user` で決まる. -""" - -from __future__ import annotations - -from probe_helpers import PMON_HEADER, gpu_line, probe_text, sample_lines - -from tongue_seg_model.remote.config import GpuFreeThreshold, ServerConfig -from tongue_seg_model.remote.gpu import ServerProbe, parse_probe_output, select_gpu -from tongue_seg_model.remote.report import format_server_report, format_shared_warning - -THRESHOLD = GpuFreeThreshold( - max_memory_used_mib=1024, max_utilization_percent=80, observe_sec=10, sample_interval_ms=500 -) -UUID0 = "GPU-0000" -SERVER = ServerConfig( - name="Newton", - priority=1, - remote_dir="~/work/TongueSegModel", - data_ready=True, -) - - -def _probe(remote_user: str | None = "hasegawa", server: ServerConfig = SERVER) -> ServerProbe: - text = probe_text( - [gpu_line(0, UUID0, used=500, util=0)], - # 平均 21%・最大 74%(断続的に使用) - samples=sample_lines(0, [0, 74, 10, 0], memory=500), - pmon=[ - *PMON_HEADER, - " 0 100 C 74 1 - - - - python", - " 0 200 C 5 1 - - - - python", - ], - apps=[f"{UUID0}, 100, 250", f"{UUID0}, 200, 250"], - owners=["100 hasegawa 99720", "200 ando 45"], - remote_user=remote_user, - ) - return ServerProbe(server, parse_probe_output(text, THRESHOLD)) - - -def test_report_shows_state_pattern_users_elapsed_and_sm() -> None: - report = format_server_report([_probe()], show_jobs=False) - assert "Newton" in report - assert "空き(利用者あり)" in report - assert "断続的に使用" in report - assert "平均 21%" in report - assert "最大 74%" in report - assert "自分" in report - assert "ando" in report - assert "27.7 時間" in report - assert "SM 最大 74%" in report - - -def test_report_marks_unreachable_server() -> None: - probe = ServerProbe(SERVER, None, "Connection timed out") - report = format_server_report([probe], show_jobs=True) - assert "Newton" in report - assert "接続不可" in report - - -def test_shared_selection_warns_with_user_names() -> None: - selection = select_gpu([_probe()]) - assert selection is not None - warning = format_shared_warning(selection) - assert warning is not None - assert "ando" in warning - - -def test_report_without_own_user_does_not_mark_self() -> None: - # 自分の名前が分からない(@@tsm-user が無い・設定に user も無い)ときは誰も「自分」にしない - report = format_server_report([_probe(None)], show_jobs=False) - assert "自分" not in report - assert "hasegawa" in report - - -def test_shared_warning_hides_own_user_name() -> None: - selection = select_gpu([_probe()]) - assert selection is not None - warning = format_shared_warning(selection) - assert warning is not None - assert "hasegawa" not in warning - - -def test_report_header_shows_host_name_when_address_is_omitted() -> None: - report = format_server_report([_probe()], show_jobs=False) - first = report.splitlines()[0] - assert first.startswith("[Newton] Newton ") - assert "None" not in report - - -def test_report_header_shows_user_and_address_when_given() -> None: - server = ServerConfig( - name="Newton", address="10.0.0.1", user="u1", priority=1, remote_dir="~/w", data_ready=True - ) - report = format_server_report([_probe(server=server)], show_jobs=False) - assert report.splitlines()[0].startswith("[Newton] u1@10.0.0.1 ") diff --git a/tests/remote/test_transfer.py b/tests/remote/test_transfer.py deleted file mode 100644 index 8e94631..0000000 --- a/tests/remote/test_transfer.py +++ /dev/null @@ -1,348 +0,0 @@ -"""回収した tar の検査・展開のテスト(SPEC_03「pull」の二重の防御の 2 段目). - -受け取った tar にホワイトリスト外の名前・パス外に出る名前・リンクが 1 つでもあれば, -何も展開せずに中止すること(展開先に何も作られないこと). - -TIASJudgeModel の tests/remote/test_transfer.py の移植.重みの名前(`checkpoints/best.pth`・ -`checkpoints/ResUNet.onnx`)と,本リポジトリで回収しない名前(`split.json`・`predictions.csv`・ -`figures/` 以外の画像・指定の無い重み)・抜け道(`:`・制御文字・ディレクトリのエントリ等)を足した. -""" - -import io -import tarfile -from collections.abc import Iterator -from pathlib import Path - -import pytest -from link_helpers import LinkFactory - -from tongue_seg_model.remote.files import PushEntry -from tongue_seg_model.remote.transfer import extract_pull_archive, write_tar_stream - -RUN_ID = "20261119-120000_resunet_abc1234-dirty" - - -def _add_file(tar: tarfile.TarFile, name: str, data: bytes = b"x") -> None: - info = tarfile.TarInfo(name) - info.size = len(data) - tar.addfile(info, io.BytesIO(data)) - - -def _add_link(tar: tarfile.TarFile, name: str, target: str, kind: bytes) -> None: - info = tarfile.TarInfo(name) - info.type = kind - info.linkname = target - tar.addfile(info) - - -def _add_dir(tar: tarfile.TarFile, name: str) -> None: - info = tarfile.TarInfo(name) - info.type = tarfile.DIRTYPE - info.mode = 0o755 - tar.addfile(info) - - -def _archive(build) -> io.BytesIO: - buffer = io.BytesIO() - with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar: - build(tar) - buffer.seek(0) - return buffer - - -def _all_files(root: Path) -> list[Path]: - return sorted(root.rglob("*")) if root.exists() else [] - - -def test_extracts_whitelisted_files(tmp_path: Path) -> None: - def build(tar: tarfile.TarFile) -> None: - _add_file(tar, f"{RUN_ID}/config.yaml", b"seed: 0\n") - _add_file(tar, f"{RUN_ID}/metrics.json", b"{}") - _add_file(tar, f"{RUN_ID}/figures/loss.png", b"png") - - dest = tmp_path / "runs" - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) - assert result.files == 3 - assert (dest / RUN_ID / "config.yaml").read_bytes() == b"seed: 0\n" - assert (dest / RUN_ID / "figures" / "loss.png").read_bytes() == b"png" - - -def test_overwrites_existing_file(tmp_path: Path) -> None: - dest = tmp_path / "runs" - (dest / RUN_ID).mkdir(parents=True) - (dest / RUN_ID / "metrics.json").write_bytes(b"old") - archive = _archive(lambda tar: _add_file(tar, f"{RUN_ID}/metrics.json", b"new")) - extract_pull_archive(archive, dest, RUN_ID, with_checkpoints=False) - assert (dest / RUN_ID / "metrics.json").read_bytes() == b"new" - - -def test_checkpoints_extracted_only_with_flag(tmp_path: Path) -> None: - def build(tar: tarfile.TarFile) -> None: - _add_file(tar, f"{RUN_ID}/config.yaml") - _add_file(tar, f"{RUN_ID}/checkpoints/best.pth", b"weights") - _add_file(tar, f"{RUN_ID}/checkpoints/ResUNet.onnx", b"onnx") - - dest = tmp_path / "runs" - with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) - assert _all_files(dest) == [] - - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True) - assert result.files == 3 - assert (dest / RUN_ID / "checkpoints" / "best.pth").read_bytes() == b"weights" - assert (dest / RUN_ID / "checkpoints" / "ResUNet.onnx").read_bytes() == b"onnx" - - -BAD_MEMBERS = { - "split_json": lambda tar: _add_file(tar, f"{RUN_ID}/split.json"), - "split_json_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/split.json"), - "other_weight": lambda tar: _add_file(tar, f"{RUN_ID}/checkpoints/epoch3.pth"), - "onnx_lowercase": lambda tar: _add_file(tar, f"{RUN_ID}/checkpoints/resunet.onnx"), - "upper_case_config": lambda tar: _add_file(tar, f"{RUN_ID}/Config.yaml"), - "upper_case_png": lambda tar: _add_file(tar, f"{RUN_ID}/figures/loss.PNG"), - "png_in_sub_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/sub/a.png"), - "jpg_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/x.jpg"), - "empty_png_name": lambda tar: _add_file(tar, f"{RUN_ID}/figures/.png"), - "trailing_dot": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a.png."), - "trailing_space": lambda tar: _add_file(tar, f"{RUN_ID}/config.yaml "), - "alternate_stream": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a:b.png"), - "stream_on_config": lambda tar: _add_file(tar, f"{RUN_ID}/config.yaml:x"), - "newline": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a\n.png"), - "control_char": lambda tar: _add_file(tar, f"{RUN_ID}/figures/a\x01.png"), - "dotdot_in_figures": lambda tar: _add_file(tar, f"{RUN_ID}/figures/../split.json"), - "absolute_etc": lambda tar: _add_file(tar, "/etc/passwd"), - "drive_config": lambda tar: _add_file(tar, "C:/config.yaml"), - "directory": lambda tar: _add_dir(tar, f"{RUN_ID}/figures"), - "run_directory": lambda tar: _add_dir(tar, RUN_ID), - "symlink_png": lambda tar: _add_link( - tar, f"{RUN_ID}/figures/a.png", "../split.json", tarfile.SYMTYPE - ), - "hardlink_to_outside": lambda tar: _add_link( - tar, f"{RUN_ID}/log.txt", "../../outside.txt", tarfile.LNKTYPE - ), - "fifo": lambda tar: _add_link(tar, f"{RUN_ID}/history.csv", "", tarfile.FIFOTYPE), - "predictions": lambda tar: _add_file(tar, f"{RUN_ID}/predictions.csv"), - "png_outside_figures": lambda tar: _add_file(tar, f"{RUN_ID}/P0001.png"), - "manifest": lambda tar: _add_file(tar, f"{RUN_ID}/manifest.csv"), - "image": lambda tar: _add_file(tar, f"{RUN_ID}/images/P0001.jpg"), - "other_run": lambda tar: _add_file(tar, "other_run/config.yaml"), - "dotdot": lambda tar: _add_file(tar, f"{RUN_ID}/../evil.txt"), - "dotdot_top": lambda tar: _add_file(tar, "../evil.txt"), - "absolute": lambda tar: _add_file(tar, "/tmp/evil.txt"), - "drive_letter": lambda tar: _add_file(tar, "C:/evil.txt"), - "drive_relative": lambda tar: _add_file(tar, "C:evil.txt"), - "backslash": lambda tar: _add_file(tar, f"{RUN_ID}\\config.yaml"), - "symlink": lambda tar: _add_link(tar, f"{RUN_ID}/log.txt", "/etc/passwd", tarfile.SYMTYPE), - "symlink_relative": lambda tar: _add_link( - tar, f"{RUN_ID}/history.csv", "../../outside", tarfile.SYMTYPE - ), - "hardlink": lambda tar: _add_link( - tar, f"{RUN_ID}/metrics.json", f"{RUN_ID}/config.yaml", tarfile.LNKTYPE - ), -} - - -@pytest.mark.parametrize("bad", list(BAD_MEMBERS), ids=list(BAD_MEMBERS)) -@pytest.mark.parametrize("position", ["first", "last"]) -def test_bad_member_aborts_without_extracting_anything( - tmp_path: Path, bad: str, position: str -) -> None: - def build(tar: tarfile.TarFile) -> None: - if position == "first": - BAD_MEMBERS[bad](tar) - _add_file(tar, f"{RUN_ID}/config.yaml") - _add_file(tar, f"{RUN_ID}/figures/cm.png") - _add_file(tar, f"{RUN_ID}/checkpoints/best.pth") - if position == "last": - BAD_MEMBERS[bad](tar) - - work = tmp_path / "work" - dest = work / "runs" - with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=True) - # 展開先にも,その外側(パス外に出る名前の行き先)にも何も作られない - assert _all_files(dest) == [] - assert not (dest / RUN_ID / "config.yaml").exists() - assert not (work / "evil.txt").exists() - assert not (tmp_path / "evil.txt").exists() - assert [p for p in _all_files(tmp_path) if p.is_file()] == [] - - -def test_error_message_does_not_contain_rejected_names(tmp_path: Path) -> None: - secret = "P0001_yamada" - - def build(tar: tarfile.TarFile) -> None: - _add_file(tar, f"{RUN_ID}/config.yaml") - _add_file(tar, f"{RUN_ID}/{secret}.png") - _add_file(tar, f"{RUN_ID}/figures/{secret}:a.png") - _add_link(tar, f"{RUN_ID}/{secret}.lnk", f"/home/{secret}", tarfile.SYMTYPE) - _add_dir(tar, f"{RUN_ID}/{secret}") - - with pytest.raises(ValueError) as excinfo: - extract_pull_archive(_archive(build), tmp_path / "runs", RUN_ID, with_checkpoints=False) - assert secret not in str(excinfo.value) - assert "yamada" not in str(excinfo.value) - - -def test_broken_archive_extracts_nothing(tmp_path: Path) -> None: - dest = tmp_path / "runs" - with pytest.raises(tarfile.TarError): - extract_pull_archive(io.BytesIO(b"not a tar" * 100), dest, RUN_ID, with_checkpoints=False) - assert _all_files(dest) == [] - - -def test_empty_archive_extracts_nothing(tmp_path: Path) -> None: - result = extract_pull_archive( - _archive(lambda tar: None), tmp_path / "runs", RUN_ID, with_checkpoints=False - ) - assert result.files == 0 - - -def test_write_tar_stream_round_trip(tmp_path: Path) -> None: - src = tmp_path / "src" - (src / "pkg").mkdir(parents=True) - (src / "pkg" / "a.py").write_bytes(b"print('a')\n") - (src / "日本語.md").write_text("x", encoding="utf-8") - entries = [ - PushEntry(src / "pkg" / "a.py", "pkg/a.py", (src / "pkg" / "a.py").stat().st_size), - PushEntry(src / "日本語.md", "日本語.md", 1), - ] - buffer = io.BytesIO() - write_tar_stream(entries, buffer) - buffer.seek(0) - with tarfile.open(fileobj=buffer, mode="r") as tar: - names = tar.getnames() - assert names == ["pkg/a.py", "日本語.md"] - member = tar.extractfile("pkg/a.py") - assert member is not None - assert member.read() == b"print('a')\n" - - -# --------------------------------------------------------------------------- -# write_tar_stream の二重の守り: 通常ファイル以外を含む entries は何も書かずに止める -# --------------------------------------------------------------------------- - - -@pytest.fixture -def links() -> Iterator[LinkFactory]: - factory = LinkFactory() - yield factory - factory.cleanup() - - -def _entry(path: Path, arcname: str) -> PushEntry: - return PushEntry(path, arcname, 0) - - -def _code_entry(root: Path) -> PushEntry: - path = root / "a.py" - path.write_bytes(b"print('a')\n") - return PushEntry(path, "a.py", path.stat().st_size) - - -@pytest.mark.parametrize("position", ["first", "last"]) -def test_write_tar_stream_rejects_file_symlink( - tmp_path: Path, links: LinkFactory, position: str -) -> None: - outside = tmp_path / "outside" - outside.mkdir() - (outside / "secret.py").write_bytes(b"secret") - link = links.symlink(tmp_path / "leak.py", outside / "secret.py") - good = _code_entry(tmp_path) - bad = _entry(link, "leak.py") - entries = [bad, good] if position == "first" else [good, bad] - buffer = io.BytesIO() - with pytest.raises(ValueError): - write_tar_stream(entries, buffer) - assert buffer.getvalue() == b"" - - -@pytest.mark.parametrize("kind", ["symlink", "junction"]) -def test_write_tar_stream_rejects_directory_link( - tmp_path: Path, links: LinkFactory, kind: str -) -> None: - outside = tmp_path / "outside" - outside.mkdir() - (outside / "secret.py").write_bytes(b"secret") - link = getattr(links, kind)(tmp_path / "ext", outside) - buffer = io.BytesIO() - with pytest.raises(ValueError): - write_tar_stream([_code_entry(tmp_path), _entry(link, "ext")], buffer) - assert buffer.getvalue() == b"" - - -def test_write_tar_stream_rejects_directory(tmp_path: Path) -> None: - (tmp_path / "pkg").mkdir() - buffer = io.BytesIO() - with pytest.raises(ValueError): - write_tar_stream([_code_entry(tmp_path), _entry(tmp_path / "pkg", "pkg")], buffer) - assert buffer.getvalue() == b"" - - -def test_write_tar_stream_rejects_missing_file(tmp_path: Path) -> None: - buffer = io.BytesIO() - with pytest.raises(ValueError): - write_tar_stream([_code_entry(tmp_path), _entry(tmp_path / "gone.py", "gone.py")], buffer) - assert buffer.getvalue() == b"" - - -def test_write_tar_stream_does_not_dereference(tmp_path: Path) -> None: - """通常ファイルだけの entries は従来どおりの tar になり,メンバーは通常ファイルのみ.""" - entries = [_code_entry(tmp_path)] - buffer = io.BytesIO() - assert write_tar_stream(entries, buffer) == entries[0].size - buffer.seek(0) - with tarfile.open(fileobj=buffer, mode="r") as tar: - assert all(member.isreg() for member in tar.getmembers()) - - -# --------------------------------------------------------------------------- -# 受け取った tar に Windows の予約名・末尾 `.` のエントリがあれば全体を拒否する -# --------------------------------------------------------------------------- - - -@pytest.mark.parametrize( - "name", - [ - f"{RUN_ID}/figures/CON.png", - f"{RUN_ID}/figures/nul.png", - f"{RUN_ID}/figures/COM1.png", - f"{RUN_ID}/figures/LPT9.png", - f"{RUN_ID}/figures/Aux.x.png", - f"{RUN_ID}/figures/nul .png", - f"{RUN_ID}/figures/a.png.", - f"{RUN_ID}/config.yaml.", - f"{RUN_ID}/figures./a.png", - ], -) -@pytest.mark.parametrize("position", ["first", "last"]) -def test_windows_unsafe_member_aborts_without_extracting_anything( - tmp_path: Path, name: str, position: str -) -> None: - def build(tar: tarfile.TarFile) -> None: - if position == "first": - _add_file(tar, name) - _add_file(tar, f"{RUN_ID}/config.yaml") - _add_file(tar, f"{RUN_ID}/figures/CONSOLE.png") - if position == "last": - _add_file(tar, name) - - dest = tmp_path / "runs" - with pytest.raises(ValueError): - extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) - assert _all_files(dest) == [] - - -def test_names_similar_to_reserved_are_extracted(tmp_path: Path) -> None: - def build(tar: tarfile.TarFile) -> None: - for name in ["CONSOLE.png", "COM10.png", "nul_.png"]: - _add_file(tar, f"{RUN_ID}/figures/{name}") - - dest = tmp_path / "runs" - result = extract_pull_archive(_archive(build), dest, RUN_ID, with_checkpoints=False) - assert result.files == 3 - assert sorted(p.name for p in (dest / RUN_ID / "figures").iterdir()) == [ - "COM10.png", - "CONSOLE.png", - "nul_.png", - ] diff --git a/tests/remote/test_whitelist.py b/tests/remote/test_whitelist.py deleted file mode 100644 index fdffa7f..0000000 --- a/tests/remote/test_whitelist.py +++ /dev/null @@ -1,656 +0,0 @@ -"""回収ホワイトリストの判定のテスト(SPEC_01「回収ホワイトリスト」・SPEC_03「pull」). - -最重要(testing ルールの必須対象 1): 名前が一致するファイルだけが回収対象になり,分割結果・ -画像ごとの予測・画像・manifest・指定の無い重みは回収されないこと.破れるとファイル名を含む結果や -画像が手元に流れる. - -回収する(`runs/<実験ID>/` 配下): `config.yaml`・`history.csv`・`metrics.json`・`log.txt`・ -`figures/*.png`(直下のみ).`--with-checkpoints` のときだけ `checkpoints/best.pth`・ -`checkpoints/ResUNet.onnx`(名前の完全一致).それ以外はすべて回収しない. - -TIASJudgeModel の tests/remote/test_whitelist.py の移植.回収するファイル名と重みの名前を -本リポジトリの SPEC_01 に合わせ,抜け道(`:`・末尾の `.` や空白・大文字小文字・制御文字・ -ディレクトリのエントリ等)と,`tsm-train` の実験 ID の形の確認を足した. -""" - -import io -import tarfile -from datetime import datetime - -import pytest - -from tongue_seg_model.remote.whitelist import ( - PULL_CHECKPOINT_FILES, - PULL_ROOT_FILES, - check_pull_members, - is_pull_allowed, - parse_find_listing, - plan_pull, - validate_run_id, -) - -RUN_ID = "20261119-120000_resunet_abc1234" - -# SPEC_01「回収ホワイトリスト」の表 -ROOT_FILES = ["config.yaml", "history.csv", "metrics.json", "log.txt"] -FIGURES = ["figures/loss.png", "figures/iou.png", "figures/learning_curve.png", "figures/a b.png"] -CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/ResUNet.onnx"] -ALLOWED = ROOT_FILES + FIGURES - -# 列挙外(回収してはならない)ファイル.--with-checkpoints を付けても回収しない -NOT_ALLOWED = [ - # 画像ごとの結果・分割結果(ファイル名を含む) - "split.json", - "predictions.csv", - "per_image_predictions.csv", - "manifest.csv", - "data/manifest.csv", - # 画像(figures/ 以外にある *.png・figures/ の png 以外) - "a.png", - "loss.png", - "P0001_tongue.png", - "P0001_tongue.jpg", - "images/P0001.png", - "masks/P0001.png", - "predictions/P0001.png", - "figures/x.jpg", - "figures/x.jpeg", - "figures/x.bmp", - "figures/x.npy", - "figures/sub/a.png", - "figures/a/b/c.png", - "sub/figures/a.png", - "figures/.png", - "figures/config.yaml", - # 名前の似たもの - "config.yml", - "config.yaml.bak", - "config.yaml~", - ".config.yaml", - "metrics.json.tmp", - "history.csv.bak", - "log.txt.1", - "sub/config.yaml", - "checkpoints/config.yaml", - # 大文字小文字の違い(完全一致で比べる) - "Config.yaml", - "CONFIG.YAML", - "Metrics.json", - "LOG.TXT", - "figures/loss.PNG", - "figures/loss.Png", - "Figures/loss.png", - "FIGURES/loss.png", - # Windows が末尾の . や空白を捨てて別の名前になるもの - "config.yaml.", - "config.yaml ", - "config.yaml. ", - "figures/a.png.", - "figures/a.png ", - "figures./a.png", - "figures /a.png", - # 代替データストリーム・Windows で使えない文字 - "config.yaml:secret", - "metrics.json::$DATA", - "figures/a:b.png", - "figures/ab.png", - 'figures/a"b.png', - "figures/a|b.png", - "figures/a?b.png", - "figures/a*b.png", - # 制御文字・改行 - "config.yaml\n", - "figures/a\n.png", - "figures/a\r.png", - "figures/a\x00.png", - "figures/a\t.png", - "figures/a\x1b.png", - "figures/a\x7f.png", - # 重み(指定の無いもの・名前が完全一致しないもの) - "checkpoints/epoch3.pth", - "checkpoints/last.pth", - "checkpoints/resunet.onnx", - "checkpoints/RESUNET.ONNX", - "checkpoints/Best.pth", - "checkpoints/best.PTH", - "checkpoints/best.pt", - "checkpoints/best.pth.", - "checkpoints/best.pth ", - "checkpoints/best.pth.bak", - "checkpoints/sub/best.pth", - "checkpoints/figures/a.png", - "Checkpoints/best.pth", - "best.pth", - "ResUNet.onnx", - "figures/best.pth", - "figures/ResUNet.onnx", -] - -UNSAFE_PATHS = [ - "..", - "../config.yaml", - "../x/config.yaml", - "figures/../config.yaml", - "figures/../split.json", - "./config.yaml", - "figures/./a.png", - "figures//a.png", - "/config.yaml", - "/etc/passwd", - "C:config.yaml", - "C:/config.yaml", - "c:/figures/a.png", - "figures\\a.png", - "..\\config.yaml", - "\\\\server\\share\\config.yaml", - "", - "/", - "figures/", - "checkpoints/../checkpoints/best.pth", -] - - -def test_root_files_are_exactly_the_spec_list() -> None: - # 回収対象を増やすときは SPEC_01 とこのテストを同時に変える - assert PULL_ROOT_FILES == frozenset(ROOT_FILES) - - -def test_checkpoint_files_are_exactly_the_spec_list() -> None: - assert PULL_CHECKPOINT_FILES == frozenset({"best.pth", "ResUNet.onnx"}) - - -class TestIsPullAllowed: - @pytest.mark.parametrize("name", ALLOWED) - @pytest.mark.parametrize("with_checkpoints", [False, True]) - def test_allowed_names(self, name: str, with_checkpoints: bool) -> None: - assert is_pull_allowed(name, with_checkpoints=with_checkpoints) - - @pytest.mark.parametrize("name", NOT_ALLOWED) - @pytest.mark.parametrize("with_checkpoints", [False, True]) - def test_names_outside_whitelist_are_not_allowed( - self, name: str, with_checkpoints: bool - ) -> None: - # --with-checkpoints は checkpoints/best.pth・ResUNet.onnx 以外の判定を変えない - assert not is_pull_allowed(name, with_checkpoints=with_checkpoints) - - @pytest.mark.parametrize("name", ["split.json", "predictions.csv", "manifest.csv"]) - def test_per_image_results_never_pulled_even_with_checkpoints(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=True) - - @pytest.mark.parametrize("name", CHECKPOINTS) - def test_checkpoints_only_with_flag(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=False) - assert is_pull_allowed(name, with_checkpoints=True) - - @pytest.mark.parametrize("name", UNSAFE_PATHS) - def test_unsafe_paths_are_not_allowed(self, name: str) -> None: - assert not is_pull_allowed(name, with_checkpoints=True) - - -class TestValidateRunId: - @pytest.mark.parametrize( - "run_id", - [ - RUN_ID, - "20261119-120000_resunet_abc1234-dirty", - "20261119-120000_synthetic-gpu_nogit", - "20261119-120000_my.config_0123456789abcdef0123456789abcdef01234567-dirty", - "a", - "A" * 200, - ], - ) - def test_accepts_normal_run_id(self, run_id: str) -> None: - assert validate_run_id(run_id) == run_id - - @pytest.mark.parametrize( - "run_id", - [ - "a/b", - "a\\b", - "..", - "../x", - "x/..", - "a..b", - "/abs", - "runs/x", - "", - ".", - ".hidden", - "-rf", - "_x", - # 末尾の改行(match と $ の組み合わせでは通ってしまう) - f"{RUN_ID}\n", - f"{RUN_ID}\r", - f"\n{RUN_ID}", - f"{RUN_ID} ", - f" {RUN_ID}", - "a b", - "a'b", - 'a"b', - "a;b", - "a$b", - "$(id)", - "`id`", - "a:b", - "C:x", - "a*", - "a\x00b", - "a\tb", - "実験", - "A" * 201, - ], - ) - def test_rejects_bad_run_id(self, run_id: str) -> None: - with pytest.raises(ValueError): - validate_run_id(run_id) - - def test_error_is_value_error_with_hint(self) -> None: - with pytest.raises(ValueError, match="実験 ID"): - validate_run_id("../x") - - -class TestRunIdOfTsmTrain: - """`tsm-train` の実験 ID(`make_run_id`)が pull の実験 ID の検証を通ること. - - `remote` から `training` を import してはならないが,テストコードからは使ってよい. - """ - - @pytest.mark.parametrize( - ("config_name", "git_commit"), - [ - ("resunet", "abc1234"), - ("resunet", "abc1234-dirty"), - ("synthetic", "nogit"), - ("synthetic-gpu", "0123456789abcdef0123456789abcdef01234567-dirty"), - ("my.config_v2", "deadbeef"), - ("C" * 64, "a" * 64), - ], - ) - def test_make_run_id_passes(self, config_name: str, git_commit: str) -> None: - from tongue_seg_model.training.run_artifacts import make_run_id - - run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, git_commit) - assert validate_run_id(run_id) == run_id - - def test_value_passed_by_remote_is_accepted_by_training(self) -> None: - """`format_git_commit` が渡す値を `resolve_git_commit` がそのまま受け取ること.""" - from tongue_seg_model.remote.commands import format_git_commit - from tongue_seg_model.training.run_artifacts import make_run_id, resolve_git_commit - - for short_hash in ["abc1", "abc1234", "0123456789abcdef0123456789abcdef01234567"]: - for dirty in (False, True): - value = format_git_commit(short_hash, dirty=dirty) - assert value is not None - assert resolve_git_commit({"TSM_GIT_COMMIT": value}) == value - run_id = make_run_id(datetime(2026, 1, 2, 3, 4, 5), "resunet", value) - assert validate_run_id(run_id) == run_id - - -def test_git_commit_env_var_is_the_same_in_remote_and_training() -> None: - """`TSM_GIT_COMMIT` の名前は 2 か所に置かれている(remote は training を import しないため).""" - from tongue_seg_model.remote import commands - from tongue_seg_model.training import run_artifacts - - assert commands.GIT_COMMIT_ENV_VAR == run_artifacts.GIT_COMMIT_ENV_VAR == "TSM_GIT_COMMIT" - - -class TestPlanPull: - def _listing(self, names: list[str], kind: str = "f") -> list[tuple[str, str]]: - return [(kind, f"{RUN_ID}/{name}") for name in names] - - def test_selects_only_whitelisted_files(self) -> None: - listing = self._listing(ALLOWED + NOT_ALLOWED + CHECKPOINTS) - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) - assert sorted(plan.files) == sorted(f"{RUN_ID}/{name}" for name in ALLOWED) - assert plan.skipped == len(NOT_ALLOWED) + len(CHECKPOINTS) - assert plan.skipped_checkpoints == len(CHECKPOINTS) - - def test_with_checkpoints_includes_only_two_weights(self) -> None: - listing = self._listing( - ["config.yaml", *CHECKPOINTS, "checkpoints/epoch3.pth", "split.json", "predictions.csv"] - ) - plan = plan_pull(listing, RUN_ID, with_checkpoints=True) - assert sorted(plan.files) == sorted( - [f"{RUN_ID}/config.yaml", *(f"{RUN_ID}/{name}" for name in CHECKPOINTS)] - ) - assert plan.skipped == 3 - assert plan.skipped_checkpoints == 0 - - @pytest.mark.parametrize("kind", ["l", "d", "p", "s", "c", "b", "D", "N", "?"]) - def test_non_regular_entries_are_not_selected_even_with_whitelisted_name( - self, kind: str - ) -> None: - listing = self._listing(["config.yaml", "figures/a.png", "checkpoints/best.pth"], kind) - plan = plan_pull(listing, RUN_ID, with_checkpoints=True) - assert plan.files == () - assert plan.skipped == 3 - - @pytest.mark.parametrize( - "path", - [ - "other_run/config.yaml", - f"{RUN_ID}x/config.yaml", - f"{RUN_ID.upper()}/config.yaml", - "config.yaml", - f"{RUN_ID}", - f"x/{RUN_ID}/config.yaml", - f"../{RUN_ID}/config.yaml", - ], - ) - def test_files_outside_the_run_are_not_selected(self, path: str) -> None: - plan = plan_pull([("f", path)], RUN_ID, with_checkpoints=True) - assert plan.files == () - assert plan.skipped == 1 - - def test_parse_find_listing_round_trip(self) -> None: - data = f"f {RUN_ID}/config.yaml\0f {RUN_ID}/figures/a b.png\0l {RUN_ID}/x\0".encode() - assert parse_find_listing(data) == [ - ("f", f"{RUN_ID}/config.yaml"), - ("f", f"{RUN_ID}/figures/a b.png"), - ("l", f"{RUN_ID}/x"), - ] - - def test_newline_in_server_file_name_does_not_split_entries(self) -> None: - # NUL 区切りなので,改行を含む名前で別のエントリを偽装できない - data = f"f {RUN_ID}/split.json\nf {RUN_ID}/config.yaml\0".encode() - listing = parse_find_listing(data) - assert len(listing) == 1 - assert plan_pull(listing, RUN_ID, with_checkpoints=False).files == () - - def test_non_utf8_names_are_not_selected(self) -> None: - data = b"f " + RUN_ID.encode() + b"/figures/\xff\xfe.png\0" - listing = parse_find_listing(data) - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) - # 名前としては figures/*.png に一致する.選ばれたなら tar の側でも同じ名前で検査される - assert len(plan.files) + plan.skipped == 1 - - @pytest.mark.parametrize("data", [b"fconfig.yaml\0", b" x\0", b"f \0"]) - def test_broken_listing_is_error(self, data: bytes) -> None: - with pytest.raises(ValueError): - parse_find_listing(data) - - -def _regular(name: str) -> tarfile.TarInfo: - info = tarfile.TarInfo(name) - info.size = 0 - return info - - -def _typed(name: str, kind: bytes, target: str = "") -> tarfile.TarInfo: - info = tarfile.TarInfo(name) - info.type = kind - info.linkname = target - return info - - -BAD_MEMBERS = [ - *(_regular(f"{RUN_ID}/{name}") for name in NOT_ALLOWED), - *(_regular(f"{RUN_ID}/{name}") for name in UNSAFE_PATHS), - *(_regular(name) for name in UNSAFE_PATHS), - _regular("other_run/config.yaml"), - _regular("config.yaml"), - _regular(f"{RUN_ID.upper()}/config.yaml"), - _regular(f"{RUN_ID}/../config.yaml"), - _regular(f"{RUN_ID}/../../x/config.yaml"), - _regular(f"/{RUN_ID}/config.yaml"), - _regular(f"C:/{RUN_ID}/config.yaml"), - _regular(f"C:{RUN_ID}/config.yaml"), - _regular(f"{RUN_ID}\\config.yaml"), - _regular(f"{RUN_ID}/config.yaml:stream"), - _typed(f"{RUN_ID}/config.yaml", tarfile.SYMTYPE, "/etc/passwd"), - _typed(f"{RUN_ID}/figures/a.png", tarfile.SYMTYPE, "../split.json"), - _typed(f"{RUN_ID}/metrics.json", tarfile.LNKTYPE, f"{RUN_ID}/config.yaml"), - _typed(f"{RUN_ID}/log.txt", tarfile.LNKTYPE, f"{RUN_ID}/split.json"), - _typed(f"{RUN_ID}/figures", tarfile.DIRTYPE), - _typed(RUN_ID, tarfile.DIRTYPE), - _typed(f"{RUN_ID}/config.yaml", tarfile.DIRTYPE), - _typed(f"{RUN_ID}/config.yaml", tarfile.FIFOTYPE), - _typed(f"{RUN_ID}/config.yaml", tarfile.CHRTYPE), - _typed(f"{RUN_ID}/config.yaml", tarfile.BLKTYPE), -] - - -class TestCheckPullMembers: - def test_accepts_only_whitelisted_regular_files(self) -> None: - members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED] - assert check_pull_members(members, RUN_ID, with_checkpoints=False) == len(members) - - def test_accepts_checkpoints_with_flag(self) -> None: - members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED + CHECKPOINTS] - assert check_pull_members(members, RUN_ID, with_checkpoints=True) == len(members) - - def test_empty_archive_is_accepted_as_zero(self) -> None: - assert check_pull_members([], RUN_ID, with_checkpoints=False) == 0 - - @pytest.mark.parametrize("bad", BAD_MEMBERS, ids=lambda info: repr(info.name)[:60]) - @pytest.mark.parametrize("with_checkpoints", [False, True]) - def test_rejects_whole_archive_if_any_member_is_bad( - self, bad: tarfile.TarInfo, with_checkpoints: bool - ) -> None: - members = [_regular(f"{RUN_ID}/config.yaml"), bad, _regular(f"{RUN_ID}/log.txt")] - with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints) - - @pytest.mark.parametrize("name", CHECKPOINTS) - def test_checkpoints_rejected_without_flag(self, name: str) -> None: - members = [_regular(f"{RUN_ID}/config.yaml"), _regular(f"{RUN_ID}/{name}")] - with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=False) - - def test_error_message_does_not_contain_member_names(self) -> None: - secret = "P0001_yamada_tongue" - members = [ - _regular(f"{RUN_ID}/{secret}.png"), - _regular(f"{RUN_ID}/figures/{secret}:x.png"), - _typed(f"{RUN_ID}/{secret}_link", tarfile.SYMTYPE, f"/home/{secret}"), - _typed(f"{RUN_ID}/{secret}_dir", tarfile.DIRTYPE), - _regular(f"../{secret}.csv"), - _regular(f"{RUN_ID}/checkpoints/{secret}.pth"), - ] - with pytest.raises(ValueError) as excinfo: - check_pull_members(members, RUN_ID, with_checkpoints=False) - message = str(excinfo.value) - assert secret not in message - assert "yamada" not in message - assert RUN_ID not in message - # 件数だけを示す - assert "ホワイトリスト外" in message - - def test_members_from_real_tar_file(self) -> None: - buffer = io.BytesIO() - with tarfile.open(fileobj=buffer, mode="w") as tar: - tar.addfile(_regular(f"{RUN_ID}/config.yaml"), io.BytesIO(b"")) - tar.addfile(_typed(f"{RUN_ID}/log.txt", tarfile.SYMTYPE, "/etc/shadow")) - buffer.seek(0) - with tarfile.open(fileobj=buffer, mode="r") as tar, pytest.raises(ValueError): - check_pull_members(tar.getmembers(), RUN_ID, with_checkpoints=False) - - def test_pax_path_override_is_checked(self) -> None: - """PAX ヘッダの path で名前を差し替えたメンバーも,差し替え後の名前で検査する.""" - buffer = io.BytesIO() - with tarfile.open(fileobj=buffer, mode="w", format=tarfile.PAX_FORMAT) as tar: - info = _regular(f"{RUN_ID}/config.yaml") - info.pax_headers = {"path": f"{RUN_ID}/split.json"} - tar.addfile(info, io.BytesIO(b"")) - buffer.seek(0) - with tarfile.open(fileobj=buffer, mode="r") as tar: - members = tar.getmembers() - assert members[0].name == f"{RUN_ID}/split.json" - with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=True) - - -# --------------------------------------------------------------------------- -# Windows で見かけと違う場所を指す名前(末尾の `.`・空白と予約デバイス名) -# --------------------------------------------------------------------------- - -# 予約名: CON・PRN・AUX・NUL・COM1〜9・LPT1〜9・COM¹〜³・LPT¹〜³(大文字小文字を問わず, -# 最初の `.` より前で判定する) -RESERVED_BASES = [ - "CON", - "con", - "Prn", - "aux", - "NUL", - "nul", - *(f"COM{d}" for d in "123456789"), - *(f"lpt{d}" for d in "123456789"), - "COM¹", - "com²", - "COM³", - "LPT¹", - "lpt²", - "LPT³", -] -# 予約名に似ているが予約名ではないもの -NOT_RESERVED_BASES = ["CONSOLE", "COM10", "LPT10", "COM0", "LPT0", "nul_", "_nul", "CONx", "AUX1"] - - -class TestWindowsUnsafeRunId: - @pytest.mark.parametrize( - "run_id", - [ - "abc.", - "abc..", - "nul", - "NUL", - "con.txt", - "Com1", - "lpt9.x", - "AUX", - "prn.tar.gz", - "COM¹", - "lpt³.a", - f"{RUN_ID}.", - ], - ) - def test_rejects_trailing_dot_and_reserved_names(self, run_id: str) -> None: - with pytest.raises(ValueError): - validate_run_id(run_id) - - @pytest.mark.parametrize( - "run_id", - ["CONSOLE", "COM10", "LPT10", "COM0", "nul_", "CONx", "AUX1", "CONSOLE.x", "nul_.a"], - ) - def test_names_similar_to_reserved_are_accepted(self, run_id: str) -> None: - assert validate_run_id(run_id) == run_id - - @pytest.mark.parametrize( - "run_id", - [ - "20261119-120000_resunet_abc1234-dirty", - "20261119-120000_synthetic_nogit", - "20261119-120000_resunet_0123456789abcdef0123456789abcdef01234567", - "20261119-120000_con_abc1234", - "20261119-120000_nul_nogit", - ], - ) - def test_make_run_id_shapes_are_still_accepted(self, run_id: str) -> None: - assert validate_run_id(run_id) == run_id - - @pytest.mark.parametrize("config_name", ["con", "NUL", "aux", "com1", "lpt9", "prn"]) - def test_make_run_id_with_reserved_like_config_name_passes(self, config_name: str) -> None: - """設定ファイル名が予約名でも実験 ID 全体は予約名にならない(日時で始まる).""" - from tongue_seg_model.training.run_artifacts import make_run_id - - run_id = make_run_id(datetime(2026, 11, 19, 12, 0, 0), config_name, "abc1234-dirty") - assert validate_run_id(run_id) == run_id - - -class TestWindowsUnsafePullNames: - @pytest.mark.parametrize( - "name", - [ - "figures/CON.png", - "figures/nul.png", - "figures/COM1.png", - "figures/LPT9.png", - "figures/Aux.x.png", - "figures/nul .png", - "figures/PRN.png", - "figures/com¹.png", - "figures/LPT³.png", - "figures/a.png.", - "figures/a.png ", - "figures./a.png", - "figures /a.png", - ], - ) - @pytest.mark.parametrize("with_checkpoints", [False, True]) - def test_reserved_or_trailing_dot_names_are_not_pulled( - self, name: str, with_checkpoints: bool - ) -> None: - assert not is_pull_allowed(name, with_checkpoints=with_checkpoints) - - @pytest.mark.parametrize( - "name", - [ - "figures/CONSOLE.png", - "figures/COM10.png", - "figures/nul_.png", - "figures/LPT10.png", - "figures/con_matrix.png", - "figures/a.b.png", - ], - ) - def test_names_similar_to_reserved_are_pulled(self, name: str) -> None: - assert is_pull_allowed(name, with_checkpoints=False) - - @pytest.mark.parametrize("base", RESERVED_BASES) - def test_every_reserved_base_is_rejected(self, base: str) -> None: - assert not is_pull_allowed(f"figures/{base}.png", with_checkpoints=True) - - @pytest.mark.parametrize("base", NOT_RESERVED_BASES) - def test_every_not_reserved_base_is_accepted(self, base: str) -> None: - assert is_pull_allowed(f"figures/{base}.png", with_checkpoints=False) - - def test_plan_pull_skips_reserved_names(self) -> None: - listing = [ - ("f", f"{RUN_ID}/config.yaml"), - ("f", f"{RUN_ID}/figures/CON.png"), - ("f", f"{RUN_ID}/figures/nul .png"), - ("f", f"{RUN_ID}/figures/CONSOLE.png"), - ] - plan = plan_pull(listing, RUN_ID, with_checkpoints=False) - assert plan.files == (f"{RUN_ID}/config.yaml", f"{RUN_ID}/figures/CONSOLE.png") - assert plan.skipped == 2 - - -class TestWindowsUnsafeTarMembers: - @pytest.mark.parametrize( - "name", - [ - f"{RUN_ID}/figures/CON.png", - f"{RUN_ID}/figures/nul.png", - f"{RUN_ID}/figures/COM1.png", - f"{RUN_ID}/figures/LPT9.png", - f"{RUN_ID}/figures/Aux.x.png", - f"{RUN_ID}/figures/nul .png", - f"{RUN_ID}/figures/a.png.", - f"{RUN_ID}/config.yaml.", - f"{RUN_ID}/figures./a.png", - f"{RUN_ID}./config.yaml", - f"{RUN_ID}/figures/com².png", - ], - ) - @pytest.mark.parametrize("with_checkpoints", [False, True]) - def test_whole_archive_is_rejected(self, name: str, with_checkpoints: bool) -> None: - members = [_regular(f"{RUN_ID}/config.yaml"), _regular(name), _regular(f"{RUN_ID}/log.txt")] - with pytest.raises(ValueError): - check_pull_members(members, RUN_ID, with_checkpoints=with_checkpoints) - - def test_names_similar_to_reserved_are_accepted(self) -> None: - members = [ - _regular(f"{RUN_ID}/figures/CONSOLE.png"), - _regular(f"{RUN_ID}/figures/COM10.png"), - _regular(f"{RUN_ID}/figures/nul_.png"), - ] - assert check_pull_members(members, RUN_ID, with_checkpoints=False) == 3 - - def test_error_message_does_not_contain_reserved_member_names(self) -> None: - members = [_regular(f"{RUN_ID}/figures/P0001_yamada.png."), _regular(f"{RUN_ID}/nul.txt")] - with pytest.raises(ValueError) as excinfo: - check_pull_members(members, RUN_ID, with_checkpoints=False) - assert "yamada" not in str(excinfo.value) - assert "nul" not in str(excinfo.value)