diff --git a/README.md b/README.md index bd19ff0b..d57518a3 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Follow the shortcuts in the following table to the individual demos. | Name | First Demo | Description | | --- | --- | --- | | [2023-ecp-f2f](demos/2023-ecp-f2f/README.md) | ELIXIR Compute Face-to-Face, Helsinki, Feb 7-8, 2023 | Task execution via the [Task Execution Service (TES) API](https://github.com/ga4gh/task-execution-schemas/) on Kubernetes and HPC; TES-based task distribution with random and distance-based task distribution logic; execution of a CWL workflow via the `cwl-tes` TES backend | +| [federated-analytics](demos/federated-analytics/README.md) | Not yet given | The same analysis at two Nodes via TES tasks, optionally through the proTES gateway; only aggregates leave the Nodes and are combined into the result of the whole data set | ## Test data diff --git a/demos/federated-analytics/README.md b/demos/federated-analytics/README.md new file mode 100644 index 00000000..7cc06b93 --- /dev/null +++ b/demos/federated-analytics/README.md @@ -0,0 +1,104 @@ +# Demonstrator federated-analytics + +Runs the same analysis at two Nodes through GA4GH TES, optionally through the +proTES gateway, and combines the results. Only aggregates leave the Nodes, +never the rows. + +> [!IMPORTANT] +> The demo uses the synthetic test data of [`data/`](../../data/README.md). +> Never run it on real, personal or other sensitive data. + +## How it works + +1. The data set `synthetic-growth` has one partition per Node (`node-a`, + `node-b`). [`data/manifest.json`](../../data/manifest.json) lists their + URLs. +2. For each partition, [`federated_analytics.py`](federated_analytics.py) + sends one TES task. The task downloads the partition and runs + [`local_stats.py`](local_stats.py) in a `python:3.13-slim` container. The + script prints the count, sum and sum of squares of each value column per + condition, as JSON. +3. The client reads that output from the task logs (`view=FULL`, standard + output of the executor), so no object store is needed for outputs. +4. The client combines the aggregates into the mean and standard deviation per + condition, and Welch's t statistic of `treated` against `control`. The + result is exactly the one of all rows in one place; the tests check this. + +## Quick start (no services) + +From a fresh clone, with Python 3.12 or later: + +```sh +python demos/federated-analytics/federated_analytics.py --local +``` + +`--local` runs `local_stats.py` on the local copies of the partitions instead +of in TES tasks. It works if the output ends like this: + +```text +Welch's t (treated vs control), od600: 13.81 +Welch's t (treated vs control), expression: 8.48 +``` + +Add `--json` for machine-readable output. CI runs this quick start on every +change. + +## Run against TES services + +Through one proTES gateway (all tasks to the gateway, which routes them to its +TES instances): + +```sh +export TES_TOKEN= +python demos/federated-analytics/federated_analytics.py --tes https://protes.example.org +``` + +With one TES service per partition (in the order of the manifest: `node-a`, +then `node-b`): + +```sh +python demos/federated-analytics/federated_analytics.py \ + --tes https://tes.node-a.example.org \ + --tes https://tes.node-b.example.org +``` + +| Option or variable | Meaning | +| --- | --- | +| `--tes URL` | Base URL of a TES service or gateway, without `/ga4gh/tes/v1`. Give it once (all tasks go there) or once per partition (in the order of the manifest); other counts are an error. | +| `TES_TOKEN` | Access token, sent as bearer token if set. proTES 0.3.0 and later need one, from an identity provider the gateway accepts (see [Access control](https://protes.readthedocs.io/en/latest/access-control/)). | +| `--image` | Container image with Python 3 for the tasks (default: `python:3.13-slim`). | +| `--manifest` | Manifest of the partitions (default: `data/manifest.json`). | +| `--poll` | Seconds between status requests (default: 5). | +| `--timeout` | Seconds to wait for each task, requests included (default: 1800). | + +If a request or a task fails, the demo prints the error (with a hint for HTTP +401 and 403) and exits with code 1. It then asks the services to cancel the +tasks it has sent. + +The demo sends `TES_TOKEN` only over HTTPS (plain HTTP only to `localhost`) +and refuses redirects, so that the token never goes to another origin. If a +partition has invalid data, `local_stats.py` names the row number and column +only, never values, so that no data leave the Node through the task logs. + +The services need: + +- to download the partitions from `raw.githubusercontent.com`, or copies of + them at URLs they can reach (edit a copy of the manifest and pass it with + `--manifest`); +- to accept inputs with `content` (TES 1.1), for the script; +- to report the standard output of executors in the task logs. + +proTES routes each task to one of its TES instances at random, unless its +operator enables [routing by distance to the +data](https://protes.readthedocs.io/en/latest/plugins/#routing-by-distance-to-the-data-opt-in). +For the federated case, where each partition stays at its Node, place each +partition at its Node and enable that routing, or send each partition to its +Node's TES service directly. + +## What has been run + +- The quick start (`--local`) and the TES client against an in-memory fake TES + service, in the tests of this repository. +- **Not run:** against a deployed TES service or proTES gateway with access + tokens. Please report results in the + [issues](https://github.com/elixir-cloud-aai/elixir-cloud-demos/issues). diff --git a/demos/federated-analytics/federated_analytics.py b/demos/federated-analytics/federated_analytics.py new file mode 100644 index 00000000..85db2500 --- /dev/null +++ b/demos/federated-analytics/federated_analytics.py @@ -0,0 +1,530 @@ +#!/usr/bin/env python3 +"""Run the same analysis at several Nodes and combine the results. + +For each partition of the test data set, the client sends a GA4GH TES task +that runs ``local_stats.py`` on that partition and prints aggregates (count, +sum and sum of squares). The client reads them from the task logs and +combines them into the statistics of the whole data set: mean and standard +deviation per condition, and Welch's t statistic of treated against control. +The rows never leave the Nodes; the result is the same as if all rows were in +one place. + +Send all tasks to one proTES gateway (``--tes https://protes.example.org``), +or each partition to a TES service of its own (one ``--tes`` per partition). +With ``--local``, the client runs ``local_stats.py`` on the local copies of +the partitions instead, without any service. +""" + +import argparse +import json +import math +import os +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any + +from local_stats import GROUP_COLUMN, VALUE_COLUMNS, Stats + +HERE = Path(__file__).resolve().parent +DATA_DIR = HERE.parents[1] / "data" +DATASET = "synthetic-growth" +SCRIPT = HERE / "local_stats.py" +DEFAULT_IMAGE = "python:3.13-slim" +TES_PATH = "/ga4gh/tes/v1/tasks" +TERMINAL_STATES = {"COMPLETE", "EXECUTOR_ERROR", "SYSTEM_ERROR", "CANCELED"} +CONTROL, TREATED = "control", "treated" + +# Sends a request and returns the decoded JSON response. +Transport = Callable[[urllib.request.Request], Any] + + +class TaskError(RuntimeError): + """A TES task failed or its output could not be read.""" + + +def load_partitions(manifest: Path, dataset: str = DATASET) -> list[dict[str, Any]]: + """Read the partitions of a data set from the manifest. + + Args: + manifest: Path of ``manifest.json``. + dataset: Name of the data set. + + Returns: + The file entries of the data set, one per partition. + + Raises: + KeyError: If the manifest has no such data set. + """ + data = json.loads(manifest.read_text()) + for entry in data["datasets"]: + if entry["name"] == dataset: + return list(entry["files"]) + raise KeyError(f"data set {dataset!r} not in {manifest}") + + +def combine(partials: Sequence[Stats]) -> dict[str, dict[str, dict[str, float]]]: + """Combine the aggregates of several partitions. + + Args: + partials: Aggregates of each partition, as ``local_stats.summarise`` + returns them. + + Returns: + ``{condition: {column: {"n", "mean", "sd"}}}`` over all partitions; + ``sd`` is the sample standard deviation (``nan`` for one value). + """ + totals: Stats = {} + for partial in partials: + for group, columns in partial.items(): + for col, agg in columns.items(): + total = totals.setdefault(group, {}).setdefault( + col, {"n": 0.0, "sum": 0.0, "sumsq": 0.0} + ) + for key in ("n", "sum", "sumsq"): + total[key] += agg[key] + result: dict[str, dict[str, dict[str, float]]] = {} + for group, columns in totals.items(): + for col, agg in columns.items(): + n = agg["n"] + mean = agg["sum"] / n + var = ( + max(0.0, (agg["sumsq"] - n * mean * mean) / (n - 1)) + if n > 1 + else math.nan + ) + result.setdefault(group, {})[col] = { + "n": n, + "mean": mean, + "sd": math.sqrt(var), + } + return result + + +def welch_t(a: dict[str, float], b: dict[str, float]) -> float: + """Compute Welch's t statistic of ``b`` against ``a``. + + Args: + a: ``n``, ``mean`` and ``sd`` of the first group. + b: ``n``, ``mean`` and ``sd`` of the second group. + + Returns: + The t statistic; ``nan`` if it is undefined. + """ + se = math.sqrt(a["sd"] ** 2 / a["n"] + b["sd"] ** 2 / b["n"]) + if se == 0 or math.isnan(se): + return math.nan + return (b["mean"] - a["mean"]) / se + + +def run_local(partitions: Sequence[dict[str, Any]], data_dir: Path) -> list[Stats]: + """Run ``local_stats.py`` on the local copies of the partitions. + + Args: + partitions: File entries of the manifest. + data_dir: Directory that holds the files under their ``path``. + + Returns: + The aggregates of each partition. + """ + partials = [] + for part in partitions: + out = subprocess.run( # noqa: S603 - fixed script, paths from manifest + [sys.executable, str(SCRIPT), str(data_dir / part["path"])], + check=True, + capture_output=True, + text=True, + ) + partials.append(json.loads(out.stdout)) + return partials + + +def make_task(part: dict[str, Any], script: str, image: str) -> dict[str, Any]: + """Build the TES task for one partition. + + Args: + part: File entry of the manifest. + script: Source code of ``local_stats.py``. + image: Container image with Python 3. + + Returns: + The task, as the TES API expects it. + """ + return { + "name": f"federated-analytics-{part['node']}", + "description": "Summary statistics of one partition (elixir-cloud-demos)", + "inputs": [ + {"url": part["url"], "path": "/data/input.csv", "type": "FILE"}, + {"content": script, "path": "/data/local_stats.py", "type": "FILE"}, + ], + "executors": [ + { + "image": image, + "command": ["python3", "/data/local_stats.py", "/data/input.csv"], + } + ], + } + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse redirects, so that tokens never go to another origin.""" + + def redirect_request( + self, + req: urllib.request.Request, + fp: Any, + code: int, + msg: str, + headers: Any, + newurl: str, + ) -> urllib.request.Request | None: + """Refuse to follow a redirect. + + Args: + req: The original request. + fp: The response body. + code: The HTTP status code. + msg: The HTTP reason phrase. + headers: The response headers. + newurl: The target of the redirect. + + Raises: + urllib.error.HTTPError: Always. + """ + raise urllib.error.HTTPError( + req.full_url, code, f"refused redirect to {newurl}", headers, fp + ) + + +_OPENER = urllib.request.build_opener(NoRedirect) + + +def _http(request: urllib.request.Request) -> Any: # pragma: no cover + """Send a request and decode the JSON response. + + Args: + request: The request. + + Returns: + The decoded response body. + """ + with _OPENER.open(request, timeout=60) as response: + return json.load(response) + + +class TesClient: + """Minimal client of the GA4GH TES API. + + Args: + base_url: Base URL of the service, without ``/ga4gh/tes/v1``. + token: Access token, sent as bearer token if given. + transport: Function that sends requests; for tests. + """ + + def __init__( + self, base_url: str, token: str | None = None, transport: Transport = _http + ) -> None: + """Initialise the client. + + Raises: + ValueError: If a token would go over plain HTTP to a host other + than localhost. + """ + parsed = urllib.parse.urlsplit(base_url) + if ( + token + and parsed.scheme != "https" + and parsed.hostname not in ("localhost", "127.0.0.1", "::1") + ): + raise ValueError(f"refusing to send a token to {base_url}: use HTTPS") + self.url = base_url.rstrip("/") + TES_PATH + self.token = token + self.transport = transport + + def _request(self, url: str, body: dict[str, Any] | None = None) -> Any: + """Send a GET request, or a POST request if there is a body. + + Args: + url: URL to send to. + body: JSON body of a POST request. + + Returns: + The decoded response body. + + Raises: + TaskError: If the request fails. + """ + headers = {"Accept": "application/json"} + data = None + if body is not None: + headers["Content-Type"] = "application/json" + data = json.dumps(body).encode() + if self.token: + headers["Authorization"] = f"Bearer {self.token}" + request = urllib.request.Request(url, data=data, headers=headers) + try: + return self.transport(request) + except urllib.error.HTTPError as exc: + hint = " (is TES_TOKEN set and valid?)" if exc.code in (401, 403) else "" + raise TaskError(f"{url}: HTTP {exc.code} {exc.reason}{hint}") from exc + except urllib.error.URLError as exc: + raise TaskError(f"{url}: {exc.reason}") from exc + except (OSError, ValueError) as exc: + raise TaskError(f"{url}: {exc}") from exc + + def submit(self, task: dict[str, Any]) -> str: + """Create a task. + + Args: + task: The task. + + Returns: + The ID of the task. + + Raises: + TaskError: If the response has no task ID. + """ + response = self._request(self.url, task) + if not isinstance(response, dict) or "id" not in response: + raise TaskError(f"{self.url}: malformed response, no task ID") + return str(response["id"]) + + def cancel(self, task_id: str) -> None: + """Cancel a task, as far as possible; errors are ignored. + + Args: + task_id: ID of the task. + """ + try: + self._request(f"{self.url}/{task_id}:cancel", {}) + except TaskError: + pass + + def wait( + self, + task_id: str, + poll: float = 5.0, + timeout: float = 1800.0, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + ) -> str: + """Wait for a task to end and return the output of its executor. + + Args: + task_id: ID of the task. + poll: Seconds between status requests. + timeout: Seconds to wait at most for this task, requests included. + sleep: Function to wait with; for tests. + clock: Monotonic clock in seconds; for tests. + + Returns: + The standard output of the last executor. + + Raises: + TaskError: If the task doesn't complete in time, fails, or has no + output in its logs. + """ + deadline = clock() + timeout + while True: + task = self._request(f"{self.url}/{task_id}?view=FULL") + if not isinstance(task, dict): + raise TaskError(f"task {task_id}: malformed response") + state = task.get("state", "UNKNOWN") + if state in TERMINAL_STATES: + break + if clock() >= deadline: + raise TaskError(f"task {task_id} still {state} after {timeout}s") + sleep(poll) + if state != "COMPLETE": + raise TaskError(f"task {task_id} ended in state {state}") + try: + return str(task["logs"][-1]["logs"][-1]["stdout"]) + except (KeyError, IndexError, TypeError) as exc: + raise TaskError(f"task {task_id} has no executor output") from exc + + +def run_tes( + partitions: Sequence[dict[str, Any]], + clients: Sequence[TesClient], + image: str = DEFAULT_IMAGE, + **wait_kwargs: Any, +) -> list[Stats]: + """Run ``local_stats.py`` as one TES task per partition. + + Partitions go to the clients in turn: with one client (a gateway), all + tasks go there; with one client per partition, each gets its own. + + Args: + partitions: File entries of the manifest. + clients: TES clients. + image: Container image with Python 3. + **wait_kwargs: Passed on to ``TesClient.wait``. + + Returns: + The aggregates of each partition. + + Raises: + TaskError: If a task can't be sent or fails; the tasks sent so far + are then cancelled. + """ + script = SCRIPT.read_text() + submitted: list[tuple[TesClient, str]] = [] + partials = [] + try: + for idx, part in enumerate(partitions): + client = clients[idx % len(clients)] + task_id = client.submit(make_task(part, script, image)) + print( + f"Submitted {part['node']} to {client.url}: {task_id}", + file=sys.stderr, + ) + submitted.append((client, task_id)) + for client, task_id in submitted: + stdout = client.wait(task_id, **wait_kwargs) + try: + partials.append(json.loads(stdout.strip().splitlines()[-1])) + except (IndexError, json.JSONDecodeError) as exc: + raise TaskError(f"task {task_id} printed no JSON") from exc + except TaskError: + for client, task_id in submitted: + client.cancel(task_id) + raise + return partials + + +def to_json(result: dict[str, dict[str, dict[str, float]]]) -> str: + """Serialise the combined statistics as strict JSON. + + Args: + result: Output of ``combine``. + + Returns: + JSON, with ``null`` for undefined values such as the standard + deviation of a single value. + """ + clean = { + group: { + col: {k: (None if math.isnan(v) else v) for k, v in agg.items()} + for col, agg in columns.items() + } + for group, columns in result.items() + } + return json.dumps(clean, indent=2, sort_keys=True, allow_nan=False) + + +def report(result: dict[str, dict[str, dict[str, float]]]) -> str: + """Format the combined statistics as a table. + + Args: + result: Output of ``combine``. + + Returns: + The table, one line per condition and column, then Welch's t. + """ + lines = [f"{GROUP_COLUMN:<10} {'column':<11} {'n':>4} {'mean':>8} {'sd':>8}"] + for group in sorted(result): + for col in VALUE_COLUMNS: + agg = result[group][col] + lines.append( + f"{group:<10} {col:<11} {agg['n']:>4.0f} " + f"{agg['mean']:>8.3f} {agg['sd']:>8.3f}" + ) + if CONTROL in result and TREATED in result: + for col in VALUE_COLUMNS: + t = welch_t(result[CONTROL][col], result[TREATED][col]) + lines.append(f"Welch's t ({TREATED} vs {CONTROL}), {col}: {t:.2f}") + return "\n".join(lines) + + +def _positive(value: str) -> float: + """Parse a positive number of seconds. + + Args: + value: Command line value. + + Returns: + The number. + + Raises: + argparse.ArgumentTypeError: If the value is not a positive number. + """ + try: + number = float(value) + except ValueError: + number = 0.0 + if not (number > 0 and math.isfinite(number)): + raise argparse.ArgumentTypeError(f"not a positive number: {value!r}") + return number + + +def main(argv: Sequence[str] | None = None, transport: Transport = _http) -> int: + """Run the demo from the command line. + + Args: + argv: Command line arguments; ``sys.argv[1:]`` if not given. + transport: Function that sends requests to TES; for tests. + + Returns: + The exit code. + """ + parser = argparse.ArgumentParser(description="Federated analytics demo.") + where = parser.add_mutually_exclusive_group(required=True) + where.add_argument( + "--local", action="store_true", help="run locally, without services" + ) + where.add_argument( + "--tes", + action="append", + metavar="URL", + help="base URL of a TES service or gateway; repeat for one per partition", + ) + parser.add_argument("--manifest", type=Path, default=DATA_DIR / "manifest.json") + parser.add_argument("--image", default=DEFAULT_IMAGE) + parser.add_argument("--json", action="store_true", help="print JSON") + parser.add_argument( + "--poll", type=_positive, default=5.0, help="seconds between status requests" + ) + parser.add_argument( + "--timeout", type=_positive, default=1800.0, help="seconds to wait per task" + ) + args = parser.parse_args(argv) + + partitions = load_partitions(args.manifest) + if args.local: + partials = run_local(partitions, args.manifest.parent) + else: + if len(args.tes) not in (1, len(partitions)): + parser.error( + f"give --tes once (gateway) or {len(partitions)} times " + "(one per partition)" + ) + token = os.environ.get("TES_TOKEN") or None + try: + clients = [ + TesClient(url, token=token, transport=transport) for url in args.tes + ] + except ValueError as exc: + parser.error(str(exc)) + try: + partials = run_tes( + partitions, + clients, + image=args.image, + poll=args.poll, + timeout=args.timeout, + ) + except TaskError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + result = combine(partials) + print(to_json(result) if args.json else report(result)) + return 0 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/demos/federated-analytics/local_stats.py b/demos/federated-analytics/local_stats.py new file mode 100644 index 00000000..1292e6e0 --- /dev/null +++ b/demos/federated-analytics/local_stats.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Compute summary statistics of one Node's partition. + +This script runs at each Node, inside a TES task (or locally with +``--local`` of ``federated_analytics.py``). It reads a CSV file with a +``condition`` column and numeric columns, and prints, as JSON, the count, sum +and sum of squares of each numeric column per condition. Only these +aggregates leave the Node, never the rows. + +It needs only the Python standard library, so that any Python image can run +it. +""" + +import csv +import json +import math +import sys +from collections.abc import Iterable, Sequence +from pathlib import Path + +VALUE_COLUMNS = ("od600", "expression") +GROUP_COLUMN = "condition" + +Stats = dict[str, dict[str, dict[str, float]]] + + +def summarise(rows: Iterable[dict[str, str]]) -> Stats: + """Compute count, sum and sum of squares per condition and column. + + Args: + rows: Rows with a ``condition`` column and the columns of + ``VALUE_COLUMNS``. + + Returns: + Aggregates as ``{condition: {column: {"n", "sum", "sumsq"}}}``. + + Raises: + ValueError: If there are no rows, or a row lacks a column or has a + value that is not a finite number. The message names the row + number and column only, never values, so that no data leave the + Node through error logs. + """ + stats: Stats = {} + for number, row in enumerate(rows, start=1): + group = row.get(GROUP_COLUMN) + if group is None: + raise ValueError(f"row {number}: missing column {GROUP_COLUMN!r}") + values = {} + for col in VALUE_COLUMNS: + try: + value = float(row[col]) + except (KeyError, TypeError, ValueError): + value = math.nan + if not math.isfinite(value): + raise ValueError( + f"row {number}: column {col!r} is not a finite number" + ) from None + values[col] = value + per_group = stats.setdefault(group, {}) + for col, value in values.items(): + agg = per_group.setdefault(col, {"n": 0.0, "sum": 0.0, "sumsq": 0.0}) + agg["n"] += 1 + agg["sum"] += value + agg["sumsq"] += value * value + if not stats: + raise ValueError("partition has no rows") + return stats + + +def main(argv: Sequence[str] | None = None) -> int: + """Print the aggregates of a CSV file as JSON. + + Args: + argv: Command line arguments (the path of the CSV file); + ``sys.argv[1:]`` if not given. + + Returns: + The exit code. + """ + args = list(sys.argv[1:] if argv is None else argv) + if len(args) != 1: + print("usage: local_stats.py ", file=sys.stderr) + return 2 + try: + with Path(args[0]).open(newline="") as handle: + stats = summarise(csv.DictReader(handle)) + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + print(json.dumps(stats, sort_keys=True)) + return 0 + + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml index 0174ad7a..857686c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,23 +19,25 @@ dev = [ package = false [tool.pytest.ini_options] -pythonpath = ["scripts"] +pythonpath = ["scripts", "demos/federated-analytics"] testpaths = ["tests"] -addopts = "--cov=scripts --cov-report=term-missing --cov-fail-under=100" +addopts = "--cov=scripts --cov=demos/federated-analytics --cov-report=term-missing --cov-fail-under=100" [tool.ruff] extend-exclude = ["demos/2023-ecp-f2f"] [tool.ruff.lint] select = ["E", "F", "I", "B", "UP", "D", "ANN"] +# JSON documents of the TES API are typed as Any +per-file-ignores = { "demos/federated-analytics/*" = ["ANN401"], "tests/test_federated_analytics.py" = ["ANN401"] } [tool.ruff.lint.isort] -known-first-party = ["generate_test_data"] +known-first-party = ["generate_test_data", "federated_analytics", "local_stats"] [tool.ruff.lint.pydocstyle] convention = "google" [tool.mypy] strict = true -files = ["scripts", "tests"] -mypy_path = "scripts" +files = ["scripts", "demos/federated-analytics", "tests"] +mypy_path = ["scripts", "demos/federated-analytics"] diff --git a/tests/test_federated_analytics.py b/tests/test_federated_analytics.py new file mode 100644 index 00000000..55e46f2a --- /dev/null +++ b/tests/test_federated_analytics.py @@ -0,0 +1,456 @@ +"""Tests for the federated analytics demo.""" + +import csv +import json +import math +import statistics +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any, cast + +import pytest + +import federated_analytics as fa +import local_stats + +REPO_ROOT = Path(__file__).resolve().parents[1] +MANIFEST = REPO_ROOT / "data" / "manifest.json" +DEMO = REPO_ROOT / "demos" / "federated-analytics" / "federated_analytics.py" + + +def _all_rows() -> list[dict[str, str]]: + """Read the rows of all partitions, as if they were in one place.""" + rows: list[dict[str, str]] = [] + for part in fa.load_partitions(MANIFEST): + with (MANIFEST.parent / part["path"]).open(newline="") as handle: + rows.extend(csv.DictReader(handle)) + return rows + + +class FakeTes: + """In-memory TES service that runs ``local_stats`` on submitted tasks.""" + + def __init__( + self, states: list[str] | None = None, stdout: str | None = None + ) -> None: + """Set the states to report before the final one, and the output.""" + self.states = list(states or []) + self.stdout = stdout + self.tasks: dict[str, dict[str, Any]] = {} + self.requests: list[urllib.request.Request] = [] + + def __call__(self, request: urllib.request.Request) -> Any: + """Answer a request like a TES service.""" + self.requests.append(request) + if request.full_url.endswith(":cancel"): + return {} + if request.data is not None: + task = json.loads(cast(bytes, request.data)) + task_id = f"task-{len(self.tasks) + 1}" + self.tasks[task_id] = task + return {"id": task_id} + task_id = request.full_url.rsplit("/", 1)[1].split("?")[0] + if self.states: + return {"id": task_id, "state": self.states.pop(0)} + task = self.tasks[task_id] + if self.stdout is None: + url = task["inputs"][0]["url"] + part = next(p for p in fa.load_partitions(MANIFEST) if p["url"] == url) + with (MANIFEST.parent / part["path"]).open(newline="") as handle: + stdout = json.dumps(local_stats.summarise(csv.DictReader(handle))) + else: + stdout = self.stdout + return { + "id": task_id, + "state": "COMPLETE", + "logs": [{"logs": [{"stdout": stdout + "\n"}]}], + } + + +def test_summarise_counts_sums_and_squares() -> None: + """The aggregates of a partition are count, sum and sum of squares.""" + rows = [ + {"condition": "a", "od600": "1", "expression": "2"}, + {"condition": "a", "od600": "3", "expression": "4"}, + ] + stats = local_stats.summarise(rows) + assert stats["a"]["od600"] == {"n": 2, "sum": 4, "sumsq": 10} + assert stats["a"]["expression"] == {"n": 2, "sum": 6, "sumsq": 20} + + +@pytest.mark.parametrize( + "row", + [ + {"condition": "a", "od600": "x", "expression": "1"}, + {"condition": "a", "od600": "1"}, + {"od600": "1", "expression": "1"}, + ], +) +def test_summarise_rejects_invalid_rows(row: dict[str, str]) -> None: + """Rows with missing or non-numeric values are errors.""" + with pytest.raises(ValueError): + local_stats.summarise([row]) + + +def test_local_stats_main_prints_json(capsys: pytest.CaptureFixture[str]) -> None: + """The script prints the aggregates of a file as JSON.""" + part = fa.load_partitions(MANIFEST)[0] + assert local_stats.main([str(MANIFEST.parent / part["path"])]) == 0 + stats = json.loads(capsys.readouterr().out) + assert stats["control"]["od600"]["n"] == 25 + + +def test_local_stats_main_needs_one_argument() -> None: + """Without exactly one file, the script exits with a usage error.""" + assert local_stats.main([]) == 2 + + +def test_federated_result_equals_pooled_result() -> None: + """Combining partition aggregates gives the statistics of all rows.""" + partials = fa.run_local(fa.load_partitions(MANIFEST), MANIFEST.parent) + result = fa.combine(partials) + rows = _all_rows() + for group in local_stats.summarise(rows): + for col in local_stats.VALUE_COLUMNS: + values = [float(r[col]) for r in rows if r["condition"] == group] + assert result[group][col]["n"] == len(values) + assert result[group][col]["mean"] == pytest.approx(statistics.fmean(values)) + assert result[group][col]["sd"] == pytest.approx(statistics.stdev(values)) + + +def test_combine_single_value_has_undefined_sd() -> None: + """The standard deviation of one value is not a number.""" + result = fa.combine([{"a": {"x": {"n": 1, "sum": 2, "sumsq": 4}}}]) + assert result["a"]["x"]["mean"] == 2 + assert math.isnan(result["a"]["x"]["sd"]) + + +def test_welch_t() -> None: + """Welch's t is the mean difference over its standard error.""" + a = {"n": 4.0, "mean": 1.0, "sd": 2.0} + b = {"n": 4.0, "mean": 3.0, "sd": 2.0} + assert fa.welch_t(a, b) == pytest.approx(2 / math.sqrt(2)) + assert math.isnan(fa.welch_t(a | {"sd": 0.0}, b | {"sd": 0.0})) + + +def test_load_partitions_unknown_dataset() -> None: + """Asking for a data set that isn't in the manifest is an error.""" + with pytest.raises(KeyError): + fa.load_partitions(MANIFEST, dataset="nope") + + +def test_make_task_runs_script_on_partition() -> None: + """The task downloads the partition and runs the script on it.""" + part = fa.load_partitions(MANIFEST)[0] + task = fa.make_task(part, "print(1)", "img") + assert task["inputs"][0]["url"] == part["url"] + assert task["inputs"][1]["content"] == "print(1)" + assert task["executors"][0]["image"] == "img" + + +def test_run_tes_through_gateway_equals_local() -> None: + """Through one gateway, the result is the same as locally.""" + partitions = fa.load_partitions(MANIFEST) + fake = FakeTes(states=["QUEUED", "RUNNING"]) + client = fa.TesClient("https://gw.example.org/", token="t", transport=fake) + partials = fa.run_tes(partitions, [client], sleep=lambda _: None) + assert partials == fa.run_local(partitions, MANIFEST.parent) + assert len(fake.tasks) == len(partitions) + first = fake.requests[0] + assert first.full_url == "https://gw.example.org/ga4gh/tes/v1/tasks" + assert first.get_header("Authorization") == "Bearer t" + + +def test_run_tes_one_service_per_partition() -> None: + """With one service per partition, each gets one task.""" + partitions = fa.load_partitions(MANIFEST) + fakes = [FakeTes() for _ in partitions] + clients = [ + fa.TesClient(f"https://tes{i}.example.org", transport=f) + for i, f in enumerate(fakes) + ] + fa.run_tes(partitions, clients) + assert [len(f.tasks) for f in fakes] == [1] * len(partitions) + assert fakes[0].requests[0].get_header("Authorization") is None + + +@pytest.mark.parametrize("state", ["EXECUTOR_ERROR", "SYSTEM_ERROR", "CANCELED"]) +def test_wait_raises_on_failed_task(state: str) -> None: + """A task that doesn't complete is an error.""" + fake = FakeTes(states=[state]) + client = fa.TesClient("https://tes.example.org", transport=fake) + task_id = client.submit({}) + with pytest.raises(fa.TaskError, match=state): + client.wait(task_id) + + +def test_wait_times_out() -> None: + """A task that runs too long is an error.""" + fake = FakeTes(states=["RUNNING"] * 3) + client = fa.TesClient("https://tes.example.org", transport=fake) + task_id = client.submit({}) + with pytest.raises(fa.TaskError, match="still RUNNING"): + client.wait( + task_id, + poll=1, + timeout=1, + sleep=lambda _: None, + clock=iter(range(10)).__next__, + ) + + +def test_wait_raises_without_logs() -> None: + """A completed task without executor logs is an error.""" + + def transport(request: urllib.request.Request) -> Any: + return {"id": "x"} if request.data else {"state": "COMPLETE", "logs": []} + + client = fa.TesClient("https://tes.example.org", transport=transport) + with pytest.raises(fa.TaskError, match="no executor output"): + client.wait(client.submit({})) + + +def test_run_tes_raises_on_non_json_output() -> None: + """A task that prints no JSON is an error.""" + fake = FakeTes(stdout="oops") + client = fa.TesClient("https://tes.example.org", transport=fake) + with pytest.raises(fa.TaskError, match="no JSON"): + fa.run_tes(fa.load_partitions(MANIFEST), [client]) + + +def test_report_lists_groups_and_t() -> None: + """The report has one line per condition and column, then Welch's t.""" + result = fa.combine(fa.run_local(fa.load_partitions(MANIFEST), MANIFEST.parent)) + text = fa.report(result) + assert "control" in text and "treated" in text + assert text.count("Welch's t") == len(local_stats.VALUE_COLUMNS) + + +def test_report_without_both_conditions() -> None: + """Without both conditions, the report leaves out Welch's t.""" + result = fa.combine( + [{"a": {c: {"n": 2, "sum": 2, "sumsq": 2} for c in local_stats.VALUE_COLUMNS}}] + ) + assert "Welch" not in fa.report(result) + + +def test_main_local(capsys: pytest.CaptureFixture[str]) -> None: + """``--local --json`` prints the combined statistics as JSON.""" + assert fa.main(["--local", "--json"]) == 0 + result = json.loads(capsys.readouterr().out) + assert result["treated"]["expression"]["n"] == 50 + + +def test_main_tes( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """``--tes`` sends the tasks with the token of ``TES_TOKEN``.""" + fake = FakeTes() + monkeypatch.setenv("TES_TOKEN", "secret-for-test") + assert fa.main(["--tes", "https://gw.example.org"], transport=fake) == 0 + assert "Welch's t" in capsys.readouterr().out + assert fake.requests[0].get_header("Authorization") == "Bearer secret-for-test" + + +def test_main_rejects_mismatched_tes_count( + capsys: pytest.CaptureFixture[str], +) -> None: + """``--tes`` must be given once or once per partition.""" + n_parts = len(fa.load_partitions(MANIFEST)) + urls = [arg for i in range(n_parts + 1) for arg in ("--tes", f"https://{i}.org")] + with pytest.raises(SystemExit) as exc: + fa.main(urls, transport=FakeTes()) + assert exc.value.code == 2 + assert "give --tes once" in capsys.readouterr().err + + +@pytest.mark.parametrize("value", ["0", "-1", "x", "nan", "inf"]) +def test_main_rejects_non_positive_poll(value: str) -> None: + """``--poll`` and ``--timeout`` must be positive numbers.""" + with pytest.raises(SystemExit): + fa.main(["--tes", "https://gw.org", "--poll", value], transport=FakeTes()) + + +def test_main_reports_task_errors(capsys: pytest.CaptureFixture[str]) -> None: + """A failed task ends the run with a message and exit code 1.""" + fake = FakeTes(states=["SYSTEM_ERROR"] * 2) + assert ( + fa.main(["--tes", "https://gw.example.org", "--poll", "0.01"], transport=fake) + == 1 + ) + assert "SYSTEM_ERROR" in capsys.readouterr().err + + +def test_request_wraps_http_errors() -> None: + """HTTP and network errors become task errors with a hint.""" + + def transport(request: urllib.request.Request) -> Any: + raise urllib.error.HTTPError(request.full_url, 401, "Unauthorized", {}, None) # type: ignore[arg-type] + + client = fa.TesClient("https://tes.example.org", transport=transport) + with pytest.raises(fa.TaskError, match="401.*TES_TOKEN"): + client.submit({}) + + +def test_wait_counts_request_time() -> None: + """The timeout includes the time requests take, not only sleeps.""" + fake = FakeTes(states=["RUNNING"] * 5) + client = fa.TesClient("https://tes.example.org", transport=fake) + task_id = client.submit({}) + ticks = iter([0.0, 100.0, 200.0]) + with pytest.raises(fa.TaskError, match="still RUNNING"): + client.wait( + task_id, + poll=1, + timeout=150, + sleep=lambda _: None, + clock=lambda: next(ticks), + ) + + +def test_quick_start_runs_as_script() -> None: + """The README's quick start works from a fresh clone.""" + out = subprocess.run( + [sys.executable, str(DEMO), "--local"], + check=True, + capture_output=True, + text=True, + ) + assert "Welch's t (treated vs control), expression" in out.stdout + + +def test_request_wraps_network_errors() -> None: + """Network errors become task errors.""" + + def transport(request: urllib.request.Request) -> Any: + raise urllib.error.URLError("no route") + + client = fa.TesClient("https://tes.example.org", transport=transport) + with pytest.raises(fa.TaskError, match="no route"): + client.submit({}) + + +def test_request_wraps_timeouts() -> None: + """Read timeouts become task errors.""" + + def transport(request: urllib.request.Request) -> Any: + raise TimeoutError("read timed out") + + client = fa.TesClient("https://tes.example.org", transport=transport) + with pytest.raises(fa.TaskError, match="timed out"): + client.submit({}) + + +def test_summarise_errors_name_no_values() -> None: + """Errors give the row number and column, never the values of the row.""" + rows = [ + {"condition": "a", "od600": "1", "expression": "2"}, + {"condition": "secret-group", "od600": "secret-value", "expression": "2"}, + ] + with pytest.raises(ValueError) as exc: + local_stats.summarise(rows) + assert "row 2" in str(exc.value) and "od600" in str(exc.value) + assert "secret" not in str(exc.value) + assert exc.value.__cause__ is None + + +@pytest.mark.parametrize("value", ["nan", "inf", "-inf"]) +def test_summarise_rejects_non_finite_values(value: str) -> None: + """Non-finite values are errors.""" + with pytest.raises(ValueError, match="finite"): + local_stats.summarise([{"condition": "a", "od600": value, "expression": "1"}]) + + +def test_summarise_rejects_empty_partition() -> None: + """A partition without rows is an error.""" + with pytest.raises(ValueError, match="no rows"): + local_stats.summarise([]) + + +def test_local_stats_main_reports_invalid_data( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """Invalid data end with a short message and exit code 1, no traceback.""" + path = tmp_path / "bad.csv" + path.write_text("condition,od600,expression\nsecret,x,1\n") + assert local_stats.main([str(path)]) == 1 + err = capsys.readouterr().err + assert "row 1" in err and "secret" not in err + + +def test_json_output_has_no_nan() -> None: + """Undefined values are null in JSON output.""" + result = fa.combine([{"a": {"x": {"n": 1, "sum": 2, "sumsq": 4}}}]) + assert json.loads(fa.to_json(result))["a"]["x"]["sd"] is None + + +@pytest.mark.parametrize( + "response", [{"no": "id"}, ["not", "an", "object"]], ids=["no-id", "list"] +) +def test_submit_rejects_malformed_responses(response: Any) -> None: + """A response without a task ID is a task error.""" + client = fa.TesClient("https://tes.example.org", transport=lambda _: response) + with pytest.raises(fa.TaskError, match="malformed"): + client.submit({}) + + +def test_wait_rejects_malformed_responses() -> None: + """A status response that is not an object is a task error.""" + + def transport(request: urllib.request.Request) -> Any: + return {"id": "x"} if request.data else ["oops"] + + client = fa.TesClient("https://tes.example.org", transport=transport) + with pytest.raises(fa.TaskError, match="malformed"): + client.wait(client.submit({})) + + +def test_token_needs_https() -> None: + """A token is never sent over plain HTTP, except to localhost.""" + with pytest.raises(ValueError, match="HTTPS"): + fa.TesClient("http://tes.example.org", token="t") + fa.TesClient("http://localhost:8000", token="t") + fa.TesClient("http://127.0.0.1:8000", token="t") + fa.TesClient("http://tes.example.org") + + +def test_main_refuses_token_over_http( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The command line refuses to send a token over plain HTTP.""" + monkeypatch.setenv("TES_TOKEN", "t") + with pytest.raises(SystemExit): + fa.main(["--tes", "http://gw.example.org"], transport=FakeTes()) + assert "HTTPS" in capsys.readouterr().err + + +def test_redirects_are_refused() -> None: + """Redirects are refused, so that tokens never go to another origin.""" + handler = fa.NoRedirect() + request = urllib.request.Request("https://tes.example.org/x") + with pytest.raises(urllib.error.HTTPError, match="redirect"): + handler.redirect_request( + request, None, 302, "Found", {}, "https://evil.example.org/" + ) + + +def test_run_tes_cancels_tasks_on_failure() -> None: + """When a task fails, the client cancels the tasks it has sent.""" + fake = FakeTes(states=["SYSTEM_ERROR"]) + client = fa.TesClient("https://tes.example.org", transport=fake) + with pytest.raises(fa.TaskError): + fa.run_tes(fa.load_partitions(MANIFEST), [client]) + cancelled = [r.full_url for r in fake.requests if r.full_url.endswith(":cancel")] + assert cancelled == [f"{client.url}/task-{i}:cancel" for i in (1, 2)] + + +def test_cancel_ignores_errors() -> None: + """Cancelling is best effort: errors are ignored.""" + + def transport(request: urllib.request.Request) -> Any: + raise urllib.error.URLError("down") + + fa.TesClient("https://tes.example.org", transport=transport).cancel("x")