Repository navigation
Description
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 valuesEvent 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,
}-
The
DataTyperoot_validatorcan be added to theHintsandRunStartas above. -
For
Projectionsthe 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 inRunStart, this would have the effect of defining a couple of differentProjectiontypes 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 values2: 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
evvaaaa commentedon Nov 21, 2024
@danielballan @coretl
jacopoabramo commentedon Dec 18, 2024
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.
evvaaaa commentedon Dec 19, 2024
Thanks very much for the suggestion! The converter I'm using in the draft also supports
jsonschema -> msgspec.Structso if we wanted to implement this then it would be a fairly trivial change.jacopoabramo commentedon Dec 19, 2024
@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?
evvaaaa commentedon Dec 19, 2024
@jacopoabramo
Yup, It would just mean making a new
event-model/src/event_model/generate/create_documents.py
Lines 151 to 167 in fda7e64
swapping the output file type and directory.
jacopoabramo commentedon Jan 15, 2025
@evalott100
I see that the issue is closed and you changed the approach to generating the JSON schema and the
TypedDictsdirectly from theBaseModels. Could you summarize the steps you've taken for completing the issue? I would like to try and tackle it withmsgspec.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?evvaaaa commentedon Jan 15, 2025
@jacopoabramo
In seperate PRs be adding unit tests for equivalence between
BaseModelandjsonschemavalidation, and docs.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
jsonschemafrom theBaseModelthrough standard pydantic, adding some extra json to handle validating additional arguments (e.gDataType). We've replacedProjectionwith all the logic for what isn't required with four differentProjectiontypes, this makes the logic in thejsonschemamuch easier to follow.At the least you'll be introducing one of these for
msgspec:event-model/src/event_model/generate/create_documents.py
Lines 111 to 132 in a8d4575
It could be more complex though. For
TypedDictwe have to overwrite the converters recursive definition ofDataTypewithAny, which doesn't matter sinceTypedDictsdon't do validation on keys.We pass in some jinja to the converter in order to do this:
event-model/src/event_model/generate/templates/root.jinja2
Lines 1 to 8 in a8d4575
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.
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:
I'm not familiar enough with
msgspecto 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.jacopoabramo commentedon Jan 15, 2025
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.dataOr will the RunEngine still dispatch documents as TypedDicts?
jacopoabramo commentedon Jan 15, 2025
I wanted to use
msgspecin replacement of theTypedDictsto achieve better type hinting for the documents produced by theRunEngineand 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. Furthermoremsgspechas built-in support formsgpackand 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 themsgpackandmsgpack-numpydependencies and write my own hooks for the documents.evvaaaa commentedon Jan 15, 2025
Yep, everything interal to bluesky will still be
TypedDictswith the jsonschema validation inevent_model.__init__.py. Pydantic isn't even a non-dev requirement of event-model: