-
Notifications
You must be signed in to change notification settings - Fork 14k
[FLINK-31951][format] Reset decoder on Avro deserialization failure #28715
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
spratt
wants to merge
2
commits into
apache:master
Choose a base branch
from
spratt:FLINK-31951
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+264
−2
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
132 changes: 132 additions & 0 deletions
132
...nk/formats/avro/registry/confluent/RegistryAvroDeserializationSchemaDecoderResetTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.flink.formats.avro.registry.confluent; | ||
|
|
||
| import org.apache.flink.formats.avro.RegistryAvroDeserializationSchema; | ||
|
|
||
| import io.confluent.kafka.schemaregistry.client.MockSchemaRegistryClient; | ||
| import org.apache.avro.Schema; | ||
| import org.apache.avro.SchemaBuilder; | ||
| import org.apache.avro.generic.GenericData; | ||
| import org.apache.avro.generic.GenericDatumWriter; | ||
| import org.apache.avro.generic.GenericRecord; | ||
| import org.apache.avro.io.BinaryEncoder; | ||
| import org.apache.avro.io.EncoderFactory; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.DataOutputStream; | ||
| import java.io.IOException; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| /** | ||
| * Verifies that a deserialization failure does not leave stale bytes in the {@code BinaryDecoder}'s | ||
| * internal read-ahead buffer, which would corrupt subsequent messages. | ||
| * | ||
| * <p>The bug: {@link RegistryAvroDeserializationSchema} reuses a single {@code BinaryDecoder} | ||
| * across messages. When a decode fails mid-message the decoder's internal buffer retains the | ||
| * unconsumed bytes from the failed message. The next call to {@code setBuffer()} resets the | ||
| * underlying stream but does not clear the decoder buffer, so the next message is decoded starting | ||
| * from those stale bytes and produces wrong results. | ||
| */ | ||
| class RegistryAvroDeserializationSchemaDecoderResetTest { | ||
|
|
||
| private static final Schema SCHEMA = | ||
| SchemaBuilder.record("Simple") | ||
| .namespace("test") | ||
| .fields() | ||
| .name("id") | ||
| .type() | ||
| .intType() | ||
| .noDefault() | ||
| .name("name") | ||
| .type() | ||
| .stringType() | ||
| .noDefault() | ||
| .endRecord(); | ||
|
|
||
| @Test | ||
| void testValidMessageDecodedCorrectlyAfterPriorFailure() throws Exception { | ||
| MockSchemaRegistryClient mockClient = new MockSchemaRegistryClient(); | ||
| int schemaId = mockClient.register("test", SCHEMA); | ||
|
|
||
| ConfluentSchemaRegistryCoder coder = new ConfluentSchemaRegistryCoder(mockClient); | ||
| RegistryAvroDeserializationSchema<GenericRecord> deserializer = | ||
| new RegistryAvroDeserializationSchema<>(GenericRecord.class, SCHEMA, () -> coder); | ||
|
|
||
| // Message 1: a malformed Avro payload. | ||
| // - 0x02 encodes id=1 (zigzag int, valid) | ||
| // - 0x01 encodes string length=-1 (zigzag, invalid -- triggers "Malformed data") | ||
| // - 10 zero bytes that will linger in the decoder's internal buffer after the failure | ||
| byte[] badPayload = {0x02, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; | ||
| byte[] badMessage = confluentMessage(schemaId, badPayload); | ||
|
|
||
| // Deserialization of the malformed message is expected to fail. | ||
| Exception firstError = null; | ||
| try { | ||
| deserializer.deserialize(badMessage); | ||
| } catch (Exception e) { | ||
| firstError = e; | ||
| } | ||
| assertThat(firstError).as("first (malformed) message must fail").isNotNull(); | ||
|
|
||
| // Message 2: a valid Avro payload for the same schema. | ||
| byte[] goodMessage = confluentMessage(schemaId, encodeRecord(42, "hello")); | ||
|
|
||
| // Without the fix the decoder buffer still holds the 10 zero bytes from message 1. | ||
| // Those bytes decode as id=0 and name="" instead of id=42 and name="hello". | ||
| GenericRecord result = deserializer.deserialize(goodMessage); | ||
|
|
||
| assertThat(result.get("id")) | ||
| .as("id must not be corrupted by stale bytes from the prior failure") | ||
| .isEqualTo(42); | ||
| assertThat(result.get("name").toString()) | ||
| .as("name must not be corrupted by stale bytes from the prior failure") | ||
| .isEqualTo("hello"); | ||
| } | ||
|
|
||
| // ------------------------------------------------------------------------- | ||
| // Helpers | ||
| // ------------------------------------------------------------------------- | ||
|
|
||
| /** Wraps an Avro binary payload in the Confluent wire format (magic byte + schema_id). */ | ||
| private static byte[] confluentMessage(int schemaId, byte[] avroPayload) throws IOException { | ||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
| DataOutputStream dos = new DataOutputStream(out); | ||
| dos.writeByte(0); | ||
| dos.writeInt(schemaId); | ||
| dos.flush(); | ||
| out.write(avroPayload); | ||
| return out.toByteArray(); | ||
| } | ||
|
|
||
| /** Serialises a two-field record using the standard Avro binary encoder. */ | ||
| private static byte[] encodeRecord(int id, String name) throws IOException { | ||
| GenericRecord record = new GenericData.Record(SCHEMA); | ||
| record.put("id", id); | ||
| record.put("name", name); | ||
|
|
||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
| BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); | ||
| new GenericDatumWriter<GenericRecord>(SCHEMA).write(record, encoder); | ||
| encoder.flush(); | ||
| return out.toByteArray(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
...rc/test/java/org/apache/flink/formats/avro/AvroDeserializationSchemaDecoderResetTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.flink.formats.avro; | ||
|
|
||
| import org.apache.avro.Schema; | ||
| import org.apache.avro.SchemaBuilder; | ||
| import org.apache.avro.generic.GenericData; | ||
| import org.apache.avro.generic.GenericDatumWriter; | ||
| import org.apache.avro.generic.GenericRecord; | ||
| import org.apache.avro.io.BinaryEncoder; | ||
| import org.apache.avro.io.EncoderFactory; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.IOException; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| /** | ||
| * Verifies that a deserialization failure does not leave stale bytes in the {@code BinaryDecoder}'s | ||
| * internal read-ahead buffer, which would corrupt subsequent messages decoded by {@link | ||
| * AvroDeserializationSchema}. | ||
| * | ||
| * <p>The bug: {@link AvroDeserializationSchema} reuses a single {@code BinaryDecoder} across | ||
| * messages. When a decode fails mid-message the decoder's internal buffer retains the unconsumed | ||
| * bytes from the failed message. The next call to {@code setBuffer()} resets the underlying stream | ||
| * but does not clear the decoder buffer, so the next message is decoded starting from those stale | ||
| * bytes and produces wrong results. | ||
| */ | ||
| class AvroDeserializationSchemaDecoderResetTest { | ||
|
|
||
| private static final Schema SCHEMA = | ||
| SchemaBuilder.record("Simple") | ||
| .namespace("test") | ||
| .fields() | ||
| .name("id") | ||
| .type() | ||
| .intType() | ||
| .noDefault() | ||
| .name("name") | ||
| .type() | ||
| .stringType() | ||
| .noDefault() | ||
| .endRecord(); | ||
|
|
||
| @Test | ||
| void testValidMessageDecodedCorrectlyAfterPriorFailure() throws Exception { | ||
| AvroDeserializationSchema<GenericRecord> deserializer = | ||
| AvroDeserializationSchema.forGeneric(SCHEMA); | ||
|
|
||
| // Message 1: a malformed raw Avro binary payload. | ||
| // - 0x02 encodes id=1 (zigzag int, valid) | ||
| // - 0x01 encodes string length=-1 (zigzag, invalid -- triggers "Malformed data") | ||
| // - 10 zero bytes that will linger in the decoder's internal buffer after the failure | ||
| byte[] badMessage = {0x02, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; | ||
|
|
||
| // Deserialization of the malformed message is expected to fail. | ||
| Exception firstError = null; | ||
| try { | ||
| deserializer.deserialize(badMessage); | ||
| } catch (Exception e) { | ||
| firstError = e; | ||
| } | ||
| assertThat(firstError).as("first (malformed) message must fail").isNotNull(); | ||
|
|
||
| // Message 2: a valid Avro binary payload for the same schema. | ||
| byte[] goodMessage = encodeRecord(42, "hello"); | ||
|
|
||
| // Without the fix the decoder buffer still holds the 10 zero bytes from message 1. | ||
| // Those bytes decode as id=0 and name="" instead of id=42 and name="hello". | ||
| GenericRecord result = deserializer.deserialize(goodMessage); | ||
|
|
||
| assertThat(result.get("id")) | ||
| .as("id must not be corrupted by stale bytes from the prior failure") | ||
| .isEqualTo(42); | ||
| assertThat(result.get("name").toString()) | ||
| .as("name must not be corrupted by stale bytes from the prior failure") | ||
| .isEqualTo("hello"); | ||
| } | ||
|
|
||
| /** Serialises a two-field record using the standard Avro binary encoder. */ | ||
| private static byte[] encodeRecord(int id, String name) throws IOException { | ||
| GenericRecord record = new GenericData.Record(SCHEMA); | ||
| record.put("id", id); | ||
| record.put("name", name); | ||
|
|
||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | ||
| BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); | ||
| new GenericDatumWriter<GenericRecord>(SCHEMA).write(record, encoder); | ||
| encoder.flush(); | ||
| return out.toByteArray(); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this looks like a great catch and one to get fixed. I am curious whether this scenario can be hit in the base avro format itself - if so could we fix it there?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great question. I'll investigate and get back to you.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Well caught! My investigation showed that the scenario could be hit independently in the base class and in the registry-specific case, so I've included tests and fixes for both.