"""GPU 一覧の表示のテスト.
各 GPU の状態・使い方の型と使用率の平均/最大・計算プロセスごとの所有ユーザー(自分は「自分」)・
経過時間・SM 使用率の最大が表示されること.
設定にアドレス・ユーザー名を書くキーは無いため,見出しはサーバ名(ssh の Host 名)だけを出し,
「自分」は probe の `@@labremote-user` で決まる.
"""
from __future__ import annotations
from collections.abc import Sequence
import pytest
from probe_helpers import PMON_HEADER, gpu_line, probe_text, sample_lines
from labremote.cleanup import JobLogEntry, LsSummary, RemoteListing, RunDirEntry, ServerLeftovers
from labremote.commands import SSH_FAILURE_RC
from labremote.config import GpuFreeThreshold, ServerConfig
from labremote.gpu import GpuSelection, GpuState, ServerProbe, parse_probe_output, select_gpu
from labremote.report import (
describe_skipped_links,
describe_ssh_failure,
describe_target,
format_forced_warning,
format_ls_incomplete_warning,
format_ls_report,
format_ls_server,
format_ls_unchecked_warning,
format_no_cpu_server_error,
format_no_gpu_error,
format_not_ready_alternative,
format_project_line,
format_pull_skipped,
format_server_report,
format_shared_warning,
format_size,
format_ssh_hint,
last_stderr_line,
)
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/DemoProject",
data_ready=True,
)
def _probe(remote_user: str | None = "carol", 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 carol 99720", "200 dave 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 "dave" 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 "dave" in warning
def test_report_without_own_user_does_not_mark_self() -> None:
# 自分の名前が分からない(@@labremote-user が無い)ときは誰も「自分」にしない
report = format_server_report([_probe(None)], show_jobs=False)
assert "自分" not in report
assert "carol" 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 "carol" not in warning
def test_report_header_shows_server_name_only() -> None:
# 接続先はサーバ名と同じ.[user@]host の形は出さない
report = format_server_report([_probe()], show_jobs=False)
first = report.splitlines()[0]
assert first.startswith("[Newton] priority=1 ")
assert "@" not in first
assert "None" not in report
# ---------------------------------------------------------------------------
# 表示の言葉(SPEC_03「表示の言葉」「表示する項目」)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("name", ["DemoProject", "demo-project_2", "日本語の名前"])
def test_project_line_shows_name_as_is_in_one_line(name: str) -> None:
"""SPEC_03「表示の言葉」: gpus・status の先頭に project.name を 1 行で出す."""
line = format_project_line(name)
assert name in line
assert "\n" not in line
assert "\r" not in line
def _probe_with_others(others: list[str], jobs: Sequence[str] = ()) -> ServerProbe:
text = probe_text(
[gpu_line(0, UUID0, used=5, util=0)],
apps=[],
jobs=list(jobs),
others=others,
remote_user="carol",
)
return ServerProbe(SERVER, parse_probe_output(text, THRESHOLD))
@pytest.mark.parametrize("others", [["hidden-session-a"], ["hidden-a", "hidden-b", "hidden-c"]])
def test_status_counts_other_sessions_without_names(others: list[str]) -> None:
"""SPEC_03「表示する項目」: ジョブでない tmux セッションは件数だけを出し,名前を出さない."""
report = format_server_report([_probe_with_others(others, jobs=["train1"])], show_jobs=True)
count_lines = [
line for line in report.splitlines() if "このプロジェクトのジョブではない" in line
]
assert len(count_lines) == 1
assert str(len(others)) in count_lines[0]
assert "件" in count_lines[0]
for name in others:
assert name not in report
# 実行中のジョブの名前は出す
assert "train1" in report
# ツールを指す古い書き方は使わない(SPEC_03「表示の言葉」)
assert "このツール" not in report
def test_status_without_other_sessions_has_no_count_line() -> None:
"""SPEC_03「表示する項目」: ジョブでないセッションが無ければ件数の行を出さない."""
report = format_server_report([_probe_with_others([], jobs=["train1"])], show_jobs=True)
assert "このプロジェクトのジョブではない" not in report
assert "tmux セッション" not in report
def test_gpus_does_not_show_session_count_line() -> None:
"""SPEC_03「表示する項目」: 件数の行は status のもの(gpus はジョブを出さない)."""
report = format_server_report([_probe_with_others(["hidden-a"])], show_jobs=False)
assert "hidden-a" not in report
assert "このプロジェクトのジョブではない" not in report
# ---------------------------------------------------------------------------
# CLI の表示・メッセージの組み立て
# ---------------------------------------------------------------------------
# どのプロジェクトのメッセージにも出さない言葉(SPEC_03「表示の言葉」)
_PROJECT_WORDS = ["バンドル", "学習データ", "このツール"]
class TestFormatSize:
@pytest.mark.parametrize(
("num_bytes", "unit"),
[
(0, " B"),
(1, " B"),
(1023, " B"),
(1024, " KB"),
(1024 * 1024 - 1024, " KB"),
(1024 * 1024, " MB"),
(1024**3 - 1024 * 1024, " MB"),
(1024**3, " GB"),
(5 * 1024**4, " GB"),
],
)
def test_unit_changes_at_1024(self, num_bytes: int, unit: str) -> None:
assert format_size(num_bytes).endswith(unit)
if unit == " B":
assert not format_size(num_bytes).endswith("KB")
def test_values(self) -> None:
assert format_size(1023).startswith("1023")
assert format_size(1024).startswith("1.0")
assert format_size(1536).startswith("1.5")
assert format_size(1024 * 1024).startswith("1.0")
assert format_size(1024**3).startswith("1.0")
# GB より上の単位は無い
assert format_size(2048 * 1024**3).startswith("2048.0")
class TestLastStderrLine:
@pytest.mark.parametrize("stderr", [b"", b"\n", b"\n\n \n\t\n", b" "], ids=repr)
def test_empty_or_blank_gives_empty(self, stderr: bytes) -> None:
assert last_stderr_line(stderr) == ""
def test_last_non_empty_line_is_returned_stripped(self) -> None:
stderr = b"first line\r\n second line \r\n\r\n \n"
assert last_stderr_line(stderr) == "second line"
def test_long_line_is_cut(self) -> None:
line = last_stderr_line(b"x" * 1000)
assert 0 < len(line) < 1000
assert set(line) == {"x"}
def test_short_line_is_not_cut(self) -> None:
assert last_stderr_line(b"y" * 100) == "y" * 100
@pytest.mark.parametrize(
"stderr", [b"\xff\xfe\x80 bad", b"ok\n\xe3\x81", b"\x00\xff"], ids=repr
)
def test_invalid_utf8_does_not_raise(self, stderr: bytes) -> None:
assert isinstance(last_stderr_line(stderr), str)
def test_utf8_is_decoded(self) -> None:
assert last_stderr_line("接続できない\n".encode()) == "接続できない"
class TestDescribeSshFailure:
def test_timeout(self) -> None:
text = describe_ssh_failure(SSH_FAILURE_RC, b"Connection refused", timed_out=True)
assert "タイムアウト" in text
assert "Connection refused" not in text
def test_ssh_failure_adds_last_stderr_line(self) -> None:
text = describe_ssh_failure(SSH_FAILURE_RC, b"debug\nConnection refused\n", timed_out=False)
assert str(SSH_FAILURE_RC) in text
assert "Connection refused" in text
assert "debug" not in text
def test_ssh_failure_without_stderr(self) -> None:
text = describe_ssh_failure(SSH_FAILURE_RC, b"", timed_out=False)
assert str(SSH_FAILURE_RC) in text
@pytest.mark.parametrize("rc", [1, 2, 90, 92, 127])
def test_other_rc_does_not_add_stderr(self, rc: int) -> None:
"""リモートのコマンドの標準エラーはファイル名を含みうるため出さない."""
text = describe_ssh_failure(rc, b"secret_file_name.png: error", timed_out=False)
assert str(rc) in text
assert "secret_file_name" not in text
class TestFormatSshHint:
_STDERR = b"Host key verification failed.\r\n"
def test_host_key_failure_gives_hint_with_host(self) -> None:
hint = format_ssh_hint(SSH_FAILURE_RC, self._STDERR, host="Newton", jump_host=None)
assert hint
assert "ssh Newton" in hint
assert "-J" not in hint
def test_hint_with_jump_host(self) -> None:
hint = format_ssh_hint(SSH_FAILURE_RC, self._STDERR, host="Newton", jump_host="labpc")
assert "-J labpc" in hint
assert "Newton" in hint
assert hint.index("labpc") < hint.index("Newton")
@pytest.mark.parametrize(
("rc", "stderr"),
[
(SSH_FAILURE_RC, b"Connection refused"),
(SSH_FAILURE_RC, b""),
(1, b"Host key verification failed."),
(0, b"Host key verification failed."),
],
ids=repr,
)
def test_no_hint_otherwise(self, rc: int, stderr: bytes) -> None:
assert format_ssh_hint(rc, stderr, host="Newton", jump_host="labpc") == ""
class TestDescribeSkippedLinks:
def test_zero_links(self) -> None:
text = describe_skipped_links([])
assert "0 件" in text
assert "(" not in text
def test_links_are_counted_and_named_in_order(self) -> None:
text = describe_skipped_links(["a/link1", "b/link2", "link3"])
assert "3 件" in text
assert text.index("a/link1") < text.index("b/link2") < text.index("link3")
assert "\n" not in text
class TestDescribeTarget:
def test_gpu_with_state(self) -> None:
text = describe_target("Newton", 1, "未使用")
assert "Newton" in text
assert "GPU 1" in text
assert "未使用" in text
def test_gpu_without_state(self) -> None:
text = describe_target("Newton", 0)
assert "GPU 0" in text
assert "(" not in text
def test_cpu_only(self) -> None:
text = describe_target("Newton", None)
assert "Newton" in text
assert "CPU" in text
assert "GPU 0" not in text
def _selection(state: GpuState, *, forced: bool = False, gpu_index: int = 2) -> GpuSelection:
return GpuSelection(server=SERVER, gpu_index=gpu_index, state=state, forced=forced)
class TestRunMessages:
@pytest.mark.parametrize("server_name", [None, "Newton"])
def test_no_gpu_error_mentions_no_data(self, server_name: str | None) -> None:
text = format_no_gpu_error(server_name, include_not_ready=True)
assert "--no-data" in text
assert "data_ready" not in text
if server_name:
assert server_name in text
@pytest.mark.parametrize("server_name", [None, "Newton"])
def test_no_gpu_error_mentions_data_ready(self, server_name: str | None) -> None:
text = format_no_gpu_error(server_name, include_not_ready=False)
assert "data_ready" in text
assert "--no-data" not in text
def test_no_gpu_error_wording_differs_by_no_data(self) -> None:
assert format_no_gpu_error(None, include_not_ready=True) != format_no_gpu_error(
None, include_not_ready=False
)
def test_no_cpu_server_error(self) -> None:
with_data = format_no_cpu_server_error(include_not_ready=False)
without = format_no_cpu_server_error(include_not_ready=True)
assert "data_ready" in with_data
assert "data_ready" not in without
assert with_data != without
@pytest.mark.parametrize("state", [GpuState.BUSY, GpuState.UNKNOWN])
def test_forced_warning(self, state: GpuState) -> None:
text = format_forced_warning(_selection(state, forced=True))
assert "Newton" in text
assert "GPU 2" in text
assert str(state) in text
assert "--force" in text
def test_not_ready_alternative(self) -> None:
text = format_not_ready_alternative(_selection(GpuState.UNUSED, gpu_index=3))
assert "Newton" in text
assert "GPU 3" in text
assert "data_ready: false" in text
assert "--no-data" in text
assert "\n" not in text
def test_messages_do_not_use_project_words(self) -> None:
texts = [
format_no_gpu_error(None, include_not_ready=False),
format_no_gpu_error(None, include_not_ready=True),
format_no_cpu_server_error(include_not_ready=False),
format_no_cpu_server_error(include_not_ready=True),
format_forced_warning(_selection(GpuState.BUSY, forced=True)),
format_not_ready_alternative(_selection(GpuState.UNUSED)),
]
for text in texts:
for word in _PROJECT_WORDS:
assert word not in text
class TestFormatPullSkipped:
def test_without_checkpoints_has_no_note(self) -> None:
text = format_pull_skipped(5, 0, "checkpoints")
assert "5 件" in text
assert "--with-checkpoints" not in text
assert "checkpoints" not in text
def test_with_checkpoints_has_note(self) -> None:
text = format_pull_skipped(5, 2, "weights")
assert "5 件" in text
assert "2 件" in text
assert "weights/" in text
assert "--with-checkpoints" in text
assert "\n" not in text
def test_zero_skipped(self) -> None:
assert "0 件" in format_pull_skipped(0, 0, "checkpoints")
# ---------------------------------------------------------------------------
# ls の表示(SPEC_03「ls」)
# ---------------------------------------------------------------------------
LS_RUN_A = "20261119-120000_demo_abc1234"
LS_RUN_B = "20261120-090000_demo_def5678"
def _listing(**kwargs: object) -> RemoteListing:
base: dict[str, object] = {
"remote_dir_exists": True,
"total_bytes": 5 * 1024**3,
"venv_bytes": 3 * 1024**3,
"results_dir_exists": True,
"logs_dir_exists": True,
"run_dirs": (
RunDirEntry(LS_RUN_A, 37, 120 * 1024**2, True),
RunDirEntry(LS_RUN_B, 4, 2048, True),
),
"job_logs": (JobLogEntry("train1", 2048, True), JobLogEntry("eval2", 10, False)),
"other_in_results": 2,
"other_in_logs": 1,
}
base.update(kwargs)
return RemoteListing(**base) # type: ignore[arg-type]
def _line_with(text: str, needle: str) -> str:
(line,) = [line for line in text.splitlines() if needle in line]
return line
class TestFormatLsServer:
def test_shows_run_ids_counts_sizes_and_local(self) -> None:
"""SPEC_03「ls」: 実験 ID・件数・大きさ・手元にあるか."""
text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset({LS_RUN_A}))
assert "Newton" in text
line_a = _line_with(text, LS_RUN_A)
assert "37" in line_a
assert format_size(120 * 1024**2) in line_a
assert "手元: あり" in line_a
line_b = _line_with(text, LS_RUN_B)
assert "4" in line_b
assert format_size(2048) in line_b
assert "手元: なし" in line_b
def test_shows_job_logs_running_and_stopped(self) -> None:
"""SPEC_03「ls」: ジョブのログの状態は「実行中」「停止中」."""
text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
line_t = _line_with(text, "train1")
assert "実行中" in line_t and "停止中" not in line_t
assert format_size(2048) in line_t
line_e = _line_with(text, "eval2")
assert "停止中" in line_e and "実行中" not in line_e
def test_shows_remote_dir_and_venv_sizes_and_others(self) -> None:
"""SPEC_03「ls」: remote_dir 全体と .venv の大きさ,その他の件数."""
text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
assert format_size(5 * 1024**3) in text
assert format_size(3 * 1024**3) in text
assert ".venv" in text
others = _line_with(text, "その他")
assert "2" in others and "1" in others
def test_states_are_distinguishable(self) -> None:
"""SPEC_03「ls」: remote_dir が無い・0 件・接続不可・確認できない,を区別できる."""
texts = {
"no_remote_dir": format_ls_server(
ServerLeftovers("Newton", RemoteListing(remote_dir_exists=False)), frozenset()
),
"zero": format_ls_server(
ServerLeftovers(
"Newton",
_listing(run_dirs=(), job_logs=(), other_in_results=0, other_in_logs=0),
),
frozenset(),
),
"unreachable": format_ls_server(
ServerLeftovers("Newton", None, "応答がタイムアウトした", unreachable=True),
frozenset(),
),
"unreadable": format_ls_server(
ServerLeftovers("Newton", None, "出力を解釈できない"), frozenset()
),
}
assert len(set(texts.values())) == 4
assert "接続不可" in texts["unreachable"]
assert "応答がタイムアウトした" in texts["unreachable"]
assert "確認できない" in texts["unreadable"]
assert "接続不可" not in texts["unreadable"]
assert "コードの置き場が無い" in texts["no_remote_dir"]
assert "0 件" in texts["zero"]
# 接続不可・確認できないを「何も残っていない」と表示しない
for key in ("unreachable", "unreadable"):
assert "何も残っていない" not in texts[key]
assert "0 件" not in texts[key]
for text in texts.values():
assert "Newton" in text
def test_missing_results_and_logs_dirs_are_zero(self) -> None:
listing = RemoteListing(remote_dir_exists=True, total_bytes=1024)
text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
assert "実験フォルダ: 0 件" in text
assert "ジョブのログ: 0 件" in text
def test_incomplete_run_dir_has_note(self) -> None:
"""SPEC_03「ls」: 数え切れなかったときは,実際より少ない可能性があることを添える."""
listing = _listing(
run_dirs=(
RunDirEntry(LS_RUN_A, 3, 4096, False),
RunDirEntry(LS_RUN_B, 3, 4096, True),
)
)
text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
assert "少ない" in _line_with(text, LS_RUN_A)
assert "少ない" not in _line_with(text, LS_RUN_B)
def test_incomplete_sizes_have_note(self) -> None:
listing = _listing(sizes_complete=False)
text = format_ls_server(ServerLeftovers("Newton", listing), frozenset())
assert "少ない" in _line_with(text, ".venv")
def test_complete_listing_has_no_note(self) -> None:
text = format_ls_server(ServerLeftovers("Newton", _listing()), frozenset())
assert "少ない" not in text
def test_report_joins_all_servers_in_order(self) -> None:
results = [
ServerLeftovers("Newton", _listing()),
ServerLeftovers("Archimedes", None, "x", unreachable=True),
]
text = format_ls_report(results, frozenset())
assert text.endswith("\n")
assert text.index("[Newton]") < text.index("[Archimedes]")
def _summary(**kwargs: object) -> LsSummary:
base: dict[str, object] = {
"unreachable": (),
"unreadable": (),
"incomplete": (),
"all_unreachable": False,
}
base.update(kwargs)
return LsSummary(**base) # type: ignore[arg-type]
class TestLsWarnings:
def test_no_warning_when_all_ok(self) -> None:
assert format_ls_unchecked_warning(_summary()) is None
assert format_ls_incomplete_warning(_summary()) is None
def test_unchecked_warning_names_all_servers(self) -> None:
"""SPEC_03「ls」: 確かめられなかったサーバを最後に警告する(全部の名前を含む)."""
text = format_ls_unchecked_warning(
_summary(unreachable=("Newton", "Archimedes"), unreadable=("Curie",))
)
assert text is not None
for name in ("Newton", "Archimedes", "Curie"):
assert name in text
assert "\n" not in text
@pytest.mark.parametrize("field", ["unreachable", "unreadable"])
def test_unchecked_warning_for_each_kind(self, field: str) -> None:
text = format_ls_unchecked_warning(_summary(**{field: ("Newton",)}))
assert text is not None and "Newton" in text
def test_incomplete_does_not_make_unchecked_warning(self) -> None:
assert format_ls_unchecked_warning(_summary(incomplete=("Newton",))) is None
def test_incomplete_warning_names_all_servers(self) -> None:
text = format_ls_incomplete_warning(_summary(incomplete=("Newton", "Archimedes")))
assert text is not None
assert "Newton" in text and "Archimedes" in text
assert "\n" not in text
def test_unreachable_does_not_make_incomplete_warning(self) -> None:
assert format_ls_incomplete_warning(_summary(unreachable=("Newton",))) is None