File size: 14,355 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
from __future__ import annotations

import hashlib
import json
import os
import shutil
import uuid
from datetime import UTC, datetime
from pathlib import Path

import yaml  # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict, Field

from packages.core.files import atomic_write_text


class ArtifactLifecyclePolicy(BaseModel):
    model_config = ConfigDict(extra="forbid")

    schema_version: str
    enabled: bool = True
    compact_after_release: bool = True
    preserve_globs: list[str] = Field(default_factory=list)
    remove_paths: list[str] = Field(default_factory=list)


DEFAULT_POLICY = (
    Path(__file__).resolve().parents[2] / "configs" / "artifact_lifecycle_v1.yaml"
)


def load_artifact_lifecycle_policy(path: Path | None = None) -> ArtifactLifecyclePolicy:
    selected = path or Path(os.environ.get("RHG_ARTIFACT_POLICY", DEFAULT_POLICY))
    payload = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8"))
    return ArtifactLifecyclePolicy.model_validate(payload)


def compact_released_attempt(
    output: Path,
    portable_package: Path,
    *,
    expected_package_sha256: str | None = None,
    policy: ArtifactLifecyclePolicy | None = None,
    apply: bool = True,
) -> dict[str, object]:
    """Prune reproducible generation workspaces after a portable package is verified."""

    output = output.resolve()
    portable_package = portable_package.resolve()
    selected = policy or load_artifact_lifecycle_policy()
    if not output.is_dir():
        raise NotADirectoryError(output)
    if not portable_package.exists():
        raise FileNotFoundError(portable_package)
    package_sha256 = _package_sha256(portable_package)
    if expected_package_sha256 and package_sha256 != expected_package_sha256:
        raise ValueError("portable package checksum changed before artifact compaction")

    before_bytes = _physical_size(output)
    targets = _resolve_targets(output, selected.remove_paths)
    plan = [
        {
            "path": path.relative_to(output).as_posix(),
            "physical_bytes": _physical_size(path),
        }
        for path in targets
        if path.exists()
    ]
    report: dict[str, object] = {
        "schema_version": "1.0",
        "created_at": datetime.now(UTC).isoformat(),
        "mode": "apply" if apply else "dry_run",
        "status": "planned",
        "portable_package": str(portable_package),
        "portable_sha256": package_sha256,
        "before_physical_bytes": before_bytes,
        "targets": plan,
        "preserved_files": [],
    }
    if not selected.enabled or not selected.compact_after_release or not apply:
        return report

    preserved = _preserve_evidence(output, targets, selected.preserve_globs)
    for path in targets:
        if path.is_dir() and not path.is_symlink():
            shutil.rmtree(path)
        elif path.exists() or path.is_symlink():
            path.unlink()
    after_bytes = _physical_size(output)
    report.update(
        {
            "status": "complete",
            "completed_at": datetime.now(UTC).isoformat(),
            "after_physical_bytes_before_report": after_bytes,
            "reclaimed_physical_bytes": max(before_bytes - after_bytes, 0),
            "preserved_files": preserved,
        }
    )
    report_path = output / "supervisor" / "artifact_lifecycle_report.json"
    atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
    _write_checksums(output)
    return report


def build_compact_copy(
    source: Path,
    destination: Path,
    *,
    policy: ArtifactLifecyclePolicy | None = None,
) -> dict[str, object]:
    """Build a pruned copy without mutating the immutable version directory."""

    source = source.resolve()
    destination = destination.resolve()
    selected = policy or load_artifact_lifecycle_policy()
    if not source.is_dir():
        raise NotADirectoryError(source)
    if destination == source or destination.is_relative_to(source):
        raise ValueError("compact copy destination must be outside the source version")
    if destination.exists():
        raise FileExistsError(destination)

    excluded = {
        Path(relative).as_posix().strip("/") for relative in selected.remove_paths
    }

    def ignore(directory: str, names: list[str]) -> set[str]:
        relative_dir = Path(directory).resolve().relative_to(source)
        ignored: set[str] = set()
        for name in names:
            if (Path(directory) / name).is_symlink():
                ignored.add(name)
                continue
            relative = (relative_dir / name).as_posix().strip(".").strip("/")
            if any(relative == item or relative.startswith(f"{item}/") for item in excluded):
                ignored.add(name)
        return ignored

    shutil.copytree(source, destination, symlinks=False, ignore=ignore)
    _preserve_evidence_from_source(source, destination, selected)
    report: dict[str, object] = {
        "schema_version": "1.0",
        "created_at": datetime.now(UTC).isoformat(),
        "status": "complete",
        "source_version": source.name,
        "source_physical_bytes": _physical_size(source),
        "major_physical_bytes_before_report": _physical_size(destination),
        "excluded_paths": sorted(excluded),
    }
    report_path = destination / "supervisor" / "artifact_lifecycle_report.json"
    atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
    _write_checksums(destination)
    return report


def replace_major_copy(
    source: Path,
    major: Path,
    *,
    policy: ArtifactLifecyclePolicy | None = None,
) -> dict[str, object]:
    """Atomically replace ``major`` with a compact copy of ``source``."""

    major = major.resolve()
    major.parent.mkdir(parents=True, exist_ok=True)
    token = uuid.uuid4().hex
    staging = major.parent / f".{major.name}.staging-{token}"
    backup = major.parent / f".{major.name}.backup-{token}"
    try:
        report = build_compact_copy(source, staging, policy=policy)
        if major.exists():
            major.rename(backup)
        staging.rename(major)
    except Exception:
        if backup.exists() and not major.exists():
            backup.rename(major)
        raise
    finally:
        if staging.exists():
            shutil.rmtree(staging)
    if backup.exists():
        shutil.rmtree(backup)
    return report


def replace_major_from_portable(
    portable: Path,
    major: Path,
    *,
    source_version: Path,
) -> dict[str, object]:
    """Atomically materialize ``major`` from an already verified portable bundle."""

    from packages.benchmark.portable import refresh_checksums, verify_portable_bundle

    portable = portable.resolve()
    major = major.resolve()
    source_version = source_version.resolve()
    if not portable.is_dir():
        raise NotADirectoryError(portable)
    if not (portable / "portable_manifest.json").is_file():
        raise FileNotFoundError(portable / "portable_manifest.json")
    major.parent.mkdir(parents=True, exist_ok=True)
    token = uuid.uuid4().hex
    staging = major.parent / f".{major.name}.staging-{token}"
    backup = major.parent / f".{major.name}.backup-{token}"
    try:
        symlinks = [path for path in portable.rglob("*") if path.is_symlink()]
        if symlinks:
            raise RuntimeError(f"portable source contains symlinks: {symlinks[:3]}")
        # Preserve the portable staging hardlinks. This keeps both the live major
        # directory and its tar archive compact without coupling path validity.
        shutil.copytree(portable, staging, symlinks=False, copy_function=os.link)
        snapshot_source = source_version / "snapshot.jpg"
        if not (staging / "snapshot.jpg").is_file():
            if not snapshot_source.is_file():
                raise FileNotFoundError(snapshot_source)
            shutil.copy2(snapshot_source, staging / "snapshot.jpg")
        # ``major`` has a backend-independent, fixed media contract. Older
        # portable bundles stored the video only under ``scenesmith/``; expose
        # it at the major root without duplicating file data.
        preview = staging / "preview.mp4"
        if not preview.is_file():
            preview_source = staging / "scenesmith" / "preview.mp4"
            if not preview_source.is_file():
                preview_source = source_version / "scenesmith" / "preview.mp4"
            if not preview_source.is_file():
                raise FileNotFoundError(
                    f"major preview is missing for source version: {source_version}"
                )
            os.link(preview_source, preview)
        history = staging / "iteration_history.mp4"
        if not history.is_file():
            history_source = staging / "scenesmith" / "iteration_history.mp4"
            if not history_source.is_file():
                history_source = source_version / "iteration_history.mp4"
            if not history_source.is_file():
                history_source = source_version / "scenesmith" / "iteration_history.mp4"
            if not history_source.is_file():
                raise FileNotFoundError(
                    f"major iteration history is missing for source version: {source_version}"
                )
            os.link(history_source, history)
        provenance = {
            "schema_version": "1.0",
            "materialization_version": "5.0",
            "created_at": datetime.now(UTC).isoformat(),
            "source_version": source_version.name,
            "source_portable_bundle": str(portable),
            "self_contained": True,
            "media": {
                "snapshot": "snapshot.jpg",
                "preview": "preview.mp4",
                "iteration_history": "iteration_history.mp4",
            },
        }
        atomic_write_text(
            staging / "major_manifest.json",
            json.dumps(provenance, ensure_ascii=False, indent=2) + "\n",
        )
        refresh_checksums(staging)
        verification = verify_portable_bundle(staging, require_pxr=False)
        if not verification["passed"]:
            raise RuntimeError(f"major portable verification failed: {verification['failures']}")
        if major.exists():
            major.rename(backup)
        staging.rename(major)
    except Exception:
        if backup.exists() and not major.exists():
            backup.rename(major)
        raise
    finally:
        if staging.exists():
            shutil.rmtree(staging)
    if backup.exists():
        shutil.rmtree(backup)
    return {
        "schema_version": "1.0",
        "status": "complete",
        "source_version": source_version.name,
        "source_portable_bundle": str(portable),
        "verification": verification,
    }


def _resolve_targets(output: Path, relative_paths: list[str]) -> list[Path]:
    targets: list[Path] = []
    for relative in relative_paths:
        candidate = (output / relative).resolve()
        if not candidate.is_relative_to(output):
            raise ValueError(f"artifact cleanup path escapes the run: {relative}")
        if candidate == output:
            raise ValueError("artifact cleanup cannot target the run root")
        targets.append(candidate)
    return targets


def _preserve_evidence(output: Path, targets: list[Path], globs: list[str]) -> list[str]:
    destination_root = output / "supervisor" / "generation_evidence"
    preserved: list[str] = []
    for target in targets:
        if not target.is_dir():
            continue
        for pattern in globs:
            for source in sorted(target.glob(pattern)):
                if not source.is_file():
                    continue
                relative = source.relative_to(output)
                destination = destination_root / relative
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(source, destination)
                preserved.append(destination.relative_to(output).as_posix())
    return sorted(set(preserved))


def _preserve_evidence_from_source(
    source_root: Path,
    destination_root: Path,
    policy: ArtifactLifecyclePolicy,
) -> list[str]:
    evidence_root = destination_root / "supervisor" / "generation_evidence"
    preserved: list[str] = []
    for target in _resolve_targets(source_root, policy.remove_paths):
        if not target.is_dir():
            continue
        for pattern in policy.preserve_globs:
            for source in sorted(target.glob(pattern)):
                if not source.is_file():
                    continue
                relative = source.relative_to(source_root)
                destination = evidence_root / relative
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(source, destination)
                preserved.append(destination.relative_to(destination_root).as_posix())
    return sorted(set(preserved))


def _physical_size(path: Path) -> int:
    if not path.exists():
        return 0
    files = [path] if path.is_file() else path.rglob("*")
    seen: set[tuple[int, int]] = set()
    total = 0
    for item in files:
        if not item.is_file():
            continue
        stat = item.stat()
        key = (stat.st_dev, stat.st_ino)
        if key in seen:
            continue
        seen.add(key)
        total += stat.st_blocks * 512
    return total


def _package_sha256(path: Path) -> str:
    if path.is_dir():
        digest = hashlib.sha256()
        for item in sorted(path.rglob("*")):
            if item.is_file():
                digest.update(item.relative_to(path).as_posix().encode())
                digest.update(_sha256_file(item).encode())
        return digest.hexdigest()
    return _sha256_file(path)


def _sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _write_checksums(output: Path) -> None:
    checksums = []
    for path in sorted(output.rglob("*")):
        if path.is_file() and path.name != "checksums.sha256":
            checksums.append(f"{_sha256_file(path)}  {path.relative_to(output)}")
    atomic_write_text(output / "checksums.sha256", "\n".join(checksums) + "\n")