|
4 | 4 |
|
5 | 5 | import json |
6 | 6 | import sys |
| 7 | +import time |
| 8 | +from concurrent.futures import ThreadPoolExecutor |
7 | 9 | from pathlib import Path |
8 | 10 | from types import SimpleNamespace |
9 | 11 |
|
@@ -88,3 +90,34 @@ def spy(path: Path) -> role_dispatch.RoleLaunch: |
88 | 90 | _foreign(launch, tmp_path) |
89 | 91 | _foreign(real(dispatch), tmp_path) # same refusal as the eager loader |
90 | 92 | assert calls == [dispatch] |
| 93 | + |
| 94 | + |
| 95 | +def test_concurrent_first_calls_load_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 96 | + dispatch = tmp_path / "dispatch.json" |
| 97 | + _write_valid(dispatch, tmp_path) |
| 98 | + calls: list[Path] = [] |
| 99 | + real = role_dispatch.load |
| 100 | + |
| 101 | + def slow(path: Path) -> role_dispatch.RoleLaunch: |
| 102 | + calls.append(path) |
| 103 | + time.sleep(0.05) # widen the window: without the lock every thread loads |
| 104 | + return real(path) |
| 105 | + |
| 106 | + monkeypatch.setattr(role_dispatch, "load", slow) |
| 107 | + launch = _app(tmp_path, dispatch).state.store._role_launch |
| 108 | + assert launch is not None |
| 109 | + with ThreadPoolExecutor(16) as pool: |
| 110 | + for future in [pool.submit(_foreign, launch, tmp_path) for _ in range(16)]: |
| 111 | + future.result() |
| 112 | + assert len(calls) == 1 |
| 113 | + |
| 114 | + |
| 115 | +def test_unexpected_load_error_propagates(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 116 | + def broken(path: Path) -> role_dispatch.RoleLaunch: |
| 117 | + raise RuntimeError("not a missing-file problem") |
| 118 | + |
| 119 | + monkeypatch.setattr(role_dispatch, "load", broken) |
| 120 | + launch = _app(tmp_path, tmp_path / "dispatch.json").state.store._role_launch |
| 121 | + assert launch is not None |
| 122 | + with pytest.raises(RuntimeError, match="not a missing-file problem"): |
| 123 | + launch("audit", SimpleNamespace(run_id="a" * 64), tmp_path, {}) |