Skip to content

BaseModel documents and change to schema generation #337

Closed

Description

@evvaaaa

There's been some demand for pydantic BaseModel versions of the documents.

I propose we change event-model document generation to allow for these, in a backwards compatible way.

1: Converting the current jsonschema to pydantic models

Most TypedDict document definitions only add {"additionalProperties": False} to the outputted schema, which is implicit in pydantic models, so most pydantic documents will be identical to the current ones swapping out TypedDict for BaseModel. There are other places where we add more complex logic to the schema.

Run Stop

In run-stop we have the following extra schema:

RUN_STOP_EXTRA_SCHEMA = {
    "patternProperties": {"^([^./]+)$": {"$ref": "#/$defs/DataType"}},
    "additionalProperties": False,
}

Which we can represent in pydantic as:

class RunStop(BaseModel):
    data_type: DataType
    # ... other non `DataType` fields

    class Config:
        extra = 'allow'

    @root_validator(pre=True)
    def validate_additional_fields(cls, values):
        for key, value in values.items():
            if '.' not in key and key not in cls.__fields__:
                try:
                    datatype = DataType.parse_raw(value)
                    setattr(self, key, datatype)
                except ValidationError as err:
                    raise ValueError(f"Extra non-datatype {key} received.") from err
        return values

Event Descriptor

In event-descriptor we have the following extra schema:

EVENT_DESCRIPTOR_EXTRA_SCHEMA = {
    "patternProperties": {"^([^./]+)$": {"$ref": "#/$defs/DataType"}},
    "$defs": {
        "DataType": {
            "title": "DataType",
            "patternProperties": {"^([^./]+)$": {"$ref": "#/$defs/DataType"}},
            "additionalProperties": False,
        },
    },
    "additionalProperties": False,
}

Which we can represent in pydantic the same way as above.

Run Start

The run-start additional schema is substantially more complicated:

RUN_START_EXTRA_SCHEMA = {
    "$defs": {
        "DataType": {
            "patternProperties": {"^([^./]+)$": {"$ref": "#/$defs/DataType"}},
            "additionalProperties": False,
        },
        "Projection": {
            "allOf": [
                {
                    "if": {
                        "allOf": [
                            {"properties": {"location": {"enum": ["configuration"]}}},
                            {"properties": {"type": {"enum": ["linked"]}}},
                        ]
                    },
                    "then": {
                        "required": [
                            "type",
                            "location",
                            "config_index",
                            "config_device",
                            "field",
                            "stream",
                        ]
                    },
                },
                {
                    "if": {
                        "allOf": [
                            {"properties": {"location": {"enum": ["event"]}}},
                            {"properties": {"type": {"enum": ["linked"]}}},
                        ]
                    },
                    "then": {"required": ["type", "location", "field", "stream"]},
                },
                {
                    "if": {
                        "allOf": [
                            {"properties": {"location": {"enum": ["event"]}}},
                            {"properties": {"type": {"enum": ["calculated"]}}},
                        ]
                    },
                    "then": {"required": ["type", "field", "stream", "calculation"]},
                },
                {
                    "if": {"properties": {"type": {"enum": ["static"]}}},
                    "then": {"required": ["type", "value"]},
                },
            ],
        },
    },
    "properties": {
        "hints": {
            "additionalProperties": False,
            "patternProperties": {"^([^.]+)$": {"$ref": "#/$defs/DataType"}},
        },
    },
    "patternProperties": {"^([^./]+)$": {"$ref": "#/$defs/DataType"}},
    "additionalProperties": False,
}
  1. The DataType root_validator can be added to the Hints and RunStart as above.

  2. For Projections the sanest way to adjust what we have currently would be to create a new model for each projection type and then add them as a union in RunStart, this would have the effect of defining a couple of different Projection types in the outputted schema, though it wouldn't be breaking. Alternatively there's the following method:

class Projection(BaseModel):
    type: Literal['linked', 'calculated', 'static']
    location: Optional[Literal['configuration', 'event']] = None
    config_index: Optional[int] = None
    config_device: Optional[str] = None
    field: Optional[str] = None
    stream: Optional[str] = None
    calculation: Optional[str] = None
    value: Optional[str] = None

    @root_validator(pre=True)
    def check_required_fields(cls, values):
        type_ = values.get('type')
        location = values.get('location')

        if type_ == 'linked' and location == 'configuration':
            required_fields = ['type', 'location', 'config_index', 'config_device', 'field', 'stream']
        elif type_ == 'linked' and location == 'event':
            required_fields = ['type', 'location', 'field', 'stream']
        elif type_ == 'calculated' and location == 'event':
            required_fields = ['type', 'field', 'stream', 'calculation']
        elif type_ == 'static':
            required_fields = ['type', 'value']
        else:
            required_fields = []

        for field in required_fields:
            if values.get(field) is None:
                raise ValueError(f'{field} is required for type {type_} and location {location}')

        return values

2: Updating the schema generation

Currently, we generate the jsonschema from the TypedDict definitions with pydantic, and add the EXTRA_SCHEMA dictionaries.

Instead, we'll define the pydantic models, package the schema representation of the root_validators within them and then generate both the jsonschema and the TypedDicts from the pydantic models (statically).

3: Optional fields

Pydantic doesn't allow for fields to be NotRequired, a field which is NotRequired in the TypedDict would have to be None in the pydantic model. For this reason we will forbid fields being Optional having a different meaning to NotRequired.

Fields which are Optional with default None in the BaseModel will be NotRequired[Optional[...]] in the TypedDict.

Activity

  1. self-assigned this
    on Nov 21, 2024
  2. evvaaaa commented on Nov 21, 2024

    @evvaaaa
    CollaboratorAuthor
  3. jacopoabramo commented on Dec 18, 2024

    @jacopoabramo
    Contributor

    I'm just stumbling by pure chance on this issue and I just wanted to mention if you would like to also consider using msgspec instead of/together with pydantic.

    I'm mentioning it mostly for performance reason: msgspec has quite a strong benchmark in comparison to pydantic (both in terms of speed and library size). I imagine that documents are something that should be produced and consumed as quickly as possible, I'm just throwing this extra possibility hoping to see if it's something worthwhile considering.

  4. evvaaaa commented on Dec 19, 2024

    @evvaaaa
    CollaboratorAuthor

    if you would like to also consider using msgspec instead of/together with pydantic.

    Thanks very much for the suggestion! The converter I'm using in the draft also supports jsonschema -> msgspec.Struct so if we wanted to implement this then it would be a fairly trivial change.

  5. jacopoabramo commented on Dec 19, 2024

    @jacopoabramo
    Contributor

    @evalott100 once the mentioned PR is complete I can probably give a crack at it - I don't want to mix them up. Are you using this tool by any chance?

  6. evvaaaa commented on Dec 19, 2024

    @evvaaaa
    CollaboratorAuthor

    @jacopoabramo

    Yup, It would just mean making a new

    def generate_typeddict(jsonschema_path: Path, documents_path=DOCUMENTS):
    output_path = documents_path / f"{jsonschema_path.stem}.py"
    datamodel_code_generator.generate(
    input_=jsonschema_path,
    input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
    output=output_path,
    output_model_type=datamodel_code_generator.DataModelType.TypingTypedDict,
    use_schema_description=True,
    use_field_description=True,
    use_annotated=True,
    field_constraints=True,
    wrap_string_literal=True,
    )
    with output_path.open("r+") as f:
    content = f.read()
    f.seek(0, 0)
    f.write("# ruff: noqa\n" + content)

    swapping the output file type and directory.

  7. jacopoabramo commented on Jan 15, 2025

    @jacopoabramo
    Contributor

    @evalott100

    I see that the issue is closed and you changed the approach to generating the JSON schema and the TypedDicts directly from the BaseModels. Could you summarize the steps you've taken for completing the issue? I would like to try and tackle it with msgspec.

    Also, what does this PR imply? How can I take advantage of the documents as BaseModels? Could you provide a use-case example I can take as reference?

  8. evvaaaa commented on Jan 15, 2025

    @evvaaaa
    CollaboratorAuthor

    @jacopoabramo

    I see that the issue is closed and you changed the approach to generating the JSON schema and the TypedDicts

    In seperate PRs be adding unit tests for equivalence between BaseModel and jsonschema validation, and docs.

    Could you summarize the steps you've taken for completing the issue?

    The generation itself was cleaner in #341, however that required jsonschema being the source of truth, which we decided would be worse for day to day alterations to the documents.

    The new code generates jsonschema from the BaseModel through standard pydantic, adding some extra json to handle validating additional arguments (e.g DataType). We've replaced Projection with all the logic for what isn't required with four different Projection types, this makes the logic in the jsonschema much easier to follow.

    I would like to try and tackle it with msgspec

    At the least you'll be introducing one of these for msgspec:

    def generate_typeddict(jsonschema_path: Path, documents_root=TYPEDDICTS) -> Path:
    document_path = documents_root / f"{jsonschema_path.stem}.py"
    datamodel_code_generator.generate(
    input_=jsonschema_path,
    input_file_type=datamodel_code_generator.InputFileType.JsonSchema,
    output=document_path,
    output_model_type=datamodel_code_generator.DataModelType.TypingTypedDict,
    target_python_version=datamodel_code_generator.PythonVersion.PY_38,
    use_schema_description=True,
    use_field_description=True,
    use_annotated=True,
    field_constraints=True,
    wrap_string_literal=True,
    use_double_quotes=True,
    disable_timestamp=True,
    custom_template_dir=TEMPLATES,
    )
    with document_path.open("r+") as f:
    content = f.read()
    f.seek(0, 0)
    f.write("# ruff: noqa\n" + content)
    return document_path

    It could be more complex though. For TypedDict we have to overwrite the converters recursive definition of DataType with Any, which doesn't matter since TypedDicts don't do validation on keys.

    We pass in some jinja to the converter in order to do this:

    {%- set field = fields[0] %}
    {%- if class_name == 'DataType' %}
    {{ class_name }} = Any
    {%- elif field.annotated %}
    {{ class_name }} = {{ field.annotated }}
    {%- else %}
    {{ class_name }} = {{ field.type_hint }}
    {%- endif %}

    You may have to do something more complicated, I don't know enough about msgspec to say, but if you do it would be best to keep to the datamodel template system.

    Also, what does this PR imply? How can I take advantage of the documents as BaseModels? Could you provide a use-case example I can take as reference?

    The BaseModels should be considered experimental until I get round to thoroughly testing them.

    I'll include examples in the documentation, but a client should be able to:

    from event_model.basemodels import BaseModelType, Datum, ... # And other documents
    DOCUMENT_TO_BASEMODEL = {
         "datum": Datum,
         ... # And other documents
    }
    
    ...
    
    def get_basemodel(raw_received_document: dict) -> BaseModelType
        return DOCUMENT_TO_BASEMODEL[raw_received_document["title"]](**raw_received_document)

    I'm not familiar enough with msgspec to comment on what a use-case would look like there, I imagine it would be similar but for clients which need very performant document handling.

  9. jacopoabramo commented on Jan 15, 2025

    @jacopoabramo
    Contributor

    And in relation to Bluesky itself, how would I be able to take advantage of the BaseModels in generating a document stream that instead of sending TypedDicts it sends Pydantic models? I would imagine that a first advantage is that I'd have better support for type hinting by accessing the document fields as:

    document.data

    Or will the RunEngine still dispatch documents as TypedDicts?

  10. jacopoabramo commented on Jan 15, 2025

    @jacopoabramo
    Contributor

    I'm not familiar enough with msgspec to comment on what a use-case would look like there, I imagine it would be similar but for clients which need very performant document handling.

    I wanted to use msgspec in replacement of the TypedDicts to achieve better type hinting for the documents produced by the RunEngine and consumed by any subscribed callbacks, so it would be used more internally rather than communicating with an external application via some web framework such as fastAPI. Furthermore msgspec has built-in support for msgpack and it can be extended via hooks to serialize any other non-native Python data type such as numpy arrays as well, so with some implementation I would be able to remove (at least for my specific use case) of the msgpack and msgpack-numpy dependencies and write my own hooks for the documents.

  11. evvaaaa commented on Jan 15, 2025

    @evvaaaa
    CollaboratorAuthor

    Or will the RunEngine still dispatch documents as TypedDicts?

    Yep, everything interal to bluesky will still be TypedDicts with the jsonschema validation in event_model.__init__.py. Pydantic isn't even a non-dev requirement of event-model:

    >>> import pydantic
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'pydantic'
    >>> from event_model.documents import Datum
    >>> from event_model.basemodels import Datum
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/scratch/twj43146/Programming/event-model/venv/lib/python3.11/site-packages/event_model/basemodels/__init__.py", line 3, in <module>
        from event_model.basemodels.datum import Datum
      File "/scratch/twj43146/Programming/event-model/venv/lib/python3.11/site-packages/event_model/basemodels/datum.py", line 3, in <module>
        from pydantic import (
    ModuleNotFoundError: No module named 'pydantic' 
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions