tea_preview job: one file previewed, result as run output: GET /runs/{id}?outputs=true; the TEA gate also previews one hospital EDF
This commit is contained in:
@@ -95,6 +95,24 @@ def test_shape_progress_tag():
|
||||
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
||||
|
||||
|
||||
def test_shape_outputs():
|
||||
events = [
|
||||
{
|
||||
"__typename": "ExecutionStepOutputEvent",
|
||||
"stepKey": "preview_study",
|
||||
"outputName": "result",
|
||||
"metadataEntries": [
|
||||
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
|
||||
{"label": "text"},
|
||||
],
|
||||
},
|
||||
]
|
||||
assert shape(PAYLOAD, events, outputs=True).outputs == {
|
||||
"preview_study.result": {"eeg": {"valid": False}}
|
||||
}
|
||||
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
||||
|
||||
|
||||
def _ok(response):
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
+62
-1
@@ -16,12 +16,15 @@ from collections import defaultdict
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import dagster as dg
|
||||
import pytest
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
from core.tea import ados2
|
||||
from models.definitions import tea_preview
|
||||
from persistance import config, previews
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
|
||||
@@ -139,7 +142,8 @@ def _day(value) -> date:
|
||||
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
@pytest.fixture
|
||||
def scored_hospital(api, platform):
|
||||
db = HOSPITAL / "hospital_tea.db"
|
||||
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
|
||||
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
|
||||
@@ -227,6 +231,10 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9)
|
||||
for v in expected], key # fmt: skip
|
||||
|
||||
return platform
|
||||
|
||||
|
||||
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
||||
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
|
||||
# promoted curves found (as the current platform's were captured: curves trained).
|
||||
indicators(api)
|
||||
@@ -241,3 +249,56 @@ def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
||||
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
||||
for m in shown["metrics"]) # fmt: skip
|
||||
|
||||
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
|
||||
|
||||
|
||||
def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):
|
||||
"""P3.5: previewing one of the hospital's EDFs gives its stored analysis and scores, and
|
||||
writes nothing (run here, on the already scored hospital, not as a second 80-minute load)."""
|
||||
q = platform.query
|
||||
tables = (
|
||||
"bronze.eeg_analysis", "bronze.eeg_checks", "bronze.eeg_metrics",
|
||||
"bronze.eeg_scores", "bronze.files", "silver.eeg",
|
||||
) # fmt: skip
|
||||
before = {table: platform.count(table) for table in tables}
|
||||
edf, content, birth, valid, level = q("""
|
||||
select a.edf, f.content, p.birth_date, a.valid, a.level
|
||||
from bronze.eeg_analysis a
|
||||
join bronze.files f on f.key = a.edf
|
||||
join silver.eeg e on e.edf = a.edf
|
||||
join silver.person p on p.person_id = e.person_id
|
||||
where a.valid and p.birth_date is not null and exists (
|
||||
select 1 from gold.tea_eeg_metrics m where m.edf = a.edf and m.z is not null
|
||||
)
|
||||
order by a.edf
|
||||
limit 1
|
||||
""")[0]
|
||||
values = dict(q(f"select code, value from bronze.eeg_metrics where edf = '{edf}'"))
|
||||
scores = dict(q(f"select code, z from gold.tea_eeg_metrics where edf = '{edf}'"))
|
||||
|
||||
for name in ("PLATFORM_DATABASE_URL", "MLFLOW_TRACKING_URI", "ISSSTELEON_DATA"):
|
||||
monkeypatch.setenv(name, platform.env[name])
|
||||
monkeypatch.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
|
||||
key = previews.put(bytes(content))
|
||||
with dg.DagsterInstance.ephemeral() as instance:
|
||||
run = tea_preview.execute_in_process(
|
||||
run_config={"ops": {"preview_study": {"config": {
|
||||
"edf": key, "birth_date": _day(birth).isoformat(),
|
||||
}}}},
|
||||
instance=instance,
|
||||
) # fmt: skip
|
||||
assert run.success
|
||||
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
|
||||
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
|
||||
|
||||
assert (result.eeg.valid, result.eeg.level) == (valid, level)
|
||||
assert {metric.code for metric in result.eeg.metrics} == values.keys() == scores.keys()
|
||||
for metric in result.eeg.metrics:
|
||||
value, z = values[metric.code], scores[metric.code]
|
||||
assert metric.value == (None if value is None else pytest.approx(value, rel=1e-12))
|
||||
assert (metric.score.z if metric.score else None) == (
|
||||
None if z is None else pytest.approx(z, rel=1e-9)
|
||||
)
|
||||
assert {table: platform.count(table) for table in tables} == before
|
||||
assert not list(previews.area().iterdir())
|
||||
|
||||
+17
-6
@@ -1,8 +1,9 @@
|
||||
"""Runs live in Dagster: the API starts them and reads their state, never computes."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Literal
|
||||
from typing import Any, Literal
|
||||
|
||||
import requests
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
@@ -29,7 +30,7 @@ STATE: dict[str, State] = {
|
||||
}
|
||||
|
||||
RUN_QUERY = """
|
||||
query Run($id: ID!) {
|
||||
query Run($id: ID!, $outputs: Boolean! = false) {
|
||||
runOrError(runId: $id) {
|
||||
__typename
|
||||
... on Run { runId jobName status startTime endTime tags { key value }
|
||||
@@ -41,6 +42,9 @@ query Run($id: ID!) {
|
||||
__typename
|
||||
... on EventConnection { events { __typename
|
||||
... on MessageEvent { message level stepKey }
|
||||
... on ExecutionStepOutputEvent @include(if: $outputs) {
|
||||
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
|
||||
}
|
||||
... on ExecutionStepFailureEvent { error { message causes { message } } }
|
||||
... on RunFailureEvent { error { message causes { message } } } } }
|
||||
... on RunNotFoundError { message }
|
||||
@@ -84,6 +88,7 @@ class Run(RunSummary):
|
||||
info: list[str]
|
||||
warnings: list[str]
|
||||
error: str | None
|
||||
outputs: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class Cancel(BaseModel):
|
||||
@@ -159,7 +164,7 @@ def _summary(run: dict) -> RunSummary:
|
||||
)
|
||||
|
||||
|
||||
def shape(run: dict, logs: list[dict]) -> Run:
|
||||
def shape(run: dict, logs: list[dict], outputs: bool = False) -> Run:
|
||||
summary = _summary(run)
|
||||
progress = None
|
||||
if (tag := _tags(run).get("isssteleon/progress")) is not None:
|
||||
@@ -181,6 +186,7 @@ def shape(run: dict, logs: list[dict]) -> Run:
|
||||
|
||||
info, warnings = [], []
|
||||
error = None
|
||||
result = {} if outputs else None
|
||||
for event in logs:
|
||||
kind = event["__typename"]
|
||||
if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"):
|
||||
@@ -188,6 +194,10 @@ def shape(run: dict, logs: list[dict]) -> Run:
|
||||
if step_key := event.get("stepKey"):
|
||||
line = f"{step_key}: {line}"
|
||||
(info if event["level"] == "INFO" else warnings).append(line)
|
||||
if result is not None and kind == "ExecutionStepOutputEvent":
|
||||
for entry in event.get("metadataEntries", ()):
|
||||
if "jsonString" in entry:
|
||||
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
|
||||
if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"):
|
||||
failure = event.get("error")
|
||||
error = None
|
||||
@@ -200,6 +210,7 @@ def shape(run: dict, logs: list[dict]) -> Run:
|
||||
return Run(
|
||||
**summary.model_dump(),
|
||||
progress=progress,
|
||||
outputs=result,
|
||||
steps=steps,
|
||||
info=info[-200:],
|
||||
warnings=warnings[:200],
|
||||
@@ -215,11 +226,11 @@ def _result(result: dict, typename: str) -> dict:
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def run_status(run_id: str) -> Run:
|
||||
data = graphql(RUN_QUERY, {"id": run_id})
|
||||
def run_status(run_id: str, outputs: bool = False) -> Run:
|
||||
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
|
||||
run = _result(data["runOrError"], "Run")
|
||||
logs = _result(data["logsForRun"], "EventConnection")
|
||||
return shape(run, logs["events"])
|
||||
return shape(run, logs["events"], outputs)
|
||||
|
||||
|
||||
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
||||
|
||||
Reference in New Issue
Block a user