adikou commented on code in PR #24226:
URL: https://github.com/apache/kafka/pull/24226#discussion_r4591968353


##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManagerTest.java:
##########
@@ -280,6 +282,84 @@ public void testGroupIdNotFoundWhileStableIsFatal() {
         verify(backgroundEventHandler).add(any());
     }
 
+    /**
+     * An unexpected exception thrown while handling a heartbeat response 
(successful) or a heartbeat
+     * request failure must not be lost (the callback runs on a future stage 
nobody observes). In both
+     * cases it must be logged, reach the application as an error event and 
fail the member.
+     */
+    @ParameterizedTest(name = "successfulResponse={0}")
+    @ValueSource(booleans = {true, false})
+    public void testUnexpectedErrorHandlingHeartbeatIsFatal(boolean 
successfulResponse) {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");
+
+        try (LogCaptureAppender logAppender = 
LogCaptureAppender.createAndRegister(heartbeatRequestManager.getClass())) {
+            completeHeartbeatThrowingWhileHandling(successfulResponse, 
unexpected);
+
+            assertErrorLogged(logAppender, "Unexpected error while handling " 
+ heartbeatRequestManager.heartbeatRequestName());
+        }
+        assertErrorEventCause(unexpected);
+        verify(membershipManager).transitionToFatal();
+        verify(membershipManager).onHeartbeatFailure(false);
+        assertFalse(heartbeatRequestState.requestInFlight(), "The request must 
not be left in flight");
+    }
+
+    /**
+     * If failing the member throws too (e.g. the member cannot transition to 
FATAL from its current
+     * state), the original error must still reach the application, and the 
second error must be logged.
+     */
+    @Test
+    public void testUnexpectedErrorWhileFailingMemberIsLogged() {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");

Review Comment:
   A misnomer: we do expect this exception to be thrown



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java:
##########
@@ -663,16 +663,47 @@ private NetworkClientDelegate.UnsentRequest 
makeHeartbeatRequestAndLogResponse(f
     private NetworkClientDelegate.UnsentRequest 
makeHeartbeatRequestAndHandleResponse(final long currentTimeMs) {
         NetworkClientDelegate.UnsentRequest request = 
makeHeartbeatRequest(currentTimeMs);
         return request.whenComplete((response, exception) -> {
-            long completionTimeMs = request.handler().completionTimeMs();
-            if (response != null) {
-                
metricsManager.recordRequestLatency(response.requestLatencyMs());
-                onResponse((StreamsGroupHeartbeatResponse) 
response.responseBody(), completionTimeMs);
-            } else {
-                onFailure(exception, completionTimeMs);
+            // Handle unexpected errors when processing a HB response, so that
+            // the member moves to a fatal state and the error reaches the 
application.
+            final long completionTimeMs = request.handler().completionTimeMs();
+            try {
+                if (response != null) {
+                    
metricsManager.recordRequestLatency(response.requestLatencyMs());
+                    onResponse((StreamsGroupHeartbeatResponse) 
response.responseBody(), completionTimeMs);
+                } else {
+                    onFailure(exception, completionTimeMs);
+                }
+            } catch (Throwable t) {
+                onUnexpectedResponseHandlingError(t, completionTimeMs);
             }
         });
     }
 
+    /**
+     * Handle an unexpected error thrown while handling a heartbeat response 
or a heartbeat request
+     * failure. This would be the case of a bug on the client or an 
unexpected/buggy response from the broker.
+     * The member transitions to {@link MemberState#FATAL} and the error is 
propagated to the application
+     * (just like any other fatal heartbeat error).
+     */
+    private void onUnexpectedResponseHandlingError(final Throwable error, 
final long currentTimeMs) {
+        final String errorMessage = String.format(
+            "Unexpected error while handling StreamsGroupHeartbeatRequest: 
%s", error);

Review Comment:
   Same comment on including error in the log/exception message. Cause is 
already a param



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManager.java:
##########
@@ -318,16 +319,47 @@ private NetworkClientDelegate.UnsentRequest 
makeHeartbeatRequest(final boolean i
             return logResponse(request);
         else
             return request.whenComplete((response, exception) -> {
+                // Handle unexpected errors when processing a HB response, so 
that
+                // the member moves to a fatal state and the error reaches the 
application.
                 long completionTimeMs = request.handler().completionTimeMs();
-                if (response != null) {
-                    
metricsManager.recordRequestLatency(response.requestLatencyMs());
-                    onResponse((R) response.responseBody(), completionTimeMs);
-                } else {
-                    onFailure(exception, completionTimeMs);
+                try {
+                    if (response != null) {
+                        
metricsManager.recordRequestLatency(response.requestLatencyMs());
+                        onResponse((R) response.responseBody(), 
completionTimeMs);
+                    } else {
+                        onFailure(exception, completionTimeMs);
+                    }
+                } catch (Throwable t) {
+                    onUnexpectedResponseHandlingError(t, completionTimeMs);
                 }
             });
     }
 
+    /**
+     * Handle an unexpected error thrown while handling a heartbeat response 
or a heartbeat request
+     * failure. This would be the case of a bug on the client or an 
unexpected/buggy response from the broker.
+     * The member transitions to {@link MemberState#FATAL} and the error is 
propagated to the application
+     * (just like any other fatal heartbeat error).
+     */
+    private void onUnexpectedResponseHandlingError(final Throwable error, 
final long currentTimeMs) {
+        String errorMessage = String.format("Unexpected error while handling 
%s: %s",
+            heartbeatRequestName(), error);

Review Comment:
   We're including the error already in the log line below which logs the 
proper msg+stacktrace. I think we can skip it here and just switch to string 
contact



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManagerTest.java:
##########
@@ -280,6 +282,84 @@ public void testGroupIdNotFoundWhileStableIsFatal() {
         verify(backgroundEventHandler).add(any());
     }
 
+    /**
+     * An unexpected exception thrown while handling a heartbeat response 
(successful) or a heartbeat
+     * request failure must not be lost (the callback runs on a future stage 
nobody observes). In both
+     * cases it must be logged, reach the application as an error event and 
fail the member.
+     */
+    @ParameterizedTest(name = "successfulResponse={0}")
+    @ValueSource(booleans = {true, false})
+    public void testUnexpectedErrorHandlingHeartbeatIsFatal(boolean 
successfulResponse) {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");
+
+        try (LogCaptureAppender logAppender = 
LogCaptureAppender.createAndRegister(heartbeatRequestManager.getClass())) {
+            completeHeartbeatThrowingWhileHandling(successfulResponse, 
unexpected);
+
+            assertErrorLogged(logAppender, "Unexpected error while handling " 
+ heartbeatRequestManager.heartbeatRequestName());
+        }
+        assertErrorEventCause(unexpected);
+        verify(membershipManager).transitionToFatal();
+        verify(membershipManager).onHeartbeatFailure(false);
+        assertFalse(heartbeatRequestState.requestInFlight(), "The request must 
not be left in flight");
+    }
+
+    /**
+     * If failing the member throws too (e.g. the member cannot transition to 
FATAL from its current
+     * state), the original error must still reach the application, and the 
second error must be logged.
+     */
+    @Test
+    public void testUnexpectedErrorWhileFailingMemberIsLogged() {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");
+        doThrow(new IllegalStateException("Invalid state transition from 
FENCED to FATAL"))
+            .when(membershipManager).transitionToFatal();
+
+        try (LogCaptureAppender logAppender = 
LogCaptureAppender.createAndRegister(heartbeatRequestManager.getClass())) {
+            completeHeartbeatThrowingWhileHandling(true, unexpected);
+
+            assertErrorLogged(logAppender, "Unexpected error while handling " 
+ heartbeatRequestManager.heartbeatRequestName());
+            assertErrorLogged(logAppender, "Unexpected error while failing the 
member");

Review Comment:
   We can still verify that the transition to fatal was invoked rather than 
just checking the log.



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManagerTest.java:
##########
@@ -280,6 +282,84 @@ public void testGroupIdNotFoundWhileStableIsFatal() {
         verify(backgroundEventHandler).add(any());
     }
 
+    /**
+     * An unexpected exception thrown while handling a heartbeat response 
(successful) or a heartbeat
+     * request failure must not be lost (the callback runs on a future stage 
nobody observes). In both
+     * cases it must be logged, reach the application as an error event and 
fail the member.
+     */
+    @ParameterizedTest(name = "successfulResponse={0}")
+    @ValueSource(booleans = {true, false})
+    public void testUnexpectedErrorHandlingHeartbeatIsFatal(boolean 
successfulResponse) {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");

Review Comment:
   Since you're catching Throwable above, an Error like OOMError here in 
addition, will increase coverage



##########
clients/src/test/java/org/apache/kafka/clients/consumer/internals/AbstractHeartbeatRequestManagerTest.java:
##########
@@ -280,6 +282,84 @@ public void testGroupIdNotFoundWhileStableIsFatal() {
         verify(backgroundEventHandler).add(any());
     }
 
+    /**
+     * An unexpected exception thrown while handling a heartbeat response 
(successful) or a heartbeat
+     * request failure must not be lost (the callback runs on a future stage 
nobody observes). In both
+     * cases it must be logged, reach the application as an error event and 
fail the member.
+     */
+    @ParameterizedTest(name = "successfulResponse={0}")
+    @ValueSource(booleans = {true, false})
+    public void testUnexpectedErrorHandlingHeartbeatIsFatal(boolean 
successfulResponse) {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");
+
+        try (LogCaptureAppender logAppender = 
LogCaptureAppender.createAndRegister(heartbeatRequestManager.getClass())) {
+            completeHeartbeatThrowingWhileHandling(successfulResponse, 
unexpected);
+
+            assertErrorLogged(logAppender, "Unexpected error while handling " 
+ heartbeatRequestManager.heartbeatRequestName());
+        }
+        assertErrorEventCause(unexpected);
+        verify(membershipManager).transitionToFatal();
+        verify(membershipManager).onHeartbeatFailure(false);
+        assertFalse(heartbeatRequestState.requestInFlight(), "The request must 
not be left in flight");
+    }
+
+    /**
+     * If failing the member throws too (e.g. the member cannot transition to 
FATAL from its current
+     * state), the original error must still reach the application, and the 
second error must be logged.
+     */
+    @Test
+    public void testUnexpectedErrorWhileFailingMemberIsLogged() {
+        IllegalStateException unexpected = new 
IllegalStateException("unexpected error handling heartbeat");
+        doThrow(new IllegalStateException("Invalid state transition from 
FENCED to FATAL"))
+            .when(membershipManager).transitionToFatal();
+
+        try (LogCaptureAppender logAppender = 
LogCaptureAppender.createAndRegister(heartbeatRequestManager.getClass())) {
+            completeHeartbeatThrowingWhileHandling(true, unexpected);
+
+            assertErrorLogged(logAppender, "Unexpected error while handling " 
+ heartbeatRequestManager.heartbeatRequestName());
+            assertErrorLogged(logAppender, "Unexpected error while failing the 
member");
+        }
+        assertErrorEventCause(unexpected);
+    }
+
+    /**
+     * Sends a heartbeat and completes it with a successful response, or with 
a request failure, making
+     * the handling of it throw the given error.
+     */
+    private void completeHeartbeatThrowingWhileHandling(boolean 
successfulResponse, RuntimeException error) {
+        if (successfulResponse) {

Review Comment:
   Reading `doThrow` behind a successfulResponse is a bit hard to follow. I 
guess this is to verify that we set the membership to fatal but also ensure 
that we continue on by logging another error? That seem like two more test 
cases to me. 
   
   Same for the streams test cases below



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to