From a8a992be9c9c353e6a5489148e101a7c49ba7656 Mon Sep 17 00:00:00 2001 From: DanOlds Date: Thu, 5 Nov 2026 12:33:06 -0500 Subject: [PATCH] fix: keep previous results until a run can start; no default server wait limit - powderline.run() validates the recipe and probes that the gateway's engine is importable before it clears the directory's fixed-name outputs: a mistyped recipe or a run in an environment without the engine raises and leaves the previous results in place. The probe is the installed_engine_version of the module defining the registered gateway's run(), so a replacement gateway or TOPAS is left to its own checks. - The GSAS-II client's fixed 300 s read timeout on the /simulate request is gone: a refinement takes as long as it takes, as in-process (the connect, write and pool phases keep a 30 s bound). The gsasii gateway gains server_timeout (seconds; None or 0 = no limit) and the CLI --server-timeout SECONDS, mirroring --topas-timeout; past the limit the run raises ExecutionBackendError timeout with no in-process fallback, as before. Gates: core 1848 passed / 23 skipped; gsasii 1488 / 3; docs -W clean. Refs #13 Assisted-by: claude-code:claude-fable-5-1 --- AGENTS.md | 12 ++-- CHANGELOG.md | 9 ++- README.md | 3 +- docs/TROUBLESHOOTING.md | 3 +- docs/api.rst | 4 +- docs/getting-started.rst | 3 +- docs/schemas.md | 2 +- src/powderline/api.py | 39 ++++++++++++- src/powderline/gateways/gsasii/client.py | 22 +++++++- src/powderline/gateways/gsasii/gateway.py | 31 ++++++++++- src/powderline/kicker.py | 15 ++++- tests/test_api.py | 67 ++++++++++++++++++++++- tests/test_cli.py | 5 ++ tests/test_failed_run_artefacts.py | 54 ++++++++++++++++++ 14 files changed, 243 insertions(+), 26 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 30c608b..26cd373 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,8 +37,8 @@ Core (engine-free; `import powderline` imports no engine): topas `topas_dir`, `topas_version`, `topas_timeout`); `allow_unsupported_engine_version` is refused (test-only, on the gateway's own `run`). - `kicker.py` — the one CLI: `powderline [--output DIR] - [--validate-only] [--verbose] [--use-server|--no-server] [--topas-dir DIR] - [--topas-version V] [--topas-timeout SECONDS]` and `powderline --doctor` (`doctor.py`: gateways, + [--validate-only] [--verbose] [--use-server|--no-server] [--server-timeout SECONDS] + [--topas-dir DIR] [--topas-version V] [--topas-timeout SECONDS]` and `powderline --doctor` (`doctor.py`: gateways, engine versions vs pins, server state; non-zero on a stale install, KI-13); `pixi run kicker` / `pixi run doctor` run the same `main`. Refuses templates; an engine flag for another engine's recipe exits 1. @@ -223,9 +223,11 @@ compares the server's source-tree hash with its own and refuses a stale one). gsasii `dummy.gpx`/`dummy.lst`; topas `.inp` etc.). `unit_cell_data`/`peak_list_data` from `run()` are dicts keyed by phase name. `powderline.run()` removes PowderLine's own fixed-name files from the output - directory before every run (`reports.clear_fixed_outputs`) and, when a run - fails, writes the failed envelope to `failure.json` beside the engine's own - files; no result table is written for a failed run on any engine. + directory before every run (`reports.clear_fixed_outputs`) — only once the + recipe has validated and the engine is importable, so a typo or a wrong + environment costs nothing — and, when a run fails, writes the failed envelope + to `failure.json` beside the engine's own files; no result table is written + for a failed run on any engine. - Known, deliberately-deferred behaviours are registered with stable `KI-NN` ids in `docs/known_issues.md` — check it before "fixing" a quirk; engine quirks and PowderLine's policy are on `docs/engine-behavior.md`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 67ea961..416486b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -146,12 +146,17 @@ limitations are listed in the [known-issues register](docs/known_issues.md). - A failed run leaves only the engine's own files and `failure.json`: a gsasii run no longer writes result tables before PowderLine's checks. - `powderline.run()` removes PowderLine's own fixed-name outputs from the output - directory before every run, so a reused directory holds one run's results. + directory before every run, so a reused directory holds one run's results; + only once the recipe has validated and the engine is importable, so an + invalid recipe or a run in an environment without the engine leaves the + previous results in place. - Every engine writes the same seven unit-cell report rows, `cell_a` … `cell_gamma`, `cell_volume`; a gsasii simulation writes ESD `0.0` (was empty). - The GSAS-II server needs no shared filesystem: output files come back inside the signed response (KI-12); it runs one job at a time and a stale server is - detected and refused. + detected and refused. Waiting for its answer has no time limit by default + (as in-process); `--server-timeout SECONDS` / the `server_timeout` option set + one (past it `ExecutionBackendError` `timeout`, no in-process fallback). - TOPAS runs only from a declared directory (`--topas-dir` or `topas.dir`); without one a run writes the INP and data and stops (`status: generated`). `topas.*` recipes state `engine_version: "6"` and the installed version is diff --git a/README.md b/README.md index 581851f..dd32838 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,8 @@ pixi run -e gsasii doctor # wha After `pixi reinstall powderline` the same program is the installed command `powderline …`. Flags: `--output DIR` (default: `output/` next to the recipe), `--verbose`, `--validate-only`; gsasii `--use-server` / -`--no-server`; topas `--topas-dir DIR` / `--topas-version V` / +`--no-server` / `--server-timeout SECONDS` (default: no limit); topas +`--topas-dir DIR` / `--topas-version V` / `--topas-timeout SECONDS` (default 3600; 0 = no limit). A flag given for a recipe of another engine is an error. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index d05d35b..12427bf 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -345,7 +345,8 @@ keeps the same text under `engine_details["console_tail"]`. console window and `tc.log`. A file it did write but PowderLine cannot read strictly is `output_malformed`. 5. **The engine did not run** (`Could not run the engine (…)`): `server_unavailable` / `server_disabled` / `communication_failed` / `timeout` are the - GSAS-II server's cases (see "Server Not Starting" below), and `timeout` is + GSAS-II server's cases (see "Server Not Starting" below; `timeout` only when + `--server-timeout` / `server_timeout` set a limit, there is none by default), and `timeout` is also a `tc.exe` run that outlived `--topas-timeout` / `topas.timeout` (default 3600 s: raise it for a long refinement, or look for a TOPAS dialog waiting for input); `timeout` deliberately does diff --git a/docs/api.rst b/docs/api.rst index 450c1e1..2d1903c 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -60,8 +60,8 @@ Command line .. py:module:: powderline.kicker ``powderline [--output DIR] [--validate-only] [--verbose] -[--use-server | --no-server] [--topas-dir DIR] [--topas-version V] -[--topas-timeout SECONDS]`` (the pixi +[--use-server | --no-server] [--server-timeout SECONDS] [--topas-dir DIR] +[--topas-version V] [--topas-timeout SECONDS]`` (the pixi task ``kicker`` runs the same ``main``), and ``powderline --doctor`` (the pixi task ``doctor``): what this environment can do — the gateways the registry finds, each engine's installed version against its requirement, the GSAS-II diff --git a/docs/getting-started.rst b/docs/getting-started.rst index 9bf740a..dbd1211 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -41,7 +41,8 @@ Enable verbose output:: After ``pixi reinstall powderline`` the same program is available as the installed command ``powderline ...``. Flags: ``--output DIR`` (default ``output/`` next to the recipe), ``--validate-only``, ``--verbose``; -for ``gsasii.*`` recipes ``--use-server`` / ``--no-server``; for ``topas.*`` +for ``gsasii.*`` recipes ``--use-server`` / ``--no-server`` / ``--server-timeout +SECONDS`` (how long to wait for the server's answer; default no limit); for ``topas.*`` recipes ``--topas-dir DIR`` / ``--topas-version V`` / ``--topas-timeout SECONDS`` (each tc.exe run is stopped after this long; default 3600, 0 = no limit). A flag given for a recipe diff --git a/docs/schemas.md b/docs/schemas.md index 5e64417..cfe2ed3 100644 --- a/docs/schemas.md +++ b/docs/schemas.md @@ -183,7 +183,7 @@ each name; the recipe-path view of the same values is `parameter_dispositions`. | `server_unavailable` | backend | server mode: no GSAS-II server and none could be started | | `server_disabled` | backend | `POWDERLINE_NO_SERVER` with `execution_mode='server'` | | `communication_failed` | backend | an HTTP/transport error after a server was found | -| `timeout` | backend | GSAS-II server mode: the request timed out; **no in-process fallback** (the job is still running on the server; a second run would double the work). TOPAS: `tc.exe` outlived `topas_timeout` (default 3600 s) and was stopped (the background-only run stopped at the limit is not a failure: `y_bkg` empty with `topas_background_not_calculated`) | +| `timeout` | backend | GSAS-II server mode: the server's answer outlived `server_timeout` / `--server-timeout` (no limit unless one is set); **no in-process fallback** (the job is still running on the server; a second run would double the work). TOPAS: `tc.exe` outlived `topas_timeout` (default 3600 s) and was stopped (the background-only run stopped at the limit is not a failure: `y_bkg` empty with `topas_background_not_calculated`) | | `backend_error` | backend | anything else on the execution path before the engine ran (e.g. a recipe the server could not validate) | With `validate_only=True` the result is a slim summary with the same keys on diff --git a/src/powderline/api.py b/src/powderline/api.py index 434e907..06840d8 100644 --- a/src/powderline/api.py +++ b/src/powderline/api.py @@ -11,8 +11,9 @@ warnings the validation produced. - :func:`run` uses the gateway's **runtime layer**; engine options are forwarded to the gateway unchanged. Around the gateway it owns the output - directory's PowderLine files (re/30): it removes the fixed-name outputs - before dispatch and, when the run fails, writes the failed envelope to + directory's PowderLine files (re/30): once the recipe has validated and the + gateway's engine is importable here, it removes the fixed-name outputs before + dispatch; when the run fails, it writes the failed envelope to ``failure.json`` beside the engine's own files before re-raising. This module imports no engine and no gateway module at import time (enforced @@ -149,7 +150,11 @@ def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = Fals options as explicit keywords, so an option it does not know is a ``TypeError`` naming it: - - ``gsasii``: ``execution_mode`` (``'auto'`` | ``'server'`` | ``'subprocess'``); + - ``gsasii``: ``execution_mode`` (``'auto'`` | ``'server'`` | ``'subprocess'``) + and ``server_timeout`` (seconds to wait for the GSAS-II server's answer; + default none, as for an in-process run, 0 = none; past it the run raises + ``ExecutionBackendError`` ``timeout`` and does not fall back in-process, + the job being still on the server); - ``topas``: ``topas_dir`` (the folder holding ``tc.exe``), ``topas_version`` (the installed TOPAS release, e.g. ``"6"``; a real run needs it declared, here or in ``.powderline_config.yaml``) and ``topas_timeout`` (seconds per @@ -161,6 +166,13 @@ def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = Fals engine version check and is refused here (``TypeError``); call the gateway's ``run`` directly for compatibility testing. + Before anything on disk changes, the recipe is validated and the gateway's + engine is checked to be importable here: an invalid recipe or a run in an + environment without the engine raises and leaves the output directory's + previous results in place. Then PowderLine's own fixed-name outputs are + removed from ``output_dir`` (the engine's files and anything else stay), so + a reused directory holds one run's results (re/30). + Args: recipe: a recipe dict or a validated model. output_dir: directory for the output files; created by the gateway. @@ -205,6 +217,10 @@ def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = Fals gateway = gateway_for(recipe) if validate_only: return gateway.run(recipe, output_dir, verbose=verbose, validate_only=True, **engine_options) + # Nothing on disk changes until the run can start: an invalid recipe (ValidationError) or an engine that + # is not importable here (EngineNotAvailableError) must not cost the directory its previous results. + gateway.validate(recipe, verbose=verbose) + _engine_importable(gateway) from powderline import reports reports.clear_fixed_outputs(output_dir) # one run's results per directory (re/30); the engine's files stay try: @@ -214,6 +230,23 @@ def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = Fals raise +def _engine_importable(gateway) -> None: + """Raise ``EngineNotAvailableError`` when the gateway's engine is not importable here. + + Called before the output directory is touched. The probe is what the module that defines the + gateway's ``run`` exposes as ``installed_engine_version`` (the in-tree gsasii and easydiffraction + gateways; the same function :func:`_engine_version_of` reads). A gateway whose module has none + (TOPAS, which needs no Python engine; a registered replacement; an out-of-tree gateway) is left + to its own ``run``. + """ + import sys + + module = sys.modules.get(getattr(gateway.run, "__module__", None) or "") + probe = getattr(module, "installed_engine_version", None) + if probe is not None: + probe() + + def _schema_name_of(recipe) -> str: if isinstance(recipe, dict): return str(recipe.get("schema_name", "")) diff --git a/src/powderline/gateways/gsasii/client.py b/src/powderline/gateways/gsasii/client.py index e773f3e..2a033cc 100644 --- a/src/powderline/gateways/gsasii/client.py +++ b/src/powderline/gateways/gsasii/client.py @@ -90,16 +90,26 @@ def _write_file(path: Path, data: bytes) -> None: raise +#: Time limit (s) on the connect, write and pool phases of a ``/simulate`` request: loopback, so generous. +#: The read phase is the refinement itself and is bounded only by ``GSASClient(request_timeout=...)``. +REQUEST_PHASE_TIMEOUT = 30.0 + + class GSASClient: """Client for communicating with GSAS-II server.""" - def __init__(self, fallback_to_subprocess: bool = True): + def __init__(self, fallback_to_subprocess: bool = True, request_timeout: Optional[float] = None): """Initialize client. Args: fallback_to_subprocess: If True, use subprocess when server unavailable + request_timeout: seconds to wait for the server's answer to a submitted job + (the read phase of the ``/simulate`` request). ``None``: no limit, as for + an in-process run. A limit does not free the server: the job keeps running + there, which is why a timeout never falls back in-process. """ self.fallback_to_subprocess = fallback_to_subprocess + self.request_timeout = request_timeout self._state_warning_shown = False self._start_error: Optional[str] = None # why the last auto-start could not even be attempted @@ -255,7 +265,7 @@ def _server_attempt(self, recipe_dict: dict, output_dir: Path, verbose: bool) -> except httpx.TimeoutException as e: return envelopes.failure_envelope( "backend", "timeout", - f"the GSAS-II server did not answer within the request timeout ({e}); not falling back " + f"the GSAS-II server did not answer within server_timeout ({e}); not falling back " f"in-process because the job is still running on the server (a second run would double the work)", method="server") except Exception as e: @@ -527,6 +537,12 @@ def _start_server_background(self, verbose: bool = False) -> bool: print(f" Could not auto-start server: {e}") return False + def _simulate_timeout(self): + """The ``/simulate`` request's httpx timeout: ``REQUEST_PHASE_TIMEOUT`` on connect, write and + pool; ``request_timeout`` on the read phase (the refinement), ``None`` = no limit.""" + import httpx + return httpx.Timeout(REQUEST_PHASE_TIMEOUT, read=self.request_timeout) + def _submit_to_server(self, recipe_dict: dict) -> Dict[str, Any]: """Submit simulation to server via HTTP with retry logic. @@ -549,7 +565,7 @@ def _submit_to_server(self, recipe_dict: dict) -> Dict[str, Any]: if endpoint is None: raise httpx.ConnectError("No GSAS-II server endpoint for this user") resp = self._signed_request(endpoint, 'POST', '/simulate', - payload, timeout=300.0) + payload, timeout=self._simulate_timeout()) resp.raise_for_status() return resp.json() except httpx.ConnectError as e: diff --git a/src/powderline/gateways/gsasii/gateway.py b/src/powderline/gateways/gsasii/gateway.py index 3164a3f..548a025 100644 --- a/src/powderline/gateways/gsasii/gateway.py +++ b/src/powderline/gateways/gsasii/gateway.py @@ -94,6 +94,7 @@ def run( verbose: bool = False, validate_only: bool = False, execution_mode: Literal['auto', 'server', 'subprocess'] = 'auto', + server_timeout: float | None = None, allow_unsupported_engine_version: bool = False, ) -> dict: """Execute a GSAS-II refinement from an in-memory recipe. @@ -135,6 +136,12 @@ def run( ``POWDERLINE_NO_SERVER`` environment variable is truthy (``1``/``true``/``yes``/``on``), ``'auto'`` runs in-process without starting a server and ``'server'`` returns an error result. + server_timeout: seconds to wait for the server's answer to a + submitted job (``'auto'`` / ``'server'``). ``None`` (default) or + ``0``: no limit, as for an in-process run. Past the limit the run + raises ``ExecutionBackendError`` ``timeout`` and never falls back + in-process: the job is still running on the server (one job at a + time), so a second run would double the work. allow_unsupported_engine_version: test-only bypass of the engine version check. Not reachable through ``powderline.run()``. @@ -179,7 +186,7 @@ def run( Raises: pydantic.ValidationError: the recipe fails schema validation. - ValueError: an invalid ``execution_mode``. + ValueError: an invalid ``execution_mode`` or ``server_timeout``. EngineNotAvailableError: GSAS-II is not importable (not for ``validate_only``). EngineVersionError: the installed GSAS-II is outside ``ENGINE_VERSION_SPEC``. EngineExecutionError: the engine ran and failed (``.reason``: ``diverged``, @@ -190,12 +197,13 @@ def run( ``timeout``, ``backend_error``). OSError: ``output_dir`` cannot be created. """ - # 0. Validate execution_mode early to catch typos + # 0. Validate execution_mode and server_timeout early to catch typos if execution_mode not in EXECUTION_MODES: raise ValueError( f"Invalid execution_mode={execution_mode!r}. " f"Must be one of: {', '.join(EXECUTION_MODES)}" ) + server_timeout = _server_timeout_seconds(server_timeout) # 1. The installed engine must be a supported version (skipped for validate_only) if not validate_only: @@ -241,7 +249,7 @@ def run( result['warnings'] = warnings + list(result.get('warnings') or []) # GSASClient adds them on its paths else: from powderline.gateways.gsasii.client import GSASClient - client = GSASClient(fallback_to_subprocess=execution_mode != 'server') + client = GSASClient(fallback_to_subprocess=execution_mode != 'server', request_timeout=server_timeout) result = client.submit_simulation( recipe=recipe, output_dir=output_dir, @@ -253,6 +261,23 @@ def run( return _frames(result, recipe, output_dir) +def _server_timeout_seconds(value) -> float | None: + """The ``server_timeout`` option as seconds for the client: ``None`` for no limit (``None`` or ``0``). + + Raises: + ValueError: not a number, or negative. + """ + if value is None: + return None + try: + seconds = float(value) + except (TypeError, ValueError): + raise ValueError(f"Invalid server_timeout={value!r}: a number of seconds (0 = no limit)") from None + if seconds != seconds or seconds < 0: # NaN or negative + raise ValueError(f"Invalid server_timeout={value!r}: seconds must be >= 0 (0 = no limit)") + return None if seconds == 0 else seconds + + def _frames(result: dict, model=None, output_dir=None) -> dict: """Normalise the structured fields to DataFrames and stamp the ``ok`` envelope fields. diff --git a/src/powderline/kicker.py b/src/powderline/kicker.py index 8c84fde..9978e28 100644 --- a/src/powderline/kicker.py +++ b/src/powderline/kicker.py @@ -3,8 +3,8 @@ :: powderline [--output DIR] [--validate-only] [--verbose] - [--use-server | --no-server] [--topas-dir DIR] [--topas-version V] - [--topas-timeout SECONDS] + [--use-server | --no-server] [--server-timeout SECONDS] + [--topas-dir DIR] [--topas-version V] [--topas-timeout SECONDS] powderline --doctor (what this environment can do: gateways, engines, server; re/27) (``pixi run kicker ...`` / ``python src/powderline/kicker.py ...`` run the same @@ -40,11 +40,12 @@ _FLAG_GATEWAYS = { "use_server": "gsasii", "no_server": "gsasii", + "server_timeout": "gsasii", "topas_dir": "topas", "topas_version": "topas", "topas_timeout": "topas", } -_FLAG_NAMES = {"use_server": "--use-server", "no_server": "--no-server", +_FLAG_NAMES = {"use_server": "--use-server", "no_server": "--no-server", "server_timeout": "--server-timeout", "topas_dir": "--topas-dir", "topas_version": "--topas-version", "topas_timeout": "--topas-timeout"} @@ -102,6 +103,7 @@ def engine_options_from_args(args: argparse.Namespace, gateway_name: str) -> dic ``--no-server`` / ``--use-server`` → gsasii ``execution_mode`` (``'subprocess'`` / ``'server'``; neither → the gateway's default, ``'auto'``); + ``--server-timeout`` → gsasii ``server_timeout``; ``--topas-dir`` / ``--topas-version`` / ``--topas-timeout`` → topas ``topas_dir`` / ``topas_version`` / ``topas_timeout``. @@ -126,6 +128,8 @@ def engine_options_from_args(args: argparse.Namespace, gateway_name: str) -> dic if server_disabled(): raise ValueError(f"--use-server: {NO_SERVER_MESSAGE}") options["execution_mode"] = "server" + if given["server_timeout"] is not None: + options["server_timeout"] = given["server_timeout"] if given["topas_dir"] is not None: options["topas_dir"] = given["topas_dir"] if given["topas_version"] is not None: @@ -146,6 +150,8 @@ def build_parser() -> argparse.ArgumentParser: --use-server: server only (fail if it cannot be started) --no-server: in-process only (skip the server) POWDERLINE_NO_SERVER=1 (env): never use a server; the default mode runs in-process + --server-timeout SECONDS: stop waiting for the server's answer after this long + (default: no limit, as in-process; the job itself keeps running on the server) topas.* --topas-dir DIR / --topas-version V: the TOPAS installation to run (a run needs a declared version: --topas-version or .powderline_config.yaml) --topas-timeout SECONDS: stop tc.exe after this long (default 3600; 0 = no limit) @@ -172,6 +178,9 @@ def build_parser() -> argparse.ArgumentParser: help='gsasii: server mode only (auto-start enabled, fail if still unavailable)') mode_group.add_argument('--no-server', action='store_true', help='gsasii: in-process mode only (skip the server entirely)') + parser.add_argument("--server-timeout", type=float, default=None, metavar="SECONDS", + help="gsasii: stop waiting for the server's answer after this many seconds " + "(default: no limit; 0 = no limit)") parser.add_argument("--topas-dir", type=Path, default=None, help="topas: directory containing tc.exe") parser.add_argument("--topas-version", default=None, help="topas: the installed TOPAS version to run") parser.add_argument("--topas-timeout", type=float, default=None, metavar="SECONDS", diff --git a/tests/test_api.py b/tests/test_api.py index e28fd60..6191bdb 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -257,8 +257,10 @@ def test_submit_to_server_does_not_retry_on_http_status_error( # ─── execution_mode validation tests ───────────────────────────────────────── -def test_run_invalid_execution_mode_raises(recipe_LaB6_dict, tmp_path): +def test_run_invalid_execution_mode_raises(recipe_LaB6_dict, tmp_path, monkeypatch): """run() raises ValueError immediately for an invalid execution_mode.""" + from powderline import api + monkeypatch.setattr(api, "_engine_importable", lambda gateway: None) # without GSAS-II the probe would answer first with pytest.raises(ValueError, match="Invalid execution_mode"): powderline.run( recipe_LaB6_dict, @@ -316,3 +318,66 @@ def test_validate_only_summary_carries_the_resolved_recipe(tmp_path): assert out["schema_name"] == "gsasii.rietveld" and out["metadata"]["powderline_provenance"]["parent_run_id"] is None assert powderline.validate(out).recipe.model_dump(mode="json") == out assert not (tmp_path / "out").exists() + + +# ─── the server request's time limit (PR #13 review) ────────────────────────── + +def _simulate_timeout_of(client, recipe): + """The httpx timeout the client puts on its ``/simulate`` POST (the POST itself is refused).""" + import httpx + with patch.object(GSASClient, "_endpoint", return_value=_FAKE_ENDPOINT), \ + patch("httpx.post", side_effect=httpx.ConnectError("refused")) as mock_post: + with pytest.raises(httpx.ConnectError): + client._submit_to_server(recipe) + return mock_post.call_args.kwargs["timeout"] + + +def test_simulate_request_has_no_read_limit_by_default(recipe_LaB6_dict): + """A refinement takes as long as it takes, as in-process: only the connect/write/pool phases are bounded.""" + from powderline.gateways.gsasii.client import REQUEST_PHASE_TIMEOUT + timeout = _simulate_timeout_of(GSASClient(), recipe_LaB6_dict) + assert timeout.read is None + assert timeout.connect == timeout.write == timeout.pool == REQUEST_PHASE_TIMEOUT + + +def test_simulate_request_read_limit_is_the_request_timeout(recipe_LaB6_dict): + timeout = _simulate_timeout_of(GSASClient(request_timeout=600.0), recipe_LaB6_dict) + assert timeout.read == 600.0 + + +@pytest.mark.parametrize("value,expected", [(None, None), (0, None), (0.0, None), (7200, 7200.0), ("90", 90.0)]) +def test_gateway_server_timeout_option_in_seconds(value, expected): + from powderline.gateways.gsasii.gateway import _server_timeout_seconds + assert _server_timeout_seconds(value) == expected + + +@pytest.mark.parametrize("value", [-1, "soon", float("nan")]) +def test_gateway_refuses_a_bad_server_timeout(recipe_LaB6_dict, tmp_path, value): + """Refused at step 0, before validation and the engine: also with validate_only (engine-free).""" + from powderline.gateways.gsasii import gateway + with pytest.raises(ValueError, match="Invalid server_timeout"): + gateway.run(recipe_LaB6_dict, tmp_path / "out", validate_only=True, server_timeout=value) + + +def test_gateway_hands_server_timeout_to_the_client(recipe_LaB6_dict, tmp_path, monkeypatch): + """The option reaches ``GSASClient(request_timeout=...)``; engine-free: the version check and the client are stubbed.""" + from powderline.exceptions import ExecutionBackendError + from powderline.gateways.gsasii import client as client_module, gateway + from powderline.results import failure_envelope + seen = {} + + class FakeClient: + def __init__(self, fallback_to_subprocess=True, request_timeout=None): + seen.update(fallback=fallback_to_subprocess, request_timeout=request_timeout) + + def submit_simulation(self, **kwargs): + return failure_envelope("backend", "server_unavailable", "stub", method="none") + monkeypatch.setattr(gateway, "check_engine_version", lambda **kw: None) + monkeypatch.setattr(gateway, "installed_engine_version", lambda: "5.7.9") + monkeypatch.setattr(client_module, "GSASClient", FakeClient) + with pytest.raises(ExecutionBackendError): + gateway.run(recipe_LaB6_dict, tmp_path / "out", execution_mode="server", server_timeout=1800) + assert seen == {"fallback": False, "request_timeout": 1800.0} + with pytest.raises(ExecutionBackendError): + gateway.run(recipe_LaB6_dict, tmp_path / "out", execution_mode="auto") + assert seen == {"fallback": True, "request_timeout": None} diff --git a/tests/test_cli.py b/tests/test_cli.py index 676145a..9a2e720 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -123,6 +123,10 @@ def test_engine_options_default_is_empty(): def test_engine_options_gsasii_server_flags(): assert kicker.engine_options_from_args(_args(no_server=True), "gsasii") == {"execution_mode": "subprocess"} assert kicker.engine_options_from_args(_args(use_server=True), "gsasii") == {"execution_mode": "server"} + parsed = kicker.build_parser().parse_args([str(LAB6), "--use-server", "--server-timeout", "0"]) # 0 = no limit + assert kicker.engine_options_from_args(parsed, "gsasii") == {"execution_mode": "server", "server_timeout": 0.0} + parsed = kicker.build_parser().parse_args([str(LAB6), "--server-timeout", "7200"]) + assert kicker.engine_options_from_args(parsed, "gsasii") == {"server_timeout": 7200.0} def test_engine_options_topas_flags(): @@ -136,6 +140,7 @@ def test_engine_options_topas_flags(): ({"no_server": True}, "topas"), ({"use_server": True}, "easydiffraction"), ({"topas_dir": Path("/t")}, "gsasii"), ({"topas_version": "6"}, "gsasii"), ({"topas_timeout": 0.0}, "gsasii"), ({"topas_timeout": 600.0}, "easydiffraction"), + ({"server_timeout": 0.0}, "topas"), ({"server_timeout": 60.0}, "easydiffraction"), ]) def test_engine_options_flag_for_another_engine_is_an_error(flag, gateway): with pytest.raises(ValueError, match="applies to"): diff --git a/tests/test_failed_run_artefacts.py b/tests/test_failed_run_artefacts.py index 197dd14..a47fe03 100644 --- a/tests/test_failed_run_artefacts.py +++ b/tests/test_failed_run_artefacts.py @@ -168,3 +168,57 @@ def run(recipe, output_dir, **kwargs): powderline.run(RECIPE, out) prov = json.loads((out / "failure.json").read_text(encoding="utf-8"))[roundtrip.PROVENANCE_KEY] assert prov["engine"] == "fake" and prov["engine_version"] == "9.1" + + +# ─── nothing on disk changes until the run can start (PR #13 review) ─────────── + +def test_an_invalid_recipe_leaves_the_previous_results_in_place(tmp_path): + """An invalid recipe raises before the directory is touched: a typo must not cost the previous run's tables.""" + from pydantic import ValidationError + + def validate(recipe, **opts): + raise ValidationError.from_exception_data("Fake", [{"type": "missing", "loc": ("payload", "phases"), "input": {}}]) + registry.register_gateway("fakeinvalid", lambda: registry.Gateway( + name="fakeinvalid", capabilities=lambda: {"name": "fakeinvalid", "workflows": ["fakeinvalid.rietveld"]}, + validate=validate, run=lambda *a, **k: pytest.fail("an invalid recipe must not reach run()"))) + try: + out = tmp_path / "out" + _seed(out) + with pytest.raises(ValidationError): + powderline.run({**RECIPE, "schema_name": "fakeinvalid.rietveld"}, out) + assert (out / "refined_parameters.csv").read_text(encoding="utf-8") == "stale\n" + assert (out / "output_recipe.json").read_text(encoding="utf-8") == "stale\n" + assert (out / "failure.json").read_text(encoding="utf-8") == "stale\n" # no failure record written either + finally: + registry.unregister_gateway("fakeinvalid") + registry._instances.pop("fakeinvalid", None) + + +def test_a_missing_engine_leaves_the_previous_results_in_place(fake, tmp_path, monkeypatch): + """A run in an environment without the engine raises before the directory is touched.""" + from powderline import api + from powderline.exceptions import EngineNotAvailableError + + def probe(gateway): + raise EngineNotAvailableError(gateway=gateway.name, dependency="Fake", env="fake", install_command="pixi install -e fake") + monkeypatch.setattr(api, "_engine_importable", probe) + fake(lambda recipe, output_dir, **kwargs: pytest.fail("a missing engine must not reach run()")) + out = tmp_path / "out" + _seed(out) + with pytest.raises(EngineNotAvailableError): + powderline.run(RECIPE, out) + assert (out / "refined_parameters.csv").read_text(encoding="utf-8") == "stale\n" + + +def test_engine_probe_reports_a_gsasii_engine_that_is_not_importable(monkeypatch): + """The probe is the ``installed_engine_version`` of the module defining the gateway's run(); a gateway whose + module has none (TOPAS, a registered replacement) is left to its own run().""" + import sys + from powderline import api + from powderline.exceptions import EngineNotAvailableError + + monkeypatch.setitem(sys.modules, "GSASII", None) # ``import GSASII`` raises ImportError, whatever is installed + with pytest.raises(EngineNotAvailableError): + api._engine_importable(registry.get("gsasii")) + assert api._engine_importable(registry.get("topas")) is None # no Python engine + assert api._engine_importable(_gateway("gsasii", lambda *a, **k: None)) is None # a replacement under the real name