Skip to content

Unclear error message when running plan without parameters #206

Closed

Description

@joeshannon

When the controller run subcommand is executed without providing any parameters (-p), the following is returned:

$ blueapi controller run scan
Traceback (most recent call last):
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/bin/blueapi", line 8, in <module>
    sys.exit(main())
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/src/blueapi/cli/cli.py", line 67, in wrapper
    func(*args, **kwargs)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/venv/lib/python3.10/site-packages/click/decorators.py", line 38, in new_func
    return f(get_current_context().obj, *args, **kwargs)
  File "/scratch/30day_tmp/delete15may/bs/blueapi/src/blueapi/cli/cli.py", line 106, in run_plan
    json=json.loads(parameters),
  File "/dls_sw/apps/python/miniforge/4.10.0-0/envs/python3.10/lib/python3.10/json/__init__.py", line 339, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

This is not particularly user friendly, if parameters are always required, can this be made into a mandatory argument?

Activity

  1. changed the title [-]Unclear error message when running plan without data[/-] [+]Unclear error message when running plan without parameters[/+] on May 16, 2023
  2. added
    bug
    onboarding
    on May 16, 2023
  3. tpoliaw commented on May 16, 2023

    @tpoliaw
    Contributor

    This was annoying me as well. Potentially fixed in #207

  4. callumforrester commented on Feb 7, 2024

    @callumforrester
    Contributor

    This is now a 500 internal server error from a client perspective, which isn't much better

  5. tpoliaw commented on Feb 7, 2024

    @tpoliaw
    Contributor

    Has the server side handling of it changed? If parameters are needed it should be at least a 4xx error

  6. callumforrester commented on Feb 7, 2024

    @callumforrester
    Contributor

    I believe so, and agreed, and also the CLI should translate HTTP codes into human-readable error messages

  7. stan-dot commented on Feb 16, 2024

    @stan-dot
    Contributor

    debugging the error in parallel server and client side,

    here the server
    image

    here the client
    image

  8. stan-dot commented on Feb 16, 2024

    @stan-dot
    Contributor

    at the moment the cli raises an error only in two cases:

    image

    yet the error text is about a pickle operation, so a different one from the May 2023 original post. I cannot be sure if this is an issue with setup on my end or just natural changing of the repo

  9. tpoliaw commented on Feb 16, 2024

    @tpoliaw
    Contributor

    The multiprocessing/pickling errors mean it's probably related to #343 if that helps narrow down why it's failing. If you do pass the correct parameters does it run as expected?

  10. self-assigned this
    on Feb 28, 2024
  11. stan-dot commented on Feb 28, 2024

    @stan-dot
    Contributor

    reproducing the error documenting along:
    name': 'scan', 'parameter_schema': {'additionalProperties': False, 'properties': {'axes_to_move': {'additionalProperties': {'_axes_to_move': '<class ' "'bluesky.protocols.Movable'>"}, 'title': 'Axes ' 'To ' 'Move', 'type': 'object'}, 'detectors': {'items': {'_detectors': '<class ' "'bluesky.protocols.Readable'>"}, 'title': 'Detectors', 'type': 'array'}, 'metadata': {'title': 'Metadata', 'type': 'object'}, 'spec': {'allOf': [{'type': 'string'}], 'title': 'Spec'}}, 'required': ['detectors', 'axes_to_move', 'spec'], 'title': 'scan', 'type': 'object'}},

  12. stan-dot commented on Feb 28, 2024

    @stan-dot
    Contributor

    are there plans that do not take any parameters?
    parameters = parameters or "{}" task = RunPlan(name=name, params=json.loads(parameters))
    cli.py lines 184-5. A quickfix would be to reject-return here if no parameters are supplied.

    A more complex fix would be to check the list of plans to verify the right number of parameters - which would likely occur on the server.
    
  13. stan-dot commented on Feb 28, 2024

    @stan-dot
    Contributor

    also line 185 referenced above uses Task which is referenced in #253

  14. tpoliaw commented on Feb 29, 2024

    @tpoliaw
    Contributor

    are there plans that do not take any parameters?

    There were when parameters was changed to be optional and it was annoying that they required passing -p '{}'. It may be that most plans need args now but presumably you can always write ones that don't?

  15. 5 remaining items

  16. stan-dot commented on Mar 12, 2024

    @stan-dot
    Contributor

    one possible refactor is changing the generic request to a named requests.get/post calls that can then be mocked more granularily. it's about this method in rest.py

    python def _request_and_deserialize( self, suffix: str, target_type: Type[T], data: Optional[Mapping[str, Any]] = None, method="GET", raise_if: Callable[[requests.Response], bool] = _is_exception, ) -> T: url = self._url(suffix) # todo consider changing this to a switch statement for easier mocking # alternatively do single responsiblity principle # and decoule request from deserializing. response = requests.request(method, url, json=data) if raise_if(response): message = get_status_message(response.status_code) t = response.text error_message = f"""Response failed with text: {t}, with error code: {response.status_code} which corresponds to {message}""" raise BlueskyRemoteError(error_message) deserialized = parse_obj_as(target_type, response.json()) return deserialized

  17. stan-dot commented on Mar 15, 2024

    @stan-dot
    Contributor

    hacky solution the resembles the current tests
    `mock_requests.return_value = client.get(f"/plan/{plan}")

    bunch of testing

    mock_requests.return_value = client.post("/tasks")

    bunch more testing`

  18. stan-dot commented on Mar 18, 2024

    @stan-dot
    Contributor

    this does not seem to work that well as the invocation of the blueapai controller run sleep ... runs in the background and two different calls to the API from inside that line are hard to reconcile from the subsequent lines

  19. stan-dot commented on Mar 27, 2024

    @stan-dot
    Contributor

    merely trying to run blueapi serve with the config returns an error: NFO: Application startup complete. ERROR: [Errno -2] Name or service not known INFO: Waiting for application shutdown.

  20. stan-dot commented on Mar 27, 2024

    @stan-dot
    Contributor

    still got a false negative erro in the test

  21. stan-dot commented on Mar 28, 2024

    @stan-dot
    Contributor

    `from pydantic import BaseModel, ValidationError, validator
    from typing import Optional

    class TimeSchema(BaseModel):
    time: float

    # Optional: Add a custom validator if needed
    @validator('time')
    def time_must_be_positive(cls, value):
        if value <= 0:
            raise ValueError('Time must be a positive number')
        return value
    

    `

    result - runtime validation won't work just need to write a separate schema for each plan. which I fully support but that's another ticket. all plans and experiments could be standardized...

    I mean we could add manual python validation against the 'properties' but that's not using pydantic as it was supposed to work

  22. callumforrester commented on Mar 28, 2024

    @callumforrester
    Contributor

    Hmm, yeah, I think separate ticket for custom per-parameter validation

  23. stan-dot commented on Mar 28, 2024

    @stan-dot
    Contributor

    how to mark this ticket then as pending and dependent on that ticket? I think gitlab has some better support for this kind of thing

  24. stan-dot commented on Mar 28, 2024

    @stan-dot
    Contributor

    example for future reference: `import json

    from pydantic import parse_obj_as
    from typing import Any, Optional
    from pydantic import BaseModel, Field

    class MyBaseModel(BaseModel):
    name = "base"

    class MyPlanModel(MyBaseModel):
    name: str = "Plan model"
    description: Optional[str] = Field(
    description="Docstring of the plan", default=None
    )
    parameter_schema: Optional[dict[str, Any]] = Field(
    description="Schema of the plan's parameters",
    alias="schema",
    default_factory=dict,
    )

    plan_model: MyPlanModel = MyPlanModel()
    plan_model.parameter_schema = {
    "title": "sleep",
    "type": "object",
    "properties": {"time": {"title": "Time", "type": "number"}},
    "required": ["time"],
    "additionalProperties": False,
    }

    print(plan_model.dict())

    wrong_params: str = '{"wrong":"aboslutely wrong"}'

    p = json.loads(wrong_params) or "{}"

    try:
    validated = parse_obj_as(type(plan_model.parameter_schema), p)
    print(validated)
    except ValueError as e:
    print(f"Error: {e}")
    validated = None
    `

  25. removed their assignment
    on Mar 28, 2024
  26. callumforrester commented on Apr 4, 2024

    @callumforrester
    Contributor

    From discussion: Validation is already performed server-side and errors are shipped to the client here:

    except ValidationError as e:

    All the information needed should be in resp here:

    resp = client.create_task(task)

  27. stan-dot commented on Apr 4, 2024

    @stan-dot
    Contributor

    todo:

    • add verbose error messages to the response
  28. self-assigned this
    on Apr 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugonboarding

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions