refactor(lab): move execution to Worker and manage replay and transfer lifecycles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:09:39 +03:00
parent cd34b6ce1a
commit fe5900ff3b
101 changed files with 9305 additions and 2256 deletions
@@ -0,0 +1,3 @@
Frozen registry before retiring fixed LAB V1 on 2026-11-08.
Used only by compatibility/transport contract tests, never by production admission.
Current modular admission is tested separately. Shared models remain in config.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+30 -3
View File
@@ -312,9 +312,7 @@ def test_camera_playback_source_reuses_manifest_and_exposes_exact_segment_clock(
assert first == second
assert first.segment_count == 3
assert first.segment_sha256s == tuple(
segment.sha256 for segment in manifest.epochs[0].segments
)
assert first.segment_sha256s == tuple(segment.sha256 for segment in manifest.epochs[0].segments)
assert first.segment_start_times_ns == (0, 1_000_000_000, 2_000_000_000)
assert store.prepare_calls == 1
assert inspector.inspect_calls == 1
@@ -325,3 +323,32 @@ def test_camera_frame_rejects_unbounded_memory_cache_configuration(tmp_path: Pat
inspector = _Inspector(_manifest(tmp_path))
with pytest.raises(SessionIntegrityError, match="cache bounds"):
_service(tmp_path, store, inspector, max_decode_lanes=0)
def test_worker_manifest_provider_needs_no_operator_store(tmp_path, monkeypatch):
manifest = _manifest(tmp_path)
inspector = _Inspector(manifest)
calls = []
def provider(session, source):
calls.append((session, source))
return manifest
service = RecordedCameraFrameService(
None,
inspector,
ffmpeg_path=Path(sys.executable),
cache_root=tmp_path / "cache",
manifest_provider=provider,
)
monkeypatch.setattr(service, "_decode", lambda m, e, seq: _frame(e, seq))
assert (
service.extract("recorded-session", 0).source_fragment_sha256
== manifest.epochs[0].segments[0].sha256
)
assert (
service.extract("recorded-session", 1).source_fragment_sha256
== manifest.epochs[0].segments[1].sha256
)
assert calls == [("recorded-session", "sensor.camera.right")]
assert inspector.inspect_calls == 0
+80
View File
@@ -0,0 +1,80 @@
"""Current admission and build must not depend on the retired combined LAB."""
import json
import runpy
from pathlib import Path
import pytest
from k1link.observatory.portable_run_definitions import PortableRunDefinitionRegistry
ROOT = Path(__file__).resolve().parents[1]
def test_current_registry_preserves_both_models_without_fixed_lab():
doc = json.loads((ROOT / "config/observatory-portable-run-definitions.json").read_text())
defs = {d["setup_id"]: d for d in doc["definitions"]}
assert "lab-v1-eomt-ddrnet-portable-v1" not in defs
old = json.loads(
(
ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
).read_text()
)["definitions"][0]
models = {
m["release_id"]: m
for key in ("ai-segmentation-ddrnet-v1", "ai-segmentation-eomt-v1")
for m in defs[key]["models"]
}
assert all(models[m["release_id"]] == m for m in old["models"])
registry = PortableRunDefinitionRegistry.from_file(
ROOT / "config/observatory-portable-run-definitions.json"
)
assert len(registry.ready_recorded_definitions()) == 5
def test_old_promotion_cli_cannot_reinstall_fixed_lab():
with pytest.raises(SystemExit, match="retired"):
runpy.run_path(
str(
ROOT
/ "experiments/perception/worker/observatory_portable"
/ "promote_installed_lab_v1_package.py"
),
run_name="__main__",
)
def test_modular_builder_no_longer_executes_legacy_promotion(monkeypatch):
original = runpy.run_path
def checked(path, *a, **kw):
assert "promote_installed_lab_v1" not in str(path)
return original(path, *a, **kw)
monkeypatch.setattr(runpy, "run_path", checked)
module = runpy.run_path(str(ROOT / "scripts/build_modular_ai_worker_release.py"))
assert module["_DDRNET_ASSETS"][0][0] == "ddrnet-checkpoint"
def test_build_current_modular_release_without_fixed_definition(tmp_path):
module = runpy.run_path(str(ROOT / "scripts/build_modular_ai_worker_release.py"))
output = tmp_path / "release"
module["build"](
output=output,
agent_image="1" * 64,
camera_image="2" * 64,
ddrnet_image="3" * 64,
eomt_image="4" * 64,
rf_detr_image="5" * 64,
object_distance_image="6" * 64,
source_tree_sha="7" * 64,
engine_release_root=r"D:\runtime\release",
engine_work_root=r"D:\runtime\work",
)
registry = PortableRunDefinitionRegistry.from_file(
output / "observatory-portable-run-definitions.json"
)
assert len(registry.ready_recorded_definitions()) == 5
assert all(d.setup_id != "lab-v1-eomt-ddrnet-portable-v1" for d in registry.definitions)
+183
View File
@@ -0,0 +1,183 @@
from pathlib import Path
from types import SimpleNamespace
import httpx
import pytest
from k1link.laboratory.data_deletion import LabDeletionError, OwnedLabData
from k1link.laboratory.deletion_coordinator import LabDeletionCoordinator
from k1link.laboratory.local_presentations import LocalPresentations
def owned(tmp_path):
root = tmp_path / "files"
root.mkdir()
return OwnedLabData(tmp_path / "state", {"data": root}), root
def test_delete_shared_files_last_owner_and_repeat(tmp_path):
store, root = owned(tmp_path)
(root / "shared").write_bytes(b"common")
(root / "private").write_bytes(b"result")
shared = {"root": "data", "path": "shared"}
store.register("a", [shared, {"root": "data", "path": "private"}], complete=True)
store.register("b", [shared], complete=True)
assert store.delete(["a"])["state"] == "deleted"
assert not (root / "private").exists() and (root / "shared").exists()
assert store.delete(["a"])["state"] == "deleted"
store.delete(["b"])
assert not (root / "shared").exists()
with pytest.raises(LabDeletionError):
store.register("a", [], complete=True)
def test_unknown_link_and_partial_inventory_refuse_without_deleting(tmp_path):
store, root = owned(tmp_path)
source = tmp_path / "original"
source.write_bytes(b"source")
(root / "link").symlink_to(source)
with pytest.raises(LabDeletionError):
store.register("a", [{"root": "data", "path": "link"}], complete=True)
for member in ("../original", "/original", "", "a/../../original"):
with pytest.raises(LabDeletionError):
store.register("a", [{"root": "data", "path": member}], complete=True)
with pytest.raises(LabDeletionError):
store.register("a", [], complete=False)
with pytest.raises(LabDeletionError):
store.delete(["unknown"])
assert source.read_bytes() == b"source"
def test_interrupted_delete_retries_remaining_files(tmp_path, monkeypatch):
store, root = owned(tmp_path)
for name in ("one", "two"):
(root / name).write_bytes(b"owned")
store.register("a", [{"root": "data", "path": x} for x in ("one", "two")],
complete=True)
unlink = Path.unlink
def fail(path, *args, **kwargs):
if path.name == "two":
raise OSError("device temporarily unavailable")
return unlink(path, *args, **kwargs)
with monkeypatch.context() as context:
context.setattr(Path, "unlink", fail)
with pytest.raises(OSError):
store.delete(["a"])
assert not (root / "one").exists() and (root / "two").exists()
assert store.delete(["a"])["state"] == "deleted"
assert not (root / "two").exists()
def test_worker_failure_keeps_history_and_local_data_until_retry(tmp_path, monkeypatch):
key = "observatory-run-" + "a" * 32
hidden = []
queue = SimpleNamespace(get=lambda _: SimpleNamespace(state="failed", result_id=None),
hide_deleted_projection=hidden.append)
coordinator = LabDeletionCoordinator(
store=SimpleNamespace(data_dir=tmp_path), queue=queue, compositions=None,
copies=LocalPresentations(tmp_path),
gateway=SimpleNamespace(base_url="http://worker", token=lambda: "private"))
file = tmp_path / "private-output"
file.write_bytes(b"owned")
coordinator.local.register(key, [{"root": "core", "path": file.name}], complete=True)
monkeypatch.setattr("k1link.laboratory.deletion_coordinator.inventory_local",
lambda *args: None)
status = [503]
def respond(request):
if status[0] == 503:
return httpx.Response(503)
return httpx.Response(200, json={"state": "deleted", "owners": [key]})
original = httpx.Client
monkeypatch.setattr(httpx, "Client", lambda **kw:
original(**kw, transport=httpx.MockTransport(respond)))
with pytest.raises(LabDeletionError):
coordinator.delete("job", key)
assert file.exists() and not hidden
status[0] = 200
coordinator.delete("job", key)
assert not file.exists() and hidden == [key]
coordinator.delete("job", key)
assert hidden == [key]
def test_waiting_for_worker_does_not_lock_other_lab_status(tmp_path, monkeypatch):
import threading
key = 'observatory-run-' + 'b' * 32
copies = LocalPresentations(tmp_path)
hidden = []
queue = SimpleNamespace(get=lambda _: SimpleNamespace(state='failed', result_id=None),
hide_deleted_projection=hidden.append)
coordinator = LabDeletionCoordinator(
store=SimpleNamespace(data_dir=tmp_path), queue=queue, compositions=None,
copies=copies, gateway=SimpleNamespace(base_url='http://worker', token=lambda: 'private'))
original = httpx.Client
def respond(request):
observed = []
thread = threading.Thread(target=lambda: observed.append(copies.snapshot()), daemon=True)
thread.start()
thread.join(1)
assert observed, 'Worker request must not hold the global presentation lock'
with pytest.raises(ValueError, match='удаляется'):
copies.acquire(key)
return httpx.Response(200, json={'state': 'deleted', 'owners': [key]})
monkeypatch.setattr(httpx, 'Client', lambda **kw:
original(**kw, transport=httpx.MockTransport(respond)))
coordinator.delete('job', key)
assert hidden == [key]
def test_nested_legacy_replays_removed_without_source_or_other_lab(tmp_path):
import json
from k1link.laboratory.deletion_inventory import inventory_local
root = tmp_path / "core"
root.mkdir()
cache = root / "integrated-perception-overlays" / "original-session"
selected = "e10-integrated-perception-" + "a" * 64
retained = "e10-integrated-perception-" + "b" * 64
for key in (selected, retained):
folder = cache / key
folder.mkdir(parents=True)
(folder / "view.rrd").write_bytes(b"replay")
(folder / "view.rrd.cache.json").write_text(json.dumps({"result_id": key}))
(cache / "admission.json").write_text(json.dumps({"result_id": selected}))
source = root / "recordings" / "original.rrd"
source.parent.mkdir()
source.write_bytes(b"original")
owned = OwnedLabData(tmp_path / "state", {"core": root})
inventory_local(owned, [selected])
owned.delete([selected])
assert not (cache / selected).exists()
assert not (cache / "admission.json").exists()
assert (cache / retained / "view.rrd").read_bytes() == b"replay"
assert source.read_bytes() == b"original"
def test_projection_owned_derived_recording_does_not_delete_originals(tmp_path):
import json
from k1link.laboratory.deletion_inventory import inventory_local
root = tmp_path / "core"
selected = "m49-tgs-portable-review-" + "c" * 64
folder = root / "recordings" / selected
folder.mkdir(parents=True)
(folder / "scene.operator-v12.rrd").write_bytes(b"derived")
(folder / "source.raw").write_bytes(b"must survive")
(folder / "scene.operator-v12.rrd.cache.json").write_text(json.dumps({
"schema_version": "missioncore.derived-rerun-recording-cache/v12",
"session_id": selected,
}))
original = root / "recordings" / "source-session"
original.mkdir()
(original / "scene.operator-v12.rrd").write_bytes(b"source recording")
owned = OwnedLabData(tmp_path / "state", {"core": root})
inventory_local(owned, [selected])
owned.delete([selected])
assert not (folder / "scene.operator-v12.rrd").exists()
assert (folder / "source.raw").read_bytes() == b"must survive"
assert (original / "scene.operator-v12.rrd").read_bytes() == b"source recording"
+156
View File
@@ -0,0 +1,156 @@
import json
import shutil
from dataclasses import replace
import pytest
from k1link.artifact_gateway import ArtifactIntegrityError, CentralArtifactStore
from k1link.laboratory.archive_store import (
CATALOG_SCHEMA,
INDEX_SCHEMA,
LaboratoryArchiveStore,
)
def archive(tmp_path, member_path=".runtime/compute-experiments/e1/result.bin"):
root = tmp_path / "runtime-a" / "store"
store = CentralArtifactStore(root, create=True)
source = tmp_path / "payload.bin"
source.write_bytes(b"recorded-result\x00\xff" * 64)
member = replace(store.publish_file(source), role="file-0")
index = tmp_path / "index.json"
index.write_text(json.dumps({
"schema_version": INDEX_SCHEMA,
"files": [{"path": member_path, "role": member.role,
"sha256": member.sha256, "bytes": member.byte_length}],
}))
manifest = store.publish_manifest(
artifact_type="laboratory-evidence-archive", subject_id="e1",
members=[member, replace(store.publish_file(index), role="index")],
)
return root, manifest.manifest_id, member, source.read_bytes(), member_path
def test_restore_survives_runtime_volume_relocation_without_source(tmp_path):
root, identity, member, expected, logical = archive(tmp_path)
moved = tmp_path / "another-host-volume"
shutil.move(root, moved)
(tmp_path / "payload.bin").unlink()
store = LaboratoryArchiveStore(moved)
assert store.verify(identity)["bytes"] == len(expected)
restored = store.restore_file(identity, logical, tmp_path / "restored.bin")
assert restored.read_bytes() == expected
assert restored.stat().st_mode & 0o777 == 0o600
restored.write_bytes(b"edited working copy")
assert store.verify(identity)["bytes"] == len(expected)
def test_corrupt_remote_object_is_never_accepted(tmp_path):
root, identity, member, _, logical = archive(tmp_path)
CentralArtifactStore(root).object_path(member.sha256).write_bytes(b"x" * member.byte_length)
with pytest.raises(ArtifactIntegrityError, match="checksum"):
LaboratoryArchiveStore(root).restore_file(identity, logical, tmp_path / "restored.bin")
assert not (tmp_path / "restored.bin").exists()
@pytest.mark.parametrize(
"logical", ["../escape", "/absolute", "C:/host", "a/../b", "C:relative", "\\server\\share"]
)
def test_archive_cannot_smuggle_host_paths(tmp_path, logical):
root, identity, _, _, _ = archive(tmp_path, logical)
with pytest.raises(ArtifactIntegrityError):
LaboratoryArchiveStore(root).entries(identity)
def test_restore_never_replaces_existing_work(tmp_path):
root, identity, _, _, logical = archive(tmp_path)
target = tmp_path / "existing.bin"
target.write_bytes(b"unsaved user work")
with pytest.raises(ArtifactIntegrityError, match="already exists"):
LaboratoryArchiveStore(root).restore_file(identity, logical, target)
assert target.read_bytes() == b"unsaved user work"
def test_legacy_windows_name_is_only_an_opaque_source_identity(tmp_path):
logical = r".runtime/legacy/C:\old-worker\evidence/result.json"
root, identity, _, expected, _ = archive(tmp_path, logical)
(root / "catalog.json").write_text(json.dumps({
"schema_version": CATALOG_SCHEMA,
"groups": [{"source_group": ".runtime/legacy", "manifest_id": identity}],
}))
store = LaboratoryArchiveStore(root)
assert store.find_file(logical) == identity
target = tmp_path / "restored.json"
assert store.restore_file(identity, logical, target).read_bytes() == expected
assert not (tmp_path / ".runtime").exists()
def test_catalog_resolves_original_path_after_volume_relocation(tmp_path):
root, identity, _, _, logical = archive(tmp_path)
(root / "catalog.json").write_text(json.dumps({
"schema_version": CATALOG_SCHEMA,
"groups": [{"source_group": ".runtime/compute-experiments/e1",
"manifest_id": identity}],
}))
moved = tmp_path / "moved-store"
shutil.move(root, moved)
assert LaboratoryArchiveStore(moved).find_file(logical) == identity
with pytest.raises(ArtifactIntegrityError, match="absent"):
LaboratoryArchiveStore(moved).find_file(".runtime/compute-experiments/e2/missing.bin")
def test_restore_open_race_keeps_other_writers_file(tmp_path, monkeypatch):
root, identity, _, _, logical = archive(tmp_path)
target = tmp_path / "concurrently-created.bin"
original_open = type(target).open
def raced_open(path, mode="r", *args, **kwargs):
if path == target and mode == "xb":
with original_open(path, "wb") as stream:
stream.write(b"other writer")
return original_open(path, mode, *args, **kwargs)
monkeypatch.setattr(type(target), "open", raced_open)
with pytest.raises(FileExistsError):
LaboratoryArchiveStore(root).restore_file(identity, logical, target)
assert target.read_bytes() == b"other writer"
def test_explicit_lab_delete_retires_restore_without_destroying_shared_source(tmp_path):
from k1link.laboratory.data_deletion import OwnedLabData
from k1link.laboratory.deletion_inventory import inventory_worker
result_id = 'e10-integrated-perception-' + 'a' * 64
logical = f'.runtime/compute-experiments/e10/worker-results/{result_id}/frame.bin'
root, deleted_manifest, member, expected, _ = archive(tmp_path, logical)
_, kept_manifest, _, _, kept_path = archive(tmp_path, '.runtime/recorded/source.bin')
(root / 'catalog.json').write_text(json.dumps({
'schema_version': CATALOG_SCHEMA,
'groups': [
{'source_group': '.runtime/compute-experiments/e10',
'manifest_id': deleted_manifest},
{'source_group': '.runtime/recorded', 'manifest_id': kept_manifest},
],
}))
roots = {'archive': root}
for name in ('lab', 'ai', 'tgs'):
roots[name] = tmp_path / name
roots[name].mkdir()
result = roots['lab'] / '.runtime/compute-experiments/e10/worker-results' / result_id
result.mkdir(parents=True)
(result / 'result.json').write_text(json.dumps({'result_id': result_id}))
(result / 'frame.bin').write_bytes(expected)
owned = OwnedLabData(tmp_path / 'ownership', roots)
inventory_worker(owned, [result_id])
receipt = owned.delete([result_id])
assert receipt['state'] == 'deleted'
assert not result.exists()
assert CentralArtifactStore(root).object_path(member.sha256).read_bytes() == expected
retained = LaboratoryArchiveStore(root)
assert retained.entries(deleted_manifest) == []
with pytest.raises(ArtifactIntegrityError, match='not uniquely'):
retained.restore_file(deleted_manifest, logical, tmp_path / 'resurrected.bin')
restored = retained.restore_file(kept_manifest, kept_path, tmp_path / 'source.bin')
assert restored.read_bytes() == expected
inventory_worker(owned, [result_id])
assert owned.delete([result_id])['state'] == 'deleted'
+24 -3
View File
@@ -18,6 +18,7 @@ from k1link.laboratory import (
LaboratoryRunner,
LaboratoryRunRequest,
)
from k1link.laboratory.execution_authority import WorkerLaboratoryAuthority
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
@@ -140,9 +141,7 @@ def test_repository_registry_classifies_every_evidence_definition() -> None:
"lab-v1-vegetation-shadow",
}
)
assert len(execution.definitions) + len(execution.legacy_work_ids) == len(
evidence.definitions
)
assert len(execution.definitions) + len(execution.legacy_work_ids) == len(evidence.definitions)
def test_legacy_is_read_only_and_experimental_requires_bounded_adapter() -> None:
@@ -178,6 +177,7 @@ def test_runner_uses_common_telemetry_evidence_and_immutable_receipt(
telemetry_path = tmp_path / "pipeline.jsonl"
runner = LaboratoryRunner(
worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0),
registry=execution,
evidence_registry=evidence,
sink=JsonlPipelineTelemetrySink(telemetry_path),
@@ -218,6 +218,7 @@ def test_runner_rejects_undeclared_input_before_adapter(tmp_path: Path) -> None:
raise AssertionError("must not run")
runner = LaboratoryRunner(
worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0),
registry=execution,
evidence_registry=evidence,
sink=JsonlPipelineTelemetrySink(tmp_path / "pipeline.jsonl"),
@@ -259,6 +260,7 @@ def test_m48_evaluation_uses_registered_adapter_and_common_receipt(
score,
)
runner = LaboratoryRunner(
worker_authority=WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0),
registry=execution,
evidence_registry=evidence,
sink=JsonlPipelineTelemetrySink(tmp_path / "pipeline.jsonl"),
@@ -295,3 +297,22 @@ def _canonical_json(value: object) -> bytes:
separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
def test_operator_run_rejected_before_adapter_or_disk_write(tmp_path, monkeypatch):
monkeypatch.delenv("MISSIONCORE_LAB_RUNTIME_ROLE", raising=False)
evidence, execution = _registries()
request = _request(tmp_path)
calls = []
runner = LaboratoryRunner(
registry=execution,
evidence_registry=evidence,
sink=JsonlPipelineTelemetrySink(tmp_path / "telemetry.jsonl"),
adapters={"e33-worker-shadow": lambda r: calls.append(r)},
)
with pytest.raises(LaboratoryExecutionError, match="operator execution is disabled"):
runner.run(request)
assert calls == []
assert not request.output_root.exists()
assert not request.receipt_root.exists()
assert not (tmp_path / "telemetry.jsonl").exists()
+139
View File
@@ -0,0 +1,139 @@
import httpx
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.laboratory.execution_authority import (
LaboratoryPlacementError,
WorkerLaboratoryAuthority,
)
from k1link.laboratory.worker_gateway import (
LaboratoryGatewayConfiguration,
LaboratoryWorkerGateway,
build_laboratory_worker_gateway_router,
)
def client(gateway):
app = FastAPI()
app.include_router(build_laboratory_worker_gateway_router(gateway))
return TestClient(app)
def configured(tmp_path, handler):
token = tmp_path / "token"
token.write_text("a" * 48)
token.chmod(0o600)
return LaboratoryWorkerGateway(
LaboratoryGatewayConfiguration("http://127.0.0.1:19087", token),
transport=httpx.MockTransport(handler),
)
def test_no_local_fallback(tmp_path):
with client(LaboratoryWorkerGateway(None)) as c:
assert c.get("/api/v1/laboratory/e29/catalog").status_code == 503
assert list(tmp_path.iterdir()) == []
def test_range_and_query_stream_without_staging(tmp_path):
def upstream(r):
assert r.headers["authorization"] == "Bearer " + "a" * 48
assert r.headers["accept-encoding"] == "identity"
assert r.headers["range"] == "bytes=1-3"
assert str(r.url) == "http://127.0.0.1:19087/api/v1/laboratory/e29/video?quality=x"
return httpx.Response(
206,
content=b"abc",
headers={
"content-range": "bytes 1-3/10",
"etag": '"sealed"',
"set-cookie": "secret=ignored",
},
)
with client(configured(tmp_path, upstream)) as c:
r = c.get("/api/v1/laboratory/e29/video?quality=x", headers={"range": "bytes=1-3"})
assert r.status_code == 206 and r.content == b"abc"
assert r.headers["content-range"] == "bytes 1-3/10"
assert r.headers["etag"] == '"sealed"'
assert "set-cookie" not in r.headers
assert [p.name for p in tmp_path.iterdir()] == ["token"]
def test_mutation_not_retried_and_redirect_rejected(tmp_path):
calls = []
def upstream(r):
calls.append(r.content)
return httpx.Response(307, headers={"location": "https://elsewhere.test"})
with client(configured(tmp_path, upstream)) as c:
assert c.post("/api/v1/laboratory/evaluate", json={"a": 1}).status_code == 503
assert len(calls) == 1
def test_response_budget_and_capacity_release(tmp_path, monkeypatch):
monkeypatch.setattr("k1link.laboratory.worker_gateway.MAX_RESPONSE_BYTES", 3)
gateway = configured(tmp_path, lambda _: httpx.Response(200, content=b"too big"))
with client(gateway) as c:
for _ in range(10):
assert c.get("/api/v1/laboratory/result").status_code == 503
assert gateway._capacity._value == 8
def test_request_budget(tmp_path, monkeypatch):
monkeypatch.setattr("k1link.laboratory.worker_gateway.MAX_REQUEST_BYTES", 3)
def forbidden(_):
raise AssertionError("oversized request reached Worker")
with client(configured(tmp_path, forbidden)) as c:
assert c.post("/api/v1/laboratory/result", content=b"large").status_code == 413
def test_worker_authority_blocks_operator_and_escape(tmp_path, monkeypatch):
monkeypatch.delenv("MISSIONCORE_LAB_RUNTIME_ROLE", raising=False)
assert WorkerLaboratoryAuthority.from_environment() is None
authority = WorkerLaboratoryAuthority(tmp_path.resolve(), free_reserve_bytes=0)
authority.admit_outputs(tmp_path / "job" / "result")
with pytest.raises(LaboratoryPlacementError):
authority.admit_outputs(tmp_path.parent / "escaped")
(tmp_path / "link").symlink_to(tmp_path.parent, target_is_directory=True)
with pytest.raises(LaboratoryPlacementError):
authority.admit_outputs(tmp_path / "link" / "escaped")
def test_http_remote_disallowed(tmp_path):
with pytest.raises(ValueError):
LaboratoryGatewayConfiguration("http://example.test", tmp_path / "token")
def test_replay_format_capabilities_and_encoded_points(tmp_path):
import gzip
payload = b"recorded-point-data" * 100
encoded = gzip.compress(payload)
def upstream(r):
assert r.headers["x-m48-review-capability"] == "review-token"
return httpx.Response(
200,
stream=httpx.ByteStream(encoded),
headers={
"content-encoding": "gzip",
"content-length": str(len(encoded)),
"x-rerun-format": "RRF2",
"x-uncompressed-content-length": str(len(payload)),
},
)
with client(configured(tmp_path, upstream)) as c:
response = c.get(
"/api/v1/laboratory/recorded-points",
headers={"x-m48-review-capability": "review-token"},
)
assert response.content == payload
assert response.headers["content-length"] == str(len(encoded))
assert response.headers["x-rerun-format"] == "RRF2"
assert response.headers["x-uncompressed-content-length"] == str(len(payload))
+50
View File
@@ -0,0 +1,50 @@
import hashlib
import pytest
from k1link.laboratory.worker_recorded_sources import WorkerRecordedSources
from k1link.sessions.models import SessionIntegrityError
def test_binding_rejects_changed_descriptor_and_source_escape(tmp_path):
directory = tmp_path / "descriptors"
directory.mkdir()
descriptor = directory / "source.json"
payload = b'{"session_id":"test"}'
descriptor.write_bytes(payload)
bindings = {
"schema_version": "missioncore.laboratory-recorded-source-bindings/v1",
"sources": [
{
"session_id": "test",
"source_name": "camera",
"descriptor": "descriptors/source.json",
"descriptor_sha256": hashlib.sha256(payload).hexdigest(),
"media_root": "media",
}
],
}
source = WorkerRecordedSources(tmp_path, bindings_document=bindings)
descriptor.write_bytes(b"changed")
with pytest.raises(SessionIntegrityError, match="descriptor changed"):
source.manifest("test", "camera")
descriptor.unlink()
outside = tmp_path.parent / "outside-descriptor"
outside.write_bytes(payload)
descriptor.symlink_to(outside)
with pytest.raises(SessionIntegrityError, match="Invalid Worker camera descriptor"):
source.manifest("test", "camera")
assert not (tmp_path / "bindings.json").exists()
def test_source_binding_rejects_ambiguous_or_missing_source(tmp_path):
bindings = {
"schema_version": "missioncore.laboratory-recorded-source-bindings/v1",
"sources": [{"session_id": "test", "source_name": "camera"}],
}
source = WorkerRecordedSources(tmp_path, bindings_document=bindings)
with pytest.raises(SessionIntegrityError, match="not installed"):
source.manifest("other", "camera")
bindings["sources"].append(bindings["sources"][0])
with pytest.raises(SessionIntegrityError, match="Ambiguous"):
WorkerRecordedSources(tmp_path, bindings_document=bindings)
+117
View File
@@ -0,0 +1,117 @@
import hashlib
import json
from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.laboratory.local_presentations import LocalPresentationError, LocalPresentations
from k1link.web.local_storage_api import build_local_storage_router
def fixture(tmp_path):
now = [1000.0]
store = LocalPresentations(tmp_path, clock=lambda: now[0])
store.root.mkdir()
path = store.root / ("a" * 64 + ".replay.rrd")
path.write_bytes(b"RRF2-complete-video-and-spatial-recording")
artifact = SimpleNamespace(
path=path,
sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
byte_length=path.stat().st_size,
)
sidecar = store.root / ("b" * 64 + ".json")
sidecar.write_text(json.dumps({"sha256": artifact.sha256}))
store.register("run", artifact, sidecar)
return store, now, artifact, sidecar
def test_persistence_unpin_starts_full_retention_and_catalog_survives(tmp_path):
store, now, artifact, sidecar = fixture(tmp_path)
store.policy(7)
store.pin("run", True)
now[0] += 40 * 86400
store.prune()
assert artifact.path.exists()
reloaded = LocalPresentations(tmp_path, clock=lambda: now[0])
assert reloaded.snapshot()["entries"]["run"]["pinned"]
reloaded.pin("run", False)
reloaded.prune()
assert artifact.path.exists()
now[0] += 7 * 86400
reloaded.prune()
assert not artifact.path.exists() and not sidecar.exists()
assert reloaded.snapshot()["entries"]["run"]["local"] is False
def test_no_purge_of_unknown_files_and_changed_bytes(tmp_path):
store, now, artifact, _ = fixture(tmp_path)
unknown = store.root / "original-unregistered.rrd"
unknown.write_bytes(b"valuable")
artifact.path.write_bytes(b"changed")
now[0] += 100 * 86400
store.prune()
assert unknown.read_bytes() == b"valuable"
assert artifact.path.read_bytes() == b"changed"
with pytest.raises(LocalPresentationError):
store.pin("run", True)
def test_playback_lease_and_pin_protect_delete_and_ttl(tmp_path):
store, now, artifact, _ = fixture(tmp_path)
with store.use("run"):
with pytest.raises(LocalPresentationError):
store.remove("run")
now[0] += 100 * 86400
store.prune()
assert artifact.path.exists()
store.pin("run", True)
with pytest.raises(LocalPresentationError):
store.remove("run")
def test_symlink_is_preserved_without_traversal(tmp_path):
store, _, artifact, _ = fixture(tmp_path)
victim = tmp_path / "source"
victim.write_bytes(artifact.path.read_bytes())
artifact.path.unlink()
artifact.path.symlink_to(victim)
with pytest.raises(LocalPresentationError):
store.remove("run")
assert victim.exists()
def test_shared_file_is_retained_for_other_result(tmp_path):
store, _, artifact, sidecar = fixture(tmp_path)
store.register("other", artifact, sidecar)
store.pin("other", True)
store.remove("run")
assert artifact.path.exists()
assert store.snapshot()["entries"]["other"]["local"]
def test_invalid_policy_and_pin_missing_copy_fail_without_mutation(tmp_path):
store, _, _, _ = fixture(tmp_path)
app = FastAPI()
app.include_router(build_local_storage_router(store))
with TestClient(app) as client:
root = "/api/v1/storage/laboratory"
for value in (0, 366, "7", True):
assert client.put(root + "/policy", json={"retention_days": value}).status_code == 422
assert (
client.put(root + "/policy", json={"retention_days": 7}).json()["retention_days"] == 7
)
assert client.put(root + "/copies/missing/pin", json={"pinned": True}).status_code == 409
assert client.delete(root + "/copies/run").status_code == 200
assert not client.get(root).json()["entries"]["run"]["local"]
def test_explicit_lab_deletion_removes_pin_but_not_active_playback(tmp_path):
store, _, artifact, _ = fixture(tmp_path)
store.pin("run", True)
with store.use("run"), pytest.raises(LocalPresentationError):
store.remove("run", delete_lab=True)
store.remove("run", delete_lab=True)
assert not artifact.path.exists()
assert "run" not in store.snapshot()["entries"]
+3 -3
View File
@@ -36,7 +36,7 @@ def _client(tmp_path: Path) -> tuple[TestClient, dict]:
return TestClient(app), catalog
def test_composition_projection_can_be_renamed_and_removed_through_api(
def test_composition_rename_and_delete_without_storage_service_fails_closed(
tmp_path: Path,
) -> None:
registry = ModuleRegistry.from_file(
@@ -95,8 +95,8 @@ def test_composition_projection_can_be_renamed_and_removed_through_api(
assert runs.display_name(run.run_id) == "Контрольный прогон"
removed = client.delete(f"/api/v1/observatory/ai-composition-runs/{run.run_id}")
assert removed.status_code == 204
assert runs.list(source_session_id="source-1", include_hidden=False) == ()
assert removed.status_code == 503
assert runs.list(source_session_id="source-1", include_hidden=False) == (run,)
assert runs.get(run.run_id) == run
@@ -42,8 +42,16 @@ from k1link.observatory.portable_worker_runtime import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITIONS_FILE = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
RUNTIME_FILE = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
DEFINITIONS_FILE = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
RUNTIME_FILE = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
)
def _package_and_runtime():
@@ -32,8 +32,16 @@ from k1link.observatory.worker_service import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITIONS_FILE = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
RUNTIME_FILE = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
DEFINITIONS_FILE = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
RUNTIME_FILE = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
)
def _registries() -> tuple[PortableRunDefinitionRegistry, PortableWorkerRuntimeRegistry]:
@@ -39,16 +39,17 @@ def test_generic_lab_v1_promotion_round_trips_all_three_registries(
promotion.generate(
source_definitions=(
REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
),
source_runtime=(
REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
),
ddrnet_config=(
REPOSITORY_ROOT
/ "config"
/ "perception"
/ "lab-v1-eomt-ddrnet-portable-v2.json"
REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json"
),
result_assembler_source=(
REPOSITORY_ROOT / "src" / "k1link" / "observatory" / "portable_lab_v1_executor.py"
@@ -79,9 +80,7 @@ def test_generic_lab_v1_promotion_round_trips_all_three_registries(
definition = definitions.resolve_setup("lab-v1-eomt-ddrnet-portable-v1")
candidate = runtime.resolve(definition.setup_id, definition.definition_sha256)
package = packages.resolve(definition.setup_id, definition.definition_sha256)
bindings = json.loads(
(output / "observatory-installed-lab-asset-bindings.json").read_text()
)
bindings = json.loads((output / "observatory-installed-lab-asset-bindings.json").read_text())
assert definition.executor.ready is True
assert candidate.ready is True
@@ -199,16 +198,17 @@ def _generate(
) -> None:
promotion.generate(
source_definitions=(
REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
),
source_runtime=(
REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
),
ddrnet_config=(
REPOSITORY_ROOT
/ "config"
/ "perception"
/ "lab-v1-eomt-ddrnet-portable-v2.json"
REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json"
),
result_assembler_source=(
REPOSITORY_ROOT / "src" / "k1link" / "observatory" / "portable_lab_v1_executor.py"
@@ -44,7 +44,11 @@ from k1link.observatory.worker_service import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITIONS_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
DEFINITIONS_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
PROFILE_PATH = REPOSITORY_ROOT / "config" / "perception" / "m49-tgs-portable-v2.json"
SOURCE_REVISION = "f" * 40
SOURCE_CANDIDATE_SHA256 = "a" * 64
@@ -54,7 +54,11 @@ from k1link.sessions.models import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
NOW = "2026-08-31T10:00:00.000Z"
SOURCE_SESSION_ID = "20260831T095500Z_viewer_live"
RESULT_ID = "portable-result-transport-001"
@@ -63,9 +67,7 @@ RESULT_ID = "portable-result-transport-001"
def _ready_registry(tmp_path: Path) -> PortableRunDefinitionRegistry:
registry = PortableRunDefinitionRegistry.from_file(REGISTRY_PATH)
base = registry.definitions[0]
document = cast(
dict[str, object], json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
)
document = cast(dict[str, object], json.loads(REGISTRY_PATH.read_text(encoding="utf-8")))
rows = cast(list[object], document["definitions"])
selected = copy.deepcopy(cast(dict[str, object], rows[0]))
selected["executor"] = {
@@ -106,9 +108,7 @@ class _Store:
replay: ReplayCommand
recorded_media: tuple[RecordedMediaArtifact, ...]
def get_session_with_catalog_snapshot(
self, session_id: str
) -> tuple[SessionDetail, str]:
def get_session_with_catalog_snapshot(self, session_id: str) -> tuple[SessionDetail, str]:
assert session_id == SOURCE_SESSION_ID
return self.detail, self.catalog_sha256
@@ -116,9 +116,7 @@ class _Store:
assert session_id == SOURCE_SESSION_ID
return self.replay
def list_recorded_media(
self, session_id: str
) -> tuple[RecordedMediaArtifact, ...]:
def list_recorded_media(self, session_id: str) -> tuple[RecordedMediaArtifact, ...]:
assert session_id == SOURCE_SESSION_ID
return self.recorded_media
@@ -336,9 +334,7 @@ def _fixture(tmp_path: Path) -> _Fixture:
(documents / f"{capability_sha}.json").write_bytes(capability_payload)
queue = ObservatoryRecordedJobQueue(
data_dir,
definitions=RecordedRunDefinitionRegistry(
(definition.to_recorded_run_definition(),)
),
definitions=RecordedRunDefinitionRegistry((definition.to_recorded_run_definition(),)),
clock=lambda: NOW,
)
job, created = queue.submit(
@@ -438,9 +434,7 @@ def test_source_members_are_claim_bound_and_materialized_through_cas(
assert cas_path != fixture.raw_path
assert cas_path.name == raw.sha256
metadata = next(
member
for member in manifest.members
if member.kind == "spatial-replay-metadata"
member for member in manifest.members if member.kind == "spatial-replay-metadata"
)
admitted_metadata, metadata_cas_path = fixture.service.materialize_source_member(
job_id=fixture.job.job_id,
@@ -644,3 +638,190 @@ def test_result_upload_rejects_wrong_digest_and_never_publishes_partial_member(
claimant_id="worker-006",
)
assert repeated.members[0].uploaded is False
def test_source_transport_space_preserves_original_and_reuses_exact_copy(tmp_path, monkeypatch):
from types import SimpleNamespace
from k1link.observatory import transfer_space
from k1link.observatory.portable_artifact_transport import _publish_exact_cas_member
source = tmp_path / "source.bin"
source.write_bytes(b"source-evidence")
root = tmp_path / "transport"
digest = hashlib.sha256(source.read_bytes()).hexdigest()
available = [transfer_space.FREE_RESERVE + 4]
monkeypatch.setattr(
transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=available[0])
)
with pytest.raises(transfer_space.TransferCapacityError):
_publish_exact_cas_member(
root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size
)
assert source.read_bytes() == b"source-evidence"
assert not list(root.rglob(".tmp-*"))
available[0] += 1024
target = _publish_exact_cas_member(
root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size
)
available[0] = 0
assert (
_publish_exact_cas_member(
root, source, expected_sha256=digest, expected_byte_length=source.stat().st_size
)
== target
)
def test_source_gc_waits_for_queue_then_archive_rebuilds_identically(tmp_path):
from k1link.observatory.portable_artifact_transport import (
_ordered_camera_epoch_members,
_publish_camera_epoch_archive,
)
fixture = _fixture(tmp_path)
args = dict(
job_id=fixture.job.job_id,
claim_token=fixture.claim_token,
claim_generation=fixture.job.claim_generation,
claimant_id="worker-006",
)
manifest = fixture.service.source_manifest(**args)
original, path = fixture.service.materialize_camera_epoch_archive(**args)
assert fixture.service.collect_source_copies()["protected"] == 1
fixture.queue.fail(
fixture.job.job_id,
claim_token=fixture.claim_token,
error_code="test-completed",
message="Synthetic failure closed",
)
assert fixture.service.collect_source_copies()["retired"] == 1
assert not path.exists() and fixture.raw_path.exists()
# Historical binding survives retirement and the same admitted inputs regenerate
# precisely the same tar; no deletion of a source or re-admission of old models.
rebuilt, target = _publish_camera_epoch_archive(
fixture.service._source_cas,
job=fixture.job,
members=_ordered_camera_epoch_members(manifest.members),
space=fixture.service._transfer_space,
)
assert rebuilt == original and target == path and path.is_file()
def test_package_shortage_is_retryable_before_manifest_or_body(tmp_path, monkeypatch):
from types import SimpleNamespace
from fastapi import HTTPException
from k1link.observatory import transfer_space
from k1link.web.observatory_worker_api import _artifact_call, _raise_artifact_or_queue_error
fixture = _fixture(tmp_path)
package, payload = _result_package(tmp_path, fixture)
available = [transfer_space.FREE_RESERVE + len(package.canonical_bytes) + 4096]
monkeypatch.setattr(
transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=available[0])
)
args = dict(
job_id=fixture.job.job_id,
result_sha256=package.manifest_sha256,
manifest_payload=package.canonical_bytes,
claim_token=fixture.claim_token,
claim_generation=fixture.job.claim_generation,
claimant_id="worker-006",
)
with pytest.raises(HTTPException) as caught:
_artifact_call(lambda: fixture.service.stage_result_manifest(**args))
assert caught.value.status_code == 503 and caught.value.headers["Retry-After"] == "30"
assert not list(fixture.service._result_staging.rglob("manifest.json"))
assert fixture.queue.get(fixture.job.job_id).state == "running"
available[0] += len(payload) + 10000
plan = fixture.service.stage_result_manifest(**args)
assert not plan.complete
with pytest.raises(HTTPException) as caught:
_raise_artifact_or_queue_error(transfer_space.TransferCapacityError("space"))
assert caught.value.status_code == 503
def test_completed_upload_retry_needs_no_new_disk_space(tmp_path, monkeypatch):
from types import SimpleNamespace
from k1link.observatory import transfer_space
fixture = _fixture(tmp_path)
package, payload = _result_package(tmp_path, fixture)
args = dict(
job_id=fixture.job.job_id,
result_sha256=package.manifest_sha256,
claim_token=fixture.claim_token,
claim_generation=fixture.job.claim_generation,
claimant_id="worker-006",
)
plan = fixture.service.stage_result_manifest(**args, manifest_payload=package.canonical_bytes)
async def chunks():
yield payload
asyncio.run(
fixture.service.upload_result_member(
**args, member_id=plan.members[0].member_id, chunks=chunks()
)
)
monkeypatch.setattr(transfer_space.shutil, "disk_usage", lambda _: SimpleNamespace(free=0))
assert fixture.service.stage_result_manifest(
**args, manifest_payload=package.canonical_bytes
).complete
assert asyncio.run(
fixture.service.upload_result_member(
**args, member_id=plan.members[0].member_id, chunks=chunks()
)
).complete
def test_source_route_preserves_range_and_releases_failed_request_reader(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.observatory_worker_api import (
ObservatoryWorkerAuthentication,
build_observatory_worker_router,
)
fixture = _fixture(tmp_path)
token = "synthetic-worker-token" * 3
app = FastAPI()
app.include_router(
build_observatory_worker_router(
fixture.queue,
authentication=ObservatoryWorkerAuthentication(
bearer_token_sha256=hashlib.sha256(token.encode()).hexdigest(),
contour_id="worker-006",
),
artifact_transport=fixture.service,
)
)
headers = {
"Authorization": "Bearer " + token,
"X-Mission-Core-Contour-Id": "worker-006",
"X-Mission-Core-Claim-Token": fixture.claim_token,
"X-Mission-Core-Claim-Generation": str(fixture.job.claim_generation),
}
prefix = "/api/v1/worker/observatory/recorded-jobs/" + fixture.job.job_id
with TestClient(app) as client:
manifest = client.get(prefix + "/source-materialization", headers=headers)
assert manifest.status_code == 200
member = next(m for m in manifest.json()["members"] if m["kind"] == "spatial-replay")
response = client.get(
prefix + "/source-members/" + member["member_id"],
headers={**headers, "Range": "bytes=0-3"},
)
assert response.status_code == 206 and response.content == fixture.raw_path.read_bytes()[:4]
failed = client.get(prefix + "/source-members/" + "0" * 64, headers=headers)
assert failed.status_code == 409
fixture.queue.fail(
fixture.job.job_id,
claim_token=fixture.claim_token,
error_code="test-completed",
message="Synthetic job closed",
)
assert fixture.service.collect_source_copies()["retired"] == 1
@@ -9,11 +9,17 @@ from typing import cast
import pytest
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITIONS = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
RUNTIME = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
PORTABLE_CONFIG = (
REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json"
DEFINITIONS = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
RUNTIME = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
)
PORTABLE_CONFIG = REPOSITORY_ROOT / "config" / "perception" / "lab-v1-eomt-ddrnet-portable-v2.json"
PROMOTION_SCRIPT = (
REPOSITORY_ROOT
/ "experiments"
@@ -42,10 +48,7 @@ def _asset(
) -> dict[str, object]:
return {
"asset_id": asset_id,
"host_path": (
"D:\\NDC_MISSIONCORE\\runtime\\assets\\observatory-portable\\"
+ asset_id
),
"host_path": ("D:\\NDC_MISSIONCORE\\runtime\\assets\\observatory-portable\\" + asset_id),
"container_path": container_path,
"kind": "tree" if tree else "file",
"verification": "identity-sha256" if tree else "sha256",
@@ -199,8 +202,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]:
"component": "eomt",
"status": "already-installed",
"tag": (
"ndc/mission-core-lab-v1-eomt-adapter:"
f"{component_source_revision[:12]}"
f"ndc/mission-core-lab-v1-eomt-adapter:{component_source_revision[:12]}"
),
"base_image_sha256": (
"58df7489c3f2276f9591d500a012dee03e23d35543ce3c390b4c001e6bf90794"
@@ -212,8 +214,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]:
"component": "ddrnet",
"status": "already-installed",
"tag": (
"ndc/mission-core-lab-v1-ddrnet-adapter:"
f"{component_source_revision[:12]}"
f"ndc/mission-core-lab-v1-ddrnet-adapter:{component_source_revision[:12]}"
),
"base_image_sha256": (
"591cb382c099eeb05e7ec16e2371e0b2da54d2bb5c49ec0f4ac88dbf72b0f0cd"
@@ -240,9 +241,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]:
"staged_snapshot_sha256": "9" * 64,
"staged_snapshot_file_count": 42,
"staged_snapshot_byte_length": 4096,
"staged_snapshot_canonicalization": (
"utf8-path-nul-length-nul-sha256-lf-v1"
),
"staged_snapshot_canonicalization": ("utf8-path-nul-length-nul-sha256-lf-v1"),
"embedded_snapshot_manifest_sha256": "a" * 64,
"embedded_snapshot_manifest_byte_length": 8192,
"python_dependency_bundle_sha256": "b" * 64,
@@ -259,10 +258,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]:
),
"derived_image_sha256": "c" * 64,
"image": {
"tag": (
"ndc/mission-core-observatory-worker-agent:"
f"{source_revision[:12]}"
),
"tag": (f"ndc/mission-core-observatory-worker-agent:{source_revision[:12]}"),
"id": f"sha256:{'c' * 64}",
"size_bytes": 1_000_000,
"thin_layer_bytes": 10_000,
@@ -276,10 +272,7 @@ def _write_installation_evidence(tmp_path: Path) -> tuple[Path, Path]:
},
"runtime_contract": {
"workdir": "/opt/nodedc/mission-core",
"pythonpath": (
"/opt/nodedc/mission-core/src:"
"/opt/nodedc/mission-core/deps"
),
"pythonpath": ("/opt/nodedc/mission-core/src:/opt/nodedc/mission-core/deps"),
"entrypoint": [
"python3",
"-m",
@@ -43,7 +43,10 @@ from k1link.observatory.portable_worker_runtime import (
from k1link.observatory.worker_service import ObservatoryWorkerExecutorBuildContext
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITIONS_PATH = REPOSITORY_ROOT / "config/observatory-portable-run-definitions.json"
DEFINITIONS_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab/observatory-portable-run-definitions.json"
)
RELEASE_ID = "lab-v1-eomt-ddrnet-v1"
RELEASE_SHA256 = "7" * 64
IMAGE_SHA256 = "8" * 64
@@ -76,10 +79,8 @@ class _Release:
definition.setup_id != service_module.PORTABLE_LAB_V1_SETUP_ID
or definition.definition_id != "lab-v1-eomt-ddrnet-portable"
or definition.version != 2
or definition.executable_contract_sha256
!= self.definition_contract_sha256
or definition.result_contract.contract_sha256
!= self.result_contract_sha256
or definition.executable_contract_sha256 != self.definition_contract_sha256
or definition.result_contract.contract_sha256 != self.result_contract_sha256
):
raise ValueError("release belongs to another definition")
@@ -241,17 +242,11 @@ def _image_build(
component=component,
base_image_sha256=BASE_IMAGE_SHA256S[component],
derived_image_sha256=derived_image_sha256,
dockerfile_sha256=hashlib.sha256(
f"{component}:dockerfile".encode()
).hexdigest(),
build_method=(
service_module.PORTABLE_LAB_V1_COMPONENT_IMAGE_BUILD_METHOD
),
dockerfile_sha256=hashlib.sha256(f"{component}:dockerfile".encode()).hexdigest(),
build_method=(service_module.PORTABLE_LAB_V1_COMPONENT_IMAGE_BUILD_METHOD),
installer_sha256=INSTALLER_SHA256,
shared_adapter_sha256=hashlib.sha256(b"shared-adapter").hexdigest(),
component_adapter_sha256=hashlib.sha256(
f"{component}:adapter".encode()
).hexdigest(),
component_adapter_sha256=hashlib.sha256(f"{component}:adapter".encode()).hexdigest(),
)
@@ -318,9 +313,7 @@ def _composition_inputs(
tmp_path,
definition_sha256=definition.definition_sha256,
)
receipt = service_module.load_portable_lab_v1_worker_installation_receipt(
receipt_path
)
receipt = service_module.load_portable_lab_v1_worker_installation_receipt(receipt_path)
candidate = _runtime_candidate(definition, receipt)
admission = PortableWorkerRuntimeAdmission(
candidate_sha256=candidate.candidate_sha256,
@@ -328,9 +321,7 @@ def _composition_inputs(
blockers=(),
assets=(
PortableWorkerAssetVerification(
asset_id=(
service_module.PORTABLE_LAB_V1_WORKER_INSTALLATION_RECEIPT_ASSET_ID
),
asset_id=(service_module.PORTABLE_LAB_V1_WORKER_INSTALLATION_RECEIPT_ASSET_ID),
state="matched",
reason=None,
),
@@ -408,14 +399,10 @@ def test_receipt_loader_round_trips_full_runner_identity(tmp_path: Path) -> None
receipt.runner_installation.eomt.image_sha256
)
assert receipt.ddrnet_image_build.network == "none"
assert receipt.ddrnet_image_build.build_method == (
"docker-commit-exact-layer-v1"
)
assert receipt.ddrnet_image_build.build_method == ("docker-commit-exact-layer-v1")
assert receipt.ddrnet_image_build.installer_sha256 == INSTALLER_SHA256
assert receipt.installation_evidence_sha256 == "d" * 64
assert receipt.runner_installation.definition_sha256 == (
definition.definition_sha256
)
assert receipt.runner_installation.definition_sha256 == (definition.definition_sha256)
assert tuple(asset.asset_id for asset in receipt.runner_installation.eomt.assets) == (
tuple(sorted(local_runners._EXPECTED_ASSET_TARGETS["eomt"]))
)
@@ -519,9 +506,7 @@ def test_compose_returns_exact_lab_v1_builder_registration(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
definition, candidate, receipt, admission, installation = _composition_inputs(
tmp_path
)
definition, candidate, receipt, admission, installation = _composition_inputs(tmp_path)
captured: dict[str, object] = {}
adapter = object()
@@ -560,23 +545,15 @@ def test_compose_returns_exact_lab_v1_builder_registration(
assert captured["definition"] is definition
assert captured["admission"] is admission
assert captured["installation"] is installation
assert captured["source_output_parent"] == (
tmp_path / "lab-v1-portable/source-output"
)
assert captured["eomt_runner"].__class__.__name__ == (
"InstalledPortableLabV1EomtRunner"
)
assert captured["ddrnet_runner"].__class__.__name__ == (
"InstalledPortableLabV1DdrnetRunner"
)
assert captured["source_output_parent"] == (tmp_path / "lab-v1-portable/source-output")
assert captured["eomt_runner"].__class__.__name__ == ("InstalledPortableLabV1EomtRunner")
assert captured["ddrnet_runner"].__class__.__name__ == ("InstalledPortableLabV1DdrnetRunner")
def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission(
tmp_path: Path,
) -> None:
definition, candidate, receipt, admission, installation = _composition_inputs(
tmp_path
)
definition, candidate, receipt, admission, installation = _composition_inputs(tmp_path)
changed_path = _write_receipt(
tmp_path,
definition_sha256=definition.definition_sha256,
@@ -596,9 +573,7 @@ def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission(
launcher=_Launcher(),
)
current = service_module.load_portable_lab_v1_worker_installation_receipt(
changed_path
)
current = service_module.load_portable_lab_v1_worker_installation_receipt(changed_path)
with pytest.raises(
service_module.PortableLabV1WorkerCompositionError,
match="does not seal its installation receipt",
@@ -616,9 +591,7 @@ def test_compose_fails_closed_on_changed_receipt_or_incomplete_admission(
tmp_path,
definition_sha256=definition.definition_sha256,
)
restored = service_module.load_portable_lab_v1_worker_installation_receipt(
restored_path
)
restored = service_module.load_portable_lab_v1_worker_installation_receipt(restored_path)
release = cast(_Release, installation.release)
uncovered_installation = cast(
PortableLabV1ReleaseInstallation,
@@ -45,7 +45,11 @@ from k1link.sessions.models import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
SESSION_ID = "20260831T000000Z_viewer_live"
CATALOG_SHA256 = "1" * 64
RAW_SHA256 = "2" * 64
@@ -66,7 +66,11 @@ from k1link.sessions import (
from k1link.web.observatory_api import build_observatory_router
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
NOW = "2026-08-31T08:00:00.000Z"
SOURCE_SESSION_ID = "20260831T075500Z_viewer_live"
RESULT_ID = "portable-lab-result-001"
@@ -746,7 +750,8 @@ def test_cache_does_not_hide_another_source_snapshot_or_profile_version(tmp_path
def test_cache_survives_new_store_and_archive_reconciliation(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("k1link.sessions.store.utc_now_iso", lambda: "2026-09-03T08:00:00.000Z")
cache, queue, sessions, artifacts, registry, definition, job, _, _ = _cache_fixture(tmp_path)
@@ -756,7 +761,10 @@ def test_cache_survives_new_store_and_archive_reconciliation(
reopened = SessionStore(sessions.repository_root, data_dir=sessions.data_dir)
reopened.reconcile_archive(_source_archive(tmp_path, definition))
cold_cache = PortableResultCache(
sessions=reopened, artifacts=artifacts, queue=queue, definitions=registry,
sessions=reopened,
artifacts=artifacts,
queue=queue,
definitions=registry,
calculation_profiles=PortableCalculationProfileRegistry((_profile(definition),)),
)
assert cold_cache.find(SOURCE_SESSION_ID, definition) == before
@@ -928,3 +936,162 @@ def test_cache_api_existing_skips_source_preparation_submit_and_worker(tmp_path:
request["idempotency_key"] = job.idempotency_key
assert client.post("/api/v1/observatory/runs", json=request).status_code == 202
assert len(queue.list_jobs()) == 1
def test_transport_retirement_survives_interruption_and_new_publisher(tmp_path, monkeypatch):
registry, definition, store, job, root = _fixture(tmp_path, extra_payload=b"keep-recording")
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
paths = list((root / "artifacts").rglob("*"))
paths = [p for p in paths if p.is_file()]
assert len(paths) >= 2
original = Path.unlink
deleted = []
def interrupted(path, *args, **kwargs):
if path in paths:
if deleted:
raise OSError("simulated closeout interruption")
deleted.append(path)
return original(path, *args, **kwargs)
with monkeypatch.context() as m:
m.setattr(Path, "unlink", interrupted)
with pytest.raises(PortableResultPackageIntegrityError, match="retirement incomplete"):
publisher.publish(job=job, package_root=root)
assert (root / "retired-transport.json").is_file()
assert len(deleted) == 1
new_publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
result = new_publisher.publish(job=job, package_root=root)
assert all(not p.exists() for p in paths)
assert new_publisher.publish(job=job, package_root=root).binding == result.binding
def test_transport_retirement_preserves_unknown_files_and_rejects_corrupt_retries(tmp_path):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
unknown = root / "operator-note.txt"
unknown.write_text("keep")
publisher.publish(job=job, package_root=root)
assert unknown.read_text() == "keep"
(root / "artifacts/result.json").write_text("corrupt")
with pytest.raises(PortableResultPackageIntegrityError, match="content changed"):
publisher.publish(job=job, package_root=root)
assert (root / "artifacts/result.json").read_text() == "corrupt"
def test_no_retirement_until_catalog_publication_succeeds(tmp_path, monkeypatch):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
def fail(**kwargs):
raise ValueError("catalog unavailable")
monkeypatch.setattr(store, "publish_lab_instance", fail)
with pytest.raises(PortableResultPackageIntegrityError):
publisher.publish(job=job, package_root=root)
assert (root / "artifacts/result.json").is_file()
assert not (root / "retired-transport.json").exists()
def test_retired_retry_requires_intact_archive(tmp_path):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
result = publisher.publish(job=job, package_root=root)
member = result.artifact_manifest.member("result-document")
archive = CentralArtifactStore(tmp_path / "central-artifacts")
archive.object_path(member.sha256).unlink()
with pytest.raises(PortableResultPackageIntegrityError):
publisher.publish(job=job, package_root=root)
assert (root / "retired-transport.json").exists()
def test_published_retry_preserves_original_time_profile_label_and_archive(tmp_path):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
first = publisher.publish(job=job, package_root=root)
acknowledged = replace(job, updated_at_utc="2026-09-01T08:00:00.000Z")
renamed = replace(_profile(definition), display_name="New presentation label")
restarted = _publisher(
tmp_path, store=store, registry=registry, profile=renamed, validator=_validator
)
second = restarted.publish(job=acknowledged, package_root=root)
assert second == first
assert len(list((tmp_path / "central-artifacts/manifests").rglob("*.json"))) == 1
def test_retire_published_historical_transfer_does_not_readmit_old_definition(
tmp_path, monkeypatch
):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
with monkeypatch.context() as m:
m.setattr(publisher, "_retire_transport", lambda *args: None)
published = publisher.publish(job=job, package_root=root)
current = PortableRunDefinitionRegistry.from_file(
REPOSITORY_ROOT / "config/observatory-portable-run-definitions.json"
)
publisher._definitions = current
with pytest.raises(PortableResultPublicationBlockedError, match="not in the portable registry"):
publisher.publish(job=job, package_root=root)
with pytest.raises(PortableResultPublicationBlockedError, match="not durably published"):
publisher.retire_published_transport(
job=replace(job, publication_state="pending"), package_root=root
)
assert (root / "artifacts/result.json").is_file()
completed = replace(
job, publication_state="published", publication_attempts=1, published_at_utc=NOW
)
assert publisher.retire_published_transport(job=completed, package_root=root) == published
assert not (root / "artifacts/result.json").exists()
assert publisher.retire_published_transport(job=completed, package_root=root) == published
assert publisher._definitions is current
@pytest.mark.parametrize("damage", ["binding", "archive", "staging"])
def test_historical_transfer_closeout_preserves_data_on_identity_failure(
tmp_path, monkeypatch, damage
):
registry, definition, store, job, root = _fixture(tmp_path)
publisher = _publisher(
tmp_path, store=store, registry=registry, profile=_profile(definition), validator=_validator
)
with monkeypatch.context() as m:
m.setattr(publisher, "_retire_transport", lambda *args: None)
published = publisher.publish(job=job, package_root=root)
if damage == "binding":
provenance = copy.deepcopy(published.binding.provenance)
provenance["job"]["job_id"] = "another-job"
with sqlite3.connect(store.database_path) as connection:
connection.execute(
"UPDATE observation_lab_instances SET provenance_json = ? WHERE session_id = ?",
(json.dumps(provenance), RESULT_ID),
)
elif damage == "archive":
publisher._artifact_store.object_path(
published.artifact_manifest.member("result-document").sha256
).unlink()
else:
(root / "artifacts/result.json").write_bytes(b"changed")
with pytest.raises(PortableResultPackageIntegrityError):
publisher.retire_published_transport(
job=replace(
job, publication_state="published", publication_attempts=1, published_at_utc=NOW
),
package_root=root,
)
assert (root / "artifacts/result.json").is_file()
assert not (root / "retired-transport.json").exists()
@@ -18,7 +18,11 @@ from k1link.observatory.portable_run_definitions import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
DEFINITION_SHA256 = "269d71a24b4e63cff54e01273f9d4b35fc6cdd72bc6fadec206169ae0777e6ac"
MODEL_MANIFEST_SHA256 = "3fd2d43af73bd73f89d9ffae95d8770cfdeb46033ec967509124fac6ae4afe56"
M49_DEFINITION_SHA256 = "f56d6321bd794ccdfb7d2e3b05d044b11f616ffb81ee29517386cc253046d4eb"
+5 -1
View File
@@ -27,7 +27,11 @@ from k1link.sessions.models import SessionSummary
from k1link.web.observatory_api import build_observatory_router
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
SOURCE_SESSION_ID = "20260831T080000Z_viewer_live"
@@ -27,7 +27,11 @@ from k1link.observatory.source_admission import (
from k1link.sessions.models import SessionSummary
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
RAV004_SESSION_ID = "20260828T130511Z_viewer_live"
NEW_SESSION_ID = "20260831T080000Z_viewer_live"
@@ -58,7 +58,11 @@ from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue
from k1link.sessions import RecordedMediaInspector, SessionStore
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
REGISTRY_PATH = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
def _definitions() -> PortableRunDefinitionRegistry:
@@ -36,8 +36,16 @@ from k1link.observatory.worker_agent import (
)
REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
DEFINITION_REGISTRY = REPOSITORY_ROOT / "config" / "observatory-portable-run-definitions.json"
RUNTIME_REGISTRY = REPOSITORY_ROOT / "config" / "observatory-worker-runtime-candidates.json"
DEFINITION_REGISTRY = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-portable-run-definitions.json"
)
RUNTIME_REGISTRY = (
REPOSITORY_ROOT
/ "tests/fixtures/observatory/retired-fixed-lab"
/ "observatory-worker-runtime-candidates.json"
)
def _definitions() -> PortableRunDefinitionRegistry:
+55
View File
@@ -1648,3 +1648,58 @@ def test_simulation_and_recorded_claim_cannot_win_together(tmp_path):
simulation = pool.submit(simulate)
inference = pool.submit(recorded)
assert simulation.result() != inference.result()
def test_hidden_failed_attempt_keeps_audit_and_rejects_active_work(tmp_path: Path) -> None:
queue = _queue(tmp_path)
job, claim = _running_job(queue)
with pytest.raises(ObservatoryRecordedQueueConflictError):
queue.hide_failed_projection(job.job_id)
failed = queue.fail(
job.job_id,
claim_token=claim.claim_token,
error_code="executor-error",
message="prepare failed",
)
queue.hide_failed_projection(job.job_id)
queue.hide_failed_projection(job.job_id)
assert queue.get(job.job_id) == failed
assert queue.list_jobs(include_hidden=False) == ()
assert queue.list_jobs() == (failed,)
assert _queue(tmp_path).list_jobs(include_hidden=False) == ()
@pytest.mark.parametrize(
"state,publication,protected",
[
("accepted", "not-required", True),
("queued", "not-required", True),
("claimed", "not-required", True),
("running", "not-required", True),
("paused", "not-required", True),
("preemption-pending", "not-required", True),
("reconciliation-required", "not-required", True),
("failed", "not-required", False),
("succeeded", "pending", True),
("succeeded", "failed", True),
("succeeded", "published", False),
],
)
def test_source_consumers_include_hidden_and_pending_states(
tmp_path, state, publication, protected
):
queue = _queue(tmp_path)
intent = _intent()
job, _ = queue.submit(intent)
# Exercise the SQL ownership query against every durable state, including
# records hidden from UI. No truncated history list is used for liveness.
with sqlite3.connect(tmp_path / RECORDED_JOB_DATABASE_NAME) as connection:
connection.execute(
"UPDATE observatory_recorded_jobs SET state=?, publication_state=? WHERE job_id=?",
(state, publication, job.job_id),
)
connection.execute(
"INSERT INTO observatory_hidden_job_projections VALUES (?, ?)", (job.job_id, NOW)
)
assert queue.has_source_consumers([intent.source_session_id]) is protected
assert not queue.has_source_consumers(["unrelated-source"])
+232
View File
@@ -0,0 +1,232 @@
from __future__ import annotations
import asyncio
import hashlib
import json
import os
import subprocess
import sys
from types import SimpleNamespace
import pytest
from k1link.observatory import transfer_space as capacity
from k1link.observatory.source_transport_lifecycle import SourceCopy, SourceTransportLifecycle
from k1link.web.source_transfer_response import SourceTransferFileResponse
def test_large_multicomponent_transfers_use_actual_space_and_share_reservations(
tmp_path, monkeypatch
):
gib = 1024**3
free = [40 * gib]
monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=free[0]))
inputs, results = tmp_path / "inputs", tmp_path / "results"
inputs.mkdir()
results.mkdir()
first = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=2 * gib)
second = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=2 * gib)
with first.reservation(inputs, 20 * gib) as upload:
with second.reservation(results, 16 * gib):
with pytest.raises(capacity.TransferCapacityError):
first.check(inputs, 3 * gib)
# Written bytes already reduce disk free; don't double count them.
free[0] -= 12 * gib
upload.written(12 * gib)
first.check(inputs, 2 * gib)
first.check(inputs, 18 * gib)
assert not list(first.root.glob("reservation-*.json"))
def test_reservation_survives_await_and_releases_on_cancel(tmp_path, monkeypatch):
monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100))
service = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10)
async def upload():
with service.reservation(tmp_path, 80):
await asyncio.sleep(0)
with pytest.raises(capacity.TransferCapacityError):
service.check(tmp_path, 11)
raise asyncio.CancelledError()
with pytest.raises(asyncio.CancelledError):
asyncio.run(upload())
service.check(tmp_path, 90)
def test_dead_process_reservation_recovers_without_deleting_partial_data(tmp_path, monkeypatch):
script = """import os,sys
from pathlib import Path
from k1link.observatory.transfer_space import TransferSpace
p=Path(sys.argv[1])
with TransferSpace(p/'ledger',reserve_bytes=0).reservation(p,1000):
(p/'partial').write_bytes(b'recover me')
os._exit(0)
"""
subprocess.run([sys.executable, "-c", script, str(tmp_path)], check=True, timeout=10)
assert len(list((tmp_path / "ledger").glob("reservation-*.json"))) == 1
monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100))
capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10).check(tmp_path, 90)
assert (tmp_path / "partial").read_bytes() == b"recover me"
assert not list((tmp_path / "ledger").glob("reservation-*.json"))
def test_other_process_live_reservation_is_counted(tmp_path, monkeypatch):
script = """import sys
from pathlib import Path
from k1link.observatory.transfer_space import TransferSpace
p=Path(sys.argv[1])
with TransferSpace(p/'ledger',reserve_bytes=0).reservation(p,80):
print('ready',flush=True)
sys.stdin.readline()
"""
child = subprocess.Popen(
[sys.executable, "-c", script, str(tmp_path)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
)
try:
assert child.stdout.readline().strip() == "ready"
monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100))
with pytest.raises(capacity.TransferCapacityError):
capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=10).check(tmp_path, 11)
finally:
child.communicate("done\n", timeout=10)
def test_torn_dead_reservation_recovers_but_unknown_files_stay(tmp_path, monkeypatch):
service = capacity.TransferSpace(tmp_path / "ledger", reserve_bytes=0)
torn = service.root / ("reservation-" + "a" * 32 + ".json")
torn.write_bytes(b'{"version":')
unknown = service.root / "unrelated-evidence.json"
unknown.write_text("preserve")
monkeypatch.setattr(capacity.shutil, "disk_usage", lambda _: SimpleNamespace(free=100))
service.check(tmp_path, 100)
assert not torn.exists() and unknown.read_text() == "preserve"
def _copies(tmp_path, consumers=None):
original = tmp_path / "original"
original.write_bytes(b"immutable recording")
root = tmp_path / "cas"
root.mkdir()
copy = root / "copy"
copy.write_bytes(original.read_bytes())
digest = hashlib.sha256(original.read_bytes()).hexdigest()
service = SourceTransportLifecycle(root, consumers or (lambda _: False))
with service.reading():
service.register(
SourceCopy(copy, digest, copy.stat().st_size),
sources=[SourceCopy(original, digest, original.stat().st_size)],
session_id="recording-one",
)
return service, original, copy
def test_all_shared_consumers_and_readers_must_finish(tmp_path):
pending = {"recording-one", "recording-two"}
service, original, copy = _copies(
tmp_path, lambda sessions: bool(pending.intersection(sessions))
)
digest = hashlib.sha256(original.read_bytes()).hexdigest()
with service.reading():
service.register(
SourceCopy(copy, digest, copy.stat().st_size),
sources=[SourceCopy(original, digest, original.stat().st_size)],
session_id="recording-two",
)
pending.remove("recording-one")
assert service.collect()["protected"] == 1
pending.clear()
with service.reading():
assert service.collect()["reading"] == 1
assert copy.exists()
unknown = service.root / "old-unknown"
unknown.write_bytes(b"keep")
result = service.collect()
assert result["retired"] == 1 and result["bytes"] == len(original.read_bytes())
assert original.exists() and unknown.exists() and not copy.exists()
assert service.collect()["bytes"] == 0
@pytest.mark.parametrize(
"damage", ["missing_original", "changed_original", "changed_copy", "symlink", "hardlink"]
)
def test_unproven_recovery_and_shared_files_are_preserved(tmp_path, damage):
service, original, copy = _copies(tmp_path)
if damage == "missing_original":
original.unlink()
elif damage == "changed_original":
original.write_bytes(b"different recording")
elif damage == "changed_copy":
copy.write_bytes(b"different recording")
elif damage == "symlink":
copy.unlink()
copy.symlink_to(original)
else:
os.link(copy, tmp_path / "another-owner")
assert service.collect()["unverified"] == 1
assert copy.exists()
def test_retirement_recovers_after_unlink_before_receipt(tmp_path):
service, original, copy = _copies(tmp_path)
path = next(service.ledger.glob("*.json"))
row = json.loads(path.read_bytes())
row["state"] = "retiring"
path.write_text(json.dumps(row))
copy.unlink()
assert service.collect()["retired"] == 1
assert original.exists()
assert json.loads(path.read_bytes())["state"] == "retired"
def test_explicit_cleanup_scope_never_retires_other_registered_copies(tmp_path):
service, original, selected = _copies(tmp_path)
other = service.root / "other-registered"
other.write_bytes(original.read_bytes())
digest = hashlib.sha256(original.read_bytes()).hexdigest()
with service.reading():
service.register(
SourceCopy(other, digest, other.stat().st_size),
sources=[SourceCopy(original, digest, original.stat().st_size)],
session_id="recording-two",
)
assert service.collect(only_paths=[selected])["retired"] == 1
assert not selected.exists() and other.exists() and original.exists()
assert service.collect(only_paths=[])["retired"] == 0
assert other.exists()
@pytest.mark.parametrize("disconnect", [False, True])
def test_http_reader_is_held_until_range_finishes_even_on_disconnect(tmp_path, disconnect):
service, original, copy = _copies(tmp_path)
response = SourceTransferFileResponse(copy)
response.lease_fd = service.acquire_reader()
messages = []
async def send(message):
assert service.collect()["reading"] == 1
messages.append(message)
if disconnect:
raise ConnectionError("viewer disconnected")
async def receive():
return {"type": "http.disconnect"}
scope = {
"type": "http",
"method": "GET",
"headers": [(b"range", b"bytes=0-3")],
"extensions": {"http.response.pathsend": {}},
}
if disconnect:
with pytest.raises(ConnectionError):
asyncio.run(response(scope, receive, send))
else:
asyncio.run(response(scope, receive, send))
assert messages[0]["status"] == 206
assert messages[-1]["body"] == original.read_bytes()[:4]
assert not any(m["type"] == "http.response.pathsend" for m in messages)
assert service.collect()["retired"] == 1
+70 -10
View File
@@ -454,7 +454,7 @@ def test_session_router_versions_capability_and_calculation_profile_projections(
)
def test_observatory_projection_api_renames_alias_and_deletes_only_projection(
def test_observatory_projection_api_rename_and_delete_require_storage_service(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -553,16 +553,16 @@ def test_observatory_projection_api_renames_alias_and_deletes_only_projection(
assert store.get_session(projection.session_id).summary.display_name == "Маршрут у школы"
deleted = client.delete(url)
assert deleted.status_code == 204
assert deleted.content == b""
assert client.delete(url).status_code == 404
assert deleted.status_code == 503
assert client.delete(url).status_code == 503
assert store.get_lab_instance(projection.session_id) is not None
assert store.get_session_with_catalog_snapshot(source.name)[1] == source_snapshot
assert hashlib.sha256(source_payload.read_bytes()).hexdigest() == source_payload_sha256
assert source.is_dir()
assert cache_sentinel.read_bytes() == b"must-not-be-touched"
def test_observatory_projection_api_rejects_source_and_legacy_lab(
def test_observatory_projection_api_protects_source_and_supports_legacy_catalog(
tmp_path: Path,
) -> None:
repository = tmp_path / "repo"
@@ -588,14 +588,16 @@ def test_observatory_projection_api_rejects_source_and_legacy_lab(
"display_name": "Нельзя изменить",
}
for session_id in (source.name, legacy.session_id):
url = f"/api/v1/observatory/lab-projections/{session_id}"
assert client.patch(url, json=rename_document).status_code == 409
assert client.delete(url).status_code == 409
url = f"/api/v1/observatory/lab-projections/{source.name}"
assert client.patch(url, json=rename_document).status_code == 409
assert client.delete(url).status_code == 409
legacy_url = f"/api/v1/observatory/lab-projections/{legacy.session_id}"
assert client.patch(legacy_url, json=rename_document).status_code == 200
assert client.delete(legacy_url).status_code == 503
assert source.is_dir()
assert store.get_session(source.name).summary.session_id == source.name
assert store.get_session(legacy.session_id).summary.display_name == "LAB E21 · legacy API row"
assert store.get_session(legacy.session_id).summary.display_name == "Нельзя изменить"
def test_delete_session_removes_evidence_and_cache_but_refuses_an_open_recording(
@@ -3257,3 +3259,61 @@ def test_layout_get_migrates_legacy_tool_windows_out_of_the_contract(tmp_path: P
assert loaded["version"] == 2
assert "tool_windows" not in loaded
def test_worker_perception_preserves_playback_and_has_no_local_fallback(tmp_path):
import httpx
from k1link.laboratory.worker_gateway import (
LaboratoryGatewayConfiguration,
LaboratoryWorkerGateway,
)
repository = tmp_path / "repo"
sessions = repository / "sessions"
session = make_legacy_session(sessions, "20260716T205632Z_viewer_live")
store = SessionStore(repository, data_dir=tmp_path / "data")
store.reconcile_archive(xgrids_k1_archive_source(sessions))
token = tmp_path / "token"
token.write_text("b" * 48)
calls = []
def remote(request):
calls.append(request)
if request.method == "POST":
assert json.loads(request.content)["recording_id"] == "recording-001"
return httpx.Response(200, content=b"RRF2complete-playback")
assert request.headers["range"] == "bytes=4-8"
return httpx.Response(206, content=b"movie", headers={"content-range": "bytes 4-8/50"})
class LocalMustNotRun:
def render(self, *args, **kwargs):
raise AssertionError("Operator attempted LAB execution")
def video(self, *args, **kwargs):
raise AssertionError("Operator opened working data")
gateway = LaboratoryWorkerGateway(
LaboratoryGatewayConfiguration("http://127.0.0.1:19087", token),
transport=httpx.MockTransport(remote),
)
app = FastAPI()
app.include_router(build_session_router(
store, laboratory_gateway=gateway, perception_overlay_provider=LocalMustNotRun(),
perception_media_provider=LocalMustNotRun(),
))
with TestClient(app) as client:
prefix = f"/api/v1/observation-sessions/{session.name}"
r = client.post(prefix + "/perception.rrd", json={
"application_id": "nodedc_mission_core_recorded", "recording_id": "recording-001"})
assert r.status_code == 200 and r.content == b"RRF2complete-playback"
r = client.get(prefix + "/perception-media/result-test/recording.mp4?generation=abc",
headers={"Range": "bytes=4-8"})
assert r.status_code == 206 and r.content == b"movie"
assert calls[-1].url.path.endswith("/perception-media/result-test/recording.mp4")
assert calls[-1].url.query == b"generation=abc"
gateway.configuration = None
response = client.post(prefix + "/perception.rrd", json={
"application_id": "nodedc_mission_core_recorded", "recording_id": "recording-001",
})
assert response.status_code == 503
assert len(calls) == 2
+14 -4
View File
@@ -1461,7 +1461,7 @@ def test_capability_projection_delete_removes_only_catalog_projection(
).fetchone()[0] == 0
def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows(
def test_lab_projection_mutations_admit_legacy_but_reject_source_and_corrupt_rows(
tmp_path: Path,
) -> None:
repository = tmp_path / "repo"
@@ -1539,7 +1539,14 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows(
)
connection.commit()
for session_id in (source.name, legacy.session_id, corrupt.session_id):
with sqlite3.connect(store.database_path) as connection:
connection.execute(
"UPDATE observation_lab_instances SET include_recorded_media = NULL "
"WHERE session_id = ?",
(legacy.session_id,),
)
for session_id in (source.name, corrupt.session_id):
with pytest.raises(SessionIntegrityError, match="capability-owned"):
store.rename_capability_lab_projection(session_id, "Нельзя изменить")
with pytest.raises(SessionIntegrityError, match="capability-owned"):
@@ -1551,7 +1558,11 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows(
store.delete_capability_lab_projection(mismatch.session_id)
assert store.get_session(source.name).summary.session_id == source.name
assert store.get_session(legacy.session_id).summary.display_name == "LAB E21 · legacy"
assert store.rename_capability_lab_projection(legacy.session_id, "Архив") == "Архив"
store.delete_capability_lab_projection(legacy.session_id)
with pytest.raises(SessionNotFoundError):
store.get_session(legacy.session_id)
assert source.is_dir()
with sqlite3.connect(store.database_path) as connection:
retained_ids = {
row[0]
@@ -1561,7 +1572,6 @@ def test_capability_projection_mutations_reject_source_legacy_and_corrupt_rows(
}
assert {
source.name,
legacy.session_id,
corrupt.session_id,
mismatch.session_id,
} <= retained_ids