This is an automated email from the ASF dual-hosted git repository.

markt-asf pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git

commit 70726a412b996274059ef6cf7b51c79ebcbc0de3
Author: Mark Thomas <[email protected]>
AuthorDate: Tue Dec 1 17:46:34 2026 +0000

    Do not fail if an async request is completed while error handling completes 
it
    
    AsyncContextImpl.setErrorState() checked that the request was still in the
    error state and then called complete(). If the application called complete()
    between the check and the call, the container's call failed with an
    IllegalStateException which skipped the remaining error handling for the
    request. Ignore the failure if the request is no longer in the error state.
    
    Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
 .../org/apache/catalina/core/AsyncContextImpl.java |  14 ++-
 .../coyote/TestAsyncContextImplSetErrorState.java  | 126 +++++++++++++++++++++
 webapps/docs/changelog.xml                         |   6 +
 3 files changed, 145 insertions(+), 1 deletion(-)

diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java 
b/java/org/apache/catalina/core/AsyncContextImpl.java
index bb87c80c8d..11035a7723 100644
--- a/java/org/apache/catalina/core/AsyncContextImpl.java
+++ b/java/org/apache/catalina/core/AsyncContextImpl.java
@@ -628,7 +628,19 @@ public class AsyncContextImpl implements AsyncContext, 
AsyncContextCallback {
             if (result.get()) {
                 // Still in the error state. The error page did not call
                 // complete() or dispatch(). Complete the async processing.
-                complete();
+                try {
+                    complete();
+                } catch (IllegalStateException ise) {
+                    /*
+                     * The application (or another container thread) may have 
called complete() or dispatch() after the
+                     * check above. That is not an error and the processing 
that call triggered will clean up. Only
+                     * propagate the exception if the request is still in the 
error state.
+                     */
+                    
request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
+                    if (result.get()) {
+                        throw ise;
+                    }
+                }
             }
         } else if (request.isAsyncDispatching()) {
             /*
diff --git a/test/org/apache/coyote/TestAsyncContextImplSetErrorState.java 
b/test/org/apache/coyote/TestAsyncContextImplSetErrorState.java
new file mode 100644
index 0000000000..0275da90c4
--- /dev/null
+++ b/test/org/apache/coyote/TestAsyncContextImplSetErrorState.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.coyote;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.catalina.core.AsyncContextImpl;
+
+/**
+ * Tests {@link AsyncContextImpl#setErrorState(Throwable, boolean)} when the 
application completes the asynchronous
+ * processing between the container checking that the request is still in the 
error state and the container completing
+ * it. The window is a few instructions wide so the competing call is 
simulated by an {@link ActionHook} that stands in
+ * for the async state machine.
+ */
+public class TestAsyncContextImplSetErrorState {
+
+    /**
+     * Mimics the parts of the async state machine used by setErrorState(): 
the error state, and a state that rejects a
+     * second call to complete().
+     */
+    private static class StubHook implements ActionHook {
+
+        private final boolean competingComplete;
+        private final AtomicBoolean inError = new AtomicBoolean(true);
+        private final AtomicBoolean completed = new AtomicBoolean(false);
+        private final AtomicInteger isErrorChecks = new AtomicInteger();
+
+        StubHook(boolean competingComplete) {
+            this.competingComplete = competingComplete;
+        }
+
+        @Override
+        public void action(ActionCode actionCode, Object param) {
+            switch (actionCode) {
+                case ASYNC_IS_ERROR: {
+                    AtomicBoolean result = (AtomicBoolean) param;
+                    // Checks 1 and 2 are the two made by setErrorState() 
before it calls complete()
+                    int check = isErrorChecks.incrementAndGet();
+                    result.set(inError.get());
+                    if (competingComplete && check == 2) {
+                        // The application calls complete() after the 
container has seen the error state
+                        complete();
+                    }
+                    break;
+                }
+                case ASYNC_COMPLETE: {
+                    complete();
+                    break;
+                }
+                default:
+                    break;
+            }
+        }
+
+        private void complete() {
+            if (!completed.compareAndSet(false, true)) {
+                throw new IllegalStateException();
+            }
+            inError.set(false);
+        }
+    }
+
+
+    private static AsyncContextImpl createAsyncContext(StubHook hook) {
+        Request coyoteRequest = new Request();
+        coyoteRequest.setHook(hook);
+        org.apache.catalina.connector.Request request = new 
org.apache.catalina.connector.Request(null);
+        request.setCoyoteRequest(coyoteRequest);
+        return new AsyncContextImpl(request);
+    }
+
+
+    @Test
+    public void testCompleteCalledByApplicationDuringErrorHandling() {
+        StubHook hook = new StubHook(true);
+        AsyncContextImpl asyncContext = createAsyncContext(hook);
+
+        // The container's call to complete() loses the race and must not fail
+        asyncContext.setErrorState(null, false);
+
+        // The two checks before complete() plus the check after it failed
+        Assert.assertEquals(3, hook.isErrorChecks.get());
+        Assert.assertTrue(hook.completed.get());
+    }
+
+
+    @Test
+    public void testCompleteFailureWhileStillInErrorStateIsReported() {
+        StubHook hook = new StubHook(false) {
+            @Override
+            public void action(ActionCode actionCode, Object param) {
+                if (actionCode == ActionCode.ASYNC_COMPLETE) {
+                    // Reject the call without leaving the error state
+                    throw new IllegalStateException();
+                }
+                super.action(actionCode, param);
+            }
+        };
+        AsyncContextImpl asyncContext = createAsyncContext(hook);
+
+        try {
+            asyncContext.setErrorState(null, false);
+            Assert.fail("IllegalStateException expected");
+        } catch (IllegalStateException expected) {
+            // Expected
+        }
+    }
+}
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index 526306e1c9..2749d1acdb 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -227,6 +227,12 @@
         when the container's error handling and the application complete the
         request concurrently. (markt)
       </fix>
+      <fix>
+        Avoid an <code>IllegalStateException</code> being logged, and the
+        completion of the asynchronous request being skipped, when the
+        application completes an asynchronous request while the container is
+        completing it after an error. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Coyote">


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to