File size: 5,648 Bytes
2b01b59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Small offline archive/copy integrity regressions; no real dataset required."""

import hashlib
import json
import os
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import zipfile

from package_oxt_dataset import HashCache, archive_task, regular_files, verify_native


class PackagingTests(unittest.TestCase):
    def setUp(self):
        self.temporary = tempfile.TemporaryDirectory()
        self.addCleanup(self.temporary.cleanup)
        self.root = Path(self.temporary.name)
        self.store = self.root / "zarr/wipe_board.zarr"
        self.contents = {
            ".zgroup": b'{"zarr_format":2}',
            ".zattrs": b'{"complete":true}',
            "data/value/.zarray": b'{"shape":[2],"dtype":"<i8"}',
            "data/value/0": b"small already-compressed chunk",
        }
        for relative, value in self.contents.items():
            path = self.store / relative
            path.parent.mkdir(parents=True, exist_ok=True)
            path.write_bytes(value)
        self.export_hash = "e" * 64

    def test_archive_content_crc_and_identical_resume_does_not_rewrite(self):
        first = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        archive = self.root / first["archive"]
        with zipfile.ZipFile(archive) as handle:
            self.assertIsNone(handle.testzip())
            self.assertEqual(set(handle.namelist()), {"wipe_board.zarr/" + name for name in self.contents})
            for name, expected in self.contents.items():
                self.assertEqual(handle.read("wipe_board.zarr/" + name), expected)
            self.assertTrue(all(info.compress_type == zipfile.ZIP_STORED for info in handle.infolist()))
        self.assertTrue(first["zip64_allowed"])
        self.assertTrue(first["crc_verified"])
        self.assertEqual(first["archive_sha256"], hashlib.sha256(archive.read_bytes()).hexdigest())
        before = (archive.stat().st_ino, archive.stat().st_mtime_ns, archive.read_bytes())
        with patch.object(zipfile.ZipFile, "write", side_effect=AssertionError("resume rewrote archive")), \
                patch.object(zipfile.ZipFile, "testzip", side_effect=AssertionError("unchanged verified ZIP was rechecked")):
            second = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        self.assertEqual(second, first)
        self.assertEqual(before, (archive.stat().st_ino, archive.stat().st_mtime_ns, archive.read_bytes()))

    def test_changed_same_size_source_invalidates_archive_even_with_old_mtime(self):
        first = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        chunk = self.store / "data/value/0"
        original_stat = chunk.stat()
        changed = b"X" + chunk.read_bytes()[1:]
        chunk.write_bytes(changed)
        os.utime(chunk, ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns))
        second = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        self.assertNotEqual(first["source_files_sha256"], second["source_files_sha256"])
        self.assertNotEqual(first["archive_sha256"], second["archive_sha256"])
        with zipfile.ZipFile(self.root / second["archive"]) as handle:
            self.assertEqual(handle.read("wipe_board.zarr/data/value/0"), changed)
            self.assertIsNone(handle.testzip())

    def test_corrupted_archive_is_not_reused(self):
        first = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        archive = self.root / first["archive"]
        original = archive.read_bytes()
        # Keep the size unchanged so archive SHA, not size alone, detects damage.
        archive.write_bytes(b"BAD!" + original[4:])
        repaired = archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        self.assertTrue(repaired["crc_verified"])
        self.assertEqual(repaired["archive_sha256"], hashlib.sha256(archive.read_bytes()).hexdigest())
        with zipfile.ZipFile(archive) as handle:
            self.assertIsNone(handle.testzip())
            self.assertEqual(handle.read("wipe_board.zarr/data/value/0"), self.contents["data/value/0"])

    def test_native_copy_hash_mismatch_is_rejected(self):
        directory = self.root / "native/wipe_board/fake_episode"
        directory.mkdir(parents=True)
        path = directory / "ft_sensor.h5"
        path.write_bytes(b"native FT fixture")
        expected = {"bytes": path.stat().st_size, "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
        manifest = {"episodes": [{"native_path": "native/wipe_board/fake_episode", "files": {"ft_sensor.h5": expected}}]}
        report = verify_native(self.root, manifest, HashCache())
        self.assertEqual(report["file_count"], 1)
        self.assertTrue(report["complete"])
        self.assertEqual(json.loads((self.root / "checksums/native_sha256.json").read_text()), report)
        path.write_bytes(b"X" + path.read_bytes()[1:])
        with self.assertRaisesRegex(RuntimeError, "Native copy differs"):
            verify_native(self.root, manifest, HashCache())

    def test_partial_source_refused_before_any_archive_is_published(self):
        (self.store / "unfinished.partial").write_bytes(b"unfinished")
        with self.assertRaisesRegex(ValueError, "Incomplete write remains"):
            regular_files(self.store)
        with self.assertRaisesRegex(ValueError, "Incomplete write remains"):
            archive_task(self.root, "wipe_board", self.export_hash, HashCache())
        self.assertFalse((self.root / "archives/wipe_board/wipe_board.zarr.zip").exists())


if __name__ == "__main__":
    unittest.main()