"""Regression and property tests for fx-plugins fixes: - files._targets / files.find / files.paths accepting os.PathLike (weird.md #6) - colab._AssignmentPayload accepting int enums and machineShape (vent #85) - view.view_diff resolving jj workspace root from subdirs/files (vent #78) - run.save_jobs / restore_jobs preserving Job.cell across restores (ponpuvzl) """ from __future__ import annotations import asyncio import json import os import pickle import shutil import subprocess import sys import tempfile import unittest from pathlib import Path from unittest.mock import AsyncMock, patch ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "python")) sys.path.insert(0, str(ROOT / "test")) sys.path.insert(0, str(Path(__file__).resolve().parent)) import hypothesis_profiles # noqa: E402 from hypothesis import given, settings, strategies as st # noqa: E402 import albedo_capture # noqa: E402 from albedo_plugins import colab, files as files_plugin, run as run_plugin, view # noqa: E402 from job_wake_test import Owner # noqa: E402 import scratch # noqa: E402 scratch.claim("harness") class _CustomPath: def __init__(self, target: str) -> None: self._target = target def __fspath__(self) -> str: return self._target class FilesPathLikeTest(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(25)) @given( st.lists( st.tuples( st.sampled_from(["str", "path", "custom"]), st.text( alphabet="abcdefghijklmnopqrstuvwxyz0123456789_-/", min_size=1, max_size=12, ), ), min_size=1, max_size=4, ), st.booleans(), ) def test_targets_accepts_str_pathlike_and_mixed_sequences( self, items: list[tuple[str, str]], single: bool ) -> None: def make(kind: str, raw: str) -> str | os.PathLike[str]: if kind == "str": return raw if kind == "path": return Path(raw) return _CustomPath(raw) if single: kind, raw = items[0] arg: object = make(kind, raw) expected = [Path(raw).expanduser()] else: arg = [make(kind, raw) for kind, raw in items] expected = [Path(raw).expanduser() for _, raw in items] self.assertEqual(files_plugin._targets(arg), expected) # type: ignore[arg-type] def test_find_and_paths_accept_path_and_pathlike_in_kernel(self) -> None: owner = Owner(["files", "run"]) self.addCleanup(owner.close) owner.wait_for(lambda f: f.get("type") == "ready") ws = Path(owner.workspace) (ws / "sub" / "nested").mkdir(parents=True) (ws / "other").mkdir() (ws / "sub" / "nested" / "hit.txt").write_text("needle-one\n") (ws / "other" / "two.txt").write_text("needle-two\n") owner.send( { "type": "execute", "id": "c1", "code": ( "from pathlib import Path\n" "class Custom:\n" " def __init__(self, p): self.p = p\n" " def __fspath__(self): return self.p\n" "a = await files.find('needle', Path('sub'))\n" "b = await files.find('needle', [Path('sub'), 'other'])\n" "c = await files.find('needle', Custom('sub'))\n" "d = await files.paths('*.txt', Path('sub'))\n" "e = files.read(Path('sub/nested/hit.txt'))\n" "f = files.ls(Path('sub/nested'))\n" "print(len(a), len(b), len(c), list(d), 'needle-one' in e, list(f))" ), } ) done = owner.wait_for( lambda f: f.get("type") == "done" and f.get("id") == "c1", timeout=30 ) self.assertEqual(done["status"], "ok", done) self.assertEqual( done["output"].strip(), "1 2 1 ['sub/nested/hit.txt'] True ['hit.txt']", ) VARIANT_CASES = [ ("CPU", "CPU"), ("GPU", "GPU"), ("TPU", "TPU"), (0, "CPU"), (1, "GPU"), (2, "TPU"), ] SHAPE_CASES = [ ("standard", "standard", "standard"), ("high", "high", "high"), ("highmem", "highmem", "high"), (0, "standard", "standard"), (1, "highmem", "high"), ] class ColabAssignmentEnumTest(unittest.IsolatedAsyncioTestCase): def setUp(self) -> None: self._env = patch.dict(os.environ, {"HOME": tempfile.mkdtemp()}) self._env.start() self.addCleanup(self._env.stop) @settings(max_examples=hypothesis_profiles.cases(30)) @given( st.sampled_from(VARIANT_CASES), st.sampled_from(SHAPE_CASES), st.sampled_from(["shape", "machineShape", "both"]), st.sampled_from([None, "T4", "v5e1"]), ) def test_valid_variant_and_shape_variants_normalize( self, variant_case: tuple[object, str], shape_case: tuple[object, str, str], shape_key: str, accelerator: str | None, ) -> None: raw_variant, expected_variant = variant_case raw_shape, expected_shape, expected_mem = shape_case payload: dict[str, object] = { "endpoint": "ep-1", "variant": raw_variant, } if accelerator is not None: payload["accelerator"] = accelerator if shape_key == "shape": payload["shape"] = raw_shape elif shape_key == "machineShape": payload["machineShape"] = raw_shape else: payload["machineShape"] = raw_shape payload["shape"] = "standard" if expected_mem == "high" else "highmem" inst = colab._parse_instance(payload) self.assertEqual(inst.variant, expected_variant) self.assertEqual(inst.shape, expected_shape) self.assertEqual(inst.mem, expected_mem) self.assertEqual(inst.gpu, accelerator if expected_variant == "GPU" else None) self.assertEqual(inst.tpu, accelerator if expected_variant == "TPU" else None) @settings(max_examples=hypothesis_profiles.cases(20)) @given( st.one_of( st.integers().filter(lambda x: x not in (0, 1, 2)), st.booleans(), st.lists(st.integers(), max_size=2), ), st.one_of( st.integers().filter(lambda x: x not in (0, 1)), st.booleans(), st.lists(st.integers(), max_size=2), ), st.sampled_from(["shape", "machineShape"]), ) def test_invalid_variant_and_shape_reject_without_leaking_token( self, bad_variant: object, bad_shape: object, shape_key: str ) -> None: secret = "secret-proxy-token-xyz" with self.assertRaises(colab.ColabError) as cm_var: colab._parse_instance( { "endpoint": "ep-1", "variant": bad_variant, "runtimeProxyInfo": {"token": secret}, } ) self.assertIn("variant", str(cm_var.exception)) self.assertNotIn(secret, str(cm_var.exception)) with self.assertRaises(colab.ColabError) as cm_shape: colab._parse_instance( { "endpoint": "ep-1", shape_key: bad_shape, "runtimeProxyInfo": {"token": secret}, } ) self.assertIn(shape_key, str(cm_shape.exception)) self.assertNotIn(secret, str(cm_shape.exception)) async def test_launch_and_instances_accept_int_variant_and_machine_shape( self, ) -> None: # Exact shape returned by Google Colab /tun/m/assignments and /tun/m/assign (vent 85). raw_assignment = { "endpoint": "gpu-t4-s-usw4b1-ejyocgenurxd", "variant": 1, "machineShape": 1, "accelerator": "T4", "runtimeProxyInfo": { "url": "https://vm.colab.googleusercontent.com", "token": "tok-t4", "tokenExpiresInSeconds": 3600, }, } list_body = b")]}'\n" + json.dumps({"assignments": [raw_assignment]}).encode() assign_body = b")]}'\n" + json.dumps({"assignment": raw_assignment}).encode() with ( patch.object( colab, "_account", AsyncMock(return_value={"access": "t", "email": "e@x"}), ), patch.object(colab, "_route", AsyncMock(return_value=None)), ): with patch.object(colab, "_send", return_value=(200, list_body)): [listed] = await colab.instances() self.assertEqual( (listed.variant, listed.gpu, listed.shape, listed.mem), ("GPU", "T4", "highmem", "high"), ) with patch.object(colab, "_send", return_value=(200, assign_body)): launched = await colab.launch(gpu="T4", mem="standard") self.assertEqual( (launched.variant, launched.gpu, launched.shape, launched.mem), ("GPU", "T4", "highmem", "high"), ) class ViewJjWorkspaceTest(unittest.TestCase): @staticmethod def _reference_jj_root(start: Path) -> Path | None: resolved = start.resolve() for directory in (resolved, *resolved.parents): if (directory / ".git").exists(): return None if (directory / ".jj").is_dir(): return directory return None @settings(max_examples=hypothesis_profiles.cases(25)) @given( st.lists( st.sampled_from(["none", "jj", "git", "both"]), min_size=1, max_size=4, ), st.booleans(), ) def test_jj_root_matches_vcs_precedence_for_abs_and_relative_cwd( self, levels: list[str], from_leaf_cwd: bool ) -> None: with tempfile.TemporaryDirectory() as tmp: cur = Path(tmp).resolve() for idx, kind in enumerate(levels): cur = cur / f"d{idx}" cur.mkdir() if kind in ("jj", "both"): (cur / ".jj").mkdir() if kind in ("git", "both"): (cur / ".git").mkdir() expected = self._reference_jj_root(cur) if from_leaf_cwd: prev = Path.cwd() try: os.chdir(cur) self.assertEqual(view._jj_root(Path(".")), expected) finally: os.chdir(prev) else: self.assertEqual(view._jj_root(cur), expected) @unittest.skipUnless(shutil.which("jj"), "jj is not installed") def test_view_diff_in_jj_only_worktree_from_subdir_file_and_nested_cwd( self, ) -> None: with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) main_repo = root / "main" wt_repo = root / "wt" main_repo.mkdir() subprocess.run( ["jj", "git", "init"], cwd=main_repo, check=True, capture_output=True ) (main_repo / "sub" / "deep").mkdir(parents=True) (main_repo / "sub" / "deep" / "note.txt").write_text("line1\nline2\n") subprocess.run( ["jj", "commit", "-m", "init"], cwd=main_repo, check=True, capture_output=True, ) subprocess.run( ["jj", "workspace", "add", "--no-colocate", str(wt_repo)], cwd=main_repo, check=True, capture_output=True, ) # Modify tracked file inside subdirectory of jj-only worktree (no .git). assert not (wt_repo / ".git").exists() (wt_repo / "sub" / "deep" / "note.txt").write_text("line1\nchanged\n") fake_bin = root / "bin" fake_bin.mkdir() renderer = fake_bin / "albedo-render" png_stub = b"\x89PNG\r\n\x1a\n" img_path = root / "page.png" img_path.write_bytes(png_stub) renderer.write_text( f"#!/usr/bin/env python3\n" f"import sys\n" f"diff_text = open(sys.argv[1]).read()\n" f"assert 'changed' in diff_text, diff_text\n" f"print('language diff')\n" f"print('image {img_path} 1 2 100x20')\n" ) renderer.chmod(0o755) owner = Owner( ["files", "run", "view"], env={"PATH": f"{fake_bin}:{os.environ['PATH']}"}, ) self.addCleanup(owner.close) owner.wait_for(lambda f: f.get("type") == "ready") # Override bundled RENDERER if present so fake_bin renderer runs without native build dependency. owner.send( { "type": "execute", "id": "v1", "code": ( "import os, albedo_plugins.view as _v\n" f"_v.RENDERER = Path({str(renderer)!r})\n" f"os.chdir({str(wt_repo)!r})\n" "d_root = await view_diff('.')\n" "d_sub = await view_diff('sub')\n" "d_file = await view_diff('sub/deep/note.txt')\n" "d_path = await view_diff(Path('sub/deep'))\n" f"os.chdir({str(wt_repo / 'sub')!r})\n" "d_nested = await view_diff('.')\n" "print('OK', 'diff' in d_root, 'diff' in d_sub, 'diff' in d_file, 'diff' in d_path, 'diff' in d_nested)" ), } ) done = owner.wait_for( lambda f: f.get("type") == "done" and f.get("id") == "v1", timeout=30 ) self.assertEqual(done["status"], "ok", done) self.assertIn("OK True True True True True", done["output"]) class RestoredJobCellTest(unittest.TestCase): def setUp(self) -> None: self.tmpdir = tempfile.TemporaryDirectory() self.addCleanup(self.tmpdir.cleanup) prev_spill = albedo_capture.SPILL_DIR albedo_capture.SPILL_DIR = self.tmpdir.name self.addCleanup(setattr, albedo_capture, "SPILL_DIR", prev_spill) def test_restored_job_preserves_cell_and_resaves_without_attribute_error( self, ) -> None: loop = asyncio.new_event_loop() self.addCleanup(loop.close) prev_loop = getattr(run_plugin, "loop", None) prev_jobs = dict(run_plugin.jobs) prev_retained = run_plugin.retained.copy() run_plugin.loop = loop run_plugin.jobs.clear() run_plugin.retained.clear() self.addCleanup( lambda: ( setattr(run_plugin, "loop", prev_loop), run_plugin.jobs.clear(), run_plugin.jobs.update(prev_jobs), run_plugin.retained.clear(), run_plugin.retained.update(prev_retained), ) ) cap_with_cell = albedo_capture.Capture("job-with-cell", "job") cap_with_cell.write("hello\n") cap_with_cell.end_spill() cap_legacy = albedo_capture.Capture("job-legacy", "job") cap_legacy.write("legacy\n") cap_legacy.end_spill() out_with_cell = cap_with_cell.persist() out_legacy = cap_legacy.persist() assert out_with_cell is not None and out_legacy is not None book = [ { "id": "job-with-cell", "cell": "cell-abc", "argv": ["echo", "hi"], "command": "echo hi", "exit_code": 0, "timed_out": False, "duration": 0.1, "started": 1000.0, "service": False, "traced": True, "read": True, "output": out_with_cell, }, { "id": "job-legacy", # Pre-ponpuvzl saved job dict with no "cell" key. "argv": ["echo", "old"], "command": "echo old", "exit_code": 0, "timed_out": False, "duration": 0.2, "started": 1001.0, "service": False, "traced": True, "read": False, "output": out_legacy, }, ] run_plugin.restore_jobs(book, {}) j1 = run_plugin.jobs["job-with-cell"] j2 = run_plugin.jobs["job-legacy"] self.assertEqual(j1.cell, "cell-abc") self.assertIsNone(j2.cell) self.assertEqual(run_plugin.job_record(j1)["parent_id"], "cell-abc") self.assertIsNone(run_plugin.job_record(j2)["parent_id"]) # Re-saving restored jobs must not raise AttributeError: Job has no attribute cell. state_path = os.path.join(self.tmpdir.name, "session.state") resaved = run_plugin.save_jobs(state_path) self.assertEqual([item["cell"] for item in resaved], ["cell-abc", None]) # Pickling a restored job resolves back to the live restored handle via _revive. revived = pickle.loads(pickle.dumps(j1)) self.assertIs(revived, j1) run_plugin.jobs.clear() ended = pickle.loads(pickle.dumps(j1)) self.assertIsInstance(ended, run_plugin.EndedJob) if __name__ == "__main__": unittest.main()