Spaces:
Running
Running
Sync GitHub source 592c8cbe7e8b6d8907cc52fae8436438d95b8127
Browse filesCanonical source: https://github.com/noqt/Lumi-Eggcracker/commit/592c8cbe7e8b6d8907cc52fae8436438d95b8127
Files changed (9)
- HUGGINGFACE_MANIFEST.json+22-6
- HUGGINGFACE_SYNC.json+4-4
- README.md+1-1
- TRY_IT.md+75-20
- examples/observe-first/lumi-eggcracker-observe-first.pyzAdded
- examples/observe-first/lumi-eggcracker-observe-first.pyz.sha256Added+1
- index.html+2-2
- scripts/build_observe_first_zipapp.pyAdded+287
- tests/test_observe_first_zipapp.pyAdded+183
36 unmodified lines3738394041424313 unmodified lines575859606162636451 unmodified lines11611711811912012179 unmodified lines20120220320420520620744 unmodified lines252253254255256257470 unmodified lines728729730731732733129 unmodified lines86386486586686786836 unmodified lines"size": 10537},"README.md": {"sha256": "cb48f95367b791fe2eaf46822e212e19c00b859a857fd464f6088db31299f399","size": 48062},"RELEASE_NOTES.md": {13 unmodified lines"size": 1970},"TRY_IT.md": {"sha256": "981811ae0615e0172bf8a8d32103351d5d1be995ddeaebcc7cd6d8377fa7ad01","size": 11403},"actions/validate-hosted-proof-receipt/action.yml": {"sha256": "4f66f6bfe972a945cdb686a570f51aeb7a474c48986608c9de862dfb6cf27ab3",51 unmodified lines"sha256": "a4293e0147a43483d17eb6983ffb8d46ee5f767a978f018ce5080cb37cf9fee7","size": 304},"examples/observe-first/partial-match.json": {"sha256": "2c4ec5b4c8074225aaee5e9c41aa2535cd0d4e85a7ec243dcb71f996d08a0ee2","size": 31579 unmodified lines"size": 4101},"index.html": {"sha256": "ebbbc8a071a980be63165c9553fae69cfdab7d6fbe65b6ccc6e7b4866876981f","size": 22790},"integrations/prometheus/eggcracker.rules.yml": {44 unmodified lines"sha256": "2b21689c110c4c01a998cd10b014b22ad11957758dacb793e9fda5ccc9a782e8","size": 17005},"scripts/build_release.py": {"sha256": "c3792b513b4f2811d31da7783331e7b918de243d46bd949467ff4fa11bb55746","size": 7625470 unmodified lines"sha256": "146a10077b6e90a75971677e48b7030955f89f114aef85e7bb757bd0643c3550","size": 6990},"tests/test_offline_boundary.py": {"sha256": "2138cae662b8d1a0f1b4cf7ae63ce0aef7ca887aa2d3cf684a6ef82ef46737d5","size": 9742129 unmodified lines},"schema": "noqt.huggingface_manifest.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "47b822ca5d1dcc753535a7c2fcb74aece7f9b73d","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/47b822ca5d1dcc753535a7c2fcb74aece7f9b73d"}36 unmodified lines3738394041424313 unmodified lines575859606162636451 unmodified lines11611711811912012112212312412512612712812979 unmodified lines20921021121221321421544 unmodified lines260261262263264265266267268269470 unmodified lines740741742743744745746747748749129 unmodified lines87988088188288388436 unmodified lines"size": 10537},"README.md": {"sha256": "edef2906f69c4c818aae37d9447b06da8bf536417b2451523e9799a76a4b00c0","size": 48062},"RELEASE_NOTES.md": {13 unmodified lines"size": 1970},"TRY_IT.md": {"sha256": "8f055baf9d4ffd208db06a80d57d6775b89654317fc14c3cf732ec1aa21b2076","size": 14917},"actions/validate-hosted-proof-receipt/action.yml": {"sha256": "4f66f6bfe972a945cdb686a570f51aeb7a474c48986608c9de862dfb6cf27ab3",51 unmodified lines"sha256": "a4293e0147a43483d17eb6983ffb8d46ee5f767a978f018ce5080cb37cf9fee7","size": 304},"examples/observe-first/lumi-eggcracker-observe-first.pyz": {"sha256": "2cc33f9b61eb22e0b456ad37c7938dd51ff9a74b7950d57e9747231eac818fa7","size": 38881},"examples/observe-first/lumi-eggcracker-observe-first.pyz.sha256": {"sha256": "4411f50b29e58f52a40c54f7a7d7a16729273deca89be9c8e1a00fa6c2d49b1a","size": 100},"examples/observe-first/partial-match.json": {"sha256": "2c4ec5b4c8074225aaee5e9c41aa2535cd0d4e85a7ec243dcb71f996d08a0ee2","size": 31579 unmodified lines"size": 4101},"index.html": {"sha256": "0fed8adb502782875768dbb8d6a82afdd95ff3d762002977d4b2eff0189d5af5","size": 22790},"integrations/prometheus/eggcracker.rules.yml": {44 unmodified lines"sha256": "2b21689c110c4c01a998cd10b014b22ad11957758dacb793e9fda5ccc9a782e8","size": 17005},"scripts/build_observe_first_zipapp.py": {"sha256": "b57cbffdd1e6ec0d38742923849b55b36878d76eb9f91c1e35aaacc52ae770fb","size": 10122},"scripts/build_release.py": {"sha256": "c3792b513b4f2811d31da7783331e7b918de243d46bd949467ff4fa11bb55746","size": 7625470 unmodified lines"sha256": "146a10077b6e90a75971677e48b7030955f89f114aef85e7bb757bd0643c3550","size": 6990},"tests/test_observe_first_zipapp.py": {"sha256": "5659f6c2392ed3274b035332e3579971ccc9be2397be939aea9e5bb6000d757c","size": 7486},"tests/test_offline_boundary.py": {"sha256": "2138cae662b8d1a0f1b4cf7ae63ce0aef7ca887aa2d3cf684a6ef82ef46737d5","size": 9742129 unmodified lines},"schema": "noqt.huggingface_manifest.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "592c8cbe7e8b6d8907cc52fae8436438d95b8127","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/592c8cbe7e8b6d8907cc52fae8436438d95b8127"}
123456757 unmodified lines65666768697071{"manifest": "HUGGINGFACE_MANIFEST.json","manifest_sha256": "fb6aa860fd63c02fb5681b6c582e93c64822f607e17db6de45e759a39faec9c9","mirrored_files": 200,"mode": "DERIVED_READ_ONLY_MIRROR","release_reference": {"assets": [57 unmodified lines},"schema": "noqt.huggingface_sync.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "47b822ca5d1dcc753535a7c2fcb74aece7f9b73d","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/47b822ca5d1dcc753535a7c2fcb74aece7f9b73d","target": "https://huggingface.co/spaces/noqt/eggcracker"}123456757 unmodified lines65666768697071{"manifest": "HUGGINGFACE_MANIFEST.json","manifest_sha256": "fe9cab4b55f8292aef0ecf3af75e078dfa157a76edcf3ee5112352d65ac2c848","mirrored_files": 204,"mode": "DERIVED_READ_ONLY_MIRROR","release_reference": {"assets": [57 unmodified lines},"schema": "noqt.huggingface_sync.v1","source_repository": "https://github.com/noqt/Lumi-Eggcracker","source_revision": "592c8cbe7e8b6d8907cc52fae8436438d95b8127","source_url": "https://github.com/noqt/Lumi-Eggcracker/commit/592c8cbe7e8b6d8907cc52fae8436438d95b8127","target": "https://huggingface.co/spaces/noqt/eggcracker"}
10 unmodified lines1112131415161710 unmodified lines---> Official noqt Hugging Face distribution, generated from GitHub commit> [`47b822ca5d1d`](https://github.com/noqt/Lumi-Eggcracker/commit/47b822ca5d1dcc753535a7c2fcb74aece7f9b73d). This Space distributes the source for> discovery and cloning; Eggcracker itself runs on a supported native Linux> host, not on Hugging Face. A snapshot is called current only after the> release-linked sync job verifies its returned Hub commit and full manifest.10 unmodified lines1112131415161710 unmodified lines---> Official noqt Hugging Face distribution, generated from GitHub commit> [`592c8cbe7e8b`](https://github.com/noqt/Lumi-Eggcracker/commit/592c8cbe7e8b6d8907cc52fae8436438d95b8127). This Space distributes the source for> discovery and cloning; Eggcracker itself runs on a supported native Linux> host, not on Hugging Face. A snapshot is called current only after the> release-linked sync job verifies its returned Hub commit and full manifest.
4 unmodified lines567891011121314151617181920212223244 unmodified lines2930313233343536373839404142434445464748494 unmodified lines## Source-only observe-first preview (unreleased)The current source checkout also contains a small, read-only synthetic preview.It is not part of signed v1.0.10 and makes no live-observation, approval,identity, topology, provenance, containment, safety, qualification, or releaseclaim. It reads one bounded JSON fixture, delegates to the bundled detectorcatalogue, prints a deterministic `WOULD_ACT` or `NO_COMPLETE_MATCH` result,and never writes an output file or performs actuation:```shPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/benign.jsonPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/complete-match.jsonPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/partial-match.json# Add --explain-selection only when you want the inert profile-selection explanation.PYTHONPATH=src python3 -m lumi_eggcracker.observe_first --explain-selection examples/observe-first/complete-match.json```4 unmodified linespython -m lumi_eggcracker.observe_first examples/observe-first/benign.jsonpython -m lumi_eggcracker.observe_first examples/observe-first/complete-match.jsonpython -m lumi_eggcracker.observe_first examples/observe-first/partial-match.json# Add --explain-selection only when you want the inert profile-selection explanation.python -m lumi_eggcracker.observe_first --explain-selection examples/observe-first/complete-match.json```This source-only preview is synthetic, quiescent and offline by construction.The partial fixture reports the catalogue requirements with supplied and missingevidence; an unknown or wrong-group identifier is rejected before any normaloutput. This preview is source-only, merged into the maintained main sourcebase, unreleased, not part of signed v1.0.10 and not native-qualified.The optional selection explanation names complete catalogue profiles and themaintained first-complete selection rule only; it does not claim true workloador framework identity, topology, provenance, safety, native qualification orauthorization. Nothing in this source-preview usage claims publication.The hosted proof below remains the supported disposable Linux demonstration ofthe native containment mechanism.## Start it with GitHub CLI4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283844 unmodified lines89909192939495969798991001011021031044 unmodified lines## Checkout-free source-only observe-first preview (unreleased)This separate preview runs on Python 3.11 or newer from a downloaded zipapp.It needs no Git checkout, package installation, or `PYTHONPATH`. Download thezipapp, its adjacent checksum file, and the synthetic fixture files into onedirectory. These links follow the current public `main` branch:- [Zipapp](https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/lumi-eggcracker-observe-first.pyz)- [Zipapp SHA-256 file](https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/lumi-eggcracker-observe-first.pyz.sha256)- [Benign fixture](https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/benign.json)- [Complete-match fixture](https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/complete-match.json)- [Partial-match fixture](https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/partial-match.json)On macOS or Linux, download the files and verify the adjacent checksum with`sha256sum`:```shmkdir -p observe-first-preview && cd observe-first-previewcurl -fSLO https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/lumi-eggcracker-observe-first.pyzcurl -fSLO https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/lumi-eggcracker-observe-first.pyz.sha256curl -fSLO https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/benign.jsoncurl -fSLO https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/complete-match.jsoncurl -fSLO https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first/partial-match.jsonsha256sum -c lumi-eggcracker-observe-first.pyz.sha256python3 --versionpython3 lumi-eggcracker-observe-first.pyz benign.jsonpython3 lumi-eggcracker-observe-first.pyz complete-match.jsonpython3 lumi-eggcracker-observe-first.pyz partial-match.jsonpython3 lumi-eggcracker-observe-first.pyz --explain-selection complete-match.json```On Windows PowerShell, run the equivalent commands:```powershell$previewDir = Join-Path (Get-Location) "observe-first-preview"New-Item -ItemType Directory -Path $previewDir -Force | Out-NullSet-Location $previewDir$baseUrl = "https://raw.githubusercontent.com/noqt/Lumi-Eggcracker/main/examples/observe-first"Invoke-WebRequest "$baseUrl/lumi-eggcracker-observe-first.pyz" -OutFile "lumi-eggcracker-observe-first.pyz"Invoke-WebRequest "$baseUrl/lumi-eggcracker-observe-first.pyz.sha256" -OutFile "lumi-eggcracker-observe-first.pyz.sha256"Invoke-WebRequest "$baseUrl/benign.json" -OutFile "benign.json"Invoke-WebRequest "$baseUrl/complete-match.json" -OutFile "complete-match.json"Invoke-WebRequest "$baseUrl/partial-match.json" -OutFile "partial-match.json"$checksumLine = (Get-Content "lumi-eggcracker-observe-first.pyz.sha256" -Raw).Trim()$checksumMatch = [regex]::Match($checksumLine, '^([0-9a-f]{64}) lumi-eggcracker-observe-first\.pyz$')if (-not $checksumMatch.Success) { throw "Checksum file format is invalid" }$expectedHash = $checksumMatch.Groups[1].Value$actualHash = (Get-FileHash "lumi-eggcracker-observe-first.pyz" -Algorithm SHA256).Hash.ToLowerInvariant()if ($actualHash -cne $expectedHash) { throw "Zipapp checksum mismatch" }python --versionpython .\lumi-eggcracker-observe-first.pyz .\benign.jsonpython .\lumi-eggcracker-observe-first.pyz .\complete-match.jsonpython .\lumi-eggcracker-observe-first.pyz .\partial-match.jsonpython .\lumi-eggcracker-observe-first.pyz --explain-selection .\complete-match.json```The archive's `SOURCE-MANIFEST.json` records base source commit`47b822ca5d1dcc753535a7c2fcb74aece7f9b73d` and SHA-256 values for everyincluded source member. The adjacent checksum detects a changed or incompletedownload; it is not a signature or independent authentication. The preview issynthetic, quiescent and offline. It reads one bounded JSON fixture, prints adeterministic `WOULD_ACT` or `NO_COMPLETE_MATCH` result, and performs no liveobservation, approval, output-file write, or actuation. The optional`--explain-selection` flag prints the inert catalogue-selection explanation.This source preview is unreleased, outside signed v1.0.10, and notnative-qualified. A non-match is not a safety result.If you already have a source checkout, the same preview can also be run fromits `src` directory without creating the zipapp:```shPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/benign.jsonPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/complete-match.jsonPYTHONPATH=src python3 -m lumi_eggcracker.observe_first examples/observe-first/partial-match.jsonPYTHONPATH=src python3 -m lumi_eggcracker.observe_first --explain-selection examples/observe-first/complete-match.json```4 unmodified linespython -m lumi_eggcracker.observe_first examples/observe-first/benign.jsonpython -m lumi_eggcracker.observe_first examples/observe-first/complete-match.jsonpython -m lumi_eggcracker.observe_first examples/observe-first/partial-match.jsonpython -m lumi_eggcracker.observe_first --explain-selection examples/observe-first/complete-match.json```For either entry point, the partial fixture reports catalogue requirementswith supplied and missing evidence. Unknown or wrong-group identifiers arerejected before normal output. The selection explanation names completecatalogue profiles and the maintained first-complete selection rule only; itdoes not establish true workload or framework identity, topology, provenance,safety, native qualification or authorization. Nothing in this source-previewusage claims publication.## Start it with GitHub CLI
12cc33f9b61eb22e0b456ad37c7938dd51ff9a74b7950d57e9747231eac818fa7 lumi-eggcracker-observe-first.pyz3 unmodified lines45678910638 unmodified lines6496506516526536546553 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><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."><meta name="noqt-source-revision" content="47b822ca5d1dcc753535a7c2fcb74aece7f9b73d"><meta name="theme-color" content="#090a0c"><title>Lumi Eggcracker — Native Linux AI kill switch</title><style>638 unmodified lines<section><div class="shell source-bar"><div><div class="source-id">SOURCE COMMIT · 47b822ca5d1d</div><h2>Inspect every line.</h2><p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p></div>3 unmodified lines45678910638 unmodified lines6496506516526536546553 unmodified lines<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><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."><meta name="noqt-source-revision" content="592c8cbe7e8b6d8907cc52fae8436438d95b8127"><meta name="theme-color" content="#090a0c"><title>Lumi Eggcracker — Native Linux AI kill switch</title><style>638 unmodified lines<section><div class="shell source-bar"><div><div class="source-id">SOURCE COMMIT · 592c8cbe7e8b</div><h2>Inspect every line.</h2><p>Complete source, tests, qualification documents and reproducible proof tooling are distributed in this repository.</p></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Build a deterministic source-only observe-first zipapp."""
from __future__ import annotations
import argparseimport hashlibimport ioimport jsonimport osimport statimport sysimport zipfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]SOURCE_COMMIT = "47b822ca5d1dcc753535a7c2fcb74aece7f9b73d"MAIN_MODULE = ( b"from lumi_eggcracker.observe_first import main\n" b"raise SystemExit(main())\n")ZIP_TIMESTAMP = (1980, 1, 1, 0, 0, 0)ZIP_MODE = stat.S_IFREG | 0o644MAX_SOURCE_BYTES = 8 * 1024 * 1024
SOURCE_INPUTS = ( ("LICENSE", "LICENSE", "50e6751797c50dedd75ef1b8a0d9e42f5f8472e9fbce91f34718e9f97b0c780a"), ( "src/lumi_eggcracker/__init__.py", "lumi_eggcracker/__init__.py", "8ca0bc0b310bfdfad676471477e28fe30d6311fef2c1360dc67a2c530e2acf34", ), ( "src/lumi_eggcracker/observe_first.py", "lumi_eggcracker/observe_first.py", "428997c394c5fc853e0fe5cce82b1c3eae2d09b2b72c27f35bea3e1ff9be2152", ), ( "src/lumi_eggcracker/detectors.py", "lumi_eggcracker/detectors.py", "d2f0485dbac785dce2bb5bcef451ddcb49fb5200f03e13b19acdcada3581bab7", ), ( "src/lumi_eggcracker/jsonio.py", "lumi_eggcracker/jsonio.py", "8d4955af0399dd478add5e50c2c2edc9f100ebeec49223d50c13280aef85dc15", ), ( "src/lumi_eggcracker/detector_catalogue.json", "lumi_eggcracker/detector_catalogue.json", "e0556219f7012b0657366af84804a1f3b5874d9f281a1341b4fa8ae819962c6d", ),)
class BuildError(Exception): """The requested source or output path is not safe for this build."""
def _is_reparse(metadata: os.stat_result) -> bool: reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) return bool(getattr(metadata, "st_file_attributes", 0) & reparse_flag)
def _is_safe_regular(metadata: os.stat_result) -> bool: return ( stat.S_ISREG(metadata.st_mode) and not stat.S_ISLNK(metadata.st_mode) and not _is_reparse(metadata) )
def _identity(metadata: os.stat_result) -> tuple[int, ...]: return ( stat.S_IFMT(metadata.st_mode), metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns, )
def _safe_directory_chain(directory: Path) -> Path: absolute = Path(os.path.abspath(os.fspath(directory))) chain = list(reversed((absolute, *absolute.parents))) for component in chain: try: metadata = component.lstat() except OSError as error: raise BuildError("an input or output parent cannot be inspected") from error if ( stat.S_ISLNK(metadata.st_mode) or _is_reparse(metadata) or not stat.S_ISDIR(metadata.st_mode) ): raise BuildError("input and output parents must be real directories") return absolute
def _read_regular_file(path: Path) -> bytes: _safe_directory_chain(path.parent) try: before = path.lstat() except OSError as error: raise BuildError("a required source file cannot be inspected") from error if not _is_safe_regular(before) or not 1 <= before.st_size <= MAX_SOURCE_BYTES: raise BuildError("a required source file is not a bounded regular file")
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) try: descriptor = os.open(path, flags) except OSError as error: raise BuildError("a required source file cannot be opened safely") from error
try: opened = os.fstat(descriptor) if not _is_safe_regular(opened) or _identity(opened) != _identity(before): raise BuildError("a source file changed while being opened") chunks: list[bytes] = [] total = 0 while True: chunk = os.read(descriptor, min(64 * 1024, MAX_SOURCE_BYTES + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > MAX_SOURCE_BYTES: raise BuildError("a required source file exceeds the size bound") after_open = os.fstat(descriptor) after_path = path.lstat() if ( not _is_safe_regular(after_open) or not _is_safe_regular(after_path) or _identity(opened) != _identity(after_open) or _identity(before) != _identity(after_path) or total != after_path.st_size ): raise BuildError("a source file changed while being read") return b"".join(chunks) except OSError as error: raise BuildError("a required source file cannot be read safely") from error finally: os.close(descriptor)
def _canonical_json(value: object) -> bytes: encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) return f"{encoded}\n".encode()
def _source_members() -> dict[str, bytes]: members = {"__main__.py": MAIN_MODULE} for source_name, archive_name, expected_digest in SOURCE_INPUTS: data = _read_regular_file(ROOT / source_name) actual_digest = hashlib.sha256(data).hexdigest() if actual_digest != expected_digest: raise BuildError(f"source identity mismatch for {source_name}") members[archive_name] = data
manifest = { "base_commit": SOURCE_COMMIT, "members": [ {"path": name, "sha256": hashlib.sha256(data).hexdigest()} for name, data in sorted(members.items()) ], "schema_version": "lumi-eggcracker.observe-first-source-manifest.v1", } members["SOURCE-MANIFEST.json"] = _canonical_json(manifest) return members
def _archive_bytes(members: dict[str, bytes]) -> bytes: output = io.BytesIO() with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive: archive.comment = b"" for name in sorted(members): info = zipfile.ZipInfo(name, date_time=ZIP_TIMESTAMP) info.compress_type = zipfile.ZIP_STORED info.create_system = 3 info.external_attr = ZIP_MODE << 16 info.internal_attr = 0 info.flag_bits = 0 info.extra = b"" info.comment = b"" archive.writestr(info, members[name]) return output.getvalue()
def _absolute_output(path: Path, *, label: str, suffix: str) -> Path: absolute = Path(os.path.abspath(os.fspath(path))) if not absolute.name or absolute.suffix.lower() != suffix: raise BuildError(f"{label} must have a {suffix} filename") _safe_directory_chain(absolute.parent) try: absolute.lstat() except FileNotFoundError: return absolute except OSError as error: raise BuildError(f"{label} cannot be inspected") from error raise BuildError(f"{label} must not already exist")
def _remove_if_owned(path: Path, identity: tuple[int, int]) -> None: try: metadata = path.lstat() if (metadata.st_dev, metadata.st_ino) == identity: path.unlink() except OSError: pass
def _write_new_file(path: Path, data: bytes) -> tuple[int, int]: _safe_directory_chain(path.parent) flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) try: descriptor = os.open(path, flags, 0o644) except OSError as error: raise BuildError("an output could not be created without overwriting") from error
opened = os.fstat(descriptor) identity = (opened.st_dev, opened.st_ino) try: view = memoryview(data) while view: written = os.write(descriptor, view) if written <= 0: raise OSError("short output write") view = view[written:] os.fsync(descriptor) return identity except OSError as error: _remove_if_owned(path, identity) raise BuildError("an output could not be written completely") from error finally: os.close(descriptor)
def _build(output: Path, checksum: Path) -> None: output = _absolute_output(output, label="zipapp output", suffix=".pyz") checksum = _absolute_output(checksum, label="checksum output", suffix=".sha256") if os.path.normcase(os.fspath(output)) == os.path.normcase(os.fspath(checksum)): raise BuildError("zipapp and checksum outputs must be different files")
for source_name, _, _ in SOURCE_INPUTS: source = Path(os.path.abspath(os.fspath(ROOT / source_name))) if os.path.normcase(os.fspath(source)) in { os.path.normcase(os.fspath(output)), os.path.normcase(os.fspath(checksum)), }: raise BuildError("an output path overlaps a source input")
archive_data = _archive_bytes(_source_members()) archive_digest = hashlib.sha256(archive_data).hexdigest() checksum_data = f"{archive_digest} {output.name}\n".encode("ascii") created: list[tuple[Path, tuple[int, int]]] = [] try: created.append((output, _write_new_file(output, archive_data))) created.append((checksum, _write_new_file(checksum, checksum_data))) except BuildError: for path, identity in reversed(created): _remove_if_owned(path, identity) raise
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path, help="new .pyz output path") parser.add_argument( "--checksum", type=Path, help="new checksum path (default: adjacent <output>.sha256)", ) args = parser.parse_args() output = args.output checksum = args.checksum or Path(f"{output}.sha256") try: _build(output, checksum) except BuildError as error: print(f"observe-first zipapp build refused: {error}", file=sys.stderr) return 2 except OSError: print("observe-first zipapp build refused: a file operation failed", file=sys.stderr) return 2 return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183from __future__ import annotations
import hashlibimport jsonimport osimport statimport subprocessimport sysimport tempfileimport zipfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]BUILDER = ROOT / "scripts" / "build_observe_first_zipapp.py"SOURCE_COMMIT = "47b822ca5d1dcc753535a7c2fcb74aece7f9b73d"MAIN_MODULE = ( b"from lumi_eggcracker.observe_first import main\n" b"raise SystemExit(main())\n")PINNED_HASHES = { "LICENSE": "50e6751797c50dedd75ef1b8a0d9e42f5f8472e9fbce91f34718e9f97b0c780a", "lumi_eggcracker/__init__.py": ( "8ca0bc0b310bfdfad676471477e28fe30d6311fef2c1360dc67a2c530e2acf34" ), "lumi_eggcracker/observe_first.py": ( "428997c394c5fc853e0fe5cce82b1c3eae2d09b2b72c27f35bea3e1ff9be2152" ), "lumi_eggcracker/detectors.py": ( "d2f0485dbac785dce2bb5bcef451ddcb49fb5200f03e13b19acdcada3581bab7" ), "lumi_eggcracker/jsonio.py": ( "8d4955af0399dd478add5e50c2c2edc9f100ebeec49223d50c13280aef85dc15" ), "lumi_eggcracker/detector_catalogue.json": ( "e0556219f7012b0657366af84804a1f3b5874d9f281a1341b4fa8ae819962c6d" ),}MANIFEST_NAME = "SOURCE-MANIFEST.json"MANIFEST_SCHEMA = "lumi-eggcracker.observe-first-source-manifest.v1"
def _run_builder( output: Path, *, checksum: Path | None = None) -> subprocess.CompletedProcess[bytes]: command = [sys.executable, str(BUILDER), "--output", str(output)] if checksum is not None: command.extend(["--checksum", str(checksum)]) environment = os.environ.copy() environment.pop("PYTHONPATH", None) environment["PYTHONDONTWRITEBYTECODE"] = "1" return subprocess.run(command, capture_output=True, cwd=ROOT, env=environment, check=False)
def _reference_environment() -> dict[str, str]: environment = os.environ.copy() environment.pop("PYTHONPATH", None) environment["PYTHONPATH"] = str(ROOT / "src") environment["PYTHONDONTWRITEBYTECODE"] = "1" return environment
def _expected_members() -> dict[str, str]: return {**PINNED_HASHES, "__main__.py": hashlib.sha256(MAIN_MODULE).hexdigest()}
def test_build_is_deterministic_and_binds_exact_source_members() -> None: with tempfile.TemporaryDirectory(prefix="observe-first-zipapp-build-") as raw: directory = Path(raw) first = directory / "first.pyz" second = directory / "second.pyz" second_checksum = directory / "second-checksum.sha256" first_result = _run_builder(first) second_result = _run_builder(second, checksum=second_checksum)
assert first_result.returncode == 0, first_result.stderr.decode("utf-8", errors="replace") assert second_result.returncode == 0, second_result.stderr.decode("utf-8", errors="replace") assert first.read_bytes() == second.read_bytes()
first_checksum = Path(f"{first}.sha256") first_digest = hashlib.sha256(first.read_bytes()).hexdigest() second_digest = hashlib.sha256(second.read_bytes()).hexdigest() assert first_checksum.read_text(encoding="ascii") == f"{first_digest} {first.name}\n" assert second_checksum.read_text(encoding="ascii") == f"{second_digest} {second.name}\n"
expected_members = _expected_members() with zipfile.ZipFile(first) as archive: infos = archive.infolist() names = [item.filename for item in infos] assert names == sorted(names) assert set(names) == {*expected_members, MANIFEST_NAME} for info in infos: assert info.date_time == (1980, 1, 1, 0, 0, 0) assert info.create_system == 3 assert info.compress_type == zipfile.ZIP_STORED assert stat.S_IFMT(info.external_attr >> 16) == stat.S_IFREG assert stat.S_IMODE(info.external_attr >> 16) == 0o644
for name, expected_digest in expected_members.items(): member = archive.read(name) assert hashlib.sha256(member).hexdigest() == expected_digest assert archive.read("__main__.py") == MAIN_MODULE
expected_manifest = { "base_commit": SOURCE_COMMIT, "members": [ {"path": name, "sha256": expected_members[name]} for name in sorted(expected_members) ], "schema_version": MANIFEST_SCHEMA, } manifest_bytes = archive.read(MANIFEST_NAME) assert manifest_bytes == ( json.dumps(expected_manifest, sort_keys=True, separators=(",", ":")) + "\n" ).encode("utf-8")
def test_zipapp_matches_pinned_source_module_and_rejects_malformed_input() -> None: with tempfile.TemporaryDirectory(prefix="observe-first-zipapp-run-") as raw: directory = Path(raw) archive_path = directory / "observe-first.pyz" result = _run_builder(archive_path) assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
run_directory = directory / "clean-cwd" run_directory.mkdir() archive_environment = os.environ.copy() archive_environment.pop("PYTHONPATH", None) archive_environment["PYTHONDONTWRITEBYTECODE"] = "1" reference_environment = _reference_environment()
cases = ( ("benign.json", ()), ("complete-match.json", ()), ("partial-match.json", ()), ("complete-match.json", ("--explain-selection",)), ) for fixture_name, flags in cases: fixture = ROOT / "examples" / "observe-first" / fixture_name archive_command = [sys.executable, str(archive_path), *flags, str(fixture)] archive_result = subprocess.run( archive_command, capture_output=True, cwd=run_directory, env=archive_environment, check=False, ) source_command = [ sys.executable, "-m", "lumi_eggcracker.observe_first", *flags, str(fixture), ] source_result = subprocess.run( source_command, capture_output=True, cwd=run_directory, env=reference_environment, check=False, ) assert archive_result.returncode == source_result.returncode assert archive_result.returncode == 0, archive_result.stderr.decode( "utf-8", errors="replace" ) assert source_result.returncode == 0, source_result.stderr.decode( "utf-8", errors="replace" ) assert archive_result.stderr == source_result.stderr assert json.loads(archive_result.stdout) == json.loads(source_result.stdout) assert archive_result.stdout == source_result.stdout
malformed = run_directory / "malformed.json" malformed.write_bytes(b'{"schema_version":') malformed_result = subprocess.run( [sys.executable, str(archive_path), str(malformed)], capture_output=True, cwd=run_directory, env=archive_environment, check=False, ) assert malformed_result.returncode == 2 assert malformed_result.stdout == b"" assert b"Traceback" not in malformed_result.stderrHUGGINGFACE_MANIFEST.json+22-6
HUGGINGFACE_SYNC.json+4-4
README.md+1-1
TRY_IT.md+75-20
examples/observe-first/lumi-eggcracker-observe-first.pyzAdded
examples/observe-first/lumi-eggcracker-observe-first.pyz.sha256Added+1
index.html+2-2
scripts/build_observe_first_zipapp.pyAdded+287
tests/test_observe_first_zipapp.pyAdded+183