Make simulation imports background tasks with Worker-owned sources and durable deletion

This commit is contained in:
DCCONSTRUCTIONS
2026-11-16 18:13:27 +03:00
parent 9871ae500f
commit 7c0dbd4e06
28 changed files with 1283 additions and 128 deletions
+141
View File
@@ -0,0 +1,141 @@
import json
from types import SimpleNamespace
import pytest
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineGatewayError
from k1link.simulation.projects import (
SimulationProjectNotFoundError,
SimulationProjectService,
SimulationProjectStore,
)
def fixture(tmp_path):
store = SimulationProjectStore(tmp_path)
row = store.create(
name="Disposable",
scene_type="outdoor",
source_kind="folder",
files=[dict(logical_path="a.ply", byte_length=8)],
)
receipt = dict(source_id="src-" + "a" * 64)
store.update_source_storage(
row["project_id"],
storage=dict(provider_endpoint="http://worker", receipt=receipt, local_state="remote"),
)
store.update_processing(
row["project_id"], status="processing", provider_job_id="gsp-20261116000000-1234abcd"
)
calls = []
provider = SimpleNamespace(
endpoint="http://worker",
close=lambda: None,
delete_job=lambda id: calls.append(("job", id)),
delete_retained_source=lambda r: calls.append(("source", r["source_id"])),
)
service = SimulationProjectService(store, lambda: provider)
service.deletions.start = lambda: None
return store, row["project_id"], provider, service, calls
def test_source_failure_keeps_row_and_recovery_completes_after_restart(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
good = provider.delete_retained_source
def offline(_):
raise GaussianPipelineGatewayError("Worker offline")
provider.delete_retained_source = offline
service.deletions.request(pid)
service.deletions.attempt(service.deletions.list()[0])
assert store.get(pid) and service.deletions.list()[0]["state"] == "waiting"
assert calls[0][0] == "job"
provider.delete_retained_source = good
recovered = SimulationProjectService(store, lambda: provider)
recovered.deletions.attempt(recovered.deletions.list()[0])
assert not recovered.deletions.list()
with pytest.raises(SimulationProjectNotFoundError):
store.get(pid)
assert calls[-1][0] == "source"
def test_shared_source_and_job_survive_until_last_project_owner(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
second = store.create(
name="Second",
scene_type="outdoor",
source_kind="folder",
files=[dict(logical_path="a.ply", byte_length=8)],
)
first = store.get(pid)
store.update_source_storage(second["project_id"], storage=first["source"]["storage"])
store.update_processing(
second["project_id"], status="processing", provider_job_id=first["provider"]["job_id"]
)
service.delete(pid)
assert calls == [] and store.get(second["project_id"])
service.delete(second["project_id"])
assert [call[0] for call in calls] == ["job", "source"]
def test_dependency_blocks_deletion_instead_of_orphaning_run(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
run = tmp_path / "ai-polygon/runs/run"
run.mkdir(parents=True)
(run / "run.json").write_text(json.dumps({"world_id": pid.replace("sim-", "aiworld-")}))
with pytest.raises(RuntimeError, match="сохранённых заданиях"):
service.deletions.request(pid)
assert not calls and store.get(pid)
def test_ui_delete_endpoint_persists_intent_without_waiting_for_worker(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.simulation_projects_api import build_simulation_projects_router
store, pid, provider, service, calls = fixture(tmp_path)
app = FastAPI()
app.include_router(build_simulation_projects_router(store=store, service=service))
client = TestClient(app)
assert client.delete("/api/v1/simulation-worlds/projects/" + pid).status_code == 202
assert (
client.get("/api/v1/simulation-worlds/deletions").json()["deletions"][0]["project_id"]
== pid
)
assert store.get(pid) and not calls
def test_prepared_archive_members_and_original_are_both_removed(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
store.update_source_storage(pid, prepared_receipt=dict(source_id="src-" + "b" * 64))
service.delete(pid)
assert [call[0] for call in calls] == ["job", "source", "source"]
assert calls[1][1] == "src-" + "b" * 64
def test_large_unrelated_evidence_does_not_block_deletion(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
evidence = tmp_path / "ai-polygon/urban-maps/other.json"
evidence.parent.mkdir(parents=True)
evidence.write_text('{"geometry":"' + 'x' * (9 * 1024**2) + '"}')
service.delete(pid)
assert [call[0] for call in calls] == ["job", "source"]
def test_dependency_scan_finds_identity_across_chunk_boundary(tmp_path):
from k1link.simulation.project_deletions import contains_identity
identity = "aiworld-" + "f" * 32
evidence = tmp_path / "large.json"
evidence.write_bytes(b"x" * (64 * 1024 - 10) + identity.encode() + b"x")
assert contains_identity(evidence, identity, "sim-" + "f" * 32)
def test_deleting_project_cannot_be_requeued(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
service.deletions.request(pid)
with pytest.raises(RuntimeError, match="Удаление локации уже начато"):
service.enqueue(pid)
assert not calls
+141
View File
@@ -0,0 +1,141 @@
import hashlib
from types import SimpleNamespace
import pytest
from k1link.simulation.ai_polygon.originals import retain_legacy_original
from k1link.simulation.ai_polygon.worlds import WorldStore, write_json
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineIntegrityError
def setup(tmp_path):
worlds = WorldStore(tmp_path)
wid = "aiworld-" + "a" * 32
root = worlds.root / wid
root.mkdir()
raw = b"original"
(root / "source.ply").write_bytes(raw)
sha = hashlib.sha256(raw).hexdigest()
write_json(
root / "world.json",
dict(world_id=wid, status="available", byte_length=len(raw), sha256=sha),
)
output = root / "render.sog"
output.write_bytes(b"optimized")
editor = SimpleNamespace(
request=lambda _: dict(key="cache"),
get=lambda _: dict(key="cache", status="ready", files={"scene.sog": {}}),
asset=lambda *_: (output, hashlib.sha256(b"optimized").hexdigest()),
)
source = dict(
format="ply",
entrypoint="source.ply",
total_byte_length=8,
bundle_sha256="",
members=[dict(upload_id="x", logical_path="source.ply", byte_length=8, sha256=sha)],
)
import json
# Real connector computes this exact canonical manifest; test uses its serializer.
from k1link.simulation.gaussian_pipeline_gateway import _source_bundle_upload
# key ordering is format/entrypoint/members, each member logical_path/sha256/byte_length.
identity = dict(
format="ply",
entrypoint="source.ply",
members=[dict(logical_path="source.ply", sha256=sha, byte_length=8)],
)
source["bundle_sha256"] = hashlib.sha256(
json.dumps(identity, separators=(",", ":")).encode()
).hexdigest()
bundle = _source_bundle_upload(source)
receipt = dict(
schema_version="gaussian-pipeline.source-receipt/v1",
retention="independent-of-jobs",
source_id="src-" + "b" * 64,
verified_at_utc="2026-11-16T00:00:00Z",
input=dict(kind="folder", source=source),
)
provider = SimpleNamespace(
endpoint="http://worker",
require_source_retention=lambda: None,
upload_source_bundle=lambda *_a, **_k: bundle,
retain_source=lambda _: receipt,
retained_source=lambda r, **_k: r,
)
return worlds, wid, root, editor, provider
def test_cleanup_requires_verified_original_and_keeps_result_identity(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
result = retain_legacy_original(worlds, wid, provider, editor)
assert result["removed_bytes"] == 8 and not (root / "source.ply").exists()
assert (root / "render.sog").read_bytes() == b"optimized"
assert worlds.get(wid)["original_storage"]["local_state"] == "remote"
assert retain_legacy_original(worlds, wid, provider, editor)["removed_bytes"] == 0
def test_worker_failure_never_removes_only_local_original(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
def unavailable(*_a, **_k):
raise RuntimeError("offline")
provider.retained_source = unavailable
with pytest.raises(RuntimeError, match="offline"):
retain_legacy_original(worlds, wid, provider, editor)
assert (root / "source.ply").read_bytes() == b"original"
def test_render_corruption_blocks_source_cleanup(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
(root / "render.sog").write_bytes(b"corrupt")
with pytest.raises(GaussianPipelineIntegrityError):
retain_legacy_original(worlds, wid, provider, editor)
assert (root / "source.ply").exists()
def test_original_download_streams_worker_bytes_without_local_source(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.simulation_originals_api import build_simulation_originals_router
worlds, wid, root, editor, provider = setup(tmp_path)
retain_legacy_original(worlds, wid, provider, editor)
closed = []
provider.close = lambda: closed.append(True)
provider.stream_retained_file = lambda *_: (chunk for chunk in [b"ori", b"ginal"])
app = FastAPI()
app.include_router(build_simulation_originals_router(worlds, lambda: provider))
client = TestClient(app)
response = client.get(f"/worlds/{wid}/originals")
assert response.status_code == 200
assert response.json()["files"][0]["sha256"] == worlds.get(wid)["sha256"]
response = client.get(f"/worlds/{wid}/original", params={"path": "source.ply"})
assert response.content == b"original"
assert response.headers["content-disposition"].startswith("attachment;")
assert not (root / "source.ply").exists() and closed
assert (
client.get(f"/worlds/{wid}/original", params={"path": "../world.json"}).status_code == 404
)
offline = FastAPI()
offline.include_router(build_simulation_originals_router(worlds, lambda: None))
assert TestClient(offline).get(f"/worlds/{wid}/originals").status_code == 503
def test_source_attribution_does_not_expand_closed_project_v1_response(tmp_path):
from k1link.simulation.projects import SimulationProjectStore
from k1link.web.simulation_projects_api import SimulationProjectDocument, SimulationProjectPage
store = SimulationProjectStore(tmp_path)
row = store.create(
name="Test",
scene_type="outdoor",
source_kind="folder",
files=[{"logical_path": "scene.ply", "byte_length": 8}],
attribution={"author": "Owner", "license": "Private", "source_url": None},
)
assert store.get(row["project_id"])["attribution"]["author"] == "Owner"
assert "attribution" not in SimulationProjectDocument.model_validate(row).model_dump()
assert "attribution" not in SimulationProjectPage(projects=[row]).model_dump()["projects"][0]
+3
View File
@@ -288,6 +288,9 @@ class _ReadyProvider:
destination.write_bytes(payload)
return destination
def delete_retained_source(self, receipt) -> None:
self.deleted_sources = getattr(self, "deleted_sources", []) + [receipt["source_id"]]
def delete_job(self, job_id: str) -> None:
self.deleted.append(job_id)