[
https://issues.apache.org/jira/browse/GROOVY-12763?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18144700#comment-18144700
]
ASF GitHub Bot commented on GROOVY-12763:
-----------------------------------------
daniellansun commented on code in PR #3298:
URL: https://github.com/apache/groovy/pull/3298#discussion_r4571183253
##########
COMPATIBILITY.md:
##########
@@ -1683,6 +1683,24 @@ time, is unaffected.
**Who is not affected (binary).** Existing call sites are compiled against
the unchanged existing overloads.
+### Groovy 6.0.1 — async constructs rethrow a checked exception as itself
(GROOVY-12763)
+
+In 6.0.0, `await` rethrew a checked exception from an async task unchanged,
+but other async constructs wrapped it: a scope's child task failure and a
+`defer` action in `RuntimeException`, a `withScope` body and a generator body
+in `UndeclaredThrowableException`, and a `Flow.Publisher` error consumed with
+`for await` in `RuntimeException`. All of them now rethrow the original
+exception, as `await` does. Async/await is incubating.
+
+**Who is affected.** Code that catches `RuntimeException` or
+`UndeclaredThrowableException` around these constructs and reads
+`getCause()` to find a checked exception. Catch the checked exception
+directly instead. Java callers of `AsyncScope.close()` and `withScope`,
+which declare no checked exceptions, catch `Exception` and test its type.
+
+**What is unchanged.** Unchecked exceptions and errors, which were never
+wrapped, and `await` itself. There are no API changes.
Review Comment:
Minor wording nit: since `org.apache.groovy.runtime.async.AsyncSupport`
promotes `rethrow(Throwable)` to `public static RuntimeException` and adds
`public static Throwable unwrapUndeclared(Throwable)` for cross-package access
from `groovy.concurrent`, would it be slightly more accurate to scope this
statement to `groovy.concurrent`?
```suggestion
**What is unchanged.** Unchecked exceptions and errors, which were never
wrapped, and `await` itself. There are no public API signature changes in
`groovy.concurrent`.
```
##########
src/main/java/org/apache/groovy/runtime/async/AsyncSupport.java:
##########
@@ -265,15 +265,14 @@ public static void executeDeferScope(Deque<Callable<?>>
scope) {
} catch (Throwable t) {
if (firstError == null) {
firstError = t;
- } else {
+ } else if (t != firstError) {
+ // Deferred actions may rethrow one shared exception
instance
firstError.addSuppressed(t);
}
}
}
if (firstError != null) {
- if (firstError instanceof RuntimeException re) throw re;
- if (firstError instanceof Error err) throw err;
- throw new RuntimeException(firstError);
+ throw rethrow(firstError);
Review Comment:
Two subtle observations on `executeDeferScope`:
1. **Wrapper behavior across `async` tasks vs. `async` generators:**
`executeDeferScope` itself keeps `firstError` as-is (`throw
rethrow(firstError)` without calling `unwrap`). In
`testScopeChildAndDeferUnwrapAsAwaitDoes`, `await async { defer { throw new
ExecutionException(new IOException('inner')) }; 1 }` unwraps
`ExecutionException` only because the outer `await` runs
`AsyncSupport.unwrap(...)` on the completed future. If the exact same `defer`
block runs inside an `async` generator (`yield return`), `GeneratorBridge`
calls `unwrapUndeclared` rather than `unwrap`, so `ExecutionException` is
preserved. Keeping `executeDeferScope` wrapper-neutral here actually feels like
the right design—just worth noting so the test comment / PR description aligns
with what happens in generator-hosted `defer` blocks.
2. **Transitive duplicate suppression:** `t != firstError` prevents
self-suppression against `firstError`, which fixes the crash in `GROOVY-12764`.
If Action 1 throws `errA` and Actions 2 and 3 both rethrow a shared `errB`
(`errB != errA`), `errB` is still appended twice to `errA.getSuppressed()`. A
small `addSuppressedUnique(firstError, t)` helper (shared with
`DefaultAsyncScope.close()`) would keep `getSuppressed()` free of duplicate
object references in fan-out cleanup scenarios.
##########
src/main/java/org/apache/groovy/runtime/async/AsyncSupport.java:
##########
@@ -547,11 +546,35 @@ public static Throwable unwrap(Throwable t) {
}
/**
- * Rethrows {@code failure} as itself, including a checked exception.
+ * Removes the {@link UndeclaredThrowableException} that converting a
closure
+ * to a functional interface such as {@code Function} or {@code Consumer}
puts
+ * around a checked exception. Only that layer is removed: any other
wrapper,
+ * including one the code threw itself, is returned unchanged.
+ *
+ * @param t the exception thrown through the converted closure
+ * @return the checked exception it carries, or {@code t} itself
+ */
+ public static Throwable unwrapUndeclared(Throwable t) {
+ if (t instanceof UndeclaredThrowableException) {
+ Throwable cause = t.getCause();
+ if (cause != null && !(cause instanceof RuntimeException) &&
!(cause instanceof Error)) {
+ return cause;
+ }
+ }
+ return t;
+ }
Review Comment:
If I am tracing this right, stripping a wrapper via `t.getCause()` in both
`unwrapUndeclared` and `unwrap` (just above line 546) will silently drop any
suppressed exceptions that were attached to the outer wrapper
(`t.getSuppressed()`).
For example, when an earlier-executed `defer` action (or a `Future.get()` /
reflective `Method.invoke()` call inside `async`) throws
`ExecutionException(IOException('primary'))` and a subsequent `defer` action
(or inner `try-with-resources`) throws `IOException('cleanup')`:
1. `executeDeferScope` attaches `IOException('cleanup')` via
`firstError.addSuppressed(...)` onto the outer `ExecutionException`.
2. `await` (or `DefaultAsyncScope.close()`) calls
`AsyncSupport.unwrap(...)`, returning the inner `IOException('primary')` with
`getSuppressed().length == 0`—losing `'cleanup'`.
The same loss can happen in `unwrapUndeclared` if an intermediate resource
guard attaches a suppressed exception onto `UndeclaredThrowableException`
before `withScope` or `GeneratorBridge` unwraps it. Since
`Throwable.getSuppressed()` returns a shared empty array constant in OpenJDK
when no suppressed exceptions exist, migrating them is allocation-free on the
common path:
```suggestion
public static Throwable unwrapUndeclared(Throwable t) {
if (t instanceof UndeclaredThrowableException) {
Throwable cause = t.getCause();
if (cause != null && !(cause instanceof RuntimeException) &&
!(cause instanceof Error)) {
return transferSuppressed(t, cause);
}
}
return t;
}
private static Throwable transferSuppressed(Throwable wrapper, Throwable
unwrapped) {
for (Throwable suppressed : wrapper.getSuppressed()) {
if (suppressed != unwrapped) {
unwrapped.addSuppressed(suppressed);
}
}
return unwrapped;
}
```
If we apply the same `transferSuppressed(current, next)` step inside
`unwrap(Throwable t)`'s loop above, suppressed cleanup failures across `await`,
`DefaultAsyncScope.close()`, `withScope`, and `GeneratorBridge` will all be
preserved intact.
*(Minor side note: adding a brief Javadoc sentence on `unwrapUndeclared` and
`rethrow` noting that `AsyncSupport` is internal runtime infrastructure—not
user-facing public API—could also help preserve refactoring flexibility when we
revisit closure conversion in a later release.)*
##########
src/main/java/org/apache/groovy/runtime/async/FlowPublisherAdapter.java:
##########
@@ -268,9 +268,7 @@ public boolean hasNext() {
}
if (item == ERROR) {
terminated = true;
- if (error instanceof RuntimeException re) throw re;
- if (error instanceof Error err) throw err;
- throw new RuntimeException(error);
+ throw AsyncSupport.rethrow(error);
Review Comment:
+1 on using plain `AsyncSupport.rethrow(error)` here without `unwrap` or
`unwrapUndeclared`. That ensures publisher-originated wrappers in reactive
ecosystems (such as Project Reactor's `Exceptions.propagate` /
`ReactiveException`) are preserved as upstream semantics rather than stripped
as Groovy machinery, while raw checked exceptions signaled via
`onError(Throwable)` propagate transparently.
##########
src/main/java/org/apache/groovy/runtime/async/GeneratorBridge.java:
##########
@@ -117,9 +117,8 @@ public boolean hasNext() {
done = true;
Throwable error = (Throwable) pending[1];
pending = null;
- if (error instanceof RuntimeException re) throw re;
- if (error instanceof Error err) throw err;
- throw new RuntimeException(error);
+ // A checked exception from the generator body arrives wrapped by
its SAM coercion
+ throw AsyncSupport.rethrow(AsyncSupport.unwrapUndeclared(error));
Review Comment:
Non-blocking thought on the known limitation noted in the PR description: in
real-world code, `UndeclaredThrowableException(checked)` most often comes from
JDK `java.lang.reflect.Proxy` invocation handlers (Spring AOP, MyBatis mappers,
RPC stubs) rather than manual `new UndeclaredThrowableException(...)`. Because
`UndeclaredThrowableException` is unchecked, dynamic `ConvertedClosure` adds no
second layer (and `@CompileStatic` `LambdaMetafactory` never adds
`UndeclaredThrowableException` at all), so `unwrapUndeclared` will strip the
framework proxy's wrapper in both modes.
Leaving `AsyncScope.withScope` entry-point changes for a later release makes
total sense (since adding a 1-arg `ThrowingFunction` overload on `AsyncScope`
would trigger Java lambda ambiguity, and keeping `groovy-concurrent-java` free
of `Closure` is desirable). Just as food for thought when you revisit this:
since `AsyncSupport.asyncGenerator` is internal `@GroovyABI` compiler plumbing
rather than a user-called API, adding a distinct internal entry point taking a
`ThrowingConsumer` SAM (while keeping `asyncGenerator(Consumer<Object>)` as a
binary bridge for `6.0.0` classfiles) could avoid SAM wrapping on generators
without any public API impact. Totally fine to defer both together to keep
`6.0.1` minimal!
##########
src/main/java/groovy/concurrent/AsyncScope.java:
##########
@@ -46,6 +46,15 @@
* task completes exceptionally, all sibling tasks are cancelled
* immediately. The first failure becomes the primary exception;
* subsequent failures are added as suppressed exceptions.
+ * <p>
+ * A failure is rethrown as the exception the task threw, including a
+ * checked exception, as {@code await} does.
+ *
+ * @apiNote {@link #close()} and {@code withScope} declare no checked
+ * exceptions but can still throw one. Java callers that need to handle a
+ * checked failure should catch {@code Exception} and test its type, as
+ * the Java compiler rejects a {@code catch} of a checked exception the
+ * try block does not declare.
Review Comment:
Nice addition—documenting the sneaky-throw behavior explicitly via
`@apiNote` on `AsyncScope` and `close()` is very helpful for pure Java callers
of `groovy-concurrent-java`, where `javac` rejects catching undeclared checked
exceptions per JLS §11.2.3.
Two small optional doc refinements if helpful:
1. **Cross-referencing on `withScope` overloads:** Adding a short `@apiNote`
pointer on the `withScope` methods back to the class-level note would let IDE
hover tooltips on `AsyncScope.withScope(...)` surface this caveat directly to
Java callers.
2. **Contrasting `withScope` with Java `try-with-resources`:** When a scope
body and a child task fail with (or `await`) the same exception instance,
`withScope` safely guards `if (closeError != bodyError)` at line 186, whereas
Java's `try (var scope = AsyncScope.create())` emits an unconditional
`primary.addSuppressed(closeError)` (`JDK-8317229`) and would throw
`IllegalArgumentException: Self-suppression not permitted` now that `close()`
rethrows the raw failure unwrapped.
##########
src/test/groovy/groovy/AsyncAwaitTest.groovy:
##########
@@ -4115,17 +4115,228 @@ final class AsyncAwaitTest {
}
@Test
- void testScopeCloseWithCheckedExceptionWrapped() {
+ void testScopeCloseRethrowsCheckedExceptionUnwrapped() {
assertScript '''
import groovy.concurrent.AsyncScope
def scope = AsyncScope.create()
- scope.async { throw new Exception('checked-err') }
+ scope.async { throw new IOException('checked-err') }
try {
scope.close()
assert false
- } catch (RuntimeException e) {
- assert e.cause.message == 'checked-err'
+ } catch (IOException e) {
+ assert e.message == 'checked-err'
+ }
+ '''
+ }
+
+ // Checked exceptions surface as themselves from every async construct, as
from await
+
+ @Test
+ void testWithScopeChildCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+
+ try {
+ AsyncScope.withScope { scope ->
+ scope.async { throw new IOException('child') }
+ null
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'child'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.time.Duration
+
+ try {
+ AsyncScope.withScope { scope -> throw new IOException('body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'body'
+ }
+ try {
+ AsyncScope.withScope(Duration.ofSeconds(5)) { scope -> throw
new IOException('timed body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'timed body'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+
+ try {
+ AsyncScope.withScope { scope -> throw new
ExecutionException(new IOException('inner')) }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+
+ def gen = async {
+ yield return 1
+ throw new ExecutionException(new IOException('inner'))
+ }
+ try {
+ for (x in gen) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testDeferCheckedExceptionTransparency() {
+ assertScript '''
+ try {
+ await async {
+ defer { throw new IOException('cleanup') }
+ 1
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'cleanup'
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorCheckedExceptionTransparency() {
+ assertScript '''
+ def gen = async {
+ yield return 1
+ throw new IOException('gen')
+ }
+ def seen = []
+ try {
+ for (x in gen) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'gen'
+ }
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherCheckedExceptionTransparency() {
+ assertScript '''
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def seen = []
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.submit(1)
+ // closeExceptionally may overtake an undelivered item
+ while (pub.estimateMaximumLag() > 0) Thread.onSpinWait()
+ pub.closeExceptionally(new IOException('flow'))
+ }
+ try {
+ for await (x in pub) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'flow'
+ }
+ producer.join()
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.closeExceptionally(new ExecutionException(new
IOException('inner')))
+ }
+ try {
+ for await (x in pub) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ producer.join()
+ '''
+ }
+
+ // A wrapper thrown by a child task or deferred action is removed, exactly
as await removes it
+
+ @Test
+ void testScopeChildAndDeferUnwrapAsAwaitDoes() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+ import static groovy.test.GroovyAssert.shouldFail
+
+ def wrapped = { new ExecutionException(new IOException('inner')) }
+ def viaAwait = shouldFail(IOException) { await async { throw
wrapped() } }
+ def viaChild = shouldFail(IOException) {
+ AsyncScope.withScope { scope -> scope.async { throw wrapped()
}; null }
+ }
+ def viaDefer = shouldFail(IOException) {
+ await async { defer { throw wrapped() }; 1 }
+ }
+ assert [viaAwait, viaChild, viaDefer]*.message == ['inner'] * 3
+ '''
+ }
+
+ @Test
+ void testCheckedExceptionTransparencyUnderCompileStatic() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import groovy.transform.CompileStatic
+ import static groovy.test.GroovyAssert.shouldFail
+
+ @CompileStatic
+ class Paths {
+ static void child() {
+ AsyncScope.withScope { AsyncScope scope -> scope.async {
throw new IOException('child') }; null }
+ }
+ static void body() {
+ AsyncScope.withScope { AsyncScope scope -> throw new
IOException('body') }
+ }
+ static void deferred() {
+ await async { defer { throw new IOException('defer') }; 1 }
+ }
+ static void generator() {
+ def gen = async { yield return 1; throw new
IOException('gen') }
+ for (x in gen) { }
+ }
+ }
+
+ ['child', 'body', 'defer', 'gen'].eachWithIndex { String msg, int
i ->
+ def e = shouldFail(IOException) {
+ switch (i) {
+ case 0 -> Paths.child()
+ case 1 -> Paths.body()
+ case 2 -> Paths.deferred()
+ default -> Paths.generator()
+ }
+ }
+ assert e.message == msg
}
Review Comment:
Thorough regression suite—especially spinning on `pub.estimateMaximumLag() >
0` before `closeExceptionally` to avoid `SubmissionPublisher` race flakiness!
Three targeted additions would round out the test matrix nicely:
1. **`@CompileStatic` parity for `for await` and timed `withScope`:**
`Paths` above exercises `child`, `body`, `defer`, and `generator` under
`@CompileStatic`, while `FlowPublisherAdapter` (`for await`) and
`withScope(Duration, ...)` are currently only covered in dynamic mode.
2. **Timed `withScope(Duration, ...)` shared-failure & timeout-cause
tests:** Testing a shared checked `IOException` awaited by both a timed
`withScope(Duration.ofSeconds(5))` body and its child task (regression test for
`withScopeTimeout`'s `try-with-resources` self-suppression), plus verifying
`TimeoutException.getCause()` is `InterruptedException` rather than
`UndeclaredThrowableException` when a dynamic timed scope expires.
3. **Suppressed-exception preservation across wrapper removal:** Verifying
that when an outer wrapper (such as `ExecutionException(new
IOException('primary'))` in a `defer` block followed by another `defer`
throwing `IOException('cleanup')`) is unwrapped, `'cleanup'` remains attached
to `primary.getSuppressed()`.
##########
src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java:
##########
@@ -156,13 +156,14 @@ public void close() {
}
if (firstError == null) {
firstError = cause;
- } else {
+ } else if (cause != firstError) {
+ // Children may share one failure instance, e.g. by
awaiting the same task
firstError.addSuppressed(cause);
}
} catch (Exception e) {
if (firstError == null) {
firstError = e;
- } else {
+ } else if (e != firstError) {
firstError.addSuppressed(e);
}
}
Review Comment:
Optional refinement: `cause != firstError` cleanly prevents
`Self-suppression not permitted` when the repeated failure is the very first
error. In a fan-out scope where Child 1 fails with `errA` and Children 2..N all
`await` the same failed upstream task (`errB`), `errB != errA` evaluates to
`true` on each iteration and attaches the same `errB` instance `N - 1` times to
`firstError.getSuppressed()`. Delegating both sites here (and in
`executeDeferScope`) to a tiny identity-checking helper (e.g., skipping if
`cause` is already in `firstError.getSuppressed()`) would avoid duplicate
suppressed stack traces in fan-out workloads.
##########
src/test/groovy/groovy/AsyncAwaitTest.groovy:
##########
@@ -4115,17 +4115,228 @@ final class AsyncAwaitTest {
}
@Test
- void testScopeCloseWithCheckedExceptionWrapped() {
+ void testScopeCloseRethrowsCheckedExceptionUnwrapped() {
assertScript '''
import groovy.concurrent.AsyncScope
def scope = AsyncScope.create()
- scope.async { throw new Exception('checked-err') }
+ scope.async { throw new IOException('checked-err') }
try {
scope.close()
assert false
- } catch (RuntimeException e) {
- assert e.cause.message == 'checked-err'
+ } catch (IOException e) {
+ assert e.message == 'checked-err'
+ }
+ '''
+ }
+
+ // Checked exceptions surface as themselves from every async construct, as
from await
+
+ @Test
+ void testWithScopeChildCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+
+ try {
+ AsyncScope.withScope { scope ->
+ scope.async { throw new IOException('child') }
+ null
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'child'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.time.Duration
+
+ try {
+ AsyncScope.withScope { scope -> throw new IOException('body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'body'
+ }
+ try {
+ AsyncScope.withScope(Duration.ofSeconds(5)) { scope -> throw
new IOException('timed body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'timed body'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+
+ try {
+ AsyncScope.withScope { scope -> throw new
ExecutionException(new IOException('inner')) }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+
+ def gen = async {
+ yield return 1
+ throw new ExecutionException(new IOException('inner'))
+ }
+ try {
+ for (x in gen) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testDeferCheckedExceptionTransparency() {
+ assertScript '''
+ try {
+ await async {
+ defer { throw new IOException('cleanup') }
+ 1
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'cleanup'
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorCheckedExceptionTransparency() {
+ assertScript '''
+ def gen = async {
+ yield return 1
+ throw new IOException('gen')
+ }
+ def seen = []
+ try {
+ for (x in gen) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'gen'
+ }
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherCheckedExceptionTransparency() {
+ assertScript '''
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def seen = []
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.submit(1)
+ // closeExceptionally may overtake an undelivered item
+ while (pub.estimateMaximumLag() > 0) Thread.onSpinWait()
+ pub.closeExceptionally(new IOException('flow'))
+ }
+ try {
+ for await (x in pub) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'flow'
+ }
+ producer.join()
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.closeExceptionally(new ExecutionException(new
IOException('inner')))
+ }
+ try {
+ for await (x in pub) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ producer.join()
+ '''
+ }
+
+ // A wrapper thrown by a child task or deferred action is removed, exactly
as await removes it
+
+ @Test
+ void testScopeChildAndDeferUnwrapAsAwaitDoes() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+ import static groovy.test.GroovyAssert.shouldFail
+
+ def wrapped = { new ExecutionException(new IOException('inner')) }
+ def viaAwait = shouldFail(IOException) { await async { throw
wrapped() } }
+ def viaChild = shouldFail(IOException) {
+ AsyncScope.withScope { scope -> scope.async { throw wrapped()
}; null }
+ }
+ def viaDefer = shouldFail(IOException) {
+ await async { defer { throw wrapped() }; 1 }
+ }
+ assert [viaAwait, viaChild, viaDefer]*.message == ['inner'] * 3
+ '''
+ }
+
+ @Test
+ void testCheckedExceptionTransparencyUnderCompileStatic() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import groovy.transform.CompileStatic
+ import static groovy.test.GroovyAssert.shouldFail
+
+ @CompileStatic
+ class Paths {
+ static void child() {
+ AsyncScope.withScope { AsyncScope scope -> scope.async {
throw new IOException('child') }; null }
+ }
+ static void body() {
+ AsyncScope.withScope { AsyncScope scope -> throw new
IOException('body') }
+ }
+ static void deferred() {
+ await async { defer { throw new IOException('defer') }; 1 }
+ }
+ static void generator() {
+ def gen = async { yield return 1; throw new
IOException('gen') }
+ for (x in gen) { }
+ }
+ }
+
+ ['child', 'body', 'defer', 'gen'].eachWithIndex { String msg, int
i ->
+ def e = shouldFail(IOException) {
+ switch (i) {
+ case 0 -> Paths.child()
+ case 1 -> Paths.body()
+ case 2 -> Paths.deferred()
+ default -> Paths.generator()
+ }
+ }
+ assert e.message == msg
Review Comment:
`Paths` nicely verifies 4 of the 5 constructs under `@CompileStatic`. Could
we also include the 5th path (`for await` over a `SubmissionPublisher`) and the
timed `AsyncScope.withScope(Duration, ...)` overload here (plus a test
asserting `te.cause instanceof InterruptedException` when `withScope(Duration,
...)` times out in dynamic mode)? Since `@CompileStatic` uses
`LambdaMetafactory` and distinct STC rules for `for await` and `throws
TimeoutException` overloads, covering those two paths here will give full
parity across dynamic and static compilation:
```groovy
static void timedBody() {
AsyncScope.withScope(java.time.Duration.ofSeconds(5)) {
AsyncScope scope ->
throw new IOException('timed')
}
}
static void flowPublisher() {
def pub = new
java.util.concurrent.SubmissionPublisher<Integer>()
Thread.start {
while (pub.numberOfSubscribers == 0)
Thread.onSpinWait()
pub.closeExceptionally(new IOException('flow'))
}
for await (Integer x in pub) { }
}
```
##########
src/test/groovy/groovy/AsyncAwaitTest.groovy:
##########
@@ -4242,4 +4453,43 @@ final class AsyncAwaitTest {
'''
}
+ // One failure instance reaching close or defer twice is rethrown once,
not suppressed into itself
+
+ @Test
+ void testScopeCloseSharedFailureIsNotSelfSuppressed() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import static groovy.test.GroovyAssert.shouldFail
+
+ def shared = new IllegalStateException('shared')
+ def e = shouldFail(IllegalStateException) {
+ AsyncScope.withScope { scope ->
+ scope.async { throw shared }
+ scope.async { throw shared }
+ null
+ }
+ }
+ assert e.is(shared)
+ assert e.suppressed.length == 0
+ '''
+ }
Review Comment:
To lock in the fix for `DefaultAsyncScope.withScopeTimeout`'s
`try-with-resources` self-suppression edge case (where both the timed scope
body and a child task throw or `await` the same checked exception instance),
could we add a timed-scope assertion alongside this test?
```groovy
@Test
void testWithScopeTimeoutSharedFailureIsNotSelfSuppressed() {
assertScript '''
import groovy.concurrent.AsyncScope
import java.time.Duration
import static groovy.test.GroovyAssert.shouldFail
def shared = new IOException('shared-timed')
def e = shouldFail(IOException) {
AsyncScope.withScope(Duration.ofSeconds(5)) { scope ->
def child = scope.async { throw shared }
try { await child } catch (Throwable ignored) {}
throw shared
}
}
assert e.is(shared)
assert e.suppressed.length == 0
'''
}
```
##########
src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java:
##########
@@ -284,7 +283,8 @@ public static <T> T withScopeTimeout(Executor executor,
Duration timeout,
te.initCause(e);
throw te;
}
- throw e;
+ // A checked exception from a Closure body arrives wrapped by
its SAM coercion
+ throw AsyncSupport.rethrow(AsyncSupport.unwrapUndeclared(e));
Review Comment:
I think `withScopeTimeout` still has a critical interaction with
`try-with-resources` (line 268) and `unwrapUndeclared` that reintroduces
`IllegalArgumentException: Self-suppression not permitted` (`GROOVY-12764`),
plus two subtle differences from `AsyncScope.withScope`:
1. **Unguarded `try-with-resources` self-suppression crash:** Unlike
`AsyncScope.withScope` (which closes `scope` manually with `if (closeError !=
bodyError)`), `withScopeTimeout` uses `try (DefaultAsyncScope scope = new
DefaultAsyncScope(executor))`. Per JLS §14.20.3 (and confirmed as `Won't Fix`
in OpenJDK `JDK-8317229`), `javac` emits an unconditional
`primary.addSuppressed(closeError)`. Previously, a shared checked exception was
masked because the body threw `UndeclaredThrowableException(shared)` while
`close()` threw `RuntimeException(shared)` (two distinct wrapper objects). Now
that line 287 rethrows `unwrapUndeclared(e)` and `close()` rethrows
`firstError` directly, when both the timed body and a child task fail with (or
`await`) the same exception instance:
```groovy
def upstream = async { throw new IOException('boom') }
AsyncScope.withScope(Duration.ofSeconds(5)) { scope ->
scope.async { await upstream }
await upstream
}
```
`withScopeTimeout` throws `java.lang.IllegalArgumentException:
Self-suppression not permitted` instead of `IOException('boom')`.
2. **Timeout cause retains `UndeclaredThrowableException` in dynamic
Groovy:** When `timedOut.get()` is `true` after `bodyThread.interrupt()`, a
blocking call in a dynamic Groovy closure throws `InterruptedException` wrapped
in `UndeclaredThrowableException` by SAM coercion. Calling `te.initCause(e)` at
line 283 *before* `unwrapUndeclared(e)` leaves `te.cause` as
`UndeclaredThrowableException(InterruptedException)` in dynamic mode, whereas
`@CompileStatic` (`LambdaMetafactory`, no `Proxy`) sets `te.cause` to
`InterruptedException` directly.
3. **`catch (Exception e)` vs. `catch (Throwable thrown)` & late timer
race:** `AsyncScope.withScope` catches `Throwable` (and `unwrapUndeclared`
checks `!(cause instanceof RuntimeException) && !(cause instanceof Error)` per
JLS §11.1.1), whereas `catch (Exception e)` here misses direct checked
`Throwable` subclasses under `@CompileStatic`. Also, if the timer fires right
as `body.apply(scope)` returns normally without blocking, `bodyThread`'s
interrupt flag remains set on the caller thread because `Thread.interrupted()`
only runs inside `catch`.
Aligning `withScopeTimeout` with `AsyncScope.withScope`'s manual close
structure resolves all three cleanly:
```java
public static <T> T withScopeTimeout(Executor executor, Duration timeout,
Function<AsyncScope, T> body)
throws TimeoutException {
Objects.requireNonNull(timeout, "timeout must not be null");
Objects.requireNonNull(body, "body must not be null");
var timedOut = new AtomicBoolean(false);
Thread bodyThread = Thread.currentThread();
DefaultAsyncScope scope = new DefaultAsyncScope(executor);
ScheduledFuture<?> timer = AsyncSupport.getScheduler().schedule(()
-> {
timedOut.set(true);
scope.cancelAll();
bodyThread.interrupt();
}, timeout.toMillis(), TimeUnit.MILLISECONDS);
T result;
try {
result = withCurrent(scope, () -> body.apply(scope));
} catch (Throwable thrown) {
timer.cancel(false);
Throwable bodyError = AsyncSupport.unwrapUndeclared(thrown);
if (timedOut.get() && !(bodyError instanceof Error)) {
// Clear the interrupt flag set by the timeout
Thread.interrupted();
TimeoutException te = new TimeoutException("Scope timed out
after " + timeout);
te.initCause(bodyError);
bodyError = te;
}
try {
scope.close();
} catch (Throwable closeError) {
if (closeError != bodyError) {
bodyError.addSuppressed(closeError);
}
}
throw AsyncSupport.rethrow(bodyError);
}
if (!timer.cancel(false) && timedOut.get()) {
Thread.interrupted();
}
scope.close();
return result;
}
```
##########
src/test/groovy/groovy/AsyncAwaitTest.groovy:
##########
@@ -4115,17 +4115,228 @@ final class AsyncAwaitTest {
}
@Test
- void testScopeCloseWithCheckedExceptionWrapped() {
+ void testScopeCloseRethrowsCheckedExceptionUnwrapped() {
assertScript '''
import groovy.concurrent.AsyncScope
def scope = AsyncScope.create()
- scope.async { throw new Exception('checked-err') }
+ scope.async { throw new IOException('checked-err') }
try {
scope.close()
assert false
- } catch (RuntimeException e) {
- assert e.cause.message == 'checked-err'
+ } catch (IOException e) {
+ assert e.message == 'checked-err'
+ }
+ '''
+ }
+
+ // Checked exceptions surface as themselves from every async construct, as
from await
+
+ @Test
+ void testWithScopeChildCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+
+ try {
+ AsyncScope.withScope { scope ->
+ scope.async { throw new IOException('child') }
+ null
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'child'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyCheckedExceptionTransparency() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.time.Duration
+
+ try {
+ AsyncScope.withScope { scope -> throw new IOException('body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'body'
+ }
+ try {
+ AsyncScope.withScope(Duration.ofSeconds(5)) { scope -> throw
new IOException('timed body') }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'timed body'
+ }
+ '''
+ }
+
+ @Test
+ void testWithScopeBodyKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+
+ try {
+ AsyncScope.withScope { scope -> throw new
ExecutionException(new IOException('inner')) }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+
+ def gen = async {
+ yield return 1
+ throw new ExecutionException(new IOException('inner'))
+ }
+ try {
+ for (x in gen) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ '''
+ }
+
+ @Test
+ void testDeferCheckedExceptionTransparency() {
+ assertScript '''
+ try {
+ await async {
+ defer { throw new IOException('cleanup') }
+ 1
+ }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'cleanup'
+ }
+ '''
+ }
+
+ @Test
+ void testGeneratorCheckedExceptionTransparency() {
+ assertScript '''
+ def gen = async {
+ yield return 1
+ throw new IOException('gen')
+ }
+ def seen = []
+ try {
+ for (x in gen) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'gen'
+ }
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherCheckedExceptionTransparency() {
+ assertScript '''
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def seen = []
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.submit(1)
+ // closeExceptionally may overtake an undelivered item
+ while (pub.estimateMaximumLag() > 0) Thread.onSpinWait()
+ pub.closeExceptionally(new IOException('flow'))
+ }
+ try {
+ for await (x in pub) { seen << x }
+ assert false
+ } catch (IOException e) {
+ assert e.message == 'flow'
+ }
+ producer.join()
+ assert seen == [1]
+ '''
+ }
+
+ @Test
+ void testFlowPublisherKeepsAWrapperTheCodeThrew() {
+ assertScript '''
+ import java.util.concurrent.ExecutionException
+ import java.util.concurrent.SubmissionPublisher
+
+ def pub = new SubmissionPublisher<Integer>()
+ def producer = Thread.start {
+ while (pub.numberOfSubscribers == 0) Thread.onSpinWait()
+ pub.closeExceptionally(new ExecutionException(new
IOException('inner')))
+ }
+ try {
+ for await (x in pub) { }
+ assert false
+ } catch (ExecutionException e) {
+ assert e.cause instanceof IOException
+ }
+ producer.join()
+ '''
+ }
+
+ // A wrapper thrown by a child task or deferred action is removed, exactly
as await removes it
+
+ @Test
+ void testScopeChildAndDeferUnwrapAsAwaitDoes() {
+ assertScript '''
+ import groovy.concurrent.AsyncScope
+ import java.util.concurrent.ExecutionException
+ import static groovy.test.GroovyAssert.shouldFail
+
+ def wrapped = { new ExecutionException(new IOException('inner')) }
+ def viaAwait = shouldFail(IOException) { await async { throw
wrapped() } }
+ def viaChild = shouldFail(IOException) {
+ AsyncScope.withScope { scope -> scope.async { throw wrapped()
}; null }
+ }
+ def viaDefer = shouldFail(IOException) {
+ await async { defer { throw wrapped() }; 1 }
+ }
+ assert [viaAwait, viaChild, viaDefer]*.message == ['inner'] * 3
+ '''
+ }
Review Comment:
Related to the comment on `AsyncSupport.executeDeferScope`: in `viaDefer`
(`await async { defer { throw wrapped() }; 1 }`), `ExecutionException` is
actually stripped by the outer `await` rather than by `defer` itself—whereas
inside an `async` generator (`def gen = async { defer { throw wrapped() };
yield return 1 }`), `ExecutionException` is kept. Clarifying the comment above
line 4285 (and perhaps asserting the generator-hosted `defer` case too) would
help document that distinction.
It would also be great to add a regression test here verifying that
suppressed cleanup exceptions attached to a stripped wrapper survive unwrapping
(see Comment on `AsyncSupport.unwrapUndeclared`):
```groovy
@Test
void testSuppressedExceptionPreservedWhenWrapperIsUnwrapped() {
assertScript '''
import java.util.concurrent.ExecutionException
import static groovy.test.GroovyAssert.shouldFail
def e = shouldFail(IOException) {
await async {
defer { throw new IOException('cleanup-err') }
defer { throw new ExecutionException(new
IOException('primary-err')) }
1
}
}
assert e.message == 'primary-err'
assert e.suppressed.length == 1
assert e.suppressed[0] instanceof IOException
assert e.suppressed[0].message == 'cleanup-err'
'''
}
```
##########
src/main/java/groovy/concurrent/AsyncScope.java:
##########
@@ -100,6 +109,9 @@ public interface AsyncScope extends AutoCloseable {
* Closes the scope, waiting for all child tasks to complete.
* If any child failed and fail-fast is enabled, remaining children
* are cancelled and the first failure is rethrown.
+ *
+ * @apiNote The failure is rethrown as itself, so this method can throw a
+ * checked exception it does not declare; see the class documentation.
Review Comment:
The new `@apiNote` here and on the class header is very clear for Java
callers. Two small edge cases we might optionally mention (either here or in
the class `@apiNote`):
1. **Direct `try-with-resources` usage (`try (var scope =
AsyncScope.create())`):** Unlike `withScope` (which guards `if (closeError !=
bodyError)`), `javac` desugars `try-with-resources` into an unconditional
`primary.addSuppressed(closeError)` (JLS §14.20.3 / OpenJDK `JDK-8317229`). If
caller code inside `try (var scope = AsyncScope.create())` awaits a failed
child of `scope` and lets that exception escape the `try` block,
`scope.close()` will rethrow the exact same unwrapped instance and trigger
`IllegalArgumentException: Self-suppression not permitted` unless `withScope`
is used instead.
2. **Worker-originated `InterruptedException`:** When a child task throws
`InterruptedException` on a worker thread, `close()` now rethrows that
`InterruptedException` onto the calling thread while
`Thread.currentThread().isInterrupted()` remains `false` (distinct from
interruption of the calling thread itself).
> Async scopes, defer and generators wrap checked exceptions instead of
> rethrowing them as await does
> ---------------------------------------------------------------------------------------------------
>
> Key: GROOVY-12763
> URL: https://issues.apache.org/jira/browse/GROOVY-12763
> Project: Groovy
> Issue Type: Bug
> Reporter: Paul King
> Priority: Major
>
> {{await}} rethrows a checked exception from an async task unchanged, but five
> other async paths wrap it, so the caller sees a different exception from the
> one the code threw. Unchecked exceptions and {{Error}}s pass through
> unwrapped on every path.
> {code:groovy}
> import groovy.concurrent.*
> // rethrown as is: java.lang.Exception
> await async { throw new Exception('boom') }
> // java.lang.RuntimeException, cause java.lang.Exception
> AsyncScope.withScope { s -> s.async { throw new Exception('boom') }; null }
> // java.lang.reflect.UndeclaredThrowableException, cause java.lang.Exception
> AsyncScope.withScope { s -> throw new Exception('boom') }
> // java.lang.RuntimeException, cause java.lang.Exception
> await async { defer { throw new Exception('boom') }; 1 }
> // java.lang.reflect.UndeclaredThrowableException, cause java.lang.Exception
> def g = async { yield return 1; throw new Exception('boom') }
> for (x in g) {}
> {code}
> The five paths, as of 6.0.0:
> * *Scope child failure*: {{DefaultAsyncScope.close()}} wraps a checked
> failure in {{RuntimeException}}. Its javadoc says "the first failure is
> rethrown".
> * *{{withScope}} body*: the Closure is coerced to {{Function}}, which wraps a
> checked exception in {{UndeclaredThrowableException}}. The same applies to
> {{withScope}} with a timeout.
> * *{{defer}} action*: {{AsyncSupport.executeDeferScope}} wraps it in
> {{RuntimeException}}.
> * *Generator body*: the Closure-to-{{Consumer}} coercion wraps it in
> {{UndeclaredThrowableException}} ({{GeneratorBridge}}).
> * *{{Flow.Publisher}} consumed with {{for await}}*: an {{onError}} carrying a
> checked exception is rethrown as {{RuntimeException}}
> ({{FlowPublisherAdapter}}).
> Expected: the original exception in all five cases, as with {{await}}.
> GROOVY-9381 lists exception transparency as a design principle ("callers see
> the same exceptions they would in synchronous code"), and GROOVY-12459 made a
> failing {{for await}} producer surface its checked exception rather than a
> wrapper. Kotlin's {{coroutineScope}} and C#'s {{await}} also rethrow the
> original exception.
> Proposed fix:
> * Rethrow the original exception at the three {{RuntimeException}} wrap sites.
> * In {{withScope}} and the generator, remove an
> {{UndeclaredThrowableException}} only when its cause is a checked exception,
> which is the layer the closure coercion adds. An
> {{UndeclaredThrowableException}} around an unchecked exception, or another
> wrapper the code itself threw, is kept.
> * Suppressed exceptions from scope close are kept.
> * Add an {{@apiNote}} to {{AsyncScope}} and {{close()}}: both declare no
> checked exceptions but can now throw one, so Java callers catch {{Exception}}
> and test its type.
> A wrapper that a child task or {{defer}} action throws itself, such as
> {{ExecutionException}}, is removed as {{await}} removes it. On 6.0.0 the
> extra {{RuntimeException}} happened to hide that. Whether {{await}} should
> remove only the layers the runtime added is left for a separate discussion.
> Compatibility: code that catches {{RuntimeException}} or
> {{UndeclaredThrowableException}} around these calls and then reads
> {{getCause()}} will now receive the checked exception directly.
> {{AsyncAwaitTest.testScopeCloseWithCheckedExceptionWrapped}} asserted the old
> wrapping and changes with the fix. This needs a release note.
> Known limitation: a checked exception that the code itself wrapped in an
> {{UndeclaredThrowableException}} and threw from a {{withScope}} or generator
> body is also unwrapped, because it can't be told apart from the coercion
> layer. Removing that limitation needs new entry points that avoid closure
> coercion (a generator body type declaring {{throws Throwable}}, and a
> {{Closure}} overload of {{withScope}}); that is left for a later release.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)