[
https://issues.apache.org/jira/browse/GROOVY-12763?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18144706#comment-18144706
]
ASF GitHub Bot commented on GROOVY-12763:
-----------------------------------------
daniellansun commented on code in PR #3298:
URL: https://github.com/apache/groovy/pull/3298#discussion_r4571277648
##########
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()`.
> 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)