okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
28.8 KiB490 linesraw
1"""Packaged client smoke test without site packages, engine files or model weights."""
2
3import io
4import hashlib
5import importlib.util
6import json
7import os
8import subprocess
9import sys
10import tempfile
11import threading
12import unittest
13import zipfile
14from contextlib import redirect_stdout
15from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
16from pathlib import Path
17from unittest import mock
18
19from strata_cli.cli import main as source_main
20
21
22ROOT = Path(__file__).resolve().parents[2]
23BUILDER = ROOT / "packaging/monitor_bundle.py"
24SPEC = importlib.util.spec_from_file_location("strata_monitor_bundle_builder", BUILDER)
25assert SPEC is not None and SPEC.loader is not None
26BUILDER_MODULE = importlib.util.module_from_spec(SPEC)
27SPEC.loader.exec_module(BUILDER_MODULE)
28build = BUILDER_MODULE.build
29install = BUILDER_MODULE.install
30uninstall = BUILDER_MODULE.uninstall
31update = BUILDER_MODULE.update
32rollback = BUILDER_MODULE.rollback
33commit = BUILDER_MODULE.commit
34verify = BUILDER_MODULE.verify
35
36
37class MonitorBundleTests(unittest.TestCase):
38    @staticmethod
39    def _candidate(source: Path, destination: Path) -> Path:
40        destination.parent.mkdir()
41        destination.write_bytes(source.read_bytes())
42        with zipfile.ZipFile(destination, "a") as archive:
43            archive.comment = b"candidate client revision"
44        report = json.loads(source.with_name(source.name + ".manifest.json").read_text())
45        report["bundle"] = destination.name
46        report["sha256"] = hashlib.sha256(destination.read_bytes()).hexdigest()
47        destination.with_name(destination.name + ".manifest.json").write_text(json.dumps(report))
48        verify(destination)
49        return destination
50
51    def test_crlf_license_checkout_still_verifies(self):
52        """A Windows checkout (autocrlf) ships LICENSE with CRLF; the bundle must still verify."""
53        real_copy = BUILDER_MODULE.shutil.copyfile
54
55        def crlf_license(src, dst, *args, **kwargs):
56            if Path(src).name != "LICENSE":
57                return real_copy(src, dst, *args, **kwargs)
58            text = Path(src).read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
59            Path(dst).write_bytes(text)
60            return dst
61
62        with tempfile.TemporaryDirectory() as directory:
63            bundle = Path(directory) / "monitor.pyz"
64            with mock.patch.object(BUILDER_MODULE.shutil, "copyfile", crlf_license):
65                build(bundle)
66            with zipfile.ZipFile(bundle) as archive:
67                self.assertIn(b"MIT License\r\n", archive.read("LICENSE"))
68            self.assertEqual(verify(bundle)["schema_version"], 6)
69
70    def test_update_rollback_and_commit_keep_one_verified_previous_copy(self):
71        with tempfile.TemporaryDirectory() as directory:
72            root = Path(directory)
73            first = root / "first" / "monitor.pyz"
74            first.parent.mkdir()
75            old = build(first)
76            candidate = self._candidate(first, root / "second" / "next-monitor.pyz")
77            next_sha = verify(candidate)["sha256"]
78            target = root / "optional-monitor"
79            install(first, target, if_candidate_sha256=old["sha256"])
80            preview_run = subprocess.run([sys.executable, str(BUILDER), "update", str(candidate),
81                                          "--target", str(target), "--plan"],
82                                         capture_output=True, text=True, check=True)
83            preview = json.loads(preview_run.stdout)
84            self.assertEqual((preview["current_sha256"], preview["candidate_sha256"]),
85                             (old["sha256"], next_sha))
86            self.assertTrue(preview["would_update"])
87            with self.assertRaisesRegex(ValueError, "preview again"):
88                update(candidate, target, if_current_sha256=old["sha256"],
89                       if_candidate_sha256="0" * 64)
90            self.assertFalse((root / "optional-monitor.previous").exists())
91            changed = subprocess.run([sys.executable, str(BUILDER), "update", str(candidate),
92                                      "--target", str(target), "--if-current-sha256", old["sha256"],
93                                      "--if-candidate-sha256", next_sha],
94                                     capture_output=True, text=True, check=True)
95            result = json.loads(changed.stdout)
96            self.assertTrue(result["updated"])
97            previous = root / "optional-monitor.previous"
98            self.assertEqual(verify(target / "next-monitor.pyz")["sha256"], next_sha)
99            self.assertEqual(verify(previous / "monitor.pyz")["sha256"], old["sha256"])
100            with self.assertRaisesRegex(FileExistsError, "previous"):
101                update(candidate, target, plan=True)
102            preview_run = subprocess.run([sys.executable, str(BUILDER), "rollback", "--target",
103                                          str(target), "--plan"], capture_output=True, text=True, check=True)
104            preview = json.loads(preview_run.stdout)
105            self.assertTrue(preview["would_rollback"])
106            with self.assertRaisesRegex(ValueError, "preview again"):
107                rollback(target, if_active_sha256=old["sha256"], if_rollback_sha256=old["sha256"])
108            original = os.rename
109            calls = 0
110
111            def fail_last_exchange(source, destination):
112                nonlocal calls
113                calls += 1
114                if calls == 3:
115                    raise OSError("final exchange failed")
116                return original(source, destination)
117
118            with mock.patch.object(BUILDER_MODULE.os, "rename", side_effect=fail_last_exchange):
119                with self.assertRaisesRegex(OSError, "final exchange failed"):
120                    rollback(target, if_active_sha256=next_sha, if_rollback_sha256=old["sha256"])
121            self.assertEqual(verify(target / "next-monitor.pyz")["sha256"], next_sha)
122            self.assertEqual(verify(previous / "monitor.pyz")["sha256"], old["sha256"])
123            self.assertFalse(list(root.glob(".strata-monitor-swap-*")))
124            restored = subprocess.run([sys.executable, str(BUILDER), "rollback", "--target", str(target),
125                                       "--if-active-sha256", next_sha,
126                                       "--if-rollback-sha256", old["sha256"]],
127                                      capture_output=True, text=True, check=True)
128            result = json.loads(restored.stdout)
129            self.assertTrue(result["rolled_back"])
130            self.assertEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
131            self.assertEqual(verify(previous / "next-monitor.pyz")["sha256"], next_sha)
132            with self.assertRaisesRegex(ValueError, "commit or rollback"):
133                uninstall(target)
134            planned = commit(target, plan=True)
135            self.assertTrue(planned["would_commit"])
136            accepted = subprocess.run([sys.executable, str(BUILDER), "commit", "--target", str(target),
137                                       "--if-active-sha256", old["sha256"],
138                                       "--if-previous-sha256", next_sha],
139                                      capture_output=True, text=True, check=True)
140            self.assertTrue(json.loads(accepted.stdout)["committed"])
141            self.assertFalse(previous.exists())
142            self.assertTrue(uninstall(target, if_active_sha256=old["sha256"])["removed"])
143
144    def test_update_activation_failure_restores_installed_client(self):
145        with tempfile.TemporaryDirectory() as directory:
146            root = Path(directory)
147            first = root / "first" / "monitor.pyz"
148            first.parent.mkdir()
149            old = build(first)
150            candidate = self._candidate(first, root / "second" / "monitor.pyz")
151            next_sha = verify(candidate)["sha256"]
152            target = root / "optional-monitor"
153            install(first, target, if_candidate_sha256=old["sha256"])
154            original = os.rename
155            calls = 0
156
157            def fail_activation(source, destination):
158                nonlocal calls
159                calls += 1
160                if calls == 2:
161                    raise OSError("activation failed")
162                return original(source, destination)
163
164            with mock.patch.object(BUILDER_MODULE.os, "rename", side_effect=fail_activation):
165                with self.assertRaisesRegex(OSError, "activation failed"):
166                    update(candidate, target, if_current_sha256=old["sha256"],
167                           if_candidate_sha256=next_sha)
168            self.assertEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
169            self.assertFalse((root / "optional-monitor.previous").exists())
170            self.assertFalse(list(root.glob(".strata-monitor-install-*")))
171
172            original_stage = BUILDER_MODULE._stage_copy
173
174            def change_active_during_copy(bundle, report, destination):
175                stage = original_stage(bundle, report, destination)
176                active_bundle = destination / "monitor.pyz"
177                with zipfile.ZipFile(active_bundle, "a") as archive:
178                    archive.comment = b"external owner edit"
179                manifest = active_bundle.with_name(active_bundle.name + ".manifest.json")
180                current = json.loads(manifest.read_text())
181                current["sha256"] = hashlib.sha256(active_bundle.read_bytes()).hexdigest()
182                manifest.write_text(json.dumps(current))
183                return stage
184
185            with mock.patch.object(BUILDER_MODULE, "_stage_copy", side_effect=change_active_during_copy):
186                with self.assertRaisesRegex(ValueError, "changed during copy"):
187                    update(candidate, target, if_current_sha256=old["sha256"],
188                           if_candidate_sha256=next_sha)
189            self.assertNotEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
190            self.assertFalse((root / "optional-monitor.previous").exists())
191            self.assertFalse(list(root.glob(".strata-monitor-install-*")))
192
193    def test_offline_install_plan_and_remove_touch_only_monitor_files(self):
194        with tempfile.TemporaryDirectory() as directory:
195            root = Path(directory)
196            bundle = root / "portable-client.pyz"
197            built = build(bundle)
198            target = root / "optional-monitor"
199            preview = subprocess.run([sys.executable, str(BUILDER), "install", str(bundle),
200                                      "--target", str(target), "--plan"],
201                                     capture_output=True, text=True, check=True)
202            planned = json.loads(preview.stdout)
203            self.assertTrue(planned["would_install"])
204            self.assertFalse(target.exists())
205            with self.assertRaisesRegex(ValueError, "preview again"):
206                install(bundle, target)
207            with self.assertRaisesRegex(ValueError, "preview again"):
208                install(bundle, target, if_candidate_sha256="0" * 64)
209            self.assertFalse(target.exists())
210            installed_run = subprocess.run([sys.executable, str(BUILDER), "install", str(bundle),
211                                            "--target", str(target),
212                                            "--if-candidate-sha256", planned["sha256"]],
213                                           capture_output=True, text=True, check=True)
214            installed = json.loads(installed_run.stdout)
215            self.assertTrue(installed["installed"])
216            self.assertEqual(verify(target / bundle.name)["sha256"], built["sha256"])
217            self.assertEqual({p.name for p in target.iterdir()},
218                             {bundle.name, bundle.name + ".manifest.json"})
219            if os.name == "posix":
220                self.assertEqual(target.stat().st_mode & 0o077, 0)
221                self.assertEqual((target / bundle.name).stat().st_mode & 0o077, 0)
222            portable = subprocess.run([sys.executable, "-I", str(target / bundle.name), "logs", "--help"],
223                                      cwd=directory, capture_output=True, text=True, check=True,
224                                      encoding="utf-8", errors="replace")   # (the help text has non-ASCII characters; Windows would read it as cp1252)
225            self.assertIn("--follow", portable.stdout)
226            extra = target / "user-notes.txt"
227            extra.write_text("keep me")
228            with self.assertRaisesRegex(ValueError, "unexpected"):
229                uninstall(target)
230            self.assertTrue(extra.exists())
231            extra.unlink()
232            preview_remove = subprocess.run([sys.executable, str(BUILDER), "uninstall",
233                                             "--target", str(target), "--plan"],
234                                            capture_output=True, text=True, check=True)
235            self.assertTrue(json.loads(preview_remove.stdout)["would_remove"])
236            self.assertTrue(target.exists())
237            with self.assertRaisesRegex(ValueError, "preview again"):
238                uninstall(target)
239            with self.assertRaisesRegex(ValueError, "preview again"):
240                uninstall(target, if_active_sha256="0" * 64)
241            self.assertTrue(target.exists())
242            removal = subprocess.run([sys.executable, str(BUILDER), "uninstall", "--target",
243                                      str(target), "--if-active-sha256",
244                                      json.loads(preview_remove.stdout)["sha256"]],
245                                     capture_output=True, text=True, check=True)
246            self.assertTrue(json.loads(removal.stdout)["removed"])
247            self.assertFalse(target.exists())
248
249    def test_failed_copy_leaves_no_partial_install(self):
250        with tempfile.TemporaryDirectory() as directory:
251            root = Path(directory)
252            bundle = root / "monitor.pyz"
253            built = build(bundle)
254            target = root / "optional-monitor"
255            with mock.patch.object(BUILDER_MODULE.shutil, "copyfile", side_effect=OSError("disk full")):
256                with self.assertRaisesRegex(OSError, "disk full"):
257                    install(bundle, target, if_candidate_sha256=built["sha256"])
258            self.assertFalse(target.exists())
259            self.assertFalse(list(root.glob(".strata-monitor-install-*")))
260
261    def test_bundle_verification_rejects_large_or_linked_input(self):
262        with tempfile.TemporaryDirectory() as directory:
263            root = Path(directory)
264            bundle = root / "monitor.pyz"
265            build(bundle)
266            linked = root / "linked.pyz"
267            linked.symlink_to(bundle)
268            with self.assertRaisesRegex(ValueError, "bounded regular"):
269                verify(linked)
270            with bundle.open("ab") as stream:
271                stream.write(b"x" * (1024 * 1024))
272            with self.assertRaisesRegex(ValueError, "bounded regular"):
273                verify(bundle)
274            bundle = root / "unsigned.pyz"
275            build(bundle)
276            manifest = bundle.with_name(bundle.name + ".manifest.json")
277            forged = json.loads(manifest.read_text())
278            forged["publisher_signature"] = "pretend-signed"
279            manifest.write_text(json.dumps(forged))
280            with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
281                verify(bundle)
282            manifest.write_text("[]")
283            with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
284                verify(bundle)
285
286    def test_bundle_carries_every_module_its_entry_point_imports(self):
287        """The import closure of strata_cli.monitor_commands (lazy imports included) minus the launch package must be in the bundle."""
288        import ast
289        needed, todo = set(), ["strata_cli/monitor_commands.py"]
290        while todo:
291            name = todo.pop()
292            if name in needed:
293                continue
294            needed.add(name)
295            for node in ast.walk(ast.parse((ROOT / name).read_text(encoding="utf-8"))):
296                if isinstance(node, ast.ImportFrom) and node.module and node.module.split(".")[0] == "strata_cli":
297                    names = [node.module] + [node.module + "." + a.name for a in node.names]
298                elif isinstance(node, ast.Import):
299                    names = [a.name for a in node.names]
300                else:
301                    continue
302                for module in names:
303                    path = module.replace(".", "/") + ".py"
304                    if module.startswith("strata_cli") and (ROOT / path).is_file() and "/launch/" not in path:
305                        todo.append(path)
306        self.assertLessEqual(needed, set(BUILDER_MODULE.SOURCES))
307
308    def test_plain_monitor_runs_when_the_launch_package_is_not_bundled(self):
309        """The pyz has no strata_cli.launch: interactive `monitor` must fall back to the plain Monitor, not fail."""
310        from strata_cli import monitor as monitor_module
311        from strata_cli import monitor_commands
312        ran = []
313        blocked = {"strata_cli.launch.monitor_ext": None}       # None in sys.modules makes the import raise ImportError
314        with mock.patch.dict(sys.modules, blocked),                 mock.patch.object(monitor_module.MonitorApp, "run", lambda self: ran.append(self.endpoint.base_url)),                 mock.patch.object(sys.stdout, "isatty", return_value=True):
315            code = monitor_commands.main(["monitor", "--url", "http://127.0.0.1:9"])
316        self.assertEqual((code, ran), (0, ["http://127.0.0.1:9"]))
317
318    def test_versioned_manifest_keeps_legacy_update_and_rollback_available(self):
319        with tempfile.TemporaryDirectory() as directory:
320            root = Path(directory)
321            current = root / "monitor.pyz"
322            modern = root / "next-monitor.pyz"
323            previous = root / "previous-monitor.pyz"
324            build(modern)
325            old_visual = root / "visual-monitor.pyz"
326            for old_bundle, version in ((current, 1), (previous, 2), (old_visual, 3)):
327                with zipfile.ZipFile(modern) as source, zipfile.ZipFile(old_bundle, "w", zipfile.ZIP_DEFLATED) as legacy:
328                    for item in source.infolist():
329                        if item.filename not in ("strata_cli/detail_dashboard.py", "strata_cli/nav.py",
330                                                 "strata_cli/consoleinfo.py", "strata_cli/overview.py") and \
331                                (version >= 3 or item.filename != "strata_cli/dashboard.py") and \
332                                (version != 1 or item.filename != "LICENSE"):
333                            legacy.writestr(item, source.read(item.filename))
334                report = json.loads((root / "next-monitor.pyz.manifest.json").read_text())
335                report["schema_version"] = version
336                report["bundle"] = old_bundle.name
337                report["sha256"] = hashlib.sha256(old_bundle.read_bytes()).hexdigest()
338                del report["files"]["strata_cli/detail_dashboard.py"]
339                del report["files"]["strata_cli/nav.py"]
340                del report["files"]["strata_cli/consoleinfo.py"]
341                del report["files"]["strata_cli/overview.py"]
342                if version < 3:
343                    del report["files"]["strata_cli/dashboard.py"]
344                if version == 1:
345                    del report["files"]["LICENSE"]
346                    for field in ("compatibility", "license", "license_file"):
347                        del report[field]
348                old_bundle.with_name(old_bundle.name + ".manifest.json").write_text(json.dumps(report))
349            self.assertEqual(verify(current)["schema_version"], 1)
350            self.assertEqual(verify(previous)["schema_version"], 2)
351            self.assertEqual(verify(old_visual)["schema_version"], 3)
352            self.assertEqual(verify(modern)["schema_version"], 6)
353            with zipfile.ZipFile(modern) as archive:
354                self.assertIn(b"MIT License", archive.read("LICENSE"))
355                self.assertIn(b"render_dashboard", archive.read("strata_cli/dashboard.py"))
356                self.assertIn(b"render_detail_dashboard", archive.read("strata_cli/detail_dashboard.py"))
357            target = root / "optional-monitor"
358            install(current, target, if_candidate_sha256=verify(current)["sha256"])
359            preview = update(modern, target, plan=True)
360            self.assertTrue(preview["would_update"])
361            self.assertTrue(update(modern, target, if_current_sha256=preview["current_sha256"],
362                                   if_candidate_sha256=preview["candidate_sha256"])["updated"])
363            self.assertEqual(verify(target / modern.name)["schema_version"], 6)
364            self.assertEqual(verify(root / "optional-monitor.previous" / current.name)["schema_version"], 1)
365            planned = rollback(target, plan=True)
366            self.assertTrue(rollback(target, if_active_sha256=planned["active_sha256"],
367                                     if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
368            self.assertEqual(verify(target / current.name)["schema_version"], 1)
369            second_target = root / "optional-monitor-from-v2"
370            install(previous, second_target, if_candidate_sha256=verify(previous)["sha256"])
371            preview = update(modern, second_target, plan=True)
372            self.assertTrue(update(modern, second_target,
373                                   if_current_sha256=preview["current_sha256"],
374                                   if_candidate_sha256=preview["candidate_sha256"])["updated"])
375            self.assertEqual(verify(second_target / modern.name)["schema_version"], 6)
376            planned = rollback(second_target, plan=True)
377            self.assertTrue(rollback(second_target, if_active_sha256=planned["active_sha256"],
378                                     if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
379            self.assertEqual(verify(second_target / previous.name)["schema_version"], 2)
380            third_target = root / "optional-monitor-from-v3"
381            install(old_visual, third_target, if_candidate_sha256=verify(old_visual)["sha256"])
382            preview = update(modern, third_target, plan=True)
383            self.assertTrue(update(modern, third_target,
384                                   if_current_sha256=preview["current_sha256"],
385                                   if_candidate_sha256=preview["candidate_sha256"])["updated"])
386            planned = rollback(third_target, plan=True)
387            self.assertTrue(rollback(third_target, if_active_sha256=planned["active_sha256"],
388                                     if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
389            self.assertEqual(verify(third_target / old_visual.name)["schema_version"], 3)
390
391    def test_manifest_compatibility_and_license_notice_are_checked(self):
392        with tempfile.TemporaryDirectory() as directory:
393            bundle = Path(directory) / "monitor.pyz"
394            built = build(bundle)
395            self.assertEqual(built["compatibility"], {"python_min": "3.10", "telemetry_schema": [1]})
396            self.assertEqual(built["license_file"], "LICENSE")
397            manifest = bundle.with_name(bundle.name + ".manifest.json")
398            edited = json.loads(manifest.read_text())
399            edited["compatibility"]["telemetry_schema"] = [2]
400            manifest.write_text(json.dumps(edited))
401            with self.assertRaisesRegex(ValueError, "compatibility or license"):
402                verify(bundle)
403            edited["schema_version"] = True
404            manifest.write_text(json.dumps(edited))
405            with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
406                verify(bundle)
407
408    def test_thin_bundle_and_source_share_one_shot_contract(self):
409        snapshot = {"schema_version": 1, "source": "test-server", "sampled_at": 1_790_000_000,
410                    "instance": {"id": "test-instance", "state": "ready"},
411                    "model": {"id": "fixture-model", "loaded": True},
412                    "work": {"active": 2, "queued": 1, "slots_effective": 4,
413                             "requests": [{"id": "r1", "state": "reading", "slot": 0,
414                                           "prompt_tokens": 200, "prompt_read": 50}]}}
415        paths = []
416
417        class Handler(BaseHTTPRequestHandler):
418            def do_GET(self):
419                paths.append(self.path)
420                body = json.dumps(snapshot).encode()
421                self.send_response(200)
422                self.send_header("Content-Type", "application/json")
423                self.send_header("Content-Length", str(len(body)))
424                self.end_headers()
425                self.wfile.write(body)
426
427            def log_message(self, *_args):
428                pass
429
430        server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
431        thread = threading.Thread(target=server.serve_forever, daemon=True)
432        thread.start()
433        try:
434            with tempfile.TemporaryDirectory() as directory:
435                bundle = Path(directory) / "strata-monitor.pyz"
436                subprocess.run([sys.executable, str(BUILDER), "build", str(bundle)], check=True,
437                               capture_output=True, text=True)
438                subprocess.run([sys.executable, str(BUILDER), "verify", str(bundle)], check=True,
439                               capture_output=True, text=True)
440                self.assertLess(bundle.stat().st_size, 96 * 1024)
441                with zipfile.ZipFile(bundle) as archive:
442                    self.assertIn(b"MIT License", archive.read("LICENSE"))
443                    self.assertIn("strata_cli/dashboard.py", archive.namelist())
444                if importlib.util.find_spec("textual") is not None:
445                    import_check = subprocess.run(
446                        [sys.executable, "-I", "-c",
447                         "import sys; sys.path.insert(0, " + repr(str(bundle)) + "); "
448                         "from strata_cli.monitor import MonitorApp; print(MonitorApp.__name__)"],
449                        cwd=directory, capture_output=True, text=True, check=True)
450                    self.assertEqual(import_check.stdout.strip(), "MonitorApp")
451                url = f"http://127.0.0.1:{server.server_port}"
452                source_output = io.StringIO()
453                with redirect_stdout(source_output):
454                    self.assertEqual(source_main(["monitor", "--once", "--json", "--url", url]), 0)
455                clean_env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME")}
456                clean_env["STRATA_CONNECTION_DIR"] = str(Path(directory) / "connections")
457                portable = subprocess.run([sys.executable, "-S", str(bundle), "monitor", "--once", "--json",
458                                           "--url", url], cwd=directory, env=clean_env, check=True,
459                                          capture_output=True, text=True)
460                self.assertEqual(json.loads(portable.stdout), json.loads(source_output.getvalue()))
461                bare_source = subprocess.run([sys.executable, "-S", str(ROOT / "strata.py"), "monitor",
462                                              "--once", "--json", "--url", url], cwd=directory, env=clean_env,
463                                             check=True, capture_output=True, text=True)
464                self.assertEqual(json.loads(bare_source.stdout), json.loads(portable.stdout))
465                status = subprocess.run([sys.executable, "-S", str(bundle), "status", "--json", "--url", url],
466                                        cwd=directory, env=clean_env, check=True, capture_output=True, text=True)
467                self.assertEqual(json.loads(status.stdout)["snapshot"]["work"]["active"], 2)
468                saved = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list", "--json"],
469                                       cwd=directory, env=clean_env, check=True, capture_output=True, text=True)
470                self.assertEqual(json.loads(saved.stdout)["connections"], [])
471                quiet_saved = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list", "--quiet"],
472                                             cwd=directory, env=clean_env, check=True,
473                                             capture_output=True, text=True)
474                self.assertEqual((quiet_saved.stdout, quiet_saved.stderr), ("", ""))
475                quiet_json = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list",
476                                             "--quiet", "--json"], cwd=directory, env=clean_env,
477                                            check=True, capture_output=True, text=True)
478                self.assertEqual(json.loads(quiet_json.stdout)["connections"], [])
479                self.assertEqual(paths, ["/v1/telemetry"] * 4)
480                data = bytearray(bundle.read_bytes())
481                data[-1] ^= 1
482                bundle.write_bytes(data)
483                broken = subprocess.run([sys.executable, str(BUILDER), "verify", str(bundle)],
484                                        capture_output=True, text=True)
485                self.assertEqual(broken.returncode, 1)
486                self.assertIn("SHA-256 mismatch", broken.stderr)
487        finally:
488            server.shutdown()
489            server.server_close()
490            thread.join(timeout=2)