noqt commited on
Commit
09d7817
·
verified ·
1 Parent(s): 085f660

Sync GitHub source be65266003b1406483e36902be71bb8e6e6c49ec

Browse files

Canonical source: https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec

HUGGINGFACE_MANIFEST.json CHANGED
@@ -37,7 +37,7 @@
37
  "size": 10537
38
  },
39
  "README.md": {
40
- "sha256": "a18d3c31f1987f2fa031f9f86a8e74237cb8340325ccb23d98a903a6d1c5fb50",
41
  "size": 25049
42
  },
43
  "RELEASE_NOTES.md": {
@@ -73,8 +73,8 @@
73
  "size": 1494
74
  },
75
  "docs/BROKERED_OPERATOR.md": {
76
- "sha256": "ec25e416977a0b64d8df541b2308da946e14aa786b42daf28a9c1667ea8eda8e",
77
- "size": 11515
78
  },
79
  "docs/DETECTION_RECEIPT_EXPORT.md": {
80
  "sha256": "a3100dd3f281f880a1cc1a34b293bc55a2a2a87702b5a482e354578954cc8fa0",
@@ -189,7 +189,7 @@
189
  "size": 4101
190
  },
191
  "index.html": {
192
- "sha256": "73350ec089b45a9239f3b8e6e5532193b662e3b411ef8816920f1045916dfe55",
193
  "size": 22790
194
  },
195
  "integrations/prometheus/eggcracker.rules.yml": {
@@ -424,6 +424,10 @@
424
  "sha256": "4f22dab7aebbe43d17fb107972b28a3caec1942c022f82ab89a4cf3a775d65c9",
425
  "size": 549
426
  },
 
 
 
 
427
  "src/lumi_eggcracker/brokered/linux_ipc.py": {
428
  "sha256": "6c26fd8b79f013bbbec931aa30f7c0b6c1a7de70368fcaf6121de1db39f6cff2",
429
  "size": 32508
@@ -568,6 +572,10 @@
568
  "sha256": "414e36e22c6cf6f0cb1e9576c6e3cbca1929bba74c014257153284750f24202e",
569
  "size": 15450
570
  },
 
 
 
 
571
  "tests/test_brokered_linux_ipc.py": {
572
  "sha256": "e5b7bec974741e97fd9c1af35b6539bb3caf982e81e76f6652ea37a3584aeb1c",
573
  "size": 34985
@@ -819,6 +827,6 @@
819
  },
820
  "schema": "noqt.huggingface_manifest.v1",
821
  "source_repository": "https://github.com/noqt/Lumi-Eggcracker",
822
- "source_revision": "eba52968fad4f7ebf329d6f232d7854107032417",
823
- "source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417"
824
  }
 
37
  "size": 10537
38
  },
39
  "README.md": {
40
+ "sha256": "7690fb7783d34e793d5ade4805253d17de563fca17ad09748dde6669c23db09d",
41
  "size": 25049
42
  },
43
  "RELEASE_NOTES.md": {
 
73
  "size": 1494
74
  },
75
  "docs/BROKERED_OPERATOR.md": {
76
+ "sha256": "1fea0977311d62937936c3ea122abd23111c5f03115bcb0191f097eb266d514e",
77
+ "size": 13700
78
  },
79
  "docs/DETECTION_RECEIPT_EXPORT.md": {
80
  "sha256": "a3100dd3f281f880a1cc1a34b293bc55a2a2a87702b5a482e354578954cc8fa0",
 
189
  "size": 4101
190
  },
191
  "index.html": {
192
+ "sha256": "e079727522e20ab833db71426d7014ffee3d32e78531ff927ae2bd2667d5484d",
193
  "size": 22790
194
  },
195
  "integrations/prometheus/eggcracker.rules.yml": {
 
424
  "sha256": "4f22dab7aebbe43d17fb107972b28a3caec1942c022f82ab89a4cf3a775d65c9",
425
  "size": 549
426
  },
427
+ "src/lumi_eggcracker/brokered/compare_detection_receipts.py": {
428
+ "sha256": "81045b347b3b5e13408b3ab857c769ed0b76a290416434b948a5934686c190de",
429
+ "size": 18807
430
+ },
431
  "src/lumi_eggcracker/brokered/linux_ipc.py": {
432
  "sha256": "6c26fd8b79f013bbbec931aa30f7c0b6c1a7de70368fcaf6121de1db39f6cff2",
433
  "size": 32508
 
572
  "sha256": "414e36e22c6cf6f0cb1e9576c6e3cbca1929bba74c014257153284750f24202e",
573
  "size": 15450
574
  },
575
+ "tests/test_brokered_detection_receipt_comparison.py": {
576
+ "sha256": "7efdf0e8ec4001ddc03d4d06ccc20801ee8b8b26f3bccc3095a86f9cc204660b",
577
+ "size": 12517
578
+ },
579
  "tests/test_brokered_linux_ipc.py": {
580
  "sha256": "e5b7bec974741e97fd9c1af35b6539bb3caf982e81e76f6652ea37a3584aeb1c",
581
  "size": 34985
 
827
  },
828
  "schema": "noqt.huggingface_manifest.v1",
829
  "source_repository": "https://github.com/noqt/Lumi-Eggcracker",
830
+ "source_revision": "be65266003b1406483e36902be71bb8e6e6c49ec",
831
+ "source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec"
832
  }
HUGGINGFACE_SYNC.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  "manifest": "HUGGINGFACE_MANIFEST.json",
3
- "manifest_sha256": "82ad3e95cc6ca1661fc9c09a3b85489d384d8f831c15f03eb957e80ffea005b9",
4
- "mirrored_files": 189,
5
  "mode": "DERIVED_READ_ONLY_MIRROR",
6
  "release_reference": {
7
  "assets": [
@@ -65,7 +65,7 @@
65
  },
66
  "schema": "noqt.huggingface_sync.v1",
67
  "source_repository": "https://github.com/noqt/Lumi-Eggcracker",
68
- "source_revision": "eba52968fad4f7ebf329d6f232d7854107032417",
69
- "source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417",
70
  "target": "https://huggingface.co/spaces/noqt/eggcracker"
71
  }
 
1
  {
2
  "manifest": "HUGGINGFACE_MANIFEST.json",
3
+ "manifest_sha256": "fdeb610dbf0ef60b47c494232a7b331dcd41e8dd75f6347e2953ce1341c760dc",
4
+ "mirrored_files": 191,
5
  "mode": "DERIVED_READ_ONLY_MIRROR",
6
  "release_reference": {
7
  "assets": [
 
65
  },
66
  "schema": "noqt.huggingface_sync.v1",
67
  "source_repository": "https://github.com/noqt/Lumi-Eggcracker",
68
+ "source_revision": "be65266003b1406483e36902be71bb8e6e6c49ec",
69
+ "source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec",
70
  "target": "https://huggingface.co/spaces/noqt/eggcracker"
71
  }
README.md CHANGED
@@ -11,7 +11,7 @@ short_description: Native Linux kill switch for supported local-AI workloads
11
  ---
12
 
13
  > Official noqt Hugging Face distribution, generated from GitHub commit
14
- > [`eba52968fad4`](https://github.com/noqt/Lumi-Eggcracker/commit/eba52968fad4f7ebf329d6f232d7854107032417). This Space distributes the source for
15
  > discovery and cloning; Eggcracker itself runs on a supported native Linux
16
  > host, not on Hugging Face. A snapshot is called current only after the
17
  > release-linked sync job verifies its returned Hub commit and full manifest.
 
11
  ---
12
 
13
  > Official noqt Hugging Face distribution, generated from GitHub commit
14
+ > [`be65266003b1`](https://github.com/noqt/Lumi-Eggcracker/commit/be65266003b1406483e36902be71bb8e6e6c49ec). This Space distributes the source for
15
  > discovery and cloning; Eggcracker itself runs on a supported native Linux
16
  > host, not on Hugging Face. A snapshot is called current only after the
17
  > release-linked sync job verifies its returned Hub commit and full manifest.
docs/BROKERED_OPERATOR.md CHANGED
@@ -201,3 +201,41 @@ filesystem access outside the private state directory. Verified process
201
  termination is unsupported. The wall-clock expiry depends on the trusted
202
  service's local clock. Do not use a synthetic receipt as evidence that a real
203
  process was admitted, dispatched, stopped, contained, or verified empty.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  termination is unsupported. The wall-clock expiry depends on the trusted
202
  service's local clock. Do not use a synthetic receipt as evidence that a real
203
  process was admitted, dispatched, stopped, contained, or verified empty.
204
+
205
+ ## Offline comparison of redacted detection exports
206
+
207
+ For a before/after review, the standard-library comparator accepts exactly two
208
+ explicit redacted exports and writes one bounded JSON object to stdout:
209
+
210
+ ```sh
211
+ python -B src/lumi_eggcracker/brokered/compare_detection_receipts.py \
212
+ --before ./detection-receipt-export-before.json \
213
+ --after ./detection-receipt-export-after.json
214
+ ```
215
+
216
+ Each input must be a normal, regular file no larger than the export ceiling of
217
+ 8 KiB. Parent directories must not contain symbolic links or Windows reparse
218
+ points. The comparator does not discover files, read raw receipts, import a
219
+ detector or containment runtime, create an output file, modify either input,
220
+ upload data, or contact a service. It rejects malformed, duplicate-key,
221
+ nonfinite, oversized, too-deep, and extra-field JSON with a fixed diagnostic
222
+ that does not echo a supplied path, field, value, or operating-system error.
223
+
224
+ The stdout allowlist reports the recorded source commit, version, catalogue
225
+ hash, detector profile, and result for each side, plus fixed change labels. A
226
+ `TERMINATED` to `CONTAINMENT_FAILED` transition is reported explicitly; an
227
+ unchanged result is reported as `UNCHANGED`. Both the input exports and the
228
+ comparison are labelled `NOT_AUTHENTICATED`, and live verification,
229
+ independent observation, native qualification, and performance evidence are
230
+ `NOT_PERFORMED`. The output describes recorded redacted data only; it is not a
231
+ live-safety, native-qualification, independent-use, or performance claim.
232
+
233
+ Timing is `UNAVAILABLE` when either export has no recorded timing, including a
234
+ failure export, and is never represented as zero. It is `INCOMPARABLE` when
235
+ the recorded source, version, catalogue, profile, trigger, or containment
236
+ primitive context differs. Only when that recorded context matches does the
237
+ tool show the two recorded durations and their arithmetic delta, labelled
238
+ `MATCHING_RECORDED_CONTEXT_ONLY`. It uses the exported duration fields after
239
+ validating their internal consistency; it never subtracts absolute monotonic
240
+ clock values and the exports provide no host or workload identity with which
241
+ to infer workload or performance comparability.
index.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <meta name="description" content="Lumi Eggcracker is noqt's native Linux kill switch for unapproved supported local-AI workloads. Clone the complete source from Hugging Face.">
7
- <meta name="noqt-source-revision" content="eba52968fad4f7ebf329d6f232d7854107032417">
8
  <meta name="theme-color" content="#090a0c">
9
  <title>Lumi Eggcracker — Native Linux AI kill switch</title>
10
  <style>
@@ -649,7 +649,7 @@ sudo /usr/bin/python3 -I -S scripts/first_kill.py \
649
  <section>
650
  <div class="shell source-bar">
651
  <div>
652
- <div class="source-id">SOURCE COMMIT · eba52968fad4</div>
653
  <h2>Inspect every line.</h2>
654
  <p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p>
655
  </div>
 
4
  <meta charset="utf-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
  <meta name="description" content="Lumi Eggcracker is noqt's native Linux kill switch for unapproved supported local-AI workloads. Clone the complete source from Hugging Face.">
7
+ <meta name="noqt-source-revision" content="be65266003b1406483e36902be71bb8e6e6c49ec">
8
  <meta name="theme-color" content="#090a0c">
9
  <title>Lumi Eggcracker — Native Linux AI kill switch</title>
10
  <style>
 
649
  <section>
650
  <div class="shell source-bar">
651
  <div>
652
+ <div class="source-id">SOURCE COMMIT · be65266003b1</div>
653
  <h2>Inspect every line.</h2>
654
  <p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p>
655
  </div>
src/lumi_eggcracker/brokered/compare_detection_receipts.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare two bounded, redacted detection receipt exports.
2
+
3
+ The comparator is deliberately offline. It reads exactly the two paths supplied
4
+ by its caller, validates the exporter v1 allowlist, and writes one bounded JSON
5
+ comparison to stdout. It does not import the detector, containment, broker, or
6
+ any other runtime code.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import datetime as dt
13
+ import json
14
+ import math
15
+ import os
16
+ import re
17
+ import stat
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ EXPORT_SCHEMA = "lumi-eggcracker.redacted-detection-receipt-export.v1"
23
+ COMPARISON_SCHEMA = "lumi-eggcracker.redacted-detection-receipt-comparison.v1"
24
+ RECEIPT_SCHEMA = "lumi-eggcracker.detection-receipt.v2"
25
+ DETECTOR_SCHEMA = "lumi-eggcracker.detectors.v3"
26
+ MAX_INPUT_BYTES = 8_192
27
+ MAX_OUTPUT_BYTES = 8_192
28
+ MAX_JSON_DEPTH = 64
29
+ MAX_MONOTONIC_NS = (1 << 63) - 1
30
+ _REPARSE_POINT = 0x400
31
+ _EVENT_ID = re.compile(r"[0-9a-f]{24}\Z")
32
+ _SHA256 = re.compile(r"[0-9a-f]{64}\Z")
33
+ _COMMIT = re.compile(r"[0-9a-f]{40}\Z")
34
+ _SEMVER = re.compile(
35
+ r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
36
+ r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
37
+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\Z"
38
+ )
39
+ _UTC_TIMESTAMP = re.compile(
40
+ r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
41
+ r"(?:\.[0-9]{1,6})?Z\Z"
42
+ )
43
+ _PROFILE_TRIGGER = {
44
+ "content.gguf-llama": "UNAPPROVED_AI_MATCH",
45
+ "content.gguf-ollama": "UNAPPROVED_OLLAMA_GGUF",
46
+ "content.safetensors-pytorch": "UNAPPROVED_SAFETENSORS_PYTORCH",
47
+ "content.safetensors-vllm": "UNAPPROVED_VLLM_SAFETENSORS",
48
+ }
49
+ _CONTAINMENT_PRIMITIVE = "pidfd-stop+cgroup.kill"
50
+ _TOP_LEVEL_FIELDS = {
51
+ "authentication",
52
+ "export_schema",
53
+ "live_verification",
54
+ "receipt",
55
+ "source_sha256",
56
+ }
57
+ _RECEIPT_FIELDS = {
58
+ "catalogue_sha256",
59
+ "detector",
60
+ "event_id",
61
+ "receipt_written_utc",
62
+ "recorded_result",
63
+ "schema_version",
64
+ "source_commit",
65
+ "trigger",
66
+ "version",
67
+ }
68
+ _DETECTOR_FIELDS = {"catalogue_schema", "detection_path", "profile"}
69
+ _TRIGGER_FIELDS = {"kind"}
70
+ _EVIDENCE_FIELDS = {
71
+ "empty_verified_monotonic_ns",
72
+ "first_stop_monotonic_ns",
73
+ "kill_write_completed_monotonic_ns",
74
+ "kill_write_started_monotonic_ns",
75
+ "primitive",
76
+ "qualification_to_first_stop_ms",
77
+ "root_populated",
78
+ "surviving_pids",
79
+ "trigger_to_empty_ms",
80
+ }
81
+
82
+
83
+ class ComparisonError(ValueError):
84
+ """A deliberately non-specific validation or filesystem failure."""
85
+
86
+
87
+ def _fail() -> None:
88
+ raise ComparisonError("comparison failed")
89
+
90
+
91
+ def _pairs_without_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
92
+ result: dict[str, Any] = {}
93
+ for key, value in pairs:
94
+ if key in result:
95
+ _fail()
96
+ result[key] = value
97
+ return result
98
+
99
+
100
+ def _parse_int(token: str) -> int:
101
+ if len(token) > 64:
102
+ _fail()
103
+ return int(token)
104
+
105
+
106
+ def _parse_float(token: str) -> float:
107
+ if len(token) > 128:
108
+ _fail()
109
+ value = float(token)
110
+ if not math.isfinite(value):
111
+ _fail()
112
+ mantissa = token.lower().split("e", maxsplit=1)[0]
113
+ if value == 0.0 and any(character in "123456789" for character in mantissa):
114
+ _fail()
115
+ return value
116
+
117
+
118
+ def _reject_constant(_token: str) -> None:
119
+ _fail()
120
+
121
+
122
+ def _check_depth(text: str) -> None:
123
+ depth = 0
124
+ quoted = False
125
+ escaped = False
126
+ for character in text:
127
+ if quoted:
128
+ if escaped:
129
+ escaped = False
130
+ elif character == "\\":
131
+ escaped = True
132
+ elif character == '"':
133
+ quoted = False
134
+ elif character == '"':
135
+ quoted = True
136
+ elif character in "[{":
137
+ depth += 1
138
+ if depth > MAX_JSON_DEPTH:
139
+ _fail()
140
+ elif character in "]}":
141
+ depth -= 1
142
+ if depth < 0:
143
+ _fail()
144
+ if quoted or escaped or depth:
145
+ _fail()
146
+
147
+
148
+ def _decode_export(raw: bytes) -> dict[str, Any]:
149
+ if type(raw) is not bytes or len(raw) > MAX_INPUT_BYTES:
150
+ _fail()
151
+ try:
152
+ text = raw.decode("utf-8")
153
+ _check_depth(text)
154
+ value = json.loads(
155
+ text,
156
+ object_pairs_hook=_pairs_without_duplicates,
157
+ parse_int=_parse_int,
158
+ parse_float=_parse_float,
159
+ parse_constant=_reject_constant,
160
+ )
161
+ except (ComparisonError, UnicodeDecodeError, json.JSONDecodeError, OverflowError, RecursionError, TypeError, ValueError):
162
+ _fail()
163
+ if not isinstance(value, dict):
164
+ _fail()
165
+ return value
166
+
167
+
168
+ def _path_without_parent_links(value: str | os.PathLike[str]) -> Path:
169
+ if not isinstance(value, (str, os.PathLike)):
170
+ _fail()
171
+ try:
172
+ path = Path(value)
173
+ if not path.is_absolute():
174
+ if path.drive:
175
+ _fail()
176
+ path = Path.cwd() / path
177
+ if not path.anchor or any(part == ".." for part in path.parts):
178
+ _fail()
179
+ if path.drive.startswith(("\\\\", "//")):
180
+ _fail()
181
+ # Reject Windows alternate data streams and device spellings. The
182
+ # comparator accepts ordinary files only; a colon is valid only in a
183
+ # drive anchor, never in a path component.
184
+ anchor_parts = len(Path(path.anchor).parts)
185
+ if any(":" in part for part in path.parts[anchor_parts:]):
186
+ _fail()
187
+ if os.name == "nt":
188
+ reserved = {"CON", "PRN", "AUX", "NUL"}
189
+ reserved.update({f"COM{index}" for index in range(1, 10)})
190
+ reserved.update({f"LPT{index}" for index in range(1, 10)})
191
+ for part in path.parts[anchor_parts:]:
192
+ stem = part.rstrip(" .").split(".", maxsplit=1)[0].upper()
193
+ if stem in reserved:
194
+ _fail()
195
+ return path
196
+ except (OSError, TypeError, ValueError):
197
+ _fail()
198
+
199
+
200
+ def _link_like(info: os.stat_result) -> bool:
201
+ attributes = getattr(info, "st_file_attributes", 0)
202
+ return stat.S_ISLNK(info.st_mode) or bool(attributes & _REPARSE_POINT)
203
+
204
+
205
+ def _check_directory_chain(path: Path) -> None:
206
+ try:
207
+ anchor = Path(path.anchor)
208
+ info = os.lstat(anchor)
209
+ if _link_like(info) or not stat.S_ISDIR(info.st_mode):
210
+ _fail()
211
+ for part in path.parts[len(anchor.parts) :]:
212
+ anchor = anchor / part
213
+ info = os.lstat(anchor)
214
+ if _link_like(info) or not stat.S_ISDIR(info.st_mode):
215
+ _fail()
216
+ except (OSError, ValueError):
217
+ _fail()
218
+
219
+
220
+ def _identity(info: os.stat_result) -> tuple[int, int]:
221
+ return info.st_dev, info.st_ino
222
+
223
+
224
+ def _read_source(path_value: str | os.PathLike[str]) -> bytes:
225
+ """Read one explicit regular file with bounded, race-aware checks."""
226
+
227
+ path = _path_without_parent_links(path_value)
228
+ _check_directory_chain(path.parent)
229
+ descriptor: int | None = None
230
+ try:
231
+ before = os.lstat(path)
232
+ if _link_like(before) or not stat.S_ISREG(before.st_mode):
233
+ _fail()
234
+ if before.st_size > MAX_INPUT_BYTES:
235
+ _fail()
236
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
237
+ flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
238
+ descriptor = os.open(path, flags)
239
+ opened = os.fstat(descriptor)
240
+ if (
241
+ not stat.S_ISREG(opened.st_mode)
242
+ or _link_like(opened)
243
+ or _identity(opened) != _identity(before)
244
+ or opened.st_size > MAX_INPUT_BYTES
245
+ ):
246
+ _fail()
247
+
248
+ chunks: list[bytes] = []
249
+ remaining = MAX_INPUT_BYTES + 1
250
+ while remaining:
251
+ chunk = os.read(descriptor, min(65_536, remaining))
252
+ if not chunk:
253
+ break
254
+ chunks.append(chunk)
255
+ remaining -= len(chunk)
256
+ raw = b"".join(chunks)
257
+ after = os.fstat(descriptor)
258
+ if (
259
+ len(raw) > MAX_INPUT_BYTES
260
+ or len(raw) != opened.st_size
261
+ or after.st_size != opened.st_size
262
+ or after.st_mtime_ns != opened.st_mtime_ns
263
+ or after.st_ctime_ns != opened.st_ctime_ns
264
+ ):
265
+ _fail()
266
+ return raw
267
+ except (ComparisonError, OSError, ValueError):
268
+ _fail()
269
+ finally:
270
+ if descriptor is not None:
271
+ try:
272
+ os.close(descriptor)
273
+ except OSError:
274
+ pass
275
+
276
+
277
+ def _expect_keys(value: object, expected: set[str]) -> dict[str, Any]:
278
+ if not isinstance(value, dict) or set(value) != expected:
279
+ _fail()
280
+ return value
281
+
282
+
283
+ def _required_text(
284
+ parent: dict[str, Any],
285
+ key: str,
286
+ pattern: re.Pattern[str],
287
+ *,
288
+ maximum: int = 128,
289
+ ) -> str:
290
+ value = parent.get(key)
291
+ if not isinstance(value, str) or len(value) > maximum or not pattern.fullmatch(value):
292
+ _fail()
293
+ return value
294
+
295
+
296
+ def _required_monotonic_ns(parent: dict[str, Any], key: str) -> int:
297
+ value = parent.get(key)
298
+ if type(value) is not int or not 0 <= value <= MAX_MONOTONIC_NS:
299
+ _fail()
300
+ return value
301
+
302
+
303
+ def _required_ms(parent: dict[str, Any], key: str) -> int | float:
304
+ value = parent.get(key)
305
+ if type(value) not in (int, float) or not math.isfinite(value):
306
+ _fail()
307
+ if not 0 <= value <= MAX_MONOTONIC_NS / 1_000_000:
308
+ _fail()
309
+ return value
310
+
311
+
312
+ def _validate_timestamp(value: Any) -> str:
313
+ if not isinstance(value, str) or not _UTC_TIMESTAMP.fullmatch(value):
314
+ _fail()
315
+ try:
316
+ dt.datetime.fromisoformat(value)
317
+ except ValueError:
318
+ _fail()
319
+ return value
320
+
321
+
322
+ def _validate_export(raw: bytes) -> dict[str, Any]:
323
+ document = _expect_keys(_decode_export(raw), _TOP_LEVEL_FIELDS)
324
+ if document["export_schema"] != EXPORT_SCHEMA:
325
+ _fail()
326
+ if document["authentication"] != "NOT_AUTHENTICATED":
327
+ _fail()
328
+ if document["live_verification"] != "NOT_PERFORMED":
329
+ _fail()
330
+ _required_text(document, "source_sha256", _SHA256, maximum=64)
331
+
332
+ receipt_value = document["receipt"]
333
+ if not isinstance(receipt_value, dict) or not (
334
+ set(receipt_value) == _RECEIPT_FIELDS
335
+ or set(receipt_value) == _RECEIPT_FIELDS | {"recorded_empty_evidence"}
336
+ ):
337
+ _fail()
338
+ receipt = receipt_value
339
+ if receipt["schema_version"] != RECEIPT_SCHEMA:
340
+ _fail()
341
+ _required_text(receipt, "event_id", _EVENT_ID, maximum=24)
342
+ source_commit = _required_text(receipt, "source_commit", _COMMIT, maximum=40)
343
+ version = _required_text(receipt, "version", _SEMVER, maximum=64)
344
+ catalogue_sha256 = _required_text(receipt, "catalogue_sha256", _SHA256, maximum=64)
345
+ receipt_written_utc = _validate_timestamp(receipt["receipt_written_utc"])
346
+
347
+ detector = _expect_keys(receipt["detector"], _DETECTOR_FIELDS)
348
+ profile = detector["profile"]
349
+ if not isinstance(profile, str) or profile not in _PROFILE_TRIGGER:
350
+ _fail()
351
+ if detector["detection_path"] != "CONTENT" or detector["catalogue_schema"] != DETECTOR_SCHEMA:
352
+ _fail()
353
+
354
+ trigger = _expect_keys(receipt["trigger"], _TRIGGER_FIELDS)
355
+ if trigger["kind"] != _PROFILE_TRIGGER[profile]:
356
+ _fail()
357
+
358
+ result = receipt["recorded_result"]
359
+ if result not in ("TERMINATED", "CONTAINMENT_FAILED"):
360
+ _fail()
361
+
362
+ evidence: dict[str, Any] | None = None
363
+ if result == "TERMINATED":
364
+ # The exporter always emits all timing/empty-state fields for a
365
+ # terminated result. Missing fields are invalid input, not zeroes.
366
+ if set(receipt) != _RECEIPT_FIELDS | {"recorded_empty_evidence"}:
367
+ _fail()
368
+ evidence = _expect_keys(receipt["recorded_empty_evidence"], _EVIDENCE_FIELDS)
369
+ if evidence["primitive"] != _CONTAINMENT_PRIMITIVE:
370
+ _fail()
371
+ if type(evidence["root_populated"]) is not int or evidence["root_populated"] != 0:
372
+ _fail()
373
+ if type(evidence["surviving_pids"]) is not list or evidence["surviving_pids"]:
374
+ _fail()
375
+
376
+ first_stop_ns = _required_monotonic_ns(evidence, "first_stop_monotonic_ns")
377
+ kill_started_ns = _required_monotonic_ns(evidence, "kill_write_started_monotonic_ns")
378
+ kill_completed_ns = _required_monotonic_ns(evidence, "kill_write_completed_monotonic_ns")
379
+ empty_ns = _required_monotonic_ns(evidence, "empty_verified_monotonic_ns")
380
+ if not first_stop_ns <= kill_started_ns <= kill_completed_ns <= empty_ns:
381
+ _fail()
382
+ qualification_ms = _required_ms(evidence, "qualification_to_first_stop_ms")
383
+ trigger_to_empty_ms = _required_ms(evidence, "trigger_to_empty_ms")
384
+ expected_trigger_to_empty_ms = (empty_ns - first_stop_ns) / 1_000_000
385
+ if not math.isclose(
386
+ trigger_to_empty_ms,
387
+ expected_trigger_to_empty_ms,
388
+ rel_tol=0.0,
389
+ abs_tol=1e-9,
390
+ ):
391
+ _fail()
392
+ timing = {
393
+ "qualification_to_first_stop_ms": qualification_ms,
394
+ "trigger_to_empty_ms": trigger_to_empty_ms,
395
+ "primitive": _CONTAINMENT_PRIMITIVE,
396
+ }
397
+ else:
398
+ # Failure exports intentionally contain neither timing nor raw error.
399
+ if set(receipt) != _RECEIPT_FIELDS:
400
+ _fail()
401
+ timing = None
402
+
403
+ return {
404
+ "source_commit": source_commit,
405
+ "version": version,
406
+ "catalogue_sha256": catalogue_sha256,
407
+ "profile": profile,
408
+ "trigger": trigger["kind"],
409
+ "recorded_result": result,
410
+ "receipt_written_utc": receipt_written_utc,
411
+ "timing": timing,
412
+ }
413
+
414
+
415
+ def _context(record: dict[str, Any]) -> tuple[str, ...]:
416
+ timing = record["timing"]
417
+ primitive = timing["primitive"] if timing is not None else ""
418
+ return (
419
+ record["source_commit"],
420
+ record["version"],
421
+ record["catalogue_sha256"],
422
+ record["profile"],
423
+ record["trigger"],
424
+ primitive,
425
+ )
426
+
427
+
428
+ def _result_change(before: str, after: str) -> str:
429
+ if before == after:
430
+ return "UNCHANGED"
431
+ if before == "TERMINATED" and after == "CONTAINMENT_FAILED":
432
+ return "TERMINATED_TO_CONTAINMENT_FAILED"
433
+ if before == "CONTAINMENT_FAILED" and after == "TERMINATED":
434
+ return "CONTAINMENT_FAILED_TO_TERMINATED"
435
+ return "CHANGED"
436
+
437
+
438
+ def _record_summary(record: dict[str, Any]) -> dict[str, str]:
439
+ return {
440
+ "source_commit": record["source_commit"],
441
+ "version": record["version"],
442
+ "catalogue_sha256": record["catalogue_sha256"],
443
+ "profile": record["profile"],
444
+ "recorded_result": record["recorded_result"],
445
+ }
446
+
447
+
448
+ def _timing_comparison(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
449
+ before_timing = before["timing"]
450
+ after_timing = after["timing"]
451
+ if before_timing is None or after_timing is None:
452
+ return {
453
+ "status": "UNAVAILABLE",
454
+ "basis": "MISSING_RECORDED_TIMING",
455
+ }
456
+ if _context(before) != _context(after):
457
+ return {
458
+ "status": "INCOMPARABLE",
459
+ "basis": "RECORDED_CONTEXT_MISMATCH",
460
+ }
461
+
462
+ before_durations = {
463
+ "qualification_to_first_stop_ms": before_timing["qualification_to_first_stop_ms"],
464
+ "trigger_to_empty_ms": before_timing["trigger_to_empty_ms"],
465
+ }
466
+ after_durations = {
467
+ "qualification_to_first_stop_ms": after_timing["qualification_to_first_stop_ms"],
468
+ "trigger_to_empty_ms": after_timing["trigger_to_empty_ms"],
469
+ }
470
+ return {
471
+ "status": "COMPARABLE",
472
+ "basis": "MATCHING_RECORDED_CONTEXT_ONLY",
473
+ "before_durations_ms": before_durations,
474
+ "after_durations_ms": after_durations,
475
+ "delta_ms": {
476
+ "qualification_to_first_stop_ms": (
477
+ after_durations["qualification_to_first_stop_ms"]
478
+ - before_durations["qualification_to_first_stop_ms"]
479
+ ),
480
+ "trigger_to_empty_ms": (
481
+ after_durations["trigger_to_empty_ms"]
482
+ - before_durations["trigger_to_empty_ms"]
483
+ ),
484
+ },
485
+ }
486
+
487
+
488
+ def compare_receipts(
489
+ before_path: str | os.PathLike[str],
490
+ after_path: str | os.PathLike[str],
491
+ ) -> dict[str, Any]:
492
+ """Return a fixed-field comparison of exactly two explicit exports."""
493
+
494
+ before = _validate_export(_read_source(before_path))
495
+ after = _validate_export(_read_source(after_path))
496
+ changes = {
497
+ "source_commit": "UNCHANGED" if before["source_commit"] == after["source_commit"] else "CHANGED",
498
+ "version": "UNCHANGED" if before["version"] == after["version"] else "CHANGED",
499
+ "catalogue_sha256": (
500
+ "UNCHANGED"
501
+ if before["catalogue_sha256"] == after["catalogue_sha256"]
502
+ else "CHANGED"
503
+ ),
504
+ "profile": "UNCHANGED" if before["profile"] == after["profile"] else "CHANGED",
505
+ "recorded_result": _result_change(
506
+ before["recorded_result"], after["recorded_result"]
507
+ ),
508
+ }
509
+ return {
510
+ "comparison_schema": COMPARISON_SCHEMA,
511
+ "authentication": "NOT_AUTHENTICATED",
512
+ "live_verification": "NOT_PERFORMED",
513
+ "comparison_status": "RECORDED",
514
+ "comparison_basis": "RECORDED_EXPORTS_ONLY",
515
+ "before": _record_summary(before),
516
+ "after": _record_summary(after),
517
+ "changes": changes,
518
+ "timing_comparison": _timing_comparison(before, after),
519
+ "native_qualification": "NOT_PERFORMED",
520
+ "independent_observation": "NOT_PERFORMED",
521
+ "performance_evidence": "NOT_PERFORMED",
522
+ }
523
+
524
+
525
+ def _encode_output(value: dict[str, Any]) -> bytes:
526
+ try:
527
+ encoded = (
528
+ json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n"
529
+ ).encode("utf-8")
530
+ except (TypeError, ValueError, OverflowError):
531
+ _fail()
532
+ if len(encoded) > MAX_OUTPUT_BYTES:
533
+ _fail()
534
+ return encoded
535
+
536
+
537
+ class _QuietArgumentParser(argparse.ArgumentParser):
538
+ def error(self, _message: str) -> None:
539
+ self.print_usage(sys.stderr)
540
+ self.exit(2, f"{self.prog}: invalid command line\n")
541
+
542
+
543
+ def main(argv: list[str] | None = None) -> int:
544
+ parser = _QuietArgumentParser(
545
+ prog="compare_detection_receipts.py",
546
+ description="Compare two explicit redacted detection receipt exports.",
547
+ )
548
+ parser.add_argument("--before", required=True, metavar="FILE", help="first export file")
549
+ parser.add_argument("--after", required=True, metavar="FILE", help="second export file")
550
+ args = parser.parse_args(argv)
551
+ try:
552
+ output = _encode_output(compare_receipts(args.before, args.after))
553
+ sys.stdout.write(output.decode("utf-8"))
554
+ except Exception: # noqa: BLE001 - never echo untrusted input or OS error text.
555
+ print("comparison failed: invalid redacted export or filesystem path", file=sys.stderr)
556
+ return 1
557
+ return 0
558
+
559
+
560
+ if __name__ == "__main__":
561
+ raise SystemExit(main())
tests/test_brokered_detection_receipt_comparison.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Focused tests for the offline redacted detection receipt comparator."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import importlib.util
7
+ import io
8
+ import json
9
+ import os
10
+ import tempfile
11
+ import unittest
12
+ from contextlib import redirect_stderr, redirect_stdout
13
+ from pathlib import Path
14
+
15
+ _MODULE_PATH = (
16
+ Path(__file__).parents[1]
17
+ / "src"
18
+ / "lumi_eggcracker"
19
+ / "brokered"
20
+ / "compare_detection_receipts.py"
21
+ )
22
+ _MODULE_SPEC = importlib.util.spec_from_file_location("compare_detection_receipts", _MODULE_PATH)
23
+ if _MODULE_SPEC is None or _MODULE_SPEC.loader is None: # pragma: no cover - test setup guard
24
+ raise ImportError("comparison module could not be loaded")
25
+ comparison = importlib.util.module_from_spec(_MODULE_SPEC)
26
+ _MODULE_SPEC.loader.exec_module(comparison)
27
+
28
+
29
+ def _document(
30
+ *,
31
+ result: str = "TERMINATED",
32
+ profile: str = "content.gguf-llama",
33
+ source_commit: str = "a" * 40,
34
+ version: str = "1.0.10",
35
+ catalogue_sha256: str = "b" * 64,
36
+ event_id: str = "0" * 24,
37
+ qualification_to_first_stop_ms: float = 5.0,
38
+ trigger_to_empty_ms: float = 0.25,
39
+ first_stop_ns: int = 1_000_000_000,
40
+ empty_ns: int = 1_000_250_000,
41
+ ) -> dict[str, object]:
42
+ receipt: dict[str, object] = {
43
+ "schema_version": comparison.RECEIPT_SCHEMA,
44
+ "event_id": event_id,
45
+ "source_commit": source_commit,
46
+ "version": version,
47
+ "catalogue_sha256": catalogue_sha256,
48
+ "receipt_written_utc": "2026-10-02T00:00:00Z",
49
+ "detector": {
50
+ "profile": profile,
51
+ "detection_path": "CONTENT",
52
+ "catalogue_schema": comparison.DETECTOR_SCHEMA,
53
+ },
54
+ "trigger": {"kind": comparison._PROFILE_TRIGGER[profile]},
55
+ "recorded_result": result,
56
+ }
57
+ if result == "TERMINATED":
58
+ receipt["recorded_empty_evidence"] = {
59
+ "empty_verified_monotonic_ns": empty_ns,
60
+ "first_stop_monotonic_ns": first_stop_ns,
61
+ "kill_write_completed_monotonic_ns": first_stop_ns + 200,
62
+ "kill_write_started_monotonic_ns": first_stop_ns + 100,
63
+ "primitive": comparison._CONTAINMENT_PRIMITIVE,
64
+ "qualification_to_first_stop_ms": qualification_to_first_stop_ms,
65
+ "root_populated": 0,
66
+ "surviving_pids": [],
67
+ "trigger_to_empty_ms": trigger_to_empty_ms,
68
+ }
69
+ return {
70
+ "export_schema": comparison.EXPORT_SCHEMA,
71
+ "source_sha256": "f" * 64,
72
+ "authentication": "NOT_AUTHENTICATED",
73
+ "live_verification": "NOT_PERFORMED",
74
+ "receipt": receipt,
75
+ }
76
+
77
+
78
+ def _write(path: Path, document: object, *, allow_nan: bool = False) -> None:
79
+ path.write_text(
80
+ json.dumps(document, sort_keys=True, separators=(",", ":"), allow_nan=allow_nan) + "\n",
81
+ encoding="utf-8",
82
+ )
83
+
84
+
85
+ class DetectionReceiptComparisonTests(unittest.TestCase):
86
+ def setUp(self) -> None:
87
+ # Leave the task-scoped fixtures in place so the guarded test runner can
88
+ # preserve its bounded artifacts without deleting any repository file.
89
+ self.root = Path(tempfile.mkdtemp(prefix="receipt-comparison-"))
90
+
91
+ def _write_document(self, name: str, **kwargs: object) -> Path:
92
+ path = self.root / name
93
+ _write(path, _document(**kwargs))
94
+ return path
95
+
96
+ @staticmethod
97
+ def _run_cli(before: Path, after: Path) -> tuple[int, str, str]:
98
+ stdout = io.StringIO()
99
+ stderr = io.StringIO()
100
+ with redirect_stdout(stdout), redirect_stderr(stderr):
101
+ status = comparison.main(
102
+ ["--before", str(before), "--after", str(after)]
103
+ )
104
+ return status, stdout.getvalue(), stderr.getvalue()
105
+
106
+ def test_matching_recorded_context_compares_durations_without_absolute_clock_subtraction(self) -> None:
107
+ before = self._write_document(
108
+ "before.json",
109
+ event_id="0" * 24,
110
+ qualification_to_first_stop_ms=5.0,
111
+ trigger_to_empty_ms=0.25,
112
+ first_stop_ns=3_000_000_000,
113
+ empty_ns=3_000_250_000,
114
+ )
115
+ after = self._write_document(
116
+ "after.json",
117
+ event_id="1" * 24,
118
+ qualification_to_first_stop_ms=7.0,
119
+ trigger_to_empty_ms=0.5,
120
+ first_stop_ns=1_000_000_000,
121
+ empty_ns=1_000_500_000,
122
+ )
123
+
124
+ output = comparison.compare_receipts(before, after)
125
+
126
+ self.assertEqual("RECORDED", output["comparison_status"])
127
+ self.assertEqual("NOT_AUTHENTICATED", output["authentication"])
128
+ self.assertEqual("NOT_PERFORMED", output["live_verification"])
129
+ self.assertEqual(
130
+ {
131
+ "source_commit": "UNCHANGED",
132
+ "version": "UNCHANGED",
133
+ "catalogue_sha256": "UNCHANGED",
134
+ "profile": "UNCHANGED",
135
+ "recorded_result": "UNCHANGED",
136
+ },
137
+ output["changes"],
138
+ )
139
+ self.assertEqual("COMPARABLE", output["timing_comparison"]["status"])
140
+ self.assertEqual(
141
+ "MATCHING_RECORDED_CONTEXT_ONLY",
142
+ output["timing_comparison"]["basis"],
143
+ )
144
+ self.assertEqual(
145
+ {"qualification_to_first_stop_ms": 2.0, "trigger_to_empty_ms": 0.25},
146
+ output["timing_comparison"]["delta_ms"],
147
+ )
148
+ self.assertNotIn("monotonic", json.dumps(output).lower())
149
+ self.assertLessEqual(len(comparison._encode_output(output)), comparison.MAX_OUTPUT_BYTES)
150
+
151
+ def test_terminated_to_failure_shows_transition_and_unavailable_timing(self) -> None:
152
+ before = self._write_document("before.json")
153
+ after = self._write_document(
154
+ "after.json",
155
+ result="CONTAINMENT_FAILED",
156
+ profile="content.gguf-ollama",
157
+ source_commit="d" * 40,
158
+ version="1.0.11",
159
+ catalogue_sha256="e" * 64,
160
+ event_id="2" * 24,
161
+ )
162
+
163
+ output = comparison.compare_receipts(before, after)
164
+
165
+ self.assertEqual("TERMINATED_TO_CONTAINMENT_FAILED", output["changes"]["recorded_result"])
166
+ self.assertEqual("UNAVAILABLE", output["timing_comparison"]["status"])
167
+ self.assertEqual("MISSING_RECORDED_TIMING", output["timing_comparison"]["basis"])
168
+ self.assertNotIn("delta_ms", output["timing_comparison"])
169
+ self.assertEqual("CONTAINMENT_FAILED", output["after"]["recorded_result"])
170
+
171
+ def test_mismatched_recorded_context_is_incomparable_without_durations(self) -> None:
172
+ before = self._write_document("before.json")
173
+ after = self._write_document(
174
+ "after.json",
175
+ profile="content.gguf-ollama",
176
+ source_commit="c" * 40,
177
+ version="1.0.11",
178
+ catalogue_sha256="d" * 64,
179
+ event_id="3" * 24,
180
+ first_stop_ns=10_000_000_000,
181
+ empty_ns=10_000_100_000,
182
+ trigger_to_empty_ms=0.1,
183
+ )
184
+
185
+ output = comparison.compare_receipts(before, after)
186
+
187
+ self.assertEqual("CHANGED", output["changes"]["profile"])
188
+ self.assertEqual("INCOMPARABLE", output["timing_comparison"]["status"])
189
+ self.assertEqual("RECORDED_CONTEXT_MISMATCH", output["timing_comparison"]["basis"])
190
+ self.assertNotIn("before_durations_ms", output["timing_comparison"])
191
+
192
+ def test_cli_normal_files_is_stdout_only_and_uses_fixed_safe_fields(self) -> None:
193
+ before = self._write_document("before.json")
194
+ after = self._write_document("after.json", event_id="4" * 24)
195
+ before_names = {entry.name for entry in self.root.iterdir()}
196
+
197
+ status, stdout, stderr = self._run_cli(before, after)
198
+
199
+ self.assertEqual(0, status)
200
+ self.assertEqual("", stderr)
201
+ parsed = json.loads(stdout)
202
+ self.assertEqual(comparison.COMPARISON_SCHEMA, parsed["comparison_schema"])
203
+ self.assertEqual(before_names, {entry.name for entry in self.root.iterdir()})
204
+ self.assertNotIn(str(before), stdout)
205
+ self.assertNotIn(str(after), stdout)
206
+ self.assertLessEqual(len(stdout.encode("utf-8")), comparison.MAX_OUTPUT_BYTES)
207
+
208
+ def test_strict_parser_rejects_malformed_oversized_duplicate_nonfinite_deep_and_extra_fields(self) -> None:
209
+ valid = self._write_document("valid.json")
210
+ cases: list[tuple[str, bytes, str]] = [
211
+ ("malformed", b"{", "malformed"),
212
+ (
213
+ "oversized",
214
+ b"{" + (b" " * comparison.MAX_INPUT_BYTES),
215
+ "oversized",
216
+ ),
217
+ (
218
+ "duplicate",
219
+ b'{"authentication":"NOT_AUTHENTICATED","authentication":"NOT_AUTHENTICATED"}',
220
+ "duplicate",
221
+ ),
222
+ (
223
+ "deep",
224
+ (b"[" * (comparison.MAX_JSON_DEPTH + 1))
225
+ + (b"]" * (comparison.MAX_JSON_DEPTH + 1)),
226
+ "deep",
227
+ ),
228
+ ]
229
+ extra = copy.deepcopy(_document())
230
+ extra["receipt"]["detector"]["raw"] = "SENSITIVE_SHOULD_NOT_ECHO"
231
+ cases.append(
232
+ (
233
+ "extra",
234
+ (
235
+ json.dumps(extra, sort_keys=True, separators=(",", ":")) + "\n"
236
+ ).encode("utf-8"),
237
+ "extra",
238
+ )
239
+ )
240
+ nonfinite = copy.deepcopy(_document())
241
+ nonfinite["receipt"]["recorded_empty_evidence"]["trigger_to_empty_ms"] = float("nan")
242
+ cases.append(
243
+ (
244
+ "nonfinite",
245
+ (
246
+ json.dumps(nonfinite, sort_keys=True, separators=(",", ":"), allow_nan=True)
247
+ + "\n"
248
+ ).encode("utf-8"),
249
+ "nonfinite",
250
+ )
251
+ )
252
+
253
+ for name, raw, _label in cases:
254
+ with self.subTest(case=name):
255
+ bad = self.root / f"{name}.json"
256
+ bad.write_bytes(raw)
257
+ status, stdout, stderr = self._run_cli(bad, valid)
258
+ self.assertEqual(1, status)
259
+ self.assertEqual("", stdout)
260
+ self.assertEqual(
261
+ "comparison failed: invalid redacted export or filesystem path\n", stderr
262
+ )
263
+ self.assertNotIn(str(bad), stderr)
264
+ self.assertNotIn("SENSITIVE_SHOULD_NOT_ECHO", stderr)
265
+
266
+ def test_inconsistent_timing_and_failure_evidence_are_rejected(self) -> None:
267
+ inconsistent = copy.deepcopy(_document())
268
+ inconsistent["receipt"]["recorded_empty_evidence"]["trigger_to_empty_ms"] = 9.0
269
+ first = self.root / "inconsistent.json"
270
+ _write(first, inconsistent)
271
+ second = self._write_document("second.json")
272
+ with self.assertRaises(comparison.ComparisonError):
273
+ comparison.compare_receipts(first, second)
274
+
275
+ failure_with_evidence = _document(result="CONTAINMENT_FAILED")
276
+ failure_with_evidence["receipt"]["recorded_empty_evidence"] = {}
277
+ failure = self.root / "failure-extra-evidence.json"
278
+ _write(failure, failure_with_evidence)
279
+ with self.assertRaises(comparison.ComparisonError):
280
+ comparison.compare_receipts(failure, second)
281
+
282
+ def test_symlink_input_is_rejected_when_platform_supports_symlinks(self) -> None:
283
+ source = self._write_document("source.json")
284
+ other = self._write_document("other.json", event_id="5" * 24)
285
+ linked = self.root / "linked.json"
286
+ try:
287
+ os.symlink(source, linked)
288
+ except (OSError, NotImplementedError):
289
+ self.skipTest("symlink creation is unavailable on this host")
290
+ with self.assertRaises(comparison.ComparisonError):
291
+ comparison.compare_receipts(linked, other)
292
+
293
+ def test_cli_argument_errors_and_windows_stream_spellings_are_generic(self) -> None:
294
+ source = self._write_document("source.json")
295
+ stdout = io.StringIO()
296
+ stderr = io.StringIO()
297
+ with (
298
+ redirect_stdout(stdout),
299
+ redirect_stderr(stderr),
300
+ self.assertRaises(SystemExit) as raised,
301
+ ):
302
+ comparison.main(["--before", str(source)])
303
+ self.assertEqual(2, raised.exception.code)
304
+ self.assertEqual("", stdout.getvalue())
305
+ self.assertTrue(stderr.getvalue().endswith("compare_detection_receipts.py: invalid command line\n"))
306
+ self.assertNotIn(str(source), stderr.getvalue())
307
+
308
+ with self.assertRaises(comparison.ComparisonError):
309
+ comparison.compare_receipts(str(source) + ":hidden-stream", source)
310
+
311
+
312
+ if __name__ == "__main__":
313
+ unittest.main()