"""回収の判定のテスト(SPEC_01「安全の枠」の「回収」・SPEC_02「`results`」・SPEC_03「pull」).
最重要(testing ルールの必須対象 1): 名前が一致するファイルだけが回収対象になり,分割結果・
画像ごとの予測・画像・manifest・指定の無い重みは回収されないこと.破れるとファイル名を含む結果や
画像が手元に流れる.
テスト用の設定の一覧(`tests/results_helpers.py`)で回収する(`runs/<実験ID>/` 配下):
`config.yaml`・`history.csv`・`metrics.json`・`log.txt`・`figures/*.png`(直下のみ).
`--with-checkpoints` のときだけ `checkpoints/best.pth`・`checkpoints/Model.onnx`
(名前の完全一致).それ以外はすべて回収しない.
抜け道(`:`・末尾の `.` や空白・大文字小文字・制御文字・ディレクトリのエントリ等)と,
実験 ID の形も確かめる.
"""
import io
import tarfile
from datetime import datetime
import pytest
from results_helpers import OTHER_RESULTS, SAMPLE_RESULTS
from labremote.config import ResultsConfig
from labremote.whitelist import (
check_pull_members,
has_pull_names,
is_discard_allowed,
is_pull_allowed,
is_safe_relative_path,
parse_find_listing,
plan_pull,
validate_run_id,
)
RUN_ID = "20261119-120000_demo_abc1234"
# 回収の一覧は設定から与える(tests/results_helpers.py.下の ROOT_FILES・FIGURES・CHECKPOINTS)
RESULTS = SAMPLE_RESULTS
# テスト用の設定(RESULTS)の一覧
ROOT_FILES = ["config.yaml", "history.csv", "metrics.json", "log.txt"]
FIGURES = ["figures/loss.png", "figures/iou.png", "figures/learning_curve.png", "figures/a b.png"]
CHECKPOINTS = ["checkpoints/best.pth", "checkpoints/Model.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_image.png",
"P0001_image.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/a<b.png",
"figures/a>b.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/model.onnx",
"checkpoints/MODEL.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",
"Model.onnx",
"figures/best.pth",
"figures/Model.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_test_results_list_is_exactly_the_names_above() -> None:
# テストの前提(RESULTS の一覧)と,上の ROOT_FILES・CHECKPOINTS の食い違いを防ぐ
assert RESULTS.pull.files == tuple(ROOT_FILES)
assert RESULTS.checkpoints.files == ("best.pth", "Model.onnx")
def test_default_results_pull_nothing() -> None:
# results を省略した設定では,回収の一覧が空になり何も回収しない(SPEC_02「`results`」)
empty = ResultsConfig()
for name in ALLOWED + CHECKPOINTS:
assert not is_pull_allowed(name, empty, with_checkpoints=True)
class TestIsPullAllowed:
@pytest.mark.parametrize("name", ALLOWED)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_allowed_names(self, name: str, with_checkpoints: bool) -> None:
assert is_pull_allowed(name, RESULTS, 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・Model.onnx 以外の判定を変えない
assert not is_pull_allowed(name, RESULTS, with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("name", ["split.json", "predictions.csv", "manifest.csv"])
def test_per_image_results_never_pulled_even_with_checkpoints(self, name: str) -> None:
assert not is_pull_allowed(name, RESULTS, with_checkpoints=True)
@pytest.mark.parametrize("name", CHECKPOINTS)
def test_checkpoints_only_with_flag(self, name: str) -> None:
assert not is_pull_allowed(name, RESULTS, with_checkpoints=False)
assert is_pull_allowed(name, RESULTS, with_checkpoints=True)
@pytest.mark.parametrize("name", UNSAFE_PATHS)
def test_unsafe_paths_are_not_allowed(self, name: str) -> None:
assert not is_pull_allowed(name, RESULTS, with_checkpoints=True)
class TestValidateRunId:
@pytest.mark.parametrize(
"run_id",
[
RUN_ID,
"20261119-120000_demo_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 TestRunIdOfProjectMakeRunId:
"""利用する側の `make_run_id` の実験 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:
make_run_id = pytest.importorskip("tongue_seg_model.training.run_artifacts").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 labremote.commands import format_git_commit
run_artifacts = pytest.importorskip("tongue_seg_model.training.run_artifacts")
make_run_id = run_artifacts.make_run_id
resolve_git_commit = run_artifacts.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({"LABREMOTE_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:
"""`LABREMOTE_GIT_COMMIT` の名前は 2 か所に置かれている.
remote は training を import しないため.
"""
from labremote import commands
run_artifacts = pytest.importorskip("tongue_seg_model.training.run_artifacts")
assert commands.GIT_COMMIT_ENV_VAR == run_artifacts.GIT_COMMIT_ENV_VAR == "LABREMOTE_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, RESULTS, with_checkpoints=False)
assert sorted(plan.files) == sorted(f"{RUN_ID}/{name}" for name in ALLOWED)
assert plan.skipped == len(NOT_ALLOWED) + len(CHECKPOINTS)
assert plan.skipped_checkpoints == len(CHECKPOINTS)
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, RESULTS, 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, RESULTS, 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, RESULTS, 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, RESULTS, with_checkpoints=False).files == ()
def test_non_utf8_names_are_not_selected(self) -> None:
data = b"f " + RUN_ID.encode() + b"/figures/\xff\xfe.png\0"
listing = parse_find_listing(data)
plan = plan_pull(listing, RUN_ID, RESULTS, 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, RESULTS, with_checkpoints=False) == len(members)
def test_accepts_checkpoints_with_flag(self) -> None:
members = [_regular(f"{RUN_ID}/{name}") for name in ALLOWED + CHECKPOINTS]
assert check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=True) == len(members)
def test_empty_archive_is_accepted_as_zero(self) -> None:
assert check_pull_members([], RUN_ID, RESULTS, with_checkpoints=False) == 0
@pytest.mark.parametrize("bad", BAD_MEMBERS, ids=lambda info: repr(info.name)[:60])
@pytest.mark.parametrize("with_checkpoints", [False, True])
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, RESULTS, with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("name", CHECKPOINTS)
def test_checkpoints_rejected_without_flag(self, name: str) -> None:
members = [_regular(f"{RUN_ID}/config.yaml"), _regular(f"{RUN_ID}/{name}")]
with pytest.raises(ValueError):
check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False)
def test_error_message_does_not_contain_member_names(self) -> None:
secret = "P0001_yamada_image"
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, RESULTS, 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, RESULTS, 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, RESULTS, 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_demo_abc1234-dirty",
"20261119-120000_synthetic_nogit",
"20261119-120000_demo_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 全体は予約名にならない(日時で始まる)."""
make_run_id = pytest.importorskip("tongue_seg_model.training.run_artifacts").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, RESULTS, 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, RESULTS, with_checkpoints=False)
@pytest.mark.parametrize("base", RESERVED_BASES)
def test_every_reserved_base_is_rejected(self, base: str) -> None:
assert not is_pull_allowed(f"figures/{base}.png", RESULTS, with_checkpoints=True)
@pytest.mark.parametrize("base", NOT_RESERVED_BASES)
def test_every_not_reserved_base_is_accepted(self, base: str) -> None:
assert is_pull_allowed(f"figures/{base}.png", RESULTS, 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, RESULTS, 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, RESULTS, 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, RESULTS, with_checkpoints=False) == 3
def test_error_message_does_not_contain_reserved_member_names(self) -> None:
members = [_regular(f"{RUN_ID}/figures/P0001_yamada.png."), _regular(f"{RUN_ID}/nul.txt")]
with pytest.raises(ValueError) as excinfo:
check_pull_members(members, RUN_ID, RESULTS, with_checkpoints=False)
assert "yamada" not in str(excinfo.value)
assert "nul" not in str(excinfo.value)
# ---------------------------------------------------------------------------
# 一覧を設定で変えたときの判定(SPEC_02「`results`」・SPEC_01「安全の枠」の「回収」)
# ---------------------------------------------------------------------------
# tests/results_helpers.py の OTHER_RESULTS(SAMPLE_RESULTS とは別の一覧)で回収するもの
OTHER_ALLOWED = [
"summary.txt",
"scores.tsv",
"out/plots/a.svg",
"out/plots/loss curve.svg",
"curves/train.csv",
]
OTHER_CHECKPOINTS = ["weights/final.ckpt"]
# OTHER_RESULTS で回収しないもの(--with-checkpoints を付けても)
OTHER_NOT_ALLOWED = [
# pull.dirs は path の直下だけ(path が複数の部分でも)
"out/plots/sub/a.svg",
"out/plots/a/b/c.svg",
"out/a.svg",
"plots/a.svg",
"a.svg",
"x/out/plots/a.svg",
"curves/sub/train.csv",
"out/plots/.svg",
# 大文字と小文字を区別した完全一致
"Summary.txt",
"SUMMARY.TXT",
"summary.TXT",
"out/plots/a.SVG",
"out/plots/a.Svg",
"Out/plots/a.svg",
"out/Plots/a.svg",
"Curves/train.csv",
"curves/train.CSV",
# 拡張子・中身では判断しない(一覧に無い .png・.csv・.json 等)
"summary.csv",
"metrics.csv",
"result.json",
"a.png",
"out/plots/a.png",
"out/plots/a.csv",
"curves/a.svg",
"curves/a.json",
"summary.txt.bak",
"summary.txt.",
"summary.txt ",
# discard に書いた名前は回収の一覧ではない
"trace.bin",
"debug/a.png",
"debug/sub/a.png",
# 重み: checkpoints.files に無い名前・下の階層・置き場の外・既定の置き場の名前
"weights/other.ckpt",
"weights/Final.ckpt",
"weights/final.CKPT",
"weights/final.ckpt.bak",
"weights/sub/final.ckpt",
"Weights/final.ckpt",
"final.ckpt",
"out/plots/final.ckpt",
"checkpoints/final.ckpt",
"checkpoints/best.pth",
"weights/summary.txt",
"weights/a.svg",
]
# SAMPLE_RESULTS の一覧にあった名前.OTHER_RESULTS では対象にならない(古い一覧が残っていない)
SAMPLE_NAMES = ALLOWED + CHECKPOINTS
class TestOtherResultsList:
"""一覧を設定で変えると,回収の対象がその一覧のとおりに変わる(SPEC_02「`results`」)."""
@pytest.mark.parametrize("name", OTHER_ALLOWED)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_names_in_other_list_are_allowed(self, name: str, with_checkpoints: bool) -> None:
"""SPEC_01「回収」: 設定の一覧に名前が完全に一致するファイルを回収する."""
assert is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("name", SAMPLE_NAMES)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_names_of_sample_list_are_not_allowed(self, name: str, with_checkpoints: bool) -> None:
"""SPEC_02「`results`」.
判定は設定の一覧だけを見る(別の一覧の名前・古い定数は効かない).
"""
assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("name", OTHER_NOT_ALLOWED)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_names_outside_other_list_are_not_allowed(
self, name: str, with_checkpoints: bool
) -> None:
"""SPEC_02「名前の比べ方」: 直下だけ・大文字小文字を区別した完全一致・拡張子で判断しない."""
assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("name", OTHER_CHECKPOINTS)
def test_other_checkpoints_only_with_flag(self, name: str) -> None:
"""SPEC_02「`results`」.
checkpoints.files の名前は --with-checkpoints のときだけ回収する.
"""
assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=False)
assert is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=True)
@pytest.mark.parametrize("name", ["trace.bin", "debug/a.png"])
def test_discard_names_are_not_pull_names(self, name: str) -> None:
"""SPEC_02「`results`」: discard は回収の一覧ではない(名前を書いても回収しない)."""
assert not is_pull_allowed(name, OTHER_RESULTS, with_checkpoints=True)
def test_pull_dir_with_one_part_is_also_direct_only(self) -> None:
"""SPEC_02「`results`」.
pull.dirs の対象は path の直下だけ(SAMPLE の figures でも同じ).
"""
assert is_pull_allowed("figures/a.png", RESULTS, with_checkpoints=False)
assert not is_pull_allowed("figures/sub/a.png", RESULTS, with_checkpoints=True)
class TestEmptyResultsList:
"""一覧が空(`results` を省略)のとき,何も対象にならない(SPEC_02「`results`」の冒頭)."""
@pytest.mark.parametrize(
"name",
SAMPLE_NAMES + OTHER_ALLOWED + OTHER_CHECKPOINTS + ["checkpoints/x.pth", "runs/x"],
)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_nothing_is_allowed(self, name: str, with_checkpoints: bool) -> None:
"""SPEC_02「`results`」: 省略したときは回収する名前の一覧が空になる."""
assert not is_pull_allowed(name, ResultsConfig(), with_checkpoints=with_checkpoints)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_plan_selects_nothing(self, with_checkpoints: bool) -> None:
"""SPEC_02「`results`」: 一覧が空なら,サーバの一覧から何も選ばない(重みも)."""
names = SAMPLE_NAMES + OTHER_ALLOWED + OTHER_CHECKPOINTS
listing = [("f", f"{RUN_ID}/{name}") for name in names]
plan = plan_pull(listing, RUN_ID, ResultsConfig(), with_checkpoints=with_checkpoints)
assert plan.files == ()
assert plan.skipped == len(names)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_has_no_pull_names(self, with_checkpoints: bool) -> None:
"""SPEC_02「`results`」: 一覧が空のときは回収しうる名前が無い."""
assert not has_pull_names(ResultsConfig(), with_checkpoints=with_checkpoints)
def test_checkpoints_only_has_names_only_with_flag(self) -> None:
"""SPEC_02「`results`」.
重みだけが書かれていれば,--with-checkpoints のときだけ名前がある.
"""
only_weights = ResultsConfig.model_validate({"checkpoints": {"files": ["best.pth"]}})
assert not has_pull_names(only_weights, with_checkpoints=False)
assert has_pull_names(only_weights, with_checkpoints=True)
assert has_pull_names(OTHER_RESULTS, with_checkpoints=False)
def _accepted_by_tar_check(
names: list[str], results: ResultsConfig, *, with_checkpoints: bool
) -> set[str]:
"""tar の全件検査(check_pull_members)が,1 件だけの tar として受け入れる名前の集合."""
accepted = set()
for name in names:
try:
count = check_pull_members(
[_regular(f"{RUN_ID}/{name}")], RUN_ID, results, with_checkpoints=with_checkpoints
)
except ValueError:
continue
assert count == 1
accepted.add(name)
return accepted
# 二重の確認の両方に与える名前(両方の一覧の名前・一覧に無い名前・外へ出る名前)
CANDIDATES = (
SAMPLE_NAMES
+ NOT_ALLOWED
+ UNSAFE_PATHS
+ OTHER_ALLOWED
+ OTHER_CHECKPOINTS
+ OTHER_NOT_ALLOWED
)
class TestDoubleCheckAgrees:
"""二重の確認の両方が,同じ設定で同じ判定をする(SPEC_01「安全の枠」の「回収」)."""
@pytest.mark.parametrize(
("results", "expected_without", "expected_with"),
[
(RESULTS, ALLOWED, ALLOWED + CHECKPOINTS),
(OTHER_RESULTS, OTHER_ALLOWED, OTHER_ALLOWED + OTHER_CHECKPOINTS),
(ResultsConfig(), [], []),
],
ids=["sample", "other", "empty"],
)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_plan_and_tar_check_select_the_same_names(
self,
results: ResultsConfig,
expected_without: list[str],
expected_with: list[str],
with_checkpoints: bool,
) -> None:
"""SPEC_01「回収」: サーバの一覧の絞り込みと tar の全件検査が,同じ名前を対象とする."""
listing = [("f", f"{RUN_ID}/{name}") for name in CANDIDATES]
plan = plan_pull(listing, RUN_ID, results, with_checkpoints=with_checkpoints)
planned = {path.removeprefix(f"{RUN_ID}/") for path in plan.files}
by_tar = _accepted_by_tar_check(CANDIDATES, results, with_checkpoints=with_checkpoints)
expected = set(expected_with if with_checkpoints else expected_without)
assert planned == expected
assert by_tar == expected
@pytest.mark.parametrize(
"bad",
[
"summary.txt.bak",
"config.yaml",
"figures/a.png",
"trace.bin",
"weights/other.ckpt",
"out/plots/sub/a.svg",
"../summary.txt",
],
)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_other_list_rejects_whole_archive_if_any_member_is_bad(
self, bad: str, with_checkpoints: bool
) -> None:
"""SPEC_01「回収」: 別の一覧でも,一覧に無い名前が 1 つでもあれば tar 全体を拒否する."""
members = [_regular(f"{RUN_ID}/summary.txt"), _regular(f"{RUN_ID}/{bad}")]
with pytest.raises(ValueError):
check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=with_checkpoints)
def test_other_list_rejects_weights_without_flag(self) -> None:
"""SPEC_01「回収」: 別の一覧でも,重みは --with-checkpoints 無しでは tar ごと拒否する."""
members = [_regular(f"{RUN_ID}/summary.txt"), _regular(f"{RUN_ID}/weights/final.ckpt")]
with pytest.raises(ValueError):
check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=False)
assert check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=True) == 2
@pytest.mark.parametrize(
"bad",
[
_typed(f"{RUN_ID}/summary.txt", tarfile.SYMTYPE, "/etc/passwd"),
_typed(f"{RUN_ID}/scores.tsv", tarfile.LNKTYPE, f"{RUN_ID}/trace.bin"),
_regular(f"{RUN_ID}/summary.txt:stream"),
_regular(f"{RUN_ID}/out/plots/nul.svg"),
_regular(f"{RUN_ID}/../summary.txt"),
_regular(f"/{RUN_ID}/summary.txt"),
],
ids=lambda info: repr(info.name)[:60],
)
def test_other_list_rejects_links_and_unsafe_names(self, bad: tarfile.TarInfo) -> None:
"""SPEC_01「回収」.
別の一覧でも,リンク・外へ出るパス・Windows で別の場所を指す名前は拒否.
"""
members = [_regular(f"{RUN_ID}/summary.txt"), bad]
with pytest.raises(ValueError):
check_pull_members(members, RUN_ID, OTHER_RESULTS, with_checkpoints=True)
def test_plan_counts_skipped_without_names(self) -> None:
"""SPEC_01「回収」: 回収しなかったものは件数で数え,計画の対象に名前を含めない."""
names = OTHER_ALLOWED + ["trace.bin", "secret_case07.png"] + OTHER_CHECKPOINTS
listing = [("f", f"{RUN_ID}/{name}") for name in names]
plan = plan_pull(listing, RUN_ID, OTHER_RESULTS, with_checkpoints=False)
assert plan.skipped == 3
assert plan.skipped_checkpoints == 1
assert not any("secret_case07" in path or "trace.bin" in path for path in plan.files)
# ---------------------------------------------------------------------------
# 破棄の判定(SPEC_03「clean」の「捨ててよい」・SPEC_02「`results`」の `discard`)
# ---------------------------------------------------------------------------
DISCARD_RESULTS_DICT = {
"pull": {
"files": ["config.yaml", "metrics.json"],
"dirs": [{"path": "figures", "suffix": ".png"}],
},
"checkpoints": {"dir": "checkpoints", "files": ["best.pth"]},
"discard": {
"files": ["cache.bin", "nohup.out"],
"dirs": [{"path": "debug", "suffix": ".png"}, {"path": "tmp/vis", "suffix": ".jpg"}],
},
}
DISCARD_RESULTS = ResultsConfig.model_validate(DISCARD_RESULTS_DICT)
DISCARD_ALLOWED = ["cache.bin", "nohup.out", "debug/a.png", "debug/a b.png", "tmp/vis/x.jpg"]
DISCARD_NOT_ALLOWED = [
# files は実験フォルダの直下だけ
"sub/cache.bin",
"debug/cache.bin",
"tmp/nohup.out",
# 大文字小文字が違う
"Cache.bin",
"CACHE.BIN",
"cache.Bin",
"NOHUP.OUT",
"Debug/a.png",
"DEBUG/a.png",
"debug/a.PNG",
"debug/a.pnG",
"tmp/VIS/x.jpg",
"Tmp/vis/x.jpg",
"tmp/vis/x.JPG",
# 名前の一部
"cache.bin.old",
"old.cache.bin",
"cache",
# dirs は path の直下で suffix のものだけ
"debug/sub/a.png",
"debug/a/b/c.png",
"a/debug/x.png",
"tmp/x.jpg",
"vis/x.jpg",
"tmp/vis/sub/x.jpg",
"debug2/a.png",
"debugx/a.png",
"debug/a.jpg",
"debug/apng",
"debug/a.png.bak",
# 拡張子だけの名前・path そのもの
"debug/.png",
"tmp/vis/.jpg",
"debug",
"tmp/vis",
"tmp",
# 回収の一覧・重みの名前
"config.yaml",
"metrics.json",
"figures/a.png",
"checkpoints/best.pth",
"checkpoints/x.png",
"best.pth",
]
DISCARD_UNSAFE = [
"",
"/cache.bin",
"./cache.bin",
"../cache.bin",
"x/../cache.bin",
"debug/../cache.bin",
"debug//a.png",
"debug/./a.png",
"debug\\a.png",
"C:cache.bin",
"debug/C:a.png",
"cache.bin.",
"cache.bin ",
"debug /a.png",
"debug/a.png.",
"debug/nul.png",
"debug/CON.png",
"cache.bin\n",
"cache.bin\x00",
"debug/a\x1b.png",
"debug/",
"/",
]
class TestIsDiscardAllowed:
@pytest.mark.parametrize("name", DISCARD_ALLOWED)
def test_allowed(self, name: str) -> None:
assert is_discard_allowed(name, DISCARD_RESULTS)
@pytest.mark.parametrize("name", DISCARD_NOT_ALLOWED)
def test_not_allowed(self, name: str) -> None:
assert not is_discard_allowed(name, DISCARD_RESULTS)
@pytest.mark.parametrize("name", DISCARD_UNSAFE)
def test_unsafe_paths_are_not_allowed(self, name: str) -> None:
assert not is_discard_allowed(name, DISCARD_RESULTS)
@pytest.mark.parametrize("name", UNSAFE_PATHS)
def test_pull_unsafe_paths_are_not_allowed(self, name: str) -> None:
assert not is_discard_allowed(name, DISCARD_RESULTS)
def test_default_results_discard_nothing(self) -> None:
for name in DISCARD_ALLOWED + ALLOWED + CHECKPOINTS:
assert not is_discard_allowed(name, ResultsConfig())
@pytest.mark.parametrize("name", [*ALLOWED, *CHECKPOINTS])
def test_pull_names_are_not_discardable(self, name: str) -> None:
"""回収の一覧(RESULTS)に discard が無ければ,回収の名前は捨ててよいにならない."""
assert not is_discard_allowed(name, RESULTS)
def test_safe_relative_path_matches_pull_rule(self) -> None:
for name in UNSAFE_PATHS + DISCARD_UNSAFE:
assert not is_safe_relative_path(name)
for name in ALLOWED + DISCARD_ALLOWED:
assert is_safe_relative_path(name)
def _with(**sections: object) -> ResultsConfig:
data = {**DISCARD_RESULTS_DICT, **sections}
return ResultsConfig.model_validate(data)
# 判定に使う全ての名前
_ALL_NAMES = sorted(
{*DISCARD_ALLOWED, *DISCARD_NOT_ALLOWED, *ALLOWED, *CHECKPOINTS, "summary.txt", "out/a.svg"}
)
class TestPullAndDiscardAreIndependent:
"""回収の判定は pull の一覧だけ,破棄の判定は discard の一覧だけを見る."""
@pytest.mark.parametrize(
"pull",
[
{"files": [], "dirs": []},
{"files": ["summary.txt"], "dirs": [{"path": "out", "suffix": ".svg"}]},
{"files": ["config.yaml", "metrics.json", "history.csv"], "dirs": []},
],
)
def test_changing_pull_does_not_change_discard(self, pull: dict) -> None:
changed = _with(pull=pull)
for name in _ALL_NAMES:
assert is_discard_allowed(name, changed) == is_discard_allowed(name, DISCARD_RESULTS), (
name
)
@pytest.mark.parametrize(
"discard",
[
{"files": [], "dirs": []},
{"files": ["summary.txt"], "dirs": [{"path": "out", "suffix": ".svg"}]},
{"files": ["history.csv"], "dirs": [{"path": "figures", "suffix": ".jpg"}]},
],
)
@pytest.mark.parametrize("with_checkpoints", [False, True])
def test_changing_discard_does_not_change_pull(
self, discard: dict, with_checkpoints: bool
) -> None:
changed = _with(discard=discard)
for name in _ALL_NAMES:
assert is_pull_allowed(
name, changed, with_checkpoints=with_checkpoints
) == is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=with_checkpoints), name
def test_discard_names_are_not_pulled(self) -> None:
for name in DISCARD_ALLOWED:
assert not is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=True)
def test_pull_names_are_not_discarded(self) -> None:
for name in ["config.yaml", "metrics.json", "figures/a.png", "checkpoints/best.pth"]:
assert is_pull_allowed(name, DISCARD_RESULTS, with_checkpoints=True)
assert not is_discard_allowed(name, DISCARD_RESULTS)