Skip to content

Commit 8c6909c

Browse files
Merge pull request #2161 from backend-developers-ltd/fix_to_headers_speed
fix Synapse base performance (more than 10x speed up)
2 parents 07d5596 + f416bf1 commit 8c6909c

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

bittensor/synapse.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,7 @@ class Synapse(BaseModel):
369369
"""
370370

371371
model_config = ConfigDict(validate_assignment=True)
372+
_model_json_schema: ClassVar[Dict[str, Any]]
372373

373374
def deserialize(self) -> "Synapse":
374375
"""
@@ -580,11 +581,27 @@ def failed_verification(self) -> bool:
580581
"""
581582
return self.dendrite is not None and self.dendrite.status_code == 401
582583

584+
@classmethod
585+
def _get_cached_model_json_schema(cls) -> dict:
586+
"""
587+
Returns the JSON schema for the Synapse model.
588+
589+
This method returns a cached version of the JSON schema for the Synapse model.
590+
The schema is stored in the class variable ``_model_json_schema`` and is only
591+
generated once to improve performance.
592+
593+
Returns:
594+
dict: The JSON schema for the Synapse model.
595+
"""
596+
if "_model_json_schema" not in cls.__dict__:
597+
cls._model_json_schema = cls.model_json_schema()
598+
return cls._model_json_schema
599+
583600
def get_required_fields(self):
584601
"""
585602
Get the required fields from the model's JSON schema.
586603
"""
587-
schema = self.__class__.model_json_schema()
604+
schema = self._get_cached_model_json_schema()
588605
return schema.get("required", [])
589606

590607
def to_headers(self) -> dict:
@@ -635,16 +652,15 @@ def to_headers(self) -> dict:
635652
# Getting the fields of the instance
636653
instance_fields = self.model_dump()
637654

655+
required = set(self.get_required_fields())
638656
# Iterating over the fields of the instance
639657
for field, value in instance_fields.items():
640658
# If the object is not optional, serializing it, encoding it, and adding it to the headers
641-
required = self.get_required_fields()
642-
643659
# Skipping the field if it's already in the headers or its value is None
644660
if field in headers or value is None:
645661
continue
646662

647-
elif required and field in required:
663+
elif field in required:
648664
try:
649665
# create an empty (dummy) instance of type(value) to pass pydantic validation on the axon side
650666
serialized_value = json.dumps(value.__class__.__call__())

0 commit comments

Comments
 (0)