Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <recipe.json> [--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.
Expand Down Expand Up @@ -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 `<base>.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`.
Expand Down
9 changes: 7 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ pixi run -e gsasii doctor # wha
After `pixi reinstall powderline` the same program is the installed command
`powderline <recipe.json> …`. 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.

Expand Down
3 changes: 2 additions & 1 deletion docs/TROUBLESHOOTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ Command line
.. py:module:: powderline.kicker

``powderline <recipe.json> [--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
Expand Down
3 changes: 2 additions & 1 deletion docs/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ Enable verbose output::
After ``pixi reinstall powderline`` the same program is available as the
installed command ``powderline <recipe.json> ...``. 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
Expand Down
2 changes: 1 addition & 1 deletion docs/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 36 additions & 3 deletions src/powderline/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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", ""))
Expand Down
22 changes: 19 additions & 3 deletions src/powderline/gateways/gsasii/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand All @@ -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:
Expand Down
31 changes: 28 additions & 3 deletions src/powderline/gateways/gsasii/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()``.

Expand Down Expand Up @@ -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``,
Expand All @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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.

Expand Down
Loading