File size: 9,571 Bytes
f023c9a
 
 
 
 
 
 
 
 
2629e20
f023c9a
 
e9e7451
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9e7451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f023c9a
 
 
 
 
 
 
 
6615497
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2629e20
 
 
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2629e20
f023c9a
 
 
 
6615497
 
 
 
 
 
 
2629e20
6615497
 
 
 
50f05ff
 
 
 
 
 
 
 
 
 
 
 
f023c9a
 
 
 
 
 
 
2629e20
f023c9a
 
 
 
 
 
 
 
 
 
 
2629e20
f023c9a
 
 
 
 
 
 
 
 
 
 
2629e20
f023c9a
 
 
 
 
 
 
 
 
 
 
 
a5b2982
 
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6590a6
 
 
 
 
 
 
 
f023c9a
 
e9e7451
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a5b6c3
f023c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run Eggcracker's local full qualification and produce a portable evidence pack."""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import platform
import pwd
import subprocess
import sys
import time
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
CLI = Path("/usr/local/bin/eggcracker")
POLICY = Path("/etc/lumi-eggcracker/policy.json")


def run(argv: list[str], *, timeout: int = 900) -> None:
    result = subprocess.run(argv, capture_output=True, text=True, check=False, timeout=timeout)
    if result.returncode:
        raise RuntimeError(
            result.stderr.strip() or result.stdout.strip() or "qualification command failed"
        )


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


def new_directory(path: Path) -> Path:
    if not path.is_absolute() or path.exists() or path.is_symlink() or not path.parent.is_dir():
        raise RuntimeError(
            "evidence directory must be a new absolute child of an existing directory"
        )
    path.mkdir(mode=0o700)
    return path


def doctor(operator: str, *, timeout: float = 30) -> dict[str, Any]:
    """Wait through a bounded post-restart scan and require a real PASS."""
    deadline = time.monotonic() + timeout
    latest = "Eggcracker doctor did not pass"
    while time.monotonic() < deadline:
        result = subprocess.run(
            ["/usr/sbin/runuser", "-u", operator, "--", str(CLI), "doctor"],
            capture_output=True,
            text=True,
            check=False,
            timeout=3,
        )
        latest = result.stderr.strip() or result.stdout.strip() or latest
        if result.returncode == 0:
            try:
                value = json.loads(result.stdout)
            except json.JSONDecodeError:
                value = None
            if isinstance(value, dict) and value.get("result") == "PASS":
                return value
        time.sleep(0.05)
    raise RuntimeError(latest)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Run Eggcracker's complete local qualification against an installed instance."
    )
    parser.add_argument("--operator", required=True)
    parser.add_argument("--assets-manifest", required=True, type=Path)
    parser.add_argument("--safetensors-assets-manifest", required=True, type=Path)
    parser.add_argument("--evidence-dir", required=True, type=Path)
    args = parser.parse_args()
    if not hasattr(os, "geteuid") or os.geteuid() != 0:
        raise SystemExit("self-validation must run as root")
    evidence: Path | None = None
    summary: dict[str, Any] = {
        "result": "FAIL",
        "schema_version": "lumi-eggcracker.self-validation.v1",
    }
    try:
        evidence = new_directory(args.evidence_dir)
        if not CLI.is_file() or not POLICY.is_file() or POLICY.is_symlink():
            raise RuntimeError("Eggcracker is not installed")
        policy = json.loads(POLICY.read_text(encoding="utf-8"))
        if policy.get("operator_uid") is None or policy.get("source_commit") is None:
            raise RuntimeError("installed policy is invalid")
        workload = pwd.getpwuid(int(policy["workload_uid"])).pw_name
        if workload == args.operator:
            raise RuntimeError("installed workload identity must differ from operator")
        checked = doctor(args.operator)
        environment = {
            "catalogue": checked["catalogue"],
            "platform": platform.platform(),
            "python": sys.version.split()[0],
            "source_commit": policy["source_commit"],
            "validated_utc": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
            "version": checked["version"],
        }
        (evidence / "environment.json").write_text(
            json.dumps(environment, sort_keys=True) + "\n", encoding="utf-8"
        )
        (evidence / "doctor.json").write_text(
            json.dumps(checked, sort_keys=True) + "\n", encoding="utf-8"
        )
        jobs = (
            (
                "real-ai-smoke.json",
                [
                    "smoke_content_ai.py",
                    "--assets-manifest",
                    str(args.assets_manifest),
                    "--user",
                    workload,
                    "--repetitions",
                    "5",
                ],
            ),
            (
                "safetensors-ai-smoke.json",
                [
                    "smoke_safetensors_ai.py",
                    "--assets-manifest",
                    str(args.safetensors_assets_manifest),
                    "--user",
                    workload,
                    "--repetitions",
                    "5",
                ],
            ),
            (
                "safetensors-aten-negative.json",
                [
                    "smoke_safetensors_aten_negative.py",
                    "--assets-manifest",
                    str(args.safetensors_assets_manifest),
                    "--user",
                    workload,
                    "--repetitions",
                    "5",
                ],
            ),
            (
                "content-matrix.json",
                [
                    "run_content_matrix.py",
                    "--assets-manifest",
                    str(args.assets_manifest),
                    "--user",
                    workload,
                    "--repetitions",
                    "100",
                ],
            ),
            (
                "benign-model-matrix.json",
                [
                    "run_content_benign_matrix.py",
                    "--assets-manifest",
                    str(args.assets_manifest),
                    "--user",
                    workload,
                    "--repetitions",
                    "300",
                ],
            ),
            (
                "content-adversarial-matrix.json",
                [
                    "run_content_adversarial_matrix.py",
                    "--assets-manifest",
                    str(args.assets_manifest),
                    "--user",
                    workload,
                    "--tree-repetitions",
                    "100",
                    "--startup-repetitions",
                    "20",
                    "--restart-repetitions",
                    "20",
                ],
            ),
            (
                "autonomous-regression.json",
                [
                    "run_autonomous_matrix.py",
                    "--assets-manifest",
                    str(args.assets_manifest),
                    "--discoveries",
                    "100",
                    "--approved",
                    "50",
                    "--benign",
                    "200",
                ],
            ),
            (
                "selected-workload-regression.json",
                [
                    "run_native_matrix.py",
                    "--fork-race-repetitions",
                    "100",
                    "--benign-repetitions",
                    "50",
                    "--restart-repetitions",
                    "20",
                    "--socket-attempts",
                    "100",
                ],
            ),
            (
                "overhead-benchmark.json",
                [
                    "benchmark_overhead.py",
                    "--policy",
                    str(POLICY),
                ],
            ),
        )
        for filename, arguments in jobs:
            doctor(args.operator)
            run(
                [
                    sys.executable,
                    str(ROOT / "scripts" / arguments[0]),
                    *arguments[1:],
                    "--output",
                    str(evidence / filename),
                ]
            )
        summary.update(
            {
                "result": "PASS",
                "source_commit": policy["source_commit"],
                "version": checked["version"],
            }
        )
        (evidence / "validation.json").write_text(
            json.dumps(summary, sort_keys=True) + "\n", encoding="utf-8"
        )
        report = "# Lumi Eggcracker local validation\n\nPASS: the packaged deterministic, recognition, containment, boundary, recovery and overhead qualification jobs completed on the installed instance.\n"
        (evidence / "report.md").write_text(report, encoding="utf-8")
        sums = "".join(
            f"{digest(path)}  {path.name}\n"
            for path in sorted(evidence.iterdir())
            if path.name != "SHA256SUMS"
        )
        (evidence / "SHA256SUMS").write_text(sums, encoding="utf-8")
        print(json.dumps({"evidence_dir": str(evidence), **summary}, sort_keys=True))
        return 0
    except (
        OSError,
        RuntimeError,
        TypeError,
        ValueError,
        json.JSONDecodeError,
        subprocess.SubprocessError,
    ) as error:
        summary["error"] = str(error)
        if evidence is not None:
            (evidence / "validation.json").write_text(
                json.dumps(summary, sort_keys=True) + "\n", encoding="utf-8"
            )
        raise SystemExit(f"self-validation failed: {error}") from error


if __name__ == "__main__":
    raise SystemExit(main())