Stevesolun commited on
Commit
482a9b2
·
verified ·
1 Parent(s): 23fda92

Sync ctx b62b78d (part 4)

Browse files

GitHub commit: b62b78d704ec54b3ff43e333982eef713a33c8df

src/tests/test_ci_classifier.py CHANGED
@@ -434,7 +434,7 @@ def test_no_test_policy_requires_tests_for_release_sync_artifact_scripts() -> No
434
  for script in (
435
  "scripts/sync_huggingface.py",
436
  "scripts/pack_full_wiki_tar.py",
437
- "scripts/graph_artifact_guard.py",
438
  ):
439
  result = evaluate_policy([script], (), {script: "+print('changed')\n"})
440
 
@@ -449,20 +449,15 @@ def test_ci_workflows_default_to_read_only_token_permissions() -> None:
449
  assert "\npermissions:\n contents: read\n" in workflow
450
 
451
 
452
- def test_graph_artifact_job_uses_release_asset_fallback_for_lfs_budget() -> None:
453
  workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
454
 
455
- assert "Resolve graph artifacts from release assets or targeted LFS" in workflow
456
- assert "Resolving graph artifacts from release cache, or targeted Git LFS" in workflow
457
- assert 'tag_name.startswith("graph-artifacts-")' in workflow
458
- assert "sha256:{expected_oid} size:{expected_size}" in workflow
459
- assert "Pointer for {path_name} is not in release cache" in workflow
460
- assert "searching release caches before targeted Git LFS" in workflow
461
- assert '"git", "lfs", "pull", "--include", path_name' in workflow
462
- assert "GIT_LFS_ACTIVITYTIMEOUT" in workflow
463
- assert "Hydrated {path_name} from" in workflow
464
- assert "graph/wiki-graph-runtime.tar.gz" in workflow
465
  assert "python src/validate_graph_artifacts.py" in workflow
 
466
  assert "validating pointer metadata only" not in workflow
467
 
468
 
@@ -515,13 +510,11 @@ def test_publish_static_gate_uses_canonical_python_target() -> None:
515
  def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
516
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
517
 
518
- assert "Resolve release graph artifacts from release assets" in workflow
519
- assert "Resolving graph artifacts from release cache, or targeted Git LFS" in workflow
520
- assert "searching release caches before targeted Git LFS" in workflow
521
- assert '"git", "lfs", "pull", "--include", path_name' in workflow
522
- assert "verify_hydrated_file(graph_tar, expected_oid, expected_size)" in workflow
523
- assert 'tag_name.startswith("graph-artifacts-")' in workflow
524
- assert "sha256:{expected_oid} size:{expected_size}" in workflow
525
  assert "Validate release graph artifacts" in workflow
526
  assert "python src/validate_graph_artifacts.py" in workflow
527
  assert "python src/update_repo_stats.py --check" in workflow
 
434
  for script in (
435
  "scripts/sync_huggingface.py",
436
  "scripts/pack_full_wiki_tar.py",
437
+ "scripts/graph_release_manifest.py",
438
  ):
439
  result = evaluate_policy([script], (), {script: "+print('changed')\n"})
440
 
 
449
  assert "\npermissions:\n contents: read\n" in workflow
450
 
451
 
452
+ def test_graph_artifact_job_uses_exact_release_manifest() -> None:
453
  workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
454
 
455
+ assert "Resolve graph artifacts from exact release manifest" in workflow
456
+ assert (
457
+ "python scripts/graph_release_manifest.py hydrate --manifest graph/release-artifacts.json"
458
+ ) in workflow
 
 
 
 
 
 
459
  assert "python src/validate_graph_artifacts.py" in workflow
460
+ assert "git lfs" not in workflow.lower()
461
  assert "validating pointer metadata only" not in workflow
462
 
463
 
 
510
  def test_publish_workflow_validates_and_uploads_graph_assets() -> None:
511
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
512
 
513
+ assert "Resolve release graph artifacts from exact release manifest" in workflow
514
+ assert (
515
+ "python scripts/graph_release_manifest.py hydrate --manifest graph/release-artifacts.json"
516
+ ) in workflow
517
+ assert "git lfs" not in workflow.lower()
 
 
518
  assert "Validate release graph artifacts" in workflow
519
  assert "python src/validate_graph_artifacts.py" in workflow
520
  assert "python src/update_repo_stats.py --check" in workflow
src/tests/test_ci_preflight.py CHANGED
@@ -2,6 +2,7 @@ from __future__ import annotations
2
 
3
  from datetime import datetime
4
  import hashlib
 
5
  import json
6
  import shlex
7
  from pathlib import Path
@@ -15,6 +16,7 @@ from scripts.ci_preflight import _run_no_test_policy_for_files
15
  from scripts.ci_preflight import Check
16
  from scripts.ci_preflight import PUBLIC_DOCS_TRACKER_TESTS
17
  from scripts.ci_preflight import select_checks
 
18
 
19
 
20
  def _checks_for(files: list[str], *, profile: str = "pr") -> list[Check]:
@@ -52,6 +54,11 @@ def _workflow_unit_linux_coverage_command() -> list[str]:
52
  return shlex.split(run)
53
 
54
 
 
 
 
 
 
55
  def test_pr_docs_workflow_tracker_tests_match_preflight() -> None:
56
  assert _workflow_docs_tracker_tests() == PUBLIC_DOCS_TRACKER_TESTS
57
 
@@ -82,6 +89,11 @@ def test_preflight_runs_source_gates_for_source_changes() -> None:
82
  for check in _checks_for(["src/ctx/adapters/generic/loop.py"])
83
  if check.name == "unit-linux equivalent"
84
  )
 
 
 
 
 
85
  lanes = local_fast_gate.group_checks(_checks_for(["src/ctx/adapters/generic/loop.py"]))
86
  lanes_by_name = {
87
  lane.name: [check.name for check in lane.checks]
@@ -97,7 +109,7 @@ def test_preflight_runs_source_gates_for_source_changes() -> None:
97
  assert "A-Z canary" in names
98
  assert "clean host contract" in names
99
  assert lanes_by_name == {
100
- "unit": ["unit-linux equivalent"],
101
  "canary": ["A-Z canary"],
102
  "contract": ["contract compatibility local"],
103
  "clean-host": ["clean host contract"],
@@ -109,6 +121,26 @@ def test_preflight_runs_source_gates_for_source_changes() -> None:
109
  "--max-worker-restart=0",
110
  )
111
  assert workflow_unit_command[-4:] == list(unit_check.argv[-4:])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
 
114
  def test_xdist_auto_worker_count_is_resource_capped(monkeypatch) -> None:
@@ -150,12 +182,20 @@ def test_preflight_runs_graph_validation_for_graph_artifacts() -> None:
150
  graph_lane = next(lane for lane in lanes if lane.name == "graph")
151
  graph_names = [check.name for check in graph_lane.checks]
152
 
153
- assert names.index("hydrate graph LFS") < names.index("graph artifact validation")
154
  assert "graph artifact validation" in names
155
  assert "no-test policy" not in names
156
  assert "unit-linux equivalent" not in names
157
- assert graph_names == ["hydrate graph LFS", "graph artifact validation"]
158
- assert graph_lane.checks[0].argv[1] == "scripts/ci_preflight.py"
 
 
 
 
 
 
 
 
159
 
160
 
161
  def test_local_fast_whitespace_check_runs_against_base() -> None:
@@ -450,72 +490,120 @@ def test_local_fast_kept_worktree_paths_remain_in_summary(monkeypatch, tmp_path:
450
  assert removed == []
451
 
452
 
453
- def test_preflight_graph_lfs_pointer_verification(tmp_path: Path, monkeypatch) -> None:
454
- monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
455
- artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
456
- artifact.parent.mkdir()
457
- payload = b"hydrated graph payload"
458
- expected_sha256 = hashlib.sha256(payload).hexdigest()
459
- artifact.write_text(
460
- "version https://git-lfs.github.com/spec/v1\n"
461
- f"oid sha256:{expected_sha256}\n"
462
- f"size {len(payload)}\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  encoding="utf-8",
464
  )
 
465
 
466
- pointer = ci_preflight._read_lfs_pointer(artifact)
467
 
468
- assert pointer == ci_preflight.LfsPointer(
469
- "graph/wiki-graph.tar.gz",
470
- expected_sha256,
471
- len(payload),
 
 
 
 
 
 
 
472
  )
473
- artifact.write_bytes(payload)
474
- ci_preflight._verify_hydrated_lfs_pointer(pointer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
 
 
 
 
 
 
 
 
 
476
 
477
- def test_preflight_graph_lfs_pull_uses_per_command_filters(
 
478
  tmp_path: Path,
479
  monkeypatch,
480
  ) -> None:
481
  monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
482
- monkeypatch.setattr(ci_preflight.shutil, "which", lambda _name: "/usr/bin/git")
483
- artifact = tmp_path / "graph" / "wiki-graph.tar.gz"
484
- artifact.parent.mkdir()
485
- artifact.write_text(
486
- f"version https://git-lfs.github.com/spec/v1\noid sha256:{'a' * 64}\nsize 1\n",
487
- encoding="utf-8",
 
488
  )
489
- calls: list[list[str]] = []
490
-
491
- class Result:
492
- returncode = 0
493
-
494
- def fake_run(argv: list[str], **_kwargs) -> Result:
495
- calls.append(argv)
496
- return Result()
497
-
498
- verified: list[ci_preflight.LfsPointer] = []
499
- monkeypatch.setattr(ci_preflight.subprocess, "run", fake_run)
500
- monkeypatch.setattr(ci_preflight, "_verify_hydrated_lfs_pointer", verified.append)
501
-
502
- assert ci_preflight.hydrate_graph_lfs_artifacts() == 0
503
-
504
- assert len(calls) == 1
505
- argv = calls[0]
506
- lfs_index = argv.index("lfs")
507
- assert argv[:lfs_index] == ["git", *ci_preflight.GIT_LFS_FILTER_CONFIG]
508
- assert argv[lfs_index:] == [
509
- "lfs",
510
- "pull",
511
- "--include",
512
- "graph/wiki-graph.tar.gz",
513
- "--exclude",
514
- "",
515
- ]
516
- assert verified == [
517
- ci_preflight.LfsPointer("graph/wiki-graph.tar.gz", "a" * 64, 1),
518
- ]
519
 
520
 
521
  def test_preflight_no_test_policy_invocation_uses_current_dirty_file_set() -> None:
@@ -600,7 +688,7 @@ def test_preflight_runs_browser_and_similarity_when_classified() -> None:
600
  graph_resolver_script = next(
601
  step["run"]
602
  for step in graph_steps
603
- if step.get("name") == "Resolve graph artifacts from release assets or targeted LFS"
604
  )
605
 
606
  assert "browser monitor security" in names
@@ -615,10 +703,8 @@ def test_preflight_runs_browser_and_similarity_when_classified() -> None:
615
  assert "similarity" in lane_names
616
  assert "browser" in lane_names
617
  assert "package" in lane_names
618
- assert "release_asset_wait_seconds = 300" in graph_resolver_script
619
- assert 'os.environ.get("GITHUB_EVENT_NAME") == "pull_request"' in graph_resolver_script
620
- assert "release_asset_wait_seconds = 0" in graph_resolver_script
621
- assert 'env.setdefault("GIT_LFS_CONCURRENTTRANSFERS", "1")' in graph_resolver_script
622
 
623
 
624
  def test_every_workflow_parses_under_the_strict_loader() -> None:
 
2
 
3
  from datetime import datetime
4
  import hashlib
5
+ import io
6
  import json
7
  import shlex
8
  from pathlib import Path
 
16
  from scripts.ci_preflight import Check
17
  from scripts.ci_preflight import PUBLIC_DOCS_TRACKER_TESTS
18
  from scripts.ci_preflight import select_checks
19
+ from ctx.core.graph import release_artifacts
20
 
21
 
22
  def _checks_for(files: list[str], *, profile: str = "pr") -> list[Check]:
 
54
  return shlex.split(run)
55
 
56
 
57
+ def _workflow_step_names(job: str) -> list[str]:
58
+ workflow = yaml.safe_load(Path(".github/workflows/test.yml").read_text(encoding="utf-8"))
59
+ return [str(step.get("name", "")) for step in workflow["jobs"][job]["steps"]]
60
+
61
+
62
  def test_pr_docs_workflow_tracker_tests_match_preflight() -> None:
63
  assert _workflow_docs_tracker_tests() == PUBLIC_DOCS_TRACKER_TESTS
64
 
 
89
  for check in _checks_for(["src/ctx/adapters/generic/loop.py"])
90
  if check.name == "unit-linux equivalent"
91
  )
92
+ unit_hydrate = next(
93
+ check
94
+ for check in _checks_for(["src/ctx/adapters/generic/loop.py"])
95
+ if check.name == "hydrate benchmark catalog"
96
+ )
97
  lanes = local_fast_gate.group_checks(_checks_for(["src/ctx/adapters/generic/loop.py"]))
98
  lanes_by_name = {
99
  lane.name: [check.name for check in lane.checks]
 
109
  assert "A-Z canary" in names
110
  assert "clean host contract" in names
111
  assert lanes_by_name == {
112
+ "unit": ["hydrate benchmark catalog", "unit-linux equivalent"],
113
  "canary": ["A-Z canary"],
114
  "contract": ["contract compatibility local"],
115
  "clean-host": ["clean host contract"],
 
121
  "--max-worker-restart=0",
122
  )
123
  assert workflow_unit_command[-4:] == list(unit_check.argv[-4:])
124
+ assert unit_hydrate.argv == (
125
+ "python",
126
+ "scripts/graph_release_manifest.py",
127
+ "hydrate",
128
+ "--manifest",
129
+ "graph/release-artifacts.json",
130
+ "--repo-root",
131
+ ".",
132
+ "--artifact",
133
+ "graph/wiki-graph-runtime.tar.gz",
134
+ )
135
+
136
+
137
+ @pytest.mark.parametrize("job", ["unit-linux", "test"])
138
+ def test_clean_checkout_test_jobs_hydrate_runtime_catalog_before_pytest(job: str) -> None:
139
+ names = _workflow_step_names(job)
140
+
141
+ assert names.index("Resolve benchmark catalog from exact release manifest") < names.index(
142
+ "Run tests with coverage gate" if job == "unit-linux" else "Run tests without coverage"
143
+ )
144
 
145
 
146
  def test_xdist_auto_worker_count_is_resource_capped(monkeypatch) -> None:
 
182
  graph_lane = next(lane for lane in lanes if lane.name == "graph")
183
  graph_names = [check.name for check in graph_lane.checks]
184
 
185
+ assert names.index("hydrate graph release assets") < names.index("graph artifact validation")
186
  assert "graph artifact validation" in names
187
  assert "no-test policy" not in names
188
  assert "unit-linux equivalent" not in names
189
+ assert graph_names == ["hydrate graph release assets", "graph artifact validation"]
190
+ assert graph_lane.checks[0].argv == (
191
+ "python",
192
+ "scripts/graph_release_manifest.py",
193
+ "hydrate",
194
+ "--manifest",
195
+ "graph/release-artifacts.json",
196
+ "--repo-root",
197
+ ".",
198
+ )
199
 
200
 
201
  def test_local_fast_whitespace_check_runs_against_base() -> None:
 
490
  assert removed == []
491
 
492
 
493
+ def _write_release_artifact_manifest(
494
+ root: Path,
495
+ *,
496
+ tracked_payload: bytes = b"tracked graph payload",
497
+ archive_payload: bytes = b"release archive payload",
498
+ ) -> Path:
499
+ manifest_path = root / "graph" / "release-artifacts.json"
500
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
501
+ payloads = {
502
+ "communities.json": tracked_payload,
503
+ "entity-overlays.jsonl": b"tracked overlay payload",
504
+ "skills-sh-catalog.json.gz": b"tracked catalog payload",
505
+ "wiki-graph-runtime.tar.gz": b"release runtime payload",
506
+ "wiki-graph.tar.gz": archive_payload,
507
+ }
508
+ specs = (
509
+ ("graph/communities.json", "communities.json", False),
510
+ ("graph/entity-overlays.jsonl", "entity-overlays.jsonl", False),
511
+ ("graph/skills-sh-catalog.json.gz", "skills-sh-catalog.json.gz", False),
512
+ ("graph/wiki-graph-runtime.tar.gz", "wiki-graph-runtime.tar.gz", True),
513
+ ("graph/wiki-graph.tar.gz", "wiki-graph.tar.gz", True),
514
+ )
515
+ manifest_path.write_text(
516
+ json.dumps(
517
+ {
518
+ "schema_version": 1,
519
+ "repository": "stevesolun/ctx",
520
+ "source_release_tag": "v1.0.21",
521
+ "artifacts": [
522
+ {
523
+ "path": path,
524
+ "asset_name": asset_name,
525
+ "size": len(payloads[asset_name]),
526
+ "sha256": hashlib.sha256(payloads[asset_name]).hexdigest(),
527
+ "hydrate": hydrate,
528
+ }
529
+ for path, asset_name, hydrate in specs
530
+ ],
531
+ }
532
+ )
533
+ + "\n",
534
  encoding="utf-8",
535
  )
536
+ return manifest_path
537
 
 
538
 
539
+ def test_preflight_hydrates_missing_archives_from_exact_release_url(
540
+ tmp_path: Path,
541
+ monkeypatch,
542
+ ) -> None:
543
+ monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
544
+ tracked_payload = b"tracked graph payload"
545
+ archive_payload = b"release archive payload"
546
+ manifest_path = _write_release_artifact_manifest(
547
+ tmp_path,
548
+ tracked_payload=tracked_payload,
549
+ archive_payload=archive_payload,
550
  )
551
+ tracked_assets = {
552
+ "communities.json": tracked_payload,
553
+ "entity-overlays.jsonl": b"tracked overlay payload",
554
+ "skills-sh-catalog.json.gz": b"tracked catalog payload",
555
+ }
556
+ for asset_name, payload in tracked_assets.items():
557
+ (tmp_path / "graph" / asset_name).write_bytes(payload)
558
+ release_assets = {
559
+ "wiki-graph-runtime.tar.gz": b"release runtime payload",
560
+ "wiki-graph.tar.gz": archive_payload,
561
+ }
562
+
563
+ requested_urls: list[str] = []
564
+
565
+ def fake_urlopen(url: str, *, timeout: int) -> io.BytesIO:
566
+ requested_urls.append(url)
567
+ assert timeout == 120
568
+ return io.BytesIO(release_assets[url.rsplit("/", 1)[-1]])
569
 
570
+ monkeypatch.setattr(release_artifacts.urllib.request, "urlopen", fake_urlopen)
571
+
572
+ release_artifacts.hydrate_and_verify(repo_root=tmp_path, manifest_path=manifest_path)
573
+ assert requested_urls == [
574
+ "https://github.com/stevesolun/ctx/releases/download/v1.0.21/wiki-graph-runtime.tar.gz",
575
+ "https://github.com/stevesolun/ctx/releases/download/v1.0.21/wiki-graph.tar.gz",
576
+ ]
577
+ assert (tmp_path / "graph" / "wiki-graph.tar.gz").read_bytes() == archive_payload
578
 
579
+
580
+ def test_preflight_fails_closed_on_existing_graph_artifact_tamper(
581
  tmp_path: Path,
582
  monkeypatch,
583
  ) -> None:
584
  monkeypatch.setattr(ci_preflight, "REPO_ROOT", tmp_path)
585
+ manifest_path = _write_release_artifact_manifest(tmp_path)
586
+ tracked = tmp_path / "graph" / "communities.json"
587
+ tracked.write_bytes(b"tampered")
588
+ monkeypatch.setattr(
589
+ release_artifacts.urllib.request,
590
+ "urlopen",
591
+ lambda *_args, **_kwargs: pytest.fail("tamper must fail before network access"),
592
  )
593
+
594
+ with pytest.raises(ValueError, match="artifact mismatch"):
595
+ release_artifacts.hydrate_and_verify(repo_root=tmp_path, manifest_path=manifest_path)
596
+ assert tracked.read_bytes() == b"tampered"
597
+
598
+
599
+ def test_release_artifact_manifest_rejects_unknown_fields(tmp_path: Path) -> None:
600
+ manifest_path = _write_release_artifact_manifest(tmp_path)
601
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
602
+ payload["unexpected"] = True
603
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
604
+
605
+ with pytest.raises(ValueError, match="unknown manifest fields"):
606
+ release_artifacts.load_manifest(manifest_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
 
608
 
609
  def test_preflight_no_test_policy_invocation_uses_current_dirty_file_set() -> None:
 
688
  graph_resolver_script = next(
689
  step["run"]
690
  for step in graph_steps
691
+ if "graph_release_manifest.py hydrate" in str(step.get("run", ""))
692
  )
693
 
694
  assert "browser monitor security" in names
 
703
  assert "similarity" in lane_names
704
  assert "browser" in lane_names
705
  assert "package" in lane_names
706
+ assert "--manifest graph/release-artifacts.json" in graph_resolver_script
707
+ assert "git lfs" not in graph_resolver_script.lower()
 
 
708
 
709
 
710
  def test_every_workflow_parses_under_the_strict_loader() -> None:
src/tests/test_ctx_ab_benchmark.py CHANGED
@@ -2522,6 +2522,67 @@ def test_catalog_archive_validation_rejects_traversal(tmp_path: Path) -> None:
2522
  benchmark.validate_catalog_archive(archive)
2523
 
2524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2525
  def _write_runtime_availability(
2526
  path: Path,
2527
  *,
 
2522
  benchmark.validate_catalog_archive(archive)
2523
 
2524
 
2525
+ def test_production_catalog_hydration_uses_the_strict_release_manifest(
2526
+ tmp_path: Path,
2527
+ monkeypatch: pytest.MonkeyPatch,
2528
+ ) -> None:
2529
+ root = tmp_path / "repo"
2530
+ script = root / "scripts" / "graph_release_manifest.py"
2531
+ manifest = root / "graph" / "release-artifacts.json"
2532
+ archive = root / "graph" / "wiki-graph-runtime.tar.gz"
2533
+ script.parent.mkdir(parents=True)
2534
+ manifest.parent.mkdir(parents=True)
2535
+ script.write_text("# resolver\n", encoding="utf-8")
2536
+ manifest.write_text("{}\n", encoding="utf-8")
2537
+ calls: list[tuple[list[str], Path]] = []
2538
+
2539
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
2540
+ calls.append((command, kwargs["cwd"]))
2541
+ archive.write_bytes(b"hydrated")
2542
+ return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
2543
+
2544
+ monkeypatch.setattr(benchmark.subprocess, "run", fake_run)
2545
+
2546
+ assert benchmark.hydrate_production_catalog_archive(root=root) == archive
2547
+ assert calls == [
2548
+ (
2549
+ [
2550
+ sys.executable,
2551
+ str(script),
2552
+ "hydrate",
2553
+ "--repo-root",
2554
+ str(root),
2555
+ "--manifest",
2556
+ str(manifest),
2557
+ "--artifact",
2558
+ "graph/wiki-graph-runtime.tar.gz",
2559
+ ],
2560
+ root,
2561
+ )
2562
+ ]
2563
+
2564
+
2565
+ def test_production_catalog_hydration_rejects_an_existing_tampered_archive(
2566
+ tmp_path: Path,
2567
+ monkeypatch: pytest.MonkeyPatch,
2568
+ ) -> None:
2569
+ root = tmp_path / "repo"
2570
+ archive = root / "graph" / "wiki-graph-runtime.tar.gz"
2571
+ archive.parent.mkdir(parents=True)
2572
+ archive.write_bytes(b"tampered-unmanifested-catalog")
2573
+ calls: list[list[str]] = []
2574
+
2575
+ def reject_manifest(command: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]:
2576
+ calls.append(command)
2577
+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="artifact mismatch")
2578
+
2579
+ monkeypatch.setattr(benchmark.subprocess, "run", reject_manifest)
2580
+
2581
+ with pytest.raises(RuntimeError, match="artifact mismatch"):
2582
+ benchmark.hydrate_production_catalog_archive(root=root)
2583
+ assert len(calls) == 1
2584
+
2585
+
2586
  def _write_runtime_availability(
2587
  path: Path,
2588
  *,
src/tests/test_ctx_ab_holdout_prepare.py CHANGED
@@ -602,6 +602,17 @@ def test_create_protocol_writes_authenticated_canonical_output(
602
  version="codex 1.2.3",
603
  provider_config_sha256=benchmark.codex_provider_config_sha256("openai"),
604
  )
 
 
 
 
 
 
 
 
 
 
 
605
  monkeypatch.setattr(prepare, "_repository_state", lambda _root: state)
606
  monkeypatch.setattr(prepare, "_assert_repository_unchanged", lambda _state: None)
607
  monkeypatch.setattr(prepare, "_committed_v1_protocol", lambda _state: _v1())
@@ -633,6 +644,7 @@ def test_create_protocol_writes_authenticated_canonical_output(
633
  assert digest == _sha256(output.read_bytes())
634
  assert document["frozen_at"] == "2026-07-30T10:00:00Z"
635
  assert document["product_inputs"]["revision"] == REVISION
 
636
  assert document["product_inputs"]["origin_url"] == ORIGIN_URL
637
  assert document["product_inputs"]["origin_main_revision"] == REVISION
638
  assert document["product_inputs"]["codex_binary_sha256"] == codex.sha256
 
602
  version="codex 1.2.3",
603
  provider_config_sha256=benchmark.codex_provider_config_sha256("openai"),
604
  )
605
+ hydrated: list[Path] = []
606
+
607
+ def hydrate_catalog(*, root: Path) -> Path:
608
+ hydrated.append(root)
609
+ return product_paths[1]
610
+
611
+ monkeypatch.setattr(
612
+ prepare.benchmark,
613
+ "hydrate_production_catalog_archive",
614
+ hydrate_catalog,
615
+ )
616
  monkeypatch.setattr(prepare, "_repository_state", lambda _root: state)
617
  monkeypatch.setattr(prepare, "_assert_repository_unchanged", lambda _state: None)
618
  monkeypatch.setattr(prepare, "_committed_v1_protocol", lambda _state: _v1())
 
644
  assert digest == _sha256(output.read_bytes())
645
  assert document["frozen_at"] == "2026-07-30T10:00:00Z"
646
  assert document["product_inputs"]["revision"] == REVISION
647
+ assert hydrated == [root]
648
  assert document["product_inputs"]["origin_url"] == ORIGIN_URL
649
  assert document["product_inputs"]["origin_main_revision"] == REVISION
650
  assert document["product_inputs"]["codex_binary_sha256"] == codex.sha256
src/tests/test_ctx_init.py CHANGED
@@ -24,6 +24,7 @@ from ctx.adapters.claude_code.install.skill_install import install_skill
24
  from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
25
  from ctx.adapters.generic.providers import ToolCall
26
  from ctx.core.graph.graph_packs import write_base_pack
 
27
  from ctx.core.graph.graph_store import validate_graph_store
28
  from ctx.core.install_policy_store import (
29
  has_persisted_install_policy as has_real_install_policy,
@@ -103,17 +104,6 @@ def _write_dashboard_index(path: Path, *, export_id: str = "test-export") -> Non
103
  conn.close()
104
 
105
 
106
- def _artifact_sha256_or_lfs_oid(path: Path, *, normalize_text: bool = False) -> str:
107
- data = path.read_bytes()
108
- if data.startswith(b"version https://git-lfs.github.com/spec/v1\n"):
109
- for line in data.decode("utf-8").splitlines():
110
- if line.startswith("oid sha256:"):
111
- return line.removeprefix("oid sha256:")
112
- if normalize_text:
113
- data = data.replace(b"\r\n", b"\n")
114
- return hashlib.sha256(data).hexdigest()
115
-
116
-
117
  def test_ensure_directories_creates_standard_tree(tmp_path: Path) -> None:
118
  created = ci.ensure_directories(tmp_path)
119
  # First call should create every standard subdir.
@@ -771,40 +761,34 @@ def test_download_graph_archive_verifies_sha256(
771
  )
772
  assert not bad_destination.exists()
773
 
 
 
 
 
 
 
 
 
 
 
774
 
775
  def test_graph_download_checksums_match_shipped_artifacts() -> None:
776
  root = Path(__file__).resolve().parent.parent.parent
 
777
  for mode, archive_name in ci._GRAPH_ARCHIVE_NAMES.items():
778
- path = root / "graph" / archive_name
779
- assert ci._GRAPH_ARCHIVE_SHA256[mode] == _artifact_sha256_or_lfs_oid(path)
780
-
781
- overlay_path = root / "graph" / ci._GRAPH_ENTITY_OVERLAY_NAME
782
- assert ci._GRAPH_ENTITY_OVERLAY_SHA256 == _artifact_sha256_or_lfs_oid(
783
- overlay_path,
784
- normalize_text=True,
785
- )
786
-
787
 
788
- def test_local_graph_archive_checksum_is_verified(tmp_path: Path) -> None:
789
- archive = tmp_path / "wiki-graph-runtime.tar.gz"
790
- archive.write_bytes(b"not the shipped runtime archive")
791
 
792
- with pytest.raises(ValueError, match="local graph archive checksum mismatch"):
793
- ci._verify_local_graph_archive(archive, requested_install_mode="runtime")
794
 
795
-
796
- def test_lfs_pointer_graph_archive_is_ignored(
797
  tmp_path: Path,
798
  monkeypatch: pytest.MonkeyPatch,
799
  ) -> None:
800
- graph_dir = tmp_path / "graph"
801
- graph_dir.mkdir()
802
- (graph_dir / "wiki-graph-runtime.tar.gz").write_text(
803
- "version https://git-lfs.github.com/spec/v1\n"
804
- "oid sha256:993fc08377fdb09edcff4414c59b10fc121189b4a161bf796e3f8f6600907bb1\n"
805
- "size 122141091\n",
806
- encoding="utf-8",
807
- )
808
  cwd = tmp_path / "cwd"
809
  cwd.mkdir()
810
  monkeypatch.chdir(cwd)
@@ -813,6 +797,41 @@ def test_lfs_pointer_graph_archive_is_ignored(
813
  assert ci._find_local_graph_archive("runtime") is None
814
 
815
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816
  def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
817
  tmp_path: Path,
818
  monkeypatch,
 
24
  from ctx.adapters.generic.ctx_core_tools import CtxCoreToolbox
25
  from ctx.adapters.generic.providers import ToolCall
26
  from ctx.core.graph.graph_packs import write_base_pack
27
+ from ctx.core.graph import release_artifacts
28
  from ctx.core.graph.graph_store import validate_graph_store
29
  from ctx.core.install_policy_store import (
30
  has_persisted_install_policy as has_real_install_policy,
 
104
  conn.close()
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
107
  def test_ensure_directories_creates_standard_tree(tmp_path: Path) -> None:
108
  created = ci.ensure_directories(tmp_path)
109
  # First call should create every standard subdir.
 
761
  )
762
  assert not bad_destination.exists()
763
 
764
+ bad_size_destination = tmp_path / "bad-size-wiki-graph.tar.gz"
765
+ with pytest.raises(ValueError, match="size mismatch"):
766
+ ci._download_graph_archive(
767
+ bad_size_destination,
768
+ url="https://example.invalid/wiki-graph.tar.gz",
769
+ expected_sha256=hashlib.sha256(payload).hexdigest(),
770
+ expected_size=len(payload) + 1,
771
+ )
772
+ assert not bad_size_destination.exists()
773
+
774
 
775
  def test_graph_download_checksums_match_shipped_artifacts() -> None:
776
  root = Path(__file__).resolve().parent.parent.parent
777
+ manifest = release_artifacts.load_manifest(root / "graph" / "release-artifacts.json")
778
  for mode, archive_name in ci._GRAPH_ARCHIVE_NAMES.items():
779
+ artifact = manifest.artifact_for_path(f"graph/{archive_name}")
780
+ assert ci._GRAPH_ARCHIVE_SHA256[mode] == artifact.sha256
781
+ assert ci._GRAPH_ARCHIVE_SIZE[mode] == artifact.size
 
 
 
 
 
 
782
 
783
+ overlay = manifest.artifact_for_path(f"graph/{ci._GRAPH_ENTITY_OVERLAY_NAME}")
784
+ assert ci._GRAPH_ENTITY_OVERLAY_SHA256 == overlay.sha256
785
+ assert ci._GRAPH_ENTITY_OVERLAY_SIZE == overlay.size
786
 
 
 
787
 
788
+ def test_source_checkout_without_local_graph_archive_uses_release(
 
789
  tmp_path: Path,
790
  monkeypatch: pytest.MonkeyPatch,
791
  ) -> None:
 
 
 
 
 
 
 
 
792
  cwd = tmp_path / "cwd"
793
  cwd.mkdir()
794
  monkeypatch.chdir(cwd)
 
797
  assert ci._find_local_graph_archive("runtime") is None
798
 
799
 
800
+ def test_source_checkout_release_contract_comes_from_the_strict_manifest(
801
+ tmp_path: Path,
802
+ monkeypatch: pytest.MonkeyPatch,
803
+ ) -> None:
804
+ root = tmp_path / "repo"
805
+ graph_dir = root / "graph"
806
+ graph_dir.mkdir(parents=True)
807
+ source_manifest = Path(__file__).resolve().parents[2] / "graph" / "release-artifacts.json"
808
+ payload = json.loads(source_manifest.read_text(encoding="utf-8"))
809
+ payload["source_release_tag"] = "graph-artifacts-test-source"
810
+ (graph_dir / "release-artifacts.json").write_text(
811
+ json.dumps(payload),
812
+ encoding="utf-8",
813
+ )
814
+ monkeypatch.setattr(ci, "__file__", str(root / "src" / "ctx_init.py"))
815
+
816
+ contract = ci._source_graph_release_contract("runtime")
817
+ assert contract is not None
818
+ url, sha256, size = contract
819
+ runtime = release_artifacts.load_manifest(
820
+ graph_dir / "release-artifacts.json"
821
+ ).artifact_for_path("graph/wiki-graph-runtime.tar.gz")
822
+
823
+ assert url.endswith("/releases/download/graph-artifacts-test-source/wiki-graph-runtime.tar.gz")
824
+ assert (sha256, size) == (runtime.sha256, runtime.size)
825
+
826
+
827
+ def test_local_graph_archive_checksum_is_verified(tmp_path: Path) -> None:
828
+ archive = tmp_path / "wiki-graph-runtime.tar.gz"
829
+ archive.write_bytes(b"not the shipped runtime archive")
830
+
831
+ with pytest.raises(ValueError, match="local graph archive checksum mismatch"):
832
+ ci._verify_local_graph_archive(archive, requested_install_mode="runtime")
833
+
834
+
835
  def test_custom_graph_url_requires_checksum_or_explicit_opt_out(
836
  tmp_path: Path,
837
  monkeypatch,
src/tests/test_graph_release_manifest.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import stat
6
+ import subprocess
7
+ import sys
8
+
9
+ import pytest
10
+
11
+ from ctx.core.graph import release_artifacts
12
+
13
+
14
+ def _write_local_assets(root: Path) -> dict[str, bytes]:
15
+ payloads: dict[str, bytes] = {}
16
+ for index, (path, _asset_name, _hydrate) in enumerate(
17
+ release_artifacts.GRAPH_RELEASE_ARTIFACT_SPECS,
18
+ start=1,
19
+ ):
20
+ payload = f"artifact-{index}\n".encode()
21
+ destination = root / path
22
+ destination.parent.mkdir(parents=True, exist_ok=True)
23
+ destination.write_bytes(payload)
24
+ payloads[path] = payload
25
+ return payloads
26
+
27
+
28
+ def test_refresh_writes_the_exact_five_asset_manifest_deterministically(tmp_path: Path) -> None:
29
+ payloads = _write_local_assets(tmp_path)
30
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
31
+
32
+ assert (
33
+ release_artifacts.main(
34
+ [
35
+ "refresh",
36
+ "--repo-root",
37
+ str(tmp_path),
38
+ "--manifest",
39
+ str(manifest_path),
40
+ "--source-release-tag",
41
+ "v9.8.7",
42
+ ]
43
+ )
44
+ == 0
45
+ )
46
+ first = manifest_path.read_bytes()
47
+ assert (
48
+ release_artifacts.main(
49
+ [
50
+ "refresh",
51
+ "--repo-root",
52
+ str(tmp_path),
53
+ "--manifest",
54
+ str(manifest_path),
55
+ "--source-release-tag",
56
+ "v9.8.7",
57
+ ]
58
+ )
59
+ == 0
60
+ )
61
+ assert manifest_path.read_bytes() == first
62
+ assert stat.S_IMODE(manifest_path.stat().st_mode) == 0o600
63
+
64
+ manifest = release_artifacts.load_manifest(manifest_path)
65
+ assert manifest.repository == "stevesolun/ctx"
66
+ assert manifest.source_release_tag == "v9.8.7"
67
+ assert (
68
+ tuple(
69
+ (artifact.path, artifact.asset_name, artifact.hydrate)
70
+ for artifact in manifest.artifacts
71
+ )
72
+ == release_artifacts.GRAPH_RELEASE_ARTIFACT_SPECS
73
+ )
74
+ for artifact in manifest.artifacts:
75
+ assert artifact.size == len(payloads[artifact.path])
76
+
77
+
78
+ def test_manifest_rejects_an_incomplete_artifact_roster(tmp_path: Path) -> None:
79
+ _write_local_assets(tmp_path)
80
+ manifest = release_artifacts.build_manifest(
81
+ repo_root=tmp_path,
82
+ repository="stevesolun/ctx",
83
+ source_release_tag="v1.0.21",
84
+ )
85
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
86
+ release_artifacts.write_manifest(manifest_path, manifest)
87
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
88
+ payload["artifacts"].pop()
89
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
90
+
91
+ with pytest.raises(ValueError, match="exact graph release artifact roster"):
92
+ release_artifacts.load_manifest(manifest_path)
93
+
94
+
95
+ def test_manifest_rejects_a_different_repository(tmp_path: Path) -> None:
96
+ _write_local_assets(tmp_path)
97
+ manifest = release_artifacts.build_manifest(
98
+ repo_root=tmp_path,
99
+ repository="stevesolun/ctx",
100
+ source_release_tag="v1.0.21",
101
+ )
102
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
103
+ release_artifacts.write_manifest(manifest_path, manifest)
104
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
105
+ payload["repository"] = "attacker/fork"
106
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
107
+
108
+ with pytest.raises(ValueError, match="must be stevesolun/ctx"):
109
+ release_artifacts.load_manifest(manifest_path)
110
+
111
+
112
+ def test_manifest_rejects_an_artifact_above_its_path_cap(tmp_path: Path) -> None:
113
+ _write_local_assets(tmp_path)
114
+ manifest = release_artifacts.build_manifest(
115
+ repo_root=tmp_path,
116
+ repository="stevesolun/ctx",
117
+ source_release_tag="v1.0.21",
118
+ )
119
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
120
+ release_artifacts.write_manifest(manifest_path, manifest)
121
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
122
+ payload["artifacts"][-1]["size"] = 500_000_001
123
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
124
+
125
+ with pytest.raises(ValueError, match="size exceeds"):
126
+ release_artifacts.load_manifest(manifest_path)
127
+
128
+
129
+ def test_refresh_rejects_a_local_artifact_above_its_path_cap(
130
+ tmp_path: Path,
131
+ monkeypatch: pytest.MonkeyPatch,
132
+ ) -> None:
133
+ _write_local_assets(tmp_path)
134
+ real_identity = release_artifacts.file_sha256_and_size
135
+
136
+ def oversized_full(path: Path) -> tuple[str, int]:
137
+ if path.name == "wiki-graph.tar.gz":
138
+ return "a" * 64, 500_000_001
139
+ return real_identity(path)
140
+
141
+ monkeypatch.setattr(release_artifacts, "file_sha256_and_size", oversized_full)
142
+
143
+ with pytest.raises(ValueError, match="exceeds the 500000000-byte cap"):
144
+ release_artifacts.build_manifest(
145
+ repo_root=tmp_path,
146
+ repository="stevesolun/ctx",
147
+ source_release_tag="v1.0.21",
148
+ )
149
+
150
+
151
+ @pytest.mark.parametrize("kind", ["symlink", "directory", "oversize"])
152
+ def test_manifest_input_must_be_a_small_regular_file(tmp_path: Path, kind: str) -> None:
153
+ manifest_path = tmp_path / "release-artifacts.json"
154
+ if kind == "symlink":
155
+ target = tmp_path / "target.json"
156
+ target.write_text("{}", encoding="utf-8")
157
+ manifest_path.symlink_to(target)
158
+ expected = "not a regular file"
159
+ elif kind == "directory":
160
+ manifest_path.mkdir()
161
+ expected = "not a regular file"
162
+ else:
163
+ manifest_path.write_bytes(b" " * (release_artifacts._MAX_MANIFEST_BYTES + 1))
164
+ expected = "exceeds"
165
+
166
+ with pytest.raises(ValueError, match=expected):
167
+ release_artifacts.load_manifest(manifest_path)
168
+
169
+
170
+ def test_manifest_rejects_path_escape_before_accessing_assets(tmp_path: Path) -> None:
171
+ _write_local_assets(tmp_path)
172
+ manifest = release_artifacts.build_manifest(
173
+ repo_root=tmp_path,
174
+ repository="stevesolun/ctx",
175
+ source_release_tag="v1.0.21",
176
+ )
177
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
178
+ release_artifacts.write_manifest(manifest_path, manifest)
179
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
180
+ payload["artifacts"][0]["path"] = "graph/../outside"
181
+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")
182
+
183
+ with pytest.raises(ValueError, match="safe graph/ path"):
184
+ release_artifacts.load_manifest(manifest_path)
185
+
186
+
187
+ def test_validate_rejects_symlinked_local_artifact(tmp_path: Path) -> None:
188
+ _write_local_assets(tmp_path)
189
+ manifest = release_artifacts.build_manifest(
190
+ repo_root=tmp_path,
191
+ repository="stevesolun/ctx",
192
+ source_release_tag="v1.0.21",
193
+ )
194
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
195
+ release_artifacts.write_manifest(manifest_path, manifest)
196
+ tracked = tmp_path / "graph" / "communities.json"
197
+ target = tmp_path / "outside-communities.json"
198
+ tracked.replace(target)
199
+ try:
200
+ tracked.symlink_to(target)
201
+ except OSError as exc:
202
+ pytest.skip(f"file symlinks unavailable: {exc}")
203
+
204
+ with pytest.raises(ValueError, match="not a regular file"):
205
+ release_artifacts.validate_local_artifacts(
206
+ repo_root=tmp_path,
207
+ manifest_path=manifest_path,
208
+ )
209
+
210
+
211
+ def test_selective_hydration_downloads_only_the_requested_manifest_artifact(
212
+ tmp_path: Path,
213
+ monkeypatch: pytest.MonkeyPatch,
214
+ ) -> None:
215
+ payloads = _write_local_assets(tmp_path)
216
+ manifest = release_artifacts.build_manifest(
217
+ repo_root=tmp_path,
218
+ repository="stevesolun/ctx",
219
+ source_release_tag="v1.0.21",
220
+ )
221
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
222
+ release_artifacts.write_manifest(manifest_path, manifest)
223
+ runtime_path = "graph/wiki-graph-runtime.tar.gz"
224
+ full_path = "graph/wiki-graph.tar.gz"
225
+ (tmp_path / runtime_path).unlink()
226
+ (tmp_path / full_path).unlink()
227
+ downloaded: list[str] = []
228
+
229
+ def fake_download(
230
+ destination: Path,
231
+ *,
232
+ manifest: release_artifacts.GraphReleaseManifest,
233
+ artifact: release_artifacts.GraphReleaseArtifact,
234
+ ) -> None:
235
+ del manifest
236
+ downloaded.append(artifact.path)
237
+ destination.write_bytes(payloads[artifact.path])
238
+
239
+ monkeypatch.setattr(release_artifacts, "_download_artifact", fake_download)
240
+
241
+ release_artifacts.hydrate_and_verify(
242
+ repo_root=tmp_path,
243
+ manifest_path=manifest_path,
244
+ artifact_paths=[runtime_path],
245
+ )
246
+
247
+ assert downloaded == [runtime_path]
248
+ assert (tmp_path / runtime_path).read_bytes() == payloads[runtime_path]
249
+ assert not (tmp_path / full_path).exists()
250
+
251
+
252
+ def test_cli_refresh_runs_with_the_stdlib_only(tmp_path: Path) -> None:
253
+ _write_local_assets(tmp_path)
254
+ manifest_path = tmp_path / "graph" / "release-artifacts.json"
255
+ script = Path(__file__).resolve().parents[2] / "scripts" / "graph_release_manifest.py"
256
+
257
+ result = subprocess.run(
258
+ [
259
+ sys.executable,
260
+ "-S",
261
+ str(script),
262
+ "refresh",
263
+ "--repo-root",
264
+ str(tmp_path),
265
+ "--manifest",
266
+ str(manifest_path),
267
+ "--source-release-tag",
268
+ "v1.0.21",
269
+ ],
270
+ check=False,
271
+ capture_output=True,
272
+ text=True,
273
+ )
274
+
275
+ assert result.returncode == 0, result.stderr
276
+ assert release_artifacts.load_manifest(manifest_path).source_release_tag == "v1.0.21"
src/tests/test_huggingface_sync.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import hashlib
 
6
  import sys
7
  import tarfile
8
  from pathlib import Path
@@ -16,15 +17,47 @@ if str(SCRIPTS_DIR) not in sys.path:
16
  import sync_huggingface # noqa: E402
17
 
18
 
 
 
 
 
 
 
 
 
 
19
  def _required_hydrated_artifacts() -> tuple[Path, ...]:
20
  return tuple(sync_huggingface.HYDRATED_ARTIFACT_MIN_BYTES)
21
 
22
 
23
  def _write_small_hydrated_artifacts(repo: Path) -> None:
24
- for rel in _required_hydrated_artifacts():
25
- path = repo / rel
 
 
26
  path.parent.mkdir(parents=True, exist_ok=True)
27
- path.write_bytes(b"\x1f\x8b" + rel.name.encode("utf-8"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
 
30
  def _tiny_hydrated_min_bytes() -> dict[Path, int]:
@@ -162,15 +195,12 @@ def test_hf_sync_workflow_uses_secret_and_hardened_script() -> None:
162
 
163
  assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
164
  assert "lfs: false" in text
165
- assert "Resolving graph artifacts from release cache, or targeted Git LFS" in text
166
- assert "searching release caches before targeted Git LFS" in text
167
- assert '"git", "lfs", "pull", "--include", path_name' in text
168
- assert "verify_hydrated_file(artifact, expected_oid, expected_size)" in text
169
- assert 'tag_name.startswith("graph-artifacts-")' in text
170
- assert "latest_tag" not in text
171
- for artifact in _required_hydrated_artifacts():
172
- assert artifact.as_posix() in text
173
- assert f'hydrate_from_release("{artifact.as_posix()}"' in text
174
  assert "scripts/sync_huggingface.py" in text
175
  assert "--repo-type dataset" in text
176
  assert "--repo-type model" not in text
@@ -441,7 +471,7 @@ def test_hf_graph_validation_rejects_stale_exact_counts(tmp_path: Path, monkeypa
441
  raise AssertionError("expected stale graph artifact rejection")
442
 
443
 
444
- def test_hf_export_requires_hydrated_artifacts_to_match_lfs_pointer(
445
  tmp_path: Path,
446
  monkeypatch: pytest.MonkeyPatch,
447
  ) -> None:
@@ -451,27 +481,12 @@ def test_hf_export_requires_hydrated_artifacts_to_match_lfs_pointer(
451
  graph_dir.mkdir()
452
  _write_small_hydrated_artifacts(repo)
453
  artifact = graph_dir / "wiki-graph.tar.gz"
454
- expected = b"\x1f\x8bcurrent-full-graph"
455
- artifact.write_bytes(expected)
456
- expected_oid = hashlib.sha256(expected).hexdigest()
457
- pointer = (
458
- "version https://git-lfs.github.com/spec/v1\n"
459
- f"oid sha256:{expected_oid}\n"
460
- f"size {len(expected)}\n"
461
- )
462
 
463
  monkeypatch.setattr(
464
  sync_huggingface,
465
  "HYDRATED_ARTIFACT_MIN_BYTES",
466
  _tiny_hydrated_min_bytes(),
467
  )
468
-
469
- def fake_git_bytes(_repo: Path, *_args: str) -> bytes:
470
- if _args[-1] == "HEAD:graph/wiki-graph.tar.gz":
471
- return pointer.encode("utf-8")
472
- raise sync_huggingface.subprocess.CalledProcessError(1, list(_args))
473
-
474
- monkeypatch.setattr(sync_huggingface, "_git_bytes", fake_git_bytes)
475
  monkeypatch.setattr(
476
  sync_huggingface,
477
  "_validate_graph_artifact_integrity",
@@ -481,15 +496,11 @@ def test_hf_export_requires_hydrated_artifacts_to_match_lfs_pointer(
481
  sync_huggingface._assert_hydrated_artifacts(repo)
482
 
483
  artifact.write_bytes(b"\x1f\x8bstale-full-graph")
484
- try:
485
  sync_huggingface._assert_hydrated_artifacts(repo)
486
- except RuntimeError as exc:
487
- assert "does not match HEAD LFS pointer" in str(exc)
488
- else:
489
- raise AssertionError("expected stale LFS asset rejection")
490
 
491
 
492
- def test_hf_export_skips_lfs_pointer_check_for_binary_git_artifact(
493
  tmp_path: Path,
494
  monkeypatch: pytest.MonkeyPatch,
495
  ) -> None:
@@ -498,30 +509,50 @@ def test_hf_export_skips_lfs_pointer_check_for_binary_git_artifact(
498
  graph_dir = repo / "graph"
499
  graph_dir.mkdir()
500
  _write_small_hydrated_artifacts(repo)
501
- artifact = graph_dir / "wiki-graph.tar.gz"
502
- artifact.write_bytes(b"\x1f\x8bcurrent-full-graph")
503
-
504
- def fake_git_bytes(_repo: Path, *_args: str) -> bytes:
505
- if _args[-1] == "HEAD:graph/wiki-graph.tar.gz":
506
- return b"\x1f\x8bcommitted-binary-graph"
507
- raise sync_huggingface.subprocess.CalledProcessError(1, list(_args))
508
 
509
  monkeypatch.setattr(
510
  sync_huggingface,
511
  "HYDRATED_ARTIFACT_MIN_BYTES",
512
  _tiny_hydrated_min_bytes(),
513
  )
514
- monkeypatch.setattr(sync_huggingface, "_git_bytes", fake_git_bytes)
515
  monkeypatch.setattr(
516
  sync_huggingface,
517
  "_validate_graph_artifact_integrity",
518
  lambda _repo: None,
519
  )
520
 
521
- sync_huggingface._assert_hydrated_artifacts(repo)
 
522
 
523
 
524
- def test_hf_export_rejects_corrupt_large_graph_artifact(tmp_path: Path, monkeypatch) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  repo = tmp_path / "repo"
526
  repo.mkdir()
527
  graph_dir = repo / "graph"
@@ -554,10 +585,6 @@ def test_hf_export_rejects_corrupt_large_graph_artifact(tmp_path: Path, monkeypa
554
  ),
555
  )
556
 
557
- try:
558
  sync_huggingface._assert_hydrated_artifacts(repo)
559
- except RuntimeError as exc:
560
- assert "graph artifact integrity validation failed" in str(exc)
561
- assert "wiki-graph.tar.gz" in str(exc)
562
- else:
563
- raise AssertionError("expected corrupt graph artifact rejection")
 
3
  from __future__ import annotations
4
 
5
  import hashlib
6
+ import json
7
  import sys
8
  import tarfile
9
  from pathlib import Path
 
17
  import sync_huggingface # noqa: E402
18
 
19
 
20
+ RELEASE_ARTIFACT_SPECS = (
21
+ ("graph/communities.json", "communities.json", False),
22
+ ("graph/entity-overlays.jsonl", "entity-overlays.jsonl", False),
23
+ ("graph/skills-sh-catalog.json.gz", "skills-sh-catalog.json.gz", False),
24
+ ("graph/wiki-graph-runtime.tar.gz", "wiki-graph-runtime.tar.gz", True),
25
+ ("graph/wiki-graph.tar.gz", "wiki-graph.tar.gz", True),
26
+ )
27
+
28
+
29
  def _required_hydrated_artifacts() -> tuple[Path, ...]:
30
  return tuple(sync_huggingface.HYDRATED_ARTIFACT_MIN_BYTES)
31
 
32
 
33
  def _write_small_hydrated_artifacts(repo: Path) -> None:
34
+ artifacts: list[dict[str, object]] = []
35
+ for path_name, asset_name, hydrate in RELEASE_ARTIFACT_SPECS:
36
+ rel = Path(path_name)
37
+ path = repo / path_name
38
  path.parent.mkdir(parents=True, exist_ok=True)
39
+ payload = b"\x1f\x8b" + rel.name.encode("utf-8")
40
+ path.write_bytes(payload)
41
+ artifacts.append(
42
+ {
43
+ "path": path_name,
44
+ "asset_name": asset_name,
45
+ "size": len(payload),
46
+ "sha256": hashlib.sha256(payload).hexdigest(),
47
+ "hydrate": hydrate,
48
+ }
49
+ )
50
+ (repo / "graph" / "release-artifacts.json").write_text(
51
+ json.dumps(
52
+ {
53
+ "schema_version": 1,
54
+ "repository": "stevesolun/ctx",
55
+ "source_release_tag": "v-test",
56
+ "artifacts": artifacts,
57
+ }
58
+ ),
59
+ encoding="utf-8",
60
+ )
61
 
62
 
63
  def _tiny_hydrated_min_bytes() -> dict[Path, int]:
 
195
 
196
  assert "HF_TOKEN: ${{ secrets.HF_TOKEN }}" in text
197
  assert "lfs: false" in text
198
+ assert "Hydrate required graph artifacts from exact release manifest" in text
199
+ assert (
200
+ "python scripts/graph_release_manifest.py hydrate --manifest graph/release-artifacts.json"
201
+ ) in text
202
+ assert "git lfs" not in text.lower()
203
+ assert "GIT_LFS_" not in text
 
 
 
204
  assert "scripts/sync_huggingface.py" in text
205
  assert "--repo-type dataset" in text
206
  assert "--repo-type model" not in text
 
471
  raise AssertionError("expected stale graph artifact rejection")
472
 
473
 
474
+ def test_hf_export_requires_artifacts_to_match_release_manifest(
475
  tmp_path: Path,
476
  monkeypatch: pytest.MonkeyPatch,
477
  ) -> None:
 
481
  graph_dir.mkdir()
482
  _write_small_hydrated_artifacts(repo)
483
  artifact = graph_dir / "wiki-graph.tar.gz"
 
 
 
 
 
 
 
 
484
 
485
  monkeypatch.setattr(
486
  sync_huggingface,
487
  "HYDRATED_ARTIFACT_MIN_BYTES",
488
  _tiny_hydrated_min_bytes(),
489
  )
 
 
 
 
 
 
 
490
  monkeypatch.setattr(
491
  sync_huggingface,
492
  "_validate_graph_artifact_integrity",
 
496
  sync_huggingface._assert_hydrated_artifacts(repo)
497
 
498
  artifact.write_bytes(b"\x1f\x8bstale-full-graph")
499
+ with pytest.raises(RuntimeError, match="release manifest"):
500
  sync_huggingface._assert_hydrated_artifacts(repo)
 
 
 
 
501
 
502
 
503
+ def test_hf_export_rejects_incomplete_release_manifest_identity(
504
  tmp_path: Path,
505
  monkeypatch: pytest.MonkeyPatch,
506
  ) -> None:
 
509
  graph_dir = repo / "graph"
510
  graph_dir.mkdir()
511
  _write_small_hydrated_artifacts(repo)
512
+ manifest_path = graph_dir / "release-artifacts.json"
513
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
514
+ manifest["artifacts"].pop()
515
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
 
 
 
516
 
517
  monkeypatch.setattr(
518
  sync_huggingface,
519
  "HYDRATED_ARTIFACT_MIN_BYTES",
520
  _tiny_hydrated_min_bytes(),
521
  )
 
522
  monkeypatch.setattr(
523
  sync_huggingface,
524
  "_validate_graph_artifact_integrity",
525
  lambda _repo: None,
526
  )
527
 
528
+ with pytest.raises(RuntimeError, match="invalid graph release manifest"):
529
+ sync_huggingface._assert_hydrated_artifacts(repo)
530
 
531
 
532
+ def test_hf_export_rejects_release_manifest_for_other_repository(
533
+ tmp_path: Path,
534
+ monkeypatch: pytest.MonkeyPatch,
535
+ ) -> None:
536
+ repo = tmp_path / "repo"
537
+ repo.mkdir()
538
+ _write_small_hydrated_artifacts(repo)
539
+ manifest_path = repo / "graph" / "release-artifacts.json"
540
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
541
+ manifest["repository"] = "other/ctx"
542
+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
543
+ monkeypatch.setattr(
544
+ sync_huggingface,
545
+ "HYDRATED_ARTIFACT_MIN_BYTES",
546
+ _tiny_hydrated_min_bytes(),
547
+ )
548
+
549
+ with pytest.raises(RuntimeError, match="manifest repository must"):
550
+ sync_huggingface._assert_hydrated_artifacts(repo)
551
+
552
+
553
+ def test_hf_export_rejects_corrupt_graph_before_deep_validation(
554
+ tmp_path: Path, monkeypatch
555
+ ) -> None:
556
  repo = tmp_path / "repo"
557
  repo.mkdir()
558
  graph_dir = repo / "graph"
 
585
  ),
586
  )
587
 
588
+ with pytest.raises(RuntimeError, match="does not match graph release manifest") as exc_info:
589
  sync_huggingface._assert_hydrated_artifacts(repo)
590
+ assert "wiki-graph.tar.gz" in str(exc_info.value)
 
 
 
 
src/tests/test_lfs_retirement.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+
8
+ REPO_ROOT = Path(__file__).resolve().parents[2]
9
+ GRAPH_ARCHIVES = (
10
+ "graph/wiki-graph.tar.gz",
11
+ "graph/wiki-graph-runtime.tar.gz",
12
+ )
13
+
14
+
15
+ def test_graph_archives_are_release_assets_not_git_lfs_files() -> None:
16
+ manifest = json.loads(
17
+ (REPO_ROOT / "graph" / "release-artifacts.json").read_text(encoding="utf-8")
18
+ )
19
+
20
+ hydrated_paths = {
21
+ artifact["path"] for artifact in manifest["artifacts"] if artifact["hydrate"] is True
22
+ }
23
+ assert hydrated_paths == set(GRAPH_ARCHIVES)
24
+
25
+ attributes = (REPO_ROOT / ".gitattributes").read_text(encoding="utf-8")
26
+ assert "filter=lfs" not in attributes
27
+
28
+ if not (REPO_ROOT / ".git").exists():
29
+ return
30
+ tracked = subprocess.run(
31
+ ["git", "ls-files", "--error-unmatch", *GRAPH_ARCHIVES],
32
+ cwd=REPO_ROOT,
33
+ check=False,
34
+ capture_output=True,
35
+ text=True,
36
+ )
37
+ assert tracked.returncode != 0