confluent-kafka-python icon indicating copy to clipboard operation
confluent-kafka-python copied to clipboard

Implement support of Schema Registry's schema references

Open FrancescoPessina opened this issue 6 years ago • 19 comments

Description

When consuming an Avro message with a schema which has a schema reference, the consumer fails with message confluent_kafka.avro.serializer.SerializerError: unable to fetch schema with id xx: Received bad schema (id xx) from registry: Schema parse failed.

Schema references is a new feature introduced in Confluent Platform version 5.5.0 (see here https://www.confluent.io/blog/multiple-event-types-in-the-same-kafka-topic/#avro-unions-with-schema-references)

How to reproduce

Given a schema containing a schema reference registered into the schema registry, such as:

Nested schema:

{
  "namespace": "org.schema_registry_test_app.avro",
  "type": "record",
  "name": "Result",
  "fields": [
    {
      "name": "up",
      "type": "string"
    },
    {
      "name": "down",
      "type": "string"
    }
  ]
}

Schema with reference:

{
  "namespace": "org.schema_registry_test_app.avro",
  "type": "record",
  "name": "AvroTest",
  "fields": [
    {
      "name": "id",
      "type": {
        "name": "Uuid",
        "type": "fixed",
        "size": 16
      }
    },
    {
      "name": "results",
      "type": {
        "type": "array",
        "items": "org.schema_registry_test_app.avro.Result"
      }
    }
  ]
}

Try to consume with AvroConsumer a message produced with AvroTest schema.

Checklist

Please provide the following information:

  • [x] confluent-kafka-python and librdkafka version (confluent_kafka.version(1.5.0) and confluent_kafka.libversion()):
  • [x] Apache Kafka broker version: 2.5
  • [ ] Client configuration: {...}
  • [x] Operating system: Linux (docker) and MacOS
  • [ ] Provide client logs (with 'debug': '..' as necessary)
  • [ ] Provide broker log excerpts
  • [ ] Critical issue

FrancescoPessina avatar Oct 27 '20 12:10 FrancescoPessina

I believe schema references actually are partially supported as the confluent-kafka-python API includes a references field in the Schema object. In your case you may just need to modify your API usage. Apparently AVROConsumer is legacy and replaced with DeserializingConsumer (though I don't see how subscribing to multiple topics with differing deserializers, but a single Consumer is supposed to work the new way).

I can't seem to find the API docs for the Official AVRO Python library, but I believe the source code is here: https://github.com/apache/avro/blob/master/lang/py/avro/schema.py. I'm not even sure it is being used - the confluent-kafka-python API might use fastavro exclusively now? Inspecting the official avro library suggests it supports schema references via the names object, though I can't find any usage examples.

However, one issue that I see is that you must know your referenced schemas a-priori. It would be much nicer if you could simply provide a "resolver" object that instructed avro what to do when it encountered a schema reference it didn't recognize. For example a base resolver could search a file path, while a Confluent resolver could search the Confluent schema registry. Trying to code a out-of-band resolver is proving tricky due to the chicken-and-egg scenario where you need to parse the schema to find out the list of items that need to be resolved, but if you attempt to load the schema with avro.schema.parse you'll encountered the Error:

avro.schema.SchemaParseException: Unknown named schema 'Result', known names: [].

slominskir avatar Feb 04 '21 19:02 slominskir

I have yet to figure out how to get a consumer to work with references. We may need to update the DeserializingConsumer constructor to include a named_schemas dict as fastavro.parse expects. One concern though is that it is an Internal API - fastavro actually expects you to place referenced files all in the same directory and name the files using the fully qualified name - via load_schema. Maybe @scottbelden can help us with this?

I was able to register a schema with references using the Python SchemaRegistryClient, but I did run into the API docs are wrong issue (use SchemaReference, not Schema object in references array).

slominskir avatar Feb 04 '21 21:02 slominskir

though I don't see how subscribing to multiple topics with differing deserializers but a single Consumer is supposed to work the new way

it won't. apparently a downgrade from the previous api, though consistent with other languages.

I see is that you must know your referenced schemas a-priori

yes. the plan is to expand upon this.

I have yet to figure out how to get a consumer to work with references.

My understanding is referenced schemas in avro are non-standard.

Apologies that development here is going slow. Ultimately I hope we will make an advanced consumer that can dispatch based on type, process messages concurrently and other things. As with everything, it comes down to prioritization. We really need to stabilize the new API as a priority though. We don't anticipate any significant changes.

mhowlett avatar Feb 04 '21 23:02 mhowlett

One concern though is that it is an Internal API - fastavro actually expects you to place referenced files all in the same directory and name the files using the fully qualified name - via load_schema. Maybe @scottbelden can help us with this?

I'll preface this with the fact that I don't use the schema registry and so I don't fully understand the scope of the problem being mentioned in this issue.

One option would be to put the schemas in list (a union in Avro) and then it should just work. For example, if you have this schema:

    {
        "name": "Weather",
        "type": "record",
        "fields": [{"name": "of", "type": "Location"}],
    }

That references this schema:

    {
        "name": "Location",
        "type": "record",
        "fields": [{"name": "city", "type": "long"}],
    }

Then you can combine them in a union schema and it should just work:

from fastavro import writer, reader
from io import BytesIO

schema = [
    {
        "name": "Location",
        "type": "record",
        "fields": [{"name": "city", "type": "long"}],
    },
    {
        "name": "Weather",
        "type": "record",
        "fields": [{"name": "of", "type": "Location"}],
    },
]

records = [{"of": {"city": 123}}]
bio = BytesIO()

writer(bio, schema, records)

bio.seek(0)

for record in reader(bio):
    print(record)

Alternatively... recently a new load_schema_ordered API was added to fastavro that is similar to load_schema in that it still works with file names, but allows the user to provide the list of files rather than saying they need to conform to a certain name and file location. I could imagine having a similar API or a flag on that API so that instead of providing file names, the user provides the actual schemas. So the usage would look something like this:

location_schema = {
    "name": "Location",
    "type": "record",
    "fields": [{"name": "city", "type": "long"}],
}
weather_schema = {
    "name": "Weather",
    "type": "record",
    "fields": [{"name": "of", "type": "Location"}],
}
parsed_schema = new_parse_api([location_schema, weather_schema])

Note that in both of my examples above, it would be up to the user to ensure that all the schemas are in order of sub schemas listed before the outer schemas that reference them.

scottbelden avatar Feb 05 '21 14:02 scottbelden

It seems many of the pieces are available in Python, we just need to put them together:

Given:

  1. fastavro 1.3.1 load_schema_ordered handles schema references
  2. Confluent Python Schema API handles references

The AvroDeserializer should be updated to accept a Schema object, not a String.

slominskir avatar Feb 08 '21 15:02 slominskir

In my case I am running Python 3.8.4 using FastAvro implicitly through confluent_kafka.schema_registry.avro.AvroSerializer

The schema files are not available locally, I get the subjects and schema_strings by sending a curl request to our schema-registry. This pattern works and I have plenty of examples when constructing AvroSerializers that use a schema that doesn't rely on another schema.

However, I have a situation similar to Location/Weather above. No matter what I seem to do I am unable to escape fastavro._schema_common.UnknownType: com.dataplatform.model.MonthlyValue when constructing my AvroSerializer (MonthlyValue is the child).

How can I make my schema-registry-client aware of the child schema? I've tried registering the child schema by passing a schema_string and subject_name to Schema constructor and registering that schema using SchemaRegistryClient (the same one that I then pass into AvroSerializer).

Is this just an impossible operation as things stand? About to give up and write my app in Java

UPDATE: I was able to get this working by defining the child schema inside the parent schema. In my case I use the child (Location) many times in the parent (Weather) and I need to define it the first time then I can reference it by namespace in the subsequent mentions

danep93 avatar Feb 23 '21 23:02 danep93

Simply embed all of your schemas inside one file is the only way with Python at the moment as far as I can tell. Not great if you're trying to manage large complex schemas and evolve parts separately.

slominskir avatar Feb 24 '21 21:02 slominskir

@danep93, I have the same problem. Workaround I've found is to use extension of AvroSerializer:

  class AvroSerializerExt(AvroSerializer):
    """
    Workaround to pass references.
    """
    def __init__(self, schema, schema_registry_client,
                 to_dict=None, conf=None):
        AvroSerializer.__init__(self, schema.schema_str, schema_registry_client, to_dict, conf)
        self._schema = schema

where schema is Schema object we received from Schema Registry before initializing producer.

Note that we are using fastavro 0.23.3 here, latest version of fastavro (1.3.5) requires a bit different logic (as it doesn't cache parsed schemas globally anymore).

IMHO, AvroSerializer should be updated with support for referenced schemas and already parsed schemas (as parsing schema that contains references will fail with the latest fastavro).

typhoon2k avatar Apr 01 '21 06:04 typhoon2k

Going forward using fastavro we need to choose between:

  1. Use internal _named_schemas dict (CON: it is flagged as internal only)
  2. Use the load_schema_ordered API (CON: it requires first saving schemas to the filesystem)
  3. Ask Scott for something else

Perhaps initially we force users to provide the list of referenced schemas themselves. Ideally though, it would be nice if eventually the API automatically did look-ups in the schema registry to resolve referenced schemas without users having to explicitly provide them (in order).

I see fastavro 1.3.5 is a bug fix release related to moving schema references forward: https://github.com/fastavro/fastavro/issues/450#issuecomment-811037246

slominskir avatar Apr 13 '21 22:04 slominskir

It sounds like removing the underscore and making named_schemas part of the public API is probably the way to go. I imagine most users would probably not need to mess with it, but this case along with a few others makes it seem like there are some situations where it is useful for the user to provide the named schemas. I'll put together a PR for this in the fastavro repo.

scottbelden avatar Apr 14 '21 19:04 scottbelden

named_schemas is now a public argument as of version 1.4.0: https://fastavro.readthedocs.io/en/latest/schema.html

scottbelden avatar Apr 16 '21 21:04 scottbelden

Is the long term goal to update the Python API to match the Java API? For comparison the Java AVRO Producer API usage pseudo-code:

Properties props = new Properties();
KafkaProducer producer = new KafkaProducer(props);
String userSchema = "..."
Schema.Parser parser = new Schema.Parser();
Schema schema = parser.parse(userSchema);
GenericRecord avroRecord = new GenericData.Record(schema);
ProducerRecord<Object, Object> record = new ProducerRecord<>("topic1", "key1", avroRecord);
producer.send(record);

vs Python AvroProducer Usage:

config = {...}
value_schema_str = "..."
value_schema = avro.loads(value_schema_str)
value = {"name": "Value"}
avroProducer = AvroProducer(config, default_key_schema=key_schema, default_value_schema=value_schema)
avroProducer.produce(topic='topic1', value=value, key="key1")

Note: the Python API is in a bad spot now because there are actually two producer APIs and neither are great, and both are making excuses: (1) AvroProducer says it's "legacy" and (2) SerializingProducer says it's "experimental". I'm hesitant to move this patch forward until the Python API direction is more clear and issues like whether a reader schema is required or not are resolved.

slominskir avatar Apr 19 '21 16:04 slominskir

I faced this issue when working with references in my setup. I managed to work around it, but I would like to make an official contribution to this repo so it can be an added feature.

Do I have to discuss the implementation with anyone before I just fork this repository?

landaudiogo avatar Jun 14 '21 08:06 landaudiogo

I've already got a pull request in place, but feel free to contribute comments or code if you've got a better approach:

https://github.com/confluentinc/confluent-kafka-python/pull/1088

Currently, I'm awaiting feedback on how best to handle the fact that confluent_kafka_python lib still supports Python 2.7, yet fastavro gave up support long ago - so if you attempt to use latest fastavro with references support you've got a problem. This is demonstrated by the Travis checks failing for Python 2.7 and passing for Python 3.6.

slominskir avatar Jun 14 '21 11:06 slominskir

@slominskir I took clone of your branch with #1088 changes. But I still see the same error that we get when using schema_registry.client.

I'm I missing something? below is my code and schema. commom.avsc which is register with subject io.test.common.event.EventData.

{
    "namespace": "io.test.common.event",
    "type": "record",
    "name": "EventData",
    "fields":[
        {
            "name":"id",
            "type": "string"
        },
        {
            "name":"type",
            "type":"string"
        }
    ]
}

Payload.avsc register with subject io.test.user.schema.Payload.

{
    "namespace": "io.test.user.schema",
    "type": "record",
    "name": "Payload",
    "fields": [
        {
            "name": "name",
            "type": "string"
        },
        {
            "name": "email",
            "type": "string"
        }
    ]
}

User.avsc registered with <TOPIC_NAME>-value

{
    "namespace": "io.test.user.schema",
    "type": "record",
    "name": "User",
    "fields": [
        {
            "name": "metadata",
            "type": "io.test.user.event.EventData"
        },
        {
            "name": "payload",
            "type": "io.test.user.schema.Payload"
        }
    ]
}

I have registered them using docker-compose with above given subject name. After registration the final <TOPIC_NAME>-value schema looks like below.

{
    "namespace": "io.test.user.schema",
    "type": "record",
    "name": "User",
    "fields": [
        {
            "name": "metadata",
            "type": "io.test.common.event.EventData"
        },
        {
            "name": "payload",
            "type": "Payload"
        }
    ]
}

producer.py

from confluent_kafka import SerializingProducer
from confluent_kafka.serialization import StringSerializer
from confluent_kafka.schema_registry.avro import AvroSerializer
from confluent_kafka.schema_registry import SchemaRegistryClient


def delivery_report(err, msg):
    if err is not None:
        print("Delivery failed for User record {}: {}".format(msg.key(), err))
        return
    print('User record {} successfully produced to {} [{}] at offset {}'.format(
        msg.key(), msg.topic(), msg.partition(), msg.offset()))


def main():
    topic = "appwise-webpush-local-test-q"
    schema_registry_url = "http://localhost:8081"
    bootstrap_servers_url = "localhost:9092"

    schema_registry_conf = {'url': schema_registry_url}
    schema_registry_client = SchemaRegistryClient(schema_registry_conf)
    schema = schema_registry_client.get_latest_version(subject_name=topic+"-value")
    schema = schema_registry_client.get_schema(schema.schema_id)
    schema_str = schema.schema_str

    pro_conf ={ "auto.register.schemas": False}
    # avro_serializer = AvroSerializer(schema_registry_client=schema_registry_client, schema_str=schema_str, conf=pro_conf)
    avro_serializer = AvroSerializer(schema_registry_client=schema_registry_client, schema=schema, conf=pro_conf)

    producer_conf = {'bootstrap.servers': bootstrap_servers_url,
                     'key.serializer': StringSerializer('utf_8'),
                     'value.serializer': avro_serializer}
    producer = SerializingProducer(producer_conf)

    producer.poll(0.0)
    producer.produce(topic=topic, value=value, on_delivery=delivery_report)
    producer.flush()

if __name__ == '__main__':
    main()

Error:

Traceback (most recent call last): File "producer.py", line 54, in avro_serializer = AvroSerializer(schema_registry_client, schema_str.schema_str) File "/usr/local/lib/python3.6/site-packages/confluent_kafka/schema_registry/avro.py", line 175, in init parsed_schema = parse_schema(schema_dict) File "fastavro/_schema.pyx", line 106, in fastavro._schema.parse_schema File "fastavro/_schema.pyx", line 245, in fastavro._schema._parse_schema File "fastavro/_schema.pyx", line 290, in fastavro._schema.parse_field File "fastavro/_schema.pyx", line 129, in fastavro._schema._parse_schema fastavro._schema_common.UnknownType: io.test.common.event.EventData

Even if I Crete nasted schema using fastavro --> load_schema_ordered. I get error stating value doesn't match with registered schema.

avanish-appdirect avatar Sep 27 '21 07:09 avanish-appdirect

@avanish-appdirect - Take a look at the pull request: https://github.com/confluentinc/confluent-kafka-python/pull/1088#issue-858301581 - the first comment shows how to use - you must manually enumerate all referenced schemas using SchemaReference objects and pass in the named_schemas dict to the AvroSerializer. Depending on what version of fastavro you're using the array might be named _named_schemas or named_schemas

slominskir avatar Sep 27 '21 12:09 slominskir

@avanish-appdirect - Take a look at the pull request: #1088 (comment) - the first comment shows how to use - you must manually enumerate all referenced schemas using SchemaReference objects and pass in the named_schemas array to the AvroSerializer. Depending on what version of fastavro you're using the array might be named _named_schemas or named_schemas

@slominskir As per your below code

named_schemas = {}
ref_dict = loads(ref_schema_str)
parse_schema(ref_dict, _named_schemas=named_schemas)
ref_schema = SchemaReference("org.test.MyReferencedItem", "referenced-subject", "1")
schema = Schema(schema_str, "AVRO", [ref_schema])

avro_serializer = AvroSerializer(schema_registry_client, schema, None, None, named_schemas)

named_schemas = {} i.e blank you are manually creation schema oject with your schema name and reference, then passing it to AvroSerializer so basically it is as below correct me if I'm missing anything.

AvroSerializer("http://localhost:8081",  Schema(schema_str, "AVRO", [ref_schema]), None. None, {})

So in my code mentioned above. below like of code give me exactly same schema object as created by you manually and by default named_schemas={}.

schema = schema_registry_client.get_schema(schema.schema_id)

Still I get same error as defined in above comment.

Also I have multi level nested schema. So manually creating reference for each will be difficult.

Help me out if I'm missing something or doing anything wrong. Thank you

avanish-appdirect avatar Sep 27 '21 12:09 avanish-appdirect

correct me if I'm missing anything

Yeah - the named_schemas dict is populated (filled in) via the parse_schema function call. It's not equal to {} when provided to AvroSerializer.

Also I have multi level nested schema. So manually creating reference for each will be difficult.

The patch I created doesn't attempt to automatically determine schema references. You must provide the references (in order).

slominskir avatar Sep 27 '21 13:09 slominskir

@slominskir this worked for me, when I manually parsed schema one by one and the used named space. Sorry for not understanding your flow before.

It looks like perfectly working the only problem is we need to manually registered the schema (better then creating nested schema).

I wish they merge this #1088 PR quickly.

avanish-appdirect avatar Sep 27 '21 14:09 avanish-appdirect