You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "3pacccccc (via GitHub)" <gi...@apache.org> on 2025/08/23 16:16:02 UTC

[PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

3pacccccc opened a new pull request, #24663:
URL: https://github.com/apache/pulsar/pull/24663

   Fixes https://github.com/apache/pulsar/issues/24541
   
   ### Motivation
   When a consumer with a dead-letter policy (DLQ) encounters a message with a schema mismatch (e.g., producer sends Long but consumer expects String), and the message exceeds the maximum redelivery count, the following infinite loop occurs:
      1.  The consumer tries to send the message to the DLQ.
      2.  The DLQ send fails with a SchemaSerializationException due to the schema mismatch.
      3.  The consumer returns false from processPossibleToDLQ, causing the message to be redelivered.
      4.  The message is redelivered, exceeds the redelivery count again, and the process repeats indefinitely.
    
   here's the example how to reproduce this issue:
   ```java
       public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
           String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
           admin.namespaces().createNamespace(namespace);
           // don't enforce schema validation
           admin.namespaces().setSchemaValidationEnforced(namespace, false);
           // set schema compatibility strategy to always compatible
           admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
           String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
                   + "/sendDeadLetterTopicWithMismatchSchemaProducer");
   
           // create topics
           admin.topics().createNonPartitionedTopic(topic);
           admin.topics().createNonPartitionedTopic(topic + "-DLQ");
           admin.topics().createNonPartitionedTopic(topic + "-RETRY");
   
           final int maxRedeliverCount = 1;
           final String subscriptionName = "my-subscription";
           Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
                   .topic(topic)
                   .subscriptionType(SubscriptionType.Shared)
                   .subscriptionName(subscriptionName)
                   .deadLetterPolicy(DeadLetterPolicy.builder()
                           .deadLetterTopic(topic + "-DLQ")
                           .retryLetterTopic(topic + "-RETRY")
                           .maxRedeliverCount(maxRedeliverCount)
                           .build())
                   .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
                   .messageListener((Consumer::negativeAcknowledge))
                   .subscribe();
   
           Producer<Long> producer = pulsarClient.newProducer(Schema.AVRO(Long.class)).topic(topic).create();
           producer.send(1234567890L);
       }
   ```
   and here's what's going on behind this scenario:
   
   | producer                             | broker                          | consumer                                                                                                                                                                                            |
   |--------------------------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
   | sends message with AVRO(Long) schema |                                 |                                                                                                                                                                                                     |
   |                                      | delivery to consumer            |                                                                                                                                                                                                     |
   |                                      |                                 | received message and nack this message                                                                                                                                                              |
   |                                      | delivery to consumer            |                                                                                                                                                                                                     |
   |                                      |                                 | received message and nack this message                                                                                                                                                              |
   |                                      | note: ***infinity loop start*** |
   |                                      | delivery to consumer            |                                                                                                                                                                                                     |
   |                                      |                                 | exceed ```maxRedeliverCount``` in ```deadLetterPolicy```, send to ```deadLetterTopic```                                                                                                             |
   |                                      |                                 | send to ```deadLetterTopic``` failed due to mismatch schema<sup>[1]</sup>, and result will be false in ```ConsumerImpl.processPossibleToDLQ```<sup>[2]</sup>                                        |
   |                                      |                                 | message will redelivery to broker<sup>[3]</sup>                                                                                                                                                     |
   |                                      | delivery to consumer            |                                                                                                                                                                                                     |
   |                                      |                                 | exceed ```maxRedeliverCount``` in ```deadLetterPolicy```, send to ```deadLetterTopic```                                                                                                             |
   |                                      |                                 | send to ```deadLetterTopic``` failed with ```SchemaSerializationException```due to mismatch schema<sup>[1]</sup>, and result will be false in ```ConsumerImpl.processPossibleToDLQ```<sup>[2]</sup> |
   |                                      |                                 | message will redelivery to broker<sup>[3]</sup>                                                                                                                                                     |
   |                                      | delivery to consumer            |                                                                                                                                                                                                     |
   |                                      |                                 | exceed ```maxRedeliverCount``` in ```deadLetterPolicy```, send to ```deadLetterTopic```                                                                                                             |
   |                                      |                                 | send to ```deadLetterTopic``` failed due to mismatch schema<sup>[1]</sup>, and result will be false in ```ConsumerImpl.processPossibleToDLQ```<sup>[2]</sup>                                        |
   |                                      |                                 | message will redelivery to broker<sup>[3]</sup>                                                                                                                                                     |
   |                                      | ...                             |                                                                                                                                                                                                     |
   
   [1]:https://github.com/apache/pulsar/blob/e606aeeebb6cc02f154758a9ae56fb85b621f8e0/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java#L2335
   [2]:https://github.com/apache/pulsar/blob/e606aeeebb6cc02f154758a9ae56fb85b621f8e0/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java#L2379
   [3]:https://github.com/apache/pulsar/blob/e606aeeebb6cc02f154758a9ae56fb85b621f8e0/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java#L2264
   ### Modifications
   - Catch SchemaSerializationException in processPossibleToDLQ: When this exception occurs during DLQ send, mark the message as "processed" (i.e., complete with true) to prevent redelivery and break the loop.
   - Improve logging:
   
      - Fix ambiguous debug log format from {}/{} to {}:{} for ledger and entry ID.
   
      - Unify and clarify error logs in processPossibleToDLQ to better distinguish between ProducerQueueIsFullError and other exceptions.
   ### Verifying this change
   
   - [x] Make sure that the change passes the CI checks.
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   *If the box was checked, please highlight the changes*
   
   - [ ] Dependencies (add or upgrade a dependency)
   - [ ] The public API
   - [ ] The schema
   - [ ] The default values of configurations
   - [ ] The threading model
   - [ ] The binary protocol
   - [ ] The REST endpoints
   - [ ] The admin CLI options
   - [ ] The metrics
   - [ ] Anything that affects deployment
   
   ### Documentation
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   - [ ] `doc` <!-- Your PR contains doc changes. -->
   - [ ] `doc-required` <!-- Your PR changes impact docs and you will update later -->
   - [x] `doc-not-needed` <!-- Your PR changes do not impact docs -->
   - [ ] `doc-complete` <!-- Docs have been already added -->
   
   ### Matching PR in forked repository
   
   PR in forked repository: https://github.com/3pacccccc/pulsar/pull/24
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Skip schema validation when sending messages to DLQ to avoid infinite loop when schema validation fails on an incoming message [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3224120489

   I ran some manual verification and things seem to work in an expected way. The message will get produced to the DLQ topic with the original schema version. It seems to be a property of the `AUTO_PRODUCE_BYTES` schema or `message.getReaderSchema()` that it's referring to the wrong schema when it attempts to run the validate. The solution in this PR seems to be a reasonable workaround to address this issue until we find a better solution.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Skip schema validation when sending messages to DLQ to avoid infinite loop when schema validation fails on an incoming message [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari merged PR #24663:
URL: https://github.com/apache/pulsar/pull/24663


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298532990


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   @lhotari Got it, thank you so much for your help!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Skip schema validation when sending messages to DLQ to avoid infinite loop when schema validation fails on an incoming message [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3228168736

   There's one remaining detail here. This solution will only work if SchemaCompatibilityStrategy is configured as `ALWAYS_COMPATIBLE` for the DLQ topic in the topic policy or in the namespace level. While testing this in action, it appeared that updating the SchemaCompatibilityStrategy changes at the namespace level aren't effective after a topic has been loaded.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2296537946


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   > Wouldn't this cause message loss?
   
   @lhotari  Yes, it's true that this message might get lost. However, in this specific scenario, I couldn't find a better solution other than stopping the redelivery to the broker to break the infinite loop. Do you have any suggestions?
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2296302764


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   Wouldn't this cause message loss?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Skip schema validation when sending messages to DLQ to avoid infinite loop when schema validation fails on an incoming message [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3224286974

   I think I found an answer to the wrong schema instance when using `AUTO_PRODUCE_BYTES` with `message.getReaderSchema().get()` as the schema.
   
   https://github.com/apache/pulsar/blob/1220951ac74fb4742abbbd331d6e751234c47015/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MessageImpl.java#L395-L413
   
   For example, for Avro messages, this maps finally here:
   https://github.com/apache/pulsar/blob/3b7bef1ecaf4004f36e071faaf31ddb49895115c/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/reader/MultiVersionAvroReader.java#L53-L54
   
   It will always use the original Schema instance for reading and never refresh the "readerSchema" from the schema registry. This is why the mandatory validation before serializing the message to DLQ fails. Considering this fact, I think that that `AutoProduceBytesSchema.setRequireSchemaValidation(false)` is a very reasonable way to workaround this issue for the DLQ use case.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "codecov-commenter (via GitHub)" <gi...@apache.org>.
codecov-commenter commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3223156545

   ## [Codecov](https://app.codecov.io/gh/apache/pulsar/pull/24663?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `81.81818%` with `2 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 74.23%. Comparing base ([`ba4f715`](https://app.codecov.io/gh/apache/pulsar/commit/ba4f715de39d3b087b57d8339490849d6d8108ec?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`17fd9a7`](https://app.codecov.io/gh/apache/pulsar/commit/17fd9a715c03bff8cc4f0aaccc25a1190fba2753?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 18 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/pulsar/pull/24663?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [...va/org/apache/pulsar/client/impl/ConsumerImpl.java](https://app.codecov.io/gh/apache/pulsar/pull/24663?src=pr&el=tree&filepath=pulsar-client%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpulsar%2Fclient%2Fimpl%2FConsumerImpl.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cHVsc2FyLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2NsaWVudC9pbXBsL0NvbnN1bWVySW1wbC5qYXZh) | 80.00% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/pulsar/pull/24663?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   [![Impacted file tree graph](https://app.codecov.io/gh/apache/pulsar/pull/24663/graphs/tree.svg?width=650&height=150&src=pr&token=acYqCpsK9J&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)](https://app.codecov.io/gh/apache/pulsar/pull/24663?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   
   ```diff
   @@             Coverage Diff              @@
   ##             master   #24663      +/-   ##
   ============================================
   - Coverage     74.40%   74.23%   -0.18%     
   + Complexity    33228    33201      -27     
   ============================================
     Files          1882     1885       +3     
     Lines        146854   146949      +95     
     Branches      16866    16927      +61     
   ============================================
   - Hits         109269   109083     -186     
   - Misses        28934    29164     +230     
   - Partials       8651     8702      +51     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/pulsar/pull/24663/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [inttests](https://app.codecov.io/gh/apache/pulsar/pull/24663/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `27.02% <45.45%> (+0.42%)` | :arrow_up: |
   | [systests](https://app.codecov.io/gh/apache/pulsar/pull/24663/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `22.74% <9.09%> (-0.67%)` | :arrow_down: |
   | [unittests](https://app.codecov.io/gh/apache/pulsar/pull/24663/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `73.71% <81.81%> (-0.18%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/pulsar/pull/24663?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [...sar/client/impl/schema/AutoProduceBytesSchema.java](https://app.codecov.io/gh/apache/pulsar/pull/24663?src=pr&el=tree&filepath=pulsar-client%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpulsar%2Fclient%2Fimpl%2Fschema%2FAutoProduceBytesSchema.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cHVsc2FyLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2NsaWVudC9pbXBsL3NjaGVtYS9BdXRvUHJvZHVjZUJ5dGVzU2NoZW1hLmphdmE=) | `71.79% <100.00%> (ø)` | |
   | [...va/org/apache/pulsar/client/impl/ConsumerImpl.java](https://app.codecov.io/gh/apache/pulsar/pull/24663?src=pr&el=tree&filepath=pulsar-client%2Fsrc%2Fmain%2Fjava%2Forg%2Fapache%2Fpulsar%2Fclient%2Fimpl%2FConsumerImpl.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-cHVsc2FyLWNsaWVudC9zcmMvbWFpbi9qYXZhL29yZy9hcGFjaGUvcHVsc2FyL2NsaWVudC9pbXBsL0NvbnN1bWVySW1wbC5qYXZh) | `79.54% <80.00%> (-0.16%)` | :arrow_down: |
   
   ... and [121 files with indirect coverage changes](https://app.codecov.io/gh/apache/pulsar/pull/24663/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
   </details>
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2297320832


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   @3pacccccc In https://github.com/apache/pulsar/issues/20635#issuecomment-2577625071 I have shared a suggestion: 
   > Most likely there would need to be a separate mode for AUTO_PRODUCE_BYTES where it can be chosen on the client side to skip schema validation. That feature is also useful in other use cases since it can reduce CPU usage on the client side when schema validation is skipped at producing time.
   
   I'm referring to skipping `schema.validate(message)` here:
   https://github.com/apache/pulsar/blob/da0d11644f097ae657e79b2eb7835478d79ccd0e/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/AutoProduceBytesSchema.java#L70-L85
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298584661


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/DeadLetterTopicTest.java:
##########
@@ -1548,4 +1548,50 @@ public void testDeadLetterTopicWithMaxUnackedMessagesBlocking() throws Exception
         consumer.close();
 
     }
+
+    // reproduce issue reported in https://github.com/apache/pulsar/issues/24541
+    @Test
+    public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
+        String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
+        admin.namespaces().createNamespace(namespace);
+        // don't enforce schema validation
+        admin.namespaces().setSchemaValidationEnforced(namespace, false);
+        // set schema compatibility strategy to always compatible
+        admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
+        String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
+                + "/sendDeadLetterTopicWithMismatchSchemaProducer");
+
+        // create topics
+        admin.topics().createNonPartitionedTopic(topic);
+        admin.topics().createNonPartitionedTopic(topic + "-DLQ");
+        admin.topics().createNonPartitionedTopic(topic + "-RETRY");
+
+        final int maxRedeliverCount = 1;
+        final String subscriptionName = "my-subscription";
+        Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
+                .topic(topic)
+                .subscriptionType(SubscriptionType.Shared)
+                .subscriptionName(subscriptionName)
+                .deadLetterPolicy(DeadLetterPolicy.builder()
+                        .deadLetterTopic(topic + "-DLQ")
+                        .retryLetterTopic(topic + "-RETRY")
+                        .maxRedeliverCount(maxRedeliverCount)
+                        .build())
+                .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
+                .messageListener((Consumer::negativeAcknowledge))
+                .subscribe();
+
+        Producer<Long> producer = pulsarClient.newProducer(Schema.AVRO(Long.class)).topic(topic).create();
+        producer.send(1234567890L);
+
+        Thread.sleep(3000L);
+
+        assertThat(pulsar.getBrokerService().getTopicReference(topic).get()
+                .getSubscription(subscriptionName).getConsumers().get(0).getMessageRedeliverCounter())
+                .describedAs("redeliver count of topic %s should be less than or equal to 2 because of mismatch schema",
+                        topic)
+                .isLessThanOrEqualTo(maxRedeliverCount + 1);
+        producer.close();
+        consumer.close();

Review Comment:
   At the end, it would be useful to test that it's possible to read the sent message from the DLQ using `Schema.AUTO_CONSUME` since it would be the way to handle such DLQs where there could be messages from different schemas in the same topic.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298594142


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/DeadLetterTopicTest.java:
##########
@@ -1548,4 +1548,50 @@ public void testDeadLetterTopicWithMaxUnackedMessagesBlocking() throws Exception
         consumer.close();
 
     }
+
+    // reproduce issue reported in https://github.com/apache/pulsar/issues/24541
+    @Test
+    public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
+        String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
+        admin.namespaces().createNamespace(namespace);
+        // don't enforce schema validation
+        admin.namespaces().setSchemaValidationEnforced(namespace, false);
+        // set schema compatibility strategy to always compatible
+        admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
+        String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
+                + "/sendDeadLetterTopicWithMismatchSchemaProducer");
+
+        // create topics
+        admin.topics().createNonPartitionedTopic(topic);
+        admin.topics().createNonPartitionedTopic(topic + "-DLQ");
+        admin.topics().createNonPartitionedTopic(topic + "-RETRY");
+
+        final int maxRedeliverCount = 1;
+        final String subscriptionName = "my-subscription";
+        Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
+                .topic(topic)
+                .subscriptionType(SubscriptionType.Shared)
+                .subscriptionName(subscriptionName)
+                .deadLetterPolicy(DeadLetterPolicy.builder()
+                        .deadLetterTopic(topic + "-DLQ")
+                        .retryLetterTopic(topic + "-RETRY")
+                        .maxRedeliverCount(maxRedeliverCount)
+                        .build())
+                .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
+                .messageListener((Consumer::negativeAcknowledge))

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3222867402

   @lhotari Hi, lari. I've updated the test, PTAL


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Skip schema validation when sending messages to DLQ to avoid infinite loop when schema validation fails on an incoming message [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#issuecomment-3224628729

   > I think I found an answer to the wrong schema instance when using `AUTO_PRODUCE_BYTES` with `message.getReaderSchema().get()` as the schema.
   > 
   > https://github.com/apache/pulsar/blob/1220951ac74fb4742abbbd331d6e751234c47015/pulsar-client/src/main/java/org/apache/pulsar/client/impl/MessageImpl.java#L395-L413
   > 
   > For example, for Avro messages, this maps finally here:
   > 
   > https://github.com/apache/pulsar/blob/3b7bef1ecaf4004f36e071faaf31ddb49895115c/pulsar-client/src/main/java/org/apache/pulsar/client/impl/schema/reader/MultiVersionAvroReader.java#L53-L54
   > 
   > It will always use the original Schema instance for reading and never refresh the "readerSchema" from the schema registry. This is why the mandatory validation before serializing the message to DLQ fails. Considering this fact, I think that that `AutoProduceBytesSchema.setRequireSchemaValidation(false)` is a very reasonable way to workaround this issue for the DLQ use case.
   
   @lhotari thank you so much for sharing this. this is very helpful and it's clear to me now. BTW, this solution is more reasonable than my initial attempt.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298559231


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/DeadLetterTopicTest.java:
##########
@@ -1548,4 +1548,50 @@ public void testDeadLetterTopicWithMaxUnackedMessagesBlocking() throws Exception
         consumer.close();
 
     }
+
+    // reproduce issue reported in https://github.com/apache/pulsar/issues/24541
+    @Test
+    public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
+        String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
+        admin.namespaces().createNamespace(namespace);
+        // don't enforce schema validation
+        admin.namespaces().setSchemaValidationEnforced(namespace, false);
+        // set schema compatibility strategy to always compatible
+        admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
+        String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
+                + "/sendDeadLetterTopicWithMismatchSchemaProducer");
+
+        // create topics
+        admin.topics().createNonPartitionedTopic(topic);
+        admin.topics().createNonPartitionedTopic(topic + "-DLQ");
+        admin.topics().createNonPartitionedTopic(topic + "-RETRY");
+
+        final int maxRedeliverCount = 1;
+        final String subscriptionName = "my-subscription";
+        Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
+                .topic(topic)
+                .subscriptionType(SubscriptionType.Shared)
+                .subscriptionName(subscriptionName)
+                .deadLetterPolicy(DeadLetterPolicy.builder()
+                        .deadLetterTopic(topic + "-DLQ")
+                        .retryLetterTopic(topic + "-RETRY")
+                        .maxRedeliverCount(maxRedeliverCount)
+                        .build())
+                .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
+                .messageListener((Consumer::negativeAcknowledge))

Review Comment:
   code style: there are unnecessary double parenthesis here?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298584661


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/DeadLetterTopicTest.java:
##########
@@ -1548,4 +1548,50 @@ public void testDeadLetterTopicWithMaxUnackedMessagesBlocking() throws Exception
         consumer.close();
 
     }
+
+    // reproduce issue reported in https://github.com/apache/pulsar/issues/24541
+    @Test
+    public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
+        String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
+        admin.namespaces().createNamespace(namespace);
+        // don't enforce schema validation
+        admin.namespaces().setSchemaValidationEnforced(namespace, false);
+        // set schema compatibility strategy to always compatible
+        admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
+        String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
+                + "/sendDeadLetterTopicWithMismatchSchemaProducer");
+
+        // create topics
+        admin.topics().createNonPartitionedTopic(topic);
+        admin.topics().createNonPartitionedTopic(topic + "-DLQ");
+        admin.topics().createNonPartitionedTopic(topic + "-RETRY");
+
+        final int maxRedeliverCount = 1;
+        final String subscriptionName = "my-subscription";
+        Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
+                .topic(topic)
+                .subscriptionType(SubscriptionType.Shared)
+                .subscriptionName(subscriptionName)
+                .deadLetterPolicy(DeadLetterPolicy.builder()
+                        .deadLetterTopic(topic + "-DLQ")
+                        .retryLetterTopic(topic + "-RETRY")
+                        .maxRedeliverCount(maxRedeliverCount)
+                        .build())
+                .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
+                .messageListener((Consumer::negativeAcknowledge))
+                .subscribe();
+
+        Producer<Long> producer = pulsarClient.newProducer(Schema.AVRO(Long.class)).topic(topic).create();
+        producer.send(1234567890L);
+
+        Thread.sleep(3000L);
+
+        assertThat(pulsar.getBrokerService().getTopicReference(topic).get()
+                .getSubscription(subscriptionName).getConsumers().get(0).getMessageRedeliverCounter())
+                .describedAs("redeliver count of topic %s should be less than or equal to 2 because of mismatch schema",
+                        topic)
+                .isLessThanOrEqualTo(maxRedeliverCount + 1);
+        producer.close();
+        consumer.close();

Review Comment:
   it would be useful to test that it's possible to read the sent message from the DLQ using `Schema.AUTO_CONSUME` since it would be the way to handle such DLQs where there could be messages from different schemas in the same topic.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298466547


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   > shall I simply remove the schema validation in `AutoProduceBytesSchema` directly? My concern is that this might impact the current behavior for existing users.
   
   No, we shouldn't change the current behavior. We need another way to be able to configure it.
   A simple solution would be to add a setter for `requireSchemaValidation` in `AutoProduceBytesSchema` class. 
   
   Then it would be possible to disable validation this way in `org.apache.pulsar.client.impl.ConsumerImpl.initDeadLetterProducerIfNeeded` method:
   ```
                           AutoProduceBytesSchema<byte[]> autoProduceBytes =
                                   (AutoProduceBytesSchema) Schema.AUTO_PRODUCE_BYTES(schema);
                           autoProduceBytes.setRequireSchemaValidation(false);
                           ProducerBuilder<byte[]> builder =
                                   ((ProducerBuilderImpl<byte[]>) client.newProducer(autoProduceBytes))
   ```
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298449969


##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -2365,9 +2367,15 @@ private CompletableFuture<Boolean> processPossibleToDLQ(MessageIdAdv messageId)
                                     return null;
                                 });
                     } catch (Exception e) {
-                        log.warn("[{}] [{}] [{}] Failed to send DLQ message to {} for message id {}",
+                        log.warn("[{}] [{}] [{}] Failed to process DLQ message to {} for message id {}",
                                 topicName, subscription, consumerName, deadLetterPolicy.getDeadLetterTopic(), messageId,
                                 e);
+                        if (e instanceof SchemaSerializationException) {
+                            // If a SchemaSerializationException occurs, the message should be ignored to redelivery.
+                            // Otherwise, it will be redelivered and still can't send to the DLQ
+                            // and cause an infinite loop
+                            result.complete(true);

Review Comment:
   @lhotari Thank you for the suggestion. This is indeed a better solution.
   
   shall I simply remove the schema validation in ```AutoProduceBytesSchema``` directly? My concern is that this might impact the current behavior for existing users.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Fix infinite loop when sending mismatched schema messages to DLQ [pulsar]

Posted by "3pacccccc (via GitHub)" <gi...@apache.org>.
3pacccccc commented on code in PR #24663:
URL: https://github.com/apache/pulsar/pull/24663#discussion_r2298595834


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/DeadLetterTopicTest.java:
##########
@@ -1548,4 +1548,50 @@ public void testDeadLetterTopicWithMaxUnackedMessagesBlocking() throws Exception
         consumer.close();
 
     }
+
+    // reproduce issue reported in https://github.com/apache/pulsar/issues/24541
+    @Test
+    public void sendDeadLetterTopicWithMismatchSchemaProducer() throws Exception {
+        String namespace = BrokerTestUtil.newUniqueName("my-property/my-ns");
+        admin.namespaces().createNamespace(namespace);
+        // don't enforce schema validation
+        admin.namespaces().setSchemaValidationEnforced(namespace, false);
+        // set schema compatibility strategy to always compatible
+        admin.namespaces().setSchemaCompatibilityStrategy(namespace, SchemaCompatibilityStrategy.ALWAYS_COMPATIBLE);
+        String topic = BrokerTestUtil.newUniqueName("persistent://" + namespace
+                + "/sendDeadLetterTopicWithMismatchSchemaProducer");
+
+        // create topics
+        admin.topics().createNonPartitionedTopic(topic);
+        admin.topics().createNonPartitionedTopic(topic + "-DLQ");
+        admin.topics().createNonPartitionedTopic(topic + "-RETRY");
+
+        final int maxRedeliverCount = 1;
+        final String subscriptionName = "my-subscription";
+        Consumer<String> consumer = pulsarClient.newConsumer(Schema.AVRO(String.class))
+                .topic(topic)
+                .subscriptionType(SubscriptionType.Shared)
+                .subscriptionName(subscriptionName)
+                .deadLetterPolicy(DeadLetterPolicy.builder()
+                        .deadLetterTopic(topic + "-DLQ")
+                        .retryLetterTopic(topic + "-RETRY")
+                        .maxRedeliverCount(maxRedeliverCount)
+                        .build())
+                .negativeAckRedeliveryDelay(1, TimeUnit.SECONDS)
+                .messageListener((Consumer::negativeAcknowledge))
+                .subscribe();
+
+        Producer<Long> producer = pulsarClient.newProducer(Schema.AVRO(Long.class)).topic(topic).create();
+        producer.send(1234567890L);
+
+        Thread.sleep(3000L);
+
+        assertThat(pulsar.getBrokerService().getTopicReference(topic).get()
+                .getSubscription(subscriptionName).getConsumers().get(0).getMessageRedeliverCounter())
+                .describedAs("redeliver count of topic %s should be less than or equal to 2 because of mismatch schema",
+                        topic)
+                .isLessThanOrEqualTo(maxRedeliverCount + 1);
+        producer.close();
+        consumer.close();

Review Comment:
   > it would be useful to test that it's possible to read the sent message from the DLQ using `Schema.AUTO_CONSUME` since it would be the way to handle such DLQs where there could be messages from different schemas in the same topic.
   
   OK, I'll add test



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org