You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "m1a2st (via GitHub)" <gi...@apache.org> on 2024/10/10 06:12:03 UTC

[PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

m1a2st opened a new pull request, #17440:
URL: https://github.com/apache/kafka/pull/17440

   Jira: https://issues.apache.org/jira/browse/KAFKA-17696
   
   When API calls that handle background events (e.g., poll, unsubscribe, close) encounter errors, the errors are only passed to the application thread via ErrorEvent.
   Other API calls that do not process background events (e.g., position) are not notified of these errors, meaning that issues like unauthorized access to topics will go unnoticed by those operations.
   Background operations are not aborted or notified when a metadata error occurs, such as an Unauthorized error, which can lead to situations where a call like position keeps waiting for an update, despite the Unauthorized error already happening.
   
   Due to the blocking issue in `applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);`, I consider that we should use `processBackgroundEvents` to get the events, that is better than `addAndGet`.
   
   
   ### Committer Checklist (excluded from commit message)
   - [ ] Verify design and implementation 
   - [ ] Verify test coverage and CI build status
   - [ ] Verify documentation (including upgrade notes)
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1794731648


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1594,7 +1594,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);

Review Comment:
   but there are another issue in close the consumer, I didn't have good idea to solve this.
   ```
   [2024-10-10 14:08:59,259] WARN [NodeToControllerChannelManager id=1000 name=registration] Attempting to close NetworkClient that has already been closed. (org.apache.kafka.clients.NetworkClient:694)
   [2024-10-10 14:08:59,261] ERROR [QuorumController id=1000] Cancelling deferred write event maybeFenceReplicas because the event queue is now closed. (org.apache.kafka.controller.QuorumController:1184)
   
   Failed to close kafka consumer
   org.apache.kafka.common.KafkaException: Failed to close kafka consumer
   	at org.apache.kafka.clients.consumer.internals.AsyncKafkaConsumer.close(AsyncKafkaConsumer.java:1249)
   ```



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850159400


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -186,9 +187,15 @@ public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
      */
     public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchOffsets(
             Map<TopicPartition, Long> timestampsToSearch,
-            boolean requireTimestamps) {
+            boolean requireTimestamps,
+            List<CompletableFuture<RuntimeException>> metadataErrors
+    ) {
+        AtomicReference<CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>>> 
+                topicToOffsetsResult = new AtomicReference<>();

Review Comment:
   I originally wrapped it in an additional layer to avoid the issue with Java lambdas requiring immutable variables. However, I’ve refactored this implementation to avoid any misunderstandings.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2483413363

   Hello @lianetm,
   
   Thank you for your comments. I have already addressed the issue where `CoordinatorRequestManager` catches metadata errors and passes them to the `ListOffsets` event. However, I encountered some test failures in my local environment:
   
   - **`AuthorizerIntegrationTest#testPatternSubscriptionWithNoTopicAccess`**
   - **`AuthorizerIntegrationTest#testCreatePermissionOnClusterToReadFromNonExistentTopic`**
   - **`AuthorizerIntegrationTest#testCreatePermissionOnTopicToReadFromNonExistentTopic`**
   - **`AuthorizerIntegrationTest#testListOffsetsWithTopicDescribe`**
   - **`EndToEndAuthorizationTest#testNoConsumeWithoutDescribeAclViaSubscribe`**
   
   Some of these tests are failing due to issues with the `consumer.poll` method. I am currently investigating the root cause but don’t have a clear solution yet. 
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1868388836


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +327,18 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError() {
+        List<CompletableEvent<?>> events = applicationEventReaper.reapUnCompletableApplicationEvents();

Review Comment:
   It make snese to me, I will address it



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1871585961


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   do we need to clear the metadata error right after this line? if we make it here , it means that the `metadataError` recovered (ex. unknown/unauth topic not in the subscription anymore), so we shouldn't be keeping/propagating any previous error I would say. Makes sense?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +333,21 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.

Review Comment:
   ```suggestion
        * If there is a metadata error, complete all uncompleted events that require subscription metadata
   ```
   
   something like it, to clarify that it's only for the ones requiring metadata



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1806734056


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1132,7 +1135,11 @@ private Map<TopicPartition, Long> beginningOrEndOffset(Collection<TopicPartition
 
             Map<TopicPartition, OffsetAndTimestampInternal> offsetAndTimestampMap;
             try {
-                offsetAndTimestampMap = applicationEventHandler.addAndGet(listOffsetsEvent);
+                applicationEventHandler.add(listOffsetsEvent);
+                offsetAndTimestampMap = processBackgroundEvents(
+                        listOffsetsEvent.future(),
+                        timer, __ -> false
+                );

Review Comment:
   > Is it sufficient to perform a single check of the background events before submitting the application event, or do we really need to perform multiple checks of the background events while we wait for the application event to complete?
   
   It can't process ` processBackgroundEvents()` only once before `applicationEventHandler.addAndGet`. Test will be fail if I change to below, I think a loop for processBackgroundEvents is necessary
   ```java
    processBackgroundEvents();
   offsetAndTimestampMap = applicationEventHandler.addAndGet(listOffsetsEvent);
   ```



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1874197149


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   My observation is that when we encounter a metadata error, the application thread does not immediately execute a new event, so the background thread continues to execute `runOnce`. During the next execution of `runOnce`, the metadata error gets cleared, resulting in the event not being propagated. 
   As for the event, when it throws a `TopicAuthorizationException`, it is already considered complete by `completeExceptionally`, so this event is not counted among the uncompleted ones. Make sense?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2528144402

   Thanks to @lianetm and @kirktrue for your patience and review.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2448556088

   @m1a2st—I tested this fix by merging the changes in this PR with the changes from [my PR that sets the default `group.protocol` value to `CONSUMER`](https://github.com/apache/kafka/pull/17107). Unfortunately, the integration tests that exercise authorization policies fail even with this fix 😢
   
   If you want to test that your change works across our topic and consumer group authorization integration tests, do the following:
   
   1. Change the default for `group.protocol` in [`ConsumerConfig`](https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerConfig.java#L114) 
   2. Run the integration tests which subclass `EndToEndAuthorizationTest`


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2493752628

   Hello @lianetm, Sorry for the late response. 
   
   > Would that work? I see that the main advantages would be to avoid the complexity of metadata future errors passed around to specific manager calls, and also it would be a solution applied consistently to all events (each event type then deciding if it should fail or not on topic metadata errors).
   
   I think this approach is great significantly simplifies the system by eliminating the need to pass CompletedFuture around, which reduces complexity. Also, based on current testing, the failing tests are still just these few.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2506273868

   > Note that metadata errors are the only ones that ended up in this weird situation of having 2 ways to be propagated, so that's what I was hoping we could improve. Makes sense?
   
   Yes, I understand this, however, I’m now thinking about the async consumer `poll` method. Originally, we used `processBackgroundEvent` to retrieve the Error event, but now we’re trying to use `metadataError` passing to restore its triggering point, which feels a bit difficult to find the same triggering point. due to it is processing in different thread.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1848386538


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java:
##########
@@ -425,6 +427,13 @@ public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitSync(fina
         CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
         OffsetCommitRequestState requestState = createOffsetCommitRequest(commitOffsets, deadlineMs);
         commitSyncWithRetries(requestState, result);
+        new ArrayList<>(metadataErrors).forEach(metadataError -> metadataError.whenComplete((__, error) -> {
+            if (error != null) {
+                result.completeExceptionally(error);
+                metadataErrors.remove(metadataError);
+            }
+        }));
+        

Review Comment:
   Yes, I think we should deal this fataError at another PR, it is a little bit different with this PR, because this PR should focus on Error Event how to passing to application thread.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1826189301


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1574,7 +1583,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(

Review Comment:
   I'm afraid that processing background here events could bring undesired effects, mainly because it may include callbacks, which are totally unrelated to a call to consumer.position() for instance.
   
   If there's a call to consumer.position, and a reconciliation starts in the background around the same time (ie. new partition assigned from the broker), the background will enqueue a CallbackNeededEvent, so we could end up actually running the callback here, as part of the call to position, which is not right.
   
   I believe that we should not use `processBackgroundEvents` as a means of knowing that a specific event that we sent to the background failed. We should ensure that the event is completed exceptionally in the background instead. Wouldn't that work, and avoid mixing errors and callbacks? (related info in the jira too)



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2494899697

   Hey @m1a2st , just FYI, we just enabled some auth tests that were marked as blocked on this issue, but are really not blocked on this (https://github.com/apache/kafka/pull/17885). So just merge trunk latest changes, and we can have this PR addressing/enabling only what's really related to this fix. Thanks!


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1873390205


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   > This could result in the metadata error not being propagated
   I see that point and I was also debating about it, but then the question is: why would we need to propagate a transient error with the subscription metadata that already disappeared? 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   > This could result in the metadata error not being propagated
   
   I see that point and I was also debating about it, but then the question is: why would we need to propagate a transient error with the subscription metadata that already disappeared? 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1861159924


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -168,6 +171,8 @@ private void processApplicationEvents() {
                 if (event instanceof CompletableEvent)
                     applicationEventReaper.add((CompletableEvent<?>) event);
 
+                List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);

Review Comment:
   agree we shouldn't involve the reaper before processing events (it could expire events that haven't had the chance to run once, ie. timeout 0). 
   
   Alternatively, we have the completable `event` in hand, so what about something like `maybeFailOnMetadataError(List.of(event))` right after adding it to the reaper on ln 170? (we only care about CompletableEvents anyways), would that work @m1a2st ?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2507420510

   I think I have an idea of where the problem lies. With the current approach, the `completeExceptionally` inside `updateFetchPositions` cannot successfully propagate to the application thread. 


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2508852749

   > One suggestion already: we can simplifying the tweak we had to introduce on the unsubscribe to ignore metadata errors (with your PR, they won't pop out unexpectedly), so I would say we can remove InvalidTopic and TopicAuth from here (leaving GroupAuth only)
   
   I think we should focus on `PlaintextConsumerSubscriptionTest#testSubscribeInvalidTopicCanUnsubscribe` this test, In CONSUMER protocol, we will throw `InvalidTopicException` on `unsubscribe`, If we don't want this behaviour, we also need to use other way to sallow this metadata error, WDYT?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2506174187

   Hi @m1a2st , agree we still need ErrorEvent (for HB and coordinator errors), but with this PR seems we can remove its usage for metadata errors. That would be a good thing I believe, because we would have a single consistent way of propagating metadata errors (via the triggering API event only, like most events do). Note that metadata errors are the only ones that ended up in this weird situation of having 2 ways to be propagated, so that's what I was hoping we could improve. Makes sense?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850512580


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java:
##########
@@ -188,6 +190,8 @@ private void onFailedResponse(final long currentTimeMs, final Throwable exceptio
         if (exception == Errors.GROUP_AUTHORIZATION_FAILED.exception()) {
             log.debug("FindCoordinator request failed due to authorization error {}", exception.getMessage());
             KafkaException groupAuthorizationException = GroupAuthorizationException.forGroupId(this.groupId);
+            metadataError.completeExceptionally(groupAuthorizationException);
+            metadataError = metadataError.newIncompleteFuture();

Review Comment:
   hey, you're right about the differences in how errors are propagated, but they are in different situations, some with different threading model actually, so makes sense we won't have the same approach right? (errors that need to move around the same thread vs different threads). To recap, the requirements are:
   
   1. propagate errors from background thread to app thread (here we could have a triggering event we can use, or not, so we use `ErrorEvent` consumed from poll) - this is already in place
   2. propagate errors within the background thread  to fail pending requests (here we have the case of coordinator errors, metadata errors, ...).  - this is a gap this PR is aiming to fix, split in 2 for coord and metadata
   
   Do the use cases makes sense? And do we agree that what we're trying to fix with this PR is requirement 2? If so then it makes sense that we won't be mixing events/ErrorEvent here, simply because we just need to pass errors around in the same thread (requirement 2). Please let me know if I'm missing something about the problem we're trying to fix. Thanks!



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875210056


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   ok, we're saying it gets cleared as soon as it's propagated (to ensure that it's indeed propagated), but we could still get an exception from a previously sent request (this was my concern). Anyways that's actually what we have with the classic consumer, so it's consistent (there are actually tests specifically covering the behaviour considering that). 
   https://github.com/apache/kafka/blob/ee4264439ddda7bdebcaa845752b824abba14161/core/src/test/scala/integration/kafka/api/EndToEndAuthorizationTest.scala#L553-L554  



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875232483


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegateTest.java:
##########
@@ -212,9 +213,27 @@ public void testPropagateMetadataError() {
         AuthenticationException authException = new AuthenticationException("Test Auth Exception");
         doThrow(authException).when(metadata).maybeThrowAnyException();
 
+        NetworkClientDelegate networkClientDelegate = newNetworkClientDelegate(false);
+        assertTrue(networkClientDelegate.getAndClearMetadataError().isEmpty());
+        networkClientDelegate.poll(0, time.milliseconds());
+        
+        assertTrue(networkClientDelegate.getAndClearMetadataError().isPresent());

Review Comment:
   this will clear the error so the assertions within the ifPresent will never run right? (maybe we take the Optional result of .getAndClear, check that optional is present, and then the 2 asserts on the value?)



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1860948200


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,6 +152,7 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();
         } catch (Exception e) {
+            metadataError = Optional.of(e);
             backgroundEventHandler.add(new ErrorEvent(e));

Review Comment:
   > Then why exactly is it that we still need to propagate them via ErrorEvents still too? 
   
   I agree with this comment; it would be beneficial to have a unified way to propagate errors.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2507785075

   Hello @apoorvmittal10, @AndrewJSchofield, @lianetm, @kirktrue 
   
   The current PR has changed the way metadata errors are propagated, switching from `backgroundEventHandler.add(new ErrorEvent(e))` to using `Optional` for transmission. I noticed that in SharedConsumer, the logic for handling errors on the application thread is slightly different. I think we need to sync up to understand this behavior adjustment better.
   https://github.com/apache/kafka/blob/b8c8e0c713117ee3f0e8c6c54edd5d2babde5f19/clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java#L153


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2517959270

   > Yes, I believe this approach can solve the problem, but it does feel a bit frustrating since we spent quite some time unifying the metadata error propagation method. Perhaps we can create a task later to unify the error propagation behavior of both types of consumers.
   
   Well this PR achieved unifying it within the KafkaConsumer, that's a great step! Unifying it between the 2 consumers is a different story, worth exploring but the challenge truly is that the position management is quite different between the 2 (which is the main point of friction we had in the Async consumer, where we needed to detect these failures when updating positions from poll and position, via the same event). 


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1831724350


##########
clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerConfig.java:
##########
@@ -111,7 +111,7 @@ public class ConsumerConfig extends AbstractConfig {
      * <code>group.protocol</code>
      */
     public static final String GROUP_PROTOCOL_CONFIG = "group.protocol";
-    public static final String DEFAULT_GROUP_PROTOCOL = GroupProtocol.CLASSIC.name().toLowerCase(Locale.ROOT);
+    public static final String DEFAULT_GROUP_PROTOCOL = GroupProtocol.CONSUMER.name().toLowerCase(Locale.ROOT);

Review Comment:
   we should leave this change of the default consumer in a separate PR, there is already one for it
   https://github.com/apache/kafka/pull/17107



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1574,7 +1583,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(

Review Comment:
   Hey @m1a2st , thanks for the reply. The trick here is that this `processBackgroundEvents` is kind of a generic communication channel between the app thread and background thread, that was designed as a way to communicate from background to app thread when there was no direct triggering api call:
   
   1. heartbeat/coordinator errors received in a response to requests that are triggered internally in the background (HB and FindCoordinator), not coming from app thread events.
   2. callbacks needed as part of a reconciliation triggered by the broker (not app thread event)
   
   Using this generic channel for when we do have an event that started in the app thread seems to bring in complexity and loose ends:
   
   1. Complexity because api calls would need to sort through the generic queue/channel to find the response to the specific event they are interested in, processing all background events (callbacks, errors that have no event, errors that have event), and filter out / re-enqueue...
   2. We would leave events lingering uncompleted in the background, that will never complete really (eventually expired I expect).
   
   On the other hand, we have a “direct” way of communicating  the 2 threads: via events that get completed. So if we hand an app event handy, seems sensible to just complete it with metadata errors if they happen (just like the classic achieves, given that on every poll it will throw and bubble up the metadata exception, effectively failing the triggering call). Ex. `consumer.position` (the one that started this PR), sends a CheckAndUpdatePositions event to the background, so I was expecting that we could simply complete it with the TopicAuthorizationException as a way to fail the consumer call.  
   
   Those are the concepts, but I totally hear you about the challenges on the implementation. Could you elaborate more on that to see if we can sort them out together maybe? This is a more detailed description of what I have in mind:
   
   1. Catch metadata errors on `ConsumerNetworkThread.runOnce` and completeExceptionally all the requests it has (requests returned by the managers poll here
   https://github.com/apache/kafka/blob/a0d4cbec402c6c09e601c76a7332747e80e518ca/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java#L145)
   This would propagate the failure to the app thread via the event.
   2. Notify managers of the metadata error too (ie. onMetadataERror), in case they have requests generated that did not make it to point 1, but still need to fail (ie. Commit request manager may have unsentOffsetCommitRequests/unsentOffsetFetchRequests. I don't think any other keeps requests without sending them to the network client but let's double check)
   
   What do you think? Would it work? Thanks!



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2489198670

   >  don't yet understand the need for passing the metadata error around in a Future. And I'm also still wondering if this could be handled at a lower layer so that we don't have to have bespoke code in the request managers to deal with it.
   
   The rationale behind this design is that when `ConsumerNetworkThread#processApplicationEvents` executes `checkAndUpdatePositionsEvent`, the T`opicAuthorizationException` doesn’t surface immediately. Instead, it may require several iterations of `runOnce` for the error to become apparent. Without using the future-based approach, it would be impossible to propagate this error from the background thread to the `OffsetsRequestManager`.
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1868623843


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +328,17 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            if (!events.isEmpty()) {
+                events.forEach(event -> event.future().completeExceptionally(metadataError));
+                networkClientDelegate.clearMetadataError();
+            }
+        }
+    }

Review Comment:
   Could we perform a pseudo `getAndClear()` with the metadata error?
   
   ```suggestion
       private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
               if (events.isEmpty())
                   return;
   
               Optional<Exception> error = networkClientDelegate.getAndClearMetadataError();
               error.ifPresent(e -> events.forEach(event -> event.future().completeExceptionally(e));
           }
       }
   ```
   
   



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -165,9 +167,10 @@ private void processApplicationEvents() {
 
         for (ApplicationEvent event : events) {
             try {
-                if (event instanceof CompletableEvent)
+                if (event instanceof CompletableEvent) {
                     applicationEventReaper.add((CompletableEvent<?>) event);
-
+                    maybeFailOnMetadataError(List.of((CompletableEvent<?>) event));

Review Comment:
   Could you add a comment about why we're calling `maybeFailOnMetadataError()` here as well as at the end of `runOnce()`? I'm assuming this handles an important edge case, but I'm not sure I understand why from just looking at the code. 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -230,6 +227,14 @@ private ClientRequest makeClientRequest(
             unsent.handler
         );
     }
+    
+    public Optional<Exception> metadataError() {
+        return metadataError;
+    }
+    
+    public void clearMetadataError() {
+        metadataError = Optional.empty();
+    }

Review Comment:
   Then this can be a single operation:
   
   ```suggestion
       public Optional<Exception> getAndClearMetadataError() {
           Optional<Exception> e = metadataError;
           metadataError = Optional.empty();
           return e;
       }
   ```



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEventReaper.java:
##########
@@ -155,4 +156,13 @@ public int size() {
     public boolean contains(CompletableEvent<?> event) {
         return event != null && tracked.contains(event);
     }
+
+    public List<CompletableEvent<?>> uncompletedEvents() {
+        return tracked.stream()
+                .filter(e -> e instanceof CompletableApplicationEvent<?>)
+                .map(e -> (CompletableApplicationEvent<?>) e)
+                .filter(e -> !e.future().isDone())
+                .collect(Collectors.toList());
+    }

Review Comment:
   You don't have to filter by `CompletableApplicationEvent` is because `tracked` holds `CompletableEvents` already. 
   
   ```suggestion
       public List<CompletableEvent<?>> uncompletedEvents() {
           return tracked.stream()
                   .filter(e -> !e.future().isDone())
                   .collect(Collectors.toList());
       }
   ```



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1857306123


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -153,7 +154,16 @@ void runOnce() {
                 .map(rm -> rm.maximumTimeToWait(currentTimeMs))
                 .reduce(Long.MAX_VALUE, Math::min);
 
-        reapExpiredApplicationEvents(currentTimeMs);
+        List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);
+        
+        // If there is a metadata error, complete the completable events which are not passed by error event with the metadata error
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            completableEvents.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .forEach(event -> event.future().completeExceptionally(metadataError));
+            networkClientDelegate.clearMetadataError();

Review Comment:
   if there were no events to propagate the error, this line will still clear the error. Shouldn't we clear only if we were able to propagate it?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,6 +152,7 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();
         } catch (Exception e) {
+            metadataError = Optional.of(e);
             backgroundEventHandler.add(new ErrorEvent(e));

Review Comment:
   Seems to me you're really close to being able to remove this duplicated way of propagating metadata errors (and simplify the `isPassedByErrorEvent`)
   
   We now have a way to propagate metadata errors based on the triggering event, to fill a gap we have to let calls like position know about them. Then why exactly is it that we still need to propagate them via ErrorEvents still too? Seems to be for the consumer.poll case only, but I would expect that (once the gap from the comment above is addressed), the CheckAndUpdatePositions event should fail with subscription metadata errors, no matter if called from consumer.position or from consumer.poll. Makes sense? 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -153,7 +154,16 @@ void runOnce() {
                 .map(rm -> rm.maximumTimeToWait(currentTimeMs))
                 .reduce(Long.MAX_VALUE, Math::min);
 
-        reapExpiredApplicationEvents(currentTimeMs);
+        List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);
+        
+        // If there is a metadata error, complete the completable events which are not passed by error event with the metadata error
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            completableEvents.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .forEach(event -> event.future().completeExceptionally(metadataError));
+            networkClientDelegate.clearMetadataError();

Review Comment:
   should we encapsulate this in a kind of `maybeFailOnMetadataError` that would take the events? 
   
   Then I wonder if we need to do the same also before actually processing each event?? I'm thinking that, events that do require subscription metadata (ex. CheckAndUpdatePositions), may be processed, not generate any request and complete right away, so they will never know about the metadata error right?  Right before:
   https://github.com/apache/kafka/blob/57c4c386796028dc4144dfb50a2a786dac0a51a3/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java#L181
   
   Do we need to `maybeFailOnMetadataError(event)` to cover this gap?
   
   Note that it's not a replacement for the maybeFailOnMetadataError of awaiting events, I wonder if we need them both (to cover events that complete right away and never make it to the "awaiting" list, and also the ones that are left waiting).



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1683,10 +1683,10 @@ private Fetch<K, V> collectFetch() {
      * @throws NoOffsetForPartitionException If no offset is stored for a given partition and no offset reset policy is
      *                                       defined
      */
-    private boolean updateFetchPositions(final Timer timer) {
+    private boolean updateFetchPositions(final Timer timer, final boolean isPassedByErrorEvent) {

Review Comment:
   if the suggestion below works and we can get rid of the ErrorEvent for metadata errors, I hope we could end up removing this param, and just having a kind of requiresSubscriptionMetadata defined in events, and the CheckAndUpdatePositions event would have that true. So the network client would know that it needs to completeExceptionally the future for that event (and not for others that are not related to subscription metadata)....just an idea that depends on whether we can simplify the metadata error event  



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2506142764

   Hello @lianetm, I believe we still cannot abandon the transmission method of ErrorEvent. I’ve noticed that there are other ErrorEvents that are handled differently under various scenarios. Simply using an optional transmission method is not sufficient to handle so many different situations.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2506501437

   > I’m now thinking about the async consumer poll method. Originally, we used processBackgroundEvent to retrieve the Error event, but now we’re trying to use metadataError passing to restore its triggering point, which feels a bit difficult to find the same triggering point. due to it is processing in different thread.
   
   Sorry I don't quite get this. If we say that the `CheckAndUpdatePositions` events will fail with metadata errors, I expect the poll should fail on addAndGet of that event, triggered from here:
   
   https://github.com/apache/kafka/blob/e1ba01d21440a1de011c116a0bb6933656200009/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java#L1780
   
   Isn't that the 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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2508678301

   Hey @m1a2st , thanks for the updates, very nice result unifying how metadata errors are propagated. I'll take another close look. 
   
   One suggestion already: we can simplifying the tweak we had to introduce on the `unsubscribe` to ignore metadata errors (with your PR, they won't pop out unexpectedly), so I would say we can remove InvalidTopic and TopicAuth from here (leaving GroupAuth only)
   https://github.com/apache/kafka/blob/7ca02fd90840535b22ad61517288a8dea6a39515/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java#L1584
   
   and remove these tests that cover an scenario that is not valid anymore
   https://github.com/apache/kafka/blob/7ca02fd90840535b22ad61517288a8dea6a39515/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java#L273-L304  
   
   Makes sense? 


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1806735730


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1584,7 +1593,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(
+                    checkAndUpdatePositionsEvent.future(),
+                    timer, __ -> false
+            );

Review Comment:
   > It can't process  processBackgroundEvents() only once before applicationEventHandler.addAndGet. Test will be fail if I change to below, I think a loop for processBackgroundEvents is necessary
   
   This section also failed with we only process once. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2420148944

   I believe we need to have some filtering in the background event processing logic, because we don't want the checks to inadvertently execute the `ConsumerRebalanceListenerCallbackNeededEvent` if a rebalance was initiated in the background thread.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2420144047

   Also, this PR overlaps a lot with PR #17516, right?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2495765117

   > just FYI, we just enabled some auth tests that were marked as blocked on this issue, but are really not blocked on this (https://github.com/apache/kafka/pull/17885).
   
   Here are the four failing tests I’ve categorized:
   The first type is related to `GroupAuthorizationException`, which includes the following tests:
   	•	`testCommitWithNoAccess`
   	•	`testCommitWithNoGroupAccess`
   	•	`testOffsetFetchWithNoGroupAccess`
   
   These three should be addressed in JIRA 18034.
   
   However, the test `testPatternSubscriptionWithNoTopicAccess` seems to have a different root cause. I’ve noticed that this test does not trigger the `ConsumerRebalanceListenerCallbackCompletedEvent` at all. It might be worth opening a new JIRA ticket to track this issue. WDYT?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1858598236


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -153,7 +154,16 @@ void runOnce() {
                 .map(rm -> rm.maximumTimeToWait(currentTimeMs))
                 .reduce(Long.MAX_VALUE, Math::min);
 
-        reapExpiredApplicationEvents(currentTimeMs);
+        List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);
+        
+        // If there is a metadata error, complete the completable events which are not passed by error event with the metadata error
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            completableEvents.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .forEach(event -> event.future().completeExceptionally(metadataError));
+            networkClientDelegate.clearMetadataError();

Review Comment:
   I don't think it's necessary to execute `maybeFailOnMetadataError` before `applicationEventProcessor.process(event)`. Because, under normal situation, metadata errors only occur during the processing of events. Therefore, checking for metadata errors before processing is unnecessary.
   WDYT?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2517875078

   Hey @m1a2st , sorry I had missed the ShareConsumer question before. Seems we have different needs in the 2 consumers, so we should support notifying metadata errors via the generic error queue still, but to be used only from the ShareConsumer. The AsyncConsumer would not require such notification mechanism, given that it does have triggering API events that need to be completed with the error (so avoiding duplicated way of propagation on the async consumer, that we've seen how it becomes problematic). 
   
   Why do you think we need a new event? One option could be to simply have the flag that both consumers set differently: ShareConsumer creates the networkClients with a notifyMetadataErrorsViaErrorQueue=true, the async consumer with false, and then the network clients knows what to do based on that param.
   ```
   private void maybePropagateMetadataError() {
           ...
               if (notifyMetadataErrorsViaErrorQueue) {
                   backgroundEventHandler.add(new ErrorEvent(e));
               } else {
                   metadataError = Optional.of(e);
               }
           ...
       } 
   ```
   
   Would that work to cover the needs of both consumers? thoughts?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1838719823


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -230,6 +234,10 @@ private ClientRequest makeClientRequest(
             unsent.handler
         );
     }
+    
+    public CompletableFuture<RuntimeException> metaDataError() {

Review Comment:
   typo metadataError



##########
core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala:
##########
@@ -574,7 +574,7 @@ object QuorumTestHarness {
   // The following parameter groups are to *temporarily* avoid bugs with the CONSUMER group protocol Consumer
   // implementation that would otherwise cause tests to fail.
   def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_16176: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
-  def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17696: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
+  def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17696: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersConsumerGroupProtocolOnly

Review Comment:
   this "getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17696" was meant to be temporary, so instead of this we should change the tests that are using `@MethodSource(Array("getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17696"))` to use `@MethodSource(Array("getTestQuorumAndGroupProtocolParametersAll"))`, and remove this line. Could you try that to see where we are regarding failures? 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -256,12 +257,27 @@ public CompletableFuture<Boolean> updateFetchPositions(long deadlineMs) {
                 }
             });
 
+            onMetadataError(metadataError, result);
+
         } catch (Exception e) {
             result.completeExceptionally(maybeWrapAsKafkaException(e));
         }
         return result;
     }
 
+    private void onMetadataError(CompletableFuture<RuntimeException> metadataError, 
+                                 CompletableFuture<Boolean> result) {
+        metadataError.whenComplete((__, error) -> {
+            if (error instanceof AuthorizationException && pendingOffsetFetchEvent != null) {

Review Comment:
   With this change we're propagating the metadata error to fail the pending `OffsetFetch` request. But there could be other requests in this manager that need to be aware of the metadata error too I expect, ex. `ListOffsets` (that would be the case of any api call to beginningOffsets/endOffsets/offsetsForTimes without topic access).



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1849333895


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -230,6 +234,10 @@ private ClientRequest makeClientRequest(
             unsent.handler
         );
     }
+    
+    public CompletableFuture<RuntimeException> metadataError() {
+        return metadataException;
+    }

Review Comment:
   Any reason not to match the names?
   
   ```suggestion
       public CompletableFuture<RuntimeException> metadataException() {
           return metadataException;
       }
   ```



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,6 +152,8 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();
         } catch (Exception e) {
+            metadataException.completeExceptionally(e);
+            metadataException = metadataException.newIncompleteFuture();

Review Comment:
   What's the benefit of `newIncompleteFuture()` over `new CompletableFuture()`?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -206,12 +213,20 @@ public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchO
                         " Result {}", timestampsToSearch, result);
             }
         });
-
+        

Review Comment:
   Nit: whitespace cleanup.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -206,12 +213,20 @@ public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchO
                         " Result {}", timestampsToSearch, result);
             }
         });
-
+        
         prepareFetchOffsetsRequests(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
-        return listOffsetsRequestState.globalResult.thenApply(
+
+        topicToOffsetsResult.set(listOffsetsRequestState.globalResult.thenApply(
                 result -> OffsetFetcherUtils.buildOffsetsForTimeInternalResult(
                         timestampsToSearch,
-                        result.fetchedOffsets));
+                        result.fetchedOffsets)));
+
+        new ArrayList<>(metadataErrors).forEach(metadataError -> metadataError.whenComplete((__, error) -> {
+            topicToOffsetsResult.get().completeExceptionally(error);

Review Comment:
   This looks like we're completing the same `Future` multiple times 🤔 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -186,9 +187,15 @@ public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
      */
     public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchOffsets(
             Map<TopicPartition, Long> timestampsToSearch,
-            boolean requireTimestamps) {
+            boolean requireTimestamps,
+            List<CompletableFuture<RuntimeException>> metadataErrors
+    ) {
+        AtomicReference<CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>>> 
+                topicToOffsetsResult = new AtomicReference<>();
+        
         if (timestampsToSearch.isEmpty()) {
-            return CompletableFuture.completedFuture(Collections.emptyMap());
+            topicToOffsetsResult.get().complete(Collections.emptyMap());
+            return topicToOffsetsResult.get();

Review Comment:
   Wouldn't this throw a `NullPointerException`?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -186,9 +187,15 @@ public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
      */
     public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchOffsets(
             Map<TopicPartition, Long> timestampsToSearch,
-            boolean requireTimestamps) {
+            boolean requireTimestamps,
+            List<CompletableFuture<RuntimeException>> metadataErrors
+    ) {
+        AtomicReference<CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>>> 
+                topicToOffsetsResult = new AtomicReference<>();

Review Comment:
   I'm not following the need for this to be wrapped in an `AtomicReference`. All of the things happening are happening on the background thread, right? As such they don't need to be thread safe. (That's a major design goal of the new consumer.)



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2489200990

   I’m thinking that some test fail for methods like `consumer.poll`, which involve processBackgroundEvent, if a `TopicAuthorizationException` occurs, these two error handling mechanisms might conflict, leading to behavior that deviates from expectations.
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2489954215

   > I’m thinking that some test fail for methods like `consumer.poll`, which involve processBackgroundEvent, if a `TopicAuthorizationException` occurs, these two error handling mechanisms might conflict, leading to behavior that deviates from expectations.
   
   Sorry I missed this comment before. Great point, the issue is that with this PR (no matter how we implement it) we end up failing api calls/events on metadata errors, but still also keeping the previous logic that generated an ErrorEvent for them. 
   
   https://github.com/apache/kafka/blob/e73edce10bf0badf46d729045b57dc982666bd5a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java#L155-L157
   
   We were propagating metadata errors via ErrorEvent thinking that it was only meant to be consumed from poll (which was a wrong assumption). If, with this PR, we introduce a mechanism to propagate it via the api events, I wonder if we should consider removing the redundant ErrorEvent for this case? (without ErrorEvent, poll would still fail as expected, because the CheckAndUpdatePositions would fail with the auth error)


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2422823486

   > Do we need to perform this same check in more places than just the handful in this PR?
   
   If we want process all background event from the `backgroundEventQueue`, I think when we call `applicationEventHandler.addAndGet` we always need to call `processBackgroundEvents` first, check the `backgroundEventQueue` doesn't have any error event.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "FrankYang0529 (via GitHub)" <gi...@apache.org>.
FrankYang0529 commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1805826816


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1277,10 +1284,12 @@ private void releaseAssignmentAndLeaveGroup(final Timer timer) {
         UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
         applicationEventHandler.add(unsubscribeEvent);
         try {
-            // If users subscribe to an invalid topic name, they will get InvalidTopicException in error events,
+            // If users subscribe to an invalid topic name or subscribe an authorization topic,
+            // they will get InvalidTopicException or TopicAuthorizationException in error events,
             // because network thread keeps trying to send MetadataRequest in the background.
             // Ignore it to avoid unsubscribe failed.
-            processBackgroundEvents(unsubscribeEvent.future(), timer, e -> e instanceof InvalidTopicException);
+            processBackgroundEvents(unsubscribeEvent.future(), timer,
+                    e -> e instanceof InvalidTopicException || e instanceof TopicAuthorizationException || e instanceof GroupAuthorizationException);

Review Comment:
   I think we need a similar fix for `AsyncKafkaConsumer#unsubscribe` as well.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2422360789

   Hello @FrankYang0529 feel free to reopen this [PR](https://github.com/apache/kafka/pull/17516), this PR can focus `processBackgroundEvents` and `applicationEventHandler.addAndGet`. Due to I can't pass the test, so I fix `close` method in this PR.
   


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1827819017


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1574,7 +1583,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(

Review Comment:
   > I'm afraid that processing background here events could bring undesired effects, mainly because it may include callbacks, which are totally unrelated to a call to consumer.position() for instance.
   If there's a call to consumer.position, and a reconciliation starts in the background around the same time (ie. new partition assigned from the broker), the background will enqueue a CallbackNeededEvent, so we could end up actually running the callback here, as part of the call to position, which is not right.
   
   This is a preliminary thought: to prevent CallbackNeededEvent from being executed out of order, we could use a PriorityQueue to manage events based on their timestamps. This way, if an incorrect event is retrieved, it can be re-queued without disrupting the processing sequence.
   
   > I believe that we should not use processBackgroundEvents as a means of knowing that a specific event that we sent to the background failed. We should ensure that the event is completed exceptionally in the background instead. Wouldn't that work, and avoid mixing errors and callbacks? (related info in the jira too)
   
   I've been exploring the use of CompletableFuture to manage metadata exceptions in the new Kafka consumer. However, I've encountered some test failures, which may indicate differences in behavior compared to the classic consumer. This makes me question if this approach is the best way to refactor error handling in the new consumer.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850521972


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java:
##########
@@ -425,6 +427,13 @@ public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitSync(fina
         CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
         OffsetCommitRequestState requestState = createOffsetCommitRequest(commitOffsets, deadlineMs);
         commitSyncWithRetries(requestState, result);
+        new ArrayList<>(metadataErrors).forEach(metadataError -> metadataError.whenComplete((__, error) -> {
+            if (error != null) {
+                result.completeExceptionally(error);
+                metadataErrors.remove(metadataError);
+            }
+        }));
+        

Review Comment:
   thanks for considering the split! Sounds good. 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875248156


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegateTest.java:
##########
@@ -212,9 +213,27 @@ public void testPropagateMetadataError() {
         AuthenticationException authException = new AuthenticationException("Test Auth Exception");
         doThrow(authException).when(metadata).maybeThrowAnyException();
 
+        NetworkClientDelegate networkClientDelegate = newNetworkClientDelegate(false);
+        assertTrue(networkClientDelegate.getAndClearMetadataError().isEmpty());
+        networkClientDelegate.poll(0, time.milliseconds());
+        
+        assertTrue(networkClientDelegate.getAndClearMetadataError().isPresent());

Review Comment:
   You are right, I missed that we will clear the metadata error.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1860563297


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +330,23 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, complete the completable events which are not passed by 
+     * error event with the metadata error
+     * @param events the completable events
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            List<CompletableEvent<?>> completableApplicationEvent = events.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && 
+                            ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .collect(Collectors.toList());
+            if (!completableApplicationEvent.isEmpty()) {
+                completableApplicationEvent.forEach(event -> event.future().completeExceptionally(metadataError));
+                networkClientDelegate.clearMetadataError();
+            }
+        }
+    }

Review Comment:
   If no events are present, we should not clear the metadata error. Instead, we should propagate this error to the next event. Therefore, using `foreach` to handle this scenario is not appropriate. we should check it have any event first.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1860573841


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CheckAndUpdatePositionsEvent.java:
##########
@@ -32,4 +32,8 @@ public class CheckAndUpdatePositionsEvent extends CompletableApplicationEvent<Bo
     public CheckAndUpdatePositionsEvent(long deadlineMs) {
         super(Type.CHECK_AND_UPDATE_POSITIONS, deadlineMs);
     }
+
+    public CheckAndUpdatePositionsEvent(long deadlineMs, boolean isPassedByErrorEvent) {
+        super(Type.CHECK_AND_UPDATE_POSITIONS, deadlineMs, isPassedByErrorEvent);
+    }

Review Comment:
   For me, a `CompletableApplicationEvent` is an event that needs to be handled by the application thread. The application thread has two options for processing such events: `processBackgroundEvent` and `addAndGet`. Therefore, every event should have this parameter. However, currently, only the `CheckAndUpdatePositionsEvent` uses it.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1873289601


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   I believe we shouldn't clear the metadata error here because once a metadata error is encountered, there might not necessarily be an event to trigger it next time. This could result in the metadata error not being propagated. Therefore, we should wait until it is thrown before clearing it.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1835289473


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1574,7 +1583,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(

Review Comment:
   Hello @lianetm 
   Let me first explain my understanding of the current issue and the approach I’m using.
   
   When `consumer#position()` is called and reaches the line `applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);`, it gets blocked because `addAndGet` requires a response to proceed. However, in the current setup, the background thread converts errors into Error Events. This means the application thread won’t receive any errors if it hasn’t executed `processBackgroundEvents`.
   
   >  we have a “direct” way of communicating the 2 threads
   
   To address this, I’ve implemented a `CompletableFuture<Exception> metadataException` within the `NetworkClientDelegate `class specifically for storing errors that occur in the background thread. So in `NetworkClientDelegate#maybePropagateMetadataError`, if no error is present, I refresh the future. If there is an error, I call `metadataException.completeExceptionally(e);`.
   
   The reason for this design is that when `ConsumerNetworkThread#processApplicationEvents` executes `checkAndUpdatePositionsEvent`, `TopicAuthorizationException` doesn’t immediately appear. Instead, it may take several iterations of `runOnce` before this error shows up. Without the future approach, this error can’t be propagated from the background thread to the OffsetsRequestManager. 
   
   > Catch metadata errors on ConsumerNetworkThread.runOnce and completeExceptionally all the requests it has (requests returned by the managers poll here
   
   I also catch the metadata error on this place, I think we can catch it when it also add to Error Event.
   https://github.com/m1a2st/kafka/blob/51788cfa92881f29d95bf0ee197c6e5c8cd21ea6/clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java#L156
   
   > Notify managers of the metadata error too (ie. onMetadataERror), in case they have requests generated that did not make it to point 1, but still need to fail (ie. Commit request manager may have unsentOffsetCommitRequests/unsentOffsetFetchRequests. I don't think any other keeps requests without sending them to the network client but let's double check)
   
   I also passing this error to the `OffsetsRequestManager#updateFetchPositions` when the process really get the event, It will passing the exception to the `OffsetsRequestManager` and let application thread know it is fail on `addAndGet` method.
   https://github.com/m1a2st/kafka/blob/51788cfa92881f29d95bf0ee197c6e5c8cd21ea6/clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java#L261
   
   However, some tests still fail, likely due to behavioral differences from the classic consumer. I'm not sure that I miss something about this problem. Please let me which Im missing,  Thanks for your review and suggestion.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1826189301


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1574,7 +1583,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(

Review Comment:
   I'm afraid that processing background here events could bring undesired effects, mainly because it may include callbacks, which are totally unrelated to a call to consumer.position() for instance.
   
   If there's a call to consumer.position, and a reconciliation starts in the background around the same time (ie. new partition assigned from the broker), the background will enqueue a CallbackNeededEvent, so we could end up actually running the callback here, as part of the call to position, which is not right.
   
   I believe that we should not use `processBackgroundEvents` as a means of knowing that a specific event that we sent to the background failed. We should ensure that the event is completed exceptionally in the background instead. Wouldn't that work, and avoid mixing errors and callbacks? 



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1277,10 +1284,12 @@ private void releaseAssignmentAndLeaveGroup(final Timer timer) {
         UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
         applicationEventHandler.add(unsubscribeEvent);
         try {
-            // If users subscribe to an invalid topic name, they will get InvalidTopicException in error events,
+            // If users subscribe to an invalid topic name or subscribe an authorization topic,
+            // they will get InvalidTopicException or TopicAuthorizationException in error events,
             // because network thread keeps trying to send MetadataRequest in the background.
             // Ignore it to avoid unsubscribe failed.
-            processBackgroundEvents(unsubscribeEvent.future(), timer, e -> e instanceof InvalidTopicException);
+            processBackgroundEvents(unsubscribeEvent.future(), timer,
+                    e -> e instanceof InvalidTopicException || e instanceof TopicAuthorizationException || e instanceof GroupAuthorizationException);

Review Comment:
   uhm are we sure that swallowing TopicAuth and GroupAuth on close is the right thing to do? I could surely be missing something, but I believe it's not what the classic consumer does, see my comment on it on the other PR that is also attempting this https://github.com/apache/kafka/pull/17516#discussion_r1824955585
   Thoughts?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1805164231


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1277,10 +1284,12 @@ private void releaseAssignmentAndLeaveGroup(final Timer timer) {
         UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
         applicationEventHandler.add(unsubscribeEvent);
         try {
-            // If users subscribe to an invalid topic name, they will get InvalidTopicException in error events,
+            // If users subscribe to an invalid topic name or subscribe an authorization topic,
+            // they will get InvalidTopicException or TopicAuthorizationException in error events,
             // because network thread keeps trying to send MetadataRequest in the background.
             // Ignore it to avoid unsubscribe failed.
-            processBackgroundEvents(unsubscribeEvent.future(), timer, e -> e instanceof InvalidTopicException);
+            processBackgroundEvents(unsubscribeEvent.future(), timer,
+                    e -> e instanceof InvalidTopicException || e instanceof TopicAuthorizationException || e instanceof GroupAuthorizationException);

Review Comment:
   For readability, could you introduce a `Predicate` variable, a la:
   
   ```suggestion
               final Predicate<Exception> ignoreExceptions = e ->
                   e instanceof InvalidTopicException ||
                   e instanceof TopicAuthorizationException ||
                   e instanceof GroupAuthorizationException;
               processBackgroundEvents(unsubscribeEvent.future(), timer, ignoreExceptions);
   ```



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1132,7 +1135,11 @@ private Map<TopicPartition, Long> beginningOrEndOffset(Collection<TopicPartition
 
             Map<TopicPartition, OffsetAndTimestampInternal> offsetAndTimestampMap;
             try {
-                offsetAndTimestampMap = applicationEventHandler.addAndGet(listOffsetsEvent);
+                applicationEventHandler.add(listOffsetsEvent);
+                offsetAndTimestampMap = processBackgroundEvents(
+                        listOffsetsEvent.future(),
+                        timer, __ -> false
+                );

Review Comment:
   As I understand it, we need to check for the errors from the background thread. But do we need to check _repeatedly_ during the execution of the `ListOffsetsEvent`, or can we just check once beforehand?
   
   ```suggestion
                   processBackgroundEvents();
                   offsetAndTimestampMap = applicationEventHandler.addAndGet(listOffsetsEvent);
   ```
   
   



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1584,7 +1593,11 @@ private boolean updateFetchPositions(final Timer timer) {
         try {
             CheckAndUpdatePositionsEvent checkAndUpdatePositionsEvent = new CheckAndUpdatePositionsEvent(calculateDeadlineMs(timer));
             wakeupTrigger.setActiveTask(checkAndUpdatePositionsEvent.future());
-            cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
+            applicationEventHandler.add(checkAndUpdatePositionsEvent);
+            cachedSubscriptionHasAllFetchPositions = processBackgroundEvents(
+                    checkAndUpdatePositionsEvent.future(),
+                    timer, __ -> false
+            );

Review Comment:
   ```suggestion
               processBackgroundEvents();
               cachedSubscriptionHasAllFetchPositions = applicationEventHandler.addAndGet(checkAndUpdatePositionsEvent);
   ```



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875210056


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   ok, we're saying it gets cleared as soon as it's propagated (to ensure that it's indeed propagated), and we could still get an exception from a previously sent request (this was my concern). Anyways that's actually what we have with the classic consumer, so it's consistent (there are actually tests specifically covering the behaviour considering that). 
   https://github.com/apache/kafka/blob/ee4264439ddda7bdebcaa845752b824abba14161/core/src/test/scala/integration/kafka/api/EndToEndAuthorizationTest.scala#L553-L554  



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

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


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1848318657


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java:
##########
@@ -188,6 +190,8 @@ private void onFailedResponse(final long currentTimeMs, final Throwable exceptio
         if (exception == Errors.GROUP_AUTHORIZATION_FAILED.exception()) {
             log.debug("FindCoordinator request failed due to authorization error {}", exception.getMessage());
             KafkaException groupAuthorizationException = GroupAuthorizationException.forGroupId(this.groupId);
+            metadataError.completeExceptionally(groupAuthorizationException);
+            metadataError = metadataError.newIncompleteFuture();

Review Comment:
   Although I haven’t implemented it yet, I’ve been considering that this approach would lead to three different ways of handling exceptions in the background thread:
   	1.	ErrorEvent
   	2.	Completed future
   	3.	Exception
   
   It feels a bit inconsistent, but I’ll try this out first. If it works, We can revisit and refactor this issue later.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2488429832

   Hello @lianetm, @kirktrue I will focus on `NetworkClientDelegate#maybePropagateMetadataError` in this PR, and revert `CoordinatorRequestManager` fatal error this PR, and mark fail tests which fail reason is `CoordinatorRequestManager` for `getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_18034`
   Is it make sense?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2489427648

   Hey @m1a2st, sharing a thought in case it helps. First, the problem we have is that api calls like position/endOffsets trigger events that should fail with topic metadata errors but they don't, and are left hanging until they time out. So, with that in mind, it occurred to me that we do have all the events that are awaiting responses in hand when then `ConsumerNetworkThread.runOnce` happens, because we have them within the reaper, that keeps all the completableEvents so they can be expired eventually. Couldn't we take those events and let them know about the error when it happens? Then each event decides if it should fail on topic metadata error or not. I'm picturing something along these lines:
   
   On ConsumerNetworkThread.runOnce:
   ```
           // 1. get metadata error that happens here
           networkClientDelegate.poll(pollWaitTimeMs, currentTimeMs);
           ...
           // 2. get all awaiting events after expiration applies (the reaper has them all, not just the ones generated on the current runOnce)
           List<CompletableApplicationEvent> awaitingEvents = reapExpiredApplicationEvents(currentTimeMs);
   
           // 3. notify awaiting events about the metadata error
           if (metadataError != null) {
               awaitingEvents.forEach(e -> e.onMetadataError(metadataError));
           }
   ```
   Would that work?  I see that the main advantages would be to avoid the complexity of metadata future errors passed around to specific manager calls, and also it would be a solution applied consistently to all events (each event type then deciding if it should fail or not on topic metadata errors). onMetadataError, events could no-op by default, and some should override to simply do future.completeExceptionally, ex. `CheckAndUpdatePositionsEvent`, `CommitEvent` (these two seem to be the ones leading to the failed tests in the Authorizer file, we can get into details later about what others should consider the error).
   
   I could be missing something but sharing in case it helps! Let me know. 


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1860952945


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -153,7 +154,16 @@ void runOnce() {
                 .map(rm -> rm.maximumTimeToWait(currentTimeMs))
                 .reduce(Long.MAX_VALUE, Math::min);
 
-        reapExpiredApplicationEvents(currentTimeMs);
+        List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);
+        
+        // If there is a metadata error, complete the completable events which are not passed by error event with the metadata error
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            completableEvents.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .forEach(event -> event.future().completeExceptionally(metadataError));
+            networkClientDelegate.clearMetadataError();

Review Comment:
   > so they will never fail with the metadata error because we would call completeExceptionally on a future that is already complete right?
   
   That makes sense. We could encounter a metadata error while processing the last event, and we should use that error to complete all application events at the beginning of the next loop.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1858732555


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -153,7 +154,16 @@ void runOnce() {
                 .map(rm -> rm.maximumTimeToWait(currentTimeMs))
                 .reduce(Long.MAX_VALUE, Math::min);
 
-        reapExpiredApplicationEvents(currentTimeMs);
+        List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);
+        
+        // If there is a metadata error, complete the completable events which are not passed by error event with the metadata error
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            completableEvents.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .forEach(event -> event.future().completeExceptionally(metadataError));
+            networkClientDelegate.clearMetadataError();

Review Comment:
   the trick is that events may complete right away on the call to process, so they will never fail with the metadata error because we would call completeExceptionally on a future that is already complete right?  (I wonder if this gap is the reason why you still need the `ErrorEvent` for metadata? if we remove the error event propagation on ln 156, and fill this gap, would it work? it would be nice because there would be one single consistent way of propagating metadata errors: via the calling api event. Ex. we would get TopicAuthException on poll and on positions in the same way, just because the CheckAndUpdatePositions fails. Makes sense? just suggesting to try it out, I could still be missing something but can see the gap in how we completeExceptionally with metadta errors.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1826158308


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1277,10 +1284,12 @@ private void releaseAssignmentAndLeaveGroup(final Timer timer) {
         UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
         applicationEventHandler.add(unsubscribeEvent);
         try {
-            // If users subscribe to an invalid topic name, they will get InvalidTopicException in error events,
+            // If users subscribe to an invalid topic name or subscribe an authorization topic,
+            // they will get InvalidTopicException or TopicAuthorizationException in error events,
             // because network thread keeps trying to send MetadataRequest in the background.
             // Ignore it to avoid unsubscribe failed.
-            processBackgroundEvents(unsubscribeEvent.future(), timer, e -> e instanceof InvalidTopicException);
+            processBackgroundEvents(unsubscribeEvent.future(), timer,
+                    e -> e instanceof InvalidTopicException || e instanceof TopicAuthorizationException || e instanceof GroupAuthorizationException);

Review Comment:
   uhm are we sure that swallowing TopicAuth and GroupAuth on close is the right thing to do? I could surely be missing something, but I believe it's not what the classic consumer does, see my comment on it on the other PR that is also attempting this https://github.com/apache/kafka/pull/17516#discussion_r1824955585 
   Thoughts?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2449711867

   @kirktrue , Yhanks for your reminder, I will take a look at these fail tests


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2488891424

   > I will focus on NetworkClientDelegate#maybePropagateMetadataError in this PR, and revert CoordinatorRequestManager fatal error this PR, and mark fail tests which fail reason is CoordinatorRequestManager for getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_18034
   
   Sounds great to me! So I expect we'll end up with this PR addressing how we propagate metadata errors within the background thread to fail requests that should be aware of the error (should unblock all auth tests expecting TopicAuth error in api calls). Another PR addressing how we propagate coordinator errors within the background to fail requests similarly (unblock tests expecting GroupAuthErrors in api calls)


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850181200


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetsRequestManager.java:
##########
@@ -206,12 +213,20 @@ public CompletableFuture<Map<TopicPartition, OffsetAndTimestampInternal>> fetchO
                         " Result {}", timestampsToSearch, result);
             }
         });
-
+        
         prepareFetchOffsetsRequests(timestampsToSearch, requireTimestamps, listOffsetsRequestState);
-        return listOffsetsRequestState.globalResult.thenApply(
+
+        topicToOffsetsResult.set(listOffsetsRequestState.globalResult.thenApply(
                 result -> OffsetFetcherUtils.buildOffsetsForTimeInternalResult(
                         timestampsToSearch,
-                        result.fetchedOffsets));
+                        result.fetchedOffsets)));
+
+        new ArrayList<>(metadataErrors).forEach(metadataError -> metadataError.whenComplete((__, error) -> {
+            topicToOffsetsResult.get().completeExceptionally(error);

Review Comment:
   In the current version, there are two places where CompletedFuture is used to propagate errors:
   	1.	`NetworkClientDelegate#maybePropagateMetadataError`
   	2.	`CoordinatorRequestManager`
   
   As a result, we need a list to store the different errors coming from these two sources.
   > Just with the goal of simplifying here, is a future really needed or just keeping the error could do? The main difference with the metadata errors is that the CommitRequestManager.poll called regularly will have the pending requests in hand, so we could fail them if there is a fatal error in the coordinator manager.
   
   But if we can pass the `CoordinatorRequestManager` fatal error to use exception, we should not use List to store these CompletedFuture.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1870240540


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +331,15 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (events.isEmpty())
+            return;
+        networkClientDelegate.getAndClearMetadataError().ifPresent(metadataError ->
+                events.forEach(event -> event.future().completeExceptionally(metadataError))

Review Comment:
   I wonder if we still need to tune this a bit more. Here we're failing all completable events we may have if there is a metadata error, but there are lots of events that are not concerned about subscription metadata and would also fail right? Actually, I expect we only need to fail on the `CheckAndUpdatePositions` event, that is triggered from poll and positions (aligned with how the classic consumer does client.poll on those 2 calls propagating the metadata error, all other calls that do not call client.poll will never get metadata errors and we should ensure the same).
   
   Makes sense? (if so, one options could be to have all events implement a kind of requiresSubcriptionMetadata() that returns false by default, and CheckAndUpdatePositions returns true). Thoughts? 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2517732852

   Hello @lianetm
   I think I still need to confirm with you about the `ShareConsumerImpl`. The original design of `ShareConsumerImpl` relied solely on ErrorEvent to propagate errors, and SharedConsumer does not include `CompletableEvent` during polling. Therefore, with the current design, it is unable to propagate metadata errors.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1870543237


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +331,15 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (events.isEmpty())
+            return;
+        networkClientDelegate.getAndClearMetadataError().ifPresent(metadataError ->
+                events.forEach(event -> event.future().completeExceptionally(metadataError))

Review Comment:
   It make sense to me, I will addressed it :)



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875198457


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +333,21 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, complete all uncompleted events that require subscription metadata.
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        List<? extends CompletableApplicationEvent<?>> subscriptionMetadataEvent = events.stream()
+                .filter(e -> e instanceof CompletableApplicationEvent<?>)
+                .map(e -> (CompletableApplicationEvent<?>) e)
+                .filter(CompletableApplicationEvent::requireSubscriptionMetadata)
+                .collect(Collectors.toUnmodifiableList());

Review Comment:
   nit: `.toList();`? (I believe it's unmodifiable too)



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   ok, we're saying it gets cleared as soon as it's propagated (to ensure that it's indeed propagated), but we could still get an exception from a previously sent request (this was my concern). But that's what we have with the classic consumer actually, so it's consistent (there are actually tests specifically covering the behaviour considering that)
   https://github.com/apache/kafka/blob/ee4264439ddda7bdebcaa845752b824abba14161/core/src/test/scala/integration/kafka/api/EndToEndAuthorizationTest.scala#L553-L554  



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegateTest.java:
##########
@@ -212,9 +213,26 @@ public void testPropagateMetadataError() {
         AuthenticationException authException = new AuthenticationException("Test Auth Exception");
         doThrow(authException).when(metadata).maybeThrowAnyException();
 
+        NetworkClientDelegate networkClientDelegate = newNetworkClientDelegate(false);
+        assertTrue(networkClientDelegate.getAndClearMetadataError().isEmpty());
+        networkClientDelegate.poll(0, time.milliseconds());
+        
+        networkClientDelegate.getAndClearMetadataError().ifPresent(

Review Comment:
   if the metadata error is not present this won't fail right, so should we check it's present? (and then check the value)



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1875210056


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,7 +155,11 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();

Review Comment:
   ok, we're saying it gets cleared as soon as it's propagated (to ensure that it's indeed propagated), and we could still get an exception from a previously sent request (this was my concern). Anyways that's actually what we have with the classic consumer, so it's consistent (there are actually tests specifically covering the behaviour considering that). 
   https://github.com/apache/kafka/blob/ee4264439ddda7bdebcaa845752b824abba14161/core/src/test/scala/integration/kafka/api/EndToEndAuthorizationTest.scala#L553-L554  
   
   Ok with me, I wonder if there something we could improve there for both but no need to block this as it's the current behaviour. I'll file a jira if I come up with clear thoughts about it. Thanks!



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1826158308


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:
##########
@@ -1277,10 +1284,12 @@ private void releaseAssignmentAndLeaveGroup(final Timer timer) {
         UnsubscribeEvent unsubscribeEvent = new UnsubscribeEvent(calculateDeadlineMs(timer));
         applicationEventHandler.add(unsubscribeEvent);
         try {
-            // If users subscribe to an invalid topic name, they will get InvalidTopicException in error events,
+            // If users subscribe to an invalid topic name or subscribe an authorization topic,
+            // they will get InvalidTopicException or TopicAuthorizationException in error events,
             // because network thread keeps trying to send MetadataRequest in the background.
             // Ignore it to avoid unsubscribe failed.
-            processBackgroundEvents(unsubscribeEvent.future(), timer, e -> e instanceof InvalidTopicException);
+            processBackgroundEvents(unsubscribeEvent.future(), timer,
+                    e -> e instanceof InvalidTopicException || e instanceof TopicAuthorizationException || e instanceof GroupAuthorizationException);

Review Comment:
   uhm are we sure that swallowing TopicAuth and GroupAuth on close is the right thing to do? I could surely be missing something, but I believe it's not what the classic consumer does, see my comment on it on the other PR that is also attempting this https://github.com/apache/kafka/pull/17516#discussion_r1824955585 
   Thoughts?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850110819


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -230,6 +234,10 @@ private ClientRequest makeClientRequest(
             unsent.handler
         );
     }
+    
+    public CompletableFuture<RuntimeException> metadataError() {
+        return metadataException;
+    }

Review Comment:
   I miss it, I will update it



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1846829642


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CoordinatorRequestManager.java:
##########
@@ -188,6 +190,8 @@ private void onFailedResponse(final long currentTimeMs, final Throwable exceptio
         if (exception == Errors.GROUP_AUTHORIZATION_FAILED.exception()) {
             log.debug("FindCoordinator request failed due to authorization error {}", exception.getMessage());
             KafkaException groupAuthorizationException = GroupAuthorizationException.forGroupId(this.groupId);
+            metadataError.completeExceptionally(groupAuthorizationException);
+            metadataError = metadataError.newIncompleteFuture();

Review Comment:
   Just with the goal of simplifying here, is a future really needed or just keeping the error could do? The main difference with the metadata errors is that the `CommitRequestManager.poll` called regularly will have the pending requests in hand, so we could fail them if there is a fatal error in the coordinator manager. Would that work?  



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java:
##########
@@ -425,6 +427,13 @@ public CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> commitSync(fina
         CompletableFuture<Map<TopicPartition, OffsetAndMetadata>> result = new CompletableFuture<>();
         OffsetCommitRequestState requestState = createOffsetCommitRequest(commitOffsets, deadlineMs);
         commitSyncWithRetries(requestState, result);
+        new ArrayList<>(metadataErrors).forEach(metadataError -> metadataError.whenComplete((__, error) -> {
+            if (error != null) {
+                result.completeExceptionally(error);
+                metadataErrors.remove(metadataError);
+            }
+        }));
+        

Review Comment:
   this is only handling the commit sync but we do have other requests that should also fail if there is a fatal error in the coordinator. Given that all requests that this manager sends end up being added to the `pendingRequests`, and we attempt to send them on poll, shouldn't we just check on poll of there is no coordinator due to a fatal error and fail all pendingRequests? It would ensure we behave consistently for all requests.
   
   ```
       public NetworkClientDelegate.PollResult poll(final long currentTimeMs) {
           if (!coordinatorRequestManager.coordinator().isPresent()) {
               if (coordinatorRequestManager.fatalError().isPresent()) {
                   // Fatal error looking up coordinator => Fail all pendingRequests
               }
               return EMPTY;
           }
           ...
   ```
   I created this separate Jira https://issues.apache.org/jira/browse/KAFKA-18034 for this, given that it's a different gap and fix. I would suggest we address that in a separate/simpler PR with these thoughts, what do you think? 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1850170638


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/NetworkClientDelegate.java:
##########
@@ -150,6 +152,8 @@ private void maybePropagateMetadataError() {
         try {
             metadata.maybeThrowAnyException();
         } catch (Exception e) {
+            metadataException.completeExceptionally(e);
+            metadataException = metadataException.newIncompleteFuture();

Review Comment:
   I don’t see any real benefit; I simply chose to use this method because Java provides it. Ultimately, this method internally just creates a new CompletedFuture.
   ```java
       public <U> CompletableFuture<U> newIncompleteFuture() {
           return new CompletableFuture<U>();
       }
   ```



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2506802870

   >  If we say that the CheckAndUpdatePositions events will fail with metadata errors, I expect the poll should fail on addAndGet of that event, triggered from here:
   
   we remove the Error Event, thus there are some other test fail, Im tracing these fail test, and I'm thing about how we deal with  other type of metadata error 
   - FAILED ❌ TransactionsTest > testFencingOnSend(String, String).quorum=kraft.groupProtocol=classic
   - FAILED ❌ ShareConsumerTest > testSubscribeOnInvalidTopicThrowsInvalidTopicException(String).persister=org.apache.kafka.server.share.persister.NoOpShareStatePersister
   - FAILED ❌ ShareConsumerTest > testSubscribeOnInvalidTopicThrowsInvalidTopicException(String).persister=org.apache.kafka.server.share.persister.DefaultStatePersister
   - FAILED ❌ GroupEndToEndAuthorizationTest > testNoConsumeWithoutDescribeAclViaSubscribe(String, String).quorum=kraft.groupProtocol=consumer
   - FAILED ❌ PlaintextConsumerPollTest > testNoOffsetForPartitionExceptionOnPollZero(String, String).quorum=kraft.groupProtocol=consumer
   - FAILED ❌ KafkaConsumerTest > "testMissingOffsetNoResetPolicy(GroupProtocol).groupProtocol=CONSUMER"
   - FAILED ❌ KafkaConsumerTest > "testSubscriptionOnInvalidTopic(GroupProtocol).groupProtocol=CONSUMER"
   - FAILED ❌ KafkaConsumerTest > "testFetchStableOffsetThrowInPoll(GroupProtocol).groupProtocol=CONSUMER"


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2499021858

   Regarding:
   
   > However, the test `testPatternSubscriptionWithNoTopicAccess` seems to have a different root cause. I’ve noticed that this test does not trigger the ConsumerRebalanceListenerCallbackCompletedEvent at all. It might be worth opening a new JIRA ticket to track this issue. WDYT?
   
   Agree that is unrelated to this PR. Looking into it, that test is actually checking a behviour that is different between the 2 protocols/consumer. With the new protocol a member must always provide subscribed topics (or regex) to join a group, so if subscribed to a java pattern where no topics are found (because of auth, or any reason), there won't be callbacks triggered. Seems to me that test should only run for the classic consumer (and maybe let's just add a comment about how the behaviour is different with the new protocol). Makes sense?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1859304634


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -168,6 +171,8 @@ private void processApplicationEvents() {
                 if (event instanceof CompletableEvent)
                     applicationEventReaper.add((CompletableEvent<?>) event);
 
+                List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);

Review Comment:
   Do we need to reap the events on every loop?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CheckAndUpdatePositionsEvent.java:
##########
@@ -32,4 +32,8 @@ public class CheckAndUpdatePositionsEvent extends CompletableApplicationEvent<Bo
     public CheckAndUpdatePositionsEvent(long deadlineMs) {
         super(Type.CHECK_AND_UPDATE_POSITIONS, deadlineMs);
     }
+
+    public CheckAndUpdatePositionsEvent(long deadlineMs, boolean isPassedByErrorEvent) {
+        super(Type.CHECK_AND_UPDATE_POSITIONS, deadlineMs, isPassedByErrorEvent);
+    }

Review Comment:
   At this point it looks like `CheckAndUpdatePositionsEvent` is the only event that uses `isPassedByErrorEvent`. Any reason not to define it in this event as opposed to the superclass?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEventReaper.java:
##########
@@ -102,6 +102,8 @@ public void reap(long currentTimeMs) {
         // Second, remove any events that are already complete, just to make sure we don't hold references. This will
         // include any events that finished successfully as well as any events we just completed exceptionally above.
         tracked.removeIf(e -> e.future().isDone());
+        
+        return tracked;

Review Comment:
   I'm not sure I understand this pattern. Can we add a new method that returns the tracked events instead of overloading the purpose of `reap()`?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +330,23 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, complete the completable events which are not passed by 
+     * error event with the metadata error
+     * @param events the completable events
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            List<CompletableEvent<?>> completableApplicationEvent = events.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && 
+                            ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .collect(Collectors.toList());
+            if (!completableApplicationEvent.isEmpty()) {
+                completableApplicationEvent.forEach(event -> event.future().completeExceptionally(metadataError));
+                networkClientDelegate.clearMetadataError();
+            }
+        }
+    }

Review Comment:
   Do we only want to clear the error if an event "consumed" the error?



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +330,23 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, complete the completable events which are not passed by 
+     * error event with the metadata error
+     * @param events the completable events
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (networkClientDelegate.metadataError().isPresent()) {
+            Throwable metadataError = networkClientDelegate.metadataError().get();
+            List<CompletableEvent<?>> completableApplicationEvent = events.stream()
+                    .filter(event -> !(event instanceof CompletableApplicationEvent && 
+                            ((CompletableApplicationEvent<?>) event).isPassedByErrorEvent()))
+                    .collect(Collectors.toList());
+            if (!completableApplicationEvent.isEmpty()) {
+                completableApplicationEvent.forEach(event -> event.future().completeExceptionally(metadataError));
+                networkClientDelegate.clearMetadataError();
+            }
+        }
+    }

Review Comment:
   It seems like this could be a little more succinct:
   
   ```suggestion
       private void maybeFailOnMetadataError() {
          networkClientDelegate.metadataError().ifPresent(metadataError -> {
               applicationEventReaper.tracked().stream()
                   .filter(e -> e instanceof CompletableApplicationEvent<?>)
                   .map(e -> (CompletableApplicationEvent<?>) e)
                   .filter(e -> e.isPassedByErrorEvent())
                   .filter(e -> !e.future().isDone())
                   .forEach(e -> e.future().completeExceptionally(metadataError));
               networkClientDelegate.clearMetadataError();
           }));
       }
   ```



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -168,6 +171,8 @@ private void processApplicationEvents() {
                 if (event instanceof CompletableEvent)
                     applicationEventReaper.add((CompletableEvent<?>) event);
 
+                List<CompletableEvent<?>> completableEvents = reapExpiredApplicationEvents(currentTimeMs);

Review Comment:
   It seems like we should remove the reaping from this method entirely and have `runOnce()` call `maybeFailOnMetadataError()` directly.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableApplicationEvent.java:
##########
@@ -38,6 +43,13 @@ protected CompletableApplicationEvent(final Type type, final long deadlineMs) {
         this.deadlineMs = deadlineMs;
     }
 
+    protected CompletableApplicationEvent(final Type type, final long deadlineMs, final boolean isPassedByErrorEvent) {
+        super(type);
+        this.future = new CompletableFuture<>();
+        this.deadlineMs = deadlineMs;
+        this.isPassedByErrorEvent = isPassedByErrorEvent;
+    }

Review Comment:
   I'd prefer to see the other constructor call this one so that we have as few paths as possible.



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2415794828

   Sorry for late to reply you,
   Thanks @kirktrue suggestions, I find a good way to resolve the close problem, the `TopicAuthorizationException`[1] is similar with `InvalidTopicException`, thus I think I can add an `or` check in this if else condition [2], it is more clear and simplify
   [1] https://github.com/apache/kafka/blob/604564cce3e195eece6927dc83d150e0150022fc/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java#L1232
   [2]
   https://github.com/apache/kafka/blob/604564cce3e195eece6927dc83d150e0150022fc/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java#L1283
   > Please take a look at @lianetm's comments on [KAFKA-17696](https://issues.apache.org/jira/browse/KAFKA-17696) again as I think she has some suggestions worth pursuing.
   I will take more deep think in these comments


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1868113120


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/CompletableEventReaper.java:
##########
@@ -155,4 +156,13 @@ public int size() {
     public boolean contains(CompletableEvent<?> event) {
         return event != null && tracked.contains(event);
     }
+
+    public List<CompletableEvent<?>> reapUnCompletableApplicationEvents() {

Review Comment:
   this is not really "reaping"/cancelling any event, so should we rename it? It's just retrieving uncompleted events, so  maybe uncompletedEvents/trackedEvents....



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +327,18 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError() {
+        List<CompletableEvent<?>> events = applicationEventReaper.reapUnCompletableApplicationEvents();

Review Comment:
   this is called from within a loop over the events on ln 171, so it means that in that case, we would be iterating all events in the reaper and here, for each event, right? what about this receiving the List of events as argument, then we have 2 usages:
   1. `maybeFailOnMetadataError(pendingCompletableEvents)` -> called with a list of events after all events are processed on ln 157.  Argument taken from the reaper.trackedEvents.
   2. `maybeFailOnMetadataError(List.of(event))` -> called before processing each event, argument taken from the current event in the loop.
   
   Thoughts?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2495404068

   Hello @lianetm, Thanks for your review.
   > We were propagating metadata errors via ErrorEvent thinking that it was only meant to be consumed from poll (which was a wrong assumption). If, with this PR, we introduce a mechanism to propagate it via the api events, I wonder if we should consider removing the redundant ErrorEvent for this case? (without ErrorEvent, poll would still fail as expected, because the CheckAndUpdatePositions would fail with the auth error)
   
   Based on this issue, the most straightforward solution I can think of at the moment is to add a new attribute in the event to determine whether the method call requires the use of the completedFuture for transmission. I have already drafted a version for this approach. WDYT?


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2517899431

   Yes, I believe this approach can solve the problem, but it does feel a bit frustrating since we spent quite some time unifying the metadata error propagation method. Perhaps we can create a task later to unify the error propagation behavior of both types of consumers.


-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "lianetm (via GitHub)" <gi...@apache.org>.
lianetm commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1870240540


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerNetworkThread.java:
##########
@@ -325,4 +331,15 @@ void cleanup() {
             log.debug("Closed the consumer network thread");
         }
     }
+
+    /**
+     * If there is a metadata error, completed all uncompleted events with the metadata error.
+     */
+    private void maybeFailOnMetadataError(List<CompletableEvent<?>> events) {
+        if (events.isEmpty())
+            return;
+        networkClientDelegate.getAndClearMetadataError().ifPresent(metadataError ->
+                events.forEach(event -> event.future().completeExceptionally(metadataError))

Review Comment:
   I wonder if we still need to tune this a bit more. Here we're failing all completable events we may have if there is a metadata error, but there are lots of events that are not concerned about subscription metadata and should not fail right? Actually, I expect we only need to fail on the `CheckAndUpdatePositions` event, that is triggered from poll and positions (aligned with how the classic consumer does client.poll on those 2 calls propagating the metadata error, all other calls that do not call client.poll will never get metadata errors and we should ensure the same).
   
   Makes sense? (if so, one options could be to have all events implement a kind of requiresSubcriptionMetadata() that returns false by default, and CheckAndUpdatePositions returns true). Thoughts? 



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "kirktrue (via GitHub)" <gi...@apache.org>.
kirktrue commented on code in PR #17440:
URL: https://github.com/apache/kafka/pull/17440#discussion_r1868631701


##########
core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala:
##########
@@ -576,8 +576,9 @@ object QuorumTestHarness {
   // The following parameter groups are to *temporarily* avoid bugs with the CONSUMER group protocol Consumer
   // implementation that would otherwise cause tests to fail.
   def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_16176: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
-  def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17696: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
   def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17960: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
   def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17961: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
   def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_17964: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
+  def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_18034: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly
+  def getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_18095: stream.Stream[Arguments] = getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly

Review Comment:
   KAFKA-18095 is marked as resolved in Jira. I'm assuming that means if you rebase, update the tests that use `getTestQuorumAndGroupProtocolParametersClassicGroupProtocolOnly_KAFKA_18095` to `getTestQuorumAndGroupProtocolParametersAll`, and retest, those tests should pass, right?



-- 
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: jira-unsubscribe@kafka.apache.org

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


Re: [PR] KAFKA-17696 New consumer background operations unaware of metadata errors [kafka]

Posted by "m1a2st (via GitHub)" <gi...@apache.org>.
m1a2st commented on PR #17440:
URL: https://github.com/apache/kafka/pull/17440#issuecomment-2517196485

   Thanks for @kirktrue comments, addressed them 


-- 
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: jira-unsubscribe@kafka.apache.org

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