From 070447ba4bdfe822ab0416864123a02ef5bcb51f Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 17:00:42 -0330 Subject: [PATCH 1/9] Add model eval create and pre-flight to the SDK Add rfapi.create_model_eval and rfapi.preflight_model_eval, and the Workspace methods create_model_evaluation and preflight_model_evaluation. Both return the full response. A 409 with blocks raises ModelEvalBlockedError. A 429 with eval_concurrency_limit raises ModelEvalConcurrencyLimitError. Co-Authored-By: Claude Fable 5.2 --- roboflow/adapters/rfapi.py | 76 ++++++++++++ roboflow/core/workspace.py | 50 ++++++++ tests/adapters/test_rfapi_model_evals.py | 147 +++++++++++++++++++++++ tests/test_model_eval.py | 32 +++++ 4 files changed, 305 insertions(+) diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 4b4fa8e1..f83486c2 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2320,6 +2320,21 @@ class ModelEvalAccessError(RoboflowError): """Raised when an evaluation read is not authorized (HTTP 401 or 403).""" +class ModelEvalBlockedError(RoboflowError): + """Raised when a pre-flight 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): """Raised when ``split`` is not one of the accepted values (HTTP 400).""" @@ -2342,6 +2357,7 @@ def _model_eval_error_for(response): """ code = None message = response.text + blocks = None try: body = response.json() if isinstance(body, dict): @@ -2349,6 +2365,8 @@ def _model_eval_error_for(response): if not isinstance(code, str): code = None message = body.get("message") or code or message + if isinstance(body.get("blocks"), list): + blocks = body["blocks"] except (ValueError, TypeError): pass @@ -2361,6 +2379,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 +2410,56 @@ 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) + return response.json() + + +def _eval_start_body(model, project, version): + body = {"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, +) -> 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``. + + Raises :class:`ModelEvalBlockedError` (409) and :class:`ModelEvalConcurrencyLimitError` (429). + """ + return _eval_post(api_key, workspace_url, "", _eval_start_body(model, project, version)) + + +def preflight_model_eval( + api_key: str, + workspace_url: str, + *, + model: str, + project: str, + version: Optional[Union[str, int]] = None, +) -> dict: + """POST /{workspace}/model-evals/preflight — 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, "/preflight", _eval_start_body(model, project, version)) + + def compare_model_evals( api_key: str, workspace_url: str, diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 60a8065d..e168d93f 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1643,6 +1643,56 @@ def compare_model_evaluations( frontier_metric=frontier_metric, ) + def create_model_evaluation( + self, + model: str, + project: str, + version: Optional[Union[str, int]] = None, + ) -> 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. + + 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``. + ``leakage`` and ``classMismatch`` never block the eval. They are ``None`` + when the eval has no pre-flight result. + + Raises: + roboflow.adapters.rfapi.ModelEvalBlockedError: The pre-flight check blocks the eval. + The ``blocks`` attribute lists the ``code`` and ``message`` of each block. + roboflow.adapters.rfapi.ModelEvalConcurrencyLimitError: The workspace has too many + active evals. + + Example: + >>> result = ws.create_model_evaluation("my-ws/my-model", "chess", 5) + >>> result["leakage"]["status"] + 'none' + """ + return rfapi.create_model_eval(self.__api_key, self.url, model=model, project=project, version=version) + + def preflight_model_evaluation( + 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`. + + Returns: + ``{allowed, blocks, trainedOnVersion, leakage, classMismatch}``. A blocked + request returns ``allowed: False`` with a ``blocks`` list. It does not raise. + """ + return rfapi.preflight_model_eval(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..26547890 100644 --- a/tests/adapters/test_rfapi_model_evals.py +++ b/tests/adapters/test_rfapi_model_evals.py @@ -248,5 +248,152 @@ 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_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": "preprocessing_mismatch", "message": "The preprocessing differs.", "blocks": BLOCKS} + ) + + 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": "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 TestPreflightModelEval(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_posts_to_preflight_and_returns_full_response(self, mock_post): + preflight = { + "allowed": True, + "blocks": [], + "trainedOnVersion": "2", + "leakage": CREATE_RESULT["leakage"], + "classMismatch": CREATE_RESULT["classMismatch"], + } + mock_post.return_value = _resp(200, preflight) + + result = rfapi.preflight_model_eval("k", "ws", model="ws/my-model", project="chess", version="5") + + self.assertEqual(result, preflight) + mock_post.assert_called_once_with( + f"{API_URL}/ws/model-evals/preflight", + 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_preflight_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.preflight_model_eval("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.preflight_model_eval("k", "ws", model="m", project="chess") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_model_eval.py b/tests/test_model_eval.py index 31c5fec6..d90e61ad 100644 --- a/tests/test_model_eval.py +++ b/tests/test_model_eval.py @@ -268,6 +268,38 @@ 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) + + @patch("roboflow.adapters.rfapi.preflight_model_eval") + def test_preflight_model_evaluation_returns_the_full_response(self, mock_preflight): + preflight = {"allowed": True, "blocks": [], "trainedOnVersion": "2", "leakage": None, "classMismatch": None} + mock_preflight.return_value = preflight + + result = _make_workspace().preflight_model_evaluation("ws/my-model", "chess") + + self.assertEqual(result, preflight) + mock_preflight.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 From 3d3ea6f04cccefd904cbfeba77f8ce466f10cace Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 17:00:43 -0330 Subject: [PATCH 2/9] Add eval create and eval preflight CLI commands Exit code 6 means a pre-flight block. Exit code 7 means the workspace concurrency limit. Document both commands in the changelog and the CLI quickstart. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 18 +++++ CLI-COMMANDS.md | 19 ++++++ roboflow/cli/handlers/eval.py | 110 ++++++++++++++++++++++++++++++- tests/cli/test_eval_handler.py | 117 +++++++++++++++++++++++++++++++++ 4 files changed, 263 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0646637c..89c07690 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ 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.preflight_model_evaluation(...)` returns `{allowed, blocks, ...}` and starts no job. + Leakage and class mismatch never block an eval. They are tags on the result. + The tags are `None` on evals that had no pre-flight check. + A blocked request raises `ModelEvalBlockedError` with a `blocks` list. + A full workspace raises `ModelEvalConcurrencyLimitError`. + The CLI is `roboflow eval create` and `roboflow eval preflight` + (`-m -p [-v ]`). + Exit code 6 means blocked. Exit code 7 means the concurrency limit. + The eval reads (`roboflow eval get`, `Workspace.eval`) keep the same three tags. + Needs the `POST /{workspace}/model-evals` API. + ## 1.7.5 ### Added diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 72f0ea16..3ac57b18 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -496,6 +496,25 @@ 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 preflight -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. +The tags are `null` when no pre-flight result exists. +`create` returns `reused: true` when an eval for the same model, version and +settings is pending, running or done. +Exit code `6` means a pre-flight block (the `blocks` list is in the error). +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/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index e55d556d..40968b10 100644 --- a/roboflow/cli/handlers/eval.py +++ b/roboflow/cli/handlers/eval.py @@ -24,6 +24,40 @@ # --------------------------------------------------------------------------- +@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, +) -> None: + """Evaluate a model on a dataset version of its project.""" + args = ctx_to_args(ctx, model=model, project=project, version=version) + _create_eval(args) + + +@eval_app.command("preflight") +def preflight_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) + _preflight_eval(args) + + @eval_app.command("compare") def compare_evals_cmd( ctx: typer.Context, @@ -183,7 +217,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 + pre-flight 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 +232,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 @@ -214,9 +253,78 @@ def _hint_for(exc: Exception) -> Optional[str]: return "Use one of: train, valid, test (or 'all' where supported)." if isinstance(exc, rfapi.InvalidConfidenceError): return "Pass an integer between 0 and 100." + if isinstance(exc, rfapi.ModelEvalBlockedError): + return "Run 'roboflow eval preflight' to see the blocks. Pick a version with the same preprocessing." + 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 pre-flight tags: trained-on version, leakage and class mismatch.""" + lines = [f" Trained on version: {result.get('trainedOnVersion') or 'unknown'}"] + leakage = result.get("leakage") + if leakage is None: + lines.append(" Leakage: not checked") + else: + 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 None: + lines.append(" Class mismatch: not checked") + else: + 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 + ) + except Exception as exc: + output_error(args, str(exc), hint=_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 _preflight_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.preflight_model_eval( + api_key, workspace_url, model=args.model, project=args.project, version=args.version + ) + except Exception as exc: + output_error(args, str(exc), hint=_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/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 2a982bb0..1600be33 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", + "preflight", "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,119 @@ 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_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) + + @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": "preprocessing_mismatch", "message": "x", "blocks": blocks} + result = runner.invoke(app, ["--json", *CREATE_ARGS]) + + self.assertEqual(result.exit_code, 6) + self.assertIn("preprocessing_mismatch", json.loads(result.stderr)["error"]["message"]) + + @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": "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 TestEvalPreflightCommand(unittest.TestCase): + @patch("roboflow.util.http.requests.post") + def test_json_prints_the_full_response(self, mock_post): + preflight = { + "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 = preflight + result = runner.invoke( + app, ["--json", "--api-key", "k", "--workspace", "ws", "eval", "preflight", "-m", "m", "-p", "chess"] + ) + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(json.loads(result.stdout), preflight) + self.assertTrue(mock_post.call_args.args[0].endswith("/ws/model-evals/preflight")) + + @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", "preflight", "-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): From 51d9d99283d7237a9068182c8f1c992db5e3584a Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 17:54:07 -0330 Subject: [PATCH 3/9] Add rerun to the model eval create operation With rerun, a done eval does not satisfy the request, so a new eval starts. A pending or running eval still returns with reused true. Pre-flight does not take the field. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 ++ CLI-COMMANDS.md | 3 ++- roboflow/adapters/rfapi.py | 12 +++++++++--- roboflow/cli/handlers/eval.py | 7 +++++-- roboflow/core/workspace.py | 9 ++++++++- tests/adapters/test_rfapi_model_evals.py | 12 ++++++++++++ tests/cli/test_eval_handler.py | 17 +++++++++++++++++ tests/test_model_eval.py | 10 +++++++++- 8 files changed, 64 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89c07690..d7427b19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ All notable changes to this project will be documented in this file. `Workspace.create_model_evaluation(model, project, version=None)` starts the eval and returns `{evalId, status, reused, version, trainedOnVersion, leakage, classMismatch}`. `Workspace.preflight_model_evaluation(...)` 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. The tags are `None` on evals that had no pre-flight check. A blocked request raises `ModelEvalBlockedError` with a `blocks` list. diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 3ac57b18..231c0f8d 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -510,7 +510,8 @@ Both commands return `trainedOnVersion`, `leakage` and `classMismatch`. Leakage and class mismatch never block an eval. The eval runs with these tags. The tags are `null` when no pre-flight result exists. `create` returns `reused: true` when an eval for the same model, version and -settings is pending, running or done. +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 pre-flight block (the `blocks` list is in the error). Exit code `7` means the workspace has too many active evals. Requires the `training-job:create` scope and workspace Model Evaluation access. diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index f83486c2..76b93853 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2420,7 +2420,7 @@ def _eval_post(api_key, workspace_url, path, body): def _eval_start_body(model, project, version): - body = {"modelId": model, "project": project} + body: Dict[str, Any] = {"modelId": model, "project": project} if version is not None: body["version"] = str(version) return body @@ -2433,16 +2433,22 @@ def create_model_eval( 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``. + 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) and :class:`ModelEvalConcurrencyLimitError` (429). """ - return _eval_post(api_key, workspace_url, "", _eval_start_body(model, project, version)) + body = _eval_start_body(model, project, version) + if rerun: + body["rerun"] = True + return _eval_post(api_key, workspace_url, "", body) def preflight_model_eval( diff --git a/roboflow/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index 40968b10..f6c3ab3e 100644 --- a/roboflow/cli/handlers/eval.py +++ b/roboflow/cli/handlers/eval.py @@ -35,9 +35,12 @@ def create_eval_cmd( "-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) + args = ctx_to_args(ctx, model=model, project=project, version=version, rerun=rerun) _create_eval(args) @@ -289,7 +292,7 @@ def _create_eval(args): # noqa: ANN001 workspace_url, api_key = resolved try: result = rfapi.create_model_eval( - api_key, workspace_url, model=args.model, project=args.project, version=args.version + 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=_hint_for(exc), exit_code=_eval_error_exit_code(exc)) diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index e168d93f..6ba65dd1 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1648,6 +1648,7 @@ def create_model_evaluation( model: str, project: str, version: Optional[Union[str, int]] = None, + rerun: bool = False, ) -> dict: """Evaluate a model on a dataset version of its project. @@ -1656,11 +1657,15 @@ def create_model_evaluation( 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. They are ``None`` when the eval has no pre-flight result. @@ -1675,7 +1680,9 @@ def create_model_evaluation( >>> result["leakage"]["status"] 'none' """ - return rfapi.create_model_eval(self.__api_key, self.url, model=model, project=project, version=version) + return rfapi.create_model_eval( + self.__api_key, self.url, model=model, project=project, version=version, rerun=rerun + ) def preflight_model_evaluation( self, diff --git a/tests/adapters/test_rfapi_model_evals.py b/tests/adapters/test_rfapi_model_evals.py index 26547890..e42009c7 100644 --- a/tests/adapters/test_rfapi_model_evals.py +++ b/tests/adapters/test_rfapi_model_evals.py @@ -292,6 +292,18 @@ def test_omits_version_when_not_given(self, mock_post): 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} diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 1600be33..d1d04af7 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -446,6 +446,23 @@ def test_json_prints_the_full_response(self, mock_post): 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) diff --git a/tests/test_model_eval.py b/tests/test_model_eval.py index d90e61ad..d29a7ff1 100644 --- a/tests/test_model_eval.py +++ b/tests/test_model_eval.py @@ -276,7 +276,15 @@ def test_create_model_evaluation_returns_the_full_response(self, mock_create): 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) + 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.preflight_model_eval") def test_preflight_model_evaluation_returns_the_full_response(self, mock_preflight): From e164756af63a67087243d229dd42654aca59b677 Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 19:15:16 -0330 Subject: [PATCH 4/9] Fix start-command hints and null tag output for model evals Give eval create and eval preflight their own error hints. Do not print null tags as unknown or not checked. Correct the docs for null tags, the blocked --json output, and the pre-flight arguments. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 8 +++++--- CLI-COMMANDS.md | 6 ++++-- roboflow/adapters/rfapi.py | 4 ++-- roboflow/cli/handlers/eval.py | 37 ++++++++++++++++++++-------------- roboflow/core/workspace.py | 13 +++++++----- tests/cli/test_eval_handler.py | 35 +++++++++++++++++++++++++++++++- 6 files changed, 75 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d7427b19..4f5b6ff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,16 @@ All notable changes to this project will be documented in this file. `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. - The tags are `None` on evals that had no pre-flight check. + The tags are `None` when the eval has no pre-flight result or runs on the version the model trained on. 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 preflight` (`-m -p [-v ]`). Exit code 6 means blocked. Exit code 7 means the concurrency limit. - The eval reads (`roboflow eval get`, `Workspace.eval`) keep the same three tags. - Needs the `POST /{workspace}/model-evals` API. + `Workspace.eval` and `roboflow eval get --json` keep the same three tags. + Needs the `POST /{workspace}/model-evals` and `POST /{workspace}/model-evals/preflight` APIs + ([#591](https://github.com/roboflow/roboflow-python/pull/591)). ## 1.7.5 diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 231c0f8d..68ae591e 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -508,11 +508,13 @@ 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. -The tags are `null` when no pre-flight result exists. +The tags are `null` when the eval has no pre-flight result or runs on the version the model trained on. +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 pre-flight block (the `blocks` list is in the error). +Exit code `6` means a pre-flight block. The error message lists each block. +Run `eval preflight --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. diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 76b93853..ef07fcc4 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,7 @@ 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): diff --git a/roboflow/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index f6c3ab3e..1f650649 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) # --------------------------------------------------------------------------- @@ -256,27 +256,34 @@ def _hint_for(exc: Exception) -> Optional[str]: return "Use one of: train, valid, test (or 'all' where supported)." if isinstance(exc, rfapi.InvalidConfidenceError): return "Pass an integer between 0 and 100." - if isinstance(exc, rfapi.ModelEvalBlockedError): - return "Run 'roboflow eval preflight' to see the blocks. Pick a version with the same preprocessing." + return None + + +def _start_hint_for(exc: Exception) -> Optional[str]: + """Hint for ``eval create`` and ``eval preflight`` errors. A blocked error has none: its message lists them.""" + 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." 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 pre-flight tags: trained-on version, leakage and class mismatch.""" - lines = [f" Trained on version: {result.get('trainedOnVersion') or 'unknown'}"] + """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 None: - lines.append(" Leakage: not checked") - else: + 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 None: - lines.append(" Class mismatch: not checked") - else: + 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 @@ -295,7 +302,7 @@ def _create_eval(args): # noqa: ANN001 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=_hint_for(exc), exit_code=_eval_error_exit_code(exc)) + output_error(args, str(exc), hint=_start_hint_for(exc), exit_code=_eval_error_exit_code(exc)) return lines = [ f"Eval: {result['evalId']}", @@ -320,7 +327,7 @@ def _preflight_eval(args): # noqa: ANN001 api_key, workspace_url, model=args.model, project=args.project, version=args.version ) except Exception as exc: - output_error(args, str(exc), hint=_hint_for(exc), exit_code=_eval_error_exit_code(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"]) diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 6ba65dd1..a513d687 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1666,19 +1666,22 @@ def create_model_evaluation( 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. They are ``None`` - when the eval has no pre-flight result. + ``leakage`` and ``classMismatch`` never block the eval. The three tags are + ``None`` when the eval has no pre-flight result or runs on the version the + model trained on. Raises: roboflow.adapters.rfapi.ModelEvalBlockedError: The pre-flight check blocks the eval. The ``blocks`` attribute lists the ``code`` and ``message`` of each block. roboflow.adapters.rfapi.ModelEvalConcurrencyLimitError: The workspace has too many active evals. + roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist. + 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["leakage"]["status"] - 'none' + >>> result["reused"] + False """ return rfapi.create_model_eval( self.__api_key, self.url, model=model, project=project, version=version, rerun=rerun @@ -1692,7 +1695,7 @@ def preflight_model_evaluation( ) -> dict: """Check an evaluation request without starting it. - Takes the same arguments as :meth:`create_model_evaluation`. + Takes the same arguments as :meth:`create_model_evaluation`, except ``rerun``. Returns: ``{allowed, blocks, trainedOnVersion, leakage, classMismatch}``. A blocked diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index d1d04af7..133d7d09 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -487,6 +487,37 @@ def test_text_handles_null_tags(self, mock_post): self.assertEqual(result.exit_code, 0, result.output) self.assertIn("Reused: yes", result.stdout) + for text in ["unknown", "not checked", "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) + + @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): @@ -496,7 +527,9 @@ def test_blocked_lists_the_blocks_and_exits_6(self, mock_post): result = runner.invoke(app, ["--json", *CREATE_ARGS]) self.assertEqual(result.exit_code, 6) - self.assertIn("preprocessing_mismatch", json.loads(result.stderr)["error"]["message"]) + 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): From f1cd8f9fbd54a6142b11c51607cd3326eb7067ad Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 19:41:11 -0330 Subject: [PATCH 5/9] Name the missing scope in the eval start hints A key without the training-job:create scope gets a 404, so the not-found hint names both causes. State the null tag rule once, list the errors that create and pre-flight can raise, and test the pre-flight hint. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- CLI-COMMANDS.md | 2 +- roboflow/adapters/rfapi.py | 3 ++- roboflow/cli/handlers/eval.py | 4 +++- roboflow/core/workspace.py | 12 ++++++++---- tests/cli/test_eval_handler.py | 14 +++++++++++++- 6 files changed, 28 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5b6ff4..fced586b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ All notable changes to this project will be documented in this file. `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. - The tags are `None` when the eval has no pre-flight result or runs on the version the model trained on. + A tag is `None` when it has no value: for the training version, a model with no training version, a blocked request, or an eval with no pre-flight. A blocked request raises `ModelEvalBlockedError` with a `blocks` list. `ModelEvalNotFoundError` and `ModelEvalAccessError` now cover these requests too. A full workspace raises `ModelEvalConcurrencyLimitError`. diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 68ae591e..4d7b9576 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -508,7 +508,7 @@ 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. -The tags are `null` when the eval has no pre-flight result or runs on the version the model trained on. +A tag is `null` when it has no value: for the training version, a model with no training version, a blocked request, or an eval with no pre-flight. 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 diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index ef07fcc4..ec63df8a 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2443,7 +2443,8 @@ def create_model_eval( 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) and :class:`ModelEvalConcurrencyLimitError` (429). + 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: diff --git a/roboflow/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index 1f650649..e6ba6492 100644 --- a/roboflow/cli/handlers/eval.py +++ b/roboflow/cli/handlers/eval.py @@ -266,7 +266,9 @@ def _start_hint_for(exc: Exception) -> Optional[str]: 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." + 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 diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index a513d687..461d0ca5 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1666,9 +1666,9 @@ def create_model_evaluation( 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. The three tags are - ``None`` when the eval has no pre-flight result or runs on the version the - model trained on. + ``leakage`` and ``classMismatch`` never block the eval. A tag is ``None`` + when it has no value: for the training version, a model with no training + version, a blocked request, or an eval with no pre-flight. Raises: roboflow.adapters.rfapi.ModelEvalBlockedError: The pre-flight check blocks the eval. @@ -1699,7 +1699,11 @@ def preflight_model_evaluation( Returns: ``{allowed, blocks, trainedOnVersion, leakage, classMismatch}``. A blocked - request returns ``allowed: False`` with a ``blocks`` list. It does not raise. + request returns ``allowed: False`` with a ``blocks`` list. It does not raise for a block. + + Raises: + roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist. + roboflow.adapters.rfapi.ModelEvalAccessError: The API key or workspace has no access. """ return rfapi.preflight_model_eval(self.__api_key, self.url, model=model, project=project, version=version) diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 133d7d09..8720739c 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -487,7 +487,7 @@ def test_text_handles_null_tags(self, mock_post): self.assertEqual(result.exit_code, 0, result.output) self.assertIn("Reused: yes", result.stdout) - for text in ["unknown", "not checked", "Leakage", "Class"]: + for text in ["unknown", "not checked", "Trained on", "Leakage", "Class"]: self.assertNotIn(text, result.stdout) @patch("roboflow.util.http.requests.post") @@ -509,6 +509,7 @@ def test_not_found_hint_names_the_inputs(self, mock_post): 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): @@ -542,6 +543,17 @@ def test_concurrency_limit_exits_7(self, mock_post): class TestEvalPreflightCommand(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", "preflight", "-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): preflight = { From d181d2b88430d3c82485de5e0c21f826c32a23d0 Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Thu, 26 Nov 2026 20:05:29 -0330 Subject: [PATCH 6/9] Correct the null tag wording and the not-found error text A blocked pre-flight can return tags with values, so the null tag sentence no longer lists it. The not-found error also covers a key without the training-job:create scope. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- CLI-COMMANDS.md | 2 +- roboflow/core/workspace.py | 9 +++++---- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fced586b..499b91f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ All notable changes to this project will be documented in this file. `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 it has no value: for the training version, a model with no training version, a blocked request, or an eval with no pre-flight. + 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`. diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 4d7b9576..28a2d25a 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -508,7 +508,7 @@ 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 it has no value: for the training version, a model with no training version, a blocked request, or an eval with no pre-flight. +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 diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 461d0ca5..28748556 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1667,15 +1667,15 @@ def create_model_evaluation( 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 it has no value: for the training version, a model with no training - version, a blocked request, or an eval with no pre-flight. + when the platform has no value for it, for example for the training version. Raises: roboflow.adapters.rfapi.ModelEvalBlockedError: The pre-flight check blocks the eval. The ``blocks`` attribute lists the ``code`` and ``message`` of each block. roboflow.adapters.rfapi.ModelEvalConcurrencyLimitError: The workspace has too many active evals. - roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist. + 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: @@ -1702,7 +1702,8 @@ def preflight_model_evaluation( request returns ``allowed: False`` with a ``blocks`` list. It does not raise for a block. Raises: - roboflow.adapters.rfapi.ModelEvalNotFoundError: The model, project or version does not exist. + 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.preflight_model_eval(self.__api_key, self.url, model=model, project=project, version=version) From 04159a20848cde50993ad9d36215af80094d0b1a Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Fri, 27 Nov 2026 10:49:03 -0330 Subject: [PATCH 7/9] Rename the model eval pre-flight operation to check compatibility The operation checks if a model is compatible with a dataset version. Use one term for it: the check-compatibility route, the check_model_evaluation_compatibility method and the eval check-compatibility command. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 6 +++--- CLI-COMMANDS.md | 6 +++--- roboflow/adapters/rfapi.py | 8 ++++---- roboflow/cli/handlers/eval.py | 14 +++++++------- roboflow/core/workspace.py | 8 +++++--- tests/adapters/test_rfapi_model_evals.py | 20 ++++++++++---------- tests/cli/test_eval_handler.py | 20 +++++++++++--------- tests/test_model_eval.py | 20 +++++++++++++------- 8 files changed, 56 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 499b91f2..b0ffbf2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project will be documented in this file. - 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.preflight_model_evaluation(...)` returns `{allowed, blocks, ...}` and starts no job. + `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. @@ -17,11 +17,11 @@ All notable changes to this project will be documented in this file. 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 preflight` + 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/preflight` APIs + 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 diff --git a/CLI-COMMANDS.md b/CLI-COMMANDS.md index 28a2d25a..59273ebe 100644 --- a/CLI-COMMANDS.md +++ b/CLI-COMMANDS.md @@ -500,7 +500,7 @@ without parsing message strings: `2` for authentication or access errors (401/40 ```bash # Check the request first. This starts no job. -roboflow eval preflight -m my-workspace/my-model -p my-project -v 5 --json +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 @@ -513,8 +513,8 @@ 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 pre-flight block. The error message lists each block. -Run `eval preflight --json` for the structured `blocks` list. +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. diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index ec63df8a..73f68719 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2321,7 +2321,7 @@ class ModelEvalAccessError(RoboflowError): class ModelEvalBlockedError(RoboflowError): - """Raised when a pre-flight check blocks the eval (HTTP 409 with ``blocks``). + """Raised when a compatibility check blocks the eval (HTTP 409 with ``blocks``). ``blocks`` is the server list of ``{"code": ..., "message": ...}`` dicts. """ @@ -2452,7 +2452,7 @@ def create_model_eval( return _eval_post(api_key, workspace_url, "", body) -def preflight_model_eval( +def check_model_eval_compatibility( api_key: str, workspace_url: str, *, @@ -2460,11 +2460,11 @@ def preflight_model_eval( project: str, version: Optional[Union[str, int]] = None, ) -> dict: - """POST /{workspace}/model-evals/preflight — check an eval request without starting it. + """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, "/preflight", _eval_start_body(model, project, version)) + return _eval_post(api_key, workspace_url, "/check-compatibility", _eval_start_body(model, project, version)) def compare_model_evals( diff --git a/roboflow/cli/handlers/eval.py b/roboflow/cli/handlers/eval.py index e6ba6492..a1c2fbac 100644 --- a/roboflow/cli/handlers/eval.py +++ b/roboflow/cli/handlers/eval.py @@ -44,8 +44,8 @@ def create_eval_cmd( _create_eval(args) -@eval_app.command("preflight") -def preflight_eval_cmd( +@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")], @@ -58,7 +58,7 @@ def preflight_eval_cmd( ) -> None: """Check an evaluation request without starting it.""" args = ctx_to_args(ctx, model=model, project=project, version=version) - _preflight_eval(args) + _check_compatibility_eval(args) @eval_app.command("compare") @@ -221,7 +221,7 @@ def _eval_error_exit_code(exc: Exception) -> int: 1 = general; 2 = auth; 3 = not found; 4 = conflict (eval not done); 5 = invalid argument (bad split / confidence); 6 = eval blocked by a - pre-flight check; 7 = workspace eval concurrency limit. Keeping these distinct + 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. """ @@ -260,7 +260,7 @@ def _hint_for(exc: Exception) -> Optional[str]: def _start_hint_for(exc: Exception) -> Optional[str]: - """Hint for ``eval create`` and ``eval preflight`` errors. A blocked error has none: its message lists them.""" + """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): @@ -316,7 +316,7 @@ def _create_eval(args): # noqa: ANN001 output(args, result, text="\n".join(lines)) -def _preflight_eval(args): # noqa: ANN001 +def _check_compatibility_eval(args): # noqa: ANN001 from roboflow.adapters import rfapi from roboflow.cli._output import output, output_error @@ -325,7 +325,7 @@ def _preflight_eval(args): # noqa: ANN001 return workspace_url, api_key = resolved try: - result = rfapi.preflight_model_eval( + result = rfapi.check_model_eval_compatibility( api_key, workspace_url, model=args.model, project=args.project, version=args.version ) except Exception as exc: diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index 28748556..c13b5597 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1670,7 +1670,7 @@ def create_model_evaluation( when the platform has no value for it, for example for the training version. Raises: - roboflow.adapters.rfapi.ModelEvalBlockedError: The pre-flight check blocks the eval. + roboflow.adapters.rfapi.ModelEvalBlockedError: The compatibility check blocks the eval. The ``blocks`` attribute lists the ``code`` and ``message`` of each block. roboflow.adapters.rfapi.ModelEvalConcurrencyLimitError: The workspace has too many active evals. @@ -1687,7 +1687,7 @@ def create_model_evaluation( self.__api_key, self.url, model=model, project=project, version=version, rerun=rerun ) - def preflight_model_evaluation( + def check_model_evaluation_compatibility( self, model: str, project: str, @@ -1706,7 +1706,9 @@ def preflight_model_evaluation( or the API key has no ``training-job:create`` scope. roboflow.adapters.rfapi.ModelEvalAccessError: The API key or workspace has no access. """ - return rfapi.preflight_model_eval(self.__api_key, self.url, model=model, project=project, version=version) + 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 e42009c7..8132bafa 100644 --- a/tests/adapters/test_rfapi_model_evals.py +++ b/tests/adapters/test_rfapi_model_evals.py @@ -364,30 +364,30 @@ def test_404_raises_not_found_error(self, mock_post): rfapi.create_model_eval("k", "ws", model="m", project="chess") -class TestPreflightModelEval(unittest.TestCase): +class TestCheckModelEvalCompatibility(unittest.TestCase): @patch("roboflow.util.http.requests.post") - def test_posts_to_preflight_and_returns_full_response(self, mock_post): - preflight = { + 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, preflight) + mock_post.return_value = _resp(200, compatibility_check) - result = rfapi.preflight_model_eval("k", "ws", model="ws/my-model", project="chess", version="5") + result = rfapi.check_model_eval_compatibility("k", "ws", model="ws/my-model", project="chess", version="5") - self.assertEqual(result, preflight) + self.assertEqual(result, compatibility_check) mock_post.assert_called_once_with( - f"{API_URL}/ws/model-evals/preflight", + 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_preflight_is_a_result_not_an_error(self, mock_post): + def test_a_blocked_check_is_a_result_not_an_error(self, mock_post): blocked = { "allowed": False, "blocks": BLOCKS[:1], @@ -397,14 +397,14 @@ def test_a_blocked_preflight_is_a_result_not_an_error(self, mock_post): } mock_post.return_value = _resp(200, blocked) - self.assertEqual(rfapi.preflight_model_eval("k", "ws", model="m", project="chess"), 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.preflight_model_eval("k", "ws", model="m", project="chess") + rfapi.check_model_eval_compatibility("k", "ws", model="m", project="chess") if __name__ == "__main__": diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 8720739c..7f48afc0 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -35,7 +35,7 @@ def test_eval_root_help(self) -> None: def test_each_subcommand_help(self) -> None: for cmd in [ "create", - "preflight", + "check-compatibility", "list", "get", "map-results", @@ -542,13 +542,14 @@ def test_concurrency_limit_exits_7(self, mock_post): self.assertIn("hint", json.loads(result.stderr)["error"]) -class TestEvalPreflightCommand(unittest.TestCase): +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", "preflight", "-m", "m", "-p", "chess"] + app, + ["--json", "--api-key", "k", "--workspace", "ws", "eval", "check-compatibility", "-m", "m", "-p", "chess"], ) self.assertEqual(result.exit_code, 3) @@ -556,20 +557,21 @@ def test_not_found_hint_names_the_scope(self, mock_post): @patch("roboflow.util.http.requests.post") def test_json_prints_the_full_response(self, mock_post): - preflight = { + 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 = preflight + mock_post.return_value.json.return_value = compatibility_check result = runner.invoke( - app, ["--json", "--api-key", "k", "--workspace", "ws", "eval", "preflight", "-m", "m", "-p", "chess"] + 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), preflight) - self.assertTrue(mock_post.call_args.args[0].endswith("/ws/model-evals/preflight")) + 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): @@ -582,7 +584,7 @@ def test_text_lists_blocks(self, mock_post): "classMismatch": None, } result = runner.invoke( - app, ["--api-key", "k", "--workspace", "ws", "eval", "preflight", "-m", "m", "-p", "chess"] + app, ["--api-key", "k", "--workspace", "ws", "eval", "check-compatibility", "-m", "m", "-p", "chess"] ) self.assertEqual(result.exit_code, 0, result.output) diff --git a/tests/test_model_eval.py b/tests/test_model_eval.py index d29a7ff1..22360cee 100644 --- a/tests/test_model_eval.py +++ b/tests/test_model_eval.py @@ -286,15 +286,21 @@ def test_create_model_evaluation_forwards_rerun(self, mock_create): mock_create.assert_called_once_with("k", "lee-sandbox", model="m", project="chess", version=5, rerun=True) - @patch("roboflow.adapters.rfapi.preflight_model_eval") - def test_preflight_model_evaluation_returns_the_full_response(self, mock_preflight): - preflight = {"allowed": True, "blocks": [], "trainedOnVersion": "2", "leakage": None, "classMismatch": None} - mock_preflight.return_value = preflight + @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().preflight_model_evaluation("ws/my-model", "chess") + result = _make_workspace().check_model_evaluation_compatibility("ws/my-model", "chess") - self.assertEqual(result, preflight) - mock_preflight.assert_called_once_with("k", "lee-sandbox", model="ws/my-model", project="chess", version=None) + 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 From 8cbe7e1a5938ec749155400f3662940ae378acc8 Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Fri, 27 Nov 2026 17:20:53 -0330 Subject: [PATCH 8/9] Read the new error bodies of the model eval start call A blocked start returns the message in error, the code in code and the blocks in details.blocks. The concurrency limit returns a nested error object. The exception types and attributes stay the same. Co-Authored-By: Claude Fable 5.2 --- roboflow/adapters/rfapi.py | 26 ++++++++++++++++-------- roboflow/core/workspace.py | 2 ++ tests/adapters/test_rfapi_model_evals.py | 10 +++++++-- tests/cli/test_eval_handler.py | 9 ++++++-- 4 files changed, 35 insertions(+), 12 deletions(-) diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 73f68719..331e4aaa 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2346,14 +2346,18 @@ class InvalidConfidenceError(RoboflowError): def _model_eval_error_for(response): """Translate a model-eval error response into the right RoboflowError subclass. - The model-eval REST surface returns errors as a flat envelope:: + The model-eval read routes return a flat envelope:: {"error": "", "message": ""} + The create routes 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 @@ -2361,12 +2365,18 @@ def _model_eval_error_for(response): 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 - if isinstance(body.get("blocks"), list): - blocks = body["blocks"] + error = body.get("error") + if isinstance(error, dict): + code, text = error.get("code"), error.get("message") + elif "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 isinstance(details, dict) and isinstance(details.get("blocks"), list): + blocks = details["blocks"] except (ValueError, TypeError): pass diff --git a/roboflow/core/workspace.py b/roboflow/core/workspace.py index c13b5597..e09792b5 100644 --- a/roboflow/core/workspace.py +++ b/roboflow/core/workspace.py @@ -1672,6 +1672,7 @@ def create_model_evaluation( 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, @@ -1700,6 +1701,7 @@ def check_model_evaluation_compatibility( 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, diff --git a/tests/adapters/test_rfapi_model_evals.py b/tests/adapters/test_rfapi_model_evals.py index 8132bafa..76a7d0db 100644 --- a/tests/adapters/test_rfapi_model_evals.py +++ b/tests/adapters/test_rfapi_model_evals.py @@ -317,7 +317,13 @@ def test_keeps_null_tags_of_a_reused_eval(self, mock_post): @patch("roboflow.util.http.requests.post") def test_409_raises_blocked_error_with_blocks(self, mock_post): mock_post.return_value = _resp( - 409, {"error": "preprocessing_mismatch", "message": "The preprocessing differs.", "blocks": BLOCKS} + 409, + { + "error": BLOCKS[0]["message"], + "code": BLOCKS[0]["code"], + "details": {"blocks": BLOCKS}, + "retryable": False, + }, ) with self.assertRaises(rfapi.ModelEvalBlockedError) as ctx: @@ -331,7 +337,7 @@ def test_409_raises_blocked_error_with_blocks(self, mock_post): @patch("roboflow.util.http.requests.post") def test_429_raises_concurrency_limit_error(self, mock_post): mock_post.return_value = _resp( - 429, {"error": "eval_concurrency_limit", "message": "10 evaluations are active."} + 429, {"error": {"code": "eval_concurrency_limit", "message": "10 evaluations are active."}} ) with self.assertRaises(rfapi.ModelEvalConcurrencyLimitError) as ctx: diff --git a/tests/cli/test_eval_handler.py b/tests/cli/test_eval_handler.py index 7f48afc0..343867d2 100644 --- a/tests/cli/test_eval_handler.py +++ b/tests/cli/test_eval_handler.py @@ -524,7 +524,12 @@ def test_access_hint_names_the_create_scope(self, mock_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": "preprocessing_mismatch", "message": "x", "blocks": blocks} + 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) @@ -535,7 +540,7 @@ def test_blocked_lists_the_blocks_and_exits_6(self, mock_post): @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": "eval_concurrency_limit", "message": "Wait."} + 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) From 8bb87580559062240751b64b695c4d39870582f2 Mon Sep 17 00:00:00 2001 From: Lee Clement Date: Fri, 27 Nov 2026 17:31:25 -0330 Subject: [PATCH 9/9] Limit the nested error reading to the model eval start calls The read routes keep their released error text and --json output for a body with a nested error object. Only create and the compatibility check read the new bodies. Co-Authored-By: Claude Fable 5.2 --- roboflow/adapters/rfapi.py | 18 +++++++++--------- tests/adapters/test_rfapi_model_evals.py | 11 +++++++++++ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/roboflow/adapters/rfapi.py b/roboflow/adapters/rfapi.py index 331e4aaa..11d3577c 100644 --- a/roboflow/adapters/rfapi.py +++ b/roboflow/adapters/rfapi.py @@ -2343,16 +2343,16 @@ 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 read routes return a flat envelope:: + The read routes return a flat envelope:: {"error": "", "message": ""} - The create routes return ``{"error": "", "code": "", "details": {"blocks": [...]}}`` - for a blocked start and ``{"error": {"code": "", "message": ""}}`` for the - concurrency limit. + 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 @@ -2366,16 +2366,16 @@ def _model_eval_error_for(response): body = response.json() if isinstance(body, dict): error = body.get("error") - if isinstance(error, dict): + if start and isinstance(error, dict): code, text = error.get("code"), error.get("message") - elif "code" in body: + 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 isinstance(details, dict) and isinstance(details.get("blocks"), list): + if start and isinstance(details, dict) and isinstance(details.get("blocks"), list): blocks = details["blocks"] except (ValueError, TypeError): pass @@ -2425,7 +2425,7 @@ def _eval_post(api_key, workspace_url, path, body): 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) + raise _model_eval_error_for(response, start=True) return response.json() diff --git a/tests/adapters/test_rfapi_model_evals.py b/tests/adapters/test_rfapi_model_evals.py index 76a7d0db..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"})