Run isolated export tasks concurrently and overlap cleanup
This commit is contained in:
1 parent
5b974c9b45
commit
8029d146cb
8 files changed
+341
-41
No files matched your search
@@ -131,3 +131,21 @@ def test_preflight_exception_is_a_warning_not_a_batch_blocker(tmp_path, monkeypa
|
||||
monkeypatch.setattr(cli, "_save_settings", lambda value: None)
|
||||
assert cli.main(["--input", str(tmp_path), "--output", str(tmp_path / "out"), "--yes"]) == 0
|
||||
assert list((tmp_path / "out").glob("批次_*/batch.json"))
|
||||
|
||||
|
||||
def test_batch_passes_worker_limit_and_records_execution_mode(tmp_path):
|
||||
from mentorexport.cli import run_batch
|
||||
limits = []
|
||||
def exporter(project, installation, folder, shared, **options):
|
||||
limits.append(options["jobs"])
|
||||
return {"status": "success", "items": []}
|
||||
batch, code = run_batch([{"name": "工程", "path": str(tmp_path / "a.prj")}], [], {},
|
||||
tmp_path / "out", tmp_path, exporter=exporter, jobs=2)
|
||||
record = json.loads((batch / "batch.json").read_text(encoding="utf-8"))
|
||||
assert code == 0 and limits == [2] and record["execution"]["jobs"] == 2
|
||||
|
||||
|
||||
def test_invalid_worker_limit_does_not_start_export(tmp_path):
|
||||
from mentorexport.cli import main
|
||||
for jobs in ("0", "9"):
|
||||
assert main(["--input", str(tmp_path), "--jobs", jobs, "--yes"]) == 2
|
||||
+158
-1
@@ -25,6 +25,163 @@ def backend():
|
||||
return exports
|
||||
|
||||
|
||||
def test_parallel_exports_overlap_on_distinct_clones_and_keep_receipt_order(sample, monkeypatch):
|
||||
from threading import Barrier, Lock
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
barrier, lock = Barrier(2), Lock()
|
||||
calls, workspaces = [], []
|
||||
run_ascii = ascii_runner(calls)
|
||||
active = maximum = 0
|
||||
def runner(command, cwd, environment, log_dir, **kwargs):
|
||||
nonlocal active, maximum
|
||||
with lock:
|
||||
active += 1
|
||||
maximum = max(maximum, active)
|
||||
workspaces.append(Path(cwd))
|
||||
try:
|
||||
barrier.wait(timeout=5)
|
||||
return run_ascii(command, cwd, environment, log_dir, **kwargs)
|
||||
finally:
|
||||
with lock:
|
||||
active -= 1
|
||||
monkeypatch.setattr(exports, "_run", runner)
|
||||
result = exports.export_project(project, install, root / "parallel", root / "shared", jobs=2, progress=lambda _: None)
|
||||
assert maximum == 2 and len(set(workspaces)) == 2
|
||||
assert [item["key"] for item in result["items"]] == [spec[0] for spec in exports.ITEMS]
|
||||
assert [i["key"] for i in result["items"] if i["status"] == "success"] == ["ascii_flat", "ascii_hier"]
|
||||
assert result["source_unchanged"] and result["execution"]["jobs"] == 2
|
||||
|
||||
|
||||
def test_library_starts_after_flat_without_waiting_for_other_exports(sample, monkeypatch):
|
||||
from threading import Event
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
library_started = Event()
|
||||
runner = ascii_runner([])
|
||||
def run(command, *args, **kwargs):
|
||||
if "-h" in command:
|
||||
assert library_started.wait(5), "library waited for unrelated exports"
|
||||
return runner(command, *args, **kwargs)
|
||||
def library(item, project, installation, result, *args):
|
||||
flat = next(i for i in result["items"] if i["key"] == "ascii_flat")
|
||||
assert flat["status"] == "success" and Path(flat["outputs"][0]).is_file()
|
||||
library_started.set()
|
||||
item.update(status="unavailable", reason="fixture without library")
|
||||
monkeypatch.setattr(exports, "_run", run)
|
||||
monkeypatch.setattr(exports, "_export_library", library)
|
||||
result = exports.export_project(project, install, root / "parallel", root / "shared", jobs=2, progress=lambda _: None)
|
||||
assert library_started.is_set() and result["items"][1]["status"] == "success"
|
||||
|
||||
|
||||
def test_snapshot_listing_overlaps_with_exports(sample, monkeypatch):
|
||||
from threading import Barrier
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
install["tools"]["constraints_xml"] = install["tools"]["ascii"]
|
||||
barrier = Barrier(2)
|
||||
runner = ascii_runner([])
|
||||
def run(command, cwd, environment, log_dir, **kwargs):
|
||||
if "-list" in command or "-f" in command:
|
||||
barrier.wait(timeout=5)
|
||||
if "-list" in command:
|
||||
Path(log_dir).mkdir(parents=True)
|
||||
(Path(log_dir) / "stdout.txt").write_text(" -> Saved\n")
|
||||
return {"exit_code": 0}
|
||||
return runner(command, cwd, environment, log_dir, **kwargs)
|
||||
monkeypatch.setattr(exports, "_run", run)
|
||||
result = exports.export_project(project, install, root / "parallel", root / "shared", jobs=2, progress=lambda _: None)
|
||||
assert result["snapshot_discovery"]["status"] == "success"
|
||||
assert result["items"][0]["status"] == "success"
|
||||
|
||||
|
||||
def test_forced_descendant_shutdown_keeps_files_but_never_reuses_as_verified(sample, monkeypatch):
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
calls = []
|
||||
ascii_run = ascii_runner(calls)
|
||||
def runner(*args, **kwargs):
|
||||
run = ascii_run(*args, **kwargs)
|
||||
run["cleanup"] = {"errors": [], "processes": [{"forced_termination": True,
|
||||
"forced_root_termination": False, "forced_descendant_pids": [123],
|
||||
"termination_reason": "descendant_grace_expired", "job_active_processes": 0}]}
|
||||
return run
|
||||
monkeypatch.setattr(exports, "_run", runner)
|
||||
first = exports.export_project(project, install, root / "first", root / "shared", jobs=2, progress=lambda _: None)
|
||||
assert first["items"][0]["status"] == "exported" and first["items"][0]["outputs"]
|
||||
assert first["items"][0]["validation"]["status"] == "warning"
|
||||
exports.export_project(project, install, root / "retry", root / "shared", jobs=2, previous=first, progress=lambda _: None)
|
||||
assert len(calls) == 4
|
||||
|
||||
|
||||
def test_forced_library_shutdown_retains_records_without_trusted_cache(sample, monkeypatch):
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
library = root / "library/PartsDBLibs"
|
||||
library.mkdir(parents=True)
|
||||
(library / "a.pdb").write_bytes(b"parts")
|
||||
project["library"] = str(library.parent)
|
||||
monkeypatch.setattr(exports, "VALIDATED_DLLS", {})
|
||||
monkeypatch.setattr(exports, "_LIBRARY_CACHE", {})
|
||||
calls = []
|
||||
def runner(command, cwd, environment, log_dir, **kwargs):
|
||||
if "-f" in command or "-h" in command:
|
||||
output = Path(next(arg.split("=", 1)[1] for arg in command if arg.startswith("-file=")))
|
||||
output.write_text("iCDB Ascii Report\n" + ("Block Top\n" if "-h" in command else "Config default\n") + "\tProp Part Number USED\n")
|
||||
return dict(exit_code=0, cleanup={"errors": []})
|
||||
calls.append(command)
|
||||
Path(log_dir).mkdir(parents=True, exist_ok=True)
|
||||
(Path(log_dir) / "stdout.txt").write_text(json.dumps({"mode": "parts", "count": 1, "records": [{"name": "USED"}]}), encoding="utf-8")
|
||||
return dict(exit_code=0, cleanup={"errors": [], "processes": [{"forced_termination": True}]})
|
||||
monkeypatch.setattr(exports, "_run", runner)
|
||||
first = exports.export_project(project, install, root / "first", root / "shared", jobs=2, progress=lambda _: None)
|
||||
item = next(i for i in first["items"] if i["key"] == "library")
|
||||
assert item["status"] == "exported" and item["validation"]["status"] == "warning"
|
||||
data = next(json.loads(Path(path).read_text(encoding="utf-8")) for path in item["outputs"] if Path(path).name.startswith("used-"))
|
||||
assert data["records"]["parts"][0]["name"] == "USED" and data["complete"] is False
|
||||
exports.export_project(project, install, root / "retry", root / "shared", jobs=2, previous=first, progress=lambda _: None)
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_parallel_cancel_drains_active_tasks_without_launching_queued_vendor_work(sample, monkeypatch):
|
||||
from threading import Barrier
|
||||
exports = backend()
|
||||
project, install, root = sample
|
||||
stop, barrier = Event(), Barrier(2)
|
||||
calls = []
|
||||
def runner(command, cwd, *args, **kwargs):
|
||||
calls.append(command)
|
||||
barrier.wait(timeout=5)
|
||||
stop.set()
|
||||
return dict(exit_code=None, cancelled=True, cleanup={"errors": []})
|
||||
monkeypatch.setattr(exports, "_run", runner)
|
||||
result = exports.export_project(project, install, root / "cancel", root / "shared", jobs=2,
|
||||
stop_event=stop, progress=lambda _: None)
|
||||
assert len(calls) == 2 and result["status"] == "cancelled"
|
||||
assert all(item["status"] == "cancelled" for item in result["items"])
|
||||
|
||||
|
||||
def test_process_exit_notification_advances_without_polling_delay(tmp_path, monkeypatch):
|
||||
exports = backend()
|
||||
class Process:
|
||||
pid = 123
|
||||
finished = False
|
||||
def poll(self): return 0 if self.finished else None
|
||||
def wait(self, timeout=None):
|
||||
self.finished = True
|
||||
return 0
|
||||
class Desktop:
|
||||
cleanup_record = {"errors": [], "processes": []}
|
||||
def __init__(self, *args, **kwargs): pass
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): pass
|
||||
def start_process(self, *args, **kwargs): return Process()
|
||||
def inspect_dialogs(self, pid): return []
|
||||
monkeypatch.setattr(exports, "PrivateDesktop", Desktop)
|
||||
result = exports._run(["fixture"], tmp_path, {}, tmp_path / "logs", stop_event=None, timeout=0.15)
|
||||
assert result["exit_code"] == 0 and not result["timed_out"]
|
||||
|
||||
|
||||
def ascii_runner(calls):
|
||||
def run(command, cwd, environment, log_dir, *, stop_event, timeout):
|
||||
calls.append(command)
|
||||
@@ -216,7 +373,7 @@ def test_uncertain_snapshot_cleanup_continues_exports_and_preserves_copy(sample,
|
||||
return dict(exit_code=0, cleanup_uncertain=True, cleanup={"errors": ["exit unconfirmed"]})
|
||||
monkeypatch.setattr(exports, "_run", runner)
|
||||
result = exports.export_project(project, install, root / "attempt", root / "shared", progress=lambda _: None)
|
||||
assert len(calls) == 3 and "-list" in calls[0]
|
||||
assert len(calls) == 3 and any("-list" in call for call in calls)
|
||||
assert result["cleanup_uncertain"] is True
|
||||
assert result["status"] == "skipped"
|
||||
assert not any(i["status"] == "cancelled" for i in result["items"])
|
||||
|
||||
Reference in new issue
Block a user