okami.mom/strata

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

Niko1221Merge main c1ff07f1a into f-own-intfefaa985c

main
12.9 KiB258 linesraw
1"""Lane NET item 7: setup may use an Unsloth mmproj-F16.gguf that the person already has as the Flash-Next picture reader, and the plan says the same.
2
3The rule (setup.ALT_READERS, setup.accepted_alt_reader, setup.resolve_reader; the plan asks the same function through modelstate.reader_present):
4  * only a file named mmproj-F16.gguf with the pinned size AND SHA-256, in a place where setup already looks for the pinned reader;
5  * only when no pinned BF16 file is found anywhere (the pinned file always wins); anything else with that name is ignored, as before;
6  * never downloaded, never deleted, never given a mark beside it: the SHA-256 is remembered in Strata's marks/ (keyed by real path, size,
7    modification time and change time, so a replaced file is hashed again, also one rewritten in place with size and time kept);
8  * the plan hashes without writing a mark and says nothing.
9The tests use a small stand-in file and patch the pin; one test holds the real pin."""
10
11from __future__ import annotations
12
13import contextlib
14import hashlib
15import io
16import os
17import tempfile
18import time
19import unittest
20from pathlib import Path
21from unittest import mock
22
23from strata_cli.launch import modelstate
24from tests.terminal.launch_support import HW_12, Home, catalog
25
26ALT = "mmproj-F16.gguf"
27GOOD = b"unsloth-reader " * 100
28BAD = b"another-reader " * 100                                 # the same size, another content
29assert len(GOOD) == len(BAD)
30NOTE = ("  note: {path} has the name of Unsloth's picture reader but is a different file, so it is not used. "
31        "The picture reader is downloaded (0.9 GB).")
32
33
34class Base(unittest.TestCase):
35    def setUp(self):
36        home = Home().__enter__()
37        self.addCleanup(home.__exit__, None, None, None)
38        t = tempfile.TemporaryDirectory(prefix="strata-altreader-")
39        self.addCleanup(t.cleanup)
40        self.base = Path(t.name)
41        self.cat = catalog(HW_12)
42        self.mod = self.cat.strata.setup_module()               # the module the plan asks too
43        self.pinned = self.mod.MMPROJ
44        for p in (mock.patch.dict(self.mod.ALT_READERS, {self.pinned: (ALT, len(GOOD), hashlib.sha256(GOOD).hexdigest())}),
45                  mock.patch.object(self.mod, "ROOT", self.base / "strata-root")):
46            p.start()
47            self.addCleanup(p.stop)
48        self.own = self.base / "mine" / "IQ3_XXS"               # a person's own folder of shards
49        self.own.mkdir(parents=True)
50        self.models = self.base / "data" / "models"             # Strata's own models folder (the pinned file would be here)
51        self.models.mkdir(parents=True)
52
53    def start(self, gguf_dir="own"):
54        """What setup does for the reader: (kind, path, printed text)."""
55        out = io.StringIO()
56        gd = self.own if gguf_dir == "own" else gguf_dir
57        with contextlib.redirect_stdout(out):
58            kind, path = self.mod.resolve_reader(self.pinned, self.models / self.pinned, self.models, [], gd, 907543008)
59        return kind, path, out.getvalue()
60
61    def plan(self):
62        """What the plan believes: does setup find a reader without a download (and what it printed)."""
63        out = io.StringIO()
64        with contextlib.redirect_stdout(out):
65            present = modelstate.reader_present(self.cat, "qwen", [self.base / "data"], own=self.own)
66        return present, out.getvalue()
67
68    def marks(self):
69        d = self.mod.ROOT / "marks"
70        return sorted(d.iterdir()) if d.is_dir() else []
71
72    def hashes(self):
73        """Count the files setup hashes from here on."""
74        real = self.mod._hash_file
75        calls = []
76
77        def counting(path, size):
78            calls.append(Path(path).name)
79            return real(path, size)
80        p = mock.patch.object(self.mod, "_hash_file", counting)
81        p.start()
82        self.addCleanup(p.stop)
83        return calls
84
85
86class TheRealPin(unittest.TestCase):
87    def test_the_pinned_values_are_the_owners(self):
88        import setup
89        self.assertEqual(setup.ALT_READERS[setup.MMPROJ], ("mmproj-F16.gguf", 904004000,
90                                                            "1f7b7f0b984cf065c604360c29c8098362ed61b290db0ff12c6f360bb1a8a980"))
91        self.assertEqual(setup.MMPROJ, "mmproj-Qwen3.8-Flash-Next-BF16.gguf")
92        self.assertEqual(list(setup.ALT_READERS), [setup.MMPROJ], "Flash-Next's pinned file only, no other family")
93
94
95class Accepted(Base):
96    def test_a_file_with_the_pinned_size_and_hash_is_used_and_checked_once(self):
97        (self.own / ALT).write_bytes(GOOD)
98        hashed = self.hashes()
99        present, said = self.plan()                              # the plan first: hashes, says nothing, writes nothing
100        self.assertTrue(present)
101        self.assertEqual(said, "")
102        self.assertEqual(self.marks(), [], "the plan writes no mark")
103        kind, path, said = self.start()
104        self.assertEqual((kind, path), ("alt", self.own / ALT))
105        self.assertEqual(said, f"  checking {ALT} (SHA-256, 0.0 GB) ...\n")
106        self.assertEqual(len(self.marks()), 1, "one mark in Strata's own folder")
107        self.assertEqual(sorted(p.name for p in self.own.iterdir()), [ALT], "nothing was written beside the person's file")
108        before = len(hashed)
109        kind, _path, said = self.start()                         # the next run: the mark answers
110        self.assertEqual((kind, said), ("alt", ""))
111        self.assertTrue(self.plan()[0])
112        self.assertEqual(len(hashed), before, "no second hash")
113
114    def test_the_folder_above_and_its_models_folder_and_the_data_models_folder_count_too(self):
115        for where in (self.own.parent, self.own.parent / "models", self.models):
116            where.mkdir(parents=True, exist_ok=True)
117            f = where / ALT
118            f.write_bytes(GOOD)
119            self.assertEqual(self.start()[:2], ("alt", f), str(where))
120            self.assertTrue(self.plan()[0], str(where))
121            f.unlink()
122        self.assertEqual(self.start()[0], "fetch")
123        self.assertFalse(self.plan()[0])
124
125
126class NotAccepted(Base):
127    def test_a_wrong_size_is_ignored_exactly_as_before(self):
128        (self.own / ALT).write_bytes(GOOD[:-1])
129        hashed = self.hashes()
130        kind, path, said = self.start()
131        self.assertEqual((kind, path, said), ("fetch", self.models / self.pinned, ""))
132        self.assertEqual(hashed, [], "not even hashed")
133        self.assertEqual(self.plan(), (False, ""))
134        self.assertEqual((self.own / ALT).read_bytes(), GOOD[:-1])
135
136    def test_a_wrong_hash_is_ignored_with_the_note_and_the_pinned_file_is_downloaded(self):
137        (self.own / ALT).write_bytes(BAD)
138        hashed = self.hashes()
139        kind, path, said = self.start()
140        self.assertEqual((kind, path), ("fetch", self.models / self.pinned))
141        self.assertEqual(said, f"  checking {ALT} (SHA-256, 0.0 GB) ...\n" + NOTE.format(path=self.own / ALT) + "\n")
142        self.assertEqual(self.plan(), (False, ""), "the plan agrees with the start: the reader is downloaded")
143        self.assertEqual((self.own / ALT).read_bytes(), BAD, "the person's file is never touched")
144        self.assertEqual(sorted(p.name for p in self.own.iterdir()), [ALT])
145        before = len(hashed)
146        kind, _path, said = self.start()                         # remembered: not hashed again, the note says it again
147        self.assertEqual(kind, "fetch")
148        self.assertEqual(said, NOTE.format(path=self.own / ALT) + "\n")
149        self.assertEqual(len(hashed), before)
150
151    def test_another_name_is_never_looked_at(self):
152        (self.own / "mmproj-BF16.gguf").write_bytes(GOOD)
153        (self.own / "mmproj-Q8_0.gguf").write_bytes(GOOD)
154        self.assertEqual(self.start()[0], "fetch")
155        self.assertFalse(self.plan()[0])
156
157    def test_the_pinned_file_always_wins(self):
158        (self.own / ALT).write_bytes(GOOD)
159        pinned = self.own / self.pinned
160        pinned.write_bytes(b"x" * 10)                            # beside the files: by name, any size (setup's mmproj_beside)
161        hashed = self.hashes()
162        kind, path, said = self.start()
163        self.assertEqual((kind, path, said), ("near", pinned, ""))
164        self.assertEqual(hashed, [], "the alternative is not even hashed")
165        self.assertTrue(self.plan()[0])
166        pinned.unlink()
167        (self.models / self.pinned).write_bytes(b"y")            # Strata's own models folder
168        kind, path, said = self.start()
169        self.assertEqual((kind, path, said), ("fetch", self.models / self.pinned, ""), "the pinned file is used (and verified later by setup)")
170        self.assertTrue(self.plan()[0])
171        self.assertEqual(hashed, [])
172
173
174class Replaced(Base):
175    def test_a_file_accepted_once_and_then_replaced_by_another_of_the_same_size_is_hashed_again_and_refused(self):
176        f = self.own / ALT
177        f.write_bytes(GOOD)
178        self.assertEqual(self.start()[0], "alt")
179        self.assertEqual(len(self.marks()), 1)
180        hashed = self.hashes()
181        stat = f.stat()
182        f.write_bytes(BAD)                                       # the same size and place, other bytes
183        os.utime(f, ns=(stat.st_atime_ns, stat.st_mtime_ns + 5_000_000_000))      # (a new modification time, as any real replacement has)
184        kind, _path, said = self.start()
185        self.assertEqual(kind, "fetch")
186        self.assertIn("is a different file", said)
187        self.assertEqual(hashed, [ALT], "hashed again")
188        self.assertEqual(self.plan(), (False, ""))
189
190    def test_a_rewrite_in_place_that_keeps_size_and_modification_time_is_hashed_again_and_refused(self):
191        f = self.own / ALT
192        f.write_bytes(GOOD)
193        self.assertEqual(self.start()[0], "alt")
194        self.assertEqual(len(self.marks()), 1)
195        hashed = self.hashes()
196        stat = f.stat()
197        time.sleep(0.05)                                         # past the file system clock step (a kernel tick on Linux)
198        with open(f, "r+b") as fh:                               # the same file, rewritten in place (no new file, no rename)
199            fh.write(BAD)
200        os.utime(f, ns=(stat.st_atime_ns, stat.st_mtime_ns))     # the old modification time put back
201        self.assertEqual((f.stat().st_size, f.stat().st_mtime_ns), (stat.st_size, stat.st_mtime_ns), "size and modification time as before")
202        kind, _path, said = self.start()
203        self.assertEqual(kind, "fetch")
204        self.assertIn("is a different file", said)
205        self.assertEqual(hashed, [ALT], "hashed again")
206        self.assertEqual(self.plan(), (False, ""))
207
208    def test_the_change_time_moves_on_such_a_rewrite_on_this_system(self):
209        f = self.own / ALT
210        f.write_bytes(GOOD)
211        st = f.stat()
212        before = self.mod._change_time_ns(f, st)
213        time.sleep(0.05)                                         # past the file system clock step (a kernel tick on Linux)
214        with open(f, "r+b") as fh:
215            fh.write(BAD)
216        os.utime(f, ns=(st.st_atime_ns, st.st_mtime_ns))
217        self.assertNotEqual(self.mod._change_time_ns(f, f.stat()), before)
218        if os.name == "nt":                                      # Windows: the file system's ChangeTime, not os.stat's ctime (the creation time)
219            self.assertNotEqual(self.mod._change_time_ns(f, f.stat()), f.stat().st_ctime_ns)
220
221    def test_other_kept_marks_keep_their_key(self):
222        f = self.own / "model-00001-of-00002.gguf"
223        f.write_bytes(b"shard")
224        st = f.stat()
225        key = f"{f.resolve()}|{st.st_size}|{st.st_mtime_ns}"
226        self.assertEqual(self.mod._kept_mark(f).name, hashlib.sha1(key.encode()).hexdigest()[:24] + ".done",
227                         "the key of every other kept mark (an Engram's too) is unchanged, so no mark made before is lost")
228        self.assertNotEqual(self.mod._alt_reader_mark(f), self.mod._kept_mark(f))
229
230    def test_a_changed_size_has_no_mark_either(self):
231        f = self.own / ALT
232        f.write_bytes(GOOD)
233        self.assertEqual(self.start()[0], "alt")
234        f.write_bytes(GOOD + b"!")
235        self.assertEqual(self.start(), ("fetch", self.models / self.pinned, ""))
236
237    def test_the_mark_is_keyed_by_the_real_path_so_a_linked_folder_shares_it_and_cannot_hide_a_replacement(self):
238        real = self.base / "real"
239        real.mkdir()
240        (real / ALT).write_bytes(GOOD)
241        link = self.base / "link"
242        try:
243            os.symlink(real, link, target_is_directory=True)
244        except (OSError, NotImplementedError, AttributeError):
245            self.skipTest("this account cannot make symbolic links")
246        self.assertEqual(self.start(gguf_dir=real)[0], "alt")
247        hashed = self.hashes()
248        self.assertEqual(self.start(gguf_dir=link)[0], "alt")
249        self.assertEqual(hashed, [], "the same file through the link: the same mark")
250        stat = (real / ALT).stat()
251        (real / ALT).write_bytes(BAD)
252        os.utime(real / ALT, ns=(stat.st_atime_ns, stat.st_mtime_ns + 5_000_000_000))
253        self.assertEqual(self.start(gguf_dir=link)[0], "fetch", "replaced behind the link: hashed again, refused")
254        self.assertEqual(hashed, [ALT])
255
256
257if __name__ == "__main__":
258    unittest.main()