Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
## Unreleased

### Fixes
- Fix a slowdown of `AvroSerializer` and `AvroDeserializer` (#2255): they expanded the
schema with `fastavro.expand_schema` and walked it for inline tags on every message.
Both results are now cached per schema, and the deserializer only computes them when
it executes rules.
- Fix `AvroDeserializer` rejecting messages of 5 bytes or fewer when the schema GUID is
sent in a header (`header_schema_id_serializer`), for example `int` keys or short
strings. The length check now runs where the schema id framing is parsed, so it
Expand Down
60 changes: 51 additions & 9 deletions src/confluent_kafka/schema_registry/_async/avro.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import asyncio as _locks
import io
import json
from typing import Any, Awaitable, Callable, Coroutine, Dict, Optional, Tuple, Union, cast
from typing import Any, Awaitable, Callable, Coroutine, Dict, Optional, Set, Tuple, Union, cast

from fastavro import schemaless_reader, schemaless_writer
from fastavro.schema import expand_schema
Expand Down Expand Up @@ -256,6 +256,8 @@ class AsyncAvroSerializer(AsyncBaseSerializer):
'_schema_name',
'_to_dict',
'_parsed_schemas',
'_expanded_schemas',
'_inline_tags',
'_strict',
'_strict_allow_default',
]
Expand Down Expand Up @@ -300,6 +302,8 @@ async def __init_impl(
self._known_subjects: set[str] = set()
self._known_subjects_lock = _locks.Lock()
self._parsed_schemas = ParsedSchemaCache()
self._expanded_schemas = ParsedSchemaCache()
self._inline_tags = ParsedSchemaCache()

if to_dict is not None and not callable(to_dict):
raise ValueError(
Expand Down Expand Up @@ -484,7 +488,7 @@ async def __serialize_impl(self, obj: object, ctx: Optional[SerializationContext
if latest_schema is not None and ctx is not None and subject is not None:
parsed_schema = await self._get_parsed_schema(latest_schema.schema)

expanded_parsed_schema = expand_schema(parsed_schema)
expanded_parsed_schema = self._get_expanded_schema(latest_schema.schema, parsed_schema)

def field_transformer(rule_ctx, field_transform, msg):
return transform(rule_ctx, expanded_parsed_schema, msg, field_transform) # noqa: E731
Expand All @@ -499,7 +503,7 @@ def field_transformer(rule_ctx, field_transform, msg):
None,
latest_schema.schema,
value,
get_inline_tags(parsed_schema),
self._get_inline_tags(latest_schema.schema, parsed_schema),
field_transformer,
)

Expand Down Expand Up @@ -558,6 +562,20 @@ async def _get_parsed_schema(self, schema: Schema) -> AvroSchema:
self._parsed_schemas.set(schema, parsed_schema)
return parsed_schema

def _get_expanded_schema(self, schema: Schema, parsed_schema: AvroSchema) -> AvroSchema:
expanded_schema = self._expanded_schemas.get_parsed_schema(schema)
if expanded_schema is None:
expanded_schema = expand_schema(parsed_schema)
self._expanded_schemas.set(schema, expanded_schema)
return expanded_schema

def _get_inline_tags(self, schema: Schema, parsed_schema: AvroSchema) -> Dict[str, Set[str]]:
inline_tags = self._inline_tags.get_parsed_schema(schema)
if inline_tags is None:
inline_tags = get_inline_tags(parsed_schema)
self._inline_tags.set(schema, inline_tags)
return inline_tags


class AsyncAvroSerializerBuilder(SerializerBuilder):
"""
Expand Down Expand Up @@ -765,7 +783,15 @@ class AsyncAvroDeserializer(AsyncBaseDeserializer):
`Apache Avro Schema Resolution <https://avro.apache.org/docs/1.8.2/spec.html#Schema+Resolution>`_
"""

__slots__ = ['_reader_schema', '_from_dict', '_return_record_name', '_schema', '_parsed_schemas']
__slots__ = [
'_reader_schema',
'_from_dict',
'_return_record_name',
'_schema',
'_parsed_schemas',
'_expanded_schemas',
'_inline_tags',
]

_default_conf = {
'use.latest.version': False,
Expand Down Expand Up @@ -800,6 +826,8 @@ async def __init_impl(
self._registry = schema_registry_client
self._rule_registry = rule_registry if rule_registry else RuleRegistry.get_global_instance()
self._parsed_schemas = ParsedSchemaCache()
self._expanded_schemas = ParsedSchemaCache()
self._inline_tags = ParsedSchemaCache()
self._use_schema_id = None

conf_copy = self._default_conf.copy()
Expand Down Expand Up @@ -968,13 +996,13 @@ async def __deserialize_impl(
else:
obj_dict = schemaless_reader(payload, writer_schema, reader_schema, self._return_record_name)

expanded_reader_schema = expand_schema(reader_schema)
if ctx is not None and subject is not None:
expanded_reader_schema = self._get_expanded_schema(reader_schema_raw, reader_schema)

def field_transformer(rule_ctx, field_transform, message):
return transform(rule_ctx, expanded_reader_schema, message, field_transform) # noqa: E731
def field_transformer(rule_ctx, field_transform, message):
return transform(rule_ctx, expanded_reader_schema, message, field_transform) # noqa: E731

if ctx is not None and subject is not None:
inline_tags = get_inline_tags(reader_schema) if reader_schema is not None else None
inline_tags = self._get_inline_tags(reader_schema_raw, reader_schema)
obj_dict = self._execute_rules(
ctx, subject, RuleMode.READ, None, reader_schema_raw, obj_dict, inline_tags, field_transformer, data
)
Expand Down Expand Up @@ -1002,6 +1030,20 @@ async def _get_parsed_schema(self, schema: Schema) -> AvroSchema:
self._parsed_schemas.set(schema, parsed_schema)
return parsed_schema

def _get_expanded_schema(self, schema: Schema, parsed_schema: AvroSchema) -> AvroSchema:
expanded_schema = self._expanded_schemas.get_parsed_schema(schema)
if expanded_schema is None:
expanded_schema = expand_schema(parsed_schema)
self._expanded_schemas.set(schema, expanded_schema)
return expanded_schema

def _get_inline_tags(self, schema: Schema, parsed_schema: AvroSchema) -> Dict[str, Set[str]]:
inline_tags = self._inline_tags.get_parsed_schema(schema)
if inline_tags is None:
inline_tags = get_inline_tags(parsed_schema)
self._inline_tags.set(schema, inline_tags)
return inline_tags


class AsyncAvroDeserializerBuilder(DeserializerBuilder):
"""
Expand Down
60 changes: 51 additions & 9 deletions src/confluent_kafka/schema_registry/_sync/avro.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import io
import json
import threading as _locks
from typing import Any, Callable, Dict, Optional, Tuple, Union, cast
from typing import Any, Callable, Dict, Optional, Set, Tuple, Union, cast

from fastavro import schemaless_reader, schemaless_writer
from fastavro.schema import expand_schema
Expand Down Expand Up @@ -252,6 +252,8 @@ class AvroSerializer(BaseSerializer):
'_schema_name',
'_to_dict',
'_parsed_schemas',
'_expanded_schemas',
'_inline_tags',
'_strict',
'_strict_allow_default',
]
Expand Down Expand Up @@ -296,6 +298,8 @@ def __init_impl(
self._known_subjects: set[str] = set()
self._known_subjects_lock = _locks.Lock()
self._parsed_schemas = ParsedSchemaCache()
self._expanded_schemas = ParsedSchemaCache()
self._inline_tags = ParsedSchemaCache()

if to_dict is not None and not callable(to_dict):
raise ValueError(
Expand Down Expand Up @@ -480,7 +484,7 @@ def __serialize_impl(self, obj: object, ctx: Optional[SerializationContext] = No
if latest_schema is not None and ctx is not None and subject is not None:
parsed_schema = self._get_parsed_schema(latest_schema.schema)

expanded_parsed_schema = expand_schema(parsed_schema)
expanded_parsed_schema = self._get_expanded_schema(latest_schema.schema, parsed_schema)

def field_transformer(rule_ctx, field_transform, msg):
return transform(rule_ctx, expanded_parsed_schema, msg, field_transform) # noqa: E731
Expand All @@ -495,7 +499,7 @@ def field_transformer(rule_ctx, field_transform, msg):
None,
latest_schema.schema,
value,
get_inline_tags(parsed_schema),
self._get_inline_tags(latest_schema.schema, parsed_schema),
field_transformer,
)

Expand Down Expand Up @@ -554,6 +558,20 @@ def _get_parsed_schema(self, schema: Schema) -> AvroSchema:
self._parsed_schemas.set(schema, parsed_schema)
return parsed_schema

def _get_expanded_schema(self, schema: Schema, parsed_schema: AvroSchema) -> AvroSchema:
expanded_schema = self._expanded_schemas.get_parsed_schema(schema)
if expanded_schema is None:
expanded_schema = expand_schema(parsed_schema)
self._expanded_schemas.set(schema, expanded_schema)
return expanded_schema

def _get_inline_tags(self, schema: Schema, parsed_schema: AvroSchema) -> Dict[str, Set[str]]:
inline_tags = self._inline_tags.get_parsed_schema(schema)
if inline_tags is None:
inline_tags = get_inline_tags(parsed_schema)
self._inline_tags.set(schema, inline_tags)
return inline_tags


class AvroSerializerBuilder(SerializerBuilder):
"""
Expand Down Expand Up @@ -756,7 +774,15 @@ class AvroDeserializer(BaseDeserializer):
`Apache Avro Schema Resolution <https://avro.apache.org/docs/1.8.2/spec.html#Schema+Resolution>`_
"""

__slots__ = ['_reader_schema', '_from_dict', '_return_record_name', '_schema', '_parsed_schemas']
__slots__ = [
'_reader_schema',
'_from_dict',
'_return_record_name',
'_schema',
'_parsed_schemas',
'_expanded_schemas',
'_inline_tags',
]

_default_conf = {
'use.latest.version': False,
Expand Down Expand Up @@ -791,6 +817,8 @@ def __init_impl(
self._registry = schema_registry_client
self._rule_registry = rule_registry if rule_registry else RuleRegistry.get_global_instance()
self._parsed_schemas = ParsedSchemaCache()
self._expanded_schemas = ParsedSchemaCache()
self._inline_tags = ParsedSchemaCache()
self._use_schema_id = None

conf_copy = self._default_conf.copy()
Expand Down Expand Up @@ -955,13 +983,13 @@ def __deserialize_impl(
else:
obj_dict = schemaless_reader(payload, writer_schema, reader_schema, self._return_record_name)

expanded_reader_schema = expand_schema(reader_schema)
if ctx is not None and subject is not None:
expanded_reader_schema = self._get_expanded_schema(reader_schema_raw, reader_schema)

def field_transformer(rule_ctx, field_transform, message):
return transform(rule_ctx, expanded_reader_schema, message, field_transform) # noqa: E731
def field_transformer(rule_ctx, field_transform, message):
return transform(rule_ctx, expanded_reader_schema, message, field_transform) # noqa: E731

if ctx is not None and subject is not None:
inline_tags = get_inline_tags(reader_schema) if reader_schema is not None else None
inline_tags = self._get_inline_tags(reader_schema_raw, reader_schema)
obj_dict = self._execute_rules(
ctx, subject, RuleMode.READ, None, reader_schema_raw, obj_dict, inline_tags, field_transformer, data
)
Expand Down Expand Up @@ -989,6 +1017,20 @@ def _get_parsed_schema(self, schema: Schema) -> AvroSchema:
self._parsed_schemas.set(schema, parsed_schema)
return parsed_schema

def _get_expanded_schema(self, schema: Schema, parsed_schema: AvroSchema) -> AvroSchema:
expanded_schema = self._expanded_schemas.get_parsed_schema(schema)
if expanded_schema is None:
expanded_schema = expand_schema(parsed_schema)
self._expanded_schemas.set(schema, expanded_schema)
return expanded_schema

def _get_inline_tags(self, schema: Schema, parsed_schema: AvroSchema) -> Dict[str, Set[str]]:
inline_tags = self._inline_tags.get_parsed_schema(schema)
if inline_tags is None:
inline_tags = get_inline_tags(parsed_schema)
self._inline_tags.set(schema, inline_tags)
return inline_tags


class AvroDeserializerBuilder(DeserializerBuilder):
"""
Expand Down
56 changes: 56 additions & 0 deletions tests/schema_registry/_async/test_avro_serdes.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

import pytest
from fastavro._logical_readers import UUID
from fastavro.schema import expand_schema

import confluent_kafka.schema_registry._async.avro as avro_module
from confluent_kafka.schema_registry import (
AsyncSchemaRegistryClient,
Metadata,
Expand Down Expand Up @@ -3852,3 +3854,57 @@ async def test_cluster_id_resolver_last_one_wins():
assert await client.get_latest_version("second-subject") is not None

await client.delete_associations(resource_id="mock-resource-resolver-5", cascade_lifecycle=True)


def _count_expand_schema_calls(monkeypatch):
calls = []

def counting_expand_schema(schema):
calls.append(schema)
return expand_schema(schema)

monkeypatch.setattr(avro_module, 'expand_schema', counting_expand_schema)
return calls


async def test_avro_deserializer_expands_reader_schema_once(monkeypatch):
conf = {'url': _BASE_URL}
client = AsyncSchemaRegistryClient.new_client(conf)
schema = {
'type': 'record',
'name': 'test',
'fields': [
{'name': 'intField', 'type': 'int'},
{
'name': 'nested',
'type': {'type': 'record', 'name': 'nested', 'fields': [{'name': 'f', 'type': 'string'}]},
},
],
}
obj = {'intField': 123, 'nested': {'f': 'hi'}}
ser = await AsyncAvroSerializer(client, schema_str=json.dumps(schema), conf={'auto.register.schemas': True})
ser_ctx = SerializationContext(_TOPIC, MessageField.VALUE)
obj_bytes = await ser(obj, ser_ctx)
deser = await AsyncAvroDeserializer(client)
expand_schema_calls = _count_expand_schema_calls(monkeypatch)

for _ in range(3):
assert await deser(obj_bytes, ser_ctx) == obj

assert len(expand_schema_calls) == 1


async def test_avro_serializer_expands_latest_schema_once(monkeypatch):
conf = {'url': _BASE_URL}
client = AsyncSchemaRegistryClient.new_client(conf)
schema = {'type': 'record', 'name': 'test', 'fields': [{'name': 'intField', 'type': 'int'}]}
await client.register_schema(_SUBJECT, Schema(json.dumps(schema), 'AVRO'))
ser_conf = {'auto.register.schemas': False, 'use.latest.version': True}
ser = await AsyncAvroSerializer(client, schema_str=json.dumps(schema), conf=ser_conf)
ser_ctx = SerializationContext(_TOPIC, MessageField.VALUE)
expand_schema_calls = _count_expand_schema_calls(monkeypatch)

for _ in range(3):
await ser({'intField': 123}, ser_ctx)

assert len(expand_schema_calls) == 1
Loading