okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
6.2 KiB126 linesraw
1"""feed_tool can gzip its tar.gz archives with several threads (OPT-IN, STRATA_PACK_THREADS) (Q4-READY 11-10: the gzip of one 180 MB engine archive was ~50 s on one core of a release box).
2
3What these tests pin:
4  * a multi-threaded archive holds the same members, modes and bytes as the single-stream one (STRATA_PACK_THREADS=1, the gzip of before);
5  * it is several gzip members, and Python's gzip / tarfile (what Control's updater and components.py read) and the system's tar read it as one stream;
6  * the same tree always gives the same archive bytes (no file name or time in the gzip headers);
7  * pack-engine's entry names the archive's real sha256 and size, and a zip is unchanged.
8"""
9from __future__ import annotations
10
11import gzip
12import hashlib
13import io
14import os
15import shutil
16import subprocess
17import sys
18import tarfile
19import tempfile
20import unittest
21from pathlib import Path
22from unittest import mock
23
24ROOT = Path(__file__).resolve().parents[2]
25sys.path.insert(0, str(ROOT))
26sys.path.insert(0, str(ROOT / "packaging"))
27
28import feed_tool  # noqa: E402
29
30
31def sha(p: Path) -> str:
32    return hashlib.sha256(p.read_bytes()).hexdigest()
33
34
35def members(archive: Path) -> list[tuple]:
36    with tarfile.open(archive, "r:gz") as tar:
37        out = []
38        for m in tar.getmembers():
39            data = tar.extractfile(m).read() if m.isfile() else b""
40            out.append((m.name, m.mode, m.type, m.linkname, hashlib.sha256(data).hexdigest()))
41        return out
42
43
44class ParallelGzip(unittest.TestCase):
45    def setUp(self):
46        self.tmp = tempfile.TemporaryDirectory()
47        self.addCleanup(self.tmp.cleanup)
48        self.root = Path(self.tmp.name)
49        self.tree = self.root / "tree"
50        (self.tree / "lib").mkdir(parents=True)
51        rnd = os.urandom(300_000)
52        (self.tree / "strata").write_bytes(b"\x7fELF" + rnd)                       # an "executable" (ELF magic)
53        (self.tree / "lib" / "big.so").write_bytes(rnd * 7 + b"tail")               # compressible + random, several blocks
54        (self.tree / "notes.txt").write_text("hello\n" * 5000)
55        (self.tree / "empty.bin").write_bytes(b"")
56        self.files = feed_tool._tree(self.tree)
57        p = mock.patch.object(feed_tool, "GZIP_BLOCK", 64 * 1024)                  # small blocks: many members even for a small tree
58        p.start()
59        self.addCleanup(p.stop)
60
61    def pack(self, name: str, threads: int) -> Path:
62        out = self.root / name
63        with mock.patch.dict(os.environ, {"STRATA_PACK_THREADS": str(threads)}):
64            feed_tool._write_archive(self.files, out, "tar.gz", "strata")
65        return out
66
67    def test_the_same_members_and_bytes_as_the_single_stream_archive(self):
68        one = self.pack("one.tar.gz", 1)
69        many = self.pack("many.tar.gz", 4)
70        self.assertEqual(members(one), members(many))
71        self.assertFalse((self.root / "many.tar.gz.tar-part").exists(), "the plain tar beside the archive is removed")
72
73    def test_several_gzip_members_read_as_one_stream(self):
74        many = self.pack("many.tar.gz", 4)
75        raw = many.read_bytes()
76        self.assertGreater(raw.count(b"\x1f\x8b\x08"), 4, "more than one gzip member")
77        plain = self.root / "plain.tar"
78        feed_tool._write_tar(self.files, plain, "w", "strata")
79        self.assertEqual(gzip.decompress(raw), plain.read_bytes())               # Python's gzip reads every member
80        with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tar:          # tarfile's r:gz (strata_control/components.py, updater.py)
81            self.assertEqual(len(tar.getmembers()), len(members(many)))
82        tar_exe = shutil.which("tar")
83        if tar_exe and os.name != "nt":
84            listed = subprocess.run([tar_exe, "-tzf", str(many)], capture_output=True, text=True)
85            self.assertEqual(listed.returncode, 0, listed.stderr)
86            self.assertEqual(sorted(l.rstrip("/") for l in listed.stdout.split()), sorted(m[0] for m in members(many)))
87            dest = self.root / "x"
88            dest.mkdir()
89            self.assertEqual(subprocess.run([tar_exe, "-xzf", str(many), "-C", str(dest)]).returncode, 0)
90            self.assertEqual((dest / "lib" / "big.so").read_bytes(), (self.tree / "lib" / "big.so").read_bytes())
91
92    def test_the_same_tree_gives_the_same_bytes(self):
93        a = self.pack("a.tar.gz", 4)
94        b = self.pack("b.tar.gz", 3)
95        self.assertEqual(sha(a), sha(b))                                         # pieces are cut by bytes, not by thread count
96
97    def test_the_thread_count(self):
98        with mock.patch.dict(os.environ, {"STRATA_PACK_THREADS": "1"}):
99            self.assertEqual(feed_tool.gzip_threads(), 1)
100        with mock.patch.dict(os.environ, {"STRATA_PACK_THREADS": "6"}):
101            self.assertEqual(feed_tool.gzip_threads(), 6)
102        for unset in ("", "x", "0"):                                          # OPT-IN: no setting (or a bad one) is the single stream
103            with mock.patch.dict(os.environ, {"STRATA_PACK_THREADS": unset}), mock.patch.object(os, "cpu_count", return_value=32):
104                self.assertEqual(feed_tool.gzip_threads(), 1)
105        env = {k: v for k, v in os.environ.items() if k != "STRATA_PACK_THREADS"}
106        with mock.patch.dict(os.environ, env, clear=True):
107            self.assertEqual(feed_tool.gzip_threads(), 1)
108
109    def test_the_default_archive_is_the_single_stream_gzip_of_before(self):
110        env = {k: v for k, v in os.environ.items() if k != "STRATA_PACK_THREADS"}
111        out = self.root / "default.tar.gz"
112        with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(feed_tool, "_parallel_gzip", side_effect=AssertionError("threaded by default")):
113            feed_tool._write_archive(self.files, out, "tar.gz", "strata")
114        self.assertEqual(out.read_bytes()[:3], b"\x1f\x8b\x08")
115        with gzip.open(out) as g:                                               # one stream, as tarfile w:gz writes it
116            g.read()
117
118    def test_a_zip_is_unchanged(self):
119        out = self.root / "c.zip"
120        with mock.patch.dict(os.environ, {"STRATA_PACK_THREADS": "4"}), mock.patch.object(feed_tool, "_parallel_gzip", side_effect=AssertionError("zip")):
121            feed_tool._write_archive(self.files, out, "zip", "strata.exe")
122        self.assertTrue(out.is_file())
123
124
125if __name__ == "__main__":
126    unittest.main()