From 7ad1a67ea84c59f071231c994c7b78b2c1a3b452 Mon Sep 17 00:00:00 2001 From: gspark-etri Date: Tue, 3 Nov 2026 06:48:01 +0900 Subject: [PATCH] Add public ATOM artifact metadata probe with interruption checkpoints --- bench/inspect_atom_artifacts.py | 217 +++++++++++++++++++++++ experiments/ATOM-INSPECT-PROTOCOL.md | 102 +++++++++++ tests/swap/test_atom_inspect.py | 253 +++++++++++++++++++++++++++ 3 files changed, 572 insertions(+) create mode 100644 bench/inspect_atom_artifacts.py create mode 100644 experiments/ATOM-INSPECT-PROTOCOL.md create mode 100644 tests/swap/test_atom_inspect.py diff --git a/bench/inspect_atom_artifacts.py b/bench/inspect_atom_artifacts.py new file mode 100644 index 0000000..8ac7578 --- /dev/null +++ b/bench/inspect_atom_artifacts.py @@ -0,0 +1,217 @@ +"""Collect public compiled-model metadata; does not create a native runtime.""" +import argparse +from datetime import datetime, timezone +import hashlib +import importlib +import importlib.metadata +import json +import math +import os +from pathlib import Path, PurePosixPath +import platform +import re +import stat +import sys +import time + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def save(output, result): + temporary = output / '.result.tmp' + try: + with temporary.open('w', encoding='utf-8', newline='\n') as stream: + json.dump(result, stream, ensure_ascii=False, allow_nan=False, indent=2) + stream.write('\n') + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, output / 'result.json') + finally: + temporary.unlink(missing_ok=True) + + +def error(phase, exception): + return dict(phase=phase, type=type(exception).__name__, message=str(exception)) + + +def validate_manifest(raw): + document = json.loads(raw) + if not isinstance(document, dict) or document.get('schema') != 'rngd-pd.atom-inspect-inputs.v1': + raise ValueError('unsupported input manifest schema') + rows = document.get('files') + if not isinstance(rows, list) or not 1 <= len(rows) <= 18: + raise ValueError('manifest requires1–18 compiled files') + seen = set() + for row in rows: + if not isinstance(row, dict): + raise ValueError('file entry must be an object') + name = row.get('path') + if not isinstance(name, str) or not name or '\\' in name or ':' in name: + raise ValueError('invalid input path') + relative = PurePosixPath(name) + if relative.is_absolute() or '..' in relative.parts or relative.as_posix() != name or relative.suffix != '.rbln': + raise ValueError('path must be a canonical relative .rbln path') + if name in seen: + raise ValueError('duplicate input path') + seen.add(name) + if type(row.get('bytes')) is not int or row['bytes'] <= 0: + raise ValueError('input size must be a positive integer') + if not isinstance(row.get('sha256'), str) or not re.fullmatch('[0-9a-f]{64}', row['sha256']): + raise ValueError('input SHA must be64 lowercase hex digits') + return rows + + +def fingerprint(path): + info = path.stat(follow_symlinks=False) + if not stat.S_ISREG(info.st_mode): + raise ValueError('input must be a regular file') + return [info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns] + + +def check_metadata(value): + if isinstance(value, dict): + for key, item in value.items(): + if not isinstance(key, str): + raise TypeError('metadata dictionary keys must be strings') + check_metadata(item) + elif isinstance(value, list): + for item in value: + check_metadata(item) + elif value is None or type(value) in (str, int, bool): + pass + elif type(value) is float and math.isfinite(value): + pass + else: + raise TypeError('metadata contains a non-JSON value: ' + type(value).__name__) + + +def inspect_file(root, expected, inspect, row, checkpoint): + row.update(path=expected['path'], expected_bytes=expected['bytes'], expected_sha256=expected['sha256'], + status='running', phase='input_hash', started_utc=now(), native_api_called=False) + checkpoint() + phase = 'input_hash' + started = time.perf_counter() + try: + path = root / expected['path'] + cursor = root + for component in PurePosixPath(expected['path']).parts: + cursor = cursor / component + if cursor.is_symlink(): + raise ValueError('symlink input is forbidden') + before = fingerprint(path) + row['input_stat_before'] = before + if before[2] != expected['bytes']: + raise ValueError('input size differs from frozen manifest') + digest = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): + digest.update(block) + row['observed_sha256'] = digest.hexdigest() + if fingerprint(path) != before: + raise ValueError('input changed during hashing') + if row['observed_sha256'] != expected['sha256']: + raise ValueError('input SHA differs from frozen manifest') + row['input_hash_s'] = time.perf_counter() - started + # A pre-call checkpoint cannot prove whether an abruptly terminated + # process actually entered the SDK, so its call outcome stays unknown. + row.update(phase='inspect_pending', native_api_called=None) + phase = 'output_snapshot' + checkpoint() + phase = 'inspect' + row['native_api_called'] = True + inspect_started = time.perf_counter() + try: + metadata = inspect(str(path)) + finally: + row['inspect_s'] = time.perf_counter() - inspect_started + phase = 'metadata' + if not isinstance(metadata, dict): + raise TypeError('inspect must return a metadata dictionary') + check_metadata(metadata) + if len(json.dumps(metadata, ensure_ascii=False, allow_nan=False).encode('utf-8')) > 8 * 1024 * 1024: + raise ValueError('metadata exceeds8MiB') + row['metadata'] = metadata + phase = 'input_stability' + row['input_stat_after'] = fingerprint(path) + if row['input_stat_after'] != before: + raise ValueError('input changed during inspection') + row['status'] = 'completed' + except Exception as exception: + row['status'] = 'failed' + row['error'] = error(phase, exception) + if phase == 'input_hash': + row['input_hash_s'] = time.perf_counter() - started + row['phase'] = 'completed' if row['status'] == 'completed' else phase + row['finished_utc'] = now() + return row + + +def run_probe(manifest_path, input_root, output): + root = Path(input_root).resolve(strict=True) + destination = Path(output).resolve() + if not root.is_dir() or destination == root or root in destination.parents: + raise ValueError('output must be outside the input tree') + destination.mkdir(parents=True, exist_ok=False) + result = dict(schema='rngd-pd.atom-inspect-result.v1', status='running', started_utc=now(), + command=sys.argv, source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + input_root=str(root), manifest_path=str(Path(manifest_path).resolve()), + python=platform.python_version(), platform=platform.platform(), + runtime_api_called=False, coverage='unknown', files=[], + interpretation='Declared metadata only; not exhaustive coverage, live allocation, residency or serving correctness') + save(destination, result) + phase = 'manifest' + try: + with Path(manifest_path).open('rb') as stream: + raw = stream.read(256 * 1024 + 1) + if len(raw) > 256 * 1024: + raise ValueError('manifest exceeds256KiB') + result['manifest_sha256'] = hashlib.sha256(raw).hexdigest() + (destination / 'inputs.json').write_bytes(raw) + rows = validate_manifest(raw) + result['expected_files'] = len(rows) + phase = 'sdk' + result['package_versions'] = {} + for name in ('rebel-compiler', 'rebel'): + try: + result['package_versions'][name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + result['package_versions'][name] = None + started = time.perf_counter() + try: + rebel = importlib.import_module('rebel') + inspect = rebel.RBLNCompiledModel.inspect + if not callable(inspect): + raise TypeError('public inspect API is not callable') + finally: + result['sdk_import_s'] = time.perf_counter() - started + phase = 'output_snapshot' + save(destination, result) + for expected in rows: + row = {} + result['files'].append(row) + inspect_file(root, expected, inspect, row, lambda: save(destination, result)) + save(destination, result) + result['status'] = 'completed' if all(row['status'] == 'completed' for row in result['files']) else 'failed' + except Exception as exception: + result['status'] = 'failed' + result['error'] = error(phase, exception) + result['finished_utc'] = now() + save(destination, result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--manifest', type=Path, required=True) + parser.add_argument('--input-root', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + result = run_probe(args.manifest, args.input_root, args.output) + print(json.dumps(dict(status=result['status'], files=len(result['files']), coverage='unknown'))) + return 0 if result['status'] == 'completed' else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/experiments/ATOM-INSPECT-PROTOCOL.md b/experiments/ATOM-INSPECT-PROTOCOL.md new file mode 100644 index 0000000..0736c66 --- /dev/null +++ b/experiments/ATOM-INSPECT-PROTOCOL.md @@ -0,0 +1,102 @@ +# Public ATOM artifact inspection plan + +Issue: https://github.com/ai-computing/rngd-pd/issues/55 + +## Question and scope + +What metadata does the installed SDK actually expose for the frozen compiled +artifacts? Use only `rebel.RBLNCompiledModel.inspect(path)`, documented at +https://docs.rbln.ai/v0.11.0/software/api/python/python_api.html. +Keep the complete JSON metadata and errors. Do not interpret proprietary +bytes, construct a compiled-model object, create a runtime, compile, infer, +or request an accelerator. The SDK owns the format interpretation. + +The result is metadata evidence, not a serving benchmark. An input shape is +not exhaustive bucket coverage; missing fields are unknown. Allocation +estimates do not establish measured memory or live weight sharing. The +installed package version does not establish an artifact's compiler version. +Retain both independently. No SDK or system installation is part of this work. + +## Input and output contract + +`bench/inspect_atom_artifacts.py --manifest INPUT.json --input-root ROOT +--output NEW_DIRECTORY` consumes this explicit, pre-frozen input list: + +```json +{"schema":"rngd-pd.atom-inspect-inputs.v1","files":[ + {"path":"relative/model.rbln","bytes":123,"sha256":"64 lowercase hex digits"} +]} +``` + +Use 1–18 unique regular `.rbln` files, a manifest at most256KiB, and an +immutable, read-only input tree. Reject absolute/traversing/backslash paths, +symlinks and output paths inside that tree. Compute each complete input SHA +and compare it before calling inspect; charge hashing separately. Check file +identity/stat stability across hashing and inspection. Those checks do not +replace the immutable-mount requirement or prove absence of adversarial +concurrent writes. Never derive expectations from names or stat alone. + +Create a fresh output directory and atomically replace only its own +`result.json` progress snapshot. Preserve every file attempt and continue +after an individual inspection failure. Environment/manifest failures are +explicit nonzero outcomes, not missing capabilities or successful probes. +Checkpoint the running path before hashing and its verified full SHA before +SDK dispatch. A pre-call checkpoint uses `native_api_called: null`: abrupt +termination may occur on either side of the actual call, so entry is unknown. +Interrupted `running` rows never count as completed observations. This is a +progress record, not a claim of crash/power-loss durability or native-call tracing. +Preserve native metadata only when it is a JSON-compatible dictionary; +otherwise report a serialization/type failure without stringifying arbitrary +SDK objects. Record actual command, source SHA, manifest SHA, timestamps, +package versions and separate hashing/inspection durations. Save stdout and +stderr separately at execution time. This is not an n5 latency result. + +## Execution boundary + +**Native status: not_run.** Existing serial transport owners must finish +before any new node call. A later CPU-only `cdx-` Job needs a deadline, TTL, +read-only model mount, no NPU resource request and an actual inspected input +manifest. No automatic launch, controller or follow-on serving run is added. +Follow-up native dispatch requires its own frozen workload, native alternatives, +one-card budget, quality criterion and smoke/main admission. + +## Implementation plan + +Goal: make the public metadata prerequisite reproducible without widening its claims. +Architecture: one stdlib CLI; the only vendor boundary is the lazy public inspect call. +Tech stack: Python3.10+, existing Rebel SDK only on the execution node. +Spec: the contracts above; base8124570a36074338930ec7b98b1a66124d4ac9c2. + +- [x] Write behavioral tests against real temporary files and an isolated SDK + boundary; observe failure with an unimplemented probe. +- [x] Implement input admission, exact hash binding, inspection/failure + collection and fresh atomic output. Run the new tests and related suite. +- [x] Run the full repository command; distinguish environment limitations + from source failures. Existing Windows Python lacks httpx, so its full + baseline collection fails in tests/native_v4/test_serve.py. No install is + authorized here; use existing Linux CI for complete regression coverage. +- [ ] Request one independent connected-source review, fix Important issues + with observed regression failures, open a draft PR and read actual CI logs. +- [ ] Preserve source/check receipts and update the private experiment board. + +Review focus: path escape/symlink or changed inputs; SDK/import/API absence; +non-JSON metadata; failure preservation/partial matrices; rerun/output overwrite. +Tests must not be described as real native inspection. + +Ruling: independent source review found that a result appended only after +inspection loses the current attempt on interruption. Two observed failing +regressions therefore require pre-hash and pre-call progress checkpoints; +SDK calls and completed observations remain distinct. + +Local validation: new29 passed/1 Windows symlink skip; independent recheck +ran the two interruption regressions plus atomic snapshot failure (3passed) +and found no remaining Important issue. The full local command cannot collect +`tests/native_v4/test_serve.py` because httpx is absent. With only that module +excluded, an intermediate-source run ended801passed/11skipped/4subtests and +two existing package-entry-point assertions failed: +`SelectionTests.test_shm_is_registered_and_default` and +`RunnerAndMetricsTests.test_runner_registered` in tests/test_airm.py. This +worktree is not installed as a distribution; setting PYTHONPATH supplies +imports but not installed entry-point metadata. This is not a full-suite pass. +Complete installed Linux CI is required before integration. Native status +remains not_run; no package install or node call was performed here. diff --git a/tests/swap/test_atom_inspect.py b/tests/swap/test_atom_inspect.py new file mode 100644 index 0000000..aaa7953 --- /dev/null +++ b/tests/swap/test_atom_inspect.py @@ -0,0 +1,253 @@ +"""Real file/output checks; the unavailable vendor SDK alone is substituted.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import subprocess +import sys +import types + +import pytest + + +@pytest.fixture +def probe(): + path = Path(__file__).parents[2] / 'bench/inspect_atom_artifacts.py' + spec = importlib.util.spec_from_file_location('atom_inspect', path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def inputs(tmp_path): + root = tmp_path / 'input' + root.mkdir() + (root / 'a.rbln').write_bytes(b'abc') + (root / 'b.rbln').write_bytes(b'def') + rows = [dict(path='a.rbln', bytes=3, sha256='ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'), + dict(path='b.rbln', bytes=3, sha256='cb8379ac2098aa165029e3938a51da0bcecfc008fd6795f401178647f96c5b34')] + manifest = tmp_path / 'inputs.json' + manifest.write_text(json.dumps(dict(schema='rngd-pd.atom-inspect-inputs.v1', files=rows))) + return root, manifest, tmp_path / 'output' + + +def sdk(monkeypatch, inspect): + class Compiled: + def __init__(self, *args, **kwargs): + raise AssertionError('compiled object must not be constructed') + + Compiled.inspect = staticmethod(inspect) + monkeypatch.setitem(sys.modules, 'rebel', types.SimpleNamespace(RBLNCompiledModel=Compiled)) + + +def test_complete_inputs_produce_exact_metadata_and_durable_result(probe, inputs, monkeypatch): + root, manifest, output = inputs + def inspect(path): + assert Path(path) in (root / 'a.rbln', root / 'b.rbln') + return {'compiler_version': 'example', 'inputs': [{'shape': [1, 128, 4096]}], 'unknown_vendor_field': {'x': None}} + sdk(monkeypatch, inspect) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'completed' + assert json.loads((output / 'result.json').read_text()) == result + assert [row['path'] for row in result['files']] == ['a.rbln', 'b.rbln'] + assert all(row['status'] == 'completed' for row in result['files']) + assert result['files'][0]['metadata'] == {'compiler_version': 'example', 'inputs': [{'shape': [1, 128, 4096]}], 'unknown_vendor_field': {'x': None}} + assert result['manifest_sha256'] == hashlib.sha256(manifest.read_bytes()).hexdigest() + assert result['files'][0]['observed_sha256'] == 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' + assert result['runtime_api_called'] is False and result['coverage'] == 'unknown' + + +def test_wrong_hash_prevents_inspection_but_later_input_is_preserved(probe, inputs, monkeypatch): + root, manifest, output = inputs + (root / 'a.rbln').write_bytes(b'bad') + def inspect(path): + assert Path(path).name == 'b.rbln' + return {'name': 'b'} + sdk(monkeypatch, inspect) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' + assert result['files'][0]['status'] == 'failed' + assert result['files'][0]['native_api_called'] is False + assert result['files'][0]['error']['phase'] == 'input_hash' + assert result['files'][1]['metadata'] == {'name': 'b'} + + +def test_native_failure_does_not_erase_earlier_or_later_attempts(probe, inputs, monkeypatch): + root, manifest, output = inputs + def inspect(path): + if Path(path).name == 'a.rbln': + raise RuntimeError('native format refused') + return {'name': 'b'} + sdk(monkeypatch, inspect) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' + assert result['files'][0]['native_api_called'] is True + assert result['files'][0]['error'] == dict(phase='inspect', type='RuntimeError', message='native format refused') + assert result['files'][1]['status'] == 'completed' + assert json.loads((output / 'result.json').read_text())['status'] == 'failed' + + +@pytest.mark.parametrize('bad', [None, [], {'bad': object()}, {'nan': float('nan')}, {1: 'not a string key'}, {'tuple': (1, 2)}]) +def test_non_json_metadata_is_an_explicit_failure(probe, inputs, monkeypatch, bad): + root, manifest, output = inputs + sdk(monkeypatch, lambda path: bad) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' + assert all(row['error']['phase'] == 'metadata' for row in result['files']) + assert all('metadata' not in row for row in result['files']) + + +@pytest.mark.parametrize('bad_path', ['../a.rbln', '/a.rbln', 'C:/a.rbln', 'x\\a.rbln', 'a.txt', './a.rbln', 'x//a.rbln']) +def test_invalid_manifest_path_is_rejected_before_sdk_import(probe, inputs, bad_path, monkeypatch): + root, manifest, output = inputs + document = json.loads(manifest.read_text()) + document['files'][0]['path'] = bad_path + manifest.write_text(json.dumps(document)) + monkeypatch.setitem(sys.modules, 'rebel', None) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' and result['files'] == [] + assert result['error']['phase'] == 'manifest' + + +def test_duplicate_inputs_are_not_counted_twice(probe, inputs): + root, manifest, output = inputs + document = json.loads(manifest.read_text()) + document['files'][1] = document['files'][0].copy() + manifest.write_text(json.dumps(document)) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' and result['error']['phase'] == 'manifest' + + +def test_symlink_cannot_escape_input_root(probe, inputs, monkeypatch): + root, manifest, output = inputs + outside = root.parent / 'outside.rbln' + outside.write_bytes(b'abc') + (root / 'a.rbln').unlink() + try: + (root / 'a.rbln').symlink_to(outside) + except OSError: + pytest.skip('Windows symlink privilege unavailable; exercised on Linux CI') + sdk(monkeypatch, lambda path: {'name': 'b'}) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' and result['files'][0]['native_api_called'] is False + + +def test_sdk_absence_is_not_an_artifact_capability_refusal(probe, inputs, monkeypatch): + root, manifest, output = inputs + monkeypatch.setitem(sys.modules, 'rebel', None) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' and result['files'] == [] + assert result['error']['phase'] == 'sdk' + assert result['coverage'] == 'unknown' + + +def test_input_modified_during_inspection_invalidates_metadata(probe, inputs, monkeypatch): + root, manifest, output = inputs + def inspect(path): + Path(path).write_bytes(b'changed') + return {'would_be_valid': True} + sdk(monkeypatch, inspect) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' + assert all(row['error']['phase'] == 'input_stability' for row in result['files']) + assert all(row['metadata'] == {'would_be_valid': True} for row in result['files']) + + +def test_existing_output_is_never_overwritten(probe, inputs): + root, manifest, output = inputs + output.mkdir() + (output / 'result.json').write_bytes(b'old evidence') + with pytest.raises(FileExistsError): + probe.run_probe(manifest, root, output) + assert (output / 'result.json').read_bytes() == b'old evidence' + + +def test_output_cannot_modify_readonly_input_tree(probe, inputs): + root, manifest, output = inputs + with pytest.raises(ValueError, match='input'): + probe.run_probe(manifest, root, root / 'output') + assert not (root / 'output').exists() + + +def test_cli_records_bad_manifest_and_returns_nonzero(probe, inputs): + root, manifest, output = inputs + manifest.write_bytes(b'{not json') + completed = subprocess.run([sys.executable, probe.__file__, '--manifest', str(manifest), '--input-root', str(root), '--output', str(output)], capture_output=True) + assert completed.returncode == 1 + result = json.loads((output / 'result.json').read_text()) + assert result['error']['phase'] == 'manifest' + assert result['manifest_sha256'] == hashlib.sha256(b'{not json').hexdigest() + assert (output / 'inputs.json').read_bytes() == b'{not json' + + +def test_interrupted_snapshot_preserves_previous_evidence(probe, tmp_path, monkeypatch): + probe.save(tmp_path, {'status': 'running', 'files': [{'path': 'a.rbln'}]}) + before = (tmp_path / 'result.json').read_bytes() + def fail_replace(source, destination): + raise OSError('simulated storage interruption') + monkeypatch.setattr(probe.os, 'replace', fail_replace) + with pytest.raises(OSError, match='storage interruption'): + probe.save(tmp_path, {'status': 'completed', 'files': []}) + assert (tmp_path / 'result.json').read_bytes() == before + assert not (tmp_path / '.result.tmp').exists() + + +@pytest.mark.parametrize('field,value', [('bytes', True), ('bytes', -1), ('sha256', 'f' * 63), ('sha256', 'F' * 64)]) +def test_malformed_identity_is_rejected_before_native_call(probe, inputs, field, value): + root, manifest, output = inputs + document = json.loads(manifest.read_text()) + document['files'][0][field] = value + manifest.write_text(json.dumps(document)) + result = probe.run_probe(manifest, root, output) + assert result['status'] == 'failed' and result['files'] == [] + assert result['error']['phase'] == 'manifest' + + +def test_interrupted_native_call_preserves_previous_and_current_attempt(probe, inputs, monkeypatch): + root, manifest, output = inputs + def inspect(path): + if Path(path).name == 'a.rbln': + return {'name': 'a'} + snapshot = json.loads((output / 'result.json').read_text()) + assert len(snapshot['files']) == 2 + assert snapshot['files'][0]['status'] == 'completed' + current = snapshot['files'][1] + assert current['status'] == 'running' and current['phase'] == 'inspect_pending' + assert current['observed_sha256'] == 'cb8379ac2098aa165029e3938a51da0bcecfc008fd6795f401178647f96c5b34' + assert current['native_api_called'] is None + raise KeyboardInterrupt('interrupted native call') + sdk(monkeypatch, inspect) + with pytest.raises(KeyboardInterrupt, match='native call'): + probe.run_probe(manifest, root, output) + snapshot = json.loads((output / 'result.json').read_text()) + assert snapshot['status'] == 'running' and len(snapshot['files']) == 2 + assert snapshot['files'][0]['metadata'] == {'name': 'a'} + assert snapshot['files'][1]['status'] == 'running' + + +def test_interrupted_hash_preserves_current_input_attempt(probe, inputs, monkeypatch): + root, manifest, output = inputs + real_open = Path.open + class InterruptedRead: + def __init__(self, stream): + self.stream = stream + def __enter__(self): + return self + def __exit__(self, *args): + self.stream.close() + def read(self, size): + snapshot = json.loads((output / 'result.json').read_text()) + assert len(snapshot['files']) == 1 + assert snapshot['files'][0]['path'] == 'a.rbln' + assert snapshot['files'][0]['phase'] == 'input_hash' + assert snapshot['files'][0]['native_api_called'] is False + raise KeyboardInterrupt('interrupted hash') + def open_with_interrupt(path, *args, **kwargs): + stream = real_open(path, *args, **kwargs) + return InterruptedRead(stream) if path == root / 'a.rbln' and args == ('rb',) else stream + monkeypatch.setattr(Path, 'open', open_with_interrupt) + sdk(monkeypatch, lambda path: {'name': 'unused'}) + with pytest.raises(KeyboardInterrupt, match='hash'): + probe.run_probe(manifest, root, output) + assert json.loads((output / 'result.json').read_text())['files'][0]['status'] == 'running'