diff --git a/CHANGELOG.md b/CHANGELOG.md index 0646637c..b0ffbf2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ All notable changes to this project will be documented in this file. +## Unreleased + +### Added + +- Evaluate a model on a dataset version of the same project. + `Workspace.create_model_evaluation(model, project, version=None)` starts the eval + and returns `{evalId, status, reused, version, trainedOnVersion, leakage, classMismatch}`. + `Workspace.check_model_evaluation_compatibility(...)` returns `{allowed, blocks, ...}` and starts no job. + `rerun=True` (CLI: `--rerun`) starts a new eval when a done eval exists. + A pending or running eval still returns with `reused: true`. + Leakage and class mismatch never block an eval. They are tags on the result. + A tag is `None` when the platform has no value for it, for example for the training version. + A blocked request raises `ModelEvalBlockedError` with a `blocks` list. + `ModelEvalNotFoundError` and `ModelEvalAccessError` now cover these requests too. + A full workspace raises `ModelEvalConcurrencyLimitError`. + The CLI is `roboflow eval create` and `roboflow eval check-compatibility` + (`-m -p [-v ]`). + Exit code 6 means blocked. Exit code 7 means the concurrency limit. + `Workspace.eval` and `roboflow eval get --json` keep the same three tags. + Needs the `POST /{workspace}/model-evals` and `POST /{workspace}/model-evals/check-compatibility` APIs + ([#591](https://github.com/roboflow/roboflow-python/pull/591)). + ## 1.7.5 ### Added diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 72f0ea16..59273ebe 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -496,6 +496,28 @@ without parsing message strings: `2` for authentication or access errors (401/40 `invalid_split` / `invalid_confidence` (400). Requires the `model-eval:read` scope on the api key. +### Evaluate a model on another dataset version + +```bash +# Check the request first. This starts no job. +roboflow eval check-compatibility -m my-workspace/my-model -p my-project -v 5 --json + +# Start the eval. Omit -v to use the version the model trained on. +roboflow eval create -m my-workspace/my-model -p my-project -v 5 --json +``` + +Both commands return `trainedOnVersion`, `leakage` and `classMismatch`. +Leakage and class mismatch never block an eval. The eval runs with these tags. +A tag is `null` when the platform has no value for it, for example for the training version. +Text output omits a null tag. +`create` returns `reused: true` when an eval for the same model, version and +settings is pending, running or done. Add `--rerun` to start a new eval when a +done eval exists. A pending or running eval still returns `reused: true`. +Exit code `6` means a compatibility block. The error message lists each block. +Run `eval check-compatibility --json` for the structured `blocks` list. +Exit code `7` means the workspace has too many active evals. +Requires the `training-job:create` scope and workspace Model Evaluation access. + ### Compare Models ```bash diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 4b4fa8e1..11d3577c 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2309,7 +2309,7 @@ def restore_trash_item(api_key, workspace_url, item_type, item_id, parent_id=Non class ModelEvalNotFoundError(RoboflowError): - """Raised when an eval id (or workspace) does not exist (HTTP 404).""" + """Raised when an eval id, workspace, model, project or version does not exist (HTTP 404).""" class ModelEvalNotDoneError(RoboflowError): @@ -2317,7 +2317,22 @@ class ModelEvalNotDoneError(RoboflowError): class ModelEvalAccessError(RoboflowError): - """Raised when an evaluation read is not authorized (HTTP 401 or 403).""" + """Raised when an evaluation request is not authorized (HTTP 401 or 403).""" + + +class ModelEvalBlockedError(RoboflowError): + """Raised when a compatibility check blocks the eval (HTTP 409 with ``blocks``). + + ``blocks`` is the server list of ``{"code": ..., "message": ...}`` dicts. + """ + + def __init__(self, message, blocks, status_code=409): + super().__init__(message, status_code=status_code) + self.blocks = blocks + + +class ModelEvalConcurrencyLimitError(RoboflowError): + """Raised when the workspace has too many active evals (HTTP 429, ``eval_concurrency_limit``).""" class InvalidSplitError(RoboflowError): @@ -2328,27 +2343,40 @@ class InvalidConfidenceError(RoboflowError): """Raised when ``confidence`` is non-integer or out of range 0-100 (HTTP 400).""" -def _model_eval_error_for(response): +def _model_eval_error_for(response, start=False): """Translate a model-eval error response into the right RoboflowError subclass. - The model-eval REST surface returns errors as a flat envelope:: + The read routes return a flat envelope:: {"error": "", "message": ""} + The create and compatibility check calls (``start=True``) also return + ``{"error": "", "code": "", "details": {"blocks": [...]}}`` for a blocked start + and ``{"error": {"code": "", "message": ""}}`` for the concurrency limit. + Falls back to plain :class:`RoboflowError` when the body isn't JSON or the code is unrecognised, so new error codes don't crash older SDK callers. Status-code fallbacks for 404/409 keep typed exceptions - available even if the server omits the ``error`` field. + available even if the server omits the code. """ code = None message = response.text + blocks = None try: body = response.json() if isinstance(body, dict): - code = body.get("error") - if not isinstance(code, str): - code = None - message = body.get("message") or code or message + error = body.get("error") + if start and isinstance(error, dict): + code, text = error.get("code"), error.get("message") + elif start and "code" in body: + code, text = body["code"], error + else: + code, text = error, body.get("message") + code = code if isinstance(code, str) else None + message = text if isinstance(text, str) and text else code or message + details = body.get("details") + if start and isinstance(details, dict) and isinstance(details.get("blocks"), list): + blocks = details["blocks"] except (ValueError, TypeError): pass @@ -2361,6 +2389,14 @@ def _model_eval_error_for(response): cls = cls_by_code.get(code or "") if response.status_code in (401, 403): return ModelEvalAccessError(message) + if response.status_code == 409 and blocks: + return ModelEvalBlockedError( + "\n".join(f"{block.get('code')}: {block.get('message')}" for block in blocks), + blocks, + status_code=409, + ) + if response.status_code == 429 and code == "eval_concurrency_limit": + return ModelEvalConcurrencyLimitError(message, status_code=429) if cls is not None: return cls(message) if response.status_code == 404: @@ -2384,6 +2420,63 @@ def _eval_get(api_key, workspace_url, path, params=None): return response.json() +def _eval_post(api_key, workspace_url, path, body): + """POST helper for model-eval endpoints with typed error mapping.""" + url = f"{API_URL}/{workspace_url}/model-evals{path}" + response = http.post(url, params={"api_key": api_key}, json=body) + if response.status_code != 200: + raise _model_eval_error_for(response, start=True) + return response.json() + + +def _eval_start_body(model, project, version): + body: Dict[str, Any] = {"modelId": model, "project": project} + if version is not None: + body["version"] = str(version) + return body + + +def create_model_eval( + api_key: str, + workspace_url: str, + *, + model: str, + project: str, + version: Optional[Union[str, int]] = None, + rerun: bool = False, +) -> dict: + """POST /{workspace}/model-evals — evaluate a model on a dataset version of its project. + + ``model`` is ``{workspace}/{model}`` or the bare model slug. ``version`` defaults to the + version the model trained on. The call is idempotent: an eval that is pending, running or done + for the same model, version and settings comes back with ``reused: true``. With ``rerun=True`` + a done eval does not count, so a new eval starts. A pending or running eval still comes back + with ``reused: true``. + + Raises :class:`ModelEvalBlockedError` (409), :class:`ModelEvalConcurrencyLimitError` (429), + :class:`ModelEvalNotFoundError` (404) and :class:`ModelEvalAccessError` (401 or 403). + """ + body = _eval_start_body(model, project, version) + if rerun: + body["rerun"] = True + return _eval_post(api_key, workspace_url, "", body) + + +def check_model_eval_compatibility( + api_key: str, + workspace_url: str, + *, + model: str, + project: str, + version: Optional[Union[str, int]] = None, +) -> dict: + """POST /{workspace}/model-evals/check-compatibility — check an eval request without starting it. + + A blocked request is a normal result (``allowed: false`` with ``blocks``), not an error. + """ + return _eval_post(api_key, workspace_url, "/check-compatibility", _eval_start_body(model, project, version)) + + def compare_model_evals( api_key: str, workspace_url: str, diff --git a/roboflow/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index e55d556d..a1c2fbac 100644 --- a/roboflow/cli/handlers/eval.py +++ b/roboflow/cli/handlers/eval.py @@ -1,7 +1,7 @@ """Model evaluation commands. -Wraps the public ``/{workspace}/model-evals`` REST surface — list runs in a -workspace and pull each panel (mAP, confidence sweep, per-class table, +Wraps the public ``/{workspace}/model-evals`` REST surface — start a run, +check a request, list runs in a workspace and pull each panel (mAP, confidence sweep, per-class table, confusion matrix, vector clusters, per-image stats, recommendations). The eval-id is opaque (the human in the UI navigates by URL); commands take @@ -16,7 +16,7 @@ from roboflow.cli._compat import SortedGroup, ctx_to_args -eval_app = typer.Typer(cls=SortedGroup, help="Inspect model evaluation runs", no_args_is_help=True) +eval_app = typer.Typer(cls=SortedGroup, help="Create and inspect model evaluation runs", no_args_is_help=True) # --------------------------------------------------------------------------- @@ -24,6 +24,43 @@ # --------------------------------------------------------------------------- +@eval_app.command("create") +def create_eval_cmd( + ctx: typer.Context, + model: Annotated[str, typer.Option("-m", "--model", help="Model URL (workspace/model) or model slug")], + project: Annotated[str, typer.Option("-p", "--project", help="Project slug")], + version: Annotated[ + Optional[int], + typer.Option( + "-v", "--version", min=1, help="Dataset version number (default: the version the model trained on)" + ), + ] = None, + rerun: Annotated[ + bool, typer.Option("--rerun", help="Start a new eval even when a done eval exists for the request") + ] = False, +) -> None: + """Evaluate a model on a dataset version of its project.""" + args = ctx_to_args(ctx, model=model, project=project, version=version, rerun=rerun) + _create_eval(args) + + +@eval_app.command("check-compatibility") +def check_compatibility_eval_cmd( + ctx: typer.Context, + model: Annotated[str, typer.Option("-m", "--model", help="Model URL (workspace/model) or model slug")], + project: Annotated[str, typer.Option("-p", "--project", help="Project slug")], + version: Annotated[ + Optional[int], + typer.Option( + "-v", "--version", min=1, help="Dataset version number (default: the version the model trained on)" + ), + ] = None, +) -> None: + """Check an evaluation request without starting it.""" + args = ctx_to_args(ctx, model=model, project=project, version=version) + _check_compatibility_eval(args) + + @eval_app.command("compare") def compare_evals_cmd( ctx: typer.Context, @@ -183,7 +220,8 @@ def _eval_error_exit_code(exc: Exception) -> int: """Map a model-eval error to the canonical CLI exit code. 1 = general; 2 = auth; 3 = not found; 4 = conflict (eval not done); - 5 = invalid argument (bad split / confidence). Keeping these distinct + 5 = invalid argument (bad split / confidence); 6 = eval blocked by a + compatibility check; 7 = workspace eval concurrency limit. Keeping these distinct lets shell scripts and AI agents react to specific failure modes without parsing message strings. """ @@ -197,6 +235,10 @@ def _eval_error_exit_code(exc: Exception) -> int: return 4 if isinstance(exc, (rfapi.InvalidSplitError, rfapi.InvalidConfidenceError)): return 5 + if isinstance(exc, rfapi.ModelEvalBlockedError): + return 6 + if isinstance(exc, rfapi.ModelEvalConcurrencyLimitError): + return 7 return 1 @@ -217,6 +259,84 @@ def _hint_for(exc: Exception) -> Optional[str]: return None +def _start_hint_for(exc: Exception) -> Optional[str]: + """Hint for the start commands. A blocked error has none: its message lists the blocks.""" + from roboflow.adapters import rfapi + + if isinstance(exc, rfapi.ModelEvalAccessError): + return "Check your API key, its training-job:create scope, and workspace Model Evaluation access." + if isinstance(exc, rfapi.ModelEvalNotFoundError): + return ( + "Check the --model, --project and --version values, and that the API key has the training-job:create scope." + ) + if isinstance(exc, rfapi.ModelEvalConcurrencyLimitError): + return "Wait for an active eval to finish, then try again." + return None + + +def _format_tags(result) -> list: # noqa: ANN001 + """Text lines for the tags that are present: trained-on version, leakage and class mismatch.""" + lines = [] + if result.get("trainedOnVersion") is not None: + lines.append(f" Trained on version: {result['trainedOnVersion']}") + leakage = result.get("leakage") + if leakage is not None: + lines.append(f" Leakage: {leakage['status']}") + for split, counts in (leakage.get("splits") or {}).items(): + lines.append(f" {split}: {counts['leaked']} of {counts['total']} images leaked") + mismatch = result.get("classMismatch") + if mismatch is not None: + lines.append(f" Classes only in the target version: {', '.join(mismatch['targetOnly']) or 'none'}") + lines.append(f" Classes only in the model: {', '.join(mismatch['modelOnly']) or 'none'}") + return lines + + +def _create_eval(args): # noqa: ANN001 + from roboflow.adapters import rfapi + from roboflow.cli._output import output, output_error + + resolved = _resolve(args) + if not resolved: + return + workspace_url, api_key = resolved + try: + result = rfapi.create_model_eval( + api_key, workspace_url, model=args.model, project=args.project, version=args.version, rerun=args.rerun + ) + except Exception as exc: + output_error(args, str(exc), hint=_start_hint_for(exc), exit_code=_eval_error_exit_code(exc)) + return + lines = [ + f"Eval: {result['evalId']}", + f" Status: {result['status']}", + f" Reused: {'yes' if result['reused'] else 'no'}", + f" Version: {result['version']}", + *_format_tags(result), + ] + output(args, result, text="\n".join(lines)) + + +def _check_compatibility_eval(args): # noqa: ANN001 + from roboflow.adapters import rfapi + from roboflow.cli._output import output, output_error + + resolved = _resolve(args) + if not resolved: + return + workspace_url, api_key = resolved + try: + result = rfapi.check_model_eval_compatibility( + api_key, workspace_url, model=args.model, project=args.project, version=args.version + ) + except Exception as exc: + output_error(args, str(exc), hint=_start_hint_for(exc), exit_code=_eval_error_exit_code(exc)) + return + lines = [f"Allowed: {'yes' if result['allowed'] else 'no'}"] + lines.extend(f" Block {block['code']}: {block['message']}" for block in result["blocks"]) + lines.extend(_format_tags(result)) + output(args, result, text="\n".join(lines)) + + def _compare_evals(args): # noqa: ANN001 from roboflow.adapters import rfapi from roboflow.cli._output import output, output_error diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 60a8065d..e09792b5 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1643,6 +1643,75 @@ def compare_model_evaluations( frontier_metric=frontier_metric, ) + def create_model_evaluation( + self, + model: str, + project: str, + version: Optional[Union[str, int]] = None, + rerun: bool = False, + ) -> dict: + """Evaluate a model on a dataset version of its project. + + Args: + model: Model URL (``workspace/model``) or bare model slug. + project: Project URL slug. + version: Dataset version number. Defaults to the version the model + trained on. + rerun: Start a new eval even when a done eval exists for the same + model, version and settings. + + Returns: + ``{evalId, status, reused, version, trainedOnVersion, leakage, classMismatch}``. + The call is idempotent: an eval for the same model, version and settings + that is pending, running or done returns with ``reused`` set to ``True``. + With ``rerun=True`` a done eval does not count. A pending or running eval + still returns with ``reused`` set to ``True``. + ``leakage`` and ``classMismatch`` never block the eval. A tag is ``None`` + when the platform has no value for it, for example for the training version. + + Raises: + roboflow.adapters.rfapi.ModelEvalBlockedError: The compatibility check blocks the eval. + The ``blocks`` attribute lists the ``code`` and ``message`` of each block. + The ``model_not_ready`` code means the model has no finished training or complete upload. + roboflow.adapters.rfapi.ModelEvalConcurrencyLimitError: The workspace has too many + active evals. + roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist, + or the API key has no ``training-job:create`` scope. + roboflow.adapters.rfapi.ModelEvalAccessError: The API key or workspace has no access. + + Example: + >>> result = ws.create_model_evaluation("my-ws/my-model", "chess", 5) + >>> result["reused"] + False + """ + return rfapi.create_model_eval( + self.__api_key, self.url, model=model, project=project, version=version, rerun=rerun + ) + + def check_model_evaluation_compatibility( + self, + model: str, + project: str, + version: Optional[Union[str, int]] = None, + ) -> dict: + """Check an evaluation request without starting it. + + Takes the same arguments as :meth:`create_model_evaluation`, except ``rerun``. + + Returns: + ``{allowed, blocks, trainedOnVersion, leakage, classMismatch}``. A blocked + request returns ``allowed: False`` with a ``blocks`` list. It does not raise for a block. + The ``model_not_ready`` block code means the model has no finished training or complete upload. + + Raises: + roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist, + or the API key has no ``training-job:create`` scope. + roboflow.adapters.rfapi.ModelEvalAccessError: The API key or workspace has no access. + """ + return rfapi.check_model_eval_compatibility( + self.__api_key, self.url, model=model, project=project, version=version + ) + def evals( self, *, diff --git a/tests/adapters/test_rfapi_model_evals.py b/tests/adapters/test_rfapi_model_evals.py index 16b66830..49e2abe9 100644 --- a/tests/adapters/test_rfapi_model_evals.py +++ b/tests/adapters/test_rfapi_model_evals.py @@ -170,6 +170,17 @@ def test_404_status_code_fallback(self, mock_get): with self.assertRaises(rfapi.ModelEvalNotFoundError): rfapi.get_model_eval("k", "ws", "x") + @patch("roboflow.util.http.requests.get") + def test_nested_error_object_keeps_the_raw_text(self, mock_get): + body = {"error": {"type": "InvalidRequest", "message": "boom", "code": "invalid_split"}} + mock_get.return_value = _resp(400, body) + + with self.assertRaises(rfapi.RoboflowError) as ctx: + rfapi.get_model_eval("k", "ws", "x") + + self.assertEqual(str(ctx.exception), repr(body)) + self.assertNotIsInstance(ctx.exception, rfapi.InvalidSplitError) + @patch("roboflow.util.http.requests.get") def test_409_not_done(self, mock_get): mock_get.return_value = _resp(409, {"error": "model_eval_not_done", "message": "Eval still running"}) @@ -248,5 +259,170 @@ def test_compare_returns_public_result_and_sends_frontier_metric(self, mock_get) ) +CREATE_RESULT = { + "evalId": "e9", + "status": "running", + "reused": False, + "version": "5", + "trainedOnVersion": "2", + "leakage": { + "status": "detected", + "splits": { + "test": {"total": 412, "leaked": 37, "fromTrain": 30, "fromValid": 9}, + "valid": {"total": 200, "leaked": 5, "fromTrain": 5}, + }, + }, + "classMismatch": {"targetOnly": ["washer"], "modelOnly": ["nut"]}, +} +BLOCKS = [ + {"code": "preprocessing_mismatch", "message": "The preprocessing differs."}, + {"code": "different_project", "message": "The model does not belong to this project."}, +] + + +class TestCreateModelEval(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_posts_body_and_returns_full_response(self, mock_post): + mock_post.return_value = _resp(200, CREATE_RESULT) + + result = rfapi.create_model_eval("k", "ws", model="ws/my-model", project="chess", version=5) + + self.assertEqual(result, CREATE_RESULT) + mock_post.assert_called_once_with( + f"{API_URL}/ws/model-evals", + params={"api_key": "k"}, + json={"modelId": "ws/my-model", "project": "chess", "version": "5"}, + headers={"User-Agent": USER_AGENT}, + ) + + @patch("roboflow.util.http.requests.post") + def test_omits_version_when_not_given(self, mock_post): + mock_post.return_value = _resp(200, CREATE_RESULT) + + rfapi.create_model_eval("k", "ws", model="my-model", project="chess") + + self.assertEqual(mock_post.call_args.kwargs["json"], {"modelId": "my-model", "project": "chess"}) + + @patch("roboflow.util.http.requests.post") + def test_sends_rerun_only_when_true(self, mock_post): + mock_post.return_value = _resp(200, CREATE_RESULT) + + rfapi.create_model_eval("k", "ws", model="m", project="chess", version=5, rerun=True) + self.assertEqual( + mock_post.call_args.kwargs["json"], {"modelId": "m", "project": "chess", "version": "5", "rerun": True} + ) + + rfapi.create_model_eval("k", "ws", model="m", project="chess", version=5, rerun=False) + self.assertNotIn("rerun", mock_post.call_args.kwargs["json"]) + + @patch("roboflow.util.http.requests.post") + def test_keeps_null_tags_of_a_reused_eval(self, mock_post): + body = {**CREATE_RESULT, "reused": True, "trainedOnVersion": None, "leakage": None, "classMismatch": None} + mock_post.return_value = _resp(200, body) + + result = rfapi.create_model_eval("k", "ws", model="m", project="chess", version=5) + + self.assertTrue(result["reused"]) + self.assertIsNone(result["leakage"]) + + @patch("roboflow.util.http.requests.post") + def test_409_raises_blocked_error_with_blocks(self, mock_post): + mock_post.return_value = _resp( + 409, + { + "error": BLOCKS[0]["message"], + "code": BLOCKS[0]["code"], + "details": {"blocks": BLOCKS}, + "retryable": False, + }, + ) + + with self.assertRaises(rfapi.ModelEvalBlockedError) as ctx: + rfapi.create_model_eval("k", "ws", model="m", project="chess", version=5) + + self.assertEqual(ctx.exception.blocks, BLOCKS) + self.assertEqual(ctx.exception.status_code, 409) + self.assertIn("The preprocessing differs.", str(ctx.exception)) + self.assertNotIsInstance(ctx.exception, rfapi.ModelEvalNotDoneError) + + @patch("roboflow.util.http.requests.post") + def test_429_raises_concurrency_limit_error(self, mock_post): + mock_post.return_value = _resp( + 429, {"error": {"code": "eval_concurrency_limit", "message": "10 evaluations are active."}} + ) + + with self.assertRaises(rfapi.ModelEvalConcurrencyLimitError) as ctx: + rfapi.create_model_eval("k", "ws", model="m", project="chess", version=5) + + self.assertEqual(ctx.exception.status_code, 429) + self.assertIn("10 evaluations", str(ctx.exception)) + + @patch("roboflow.util.http.requests.post") + def test_429_with_another_code_is_a_generic_error(self, mock_post): + mock_post.return_value = _resp(429, {"error": "rate_limited", "message": "Slow down."}) + + with self.assertRaises(rfapi.RoboflowError) as ctx: + rfapi.create_model_eval("k", "ws", model="m", project="chess") + + self.assertNotIsInstance(ctx.exception, rfapi.ModelEvalConcurrencyLimitError) + + @patch("roboflow.util.http.requests.post") + def test_403_raises_access_error(self, mock_post): + mock_post.return_value = _resp(403, {"error": "forbidden", "message": "Plan does not include evaluations."}) + + with self.assertRaises(rfapi.ModelEvalAccessError): + rfapi.create_model_eval("k", "ws", model="m", project="chess") + + @patch("roboflow.util.http.requests.post") + def test_404_raises_not_found_error(self, mock_post): + mock_post.return_value = _resp(404, {"error": "not_found", "message": "Model not found"}) + + with self.assertRaises(rfapi.ModelEvalNotFoundError): + rfapi.create_model_eval("k", "ws", model="m", project="chess") + + +class TestCheckModelEvalCompatibility(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_posts_to_check_compatibility_and_returns_full_response(self, mock_post): + compatibility_check = { + "allowed": True, + "blocks": [], + "trainedOnVersion": "2", + "leakage": CREATE_RESULT["leakage"], + "classMismatch": CREATE_RESULT["classMismatch"], + } + mock_post.return_value = _resp(200, compatibility_check) + + result = rfapi.check_model_eval_compatibility("k", "ws", model="ws/my-model", project="chess", version="5") + + self.assertEqual(result, compatibility_check) + mock_post.assert_called_once_with( + f"{API_URL}/ws/model-evals/check-compatibility", + params={"api_key": "k"}, + json={"modelId": "ws/my-model", "project": "chess", "version": "5"}, + headers={"User-Agent": USER_AGENT}, + ) + + @patch("roboflow.util.http.requests.post") + def test_a_blocked_check_is_a_result_not_an_error(self, mock_post): + blocked = { + "allowed": False, + "blocks": BLOCKS[:1], + "trainedOnVersion": None, + "leakage": None, + "classMismatch": None, + } + mock_post.return_value = _resp(200, blocked) + + self.assertEqual(rfapi.check_model_eval_compatibility("k", "ws", model="m", project="chess"), blocked) + + @patch("roboflow.util.http.requests.post") + def test_403_raises_access_error(self, mock_post): + mock_post.return_value = _resp(403, {"error": "forbidden", "message": "No access."}) + + with self.assertRaises(rfapi.ModelEvalAccessError): + rfapi.check_model_eval_compatibility("k", "ws", model="m", project="chess") + + if __name__ == "__main__": unittest.main() diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 2a982bb0..343867d2 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -34,6 +34,8 @@ def test_eval_root_help(self) -> None: def test_each_subcommand_help(self) -> None: for cmd in [ + "create", + "check-compatibility", "list", "get", "map-results", @@ -401,6 +403,8 @@ def test_exit_codes(self) -> None: rfapi.ModelEvalAccessError("x"): 2, rfapi.ModelEvalNotFoundError("x"): 3, rfapi.ModelEvalNotDoneError("x"): 4, + rfapi.ModelEvalBlockedError("x", blocks=[]): 6, + rfapi.ModelEvalConcurrencyLimitError("x"): 7, rfapi.InvalidSplitError("x"): 5, rfapi.InvalidConfidenceError("x"): 5, rfapi.RoboflowError("x"): 1, @@ -411,6 +415,188 @@ def test_exit_codes(self) -> None: self.assertEqual(_eval_error_exit_code(exc), expected) +CREATED = { + "evalId": "e9", + "status": "running", + "reused": False, + "version": "5", + "trainedOnVersion": "2", + "leakage": { + "status": "detected", + "splits": { + "test": {"total": 412, "leaked": 37, "fromTrain": 30, "fromValid": 9}, + "valid": {"total": 200, "leaked": 5, "fromTrain": 5}, + }, + }, + "classMismatch": {"targetOnly": ["washer"], "modelOnly": ["nut"]}, +} +CREATE_ARGS = ["--api-key", "k", "--workspace", "ws", "eval", "create", "-m", "ws/my-model", "-p", "chess", "-v", "5"] + + +class TestEvalCreateCommand(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_json_prints_the_full_response(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = CREATED + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(json.loads(result.stdout), CREATED) + self.assertEqual( + mock_post.call_args.kwargs["json"], {"modelId": "ws/my-model", "project": "chess", "version": "5"} + ) + + @patch("roboflow.util.http.requests.post") + def test_rerun_flag_is_sent(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = CREATED + result = runner.invoke(app, [*CREATE_ARGS, "--rerun"]) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertIs(mock_post.call_args.kwargs["json"]["rerun"], True) + + @patch("roboflow.util.http.requests.post") + def test_rerun_is_not_sent_by_default(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = CREATED + runner.invoke(app, CREATE_ARGS) + + self.assertNotIn("rerun", mock_post.call_args.kwargs["json"]) + + @patch("roboflow.util.http.requests.post") + def test_text_shows_the_tags(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = CREATED + result = runner.invoke(app, CREATE_ARGS) + + self.assertEqual(result.exit_code, 0, result.output) + for text in ["e9", "running", "Trained on version: 2", "detected", "37", "washer", "nut"]: + self.assertIn(text, result.stdout) + + @patch("roboflow.util.http.requests.post") + def test_text_handles_null_tags(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = { + **CREATED, + "reused": True, + "trainedOnVersion": None, + "leakage": None, + "classMismatch": None, + } + result = runner.invoke(app, CREATE_ARGS) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertIn("Reused: yes", result.stdout) + for text in ["unknown", "not checked", "Trained on", "Leakage", "Class"]: + self.assertNotIn(text, result.stdout) + + @patch("roboflow.util.http.requests.post") + def test_text_handles_unknown_leakage_without_splits(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = {**CREATED, "leakage": {"status": "unknown", "splits": None}} + result = runner.invoke(app, CREATE_ARGS) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertIn("Leakage: unknown", result.stdout) + + @patch("roboflow.util.http.requests.post") + def test_not_found_hint_names_the_inputs(self, mock_post): + mock_post.return_value = MagicMock(status_code=404) + mock_post.return_value.json.return_value = {"error": {"message": "Not found"}} + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 3) + hint = json.loads(result.stderr)["error"]["hint"] + for text in ["--model", "--project", "--version"]: + self.assertIn(text, hint) + self.assertIn("training-job:create", hint) + + @patch("roboflow.util.http.requests.post") + def test_access_hint_names_the_create_scope(self, mock_post): + mock_post.return_value = MagicMock(status_code=403) + mock_post.return_value.json.return_value = {"error": {"message": "Forbidden"}} + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 2) + self.assertIn("training-job:create", json.loads(result.stderr)["error"]["hint"]) + + @patch("roboflow.util.http.requests.post") + def test_blocked_lists_the_blocks_and_exits_6(self, mock_post): + blocks = [{"code": "preprocessing_mismatch", "message": "The preprocessing differs."}] + mock_post.return_value = MagicMock(status_code=409) + mock_post.return_value.json.return_value = { + "error": blocks[0]["message"], + "code": blocks[0]["code"], + "details": {"blocks": blocks}, + "retryable": False, + } + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 6) + error = json.loads(result.stderr)["error"] + self.assertIn("preprocessing_mismatch", error["message"]) + self.assertNotIn("hint", error) + + @patch("roboflow.util.http.requests.post") + def test_concurrency_limit_exits_7(self, mock_post): + mock_post.return_value = MagicMock(status_code=429) + mock_post.return_value.json.return_value = {"error": {"code": "eval_concurrency_limit", "message": "Wait."}} + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 7) + self.assertIn("hint", json.loads(result.stderr)["error"]) + + +class TestEvalCheckCompatibilityCommand(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_not_found_hint_names_the_scope(self, mock_post): + mock_post.return_value = MagicMock(status_code=404) + mock_post.return_value.json.return_value = {"error": {"message": "Not found"}} + result = runner.invoke( + app, + ["--json", "--api-key", "k", "--workspace", "ws", "eval", "check-compatibility", "-m", "m", "-p", "chess"], + ) + + self.assertEqual(result.exit_code, 3) + self.assertIn("training-job:create", json.loads(result.stderr)["error"]["hint"]) + + @patch("roboflow.util.http.requests.post") + def test_json_prints_the_full_response(self, mock_post): + compatibility_check = { + "allowed": True, + "blocks": [], + **{k: CREATED[k] for k in ("trainedOnVersion", "leakage", "classMismatch")}, + } + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = compatibility_check + result = runner.invoke( + app, + ["--json", "--api-key", "k", "--workspace", "ws", "eval", "check-compatibility", "-m", "m", "-p", "chess"], + ) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(json.loads(result.stdout), compatibility_check) + self.assertTrue(mock_post.call_args.args[0].endswith("/ws/model-evals/check-compatibility")) + + @patch("roboflow.util.http.requests.post") + def test_text_lists_blocks(self, mock_post): + mock_post.return_value = MagicMock(status_code=200) + mock_post.return_value.json.return_value = { + "allowed": False, + "blocks": [{"code": "instant_model", "message": "Instant models cannot be evaluated."}], + "trainedOnVersion": None, + "leakage": None, + "classMismatch": None, + } + result = runner.invoke( + app, ["--api-key", "k", "--workspace", "ws", "eval", "check-compatibility", "-m", "m", "-p", "chess"] + ) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertIn("Allowed: no", result.stdout) + self.assertIn("instant_model", result.stdout) + + class TestEvalCompareCommand(unittest.TestCase): @patch("roboflow.util.http.requests.get") def test_not_found_is_a_structured_error(self, mock_get): diff --git a/tests/test_model_eval.py b/tests/test_model_eval.py index 31c5fec6..22360cee 100644 --- a/tests/test_model_eval.py +++ b/tests/test_model_eval.py @@ -268,6 +268,52 @@ def test_compare_model_evaluations_returns_public_comparison(self, mock_compare) frontier_metric="mAP5095", ) + @patch("roboflow.adapters.rfapi.create_model_eval") + def test_create_model_evaluation_returns_the_full_response(self, mock_create): + created = {"evalId": "e9", "reused": True, "trainedOnVersion": "2", "leakage": None, "classMismatch": None} + mock_create.return_value = created + + result = _make_workspace().create_model_evaluation("ws/my-model", "chess", 5) + + self.assertEqual(result, created) + mock_create.assert_called_once_with( + "k", "lee-sandbox", model="ws/my-model", project="chess", version=5, rerun=False + ) + + @patch("roboflow.adapters.rfapi.create_model_eval") + def test_create_model_evaluation_forwards_rerun(self, mock_create): + _make_workspace().create_model_evaluation("m", "chess", 5, rerun=True) + + mock_create.assert_called_once_with("k", "lee-sandbox", model="m", project="chess", version=5, rerun=True) + + @patch("roboflow.adapters.rfapi.check_model_eval_compatibility") + def test_check_model_evaluation_compatibility_returns_the_full_response(self, mock_check): + compatibility_check = { + "allowed": True, + "blocks": [], + "trainedOnVersion": "2", + "leakage": None, + "classMismatch": None, + } + mock_check.return_value = compatibility_check + + result = _make_workspace().check_model_evaluation_compatibility("ws/my-model", "chess") + + self.assertEqual(result, compatibility_check) + mock_check.assert_called_once_with("k", "lee-sandbox", model="ws/my-model", project="chess", version=None) + + def test_eval_read_keeps_the_pre_flight_tags(self): + from roboflow.core.model_eval import ModelEval + + tags = { + "trainedOnVersion": "2", + "leakage": {"status": "unknown", "splits": None}, + "classMismatch": {"targetOnly": [], "modelOnly": ["nut"]}, + } + ev = ModelEval("k", "ws", "e1", info={"evalId": "e1", "versionId": "5", **tags}) + + self.assertEqual({key: ev.to_dict()[key] for key in tags}, tags) + @patch("roboflow.adapters.rfapi.list_model_evals") def test_evals_returns_modeleval_instances(self, mock_list): from roboflow.core.model_eval import ModelEval