-
Notifications
You must be signed in to change notification settings - Fork 140
Let FastAPI perform pydantic validation of EverestConfig objects #14326
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -120,6 +120,7 @@ def start_experiment( | |
| retries: int = 5, | ||
| ) -> str: | ||
| url, cert, auth = server_context | ||
| last_error: str | None = None | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we only want the last error message? Would it be better if we appended the messages?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think they are very likely to be identical. All error message can be found in the logs if needed. |
||
| for retry in range(retries): | ||
| try: | ||
| start_endpoint = f"{url}/{EverEndpoints.START_EXPERIMENT}" | ||
|
|
@@ -132,10 +133,20 @@ def start_experiment( | |
| ) | ||
| response.raise_for_status() | ||
| return response.json()["experiment_id"] | ||
| except Exception: | ||
| except requests.HTTPError: | ||
| last_error = response.text | ||
| logger.debug(traceback.format_exc()) | ||
| if 400 <= response.status_code < 500: | ||
| break # 4xx should not trigger retries | ||
| time.sleep(retry) | ||
| except Exception: | ||
| last_error = traceback.format_exc() | ||
| logger.debug(last_error) | ||
| time.sleep(retry) | ||
| raise RuntimeError("Failed to start experiment") | ||
| message = "Failed to start experiment" | ||
| if last_error: | ||
| message += f": {last_error}" | ||
| raise RuntimeError(message) | ||
|
|
||
|
|
||
| def extract_errors_from_file(path: str) -> list[str]: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| import asyncio | ||
| import logging | ||
| import warnings | ||
| from base64 import b64encode | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
|
|
@@ -9,6 +10,7 @@ | |
| from unittest.mock import AsyncMock, MagicMock, Mock, patch | ||
|
|
||
| import pytest | ||
| import yaml | ||
| from fastapi.encoders import jsonable_encoder | ||
| from fastapi.testclient import TestClient | ||
| from starlette.websockets import WebSocketDisconnect | ||
|
|
@@ -37,6 +39,7 @@ | |
| OPT_FAILURE_REALIZATIONS, | ||
| ) | ||
| from everest.util._utils import get_everest_experiment | ||
| from tests.everest.utils import MIN_CONFIG, everest_config_with_defaults | ||
|
|
||
|
|
||
| @pytest.fixture | ||
|
|
@@ -339,21 +342,19 @@ def test_that_multiple_started_experiments_each_receive_distinct_experiment_ids( | |
| client = TestClient(app) | ||
| mock_runner = MagicMock() | ||
| mock_runner.run = AsyncMock() | ||
| with ( | ||
| patch.object(EverestConfig, "with_plugins", return_value=MagicMock()), | ||
| patch( | ||
| "ert.dark_storage.endpoints.experiment_server.ExperimentRunner", | ||
| return_value=mock_runner, | ||
| ), | ||
| config_body = everest_config_with_defaults().to_dict() | ||
| with patch( | ||
| "ert.dark_storage.endpoints.experiment_server.ExperimentRunner", | ||
| return_value=mock_runner, | ||
| ): | ||
| r1 = client.post( | ||
| "/experiment_server/start_experiment", | ||
| json={"type": "everest_config"}, | ||
| json=config_body, | ||
| headers=auth_headers, | ||
| ) | ||
| r2 = client.post( | ||
| "/experiment_server/start_experiment", | ||
| json={"type": "everest_config"}, | ||
| json=config_body, | ||
| headers=auth_headers, | ||
| ) | ||
| assert r1.status_code == r2.status_code == 200 | ||
|
|
@@ -373,6 +374,93 @@ def test_that_multiple_started_experiments_each_receive_distinct_experiment_ids( | |
| _experiments.update(original) | ||
|
|
||
|
|
||
| def test_that_start_experiment_with_incomplete_schema_returns_422(monkeypatch): | ||
| monkeypatch.setenv("ERT_STORAGE_TOKEN", "password") | ||
| credentials = b64encode(b"username:password").decode() | ||
| auth_headers = {"Authorization": f"Basic {credentials}"} | ||
| client = TestClient(app) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see that this is repeated a lot, could we add a fixture or method that generates it? e.g returns tuple of credentials, auth_headers and client?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. added fixup commit |
||
|
|
||
| # Missing all required fields (controls, objective_functions, | ||
| # config_path, model): schema validation should reject this before | ||
| # the endpoint body (and thus ExperimentRunner) is ever reached. | ||
| response = client.post( | ||
| "/experiment_server/start_experiment", | ||
| json={}, | ||
| headers=auth_headers, | ||
| ) | ||
|
|
||
| assert response.status_code == 422 | ||
| missing_fields = { | ||
| tuple(error["loc"]) | ||
| for error in response.json()["detail"] | ||
| if error["type"] == "missing" | ||
| } | ||
| assert missing_fields == { | ||
| ("body", "controls"), | ||
| ("body", "objective_functions"), | ||
| ("body", "config_path"), | ||
| ("body", "model"), | ||
| } | ||
|
|
||
|
|
||
| def test_that_start_experiment_with_unknown_forward_model_job_returns_422( | ||
| monkeypatch, | ||
| ): | ||
| monkeypatch.setenv("ERT_STORAGE_TOKEN", "password") | ||
| credentials = b64encode(b"username:password").decode() | ||
| auth_headers = {"Authorization": f"Basic {credentials}"} | ||
| client = TestClient(app) | ||
|
|
||
| config_body = yaml.safe_load(MIN_CONFIG) | { | ||
| "forward_model": ["totally_unknown_job_xyz"] | ||
| } | ||
|
|
||
| response = client.post( | ||
| "/experiment_server/start_experiment", | ||
| json=config_body, | ||
| headers=auth_headers, | ||
| ) | ||
|
|
||
| assert response.status_code == 422 | ||
| assert "unknown job totally_unknown_job_xyz" in response.text | ||
|
|
||
|
|
||
| def test_that_start_experiment_mutes_config_warnings(monkeypatch): | ||
| monkeypatch.setenv("ERT_STORAGE_TOKEN", "password") | ||
| credentials = b64encode(b"username:password").decode() | ||
| auth_headers = {"Authorization": f"Basic {credentials}"} | ||
| client = TestClient(app) | ||
| mock_runner = MagicMock() | ||
| mock_runner.run = AsyncMock() | ||
|
|
||
| config_body = yaml.safe_load(MIN_CONFIG) | ||
|
|
||
| def _raise_a_config_warning(*args, **kwargs): | ||
| warnings.warn("Forced test ConfigWarning", category=ConfigWarning, stacklevel=2) | ||
|
|
||
| monkeypatch.setattr( | ||
| "everest.config.everest_config.validate_forward_model_configs", | ||
| _raise_a_config_warning, | ||
| ) | ||
|
|
||
| with ( | ||
| patch( | ||
| "ert.dark_storage.endpoints.experiment_server.ExperimentRunner", | ||
| return_value=mock_runner, | ||
| ), | ||
| warnings.catch_warnings(record=True) as caught_warnings, | ||
| ): | ||
| warnings.simplefilter("always") | ||
| response = client.post( | ||
| "/experiment_server/start_experiment", | ||
| json=config_body, | ||
| headers=auth_headers, | ||
| ) | ||
|
|
||
| assert response.status_code == 200 | ||
| assert not any(issubclass(w.category, ConfigWarning) for w in caught_warnings) | ||
|
|
||
|
|
||
| async def test_websocket_no_events_on_connect(setup_client): | ||
| events = [] | ||
| client, subs, experiment_id = setup_client(events) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we folow the pattern of
authenticated = [Depends(verify_auth)]forDepends(_with_runtime_plugins)as well?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure it will add anything good, a little bit skeptical to the existing pattern of having a 1-member list for
authenticated- I guess it can make sense in case this list can grow. I don't think the list of dependencies for runtime_plugins can grow.