Newer
Older
LabRemote / tests / test_cleanup.py
"""`ls` のサーバの出力の解析のテスト(SPEC_03「ls」).

- 正常な出力から,実験フォルダ・ジョブのログ・その他の件数・大きさ・実行中かが読めること
- 解釈できない出力(空・目印が無い・途中で切れている・順が違う・数が読めない・知らない状態)を
  「何も残っていない」とせず `ValueError` にすること.メッセージにサーバから来た名前を入れないこと
- 実験 ID・ジョブ名の規則に合わない名前を表示に出さず「その他」に数えること
- `du`・`find` が失敗した記録を「数え切れなかった」とすること

サーバの出力はテストの中で組み立てる(`tests/ls_helpers.py`).実サーバには接続しない.

後半は `clean RUN_ID` の判定(SPEC_03「clean」の手順 1〜3.testing ルールの必須対象 2「削除の
判定」): `classify_clean` が「説明がつかないもの」を 1 件でも見つけたら消せないとすること,
手元と内容が違う・手元に無いファイルを一致としないこと,`parse_clean_output` が解釈できない
出力を拒否すること.出力は `tests/clean_helpers.py` で組み立てる.
"""

from __future__ import annotations

from dataclasses import replace

import pytest
from clean_helpers import (
    CLEAN_RESULTS,
    CLEAN_RESULTS_DICT,
    CLEAN_RUN_ID,
    clean_output,
    clean_records,
    clean_state_output,
    file_record,
    nohash_record,
    other_record,
    raw_file_record,
    sha,
)
from ls_helpers import (
    dir_record,
    encode_records,
    job_record,
    log_record,
    ls_missing_remote_dir,
    ls_output,
    ls_records,
)

from labremote.cleanup import (
    CategoryTotal,
    ClassifiedFile,
    CleanCategory,
    CleanJudgement,
    JobLogEntry,
    LocalFile,
    LsSummary,
    RemoteFile,
    RemoteListing,
    RemoteRunListing,
    RunDirEntry,
    ServerLeftovers,
    build_clean_expected_input,
    classify_clean,
    is_safe_clean_path,
    listed_run_ids,
    local_paths_to_check,
    parse_clean_output,
    parse_ls_output,
    summarize_ls,
)
from labremote.commands import (
    CLEAN_AFTER_PREFIX,
    CLEAN_BEGIN_MARKER,
    CLEAN_END_MARKER,
    CLEAN_EXPECT_END_RECORD,
    CLEAN_FILE_PREFIX,
    CLEAN_FIND_RC_PREFIX,
    CLEAN_NOHASH_PREFIX,
    CLEAN_OTHER_PREFIX,
    CLEAN_RUN_PREFIX,
    CLEAN_STATE_LINK,
    CLEAN_STATE_MISSING,
    CLEAN_STATE_NOT_DIR,
    CLEAN_STATE_PRESENT,
    CLEAN_STATE_UNREADABLE,
    LS_BEGIN_MARKER,
    LS_END_MARKER,
    LS_LOGS_END_MARKER,
    LS_LOGS_PREFIX,
    LS_REMOTE_DIR_PREFIX,
    LS_RESULTS_END_MARKER,
    LS_RESULTS_PREFIX,
    LS_SIZE_PREFIX,
    LS_TMUX_RC_PREFIX,
    LS_VENV_PREFIX,
)
from labremote.config import ResultsConfig

RUN_A = "20261119-120000_demo_abc1234"
RUN_B = "20261120-090000_demo_def5678"
KIB = 1024

# 正常な出力(実験フォルダ 2 件・その他 1 件,ログ 2 件・その他 1 件,ジョブ 1 件と,
# ログの無いセッション 1 件)
NORMAL_RECORDS = ls_records(
    total_kib=1000,
    venv_kib=600,
    results=[dir_record(RUN_A, 3, 8), "other", dir_record(RUN_B, 0, 4)],
    logs=[log_record("train1.log", 123), log_record("old.log", 50), "other"],
    jobs=[job_record("train1"), job_record("manual")],
)
NORMAL = encode_records(NORMAL_RECORDS)


def _replace(records: list, index: int, new: object) -> list:
    out = list(records)
    out[index] = new
    return out


def _index(records: list, prefix: str) -> int:
    return next(i for i, r in enumerate(records) if isinstance(r, str) and r.startswith(prefix))


# ---------------------------------------------------------------------------
# 正常な出力
# ---------------------------------------------------------------------------


class TestParseNormal:
    def test_reads_run_dirs_logs_others_and_sizes(self) -> None:
        """SPEC_03「ls」: 実験フォルダ・ログ・その他・大きさ・実行中かを読む."""
        listing = parse_ls_output(NORMAL)
        assert listing.remote_dir_exists
        assert listing.total_bytes == 1000 * KIB
        assert listing.venv_bytes == 600 * KIB
        assert listing.sizes_complete
        assert listing.results_dir_exists and listing.logs_dir_exists
        assert listing.run_dirs == (
            RunDirEntry(RUN_A, 3, 8 * KIB, True),
            RunDirEntry(RUN_B, 0, 4 * KIB, True),
        )
        assert listing.other_in_results == 1
        assert listing.job_logs == (
            JobLogEntry("train1", 123, True),
            JobLogEntry("old", 50, False),
        )
        assert listing.other_in_logs == 1
        assert listing.complete

    def test_session_without_log_is_not_shown(self) -> None:
        """SPEC_03「ls」: ログの無いセッション(manual)は,表示に出ない."""
        listing = parse_ls_output(NORMAL)
        assert "manual" not in {log.name for log in listing.job_logs}
        assert "manual" not in {d.run_id for d in listing.run_dirs}

    def test_only_logs_with_job_are_running(self) -> None:
        """SPEC_03「ls」: 同じ名前の tmux のセッションがあるログだけが実行中."""
        data = ls_output(
            logs=[log_record("a1.log"), log_record("b2.log"), log_record("c3.log")],
            jobs=[job_record("b2"), job_record("zz")],
        )
        running = {log.name: log.running for log in parse_ls_output(data).job_logs}
        assert running == {"a1": False, "b2": True, "c3": False}

    def test_missing_remote_dir_means_nothing_left(self) -> None:
        """SPEC_03「ls」: remote_dir が無いときは「何も残っていない」."""
        listing = parse_ls_output(ls_missing_remote_dir())
        assert listing == RemoteListing(remote_dir_exists=False)
        assert listing.run_dirs == () and listing.job_logs == ()

    def test_missing_results_and_logs_dirs_are_zero(self) -> None:
        """SPEC_03「ls」: 結果の置き場・ログの置き場が無いときは 0 件."""
        listing = parse_ls_output(ls_output(results=None, logs=None, jobs=[job_record("x1")]))
        assert listing.remote_dir_exists
        assert not listing.results_dir_exists
        assert not listing.logs_dir_exists
        assert listing.run_dirs == () and listing.job_logs == ()
        assert listing.other_in_results == 0 and listing.other_in_logs == 0

    def test_empty_results_and_logs(self) -> None:
        listing = parse_ls_output(ls_output(results=[], logs=[]))
        assert listing.results_dir_exists and listing.logs_dir_exists
        assert listing.run_dirs == () and listing.job_logs == ()

    @pytest.mark.parametrize("tmux_rc", [1, 127])
    def test_tmux_failure_makes_all_logs_stopped(self, tmux_rc: int) -> None:
        """tmux が無い・動いていないときは,全部が停止中(エラーにしない)."""
        data = ls_output(logs=[log_record("train1.log")], tmux_rc=tmux_rc)
        listing = parse_ls_output(data)
        assert listing.job_logs == (JobLogEntry("train1", 10, False),)

    def test_zero_sized_run_dir_and_log(self) -> None:
        data = ls_output(results=[dir_record(RUN_A, 0, 0)], logs=[log_record("t1.log", 0)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == (RunDirEntry(RUN_A, 0, 0, True),)
        assert listing.job_logs == (JobLogEntry("t1", 0, False),)

    def test_names_with_spaces_inside_record_do_not_shift_numbers(self) -> None:
        """名前は記録の最後の項目なので,名前の空白で数の位置がずれない(その他になる)."""
        data = ls_output(results=[dir_record("a 1 2 3 4", 7, 9)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1


# ---------------------------------------------------------------------------
# 数え切れなかった記録
# ---------------------------------------------------------------------------


class TestIncomplete:
    @pytest.mark.parametrize(("find_rc", "du_rc"), [(1, 0), (0, 1), (1, 1), (2, 0)])
    def test_failed_find_or_du_marks_run_dir_incomplete(self, find_rc: int, du_rc: int) -> None:
        """SPEC_03「ls」: find・du が失敗した実験フォルダは,数え切れなかった."""
        data = ls_output(results=[dir_record(RUN_A, 2, 8, find_rc=find_rc, du_rc=du_rc)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == (RunDirEntry(RUN_A, 2, 8 * KIB, False),)
        assert not listing.complete

    @pytest.mark.parametrize(("total_rc", "venv_rc"), [(1, 0), (0, 1)])
    def test_failed_du_of_remote_dir_or_venv_is_incomplete(
        self, total_rc: int, venv_rc: int
    ) -> None:
        listing = parse_ls_output(ls_output(total_rc=total_rc, venv_rc=venv_rc))
        assert not listing.sizes_complete
        assert not listing.complete

    def test_incomplete_name_that_is_not_run_id_is_other(self) -> None:
        data = ls_output(results=[dir_record("bad name", 2, 8, find_rc=1)])
        listing = parse_ls_output(data)
        assert listing.run_dirs == ()
        assert listing.other_in_results == 1


# ---------------------------------------------------------------------------
# 解釈できない出力は「何も残っていない」にしない
# ---------------------------------------------------------------------------

_SECRET = "secretname_q7"

BROKEN_OUTPUTS: dict[str, bytes] = {
    "empty": b"",
    "only_nul": b"\0",
    "garbage": b"Welcome to the server\nLast login: yesterday\n",
    "no_begin": encode_records(NORMAL_RECORDS[1:]),
    "no_end": encode_records(NORMAL_RECORDS[:-1]),
    "missing_remote_dir_without_end": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "missing"]
    ),
    "missing_remote_dir_then_records": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "missing", f"{LS_SIZE_PREFIX}0 1", LS_END_MARKER]
    ),
    "no_results_end": encode_records([r for r in NORMAL_RECORDS if r != LS_RESULTS_END_MARKER]),
    "no_logs_end": encode_records([r for r in NORMAL_RECORDS if r != LS_LOGS_END_MARKER]),
    "no_tmux_rc": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_TMUX_RC_PREFIX))]
    ),
    "no_size": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_SIZE_PREFIX))]
    ),
    "no_venv": encode_records(
        [r for r in NORMAL_RECORDS if not (isinstance(r, str) and r.startswith(LS_VENV_PREFIX))]
    ),
    "size_and_venv_swapped": encode_records(
        [
            NORMAL_RECORDS[0],
            NORMAL_RECORDS[1],
            NORMAL_RECORDS[3],
            NORMAL_RECORDS[2],
            *NORMAL_RECORDS[4:],
        ]
    ),
    "logs_before_results": encode_records(
        [
            *ls_records()[:4],
            LS_LOGS_PREFIX + "missing",
            LS_RESULTS_PREFIX + "missing",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    "end_before_tmux": encode_records(
        [*ls_records()[:-2], LS_END_MARKER, f"{LS_TMUX_RC_PREFIX}0", LS_END_MARKER]
    ),
    "dir_record_in_logs": ls_output(logs=[dir_record(RUN_A)]),
    "log_record_in_results": ls_output(results=[log_record("t1.log")]),
    "other_in_jobs": ls_output(jobs=["other"]),
    "dir_record_in_jobs": ls_output(jobs=[dir_record(RUN_A)]),
    "unknown_record_in_results": ls_output(results=["file 1 x"]),
    "unknown_record_in_logs": ls_output(logs=["dir 1 x"]),
    "unknown_record_in_jobs": ls_output(jobs=["session x"]),
    # 数が数字でない・負・空・符号付き・小数・全角
    "dir_count_word": ls_output(results=[b"dir 0 0 many 4 " + RUN_A.encode()]),
    "dir_count_negative": ls_output(results=[b"dir 0 0 -1 4 " + RUN_A.encode()]),
    "dir_count_empty": ls_output(results=[b"dir 0 0  4 " + RUN_A.encode()]),
    "dir_count_plus": ls_output(results=[b"dir 0 0 +1 4 " + RUN_A.encode()]),
    "dir_kib_decimal": ls_output(results=[b"dir 0 0 1 1.5 " + RUN_A.encode()]),
    "dir_kib_fullwidth": ls_output(results=["dir 0 0 1 4 " + RUN_A]),
    "dir_find_rc_word": ls_output(results=[b"dir x 0 1 4 " + RUN_A.encode()]),
    "dir_du_rc_negative": ls_output(results=[b"dir 0 -1 1 4 " + RUN_A.encode()]),
    "dir_too_few_fields": ls_output(results=[b"dir 0 0 1 4"]),
    "dir_too_few_fields2": ls_output(results=[b"dir 0 0 1"]),
    "dir_no_fields": ls_output(results=[b"dir "]),
    "size_negative": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 -5")),
    "size_empty": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 ")),
    "size_one_field": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0")),
    "size_word": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 big")),
    "size_exponent": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX}0 1e3")),
    "size_rc_empty": encode_records(_replace(NORMAL_RECORDS, 2, f"{LS_SIZE_PREFIX} 5")),
    "venv_word": encode_records(_replace(NORMAL_RECORDS, 3, f"{LS_VENV_PREFIX}0 x")),
    "log_size_word": ls_output(logs=[b"log big train1.log"]),
    "log_size_negative": ls_output(logs=[b"log -3 train1.log"]),
    "log_size_empty": ls_output(logs=[b"log  train1.log"]),
    "log_no_name": ls_output(logs=[b"log 12"]),
    "tmux_rc_word": ls_output(tmux_rc=0).replace(
        f"{LS_TMUX_RC_PREFIX}0".encode(), f"{LS_TMUX_RC_PREFIX}x".encode()
    ),
    "tmux_rc_empty": ls_output(tmux_rc=0).replace(
        f"{LS_TMUX_RC_PREFIX}0".encode(), LS_TMUX_RC_PREFIX.encode()
    ),
    # 知らない状態
    "remote_state_unknown": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "exists")
    ),
    "remote_state_upper": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "PRESENT")
    ),
    "remote_state_trailing_space": encode_records(
        _replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX + "present ")
    ),
    "remote_state_empty": encode_records(_replace(NORMAL_RECORDS, 1, LS_REMOTE_DIR_PREFIX)),
    "results_state_unknown": encode_records(
        _replace(NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_RESULTS_PREFIX), "x")
    ),
    "results_state_bogus": encode_records(
        _replace(
            NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_RESULTS_PREFIX), LS_RESULTS_PREFIX + "ok"
        )
    ),
    "logs_state_bogus": encode_records(
        _replace(NORMAL_RECORDS, _index(NORMAL_RECORDS, LS_LOGS_PREFIX), LS_LOGS_PREFIX + "ok")
    ),
    # 置き場が在るのに入れない(SPEC_03「ls」: 0 件とせず確認できない)
    "remote_unreadable": encode_records(
        [LS_BEGIN_MARKER, LS_REMOTE_DIR_PREFIX + "unreadable", LS_END_MARKER]
    ),
    "results_unreadable": encode_records(
        [
            *ls_records()[:4],
            LS_RESULTS_PREFIX + "unreadable",
            LS_LOGS_PREFIX + "missing",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    "logs_unreadable": encode_records(
        [
            *ls_records()[:4],
            LS_RESULTS_PREFIX + "missing",
            LS_LOGS_PREFIX + "unreadable",
            f"{LS_TMUX_RC_PREFIX}0",
            LS_END_MARKER,
        ]
    ),
    # 記録の区切りが NUL でない(改行区切りの出力)
    "newline_separated": b"\n".join(
        r if isinstance(r, bytes) else r.encode() for r in NORMAL_RECORDS
    ),
}


class TestParseBroken:
    @pytest.mark.parametrize("case", sorted(BROKEN_OUTPUTS))
    def test_unparsable_output_is_value_error(self, case: str) -> None:
        """SPEC_03「ls」: 解釈できない出力は「何も残っていない」にせず,ValueError にする."""
        with pytest.raises(ValueError):
            parse_ls_output(BROKEN_OUTPUTS[case])

    @pytest.mark.parametrize("cut", range(len(NORMAL) - 1))
    def test_truncated_output_is_value_error(self, cut: int) -> None:
        """SPEC_03「ls」: 途中で切れた出力(正常な出力を各位置で切ったもの)は ValueError.

        最後の NUL だけを落としたもの(終端の目印まで届いている)は,切れていない扱いでよい.
        """
        with pytest.raises(ValueError):
            parse_ls_output(NORMAL[:cut])

    @pytest.mark.parametrize("cut", range(len(ls_missing_remote_dir()) - 1))
    def test_truncated_missing_remote_dir_output_is_value_error(self, cut: int) -> None:
        """「コードの置き場が無い」の出力も,途中で切れていれば「何も残っていない」にしない."""
        with pytest.raises(ValueError):
            parse_ls_output(ls_missing_remote_dir()[:cut])

    def test_output_without_last_nul_is_still_complete(self) -> None:
        assert parse_ls_output(NORMAL[:-1]) == parse_ls_output(NORMAL)

    @pytest.mark.parametrize(
        "records",
        [
            [dir_record(_SECRET + " x")],
            [b"dir 0 0 many 4 " + _SECRET.encode()],
            [b"dir 0 0 1 " + _SECRET.encode()],
            [_SECRET],
            [log_record(_SECRET + ".log")],
        ],
        ids=["bad_dir_name_then_ok", "bad_count", "few_fields", "bare_name", "log_in_results"],
    )
    def test_error_message_does_not_contain_server_names(self, records: list) -> None:
        """SPEC_03「ls」・coding-style: エラーのメッセージにサーバから来た名前を入れない."""
        broken = ls_records(results=records, logs=[b"log x " + _SECRET.encode() + b".log"])
        with pytest.raises(ValueError) as excinfo:
            parse_ls_output(encode_records(broken))
        assert _SECRET not in str(excinfo.value)

    @pytest.mark.parametrize(
        "records",
        [
            {"jobs": [_SECRET]},
            {"logs": [b"log nan " + _SECRET.encode() + b".log"]},
            {"logs": [b"log 12"], "jobs": [job_record(_SECRET)]},
        ],
        ids=["bare_job", "bad_log_size", "log_without_name"],
    )
    def test_error_message_does_not_contain_server_names_in_logs(self, records: dict) -> None:
        with pytest.raises(ValueError) as excinfo:
            parse_ls_output(ls_output(**records))
        assert _SECRET not in str(excinfo.value)


# ---------------------------------------------------------------------------
# ログインの挨拶(始まりの目印より前・終わりの目印より後)
# ---------------------------------------------------------------------------


class TestSurroundingGarbage:
    @pytest.mark.parametrize(
        "banner",
        [
            b"Welcome\nLast login: Mon\n",
            b"motd\0with\0nuls\0",
            b"\x1b[31mcolor\x1b[0m\n",
            b"\xff\xfe broken utf-8\n",
        ],
    )
    def test_banner_before_begin_is_ignored(self, banner: bytes) -> None:
        assert parse_ls_output(banner + NORMAL) == parse_ls_output(NORMAL)

    @pytest.mark.parametrize("trailer", [b"bye\n", b"\0garbage\0", b"\xff\0"])
    def test_garbage_after_end_is_ignored(self, trailer: bytes) -> None:
        assert parse_ls_output(NORMAL + trailer) == parse_ls_output(NORMAL)

    # 目印が 2 つ以上ある出力は,どれが本物かを決められないので拒否する(SPEC_03「ls」の「安全」).
    # 挨拶に紛れた偽の一覧(何も残っていない)を本物として読むと,「使い終えた」と見誤る
    @pytest.mark.parametrize(
        "fake",
        [
            ls_missing_remote_dir(),
            ls_output(results=[], logs=[]),
            ls_output(results=None, logs=None),
        ],
        ids=["remote_dir_missing", "empty_dirs", "no_dirs"],
    )
    def test_fake_listing_before_real_one_is_rejected(self, fake: bytes) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(fake + NORMAL)

    def test_fake_full_listing_after_end_is_rejected(self) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(NORMAL + ls_missing_remote_dir())

    @pytest.mark.parametrize("marker", [LS_BEGIN_MARKER, LS_END_MARKER])
    @pytest.mark.parametrize("position", ["before", "after"])
    def test_duplicated_marker_is_rejected(self, marker: str, position: str) -> None:
        extra = b"\0" + marker.encode() + b"\0"
        data = extra + NORMAL if position == "before" else NORMAL + extra
        with pytest.raises(ValueError, match="解釈できない"):
            parse_ls_output(data)

    def test_marker_inside_a_name_record_is_not_a_marker(self) -> None:
        """名前が目印と同じ文字列でも,記録の全体が目印に一致しなければ目印として数えない."""
        banner = f"dir 0 0 1 4 {LS_BEGIN_MARKER}".encode() + b"\0"
        assert parse_ls_output(banner + NORMAL) == parse_ls_output(NORMAL)


# ---------------------------------------------------------------------------
# 名前の検証(規則に合わない名前は表示せず「その他」に数える)
# ---------------------------------------------------------------------------

BAD_RUN_IDS: list[str | bytes] = [
    "",
    "a b",
    " lead",
    "trail ",
    "a..b",
    "..",
    ".",
    "abc.",
    "run.",
    ".hidden",
    "_under",
    "-dash",
    "--help",
    "nul",
    "NUL",
    "con",
    "CON.txt",
    "com1",
    "lpt9.log",
    "aux",
    "a;b",
    "$(id)",
    "a$(id)",
    "a`id`",
    "a|b",
    "a&b",
    "a>b",
    "a*b",
    "a?b",
    "a'b",
    'a"b',
    "a/b",
    "a\\b",
    "a:b",
    "a\x1b[31mred",
    "a\x07bell",
    "a\x7fdel",
    "a\nb",
    "a\rb",
    "a\tb",
    "abc\n",
    "日本語",
    "a​b",
    b"a\xffb",
    b"\xc3\x28",
    "a" * 201,
]

BAD_JOB_NAMES: list[str | bytes] = [
    "",
    "a b",
    "-x",
    "_x",
    ".x",
    "a.b",
    "a..b",
    "a;b",
    "$(id)",
    "a`b`",
    "a/b",
    "a\x1b[0m",
    "a\nb",
    "train1\n",
    "日本語",
    b"a\xffb",
    "a" * 65,
]


class TestNameValidation:
    @pytest.mark.parametrize("name", BAD_RUN_IDS, ids=repr)
    def test_bad_run_id_is_counted_as_other(self, name: str | bytes) -> None:
        """SPEC_03「ls」: 実験 ID の規則に合わない名前は,実験フォルダとして出ず「その他」."""
        data = ls_output(results=[dir_record(name, 5, 9), dir_record(RUN_A, 1, 1)])
        listing = parse_ls_output(data)
        assert [d.run_id for d in listing.run_dirs] == [RUN_A]
        assert listing.other_in_results == 1
        assert listed_run_ids([ServerLeftovers("Newton", listing)]) == frozenset({RUN_A})

    @pytest.mark.parametrize("name", ["a", "A1", "x" * 200, "1.2.3", "a_b-c.d", RUN_A])
    def test_good_run_id_is_listed(self, name: str) -> None:
        listing = parse_ls_output(ls_output(results=[dir_record(name, 1, 1)]))
        assert [d.run_id for d in listing.run_dirs] == [name]
        assert listing.other_in_results == 0

    @pytest.mark.parametrize("name", BAD_JOB_NAMES, ids=repr)
    def test_bad_job_log_name_is_counted_as_other(self, name: str | bytes) -> None:
        """SPEC_03「ls」: `.log` を外した名前がジョブ名の規則に合わないものは「その他」."""
        file_name = name + (b".log" if isinstance(name, bytes) else ".log")
        jobs = [job_record(name)] if isinstance(name, str) else []
        data = ls_output(logs=[log_record(file_name), log_record("ok1.log")], jobs=jobs)
        listing = parse_ls_output(data)
        assert [log.name for log in listing.job_logs] == ["ok1"]
        assert listing.other_in_logs == 1

    @pytest.mark.parametrize(
        "file_name",
        ["train1", "train1.LOG", "train1.log.bak", "train1.txt", ".log", "train1.log ", "log"],
        ids=repr,
    )
    def test_file_without_log_suffix_is_other(self, file_name: str) -> None:
        data = ls_output(logs=[log_record(file_name)])
        listing = parse_ls_output(data)
        assert listing.job_logs == ()
        assert listing.other_in_logs == 1

    @pytest.mark.parametrize("name", ["a", "A1", "x" * 64, "a_b-c", "train1"])
    def test_good_job_name_is_listed(self, name: str) -> None:
        listing = parse_ls_output(ls_output(logs=[log_record(name + ".log")]))
        assert [log.name for log in listing.job_logs] == [name]

    def test_bad_job_session_does_not_make_anything_running(self) -> None:
        """規則に合わない名前のセッションは,規則に合うログを実行中にしない."""
        data = ls_output(
            logs=[log_record("train1.log")],
            jobs=[job_record("train1\n"), job_record("train1 "), job_record(" train1")],
        )
        assert parse_ls_output(data).job_logs == (JobLogEntry("train1", 10, False),)

    def test_bad_names_are_not_anywhere_in_listing(self) -> None:
        """規則に合わない名前は,結果のどこにも残らない(件数だけ)."""
        # 実験 ID としてもジョブ名としても規則に合わない名前(`nul` 等はジョブ名としては正しい)
        names = [n for n in BAD_JOB_NAMES if isinstance(n, str) and n and n in BAD_RUN_IDS]
        data = ls_output(
            results=[dir_record(n) for n in names],
            logs=[log_record(n + ".log") for n in names],
            jobs=[job_record(n) for n in names],
        )
        listing = parse_ls_output(data)
        assert listing.run_dirs == () and listing.job_logs == ()
        assert listing.other_in_results == len(names)
        assert listing.other_in_logs == len(names)
        text = repr(listing)
        for n in names:
            if len(n) > 3:
                assert repr(n)[1:-1] not in text


# ---------------------------------------------------------------------------
# 全サーバの要約
# ---------------------------------------------------------------------------


def _ok(name: str, *, complete: bool = True, run_ids: tuple[str, ...] = ()) -> ServerLeftovers:
    runs = tuple(RunDirEntry(r, 1, 1, complete) for r in run_ids) or (
        (RunDirEntry(RUN_A, 1, 1, False),) if not complete else ()
    )
    return ServerLeftovers(name, RemoteListing(remote_dir_exists=True, run_dirs=runs))


class TestSummary:
    def test_all_ok(self) -> None:
        summary = summarize_ls([_ok("Newton"), _ok("Archimedes")])
        assert summary == LsSummary((), (), (), False)

    def test_classifies_each_server(self) -> None:
        results = [
            _ok("Newton"),
            ServerLeftovers("Archimedes", None, "接続不可", unreachable=True),
            ServerLeftovers("Curie", None, "解釈できない"),
            _ok("Darwin", complete=False),
            ServerLeftovers("Euler", RemoteListing(remote_dir_exists=True, sizes_complete=False)),
        ]
        summary = summarize_ls(results)
        assert summary.unreachable == ("Archimedes",)
        assert summary.unreadable == ("Curie",)
        assert summary.incomplete == ("Darwin", "Euler")
        assert not summary.all_unreachable

    def test_all_unreachable(self) -> None:
        results = [
            ServerLeftovers("Newton", None, "x", unreachable=True),
            ServerLeftovers("Archimedes", None, "y", unreachable=True),
        ]
        assert summarize_ls(results).all_unreachable

    def test_unreadable_is_not_unreachable(self) -> None:
        """接続できたが解釈できないサーバは,接続不可ではない(全台接続不可にならない)."""
        results = [
            ServerLeftovers("Newton", None, "x", unreachable=True),
            ServerLeftovers("Archimedes", None, "解釈できない"),
        ]
        summary = summarize_ls(results)
        assert not summary.all_unreachable
        assert summary.unreadable == ("Archimedes",)

    def test_empty_is_not_all_unreachable(self) -> None:
        assert not summarize_ls([]).all_unreachable

    def test_listed_run_ids_collects_all_servers(self) -> None:
        results = [
            _ok("Newton", run_ids=(RUN_A,)),
            _ok("Archimedes", run_ids=(RUN_A, RUN_B)),
            ServerLeftovers("Curie", None, "x", unreachable=True),
        ]
        assert listed_run_ids(results) == frozenset({RUN_A, RUN_B})


# ===========================================================================
# clean RUN_ID の判定(SPEC_03「clean」の手順 2・3 と「判定の細部」)
# ===========================================================================


def _rf(path: str, data: bytes = b"x") -> RemoteFile:
    """サーバの通常のファイル(大きさとハッシュは data から)."""
    return RemoteFile(path, True, len(data), sha(data))


def _lf(data: bytes = b"x") -> LocalFile:
    return LocalFile(len(data), sha(data))


def _judge(
    files: list[RemoteFile],
    local: dict[str, LocalFile] | None = None,
    *,
    results: ResultsConfig = CLEAN_RESULTS,
    discard_checkpoints: bool = False,
) -> CleanJudgement:
    return classify_clean(files, local or {}, results, discard_checkpoints=discard_checkpoints)


def _category(
    file: RemoteFile,
    local: dict[str, LocalFile] | None = None,
    *,
    results: ResultsConfig = CLEAN_RESULTS,
    discard_checkpoints: bool = False,
) -> CleanCategory:
    judgement = _judge([file], local, results=results, discard_checkpoints=discard_checkpoints)
    (entry,) = judgement.entries
    assert entry.file is file
    return entry.category


# 設定の一覧(CLEAN_RESULTS)のどれにも当たらない名前
PLAIN = "result.txt"
NESTED = "sub/dir/result.txt"
_X = sha(b"x")
_Y = sha(b"y")

# 一致としない組(サーバのファイル,手元の情報)
NOT_MATCHED_CASES = {
    "not_in_local": (RemoteFile(PLAIN, True, 1, _X), {}),
    "hash_differs": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, _Y)}),
    "size_larger_same_hash": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(2, _X)}),
    "size_smaller_same_hash": (RemoteFile(PLAIN, True, 2, _X), {PLAIN: LocalFile(1, _X)}),
    "size_zero_same_hash": (RemoteFile(PLAIN, True, 0, _X), {PLAIN: LocalFile(1, _X)}),
    "local_hash_empty": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, "")}),
    "both_hash_empty": (RemoteFile(PLAIN, True, 1, ""), {PLAIN: LocalFile(1, "")}),
    "both_hash_empty_size0": (RemoteFile(PLAIN, True, 0, ""), {PLAIN: LocalFile(0, "")}),
    "local_upper": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, _X.upper())}),
    "remote_upper": (RemoteFile(PLAIN, True, 1, _X.upper()), {PLAIN: LocalFile(1, _X)}),
    "both_upper": (RemoteFile(PLAIN, True, 1, _X.upper()), {PLAIN: LocalFile(1, _X.upper())}),
    "local_leading_space": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, f" {_X}")}),
    "local_trailing_newline": (RemoteFile(PLAIN, True, 1, _X), {PLAIN: LocalFile(1, f"{_X}\n")}),
    "both_trailing_space": (
        RemoteFile(PLAIN, True, 1, f"{_X} "),
        {PLAIN: LocalFile(1, f"{_X} ")},
    ),
    "both_63_digits": (RemoteFile(PLAIN, True, 1, _X[:-1]), {PLAIN: LocalFile(1, _X[:-1])}),
    "both_65_digits": (RemoteFile(PLAIN, True, 1, _X + "0"), {PLAIN: LocalFile(1, _X + "0")}),
    "both_1_digit": (RemoteFile(PLAIN, True, 1, "0"), {PLAIN: LocalFile(1, "0")}),
    "both_not_hex": (RemoteFile(PLAIN, True, 1, "g" * 64), {PLAIN: LocalFile(1, "g" * 64)}),
    # 手元の辞書に別の相対パスでしか無い
    "key_case_first": (_rf(PLAIN), {"Result.txt": _lf()}),
    "key_case_all": (_rf(PLAIN), {"RESULT.TXT": _lf()}),
    "key_dot_slash": (_rf(PLAIN), {"./result.txt": _lf()}),
    "key_trailing_slash": (_rf(PLAIN), {"result.txt/": _lf()}),
    "key_absolute": (_rf(PLAIN), {"/result.txt": _lf()}),
    "key_trailing_space": (_rf(PLAIN), {"result.txt ": _lf()}),
    "nested_key_case_dir1": (_rf(NESTED), {"Sub/dir/result.txt": _lf()}),
    "nested_key_case_dir2": (_rf(NESTED), {"sub/Dir/result.txt": _lf()}),
    "nested_key_dot_slash": (_rf(NESTED), {"./sub/dir/result.txt": _lf()}),
    "nested_key_backslash": (_rf(NESTED), {"sub\\dir\\result.txt": _lf()}),
    "nested_key_mixed_sep": (_rf(NESTED), {"sub/dir\\result.txt": _lf()}),
    "nested_key_trailing_slash": (_rf(NESTED), {"sub/dir/result.txt/": _lf()}),
    "nested_key_double_slash": (_rf(NESTED), {"sub//dir/result.txt": _lf()}),
    "nested_key_basename_only": (_rf(NESTED), {"result.txt": _lf()}),
    "nested_key_partial": (_rf(NESTED), {"dir/result.txt": _lf()}),
}


class TestCleanMatch:
    @pytest.mark.parametrize("path", [PLAIN, NESTED, "config.yaml", "figures/a.png"])
    def test_same_size_and_hash_is_matched(self, path: str) -> None:
        """SPEC_03「clean」: 手元の同じ相対パスに,大きさとハッシュが同じファイルがあれば一致."""
        assert _category(_rf(path, b"abc"), {path: _lf(b"abc")}) is CleanCategory.MATCHED

    def test_empty_file_matches_empty_file(self) -> None:
        assert _category(_rf(PLAIN, b""), {PLAIN: _lf(b"")}) is CleanCategory.MATCHED

    @pytest.mark.parametrize("case", sorted(NOT_MATCHED_CASES))
    @pytest.mark.parametrize("flag", [False, True])
    def test_not_matched(self, case: str, flag: bool) -> None:
        """SPEC_03「clean」: 大きさとハッシュの両方が同じで,同じ相対パスのときだけ一致.

        一覧のどれにも当たらない名前なので,一致でなければ説明がつかない.
        """
        remote, local = NOT_MATCHED_CASES[case]
        judgement = _judge([remote], local, discard_checkpoints=flag)
        assert judgement.entries[0].category is CleanCategory.UNEXPLAINED
        assert judgement.matched == CategoryTotal(0, 0)
        assert not judgement.deletable

    def test_matched_only_by_own_path_among_many(self) -> None:
        """他のファイルの手元の情報で一致にならない(同じ内容の別のファイルがあっても)."""
        files = [_rf("a.txt", b"same"), _rf("b.txt", b"same")]
        judgement = _judge(files, {"a.txt": _lf(b"same")})
        assert [e.category for e in judgement.entries] == [
            CleanCategory.MATCHED,
            CleanCategory.UNEXPLAINED,
        ]

    def test_case_variants_on_server_each_need_own_local(self) -> None:
        """サーバの A.csv と a.csv を,手元の 1 つで両方一致にしない."""
        files = [_rf("A.csv", b"v"), _rf("a.csv", b"v")]
        judgement = _judge(files, {"a.csv": _lf(b"v")})
        assert judgement.matched.count == 1
        assert judgement.unexplained.count == 1
        assert not judgement.deletable


# 説明がつかないもの 1 件の種類(SPEC_03「clean」の手順 2 の「説明がつかない」)
UNEXPLAINED_KINDS: dict[str, tuple[RemoteFile, dict[str, LocalFile]]] = {
    "not_in_local": (_rf("extra.txt", b"e"), {}),
    "content_differs": (_rf("extra.txt", b"e"), {"extra.txt": _lf(b"E")}),
    "size_differs": (_rf("extra.txt", b"e"), {"extra.txt": LocalFile(2, sha(b"e"))}),
    "link": (RemoteFile("extra.txt", False), {"extra.txt": LocalFile(0, "")}),
    "link_with_matching_local": (
        RemoteFile("extra.txt", False, 1, sha(b"e")),
        {"extra.txt": _lf(b"e")},
    ),
    "unsafe_path": (_rf("a/../extra.txt", b"e"), {"a/../extra.txt": _lf(b"e")}),
    "checkpoint_without_flag": (_rf("checkpoints/best.pth", b"w"), {}),
    "checkpoint_not_in_files": (_rf("checkpoints/other.pt", b"w"), {}),
    "case_of_discard_name": (_rf("Cache.bin", b"c"), {}),
}


def _explained() -> tuple[list[RemoteFile], dict[str, LocalFile]]:
    """説明がつくものだけの一覧(一致 5 件・捨ててよい 3 件)."""
    matched = [_rf(f"m{i}/f{i}.txt", bytes([65 + i]) * (i + 1)) for i in range(5)]
    local = {f.rel_path: LocalFile(f.size_bytes, f.sha256) for f in matched}
    discard = [_rf("cache.bin", b"c"), _rf("debug/a.png", b"d"), _rf("tmp/vis/b.jpg", b"v")]
    return matched + discard, local


class TestCleanDeletable:
    def test_all_explained_is_deletable(self) -> None:
        files, local = _explained()
        judgement = _judge(files, local)
        assert judgement.deletable
        assert judgement.unexplained == CategoryTotal(0, 0)
        assert judgement.matched.count == 5 and judgement.discardable.count == 3

    @pytest.mark.parametrize("kind", sorted(UNEXPLAINED_KINDS))
    @pytest.mark.parametrize("position", ["first", "middle", "last"])
    def test_one_unexplained_makes_it_not_deletable(self, kind: str, position: str) -> None:
        """SPEC_03「clean」の手順 3: 説明がつかないものが 1 件でもあれば消せない."""
        files, local = _explained()
        extra, extra_local = UNEXPLAINED_KINDS[kind]
        index = {"first": 0, "middle": len(files) // 2, "last": len(files)}[position]
        files.insert(index, extra)
        judgement = _judge(files, {**local, **extra_local})
        assert not judgement.deletable
        assert judgement.unexplained.count == 1
        assert judgement.entries[index].category is CleanCategory.UNEXPLAINED
        assert judgement.matched.count == 5 and judgement.discardable.count == 3

    def test_all_kinds_together_are_counted(self) -> None:
        files, local = _explained()
        for i, (extra, extra_local) in enumerate(UNEXPLAINED_KINDS.values()):
            # 同じ相対パスが重ならないよう,種類ごとにフォルダを分ける
            path = extra.rel_path if extra.rel_path != "extra.txt" else f"k{i}/extra.txt"
            files.append(RemoteFile(path, extra.regular, extra.size_bytes, extra.sha256))
            for value in extra_local.values():
                local[path] = value
        judgement = _judge(files, local)
        assert not judgement.deletable
        assert judgement.unexplained.count == len(UNEXPLAINED_KINDS)

    def test_empty_run_dir_is_deletable(self) -> None:
        """SPEC_03「clean」: フォルダ以外のものが 0 件なら,消してよい."""
        judgement = _judge([])
        assert judgement.deletable
        assert judgement.total == CategoryTotal(0, 0)
        assert judgement.entries == ()


# 通常のファイル以外が当たりうる条件(どれに当たっても説明がつかない)
NON_REGULAR_PATHS = [
    "result.txt",  # 手元に同じ相対パスの一致するファイルがある(下で手元の情報を渡す)
    "cache.bin",  # discard.files
    "debug/a.png",  # discard.dirs
    "tmp/vis/a.jpg",
    "checkpoints/best.pth",  # 重み(--discard-checkpoints を付ける)
    "checkpoints/sub/x.bin",
]


class TestCleanNonRegular:
    @pytest.mark.parametrize("path", NON_REGULAR_PATHS)
    @pytest.mark.parametrize("filled", [True, False], ids=["with_hash", "without_hash"])
    @pytest.mark.parametrize("flag", [False, True])
    def test_non_regular_is_always_unexplained(self, path: str, filled: bool, flag: bool) -> None:
        """SPEC_03「clean」: リンク等は,手元・一覧・重みのフラグを見ずに説明がつかない."""
        remote = RemoteFile(path, False, 1, sha(b"x")) if filled else RemoteFile(path, False)
        local = {path: _lf(b"x") if filled else LocalFile(0, "")}
        assert _category(remote, local, discard_checkpoints=flag) is CleanCategory.UNEXPLAINED

    def test_non_regular_is_counted_and_not_deletable(self) -> None:
        judgement = _judge(
            [_rf("a.txt"), RemoteFile("cache.bin", False)],
            {"a.txt": _lf()},
            discard_checkpoints=True,
        )
        assert not judgement.deletable
        assert judgement.unexplained_not_regular == 1
        assert judgement.unexplained.count == 1


# 安全でない相対パス(SPEC_03「clean」・回収の名前の検査と同じ規則).
# 多くは,一覧・重みのフォルダ・手元の辞書のどれかに当たりうる形にしてある
UNSAFE_CLEAN_PATHS = [
    "",
    "/abs",
    "/cache.bin",
    "/checkpoints/best.pth",
    "a/../b",
    "checkpoints/../cache.bin",
    "..",
    "../cache.bin",
    ".",
    "./a",
    "./cache.bin",
    "checkpoints/./best.pth",
    "a//b",
    "debug//a.png",
    "checkpoints//best.pth",
    "a\\b",
    "debug\\a.png",
    "checkpoints\\best.pth",
    "C:x",
    "c:cache.bin",
    "checkpoints/C:best.pth",
    "a:b",
    "nul",
    "NUL",
    "CON.txt",
    "con.png",
    "debug/nul.png",
    "checkpoints/CON",
    "com1.bin",
    "LPT9",
    "nul .png",
    "cache.bin.",
    "cache.bin ",
    "debug/a.png.",
    "debug./a.png",
    "checkpoints /best.pth",
    "checkpoints./best.pth",
    "a\x00b",
    "cache.bin\x00",
    "a\nb",
    "cache.bin\n",
    "a\rb",
    "a\tb",
    "a\x1b[31mb",
    "a\x7fb",
    "a/",
    "checkpoints/",
    "debug/",
    "a\udcffb",
    "checkpoints/\udcff",
    "debug/\udc80.png",
    "a<b",
    "a>b",
    'a"b',
    "a|b",
    "a?b",
    "a*b",
    "debug/*.png",
]


class TestCleanUnsafePath:
    @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS)
    def test_is_not_safe(self, path: str) -> None:
        assert not is_safe_clean_path(path)

    @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS)
    @pytest.mark.parametrize("flag", [False, True])
    def test_unsafe_path_is_unexplained_even_with_matching_local(
        self, path: str, flag: bool
    ) -> None:
        """SPEC_03「clean」: 安全でない相対パスは,他のどの条件に当たっても説明がつかない."""
        remote = _rf(path, b"z")
        judgement = _judge([remote], {path: _lf(b"z")}, discard_checkpoints=flag)
        assert judgement.entries[0].category is CleanCategory.UNEXPLAINED
        assert not judgement.deletable
        assert judgement.unexplained_unsafe == 1

    @pytest.mark.parametrize("path", UNSAFE_CLEAN_PATHS)
    def test_local_paths_to_check_skips_unsafe(self, path: str) -> None:
        """手元を調べる対象に,安全でない相対パスを入れない(手元の外を開かない)."""
        safe = _rf("ok.txt")
        assert local_paths_to_check([_rf(path), safe, _rf(path)]) == (safe,)

    def test_local_paths_to_check_skips_non_regular(self) -> None:
        safe = _rf("ok.txt")
        files = [RemoteFile("link.txt", False), safe, RemoteFile("x", False, 1, sha(b"x"))]
        assert local_paths_to_check(files) == (safe,)

    @pytest.mark.parametrize(
        "path", ["a", "a b.txt", "sub/dir/x.bin", ".hidden", "-dash", "日本語.txt", "a..b"]
    )
    def test_safe_paths_are_checked(self, path: str) -> None:
        assert is_safe_clean_path(path)
        assert local_paths_to_check([_rf(path)]) == (_rf(path),)


class TestCleanDiscardable:
    @pytest.mark.parametrize(
        "path", ["cache.bin", "nohup.out", "debug/a.png", "debug/x y.png", "tmp/vis/b.jpg"]
    )
    def test_discard_names_are_discardable(self, path: str) -> None:
        """SPEC_03「clean」: results.discard の形に一致すれば捨ててよい(手元に無くても)."""
        assert _category(_rf(path)) is CleanCategory.DISCARDABLE

    @pytest.mark.parametrize(
        "path",
        [
            # files は実験フォルダの直下だけ
            "sub/cache.bin",
            "debug/cache.bin",
            "checkpoints2/nohup.out",
            # 大文字小文字が違う
            "Cache.bin",
            "CACHE.BIN",
            "cache.BIN",
            "Nohup.out",
            "Debug/a.png",
            "debug/a.PNG",
            "debug/a.Png",
            "tmp/Vis/b.jpg",
            "TMP/vis/b.jpg",
            # 名前の一部だけが一致する
            "cache.bin.bak",
            "xcache.bin",
            "cache.binx",
            "nohup.out2",
            # dirs は path の直下で suffix のものだけ
            "debug/sub/a.png",
            "debug/sub/deep/a.png",
            "x/debug/a.png",
            "tmp/a.jpg",
            "tmp/vis/sub/b.jpg",
            "vis/b.jpg",
            "debug2/a.png",
            "debu/a.png",
            "debug/a.jpg",
            "tmp/vis/b.png",
            "debug/a.png.txt",
            "debug/apng",
            # 拡張子だけの名前
            "debug/.png",
            "tmp/vis/.jpg",
            # dirs の path そのもの
            "debug",
            "tmp/vis",
            # pull の一覧の名前(回収の一覧は捨ててよいにならない)
            "config.yaml",
            "metrics.json",
            "figures/a.png",
        ],
    )
    def test_other_names_are_not_discardable(self, path: str) -> None:
        assert _category(_rf(path)) is CleanCategory.UNEXPLAINED
        assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.UNEXPLAINED


class TestCleanCheckpoints:
    @pytest.mark.parametrize(
        "path",
        [
            "checkpoints/best.pth",  # checkpoints.files の名前
            "checkpoints/last.pth",  # checkpoints.files に無い名前
            "checkpoints/sub/epoch1.pth",  # 下の階層
            "checkpoints/a/b/c/d.bin",
            "checkpoints/.hidden",
            "checkpoints/config.yaml",
            "checkpoints/cache.bin",
        ],
    )
    def test_under_checkpoints_dir_only_with_flag(self, path: str) -> None:
        """SPEC_03「clean」: checkpoints.dir の下の全部.--discard-checkpoints のときだけ."""
        assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.CHECKPOINT
        assert _category(_rf(path), discard_checkpoints=False) is CleanCategory.UNEXPLAINED

    @pytest.mark.parametrize(
        "path",
        [
            "checkpoints",  # その名前のファイル
            "checkpoints2/x",
            "checkpointsX/x",
            "checkpoints.bak/x",
            "checkpoint/x",
            "Checkpoints/x",
            "CHECKPOINTS/best.pth",
            "sub/checkpoints/x",
            "a/b/checkpoints/best.pth",
            "xcheckpoints/x",
            "best.pth",
        ],
    )
    def test_not_under_checkpoints_dir(self, path: str) -> None:
        assert _category(_rf(path), discard_checkpoints=True) is CleanCategory.UNEXPLAINED

    def test_configured_checkpoints_dir_is_used(self) -> None:
        """SPEC_02「`results`」: checkpoints.dir を別の名前にしたときは,その名前の下だけ."""
        data = {**CLEAN_RESULTS_DICT, "checkpoints": {"dir": "weights", "files": ["final.ckpt"]}}
        results = ResultsConfig.model_validate(data)
        for path in ["weights/final.ckpt", "weights/other.pt", "weights/sub/x"]:
            got = _category(_rf(path), results=results, discard_checkpoints=True)
            assert got is CleanCategory.CHECKPOINT, path
        for path in ["checkpoints/best.pth", "weights", "Weights/x", "weights2/x", "a/weights/x"]:
            got = _category(_rf(path), results=results, discard_checkpoints=True)
            assert got is CleanCategory.UNEXPLAINED, path

    def test_unexplained_checkpoints_are_counted_for_hint(self) -> None:
        judgement = _judge(
            [_rf("checkpoints/best.pth"), _rf("checkpoints/sub/x"), _rf("extra.txt")]
        )
        assert judgement.unexplained.count == 3
        assert judgement.unexplained_checkpoints == 2


class TestCleanOrder:
    @pytest.mark.parametrize("path", ["cache.bin", "debug/a.png"])
    def test_matched_wins_over_discardable(self, path: str) -> None:
        """SPEC_03「clean」の「分ける順」: 一致 → 捨ててよい."""
        assert _category(_rf(path, b"q"), {path: _lf(b"q")}) is CleanCategory.MATCHED

    @pytest.mark.parametrize("flag", [False, True])
    def test_matched_wins_over_checkpoint(self, flag: bool) -> None:
        path = "checkpoints/best.pth"
        got = _category(_rf(path, b"w"), {path: _lf(b"w")}, discard_checkpoints=flag)
        assert got is CleanCategory.MATCHED

    def test_discardable_when_local_differs(self) -> None:
        """手元と内容が違っても,捨ててよい一覧に当たれば捨ててよい(次の区分へ進む)."""
        got = _category(_rf("cache.bin", b"a"), {"cache.bin": _lf(b"b")})
        assert got is CleanCategory.DISCARDABLE

    def test_checkpoint_when_local_differs(self) -> None:
        path = "checkpoints/best.pth"
        got = _category(_rf(path, b"a"), {path: _lf(b"b")}, discard_checkpoints=True)
        assert got is CleanCategory.CHECKPOINT


class TestCleanTotals:
    def test_category_totals_and_overall_total(self) -> None:
        files = [
            _rf("a.txt", b"1"),  # 一致 1
            _rf("sub/b.txt", b"22"),  # 一致 2
            _rf("cache.bin", b"333"),  # 捨ててよい 3
            _rf("debug/x.png", b"4444"),  # 捨ててよい 4
            _rf("checkpoints/best.pth", b"5" * 50),  # 重み 50
            _rf("checkpoints/s/x", b"6" * 60),  # 重み 60
            _rf("other.txt", b"7" * 7),  # 説明がつかない 7
            RemoteFile("link", False),  # 説明がつかない 0
            _rf("c.txt", b"8" * 8),  # 手元と違う 8
        ]
        local = {"a.txt": _lf(b"1"), "sub/b.txt": _lf(b"22"), "c.txt": _lf(b"9" * 8)}
        judgement = _judge(files, local, discard_checkpoints=True)
        assert judgement.matched == CategoryTotal(2, 3)
        assert judgement.discardable == CategoryTotal(2, 7)
        assert judgement.checkpoints == CategoryTotal(2, 110)
        assert judgement.unexplained == CategoryTotal(3, 15)
        assert judgement.total == CategoryTotal(9, 135)
        assert not judgement.deletable
        assert [e.file for e in judgement.entries] == files

    def test_large_sizes_are_summed(self) -> None:
        big = 5 * 1024**4
        files = [RemoteFile(f"f{i}", True, big, sha(b"x")) for i in range(3)]
        local = {f.rel_path: LocalFile(big, sha(b"x")) for f in files}
        judgement = _judge(files, local)
        assert judgement.matched == CategoryTotal(3, 3 * big)
        assert judgement.total == CategoryTotal(3, 3 * big)


class TestDiscardCheckpointsLoosensOnlyWeights:
    def test_flag_changes_only_files_under_checkpoints_dir(self) -> None:
        """SPEC_03「clean」: --discard-checkpoints で変わるのは,重みのフォルダの下の区分だけ."""
        files = [
            _rf("a.txt", b"1"),
            _rf("cache.bin"),
            _rf("debug/x.png"),
            _rf("checkpoints/best.pth", b"w"),
            _rf("checkpoints/sub/x", b"w2"),
            _rf("checkpoints/m.pth", b"m"),  # 手元と一致
            _rf("checkpoints"),
            _rf("Checkpoints/x"),
            _rf("sub/checkpoints/x"),
            _rf("extra.txt"),
            RemoteFile("checkpoints/link", False),
            _rf("checkpoints/../x"),
            _rf("checkpoints//x"),
            _rf("checkpoints/\udcff"),
        ]
        local = {"a.txt": _lf(b"1"), "checkpoints/m.pth": _lf(b"m")}
        off = _judge(files, local, discard_checkpoints=False)
        on = _judge(files, local, discard_checkpoints=True)
        changed = [
            (a.file.rel_path, a.category, b.category)
            for a, b in zip(off.entries, on.entries, strict=True)
            if a.category is not b.category
        ]
        assert changed == [
            ("checkpoints/best.pth", CleanCategory.UNEXPLAINED, CleanCategory.CHECKPOINT),
            ("checkpoints/sub/x", CleanCategory.UNEXPLAINED, CleanCategory.CHECKPOINT),
        ]
        assert off.checkpoints == CategoryTotal(0, 0)
        assert not on.deletable  # 他の説明がつかないものは残る


# ---------------------------------------------------------------------------
# clean の一覧の出力の解析(SPEC_03「clean」の「サーバの出力の扱い」)
# ---------------------------------------------------------------------------

CLEAN_ENTRIES = [
    file_record("metrics.json", b"{}"),
    file_record("sub dir/a b.txt", b"hello"),
    other_record("link"),
    file_record("empty.bin", b""),
    other_record("sub dir/fifo"),
    file_record("checkpoints/best.pth", b"w" * 1000),
]
CLEAN_NORMAL_RECORDS = clean_records(CLEAN_ENTRIES)
CLEAN_NORMAL = clean_output(CLEAN_ENTRIES)
CLEAN_EMPTY = clean_output([])
_H = sha(b"x")
_RUN_PREFIX = f"./{CLEAN_RUN_ID}/"
_CLEAN_SECRET = "secretcleanname_z3"


def _parse(data: bytes) -> RemoteRunListing:
    return parse_clean_output(data, CLEAN_RUN_ID)


class TestParseCleanNormal:
    def test_reads_files_and_others_in_order(self) -> None:
        listing = _parse(CLEAN_NORMAL)
        assert listing.state == CLEAN_STATE_PRESENT
        assert listing.files == (
            RemoteFile("metrics.json", True, 2, sha(b"{}")),
            RemoteFile("sub dir/a b.txt", True, 5, sha(b"hello")),
            RemoteFile("link", False),
            RemoteFile("empty.bin", True, 0, sha(b"")),
            RemoteFile("sub dir/fifo", False),
            RemoteFile("checkpoints/best.pth", True, 1000, sha(b"w" * 1000)),
        )

    def test_empty_run_dir(self) -> None:
        assert _parse(CLEAN_EMPTY) == RemoteRunListing(CLEAN_STATE_PRESENT, ())

    @pytest.mark.parametrize(
        "state",
        [CLEAN_STATE_MISSING, CLEAN_STATE_LINK, CLEAN_STATE_NOT_DIR, CLEAN_STATE_UNREADABLE],
    )
    def test_other_states(self, state: str) -> None:
        listing = _parse(clean_state_output(state))
        assert listing == RemoteRunListing(state)
        assert listing.files == ()

    def test_output_without_last_nul_is_still_complete(self) -> None:
        """ls と同じく,最後の NUL だけを落としたもの(終端の目印まで届いている)は読める."""
        assert _parse(CLEAN_NORMAL[:-1]) == _parse(CLEAN_NORMAL)
        assert _parse(CLEAN_EMPTY[:-1]) == _parse(CLEAN_EMPTY)

    @pytest.mark.parametrize(
        "name",
        ["a  b", " lead", "trail ", "x\ny", "back\\slash", "q'uote", "$(touch PWNED)", "-rf"],
    )
    def test_names_with_spaces_and_specials_are_kept_whole(self, name: str) -> None:
        """名前の空白で欄がずれない(パスは最後の欄で,空白を含んだまま読む)."""
        listing = _parse(clean_output([file_record(name, b"abc")]))
        assert listing.files == (RemoteFile(name, True, 3, sha(b"abc")),)

    def test_name_that_is_not_utf8_is_read_but_unsafe(self) -> None:
        """UTF-8 として読めない名前は,解析では読み,判定で安全でないとする."""
        listing = _parse(clean_output([file_record(b"bad\xff.bin")]))
        (found,) = listing.files
        assert not is_safe_clean_path(found.rel_path)
        judgement = classify_clean(
            listing.files, {found.rel_path: LocalFile(1, sha(b"x"))}, CLEAN_RESULTS,
            discard_checkpoints=True,
        )  # fmt: skip
        assert not judgement.deletable

    def test_path_with_dot_dot_under_run_dir_is_parsed_then_unexplained(self) -> None:
        listing = _parse(clean_output([raw_file_record("1", _H, f"{_RUN_PREFIX}../escape")]))
        judgement = classify_clean(
            listing.files, {"../escape": LocalFile(1, _H)}, CLEAN_RESULTS,
            discard_checkpoints=True,
        )  # fmt: skip
        assert not judgement.deletable

    def test_large_size(self) -> None:
        size = 123 * 1024**4
        listing = _parse(clean_output([raw_file_record(str(size), _H, f"{_RUN_PREFIX}big")]))
        assert listing.files[0].size_bytes == size

    @pytest.mark.parametrize("banner", [b"Welcome\nLast login: Mon\n", b"motd\0nul\0", b"\xff\0"])
    def test_banner_before_begin_is_ignored(self, banner: bytes) -> None:
        assert _parse(banner + CLEAN_NORMAL) == _parse(CLEAN_NORMAL)

    @pytest.mark.parametrize("trailer", [b"bye\n", b"\0garbage\0", b"\xff\0"])
    def test_garbage_after_end_is_ignored(self, trailer: bytes) -> None:
        assert _parse(CLEAN_NORMAL + trailer) == _parse(CLEAN_NORMAL)


def _without(records: list, prefix: str) -> list:
    return [r for r in records if not (isinstance(r, str) and r.startswith(prefix))]


def _swap(records: list, i: int, j: int) -> list:
    out = list(records)
    out[i], out[j] = out[j], out[i]
    return out


_FIND_RC_INDEX = len(CLEAN_NORMAL_RECORDS) - 3
_AFTER_INDEX = len(CLEAN_NORMAL_RECORDS) - 2

BROKEN_CLEAN_OUTPUTS: dict[str, bytes] = {
    "empty": b"",
    "only_nul": b"\0",
    "garbage": b"Welcome to the server\n",
    "newline_separated": b"\n".join(
        r if isinstance(r, bytes) else r.encode() for r in CLEAN_NORMAL_RECORDS
    ),
    # 目印が欠けている
    "no_begin": encode_records(CLEAN_NORMAL_RECORDS[1:]),
    "no_end": encode_records(CLEAN_NORMAL_RECORDS[:-1]),
    "no_run_state": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_RUN_PREFIX)),
    "no_find_rc": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_FIND_RC_PREFIX)),
    "no_after": encode_records(_without(CLEAN_NORMAL_RECORDS, CLEAN_AFTER_PREFIX)),
    "empty_no_find_rc": encode_records(_without(clean_records([]), CLEAN_FIND_RC_PREFIX)),
    "present_then_end": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT, CLEAN_END_MARKER]
    ),
    "missing_without_end": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING]
    ),
    "missing_then_records": encode_records(
        [
            CLEAN_BEGIN_MARKER,
            CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING,
            file_record("a"),
            CLEAN_END_MARKER,
        ]
    ),
    "missing_then_find_rc": encode_records(
        [
            CLEAN_BEGIN_MARKER,
            CLEAN_RUN_PREFIX + CLEAN_STATE_MISSING,
            f"{CLEAN_FIND_RC_PREFIX}0",
            CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT,
            CLEAN_END_MARKER,
        ]
    ),
    # 目印の順が違う
    "find_rc_before_entries": encode_records(
        [
            CLEAN_BEGIN_MARKER,
            CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT,
            f"{CLEAN_FIND_RC_PREFIX}0",
            *CLEAN_ENTRIES,
            CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT,
            CLEAN_END_MARKER,
        ]
    ),
    "after_before_find_rc": encode_records(
        _swap(CLEAN_NORMAL_RECORDS, _FIND_RC_INDEX, _AFTER_INDEX)
    ),
    "end_before_after": encode_records(
        _swap(CLEAN_NORMAL_RECORDS, _AFTER_INDEX, len(CLEAN_NORMAL_RECORDS) - 1)
    ),
    "run_state_after_entries": encode_records(
        [
            CLEAN_BEGIN_MARKER,
            *CLEAN_ENTRIES,
            CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT,
            f"{CLEAN_FIND_RC_PREFIX}0",
            CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT,
            CLEAN_END_MARKER,
        ]
    ),
    "run_marker_in_entries": clean_output([CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT]),
    "after_marker_in_entries": clean_output([CLEAN_AFTER_PREFIX + CLEAN_STATE_PRESENT]),
    "two_find_rc": encode_records(
        [
            *CLEAN_NORMAL_RECORDS[:_FIND_RC_INDEX],
            f"{CLEAN_FIND_RC_PREFIX}0",
            *CLEAN_NORMAL_RECORDS[_FIND_RC_INDEX:],
        ]
    ),
    "entry_after_find_rc": encode_records(
        [
            *CLEAN_NORMAL_RECORDS[: _FIND_RC_INDEX + 1],
            file_record("late.txt"),
            *CLEAN_NORMAL_RECORDS[_AFTER_INDEX:],
        ]
    ),
    "entry_after_after": encode_records(
        [*CLEAN_NORMAL_RECORDS[:-1], file_record("late.txt"), CLEAN_END_MARKER]
    ),
    # 大きさ
    "size_word": clean_output([raw_file_record("big", _H, f"{_RUN_PREFIX}a")]),
    "size_negative": clean_output([raw_file_record("-1", _H, f"{_RUN_PREFIX}a")]),
    "size_empty": clean_output([raw_file_record("", _H, f"{_RUN_PREFIX}a")]),
    "size_plus": clean_output([raw_file_record("+1", _H, f"{_RUN_PREFIX}a")]),
    "size_decimal": clean_output([raw_file_record("1.5", _H, f"{_RUN_PREFIX}a")]),
    "size_exponent": clean_output([raw_file_record("1e3", _H, f"{_RUN_PREFIX}a")]),
    "size_hex": clean_output([raw_file_record("0x10", _H, f"{_RUN_PREFIX}a")]),
    "size_fullwidth": clean_output([raw_file_record("1", _H, f"{_RUN_PREFIX}a")]),
    "size_underscore": clean_output([raw_file_record("1_000", _H, f"{_RUN_PREFIX}a")]),
    # ハッシュ
    "hash_63": clean_output([raw_file_record("1", _H[:-1], f"{_RUN_PREFIX}a")]),
    "hash_65": clean_output([raw_file_record("1", _H + "0", f"{_RUN_PREFIX}a")]),
    "hash_upper": clean_output([raw_file_record("1", _H.upper(), f"{_RUN_PREFIX}a")]),
    "hash_not_hex": clean_output([raw_file_record("1", "g" * 64, f"{_RUN_PREFIX}a")]),
    "hash_empty": clean_output([raw_file_record("1", "", f"{_RUN_PREFIX}a")]),
    "hash_dash": clean_output([raw_file_record("1", "-", f"{_RUN_PREFIX}a")]),
    "hash_fullwidth": clean_output([raw_file_record("1", "a" + _H[1:], f"{_RUN_PREFIX}a")]),
    # 欄が足りない
    "file_without_path": clean_output([f"file 1 {_H}"]),
    "file_without_hash": clean_output(["file 1"]),
    "file_bare": clean_output(["file "]),
    "file_word_only": clean_output(["file"]),
    "other_bare": clean_output(["other "]),
    "other_word_only": clean_output(["other"]),
    # 同じ相対パスが 2 回
    "duplicate_file_file": clean_output([file_record("a.txt"), file_record("a.txt")]),
    "duplicate_file_file_other_hash": clean_output(
        [file_record("a.txt", b"1"), file_record("a.txt", b"2")]
    ),
    "duplicate_file_other": clean_output([file_record("a.txt"), other_record("a.txt")]),
    "duplicate_other_file": clean_output([other_record("a.txt"), file_record("a.txt")]),
    "duplicate_other_other": clean_output([other_record("a.txt"), other_record("a.txt")]),
    "duplicate_apart": clean_output(
        [file_record("sub/a"), file_record("b"), file_record("c"), file_record("sub/a")]
    ),
    # ハッシュを取れなかった
    "nohash": clean_output([nohash_record("a.txt")]),
    "nohash_among_files": clean_output([file_record("a"), nohash_record("b"), file_record("c")]),
    "nohash_bare": clean_output(["nohash "]),
    # パスが ./<RUN_ID>/ の下でない
    "path_other_run": clean_output([file_record("a", run_id="20261120-090000_demo_def5678")]),
    "path_run_itself": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID}")]),
    "path_run_itself_slash": clean_output([raw_file_record("1", _H, _RUN_PREFIX)]),
    "path_run_prefix_x": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID}x/a")]),
    "path_run_shorter": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID[:-1]}/a")]),
    "path_parent": clean_output([raw_file_record("1", _H, "../a")]),
    "path_parent_run": clean_output([raw_file_record("1", _H, f"../{CLEAN_RUN_ID}/a")]),
    "path_without_dot": clean_output([raw_file_record("1", _H, f"{CLEAN_RUN_ID}/a")]),
    "path_absolute": clean_output([raw_file_record("1", _H, f"/{CLEAN_RUN_ID}/a")]),
    "path_dot": clean_output([raw_file_record("1", _H, "./a")]),
    "path_case": clean_output([raw_file_record("1", _H, f"./{CLEAN_RUN_ID.upper()}/a")]),
    "other_path_other_run": clean_output(
        [other_record("a", run_id="20261120-090000_demo_def5678")]
    ),
    "other_path_run_itself": clean_output([f"other ./{CLEAN_RUN_ID}"]),
    # find の終了コード
    "find_rc_1": clean_output(CLEAN_ENTRIES, find_rc=1),
    "find_rc_2": clean_output(CLEAN_ENTRIES, find_rc=2),
    "find_rc_1_empty": clean_output([], find_rc=1),
    "find_rc_word": clean_output(CLEAN_ENTRIES, find_rc="x"),
    "find_rc_empty": clean_output(CLEAN_ENTRIES, find_rc=""),
    "find_rc_negative": clean_output(CLEAN_ENTRIES, find_rc="-1"),
    # 一覧の後の状態
    "after_link": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_LINK),
    "after_notdir": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_NOT_DIR),
    "after_missing": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_MISSING),
    "after_unreadable": clean_output(CLEAN_ENTRIES, after=CLEAN_STATE_UNREADABLE),
    "after_link_empty": clean_output([], after=CLEAN_STATE_LINK),
    "after_unknown": clean_output(CLEAN_ENTRIES, after="ok"),
    "after_upper": clean_output(CLEAN_ENTRIES, after="PRESENT"),
    "after_empty": clean_output(CLEAN_ENTRIES, after=""),
    # 知らない種類の記録
    "unknown_dir_record": clean_output([f"dir {_RUN_PREFIX}a"]),
    "unknown_upper_file": clean_output([f"FILE 1 {_H} {_RUN_PREFIX}a"]),
    "unknown_link_record": clean_output([f"link {_RUN_PREFIX}a"]),
    "unknown_empty_record": clean_output([""]),
    "unknown_bare_path": clean_output([f"{_RUN_PREFIX}a"]),
    "unknown_file_tab": clean_output([f"file\t1\t{_H}\t{_RUN_PREFIX}a"]),
    # 状態が知らない値
    "state_unknown": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "exists", CLEAN_END_MARKER]
    ),
    "state_upper": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "MISSING", CLEAN_END_MARKER]
    ),
    "state_trailing_space": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "missing ", CLEAN_END_MARKER]
    ),
    "state_empty": encode_records([CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX, CLEAN_END_MARKER]),
    "present_upper": encode_records(
        [CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + "PRESENT", *CLEAN_NORMAL_RECORDS[2:]]
    ),
}


class TestParseCleanBroken:
    @pytest.mark.parametrize("case", sorted(BROKEN_CLEAN_OUTPUTS))
    def test_unparsable_output_is_value_error(self, case: str) -> None:
        """SPEC_03「clean」: 解釈できない出力は「説明がつく」と見なさず ValueError にする."""
        with pytest.raises(ValueError):
            _parse(BROKEN_CLEAN_OUTPUTS[case])

    @pytest.mark.parametrize("cut", range(len(CLEAN_NORMAL) - 1))
    def test_truncated_output_is_value_error(self, cut: int) -> None:
        """正常な出力を各バイト位置で切ったものは ValueError(最後の NUL だけを落としたものは除く).

        ls と同じ扱い.
        """
        with pytest.raises(ValueError):
            _parse(CLEAN_NORMAL[:cut])

    @pytest.mark.parametrize("cut", range(len(CLEAN_EMPTY) - 1))
    def test_truncated_empty_output_is_value_error(self, cut: int) -> None:
        """「空の実験フォルダ」の出力も,途中で切れていれば消せると読まない."""
        with pytest.raises(ValueError):
            _parse(CLEAN_EMPTY[:cut])

    @pytest.mark.parametrize("state", [CLEAN_STATE_MISSING, CLEAN_STATE_LINK])
    def test_truncated_state_output_is_value_error(self, state: str) -> None:
        data = clean_state_output(state)
        for cut in range(len(data) - 1):
            with pytest.raises(ValueError):
                _parse(data[:cut])

    @pytest.mark.parametrize(
        "run_id", ["", "..", "a/b", "-rf", "a;b", "$(x)", f"{CLEAN_RUN_ID}\n", "x.", "nul"]
    )
    def test_bad_run_id_is_value_error(self, run_id: str) -> None:
        with pytest.raises(ValueError):
            parse_clean_output(CLEAN_EMPTY, run_id)

    def test_run_id_must_match_output(self) -> None:
        """別の実験 ID で取った出力を,この実験 ID の一覧として読まない."""
        with pytest.raises(ValueError):
            parse_clean_output(CLEAN_NORMAL, "20261120-090000_demo_def5678")

    @pytest.mark.parametrize(
        "entries",
        [
            [file_record(_CLEAN_SECRET), file_record(_CLEAN_SECRET)],
            [file_record(_CLEAN_SECRET), other_record(_CLEAN_SECRET)],
            [raw_file_record("big", _H, f"{_RUN_PREFIX}{_CLEAN_SECRET}")],
            [raw_file_record("1", "XYZ", f"{_RUN_PREFIX}{_CLEAN_SECRET}")],
            [raw_file_record("1", _H, f"./other/{_CLEAN_SECRET}")],
            [nohash_record(_CLEAN_SECRET)],
            [f"weird {_RUN_PREFIX}{_CLEAN_SECRET}"],
            [f"file 1 {_CLEAN_SECRET}"],
            [_CLEAN_SECRET],
        ],
        ids=[
            "dup", "dup_other", "size", "hash", "outside", "nohash", "kind", "fields", "bare",
        ],
    )  # fmt: skip
    def test_error_message_does_not_contain_server_names(self, entries: list) -> None:
        """SPEC_03「clean」: 相対パス・ファイル名は,エラーのどこにも出さない."""
        with pytest.raises(ValueError) as excinfo:
            _parse(clean_output([file_record(f"ok_{_CLEAN_SECRET}"), *entries]))
        assert _CLEAN_SECRET not in str(excinfo.value)
        assert "secretclean" not in repr(excinfo.value)

    @pytest.mark.parametrize("find_rc", [1])
    def test_find_failure_message_has_no_names(self, find_rc: int) -> None:
        with pytest.raises(ValueError) as excinfo:
            _parse(clean_output([file_record(_CLEAN_SECRET)], find_rc=find_rc))
        assert _CLEAN_SECRET not in str(excinfo.value)


class TestParseCleanFakeListing:
    # 挨拶に紛れた偽の一覧(空の実験フォルダ = 消せる)を本物として読まない
    @pytest.mark.parametrize(
        "fake",
        [CLEAN_EMPTY, clean_state_output(CLEAN_STATE_MISSING), CLEAN_NORMAL],
        ids=["empty_run_dir", "missing", "normal"],
    )
    def test_fake_listing_before_real_one_is_rejected(self, fake: bytes) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            _parse(fake + CLEAN_NORMAL)

    @pytest.mark.parametrize(
        "fake", [CLEAN_EMPTY, clean_state_output(CLEAN_STATE_MISSING)], ids=["empty", "missing"]
    )
    def test_fake_listing_after_end_is_rejected(self, fake: bytes) -> None:
        with pytest.raises(ValueError, match="解釈できない"):
            _parse(CLEAN_NORMAL + fake)

    def test_fake_empty_listing_before_failing_real_one_is_rejected(self) -> None:
        """本物が find の失敗でも,前の偽の「空」を読んで消せるとしない."""
        with pytest.raises(ValueError):
            _parse(CLEAN_EMPTY + clean_output(CLEAN_ENTRIES, find_rc=1))

    @pytest.mark.parametrize("marker", [CLEAN_BEGIN_MARKER, CLEAN_END_MARKER])
    @pytest.mark.parametrize("position", ["before", "after"])
    def test_duplicated_marker_is_rejected(self, marker: str, position: str) -> None:
        extra = b"\0" + marker.encode() + b"\0"
        data = extra + CLEAN_NORMAL if position == "before" else CLEAN_NORMAL + extra
        with pytest.raises(ValueError, match="解釈できない"):
            _parse(data)

    def test_marker_text_inside_a_name_is_not_a_marker(self) -> None:
        listing = _parse(clean_output([file_record(CLEAN_END_MARKER), other_record("x")]))
        assert [f.rel_path for f in listing.files] == [CLEAN_END_MARKER, "x"]


# ---------------------------------------------------------------------------
# 消す直前の照合へ送る一覧(SPEC_03「clean」の「削除の細部」の「手元から送るもの」)
# ---------------------------------------------------------------------------

_SECRET = "secretexpectname_z9"
_EXPECT_END = CLEAN_EXPECT_END_RECORD.encode("ascii")


def _split_expected(data: bytes) -> list[bytes]:
    """送る一覧を記録に分ける(各記録の後に NUL が 1 つ)."""
    assert data.endswith(b"\0")
    return data[:-1].split(b"\0")


# 消せない(説明がつかないものが 1 件ある)判定を作る.どれからも一覧を作らない
UNEXPLAINED_JUDGEMENTS = {
    "not_in_local": lambda: _judge([_rf("a.txt"), _rf(f"{_SECRET}.txt")], {"a.txt": _lf()}),
    "content_differs": lambda: _judge([_rf(f"{_SECRET}.txt", b"x")], {f"{_SECRET}.txt": _lf(b"y")}),
    "size_differs": lambda: _judge([_rf(f"{_SECRET}.txt", b"x")], {f"{_SECRET}.txt": _lf(b"xx")}),
    "link": lambda: _judge([_rf("a.txt"), RemoteFile(f"{_SECRET}_link", False)], {"a.txt": _lf()}),
    "unsafe_dotdot": lambda: _judge([_rf(f"../{_SECRET}")], {f"../{_SECRET}": _lf()}),
    "unsafe_absolute": lambda: _judge([_rf(f"/{_SECRET}")], {f"/{_SECRET}": _lf()}),
    "unsafe_backslash": lambda: _judge([_rf(f"a\\{_SECRET}")], {f"a\\{_SECRET}": _lf()}),
    "unsafe_newline": lambda: _judge([_rf(f"a\n{_SECRET}")], {f"a\n{_SECRET}": _lf()}),
    "not_utf8": lambda: _judge([_rf(f"{_SECRET}\udcff")]),
    "checkpoint_without_flag": lambda: _judge([_rf(f"checkpoints/{_SECRET}.pth")]),
    "one_among_many": lambda: _judge(
        [_rf("metrics.json"), _rf("cache.bin"), _rf(f"{_SECRET}.txt")], {"metrics.json": _lf()}
    ),
}


class TestBuildCleanExpectedInput:
    @pytest.mark.parametrize("kind", list(UNEXPLAINED_JUDGEMENTS))
    def test_not_deletable_judgement_is_rejected(self, kind: str) -> None:
        """testing ルールの必須対象 2: 説明がつかないものが 1 件でもあれば,送る一覧を作らない."""
        judgement = UNEXPLAINED_JUDGEMENTS[kind]()
        assert not judgement.deletable
        with pytest.raises(ValueError) as excinfo:
            build_clean_expected_input(judgement, CLEAN_RUN_ID)
        assert _SECRET not in str(excinfo.value)

    def test_forged_judgement_with_unexplained_entry_is_rejected(self) -> None:
        """件数が 0 でも,説明がつかない区分の記録が混じっていれば作らない(二重の守り)."""
        good = _judge([_rf("metrics.json")], {"metrics.json": _lf()})
        assert good.deletable
        forged = replace(
            good,
            entries=(*good.entries, ClassifiedFile(_rf(_SECRET), CleanCategory.UNEXPLAINED)),
        )
        assert forged.deletable
        with pytest.raises(ValueError):
            build_clean_expected_input(forged, CLEAN_RUN_ID)

    def test_forged_judgement_with_unexplained_count_is_rejected(self) -> None:
        good = _judge([_rf("metrics.json")], {"metrics.json": _lf()})
        forged = replace(good, unexplained=CategoryTotal(1, 1))
        with pytest.raises(ValueError):
            build_clean_expected_input(forged, CLEAN_RUN_ID)

    @pytest.mark.parametrize(
        "bad",
        [
            RemoteFile("a.txt", True, 1, "g" * 64),
            RemoteFile("a.txt", True, 1, _X.upper()),
            RemoteFile("a.txt", True, 1, _X[:-1]),
            RemoteFile("a.txt", True, -1, _X),
            RemoteFile("a\0b", True, 1, _X),
            RemoteFile("", True, 1, _X),
        ],
        ids=["not_hex", "upper", "short", "negative", "nul", "empty_path"],
    )
    def test_record_that_cannot_be_written_is_rejected(self, bad: RemoteFile) -> None:
        """記録にできない(区切りが崩れる・形が違う)ものが入った判定からは作らない."""
        good = _judge([_rf("metrics.json")], {"metrics.json": _lf()})
        forged = replace(good, entries=(ClassifiedFile(bad, CleanCategory.MATCHED),))
        with pytest.raises(ValueError):
            build_clean_expected_input(forged, CLEAN_RUN_ID)

    def test_all_explained_entries_are_included(self) -> None:
        """一致・捨ててよい・重み(捨てる)の全件と,最後に終わりの記録."""
        files = {
            "metrics.json": b"{}",
            "sub/a b.txt": b"hello",
            "figures/loss.png": b"png" * 100,
            "cache.bin": b"c" * 10,
            "debug/x.png": b"d",
            "checkpoints/best.pth": b"w" * 50,
            "checkpoints/sub/e1.pth": b"",
        }
        matched = ["metrics.json", "sub/a b.txt", "figures/loss.png"]
        judgement = _judge(
            [_rf(rel, data) for rel, data in files.items()],
            {rel: _lf(files[rel]) for rel in matched},
            discard_checkpoints=True,
        )
        assert judgement.deletable
        assert (judgement.matched.count, judgement.discardable.count) == (3, 2)
        assert judgement.checkpoints.count == 2
        data = build_clean_expected_input(judgement, CLEAN_RUN_ID)
        records = _split_expected(data)
        assert records[-1] == _EXPECT_END
        assert len(records) == judgement.total.count + 1
        expected = [file_record(rel, body) for rel, body in files.items()]
        assert sorted(records[:-1]) == sorted(expected)
        assert data.count(b"\0") == len(files) + 1

    def test_empty_judgement_is_end_record_only(self) -> None:
        judgement = _judge([])
        assert judgement.deletable
        assert build_clean_expected_input(judgement, CLEAN_RUN_ID) == _EXPECT_END + b"\0"

    @pytest.mark.parametrize(
        "rel", ["a b.txt", "it's", "$(touch x)", "-rf", "~", "日本語/名前.txt", "x;y", "`id`"]
    )
    def test_record_form_matches_server_listing(self, rel: str) -> None:
        """記録の形は,一覧のスクリプトの出力(tests/clean_helpers.py)と同じ."""
        judgement = _judge([_rf(rel, b"v")], {rel: _lf(b"v")})
        records = _split_expected(build_clean_expected_input(judgement, CLEAN_RUN_ID))
        assert records == [file_record(rel, b"v"), _EXPECT_END]

    def test_end_record_is_not_a_file_record(self) -> None:
        for prefix in (CLEAN_FILE_PREFIX, CLEAN_OTHER_PREFIX, CLEAN_NOHASH_PREFIX):
            assert not CLEAN_EXPECT_END_RECORD.startswith(prefix)
        assert "\0" not in CLEAN_EXPECT_END_RECORD

    @pytest.mark.parametrize(
        "run_id",
        ["", "..", ".", "a/b", "-rf", "a;b", "$(x)", "*", f"{CLEAN_RUN_ID}\n", "x.", "nul", "a b"],
    )
    def test_bad_run_id_is_rejected(self, run_id: str) -> None:
        judgement = _judge([_rf("metrics.json")], {"metrics.json": _lf()})
        with pytest.raises(ValueError):
            build_clean_expected_input(judgement, run_id)

    def test_paths_use_the_given_run_id(self) -> None:
        """記録のパスは,渡した実験 ID の下.

        判定は実験 ID を持たないので,別の(正しい形の)ID を渡しても組み立つ.その一覧は
        サーバでの照合で合わない(tests/test_commands.py の
        test_list_of_other_run_does_not_delete).
        """
        judgement = _judge([_rf("metrics.json")], {"metrics.json": _lf()})
        records = _split_expected(build_clean_expected_input(judgement, RUN_B))
        assert records == [file_record("metrics.json", run_id=RUN_B), _EXPECT_END]