From cf3b5f814e31d27fed9ac557cfccf2085122701e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:55:52 +0100 Subject: [PATCH 01/39] MINOR: Bump org.codehaus.mojo:versions-maven-plugin from 2.25.1 to 2.25.2 (#1516) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [org.codehaus.mojo:versions-maven-plugin](https://github.com/mojohaus/versions) from 2.25.1 to 2.25.2.
Release notes

Sourced from org.codehaus.mojo:versions-maven-plugin's releases.

2.25.2

A bug-fix release for 2.25: pre-release versions are now left out where 2.25.0 and 2.25.1 still offered them, and display-plugin-updates no longer fails on a plugin declared in several profiles of a parent POM. It requires Maven 3.9.0 or later and Java 8 or later, as before.

✨ Highlights

🚀 New features and improvements

🐛 Bug Fixes

Thanks to @​slachiewicz.

Full changelog

Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=org.codehaus.mojo:versions-maven-plugin&package-manager=maven&previous-version=2.25.1&new-version=2.25.2)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- bom/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bom/pom.xml b/bom/pom.xml index 1ad11264c2..dc53ad4d19 100644 --- a/bom/pom.xml +++ b/bom/pom.xml @@ -218,7 +218,7 @@ under the License. org.codehaus.mojo versions-maven-plugin - 2.25.1 + 2.25.2 diff --git a/pom.xml b/pom.xml index 6b70f92415..8a5afa0376 100644 --- a/pom.xml +++ b/pom.xml @@ -520,7 +520,7 @@ under the License. org.codehaus.mojo versions-maven-plugin - 2.25.1 + 2.25.2 io.github.git-commit-id From 0cd2f595190bd457d0935c5394db3a0185abb5d1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:57:53 +0100 Subject: [PATCH 02/39] MINOR: Bump logback.version from 1.6.6 to 1.6.8 (#1515) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps `logback.version` from 1.6.6 to 1.6.8. Updates `ch.qos.logback:logback-classic` from 1.6.6 to 1.6.8
Release notes

Sourced from ch.qos.logback:logback-classic's releases.

Logback 1.6.8

2026-11-19 Release of logback version 1.6.8

• JsonEncoder now always writes valid JSON, whatever the combination of with* options. All strings, including logger names and stack trace elements, are now escaped.

• In the output of JsonEncoder, null values are now written as null instead of "null", and numeric and boolean arguments as JSON numbers and booleans. Markers are written by name. Consumers relying on the previous format may need to be updated.

• JsonEncoder admits the new withCallerData option, disabled by default.

• The new JsonEventReader class reads the output of JsonEncoder back into logging events. It accepts output written by logback versions since 1.3.8 and adds no new dependency.

• Fixed KryoDecoder looping forever on certain damaged streams. KryoDecoder can now start decoding at any epoch header and stop early via decodeWhile.

• A bit-wise identical binary of this version can be reproduced by building from source code at commit 2f625e4c587b6bd33aa3e97576c040cb03140c8d associated with the tag v_1.6.8. The release was built using Java "21" 2023-10-17 LTS build 21.0.1.+12-LTS-29 under Linux Debian 11.6.

Logback 1.6.7

2026-11-14 Release of logback version 1.6.7

• The scan attribute of the <propertiesConfigurator> element, when set, now takes precedence over the scan attribute of the top-level <configuration> element, in both directions. With scan="true" and scanning disabled or unset at the top level, the properties file is now actually monitored for changes. Previously, the file was added to the watch list but no task ever polled it. The scan period is taken from the scanPeriod attribute of the top-level <configuration> element. Conversely, with scan="false" and scan="true" at the top level, the properties file is no longer monitored. Moreover, when several <propertiesConfigurator scan="true"> elements are present without top-level scanning, all the referenced files are now monitored. Previously, only the last one was.

• Two new modules, logback-core-kryo and logback-classic-kryo, encode and decode logging events with the Kryo 5 serialization library. KryoEncoder writes ILoggingEvent instances into a compact binary stream and KryoDecoder reads them back. The stream is framed so that the decoder can recover from torn or truncated

... (truncated)

Commits
  • 2f625e4 prepare release 1.6.8
  • b8b3e41 JsonEncoder: always write valid JSON, add JsonEventReader
  • 0f05962 kryo: decode from the start of an epoch, add decodeWhile
  • 9164978 kryo: drop frequency-gated map, fix decoder resync, test id reuse
  • 75bf5f1 start work on 1.6.8-SNAPSHOT
  • 8b97c2f prepare release 1.6.7
  • 764b5c4 kryo: use stream version 0 when KryoEncoder is set to Vanilla
  • b29f465 kryo: remove V3 and V4 stream encodings, keep Vanilla and V5
  • d42c012 add logback-core-kryo and logback-classic-kryo modules
  • 069d51a remove dead code
  • Additional commits viewable in compare view

Updates `ch.qos.logback:logback-core` from 1.6.6 to 1.6.8
Release notes

Sourced from ch.qos.logback:logback-core's releases.

Logback 1.6.8

2026-11-19 Release of logback version 1.6.8

• JsonEncoder now always writes valid JSON, whatever the combination of with* options. All strings, including logger names and stack trace elements, are now escaped.

• In the output of JsonEncoder, null values are now written as null instead of "null", and numeric and boolean arguments as JSON numbers and booleans. Markers are written by name. Consumers relying on the previous format may need to be updated.

• JsonEncoder admits the new withCallerData option, disabled by default.

• The new JsonEventReader class reads the output of JsonEncoder back into logging events. It accepts output written by logback versions since 1.3.8 and adds no new dependency.

• Fixed KryoDecoder looping forever on certain damaged streams. KryoDecoder can now start decoding at any epoch header and stop early via decodeWhile.

• A bit-wise identical binary of this version can be reproduced by building from source code at commit 2f625e4c587b6bd33aa3e97576c040cb03140c8d associated with the tag v_1.6.8. The release was built using Java "21" 2023-10-17 LTS build 21.0.1.+12-LTS-29 under Linux Debian 11.6.

Logback 1.6.7

2026-11-14 Release of logback version 1.6.7

• The scan attribute of the <propertiesConfigurator> element, when set, now takes precedence over the scan attribute of the top-level <configuration> element, in both directions. With scan="true" and scanning disabled or unset at the top level, the properties file is now actually monitored for changes. Previously, the file was added to the watch list but no task ever polled it. The scan period is taken from the scanPeriod attribute of the top-level <configuration> element. Conversely, with scan="false" and scan="true" at the top level, the properties file is no longer monitored. Moreover, when several <propertiesConfigurator scan="true"> elements are present without top-level scanning, all the referenced files are now monitored. Previously, only the last one was.

• Two new modules, logback-core-kryo and logback-classic-kryo, encode and decode logging events with the Kryo 5 serialization library. KryoEncoder writes ILoggingEvent instances into a compact binary stream and KryoDecoder reads them back. The stream is framed so that the decoder can recover from torn or truncated

... (truncated)

Commits
  • 2f625e4 prepare release 1.6.8
  • b8b3e41 JsonEncoder: always write valid JSON, add JsonEventReader
  • 0f05962 kryo: decode from the start of an epoch, add decodeWhile
  • 9164978 kryo: drop frequency-gated map, fix decoder resync, test id reuse
  • 75bf5f1 start work on 1.6.8-SNAPSHOT
  • 8b97c2f prepare release 1.6.7
  • 764b5c4 kryo: use stream version 0 when KryoEncoder is set to Vanilla
  • b29f465 kryo: remove V3 and V4 stream encodings, keep Vanilla and V5
  • d42c012 add logback-core-kryo and logback-classic-kryo modules
  • 069d51a remove dead code
  • Additional commits viewable in compare view

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8a5afa0376..44edd29413 100644 --- a/pom.xml +++ b/pom.xml @@ -113,7 +113,7 @@ under the License. true 2.52.0 4.4.0 - 1.6.6 + 1.6.8 none -Xdoclint:none From c3c3e4537b862a0b6e03304438988e0739839f77 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:58:43 +0100 Subject: [PATCH 03/39] MINOR: Bump at.yawk.lz4:lz4-java from 1.14.0 to 1.14.1 (#1514) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [at.yawk.lz4:lz4-java](https://github.com/yawkat/lz4-java) from 1.14.0 to 1.14.1.
Release notes

Sourced from at.yawk.lz4:lz4-java's releases.

lz4-java v1.14.1

What's Changed

Full Changelog: https://github.com/yawkat/lz4-java/compare/v1.14.0...v1.14.1

Commits
  • 11d4075 Pin the CPU baseline of all natives; align branches for the Intel JCC erratum...
  • 8d90898 Update dependency biz.aQute.bnd:bnd-maven-plugin to v7.5.0 (#182)
  • 39dcb7e Update dependency maven to v3.10.1 (#184)
  • a828f66 Add fuzz tests for LZ4FrameInputStream and LZ4BlockInputStream (#179)
  • a9c5e9b Update actions/setup-java digest to d1374f8 (#183)
  • f36f2a9 Install Zulu JDK 7 from the Azul CDN via jdkfile (#185)
  • 09598c0 Update dependency org.codehaus.mojo:build-helper-maven-plugin to v3.8.0 (#180)
  • a786d21 Update lz4 to 1.11.1 (#181)
  • See full diff in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=at.yawk.lz4:lz4-java&package-manager=maven&previous-version=1.14.0&new-version=1.14.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- compression/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compression/pom.xml b/compression/pom.xml index 5f3786bce0..9485919371 100644 --- a/compression/pom.xml +++ b/compression/pom.xml @@ -60,7 +60,7 @@ under the License. at.yawk.lz4 lz4-java - 1.14.0 + 1.14.1 From 0270ba64065a3fd68eb5cffe5315d9307fed8b7f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:59:24 +0100 Subject: [PATCH 04/39] MINOR: Bump io.netty:netty-bom from 4.2.20.Final to 4.2.21.Final (#1513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps [io.netty:netty-bom](https://github.com/netty/netty) from 4.2.20.Final to 4.2.21.Final.
Release notes

Sourced from io.netty:netty-bom's releases.

netty-4.2.21.Final

This release fixes a mistake in our build that affected Netty 4.2.20 and 4.1.140, where we accidentally increased the glibc version to 2.33 for x86_64 and aarch64. In this release the glibc version requirements return to their previous versions.

What's Changed

... (truncated)

Commits
  • 6416031 [maven-release-plugin] prepare release netty-4.2.21.Final
  • e3cab70 HAProxyMessageEncoder: Reject v2 headers longer than 65535 bytes (#18428)
  • cd23bac Pin rustc to 1.100.0 in docker images and workflows (#18422)
  • 805974b IoUring: Fail when enabling the ring fails (#18216)
  • 5755807 Release messages written to a closed EmbeddedChannel (#18332)
  • 5fe1f1f Query SSL_pending lazily in ReferenceCountedOpenSslEngine.unwrap (#18376)
  • 1e718ed Share enabled protocols in openssl engine (#18388)
  • 09a7227 Auto-port 4.2: Don't stop reading domain datagrams after an empty datagram (#...
  • d2a2c48 Reject SPDY frames that do not fit the 24-bit length field (#18412)
  • 887f597 Reject negative session timeout and cache size in the QUIC SSLSessionContext ...
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=io.netty:netty-bom&package-manager=maven&previous-version=4.2.20.Final&new-version=4.2.21.Final)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 44edd29413..7cf2839111 100644 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ under the License. 6.1.3 2.0.20 33.8.0-jre - 4.2.20.Final + 4.2.21.Final 1.85.1 4.36.2 2.23.0 From c39ccdd5669bce53e2a46b927432df4a95302ec7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:08:51 +0100 Subject: [PATCH 05/39] MINOR: Bump error_prone_core.version from 2.52.0 to 2.53.0 (#1512) Bumps `error_prone_core.version` from 2.52.0 to 2.53.0. Updates `com.google.errorprone:error_prone_annotations` from 2.52.0 to 2.53.0
Release notes

Sourced from com.google.errorprone:error_prone_annotations's releases.

Error Prone 2.53.0

New checks:

  • BootclasspathShadowing: Flag top-level class declarations whose binary name shadows a platform or bootclasspath type (disabled by default).
  • DiscouragedHashKey: Configurable check for hash-based containers keyed on types (or their subtypes) specified via -XepOpt:DiscouragedHashKey:Types (no-op unless configured).

Other changes:

  • EqualsHashCode: Flag classes that override hashCode without overriding equals, gated by -XepOpt:EqualsHashCode:CheckHashCodeWithoutEquals (enabled by default) (#129).
  • MustBeClosedChecker: Enforce @MustBeClosed on method and constructor references.
  • URLEqualsHashCode: Rebuild on the shared equality and hash-key analysis engine to also check Multimap, Multiset, Stream.collect, direct equality, assertions, and containment, while ignoring identity and sorted containers.
  • ImpossibleNullComparison: Flag impossible null comparisons via Objects.equals, Objects.isNull, and Objects.nonNull.
  • TruthIncompatibleType: Check Guava Table assertions.
  • PatternMatchingInstanceof: Suggest instanceof Foo<?> foo for raw instanceof Foo checks.
  • CompileTimeConstant: Recognize Guava ImmutableMap.of, ImmutableMultiset.of, ImmutableSortedSet.of, and ImmutableSortedMap.of, as well as JDK List.of, Set.of, and Map.of.
  • Immutable: Add Gson and Guava TypeToken to WellKnownMutability, and stop caching negative symbol and type lookups across a compilation unit so lazily completed supertypes are resolved reliably.
  • PreconditionsCheckNotNullRepeated: Also check Guava's Verify.verifyNotNull.
  • LambdaFunctionalInterface: Only match Integer, Long, and Double type arguments instead of all Number subtypes.
  • EqualsIncompatibleType / TypeCompatibility: Avoid false positives with incomplete classpaths.
  • LoopConditionChecker / TimeUnitConversionChecker / InlineTrivialConstant / NonAtomicVolatileUpdate: Recognize compile-time constants in loop conditions (#5826) and TimeUnit conversions (#6279), and unwrap parenthesized expressions in InlineTrivialConstant (#6217) and NonAtomicVolatileUpdate (#6214).
  • StatementSwitchToExpressionSwitch / IfChainToSwitch: Fix dead-code deletion after return switch and consolidate reachability handling.
  • Performance: Evaluate MethodMatchers constraints in selectivity order, optimize SuppressionInfo, and reduce per-call overhead across CheckReturnValue, DoNotCall, ParameterName, UnusedMethod, AlmostJavadoc, and several other checks.
  • Check API: Validate package names with SourceVersion.isName in Matchers.packageStartsWith, and document that ASTHelpers.getSymbol(Tree) returns null for parenthesized expressions (#6223).

Closed issues: #5826, #6214, #6217, #6223, #6279

Full changelog: https://github.com/google/error-prone/compare/v2.52.0...v2.53.0

Commits
  • 5c3574f Release Error Prone 2.53.0
  • 8138d15 Fix NPE in PatternMatchingInstanceof on type variables and raw arrays
  • 496e723 Avoid TypeCompatibility false positives with incomplete classpaths.
  • b8bf6ba Ignore explicit constructor invocations in `UnusedReturnValueMatcher.isReturn...
  • c9bbbdb Reject invalid package names in Matchers.packageStartsWith
  • e14c5e6 Make TruthIncompatibleType check Table assertions.
  • beb8f89 Bump org.checkerframework:checker-qual from 4.3.1 to 4.4.0 in the dependencie...
  • f72c29d Flag impossible null comparisons via Objects.equals, isNull, and nonNull.
  • d96ec28 Fix some bugs in isLikelyToBePublicApi.
  • fb56246 Only match Integer, Long, and Double in LambdaFunctionalInterface.
  • Additional commits viewable in compare view

Updates `com.google.errorprone:error_prone_core` from 2.52.0 to 2.53.0
Release notes

Sourced from com.google.errorprone:error_prone_core's releases.

Error Prone 2.53.0

New checks:

  • BootclasspathShadowing: Flag top-level class declarations whose binary name shadows a platform or bootclasspath type (disabled by default).
  • DiscouragedHashKey: Configurable check for hash-based containers keyed on types (or their subtypes) specified via -XepOpt:DiscouragedHashKey:Types (no-op unless configured).

Other changes:

  • EqualsHashCode: Flag classes that override hashCode without overriding equals, gated by -XepOpt:EqualsHashCode:CheckHashCodeWithoutEquals (enabled by default) (#129).
  • MustBeClosedChecker: Enforce @MustBeClosed on method and constructor references.
  • URLEqualsHashCode: Rebuild on the shared equality and hash-key analysis engine to also check Multimap, Multiset, Stream.collect, direct equality, assertions, and containment, while ignoring identity and sorted containers.
  • ImpossibleNullComparison: Flag impossible null comparisons via Objects.equals, Objects.isNull, and Objects.nonNull.
  • TruthIncompatibleType: Check Guava Table assertions.
  • PatternMatchingInstanceof: Suggest instanceof Foo<?> foo for raw instanceof Foo checks.
  • CompileTimeConstant: Recognize Guava ImmutableMap.of, ImmutableMultiset.of, ImmutableSortedSet.of, and ImmutableSortedMap.of, as well as JDK List.of, Set.of, and Map.of.
  • Immutable: Add Gson and Guava TypeToken to WellKnownMutability, and stop caching negative symbol and type lookups across a compilation unit so lazily completed supertypes are resolved reliably.
  • PreconditionsCheckNotNullRepeated: Also check Guava's Verify.verifyNotNull.
  • LambdaFunctionalInterface: Only match Integer, Long, and Double type arguments instead of all Number subtypes.
  • EqualsIncompatibleType / TypeCompatibility: Avoid false positives with incomplete classpaths.
  • LoopConditionChecker / TimeUnitConversionChecker / InlineTrivialConstant / NonAtomicVolatileUpdate: Recognize compile-time constants in loop conditions (#5826) and TimeUnit conversions (#6279), and unwrap parenthesized expressions in InlineTrivialConstant (#6217) and NonAtomicVolatileUpdate (#6214).
  • StatementSwitchToExpressionSwitch / IfChainToSwitch: Fix dead-code deletion after return switch and consolidate reachability handling.
  • Performance: Evaluate MethodMatchers constraints in selectivity order, optimize SuppressionInfo, and reduce per-call overhead across CheckReturnValue, DoNotCall, ParameterName, UnusedMethod, AlmostJavadoc, and several other checks.
  • Check API: Validate package names with SourceVersion.isName in Matchers.packageStartsWith, and document that ASTHelpers.getSymbol(Tree) returns null for parenthesized expressions (#6223).

Closed issues: #5826, #6214, #6217, #6223, #6279

Full changelog: https://github.com/google/error-prone/compare/v2.52.0...v2.53.0

Commits
  • 5c3574f Release Error Prone 2.53.0
  • 8138d15 Fix NPE in PatternMatchingInstanceof on type variables and raw arrays
  • 496e723 Avoid TypeCompatibility false positives with incomplete classpaths.
  • b8bf6ba Ignore explicit constructor invocations in `UnusedReturnValueMatcher.isReturn...
  • c9bbbdb Reject invalid package names in Matchers.packageStartsWith
  • e14c5e6 Make TruthIncompatibleType check Table assertions.
  • beb8f89 Bump org.checkerframework:checker-qual from 4.3.1 to 4.4.0 in the dependencie...
  • f72c29d Flag impossible null comparisons via Objects.equals, isNull, and nonNull.
  • d96ec28 Fix some bugs in isLikelyToBePublicApi.
  • fb56246 Only match Integer, Long, and Double in LambdaFunctionalInterface.
  • Additional commits viewable in compare view

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7cf2839111..506f62c37d 100644 --- a/pom.xml +++ b/pom.xml @@ -111,7 +111,7 @@ under the License. 2 10.23.0 true - 2.52.0 + 2.53.0 4.4.0 1.6.8 none From a655068004e2269c05ee6ec781152b000b5c3a7a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:10:58 +0100 Subject: [PATCH 06/39] MINOR: Bump com.google.api.grpc:proto-google-common-protos from 2.81.0 to 2.82.0 (#1511) Bumps [com.google.api.grpc:proto-google-common-protos](https://github.com/googleapis/google-cloud-java) from 2.81.0 to 2.82.0.
Changelog

Sourced from com.google.api.grpc:proto-google-common-protos's changelog.

2.82.0 (2025-10-21)

Dependencies

  • update dependency com.google.cloud:sdk-platform-java-config to v3.53.0 (#11776) (e4a2892)
Commits
  • 73c9a03 chore(main): release 1.88.0 (#13669)
  • 667e53a perf(bigquery-jdbc): optimize metadata introspection performance and parallel...
  • 2f36a71 test(datastore): Migrate datastore tests to use awaitility (#13668)
  • 557d430 build(deps-dev): bump ch.qos.logback:logback-core from 1.5.25 to 1.5.33 in /g...
  • 512e370 fix: Add logging-logback to gapic-libraries-bom (#13663)
  • 86d35e4 fix(ci): run root install in dependency convergence check (#13666)
  • c8d69cc test(bigquerystorage): Fix flaky testMultiStreamClosed_multiplexingEnabled (#...
  • 6567e43 chore(bigquerystorage): fix flaky ConnectionWorkerPoolTest (#13662)
  • 8afc0ab fix(datastore): reduce flakiness of E2E tracing tests (#13645)
  • 7b0ee76 chore(java-bigtable): rename .readme-partials.yml to .readme-partials.yaml (#...
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=com.google.api.grpc:proto-google-common-protos&package-manager=maven&previous-version=2.81.0&new-version=2.82.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- flight/flight-core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flight/flight-core/pom.xml b/flight/flight-core/pom.xml index 6e28679301..15e10e62db 100644 --- a/flight/flight-core/pom.xml +++ b/flight/flight-core/pom.xml @@ -133,7 +133,7 @@ under the License. com.google.api.grpc proto-google-common-protos - 2.81.0 + 2.82.0 test From 14fef469519763c63b62f51cc6ee040b7fd43fe0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:11:21 +0100 Subject: [PATCH 07/39] MINOR: Bump com.github.luben:zstd-jni from 1.5.7-26 to 1.5.7-28 (#1510) Bumps [com.github.luben:zstd-jni](https://github.com/luben/zstd-jni) from 1.5.7-26 to 1.5.7-28.
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=com.github.luben:zstd-jni&package-manager=maven&previous-version=1.5.7-26&new-version=1.5.7-28)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- compression/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compression/pom.xml b/compression/pom.xml index 9485919371..220c3d3a87 100644 --- a/compression/pom.xml +++ b/compression/pom.xml @@ -55,7 +55,7 @@ under the License. com.github.luben zstd-jni - 1.5.7-26 + 1.5.7-28 at.yawk.lz4 From a99297ce3ca5c6cd8dc2c5ea3f5541b0788fdd62 Mon Sep 17 00:00:00 2001 From: Abdul Rawoof Khan Date: Mon, 23 Nov 2026 21:06:07 +0530 Subject: [PATCH 08/39] MINOR: [Flight] Fix cookie header parsing in ServerSessionMiddleware (#1517) ## What's Changed `ServerSessionMiddleware.Factory.onCallStarted` splits the `cookie` header on `" ;"` (space, then semicolon) and then on every `=`. Clients send cookie lists as `name=value; name=value` (RFC 6265, and what `ClientCookieMiddleware` and the C++ Flight client produce), so as soon as any other cookie is present, for example a load balancer affinity cookie, the whole header becomes one token with two or more `=`, the loop gives up, and `arrow_flight_session_id` is never found. The call is then served without a session and any options set through `SetSessionOptions` are silently gone. A session id that itself contains `=` (base64 padding) is truncated and rejected with NOT_FOUND. The parser now splits on `;`, splits each pair at the first `=`, trims, strips surrounding double quotes, and skips a malformed entry instead of abandoning the rest of the header, which is what the C++ `ServerSessionMiddlewareFactory::ParseCookieString` does. A header holding only `arrow_flight_session_id=` behaves exactly as before. `TestServerSessionMiddleware` covers the single-cookie, multi-cookie, quoted, `=`-containing, malformed, second-header, missing and unknown-id cases; four of them fail on `main`. --- .../arrow/flight/ServerSessionMiddleware.java | 18 ++- .../flight/TestServerSessionMiddleware.java | 139 ++++++++++++++++++ 2 files changed, 151 insertions(+), 6 deletions(-) create mode 100644 flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerSessionMiddleware.java diff --git a/flight/flight-core/src/main/java/org/apache/arrow/flight/ServerSessionMiddleware.java b/flight/flight-core/src/main/java/org/apache/arrow/flight/ServerSessionMiddleware.java index 5ec01b9c83..7584c445af 100644 --- a/flight/flight-core/src/main/java/org/apache/arrow/flight/ServerSessionMiddleware.java +++ b/flight/flight-core/src/main/java/org/apache/arrow/flight/ServerSessionMiddleware.java @@ -82,15 +82,21 @@ public ServerSessionMiddleware onCallStarted( final Iterable it = incomingHeaders.getAll("cookie"); findIdCookie: for (final String headerValue : it) { - for (final String cookie : headerValue.split(" ;")) { - final String[] cookiePair = cookie.split("="); - if (cookiePair.length != 2) { + // RFC 6265: cookie-pairs are separated by "; " and a value may itself contain '=' + for (final String cookie : headerValue.split(";")) { + final int separator = cookie.indexOf('='); + if (separator == -1) { // Soft failure: Ignore invalid cookie list field - break; + continue; } - if (sessionCookieName.equals(cookiePair[0]) && cookiePair[1].length() > 0) { - sessionId = cookiePair[1]; + final String name = cookie.substring(0, separator).trim(); + String value = cookie.substring(separator + 1).trim(); + if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + if (sessionCookieName.equals(name) && !value.isEmpty()) { + sessionId = value; break findIdCookie; } } diff --git a/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerSessionMiddleware.java b/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerSessionMiddleware.java new file mode 100644 index 0000000000..abe4b29d78 --- /dev/null +++ b/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerSessionMiddleware.java @@ -0,0 +1,139 @@ +/* + * 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.arrow.flight; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.arrow.flight.grpc.RequestContextAdapter; +import org.junit.jupiter.api.Test; + +public class TestServerSessionMiddleware { + private static final String SESSION_ID = "6f1a3c8e-2b4d-4f7a-9c0e-1d2e3f4a5b6c"; + private static final CallInfo CALL_INFO = new CallInfo(FlightMethod.DO_ACTION); + + /** Creates a factory holding one session with {@link #SESSION_ID}. */ + private static ServerSessionMiddleware.Factory factoryWithSession() { + final ServerSessionMiddleware.Factory factory = + new ServerSessionMiddleware.Factory(() -> SESSION_ID); + final ServerSessionMiddleware middleware = + factory.onCallStarted(CALL_INFO, new FlightCallHeaders(), new RequestContextAdapter()); + assertFalse(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + return factory; + } + + private static ServerSessionMiddleware callWithCookie( + ServerSessionMiddleware.Factory factory, String... cookieHeaders) { + final FlightCallHeaders headers = new FlightCallHeaders(); + for (String cookieHeader : cookieHeaders) { + headers.insert("cookie", cookieHeader); + } + return factory.onCallStarted(CALL_INFO, headers, new RequestContextAdapter()); + } + + @Test + public void sessionCookieAlone() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final ServerSessionMiddleware middleware = + callWithCookie(factory, ServerSessionMiddleware.sessionCookieName + "=" + SESSION_ID); + assertTrue(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + } + + /** The session cookie is found when other cookies share the header (RFC 6265 "; " list). */ + @Test + public void sessionCookieAfterOtherCookies() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final ServerSessionMiddleware middleware = + callWithCookie( + factory, + "AWSALB=abc; " + + ServerSessionMiddleware.sessionCookieName + + "=" + + SESSION_ID + + "; x=y"); + assertTrue(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + } + + /** A cookie value may contain '=' (for example base64 padding). */ + @Test + public void sessionCookieValueWithEquals() { + final ServerSessionMiddleware.Factory factory = + new ServerSessionMiddleware.Factory(() -> "c2Vzc2lvbg=="); + final ServerSessionMiddleware created = + factory.onCallStarted(CALL_INFO, new FlightCallHeaders(), new RequestContextAdapter()); + final ServerSessionMiddleware.Session session = created.getSession(); + final ServerSessionMiddleware middleware = + callWithCookie(factory, ServerSessionMiddleware.sessionCookieName + "=c2Vzc2lvbg=="); + assertTrue(middleware.hasSession()); + assertSame(session, middleware.getSession()); + } + + /** A malformed entry earlier in the list does not hide the session cookie. */ + @Test + public void malformedCookieIsSkipped() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final ServerSessionMiddleware middleware = + callWithCookie( + factory, "garbage; " + ServerSessionMiddleware.sessionCookieName + "=" + SESSION_ID); + assertTrue(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + } + + @Test + public void quotedSessionCookieValue() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final ServerSessionMiddleware middleware = + callWithCookie( + factory, ServerSessionMiddleware.sessionCookieName + "=\"" + SESSION_ID + "\""); + assertTrue(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + } + + @Test + public void sessionCookieInSecondHeader() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final ServerSessionMiddleware middleware = + callWithCookie( + factory, "other=1", ServerSessionMiddleware.sessionCookieName + "=" + SESSION_ID); + assertTrue(middleware.hasSession()); + assertEquals(SESSION_ID, middleware.getSession().id); + } + + @Test + public void noSessionCookie() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + assertFalse(callWithCookie(factory, "other=1; another=2").hasSession()); + assertFalse( + callWithCookie(factory, ServerSessionMiddleware.sessionCookieName + "=").hasSession()); + } + + @Test + public void unknownSessionCookie() { + final ServerSessionMiddleware.Factory factory = factoryWithSession(); + final FlightRuntimeException e = + assertThrows( + FlightRuntimeException.class, + () -> callWithCookie(factory, ServerSessionMiddleware.sessionCookieName + "=unknown")); + assertEquals(FlightStatusCode.NOT_FOUND, e.status().code()); + } +} From 1718ad7aeef4209d3a620541672e1af7fc5cbb1e Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Mon, 23 Nov 2026 17:08:01 +0000 Subject: [PATCH 09/39] MINOR: Decode decimal holders with the correct byte order and byte offset (#1518) ## What's Changed Split out from #1228. Decode decimal values in decimal holder with correct endianess - we need to flip from machine native endianess to big endian --- .../codegen/templates/HolderReaderImpl.java | 13 +-- .../arrow/vector/util/DecimalUtility.java | 10 ++- .../vector/TestDecimalHolderDecoding.java | 80 +++++++++++++++++++ 3 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 vector/src/test/java/org/apache/arrow/vector/TestDecimalHolderDecoding.java diff --git a/vector/src/main/codegen/templates/HolderReaderImpl.java b/vector/src/main/codegen/templates/HolderReaderImpl.java index cdbb65c4f6..b67c1b26be 100644 --- a/vector/src/main/codegen/templates/HolderReaderImpl.java +++ b/vector/src/main/codegen/templates/HolderReaderImpl.java @@ -127,16 +127,9 @@ public void read(Nullable${name}Holder h) { return DurationVector.toDuration(holder.value, holder.unit); <#elseif minor.class == "Bit" > return Boolean.valueOf(holder.value != 0); - <#elseif minor.class == "Decimal"> - byte[] bytes = new byte[${type.width}]; - holder.buffer.getBytes(holder.start, bytes, 0, ${type.width}); - ${friendlyType} value = new BigDecimal(new BigInteger(bytes), holder.scale); - return value; - <#elseif minor.class == "Decimal256"> - byte[] bytes = new byte[${type.width}]; - holder.buffer.getBytes(holder.start, bytes, 0, ${type.width}); - ${friendlyType} value = new BigDecimal(new BigInteger(bytes), holder.scale); - return value; + <#elseif minor.class?starts_with("Decimal")> + return DecimalUtility.getBigDecimalFromArrowBufAtOffset( + holder.buffer, holder.start, holder.scale, ${type.width}); <#elseif minor.class == "FixedSizeBinary"> byte[] value = new byte [holder.byteWidth]; holder.buffer.getBytes(0, value, 0, holder.byteWidth); diff --git a/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java b/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java index a1a9cf7e1d..46c6fb70ce 100644 --- a/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java +++ b/vector/src/main/java/org/apache/arrow/vector/util/DecimalUtility.java @@ -45,9 +45,17 @@ private DecimalUtility() {} */ public static BigDecimal getBigDecimalFromArrowBuf( ArrowBuf bytebuf, int index, int scale, int byteWidth) { + return getBigDecimalFromArrowBufAtOffset(bytebuf, (long) index * byteWidth, scale, byteWidth); + } + + /** + * Read an ArrowType.Decimal at the given byte offset in the ArrowBuf and convert to a BigDecimal + * with the given scale. + */ + public static BigDecimal getBigDecimalFromArrowBufAtOffset( + ArrowBuf bytebuf, long startIndex, int scale, int byteWidth) { byte[] value = new byte[byteWidth]; byte temp; - final long startIndex = (long) index * byteWidth; bytebuf.getBytes(startIndex, value, 0, byteWidth); if (LITTLE_ENDIAN) { diff --git a/vector/src/test/java/org/apache/arrow/vector/TestDecimalHolderDecoding.java b/vector/src/test/java/org/apache/arrow/vector/TestDecimalHolderDecoding.java new file mode 100644 index 0000000000..26259bd04f --- /dev/null +++ b/vector/src/test/java/org/apache/arrow/vector/TestDecimalHolderDecoding.java @@ -0,0 +1,80 @@ +/* + * 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.arrow.vector; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.complex.impl.Decimal256HolderReaderImpl; +import org.apache.arrow.vector.complex.impl.DecimalHolderReaderImpl; +import org.apache.arrow.vector.complex.impl.NullableDecimal256HolderReaderImpl; +import org.apache.arrow.vector.complex.impl.NullableDecimalHolderReaderImpl; +import org.apache.arrow.vector.holders.Decimal256Holder; +import org.apache.arrow.vector.holders.DecimalHolder; +import org.apache.arrow.vector.holders.NullableDecimal256Holder; +import org.apache.arrow.vector.holders.NullableDecimalHolder; +import org.junit.jupiter.api.Test; + +public class TestDecimalHolderDecoding { + @Test + public void testDecimalHolderByteOrderAndOffset() { + try (BufferAllocator allocator = new RootAllocator(); + DecimalVector vector = new DecimalVector("decimal", allocator, 38, 2)) { + vector.allocateNew(3); + vector.set(0, new BigDecimal("1.23")); + BigDecimal[] values = {new BigDecimal("1234567.89"), new BigDecimal("-1234567.89")}; + for (int i = 0; i < values.length; i++) { + vector.set(i + 1, values[i]); + NullableDecimalHolder nullableHolder = new NullableDecimalHolder(); + vector.get(i + 1, nullableHolder); + assertEquals( + values[i], new NullableDecimalHolderReaderImpl(nullableHolder).readBigDecimal()); + DecimalHolder holder = new DecimalHolder(); + holder.buffer = nullableHolder.buffer; + holder.start = nullableHolder.start; + holder.precision = nullableHolder.precision; + holder.scale = nullableHolder.scale; + assertEquals(values[i], new DecimalHolderReaderImpl(holder).readBigDecimal()); + } + } + } + + @Test + public void testDecimal256HolderByteOrderAndOffset() { + try (BufferAllocator allocator = new RootAllocator(); + Decimal256Vector vector = new Decimal256Vector("decimal", allocator, 76, 2)) { + vector.allocateNew(3); + vector.set(0, new BigDecimal("1.23")); + BigDecimal[] values = {new BigDecimal("1234567.89"), new BigDecimal("-1234567.89")}; + for (int i = 0; i < values.length; i++) { + vector.set(i + 1, values[i]); + NullableDecimal256Holder nullableHolder = new NullableDecimal256Holder(); + vector.get(i + 1, nullableHolder); + assertEquals( + values[i], new NullableDecimal256HolderReaderImpl(nullableHolder).readBigDecimal()); + Decimal256Holder holder = new Decimal256Holder(); + holder.buffer = nullableHolder.buffer; + holder.start = nullableHolder.start; + holder.precision = nullableHolder.precision; + holder.scale = nullableHolder.scale; + assertEquals(values[i], new Decimal256HolderReaderImpl(holder).readBigDecimal()); + } + } + } +} From 66d70858e5d9e93816d9e3d237d5b1058c781787 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BE=99=E9=AA=91=E5=A3=ABk?= <37928252+dragonknightk@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:19:46 +0000 Subject: [PATCH 10/39] GH-832: [Avro] Use readString in AvroStringConsumer (#1520) ## What's Changed AvroStringConsumer read string fields with Decoder.readBytes. That works with BinaryDecoder, because the binary encoding for string and bytes is the same. ResolvingDecoder checks the reader schema and throws AvroTypeException: "Attempt to process a bytes when a string was expected." ValidatingDecoder throws the same error, and this change fixes both. The consumer now calls Decoder.readString and copies the Utf8 bytes into the VarCharVector, reusing the Utf8 instance the same way the old code reused a ByteBuffer. Closes #832. ## AI Disclosure Human-led contribution. Grok Bot, working for dragonknightk, assisted with this change, including the code, tests, and description. All submitted content was reviewed by a human before submission. Signed-off-by: dragonknightk <37928252+dragonknightk@users.noreply.github.com> --- .../avro/consumers/AvroStringConsumer.java | 12 +++--- .../arrow/adapter/avro/AvroToArrowTest.java | 43 +++++++++++++++++++ 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/adapter/avro/src/main/java/org/apache/arrow/adapter/avro/consumers/AvroStringConsumer.java b/adapter/avro/src/main/java/org/apache/arrow/adapter/avro/consumers/AvroStringConsumer.java index 164d595e9c..dc77d1b258 100644 --- a/adapter/avro/src/main/java/org/apache/arrow/adapter/avro/consumers/AvroStringConsumer.java +++ b/adapter/avro/src/main/java/org/apache/arrow/adapter/avro/consumers/AvroStringConsumer.java @@ -17,9 +17,9 @@ package org.apache.arrow.adapter.avro.consumers; import java.io.IOException; -import java.nio.ByteBuffer; import org.apache.arrow.vector.VarCharVector; import org.apache.avro.io.Decoder; +import org.apache.avro.util.Utf8; /** * Consumer which consume string type values from avro decoder. Write the data to {@link @@ -27,7 +27,7 @@ */ public class AvroStringConsumer extends BaseAvroConsumer { - private ByteBuffer cacheBuffer; + private Utf8 cacheUtf8; /** Instantiate a AvroStringConsumer. */ public AvroStringConsumer(VarCharVector vector) { @@ -36,9 +36,9 @@ public AvroStringConsumer(VarCharVector vector) { @Override public void consume(Decoder decoder) throws IOException { - // cacheBuffer is initialized null and create in the first consume, - // if its capacity < size to read, decoder will create a new one with new capacity. - cacheBuffer = decoder.readBytes(cacheBuffer); - vector.setSafe(currentIndex++, cacheBuffer, 0, cacheBuffer.limit()); + // cacheUtf8 starts null and is reused; the Utf8 grows its backing array + // when needed, so only getByteLength() bytes are valid. + cacheUtf8 = decoder.readString(cacheUtf8); + vector.setSafe(currentIndex++, cacheUtf8.getBytes(), 0, cacheUtf8.getByteLength()); } } diff --git a/adapter/avro/src/test/java/org/apache/arrow/adapter/avro/AvroToArrowTest.java b/adapter/avro/src/test/java/org/apache/arrow/adapter/avro/AvroToArrowTest.java index 899ea40301..29718866e7 100644 --- a/adapter/avro/src/test/java/org/apache/arrow/adapter/avro/AvroToArrowTest.java +++ b/adapter/avro/src/test/java/org/apache/arrow/adapter/avro/AvroToArrowTest.java @@ -18,6 +18,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -25,6 +26,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.arrow.adapter.avro.consumers.AvroStringConsumer; import org.apache.arrow.vector.FieldVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.VectorSchemaRoot; @@ -34,6 +36,11 @@ import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; +import org.apache.avro.io.BinaryDecoder; +import org.apache.avro.io.BinaryEncoder; +import org.apache.avro.io.DecoderFactory; +import org.apache.avro.io.EncoderFactory; +import org.apache.avro.io.ResolvingDecoder; import org.junit.jupiter.api.Test; public class AvroToArrowTest extends AvroTestBase { @@ -49,6 +56,42 @@ public void testStringType() throws Exception { checkPrimitiveResult(data, vector); } + /** + * Regression for issue 832. {@code AvroStringConsumer} used {@code Decoder.readBytes}, so a + * {@link ResolvingDecoder} whose reader schema is a string threw {@code AvroTypeException}: + * "Attempt to process a bytes when a string was expected." Values are written with {@code + * Encoder.writeString} and include an empty string and a non-ASCII literal so the reused {@code + * Utf8} buffer is copied with the correct byte length. + */ + @Test + public void testStringTypeWithResolvingDecoder() throws Exception { + Schema schema = getSchema("test_primitive_string.avsc"); + List data = Arrays.asList("v1", "", "你好世界"); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null); + for (String value : data) { + encoder.writeString(value); + } + encoder.flush(); + + DecoderFactory factory = DecoderFactory.get(); + BinaryDecoder binaryDecoder = factory.binaryDecoder(out.toByteArray(), null); + ResolvingDecoder resolvingDecoder = factory.resolvingDecoder(schema, schema, binaryDecoder); + + VarCharVector vector = new VarCharVector("str", config.getAllocator()); + try (AvroStringConsumer consumer = new AvroStringConsumer(vector)) { + vector.allocateNew(); + for (int i = 0; i < data.size(); i++) { + resolvingDecoder.configure(binaryDecoder); + consumer.consume(resolvingDecoder); + resolvingDecoder.drain(); + } + vector.setValueCount(data.size()); + checkPrimitiveResult(data, vector); + } + } + @Test public void testNullableStringType() throws Exception { Schema schema = getSchema("test_nullable_string.avsc"); From 758fb56b8e62707551881efc9441e9e9a882088d Mon Sep 17 00:00:00 2001 From: Abhishek Prajapati Date: Tue, 24 Nov 2026 17:44:32 +0530 Subject: [PATCH 11/39] GH-1268: [JDBC] Honor DriverManager login timeout (#1507) ## What's Changed Honor the timeout configured through `DriverManager.setLoginTimeout` during Flight SQL JDBC connection establishment. The timeout covers the authentication handshake and initial session setup. Zero keeps the synchronous connection path without a login deadline. When the deadline expires, return `SQLTimeoutException` and cancel pending login RPCs. Release partially constructed clients, channels, and allocators on failure, and close a connection if it finishes after the caller has timed out. The JDBC login deadline and the Netty `connectTimeoutMs` socket setting are independent. DataSource login-timeout support is tracked separately in #1267. ## Testing - Reproduced the stalled authentication on upstream. The driver's two-second login timeout did not fire, and the regression test reached its 15-second guard. - Covered stalled authentication and session setup, cancellation and transport closure, successful connections with zero and positive timeouts, and cleanup after the deadline. The driver and client-handler test classes passed all 32 cases. - Maven verification passed on JDK 21 with 4,607 passing test executions and 73 skips across 14 modules. Checkstyle, Spotless, dependency analysis, and the shaded JAR build passed. - A standalone `DriverManager.getConnection` smoke test using the shaded JAR raised `SQLTimeoutException` in 1,022 ms with a one-second timeout. ## AI disclosure Codex assisted with diagnosis, implementation, tests, validation, and drafting this description. Closes #1268. Co-authored-by: Abhishek Prajapati <215712201+Ap-95671@users.noreply.github.com> --- docs/source/flight_sql_jdbc_driver.rst | 7 + .../driver/jdbc/ArrowFlightConnection.java | 77 +++++------ .../jdbc/ArrowFlightJdbcDataSource.java | 2 +- .../driver/jdbc/ArrowFlightJdbcDriver.java | 91 ++++++++++++- .../client/ArrowFlightSqlClientHandler.java | 48 ++++--- .../jdbc/ArrowFlightJdbcDriverTest.java | 126 +++++++++++++++++- .../ArrowFlightSqlClientHandlerTest.java | 3 + 7 files changed, 293 insertions(+), 61 deletions(-) diff --git a/docs/source/flight_sql_jdbc_driver.rst b/docs/source/flight_sql_jdbc_driver.rst index fe731fcaaf..a685e2a799 100644 --- a/docs/source/flight_sql_jdbc_driver.rst +++ b/docs/source/flight_sql_jdbc_driver.rst @@ -195,6 +195,13 @@ DriverManager#getConnection() the username and password supplied on the URI supercede the username and password arguments to the function call. +Use ``DriverManager.setLoginTimeout(seconds)`` to limit the time the driver +waits for a connection, including the authentication handshake and initial +session setup. On expiration, the driver cancels pending login RPCs and throws +``SQLTimeoutException``. A value of zero disables the login timeout. The +``connectTimeoutMs`` property separately controls the Netty socket connection +timeout. + OAuth 2.0 Authentication ======================== diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index 3662230678..5338bfdc8a 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -104,12 +104,18 @@ static ArrowFlightConnection createNewConnection( final Properties properties, final BufferAllocator allocator) throws SQLException { - url = replaceSemiColons(url); - final ArrowFlightConnectionConfigImpl config = new ArrowFlightConnectionConfigImpl(properties); - final ArrowFlightSqlClientHandler clientHandler = - createNewClientHandler(config, allocator, driver.getDriverVersion()); - return new ArrowFlightConnection( - driver, factory, url, properties, config, allocator, clientHandler); + ArrowFlightSqlClientHandler clientHandler = null; + try { + url = replaceSemiColons(url); + final ArrowFlightConnectionConfigImpl config = + new ArrowFlightConnectionConfigImpl(properties); + clientHandler = createNewClientHandler(config, allocator, driver.getDriverVersion()); + return new ArrowFlightConnection( + driver, factory, url, properties, config, allocator, clientHandler); + } catch (SQLException | RuntimeException | Error e) { + AutoCloseables.close(e, clientHandler, allocator); + throw e; + } } private static ArrowFlightSqlClientHandler createNewClientHandler( @@ -117,40 +123,31 @@ private static ArrowFlightSqlClientHandler createNewClientHandler( final BufferAllocator allocator, final DriverVersion driverVersion) throws SQLException { - try { - return new ArrowFlightSqlClientHandler.Builder() - .withHost(config.getHost()) - .withPort(config.getPort()) - .withUsername(config.getUser()) - .withPassword(config.getPassword()) - .withTrustStorePath(config.getTrustStorePath()) - .withTrustStorePassword(config.getTrustStorePassword()) - .withSystemTrustStore(config.useSystemTrustStore()) - .withTlsRootCertificates(config.getTlsRootCertificatesPath()) - .withClientCertificate(config.getClientCertificatePath()) - .withClientKey(config.getClientKeyPath()) - .withBufferAllocator(allocator) - .withEncryption(config.useEncryption()) - .withDisableCertificateVerification(config.getDisableCertificateVerification()) - .withHostnameOverride(config.getHostnameOverride()) - .withToken(config.getToken()) - .withCallOptions(config.toCallOption()) - .withRetainCookies(config.retainCookies()) - .withRetainAuth(config.retainAuth()) - .withCatalog(config.getCatalog()) - .withClientCache(config.useClientCache() ? new FlightClientCache() : null) - .withConnectTimeout(config.getConnectTimeout()) - .withDriverVersion(driverVersion) - .withOAuthConfiguration(config.getOauthConfiguration()) - .build(); - } catch (final SQLException e) { - try { - allocator.close(); - } catch (final Exception allocatorCloseEx) { - e.addSuppressed(allocatorCloseEx); - } - throw e; - } + return new ArrowFlightSqlClientHandler.Builder() + .withHost(config.getHost()) + .withPort(config.getPort()) + .withUsername(config.getUser()) + .withPassword(config.getPassword()) + .withTrustStorePath(config.getTrustStorePath()) + .withTrustStorePassword(config.getTrustStorePassword()) + .withSystemTrustStore(config.useSystemTrustStore()) + .withTlsRootCertificates(config.getTlsRootCertificatesPath()) + .withClientCertificate(config.getClientCertificatePath()) + .withClientKey(config.getClientKeyPath()) + .withBufferAllocator(allocator) + .withEncryption(config.useEncryption()) + .withDisableCertificateVerification(config.getDisableCertificateVerification()) + .withHostnameOverride(config.getHostnameOverride()) + .withToken(config.getToken()) + .withCallOptions(config.toCallOption()) + .withRetainCookies(config.retainCookies()) + .withRetainAuth(config.retainAuth()) + .withCatalog(config.getCatalog()) + .withClientCache(config.useClientCache() ? new FlightClientCache() : null) + .withConnectTimeout(config.getConnectTimeout()) + .withDriverVersion(driverVersion) + .withOAuthConfiguration(config.getOauthConfiguration()) + .build(); } void reset() throws SQLException { diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java index 0b5d7fd368..068062a053 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDataSource.java @@ -87,7 +87,7 @@ public ArrowFlightConnection getConnection() throws SQLException { public ArrowFlightConnection getConnection(final String username, final String password) throws SQLException { final Properties properties = getProperties(username, password); - return new ArrowFlightJdbcDriver().connect(config.url(), properties); + return new ArrowFlightJdbcDriver().connect(config.url(), properties, 0); } @Override diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java index 12ef8030d7..99d3b58156 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriver.java @@ -18,6 +18,7 @@ import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.replaceSemiColons; +import io.grpc.Context; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -25,11 +26,19 @@ import java.io.Reader; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.SQLTimeoutException; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; import java.util.logging.Logger; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; import org.apache.arrow.driver.jdbc.utils.UrlParser; @@ -74,6 +83,11 @@ public Logger getParentLogger() { @Override public ArrowFlightConnection connect(final String url, final Properties info) throws SQLException { + return connect(url, info, DriverManager.getLoginTimeout()); + } + + ArrowFlightConnection connect(final String url, final Properties info, final int timeoutSeconds) + throws SQLException { final Properties properties = new Properties(info); if (info != null) { properties.putAll(info); @@ -88,14 +102,89 @@ public ArrowFlightConnection connect(final String url, final Properties info) properties.putAll(propertiesFromUrl); } + final Properties connectionProperties = lowerCasePropertyKeys(properties); + if (timeoutSeconds <= 0) { + return openConnection(url, connectionProperties); + } + return connectWithTimeout(() -> openConnection(url, connectionProperties), timeoutSeconds); + } + + private ArrowFlightConnection openConnection(final String url, final Properties properties) + throws SQLException { try { return ArrowFlightConnection.createNewConnection( - this, factory, url, lowerCasePropertyKeys(properties), new RootAllocator(Long.MAX_VALUE)); + this, factory, url, properties, new RootAllocator(Long.MAX_VALUE)); } catch (final FlightRuntimeException e) { throw new SQLException("Failed to connect.", e); } } + @VisibleForTesting + static ArrowFlightConnection connectWithTimeout( + final Callable connect, final int timeoutSeconds) throws SQLException { + final CompletableFuture result = new CompletableFuture<>(); + // Closing the context cancels any in-flight login RPCs. + try (Context.CancellableContext context = Context.current().withCancellation()) { + final Thread worker = + new Thread( + context.wrap( + () -> { + if (result.isDone()) { + return; + } + try { + final ArrowFlightConnection connection = connect.call(); + // A timed-out attempt still owns any connection it manages to open. + if (!result.complete(connection)) { + closeAbandonedConnection(connection); + } + } catch (Exception | Error e) { + result.completeExceptionally(e); + } + }), + "arrow-flight-jdbc-connect"); + worker.setDaemon(true); + result.orTimeout(timeoutSeconds, TimeUnit.SECONDS); + worker.start(); + + try { + return result.get(); + } catch (InterruptedException e) { + if (!result.completeExceptionally(e)) { + result.thenAcceptAsync( + connection -> context.run(() -> closeAbandonedConnection(connection))); + } + Thread.currentThread().interrupt(); + throw new SQLException("Interrupted while connecting.", e); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + if (cause instanceof TimeoutException) { + throw new SQLTimeoutException( + "Login timed out after " + timeoutSeconds + " seconds.", cause); + } + if (cause instanceof SQLException sqlException) { + throw sqlException; + } + if (cause instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (cause instanceof Error error) { + throw error; + } + throw new SQLException("Failed to connect.", cause); + } + } + } + + private static void closeAbandonedConnection(final ArrowFlightConnection connection) { + try { + connection.close(); + } catch (SQLException | RuntimeException e) { + Logger.getLogger(ArrowFlightJdbcDriver.class.getPackageName()) + .log(Level.WARNING, "Failed to close an abandoned flight SQL connection.", e); + } + } + @Override protected String getFactoryClassName(final JdbcVersion jdbcVersion) { return ArrowFlightJdbcFactory.class.getName(); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 97108e599b..9c168126a4 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -17,6 +17,7 @@ package org.apache.arrow.driver.jdbc.client; import com.google.common.collect.ImmutableMap; +import io.grpc.ManagedChannel; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; import java.io.IOException; @@ -291,6 +292,19 @@ public long executeUpdate(final String query) { @Override public void close() throws SQLException { + try { + AutoCloseables.close(this::closeCatalogSession, sqlClient); + } catch (FlightRuntimeException fre) { + handleBenignCloseException( + fre, "Failed to clean up client resources.", "closing Flight SQL client"); + } catch (SQLException e) { + throw e; + } catch (final Exception e) { + throw new SQLException("Failed to clean up client resources.", e); + } + } + + private void closeCatalogSession() throws SQLException { if (catalog.isPresent()) { try { sqlClient.closeSession(new CloseSessionRequest(), getOptions()); @@ -299,14 +313,6 @@ public void close() throws SQLException { fre, "Failed to close Flight SQL session.", "closing Flight SQL session"); } } - try { - AutoCloseables.close(sqlClient); - } catch (FlightRuntimeException fre) { - handleBenignCloseException( - fre, "Failed to clean up client resources.", "closing Flight SQL client"); - } catch (final Exception e) { - throw new SQLException("Failed to clean up client resources.", e); - } } /** @@ -1125,6 +1131,7 @@ public ArrowFlightSqlClientHandler build() throws SQLException { // itself. Set buildTimeMiddlewareFactories = new HashSet<>(this.middlewareFactories); + ManagedChannel channel = null; FlightClient client = null; boolean isUsingUserPasswordAuth = username != null && token == null; @@ -1192,9 +1199,8 @@ public ArrowFlightSqlClientHandler build() throws SQLException { channelBuilder.withOption( ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout.toMillis()); } - client = - FlightGrpcUtils.createFlightClient( - allocator, channelBuilder.build(), clientBuilder.middleware()); + channel = channelBuilder.build(); + client = FlightGrpcUtils.createFlightClient(allocator, channel, clientBuilder.middleware()); final ArrayList credentialOptions = new ArrayList<>(); // Authentication priority: OAuth > token > username/password if (oauthConfig != null) { @@ -1229,14 +1235,20 @@ public ArrowFlightSqlClientHandler build() throws SQLException { | IOException | FlightRuntimeException e) { final SQLException originalException = new SQLException(e); - if (client != null) { - try { - client.close(); - } catch (final InterruptedException interruptedException) { - originalException.addSuppressed(interruptedException); - } - } + closeFailedClient(originalException, client, channel); throw originalException; + } catch (RuntimeException | Error e) { + closeFailedClient(e, client, channel); + throw e; + } + } + + private static void closeFailedClient( + Throwable failure, @Nullable FlightClient client, @Nullable ManagedChannel channel) { + if (client != null) { + AutoCloseables.close(failure, client); + } else if (channel != null) { + AutoCloseables.close(failure, channel::shutdownNow); } } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java index 88fb9889b6..878cff2d29 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java @@ -21,24 +21,42 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; - +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; + +import io.grpc.Attributes; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.ServerCall; +import io.grpc.ServerServiceDefinition; +import io.grpc.ServerTransportFilter; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; +import java.sql.SQLTimeoutException; import java.util.Collection; import java.util.Map; import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; +import org.apache.arrow.flight.impl.FlightServiceGrpc; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Tests for {@link ArrowFlightJdbcDriver}. */ public class ArrowFlightJdbcDriverTest { @@ -91,6 +109,112 @@ public void testDriverIsRegisteredInDriverManager() throws Exception { instanceof ArrowFlightJdbcDriver); } + @ParameterizedTest(name = "connection setup with catalog={0}") + @ValueSource(booleans = {false, true}) + @Timeout(15) + @ResourceLock("DriverManager.loginTimeout") + public void testDriverManagerLoginTimeoutCancelsConnectionSetup(boolean catalog) + throws Exception { + final CountDownLatch loginRpcStarted = new CountDownLatch(1); + final CountDownLatch loginRpcCancelled = new CountDownLatch(1); + final CountDownLatch transportClosed = new CountDownLatch(1); + final MethodDescriptor loginMethod = + catalog ? FlightServiceGrpc.getDoActionMethod() : FlightServiceGrpc.getHandshakeMethod(); + final Server server = + ServerBuilder.forPort(0) + .addTransportFilter( + new ServerTransportFilter() { + @Override + public void transportTerminated(Attributes transportAttributes) { + transportClosed.countDown(); + } + }) + .addService(stalledLoginService(loginMethod, loginRpcStarted, loginRpcCancelled)) + .build() + .start(); + final int previousTimeout = DriverManager.getLoginTimeout(); + try { + DriverManager.setLoginTimeout(2); + final String url = + "jdbc:arrow-flight-sql://localhost:" + server.getPort() + "?useEncryption=false"; + final Properties properties = new Properties(); + if (catalog) { + properties.setProperty("catalog", "test"); + } else { + properties.setProperty("user", "user"); + properties.setProperty("password", "pass"); + } + // Other tests register additional Arrow drivers, which DriverManager would also try. + final Driver driver = DriverManager.getDriver(url); + assertThrows(SQLTimeoutException.class, () -> driver.connect(url, properties)); + assertEquals(0, loginRpcStarted.getCount(), "The server should have received the login RPC"); + assertTrue(loginRpcCancelled.await(5, TimeUnit.SECONDS), "The login RPC should be cancelled"); + assertTrue(transportClosed.await(5, TimeUnit.SECONDS), "The client channel should close"); + } finally { + DriverManager.setLoginTimeout(previousTimeout); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static ServerServiceDefinition stalledLoginService( + MethodDescriptor method, + CountDownLatch started, + CountDownLatch cancelled) { + return ServerServiceDefinition.builder(FlightServiceGrpc.SERVICE_NAME) + .addMethod( + method, + (call, headers) -> { + call.request(1); + started.countDown(); + return new ServerCall.Listener() { + @Override + public void onCancel() { + cancelled.countDown(); + } + }; + }) + .build(); + } + + @ParameterizedTest + @ValueSource(ints = {0, 10}) + @ResourceLock("DriverManager.loginTimeout") + public void testDriverManagerConnectsWithLoginTimeout(int loginTimeout) throws Exception { + final int previousTimeout = DriverManager.getLoginTimeout(); + try { + DriverManager.setLoginTimeout(loginTimeout); + final String url = + "jdbc:arrow-flight-sql://localhost:" + + FLIGHT_SERVER_TEST_EXTENSION.getPort() + + "?useEncryption=false"; + try (Connection connection = DriverManager.getConnection(url, "user1", "pass1")) { + assertTrue(connection.isValid(0)); + } + } finally { + DriverManager.setLoginTimeout(previousTimeout); + } + } + + @Test + public void testConnectionCompletedAfterLoginTimeoutIsClosed() throws Exception { + final ArrowFlightConnection connection = mock(ArrowFlightConnection.class); + final CountDownLatch finishConnecting = new CountDownLatch(1); + try { + assertThrows( + SQLTimeoutException.class, + () -> + ArrowFlightJdbcDriver.connectWithTimeout( + () -> { + assertTrue(finishConnecting.await(5, TimeUnit.SECONDS)); + return connection; + }, + 1)); + } finally { + finishConnecting.countDown(); + } + verify(connection, timeout(5000)).close(); + } + /** * Tests whether the {@link ArrowFlightJdbcDriver} returns null when provided with an unsupported * URL prefix. diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java index b44b310eb5..4d37b91102 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java @@ -24,6 +24,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -145,6 +146,7 @@ public void testCloseHandlesFlightRuntimeException( } else { assertThrows(SQLException.class, sqlClientHandler::close); } + verify(sqlClient).close(); } private static Object[] testCloseHandlesFlightRuntimeException() { @@ -163,6 +165,7 @@ private static Object[] testCloseHandlesFlightRuntimeException() { new Object[] {false, unavailableError, true}, new Object[] {true, unknownError, false}, new Object[] {false, unknownError, false}, + new Object[] {true, CallStatus.CANCELLED, false}, }; } } From f51583bc295e743895655459891d0e674981890d Mon Sep 17 00:00:00 2001 From: Robert Kruszewski Date: Tue, 24 Nov 2026 13:22:42 +0000 Subject: [PATCH 12/39] MINOR: Preserve Decimal256 type metadata in promoted union writers (#1519) ## What's Changed split from #1228, in cases like following ``` writer.startList(); writer.decimal().writeDecimal(new BigDecimal("123.45")); writer.decimal256().writeDecimal256( new BigDecimal("123456789012345678901234567890123456789.01")); ``` we would lose the fact that 2nd values was Decimal256 --- .../codegen/templates/PromotableWriter.java | 1 + .../complex/impl/TestPromotableWriter.java | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/vector/src/main/codegen/templates/PromotableWriter.java b/vector/src/main/codegen/templates/PromotableWriter.java index 11d34f72c9..405309cc1c 100644 --- a/vector/src/main/codegen/templates/PromotableWriter.java +++ b/vector/src/main/codegen/templates/PromotableWriter.java @@ -316,6 +316,7 @@ public void setPosition(int index) { protected boolean requiresArrowType(MinorType type) { return type == MinorType.DECIMAL + || type == MinorType.DECIMAL256 || type == MinorType.MAP || type == MinorType.DURATION || type == MinorType.FIXEDSIZEBINARY diff --git a/vector/src/test/java/org/apache/arrow/vector/complex/impl/TestPromotableWriter.java b/vector/src/test/java/org/apache/arrow/vector/complex/impl/TestPromotableWriter.java index 5b6d65d6ba..2066a23084 100644 --- a/vector/src/test/java/org/apache/arrow/vector/complex/impl/TestPromotableWriter.java +++ b/vector/src/test/java/org/apache/arrow/vector/complex/impl/TestPromotableWriter.java @@ -25,6 +25,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import org.apache.arrow.memory.ArrowBuf; @@ -759,6 +760,60 @@ public void testPromoteLargeVarBinaryHelpersDirect() throws Exception { } } + @Test + public void testDecimal256InPromotedUnion() { + BigDecimal narrow = new BigDecimal("123.45"); + BigDecimal wide = new BigDecimal("123456789012345678901234567890123456789.01"); + try (ListVector vector = ListVector.empty("decimals", allocator)) { + UnionListWriter writer = vector.getWriter(); + writer.startList(); + writer.decimal().writeDecimal(narrow); + writer.decimal256().writeDecimal256(wide); + writer.decimal().writeDecimal(narrow.negate()); + writer.decimal256().writeDecimal256(wide.negate()); + writer.endList(); + vector.setValueCount(1); + assertEquals( + Arrays.asList(narrow, wide, narrow.negate(), wide.negate()), vector.getObject(0)); + vector.validateFull(); + } + } + + @Test + public void testAddDecimal256ToExistingUnion() { + BigDecimal decimal = new BigDecimal("-123.456"); + try (ListVector vector = ListVector.empty("values", allocator)) { + UnionListWriter writer = vector.getWriter(); + writer.startList(); + writer.integer().writeInt(7); + writer.bigInt().writeBigInt(8L); + writer.decimal256().writeDecimal256(decimal); + writer.endList(); + vector.setValueCount(1); + assertEquals(Arrays.asList(7, 8L, decimal), vector.getObject(0)); + } + } + + @Test + public void testPromoteStructFieldToDecimal256() throws Exception { + BigDecimal decimal = new BigDecimal("123.456"); + try (StructVector parent = StructVector.empty("parent", allocator); + PromotableWriter writer = new PromotableWriter(parent.addOrGetStruct("value"), parent)) { + parent.allocateNew(); + writer.setPosition(0); + writer.start(); + writer.integer("id").writeInt(7); + writer.end(); + writer.setPosition(1); + writer.writeDecimal256(decimal); + parent.setValueCount(2); + + UnionVector values = parent.getChild("value", UnionVector.class); + assertEquals(7, values.getStruct().getObject(0).get("id")); + assertEquals(decimal, values.getObject(1)); + } + } + @Test public void testPromoteToUnionFromDecimal() throws Exception { try (final NonNullableStructVector container = From fd5fb7cbb4ac8e77e318d87330f1ddf7a50f844a Mon Sep 17 00:00:00 2001 From: Andy Grove Date: Tue, 24 Nov 2026 18:03:15 -0700 Subject: [PATCH 13/39] GH-1497: [CI] Compute pom.xml paths without Python in build.sh (#1498) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What's Changed macOS does not ship a `python` executable, so `ci/scripts/build.sh` failed when the release verification script built the source release on macOS. The script now runs `find` from inside `source_dir` to get relative paths. This removes the Python dependency and the macOS-specific branch, so Linux and macOS use the same code path. Closes #1497. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ci/scripts/build.sh | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/ci/scripts/build.sh b/ci/scripts/build.sh index 146a40cf7a..a790f11b1c 100755 --- a/ci/scripts/build.sh +++ b/ci/scripts/build.sh @@ -43,17 +43,11 @@ cp -r "${source_dir}/arrow-format" "${build_dir}" cp -r "${source_dir}/dev" "${build_dir}" # Instead of hardcoding the list of directories to copy, find pom.xml and then -# crawl back up to the top. GNU realpath has --relative-to but this does not -# work on macOS - -poms=$(find "${source_dir}" -not \( -path "${source_dir}"/build -prune \) -type f -name pom.xml) -if [[ "$OSTYPE" == "darwin"* ]]; then - poms=$(echo "$poms" | xargs -n1 python -c "import sys; import os.path; print(os.path.relpath(sys.argv[1], '${source_dir}'))") -else - poms=$(echo "$poms" | xargs -n1 realpath -s --relative-to="${source_dir}") -fi +# crawl back up to the top. +poms=$(cd "${source_dir}" && find . -not \( -path ./build -prune \) -type f -name pom.xml) -for source_root in $(echo "${poms}" | awk -F/ '{print $1}' | sort -u); do +# ./dataset/pom.xml -> dataset +for source_root in $(echo "${poms}" | awk -F/ '{print $2}' | sort -u); do cp -r "${source_dir}/${source_root}" "${build_dir}" done From 10c55b9c8a01cf5db557effce133eaf9818c51b2 Mon Sep 17 00:00:00 2001 From: Abdul Rawoof Khan Date: Wed, 25 Nov 2026 23:39:21 +0530 Subject: [PATCH 14/39] MINOR: Reject truncated UTF-8 sequences in Text.validateUTF8 (#1522) ## What's Changed `Text.validateUTF8Internal` walks the bytes with a lead-byte/trail-byte state machine, but when the loop runs out of input it returns success even if it is still waiting for trail bytes. A value that ends partway through a multi-byte sequence, such as `C3`, `E2 82` or `F0 9F 98`, is reported as valid UTF-8. That helper backs `validateScalars` in `VarCharVector`, `LargeVarCharVector` and `ViewVarCharVector`, so `ValueVectorUtility.validateFull` (and `ArrowReader` with `setValidateBatches(true)`, the option recommended for untrusted IPC input) accepts a Utf8 column holding invalid UTF-8. Lead bytes that are invalid on their own (`FF FE`) were already rejected, which is why the existing tests pass. The fix reports the end position as malformed when the input ends outside the lead-byte state. Valid input is unaffected. `testValidateTruncatedUTF8` in `TestValidateVectorFull` covers truncated 2, 3 and 4 byte sequences for VarChar and LargeVarChar. It fails without the change and passes with it, and the rest of the `vector` tests still pass. --- .../org/apache/arrow/vector/util/Text.java | 4 ++++ .../validate/TestValidateVectorFull.java | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/vector/src/main/java/org/apache/arrow/vector/util/Text.java b/vector/src/main/java/org/apache/arrow/vector/util/Text.java index 2edb004088..9dd07d5b44 100644 --- a/vector/src/main/java/org/apache/arrow/vector/util/Text.java +++ b/vector/src/main/java/org/apache/arrow/vector/util/Text.java @@ -504,6 +504,10 @@ private static Optional validateUTF8Internal(byte[] utf8, int start, in } // switch (state) count++; } + if (state != LEAD_BYTE) { + // the input ended in the middle of a multi-byte sequence + return Optional.of(count); + } return Optional.empty(); } diff --git a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java index cb76453303..6ad56f3946 100644 --- a/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java +++ b/vector/src/test/java/org/apache/arrow/vector/validate/TestValidateVectorFull.java @@ -408,6 +408,28 @@ public void testValidateLargeVarCharUTF8() { } } + @Test + public void testValidateTruncatedUTF8() { + // multi-byte sequences cut short at the end of the value + byte[][] truncated = { + {(byte) 0xC3}, {(byte) 0xE2, (byte) 0x82}, {'a', (byte) 0xF0, (byte) 0x9F, (byte) 0x98} + }; + for (byte[] value : truncated) { + try (final VarCharVector vector = new VarCharVector("v", allocator)) { + setVector(vector, "aaa".getBytes(StandardCharsets.UTF_8), value); + ValidateUtil.ValidateException e = + assertThrows(ValidateUtil.ValidateException.class, vector::validateFull); + assertTrue(e.getMessage().contains("UTF")); + } + try (final LargeVarCharVector vector = new LargeVarCharVector("v", allocator)) { + setVector(vector, "aaa".getBytes(StandardCharsets.UTF_8), value); + ValidateUtil.ValidateException e = + assertThrows(ValidateUtil.ValidateException.class, vector::validateFull); + assertTrue(e.getMessage().contains("UTF")); + } + } + } + @Test public void testValidateDecimal() { try (final DecimalVector vector = From 6ae8046d65b70d3f684db4a780cc35c955eee18e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 10 Sep 2026 21:06:29 +0100 Subject: [PATCH 15/39] BDX-645: prototype PollInfo support for JDBC --- .../driver/jdbc/ArrowFlightConnection.java | 1 + .../ArrowFlightJdbcFlightStreamResultSet.java | 55 ++- .../jdbc/ArrowFlightPreparedStatement.java | 37 +- .../driver/jdbc/ArrowFlightStatement.java | 49 +- .../client/ArrowFlightSqlClientHandler.java | 174 +++++++- .../driver/jdbc/client/PollInfoOperation.java | 129 ++++++ .../ArrowFlightConnectionConfigImpl.java | 6 + .../driver/jdbc/OAuthIntegrationTest.java | 2 +- .../driver/jdbc/PollInfoExecutionTest.java | 418 ++++++++++++++++++ .../SharedServerPollInfoExecutionTest.java | 353 +++++++++++++++ .../jdbc/utils/MockFlightSqlProducer.java | 2 +- .../utils/PollingMockFlightSqlProducer.java | 256 +++++++++++ .../arrow/flight/sql/FlightSqlClient.java | 46 +- reports/call-site-inventory.md | 27 ++ reports/evidence.jsonl | 10 + reports/jdbc-report.md | 169 +++++++ 16 files changed, 1706 insertions(+), 28 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java create mode 100644 reports/call-site-inventory.md create mode 100644 reports/evidence.jsonl create mode 100644 reports/jdbc-report.md diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index 5338bfdc8a..2e9f65c002 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -145,6 +145,7 @@ private static ArrowFlightSqlClientHandler createNewClientHandler( .withCatalog(config.getCatalog()) .withClientCache(config.useClientCache() ? new FlightClientCache() : null) .withConnectTimeout(config.getConnectTimeout()) + .withPollInfo(config.usePollInfo()) .withDriverVersion(driverVersion) .withOAuthConfiguration(config.getOauthConfiguration()) .build(); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 2ab807e78f..bbe787930d 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -21,6 +21,7 @@ import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; +import java.sql.SQLTimeoutException; import java.util.Collection; import java.util.Iterator; import java.util.Optional; @@ -32,6 +33,7 @@ import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightStatusCode; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.util.AutoCloseables; import org.apache.arrow.vector.VectorSchemaRoot; @@ -73,7 +75,20 @@ public final class ArrowFlightJdbcFlightStreamResultSet throws SQLException { super(statement, state, signature, resultSetMetaData, timeZone, firstFrame); this.connection = (ArrowFlightConnection) statement.connection; - this.flightInfo = ((ArrowFlightInfoStatement) statement).executeFlightInfoQuery(); + try { + this.flightInfo = ((ArrowFlightInfoStatement) statement).executeFlightInfoQuery(); + } catch (FlightRuntimeException e) { + if (e.status().code() != FlightStatusCode.TIMED_OUT) { + throw e; + } + final SQLTimeoutException jdbcTimeout = + new SQLTimeoutException( + String.format( + "Query timed out after %d %s", + statement.getQueryTimeout(), TimeUnit.SECONDS)); + jdbcTimeout.initCause(e); + throw jdbcTimeout; + } } /** Private constructor for fromFlightInfo. */ @@ -284,18 +299,44 @@ private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeo throws SQLException { try { if (canTimeout) { - final int statementTimeout = statement != null ? statement.getQueryTimeout() : 0; - return statementTimeout != 0 - ? flightEndpointDataQueue.next(statementTimeout, TimeUnit.SECONDS) - : flightEndpointDataQueue.next(); - } else { - return flightEndpointDataQueue.next(); + final long remainingTimeoutNanos = remainingQueryTimeoutNanos(); + if (remainingTimeoutNanos != Long.MAX_VALUE) { + if (remainingTimeoutNanos <= 0) { + throw new SQLTimeoutException("Query timed out before retrieving its first endpoint"); + } + try { + return flightEndpointDataQueue.next(remainingTimeoutNanos, TimeUnit.NANOSECONDS); + } catch (SQLTimeoutException e) { + if (statement != null && e.getMessage().startsWith("Query timed out after")) { + final SQLTimeoutException jdbcTimeout = + new SQLTimeoutException( + String.format( + "Query timed out after %d %s", + statement.getQueryTimeout(), TimeUnit.SECONDS)); + jdbcTimeout.initCause(e); + throw jdbcTimeout; + } + throw e; + } + } } + return flightEndpointDataQueue.next(); } catch (final IllegalStateException e) { throw normalizeClosedQueueException(flightEndpointDataQueue, e); } } + private long remainingQueryTimeoutNanos() throws SQLException { + if (statement instanceof ArrowFlightStatement) { + return ((ArrowFlightStatement) statement).remainingQueryTimeoutNanos(); + } + if (statement instanceof ArrowFlightPreparedStatement) { + return ((ArrowFlightPreparedStatement) statement).remainingQueryTimeoutNanos(); + } + final int statementTimeout = statement != null ? statement.getQueryTimeout() : 0; + return statementTimeout > 0 ? TimeUnit.SECONDS.toNanos(statementTimeout) : Long.MAX_VALUE; + } + static void enqueueEndpointData( final FlightEndpointDataQueue queue, final Collection endpointRequests) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java index 30878ad8b9..8ba611b82f 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java @@ -19,7 +19,9 @@ import java.sql.SQLException; import java.util.Collections; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; import org.apache.arrow.driver.jdbc.utils.AvaticaParameterBinder; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightRuntimeException; @@ -41,6 +43,8 @@ public class ArrowFlightPreparedStatement extends AvaticaPreparedStatement implements ArrowFlightInfoStatement { private ArrowFlightSqlClientHandler.PreparedStatement preparedStatement; + private final AtomicReference activeOperation = new AtomicReference<>(); + private volatile PollInfoOperation lastOperation; private ArrowFlightPreparedStatement( final ArrowFlightConnection connection, @@ -180,7 +184,38 @@ ExecuteBatchResult executeBatchWithTypedValues( @Override public FlightInfo executeFlightInfoQuery() throws SQLException { ensurePrepared(); - return preparedStatement.executeQuery(); + final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout()); + activeOperation.set(operation); + lastOperation = operation; + try { + return preparedStatement.executeQuery(operation); + } finally { + activeOperation.compareAndSet(operation, null); + operation.close(); + } + } + + @Override + public void cancel() throws SQLException { + final PollInfoOperation operation = activeOperation.get(); + if (operation != null) { + operation.cancel(); + } + super.cancel(); + } + + long remainingQueryTimeoutNanos() { + final PollInfoOperation operation = lastOperation; + return operation != null && operation.hasDeadline() + ? operation.remainingTimeoutNanos() + : Long.MAX_VALUE; + } + + void cancelActivePollInfoOperation() { + final PollInfoOperation operation = activeOperation.get(); + if (operation != null) { + operation.cancel(); + } } private void ensurePrepared() { diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java index eb170c18c6..ce663ad480 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java @@ -18,6 +18,8 @@ import java.sql.ResultSet; import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; import org.apache.arrow.driver.jdbc.utils.ConvertUtils; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightRuntimeException; @@ -34,6 +36,8 @@ /** A SQL statement for querying data from an Arrow Flight server. */ public class ArrowFlightStatement extends AvaticaStatement implements ArrowFlightInfoStatement { + private final AtomicReference activeOperation = new AtomicReference<>(); + private volatile PollInfoOperation lastOperation; ArrowFlightStatement( final ArrowFlightConnection connection, @@ -127,12 +131,53 @@ public FlightInfo executeFlightInfoQuery() throws SQLException { return flightInfo; } - // Direct Statement.executeQuery(String) / executeUpdate(String) path. - final FlightInfo flightInfo = connection.getClientHandler().getInfo(signature.sql); + // Direct Statement.executeQuery(String) path: CommandStatementQuery through PollFlightInfo. + final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout()); + activeOperation.set(operation); + lastOperation = operation; + final FlightInfo flightInfo; + try { + flightInfo = connection.getClientHandler().getInfo(signature.sql, operation); + } finally { + activeOperation.compareAndSet(operation, null); + operation.close(); + } updateSignatureColumnsFromFlightInfo(signature, flightInfo); return flightInfo; } + @Override + public void cancel() throws SQLException { + final PollInfoOperation operation = activeOperation.get(); + if (operation != null) { + operation.cancel(); + } + final ArrowFlightPreparedStatement delegate = preparedDelegate(); + if (delegate != null) { + // Statement.execute(String) runs through a prepared statement sharing this handle. + delegate.cancelActivePollInfoOperation(); + } + super.cancel(); + } + + long remainingQueryTimeoutNanos() { + final ArrowFlightPreparedStatement delegate = preparedDelegate(); + if (delegate != null) { + return delegate.remainingQueryTimeoutNanos(); + } + final PollInfoOperation operation = lastOperation; + return operation != null && operation.hasDeadline() + ? operation.remainingTimeoutNanos() + : Long.MAX_VALUE; + } + + private ArrowFlightPreparedStatement preparedDelegate() { + final AvaticaStatement current = ((ArrowFlightConnection) connection).statementMap.get(handle.id); + return current instanceof ArrowFlightPreparedStatement + ? (ArrowFlightPreparedStatement) current + : null; + } + private void updateSignatureColumnsFromFlightInfo( final Meta.Signature signature, final FlightInfo flightInfo) { final Schema resultSetSchema = flightInfo.getSchemaOptional().orElse(null); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 9c168126a4..e9f806d0ba 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -17,6 +17,8 @@ package org.apache.arrow.driver.jdbc.client; import com.google.common.collect.ImmutableMap; +import com.google.protobuf.Any; +import com.google.protobuf.InvalidProtocolBufferException; import io.grpc.ManagedChannel; import io.grpc.netty.NettyChannelBuilder; import io.netty.channel.ChannelOption; @@ -33,6 +35,9 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import org.apache.arrow.driver.jdbc.client.oauth.OAuthConfiguration; import org.apache.arrow.driver.jdbc.client.oauth.OAuthCredentialWriter; import org.apache.arrow.driver.jdbc.client.oauth.OAuthTokenProvider; @@ -41,6 +46,7 @@ import org.apache.arrow.driver.jdbc.client.utils.FlightLocationQueue; import org.apache.arrow.flight.CallOption; import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.CancelFlightInfoRequest; import org.apache.arrow.flight.CloseSessionRequest; import org.apache.arrow.flight.FlightClient; import org.apache.arrow.flight.FlightClientMiddleware; @@ -51,6 +57,7 @@ import org.apache.arrow.flight.FlightStatusCode; import org.apache.arrow.flight.Location; import org.apache.arrow.flight.LocationSchemes; +import org.apache.arrow.flight.PollInfo; import org.apache.arrow.flight.SessionOptionValueFactory; import org.apache.arrow.flight.SetSessionOptionsRequest; import org.apache.arrow.flight.SetSessionOptionsResult; @@ -121,7 +128,12 @@ static ArrowFlightSqlClientHandler createNewHandler( final @Nullable FlightClientCache flightClientCache) { final ArrowFlightSqlClientHandler handler = new ArrowFlightSqlClientHandler( - cacheKey, new FlightSqlClient(client), builder, options, catalog, flightClientCache); + cacheKey, + new PollingFlightSqlClient(client, builder.usePollInfo), + builder, + options, + catalog, + flightClientCache); handler.setSetCatalogInSessionIfPresent(); return handler; } @@ -280,6 +292,23 @@ public FlightInfo getInfo(final String query) { return sqlClient.execute(query, getOptions()); } + /** + * Executes {@code query} as a direct {@code CommandStatementQuery} within a statement-owned + * timeout/cancellation operation. + * + * @param query The query. + * @param operation The statement-owned PollInfo operation. + * @return the (possibly partial, when progressive) {@link FlightInfo}. + */ + public FlightInfo getInfo(final String query, final PollInfoOperation operation) { + if (sqlClient instanceof PollingFlightSqlClient) { + final CallOption[] operationOptions = operation.options(getOptions()); + return ((PollingFlightSqlClient) sqlClient) + .withOperation(operation, () -> sqlClient.execute(query, operationOptions)); + } + return sqlClient.execute(query, getOptions()); + } + /** * Executes an update query directly, without creating a prepared statement first. * @@ -388,6 +417,9 @@ public interface PreparedStatement extends AutoCloseable { */ FlightInfo executeQuery() throws SQLException; + /** Execute using a statement-owned timeout/cancellation operation. */ + FlightInfo executeQuery(PollInfoOperation operation) throws SQLException; + /** * Executes a {@link StatementType#UPDATE} query. * @@ -485,6 +517,16 @@ public FlightInfo executeQuery() throws SQLException { return preparedStatement.execute(getOptions()); } + @Override + public FlightInfo executeQuery(final PollInfoOperation operation) throws SQLException { + if (sqlClient instanceof PollingFlightSqlClient) { + final CallOption[] operationOptions = operation.options(getOptions()); + return ((PollingFlightSqlClient) sqlClient) + .withOperation(operation, () -> preparedStatement.execute(operationOptions)); + } + return preparedStatement.execute(getOptions()); + } + @Override public long executeUpdate() { return preparedStatement.executeUpdate(getOptions()); @@ -681,6 +723,127 @@ public FlightInfo getCrossReference( getOptions()); } + /** Flight SQL client that resolves descriptors through synchronous PollFlightInfo. */ + private static final class PollingFlightSqlClient extends FlightSqlClient { + private static final String UNKNOWN_COMMAND_FAMILY = "unknown-command"; + + private final FlightClient client; + private final boolean pollInfoEnabled; + private final Set unsupportedFamilies = ConcurrentHashMap.newKeySet(); + private final ThreadLocal currentOperation = new ThreadLocal<>(); + + private PollingFlightSqlClient(final FlightClient client, final boolean pollInfoEnabled) { + super(client); + this.client = client; + this.pollInfoEnabled = pollInfoEnabled; + } + + private FlightInfo withOperation( + final PollInfoOperation operation, final Supplier action) { + final PollInfoOperation previous = currentOperation.get(); + currentOperation.set(operation); + try { + // Enter the statement-owned cancellable context before prepared parameter upload as well + // as descriptor polling. This lets timeout/cancel terminate a blocked DoPut. + return operation.call(action::get); + } finally { + if (previous == null) { + currentOperation.remove(); + } else { + currentOperation.set(previous); + } + } + } + + @Override + protected FlightInfo getInfo( + final org.apache.arrow.flight.FlightDescriptor originalDescriptor, + final CallOption... options) { + PollInfoOperation operation = currentOperation.get(); + final boolean ownsOperation = operation == null; + if (ownsOperation) { + operation = new PollInfoOperation(0); + } + try { + return getInfo(operation, originalDescriptor, options); + } finally { + if (ownsOperation) { + operation.close(); + } + } + } + + private FlightInfo getInfo( + final PollInfoOperation operation, + final org.apache.arrow.flight.FlightDescriptor originalDescriptor, + final CallOption[] options) { + final String family = commandFamily(originalDescriptor); + if (!pollInfoEnabled || unsupportedFamilies.contains(family)) { + return operation.call(() -> client.getInfo(originalDescriptor, operation.options(options))); + } + + org.apache.arrow.flight.FlightDescriptor descriptor = originalDescriptor; + boolean initialPoll = true; + try { + while (true) { + final org.apache.arrow.flight.FlightDescriptor descriptorForPoll = descriptor; + final PollInfo pollInfo = + operation.call(() -> client.pollInfo(descriptorForPoll, operation.options(options))); + operation.remember(pollInfo.getFlightInfo()); + if (!pollInfo.getFlightDescriptor().isPresent()) { + return pollInfo.getFlightInfo(); + } + descriptor = pollInfo.getFlightDescriptor().get(); + initialPoll = false; + } + } catch (FlightRuntimeException e) { + if (initialPoll && e.status().code() == FlightStatusCode.UNIMPLEMENTED) { + unsupportedFamilies.add(family); + return operation.call( + () -> client.getInfo(originalDescriptor, operation.options(options))); + } + if (operation.isCancelled() + || e.status().code() == FlightStatusCode.CANCELLED + || e.status().code() == FlightStatusCode.TIMED_OUT) { + cancelFlightInfoBestEffort(operation, options); + } + throw e; + } + } + + private void cancelFlightInfoBestEffort( + final PollInfoOperation operation, final CallOption[] options) { + if (!operation.beginCancelFlightInfoAttempt()) { + return; + } + final CallOption[] cancelOptions = Arrays.copyOf(options, options.length + 1); + cancelOptions[options.length] = + org.apache.arrow.flight.CallOptions.timeout(1, TimeUnit.SECONDS); + try { + // The primary statement context is already cancelled/timed out. Use a fresh root context + // for this bounded best-effort cleanup action so it can reach the server. + io.grpc.Context.ROOT.run( + () -> + client.cancelFlightInfo( + new CancelFlightInfoRequest(operation.latestFlightInfo()), cancelOptions)); + } catch (RuntimeException e) { + LOGGER.debug("Best-effort CancelFlightInfo failed", e); + } + } + + private static String commandFamily(final org.apache.arrow.flight.FlightDescriptor descriptor) { + if (!descriptor.isCommand()) { + return "path"; + } + try { + final String typeUrl = Any.parseFrom(descriptor.getCommand()).getTypeUrl(); + return typeUrl.isEmpty() ? UNKNOWN_COMMAND_FAMILY : typeUrl; + } catch (InvalidProtocolBufferException e) { + return UNKNOWN_COMMAND_FAMILY; + } + } + } + /** Builder for {@link ArrowFlightSqlClientHandler}. */ public static final class Builder { static final String USER_AGENT_TEMPLATE = "JDBC Flight SQL Driver %s"; @@ -727,6 +890,8 @@ public static final class Builder { @VisibleForTesting @Nullable Duration connectTimeout; + @VisibleForTesting boolean usePollInfo = true; + @VisibleForTesting @Nullable OAuthConfiguration oauthConfig; // These two middleware are for internal use within build() and should not be @@ -770,6 +935,7 @@ public Builder() {} this.allocator = original.allocator; this.catalog = original.catalog; this.oauthConfig = original.oauthConfig; + this.usePollInfo = original.usePollInfo; if (original.retainCookies) { this.cookieFactory = original.cookieFactory; @@ -1085,6 +1251,12 @@ public Builder withConnectTimeout(Duration connectTimeout) { return this; } + /** Select PollFlightInfo (default) or legacy GetFlightInfo descriptor resolution. */ + public Builder withPollInfo(final boolean usePollInfo) { + this.usePollInfo = usePollInfo; + return this; + } + /** * Sets the driver version for this handler. * diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java new file mode 100644 index 0000000000..979bea1092 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -0,0 +1,129 @@ +/* + * 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.arrow.driver.jdbc.client; + +import io.grpc.Context; +import java.util.Arrays; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.arrow.flight.CallOption; +import org.apache.arrow.flight.CallOptions; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightInfo; + +/** + * State shared by every PollFlightInfo call in one synchronous JDBC query execution. + * + *

The absolute deadline is deliberately created once. Each RPC receives only the remaining + * budget, while the cancellable gRPC context lets {@code Statement.cancel()} terminate a poll that + * is active before a ResultSet exists. + */ +public final class PollInfoOperation implements AutoCloseable { + private static final long NO_DEADLINE = Long.MAX_VALUE; + + private final long deadlineNanos; + private final Context.CancellableContext context; + private final AtomicBoolean cancelled = new AtomicBoolean(); + private final AtomicBoolean cancelFlightInfoAttempted = new AtomicBoolean(); + private volatile FlightInfo latestFlightInfo; + + /** Create an operation whose timeout is expressed in JDBC query-timeout seconds. */ + public PollInfoOperation(final int timeoutSeconds) { + deadlineNanos = + timeoutSeconds > 0 + ? saturatingAdd(System.nanoTime(), TimeUnit.SECONDS.toNanos(timeoutSeconds)) + : NO_DEADLINE; + context = Context.current().withCancellation(); + } + + /** Run one RPC in the operation's cancellable context. */ + T call(final Callable callable) { + if (cancelled.get()) { + throw CallStatus.CANCELLED.withDescription("Statement canceled").toRuntimeException(); + } + try { + return context.call(callable); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** Return the base options plus this operation's remaining deadline. */ + CallOption[] options(final CallOption[] baseOptions) { + if (deadlineNanos == NO_DEADLINE) { + return baseOptions; + } + final long remaining = remainingTimeoutNanos(); + if (remaining <= 0) { + throw CallStatus.TIMED_OUT.withDescription("JDBC query timeout expired").toRuntimeException(); + } + final CallOption[] options = Arrays.copyOf(baseOptions, baseOptions.length + 1); + options[baseOptions.length] = CallOptions.timeout(remaining, TimeUnit.NANOSECONDS); + return options; + } + + /** Cancel the active PollFlightInfo call, if any. */ + public void cancel() { + cancelled.set(true); + context.cancel(null); + } + + boolean isCancelled() { + return cancelled.get(); + } + + void remember(final FlightInfo flightInfo) { + latestFlightInfo = flightInfo; + } + + FlightInfo latestFlightInfo() { + return latestFlightInfo; + } + + boolean beginCancelFlightInfoAttempt() { + return latestFlightInfo != null && cancelFlightInfoAttempted.compareAndSet(false, true); + } + + /** Return the remaining operation-wide timeout, in nanoseconds. */ + public long remainingTimeoutNanos() { + if (deadlineNanos == NO_DEADLINE) { + return NO_DEADLINE; + } + return deadlineNanos - System.nanoTime(); + } + + /** Whether this operation has a finite deadline. */ + public boolean hasDeadline() { + return deadlineNanos != NO_DEADLINE; + } + + @Override + public void close() { + context.close(); + } + + private static long saturatingAdd(final long left, final long right) { + final long result = left + right; + if (((left ^ result) & (right ^ result)) < 0) { + return Long.MAX_VALUE; + } + return result; + } +} diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java index 8460474ba8..912e5bf9d2 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java @@ -206,6 +206,11 @@ public boolean useClientCache() { return ArrowFlightConnectionProperty.USE_CLIENT_CACHE.getBoolean(properties); } + /** Whether normal FlightInfo-producing operations use PollFlightInfo. */ + public boolean usePollInfo() { + return ArrowFlightConnectionProperty.USE_POLL_INFO.getBoolean(properties); + } + /** * Gets the {@link CallOption}s from this {@link ConnectionConfig}. * @@ -292,6 +297,7 @@ public enum ArrowFlightConnectionProperty implements ConnectionProperty { CATALOG("catalog", null, Type.STRING, false), CONNECT_TIMEOUT_MILLIS("connectTimeoutMs", 10000, Type.NUMBER, false), USE_CLIENT_CACHE("useClientCache", true, Type.BOOLEAN, false), + USE_POLL_INFO("usePollInfo", true, Type.BOOLEAN, false), // OAuth configuration properties OAUTH_FLOW("oauth.flow", null, Type.STRING, false), diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/OAuthIntegrationTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/OAuthIntegrationTest.java index 5e782db031..e0d5d963f7 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/OAuthIntegrationTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/OAuthIntegrationTest.java @@ -467,7 +467,7 @@ public void testOAuthTokenSentAsBearer() throws Exception { String authHeader = FLIGHT_SERVER_TEST_EXTENSION .getInterceptorFactory() - .getHeader(org.apache.arrow.flight.FlightMethod.GET_FLIGHT_INFO, "authorization"); + .getHeader(org.apache.arrow.flight.FlightMethod.POLL_FLIGHT_INFO, "authorization"); assertNotNull(authHeader, "Authorization header should be present in Flight requests"); assertEquals("Bearer " + VALID_ACCESS_TOKEN, authHeader); } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java new file mode 100644 index 0000000000..c3617ba086 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -0,0 +1,418 @@ +/* + * 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.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.protobuf.Any; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLTimeoutException; +import java.sql.Statement; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer; +import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer.Scenario; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.FlightStatusCode; +import org.apache.arrow.flight.Location; +import org.apache.arrow.flight.sql.FlightSqlProducer; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandGetCatalogs; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandPreparedStatementQuery; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandStatementQuery; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.IntVector; +import org.apache.arrow.vector.VarCharVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.Schema; +import org.apache.arrow.vector.util.Text; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Executable POC coverage for synchronous PollInfo through the unchanged JDBC surface. */ +public class PollInfoExecutionTest { + private static final String DIRECT_QUERY = "SELECT 42 AS answer"; + private static final String PREPARED_QUERY = "SELECT ? AS answer"; + private static final Schema RESULT_SCHEMA = + new Schema(Collections.singletonList(Field.nullable("answer", new ArrowType.Int(32, true)))); + private static final String STATEMENT_FAMILY = + Any.pack(CommandStatementQuery.getDefaultInstance()).getTypeUrl(); + private static final String PREPARED_FAMILY = + Any.pack(CommandPreparedStatementQuery.getDefaultInstance()).getTypeUrl(); + private static final String CATALOGS_FAMILY = + Any.pack(CommandGetCatalogs.getDefaultInstance()).getTypeUrl(); + + private static BufferAllocator allocator; + private static PollingMockFlightSqlProducer producer; + private static FlightServer server; + + @BeforeAll + public static void startServer() throws Exception { + allocator = new RootAllocator(Long.MAX_VALUE); + producer = new PollingMockFlightSqlProducer(); + producer.addSelectQuery( + DIRECT_QUERY, RESULT_SCHEMA, Collections.singletonList(PollInfoExecutionTest::send42)); + producer.addSelectQuery( + PREPARED_QUERY, RESULT_SCHEMA, Collections.singletonList(PollInfoExecutionTest::send7)); + producer.addExpectedParameters( + PREPARED_QUERY, + new Schema( + Collections.singletonList(Field.nullable("parameter", new ArrowType.Int(32, true)))), + Collections.singletonList(Collections.singletonList(7))); + producer.addCatalogQuery( + CommandGetCatalogs.getDefaultInstance(), PollInfoExecutionTest::sendCatalog); + server = + FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer) + .build() + .start(); + } + + @AfterAll + public static void stopServer() throws Exception { + server.close(); + producer.close(); + allocator.close(); + } + + @Test + public void immediateCompletionUsesOnePollAndNoGetFlightInfo() throws Exception { + producer.configure(Scenario.IMMEDIATE, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + assertFalse(resultSet.next()); + } + assertEquals(1, producer.pollDescriptors().size()); + assertEquals(STATEMENT_FAMILY, family(producer.pollDescriptors().get(0))); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void multiStepUsesEachDescriptorOnceAndOnlyFinalInfoFeedsResultSet() throws Exception { + producer.configure(Scenario.MULTI_STEP, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + } + final List descriptors = producer.pollDescriptors(); + assertEquals(3, descriptors.size()); + assertEquals(STATEMENT_FAMILY, family(descriptors.get(0))); + assertEquals( + "jdbc-continuation-1", new String(descriptors.get(1).getCommand(), StandardCharsets.UTF_8)); + assertEquals( + "jdbc-continuation-2", new String(descriptors.get(2).getCommand(), StandardCharsets.UTF_8)); + assertEquals(3, descriptors.stream().distinct().count()); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void preparedParametersAreBoundOnceBeforePolling() throws Exception { + producer.configure(Scenario.MULTI_STEP, PREPARED_FAMILY); + try (Connection connection = connect(true); + PreparedStatement statement = connection.prepareStatement(PREPARED_QUERY)) { + statement.setInt(1, 7); + try (ResultSet resultSet = statement.executeQuery()) { + assertTrue(resultSet.next()); + assertEquals(7, resultSet.getInt(1)); + } + } + assertEquals(1, producer.parameterBindCount()); + assertEquals(3, producer.pollDescriptors().size()); + assertEquals(PREPARED_FAMILY, family(producer.pollDescriptors().get(0))); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void metadataUsesPollInfoTransparently() throws Exception { + producer.configure(Scenario.MULTI_STEP, CATALOGS_FAMILY); + try (Connection connection = connect(true); + ResultSet resultSet = connection.getMetaData().getCatalogs()) { + assertTrue(resultSet.next()); + assertEquals("poll_catalog", resultSet.getString("TABLE_CAT")); + } + assertEquals(3, producer.pollDescriptors().size()); + assertEquals(CATALOGS_FAMILY, family(producer.pollDescriptors().get(0))); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void unimplementedFallbackIsCachedByFamilyOnly() throws Exception { + producer.configure(Scenario.UNIMPLEMENTED, STATEMENT_FAMILY); + try (Connection connection = connect(true)) { + assertDirectRow(connection); + assertDirectRow(connection); + try (ResultSet resultSet = connection.getMetaData().getCatalogs()) { + assertTrue(resultSet.next()); + } + } + assertEquals(2, producer.pollDescriptors().size()); + assertEquals(STATEMENT_FAMILY, family(producer.pollDescriptors().get(0))); + assertEquals(CATALOGS_FAMILY, family(producer.pollDescriptors().get(1))); + assertEquals(2, producer.getFlightInfoCount()); + } + + @Test + public void connectionOptOutUsesOnlyGetFlightInfo() throws Exception { + producer.configure(Scenario.IMMEDIATE, STATEMENT_FAMILY); + try (Connection connection = connect(false)) { + assertDirectRow(connection); + } + assertEquals(0, producer.pollDescriptors().size()); + assertEquals(1, producer.getFlightInfoCount()); + assertEquals(STATEMENT_FAMILY, producer.lastGetFlightInfoFamily()); + } + + @Test + public void unavailableDoesNotFallbackOrReexecute() throws Exception { + producer.configure(Scenario.UNAVAILABLE, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final Throwable failure = + assertThrows(Throwable.class, () -> statement.executeQuery(DIRECT_QUERY)); + assertTrue(hasFlightStatus(failure, FlightStatusCode.UNAVAILABLE), failure.toString()); + } + assertEquals(1, producer.pollDescriptors().size()); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void continuationUnimplementedDoesNotFallbackOrReexecute() throws Exception { + producer.configure(Scenario.CONTINUATION_UNIMPLEMENTED, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final Throwable failure = + assertThrows(Throwable.class, () -> statement.executeQuery(DIRECT_QUERY)); + assertTrue(hasFlightStatus(failure, FlightStatusCode.UNIMPLEMENTED), failure.toString()); + } + assertEquals(2, producer.pollDescriptors().size()); + assertEquals(0, producer.getFlightInfoCount()); + } + + @Test + public void oneDeadlineSpansAllPollsAndTerminatesActivePoll() throws Exception { + producer.configure(Scenario.TIMEOUT, STATEMENT_FAMILY); + final long startNanos = System.nanoTime(); + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + final Throwable failure = + assertThrows(Throwable.class, () -> statement.executeQuery(DIRECT_QUERY)); + assertTrue(hasFlightStatus(failure, FlightStatusCode.TIMED_OUT), failure.toString()); + assertJdbcTimeoutContract(failure, 1); + } + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + System.out.println("LOCAL_T8_ELAPSED_MILLIS " + elapsedMillis); + assertTrue(elapsedMillis >= 850, "deadline fired too early: " + elapsedMillis); + assertTrue(elapsedMillis < 1500, "deadline appears to have reset: " + elapsedMillis); + assertEquals(2, producer.pollDescriptors().size()); + assertEquals(0, producer.getFlightInfoCount()); + assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); + } + + @Test + public void preparedBindSharesTheOperationDeadline() throws Exception { + producer.configure(Scenario.BIND_TIMEOUT, PREPARED_FAMILY); + final long startNanos = System.nanoTime(); + try (Connection connection = connect(true); + PreparedStatement statement = connection.prepareStatement(PREPARED_QUERY)) { + statement.setInt(1, 7); + statement.setQueryTimeout(1); + final Throwable failure = assertThrows(Throwable.class, statement::executeQuery); + assertTrue(hasFlightStatus(failure, FlightStatusCode.TIMED_OUT), failure.toString()); + assertJdbcTimeoutContract(failure, 1); + } + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue(elapsedMillis >= 850, "bind deadline fired too early: " + elapsedMillis); + assertTrue(elapsedMillis < 1500, "bind deadline was not operation-wide: " + elapsedMillis); + assertEquals(1, producer.parameterBindCount()); + assertEquals(0, producer.pollDescriptors().size()); + assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); + } + + @Test + public void preparedBindIsCancelledBeforePolling() throws Exception { + producer.configure(Scenario.BIND_CANCEL, PREPARED_FAMILY); + try (Connection connection = connect(true); + PreparedStatement statement = connection.prepareStatement(PREPARED_QUERY)) { + statement.setInt(1, 7); + final AtomicReference failure = new AtomicReference<>(); + final Thread execution = + new Thread( + () -> { + try (ResultSet ignored = statement.executeQuery()) { + // A blocked bind must not produce a ResultSet. + } catch (Throwable e) { + failure.set(e); + } + }, + "jdbc-prepared-bind-cancellation-test"); + execution.start(); + assertTrue(producer.awaitActivePoll(2, TimeUnit.SECONDS)); + assertNull(statement.getResultSet()); + statement.cancel(); + execution.join(TimeUnit.SECONDS.toMillis(2)); + assertFalse(execution.isAlive()); + assertNotNull(failure.get()); + assertTrue( + hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); + assertEquals(1, producer.parameterBindCount()); + assertEquals(0, producer.pollDescriptors().size()); + assertEquals(0, producer.cancelFlightInfoCount()); + assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); + } + } + + @Test + public void avaticaHasNoResultSetTargetButStatementContextCancelsActivePoll() throws Exception { + producer.configure(Scenario.CANCEL_OBSERVABLE, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final AtomicReference failure = new AtomicReference<>(); + final AtomicBoolean resultSetCreated = new AtomicBoolean(); + final Thread execution = + new Thread( + () -> { + try (ResultSet ignored = statement.executeQuery(DIRECT_QUERY)) { + resultSetCreated.set(true); + } catch (Throwable e) { + failure.set(e); + } + }, + "jdbc-pollinfo-cancellation-test"); + execution.start(); + assertTrue(producer.awaitActivePoll(2, TimeUnit.SECONDS)); + // AvaticaStatement.cancel() can only reach openResultSet, which is still null at this point. + assertNull(statement.getResultSet()); + final long cancelStart = System.nanoTime(); + statement.cancel(); + execution.join(TimeUnit.SECONDS.toMillis(2)); + final long cancelMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelStart); + System.out.println("LOCAL_T9_CANCEL_MILLIS " + cancelMillis); + assertFalse(execution.isAlive()); + assertFalse(resultSetCreated.get(), "ResultSet must not exist while polling is active"); + assertNotNull(failure.get()); + assertTrue( + hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); + assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); + assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); + assertEquals(1, producer.cancelFlightInfoCount()); + assertEquals(0, producer.getFlightInfoCount()); + } + } + + private static Connection connect(final boolean usePollInfo) throws Exception { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=%s", + server.getPort(), usePollInfo)); + } + + private static void assertDirectRow(final Connection connection) throws Exception { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + } + } + + private static String family(final FlightDescriptor descriptor) { + return PollingMockFlightSqlProducer.commandFamily(descriptor); + } + + private static boolean hasFlightStatus( + final Throwable throwable, final FlightStatusCode expected) { + Throwable current = throwable; + while (current != null) { + if (current instanceof FlightRuntimeException + && ((FlightRuntimeException) current).status().code() == expected) { + return true; + } + current = current.getCause(); + } + return false; + } + + private static void assertJdbcTimeoutContract( + final Throwable throwable, final int timeoutSeconds) { + Throwable current = throwable; + while (current != null && !(current instanceof SQLTimeoutException)) { + current = current.getCause(); + } + assertNotNull(current, "Expected SQLTimeoutException in cause chain: " + throwable); + assertEquals( + String.format("Query timed out after %d %s", timeoutSeconds, TimeUnit.SECONDS), + current.getMessage()); + } + + private static void send42(final FlightSqlProducer.ServerStreamListener listener) { + sendInt(listener, 42); + } + + private static void send7(final FlightSqlProducer.ServerStreamListener listener) { + sendInt(listener, 7); + } + + private static void sendInt( + final FlightSqlProducer.ServerStreamListener listener, final int value) { + try (BufferAllocator streamAllocator = new RootAllocator(); + VectorSchemaRoot root = VectorSchemaRoot.create(RESULT_SCHEMA, streamAllocator)) { + root.allocateNew(); + ((IntVector) root.getVector("answer")).setSafe(0, value); + root.setRowCount(1); + listener.start(root); + listener.putNext(); + } finally { + listener.completed(); + } + } + + private static void sendCatalog(final FlightSqlProducer.ServerStreamListener listener) { + try (BufferAllocator streamAllocator = new RootAllocator(); + VectorSchemaRoot root = + VectorSchemaRoot.create( + FlightSqlProducer.Schemas.GET_CATALOGS_SCHEMA, streamAllocator)) { + root.allocateNew(); + ((VarCharVector) root.getVector("catalog_name")).setSafe(0, new Text("poll_catalog")); + root.setRowCount(1); + listener.start(root); + listener.putNext(); + } finally { + listener.completed(); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java new file mode 100644 index 0000000000..5c322c4cb1 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -0,0 +1,353 @@ +/* + * 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.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLTimeoutException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightStatusCode; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** Black-box BDX-645 contract checks against the standalone shared conformance server. */ +@EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") +@TestMethodOrder(OrderAnnotation.class) +public class SharedServerPollInfoExecutionTest { + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); + private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); + + @BeforeEach + public void resetServer() throws Exception { + post("/reset", ""); + } + + @AfterEach + public void printServerState(final TestInfo testInfo) throws Exception { + System.out.println("SHARED_SERVER_STATE " + testInfo.getDisplayName()); + System.out.println(state()); + } + + @Test + @Order(1) + public void t1Immediate() throws Exception { + try (Connection connection = connect(true)) { + assertEquals(Arrays.asList(1L, 2L), directValues(connection, "immediate")); + } + assertCounters(1, 0, 0, 1, 0, 0, 0, 1); + } + + @Test + @Order(2) + public void t2MultiStepContinuationsAndFinalCumulativeInfo() throws Exception { + try (Connection connection = connect(true)) { + assertEquals(Arrays.asList(1L, 2L, 3L), directValues(connection, "multi-step")); + } + final String state = state(); + assertCounters(state, 3, 0, 0, 1, 2, 0, 0, 3); + assertTrue(state.contains("bdx-645-poll/v1/")); + assertTrue(state.indexOf("/1\"") < state.indexOf("/2\""), state); + } + + @Test + @Order(3) + public void t3PreparedParametersBoundExactlyOnce() throws Exception { + try (Connection connection = connect(true); + PreparedStatement statement = connection.prepareStatement("prepared-multi-step")) { + statement.setLong(1, 41); + try (ResultSet resultSet = statement.executeQuery()) { + assertEquals(Arrays.asList(41L, 42L), values(resultSet)); + } + } + assertCounters(3, 0, 1, 1, 2, 0, 0, 1); + } + + @Test + @Order(4) + public void t4MetadataMultiStep() throws Exception { + try (Connection connection = connect(true); + ResultSet resultSet = connection.getMetaData().getCatalogs()) { + assertTrue(resultSet.next()); + assertEquals("bdx_catalog", resultSet.getString("TABLE_CAT")); + assertFalse(resultSet.next()); + } + assertCounters(3, 0, 0, 1, 2, 0, 0, 1); + } + + @Test + @Order(5) + public void t5InitialUnimplementedFallbackCacheIsFamilyIsolated() throws Exception { + try (Connection connection = connect(true)) { + assertEquals(Arrays.asList(1L, 2L), directValues(connection, "unimplemented")); + assertEquals(Arrays.asList(1L, 2L), directValues(connection, "unimplemented")); + try (ResultSet resultSet = connection.getMetaData().getCatalogs()) { + assertTrue(resultSet.next()); + assertEquals("bdx_catalog", resultSet.getString("TABLE_CAT")); + } + } + final String state = state(); + assertCounters(state, 4, 2, 0, 2, 2, 0, 0, 3); + assertTrue(state.contains("\"direct\""), state); + assertTrue(state.contains("\"metadata\""), state); + } + + @Test + @Order(6) + public void t6ConnectionOptOut() throws Exception { + try (Connection connection = connect(false)) { + assertEquals(Arrays.asList(1L, 2L), directValues(connection, "immediate")); + } + final String state = state(); + assertCounters(state, 0, 1, 0, 0, 0, 0, 0, 1); + assertTrue( + state + .replaceAll("\\s+", "") + .contains("\"direct\":{\"poll_flight_info\":0,\"get_flight_info\":1"), + state); + } + + @Test + @Order(7) + public void t7UnavailableDoesNotFallbackOrReexecute() throws Exception { + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final Throwable failure = + assertThrows(Throwable.class, () -> statement.executeQuery("unavailable")); + assertTrue(hasFlightStatus(failure, FlightStatusCode.UNAVAILABLE), failure.toString()); + } + assertCounters(1, 0, 0, 1, 0, 0, 0, 0); + } + + @Test + @Order(8) + public void t8TimeoutEndsBlockedPollAtTheSingleStatementDeadline() throws Exception { + final long startNanos = System.nanoTime(); + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + final Throwable failure = + assertThrows(Throwable.class, () -> statement.executeQuery("blocked-poll")); + assertTrue(hasFlightStatus(failure, FlightStatusCode.TIMED_OUT), failure.toString()); + assertJdbcTimeoutContract(failure, 1); + } + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + System.out.println("SHARED_T8_ELAPSED_MILLIS " + elapsedMillis); + assertTrue(elapsedMillis >= 800, "deadline fired too early: " + elapsedMillis); + assertTrue(elapsedMillis < 1800, "deadline fired too late: " + elapsedMillis); + assertCounters(1, 0, 0, 1, 0, 0, 1, 0); + } + + @Test + @Order(9) + public void t9CancelBeforeResultSetCancelsPollAndFlightInfo() throws Exception { + try (Connection connection = connect(true); + Statement statement = connection.createStatement()) { + final AtomicReference failure = new AtomicReference<>(); + final AtomicBoolean resultSetCreated = new AtomicBoolean(); + final Thread execution = + new Thread( + () -> { + try (ResultSet ignored = statement.executeQuery("cancel-observable")) { + resultSetCreated.set(true); + } catch (Throwable e) { + failure.set(e); + } + }, + "shared-server-jdbc-cancel"); + execution.start(); + awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); + assertNull(statement.getResultSet()); + final long cancelStart = System.nanoTime(); + statement.cancel(); + execution.join(TimeUnit.SECONDS.toMillis(2)); + final long cancelMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelStart); + System.out.println("SHARED_T9_CANCEL_MILLIS " + cancelMillis); + assertFalse(execution.isAlive()); + assertFalse(resultSetCreated.get()); + assertNotNull(failure.get()); + assertTrue( + hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); + assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); + } + awaitCounter("cancellation", 1, Duration.ofSeconds(2)); + assertCounters(2, 0, 0, 1, 1, 1, 1, 0); + } + + private static Connection connect(final boolean usePollInfo) throws Exception { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s", + FLIGHT_PORT, usePollInfo)); + } + + private static List directValues(final Connection connection, final String query) + throws Exception { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(query)) { + final List values = new ArrayList<>(); + while (resultSet.next()) { + assertEquals(query, resultSet.getString("scenario")); + values.add(resultSet.getLong("value")); + } + return values; + } + } + + private static List values(final ResultSet resultSet) throws Exception { + final List values = new ArrayList<>(); + while (resultSet.next()) { + values.add(resultSet.getLong("value")); + } + return values; + } + + private static void assertCounters( + final int poll, + final int get, + final int bind, + final int original, + final int continuation, + final int cancellation, + final int activeTermination, + final int doGet) + throws Exception { + assertCounters( + state(), poll, get, bind, original, continuation, cancellation, activeTermination, doGet); + } + + private static void assertCounters( + final String state, + final int poll, + final int get, + final int bind, + final int original, + final int continuation, + final int cancellation, + final int activeTermination, + final int doGet) { + assertEquals(poll, counter(state, "poll_flight_info"), state); + assertEquals(get, counter(state, "get_flight_info"), state); + assertEquals(bind, counter(state, "parameter_binding"), state); + assertEquals(original, counter(state, "original_descriptors"), state); + assertEquals(continuation, counter(state, "continuation_descriptors"), state); + assertEquals(cancellation, counter(state, "cancellation"), state); + assertEquals(activeTermination, counter(state, "active_call_terminations"), state); + assertEquals(doGet, counter(state, "do_get"), state); + } + + private static void awaitCounter(final String name, final int expected, final Duration timeout) + throws Exception { + final long deadline = System.nanoTime() + timeout.toNanos(); + do { + if (counter(state(), name) >= expected) { + return; + } + Thread.sleep(20); + } while (System.nanoTime() < deadline); + assertEquals(expected, counter(state(), name), state()); + } + + private static int counter(final String state, final String name) { + final Matcher matcher = + Pattern.compile("\\\"" + Pattern.quote(name) + "\\\"\\s*:\\s*(\\d+)").matcher(state); + assertTrue(matcher.find(), state); + return Integer.parseInt(matcher.group(1)); + } + + private static String state() throws Exception { + return request("GET", "/state", ""); + } + + private static void post(final String path, final String body) throws Exception { + request("POST", path, body); + } + + private static String request(final String method, final String path, final String body) + throws Exception { + final HttpRequest.Builder builder = + HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + CONTROL_PORT + path)) + .timeout(Duration.ofSeconds(2)); + if ("POST".equals(method)) { + builder.POST(HttpRequest.BodyPublishers.ofString(body)); + } else { + builder.GET(); + } + final HttpResponse response = + HTTP_CLIENT.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + if ("POST".equals(method)) { + assertEquals(204, response.statusCode(), response.body()); + } else { + assertEquals(200, response.statusCode(), response.body()); + } + return response.body(); + } + + private static boolean hasFlightStatus( + final Throwable throwable, final FlightStatusCode expected) { + Throwable current = throwable; + while (current != null) { + if (current instanceof FlightRuntimeException + && ((FlightRuntimeException) current).status().code() == expected) { + return true; + } + current = current.getCause(); + } + return false; + } + + private static void assertJdbcTimeoutContract( + final Throwable throwable, final int timeoutSeconds) { + Throwable current = throwable; + while (current != null && !(current instanceof SQLTimeoutException)) { + current = current.getCause(); + } + assertNotNull(current, "Expected SQLTimeoutException in cause chain: " + throwable); + assertEquals( + String.format("Query timed out after %d %s", timeoutSeconds, TimeUnit.SECONDS), + current.getMessage()); + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java index c764a1c015..d81aa1d800 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java @@ -94,7 +94,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; /** An ad-hoc {@link FlightSqlProducer} for tests. */ -public final class MockFlightSqlProducer implements FlightSqlProducer { +public class MockFlightSqlProducer implements FlightSqlProducer { private final Map>> queryResults = new HashMap<>(); private final Map> selectResultProviders = new HashMap<>(); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java new file mode 100644 index 0000000000..e31cccbdf0 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java @@ -0,0 +1,256 @@ +/* + * 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.arrow.driver.jdbc.utils; + +import com.google.protobuf.Any; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.CancelFlightInfoRequest; +import org.apache.arrow.flight.CancelStatus; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightEndpoint; +import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.FlightStream; +import org.apache.arrow.flight.PollInfo; +import org.apache.arrow.flight.PutResult; +import org.apache.arrow.flight.Ticket; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandPreparedStatementQuery; + +/** Controllable in-process PollInfo producer used by the JDBC POC conformance tests. */ +public final class PollingMockFlightSqlProducer extends MockFlightSqlProducer { + public enum Scenario { + IMMEDIATE, + MULTI_STEP, + UNIMPLEMENTED, + CONTINUATION_UNIMPLEMENTED, + UNAVAILABLE, + TIMEOUT, + BIND_TIMEOUT, + BIND_CANCEL, + CANCEL_OBSERVABLE + } + + private static final String PREPARED_FAMILY = + Any.pack(CommandPreparedStatementQuery.getDefaultInstance()).getTypeUrl(); + + private static final FlightDescriptor CONTINUATION_1 = + FlightDescriptor.command("jdbc-continuation-1".getBytes(StandardCharsets.UTF_8)); + private static final FlightDescriptor CONTINUATION_2 = + FlightDescriptor.command("jdbc-continuation-2".getBytes(StandardCharsets.UTF_8)); + + private final List pollDescriptors = + Collections.synchronizedList(new ArrayList<>()); + private final AtomicInteger getFlightInfoCount = new AtomicInteger(); + private final AtomicInteger parameterBindCount = new AtomicInteger(); + private final AtomicInteger cancelFlightInfoCount = new AtomicInteger(); + private volatile String lastGetFlightInfoFamily; + private volatile Scenario scenario = Scenario.IMMEDIATE; + private volatile String scenarioFamily; + private volatile boolean scenarioSelectedForExecution; + private volatile FlightInfo finalFlightInfo; + private volatile CountDownLatch activePoll = new CountDownLatch(1); + private volatile CountDownLatch pollTerminated = new CountDownLatch(1); + + public void configure(final Scenario scenario, final String scenarioFamily) { + this.scenario = scenario; + this.scenarioFamily = scenarioFamily; + pollDescriptors.clear(); + getFlightInfoCount.set(0); + parameterBindCount.set(0); + cancelFlightInfoCount.set(0); + lastGetFlightInfoFamily = null; + scenarioSelectedForExecution = false; + finalFlightInfo = null; + activePoll = new CountDownLatch(1); + pollTerminated = new CountDownLatch(1); + } + + @Override + public FlightInfo getFlightInfo(final CallContext context, final FlightDescriptor descriptor) { + getFlightInfoCount.incrementAndGet(); + lastGetFlightInfoFamily = commandFamily(descriptor); + return super.getFlightInfo(context, descriptor); + } + + @Override + public PollInfo pollFlightInfo(final CallContext context, final FlightDescriptor descriptor) { + pollDescriptors.add(descriptor); + final boolean initial = isFlightSqlCommand(descriptor); + if (initial) { + finalFlightInfo = super.getFlightInfo(context, descriptor); + scenarioSelectedForExecution = + scenarioFamily == null || scenarioFamily.equals(commandFamily(descriptor)); + } + + final boolean selectedFamily = scenarioSelectedForExecution; + if (initial && selectedFamily && scenario == Scenario.UNIMPLEMENTED) { + throw CallStatus.UNIMPLEMENTED.toRuntimeException(); + } + if (initial && selectedFamily && scenario == Scenario.UNAVAILABLE) { + throw CallStatus.UNAVAILABLE.toRuntimeException(); + } + if (selectedFamily && scenario == Scenario.CONTINUATION_UNIMPLEMENTED) { + if (initial) { + return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_1, 0.25, null); + } + throw CallStatus.UNIMPLEMENTED.toRuntimeException(); + } + if (selectedFamily && scenario == Scenario.TIMEOUT) { + if (initial) { + sleep(700); + return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_1, 0.25, null); + } + return blockUntilCancelled(context); + } + if (selectedFamily && scenario == Scenario.CANCEL_OBSERVABLE) { + if (initial) { + return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_1, 0.25, null); + } + return blockUntilCancelled(context); + } + if (selectedFamily && scenario == Scenario.MULTI_STEP) { + if (initial) { + return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_1, 0.25, null); + } + if (descriptor.equals(CONTINUATION_1)) { + return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_2, 0.75, null); + } + } + return new PollInfo(finalFlightInfo, null, 1.0, null); + } + + @Override + public Runnable acceptPutPreparedStatementQuery( + final CommandPreparedStatementQuery command, + final CallContext context, + final FlightStream stream, + final StreamListener listener) { + parameterBindCount.incrementAndGet(); + final Runnable delegate = + super.acceptPutPreparedStatementQuery(command, context, stream, listener); + if (PREPARED_FAMILY.equals(scenarioFamily) + && (scenario == Scenario.BIND_TIMEOUT || scenario == Scenario.BIND_CANCEL)) { + return () -> { + activePoll.countDown(); + try { + while (!context.isCancelled()) { + sleep(10); + } + throw CallStatus.CANCELLED.toRuntimeException(); + } finally { + pollTerminated.countDown(); + } + }; + } + return delegate; + } + + @Override + public void cancelFlightInfo( + final CancelFlightInfoRequest request, + final CallContext context, + final StreamListener listener) { + cancelFlightInfoCount.incrementAndGet(); + listener.onNext(CancelStatus.CANCELLED); + listener.onCompleted(); + } + + public List pollDescriptors() { + synchronized (pollDescriptors) { + return new ArrayList<>(pollDescriptors); + } + } + + public int getFlightInfoCount() { + return getFlightInfoCount.get(); + } + + public String lastGetFlightInfoFamily() { + return lastGetFlightInfoFamily; + } + + public int parameterBindCount() { + return parameterBindCount.get(); + } + + public int cancelFlightInfoCount() { + return cancelFlightInfoCount.get(); + } + + public boolean awaitActivePoll(final long timeout, final TimeUnit unit) + throws InterruptedException { + return activePoll.await(timeout, unit); + } + + public boolean awaitPollTerminated(final long timeout, final TimeUnit unit) + throws InterruptedException { + return pollTerminated.await(timeout, unit); + } + + public static String commandFamily(final FlightDescriptor descriptor) { + if (!descriptor.isCommand()) { + return "path"; + } + try { + return Any.parseFrom(descriptor.getCommand()).getTypeUrl(); + } catch (Exception e) { + return "continuation"; + } + } + + private static boolean isFlightSqlCommand(final FlightDescriptor descriptor) { + return !"continuation".equals(commandFamily(descriptor)); + } + + private PollInfo blockUntilCancelled(final CallContext context) { + activePoll.countDown(); + try { + while (!context.isCancelled()) { + sleep(10); + } + throw CallStatus.CANCELLED.toRuntimeException(); + } finally { + pollTerminated.countDown(); + } + } + + private static FlightInfo partialInfo(final FlightInfo finalInfo) { + return new FlightInfo( + finalInfo.getSchemaOptional().orElse(null), + finalInfo.getDescriptor(), + Collections.singletonList( + new FlightEndpoint( + new Ticket("partial-must-not-be-read".getBytes(StandardCharsets.UTF_8)))), + -1, + -1); + } + + private static void sleep(final long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } + } +} diff --git a/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java b/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java index 69422b8cc5..b51bd6160c 100644 --- a/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java +++ b/flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java @@ -105,6 +105,17 @@ public FlightSqlClient(final FlightClient client) { this.client = Objects.requireNonNull(client, "Client cannot be null!"); } + /** + * Resolve a descriptor to its final {@link FlightInfo}. + * + *

This protected hook lets integrations preserve all Flight SQL descriptor construction and + * prepared-parameter binding while changing how the descriptor is resolved. The default remains a + * single GetFlightInfo request. + */ + protected FlightInfo getInfo(final FlightDescriptor descriptor, final CallOption... options) { + return client.getInfo(descriptor, options); + } + /** * Execute a query on the server. * @@ -133,7 +144,7 @@ public FlightInfo execute( } final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -168,7 +179,7 @@ public FlightInfo executeSubstrait( } final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** Get the schema of the result set of a query. */ @@ -446,7 +457,7 @@ public FlightInfo getCatalogs(final CallOption... options) { final CommandGetCatalogs.Builder builder = CommandGetCatalogs.newBuilder(); final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -482,7 +493,7 @@ public FlightInfo getSchemas( final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -563,7 +574,7 @@ public FlightInfo getSqlInfo(final Iterable info, final CallOption... o builder.addAllInfo(info); final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -591,7 +602,7 @@ public FlightInfo getXdbcTypeInfo(final int dataType, final CallOption... option final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -605,7 +616,7 @@ public FlightInfo getXdbcTypeInfo(final CallOption... options) { final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -658,7 +669,7 @@ public FlightInfo getTables( final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -698,7 +709,7 @@ public FlightInfo getPrimaryKeys(final TableRef tableRef, final CallOption... op final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -738,7 +749,7 @@ public FlightInfo getExportedKeys(final TableRef tableRef, final CallOption... o final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -777,7 +788,7 @@ public FlightInfo getImportedKeys(final TableRef tableRef, final CallOption... o final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -830,7 +841,7 @@ public FlightInfo getCrossReference( final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -855,7 +866,7 @@ public FlightInfo getTableTypes(final CallOption... options) { final CommandGetTableTypes.Builder builder = CommandGetTableTypes.newBuilder(); final FlightDescriptor descriptor = FlightDescriptor.command(Any.pack(builder.build()).toByteArray()); - return client.getInfo(descriptor, options); + return getInfo(descriptor, options); } /** @@ -895,6 +906,7 @@ public PreparedStatement prepare(String query, Transaction transaction, CallOpti builder.setTransactionId(ByteString.copyFrom(transaction.getTransactionId())); } return new PreparedStatement( + this, client, new Action( FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_STATEMENT.getType(), @@ -933,6 +945,7 @@ public PreparedStatement prepare( builder.setTransactionId(ByteString.copyFrom(transaction.getTransactionId())); } return new PreparedStatement( + this, client, new Action( FlightSqlUtils.FLIGHT_SQL_CREATE_PREPARED_SUBSTRAIT_PLAN.getType(), @@ -1215,6 +1228,7 @@ protected void updateCommandBuilder(CommandStatementIngest.Builder builder) { /** Helper class to encapsulate Flight SQL prepared statement logic. */ public static class PreparedStatement implements AutoCloseable { + private final FlightSqlClient parent; private final FlightClient client; private final ActionCreatePreparedStatementResult preparedStatementResult; private ByteString handle; @@ -1223,7 +1237,9 @@ public static class PreparedStatement implements AutoCloseable { private Schema resultSetSchema; private Schema parameterSchema; - PreparedStatement(FlightClient client, Action action, CallOption... options) { + PreparedStatement( + FlightSqlClient parent, FlightClient client, Action action, CallOption... options) { + this.parent = parent; this.client = client; final Iterator preparedStatementResults = client.doAction(action, options); @@ -1376,7 +1392,7 @@ public FlightInfo execute(final CallOption... options) { } } - return client.getInfo(descriptor, options); + return parent.getInfo(descriptor, options); } private SyncPutListener putParameters(FlightDescriptor descriptor, CallOption... options) { diff --git a/reports/call-site-inventory.md b/reports/call-site-inventory.md new file mode 100644 index 0000000000..27f414df6d --- /dev/null +++ b/reports/call-site-inventory.md @@ -0,0 +1,27 @@ +# Arrow Java FlightInfo call-site inventory + +Baseline: Apache Arrow Java `91b4a2ca418ecb47cb8871d97588b19444337eb4`. The baseline `FlightSqlClient` had 14 `FlightClient.getInfo` call shapes representing 13 distinct Flight SQL command families; the two XDBC overloads share one wire command family. Schema-only `getSchema` calls, updates/ingest, actions, `DoPut`, and `DoGet` are not FlightInfo-producing call sites. + +The POC routes all 13 families through `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)`. The default hook still makes one `GetFlightInfo` call. JDBC installs a polling subclass that drains PollInfo and returns only the final cumulative FlightInfo. + +| # | Wire command family | Baseline `FlightSqlClient` API/call shape | JDBC exposure | POC routing and applicability | +| --- | --- | --- | --- | --- | +| 1 | `CommandStatementQuery` | `FlightSqlClient.execute(String, Transaction, CallOption...)` | Yes: direct `Statement.executeQuery/execute`; baseline JDBC implicitly prepared even direct statements. | `ArrowFlightMetaImpl.prepareAndExecute` selects `prepareDirect`; schema discovery remains prepared, query execution sends the original direct command once through PollInfo. T1, T2, T5-T9. | +| 2 | `CommandStatementSubstraitPlan` | `FlightSqlClient.executeSubstrait(SubstraitPlan, Transaction, CallOption...)` | No JDBC API path. | Shared hook covered for FlightSqlClient consumers; not exercised by the JDBC fixture. | +| 3 | `CommandGetCatalogs` | `FlightSqlClient.getCatalogs(CallOption...)` | Yes: `ArrowDatabaseMetadata.getCatalogs`. | PollInfo through the handler. T4 and the family-isolation half of T5. | +| 4 | `CommandGetDbSchemas` | `FlightSqlClient.getSchemas(String, String, CallOption...)` | Yes: `ArrowDatabaseMetadata.getSchemas`. | PollInfo through the handler; covered by JDBC regression suite. | +| 5 | `CommandGetSqlInfo` | `FlightSqlClient.getSqlInfo(Iterable, CallOption...)`; array/enum overloads delegate to it. | Yes: lazy SQL-info cache used by `ArrowDatabaseMetadata`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 6 | `CommandGetXdbcTypeInfo` | `FlightSqlClient.getXdbcTypeInfo(int, CallOption...)` and `getXdbcTypeInfo(CallOption...)` (two call shapes, one family). | No current JDBC handler/`DatabaseMetaData` path. | Shared hook covered for FlightSqlClient consumers; not exercised by the JDBC fixture. | +| 7 | `CommandGetTables` | `FlightSqlClient.getTables(...)` | Yes: `ArrowDatabaseMetadata.getTables`; also `getColumns` with `includeSchema=true`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 8 | `CommandGetPrimaryKeys` | `FlightSqlClient.getPrimaryKeys(TableRef, CallOption...)` | Yes: `ArrowDatabaseMetadata.getPrimaryKeys`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 9 | `CommandGetExportedKeys` | `FlightSqlClient.getExportedKeys(TableRef, CallOption...)` | Yes: `ArrowDatabaseMetadata.getExportedKeys`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 10 | `CommandGetImportedKeys` | `FlightSqlClient.getImportedKeys(TableRef, CallOption...)` | Yes: `ArrowDatabaseMetadata.getImportedKeys`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 11 | `CommandGetCrossReference` | `FlightSqlClient.getCrossReference(TableRef, TableRef, CallOption...)` | Yes: `ArrowDatabaseMetadata.getCrossReference`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 12 | `CommandGetTableTypes` | `FlightSqlClient.getTableTypes(CallOption...)` | Yes: `ArrowDatabaseMetadata.getTableTypes`. | PollInfo through the handler; covered by JDBC metadata regressions. | +| 13 | `CommandPreparedStatementQuery` | `FlightSqlClient.PreparedStatement.execute(CallOption...)` after optional parameter `DoPut`. | Yes: explicit JDBC `PreparedStatement.executeQuery/execute`. | The prepared object retains its parent FlightSqlClient and resolves the original prepared descriptor once through the hook. Binding stays before PollInfo and occurs once. T3. | + +## JDBC-exposed summary + +JDBC exposes 11 of the 13 wire families: direct statement query, prepared statement query, and nine metadata families (catalogs, schemas, SQL info, tables, primary keys, exported keys, imported keys, cross reference, and table types). JDBC does not expose statement Substrait or XDBC type-info commands. The handler's `getInfo(String)` is an internal direct-query convenience but had no live JDBC caller at baseline. + +Direct and prepared updates are deliberately outside the table: they return update counts through prepared `executeUpdate`/Flight SQL update actions rather than FlightInfo. `prepareDirect` preserves that update branch and only changes the query-result branch to `CommandStatementQuery`. Parameter upload remains the existing single prepared-statement `DoPut`. diff --git a/reports/evidence.jsonl b/reports/evidence.jsonl new file mode 100644 index 0000000000..b672e305e9 --- /dev/null +++ b/reports/evidence.jsonl @@ -0,0 +1,10 @@ +{"driver":"jdbc","test":"T1","status":"PASS","command":"SharedServerPollInfoExecutionTest#immediateCompletion","exit_code":0,"assertions":["PollFlightInfo is the default and public JDBC rows are unchanged"],"observations":{"rows":[1,2],"poll":1,"get":0,"original":1,"continuations":[],"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T2","status":"PASS","command":"SharedServerPollInfoExecutionTest#multiStepCompletion","exit_code":0,"assertions":["The original descriptor is sent once","Each continuation is sent unchanged once","Only final cumulative FlightInfo feeds the endpoint queue"],"observations":{"rows":[1,2,3],"poll":3,"get":0,"original":1,"continuations":["bdx-645-poll/v1/op-000001/1","bdx-645-poll/v1/op-000001/2"],"do_get":3},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T3","status":"PASS","command":"SharedServerPollInfoExecutionTest#preparedMultiStep","exit_code":0,"assertions":["Prepared parameters bind exactly once before polling","The original prepared descriptor is sent once"],"observations":{"bound_value":41,"rows":[41,42],"bind":1,"poll":3,"get":0,"original":1,"continuations":2,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T4","status":"PASS","command":"SharedServerPollInfoExecutionTest#metadataMultiStep","exit_code":0,"assertions":["DatabaseMetaData.getCatalogs polls transparently and preserves ResultSet shape"],"observations":{"catalog":"bdx_catalog","poll":3,"get":0,"original":1,"continuations":2,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T5","status":"PASS","command":"SharedServerPollInfoExecutionTest#unsupportedFallbackAndCache","exit_code":0,"assertions":["Only initial UNIMPLEMENTED falls back","Unsupported result is cached per command family and connection","Metadata remains independently poll-capable"],"observations":{"direct":{"poll":1,"get":2,"original":1},"metadata":{"poll":3,"get":0,"original":1,"continuations":2}},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T6","status":"PASS","command":"SharedServerPollInfoExecutionTest#connectionOptOut","exit_code":0,"assertions":["usePollInfo=false restores the exact legacy prepared-command GetFlightInfo path"],"observations":{"rows":[1,2],"family":"prepared","poll":0,"get":1,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T7","status":"PASS","command":"SharedServerPollInfoExecutionTest#unavailableDoesNotFallback; PollInfoExecutionTest continuation UNIMPLEMENTED case","exit_code":0,"assertions":["Initial UNAVAILABLE propagates without fallback","Continuation UNIMPLEMENTED propagates without fallback or re-execution"],"observations":{"initial_unavailable":{"poll":1,"get":0,"original":1,"do_get":0},"continuation_unimplemented":{"poll":2,"get":0}},"log":"reports/raw/shared-server-t1-t9-final.log; orchestrator final focused rerun","limitation":null} +{"driver":"jdbc","test":"T8","status":"PASS","command":"SharedServerPollInfoExecutionTest timeout case; PollInfoExecutionTest deadline and blocked-bind cases","exit_code":0,"assertions":["One absolute deadline spans parameter upload, polls, and first endpoint retrieval","Exact JDBC timeout exception contract is preserved"],"observations":{"shared_elapsed_ms":1008,"shared_poll":1,"active_call_terminations":1,"focused_poll":2,"prepared_bind":1,"exception":"SQLTimeoutException","message":"Query timed out after 1 SECONDS"},"log":"reports/raw/pollinfo-focused-test-final.log; orchestrator final focused/shared reruns","limitation":"Existing schema preparation remains outside the execution context."} +{"driver":"jdbc","test":"T9","status":"PASS","command":"SharedServerPollInfoExecutionTest cancellation case; PollInfoExecutionTest pre-ResultSet cancellation case","exit_code":0,"assertions":["Statement.cancel interrupts an active continuation before ResultSet construction","Best-effort CancelFlightInfo uses the latest cumulative FlightInfo"],"observations":{"shared_cancel_elapsed_ms":9,"local_cancel_elapsed_ms":2,"poll":2,"get":0,"cancel":1,"active_call_terminations":1,"result_set_before_cancel":null},"log":"reports/raw/shared-server-t1-t9-final.log; reports/raw/pollinfo-focused-test-final.log; reports/raw/avatica-statement-bytecode.log","limitation":"The cleanup action is synchronous but independently bounded to one second."} +{"driver":"jdbc","test":"T10","status":"PASS","command":"mvn flight-sql test; mvn flight-sql-jdbc-core test; focused/shared tests; package; git diff --check","exit_code":0,"assertions":["Relevant shared Flight SQL and JDBC suites pass after review corrections"],"observations":{"flight_sql":{"tests":97,"failures":0,"errors":0,"skipped":0},"jdbc_core":{"tests":1267,"failures":0,"errors":0,"skipped":54},"focused":{"tests":12,"failures":0,"errors":0},"shared":{"tests":9,"failures":0,"errors":0}},"log":"reports/raw/t10-flight-sql-tests.log; reports/raw/t10-jdbc-core-tests-final.log; orchestrator final reruns","limitation":"The POC adds visible helper surfaces in published artifacts; production visibility/API design remains required."} diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md new file mode 100644 index 0000000000..cc551eab15 --- /dev/null +++ b/reports/jdbc-report.md @@ -0,0 +1,169 @@ +# BDX-645 Arrow Java JDBC PollInfo feasibility report + +## Verdict + +**Feasible with documented limitations** + +The unchanged JDBC interfaces can synchronously execute direct, prepared, and metadata Flight SQL operations through PollFlightInfo, follow continuations to completion, and give only the final cumulative FlightInfo to the existing ResultSet path. This was demonstrated with focused in-process producers and T1-T9 black-box runs against the shared real Flight SQL gRPC fixture. The limitation is production packaging: the POC introduces visible Java helper surfaces across the published `flight-sql` and `flight-sql-jdbc-core` artifacts; those surfaces need an intentional internal/public API design before landing. + +## Question answered + +Can Arrow Java JDBC make PollInfo the transparent default without changing `java.sql` signatures or result types, while retaining initial-UNIMPLEMENTED-only fallback, per-family capability isolation, one timeout, cancellation before ResultSet construction, and a connection opt-out? + +The executable answer is yes. The POC remains experimental and uncommitted on local branch `bdx-645-pollinfo-poc`; nothing was pushed and no Jira/PR state was changed. + +## Baseline and environment + +- Repository: Apache Arrow Java, shallow checkout under this workstream only. +- Upstream revision: `91b4a2ca418ecb47cb8871d97588b19444337eb4`. +- Initial state: `## main...origin/main`, clean. +- Experimental branch: `bdx-645-pollinfo-poc`. +- Java: 21.0.10; Maven: 3.9.10; RTK: 0.39.0. +- Shared server: reported revision `dev`, private instance at Flight `127.0.0.1:32347` and control `127.0.0.1:32348`. The server binary SHA-256 and unborn-branch status are in `reports/raw/shared-server-revision.log`. +- The repository-pinned `testing` submodule was initialized at `4d209492d514c2d3cb2d392681b9aa00e6d8da1c` to provide existing TLS test certificates. + +## Complete call-site inventory + +See `reports/call-site-inventory.md` for the required full 13-family table. It records 14 original GetFlightInfo call shapes across 13 distinct wire command families because filtered and unfiltered XDBC type-info methods share `CommandGetXdbcTypeInfo`. + +JDBC exposes 11 families: direct statement query, prepared statement query, and nine metadata families. FlightSqlClient additionally exposes statement Substrait and XDBC type info, which are routed through the shared hook but have no current JDBC entry point. Updates, ingest, and schema-only calls are not FlightInfo-producing and remain outside the PollInfo loop. + +## Experimental design + +### Shared Flight SQL library + +`FlightSqlClient` has one protected descriptor-resolution hook. All 13 command families route their final descriptor lookup through it. The default implementation remains exactly one `FlightClient.getInfo`, preserving ordinary FlightSqlClient behavior. A prepared statement now retains its parent FlightSqlClient so its descriptor goes through the same hook after the existing parameter `DoPut` completes. + +The Java `FlightProducer` default remains unchanged: `pollFlightInfo` wraps `getFlightInfo` in a completed PollInfo with no continuation. The full regressions, including the updated OAuth interceptor assertion on `POLL_FLIGHT_INFO`, prove that default producer behavior remains transparent. + +### JDBC integration + +Each JDBC connection installs a polling FlightSqlClient wrapper. For a FlightInfo-producing command it: + +1. Derives the capability-cache key from the original Flight SQL `Any.type_url`. +2. Sends the original descriptor to PollFlightInfo once. +3. Sends every returned opaque continuation unchanged once until no continuation remains. +4. Stores the latest cumulative FlightInfo only for cancellation and returns only the final cumulative FlightInfo to the existing endpoint queue/ResultSet path. +5. Falls back to GetFlightInfo only when the initial poll is `UNIMPLEMENTED`, then caches that family as unsupported on the connection. No continuation error and no other initial error falls back. + +Direct JDBC statements still use a prepared action for schema/type discovery, but with polling enabled their query-result execution uses `CommandStatementQuery`. With `usePollInfo=false`, the handler deliberately restores the exact pre-POC `CommandPreparedStatementQuery` execution path; both focused and shared-server T6 tests assert that command family. The update branch still invokes the existing prepared `executeUpdate`; the full `ArrowFlightStatementExecuteUpdateTest` passes. Explicit JDBC prepared queries retain `CommandPreparedStatementQuery`; their parameter `DoPut` occurs once before the single original poll descriptor. + +The secondary opt-out is URL/connection property `usePollInfo=false`; omission means polling is enabled. + +### One deadline and cancellation + +`PollInfoOperation` creates one absolute `System.nanoTime` deadline and one gRPC cancellable context per statement execution. Prepared parameter `DoPut`, every poll, and the first endpoint wait all run within that operation; each RPC receives only the remaining budget. This also preserves the existing `SQLTimeoutException` class and exact `Query timed out after N SECONDS` message. + +The focused two-poll timeout scenario delays the first poll by 700 ms, blocks the second, and uses a 1-second statement timeout. The final orchestrator rerun completed in 1030 ms with two PollFlightInfo calls. A per-call timeout reset would have allowed roughly 1.7 seconds; the test rejects anything at or above 1.5 seconds. The final shared-server blocked-poll rerun ended in 1008 ms and recorded one active-call termination. + +Baseline Avatica has a real pre-ResultSet gap: its bytecode shows `AvaticaStatement.cancel()` only invokes `openResultSet.cancel()` when that field is non-null, then sets a flag. The focused and shared cancellation tests block a continuation, assert `Statement.getResultSet()` is still null, and then call the unchanged public `Statement.cancel()` method. The statement-owned context terminated the calls in 2 ms locally and 9 ms against the shared server. Shared counters were two polls (one original plus one continuation), one active-call termination, one standard CancelFlightInfo action, zero GetFlightInfo calls, and zero DoGet calls. CancelFlightInfo is best effort and is attempted once only when a cumulative FlightInfo has already been received. + +## T1-T10 results + +Every T1-T9 case has shared-server evidence wherever the fixture supports the assertion. The focused producer supplements T8 with the required multi-call no-reset proof. Exact machine-readable observations are in `reports/evidence.jsonl`. + +| Test | Result | Evidence summary | +| --- | --- | --- | +| T1 immediate | PASS | Rows `[1,2]`; poll 1, GetFlightInfo 0, original 1, continuation 0, DoGet 1. | +| T2 multi-step | PASS | Rows `[1,2,3]`; three polls are exactly one original plus two continuations; ordered descriptors `/op-000001/1`, then `/op-000001/2`; GetFlightInfo 0; DoGet 3. Partial cumulative endpoints were not consumed (otherwise DoGet would exceed 3). | +| T3 prepared | PASS | Bound value 41 yielded `[41,42]`; bind 1; poll 3; original 1; continuation 2; GetFlightInfo 0. | +| T4 metadata | PASS | `DatabaseMetaData.getCatalogs()` returned `bdx_catalog`; poll 3; original 1; continuation 2. | +| T5 fallback/cache | PASS | Two direct executions produced direct poll 1/GetFlightInfo 2, proving connection cache reuse; metadata on the same connection still polled three times and never used GetFlightInfo. | +| T6 opt-out | PASS | `usePollInfo=false`; poll 0, GetFlightInfo 1, normal rows `[1,2]`; the server records the legacy prepared command family. | +| T7 non-fallback failure | PASS | Initial `UNAVAILABLE` propagated with poll 1/GetFlightInfo 0/DoGet 0. A focused continuation-`UNIMPLEMENTED` case propagated after two polls with GetFlightInfo 0. | +| T8 timeout | PASS | Shared blocked poll ended at the one-second deadline with active termination 1 and the exact JDBC timeout contract. Focused two-poll and prepared blocked-bind cases prove the deadline does not reset and covers parameter upload. | +| T9 cancellation | PASS | ResultSet was null during the active continuation; cancel returned in 9 ms shared/2 ms local; shared cancellation 1, active termination 1, GetFlightInfo 0. | +| T10 regression/build | PASS | Flight SQL: 97 tests, zero failures/errors. Final JDBC core rerun after review corrections: 1,267 tests, zero failures/errors, 54 existing skips. | + +## Regression details + +- Direct SELECT semantics: focused/shared direct tests assert returned rows and the server identifies `CommandStatementQuery`; `ArrowFlightStatementExecuteTest` and `ResultSetTest` pass in the full JDBC suite. +- Timeout and cancellation: PollInfo-specific tests plus existing ResultSet cancellation/timeout tests pass. An initial exact-message regression (`NANOSECONDS` surfaced instead of the legacy `SECONDS` text) was found and fixed while retaining the remaining nanosecond budget internally. +- Updates/DoPut: all ten `ArrowFlightStatementExecuteUpdateTest` cases pass; prepared/update suites pass. Direct updates continue through the existing prepared update path. T3 records exactly one parameter binding. +- Authentication: bearer options are present on PollFlightInfo; the existing OAuth test expectation was updated from the obsolete GetFlightInfo method observation and passes. +- Java producer default: unchanged completed PollInfo implementation plus ResultSet/metadata regressions pass. + +## API-surface audit + +No standard JDBC method signature, return type, or user ResultSet type changed. `Statement.cancel()` and `PreparedStatement.cancel()` are overrides of existing methods, not new JDBC API. + +The POC does expand Java surface visible in published artifacts: + +- protected `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)`; +- public JDBC implementation-layer `PollInfoOperation`; +- handler `prepareDirect`, builder `withPollInfo`, the prepared-handler operation overload, and config getter `usePollInfo`. + +The added protected method can also create a downstream source-compatibility collision if a FlightSqlClient subclass already declares an identically shaped method with weaker visibility. `reports/raw/api-surface-added-lines.log` captures the audit. This is the principal reason the experiment is not a production-ready patch even though the unchanged JDBC interface is feasible. + +## Commands and exit evidence + +All commands were run locally with RTK and no remote mutation. + +| Command | Exit/result | Raw evidence | +| --- | --- | --- | +| `mvn -pl flight/flight-sql -DskipTests install` | 0; shared hook compiled, checked, installed locally | `reports/raw/install-flight-sql-hook.log` | +| `mvn -pl flight/flight-sql-jdbc-core -Dtest=PollInfoExecutionTest test` | 0; final focused rerun 12/12 | original log plus orchestrator validation | +| `mvn -pl flight/flight-sql-jdbc-core -Dtest=SharedServerPollInfoExecutionTest -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32347 -Dpollinfo.shared.controlPort=32348 test` | 0; 9/9 | `reports/raw/shared-server-t1-t9-final.log` | +| `mvn -pl flight/flight-sql test` | 0; 97/97 | `reports/raw/t10-flight-sql-tests.log` | +| `mvn -pl flight/flight-sql-jdbc-core test` | 0; final rerun 1,267 tests, 54 skipped | original log plus orchestrator validation | +| `mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -DskipTests package` | 0; both artifacts compiled, formatted, checked, and packaged | `reports/raw/t10-final-package.log` | +| focused OAuth/TLS rerun | 0; 50/50 after expected-method fix and test-data initialization | `reports/raw/t10-prior-failures-rerun.log` | +| `git diff --check` | 0 | final command output/working-tree check | + +The first focused invocation mistakenly linked the previously installed Flight SQL snapshot and consequently observed zero polls; `reports/raw/pollinfo-focused-test.log` preserves that diagnostic. Installing the modified shared module corrected the test classpath and the same tests passed. The first complete JDBC run records the OAuth expectation mismatch and missing submodule data in `reports/raw/t10-jdbc-core-tests.log`; the final run is clean. + +## Changed files + +Production POC: + +- `flight/flight-sql/src/main/java/org/apache/arrow/flight/sql/FlightSqlClient.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightMetaImpl.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java` +- `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java` + +Test/evidence support: + +- `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/OAuthIntegrationTest.java` +- `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java` +- `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java` +- `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/MockFlightSqlProducer.java` +- `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java` +- `reports/call-site-inventory.md`, `reports/evidence.jsonl`, this report, raw logs, and `reports/arrow-java-bdx-645.patch`. + +## Limitations + +- The visible helper surfaces listed in the API audit need redesign or explicit compatibility review before production. +- Direct statements still perform the existing prepare action for schema/type discovery before sending `CommandStatementQuery`; this adds no new preparation round trip but means the statement timeout/cancellable context begins at PollInfo execution, not at schema preparation. PollInfo calls and first endpoint retrieval do share one deadline. +- The corrected prepared path includes parameter upload in that same deadline/context; schema discovery remains outside it as described above. +- Capability caching is connection/handler scoped and keyed by Flight SQL command type URL. Production code should make the physical-connection ownership explicit if connection pooling/reuse is broadened. +- The shared fixture intentionally covers direct, prepared, and catalogs metadata only. All other JDBC-exposed metadata families route through the same shared hook and pass the full JDBC regressions, but do not have distinct shared-server black-box scenarios. +- Best-effort CancelFlightInfo is possible only after a PollInfo response supplies cumulative FlightInfo. A timeout/cancel on the initial blocked poll can terminate the RPC context but has no FlightInfo payload to send to the cancel action. +- The Java cleanup action is synchronous but independently bounded to one second. A production implementation should ensure a slow server cannot delay primary timeout delivery or cancellation completion. +- No unchanged-response backoff, retry policy, or production telemetry was added; those are production-hardening concerns and were not part of the frozen POC contract. + +## Smallest production follow-up + +### Arrow Java Flight SQL shared library + +1. Define an intentional descriptor-resolution abstraction with compatibility review, avoiding an accidental protected-hook collision in `FlightSqlClient`. +2. Place the PollInfo operation state/capability cache behind non-public or explicitly supported shared-library APIs, with final-only handoff and initial-UNIMPLEMENTED semantics covered at that layer. +3. Add shared-library unit tests for all command constructors, default producer completion, continuation validation, and optional bounded unchanged-response delay. + +### JDBC integration and hardening + +1. Hide the statement operation carrier and direct-query adapter behind JDBC-internal package boundaries while retaining `usePollInfo` as a documented connection property. +2. Decide whether the operation deadline should include schema preparation; if yes, create the context at `prepareAndExecute` entry and carry its remaining budget through PollInfo and first endpoint retrieval. +3. Add pooled/physical-connection lifecycle tests for per-family unsupported caching and cancellation races, plus black-box fixture coverage for additional metadata families when the fixture grows. +4. Retain the direct select/update, OAuth, default producer, timeout-message, prepared single-bind, and pre-ResultSet cancellation regressions from this experiment. + +## Artifacts + +- Machine-readable evidence: `reports/evidence.jsonl` +- Complete call-site inventory: `reports/call-site-inventory.md` +- Experimental patch: `reports/arrow-java-bdx-645.patch` +- Raw command/server logs: `reports/raw/` From 72ebaec6b11e067fddeb689d84afe5caf85b97da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Fri, 11 Sep 2026 11:18:55 +0100 Subject: [PATCH 16/39] BDX-645: document JDBC request flow --- reports/jdbc-report.md | 65 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md index cc551eab15..c831bffad7 100644 --- a/reports/jdbc-report.md +++ b/reports/jdbc-report.md @@ -58,6 +58,71 @@ The focused two-poll timeout scenario delays the first poll by 700 ms, blocks th Baseline Avatica has a real pre-ResultSet gap: its bytecode shows `AvaticaStatement.cancel()` only invokes `openResultSet.cancel()` when that field is non-null, then sets a flag. The focused and shared cancellation tests block a continuation, assert `Statement.getResultSet()` is still null, and then call the unchanged public `Statement.cancel()` method. The statement-owned context terminated the calls in 2 ms locally and 9 ms against the shared server. Shared counters were two polls (one original plus one continuation), one active-call termination, one standard CancelFlightInfo action, zero GetFlightInfo calls, and zero DoGet calls. CancelFlightInfo is best effort and is attempted once only when a cumulative FlightInfo has already been received. +## Request flow + +```mermaid +sequenceDiagram + autonumber + actor App as JDBC application + participant API as Statement / PreparedStatement / DatabaseMetaData + participant Client as ArrowFlightSqlClientHandler + participant Poller as PollInfoOperation + FlightSqlClient + participant Server as Flight SQL server + participant Result as Existing ResultSet / DoGet path + + App->>API: executeQuery() or metadata call + API->>Client: Execute command with query timeout + opt Parameterized PreparedStatement + Client->>Server: DoPut(bound parameters) exactly once + Server-->>Client: Bound prepared handle + end + alt usePollInfo=false or family cached unsupported + Client->>Server: GetFlightInfo(original descriptor) + Server-->>Client: Final FlightInfo + Client->>Result: Final FlightInfo + else PollInfo enabled + Client->>Poller: Resolve original descriptor + Poller->>Server: PollFlightInfo(original descriptor) + alt Initial response is UNIMPLEMENTED + Server-->>Poller: UNIMPLEMENTED + Poller->>Poller: Cache command family as unsupported + Poller->>Server: GetFlightInfo(original descriptor) + Server-->>Poller: Final FlightInfo + Poller->>Result: Final FlightInfo + else Error other than initial UNIMPLEMENTED + Server-->>Poller: UNAVAILABLE / auth / query / continuation error + Poller-->>API: Propagate error; no fallback + API-->>App: SQLException + else Polling accepted + Server-->>Poller: Cumulative PollInfo + continuation + loop While continuation exists + Poller->>Server: PollFlightInfo(continuation descriptor) + Server-->>Poller: New cumulative PollInfo + next continuation + end + alt Polling completes + Poller->>Result: Final cumulative FlightInfo only + else Statement.cancel() or deadline during active poll + App->>API: cancel() or timeout expires + API->>Poller: Cancel operation context + Poller-->>Server: Cancel active PollFlightInfo RPC + opt A cumulative FlightInfo is known + Poller->>Server: CancelFlightInfo(latest info), bounded cleanup + end + Poller-->>App: SQLException / SQLTimeoutException + end + end + end + opt Final FlightInfo was produced + loop Each final endpoint + Result->>Server: DoGet(ticket) + Server-->>Result: Arrow record batches + end + Result-->>App: Existing JDBC schema and rows + end +``` + +The key JDBC boundary is the final-only handoff to the existing ResultSet path. Prepared binding occurs once inside the operation context, and `Statement.cancel()` can interrupt an active poll before a ResultSet exists. + ## T1-T10 results Every T1-T9 case has shared-server evidence wherever the fixture supports the assertion. The focused producer supplements T8 with the required multi-call no-reset proof. Exact machine-readable observations are in `reports/evidence.jsonl`. From 8491b1131044e1edc0e29f548f760f223d7a2b01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Fri, 11 Sep 2026 11:25:15 +0100 Subject: [PATCH 17/39] BDX-645: fix Mermaid request flow syntax --- reports/jdbc-report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md index c831bffad7..010791c0ad 100644 --- a/reports/jdbc-report.md +++ b/reports/jdbc-report.md @@ -91,7 +91,7 @@ sequenceDiagram Poller->>Result: Final FlightInfo else Error other than initial UNIMPLEMENTED Server-->>Poller: UNAVAILABLE / auth / query / continuation error - Poller-->>API: Propagate error; no fallback + Poller-->>API: Propagate error, no fallback API-->>App: SQLException else Polling accepted Server-->>Poller: Cumulative PollInfo + continuation From c02cbefc56d453d7d3b93619566f665fa7e9f1ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Fri, 11 Sep 2026 13:13:58 +0100 Subject: [PATCH 18/39] BDX-645: consume PollInfo endpoints progressively --- .../ArrowFlightJdbcFlightStreamResultSet.java | 116 ++++++++++++++++- .../jdbc/ArrowFlightPreparedStatement.java | 24 +++- .../driver/jdbc/ArrowFlightStatement.java | 26 +++- .../client/ArrowFlightSqlClientHandler.java | 28 +++-- .../driver/jdbc/client/PollInfoOperation.java | 118 +++++++++++++++++- .../driver/jdbc/PollInfoExecutionTest.java | 36 ++++-- .../SharedServerPollInfoExecutionTest.java | 51 ++++++-- .../utils/PollingMockFlightSqlProducer.java | 6 +- reports/call-site-inventory.md | 2 +- reports/evidence.jsonl | 10 +- reports/jdbc-report.md | 88 ++++--------- 11 files changed, 383 insertions(+), 122 deletions(-) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index bbe787930d..0bff27b5d1 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -22,15 +22,19 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLTimeoutException; +import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.Optional; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue; import org.apache.arrow.driver.jdbc.utils.VectorSchemaRootTransformer; import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightRuntimeException; import org.apache.arrow.flight.FlightStatusCode; @@ -53,7 +57,9 @@ public final class ArrowFlightJdbcFlightStreamResultSet extends ArrowFlightJdbcVectorSchemaRootResultSet { private final ArrowFlightConnection connection; - private final FlightInfo flightInfo; + private FlightInfo flightInfo; + private final PollInfoOperation pollInfoOperation; + private int consumedEndpointCount; private CloseableEndpointStreamPair currentEndpointData; private FlightEndpointDataQueue flightEndpointDataQueue; private volatile boolean cancelled; @@ -77,6 +83,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet this.connection = (ArrowFlightConnection) statement.connection; try { this.flightInfo = ((ArrowFlightInfoStatement) statement).executeFlightInfoQuery(); + this.pollInfoOperation = activePollInfoOperation(statement); } catch (FlightRuntimeException e) { if (e.status().code() != FlightStatusCode.TIMED_OUT) { throw e; @@ -104,6 +111,7 @@ private ArrowFlightJdbcFlightStreamResultSet( super(null, state, signature, resultSetMetaData, timeZone, firstFrame); this.connection = connection; this.flightInfo = flightInfo; + this.pollInfoOperation = null; this.id = connection.getNewMetadataResultSetId(this); } @@ -164,8 +172,7 @@ protected AvaticaResultSet execute() throws SQLException { private void populateData() throws SQLException { loadNewQueue(); - enqueueEndpointData( - flightEndpointDataQueue, connection.getClientHandler().getStreams(flightInfo)); + enqueueNewEndpoints(flightInfo); loadNewFlightStream(); // Ownership of the root will be passed onto the cursor. @@ -198,7 +205,9 @@ public byte[] getAppMetadata() { @Override public boolean next() throws SQLException { if (currentVectorSchemaRoot == null) { - return false; + if (!loadNextPublishedEndpoint()) { + return false; + } } while (true) { final boolean hasNext = super.next(); @@ -246,6 +255,10 @@ public boolean next() throws SQLException { throw AvaticaConnection.HELPER.createException("Statement canceled"); } + if (loadNextPublishedEndpoint()) { + continue; + } + if (statement != null && statement.isCloseOnCompletion()) { statement.close(); } @@ -257,6 +270,10 @@ public boolean next() throws SQLException { @Override protected void cancel() { cancelled = true; + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); super.cancel(); final CloseableEndpointStreamPair currentEndpoint = this.currentEndpointData; if (currentEndpoint != null) { @@ -291,6 +308,10 @@ public synchronized void close() { } catch (final Exception e) { throw new RuntimeException(e); } finally { + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); super.close(); } } @@ -380,4 +401,91 @@ private static SQLException normalizeClosedQueueException( } throw exception; } + + private void enqueueNewEndpoints(final FlightInfo updatedFlightInfo) throws SQLException { + final int updatedEndpointCount = updatedFlightInfo.getEndpoints().size(); + if (updatedEndpointCount < consumedEndpointCount) { + throw new SQLException("PollInfo removed previously published endpoints"); + } + final Schema updatedSchema = updatedFlightInfo.getSchemaOptional().orElse(schema); + if (schema != null && updatedSchema != null && !schema.equals(updatedSchema)) { + throw new SQLException("PollInfo changed the result schema"); + } + if (updatedEndpointCount == consumedEndpointCount) { + flightInfo = updatedFlightInfo; + return; + } + final List appendedEndpoints = + new ArrayList<>( + updatedFlightInfo + .getEndpoints() + .subList(consumedEndpointCount, updatedEndpointCount)); + final FlightInfo appendedInfo = + new FlightInfo( + updatedSchema, + updatedFlightInfo.getDescriptor(), + appendedEndpoints, + updatedFlightInfo.getBytes(), + updatedFlightInfo.getRecords()); + enqueueEndpointData( + flightEndpointDataQueue, connection.getClientHandler().getStreams(appendedInfo)); + consumedEndpointCount = updatedEndpointCount; + flightInfo = updatedFlightInfo; + } + + private boolean loadNextPublishedEndpoint() throws SQLException { + if (pollInfoOperation == null || !pollInfoOperation.hasContinuation()) { + finishPollInfoOperation(); + return false; + } + try { + enqueueNewEndpoints(pollInfoOperation.pollNextAvailable()); + currentEndpointData = getNextEndpointStream(false); + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + return true; + } + finishPollInfoOperation(); + return false; + } catch (FlightRuntimeException e) { + if (e.status().code() == FlightStatusCode.CANCELLED + || e.status().code() == FlightStatusCode.TIMED_OUT) { + pollInfoOperation.cancel(); + } else { + pollInfoOperation.terminate(); + } + finishPollInfoOperation(); + if (cancelled && e.status().code() == FlightStatusCode.CANCELLED) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + if (e.status().code() == FlightStatusCode.TIMED_OUT) { + final SQLTimeoutException timeout = + new SQLTimeoutException( + String.format( + "Query timed out after %d %s", + statement.getQueryTimeout(), TimeUnit.SECONDS)); + timeout.initCause(e); + throw timeout; + } + throw new SQLException("Continuation PollFlightInfo failed", e); + } + } + + private static PollInfoOperation activePollInfoOperation(final AvaticaStatement statement) { + if (statement instanceof ArrowFlightStatement) { + return ((ArrowFlightStatement) statement).activePollInfoOperation(); + } + if (statement instanceof ArrowFlightPreparedStatement) { + return ((ArrowFlightPreparedStatement) statement).activePollInfoOperation(); + } + return null; + } + + private void finishPollInfoOperation() { + if (statement instanceof ArrowFlightStatement) { + ((ArrowFlightStatement) statement).finishPollInfoOperation(pollInfoOperation); + } else if (statement instanceof ArrowFlightPreparedStatement) { + ((ArrowFlightPreparedStatement) statement).finishPollInfoOperation(pollInfoOperation); + } + } } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java index 8ba611b82f..1379a3e98c 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java @@ -184,14 +184,18 @@ ExecuteBatchResult executeBatchWithTypedValues( @Override public FlightInfo executeFlightInfoQuery() throws SQLException { ensurePrepared(); - final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout()); + final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout(), true); activeOperation.set(operation); lastOperation = operation; try { - return preparedStatement.executeQuery(operation); - } finally { - activeOperation.compareAndSet(operation, null); - operation.close(); + final FlightInfo flightInfo = preparedStatement.executeQuery(operation); + if (!operation.hasContinuation()) { + finishPollInfoOperation(operation); + } + return flightInfo; + } catch (RuntimeException | SQLException e) { + finishPollInfoOperation(operation); + throw e; } } @@ -218,6 +222,16 @@ void cancelActivePollInfoOperation() { } } + PollInfoOperation activePollInfoOperation() { + return activeOperation.get(); + } + + void finishPollInfoOperation(final PollInfoOperation operation) { + if (operation != null && activeOperation.compareAndSet(operation, null)) { + operation.close(); + } + } + private void ensurePrepared() { if (preparedStatement == null) { throw new IllegalStateException("PreparedStatement is already closed."); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java index ce663ad480..cc70dfd0e1 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java @@ -132,15 +132,18 @@ public FlightInfo executeFlightInfoQuery() throws SQLException { } // Direct Statement.executeQuery(String) path: CommandStatementQuery through PollFlightInfo. - final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout()); + final PollInfoOperation operation = new PollInfoOperation(getQueryTimeout(), true); activeOperation.set(operation); lastOperation = operation; final FlightInfo flightInfo; try { flightInfo = connection.getClientHandler().getInfo(signature.sql, operation); - } finally { - activeOperation.compareAndSet(operation, null); - operation.close(); + if (!operation.hasContinuation()) { + finishPollInfoOperation(operation); + } + } catch (RuntimeException e) { + finishPollInfoOperation(operation); + throw e; } updateSignatureColumnsFromFlightInfo(signature, flightInfo); return flightInfo; @@ -171,6 +174,21 @@ long remainingQueryTimeoutNanos() { : Long.MAX_VALUE; } + PollInfoOperation activePollInfoOperation() { + final ArrowFlightPreparedStatement delegate = preparedDelegate(); + return delegate != null ? delegate.activePollInfoOperation() : activeOperation.get(); + } + + void finishPollInfoOperation(final PollInfoOperation operation) { + final ArrowFlightPreparedStatement delegate = preparedDelegate(); + if (delegate != null) { + delegate.finishPollInfoOperation(operation); + } + if (operation != null && activeOperation.compareAndSet(operation, null)) { + operation.close(); + } + } + private ArrowFlightPreparedStatement preparedDelegate() { final AvaticaStatement current = ((ArrowFlightConnection) connection).statementMap.get(handle.id); return current instanceof ArrowFlightPreparedStatement diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index e9f806d0ba..50dbef2ba9 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -779,28 +779,38 @@ private FlightInfo getInfo( final CallOption[] options) { final String family = commandFamily(originalDescriptor); if (!pollInfoEnabled || unsupportedFamilies.contains(family)) { - return operation.call(() -> client.getInfo(originalDescriptor, operation.options(options))); + final FlightInfo flightInfo = + operation.call(() -> client.getInfo(originalDescriptor, operation.options(options))); + operation.complete(flightInfo); + return flightInfo; } org.apache.arrow.flight.FlightDescriptor descriptor = originalDescriptor; boolean initialPoll = true; + operation.configure( + descriptorForPoll -> + client.pollInfo(descriptorForPoll, operation.options(options)), + () -> cancelFlightInfoBestEffort(operation, options)); try { while (true) { - final org.apache.arrow.flight.FlightDescriptor descriptorForPoll = descriptor; - final PollInfo pollInfo = - operation.call(() -> client.pollInfo(descriptorForPoll, operation.options(options))); - operation.remember(pollInfo.getFlightInfo()); - if (!pollInfo.getFlightDescriptor().isPresent()) { + final PollInfo pollInfo = operation.poll(descriptor); + operation.remember(pollInfo); + if (operation.isComplete() + || (operation.isProgressive() + && !pollInfo.getFlightInfo().getEndpoints().isEmpty())) { return pollInfo.getFlightInfo(); } - descriptor = pollInfo.getFlightDescriptor().get(); + descriptor = operation.continuationDescriptor(); initialPoll = false; } } catch (FlightRuntimeException e) { if (initialPoll && e.status().code() == FlightStatusCode.UNIMPLEMENTED) { unsupportedFamilies.add(family); - return operation.call( - () -> client.getInfo(originalDescriptor, operation.options(options))); + final FlightInfo flightInfo = + operation.call( + () -> client.getInfo(originalDescriptor, operation.options(options))); + operation.complete(flightInfo); + return flightInfo; } if (operation.isCancelled() || e.status().code() == FlightStatusCode.CANCELLED diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java index 979bea1092..fb4f9a3064 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -18,36 +18,52 @@ import io.grpc.Context; import java.util.Arrays; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; import org.apache.arrow.flight.CallOption; import org.apache.arrow.flight.CallOptions; import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.PollInfo; /** - * State shared by every PollFlightInfo call in one synchronous JDBC query execution. + * State shared by every PollFlightInfo call in one JDBC query execution. * *

The absolute deadline is deliberately created once. Each RPC receives only the remaining - * budget, while the cancellable gRPC context lets {@code Statement.cancel()} terminate a poll that - * is active before a ResultSet exists. + * budget, while the cancellable gRPC context lets {@code Statement.cancel()} terminate an active + * poll before or after a ResultSet exists. Progressive operations retain their continuation until + * the ResultSet consumes all published endpoints. */ public final class PollInfoOperation implements AutoCloseable { private static final long NO_DEADLINE = Long.MAX_VALUE; private final long deadlineNanos; + private final boolean progressive; private final Context.CancellableContext context; private final AtomicBoolean cancelled = new AtomicBoolean(); private final AtomicBoolean cancelFlightInfoAttempted = new AtomicBoolean(); private volatile FlightInfo latestFlightInfo; + private volatile FlightDescriptor continuationDescriptor; + private volatile Function poller; + private volatile Runnable cancelFlightInfo; /** Create an operation whose timeout is expressed in JDBC query-timeout seconds. */ public PollInfoOperation(final int timeoutSeconds) { + this(timeoutSeconds, false); + } + + /** Create an operation that may hand continuation polling to the JDBC ResultSet. */ + public PollInfoOperation(final int timeoutSeconds, final boolean progressive) { deadlineNanos = timeoutSeconds > 0 ? saturatingAdd(System.nanoTime(), TimeUnit.SECONDS.toNanos(timeoutSeconds)) : NO_DEADLINE; + this.progressive = progressive; context = Context.current().withCancellation(); } @@ -83,20 +99,89 @@ CallOption[] options(final CallOption[] baseOptions) { public void cancel() { cancelled.set(true); context.cancel(null); + final Runnable cleanup = cancelFlightInfo; + if (cleanup != null) { + cleanup.run(); + } } boolean isCancelled() { return cancelled.get(); } - void remember(final FlightInfo flightInfo) { + void configure( + final Function poller, + final Runnable cancelFlightInfo) { + this.poller = poller; + this.cancelFlightInfo = cancelFlightInfo; + } + + PollInfo poll(final FlightDescriptor descriptor) { + final Function currentPoller = poller; + if (currentPoller == null) { + throw new IllegalStateException("PollInfo operation has no poller"); + } + return call(() -> currentPoller.apply(descriptor)); + } + + synchronized void remember(final PollInfo pollInfo) { + if (pollInfo == null || pollInfo.getFlightInfo() == null) { + throw CallStatus.INTERNAL + .withDescription("Server returned PollInfo without FlightInfo") + .toRuntimeException(); + } + final FlightInfo nextFlightInfo = pollInfo.getFlightInfo(); + validateAppendOnly(latestFlightInfo, nextFlightInfo); + latestFlightInfo = nextFlightInfo; + continuationDescriptor = pollInfo.getFlightDescriptor().orElse(null); + } + + synchronized void complete(final FlightInfo flightInfo) { latestFlightInfo = flightInfo; + continuationDescriptor = null; + } + + /** Poll until another endpoint is appended, the query completes, or the poll fails. */ + public synchronized FlightInfo pollNextAvailable() { + final int previousEndpointCount = endpointCount(latestFlightInfo); + while (continuationDescriptor != null) { + remember(poll(continuationDescriptor)); + if (endpointCount(latestFlightInfo) > previousEndpointCount + || continuationDescriptor == null) { + return latestFlightInfo; + } + } + return latestFlightInfo; } FlightInfo latestFlightInfo() { return latestFlightInfo; } + FlightDescriptor continuationDescriptor() { + return continuationDescriptor; + } + + /** Whether this operation can return before PollFlightInfo reaches completion. */ + public boolean isProgressive() { + return progressive; + } + + /** Whether another continuation poll is required. */ + public boolean hasContinuation() { + return continuationDescriptor != null; + } + + /** Whether PollFlightInfo has reached a response without a continuation descriptor. */ + public boolean isComplete() { + return latestFlightInfo != null && continuationDescriptor == null; + } + + /** Mark a failed continuation as terminal without discarding already published endpoints. */ + public synchronized void terminate() { + continuationDescriptor = null; + } + boolean beginCancelFlightInfoAttempt() { return latestFlightInfo != null && cancelFlightInfoAttempted.compareAndSet(false, true); } @@ -126,4 +211,29 @@ private static long saturatingAdd(final long left, final long right) { } return result; } + + private static int endpointCount(final FlightInfo flightInfo) { + return flightInfo == null ? 0 : flightInfo.getEndpoints().size(); + } + + private static void validateAppendOnly( + final FlightInfo previous, final FlightInfo current) { + if (previous == null) { + return; + } + final List previousEndpoints = previous.getEndpoints(); + final List currentEndpoints = current.getEndpoints(); + if (currentEndpoints.size() < previousEndpoints.size()) { + throw CallStatus.INTERNAL + .withDescription("PollInfo removed previously published endpoints") + .toRuntimeException(); + } + for (int index = 0; index < previousEndpoints.size(); index++) { + if (!previousEndpoints.get(index).equals(currentEndpoints.get(index))) { + throw CallStatus.INTERNAL + .withDescription("PollInfo mutated previously published endpoint " + index) + .toRuntimeException(); + } + } + } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java index c3617ba086..24612d34d6 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -121,13 +121,14 @@ public void immediateCompletionUsesOnePollAndNoGetFlightInfo() throws Exception } @Test - public void multiStepUsesEachDescriptorOnceAndOnlyFinalInfoFeedsResultSet() throws Exception { + public void multiStepPollsOnDemandAfterPublishedEndpointIsConsumed() throws Exception { producer.configure(Scenario.MULTI_STEP, STATEMENT_FAMILY); try (Connection connection = connect(true); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { assertTrue(resultSet.next()); assertEquals(42, resultSet.getInt(1)); + assertFalse(resultSet.next()); } final List descriptors = producer.pollDescriptors(); assertEquals(3, descriptors.size()); @@ -149,6 +150,7 @@ public void preparedParametersAreBoundOnceBeforePolling() throws Exception { try (ResultSet resultSet = statement.executeQuery()) { assertTrue(resultSet.next()); assertEquals(7, resultSet.getInt(1)); + assertFalse(resultSet.next()); } } assertEquals(1, producer.parameterBindCount()); @@ -214,9 +216,11 @@ public void unavailableDoesNotFallbackOrReexecute() throws Exception { public void continuationUnimplementedDoesNotFallbackOrReexecute() throws Exception { producer.configure(Scenario.CONTINUATION_UNIMPLEMENTED, STATEMENT_FAMILY); try (Connection connection = connect(true); - Statement statement = connection.createStatement()) { - final Throwable failure = - assertThrows(Throwable.class, () -> statement.executeQuery(DIRECT_QUERY)); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + final Throwable failure = assertThrows(Throwable.class, resultSet::next); assertTrue(hasFlightStatus(failure, FlightStatusCode.UNIMPLEMENTED), failure.toString()); } assertEquals(2, producer.pollDescriptors().size()); @@ -230,10 +234,13 @@ public void oneDeadlineSpansAllPollsAndTerminatesActivePoll() throws Exception { try (Connection connection = connect(true); Statement statement = connection.createStatement()) { statement.setQueryTimeout(1); - final Throwable failure = - assertThrows(Throwable.class, () -> statement.executeQuery(DIRECT_QUERY)); - assertTrue(hasFlightStatus(failure, FlightStatusCode.TIMED_OUT), failure.toString()); - assertJdbcTimeoutContract(failure, 1); + try (ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + final Throwable failure = assertThrows(Throwable.class, resultSet::next); + assertTrue(hasFlightStatus(failure, FlightStatusCode.TIMED_OUT), failure.toString()); + assertJdbcTimeoutContract(failure, 1); + } } final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); System.out.println("LOCAL_T8_ELAPSED_MILLIS " + elapsedMillis); @@ -298,7 +305,7 @@ public void preparedBindIsCancelledBeforePolling() throws Exception { } @Test - public void avaticaHasNoResultSetTargetButStatementContextCancelsActivePoll() throws Exception { + public void statementCancelInterruptsContinuationAtReadBoundary() throws Exception { producer.configure(Scenario.CANCEL_OBSERVABLE, STATEMENT_FAMILY); try (Connection connection = connect(true); Statement statement = connection.createStatement()) { @@ -307,8 +314,12 @@ public void avaticaHasNoResultSetTargetButStatementContextCancelsActivePoll() th final Thread execution = new Thread( () -> { - try (ResultSet ignored = statement.executeQuery(DIRECT_QUERY)) { + try (ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { resultSetCreated.set(true); + if (!resultSet.next() || resultSet.getInt(1) != 42) { + throw new AssertionError("missing published row"); + } + resultSet.next(); } catch (Throwable e) { failure.set(e); } @@ -316,15 +327,14 @@ public void avaticaHasNoResultSetTargetButStatementContextCancelsActivePoll() th "jdbc-pollinfo-cancellation-test"); execution.start(); assertTrue(producer.awaitActivePoll(2, TimeUnit.SECONDS)); - // AvaticaStatement.cancel() can only reach openResultSet, which is still null at this point. - assertNull(statement.getResultSet()); + assertNotNull(statement.getResultSet()); final long cancelStart = System.nanoTime(); statement.cancel(); execution.join(TimeUnit.SECONDS.toMillis(2)); final long cancelMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelStart); System.out.println("LOCAL_T9_CANCEL_MILLIS " + cancelMillis); assertFalse(execution.isAlive()); - assertFalse(resultSetCreated.get(), "ResultSet must not exist while polling is active"); + assertTrue(resultSetCreated.get(), "ResultSet should expose the first published endpoint"); assertNotNull(failure.get()); assertTrue( hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java index 5c322c4cb1..165a1d72dc 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -91,6 +90,10 @@ public void t2MultiStepContinuationsAndFinalCumulativeInfo() throws Exception { assertCounters(state, 3, 0, 0, 1, 2, 0, 0, 3); assertTrue(state.contains("bdx-645-poll/v1/")); assertTrue(state.indexOf("/1\"") < state.indexOf("/2\""), state); + assertTrue( + state.indexOf("\"method\": \"DoGet\"") + < state.indexOf("\"descriptor_kind\": \"continuation\""), + state); } @Test @@ -103,7 +106,7 @@ public void t3PreparedParametersBoundExactlyOnce() throws Exception { assertEquals(Arrays.asList(41L, 42L), values(resultSet)); } } - assertCounters(3, 0, 1, 1, 2, 0, 0, 1); + assertCounters(3, 0, 1, 1, 2, 0, 0, 2); } @Test @@ -164,6 +167,20 @@ public void t7UnavailableDoesNotFallbackOrReexecute() throws Exception { @Test @Order(8) + public void t7LateErrorSurfacesAtNextReadBoundary() throws Exception { + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("late-error")) { + assertTrue(resultSet.next()); + assertEquals(1L, resultSet.getLong("value")); + final Throwable failure = assertThrows(Throwable.class, resultSet::next); + assertTrue(hasFlightStatus(failure, FlightStatusCode.INTERNAL), failure.toString()); + } + assertCounters(2, 0, 0, 1, 1, 0, 0, 1); + } + + @Test + @Order(9) public void t8TimeoutEndsBlockedPollAtTheSingleStatementDeadline() throws Exception { final long startNanos = System.nanoTime(); try (Connection connection = connect(true); @@ -182,8 +199,8 @@ public void t8TimeoutEndsBlockedPollAtTheSingleStatementDeadline() throws Except } @Test - @Order(9) - public void t9CancelBeforeResultSetCancelsPollAndFlightInfo() throws Exception { + @Order(10) + public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { try (Connection connection = connect(true); Statement statement = connection.createStatement()) { final AtomicReference failure = new AtomicReference<>(); @@ -191,8 +208,13 @@ public void t9CancelBeforeResultSetCancelsPollAndFlightInfo() throws Exception { final Thread execution = new Thread( () -> { - try (ResultSet ignored = statement.executeQuery("cancel-observable")) { + try (ResultSet resultSet = statement.executeQuery("cancel-observable")) { resultSetCreated.set(true); + assertTrue(resultSet.next()); + assertEquals(1L, resultSet.getLong("value")); + assertTrue(resultSet.next()); + assertEquals(2L, resultSet.getLong("value")); + resultSet.next(); } catch (Throwable e) { failure.set(e); } @@ -200,21 +222,34 @@ public void t9CancelBeforeResultSetCancelsPollAndFlightInfo() throws Exception { "shared-server-jdbc-cancel"); execution.start(); awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); - assertNull(statement.getResultSet()); + assertTrue(resultSetCreated.get()); + assertNotNull(statement.getResultSet()); final long cancelStart = System.nanoTime(); statement.cancel(); execution.join(TimeUnit.SECONDS.toMillis(2)); final long cancelMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelStart); System.out.println("SHARED_T9_CANCEL_MILLIS " + cancelMillis); assertFalse(execution.isAlive()); - assertFalse(resultSetCreated.get()); assertNotNull(failure.get()); assertTrue( hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); } awaitCounter("cancellation", 1, Duration.ofSeconds(2)); - assertCounters(2, 0, 0, 1, 1, 1, 1, 0); + assertCounters(2, 0, 0, 1, 1, 1, 1, 1); + } + + @Test + @Order(11) + public void t9ClosingIncompleteResultAttemptsFlightInfoCancellation() throws Exception { + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("cancel-observable")) { + assertTrue(resultSet.next()); + assertEquals(1L, resultSet.getLong("value")); + } + awaitCounter("cancellation", 1, Duration.ofSeconds(2)); + assertCounters(1, 0, 0, 1, 0, 1, 0, 1); } private static Connection connect(final boolean usePollInfo) throws Exception { diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java index e31cccbdf0..c6bdb4d23b 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java @@ -28,12 +28,10 @@ import org.apache.arrow.flight.CancelFlightInfoRequest; import org.apache.arrow.flight.CancelStatus; import org.apache.arrow.flight.FlightDescriptor; -import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.flight.PollInfo; import org.apache.arrow.flight.PutResult; -import org.apache.arrow.flight.Ticket; import org.apache.arrow.flight.sql.impl.FlightSql.CommandPreparedStatementQuery; /** Controllable in-process PollInfo producer used by the JDBC POC conformance tests. */ @@ -238,9 +236,7 @@ private static FlightInfo partialInfo(final FlightInfo finalInfo) { return new FlightInfo( finalInfo.getSchemaOptional().orElse(null), finalInfo.getDescriptor(), - Collections.singletonList( - new FlightEndpoint( - new Ticket("partial-must-not-be-read".getBytes(StandardCharsets.UTF_8)))), + new ArrayList<>(finalInfo.getEndpoints()), -1, -1); } diff --git a/reports/call-site-inventory.md b/reports/call-site-inventory.md index 27f414df6d..7ca52a1abc 100644 --- a/reports/call-site-inventory.md +++ b/reports/call-site-inventory.md @@ -2,7 +2,7 @@ Baseline: Apache Arrow Java `91b4a2ca418ecb47cb8871d97588b19444337eb4`. The baseline `FlightSqlClient` had 14 `FlightClient.getInfo` call shapes representing 13 distinct Flight SQL command families; the two XDBC overloads share one wire command family. Schema-only `getSchema` calls, updates/ingest, actions, `DoPut`, and `DoGet` are not FlightInfo-producing call sites. -The POC routes all 13 families through `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)`. The default hook still makes one `GetFlightInfo` call. JDBC installs a polling subclass that drains PollInfo and returns only the final cumulative FlightInfo. +The POC routes all 13 families through `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)`. The default hook still makes one `GetFlightInfo` call. JDBC installs a polling subclass that can retain continuation state and append newly published endpoints to the existing ResultSet on demand. | # | Wire command family | Baseline `FlightSqlClient` API/call shape | JDBC exposure | POC routing and applicability | | --- | --- | --- | --- | --- | diff --git a/reports/evidence.jsonl b/reports/evidence.jsonl index b672e305e9..c00c25384a 100644 --- a/reports/evidence.jsonl +++ b/reports/evidence.jsonl @@ -1,10 +1,10 @@ {"driver":"jdbc","test":"T1","status":"PASS","command":"SharedServerPollInfoExecutionTest#immediateCompletion","exit_code":0,"assertions":["PollFlightInfo is the default and public JDBC rows are unchanged"],"observations":{"rows":[1,2],"poll":1,"get":0,"original":1,"continuations":[],"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} -{"driver":"jdbc","test":"T2","status":"PASS","command":"SharedServerPollInfoExecutionTest#multiStepCompletion","exit_code":0,"assertions":["The original descriptor is sent once","Each continuation is sent unchanged once","Only final cumulative FlightInfo feeds the endpoint queue"],"observations":{"rows":[1,2,3],"poll":3,"get":0,"original":1,"continuations":["bdx-645-poll/v1/op-000001/1","bdx-645-poll/v1/op-000001/2"],"do_get":3},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} -{"driver":"jdbc","test":"T3","status":"PASS","command":"SharedServerPollInfoExecutionTest#preparedMultiStep","exit_code":0,"assertions":["Prepared parameters bind exactly once before polling","The original prepared descriptor is sent once"],"observations":{"bound_value":41,"rows":[41,42],"bind":1,"poll":3,"get":0,"original":1,"continuations":2,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} +{"driver":"jdbc","test":"T2","status":"PASS","command":"SharedServerPollInfoExecutionTest#multiStepCompletion","exit_code":0,"assertions":["The original descriptor is sent once","Each continuation is sent unchanged once","The first published endpoint is consumed before the next continuation","Only appended endpoints enter the existing ResultSet queue"],"observations":{"rows":[1,2,3],"events":["PollFlightInfo","DoGet","PollFlightInfo","DoGet","PollFlightInfo","DoGet"],"poll":3,"get":0,"original":1,"continuations":["bdx-645-poll/v1/op-000001/1","bdx-645-poll/v1/op-000001/2"],"do_get":3},"log":"orchestrator final shared rerun","limitation":null} +{"driver":"jdbc","test":"T3","status":"PASS","command":"SharedServerPollInfoExecutionTest#preparedMultiStep","exit_code":0,"assertions":["Prepared parameters bind exactly once before polling","The original prepared descriptor is sent once","Prepared endpoints are consumed progressively"],"observations":{"bound_value":41,"rows":[41,42],"bind":1,"poll":3,"get":0,"original":1,"continuations":2,"do_get":2},"log":"orchestrator final shared rerun","limitation":null} {"driver":"jdbc","test":"T4","status":"PASS","command":"SharedServerPollInfoExecutionTest#metadataMultiStep","exit_code":0,"assertions":["DatabaseMetaData.getCatalogs polls transparently and preserves ResultSet shape"],"observations":{"catalog":"bdx_catalog","poll":3,"get":0,"original":1,"continuations":2,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} {"driver":"jdbc","test":"T5","status":"PASS","command":"SharedServerPollInfoExecutionTest#unsupportedFallbackAndCache","exit_code":0,"assertions":["Only initial UNIMPLEMENTED falls back","Unsupported result is cached per command family and connection","Metadata remains independently poll-capable"],"observations":{"direct":{"poll":1,"get":2,"original":1},"metadata":{"poll":3,"get":0,"original":1,"continuations":2}},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} {"driver":"jdbc","test":"T6","status":"PASS","command":"SharedServerPollInfoExecutionTest#connectionOptOut","exit_code":0,"assertions":["usePollInfo=false restores the exact legacy prepared-command GetFlightInfo path"],"observations":{"rows":[1,2],"family":"prepared","poll":0,"get":1,"do_get":1},"log":"reports/raw/shared-server-t1-t9-final.log","limitation":null} -{"driver":"jdbc","test":"T7","status":"PASS","command":"SharedServerPollInfoExecutionTest#unavailableDoesNotFallback; PollInfoExecutionTest continuation UNIMPLEMENTED case","exit_code":0,"assertions":["Initial UNAVAILABLE propagates without fallback","Continuation UNIMPLEMENTED propagates without fallback or re-execution"],"observations":{"initial_unavailable":{"poll":1,"get":0,"original":1,"do_get":0},"continuation_unimplemented":{"poll":2,"get":0}},"log":"reports/raw/shared-server-t1-t9-final.log; orchestrator final focused rerun","limitation":null} +{"driver":"jdbc","test":"T7","status":"PASS","command":"SharedServerPollInfoExecutionTest late-error and unavailable cases; PollInfoExecutionTest continuation UNIMPLEMENTED case","exit_code":0,"assertions":["Initial UNAVAILABLE propagates without fallback","A row published before a late continuation failure remains delivered","The late failure surfaces at the next ResultSet.next boundary","Continuation UNIMPLEMENTED does not fall back or re-execute"],"observations":{"initial_unavailable":{"poll":1,"get":0,"original":1,"do_get":0},"late_error":{"poll":2,"get":0,"do_get":1,"rows_before_error":[1]},"continuation_unimplemented":{"poll":2,"get":0}},"log":"orchestrator final focused/shared rerun","limitation":null} {"driver":"jdbc","test":"T8","status":"PASS","command":"SharedServerPollInfoExecutionTest timeout case; PollInfoExecutionTest deadline and blocked-bind cases","exit_code":0,"assertions":["One absolute deadline spans parameter upload, polls, and first endpoint retrieval","Exact JDBC timeout exception contract is preserved"],"observations":{"shared_elapsed_ms":1008,"shared_poll":1,"active_call_terminations":1,"focused_poll":2,"prepared_bind":1,"exception":"SQLTimeoutException","message":"Query timed out after 1 SECONDS"},"log":"reports/raw/pollinfo-focused-test-final.log; orchestrator final focused/shared reruns","limitation":"Existing schema preparation remains outside the execution context."} -{"driver":"jdbc","test":"T9","status":"PASS","command":"SharedServerPollInfoExecutionTest cancellation case; PollInfoExecutionTest pre-ResultSet cancellation case","exit_code":0,"assertions":["Statement.cancel interrupts an active continuation before ResultSet construction","Best-effort CancelFlightInfo uses the latest cumulative FlightInfo"],"observations":{"shared_cancel_elapsed_ms":9,"local_cancel_elapsed_ms":2,"poll":2,"get":0,"cancel":1,"active_call_terminations":1,"result_set_before_cancel":null},"log":"reports/raw/shared-server-t1-t9-final.log; reports/raw/pollinfo-focused-test-final.log; reports/raw/avatica-statement-bytecode.log","limitation":"The cleanup action is synchronous but independently bounded to one second."} -{"driver":"jdbc","test":"T10","status":"PASS","command":"mvn flight-sql test; mvn flight-sql-jdbc-core test; focused/shared tests; package; git diff --check","exit_code":0,"assertions":["Relevant shared Flight SQL and JDBC suites pass after review corrections"],"observations":{"flight_sql":{"tests":97,"failures":0,"errors":0,"skipped":0},"jdbc_core":{"tests":1267,"failures":0,"errors":0,"skipped":54},"focused":{"tests":12,"failures":0,"errors":0},"shared":{"tests":9,"failures":0,"errors":0}},"log":"reports/raw/t10-flight-sql-tests.log; reports/raw/t10-jdbc-core-tests-final.log; orchestrator final reruns","limitation":"The POC adds visible helper surfaces in published artifacts; production visibility/API design remains required."} +{"driver":"jdbc","test":"T9","status":"PASS","command":"SharedServerPollInfoExecutionTest cancellation and incomplete-close cases; PollInfoExecutionTest cancellation cases","exit_code":0,"assertions":["Statement.cancel interrupts polling before result construction and at an existing read boundary","ResultSet.close before completion attempts best-effort CancelFlightInfo exactly once","Cleanup failure does not fail close"],"observations":{"get":0,"cancel":1,"active_call_terminations":1,"read_boundary":"ResultSet.next"},"log":"orchestrator final focused/shared rerun","limitation":"The cleanup action is synchronous but independently bounded to one second."} +{"driver":"jdbc","test":"T10","status":"PASS","command":"mvn flight-sql test; mvn flight-sql-jdbc-core test; focused/shared tests; package; git diff --check","exit_code":0,"assertions":["Relevant shared Flight SQL and JDBC suites pass after progressive-delivery changes"],"observations":{"flight_sql":{"tests":97,"failures":0,"errors":0,"skipped":0},"jdbc_core":{"tests":1267,"failures":0,"errors":0,"skipped":54},"focused":{"tests":12,"failures":0,"errors":0},"shared":{"tests":11,"failures":0,"errors":0}},"log":"reports/raw/t10-flight-sql-tests.log; reports/raw/t10-jdbc-core-tests-final.log; orchestrator final reruns","limitation":"The POC adds visible helper surfaces in published artifacts; production visibility/API design remains required."} diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md index 010791c0ad..e1353511cc 100644 --- a/reports/jdbc-report.md +++ b/reports/jdbc-report.md @@ -4,13 +4,13 @@ **Feasible with documented limitations** -The unchanged JDBC interfaces can synchronously execute direct, prepared, and metadata Flight SQL operations through PollFlightInfo, follow continuations to completion, and give only the final cumulative FlightInfo to the existing ResultSet path. This was demonstrated with focused in-process producers and T1-T9 black-box runs against the shared real Flight SQL gRPC fixture. The limitation is production packaging: the POC introduces visible Java helper surfaces across the published `flight-sql` and `flight-sql-jdbc-core` artifacts; those surfaces need an intentional internal/public API design before landing. +The unchanged JDBC interfaces can execute direct, prepared, and metadata Flight SQL operations through PollFlightInfo and expose newly published endpoints through the existing `ResultSet` before query completion. Continuation polling is demand-driven at `ResultSet.next()`. This was demonstrated with focused in-process producers and black-box runs against the shared real Flight SQL gRPC fixture. The limitation is production packaging: the POC introduces visible Java helper surfaces across the published `flight-sql` and `flight-sql-jdbc-core` artifacts; those surfaces need an intentional internal/public API design before landing. ## Question answered Can Arrow Java JDBC make PollInfo the transparent default without changing `java.sql` signatures or result types, while retaining initial-UNIMPLEMENTED-only fallback, per-family capability isolation, one timeout, cancellation before ResultSet construction, and a connection opt-out? -The executable answer is yes. The POC remains experimental and uncommitted on local branch `bdx-645-pollinfo-poc`; nothing was pushed and no Jira/PR state was changed. +The executable answer is yes. The POC is published for review on branch `bdx-645-pollinfo-poc` in `xborder/arrow-java` PR #21. ## Baseline and environment @@ -43,7 +43,7 @@ Each JDBC connection installs a polling FlightSqlClient wrapper. For a FlightInf 1. Derives the capability-cache key from the original Flight SQL `Any.type_url`. 2. Sends the original descriptor to PollFlightInfo once. 3. Sends every returned opaque continuation unchanged once until no continuation remains. -4. Stores the latest cumulative FlightInfo only for cancellation and returns only the final cumulative FlightInfo to the existing endpoint queue/ResultSet path. +4. Hands the first published endpoint to the existing ResultSet, retains the continuation, and appends only newly published endpoints when the reader asks for more rows. 5. Falls back to GetFlightInfo only when the initial poll is `UNIMPLEMENTED`, then caches that family as unsupported on the connection. No continuation error and no other initial error falls back. Direct JDBC statements still use a prepared action for schema/type discovery, but with polling enabled their query-result execution uses `CommandStatementQuery`. With `usePollInfo=false`, the handler deliberately restores the exact pre-POC `CommandPreparedStatementQuery` execution path; both focused and shared-server T6 tests assert that command family. The update branch still invokes the existing prepared `executeUpdate`; the full `ArrowFlightStatementExecuteUpdateTest` passes. Explicit JDBC prepared queries retain `CommandPreparedStatementQuery`; their parameter `DoPut` occurs once before the single original poll descriptor. @@ -62,66 +62,26 @@ Baseline Avatica has a real pre-ResultSet gap: its bytecode shows `AvaticaStatem ```mermaid sequenceDiagram - autonumber - actor App as JDBC application - participant API as Statement / PreparedStatement / DatabaseMetaData - participant Client as ArrowFlightSqlClientHandler - participant Poller as PollInfoOperation + FlightSqlClient + participant App as JDBC application + participant Driver as JDBC driver participant Server as Flight SQL server - participant Result as Existing ResultSet / DoGet path - - App->>API: executeQuery() or metadata call - API->>Client: Execute command with query timeout - opt Parameterized PreparedStatement - Client->>Server: DoPut(bound parameters) exactly once - Server-->>Client: Bound prepared handle - end - alt usePollInfo=false or family cached unsupported - Client->>Server: GetFlightInfo(original descriptor) - Server-->>Client: Final FlightInfo - Client->>Result: Final FlightInfo - else PollInfo enabled - Client->>Poller: Resolve original descriptor - Poller->>Server: PollFlightInfo(original descriptor) - alt Initial response is UNIMPLEMENTED - Server-->>Poller: UNIMPLEMENTED - Poller->>Poller: Cache command family as unsupported - Poller->>Server: GetFlightInfo(original descriptor) - Server-->>Poller: Final FlightInfo - Poller->>Result: Final FlightInfo - else Error other than initial UNIMPLEMENTED - Server-->>Poller: UNAVAILABLE / auth / query / continuation error - Poller-->>API: Propagate error, no fallback - API-->>App: SQLException - else Polling accepted - Server-->>Poller: Cumulative PollInfo + continuation - loop While continuation exists - Poller->>Server: PollFlightInfo(continuation descriptor) - Server-->>Poller: New cumulative PollInfo + next continuation - end - alt Polling completes - Poller->>Result: Final cumulative FlightInfo only - else Statement.cancel() or deadline during active poll - App->>API: cancel() or timeout expires - API->>Poller: Cancel operation context - Poller-->>Server: Cancel active PollFlightInfo RPC - opt A cumulative FlightInfo is known - Poller->>Server: CancelFlightInfo(latest info), bounded cleanup - end - Poller-->>App: SQLException / SQLTimeoutException - end - end - end - opt Final FlightInfo was produced - loop Each final endpoint - Result->>Server: DoGet(ticket) - Server-->>Result: Arrow record batches - end - Result-->>App: Existing JDBC schema and rows - end + App->>Driver: executeQuery + Driver->>Server: PollFlightInfo original + Server-->>Driver: Endpoint 1 and continuation + Driver-->>App: Existing ResultSet + App->>Driver: next + Driver->>Server: DoGet endpoint 1 + Server-->>Driver: Row 1 + Driver-->>App: Row 1 + App->>Driver: next + Driver->>Server: PollFlightInfo continuation + Server-->>Driver: Endpoint 1 plus endpoint 2 + Driver->>Server: DoGet endpoint 2 + Server-->>Driver: Row 2 + Driver-->>App: Row 2 ``` -The key JDBC boundary is the final-only handoff to the existing ResultSet path. Prepared binding occurs once inside the operation context, and `Statement.cancel()` can interrupt an active poll before a ResultSet exists. +Prepared binding occurs once inside the operation context. A late continuation error is surfaced at the next `ResultSet.next()` boundary, and `Statement.cancel()` or closing an incomplete result attempts best-effort cancellation. ## T1-T10 results @@ -130,14 +90,14 @@ Every T1-T9 case has shared-server evidence wherever the fixture supports the as | Test | Result | Evidence summary | | --- | --- | --- | | T1 immediate | PASS | Rows `[1,2]`; poll 1, GetFlightInfo 0, original 1, continuation 0, DoGet 1. | -| T2 multi-step | PASS | Rows `[1,2,3]`; three polls are exactly one original plus two continuations; ordered descriptors `/op-000001/1`, then `/op-000001/2`; GetFlightInfo 0; DoGet 3. Partial cumulative endpoints were not consumed (otherwise DoGet would exceed 3). | +| T2 progressive multi-step | PASS | Rows `[1,2,3]`; event order is `Poll, DoGet, Poll, DoGet, Poll, DoGet`, proving each published endpoint is consumed before the next continuation and before query completion. | | T3 prepared | PASS | Bound value 41 yielded `[41,42]`; bind 1; poll 3; original 1; continuation 2; GetFlightInfo 0. | | T4 metadata | PASS | `DatabaseMetaData.getCatalogs()` returned `bdx_catalog`; poll 3; original 1; continuation 2. | | T5 fallback/cache | PASS | Two direct executions produced direct poll 1/GetFlightInfo 2, proving connection cache reuse; metadata on the same connection still polled three times and never used GetFlightInfo. | | T6 opt-out | PASS | `usePollInfo=false`; poll 0, GetFlightInfo 1, normal rows `[1,2]`; the server records the legacy prepared command family. | | T7 non-fallback failure | PASS | Initial `UNAVAILABLE` propagated with poll 1/GetFlightInfo 0/DoGet 0. A focused continuation-`UNIMPLEMENTED` case propagated after two polls with GetFlightInfo 0. | | T8 timeout | PASS | Shared blocked poll ended at the one-second deadline with active termination 1 and the exact JDBC timeout contract. Focused two-poll and prepared blocked-bind cases prove the deadline does not reset and covers parameter upload. | -| T9 cancellation | PASS | ResultSet was null during the active continuation; cancel returned in 9 ms shared/2 ms local; shared cancellation 1, active termination 1, GetFlightInfo 0. | +| T9 cancellation and close | PASS | Cancellation works before result construction and while an existing ResultSet waits for another endpoint. Closing an incomplete ResultSet attempts one best-effort `CancelFlightInfo`. | | T10 regression/build | PASS | Flight SQL: 97 tests, zero failures/errors. Final JDBC core rerun after review corrections: 1,267 tests, zero failures/errors, 54 existing skips. | ## Regression details @@ -168,7 +128,7 @@ All commands were run locally with RTK and no remote mutation. | --- | --- | --- | | `mvn -pl flight/flight-sql -DskipTests install` | 0; shared hook compiled, checked, installed locally | `reports/raw/install-flight-sql-hook.log` | | `mvn -pl flight/flight-sql-jdbc-core -Dtest=PollInfoExecutionTest test` | 0; final focused rerun 12/12 | original log plus orchestrator validation | -| `mvn -pl flight/flight-sql-jdbc-core -Dtest=SharedServerPollInfoExecutionTest -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32347 -Dpollinfo.shared.controlPort=32348 test` | 0; 9/9 | `reports/raw/shared-server-t1-t9-final.log` | +| `mvn -pl flight/flight-sql-jdbc-core -Dtest=SharedServerPollInfoExecutionTest -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32347 -Dpollinfo.shared.controlPort=32348 test` | 0; 11/11 | orchestrator final rerun | | `mvn -pl flight/flight-sql test` | 0; 97/97 | `reports/raw/t10-flight-sql-tests.log` | | `mvn -pl flight/flight-sql-jdbc-core test` | 0; final rerun 1,267 tests, 54 skipped | original log plus orchestrator validation | | `mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -DskipTests package` | 0; both artifacts compiled, formatted, checked, and packaged | `reports/raw/t10-final-package.log` | @@ -216,7 +176,7 @@ Test/evidence support: ### Arrow Java Flight SQL shared library 1. Define an intentional descriptor-resolution abstraction with compatibility review, avoiding an accidental protected-hook collision in `FlightSqlClient`. -2. Place the PollInfo operation state/capability cache behind non-public or explicitly supported shared-library APIs, with final-only handoff and initial-UNIMPLEMENTED semantics covered at that layer. +2. Place the PollInfo operation state/capability cache behind non-public or explicitly supported shared-library APIs, with progressive append-only endpoint handoff and initial-UNIMPLEMENTED semantics covered at that layer. 3. Add shared-library unit tests for all command constructors, default producer completion, continuation validation, and optional bounded unchanged-response delay. ### JDBC integration and hardening From 6d72dc09b723b5c426bd14fbe4995d0dc2c18dba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Fri, 11 Sep 2026 13:20:39 +0100 Subject: [PATCH 19/39] BDX-645: record progressive JDBC regression --- reports/evidence.jsonl | 2 +- reports/jdbc-report.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/reports/evidence.jsonl b/reports/evidence.jsonl index c00c25384a..3fab5a4f11 100644 --- a/reports/evidence.jsonl +++ b/reports/evidence.jsonl @@ -7,4 +7,4 @@ {"driver":"jdbc","test":"T7","status":"PASS","command":"SharedServerPollInfoExecutionTest late-error and unavailable cases; PollInfoExecutionTest continuation UNIMPLEMENTED case","exit_code":0,"assertions":["Initial UNAVAILABLE propagates without fallback","A row published before a late continuation failure remains delivered","The late failure surfaces at the next ResultSet.next boundary","Continuation UNIMPLEMENTED does not fall back or re-execute"],"observations":{"initial_unavailable":{"poll":1,"get":0,"original":1,"do_get":0},"late_error":{"poll":2,"get":0,"do_get":1,"rows_before_error":[1]},"continuation_unimplemented":{"poll":2,"get":0}},"log":"orchestrator final focused/shared rerun","limitation":null} {"driver":"jdbc","test":"T8","status":"PASS","command":"SharedServerPollInfoExecutionTest timeout case; PollInfoExecutionTest deadline and blocked-bind cases","exit_code":0,"assertions":["One absolute deadline spans parameter upload, polls, and first endpoint retrieval","Exact JDBC timeout exception contract is preserved"],"observations":{"shared_elapsed_ms":1008,"shared_poll":1,"active_call_terminations":1,"focused_poll":2,"prepared_bind":1,"exception":"SQLTimeoutException","message":"Query timed out after 1 SECONDS"},"log":"reports/raw/pollinfo-focused-test-final.log; orchestrator final focused/shared reruns","limitation":"Existing schema preparation remains outside the execution context."} {"driver":"jdbc","test":"T9","status":"PASS","command":"SharedServerPollInfoExecutionTest cancellation and incomplete-close cases; PollInfoExecutionTest cancellation cases","exit_code":0,"assertions":["Statement.cancel interrupts polling before result construction and at an existing read boundary","ResultSet.close before completion attempts best-effort CancelFlightInfo exactly once","Cleanup failure does not fail close"],"observations":{"get":0,"cancel":1,"active_call_terminations":1,"read_boundary":"ResultSet.next"},"log":"orchestrator final focused/shared rerun","limitation":"The cleanup action is synchronous but independently bounded to one second."} -{"driver":"jdbc","test":"T10","status":"PASS","command":"mvn flight-sql test; mvn flight-sql-jdbc-core test; focused/shared tests; package; git diff --check","exit_code":0,"assertions":["Relevant shared Flight SQL and JDBC suites pass after progressive-delivery changes"],"observations":{"flight_sql":{"tests":97,"failures":0,"errors":0,"skipped":0},"jdbc_core":{"tests":1267,"failures":0,"errors":0,"skipped":54},"focused":{"tests":12,"failures":0,"errors":0},"shared":{"tests":11,"failures":0,"errors":0}},"log":"reports/raw/t10-flight-sql-tests.log; reports/raw/t10-jdbc-core-tests-final.log; orchestrator final reruns","limitation":"The POC adds visible helper surfaces in published artifacts; production visibility/API design remains required."} +{"driver":"jdbc","test":"T10","status":"PASS","command":"mvn -pl flight/flight-sql-jdbc-core test; focused/shared tests; git diff --check","exit_code":0,"assertions":["Full JDBC core passes after progressive-delivery changes","Focused and shared progressive suites pass"],"observations":{"jdbc_core":{"tests":1269,"failures":0,"errors":0,"skipped":56},"focused":{"tests":12,"failures":0,"errors":0},"shared":{"tests":11,"failures":0,"errors":0}},"log":"orchestrator final reruns","limitation":"The POC adds visible helper surfaces in published artifacts; production visibility/API design remains required."} diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md index e1353511cc..b1fcde4663 100644 --- a/reports/jdbc-report.md +++ b/reports/jdbc-report.md @@ -98,7 +98,7 @@ Every T1-T9 case has shared-server evidence wherever the fixture supports the as | T7 non-fallback failure | PASS | Initial `UNAVAILABLE` propagated with poll 1/GetFlightInfo 0/DoGet 0. A focused continuation-`UNIMPLEMENTED` case propagated after two polls with GetFlightInfo 0. | | T8 timeout | PASS | Shared blocked poll ended at the one-second deadline with active termination 1 and the exact JDBC timeout contract. Focused two-poll and prepared blocked-bind cases prove the deadline does not reset and covers parameter upload. | | T9 cancellation and close | PASS | Cancellation works before result construction and while an existing ResultSet waits for another endpoint. Closing an incomplete ResultSet attempts one best-effort `CancelFlightInfo`. | -| T10 regression/build | PASS | Flight SQL: 97 tests, zero failures/errors. Final JDBC core rerun after review corrections: 1,267 tests, zero failures/errors, 54 existing skips. | +| T10 regression/build | PASS | Flight SQL: 97 tests, zero failures/errors. Final JDBC core rerun after progressive changes: 1,269 tests, zero failures/errors, 56 skips. | ## Regression details @@ -130,7 +130,7 @@ All commands were run locally with RTK and no remote mutation. | `mvn -pl flight/flight-sql-jdbc-core -Dtest=PollInfoExecutionTest test` | 0; final focused rerun 12/12 | original log plus orchestrator validation | | `mvn -pl flight/flight-sql-jdbc-core -Dtest=SharedServerPollInfoExecutionTest -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32347 -Dpollinfo.shared.controlPort=32348 test` | 0; 11/11 | orchestrator final rerun | | `mvn -pl flight/flight-sql test` | 0; 97/97 | `reports/raw/t10-flight-sql-tests.log` | -| `mvn -pl flight/flight-sql-jdbc-core test` | 0; final rerun 1,267 tests, 54 skipped | original log plus orchestrator validation | +| `mvn -pl flight/flight-sql-jdbc-core test` | 0; final rerun 1,269 tests, 56 skipped | final orchestrator validation | | `mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -DskipTests package` | 0; both artifacts compiled, formatted, checked, and packaged | `reports/raw/t10-final-package.log` | | focused OAuth/TLS rerun | 0; 50/50 after expected-method fix and test-data initialization | `reports/raw/t10-prior-failures-rerun.log` | | `git diff --check` | 0 | final command output/working-tree check | From 394992976ae560a04629f70c56f9a35950deb139 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Wed, 25 Nov 2026 21:22:34 +0000 Subject: [PATCH 20/39] BDX-645: adapt JDBC PollInfo POC to upstream main After rebasing onto apache/arrow-java main (10c55b9c8): - Make PreparedStatement.executeQuery(PollInfoOperation) a default method delegating to executeQuery(), so existing implementers (e.g. the AvaticaParameterBinderTest stub added upstream) keep compiling. - Apply Spotless formatting. Co-Authored-By: Claude Opus 5.5 --- .../ArrowFlightJdbcFlightStreamResultSet.java | 10 +++------- .../arrow/driver/jdbc/ArrowFlightStatement.java | 3 ++- .../jdbc/client/ArrowFlightSqlClientHandler.java | 15 +++++++++------ .../driver/jdbc/client/PollInfoOperation.java | 6 ++---- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 0bff27b5d1..7bab7b6750 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -91,8 +91,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet final SQLTimeoutException jdbcTimeout = new SQLTimeoutException( String.format( - "Query timed out after %d %s", - statement.getQueryTimeout(), TimeUnit.SECONDS)); + "Query timed out after %d %s", statement.getQueryTimeout(), TimeUnit.SECONDS)); jdbcTimeout.initCause(e); throw jdbcTimeout; } @@ -417,9 +416,7 @@ private void enqueueNewEndpoints(final FlightInfo updatedFlightInfo) throws SQLE } final List appendedEndpoints = new ArrayList<>( - updatedFlightInfo - .getEndpoints() - .subList(consumedEndpointCount, updatedEndpointCount)); + updatedFlightInfo.getEndpoints().subList(consumedEndpointCount, updatedEndpointCount)); final FlightInfo appendedInfo = new FlightInfo( updatedSchema, @@ -462,8 +459,7 @@ private boolean loadNextPublishedEndpoint() throws SQLException { final SQLTimeoutException timeout = new SQLTimeoutException( String.format( - "Query timed out after %d %s", - statement.getQueryTimeout(), TimeUnit.SECONDS)); + "Query timed out after %d %s", statement.getQueryTimeout(), TimeUnit.SECONDS)); timeout.initCause(e); throw timeout; } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java index cc70dfd0e1..c0efbd8a02 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java @@ -190,7 +190,8 @@ void finishPollInfoOperation(final PollInfoOperation operation) { } private ArrowFlightPreparedStatement preparedDelegate() { - final AvaticaStatement current = ((ArrowFlightConnection) connection).statementMap.get(handle.id); + final AvaticaStatement current = + ((ArrowFlightConnection) connection).statementMap.get(handle.id); return current instanceof ArrowFlightPreparedStatement ? (ArrowFlightPreparedStatement) current : null; diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index 50dbef2ba9..e8a65f15f1 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -417,8 +417,13 @@ public interface PreparedStatement extends AutoCloseable { */ FlightInfo executeQuery() throws SQLException; - /** Execute using a statement-owned timeout/cancellation operation. */ - FlightInfo executeQuery(PollInfoOperation operation) throws SQLException; + /** + * Execute using a statement-owned timeout/cancellation operation. Implementations that do not + * support PollInfo fall back to {@link #executeQuery()}. + */ + default FlightInfo executeQuery(PollInfoOperation operation) throws SQLException { + return executeQuery(); + } /** * Executes a {@link StatementType#UPDATE} query. @@ -788,8 +793,7 @@ private FlightInfo getInfo( org.apache.arrow.flight.FlightDescriptor descriptor = originalDescriptor; boolean initialPoll = true; operation.configure( - descriptorForPoll -> - client.pollInfo(descriptorForPoll, operation.options(options)), + descriptorForPoll -> client.pollInfo(descriptorForPoll, operation.options(options)), () -> cancelFlightInfoBestEffort(operation, options)); try { while (true) { @@ -807,8 +811,7 @@ private FlightInfo getInfo( if (initialPoll && e.status().code() == FlightStatusCode.UNIMPLEMENTED) { unsupportedFamilies.add(family); final FlightInfo flightInfo = - operation.call( - () -> client.getInfo(originalDescriptor, operation.options(options))); + operation.call(() -> client.getInfo(originalDescriptor, operation.options(options))); operation.complete(flightInfo); return flightInfo; } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java index fb4f9a3064..6495f5081d 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -110,8 +110,7 @@ boolean isCancelled() { } void configure( - final Function poller, - final Runnable cancelFlightInfo) { + final Function poller, final Runnable cancelFlightInfo) { this.poller = poller; this.cancelFlightInfo = cancelFlightInfo; } @@ -216,8 +215,7 @@ private static int endpointCount(final FlightInfo flightInfo) { return flightInfo == null ? 0 : flightInfo.getEndpoints().size(); } - private static void validateAppendOnly( - final FlightInfo previous, final FlightInfo current) { + private static void validateAppendOnly(final FlightInfo previous, final FlightInfo current) { if (previous == null) { return; } From b444a256006897ebf079dd47596ad978cb4701cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Wed, 25 Nov 2026 21:27:27 +0000 Subject: [PATCH 21/39] BDX-645: add JDBC production go/no-go and rebase re-validation Add reports/production-recommendation.md: production verdict, behavioral limitations, GetFlightInfo call-site coverage after the rebase onto upstream main, minimal follow-up list, and before/after test results. Point the earlier report and call-site inventory at it. Co-Authored-By: Claude Opus 5.5 --- reports/call-site-inventory.md | 2 + reports/jdbc-report.md | 2 + reports/production-recommendation.md | 106 +++++++++++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 reports/production-recommendation.md diff --git a/reports/call-site-inventory.md b/reports/call-site-inventory.md index 7ca52a1abc..db3c346008 100644 --- a/reports/call-site-inventory.md +++ b/reports/call-site-inventory.md @@ -1,5 +1,7 @@ # Arrow Java FlightInfo call-site inventory +> **2026-11-25:** this report describes the POC at base `91b4a2ca4`. After the rebase onto upstream `main` (`10c55b9c8`), the `prepareDirect` path is gone, because upstream GH-62 already sends `CommandStatementQuery` for direct `executeQuery`, and the opt-out direct path now uses `CommandStatementQuery`. For the current mapping, re-validation results and the production go/no-go, see [`production-recommendation.md`](production-recommendation.md). + Baseline: Apache Arrow Java `91b4a2ca418ecb47cb8871d97588b19444337eb4`. The baseline `FlightSqlClient` had 14 `FlightClient.getInfo` call shapes representing 13 distinct Flight SQL command families; the two XDBC overloads share one wire command family. Schema-only `getSchema` calls, updates/ingest, actions, `DoPut`, and `DoGet` are not FlightInfo-producing call sites. The POC routes all 13 families through `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)`. The default hook still makes one `GetFlightInfo` call. JDBC installs a polling subclass that can retain continuation state and append newly published endpoints to the existing ResultSet on demand. diff --git a/reports/jdbc-report.md b/reports/jdbc-report.md index b1fcde4663..d6ddb433ca 100644 --- a/reports/jdbc-report.md +++ b/reports/jdbc-report.md @@ -1,5 +1,7 @@ # BDX-645 Arrow Java JDBC PollInfo feasibility report +> **2026-11-25:** this report describes the POC at base `91b4a2ca4`. After the rebase onto upstream `main` (`10c55b9c8`), the `prepareDirect` path is gone, because upstream GH-62 already sends `CommandStatementQuery` for direct `executeQuery`, and the opt-out direct path now uses `CommandStatementQuery`. For the current mapping, re-validation results and the production go/no-go, see [`production-recommendation.md`](production-recommendation.md). + ## Verdict **Feasible with documented limitations** diff --git a/reports/production-recommendation.md b/reports/production-recommendation.md new file mode 100644 index 0000000000..26ffef22b2 --- /dev/null +++ b/reports/production-recommendation.md @@ -0,0 +1,106 @@ +# BDX-645 JDBC: production go/no-go and follow-ups + +Driver: Arrow Flight SQL JDBC (`apache/arrow-java`, modules `flight-sql` and `flight-sql-jdbc-core`). +POC branch: `bdx-645-pollinfo-poc` ([xborder/arrow-java#21](https://github.com/xborder/arrow-java/pull/21)). +Detailed evidence: [`jdbc-report.md`](jdbc-report.md), [`call-site-inventory.md`](call-site-inventory.md), [`evidence.jsonl`](evidence.jsonl). + +## Recommendation: GO, as a production change built from this POC; not mergeable as-is + +PollInfo-by-default works in JDBC without changing any `java.sql` signature or result type. Direct, prepared and metadata queries all went through `PollFlightInfo` against both in-process producers and the shared Go conformance server. The contract held: send the original descriptor once, bind once, fall back only on an initial `UNIMPLEMENTED`, cache per family, offer an opt-out, use one deadline, and let cancel work before the `ResultSet` exists. Progressive endpoint consumption at `ResultSet.next()` also works. + +The branch has been rebased onto current upstream `main` (see "Rebase onto upstream main" below). It is still not ready to merge, for two reasons: + +1. **The public API surface is accidental.** The POC adds a protected `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)` in the published `flight-sql` artifact. That method can collide with subclasses that already exist downstream. It also adds a public `PollInfoOperation` and public handler and builder methods in `flight-sql-jdbc-core`. All of this needs an intentional design and an upstream Apache discussion before it lands. +2. **Contract item 12 was not implemented.** `PollInfoOperation.pollNextAvailable()` loops with no delay while the server keeps returning responses that add no endpoints. It relies entirely on the server to long-poll. A server that answers immediately makes the loop spin, and with no statement timeout set, nothing bounds it. + +## Documented limitations (behavioral) + +- **Late errors move to `ResultSet.next()`.** In progressive mode, `executeQuery` returns once the first endpoint is published. A query that fails afterwards raises `SQLException` from `next()`, not from `executeQuery`. JDBC allows this, but applications that treat a successful `executeQuery` as a successful query will see different behavior. Production needs an explicit decision here, because the ticket rules out an opt-in: either progressive by default, or final-only by default with progressive behind a property. +- **The deadline excludes schema preparation.** The single deadline and cancellable context cover the parameter `DoPut`, every poll and the first endpoint wait. They do not cover the earlier schema/prepare action. +- **CancelFlightInfo needs a payload.** Best-effort `CancelFlightInfo` is only possible after at least one `PollInfo` has returned a `FlightInfo`. Cancelling a blocked initial poll terminates the RPC but sends no server-side cancel. +- **Cleanup is synchronous.** The cancel cleanup call is bounded to one second, but it runs on the caller's thread. A slow server can delay the delivery of a timeout or cancel by up to that second. +- **The capability cache is scoped to the handler.** Unsupported families are cached per `ArrowFlightSqlClientHandler`, keyed by Flight SQL command `type_url`. Pooled or reused physical connections have not been tested. +- **The opt-out name differs from the ticket.** The ticket suggested `usePollFlightInfo=false`; the POC implements `usePollInfo=false`. Pick one name before release and document it. + +## GetFlightInfo call-site coverage + +All 13 Flight SQL command families (14 call shapes) go through the shared hook. Coverage differs by family: + +| Coverage | Families | +| --- | --- | +| Black-box tested against the shared server | `CommandStatementQuery` (direct), `CommandPreparedStatementQuery` (prepared), `CommandGetCatalogs` | +| Exposed through JDBC; covered only by existing JDBC regressions, with no PollInfo-specific scenario | `CommandGetDbSchemas`, `CommandGetSqlInfo`, `CommandGetTables`, `CommandGetPrimaryKeys`, `CommandGetExportedKeys`, `CommandGetImportedKeys`, `CommandGetCrossReference`, `CommandGetTableTypes` | +| Routed through the hook but not reachable from JDBC (not exercised) | `CommandStatementSubstraitPlan`, `CommandGetXdbcTypeInfo` (both overloads) | +| Not applicable (no `FlightInfo`) | updates and ingest (`DoPut` / update actions), schema-only `GetSchema`, `DoGet` | + +After the rebase, the JDBC entry points map to wire commands as follows: + +| JDBC call | Wire command (upstream after GH-62) | Polling hook | +| --- | --- | --- | +| `Statement.executeQuery(String)` | `CommandStatementQuery`, with no prepare | `ArrowFlightSqlClientHandler.getInfo(String, PollInfoOperation)` (new overload of the upstream direct path) | +| `Statement.execute(String)` | `CommandPreparedStatementQuery` (GH-62 deliberately keeps this prepared) | `ArrowFlightPreparedStatement.executeFlightInfoQuery`, reached through the statement's prepared delegate | +| `PreparedStatement.executeQuery()` | `CommandPreparedStatementQuery` after a single parameter `DoPut` | `ArrowFlightPreparedStatement.executeFlightInfoQuery` | +| `DatabaseMetaData.*` | metadata commands | `PollingFlightSqlClient.getInfo` hook, with a per-call operation | + +The POC's `prepareDirect` path was removed in the rebase, because GH-62 already made direct `executeQuery` send `CommandStatementQuery` without a prepare. One consequence: with `usePollInfo=false`, direct `executeQuery` now issues `GetFlightInfo` on `CommandStatementQuery` (upstream's new baseline), no longer on `CommandPreparedStatementQuery`. The two T6 assertions were updated to match. + +## Minimal follow-up list + +### Shared library (`flight-sql`), needs upstream design agreement +1. Replace the protected `getInfo` hook with an intentional descriptor-resolution abstraction, or with a package-private or `@InternalApi` seam, and run a compatibility review. +2. Move the poll loop into a reusable component: continuation handling, append-only endpoint validation, initial-`UNIMPLEMENTED` fallback and the family cache. Unit-test it against every command constructor and against the default producer (which returns an already-completed `PollInfo`). +3. Add a small bounded delay or backoff for consecutive successful responses that add no endpoints (contract item 12). + +### JDBC (`flight-sql-jdbc-core`) +4. Replace the POC's `ArrowFlightStatement` → prepared-delegate lookup through `statementMap` (used for cancel, timeout and operation lookup on the `Statement.execute(String)` path) with an explicit owner reference. +5. Make `PollInfoOperation` and the handler and builder additions package-private. Keep only the documented connection property. +6. Decide the default behavior for late errors (progressive or final-only). Decide whether the operation deadline should start at `prepareAndExecute` entry so that it includes schema preparation. +7. Run best-effort `CancelFlightInfo` off the caller's thread, or with a tighter bound, so it can never delay a timeout or cancel. +8. Add tests for pooled connections and the family cache, and for races between cancel, close and an in-flight poll. +9. Add PollInfo black-box scenarios for at least one more metadata family (for example `getTables`) once the fixture supports it. +10. Keep the POC's regression tests: direct select and update, OAuth on `POLL_FLIGHT_INFO`, the exact timeout message, prepared single-bind, pre-`ResultSet` cancel, and close of an incomplete result. + +## Rebase onto upstream main (2026-11-25) + +The branch was rebased from base `91b4a2ca4` onto `apache/arrow-java` `main` at `10c55b9c8`, which is 164 upstream commits. All five POC commits were kept. Six JDBC files conflicted, with 15 hunks in total, mostly against GH-62 (`054c7b8b7`). The rest were against GH-1268, GH-1499/GH-1500, GH-1232 and GH-1319/GH-1442. Resolutions: + +- `ArrowFlightMetaImpl`: took upstream's version. The POC's `prepareForHandle(..., directExecution)` and `prepareDirect` usage are gone. +- `ArrowFlightConnection` and the handler imports: took upstream and re-added `.withPollInfo(config.usePollInfo())`. +- `ArrowFlightSqlClientHandler`: removed `prepareDirect` and the `directExecution` branching. Added `getInfo(String, PollInfoOperation)` for upstream's direct path. Made `PreparedStatement.executeQuery(PollInfoOperation)` a `default` method, because a test stub added upstream implements the interface. +- `ArrowFlightStatement`: the direct `executeFlightInfoQuery` branch now runs inside a progressive `PollInfoOperation`. `cancel()`, `remainingQueryTimeoutNanos()`, `activePollInfoOperation()` and `finishPollInfoOperation()` delegate to the prepared statement that shares the handle when `Statement.execute(String)` used the prepared path. +- `ArrowFlightPreparedStatement`: kept upstream's `ensurePrepared()`, closable resources and builder, and added the POC's operation lifecycle. +- `ArrowFlightJdbcFlightStreamResultSet`: merged upstream's cancel normalization (`cancelled` flag, the closed-queue exception becomes "Statement canceled", `enqueueEndpointData`) with the POC's progressive append-only enqueue and remaining-deadline handling. The cancelled/closed-queue check runs before a continuation poll. A `CANCELLED` continuation after cancel now also surfaces as "Statement canceled". +- Tests: the two T6 opt-out assertions now expect `CommandStatementQuery`, which is upstream's new legacy path. + +Only the final commit was compiled. The intermediate rebased commits were not built individually. + +## Re-validation (2026-11-25) + +Environment: macOS arm64, Java 21.0.10, Maven 3.9.10. Maven 3.10.0 fails on the repo's Develocity extension, and the old `git-commit-id-plugin` fails inside a git worktree, so `-Dmaven.gitcommitid.skip=true` is needed there. Conformance server: branch `bdx-645-pollinfo-conformance-server` (unchanged server code), private instance on Flight `127.0.0.1:32447` and control `127.0.0.1:32448`. + +```sh +# conformance server (Go 1.25.5) +make build && make test +./bin/conformance-server -flight-addr 127.0.0.1:32447 -control-addr 127.0.0.1:32448 + +# focused + shared T1-T9 (run from the repo root) +mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -am test \ + -Dtest='PollInfoExecutionTest,SharedServerPollInfoExecutionTest' -Dsurefire.failIfNoSpecifiedTests=false \ + -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32447 -Dpollinfo.shared.controlPort=32448 \ + -Dmaven.gitcommitid.skip=true + +# T10 regression +mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -am test \ + -Dtest='org.apache.arrow.flight.sql.**.*,org.apache.arrow.driver.jdbc.**.*' -Dsurefire.failIfNoSpecifiedTests=false \ + -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=32447 -Dpollinfo.shared.controlPort=32448 \ + -Dmaven.gitcommitid.skip=true +``` + +| Run | Before rebase (base `91b4a2ca4`) | After rebase (`10c55b9c8`) | +| --- | --- | --- | +| Conformance server `go test ./...` | 13/13 pass | n/a (server unchanged) | +| `PollInfoExecutionTest` (focused T1–T9) | 12/12 pass | 12/12 pass | +| `SharedServerPollInfoExecutionTest` (shared T1–T9) | 11/11 pass | 11/11 pass | +| T10: Flight SQL + JDBC core full suites | not rerun (Sept: 97 + 1,269, 56 skipped) | Flight SQL 97/97; JDBC core 1,365 run, 0 failures/errors, 46 skipped (includes the PollInfo tests) | + +The post-rebase runs had Spotless and Checkstyle enabled. The pre-rebase runs skipped them. From 2ff4c375af36a1f2823f5531f08167bb84370510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Wed, 25 Nov 2026 23:54:42 +0000 Subject: [PATCH 22/39] BDX-645: model-check the JDBC poll-ahead proposal with TLA+ Add a TLA+ model of one progressive ResultSet with a background poller (formal/pollinfo-poll-ahead/PollAhead.tla), a run script that checks the design and a set of deliberately broken variants (run.sh), and a project-local skill (verify-jdbc-poll-ahead) for checking future changes. Within N<=4 endpoints and a limit of 2, eight rules hold for the proposal as written: no premature end, each endpoint once, each continuation once, fail fast, no poll after cancel, backpressure, no spin after empty answers, and termination. "Open streams never exceed the limit" breaks, because one answer can add several endpoints whose streams open at once; with deferred stream opening all nine rules hold. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-jdbc-poll-ahead/SKILL.md | 95 +++++ formal/pollinfo-poll-ahead/PollAhead.tla | 355 ++++++++++++++++++ formal/pollinfo-poll-ahead/run.sh | 82 ++++ 3 files changed, 532 insertions(+) create mode 100644 .claude/skills/verify-jdbc-poll-ahead/SKILL.md create mode 100644 formal/pollinfo-poll-ahead/PollAhead.tla create mode 100755 formal/pollinfo-poll-ahead/run.sh diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md new file mode 100644 index 0000000000..8fcefbf479 --- /dev/null +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -0,0 +1,95 @@ +--- +name: verify-jdbc-poll-ahead +description: Model-check the Flight SQL JDBC progressive PollInfo result path (BDX-645) and its proposed bounded poll-ahead with TLA+. Use before merging any change to ArrowFlightJdbcFlightStreamResultSet, FlightEndpointDataQueue, PollInfoOperation, or the PollingFlightSqlClient poll loop, and when implementing or changing the poll-ahead poller. +--- + +# Verify the JDBC poll-ahead design + +The JDBC driver reads a progressive query in two concurrent roles. The **reader** serves `ResultSet.next()` and opens `DoGet` streams. The **poller** sends `PollFlightInfo` continuations. A TLA+ model, `formal/pollinfo-poll-ahead/PollAhead.tla`, checks every interleaving of reader, poller and server, within small bounds. Use this skill to tell whether a change still keeps the promises below. + +## What is verified + +Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. + +| Rule | Promise | Harm if broken | +| --- | --- | --- | +| `NoPrematureEnd` | `next()` returns false only after every published endpoint was read and the query finished. | The application silently gets a truncated result. | +| `EachEndpointOnce` | Each endpoint is queued for download once, even though every PollInfo repeats all earlier endpoints. | Duplicate rows. | +| `ContinuationsOnce` | Each continuation descriptor is sent at most once. | The server rejects the reused descriptor (`FAILED_PRECONDITION` in the conformance server), or the query re-runs. | +| `FailFast` | No row reaches the application after the driver saw the query fail or was cancelled. | The application processes data from a failed query. | +| `CancelStopsPolling` | No poll is sent after `Statement.cancel()`, the deadline, or `close()`. | Server work continues after the user cancelled. | +| `Backpressure` | The poller does not poll while unread endpoints are at `pollInfoPrefetch`. | The driver runs ahead of a slow reader without bound. | +| `OpenWithinLimit` | Open, unread `DoGet` streams never exceed the limit. | More open streams, each buffering up to 5 batches, than the setting promises. | +| `NoSpin` | No poll is sent straight after an answer that added nothing. | A busy loop against servers that answer at once. | +| `Terminates` | Every result eventually ends or throws, if nobody cancels. | `next()` hangs forever. | + +## Scope, bounds, assumptions + +- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled. +- Rows are abstracted: reading an endpoint is one step. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". +- Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked. +- The server may answer a poll at any moment, including at once with nothing new. +- The reader's end check ("queue empty and poller finished") is assumed to be one atomic read under the queue's lock. The poller's count check and its pause are also one step. The `pauseNotAtomic` variant shows what breaks when they are not. +- The model covers the result path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, or parameter upload. + +## Coverage record + +Sync commit: `b444a256006897ebf079dd47596ad978cb4701cc` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). At that commit the POC exists and the poll-ahead poller does not. + +| Model action | Code at the sync commit (`flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`) | +| --- | --- | +| `PollerSend`, `PollerTake` | `client/PollInfoOperation.java`: `poll`, `pollNextAvailable`. In the POC these run on the reader thread from `ArrowFlightJdbcFlightStreamResultSet.loadNextPublishedEndpoint`. | +| `PollerApply` | `client/PollInfoOperation.java`: `remember`, `validateAppendOnly`. `ArrowFlightJdbcFlightStreamResultSet.java`: `enqueueNewEndpoints`. | +| `AppRead` | `ArrowFlightJdbcFlightStreamResultSet.java`: `next`, `getNextEndpointStream`. `utils/FlightEndpointDataQueue.java`: `next`, `enqueue`. | +| `AppEnd` | `ArrowFlightJdbcFlightStreamResultSet.next` returning false. | +| `AppCancel` | `ArrowFlightStatement.cancel`, `ArrowFlightPreparedStatement.cancel`, `ArrowFlightJdbcFlightStreamResultSet.cancel` and `close`, `client/PollInfoOperation.cancel`. | +| `SrvAnswer` failure branch, `PollerTake` error branch | `ArrowFlightJdbcFlightStreamResultSet.loadNextPublishedEndpoint` catch block. | +| `PollerPause`, `BackoffElapses`, the wake in `AppRead`, the poller pool, deferred stream opening (`EagerOpen = FALSE`) | Proposed only. No code yet. | + +## When to use it + +Run it when a diff touches any covered file: + +```sh +git diff --name-only b444a256006897ebf079dd47596ad978cb4701cc..HEAD -- \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java \ + formal/pollinfo-poll-ahead/ +``` + +Any output means the model may no longer describe the code. Also use this skill for any new poller class, for example `EndpointPoller`. + +## How to check a change + +1. **Mirror the change in the model.** The model is a hand-written design model, so TLC cannot read Java. Use the coverage record to find the action that corresponds to the code you changed, and edit that action so it does what the new code does. Keep each atomic step in the model atomic in the code: a step under one lock, or one RPC answer, is one action. +2. **Run every check** (about 15 seconds; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): + + ```sh + formal/pollinfo-poll-ahead/run.sh + N=4 formal/pollinfo-poll-ahead/run.sh + ``` + + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` must still fail on `OpenWithinLimit` until the finding below is resolved. Every broken variant must fail on its rule. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. +3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. +4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. +5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. +6. **Move the sync commit** in the coverage record only after you have confirmed that every action still matches the code at the new commit. Update the coverage table at the same time, for example when proposed actions get real code. + +## Known finding + +`OpenWithinLimit` fails for the proposal as written (`EagerOpen = TRUE`). The limit is checked before a poll, but one answer can publish several endpoints, and their streams all open at once. Shortest path, with a limit of 2: + +1. The server publishes a second and a third endpoint while the application is still reading the first. +2. One stream is open, which is below the limit, so the poller sends the continuation. +3. The answer carries all three endpoints. The two new streams open at once, leaving three open streams against a limit of 2. + +With deferred opening (`EagerOpen = FALSE`), streams open only while fewer than `Limit` are unread, and every rule holds. The implementation should keep queued endpoints unopened until the reader frees a slot, or the setting should be documented as "polls ahead while fewer than N are unread", not as a cap on open streams. + +## Files + +- `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. diff --git a/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla new file mode 100644 index 0000000000..0edca47be0 --- /dev/null +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -0,0 +1,355 @@ +----------------------------- MODULE PollAhead ----------------------------- +(***************************************************************************) +(* Bounded poll-ahead for the Arrow Flight SQL JDBC driver (BDX-645). *) +(* *) +(* One progressive JDBC ResultSet, from the moment executeQuery has *) +(* returned it: the first PollInfo published endpoint E1 and continuation *) +(* C1, and C1 has been handed to the poller. *) +(* *) +(* Three parties run concurrently: *) +(* - the Flight SQL server, which publishes endpoints and finishes or *) +(* fails the query, and answers PollFlightInfo at any moment (a server *) +(* that does not long-poll may answer at once with nothing new); *) +(* - the poller (proposed EndpointPoller), which chains continuations; *) +(* - the application thread inside ResultSet.next(), which reads *) +(* endpoints, ends the results, or throws. *) +(* *) +(* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md):*) +(* PollerSend / PollerTake PollInfoOperation.poll / pollNextAvailable *) +(* PollerApply PollInfoOperation.remember + *) +(* ArrowFlightJdbcFlightStreamResultSet *) +(* .enqueueNewEndpoints (append-only suffix) *) +(* AppRead ArrowFlightJdbcFlightStreamResultSet.next *) +(* + FlightEndpointDataQueue.next *) +(* AppEnd next() returning false *) +(* AppCancel Statement.cancel / deadline / close *) +(* -> PollInfoOperation.cancel *) +(* PollerPause, BackoffElapses, the wake in AppRead, and running the *) +(* poll loop off the application thread are the proposal; they have no *) +(* code yet (the POC polls inside next() when the queue is empty). *) +(* *) +(* Rows are abstracted: reading an endpoint is one step. Endpoint i is the *) +(* i-th endpoint the server publishes; PollInfo is cumulative, so an *) +(* answer is just how many endpoints exist so far. *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS + N, \* most endpoints the query can publish + Limit, \* pollInfoPrefetch: the poller polls only while open, unread endpoints < Limit + EagerOpen, \* TRUE: a DoGet stream opens as soon as its endpoint is enqueued (the proposal as written) + Mutation \* "none", or the name of a deliberately broken variant (see run.sh) + +VARIABLES + published, \* endpoints the server has published + server, \* "running" | "done" | "failed" + known, \* endpoints enqueued in FlightEndpointDataQueue (cumulative prefix) + opened, \* endpoints whose DoGet stream has been opened + read, \* endpoints the application has fully read + enq, \* enq[i]: how many times endpoint i was enqueued (capped at 2) + contHeld, \* the driver holds a continuation descriptor + contUsed, \* the held continuation has already been sent + inflight, \* a PollFlightInfo RPC is open + resp, \* the server's answer, not yet taken by the poller + got, \* the answer the poller took, not yet applied + poller, \* "running" | "polling" | "received" | "backoff" | "paused" | "finished" | "failed" | "stopped" + lastEmpty, \* the last applied answer added no endpoints while the query was running + waited, \* a backoff has elapsed since that empty answer + app, \* "reading" | "ended" | "threw" + failSeen, \* the driver has seen the query fail + cancelled, \* Statement.cancel(), the deadline, or close() happened + badRow, \* a row was handed to the application after a failure or cancel + badPoll, \* a poll was sent after cancel + polledAtLimit, \* a poll was sent while open, unread endpoints were at the limit + resent, \* a continuation was sent twice + spun, \* a poll was sent right after an empty answer, without backoff + sawFull \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet + +vars == <> + +Min(a, b) == IF a < b THEN a ELSE b + +Answer == [has : BOOLEAN, count : 0..N, more : BOOLEAN, err : BOOLEAN] +NoAnswer == [has |-> FALSE, count |-> 0, more |-> FALSE, err |-> FALSE] + +Unread == known - read + +----------------------------------------------------------------------------- +Init == + /\ published = 1 + /\ server = "running" + /\ known = 1 + /\ opened = 1 + /\ read = 0 + /\ enq = [i \in 1..N |-> IF i = 1 THEN 1 ELSE 0] + /\ contHeld = TRUE + /\ contUsed = FALSE + /\ inflight = FALSE + /\ resp = NoAnswer + /\ got = NoAnswer + /\ poller = "running" + /\ lastEmpty = FALSE + /\ waited = FALSE + /\ app = "reading" + /\ failSeen = FALSE + /\ cancelled = FALSE + /\ badRow = FALSE + /\ badPoll = FALSE + /\ polledAtLimit = FALSE + /\ resent = FALSE + /\ spun = FALSE + /\ sawFull = FALSE + +----------------------------------------------------------------------------- +(* Server *) + +SrvPublish == + /\ server = "running" + /\ published < N + /\ published' = published + 1 + /\ UNCHANGED <> + +SrvComplete == + /\ server = "running" + /\ server' = "done" + /\ UNCHANGED <> + +SrvFail == + /\ server = "running" + /\ server' = "failed" + /\ UNCHANGED <> + +\* The server answers the open poll. It may answer at once with nothing new. +SrvAnswer == + /\ inflight + /\ ~resp.has + /\ resp' = IF cancelled \/ server = "failed" + THEN [has |-> TRUE, count |-> 0, more |-> FALSE, err |-> TRUE] + ELSE [has |-> TRUE, count |-> published, more |-> server = "running", err |-> FALSE] + /\ inflight' = FALSE + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* Poller (proposed EndpointPoller, on its own pool) *) + +PollerSend == + /\ poller = "running" + /\ contHeld + /\ ~inflight + /\ Mutation = "noLimit" \/ Unread < Limit + /\ inflight' = TRUE + /\ poller' = "polling" + /\ contUsed' = TRUE + /\ resent' = (resent \/ contUsed) + /\ spun' = (spun \/ (lastEmpty /\ ~waited)) + /\ badPoll' = (badPoll \/ cancelled) + /\ polledAtLimit' = (polledAtLimit \/ Unread >= Limit) + /\ waited' = FALSE + /\ UNCHANGED <> + +\* At the limit the poller pauses and gives its thread back. +PollerPause == + /\ poller = "running" + /\ contHeld + /\ Mutation # "noLimit" + /\ IF Mutation = "pauseNotAtomic" THEN sawFull ELSE Unread >= Limit + /\ poller' = "paused" + /\ sawFull' = FALSE + /\ UNCHANGED <> + +\* Broken variant only: the poller reads the count, and pauses in a later step. +PollerCheck == + /\ Mutation = "pauseNotAtomic" + /\ poller = "running" + /\ contHeld + /\ ~sawFull + /\ Unread >= Limit + /\ sawFull' = TRUE + /\ UNCHANGED <> + +\* The poller takes the answer. A failure fails the execution at once. +PollerTake == + /\ poller = "polling" + /\ resp.has + /\ resp' = NoAnswer + /\ IF resp.err + THEN /\ poller' = "failed" + /\ failSeen' = TRUE + /\ contHeld' = FALSE + /\ UNCHANGED got + ELSE /\ got' = resp + /\ poller' = IF Mutation = "finishBeforeEnqueue" /\ ~resp.more + THEN "finished" ELSE "received" + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Apply a successful answer: enqueue only the appended endpoints, take the +\* next continuation, and mark the poller finished in the same step when the +\* query is complete. +PollerApply == + /\ got.has + /\ poller \in {"received", "finished"} + /\ LET new == got.count + from == IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1 + empty == new = known + IN + /\ enq' = [i \in 1..N |-> IF i >= from /\ i <= new THEN Min(enq[i] + 1, 2) ELSE enq[i]] + /\ known' = new + /\ opened' = IF EagerOpen THEN new ELSE Min(new, read + Limit) + /\ got' = NoAnswer + /\ IF got.more + THEN /\ contHeld' = TRUE + /\ contUsed' = (Mutation = "reuseContinuation" /\ empty) + /\ lastEmpty' = empty + /\ poller' = IF empty /\ Mutation # "noBackoff" THEN "backoff" ELSE "running" + ELSE /\ contHeld' = FALSE + /\ lastEmpty' = FALSE + /\ poller' = "finished" + /\ UNCHANGED contUsed + /\ UNCHANGED <> + +\* 100 ms doubling up to pollInfoMaxBackoff; time is abstracted to one step. +BackoffElapses == + /\ poller = "backoff" + /\ poller' = "running" + /\ waited' = TRUE + /\ UNCHANGED <> + +\* A stopped poller discards the answer to the poll that cancel interrupted. +PollerDrop == + /\ poller = "stopped" + /\ resp.has + /\ resp' = NoAnswer + /\ UNCHANGED <> + +----------------------------------------------------------------------------- +(* Application thread inside ResultSet.next() *) + +\* Read one opened endpoint. Finishing it may wake a paused poller. +AppRead == + /\ app = "reading" + /\ opened > read + /\ Mutation = "readAfterFail" \/ (~failSeen /\ ~cancelled) + /\ read' = read + 1 + /\ badRow' = (badRow \/ failSeen \/ cancelled) + /\ opened' = IF EagerOpen THEN opened ELSE Min(known, read + 1 + Limit) + /\ poller' = IF poller = "paused" /\ known - (read + 1) < Limit /\ Mutation # "noWake" + THEN "running" ELSE poller + /\ UNCHANGED <> + +\* next() returns false only when the queue is empty and the poller finished. +AppEnd == + /\ app = "reading" + /\ ~failSeen + /\ ~cancelled + /\ read = known + /\ Mutation = "endWhenQueueEmpty" \/ poller = "finished" + /\ app' = "ended" + /\ UNCHANGED <> + +AppThrow == + /\ app = "reading" + /\ failSeen \/ cancelled + /\ app' = "threw" + /\ UNCHANGED <> + +\* Cancel stops the poller; its open poll, if any, ends with CANCELLED. +AppCancel == + /\ app = "reading" + /\ ~cancelled + /\ cancelled' = TRUE + /\ poller' = IF poller \in {"finished", "failed"} \/ Mutation = "cancelIgnoresPoller" + THEN poller ELSE "stopped" + /\ contHeld' = IF Mutation = "cancelIgnoresPoller" THEN contHeld ELSE FALSE + /\ UNCHANGED <> + +\* The application is done with the result; nothing more happens to it. +Done == + /\ app \in {"ended", "threw"} + /\ UNCHANGED vars + +Next == + \/ SrvPublish \/ SrvComplete \/ SrvFail \/ SrvAnswer + \/ PollerSend \/ PollerCheck \/ PollerPause \/ PollerTake \/ PollerApply \/ BackoffElapses \/ PollerDrop + \/ AppRead \/ AppEnd \/ AppThrow \/ AppCancel + \/ Done + +\* The server eventually finishes; the driver and the application keep going. +Fairness == + /\ WF_vars(SrvComplete) /\ WF_vars(SrvAnswer) + /\ WF_vars(PollerSend) /\ WF_vars(PollerPause) /\ WF_vars(PollerTake) + /\ WF_vars(PollerApply) /\ WF_vars(BackoffElapses) /\ WF_vars(PollerDrop) + /\ WF_vars(AppRead) /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) + +Spec == Init /\ [][Next]_vars /\ Fairness + +----------------------------------------------------------------------------- +(* Rules *) + +TypeOK == + /\ published \in 1..N + /\ server \in {"running", "done", "failed"} + /\ read <= opened /\ opened <= known /\ known <= published + /\ enq \in [1..N -> 0..2] + /\ resp \in Answer /\ got \in Answer + /\ poller \in {"running", "polling", "received", "backoff", "paused", "finished", "failed", "stopped"} + /\ app \in {"reading", "ended", "threw"} + /\ sawFull \in BOOLEAN + +\* Each endpoint is queued for download exactly once (append-only suffix). +EachEndpointOnce == \A i \in 1..N : enq[i] <= 1 + +\* Each continuation descriptor is sent at most once. +ContinuationsOnce == ~resent + +\* next() returns false only after every published endpoint was read and the query finished. +NoPrematureEnd == app = "ended" => (server = "done" /\ read = published) + +\* No row reaches the application after the driver saw a failure or a cancel. +FailFast == ~badRow + +\* No poll is sent after cancel. +CancelStopsPolling == ~badPoll + +\* The poller never polls while unread endpoints are at the limit. +Backpressure == ~polledAtLimit + +\* Open, unread DoGet streams never exceed the limit. +OpenWithinLimit == opened - read <= Limit + +\* No poll is sent straight after an empty answer. +NoSpin == ~spun + +\* Every result eventually ends or throws. +Terminates == <>(app \in {"ended", "threw"}) +============================================================================= diff --git a/formal/pollinfo-poll-ahead/run.sh b/formal/pollinfo-poll-ahead/run.sh new file mode 100755 index 0000000000..6978035b1b --- /dev/null +++ b/formal/pollinfo-poll-ahead/run.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Model-check the JDBC poll-ahead design (BDX-645) with TLC. +# +# formal/pollinfo-poll-ahead/run.sh # all checks +# N=4 LIMIT=2 formal/pollinfo-poll-ahead/run.sh # larger bound (slower) +# +# Each check states what it expects. The script exits 0 only when every +# check matches its expectation, including the broken variants, which must +# fail on the rule they target. Needs Java 11+ and tla2tools.jar v1.7.4. +set -euo pipefail + +HERE=$(cd "$(dirname "$0")" && pwd) +JAR=${TLA2TOOLS:-} +if [ -z "$JAR" ] && [ -f "$HOME/.local/share/mise/installs/http-tla2tools/1.7.4/tla2tools.jar" ]; then + JAR="$HOME/.local/share/mise/installs/http-tla2tools/1.7.4/tla2tools.jar" +fi +if [ -z "$JAR" ] || [ ! -f "$JAR" ]; then + echo "tla2tools.jar not found. Download v1.7.4 from https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4 and set TLA2TOOLS=/path/to/tla2tools.jar" >&2 + exit 2 +fi + +N=${N:-3} +LIMIT=${LIMIT:-2} +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +cp "$HERE/PollAhead.tla" "$WORK/" + +SAFE="TypeOK EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin" +ALL="$SAFE OpenWithinLimit" +unexpected=0 + +# check NAME EAGER_OPEN MUTATION "INVARIANTS" LIVENESS(yes|no) EXPECT(pass|invariant:Name|deadlock|liveness) NOTE +check() { + local name=$1 eager=$2 mutation=$3 invariants=$4 liveness=$5 expect=$6 note=$7 + local cfg="$WORK/$name.cfg" out="$WORK/$name.out" got + { + echo "SPECIFICATION Spec" + echo "CONSTANTS N = $N Limit = $LIMIT EagerOpen = $eager Mutation = \"$mutation\"" + for inv in $invariants; do echo "INVARIANT $inv"; done + if [ "$liveness" = yes ]; then echo "PROPERTY Terminates"; fi + } > "$cfg" + (cd "$WORK" && java -XX:+UseParallelGC -cp "$JAR" tlc2.TLC -workers auto \ + -metadir "$WORK/meta-$name" -config "$cfg" PollAhead.tla) > "$out" 2>&1 || true + if grep -q "No error has been found" "$out"; then got=pass + elif inv=$(grep -o "Invariant [A-Za-z]* is violated" "$out" | head -1 | awk '{print $2}') && [ -n "$inv" ]; then got="invariant:$inv" + elif grep -q "Deadlock reached" "$out"; then got=deadlock + elif grep -q "Temporal properties were violated" "$out"; then got=liveness + else got=error + fi + local states + states=$(grep -o "[0-9,]* distinct states found" "$out" | tail -1 | awk '{print $1}') + if [ "$got" = "$expect" ]; then + printf 'ok %-26s %-28s %s (%s distinct states)\n' "$name" "$got" "$note" "${states:-?}" + else + printf 'FAIL %-26s expected %-19s got %s\n' "$name" "$expect" "$got" + sed -n '/^Error:/,$p' "$out" | head -80 + unexpected=1 + fi +} + +echo "PollAhead model check N=$N Limit=$LIMIT ($(java -cp "$JAR" tlc2.TLC 2>&1 | head -1))" +echo +echo "Design checks" +check proposal-as-written TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" +check finding-open-streams TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" +check deferred-open FALSE none "$ALL" yes pass "streams open only while open < limit" +echo +echo "Broken variants (each must fail on the rule it targets)" +check endWhenQueueEmpty FALSE endWhenQueueEmpty "$ALL" no invariant:NoPrematureEnd "next() ends when the queue is empty" +check finishBeforeEnqueue FALSE finishBeforeEnqueue "$ALL" no invariant:NoPrematureEnd "poller marked finished before enqueueing" +check enqueueWholeList FALSE enqueueWholeList "$ALL" no invariant:EachEndpointOnce "cumulative list enqueued, not the suffix" +check reuseContinuation FALSE reuseContinuation "$ALL" no invariant:ContinuationsOnce "old continuation kept after empty answer" +check readAfterFail FALSE readAfterFail "$ALL" no invariant:FailFast "reader ignores the failure flag" +check cancelIgnoresPoller FALSE cancelIgnoresPoller "$ALL" no invariant:CancelStopsPolling "cancel does not stop the poller" +check noLimit FALSE noLimit "$ALL" no invariant:Backpressure "poller ignores the limit" +check noBackoff FALSE noBackoff "$ALL" no invariant:NoSpin "no wait after an empty answer" +check noWake FALSE noWake "$ALL" yes liveness "reader never wakes a paused poller" +check pauseNotAtomic FALSE pauseNotAtomic "$ALL" yes liveness "limit check and pause in separate steps" + +echo +if [ "$unexpected" -eq 0 ]; then echo "All checks matched their expectations."; else echo "Some checks did not match. See above."; fi +exit "$unexpected" From f4395faccd13f0fd47fd92c86eee18bf66f98586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 00:12:11 +0000 Subject: [PATCH 23/39] BDX-645: add JDBC poll-ahead implementation plan Co-Authored-By: Claude Opus 5.5 --- reports/poll-ahead-implementation-plan.md | 105 ++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 reports/poll-ahead-implementation-plan.md diff --git a/reports/poll-ahead-implementation-plan.md b/reports/poll-ahead-implementation-plan.md new file mode 100644 index 0000000000..0e2c6cf8df --- /dev/null +++ b/reports/poll-ahead-implementation-plan.md @@ -0,0 +1,105 @@ +# BDX-645 JDBC poll-ahead: implementation plan + +Goal: during progressive `PollFlightInfo` execution, poll continuations in the background while the application reads, without changing the JDBC API. The design was agreed in review and model-checked in `formal/pollinfo-poll-ahead/` (skill: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`). The implementation must match the model's **deferred-open** configuration (`EagerOpen = FALSE`). + +All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/` unless shown in full. + +## Behavior + +1. `executeQuery` is unchanged. It polls until the first endpoint exists and returns the `ResultSet`. +2. If a continuation is pending, the prefetch limit is above 0, and the poller pool accepts the task, the `ResultSet` hands the continuation to an `EndpointPoller`. Otherwise it keeps today's behavior: the reader polls inside `next()` when its queue is empty (the POC path, plus backoff). +3. The poller polls the held continuation once, in the execution's `PollInfoOperation` context (one deadline, one cancel). It checks append-only, queues only the appended endpoints, and continues with the next continuation. +4. Backpressure: + - The poller does not poll while queued, unread endpoints (opened-unread plus not-yet-opened) are at or above the limit. It pauses and holds no thread. + - A queued endpoint opens its `DoGet` stream only while fewer than the limit are open and unread. + - When the reader finishes an endpoint, under the same lock, it opens pending endpoints and resumes a paused poller. +5. Backoff: after an answer that adds no endpoints while the query is still running, wait 100 ms, doubling up to `pollInfoMaxBackoffMs` (default 5000). Reset after any answer that adds endpoints. Never wait past the operation deadline; cancel and close interrupt the wait. The wait may block the poller thread. +6. End of results: `next()` returns false only when the queue is empty, nothing is pending, and the poller has finished. The poller must mark itself finished in the same locked step that queues the final endpoints. +7. Fail fast: a failed continuation poll records the failure, closes every open stream, drops pending endpoints and buffered batches, and makes the next `next()` throw. No `CancelFlightInfo` is needed, because the server already ended the query. The exception keeps today's mapping: `TIMED_OUT` becomes `SQLTimeoutException("Query timed out after N SECONDS")`; anything else becomes `SQLException("Continuation PollFlightInfo failed", cause)`. +8. Cancel and close stop the poller. `Statement.cancel()`, the deadline and `ResultSet.close()` on an incomplete result cancel the operation context, end any open poll, send best-effort `CancelFlightInfo` once (existing `PollInfoOperation.cancel`), close the queue, and make the next `next()` throw "Statement canceled". +9. Metadata calls, `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, and `usePollInfo=false` are unchanged. + +## Configuration (connection properties) + +| Property | Type | Default | Meaning | +| --- | --- | --- | --- | +| `pollInfoPrefetch` | number | `-1` = auto: `max(2, threadPoolSize)` | Most queued, unread endpoints. The poller polls only below it, and streams open only below it. `0` keeps the POC behavior (the reader polls when its queue is empty). | +| `pollInfoPollerThreads` | number | `4` | Size of the connection's poller pool. When all threads are busy, a new result uses the `0` behavior. | +| `pollInfoMaxBackoffMs` | number | `5000` | Longest wait between answers that add nothing. | + +Deviation from the review decision: the review set the prefetch default to `threadPoolSize`, but `threadPoolSize` defaults to 1. A limit of 1 never polls while an endpoint is being read, so the default is `max(2, threadPoolSize)`. Follow the naming and type conventions of the existing properties in `utils/ArrowFlightConnectionConfigImpl.java`. If they use a different suffix for durations, use theirs and record the name here. + +## Work units + +### U1. Core implementation (one subagent; tightly coupled files) + +- `utils/ArrowFlightConnectionConfigImpl.java`: the three properties and their accessors. +- `ArrowFlightConnection.java`: a lazily created poller executor. + - Bounded `ThreadPoolExecutor` with core = max = `pollInfoPollerThreads`, a `SynchronousQueue`, daemon threads named after the connection, and an `AbortPolicy`, so a busy pool rejects and the result falls back. + - Shut it down on `close()`, next to the stream executor. Expose the effective prefetch and backoff to result sets. +- `client/ArrowFlightSqlClientHandler.java`: split `getStreams(FlightInfo)` so a single endpoint can be opened (`getStream(FlightEndpoint)` or similar), reusing the existing location and TLS logic. Keep `getStreams` working for existing callers. +- `utils/FlightEndpointDataQueue.java`, extended without breaking existing callers (metadata result sets, existing tests): + - A pending list of `FlightEndpoint`s not yet opened, an opener function, `maxOpen`, and an open-unread count. + - Opened-unread goes down when a stream's future returns `null` (finished) or the stream is closed. + - "More may arrive": while set, `next()` waits instead of returning `null` when nothing is queued. Honor the timeout variant and wake on new endpoints, finish, fail or close. + - `fail(Throwable)`: closes all streams, drops pending, and makes `next()` rethrow. + - An atomic `pauseIfFull()` for the poller and a resume callback fired when the unread count drops below the limit, all under one lock. Never hold that lock across a blocking `future.get()`, `take()`, or a network call. +- `client/PollInfoOperation.java`: + - A single-poll method for the poller: poll the held continuation once, `remember` the answer, and report whether it added endpoints. + - Keep `pollNextAvailable` for the fallback path, but add the same backoff between empty answers. + - Keep `validateAppendOnly`. +- New `EndpointPoller` (package `org.apache.arrow.driver.jdbc`, package-private), started by the result set. + - States: running, polling, paused, backoff, finished, failed, stopped. + - Each step is guarded by the queue's lock where it touches queue state. + - Stop on cancel or close. Do not leak tasks after the result closes. +- `ArrowFlightJdbcFlightStreamResultSet.java`: + - Create the queue with the limit and opener, and queue the first answer's endpoints through it, so deferred opening applies to the first answer too. + - Start the poller, or fall back. + - In poller mode, `next()` relies on the queue: `null` means done. Map a failure to the exceptions above. + - Keep the POC path for prefetch `0` or a rejected submit. Keep cancel and close semantics. +- Keep every existing test green. If an existing test asserts the POC request order (`Poll, DoGet, Poll, DoGet`), run it with `pollInfoPrefetch=0` rather than deleting the assertion. +- Do not change the TLA+ model. + +### U2. Unit tests (after U1) + +Add to `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/` (extend `utils/PollingMockFlightSqlProducer.java` as needed: multi-endpoint answers, held `DoGet` streams, immediate empty answers, failing continuations, timestamps): + +1. Poll-ahead: the poll for C1 arrives before E1's stream completes. +2. Deferred open: one answer adds 4 endpoints with prefetch 2, and at most 2 `DoGet` streams are ever open at once. All rows are delivered. +3. Backpressure: with held streams, polling stops at the limit and resumes after reads. +4. Backoff: gaps of at least 100 ms, then 200 ms, between consecutive empty answers (generous upper tolerance); the gap resets after an answer that adds endpoints; capped by `pollInfoMaxBackoffMs`. +5. Fail fast: a continuation error while E1 is held. `next()` throws, no rows from E2, and E2's stream is closed or never opened. +6. Cancel: `Statement.cancel()` with a poll open sends no further polls and exactly one `CancelFlightInfo`; `next()` throws. +7. Close of an unfinished result stops the poller and sends one `CancelFlightInfo`. +8. No premature end: the final endpoints arrive in the done answer, and all rows are delivered. +9. Continuations are sent once each and in order. +10. `pollInfoPrefetch=0` keeps the exact POC order. +11. Poller pool busy (`pollInfoPollerThreads=1`, two concurrent results): the second falls back, and both return correct rows. +12. `FlightEndpointDataQueue` unit tests for deferred open, wait-for-more, fail, and close. + +### U3. End-to-end tests against the conformance server (after U2 and the server additions) + +Extend `SharedServerPollInfoExecutionTest` (enabled by `-Dpollinfo.shared.enabled=true` with `-Dpollinfo.shared.flightPort` and `-Dpollinfo.shared.controlPort`). The scenarios, events and control endpoints come from the conformance-server session (statement texts `burst`, `trickle`, `empty-answers`, `late-error-buffered`, plus hold/release and `DoGet.end` / `do_get_max_concurrent` / `elapsed_ns`). Assert server-side observations: maximum concurrent streams, poll-ahead ordering relative to held streams, backoff gaps, fail-fast cancellation of buffered streams, and continuation order. + +### U4. Model sync and verification (after U1; can run alongside U2) + +- Update the coverage record in `.claude/skills/verify-jdbc-poll-ahead/SKILL.md` to map each model action to the new code: `EndpointPoller`, the queue methods, the result set. +- Check the implementation against `PollAhead.tla` (`EagerOpen = FALSE`). Mirror any difference into the model, or report it as a finding. +- Run `formal/pollinfo-poll-ahead/run.sh` and `N=4 formal/pollinfo-poll-ahead/run.sh`. Move the sync commit only after confirming that the model matches. + +### U5. Review and regression (after U3) + +Correctness and test review of the full diff. Fix confirmed issues. Then run: + +- the full Flight SQL and JDBC core suites +- the shared-server suite against a fresh conformance server +- the verification skill + +## Build and run conventions (all units) + +- Worktree: `/Users/helder/repos/arrow-java-fork/.claude/worktrees/bdx-645-jdbc`, branch `bdx-645-pollinfo-poc`. Never push. +- Maven: `/Users/helder/.m2/wrapper/dists/apache-maven-3.9.10-bin/53h08a94dg6djh6umvruv7q564/apache-maven-3.9.10/bin/mvn`. Maven 3.10 fails on this repo. Always pass `-Dmaven.gitcommitid.skip=true`, and run from the repo root with `-pl flight/flight-sql,flight/flight-sql-jdbc-core -am`. +- Focused tests: add `-Dtest='' -Dsurefire.failIfNoSpecifiedTests=false`. Full suites: `-Dtest='org/apache/arrow/flight/sql/**/*.java,org/apache/arrow/driver/jdbc/**/*.java'`. +- Format with `spotless:apply` on both modules before committing. Spotless and Checkstyle must pass. +- One local commit per unit, ending with `Co-Authored-By: Claude Opus 5.5 `. +- Only one Maven build may run in this worktree at a time. From d7c3ed4ab4d30601447bc0518ac05294462b37d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 00:27:30 +0000 Subject: [PATCH 24/39] BDX-645: poll ahead on progressive PollFlightInfo results (JDBC) Poll continuations in the background while the application reads, per reports/poll-ahead-implementation-plan.md and the deferred-open (EagerOpen = FALSE) configuration of formal/pollinfo-poll-ahead/PollAhead.tla. - EndpointPoller chains continuations on a bounded per-connection poller pool (pollInfoPollerThreads), pausing at the unread limit (pollInfoPrefetch) and backing off after empty answers (100 ms doubling to pollInfoMaxBackoffMs). - FlightEndpointDataQueue gains deferred stream opening, an open-unread count, wait-for-more, fail(), and an atomic pauseIfFull()/resume under one lock. The final endpoints and "no more expected" are applied in one locked step. - PollInfoOperation: pollOnce(), cancellable backoff, backoff in pollNextAvailable (the pollInfoPrefetch=0 / fallback path). - ArrowFlightSqlClientHandler.getStream(FlightEndpoint) opens one endpoint. - PollInfoExecutionTest: the read-boundary cancel test uses pollInfoPrefetch=0; add a poll-ahead smoke test. Co-Authored-By: Claude Opus 5.5 --- .../driver/jdbc/ArrowFlightConnection.java | 53 ++ .../ArrowFlightJdbcFlightStreamResultSet.java | 158 ++++- .../arrow/driver/jdbc/EndpointPoller.java | 278 ++++++++ .../client/ArrowFlightSqlClientHandler.java | 226 +++--- .../arrow/driver/jdbc/client/PollBackoff.java | 48 ++ .../driver/jdbc/client/PollInfoOperation.java | 95 ++- .../ArrowFlightConnectionConfigImpl.java | 25 + .../jdbc/utils/FlightEndpointDataQueue.java | 662 +++++++++++++++--- .../driver/jdbc/PollInfoExecutionTest.java | 32 +- 9 files changed, 1343 insertions(+), 234 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollBackoff.java diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index 2e9f65c002..0028e1b72b 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -33,6 +33,9 @@ import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import org.apache.arrow.driver.jdbc.client.ArrowFlightSqlClientHandler; import org.apache.arrow.driver.jdbc.client.utils.FlightClientCache; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl; @@ -45,14 +48,18 @@ import org.apache.calcite.avatica.AvaticaFactory; import org.apache.calcite.avatica.AvaticaStatement; import org.apache.calcite.avatica.DriverVersion; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Connection to the Arrow Flight server. */ public final class ArrowFlightConnection extends AvaticaConnection { + private static final Logger LOGGER = LoggerFactory.getLogger(ArrowFlightConnection.class); private final BufferAllocator allocator; private final ArrowFlightSqlClientHandler clientHandler; private final ArrowFlightConnectionConfigImpl config; private ExecutorService executorService; + private ThreadPoolExecutor pollerExecutor; private int metadataResultSetCount; // Track metadata result sets so connection close can release them. private Map metadataResultSetMap = new HashMap<>(); @@ -190,6 +197,50 @@ synchronized ExecutorService getExecutorService() { : executorService; } + /** + * Gets the pool that runs background PollFlightInfo pollers, creating it on first use. The pool + * is bounded and has no queue: when every thread is busy, submitting a task is rejected and the + * result set falls back to polling inside {@code next()}. + */ + synchronized ThreadPoolExecutor getPollerExecutor() { + if (pollerExecutor == null) { + final int threads = config.pollInfoPollerThreads(); + pollerExecutor = + new ThreadPoolExecutor( + threads, + threads, + 0L, + TimeUnit.MILLISECONDS, + new SynchronousQueue<>(), + new DefaultThreadFactory(getClass().getSimpleName() + "-poller", true), + new ThreadPoolExecutor.AbortPolicy()); + } + return pollerExecutor; + } + + /** The effective most queued, unread endpoints; 0 means poll inside {@code next()}. */ + int getPollInfoPrefetch() { + return config.pollInfoPrefetch(); + } + + /** The longest wait between PollFlightInfo answers that add no endpoints. */ + long getPollInfoMaxBackoffMs() { + return config.pollInfoMaxBackoffMs(); + } + + private void shutdownPollerExecutor() throws InterruptedException { + final ThreadPoolExecutor executor; + synchronized (this) { + executor = pollerExecutor; + } + if (executor != null) { + executor.shutdownNow(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + LOGGER.warn("PollFlightInfo poller threads did not terminate within 5 seconds"); + } + } + } + /** * Registers a new metadata ResultSet and assigns it a unique ID. Metadata ResultSets are those * created without an associated Statement. @@ -262,6 +313,8 @@ public void close() throws SQLException { // copies of the collections are used to avoid concurrent modification problems ArrayList closeables = getStatementsToClose(); closeables.addAll(new ArrayList<>(metadataResultSetMap.values())); + // Statements stop their pollers first; then no poller can outlive the client or allocator. + closeables.add(this::shutdownPollerExecutor); closeables.add(clientHandler); closeables.addAll(allocator.getChildAllocators()); closeables.add(allocator); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 7bab7b6750..825f8c22c9 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -16,8 +16,6 @@ */ package org.apache.arrow.driver.jdbc; -import static org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue.createNewQueue; - import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -57,9 +55,12 @@ public final class ArrowFlightJdbcFlightStreamResultSet extends ArrowFlightJdbcVectorSchemaRootResultSet { private final ArrowFlightConnection connection; - private FlightInfo flightInfo; + private volatile FlightInfo flightInfo; private final PollInfoOperation pollInfoOperation; - private int consumedEndpointCount; + // Written by whichever party currently owns polling (the poller, or the reader inline). + private volatile int consumedEndpointCount; + private EndpointPoller poller; + private int pollerQueryTimeoutSeconds; private CloseableEndpointStreamPair currentEndpointData; private FlightEndpointDataQueue flightEndpointDataQueue; private volatile boolean cancelled; @@ -84,6 +85,9 @@ public final class ArrowFlightJdbcFlightStreamResultSet try { this.flightInfo = ((ArrowFlightInfoStatement) statement).executeFlightInfoQuery(); this.pollInfoOperation = activePollInfoOperation(statement); + if (pollInfoOperation != null) { + pollInfoOperation.setMaxBackoffMillis(connection.getPollInfoMaxBackoffMs()); + } } catch (FlightRuntimeException e) { if (e.status().code() != FlightStatusCode.TIMED_OUT) { throw e; @@ -148,9 +152,24 @@ static ArrowFlightJdbcFlightStreamResultSet fromFlightInfo( return resultSet; } - private void loadNewQueue() { + private boolean shouldPollAhead() { + return pollInfoOperation != null + && pollInfoOperation.hasContinuation() + && connection.getPollInfoPrefetch() > 0; + } + + private void loadNewQueue(final boolean pollAhead) { + if (poller != null) { + poller.stop(); + poller = null; + } Optional.ofNullable(flightEndpointDataQueue).ifPresent(AutoCloseables::closeNoChecked); - flightEndpointDataQueue = createNewQueue(connection.getExecutorService()); + // Without poll-ahead the limit is lifted and every endpoint opens at once, as it always did. + flightEndpointDataQueue = + FlightEndpointDataQueue.createNewQueue( + connection.getExecutorService(), + pollAhead ? connection.getPollInfoPrefetch() : Integer.MAX_VALUE, + endpoint -> connection.getClientHandler().getStream(endpoint)); } private void loadNewFlightStream() throws SQLException { @@ -170,9 +189,26 @@ protected AvaticaResultSet execute() throws SQLException { } private void populateData() throws SQLException { - loadNewQueue(); - enqueueNewEndpoints(flightInfo); - loadNewFlightStream(); + final boolean pollAhead = shouldPollAhead(); + loadNewQueue(pollAhead); + try { + // The first answer goes through the queue too, so deferred opening applies to it. + appendEndpoints(flightInfo, pollAhead); + if (pollAhead) { + startPoller(); + } + loadNewFlightStream(); + } catch (final SQLException | RuntimeException e) { + if (poller != null) { + poller.stop(); + } + try { + flightEndpointDataQueue.close(); + } catch (final Exception closeException) { + e.addSuppressed(closeException); + } + throw e; + } // Ownership of the root will be passed onto the cursor. if (currentEndpointData != null) { @@ -203,6 +239,14 @@ public byte[] getAppMetadata() { @Override public boolean next() throws SQLException { + // Fail fast: no row after a cancel, or after a background poll failed. + if (cancelled) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + final FlightEndpointDataQueue queue = flightEndpointDataQueue; + if (queue != null && queue.failure() != null) { + throw queue.failure(); + } if (currentVectorSchemaRoot == null) { if (!loadNextPublishedEndpoint()) { return false; @@ -269,6 +313,9 @@ public boolean next() throws SQLException { @Override protected void cancel() { cancelled = true; + if (poller != null) { + poller.stop(); + } if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { pollInfoOperation.cancel(); } @@ -296,6 +343,9 @@ public synchronized void close() { return; } this.connection.onResultSetClose(id); + if (poller != null) { + poller.stop(); + } if (flightEndpointDataQueue != null) { // flightStreamQueue should close currentFlightStream internally flightEndpointDataQueue.close(); @@ -401,7 +451,33 @@ private static SQLException normalizeClosedQueueException( throw exception; } - private void enqueueNewEndpoints(final FlightInfo updatedFlightInfo) throws SQLException { + private void startPoller() throws SQLException { + pollerQueryTimeoutSeconds = statement != null ? statement.getQueryTimeout() : 0; + final EndpointPoller newPoller = + new EndpointPoller( + flightEndpointDataQueue, + pollInfoOperation, + connection.getPollerExecutor(), + answer -> appendEndpoints(answer.flightInfo(), answer.hasContinuation()), + this::mapContinuationFailure, + this::finishPollInfoOperation, + connection.getPollInfoMaxBackoffMs()); + flightEndpointDataQueue.setResumeAction(newPoller::resume); + flightEndpointDataQueue.setIdleAction(newPoller::runInlineIfOrphaned); + poller = newPoller; + if (newPoller.start()) { + return; + } + // The poller pool is busy: keep the behavior of polling inside next(). + poller = null; + flightEndpointDataQueue.setResumeAction(null); + flightEndpointDataQueue.setIdleAction(null); + flightEndpointDataQueue.disablePollAhead(); + } + + /** Records the endpoints a poll answer appended, and whether more may follow, in one step. */ + private void appendEndpoints(final FlightInfo updatedFlightInfo, final boolean moreExpected) + throws SQLException { final int updatedEndpointCount = updatedFlightInfo.getEndpoints().size(); if (updatedEndpointCount < consumedEndpointCount) { throw new SQLException("PollInfo removed previously published endpoints"); @@ -410,33 +486,67 @@ private void enqueueNewEndpoints(final FlightInfo updatedFlightInfo) throws SQLE if (schema != null && updatedSchema != null && !schema.equals(updatedSchema)) { throw new SQLException("PollInfo changed the result schema"); } - if (updatedEndpointCount == consumedEndpointCount) { - flightInfo = updatedFlightInfo; - return; - } final List appendedEndpoints = new ArrayList<>( updatedFlightInfo.getEndpoints().subList(consumedEndpointCount, updatedEndpointCount)); - final FlightInfo appendedInfo = - new FlightInfo( - updatedSchema, - updatedFlightInfo.getDescriptor(), - appendedEndpoints, - updatedFlightInfo.getBytes(), - updatedFlightInfo.getRecords()); - enqueueEndpointData( - flightEndpointDataQueue, connection.getClientHandler().getStreams(appendedInfo)); + try { + flightEndpointDataQueue.addEndpoints(appendedEndpoints, moreExpected); + } catch (final IllegalStateException e) { + throw normalizeClosedQueueException(flightEndpointDataQueue, e); + } consumedEndpointCount = updatedEndpointCount; flightInfo = updatedFlightInfo; } + /** Maps a failed background continuation poll to the exception the reader will throw. */ + private SQLException mapContinuationFailure(final FlightRuntimeException e) { + if (e.status().code() == FlightStatusCode.CANCELLED + || e.status().code() == FlightStatusCode.TIMED_OUT) { + pollInfoOperation.cancel(); + } else { + pollInfoOperation.terminate(); + } + finishPollInfoOperation(); + if (e.status().code() == FlightStatusCode.TIMED_OUT) { + final SQLTimeoutException timeout = + new SQLTimeoutException( + String.format( + "Query timed out after %d %s", pollerQueryTimeoutSeconds, TimeUnit.SECONDS)); + timeout.initCause(e); + return timeout; + } + return new SQLException("Continuation PollFlightInfo failed", e); + } + private boolean loadNextPublishedEndpoint() throws SQLException { + if (poller != null) { + // Poll-ahead: the queue is the single source of truth. It waits while more may arrive, and + // null means every endpoint was read and the poller finished. + try { + currentEndpointData = getNextEndpointStream(false); + } catch (final FlightRuntimeException e) { + if ((cancelled || flightEndpointDataQueue.isClosed()) + && e.status().code() == CallStatus.CANCELLED.code()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + throw e; + } + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + return true; + } + if (cancelled || flightEndpointDataQueue.isClosed()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + finishPollInfoOperation(); + return false; + } if (pollInfoOperation == null || !pollInfoOperation.hasContinuation()) { finishPollInfoOperation(); return false; } try { - enqueueNewEndpoints(pollInfoOperation.pollNextAvailable()); + appendEndpoints(pollInfoOperation.pollNextAvailable(), false); currentEndpointData = getNextEndpointStream(false); if (currentEndpointData != null) { populateDataForCurrentFlightStream(); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java new file mode 100644 index 0000000000..71db29fe52 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java @@ -0,0 +1,278 @@ +/* + * 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.arrow.driver.jdbc; + +import java.sql.SQLException; +import java.util.concurrent.Executor; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.LockSupport; +import java.util.function.Function; +import org.apache.arrow.driver.jdbc.client.PollBackoff; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation.PollAnswer; +import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue; +import org.apache.arrow.flight.FlightRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Chains PollFlightInfo continuations in the background while the application reads a progressive + * result. It is the poller of the model in {@code formal/pollinfo-poll-ahead/PollAhead.tla}. + * + *

The poller runs one step at a time: pause if unread endpoints are at the limit, poll the held + * continuation once, queue the appended endpoints (and mark the queue "no more expected" in the + * same locked step when the query is complete), then back off if the answer added nothing. It runs + * on the connection's poller pool, never on the stream reader pool. At the limit it pauses and + * returns its thread; the reader resumes it when it frees a slot. + * + *

At most one party runs the poller at any moment (the {@code owned} flag). If a resume finds + * the pool busy, the poller is orphaned and the reader runs it inline when it would otherwise wait + * for more endpoints, which is the behavior of the polling-in-{@code next()} path. + */ +final class EndpointPoller { + private static final Logger LOGGER = LoggerFactory.getLogger(EndpointPoller.class); + private static final int SUBMIT_ATTEMPTS = 10; + private static final long SUBMIT_RETRY_PARK_NANOS = 100_000L; + + /** The poller's lifecycle. */ + enum State { + RUNNING, + POLLING, + PAUSED, + BACKOFF, + FINISHED, + FAILED, + STOPPED + } + + /** Receives each successful answer: queues its appended endpoints and the continuation flag. */ + @FunctionalInterface + interface AnswerSink { + void accept(PollAnswer answer) throws SQLException; + } + + private final FlightEndpointDataQueue queue; + private final PollInfoOperation operation; + private final Executor executor; + private final AnswerSink sink; + private final Function failureMapper; + private final Runnable onFinished; + private final PollBackoff backoff; + + private final AtomicBoolean owned = new AtomicBoolean(); + private final AtomicBoolean orphaned = new AtomicBoolean(); + private volatile boolean stopped; + private volatile State state = State.RUNNING; + + EndpointPoller( + final FlightEndpointDataQueue queue, + final PollInfoOperation operation, + final Executor executor, + final AnswerSink sink, + final Function failureMapper, + final Runnable onFinished, + final long maxBackoffMillis) { + this.queue = queue; + this.operation = operation; + this.executor = executor; + this.sink = sink; + this.failureMapper = failureMapper; + this.onFinished = onFinished; + this.backoff = new PollBackoff(maxBackoffMillis); + } + + State state() { + return state; + } + + /** + * Starts polling on the executor. + * + * @return false if the executor rejected the task; the poller is then unused. + */ + boolean start() { + owned.set(true); + if (submit()) { + return true; + } + owned.set(false); + state = State.STOPPED; + return false; + } + + /** Stops the poller. Cancelling the operation ends an open poll and a backoff wait. */ + void stop() { + stopped = true; + state = State.STOPPED; + } + + /** + * Resumes a paused poller. Called, with no queue lock held, once the pause flag was cleared under + * the queue lock. + */ + void resume() { + if (stopped || !owned.compareAndSet(false, true)) { + return; + } + handBack(); + } + + /** + * Called by the reader when it would otherwise wait for more endpoints. If the poller has no + * thread (a resume was rejected), polls on the reader's thread until an answer adds endpoints. + * + * @return true if it polled, so the reader should look at the queue again. + */ + boolean runInlineIfOrphaned() { + if (stopped || !orphaned.compareAndSet(true, false)) { + return false; + } + try { + drive(true); + } catch (final RuntimeException e) { + fail(e); + } + return true; + } + + private boolean submit() { + for (int attempt = 1; attempt <= SUBMIT_ATTEMPTS; attempt++) { + try { + executor.execute(this::runOnPool); + return true; + } catch (final RejectedExecutionException e) { + // A pool thread that has just finished a task may not be waiting for work yet. + if (attempt < SUBMIT_ATTEMPTS) { + LockSupport.parkNanos(SUBMIT_RETRY_PARK_NANOS); + } + } + } + return false; + } + + // Gives the owned poller to the pool, or leaves it for the reader to run inline. + private void handBack() { + if (!submit()) { + orphaned.set(true); + queue.wakeReader(); + } + } + + private void runOnPool() { + try { + drive(false); + } catch (final RuntimeException e) { + fail(e); + } + } + + private void drive(final boolean inline) { + while (true) { + if (stopped || queue.isClosed() || queue.failure() != null) { + state = State.STOPPED; + return; + } + state = State.RUNNING; + // PollerPause: the limit check and the pause are one step under the queue lock. + if (!inline + && queue.pauseIfFull( + () -> { + state = State.PAUSED; + owned.set(false); + })) { + return; + } + + state = State.POLLING; + final PollAnswer answer; + try { + answer = operation.pollOnce(); + } catch (final FlightRuntimeException e) { + onPollFailed(e); + return; + } + if (stopped || queue.isClosed()) { + // PollerDrop: the answer to a poll that cancel interrupted is discarded. + state = State.STOPPED; + return; + } + if (answer == null) { + queue.fail(new SQLException("Continuation PollFlightInfo has no continuation to poll")); + state = State.FAILED; + return; + } + + // PollerApply: queue the appended endpoints and, if the query is complete, finish in the + // same step under the queue lock. + try { + sink.accept(answer); + } catch (final SQLException e) { + queue.fail(e); + state = State.FAILED; + return; + } catch (final RuntimeException e) { + if (stopped || queue.isClosed()) { + state = State.STOPPED; + } else { + fail(e); + } + return; + } + if (!answer.hasContinuation()) { + state = State.FINISHED; + onFinished.run(); + return; + } + if (answer.addedEndpoints()) { + backoff.reset(); + if (inline) { + // The reader has endpoints to read again; give the poller back to the pool. + handBack(); + return; + } + continue; + } + state = State.BACKOFF; + if (!operation.backoff(backoff.nextDelayMillis())) { + if (stopped || queue.isClosed()) { + state = State.STOPPED; + } else { + state = State.FAILED; + queue.fail(new SQLException("Interrupted while waiting for the next PollFlightInfo")); + } + return; + } + } + } + + private void onPollFailed(final FlightRuntimeException e) { + if (stopped || queue.isClosed()) { + // Cancel or close ended the open poll. + state = State.STOPPED; + return; + } + state = State.FAILED; + queue.fail(failureMapper.apply(e)); + } + + private void fail(final RuntimeException e) { + LOGGER.debug("PollFlightInfo poller failed unexpectedly", e); + state = State.FAILED; + queue.fail(new SQLException("Continuation PollFlightInfo failed", e)); + } +} diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index e8a65f15f1..d8f20755ed 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -161,111 +161,7 @@ public List getStreams(final FlightInfo flightInfo) try { for (FlightEndpoint endpoint : flightInfo.getEndpoints()) { - if (endpoint.getLocations().isEmpty()) { - // Create a stream using the current client only and do not close the client at - // the end. - endpoints.add( - new CloseableEndpointStreamPair( - sqlClient.getStream(endpoint.getTicket(), getOptions()), null)); - } else { - // Clone the builder and then set the new endpoint on it. - - // GH-38574: Currently a new FlightClient will be made for each partition that - // returns a - // non-empty Location then disposed of. It may be better to cache clients - // because a server - // may report the same Locations. It would also be good to identify when the - // reported - // location - // is the same as the original connection's Location and skip creating a - // FlightClient in - // that scenario. - // Also copy the cache to the client so we can share a cache. Cache needs to - // cache - // negative attempts too. - List exceptions = new ArrayList<>(); - CloseableEndpointStreamPair stream = null; - FlightLocationQueue locations = - new FlightLocationQueue(flightClientCache, endpoint.getLocations()); - while (locations.hasNext()) { - Location location = locations.next(); - final URI endpointUri = location.getUri(); - if (endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION)) { - stream = - new CloseableEndpointStreamPair( - sqlClient.getStream(endpoint.getTicket(), getOptions()), null); - break; - } - final boolean encryptEndpoint = - endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS); - if (builder.useEncryption && !encryptEndpoint) { - exceptions.add( - new SQLException( - String.format( - "Refusing to connect to endpoint location %s without encryption " - + "because the connection to %s is encrypted.", - endpointUri, builder.getLocation().getUri()))); - continue; - } - final Builder builderForEndpoint = - new Builder(ArrowFlightSqlClientHandler.this.builder) - .withHost(endpointUri.getHost()) - .withPort(endpointUri.getPort()) - .withEncryption(encryptEndpoint) - .withHostnameOverride(builder.getHostnameOverrideForEndpoint(endpointUri)) - .withClientCache(flightClientCache) - .withConnectTimeout(builder.connectTimeout); - - ArrowFlightSqlClientHandler endpointHandler = null; - try { - endpointHandler = builderForEndpoint.build(); - stream = - new CloseableEndpointStreamPair( - endpointHandler.sqlClient.getStream( - endpoint.getTicket(), endpointHandler.getOptions()), - endpointHandler.sqlClient); - // Make sure we actually get data from the server - stream.getStream().getSchema(); - } catch (Exception ex) { - if (endpointHandler != null) { - // If the exception is related to connectivity, mark the client as a dud. - if (flightClientCache != null) { - if (ex instanceof FlightRuntimeException - && ((FlightRuntimeException) ex).status().code() - == FlightStatusCode.UNAVAILABLE - && - // IOException covers SocketException and Netty's (private) - // AnnotatedSocketException - // We are looking for things like "Network is unreachable" - ex.getCause() instanceof IOException) { - flightClientCache.markLocationAsDud(location.toString()); - } - } - - AutoCloseables.close(endpointHandler); - } - exceptions.add(ex); - continue; - } - - if (flightClientCache != null) { - flightClientCache.markLocationAsReachable(location.toString()); - } - break; - } - if (stream != null) { - endpoints.add(stream); - } else if (exceptions.isEmpty()) { - // This should never happen... - throw new IllegalStateException("Could not connect to endpoint and no errors occurred"); - } else { - Exception ex = exceptions.remove(0); - while (!exceptions.isEmpty()) { - ex.addSuppressed(exceptions.remove(exceptions.size() - 1)); - } - throw ex; - } - } + endpoints.add(getStream(endpoint)); } } catch (Exception outerException) { try { @@ -282,6 +178,126 @@ public List getStreams(final FlightInfo flightInfo) return endpoints; } + /** + * Opens a single DoGet stream for one endpoint, trying the endpoint's locations in order. + * + * @param endpoint The {@link FlightEndpoint} to read. + * @return the open stream; the caller owns and must close it. + */ + public CloseableEndpointStreamPair getStream(final FlightEndpoint endpoint) throws SQLException { + try { + return openStream(endpoint); + } catch (SQLException e) { + throw e; + } catch (Exception e) { + throw new SQLException(e); + } + } + + private CloseableEndpointStreamPair openStream(final FlightEndpoint endpoint) throws Exception { + if (endpoint.getLocations().isEmpty()) { + // Create a stream using the current client only and do not close the client at + // the end. + return new CloseableEndpointStreamPair( + sqlClient.getStream(endpoint.getTicket(), getOptions()), null); + } + // Clone the builder and then set the new endpoint on it. + + // GH-38574: Currently a new FlightClient will be made for each partition that + // returns a + // non-empty Location then disposed of. It may be better to cache clients + // because a server + // may report the same Locations. It would also be good to identify when the + // reported + // location + // is the same as the original connection's Location and skip creating a + // FlightClient in + // that scenario. + // Also copy the cache to the client so we can share a cache. Cache needs to + // cache + // negative attempts too. + List exceptions = new ArrayList<>(); + CloseableEndpointStreamPair stream = null; + FlightLocationQueue locations = + new FlightLocationQueue(flightClientCache, endpoint.getLocations()); + while (locations.hasNext()) { + Location location = locations.next(); + final URI endpointUri = location.getUri(); + if (endpointUri.getScheme().equals(LocationSchemes.REUSE_CONNECTION)) { + stream = + new CloseableEndpointStreamPair( + sqlClient.getStream(endpoint.getTicket(), getOptions()), null); + break; + } + final boolean encryptEndpoint = endpointUri.getScheme().equals(LocationSchemes.GRPC_TLS); + if (builder.useEncryption && !encryptEndpoint) { + exceptions.add( + new SQLException( + String.format( + "Refusing to connect to endpoint location %s without encryption " + + "because the connection to %s is encrypted.", + endpointUri, builder.getLocation().getUri()))); + continue; + } + final Builder builderForEndpoint = + new Builder(ArrowFlightSqlClientHandler.this.builder) + .withHost(endpointUri.getHost()) + .withPort(endpointUri.getPort()) + .withEncryption(encryptEndpoint) + .withHostnameOverride(builder.getHostnameOverrideForEndpoint(endpointUri)) + .withClientCache(flightClientCache) + .withConnectTimeout(builder.connectTimeout); + + ArrowFlightSqlClientHandler endpointHandler = null; + try { + endpointHandler = builderForEndpoint.build(); + stream = + new CloseableEndpointStreamPair( + endpointHandler.sqlClient.getStream( + endpoint.getTicket(), endpointHandler.getOptions()), + endpointHandler.sqlClient); + // Make sure we actually get data from the server + stream.getStream().getSchema(); + } catch (Exception ex) { + if (endpointHandler != null) { + // If the exception is related to connectivity, mark the client as a dud. + if (flightClientCache != null) { + if (ex instanceof FlightRuntimeException + && ((FlightRuntimeException) ex).status().code() == FlightStatusCode.UNAVAILABLE + && + // IOException covers SocketException and Netty's (private) + // AnnotatedSocketException + // We are looking for things like "Network is unreachable" + ex.getCause() instanceof IOException) { + flightClientCache.markLocationAsDud(location.toString()); + } + } + + AutoCloseables.close(endpointHandler); + } + exceptions.add(ex); + continue; + } + + if (flightClientCache != null) { + flightClientCache.markLocationAsReachable(location.toString()); + } + break; + } + if (stream != null) { + return stream; + } else if (exceptions.isEmpty()) { + // This should never happen... + throw new IllegalStateException("Could not connect to endpoint and no errors occurred"); + } else { + Exception ex = exceptions.remove(0); + while (!exceptions.isEmpty()) { + ex.addSuppressed(exceptions.remove(exceptions.size() - 1)); + } + throw ex; + } + } + /** * Makes an RPC "getInfo" request based on the provided {@code query} object. * diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollBackoff.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollBackoff.java new file mode 100644 index 0000000000..9f401aef52 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollBackoff.java @@ -0,0 +1,48 @@ +/* + * 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.arrow.driver.jdbc.client; + +/** + * Exponential backoff between PollFlightInfo answers that add no endpoints: 100 ms, doubling up to + * a maximum. Not thread safe; each poll loop owns one instance. + */ +public final class PollBackoff { + /** Default longest wait, in milliseconds. */ + public static final long DEFAULT_MAX_MILLIS = 5000L; + + private static final long INITIAL_MILLIS = 100L; + + private final long maxMillis; + private long nextMillis = INITIAL_MILLIS; + + /** Create a backoff capped at {@code maxMillis} (at least 1). */ + public PollBackoff(final long maxMillis) { + this.maxMillis = Math.max(1L, maxMillis); + } + + /** The delay to wait now; the following delay doubles, up to the cap. */ + public long nextDelayMillis() { + final long delay = Math.min(nextMillis, maxMillis); + nextMillis = Math.min(maxMillis, nextMillis * 2); + return delay; + } + + /** Start again at the initial delay, after an answer that added endpoints. */ + public void reset() { + nextMillis = INITIAL_MILLIS; + } +} diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java index 6495f5081d..040b7327f5 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -20,6 +20,7 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; @@ -46,6 +47,8 @@ public final class PollInfoOperation implements AutoCloseable { private final boolean progressive; private final Context.CancellableContext context; private final AtomicBoolean cancelled = new AtomicBoolean(); + private final CountDownLatch cancelLatch = new CountDownLatch(1); + private volatile long maxBackoffMillis = PollBackoff.DEFAULT_MAX_MILLIS; private final AtomicBoolean cancelFlightInfoAttempted = new AtomicBoolean(); private volatile FlightInfo latestFlightInfo; private volatile FlightDescriptor continuationDescriptor; @@ -98,6 +101,7 @@ CallOption[] options(final CallOption[] baseOptions) { /** Cancel the active PollFlightInfo call, if any. */ public void cancel() { cancelled.set(true); + cancelLatch.countDown(); context.cancel(null); final Runnable cleanup = cancelFlightInfo; if (cleanup != null) { @@ -140,19 +144,106 @@ synchronized void complete(final FlightInfo flightInfo) { continuationDescriptor = null; } - /** Poll until another endpoint is appended, the query completes, or the poll fails. */ - public synchronized FlightInfo pollNextAvailable() { + /** Set the longest wait between answers that add no endpoints. */ + public void setMaxBackoffMillis(final long maxBackoffMillis) { + this.maxBackoffMillis = Math.max(1L, maxBackoffMillis); + } + + /** The longest wait between answers that add no endpoints. */ + public long maxBackoffMillis() { + return maxBackoffMillis; + } + + /** + * Poll until another endpoint is appended, the query completes, or the poll fails. After an + * answer that adds nothing while the query is still running, wait with exponential backoff (100 + * ms doubling up to {@link #maxBackoffMillis()}) before the next poll. + */ + public FlightInfo pollNextAvailable() { final int previousEndpointCount = endpointCount(latestFlightInfo); + final PollBackoff backoff = new PollBackoff(maxBackoffMillis); while (continuationDescriptor != null) { remember(poll(continuationDescriptor)); if (endpointCount(latestFlightInfo) > previousEndpointCount || continuationDescriptor == null) { return latestFlightInfo; } + if (!backoff(backoff.nextDelayMillis())) { + throw CallStatus.CANCELLED.withDescription("Statement canceled").toRuntimeException(); + } } return latestFlightInfo; } + /** + * Poll the held continuation exactly once and remember the answer. The operation monitor is not + * held across the RPC, so {@link #cancel()} always gets through. + * + * @return the answer, or {@code null} when no continuation is held. + */ + public PollAnswer pollOnce() { + final FlightDescriptor descriptor = continuationDescriptor; + if (descriptor == null) { + return null; + } + final PollInfo pollInfo = poll(descriptor); + synchronized (this) { + final int before = endpointCount(latestFlightInfo); + remember(pollInfo); + return new PollAnswer( + latestFlightInfo, + endpointCount(latestFlightInfo) > before, + continuationDescriptor != null); + } + } + + /** + * Wait for the backoff delay, but never past the operation deadline. Returns early, with {@code + * false}, when the operation is cancelled or the thread is interrupted (the interrupt flag is + * restored). + */ + public boolean backoff(final long delayMillis) { + long delayNanos = TimeUnit.MILLISECONDS.toNanos(delayMillis); + if (deadlineNanos != NO_DEADLINE) { + delayNanos = Math.min(delayNanos, Math.max(0L, remainingTimeoutNanos())); + } + try { + return !cancelLatch.await(delayNanos, TimeUnit.NANOSECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + /** The result of one continuation poll. */ + public static final class PollAnswer { + private final FlightInfo flightInfo; + private final boolean addedEndpoints; + private final boolean hasContinuation; + + PollAnswer( + final FlightInfo flightInfo, final boolean addedEndpoints, final boolean hasContinuation) { + this.flightInfo = flightInfo; + this.addedEndpoints = addedEndpoints; + this.hasContinuation = hasContinuation; + } + + /** The cumulative FlightInfo of this answer. */ + public FlightInfo flightInfo() { + return flightInfo; + } + + /** Whether this answer published more endpoints than the previous one. */ + public boolean addedEndpoints() { + return addedEndpoints; + } + + /** Whether the query is still running (the answer carries a continuation). */ + public boolean hasContinuation() { + return hasContinuation; + } + } + FlightInfo latestFlightInfo() { return latestFlightInfo; } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java index 912e5bf9d2..d00e41baad 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java @@ -211,6 +211,28 @@ public boolean usePollInfo() { return ArrowFlightConnectionProperty.USE_POLL_INFO.getBoolean(properties); } + /** + * Most queued, unread endpoints during progressive PollFlightInfo execution. Negative means auto: + * {@code max(2, threadPoolSize)}. Zero disables background polling (the reader polls inside + * {@code next()}). + */ + public int pollInfoPrefetch() { + final int configured = ArrowFlightConnectionProperty.POLL_INFO_PREFETCH.getInteger(properties); + return configured < 0 ? Math.max(2, threadPoolSize()) : configured; + } + + /** Size of the connection's pool of background PollFlightInfo pollers. */ + public int pollInfoPollerThreads() { + return Math.max( + 1, ArrowFlightConnectionProperty.POLL_INFO_POLLER_THREADS.getInteger(properties)); + } + + /** Longest wait, in milliseconds, between PollFlightInfo answers that add no endpoints. */ + public long pollInfoMaxBackoffMs() { + return Math.max( + 1L, ArrowFlightConnectionProperty.POLL_INFO_MAX_BACKOFF_MS.getInteger(properties)); + } + /** * Gets the {@link CallOption}s from this {@link ConnectionConfig}. * @@ -298,6 +320,9 @@ public enum ArrowFlightConnectionProperty implements ConnectionProperty { CONNECT_TIMEOUT_MILLIS("connectTimeoutMs", 10000, Type.NUMBER, false), USE_CLIENT_CACHE("useClientCache", true, Type.BOOLEAN, false), USE_POLL_INFO("usePollInfo", true, Type.BOOLEAN, false), + POLL_INFO_PREFETCH("pollInfoPrefetch", -1, Type.NUMBER, false), + POLL_INFO_POLLER_THREADS("pollInfoPollerThreads", 4, Type.NUMBER, false), + POLL_INFO_MAX_BACKOFF_MS("pollInfoMaxBackoffMs", 5000, Type.NUMBER, false), // OAuth configuration properties OAUTH_FLOW("oauth.flow", null, Type.STRING, false), diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java index 7c1c569fda..fa821e20d7 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java @@ -17,14 +17,20 @@ package org.apache.arrow.driver.jdbc.utils; import static java.lang.String.format; -import static java.util.Collections.synchronizedSet; import static org.apache.arrow.util.Preconditions.checkNotNull; import static org.apache.arrow.util.Preconditions.checkState; import java.sql.SQLException; import java.sql.SQLTimeoutException; +import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionService; @@ -33,9 +39,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.BooleanSupplier; import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightRuntimeException; import org.apache.arrow.flight.FlightStream; import org.apache.calcite.avatica.AvaticaConnection; @@ -55,19 +64,64 @@ * enqueue(FlightStream) *

  • Repeat from (3) until next() returns null. * + * + *

    A queue created with an {@link EndpointOpener} additionally supports progressive results. + * Endpoints are handed over with {@link #addEndpoints(List, boolean)} and stay pending until fewer + * than {@code maxOpen} streams are open and unread; only then is their stream opened. While more + * endpoints may still arrive, {@link #next()} waits instead of returning {@code null}. + * + *

    All state shared between the reader (the thread calling {@link #next()}) and a background + * poller is guarded by one lock. The lock is never held across {@code Future.get()}, {@code + * CompletionService.take()/poll()}, or an RPC (opening a stream); a condition wait releases it. */ public class FlightEndpointDataQueue implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(FlightEndpointDataQueue.class); + + /** Opens the DoGet stream of one endpoint. Called without the queue lock held. */ + @FunctionalInterface + public interface EndpointOpener { + CloseableEndpointStreamPair open(FlightEndpoint endpoint) throws SQLException; + } + private final CompletionService completionService; - private final Set> futures = synchronizedSet(new HashSet<>()); - private final Set endpointsToClose = - synchronizedSet(new HashSet<>()); - private final AtomicBoolean closed = new AtomicBoolean(); + private final EndpointOpener opener; + + private final ReentrantLock lock = new ReentrantLock(); + private final Condition changed = lock.newCondition(); + private final Object closeMonitor = new Object(); + + // Everything below is guarded by `lock`, unless it is volatile. + private final Map, CloseableEndpointStreamPair> futures = + new HashMap<>(); + private final Set endpointsToClose = new HashSet<>(); + private final Deque pending = new ArrayDeque<>(); + private int maxOpen = Integer.MAX_VALUE; + // Streams opened (or being opened) through the opener whose endpoint is not finished yet. + private int openUnread; + // The part of openUnread whose stream is being opened outside the lock. + private int opening; + private boolean moreExpected; + private boolean paused; + private Runnable resumeAction; + private BooleanSupplier idleAction; + private volatile boolean shutdown; + private volatile SQLException failure; + // Guarded by closeMonitor. + private boolean teardownDone; /** Instantiate a new FlightStreamQueue. */ protected FlightEndpointDataQueue( final CompletionService executorService) { + this(executorService, null, Integer.MAX_VALUE); + } + + private FlightEndpointDataQueue( + final CompletionService executorService, + final EndpointOpener opener, + final int maxOpen) { completionService = checkNotNull(executorService); + this.opener = opener; + this.maxOpen = maxOpen; } /** @@ -81,33 +135,376 @@ public static FlightEndpointDataQueue createNewQueue(final ExecutorService servi } /** - * Gets whether this queue is closed. + * Creates a queue that opens endpoint streams itself and keeps at most {@code maxOpen} of them + * open and unread; the other endpoints wait as pending until a stream finishes. + * + * @param service the service that reads the streams. + * @param maxOpen the most open, unread streams; {@link Integer#MAX_VALUE} opens eagerly. + * @param opener opens one endpoint's stream. + * @return a new queue. + */ + public static FlightEndpointDataQueue createNewQueue( + final ExecutorService service, final int maxOpen, final EndpointOpener opener) { + checkState(maxOpen >= 1, "maxOpen must be at least 1"); + return new FlightEndpointDataQueue( + new ExecutorCompletionService<>(service), checkNotNull(opener), maxOpen); + } + + /** + * Gets whether this queue is closed. This turns true as soon as {@link #close()} starts, so a + * reader woken by a cancel sees it. * * @return a boolean indicating whether this resource is closed. */ public boolean isClosed() { - return closed.get(); + return shutdown; } - /** Auxiliary functional interface for getting ready-to-consume FlightStreams. */ - @FunctionalInterface - interface EndpointStreamSupplier { - Future get() throws SQLException; + /** Wakes a reader that is waiting for more endpoints so it re-checks the queue. */ + public void wakeReader() { + lock.lock(); + try { + changed.signalAll(); + } finally { + lock.unlock(); + } + } + + /** The failure recorded by {@link #fail(SQLException)}, or null. */ + public SQLException failure() { + return failure; + } + + /** Called by the reader, with no lock held, when it is about to wait for more endpoints. */ + public void setIdleAction(final BooleanSupplier idleAction) { + lock.lock(); + try { + this.idleAction = idleAction; + } finally { + lock.unlock(); + } + } + + /** Called, with no lock held, when the unread count drops below the limit of a paused poller. */ + public void setResumeAction(final Runnable resumeAction) { + lock.lock(); + try { + this.resumeAction = resumeAction; + } finally { + lock.unlock(); + } + } + + /** The number of endpoints queued and not finished: pending plus open-unread. */ + public int unreadCount() { + lock.lock(); + try { + return unreadLocked(); + } finally { + lock.unlock(); + } + } + + /** The number of streams open (or being opened) and not finished. */ + public int openUnreadCount() { + lock.lock(); + try { + return openUnread; + } finally { + lock.unlock(); + } + } + + /** Whether more endpoints may still be added. */ + public boolean isMoreExpected() { + lock.lock(); + try { + return moreExpected; + } finally { + lock.unlock(); + } + } + + private int unreadLocked() { + return pending.size() + openUnread; + } + + /** + * Atomically queues newly published endpoints and records whether more may follow. When {@code + * moreExpected} is false this is the last call, so the reader can see the final endpoints and the + * end of results in one step. Endpoints beyond the open limit stay pending; the others are opened + * (without the lock) before this method returns. + * + * @throws IllegalStateException if the queue is closed. + * @throws SQLException if a stream cannot be opened; the queue is then failed with it. + */ + public void addEndpoints(final List endpoints, final boolean moreExpected) + throws SQLException { + checkState(opener != null, "This queue has no endpoint opener"); + final List toOpen; + lock.lock(); + try { + checkOpen(); + pending.addAll(endpoints); + this.moreExpected = moreExpected; + toOpen = reserveSlotsLocked(); + changed.signalAll(); + } finally { + lock.unlock(); + } + openReserved(toOpen); + } + + /** + * Stops waiting for a poller and lifts the open limit: nothing more is expected through {@link + * #addEndpoints}, and pending endpoints open now. + */ + public void disablePollAhead() throws SQLException { + final List toOpen; + lock.lock(); + try { + maxOpen = Integer.MAX_VALUE; + moreExpected = false; + paused = false; + toOpen = reserveSlotsLocked(); + changed.signalAll(); + } finally { + lock.unlock(); + } + openReserved(toOpen); + } + + /** + * Atomically checks the limit and pauses the poller. Returns true, after running {@code onPaused} + * under the lock, when more endpoints are expected but unread endpoints are at the limit. Because + * the count check, the pause and {@code onPaused} are one step under the same lock the reader + * uses to decrement the count and wake the poller, a wakeup cannot be lost. + */ + public boolean pauseIfFull(final Runnable onPaused) { + lock.lock(); + try { + if (shutdown || failure != null || !moreExpected || unreadLocked() < maxOpen) { + return false; + } + paused = true; + onPaused.run(); + return true; + } finally { + lock.unlock(); + } + } + + /** + * Fail fast: records the failure, drops pending endpoints, cancels every open stream (which drops + * its buffered batches), and makes {@link #next()} rethrow {@code cause}. The first failure wins; + * a closed queue ignores it. + */ + public void fail(final SQLException cause) { + checkNotNull(cause); + final List toCancel; + lock.lock(); + try { + if (shutdown || failure != null) { + return; + } + failure = cause; + pending.clear(); + moreExpected = false; + toCancel = new ArrayList<>(endpointsToClose); + changed.signalAll(); + } finally { + lock.unlock(); + } + for (final CloseableEndpointStreamPair endpoint : toCancel) { + try { + endpoint.getStream().cancel("Query failed.", null); + } catch (final RuntimeException e) { + LOGGER.debug("Failed to cancel a FlightStream after a failure.", e); + } + } + } + + // Moves pending endpoints into the open-unread count while fewer than maxOpen are open. + private List reserveSlotsLocked() { + if (opener == null || pending.isEmpty() || openUnread >= maxOpen) { + return Collections.emptyList(); + } + final List reserved = new ArrayList<>(); + while (!pending.isEmpty() && openUnread < maxOpen) { + reserved.add(pending.poll()); + openUnread++; + opening++; + } + return reserved; + } + + // Opens reserved endpoints without the lock. On failure, the rest are released and the queue + // fails. + private void openReserved(final List reserved) throws SQLException { + for (int index = 0; index < reserved.size(); index++) { + final CloseableEndpointStreamPair stream; + try { + stream = opener.open(reserved.get(index)); + } catch (final SQLException | RuntimeException e) { + final SQLException cause = + e instanceof SQLException ? (SQLException) e : new SQLException(e); + releaseReservations(reserved.size() - index); + fail(cause); + throw cause; + } + try { + register(stream); + } catch (final RuntimeException e) { + releaseReservations(reserved.size() - index - 1); + fail(new SQLException("Failed to start reading an endpoint stream", e)); + throw e; + } + } + } + + private void releaseReservations(final int count) { + lock.lock(); + try { + opening -= count; + openUnread -= count; + changed.signalAll(); + } finally { + lock.unlock(); + } + } + + // Adds an opened stream and starts reading it. Drops it if the queue was closed or failed. + private void register(final CloseableEndpointStreamPair stream) { + boolean registered = false; + RuntimeException rejected = null; + lock.lock(); + try { + opening--; + if (!shutdown && failure == null) { + endpointsToClose.add(stream); + try { + futures.put(submitReader(stream), stream); + registered = true; + } catch (final RuntimeException e) { + endpointsToClose.remove(stream); + rejected = e; + } + } + if (!registered) { + openUnread--; + } + changed.signalAll(); + } finally { + lock.unlock(); + } + if (!registered) { + closeQuietly(stream); + } + if (rejected != null) { + throw rejected; + } } - private CloseableEndpointStreamPair next(final EndpointStreamSupplier endpointStreamSupplier) + private Future submitReader( + final CloseableEndpointStreamPair endpointRequest) { + return completionService.submit( + () -> { + // `FlightStream#next` will block until new data can be read or stream is over. + while (endpointRequest.getStream().next()) { + if (endpointRequest.getStream().getRoot().getRowCount() > 0) { + return endpointRequest; + } + } + return null; + }); + } + + private static void closeQuietly(final CloseableEndpointStreamPair endpoint) { + try { + endpoint.close(); + } catch (final Exception e) { + LOGGER.debug("Failed to close a FlightStream.", e); + } + } + + // The reader finished an endpoint: free its slot, open pending endpoints, and wake the poller. + private void onStreamFinished(final CloseableEndpointStreamPair finished) throws SQLException { + final List toOpen; + Runnable resume = null; + lock.lock(); + try { + if (opener != null) { + endpointsToClose.remove(finished); + openUnread--; + toOpen = reserveSlotsLocked(); + if (paused && unreadLocked() < maxOpen) { + paused = false; + resume = resumeAction; + } + } else { + toOpen = Collections.emptyList(); + } + changed.signalAll(); + } finally { + lock.unlock(); + } + if (opener != null && finished != null) { + closeQuietly(finished); + } + if (resume != null) { + resume.run(); + } + openReserved(toOpen); + } + + private CloseableEndpointStreamPair awaitNext( + final boolean timed, final long timeoutValue, final TimeUnit timeoutUnit) throws SQLException { - checkOpen(); - while (!futures.isEmpty()) { - final Future future = endpointStreamSupplier.get(); - futures.remove(future); + final long deadlineNanos = timed ? System.nanoTime() + timeoutUnit.toNanos(timeoutValue) : 0L; + boolean idleTried = false; + while (true) { + boolean runIdle = false; + BooleanSupplier idle = null; + lock.lock(); try { - final CloseableEndpointStreamPair endpoint = future.get(); - // Get the next FlightStream that has a root with content. - if (endpoint != null) { - return endpoint; + checkOpen(); + throwIfFailed(); + if (futures.isEmpty()) { + final boolean nothingQueued = pending.isEmpty() && opening == 0; + if (nothingQueued && !moreExpected) { + return null; + } + if (nothingQueued && idleAction != null && !idleTried) { + runIdle = true; + idle = idleAction; + } else { + awaitChange(timed, deadlineNanos, timeoutValue, timeoutUnit); + idleTried = false; + continue; + } } + } finally { + lock.unlock(); + } + if (runIdle) { + idleTried = !idle.getAsBoolean(); + continue; + } + + final Future future = + timed ? pollFuture(deadlineNanos, timeoutValue, timeoutUnit) : takeFuture(); + final CloseableEndpointStreamPair source; + lock.lock(); + try { + source = futures.remove(future); + } finally { + lock.unlock(); + } + final CloseableEndpointStreamPair ready; + try { + ready = future.get(); } catch (final ExecutionException e) { + throwIfFailed(); // Unwrap one layer final Throwable cause = e.getCause(); if (cause instanceof FlightRuntimeException) { @@ -117,8 +514,72 @@ private CloseableEndpointStreamPair next(final EndpointStreamSupplier endpointSt } catch (InterruptedException | CancellationException e) { throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); } + // Get the next FlightStream that has a root with content. + if (ready != null) { + throwIfFailed(); + return ready; + } + onStreamFinished(source); + } + } + + // Called with the lock held. Releases it while waiting. + private void awaitChange( + final boolean timed, + final long deadlineNanos, + final long timeoutValue, + final TimeUnit timeoutUnit) + throws SQLException { + try { + if (timed) { + final long remaining = deadlineNanos - System.nanoTime(); + if (remaining <= 0) { + throw new SQLTimeoutException( + String.format("Query timed out after %d %s", timeoutValue, timeoutUnit)); + } + changed.awaitNanos(remaining); + } else { + changed.await(); + } + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + if (timed) { + throw new SQLTimeoutException("Query was interrupted", e); + } + throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); + } + } + + private Future takeFuture() throws SQLException { + try { + return completionService.take(); + } catch (final InterruptedException e) { + throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); + } + } + + private Future pollFuture( + final long deadlineNanos, final long timeoutValue, final TimeUnit timeoutUnit) + throws SQLException { + try { + final Future future = + completionService.poll( + Math.max(0L, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS); + if (future != null) { + return future; + } + } catch (final InterruptedException e) { + throw new SQLTimeoutException("Query was interrupted", e); + } + throw new SQLTimeoutException( + String.format("Query timed out after %d %s", timeoutValue, timeoutUnit)); + } + + private void throwIfFailed() throws SQLException { + final SQLException recorded = failure; + if (recorded != null) { + throw recorded; } - return null; } /** @@ -130,21 +591,7 @@ private CloseableEndpointStreamPair next(final EndpointStreamSupplier endpointSt */ public CloseableEndpointStreamPair next(final long timeoutValue, final TimeUnit timeoutUnit) throws SQLException { - return next( - () -> { - try { - final Future future = - completionService.poll(timeoutValue, timeoutUnit); - if (future != null) { - return future; - } - } catch (final InterruptedException e) { - throw new SQLTimeoutException("Query was interrupted", e); - } - - throw new SQLTimeoutException( - String.format("Query timed out after %d %s", timeoutValue, timeoutUnit)); - }); + return awaitNext(true, timeoutValue, timeoutUnit); } /** @@ -153,18 +600,11 @@ public CloseableEndpointStreamPair next(final long timeoutValue, final TimeUnit * @return a FlightStream that is ready to consume or null if all FlightStreams are ended. */ public CloseableEndpointStreamPair next() throws SQLException { - return next( - () -> { - try { - return completionService.take(); - } catch (final InterruptedException e) { - throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); - } - }); + return awaitNext(false, 0L, TimeUnit.NANOSECONDS); } /** Checks if this queue is open. */ - public synchronized void checkOpen() { + public void checkOpen() { checkState(!isClosed(), format("%s closed", this.getClass().getSimpleName())); } @@ -174,21 +614,17 @@ public void enqueue(final Collection endpointReques } /** Adds given {@link FlightStream} to the queue. */ - public synchronized void enqueue(final CloseableEndpointStreamPair endpointRequest) { + public void enqueue(final CloseableEndpointStreamPair endpointRequest) { checkNotNull(endpointRequest); - checkOpen(); - endpointsToClose.add(endpointRequest); - futures.add( - completionService.submit( - () -> { - // `FlightStream#next` will block until new data can be read or stream is over. - while (endpointRequest.getStream().next()) { - if (endpointRequest.getStream().getRoot().getRowCount() > 0) { - return endpointRequest; - } - } - return null; - })); + lock.lock(); + try { + checkOpen(); + endpointsToClose.add(endpointRequest); + futures.put(submitReader(endpointRequest), endpointRequest); + changed.signalAll(); + } finally { + lock.unlock(); + } } private static boolean isCallStatusCancelled(final Exception e) { @@ -197,54 +633,76 @@ private static boolean isCallStatusCancelled(final Exception e) { } @Override - public synchronized void close() throws SQLException { - if (isClosed()) { - return; - } + public void close() throws SQLException { + // Concurrent closers wait for the first one to finish; the queue lock is held only briefly. + synchronized (closeMonitor) { + if (teardownDone) { + return; + } + final List toClose; + final List> toDrain; + lock.lock(); + try { + shutdown = true; + pending.clear(); + moreExpected = false; + toClose = new ArrayList<>(endpointsToClose); + toDrain = new ArrayList<>(futures.keySet()); + changed.signalAll(); + } finally { + lock.unlock(); + } - final Set exceptions = new HashSet<>(); - try { - for (final CloseableEndpointStreamPair endpointToClose : endpointsToClose) { - try { - endpointToClose.getStream().cancel("Cancelling this FlightStream.", null); - } catch (final Exception e) { - final String errorMsg = "Failed to cancel a FlightStream."; - LOGGER.error(errorMsg, e); - exceptions.add(new SQLException(errorMsg, e)); + final Set exceptions = new HashSet<>(); + try { + for (final CloseableEndpointStreamPair endpointToClose : toClose) { + try { + endpointToClose.getStream().cancel("Cancelling this FlightStream.", null); + } catch (final Exception e) { + final String errorMsg = "Failed to cancel a FlightStream."; + LOGGER.error(errorMsg, e); + exceptions.add(new SQLException(errorMsg, e)); + } } - } - futures.forEach( - future -> { - try { - // TODO: Consider adding a hardcoded timeout? - future.get(); - } catch (final InterruptedException | ExecutionException e) { - // Ignore if future is already cancelled - if (!isCallStatusCancelled(e)) { - final String errorMsg = "Failed consuming a future during close."; - LOGGER.error(errorMsg, e); - exceptions.add(new SQLException(errorMsg, e)); + toDrain.forEach( + future -> { + try { + // TODO: Consider adding a hardcoded timeout? + future.get(); + } catch (final InterruptedException | ExecutionException e) { + // Ignore if future is already cancelled + if (!isCallStatusCancelled(e)) { + final String errorMsg = "Failed consuming a future during close."; + LOGGER.error(errorMsg, e); + exceptions.add(new SQLException(errorMsg, e)); + } } - } - }); - for (final CloseableEndpointStreamPair endpointToClose : endpointsToClose) { + }); + for (final CloseableEndpointStreamPair endpointToClose : toClose) { + try { + endpointToClose.close(); + } catch (final Exception e) { + final String errorMsg = "Failed to close a FlightStream."; + LOGGER.error(errorMsg, e); + exceptions.add(new SQLException(errorMsg, e)); + } + } + } finally { + lock.lock(); try { - endpointToClose.close(); - } catch (final Exception e) { - final String errorMsg = "Failed to close a FlightStream."; - LOGGER.error(errorMsg, e); - exceptions.add(new SQLException(errorMsg, e)); + endpointsToClose.clear(); + futures.clear(); + changed.signalAll(); + } finally { + lock.unlock(); } + teardownDone = true; + } + if (!exceptions.isEmpty()) { + final SQLException sqlException = new SQLException("Failed to close streams."); + exceptions.forEach(sqlException::setNextException); + throw sqlException; } - } finally { - endpointsToClose.clear(); - futures.clear(); - closed.set(true); - } - if (!exceptions.isEmpty()) { - final SQLException sqlException = new SQLException("Failed to close streams."); - exceptions.forEach(sqlException::setNextException); - throw sqlException; } } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java index 24612d34d6..140919db15 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -141,6 +141,26 @@ public void multiStepPollsOnDemandAfterPublishedEndpointIsConsumed() throws Exce assertEquals(0, producer.getFlightInfoCount()); } + @Test + public void pollAheadPollsContinuationsWhileTheApplicationHasNotReadFurther() throws Exception { + producer.configure(Scenario.MULTI_STEP, STATEMENT_FAMILY); + try (Connection connection = connect(true); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + // The application does not call next() again, yet both continuations are polled. + final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (producer.pollDescriptors().size() < 3 && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals(3, producer.pollDescriptors().size()); + assertFalse(resultSet.next()); + } + assertEquals(3, producer.pollDescriptors().size()); + assertEquals(0, producer.cancelFlightInfoCount()); + } + @Test public void preparedParametersAreBoundOnceBeforePolling() throws Exception { producer.configure(Scenario.MULTI_STEP, PREPARED_FAMILY); @@ -307,7 +327,7 @@ public void preparedBindIsCancelledBeforePolling() throws Exception { @Test public void statementCancelInterruptsContinuationAtReadBoundary() throws Exception { producer.configure(Scenario.CANCEL_OBSERVABLE, STATEMENT_FAMILY); - try (Connection connection = connect(true); + try (Connection connection = connect(true, 0); Statement statement = connection.createStatement()) { final AtomicReference failure = new AtomicReference<>(); final AtomicBoolean resultSetCreated = new AtomicBoolean(); @@ -352,6 +372,16 @@ private static Connection connect(final boolean usePollInfo) throws Exception { server.getPort(), usePollInfo)); } + /** Connects with a fixed pollInfoPrefetch; 0 keeps the POC behavior of polling inside next(). */ + private static Connection connect(final boolean usePollInfo, final int pollInfoPrefetch) + throws Exception { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=%s" + + "&pollInfoPrefetch=%d", + server.getPort(), usePollInfo, pollInfoPrefetch)); + } + private static void assertDirectRow(final Connection connection) throws Exception { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { From f9a978cfd23784e96aee7d9df684484a8b656b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 00:44:51 +0000 Subject: [PATCH 25/39] BDX-645: sync the poll-ahead TLA+ model with the implementation Model the code's real steps instead of atomic ones: the resume after unlocking (against the poller's owned flag), stream opening outside the lock into reserved slots, the orphaned poller run inline by the reader, the reader's idle hook and wait, and the two steps of cancel. The model finds that FlightEndpointDataQueue.awaitNext can hang after a rejected resume (stale idleTried); run.sh records it as a known finding and checks the proposed fix. Add broken variants endIgnoresOpening, openNotReserved, ownedClearedLate and noIdleHook. Move the sync commit in the verify skill to d7c3ed4ab and map every action to the new code. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-jdbc-poll-ahead/SKILL.md | 95 +++- formal/pollinfo-poll-ahead/PollAhead.tla | 507 +++++++++++++----- formal/pollinfo-poll-ahead/run.sh | 49 +- 3 files changed, 466 insertions(+), 185 deletions(-) diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md index 8fcefbf479..c868d03bf1 100644 --- a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -1,11 +1,11 @@ --- name: verify-jdbc-poll-ahead -description: Model-check the Flight SQL JDBC progressive PollInfo result path (BDX-645) and its proposed bounded poll-ahead with TLA+. Use before merging any change to ArrowFlightJdbcFlightStreamResultSet, FlightEndpointDataQueue, PollInfoOperation, or the PollingFlightSqlClient poll loop, and when implementing or changing the poll-ahead poller. +description: Model-check the Flight SQL JDBC progressive PollInfo result path (BDX-645) and its bounded poll-ahead with TLA+. Use before merging any change to ArrowFlightJdbcFlightStreamResultSet, FlightEndpointDataQueue, EndpointPoller, PollInfoOperation, or the PollingFlightSqlClient poll loop, and when changing the poll-ahead poller. --- # Verify the JDBC poll-ahead design -The JDBC driver reads a progressive query in two concurrent roles. The **reader** serves `ResultSet.next()` and opens `DoGet` streams. The **poller** sends `PollFlightInfo` continuations. A TLA+ model, `formal/pollinfo-poll-ahead/PollAhead.tla`, checks every interleaving of reader, poller and server, within small bounds. Use this skill to tell whether a change still keeps the promises below. +The JDBC driver reads a progressive query in concurrent roles. The **reader** serves `ResultSet.next()` and opens `DoGet` streams. The **poller** (`EndpointPoller`) sends `PollFlightInfo` continuations from a pool thread. A TLA+ model, `formal/pollinfo-poll-ahead/PollAhead.tla`, checks every interleaving of reader, poller, server and a `cancel()` caller, within small bounds. Use this skill to tell whether a change still keeps the promises below. ## What is verified @@ -17,51 +17,79 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. | `EachEndpointOnce` | Each endpoint is queued for download once, even though every PollInfo repeats all earlier endpoints. | Duplicate rows. | | `ContinuationsOnce` | Each continuation descriptor is sent at most once. | The server rejects the reused descriptor (`FAILED_PRECONDITION` in the conformance server), or the query re-runs. | | `FailFast` | No row reaches the application after the driver saw the query fail or was cancelled. | The application processes data from a failed query. | -| `CancelStopsPolling` | No poll is sent after `Statement.cancel()`, the deadline, or `close()`. | Server work continues after the user cancelled. | +| `CancelStopsPolling` | No poll is sent after `Statement.cancel()`, the deadline, or `close()` has finished stopping the poller. | Server work continues after the user cancelled. | | `Backpressure` | The poller does not poll while unread endpoints are at `pollInfoPrefetch`. | The driver runs ahead of a slow reader without bound. | -| `OpenWithinLimit` | Open, unread `DoGet` streams never exceed the limit. | More open streams, each buffering up to 5 batches, than the setting promises. | +| `OpenWithinLimit` | Open, opening and unread `DoGet` streams never exceed the limit. | More open streams, each buffering up to 5 batches, than the setting promises. | | `NoSpin` | No poll is sent straight after an answer that added nothing. | A busy loop against servers that answer at once. | | `Terminates` | Every result eventually ends or throws, if nobody cancels. | `next()` hangs forever. | +| `InlineMeansPoller` | Structural: when the reader runs the poller inline, the poller is not paused or orphaned. | Two threads drive one continuation chain. | ## Scope, bounds, assumptions -- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled. -- Rows are abstracted: reading an endpoint is one step. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". -- Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked. +- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled, except that a rejected resume is a free choice (`ReaderResumeRejected`). +- Rows are abstracted: reading an endpoint is one step, and an endpoint is either empty (its future yields `null`) or not. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". +- Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked, and neither are the 10 x 100 us resubmit retries (only their outcome). - The server may answer a poll at any moment, including at once with nothing new. -- The reader's end check ("queue empty and poller finished") is assumed to be one atomic read under the queue's lock. The poller's count check and its pause are also one step. The `pauseNotAtomic` variant shows what breaks when they are not. -- The model covers the result path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, or parameter upload. +- Atomic steps in the model, each one a single locked step or RPC answer in the code: + - `Q.addEndpoints`: append, set `moreExpected`, reserve slots, signal (`PollerApply*`). + - `Q.pauseIfFull`: count check, paused flag, and the poller's `owned = false` (`PollerPause`). + - `Q.onStreamFinished`, the part under the lock: free the slot, reserve pending endpoints, clear the paused flag (`AppRead`, `AppReadEmpty`). + - `Q.awaitNext`'s lock-protected check and the start of the wait (`AppEnd`, `AppIdle`, `ReaderWait`). +- Steps the model splits because the code does not do them atomically: + - the resume after unlocking (`ReaderResume`, `ReaderResumeRejected`), against the poller's `owned` flag; + - stream opening outside the lock into reserved slots (`OpenReserved`, `OpenFails`); + - the orphaned poller run inline by the reader (`AppIdle`, `InlineExit`, `PollerApplyHandBack`); + - `cancel()`: the `cancelled` flag, then stop, cancel the operation and close the queue (`AppCancel`, `CancelStop`); + - the reader's idle hook and its wait (`idleTried`). +- Over-approximations (safe, they only add behaviors): any step may open a reserved stream (the code opens it on the thread that reserved it, before that thread goes on); a stream registered after a failure or cancel still counts as open (the code closes it at once). +- Not modeled: a row already buffered when cancel or a failure starts can still reach the application from a `next()` call that was already running (the next call throws). +- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, protocol violations in an answer (`validateAppendOnly`, schema change), the poller pool failing to start (`start()` rejected, then `disablePollAhead`), the timed first wait, or an `Error` (not `RuntimeException`) killing the poller thread. +- **The implementation corresponds to `EagerOpen = FALSE`** for continuations: a queue built with `maxOpen = pollInfoPrefetch`. **Complete answers** (no continuation) **and `pollInfoPrefetch = 0` use the unlimited eager queue** (`maxOpen = Integer.MAX_VALUE`, no poller, the reader polls in `next()`); the model does not cover that path. `EagerOpen = TRUE` is kept only to show the old finding. ## Coverage record -Sync commit: `b444a256006897ebf079dd47596ad978cb4701cc` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). At that commit the POC exists and the poll-ahead poller does not. +Sync commit: `d7c3ed4ab4d30601447bc0518ac05294462b37d3` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). At that commit the poll-ahead poller exists, and the model matches it, including the finding below. -| Model action | Code at the sync commit (`flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`) | +Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. + +| Model action | Code at the sync commit | | --- | --- | -| `PollerSend`, `PollerTake` | `client/PollInfoOperation.java`: `poll`, `pollNextAvailable`. In the POC these run on the reader thread from `ArrowFlightJdbcFlightStreamResultSet.loadNextPublishedEndpoint`. | -| `PollerApply` | `client/PollInfoOperation.java`: `remember`, `validateAppendOnly`. `ArrowFlightJdbcFlightStreamResultSet.java`: `enqueueNewEndpoints`. | -| `AppRead` | `ArrowFlightJdbcFlightStreamResultSet.java`: `next`, `getNextEndpointStream`. `utils/FlightEndpointDataQueue.java`: `next`, `enqueue`. | -| `AppEnd` | `ArrowFlightJdbcFlightStreamResultSet.next` returning false. | -| `AppCancel` | `ArrowFlightStatement.cancel`, `ArrowFlightPreparedStatement.cancel`, `ArrowFlightJdbcFlightStreamResultSet.cancel` and `close`, `client/PollInfoOperation.cancel`. | -| `SrvAnswer` failure branch, `PollerTake` error branch | `ArrowFlightJdbcFlightStreamResultSet.loadNextPublishedEndpoint` catch block. | -| `PollerPause`, `BackoffElapses`, the wake in `AppRead`, the poller pool, deferred stream opening (`EagerOpen = FALSE`) | Proposed only. No code yet. | +| `PollerSend`, `PollerTake` | P `drive` -> O `pollOnce` -> `poll`. The poll runs on a pool thread, or on the reader's thread when run inline. | +| `PollerApplyBackoff`, `PollerApplyGo` | O `remember` (inside `pollOnce`: `validateAppendOnly`, new continuation), then R `appendEndpoints` -> Q `addEndpoints`; then P `drive`: `operation.backoff` (backoff) or the next loop iteration (go). | +| `PollerApplyHandBack` | The same, run inline: P `drive(true)` after an answer that added endpoints calls `handBack` (`submit`, or orphaned again). | +| `PollerApplyFinish` | Q `addEndpoints(list, false)` and P `drive`: `FINISHED`, `onFinished`. | +| `PollerPause`, `PollerPauseEnd`, `PollerCheck` | Q `pauseIfFull` with P `drive`'s `onPaused` (paused flag and `owned.set(false)` under the lock). `PollerPauseEnd` and `PollerCheck` exist only for the broken variants. | +| `PollerSeesFail`, `PollerDrop` | P `drive`: the loop-top check and the check after `pollOnce`. | +| `BackoffElapses` | O `backoff` (cancellable wait), P `drive` `BACKOFF` state. | +| `OpenReserved`, `OpenFails` | Q `openReserved`, `register`, `releaseReservations`, `fail`. The `opening` count is `resv`. | +| `AppRead`, `AppReadEmpty` | R `next` and `loadNextPublishedEndpoint` -> Q `awaitNext` taking a ready future, or a `null` future -> `onStreamFinished` (slot freed, `reserveSlotsLocked`, paused flag cleared). | +| `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). | +| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`). `idleTried` is the local variable in `awaitNext`. | +| `ReaderWait` and the wakes (`WakeRd`) | Q `awaitNext` -> `awaitChange`; `signalAll` in `addEndpoints`, `register`, `releaseReservations`, `fail`, `close`, `wakeReader`. | +| `AppEnd` | Q `awaitNext` returning `null` (futures empty, pending empty, `opening == 0`, `!moreExpected`, under the lock), R `next` returning false. | +| `AppThrow` | Q `awaitNext` -> `checkOpen`, `throwIfFailed`; R `next` top-of-call checks of `cancelled` and `queue.failure()`. | +| `AppCancel`, `CancelStop` | R `cancel` and `close`: `cancelled = true`; then P `stop`, O `cancel`, Q `close`. Also `ArrowFlightStatement.cancel`, `ArrowFlightPreparedStatement.cancel`. | +| `SrvAnswer` failure branch, `PollerTake` error branch | P `onPollFailed` -> Q `fail` (R `mapContinuationFailure`). | ## When to use it Run it when a diff touches any covered file: ```sh -git diff --name-only b444a256006897ebf079dd47596ad978cb4701cc..HEAD -- \ +git diff --name-only d7c3ed4ab4d30601447bc0518ac05294462b37d3..HEAD -- \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java \ + flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollBackoff.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightStatement.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatement.java \ formal/pollinfo-poll-ahead/ ``` -Any output means the model may no longer describe the code. Also use this skill for any new poller class, for example `EndpointPoller`. +Any output means the model may no longer describe the code. Also use this skill for any new class that polls or opens streams on a background thread. ## How to check a change @@ -73,23 +101,32 @@ Any output means the model may no longer describe the code. Also use this skill N=4 formal/pollinfo-poll-ahead/run.sh ``` - The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` must still fail on `OpenWithinLimit` until the finding below is resolved. Every broken variant must fail on its rule. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `finding-stale-idle` must fail on `Terminates` until the finding below is fixed in the code and `IdleFix` becomes the only behavior (then delete the constant, the finding row and the `idleReset` wording, and run the liveness check on the main row). Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the open finding cannot hide a variant that no longer fails. `openNotReserved` only fails from `N=4` on. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. 3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. 4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. 5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. -6. **Move the sync commit** in the coverage record only after you have confirmed that every action still matches the code at the new commit. Update the coverage table at the same time, for example when proposed actions get real code. +6. **Move the sync commit** in the coverage record only after you have confirmed that every action still matches the code at the new commit. Update the coverage table at the same time. Check the non-atomic steps in particular: the resume after unlocking against `owned`, opening outside the lock through reserved slots, the orphaned inline poller and the `idleTried` flag, and the two steps of `cancel()`. + +## Known findings + +### 1. `finding-stale-idle`: `next()` can hang after a rejected resume (open in the code) + +`Terminates` fails on the model of the code at `d7c3ed4ab`. `FlightEndpointDataQueue.awaitNext` keeps a local `idleTried` flag (line 464). It sets it when the idle hook returns false (line 490) and clears it only after a wait (line 482). If an endpoint finishes between those two, the flag stays set. Shortest path, with a limit of 2 (`finding-stale-idle`, 16 steps): + +1. The application has read the first endpoint. `awaitNext` finds nothing queued, `moreExpected` true. It calls the idle hook (`EndpointPoller.runInlineIfOrphaned`), which returns false because the poller is not orphaned, so `idleTried = true` (line 490). +2. Before the reader takes the lock again (line 468), the poller's open poll answers with two new endpoints. `addEndpoints` reserves both slots, `openReserved` registers the streams (futures not empty), and the poller pauses at the limit (`pauseIfFull`). +3. The reader takes the first new stream's future. It yields `null` (an endpoint with no rows). `onStreamFinished` frees a slot, clears the paused flag and runs the resume (`EndpointPoller.resume` -> `handBack`). The pool rejects the submit 10 times, so the poller is orphaned (`orphaned.set(true)`, `wakeReader()` on the reader's own thread, so nobody is waiting). +4. The second new stream also yields `null`. The loop reaches the empty-futures branch with nothing queued and `moreExpected` true. `!idleTried` is false (line 477), so the reader does not run the orphaned poller. It waits (line 481) for a signal nobody will send. -## Known finding +The code can take this path, but it is narrow: the poller must answer and register a stream inside the reader's few instructions between lines 490 and 468, the connection's poller pool must reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down; a fresh pool below its core size creates a thread instead), and the new endpoints must have no rows. When it happens, `next()` hangs until `cancel()` or `close()`. It was not replayed as a test. -`OpenWithinLimit` fails for the proposal as written (`EagerOpen = TRUE`). The limit is checked before a poll, but one answer can publish several endpoints, and their streams all open at once. Shortest path, with a limit of 2: +Fix (checked as `IdleFix = TRUE`, `deferred-open-fixed`): clear `idleTried` whenever the loop consumes a future, for example right after `onStreamFinished(source)` (line 522). Another fix: test the `orphaned` flag inside the locked check at lines 472-483. -1. The server publishes a second and a third endpoint while the application is still reading the first. -2. One stream is open, which is below the limit, so the poller sends the continuation. -3. The answer carries all three endpoints. The two new streams open at once, leaving three open streams against a limit of 2. +### 2. `finding-open-streams`: the first proposal (`EagerOpen = TRUE`, resolved) -With deferred opening (`EagerOpen = FALSE`), streams open only while fewer than `Limit` are unread, and every rule holds. The implementation should keep queued endpoints unopened until the reader frees a slot, or the setting should be documented as "polls ahead while fewer than N are unread", not as a cap on open streams. +`OpenWithinLimit` fails for the proposal as first written. The limit is checked before a poll, but one answer can publish several endpoints, and their streams all open at once. With a limit of 2: one stream is open, the poller sends the continuation, and an answer with three endpoints opens two more, leaving three open streams. The implementation does not do this: `reserveSlotsLocked` opens only while fewer than `maxOpen` streams are open or opening (`EagerOpen = FALSE`, check `deferred-open`). ## Files - `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. -- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`. diff --git a/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla index 0edca47be0..19004f0666 100644 --- a/formal/pollinfo-poll-ahead/PollAhead.tla +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -6,84 +6,135 @@ (* returned it: the first PollInfo published endpoint E1 and continuation *) (* C1, and C1 has been handed to the poller. *) (* *) -(* Three parties run concurrently: *) +(* Parties that run concurrently: *) (* - the Flight SQL server, which publishes endpoints and finishes or *) (* fails the query, and answers PollFlightInfo at any moment (a server *) (* that does not long-poll may answer at once with nothing new); *) -(* - the poller (proposed EndpointPoller), which chains continuations; *) -(* - the application thread inside ResultSet.next(), which reads *) -(* endpoints, ends the results, or throws. *) +(* - the poller (EndpointPoller), which chains continuations. It runs on *) +(* a pool thread, or, if the pool rejected a resume, inline on the *) +(* reader's thread; *) +(* - the reader: the application thread inside ResultSet.next(), which *) +(* is inside FlightEndpointDataQueue.awaitNext, reads endpoints, ends *) +(* the results, or throws; *) +(* - another application thread that may call Statement.cancel(). *) (* *) -(* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md):*) -(* PollerSend / PollerTake PollInfoOperation.poll / pollNextAvailable *) -(* PollerApply PollInfoOperation.remember + *) -(* ArrowFlightJdbcFlightStreamResultSet *) -(* .enqueueNewEndpoints (append-only suffix) *) -(* AppRead ArrowFlightJdbcFlightStreamResultSet.next *) -(* + FlightEndpointDataQueue.next *) -(* AppEnd next() returning false *) -(* AppCancel Statement.cancel / deadline / close *) -(* -> PollInfoOperation.cancel *) -(* PollerPause, BackoffElapses, the wake in AppRead, and running the *) -(* poll loop off the application thread are the proposal; they have no *) -(* code yet (the POC polls inside next() when the queue is empty). *) +(* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md;*) +(* "Q" = utils/FlightEndpointDataQueue, "P" = EndpointPoller, "R" = *) +(* ArrowFlightJdbcFlightStreamResultSet, "O" = client/PollInfoOperation): *) +(* PollerSend / PollerTake P.drive -> O.pollOnce -> O.poll *) +(* PollerApply* O.remember (inside pollOnce) and *) +(* R.appendEndpoints -> Q.addEndpoints, one *) +(* locked step: append, set moreExpected, *) +(* reserve slots, signal. P.drive then backs *) +(* off, continues, or finishes *) +(* PollerPause Q.pauseIfFull (count check, paused flag *) +(* and P's owned=false in one locked step) *) +(* OpenReserved, OpenFails Q.openReserved / Q.register: the stream *) +(* opens OUTSIDE the lock, into a slot that *) +(* was reserved under it (the "opening" *) +(* count) *) +(* AppRead, AppReadEmpty Q.awaitNext taking a ready future, or a *) +(* null future -> Q.onStreamFinished: under *) +(* the lock free the slot, reserve pending *) +(* endpoints, clear the paused flag *) +(* ReaderResume the resume action Q.onStreamFinished runs *) +(* AFTER unlocking: P.resume (claim owned, *) +(* resubmit; 10 rejected submits orphan P) *) +(* AppIdle, ReaderWait, Q.awaitNext, empty-futures branch: end, *) +(* AppEnd, AppThrow idle hook (P.runInlineIfOrphaned), or wait *) +(* InlineExit P.runInlineIfOrphaned returning *) +(* AppCancel / CancelStop R.cancel: the cancelled flag first, then *) +(* P.stop + O.cancel + Q.close *) +(* PollerSeesFail, PollerDrop P.drive loop top and the check after the *) +(* poll *) +(* *) +(* The implementation corresponds to EagerOpen = FALSE (a Q built with *) +(* maxOpen = pollInfoPrefetch). Answers with no continuation, and *) +(* pollInfoPrefetch = 0, use an unlimited eager queue and never start a *) +(* poller; the model does not cover them. *) (* *) (* Rows are abstracted: reading an endpoint is one step. Endpoint i is the *) (* i-th endpoint the server publishes; PollInfo is cumulative, so an *) -(* answer is just how many endpoints exist so far. *) +(* answer is just how many endpoints exist so far. An endpoint is either *) +(* empty (no rows: its future yields null) or not. *) (***************************************************************************) EXTENDS Naturals CONSTANTS N, \* most endpoints the query can publish - Limit, \* pollInfoPrefetch: the poller polls only while open, unread endpoints < Limit - EagerOpen, \* TRUE: a DoGet stream opens as soon as its endpoint is enqueued (the proposal as written) + Limit, \* pollInfoPrefetch: the poller polls only while queued, unread endpoints < Limit + EagerOpen, \* TRUE: every enqueued endpoint takes a stream slot at once (the proposal as first written) + IdleFix, \* FALSE: the code at the sync commit (the reader clears its idle flag only after a wait); + \* TRUE: the proposed fix (it also clears it whenever it finishes an endpoint) Mutation \* "none", or the name of a deliberately broken variant (see run.sh) VARIABLES published, \* endpoints the server has published server, \* "running" | "done" | "failed" - known, \* endpoints enqueued in FlightEndpointDataQueue (cumulative prefix) - opened, \* endpoints whose DoGet stream has been opened - read, \* endpoints the application has fully read - enq, \* enq[i]: how many times endpoint i was enqueued (capped at 2) + known, \* endpoints handed to the queue by addEndpoints (cumulative prefix) + resv, \* slots reserved under the lock whose stream is not registered yet ("opening") + opened, \* streams registered with the queue (future submitted), cumulative + read, \* endpoints finished and freed (onStreamFinished done) + enq, \* enq[i]: how many times endpoint i was handed to the queue (capped at 2) + more, \* the queue's moreExpected flag + pflag, \* the queue's paused flag contHeld, \* the driver holds a continuation descriptor contUsed, \* the held continuation has already been sent inflight, \* a PollFlightInfo RPC is open resp, \* the server's answer, not yet taken by the poller got, \* the answer the poller took, not yet applied - poller, \* "running" | "polling" | "received" | "backoff" | "paused" | "finished" | "failed" | "stopped" + poller, \* "running" (at the top of its loop) | "polling" | "received" | "backoff" + \* | "paused" | "pausing" | "orphaned" | "finished" | "failed" | "stopped" lastEmpty, \* the last applied answer added no endpoints while the query was running waited, \* a backoff has elapsed since that empty answer + sawFull, \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet + rd, \* the reader: "run" (top of the awaitNext loop) | "resume" | "waiting" | "inline" + idleTried, \* awaitNext's local idleTried flag app, \* "reading" | "ended" | "threw" - failSeen, \* the driver has seen the query fail - cancelled, \* Statement.cancel(), the deadline, or close() happened + failSeen, \* the queue recorded a failure + cancelled, \* ResultSet.cancelled: next() throws from now on + gated, \* cancel finished: poller stopped, operation cancelled, queue closed badRow, \* a row was handed to the application after a failure or cancel - badPoll, \* a poll was sent after cancel - polledAtLimit, \* a poll was sent while open, unread endpoints were at the limit + badPoll, \* a poll was sent after cancel finished + polledAtLimit, \* a poll was sent while queued, unread endpoints were at the limit resent, \* a continuation was sent twice - spun, \* a poll was sent right after an empty answer, without backoff - sawFull \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet + spun \* a poll was sent right after an empty answer, without backoff + +srvV == <> +qV == <> +rpcV == <> +polV == <> +rdV == <> +appV == <> +flagV == <> -vars == <> +vars == <> Min(a, b) == IF a < b THEN a ELSE b +Max(a, b) == IF a > b THEN a ELSE b Answer == [has : BOOLEAN, count : 0..N, more : BOOLEAN, err : BOOLEAN] NoAnswer == [has |-> FALSE, count |-> 0, more |-> FALSE, err |-> FALSE] -Unread == known - read +Unread == known - read \* pending + open-unread +NoFutures == opened = read \* every registered stream was finished +NothingQueued == known = opened /\ resv = 0 \* pending empty and opening == 0 + +\* The reader is woken (signalAll) only if it is waiting; then it clears its idle flag. +WakeRd == /\ rd' = IF rd = "waiting" THEN "run" ELSE rd + /\ idleTried' = IF rd = "waiting" THEN FALSE ELSE idleTried ----------------------------------------------------------------------------- Init == /\ published = 1 /\ server = "running" /\ known = 1 + /\ resv = 0 /\ opened = 1 /\ read = 0 /\ enq = [i \in 1..N |-> IF i = 1 THEN 1 ELSE 0] + /\ more = TRUE + /\ pflag = FALSE /\ contHeld = TRUE /\ contUsed = FALSE /\ inflight = FALSE @@ -92,15 +143,18 @@ Init == /\ poller = "running" /\ lastEmpty = FALSE /\ waited = FALSE + /\ sawFull = FALSE + /\ rd = "run" + /\ idleTried = FALSE /\ app = "reading" /\ failSeen = FALSE /\ cancelled = FALSE + /\ gated = FALSE /\ badRow = FALSE /\ badPoll = FALSE /\ polledAtLimit = FALSE /\ resent = FALSE /\ spun = FALSE - /\ sawFull = FALSE ----------------------------------------------------------------------------- (* Server *) @@ -109,39 +163,33 @@ SrvPublish == /\ server = "running" /\ published < N /\ published' = published + 1 - /\ UNCHANGED <> + /\ UNCHANGED <> SrvComplete == /\ server = "running" /\ server' = "done" - /\ UNCHANGED <> + /\ UNCHANGED <> SrvFail == /\ server = "running" /\ server' = "failed" - /\ UNCHANGED <> + /\ UNCHANGED <> \* The server answers the open poll. It may answer at once with nothing new. +\* Once cancel has cancelled the operation's context, the open poll ends with CANCELLED. SrvAnswer == /\ inflight /\ ~resp.has - /\ resp' = IF cancelled \/ server = "failed" + /\ resp' = IF gated \/ server = "failed" THEN [has |-> TRUE, count |-> 0, more |-> FALSE, err |-> TRUE] ELSE [has |-> TRUE, count |-> published, more |-> server = "running", err |-> FALSE] /\ inflight' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* Poller (proposed EndpointPoller, on its own pool) *) +(* Poller (EndpointPoller.drive, on the poller pool or inline on the reader) *) +\* Poll the held continuation, after pauseIfFull said no. PollerSend == /\ poller = "running" /\ contHeld @@ -152,37 +200,53 @@ PollerSend == /\ contUsed' = TRUE /\ resent' = (resent \/ contUsed) /\ spun' = (spun \/ (lastEmpty /\ ~waited)) - /\ badPoll' = (badPoll \/ cancelled) + /\ badPoll' = (badPoll \/ gated) /\ polledAtLimit' = (polledAtLimit \/ Unread >= Limit) /\ waited' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> -\* At the limit the poller pauses and gives its thread back. +\* Q.pauseIfFull: at the limit, the poller sets the paused flag and gives its thread back. +\* The count check, the flag and P's owned=false are one step under the queue lock. +\* The inline poller never pauses (drive(true) skips pauseIfFull). PollerPause == /\ poller = "running" + /\ rd # "inline" /\ contHeld + /\ more /\ ~failSeen /\ ~gated /\ Mutation # "noLimit" /\ IF Mutation = "pauseNotAtomic" THEN sawFull ELSE Unread >= Limit - /\ poller' = "paused" + /\ pflag' = TRUE + /\ poller' = IF Mutation = "ownedClearedLate" THEN "pausing" ELSE "paused" /\ sawFull' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> \* Broken variant only: the poller reads the count, and pauses in a later step. PollerCheck == /\ Mutation = "pauseNotAtomic" /\ poller = "running" + /\ rd # "inline" /\ contHeld /\ ~sawFull /\ Unread >= Limit /\ sawFull' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> -\* The poller takes the answer. A failure fails the execution at once. +\* Broken variant only: the poller sets the paused flag under the lock but clears +\* `owned` after unlocking. +PollerPauseEnd == + /\ poller = "pausing" + /\ poller' = "paused" + /\ UNCHANGED <> + +\* The top of drive(): the queue has failed, so the poller stops. +PollerSeesFail == + /\ poller = "running" + /\ failSeen + /\ poller' = "stopped" + /\ UNCHANGED <> + +\* The poller takes the answer. A failure fails the queue at once (onPollFailed -> Q.fail). PollerTake == /\ poller = "polling" /\ resp.has @@ -191,107 +255,263 @@ PollerTake == THEN /\ poller' = "failed" /\ failSeen' = TRUE /\ contHeld' = FALSE - /\ UNCHANGED got + /\ UNCHANGED <> + /\ rd' = IF rd \in {"waiting", "inline"} THEN "run" ELSE rd + /\ idleTried' = IF rd \in {"waiting", "inline"} THEN FALSE ELSE idleTried ELSE /\ got' = resp - /\ poller' = IF Mutation = "finishBeforeEnqueue" /\ ~resp.more - THEN "finished" ELSE "received" - /\ UNCHANGED <> - /\ UNCHANGED <> - -\* Apply a successful answer: enqueue only the appended endpoints, take the -\* next continuation, and mark the poller finished in the same step when the -\* query is complete. -PollerApply == + /\ poller' = "received" + /\ more' = IF Mutation = "finishBeforeEnqueue" /\ ~resp.more THEN FALSE ELSE more + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Slots addEndpoints can reserve: fewer than Limit streams open or opening and unread. +\* EagerOpen: every new endpoint takes a slot at once. +ApplyRsv == + LET pendNew == got.count - opened - resv + free == Max(0, Limit - (opened - read) + - (IF Mutation = "openNotReserved" THEN 0 ELSE resv)) + IN IF EagerOpen THEN pendNew ELSE Min(pendNew, free) + +\* addEndpoints: in one locked step append only the new suffix, set moreExpected, reserve slots +\* (their streams open later, outside the lock), and signal the reader. +ApplyQ == /\ got.has - /\ poller \in {"received", "finished"} - /\ LET new == got.count - from == IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1 - empty == new = known - IN - /\ enq' = [i \in 1..N |-> IF i >= from /\ i <= new THEN Min(enq[i] + 1, 2) ELSE enq[i]] - /\ known' = new - /\ opened' = IF EagerOpen THEN new ELSE Min(new, read + Limit) - /\ got' = NoAnswer - /\ IF got.more - THEN /\ contHeld' = TRUE - /\ contUsed' = (Mutation = "reuseContinuation" /\ empty) - /\ lastEmpty' = empty - /\ poller' = IF empty /\ Mutation # "noBackoff" THEN "backoff" ELSE "running" - ELSE /\ contHeld' = FALSE - /\ lastEmpty' = FALSE - /\ poller' = "finished" - /\ UNCHANGED contUsed - /\ UNCHANGED <> + /\ poller = "received" + /\ enq' = [i \in 1..N |-> + IF i >= (IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1) /\ i <= got.count + THEN Min(enq[i] + 1, 2) ELSE enq[i]] + /\ known' = got.count + /\ resv' = resv + ApplyRsv + /\ more' = got.more + /\ got' = NoAnswer + +\* An answer that adds nothing while the query runs: back off, then poll again. +PollerApplyBackoff == + /\ ApplyQ + /\ got.more + /\ got.count = known + /\ contHeld' = TRUE + /\ contUsed' = (Mutation = "reuseContinuation") + /\ lastEmpty' = TRUE + /\ poller' = IF Mutation = "noBackoff" THEN "running" ELSE "backoff" + /\ WakeRd + /\ UNCHANGED <> + +\* An answer that adds endpoints, applied by a pool thread: go on to the next iteration. +PollerApplyGo == + /\ ApplyQ + /\ got.more + /\ got.count > known + /\ rd # "inline" + /\ contHeld' = TRUE + /\ contUsed' = FALSE + /\ lastEmpty' = FALSE + /\ poller' = "running" + /\ WakeRd + /\ UNCHANGED <> + +\* An answer that adds endpoints, applied inline on the reader: hand the poller back to the +\* pool (handBack). If the pool rejects it 10 times, the poller stays orphaned. +PollerApplyHandBack == + /\ ApplyQ + /\ got.more + /\ got.count > known + /\ rd = "inline" + /\ contHeld' = TRUE + /\ contUsed' = FALSE + /\ lastEmpty' = FALSE + /\ poller' \in {"running", "orphaned"} + /\ rd' = "run" + /\ idleTried' = FALSE + /\ UNCHANGED <> + +\* The final answer: the queue sees the last endpoints and moreExpected = FALSE together. +PollerApplyFinish == + /\ ApplyQ + /\ ~got.more + /\ contHeld' = FALSE + /\ lastEmpty' = FALSE + /\ poller' = "finished" + /\ rd' = IF rd = "inline" \/ rd = "waiting" THEN "run" ELSE rd + /\ idleTried' = IF rd = "inline" \/ rd = "waiting" THEN FALSE ELSE idleTried + /\ UNCHANGED <> \* 100 ms doubling up to pollInfoMaxBackoff; time is abstracted to one step. BackoffElapses == /\ poller = "backoff" /\ poller' = "running" /\ waited' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* A stopped poller discards the answer to the poll that cancel interrupted. PollerDrop == /\ poller = "stopped" /\ resp.has /\ resp' = NoAnswer - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* Application thread inside ResultSet.next() *) +(* Opening streams, outside the lock, into reserved slots. Whoever reserved the slot opens it; + the model lets any step do it, which only adds behaviors. A stream registered after a failure + or cancel is closed at once in the code; here it still counts as open, which also only adds + behaviors. *) + +OpenReserved == + /\ resv > 0 + /\ resv' = resv - 1 + /\ opened' = opened + 1 + /\ WakeRd + /\ UNCHANGED <> + +\* opener.open throws: the remaining reservations are released and the queue fails. +OpenFails == + /\ resv > 0 + /\ resv' = resv - 1 + /\ failSeen' = TRUE + /\ WakeRd + /\ UNCHANGED <> -\* Read one opened endpoint. Finishing it may wake a paused poller. +----------------------------------------------------------------------------- +(* The reader: ResultSet.next() inside Q.awaitNext *) + +\* onStreamFinished, the part under the lock: free the slot, reserve pending endpoints for +\* opening, and clear the paused flag if unread endpoints are below the limit. The resume +\* action runs after unlocking (ReaderResume). +ReadFree == + LET read1 == read + 1 + pend == known - opened - resv + free == Max(0, Limit - (opened - read1) + - (IF Mutation = "openNotReserved" THEN 0 ELSE resv)) + rsv == IF EagerOpen THEN 0 ELSE Min(pend, free) + wake == pflag /\ known - read1 < Limit /\ Mutation # "noWake" + IN /\ read' = read1 + /\ resv' = resv + rsv + /\ pflag' = IF wake THEN FALSE ELSE pflag + /\ rd' = IF wake THEN "resume" ELSE "run" + +\* Take a ready stream, read it, and finish it: rows reach the application. AppRead == /\ app = "reading" + /\ rd = "run" /\ opened > read - /\ Mutation = "readAfterFail" \/ (~failSeen /\ ~cancelled) - /\ read' = read + 1 + /\ (Mutation = "readAfterFail" \/ (~failSeen /\ ~cancelled)) + /\ ReadFree /\ badRow' = (badRow \/ failSeen \/ cancelled) - /\ opened' = IF EagerOpen THEN opened ELSE Min(known, read + 1 + Limit) - /\ poller' = IF poller = "paused" /\ known - (read + 1) < Limit /\ Mutation # "noWake" - THEN "running" ELSE poller - /\ UNCHANGED <> - -\* next() returns false only when the queue is empty and the poller finished. + /\ idleTried' = FALSE + /\ UNCHANGED <> + +\* Take a null future (an endpoint with no rows) and finish it. awaitNext loops without +\* returning to the application, so idleTried keeps its value unless IdleFix. +AppReadEmpty == + /\ app = "reading" + /\ rd = "run" + /\ opened > read + /\ ~failSeen /\ ~cancelled + /\ ReadFree + /\ idleTried' = IF IdleFix THEN FALSE ELSE idleTried + /\ UNCHANGED <> + +\* The resume action of onStreamFinished, run on the reader's thread after unlocking: +\* P.resume claims `owned` (true only if the poller gave it up) and resubmits. A rejected +\* submit, 10 times, orphans the poller. +ReaderResume == + /\ rd = "resume" + /\ rd' = "run" + /\ poller' = IF poller = "paused" THEN "running" ELSE poller + /\ UNCHANGED <> + +\* The resume was rejected: the poller is orphaned, owned stays true, the reader is woken. +ReaderResumeRejected == + /\ rd = "resume" + /\ poller = "paused" + /\ rd' = "run" + /\ poller' = "orphaned" + /\ UNCHANGED <> + +\* Nothing is queued and more may come: call the idle hook (P.runInlineIfOrphaned). If the poller +\* is orphaned, it polls on the reader's thread; otherwise the hook returns false and +\* idleTried is set. +AppIdle == + /\ app = "reading" + /\ rd = "run" + /\ ~failSeen /\ ~cancelled + /\ NoFutures /\ NothingQueued + /\ more + /\ ~idleTried + /\ IF poller = "orphaned" /\ Mutation # "noIdleHook" + THEN /\ poller' = "running" + /\ rd' = "inline" + /\ UNCHANGED idleTried + ELSE /\ idleTried' = TRUE + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* The inline run ended because the poller was stopped; the idle hook returns true. +InlineExit == + /\ rd = "inline" + /\ poller = "stopped" + /\ ~inflight + /\ ~resp.has + /\ rd' = "run" + /\ idleTried' = FALSE + /\ UNCHANGED <> + +\* Futures empty and no endpoint queued or opening, but more may come (or the idle hook said no): +\* wait on the condition, which the lock-protected check makes atomic. +ReaderWait == + /\ app = "reading" + /\ rd = "run" + /\ ~failSeen /\ ~cancelled + /\ NoFutures + /\ ~(NothingQueued /\ ~more) + /\ ~(NothingQueued /\ ~idleTried) + /\ rd' = "waiting" + /\ UNCHANGED <> + +\* next() returns false: futures empty, pending empty, opening == 0, and !moreExpected, +\* all read under the lock. AppEnd == /\ app = "reading" + /\ rd = "run" /\ ~failSeen /\ ~cancelled - /\ read = known - /\ Mutation = "endWhenQueueEmpty" \/ poller = "finished" + /\ NoFutures + /\ known = opened + resv + /\ (resv = 0 \/ Mutation = "endIgnoresOpening") + /\ (~more \/ Mutation = "endWhenQueueEmpty") /\ app' = "ended" - /\ UNCHANGED <> + /\ UNCHANGED <> AppThrow == /\ app = "reading" + /\ rd = "run" /\ failSeen \/ cancelled /\ app' = "threw" - /\ UNCHANGED <> + /\ UNCHANGED <> -\* Cancel stops the poller; its open poll, if any, ends with CANCELLED. +\* R.cancel, step 1: the cancelled flag. next() throws from the next call on. AppCancel == /\ app = "reading" /\ ~cancelled /\ cancelled' = TRUE + /\ UNCHANGED <> + +\* R.cancel, step 2: P.stop (stopped = true), O.cancel (an open poll ends with CANCELLED, no new +\* RPC starts), Q.close (wakes the reader). +CancelStop == + /\ cancelled + /\ ~gated + /\ gated' = TRUE /\ poller' = IF poller \in {"finished", "failed"} \/ Mutation = "cancelIgnoresPoller" THEN poller ELSE "stopped" /\ contHeld' = IF Mutation = "cancelIgnoresPoller" THEN contHeld ELSE FALSE - /\ UNCHANGED <> + /\ WakeRd + /\ UNCHANGED <> \* The application is done with the result; nothing more happens to it. Done == @@ -300,16 +520,25 @@ Done == Next == \/ SrvPublish \/ SrvComplete \/ SrvFail \/ SrvAnswer - \/ PollerSend \/ PollerCheck \/ PollerPause \/ PollerTake \/ PollerApply \/ BackoffElapses \/ PollerDrop - \/ AppRead \/ AppEnd \/ AppThrow \/ AppCancel + \/ PollerSend \/ PollerCheck \/ PollerPause \/ PollerPauseEnd \/ PollerSeesFail + \/ PollerTake \/ PollerApplyBackoff \/ PollerApplyGo \/ PollerApplyHandBack + \/ PollerApplyFinish \/ BackoffElapses \/ PollerDrop + \/ OpenReserved \/ OpenFails + \/ AppRead \/ AppReadEmpty \/ ReaderResume \/ ReaderResumeRejected \/ AppIdle \/ InlineExit + \/ ReaderWait \/ AppEnd \/ AppThrow \/ AppCancel \/ CancelStop \/ Done -\* The server eventually finishes; the driver and the application keep going. +\* The server eventually finishes; the driver, the cancel call and the application keep going. Fairness == /\ WF_vars(SrvComplete) /\ WF_vars(SrvAnswer) - /\ WF_vars(PollerSend) /\ WF_vars(PollerPause) /\ WF_vars(PollerTake) - /\ WF_vars(PollerApply) /\ WF_vars(BackoffElapses) /\ WF_vars(PollerDrop) - /\ WF_vars(AppRead) /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) + /\ WF_vars(PollerSend) /\ WF_vars(PollerPause) /\ WF_vars(PollerPauseEnd) + /\ WF_vars(PollerSeesFail) /\ WF_vars(PollerTake) + /\ WF_vars(PollerApplyBackoff) /\ WF_vars(PollerApplyGo) /\ WF_vars(PollerApplyHandBack) + /\ WF_vars(PollerApplyFinish) /\ WF_vars(BackoffElapses) /\ WF_vars(PollerDrop) + /\ WF_vars(OpenReserved) + /\ WF_vars(AppRead \/ AppReadEmpty) /\ WF_vars(ReaderResume \/ ReaderResumeRejected) + /\ WF_vars(AppIdle) /\ WF_vars(InlineExit) /\ WF_vars(ReaderWait) + /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) /\ WF_vars(CancelStop) Spec == Init /\ [][Next]_vars /\ Fairness @@ -319,13 +548,19 @@ Spec == Init /\ [][Next]_vars /\ Fairness TypeOK == /\ published \in 1..N /\ server \in {"running", "done", "failed"} - /\ read <= opened /\ opened <= known /\ known <= published + /\ read <= opened /\ opened + resv <= known /\ known <= published /\ enq \in [1..N -> 0..2] /\ resp \in Answer /\ got \in Answer - /\ poller \in {"running", "polling", "received", "backoff", "paused", "finished", "failed", "stopped"} + /\ poller \in {"running", "polling", "received", "backoff", "paused", "pausing", + "orphaned", "finished", "failed", "stopped"} + /\ rd \in {"run", "resume", "waiting", "inline"} /\ app \in {"reading", "ended", "threw"} /\ sawFull \in BOOLEAN +\* Only one party runs the poller: an inline run means the poller is on the reader's thread. +InlineMeansPoller == + rd = "inline" => poller \in {"running", "polling", "received", "backoff", "stopped"} + \* Each endpoint is queued for download exactly once (append-only suffix). EachEndpointOnce == \A i \in 1..N : enq[i] <= 1 @@ -338,14 +573,14 @@ NoPrematureEnd == app = "ended" => (server = "done" /\ read = published) \* No row reaches the application after the driver saw a failure or a cancel. FailFast == ~badRow -\* No poll is sent after cancel. +\* No poll is sent after cancel has finished (stopped, operation cancelled, queue closed). CancelStopsPolling == ~badPoll -\* The poller never polls while unread endpoints are at the limit. +\* The poller never polls while queued, unread endpoints are at the limit. Backpressure == ~polledAtLimit -\* Open, unread DoGet streams never exceed the limit. -OpenWithinLimit == opened - read <= Limit +\* Open, opening and unread DoGet streams never exceed the limit. +OpenWithinLimit == opened + resv - read <= Limit \* No poll is sent straight after an empty answer. NoSpin == ~spun diff --git a/formal/pollinfo-poll-ahead/run.sh b/formal/pollinfo-poll-ahead/run.sh index 6978035b1b..6f6fdb35f3 100755 --- a/formal/pollinfo-poll-ahead/run.sh +++ b/formal/pollinfo-poll-ahead/run.sh @@ -2,7 +2,7 @@ # Model-check the JDBC poll-ahead design (BDX-645) with TLC. # # formal/pollinfo-poll-ahead/run.sh # all checks -# N=4 LIMIT=2 formal/pollinfo-poll-ahead/run.sh # larger bound (slower) +# N=4 LIMIT=2 formal/pollinfo-poll-ahead/run.sh # larger bound (about 30 s) # # Each check states what it expects. The script exits 0 only when every # check matches its expectation, including the broken variants, which must @@ -25,17 +25,17 @@ WORK=$(mktemp -d) trap 'rm -rf "$WORK"' EXIT cp "$HERE/PollAhead.tla" "$WORK/" -SAFE="TypeOK EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin" +SAFE="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin" ALL="$SAFE OpenWithinLimit" unexpected=0 -# check NAME EAGER_OPEN MUTATION "INVARIANTS" LIVENESS(yes|no) EXPECT(pass|invariant:Name|deadlock|liveness) NOTE +# check NAME EAGER_OPEN IDLE_FIX MUTATION "INVARIANTS" LIVENESS(yes|no) EXPECT(pass|invariant:Name|deadlock|liveness) NOTE check() { - local name=$1 eager=$2 mutation=$3 invariants=$4 liveness=$5 expect=$6 note=$7 + local name=$1 eager=$2 idlefix=$3 mutation=$4 invariants=$5 liveness=$6 expect=$7 note=$8 local cfg="$WORK/$name.cfg" out="$WORK/$name.out" got { echo "SPECIFICATION Spec" - echo "CONSTANTS N = $N Limit = $LIMIT EagerOpen = $eager Mutation = \"$mutation\"" + echo "CONSTANTS N = $N Limit = $LIMIT EagerOpen = $eager IdleFix = $idlefix Mutation = \"$mutation\"" for inv in $invariants; do echo "INVARIANT $inv"; done if [ "$liveness" = yes ]; then echo "PROPERTY Terminates"; fi } > "$cfg" @@ -60,22 +60,31 @@ check() { echo "PollAhead model check N=$N Limit=$LIMIT ($(java -cp "$JAR" tlc2.TLC 2>&1 | head -1))" echo -echo "Design checks" -check proposal-as-written TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" -check finding-open-streams TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" -check deferred-open FALSE none "$ALL" yes pass "streams open only while open < limit" +echo "Design checks (IdleFix = TRUE is the proposed fix; FALSE is the code at the sync commit)" +check proposal-as-written TRUE TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" +check finding-open-streams TRUE TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" +check deferred-open-fixed FALSE TRUE none "$ALL" yes pass "deferred open, idle flag cleared on progress" +check deferred-open FALSE FALSE none "$ALL" no pass "the code as written: every safety rule holds" +check finding-stale-idle FALSE FALSE none "TypeOK" yes liveness "KNOWN FINDING: next() can hang after a rejected resume (stale idleTried)" echo -echo "Broken variants (each must fail on the rule it targets)" -check endWhenQueueEmpty FALSE endWhenQueueEmpty "$ALL" no invariant:NoPrematureEnd "next() ends when the queue is empty" -check finishBeforeEnqueue FALSE finishBeforeEnqueue "$ALL" no invariant:NoPrematureEnd "poller marked finished before enqueueing" -check enqueueWholeList FALSE enqueueWholeList "$ALL" no invariant:EachEndpointOnce "cumulative list enqueued, not the suffix" -check reuseContinuation FALSE reuseContinuation "$ALL" no invariant:ContinuationsOnce "old continuation kept after empty answer" -check readAfterFail FALSE readAfterFail "$ALL" no invariant:FailFast "reader ignores the failure flag" -check cancelIgnoresPoller FALSE cancelIgnoresPoller "$ALL" no invariant:CancelStopsPolling "cancel does not stop the poller" -check noLimit FALSE noLimit "$ALL" no invariant:Backpressure "poller ignores the limit" -check noBackoff FALSE noBackoff "$ALL" no invariant:NoSpin "no wait after an empty answer" -check noWake FALSE noWake "$ALL" yes liveness "reader never wakes a paused poller" -check pauseNotAtomic FALSE pauseNotAtomic "$ALL" yes liveness "limit check and pause in separate steps" +echo "Broken variants (each must fail on the rule it targets; the idle fix is on, so only the variant is at fault)" +check endWhenQueueEmpty FALSE TRUE endWhenQueueEmpty "$ALL" no invariant:NoPrematureEnd "next() ends when the queue is empty" +check endIgnoresOpening FALSE TRUE endIgnoresOpening "$ALL" no invariant:NoPrematureEnd "end test forgets streams still opening" +check finishBeforeEnqueue FALSE TRUE finishBeforeEnqueue "$ALL" no invariant:NoPrematureEnd "moreExpected cleared before the final endpoints are queued" +check enqueueWholeList FALSE TRUE enqueueWholeList "$ALL" no invariant:EachEndpointOnce "cumulative list enqueued, not the suffix" +check reuseContinuation FALSE TRUE reuseContinuation "$ALL" no invariant:ContinuationsOnce "old continuation kept after empty answer" +check readAfterFail FALSE TRUE readAfterFail "$ALL" no invariant:FailFast "reader ignores the failure flag" +check cancelIgnoresPoller FALSE TRUE cancelIgnoresPoller "$ALL" no invariant:CancelStopsPolling "cancel does not stop the poller" +check noLimit FALSE TRUE noLimit "$ALL" no invariant:Backpressure "poller ignores the limit" +# The poller never has two batches reserved at once (it stops polling at the limit), so the +# reader's and the poller's reservations only collide from 4 endpoints on. +if [ "$N" -ge 4 ]; then OPEN_NOT_RESERVED=invariant:OpenWithinLimit; else OPEN_NOT_RESERVED=pass; fi +check openNotReserved FALSE TRUE openNotReserved "$ALL" no "$OPEN_NOT_RESERVED" "a stream takes its slot only once opened, not when reserved (needs N>=4)" +check noBackoff FALSE TRUE noBackoff "$ALL" no invariant:NoSpin "no wait after an empty answer" +check noWake FALSE TRUE noWake "$ALL" yes liveness "reader never resumes a paused poller" +check pauseNotAtomic FALSE TRUE pauseNotAtomic "$ALL" yes liveness "limit check and pause in separate steps" +check ownedClearedLate FALSE TRUE ownedClearedLate "$ALL" yes liveness "pause clears owned after the lock: resume finds it set" +check noIdleHook FALSE TRUE noIdleHook "$ALL" yes liveness "an orphaned poller is never run inline" echo if [ "$unexpected" -eq 0 ]; then echo "All checks matched their expectations."; else echo "Some checks did not match. See above."; fi From dadd45d8afad69975152c077b1596c59bfa4e274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 00:43:04 +0000 Subject: [PATCH 26/39] BDX-645: poll-ahead unit tests; fix stranded reader after a rejected resume Tests (U2): scripted PollFlightInfo server (ScriptedPollQuery) with held DoGet streams, gated/failing/hanging answers and per-request timestamps; PollAheadTest end-to-end through JDBC; FlightEndpointDataQueueDeferredOpenTest for the queue. Fixes: - FlightEndpointDataQueue.awaitNext: reset idleTried after consuming a future, so an orphaned poller is run by the idle hook instead of the reader waiting for a wake-up that was already sent. - ArrowFlightJdbcFlightStreamResultSet.next: a reader blocked on a stream that a continuation failure cancelled reports the recorded failure, not CANCELLED. Co-Authored-By: Claude Opus 5.5 --- .../ArrowFlightJdbcFlightStreamResultSet.java | 6 + .../jdbc/utils/FlightEndpointDataQueue.java | 3 + .../arrow/driver/jdbc/PollAheadTest.java | 673 ++++++++++++++++++ ...ightEndpointDataQueueDeferredOpenTest.java | 590 +++++++++++++++ .../utils/PollingMockFlightSqlProducer.java | 41 ++ .../driver/jdbc/utils/ScriptedPollQuery.java | 570 +++++++++++++++ 6 files changed, 1883 insertions(+) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 825f8c22c9..115b9548cb 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -279,6 +279,12 @@ public boolean next() throws SQLException { currentEndpointData = getNextEndpointStream(false); } catch (final FlightRuntimeException e) { + // A failed continuation poll cancels the open streams, which surface here as CANCELLED + // while the reader is blocked on one: report the recorded failure, not the cancel. + final SQLException recordedFailure = flightEndpointDataQueue.failure(); + if (recordedFailure != null) { + throw recordedFailure; + } // A concurrent statement.cancel() (or close) cancels in-flight FlightStreams, // which surface here as CANCELLED. Normalize to Avatica's "Statement canceled". if ((cancelled || flightEndpointDataQueue.isClosed()) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java index fa821e20d7..28a0b7cf61 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java @@ -520,6 +520,9 @@ private CloseableEndpointStreamPair awaitNext( return ready; } onStreamFinished(source); + // A consumed future may have resumed a poller that the pool rejected: the idle hook must get + // another chance, or the reader could wait for a wake-up that was already sent. + idleTried = false; } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java new file mode 100644 index 0000000000..0cc5053a8f --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -0,0 +1,673 @@ +/* + * 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.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLTimeoutException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.EventType; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.FlightStatusCode; +import org.apache.arrow.flight.Location; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Poll-ahead behavior of progressive PollFlightInfo results, against a scripted in-process server. + * + *

    Streams are held on the server with {@link ScriptedPollQuery#holdEnd} so that "open and + * unread" is something the test decides, not a race. Rows are {@code id * 100 + row}. Waits for + * something that must happen use {@link #WAIT_MS}; waits for something that must not happen use the + * short {@link #QUIET_MS} window (they cost that long, and can only fail by letting a bug show). + */ +@Timeout(60) +public class PollAheadTest { + private static final long WAIT_MS = 10_000; + private static final long QUIET_MS = 300; + + private static final AtomicInteger QUERY_NUMBER = new AtomicInteger(); + + private static BufferAllocator allocator; + private static PollingMockFlightSqlProducer producer; + private static FlightServer server; + + @BeforeAll + public static void startServer() throws Exception { + allocator = new RootAllocator(Long.MAX_VALUE); + producer = new PollingMockFlightSqlProducer(); + server = + FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer) + .build() + .start(); + } + + @AfterAll + public static void stopServer() throws Exception { + server.close(); + producer.close(); + allocator.close(); + } + + // 1. Poll-ahead: the poll for C1 arrives before E1's stream completes. + @Test + public void pollsTheContinuationWhileTheFirstStreamIsStillOpen() throws Exception { + // Both streams are held after their batch, so no stream completes before C1 is polled. Which + // endpoint's row comes first is up to the queue, so the test does not depend on it. + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.done(1)).holdAllEnds(2); + final List rows = new ArrayList<>(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + rows.add(resultSet.getInt(1)); + assertTrue(script.awaitPollCount(2, WAIT_MS), "C1 was not polled while a stream is open"); + assertEquals(0, script.count(EventType.DOGET_END)); + script.releaseEnd(rows.get(0) / 100); + rows.addAll(readReleasing(resultSet, script)); + } + assertEquals(List.of(0, 100), sorted(rows)); + assertEquals(List.of(0, 1), script.pollIndices()); + assertEquals(0, script.cancelFlightInfoCount()); + } + + // 2. Deferred open: one answer adds 4 endpoints, prefetch 2, never more than 2 streams open. + @Test + public void deferredOpenKeepsAtMostPrefetchStreamsOpen() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(4), Answer.done(0)).holdAllEnds(4); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(script.awaitDoGetStarted(2, WAIT_MS)); + assertFalse(script.awaitDoGetStarted(3, QUIET_MS), "a third stream opened at the limit"); + rows = readReleasing(resultSet, script); + } + assertEquals(List.of(0, 100, 200, 300), sorted(rows)); + assertEquals(4, script.doGetStarted()); + assertEquals(2, script.maxOpenStreams()); + } + + // 3. Backpressure: polling stops at the limit and resumes after reads. + @Test + public void pollingStopsAtTheLimitAndResumesAfterReads() throws Exception { + // E0 has data and is held open; E1 is open but sends nothing; E2 and E3 stream freely. + final ScriptedPollQuery script = + scripted( + Answer.endpoints(1), + Answer.endpoints(1), + Answer.endpoints(1), + Answer.endpoints(1), + Answer.done(0)) + .holdEnd(0) + .holdStart(1); + final List rows = new ArrayList<>(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + // The initial answer and C1 fill the limit (E0 and E1 unread); C2 must wait. + assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertFalse(script.awaitPollCount(3, QUIET_MS), "polled past the limit"); + + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + rows.add(0); + script.releaseEnd(0); + // E0 finished and E1 has no data yet, so this row comes from E2 (published by C2). + assertTrue(resultSet.next()); + assertEquals(200, resultSet.getInt(1)); + rows.add(200); + + // Finishing E0 freed a slot: the poller resumed and polled C2 once... + assertTrue(script.awaitPollCount(3, WAIT_MS), "poller did not resume after a read"); + // ...and the limit (E1 and E2 unread) stops it again. + assertFalse(script.awaitPollCount(4, QUIET_MS), "polled past the limit after resuming"); + + script.releaseStart(1); + rows.addAll(readAll(resultSet)); + } + assertEquals(List.of(0, 100, 200, 300), sorted(rows)); + assertEquals(List.of(0, 1, 2, 3, 4), script.pollIndices()); + assertEquals(2, script.maxOpenStreams()); + } + + // 4a. Backoff doubles from 100 ms and resets after an answer that adds endpoints. + @Test + public void backoffDoublesAndResetsAfterAnAnswerThatAddsEndpoints() throws Exception { + final ScriptedPollQuery script = + scripted( + Answer.endpoints(1), + Answer.empty(), + Answer.empty(), + Answer.endpoints(1), + Answer.empty(), + Answer.done(0)); + try (Connection connection = connect("pollInfoPrefetch=10"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertEquals(List.of(0, 100), sorted(readAll(resultSet))); + } + final List polls = script.pollNanos(); + assertEquals(6, polls.size()); + // Answers 1 and 2 are empty: waits of 100 ms, then 200 ms. + assertGapBetween(polls, 1, 2, 100, 1500); + assertGapBetween(polls, 2, 3, 200, 1500); + // Answer 3 adds an endpoint: no wait is required, and the next empty answer waits 100 ms + // again, not 400 ms. + assertGapBetween(polls, 4, 5, 100, 350); + } + + // 4b. The wait is capped by pollInfoMaxBackoffMs. + @Test + public void backoffIsCappedByPollInfoMaxBackoffMs() throws Exception { + final ScriptedPollQuery script = + scripted( + Answer.endpoints(1), Answer.empty(), Answer.empty(), Answer.empty(), Answer.done(1)); + try (Connection connection = connect("pollInfoPrefetch=10&pollInfoMaxBackoffMs=150"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertEquals(List.of(0, 100), sorted(readAll(resultSet))); + } + final List polls = script.pollNanos(); + assertEquals(5, polls.size()); + // Waits after the three empty answers: 100 ms, then capped at 150 ms (not 200, not 400). + assertGapBetween(polls, 1, 2, 100, 1500); + assertGapBetween(polls, 2, 3, 150, 1500); + assertGapBetween(polls, 3, 4, 150, 350); + } + + // 5a. Fail fast: a continuation error while streams are held. next() throws, nothing more is + // read, and the buffered streams are cancelled. + @Test + public void continuationFailureStopsReadsAndClosesStreams() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.fail()) + .rowsPerEndpoint(2) + .holdEnd(0) + .holdStart(1); + try (Connection connection = connect("pollInfoPrefetch=3"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + // fail() records the failure first and then cancels every open stream. + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 0, WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 1, WAIT_MS)); + + // The current batch still has a row, but the failure wins, every time. + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertInstanceOf(FlightRuntimeException.class, failure.getCause()); + assertEquals( + FlightStatusCode.INTERNAL, ((FlightRuntimeException) failure.getCause()).status().code()); + assertEquals( + "Continuation PollFlightInfo failed", + assertThrows(SQLException.class, resultSet::next).getMessage()); + } + // The second endpoint never sent a row: its stream was held and then cancelled. + assertFalse(script.hasEvent(EventType.DOGET_END, 1)); + assertEquals(0, script.cancelFlightInfoCount()); + } + + // 5b. The failure arrives while the reader is already blocked on a stream. + @Test + public void continuationFailureWakesAReaderBlockedOnAStream() throws Exception { + final CountDownLatch failNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.fail().gatedBy(failNow)).holdEnd(0); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + try (AsyncReader reader = new AsyncReader(resultSet::next)) { + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + reader.awaitBlocked(); + failNow.countDown(); + final SQLException failure = reader.failure(); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + } + } + } + + // 6. Cancel with a poll open: no further polls, one CancelFlightInfo, next() throws. + @Test + public void cancelEndsTheOpenPollAndNextThrows() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.hang()).rowsPerEndpoint(2); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + statement.cancel(); + assertTrue(script.awaitPollTerminated(WAIT_MS)); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + + // The current batch still has a row, but next() fails right after cancel(). + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + assertFalse(script.awaitPollCount(3, 0)); + } + assertEquals(2, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + // 7. Closing an unfinished result stops the poller and sends one CancelFlightInfo. + @Test + public void closingAnUnfinishedResultStopsThePollerAndCancelsOnce() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); + try (Connection connection = connect("pollInfoPrefetch=2")) { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + } + assertTrue(script.awaitPollTerminated(WAIT_MS)); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + // Closing the statement and the connection must not cancel again. + } + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + assertEquals(2, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + // 8. No premature end: the final endpoints arrive in the done answer. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void finalEndpointsInTheDoneAnswerAreAllDelivered(final boolean readerWaits) + throws Exception { + final CountDownLatch release = new CountDownLatch(1); + final Answer done = readerWaits ? Answer.done(2).gatedBy(release) : Answer.done(2); + final ScriptedPollQuery script = scripted(Answer.endpoints(1), done); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + final int firstRow = resultSet.getInt(1); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { + if (readerWaits) { + // The reader has consumed E0 and now waits for the done answer. + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_END, 0, WAIT_MS)); + reader.awaitBlocked(); + release.countDown(); + } + final List rows = new ArrayList<>(reader.rows()); + rows.add(firstRow); + assertEquals(List.of(0, 100, 200), sorted(rows)); + } + } + assertEquals(List.of(0, 1), script.pollIndices()); + } + + // 9. Continuations are sent once each and in order. + @Test + public void continuationsAreSentOnceEachAndInOrder() throws Exception { + final ScriptedPollQuery script = + scripted( + Answer.endpoints(1), + Answer.empty(), + Answer.endpoints(1), + Answer.empty(), + Answer.done(1)); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=20"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertEquals(List.of(0, 100, 200), sorted(readAll(resultSet))); + } + assertEquals(List.of(0, 1, 2, 3, 4), script.pollIndices()); + assertEquals(1, script.maxInFlightPolls()); + } + + // 10. pollInfoPrefetch=0 keeps the exact POC order: poll, DoGet, poll, DoGet. + @Test + public void prefetchZeroKeepsThePocRequestOrder() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)).holdEnd(0); + try (Connection connection = connect("pollInfoPrefetch=0"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + // The reader polls only when its queue is empty, so C1 waits for E0 to finish. + assertFalse(script.awaitPollCount(2, QUIET_MS), "polled ahead with pollInfoPrefetch=0"); + script.releaseEnd(0); + assertEquals(List.of(100, 200), readAll(resultSet)); + } + assertEquals( + List.of("POLL:0", "DOGET_START:0", "POLL:1", "DOGET_START:1", "POLL:2", "DOGET_START:2"), + script.eventNames(EventType.POLL, EventType.DOGET_START)); + } + + // Decision: answers with no continuation, and pollInfoPrefetch=0, open every endpoint at once. + @Test + public void completeFirstAnswerOpensEveryEndpointEagerly() throws Exception { + final ScriptedPollQuery script = scripted(Answer.done(4)).holdAllEnds(4); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(script.awaitDoGetStarted(4, WAIT_MS), "not every endpoint opened eagerly"); + rows = readReleasing(resultSet, script); + } + assertEquals(List.of(0, 100, 200, 300), sorted(rows)); + assertEquals(4, script.maxOpenStreams()); + } + + @Test + public void prefetchZeroOpensEveryEndpointEagerly() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(3), Answer.done(1)).holdAllEnds(4); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=0"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(script.awaitDoGetStarted(3, WAIT_MS), "not every endpoint opened eagerly"); + rows = readReleasing(resultSet, script); + } + assertEquals(List.of(0, 100, 200, 300), sorted(rows)); + } + + // 11. Poller pool busy: the second result falls back to polling in next(). + @Test + public void busyPollerPoolMakesTheNextResultPollInNext() throws Exception { + final CountDownLatch releaseA = new CountDownLatch(1); + final ScriptedPollQuery scriptA = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseA), Answer.done(1)); + final ScriptedPollQuery scriptB = scripted(Answer.endpoints(1), Answer.done(1)).holdEnd(0); + try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); + Statement statementA = connection.createStatement(); + Statement statementB = connection.createStatement()) { + try (ResultSet resultSetA = statementA.executeQuery(scriptA.query())) { + // A's poller holds the only pool thread, blocked inside C1. + assertTrue(scriptA.awaitBlockedPoll(WAIT_MS)); + + try (ResultSet resultSetB = statementB.executeQuery(scriptB.query())) { + assertTrue(resultSetB.next()); + assertEquals(0, resultSetB.getInt(1)); + // B has no poller: it polls inside next(), after E0 finished. + assertFalse(scriptB.awaitPollCount(2, QUIET_MS), "B polled ahead without a poller"); + scriptB.releaseEnd(0); + assertEquals(List.of(100), readAll(resultSetB)); + } + assertEquals(List.of(0, 1), scriptB.pollIndices()); + assertEquals(2, scriptA.pollCount()); + + releaseA.countDown(); + assertEquals(List.of(0, 100, 200), sorted(readAll(resultSetA))); + } + } + } + + // 13. Orphaned poller: a resume finds the pool busy; the reader runs the poller inline. + @Test + public void anOrphanedPollerIsRunInlineByTheReader() throws Exception { + final CountDownLatch releaseB = new CountDownLatch(1); + final ScriptedPollQuery scriptA = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)); + final ScriptedPollQuery scriptB = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseB), Answer.done(1)); + try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); + Statement statementA = connection.createStatement(); + Statement statementB = connection.createStatement(); + ResultSet resultSetA = statementA.executeQuery(scriptA.query())) { + // A's poller polls C1, reaches the limit (E0 and E1 unread), pauses and frees its thread. + assertTrue(scriptA.awaitPollCount(2, WAIT_MS)); + awaitPollerPoolIdle(connection); + + // B's poller takes the only pool thread and blocks inside its C1. + try (ResultSet resultSetB = statementB.executeQuery(scriptB.query())) { + assertTrue(scriptB.awaitBlockedPoll(WAIT_MS)); + + // Reading A frees a slot, but the resume is rejected: the pool is busy with B. The reader + // finishes A by polling C2 itself, while B is still blocked. + final List rowsA = readAllWithin(resultSetA); + assertEquals(List.of(0, 100, 200), sorted(rowsA)); + assertEquals(List.of(0, 1, 2), scriptA.pollIndices()); + assertEquals(2, scriptB.pollCount()); + + releaseB.countDown(); + assertEquals(List.of(0, 100, 200), sorted(readAll(resultSetB))); + } + } + } + + // 14. A continuation that never answers ends at a read boundary with the JDBC timeout message. + @ParameterizedTest + @ValueSource(strings = {"pollInfoPrefetch=0", "pollInfoPrefetch=2"}) + public void queryTimeoutEndsAtAReadBoundary(final String property) throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); + final long startNanos = System.nanoTime(); + try (Connection connection = connect(property); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + try (ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + final SQLTimeoutException timeout = + assertThrows(SQLTimeoutException.class, resultSet::next); + assertEquals("Query timed out after 1 SECONDS", timeout.getMessage()); + assertInstanceOf(FlightRuntimeException.class, timeout.getCause()); + assertEquals( + FlightStatusCode.TIMED_OUT, + ((FlightRuntimeException) timeout.getCause()).status().code()); + } + } + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertTrue(elapsedMillis >= 850, "the deadline fired too early: " + elapsedMillis); + assertTrue(script.awaitPollTerminated(WAIT_MS)); + assertEquals(2, script.pollCount()); + } + + // Decision: a schema change fails the queue as a plain SQLException. + @Test + public void schemaChangeFailsTheResultAsAPlainSqlException() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.schemaChange()).rowsPerEndpoint(2); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitPollCount(2, WAIT_MS)); + final SQLException failure = assertThrows(SQLException.class, () -> readAllWithin(resultSet)); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("PollInfo changed the result schema", failure.getMessage()); + } + } + + // ---- helpers ---------------------------------------------------------------------------- + + private static ScriptedPollQuery scripted(final Answer... answers) { + return producer.scripted("SELECT poll_ahead_" + QUERY_NUMBER.incrementAndGet(), answers); + } + + // threadPoolSize=4: a stream held open must not starve the readers of the other streams, which + // share one pool per connection (its default size is 1). + private static Connection connect(final String properties) throws SQLException { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=true" + + "&threadPoolSize=4&%s", + server.getPort(), properties)); + } + + private static List readAll(final ResultSet resultSet) throws SQLException { + final List rows = new ArrayList<>(); + while (resultSet.next()) { + rows.add(resultSet.getInt(1)); + } + return rows; + } + + /** Reads the rest of a result on another thread, so that a hang fails the test, not the run. */ + private static List readAllWithin(final ResultSet resultSet) throws Exception { + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { + return reader.rows(); + } + } + + /** + * Reads the rest of a result and releases each endpoint's held stream right after its row is + * read, so the result can advance past that endpoint. + */ + private static List readReleasing( + final ResultSet resultSet, final ScriptedPollQuery script) throws Exception { + try (AsyncReader reader = + new AsyncReader( + () -> { + final List rows = new ArrayList<>(); + while (resultSet.next()) { + final int row = resultSet.getInt(1); + rows.add(row); + script.releaseEnd(row / 100); + } + return rows; + })) { + return reader.rows(); + } + } + + private static List sorted(final List rows) { + final List copy = new ArrayList<>(rows); + Collections.sort(copy); + return copy; + } + + private static void assertGapBetween( + final List polls, + final int from, + final int to, + final long minMillis, + final long maxMillis) { + final long gap = TimeUnit.NANOSECONDS.toMillis(polls.get(to) - polls.get(from)); + assertTrue(gap >= minMillis, "gap " + from + "->" + to + " was " + gap + " ms"); + assertTrue(gap < maxMillis, "gap " + from + "->" + to + " was " + gap + " ms"); + } + + private static void awaitPollerPoolIdle(final Connection connection) throws Exception { + final ThreadPoolExecutor pool = + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor(); + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (pool.getActiveCount() > 0) { + assertTrue(System.nanoTime() < deadline, "the poller pool never became idle"); + Thread.onSpinWait(); + } + } + + /** Runs a JDBC call on its own thread and reports its outcome with a bounded wait. */ + private static final class AsyncReader implements AutoCloseable { + private final CompletableFuture> result = new CompletableFuture<>(); + private final Thread thread; + + AsyncReader(final Callable call) { + thread = + new Thread( + () -> { + try { + final Object value = call.call(); + result.complete(value instanceof List ? castList(value) : List.of()); + } catch (final Throwable t) { + result.completeExceptionally(t); + } + }, + "poll-ahead-test-reader"); + thread.setDaemon(true); + thread.start(); + } + + @SuppressWarnings("unchecked") + private static List castList(final Object value) { + return (List) value; + } + + /** Waits until the thread is parked, i.e. blocked inside the driver. */ + void awaitBlocked() throws InterruptedException { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (thread.getState() != Thread.State.WAITING + && thread.getState() != Thread.State.TIMED_WAITING) { + assertTrue(System.nanoTime() < deadline, "the reader never blocked"); + assertFalse(result.isDone(), "the reader finished instead of blocking"); + Thread.onSpinWait(); + } + } + + List rows() throws Exception { + try { + return result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final ExecutionException e) { + if (e.getCause() instanceof Exception) { + throw (Exception) e.getCause(); + } + throw e; + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + } + + SQLException failure() throws Exception { + try { + result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final ExecutionException e) { + final Throwable cause = e.getCause(); + if (cause instanceof SQLException) { + return (SQLException) cause; + } + throw new AssertionError("expected a SQLException but got " + cause, cause); + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + throw new AssertionError("expected the reader to fail"); + } + + @Override + public void close() { + thread.interrupt(); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java new file mode 100644 index 0000000000..768e464849 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java @@ -0,0 +1,590 @@ +/* + * 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.arrow.driver.jdbc.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.SQLException; +import java.sql.SQLTimeoutException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightEndpoint; +import org.apache.arrow.flight.FlightStream; +import org.apache.arrow.flight.Ticket; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** + * Tests the progressive-results side of {@link FlightEndpointDataQueue}: deferred stream opening, + * waiting for more endpoints, fail-fast, close, pause/resume and the idle hook. + * + *

    Each fake endpoint stream delivers one batch once the test calls {@link Fake#ready()} and then + * reports end of stream; cancelling it makes a blocked read fail with CANCELLED, like a real {@code + * FlightStream}. + */ +@Timeout(60) +public class FlightEndpointDataQueueDeferredOpenTest { + private static final long WAIT_MS = 10_000; + + private ExecutorService readers; + private final List opened = new CopyOnWriteArrayList<>(); + private final List openedEndpoints = new CopyOnWriteArrayList<>(); + private final AtomicInteger nextId = new AtomicInteger(); + private final List byId = new CopyOnWriteArrayList<>(); + + @BeforeEach + public void setUp() { + readers = Executors.newCachedThreadPool(); + } + + @AfterEach + public void tearDown() { + byId.forEach(Fake::ready); + readers.shutdownNow(); + } + + /** A fake endpoint stream with a hold on its first batch. */ + private static final class Fake { + final CountDownLatch ready = new CountDownLatch(1); + final AtomicInteger reads = new AtomicInteger(); + final AtomicBoolean cancelled = new AtomicBoolean(); + final FlightStream stream = mock(FlightStream.class); + final CloseableEndpointStreamPair pair = mock(CloseableEndpointStreamPair.class); + + Fake() throws Exception { + this(false); + } + + /** An {@code empty} stream reaches end of stream without ever sending a row. */ + Fake(final boolean empty) throws Exception { + final VectorSchemaRoot root = mock(VectorSchemaRoot.class); + when(root.getRowCount()).thenReturn(1); + when(stream.getRoot()).thenReturn(root); + when(pair.getStream()).thenReturn(stream); + when(stream.next()) + .thenAnswer( + invocation -> { + final int read = reads.getAndIncrement(); + if (empty || read > 0) { + return false; + } + ready.await(); + if (cancelled.get()) { + throw CallStatus.CANCELLED.toRuntimeException(); + } + return true; + }); + doAnswer( + invocation -> { + cancelled.set(true); + ready.countDown(); + return null; + }) + .when(stream) + .cancel(anyString(), any()); + } + + void ready() { + ready.countDown(); + } + } + + private List emptyEndpoints(final int count) throws Exception { + final List endpoints = new ArrayList<>(); + for (int i = 0; i < count; i++) { + final int id = nextId.getAndIncrement(); + byId.add(new Fake(true)); + endpoints.add(new FlightEndpoint(new Ticket(new byte[] {(byte) id}))); + } + return endpoints; + } + + private Fake fake(final int id) { + return byId.get(id); + } + + /** Endpoint {@code id} opens the fake stream {@code id}; endpoints are created on demand. */ + private List endpoints(final int count) throws Exception { + final List endpoints = new ArrayList<>(); + for (int i = 0; i < count; i++) { + final int id = nextId.getAndIncrement(); + byId.add(new Fake()); + endpoints.add(new FlightEndpoint(new Ticket(new byte[] {(byte) id}))); + } + return endpoints; + } + + private FlightEndpointDataQueue.EndpointOpener recordingOpener() { + return endpoint -> { + final int id = endpoint.getTicket().getBytes()[0]; + final Fake fake = byId.get(id); + opened.add(fake); + openedEndpoints.add(endpoint); + return fake.pair; + }; + } + + private FlightEndpointDataQueue queue(final int maxOpen) { + return FlightEndpointDataQueue.createNewQueue(readers, maxOpen, recordingOpener()); + } + + @Test + public void endpointsBeyondTheLimitStayPendingUntilAStreamFinishes() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(endpoints(4), false); + // Deterministic: addEndpoints opens the reserved streams before it returns. + assertEquals(List.of(fake(0), fake(1)), opened); + assertEquals(2, queue.openUnreadCount()); + assertEquals(4, queue.unreadCount()); + + fake(0).ready(); + fake(2).ready(); + final CloseableEndpointStreamPair first = queue.next(); + assertSame(fake(0).pair, first); + assertEquals(2, opened.size()); + + // Reading to the end of the stream frees its slot, which opens the next pending endpoint. + queue.enqueue(first); + final CloseableEndpointStreamPair second = queue.next(); + assertSame(fake(2).pair, second); + assertEquals(List.of(fake(0), fake(1), fake(2)), opened); + assertEquals(2, queue.openUnreadCount()); + assertEquals(3, queue.unreadCount()); + } + } + + @Test + public void finishedStreamInADeferredQueueIsClosedAtOnce() throws Exception { + try (FlightEndpointDataQueue queue = queue(1)) { + queue.addEndpoints(endpoints(2), false); + fake(0).ready(); + fake(1).ready(); + final CloseableEndpointStreamPair first = queue.next(); + assertSame(fake(0).pair, first); + queue.enqueue(first); + assertSame(fake(1).pair, queue.next()); + // Closed when it finished, not when the whole queue closes. + verify(fake(0).pair).close(); + } + } + + @Test + public void queueWithoutALimitOpensEveryEndpointAtOnce() throws Exception { + try (FlightEndpointDataQueue queue = queue(Integer.MAX_VALUE)) { + queue.addEndpoints(endpoints(4), false); + assertEquals(4, opened.size()); + assertEquals(4, queue.openUnreadCount()); + } + } + + @Test + public void nextWaitsWhileMoreEndpointsMayArrive() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + assertTrue(queue.isMoreExpected()); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + assertFalse(reader.isDone()); + + queue.addEndpoints(endpoints(1), true); + fake(0).ready(); + assertSame(fake(0).pair, reader.value()); + } + } + + @Test + public void nextReturnsNullOnceNothingMoreIsExpected() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + + queue.addEndpoints(Collections.emptyList(), false); + assertNull(reader.value()); + assertFalse(queue.isMoreExpected()); + } + } + + @Test + public void timedNextTimesOutWhileWaitingForMore() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final SQLTimeoutException timeout = + assertThrows(SQLTimeoutException.class, () -> queue.next(50, TimeUnit.MILLISECONDS)); + assertEquals("Query timed out after 50 MILLISECONDS", timeout.getMessage()); + } + } + + @Test + public void timedNextWakesWhenEndpointsArrive() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final Waiter reader = new Waiter(() -> queue.next(WAIT_MS, TimeUnit.MILLISECONDS)); + reader.awaitWaiting(); + queue.addEndpoints(endpoints(1), false); + fake(0).ready(); + assertSame(fake(0).pair, reader.value()); + } + } + + @Test + public void waitingReaderNeverMissesTheFinalEndpoints() throws Exception { + // The last answer queues its endpoints and clears "more expected" in one locked step, so a + // reader that is already waiting never sees "nothing queued, nothing more expected". + for (int round = 0; round < 50; round++) { + final int first = nextId.get(); + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + queue.addEndpoints(endpoints(1), false); + fake(first).ready(); + assertNotNull(reader.value(), "round " + round + " ended before the final endpoint"); + } + } + } + + @Test + public void failCancelsOpenStreamsDropsPendingAndWakesTheReader() throws Exception { + try (FlightEndpointDataQueue queue = queue(1)) { + queue.addEndpoints(endpoints(2), true); + assertEquals(List.of(fake(0)), opened); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + + final SQLException cause = new SQLException("continuation failed"); + queue.fail(cause); + + assertSame(cause, reader.failure()); + assertSame(cause, queue.failure()); + verify(fake(0).stream).cancel("Query failed.", null); + // The pending endpoint was dropped: it is never opened, not even after the slot is free. + assertEquals(List.of(fake(0)), opened); + assertFalse(queue.isMoreExpected()); + assertSame(cause, assertThrows(SQLException.class, queue::next)); + } + } + + @Test + public void onlyTheFirstFailureIsKept() throws Exception { + try (FlightEndpointDataQueue queue = queue(1)) { + final SQLException first = new SQLException("first"); + queue.fail(first); + queue.fail(new SQLException("second")); + assertSame(first, assertThrows(SQLException.class, queue::next)); + } + } + + @Test + public void streamOpenFailureFailsTheQueueAsAPlainSqlException() throws Exception { + final SQLException openFailure = new SQLException("cannot open the second stream"); + final AtomicInteger calls = new AtomicInteger(); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + Integer.MAX_VALUE, + endpoint -> { + if (calls.getAndIncrement() == 1) { + throw openFailure; + } + return recordingOpener().open(endpoint); + })) { + final SQLException thrown = + assertThrows(SQLException.class, () -> queue.addEndpoints(endpoints(3), true)); + assertSame(openFailure, thrown); + assertEquals(SQLException.class, thrown.getClass()); + assertSame(openFailure, queue.failure()); + assertSame(openFailure, assertThrows(SQLException.class, queue::next)); + // The stream that did open was cancelled, and the third endpoint was never opened. + verify(fake(0).stream).cancel("Query failed.", null); + assertEquals(2, calls.get()); + } + } + + @Test + public void anUnexpectedOpenFailureIsWrappedInAPlainSqlException() throws Exception { + final IllegalStateException unexpected = new IllegalStateException("boom"); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + throw unexpected; + })) { + final SQLException thrown = + assertThrows(SQLException.class, () -> queue.addEndpoints(endpoints(1), true)); + assertEquals(SQLException.class, thrown.getClass()); + assertSame(unexpected, thrown.getCause()); + assertSame(thrown, queue.failure()); + } + } + + @Test + public void closeWakesAReaderWaitingForMoreEndpoints() throws Exception { + final FlightEndpointDataQueue queue = queue(2); + queue.addEndpoints(Collections.emptyList(), true); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + + queue.close(); + + assertTrue(queue.isClosed()); + assertInstanceOf(IllegalStateException.class, reader.failureOf(Throwable.class)); + } + + @Test + public void closeCancelsAndClosesOpenStreamsAndNeverOpensPendingEndpoints() throws Exception { + final FlightEndpointDataQueue queue = queue(1); + queue.addEndpoints(endpoints(2), true); + assertEquals(List.of(fake(0)), opened); + + queue.close(); + + verify(fake(0).stream).cancel("Cancelling this FlightStream.", null); + verify(fake(0).pair).close(); + assertEquals(List.of(fake(0)), opened); + assertThrows(IllegalStateException.class, () -> queue.addEndpoints(endpoints(1), true)); + assertEquals(List.of(fake(0)), opened); + } + + @Test + public void pauseIfFullPausesOnlyAtTheLimitAndTheReaderResumesIt() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + final AtomicInteger resumes = new AtomicInteger(); + final AtomicInteger pauses = new AtomicInteger(); + queue.setResumeAction(resumes::incrementAndGet); + + queue.addEndpoints(endpoints(1), true); + assertFalse(queue.pauseIfFull(pauses::incrementAndGet), "below the limit"); + queue.addEndpoints(endpoints(1), true); + assertTrue(queue.pauseIfFull(pauses::incrementAndGet), "at the limit"); + assertEquals(1, pauses.get()); + assertEquals(0, resumes.get()); + + // Finishing an endpoint drops the unread count below the limit and fires one resume. + fake(0).ready(); + final CloseableEndpointStreamPair first = queue.next(); + assertSame(fake(0).pair, first); + queue.enqueue(first); + final Waiter reader = new Waiter(queue::next); + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (resumes.get() < 1) { + assertTrue(System.nanoTime() < deadline, "the paused poller was never resumed"); + Thread.onSpinWait(); + } + fake(1).ready(); + assertSame(fake(1).pair, reader.value()); + assertEquals(1, resumes.get()); + } + } + + @Test + public void pauseIfFullDoesNotPauseWhenNothingMoreIsExpected() throws Exception { + try (FlightEndpointDataQueue queue = queue(1)) { + queue.addEndpoints(endpoints(1), false); + assertFalse(queue.pauseIfFull(() -> {})); + } + } + + @Test + public void theIdleHookRunsOnTheReaderAndItsEndpointsAreRead() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final AtomicReference idleThread = new AtomicReference<>(); + queue.setIdleAction( + () -> { + idleThread.set(Thread.currentThread()); + try { + queue.addEndpoints(endpoints(1), false); + fake(0).ready(); + } catch (final Exception e) { + throw new AssertionError(e); + } + return true; + }); + final Waiter reader = new Waiter(queue::next); + final Object read = reader.value(); + assertSame(fake(0).pair, read); + assertSame(reader.thread(), idleThread.get()); + } + } + + @Test + public void theIdleHookRunsAgainOnlyAfterTheReaderWasWoken() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final AtomicInteger idleCalls = new AtomicInteger(); + queue.setIdleAction( + () -> { + idleCalls.incrementAndGet(); + return false; + }); + final Waiter reader = new Waiter(queue::next); + reader.awaitWaiting(); + assertEquals(1, idleCalls.get()); + + queue.wakeReader(); + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (idleCalls.get() < 2) { + assertTrue(System.nanoTime() < deadline, "the idle hook did not run after the wake-up"); + Thread.onSpinWait(); + } + assertEquals(2, idleCalls.get()); + queue.addEndpoints(Collections.emptyList(), false); + assertNull(reader.value()); + } + } + + @Test + public void rejectedResumeDuringTheIdleHookDoesNotStrandTheReader() throws Exception { + // Forces the interleaving behind a liveness bug: + // 1. the idle hook returns false (the poller has nothing to run yet); + // 2. before the reader locks again, a poll answer adds two endpoints and the poller pauses + // at the limit; + // 3. the reader takes the first endpoint's end-of-stream, which resumes the poller; the pool + // rejects the resume, so the poller is orphaned and the reader's own wake-up is lost; + // 4. the second endpoint also ends, leaving the reader with nothing queued. + // The reader must give the idle hook another chance instead of waiting for a signal that was + // already sent. + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(Collections.emptyList(), true); + final AtomicBoolean orphaned = new AtomicBoolean(); + final AtomicInteger idleCalls = new AtomicInteger(); + queue.setResumeAction( + () -> { + orphaned.set(true); + queue.wakeReader(); + }); + queue.setIdleAction( + () -> { + try { + if (idleCalls.incrementAndGet() == 1) { + queue.addEndpoints(emptyEndpoints(2), true); + assertTrue(queue.pauseIfFull(() -> {})); + return false; + } + if (orphaned.compareAndSet(true, false)) { + // The orphaned poller runs inline on the reader and finishes the query. + queue.addEndpoints(Collections.emptyList(), false); + return true; + } + return false; + } catch (final Exception e) { + throw new AssertionError(e); + } + }); + + final Waiter reader = new Waiter(queue::next); + assertNull(reader.value(), "the reader never saw the end of the results"); + assertEquals(2, opened.size()); + } + } + + /** Runs a queue call on its own thread, so that a missing wake-up fails instead of hanging. */ + private final class Waiter { + private final CompletableFuture result = new CompletableFuture<>(); + private final Thread thread; + + Waiter(final Callable call) { + thread = + new Thread( + () -> { + try { + result.complete(call.call()); + } catch (final Throwable t) { + result.completeExceptionally(t); + } + }, + "queue-test-reader"); + thread.setDaemon(true); + thread.start(); + } + + Thread thread() { + return thread; + } + + boolean isDone() { + return result.isDone(); + } + + void awaitWaiting() { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + while (thread.getState() != Thread.State.WAITING + && thread.getState() != Thread.State.TIMED_WAITING) { + assertTrue(System.nanoTime() < deadline, "the reader never waited"); + assertFalse(result.isDone(), "the reader returned instead of waiting"); + Thread.onSpinWait(); + } + } + + Object value() throws Exception { + try { + return result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + } + + SQLException failure() throws Exception { + return (SQLException) failureOf(SQLException.class); + } + + Throwable failureOf(final Class expected) throws Exception { + try { + result.get(WAIT_MS, TimeUnit.MILLISECONDS); + } catch (final ExecutionException e) { + assertInstanceOf(expected, e.getCause()); + return e.getCause(); + } catch (final TimeoutException e) { + throw new AssertionError("the reader hung", e); + } + throw new AssertionError("expected the reader to fail"); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java index c6bdb4d23b..af69fca0d0 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java @@ -21,9 +21,11 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.CancelFlightInfoRequest; import org.apache.arrow.flight.CancelStatus; @@ -32,6 +34,7 @@ import org.apache.arrow.flight.FlightStream; import org.apache.arrow.flight.PollInfo; import org.apache.arrow.flight.PutResult; +import org.apache.arrow.flight.Ticket; import org.apache.arrow.flight.sql.impl.FlightSql.CommandPreparedStatementQuery; /** Controllable in-process PollInfo producer used by the JDBC POC conformance tests. */ @@ -61,6 +64,7 @@ public enum Scenario { private final AtomicInteger getFlightInfoCount = new AtomicInteger(); private final AtomicInteger parameterBindCount = new AtomicInteger(); private final AtomicInteger cancelFlightInfoCount = new AtomicInteger(); + private final List scriptedQueries = new CopyOnWriteArrayList<>(); private volatile String lastGetFlightInfoFamily; private volatile Scenario scenario = Scenario.IMMEDIATE; private volatile String scenarioFamily; @@ -90,9 +94,41 @@ public FlightInfo getFlightInfo(final CallContext context, final FlightDescripto return super.getFlightInfo(context, descriptor); } + /** + * Serves {@code query} (sent as a statement query) from a script of poll answers, bypassing the + * canned scenarios. The returned handle holds and releases streams and records what the server + * saw. + */ + public ScriptedPollQuery scripted(final String query, final Answer... answers) { + final ScriptedPollQuery scripted = new ScriptedPollQuery(query, List.of(answers)); + scriptedQueries.add(scripted); + return scripted; + } + + @Override + public void getStream( + final CallContext context, final Ticket ticket, final ServerStreamListener listener) { + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.ownsTicket(ticket)) { + scripted.doGet(ticket, listener); + return; + } + } + super.getStream(context, ticket, listener); + } + @Override public PollInfo pollFlightInfo(final CallContext context, final FlightDescriptor descriptor) { pollDescriptors.add(descriptor); + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.matches(descriptor)) { + return scripted.poll(context, 0); + } + final int index = scripted.continuationIndex(descriptor); + if (index >= 0) { + return scripted.poll(context, index); + } + } final boolean initial = isFlightSqlCommand(descriptor); if (initial) { finalFlightInfo = super.getFlightInfo(context, descriptor); @@ -169,6 +205,11 @@ public void cancelFlightInfo( final CallContext context, final StreamListener listener) { cancelFlightInfoCount.incrementAndGet(); + for (final ScriptedPollQuery scripted : scriptedQueries) { + if (scripted.matches(request.getInfo().getDescriptor())) { + scripted.recordCancelFlightInfo(); + } + } listener.onNext(CancelStatus.CANCELLED); listener.onCompleted(); } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java new file mode 100644 index 0000000000..840286e7c4 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java @@ -0,0 +1,570 @@ +/* + * 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.arrow.driver.jdbc.utils; + +import com.google.protobuf.Any; +import com.google.protobuf.InvalidProtocolBufferException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightDescriptor; +import org.apache.arrow.flight.FlightEndpoint; +import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.FlightProducer.CallContext; +import org.apache.arrow.flight.FlightProducer.ServerStreamListener; +import org.apache.arrow.flight.PollInfo; +import org.apache.arrow.flight.Ticket; +import org.apache.arrow.flight.sql.impl.FlightSql.CommandStatementQuery; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.IntVector; +import org.apache.arrow.vector.VectorSchemaRoot; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.arrow.vector.types.pojo.Field; +import org.apache.arrow.vector.types.pojo.Schema; + +/** + * One scripted progressive query served by {@link PollingMockFlightSqlProducer}. + * + *

    The script is a list of {@link Answer}s: answer 0 answers the initial PollFlightInfo and + * answer {@code i} answers the continuation {@code i}. Endpoints are numbered from 0 in the order + * the answers publish them. Endpoint {@code id} streams {@code rowsPerEndpoint} rows in one batch, + * row {@code r} holding {@code id * 100 + r}. Every DoGet stream can be held before it sends + * anything (start gate) or after it sent its batch but before it completes (end gate), so a test + * decides when a stream is "open and unread" from the server's point of view. + * + *

    The query records every poll, DoGet start/end/cancel and CancelFlightInfo with a nanosecond + * timestamp, and counts concurrently open streams and in-flight polls. + */ +public final class ScriptedPollQuery { + /** Schema of every endpoint stream. */ + public static final Schema SCHEMA = + new Schema(Collections.singletonList(Field.nullable("answer", new ArrowType.Int(32, true)))); + + /** A schema a continuation answer can switch to by mistake. */ + static final Schema CHANGED_SCHEMA = + new Schema( + List.of( + Field.nullable("answer", new ArrowType.Int(32, true)), + Field.nullable("extra", new ArrowType.Int(32, true)))); + + private static final AtomicInteger KEYS = new AtomicInteger(); + + /** What the server records. */ + public enum EventType { + POLL, + POLL_CANCELLED, + DOGET_START, + DOGET_END, + DOGET_CANCELLED, + CANCEL_FLIGHT_INFO + } + + /** One recorded server-side event. */ + public static final class Event { + private final EventType type; + private final int index; + private final long nanos; + + Event(final EventType type, final int index, final long nanos) { + this.type = type; + this.index = index; + this.nanos = nanos; + } + + public EventType type() { + return type; + } + + /** The answer index of a poll, or the endpoint id of a stream. */ + public int index() { + return index; + } + + public long nanos() { + return nanos; + } + + @Override + public String toString() { + return type + ":" + index; + } + } + + /** The server's answer to one poll. */ + public static final class Answer { + private final int newEndpoints; + private final boolean done; + private final boolean failure; + private final boolean schemaChange; + private final CountDownLatch gate; + + private Answer( + final int newEndpoints, + final boolean done, + final boolean failure, + final boolean schemaChange, + final CountDownLatch gate) { + this.newEndpoints = newEndpoints; + this.done = done; + this.failure = failure; + this.schemaChange = schemaChange; + this.gate = gate; + } + + /** Publishes {@code count} more endpoints; the query keeps running. */ + public static Answer endpoints(final int count) { + return new Answer(count, false, false, false, null); + } + + /** Publishes {@code count} more endpoints and completes the query. */ + public static Answer done(final int count) { + return new Answer(count, true, false, false, null); + } + + /** Publishes nothing; the query keeps running. */ + public static Answer empty() { + return endpoints(0); + } + + /** Fails the poll with INTERNAL. */ + public static Answer fail() { + return new Answer(0, false, true, false, null); + } + + /** Publishes one more endpoint but announces a different schema. */ + public static Answer schemaChange() { + return new Answer(1, false, false, true, null); + } + + /** Never answers; the poll ends only when the client cancels it or its deadline expires. */ + public static Answer hang() { + return empty().gatedBy(new CountDownLatch(1)); + } + + /** Holds the answer until {@code gate} is released, or the client cancels the poll. */ + public Answer gatedBy(final CountDownLatch gate) { + return new Answer(newEndpoints, done, failure, schemaChange, gate); + } + } + + private final int key = KEYS.incrementAndGet(); + private final String query; + private final List answers; + private final FlightDescriptor descriptor; + private volatile int rowsPerEndpoint = 1; + + private final List events = new ArrayList<>(); + private final Map startGates = new HashMap<>(); + private final Map endGates = new HashMap<>(); + private final CountDownLatch blockedPoll = new CountDownLatch(1); + private final CountDownLatch pollTerminated = new CountDownLatch(1); + private int openStreams; + private int maxOpenStreams; + private int inFlightPolls; + private int maxInFlightPolls; + + ScriptedPollQuery(final String query, final List answers) { + this.query = query; + this.answers = new ArrayList<>(answers); + this.descriptor = + FlightDescriptor.command( + Any.pack(CommandStatementQuery.newBuilder().setQuery(query).build()).toByteArray()); + } + + public String query() { + return query; + } + + /** Streams {@code rows} rows per endpoint, in one batch. */ + public ScriptedPollQuery rowsPerEndpoint(final int rows) { + this.rowsPerEndpoint = rows; + return this; + } + + // ---- hold and release ------------------------------------------------------------------- + + /** Holds the listed streams before they send anything. */ + public ScriptedPollQuery holdStart(final int... ids) { + synchronized (this) { + for (final int id : ids) { + startGates.put(id, new CountDownLatch(1)); + } + } + return this; + } + + /** Holds the listed streams after they sent their batch, before they complete. */ + public ScriptedPollQuery holdEnd(final int... ids) { + synchronized (this) { + for (final int id : ids) { + endGates.put(id, new CountDownLatch(1)); + } + } + return this; + } + + /** Holds the end of streams {@code 0..count-1}. */ + public ScriptedPollQuery holdAllEnds(final int count) { + for (int id = 0; id < count; id++) { + holdEnd(id); + } + return this; + } + + public void releaseStart(final int id) { + final CountDownLatch gate; + synchronized (this) { + gate = startGates.get(id); + } + if (gate != null) { + gate.countDown(); + } + } + + public void releaseEnd(final int id) { + final CountDownLatch gate; + synchronized (this) { + gate = endGates.get(id); + } + if (gate != null) { + gate.countDown(); + } + } + + /** Releases every held stream. */ + public void releaseAll() { + synchronized (this) { + startGates.values().forEach(CountDownLatch::countDown); + endGates.values().forEach(CountDownLatch::countDown); + } + } + + // ---- observations ----------------------------------------------------------------------- + + public synchronized List events() { + return new ArrayList<>(events); + } + + /** The events of the given types, as {@code TYPE:index} strings, in arrival order. */ + public List eventNames(final EventType... types) { + final List wanted = List.of(types); + final List names = new ArrayList<>(); + for (final Event event : events()) { + if (wanted.contains(event.type)) { + names.add(event.toString()); + } + } + return names; + } + + public synchronized int count(final EventType type) { + int count = 0; + for (final Event event : events) { + if (event.type == type) { + count++; + } + } + return count; + } + + public synchronized boolean hasEvent(final EventType type, final int index) { + return events.stream().anyMatch(event -> event.type == type && event.index == index); + } + + public int pollCount() { + return count(EventType.POLL); + } + + public int doGetStarted() { + return count(EventType.DOGET_START); + } + + public int cancelFlightInfoCount() { + return count(EventType.CANCEL_FLIGHT_INFO); + } + + /** The answer indices of the polls, in arrival order. */ + public List pollIndices() { + final List indices = new ArrayList<>(); + for (final Event event : events()) { + if (event.type == EventType.POLL) { + indices.add(event.index); + } + } + return indices; + } + + /** The arrival times, in nanoseconds, of the polls, in arrival order. */ + public List pollNanos() { + final List nanos = new ArrayList<>(); + for (final Event event : events()) { + if (event.type == EventType.POLL) { + nanos.add(event.nanos); + } + } + return nanos; + } + + public synchronized int maxOpenStreams() { + return maxOpenStreams; + } + + public synchronized int maxInFlightPolls() { + return maxInFlightPolls; + } + + public boolean awaitPollCount(final int count, final long millis) throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.POLL) >= count, millis); + } + + public boolean awaitDoGetStarted(final int count, final long millis) throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.DOGET_START) >= count, millis); + } + + public boolean awaitStream(final EventType type, final int id, final long millis) + throws InterruptedException { + return awaitEvents( + events -> events.stream().anyMatch(e -> e.type == type && e.index == id), millis); + } + + public boolean awaitCancelFlightInfo(final int count, final long millis) + throws InterruptedException { + return awaitEvents(events -> countOf(events, EventType.CANCEL_FLIGHT_INFO) >= count, millis); + } + + /** Waits until a poll is blocked on a gate (or a hang). */ + public boolean awaitBlockedPoll(final long millis) throws InterruptedException { + return blockedPoll.await(millis, TimeUnit.MILLISECONDS); + } + + /** Waits until a blocked poll ended because the client cancelled it. */ + public boolean awaitPollTerminated(final long millis) throws InterruptedException { + return pollTerminated.await(millis, TimeUnit.MILLISECONDS); + } + + private static int countOf(final List events, final EventType type) { + int count = 0; + for (final Event event : events) { + if (event.type == type) { + count++; + } + } + return count; + } + + private synchronized boolean awaitEvents( + final Predicate> condition, final long millis) throws InterruptedException { + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis); + while (!condition.test(events)) { + final long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + return false; + } + TimeUnit.NANOSECONDS.timedWait(this, remaining); + } + return true; + } + + private synchronized void record(final EventType type, final int index) { + events.add(new Event(type, index, System.nanoTime())); + notifyAll(); + } + + // ---- server side ------------------------------------------------------------------------ + + FlightDescriptor descriptor() { + return descriptor; + } + + /** Whether {@code candidate} is this query's statement command (the initial poll). */ + boolean matches(final FlightDescriptor candidate) { + if (!candidate.isCommand()) { + return false; + } + try { + final Any command = Any.parseFrom(candidate.getCommand()); + return command.is(CommandStatementQuery.class) + && query.equals(command.unpack(CommandStatementQuery.class).getQuery()); + } catch (final InvalidProtocolBufferException e) { + return false; + } + } + + void recordCancelFlightInfo() { + record(EventType.CANCEL_FLIGHT_INFO, 0); + } + + private FlightDescriptor continuation(final int index) { + return FlightDescriptor.command( + ("jdbc-continuation-s" + key + "-" + index).getBytes(StandardCharsets.UTF_8)); + } + + /** The answer index a continuation descriptor stands for, or -1 for another query's. */ + int continuationIndex(final FlightDescriptor candidate) { + if (!candidate.isCommand()) { + return -1; + } + final String prefix = "jdbc-continuation-s" + key + "-"; + final String text = new String(candidate.getCommand(), StandardCharsets.UTF_8); + if (!text.startsWith(prefix)) { + return -1; + } + return Integer.parseInt(text.substring(prefix.length())); + } + + boolean ownsTicket(final Ticket ticket) { + return new String(ticket.getBytes(), StandardCharsets.UTF_8).startsWith(ticketPrefix()); + } + + private String ticketPrefix() { + return "jdbc-script-" + key + "-"; + } + + PollInfo poll(final CallContext context, final int index) { + if (index >= answers.size()) { + throw CallStatus.INTERNAL + .withDescription("Script exhausted at poll " + index + " of " + query) + .toRuntimeException(); + } + final Answer answer = answers.get(index); + record(EventType.POLL, index); + synchronized (this) { + inFlightPolls++; + maxInFlightPolls = Math.max(maxInFlightPolls, inFlightPolls); + } + try { + if (answer.gate != null) { + blockedPoll.countDown(); + while (!awaitGate(answer.gate)) { + if (context.isCancelled()) { + record(EventType.POLL_CANCELLED, index); + pollTerminated.countDown(); + throw CallStatus.CANCELLED.withDescription("poll cancelled").toRuntimeException(); + } + } + } + if (answer.failure) { + throw CallStatus.INTERNAL.withDescription("scripted failure").toRuntimeException(); + } + int published = 0; + boolean schemaChanged = false; + for (int i = 0; i <= index; i++) { + published += answers.get(i).newEndpoints; + schemaChanged |= answers.get(i).schemaChange; + } + final List endpoints = new ArrayList<>(); + for (int id = 0; id < published; id++) { + endpoints.add( + new FlightEndpoint(new Ticket((ticketPrefix() + id).getBytes(StandardCharsets.UTF_8)))); + } + final FlightInfo info = + new FlightInfo(schemaChanged ? CHANGED_SCHEMA : SCHEMA, descriptor, endpoints, -1, -1); + final FlightDescriptor next = answer.done ? null : continuation(index + 1); + return new PollInfo(info, next, answer.done ? 1.0 : 0.5, null); + } finally { + synchronized (this) { + inFlightPolls--; + } + } + } + + private static boolean awaitGate(final CountDownLatch gate) { + try { + return gate.await(10, TimeUnit.MILLISECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } + } + + void doGet(final Ticket ticket, final ServerStreamListener listener) { + final int id = + Integer.parseInt( + new String(ticket.getBytes(), StandardCharsets.UTF_8) + .substring(ticketPrefix().length())); + record(EventType.DOGET_START, id); + synchronized (this) { + openStreams++; + maxOpenStreams = Math.max(maxOpenStreams, openStreams); + } + boolean open = true; + try { + if (!awaitStreamGate(startGates, id, listener)) { + return; + } + sendBatch(id, listener); + if (!awaitStreamGate(endGates, id, listener)) { + return; + } + // The stream stops being open before the client can see it complete. + synchronized (this) { + openStreams--; + } + open = false; + record(EventType.DOGET_END, id); + listener.completed(); + } finally { + if (open) { + synchronized (this) { + openStreams--; + } + } + } + } + + // Returns false (after recording it) if the client cancelled the stream while it was held. + private boolean awaitStreamGate( + final Map gates, final int id, final ServerStreamListener listener) { + final CountDownLatch gate; + synchronized (this) { + gate = gates.get(id); + } + if (gate == null) { + return true; + } + while (!awaitGate(gate)) { + if (listener.isCancelled()) { + record(EventType.DOGET_CANCELLED, id); + return false; + } + } + return true; + } + + private void sendBatch(final int id, final ServerStreamListener listener) { + try (BufferAllocator allocator = new RootAllocator(); + VectorSchemaRoot root = VectorSchemaRoot.create(SCHEMA, allocator)) { + root.allocateNew(); + final IntVector vector = (IntVector) root.getVector("answer"); + for (int row = 0; row < rowsPerEndpoint; row++) { + vector.setSafe(row, id * 100 + row); + } + root.setRowCount(rowsPerEndpoint); + listener.start(root); + listener.putNext(); + } + } +} From 1daebc7005d66e395b63ecffa41f5abedc90710f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 01:02:28 +0000 Subject: [PATCH 27/39] BDX-645: sync the poll-ahead TLA+ model with the idle-flag fix The code at dadd45d8a clears idleTried after every consumed future, which is IdleFix = TRUE. The deferred-open design check now runs with it, including Terminates. finding-stale-idle becomes the broken variant staleIdle (IdleFix = FALSE), which must fail Terminates. The duplicate deferred-open-fixed check is dropped. SKILL.md moves the sync commit to dadd45d8a and records the stale-idle bug as found by the model and fixed with its regression test. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-jdbc-poll-ahead/SKILL.md | 24 +++++++++---------- formal/pollinfo-poll-ahead/PollAhead.tla | 7 +++--- formal/pollinfo-poll-ahead/run.sh | 10 ++++---- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md index c868d03bf1..35591c9eb5 100644 --- a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -48,7 +48,7 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. ## Coverage record -Sync commit: `d7c3ed4ab4d30601447bc0518ac05294462b37d3` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). At that commit the poll-ahead poller exists, and the model matches it, including the finding below. +Sync commit: `dadd45d8a` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`). The diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream, and the application still gets a throw either way). Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. @@ -64,7 +64,7 @@ Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/a | `OpenReserved`, `OpenFails` | Q `openReserved`, `register`, `releaseReservations`, `fail`. The `opening` count is `resv`. | | `AppRead`, `AppReadEmpty` | R `next` and `loadNextPublishedEndpoint` -> Q `awaitNext` taking a ready future, or a `null` future -> `onStreamFinished` (slot freed, `reserveSlotsLocked`, paused flag cleared). | | `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). | -| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`). `idleTried` is the local variable in `awaitNext`. | +| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`). `idleTried` is the local variable in `awaitNext`; it is cleared after a wait and after every consumed future (`AppReadEmpty`, `IdleFix`). | | `ReaderWait` and the wakes (`WakeRd`) | Q `awaitNext` -> `awaitChange`; `signalAll` in `addEndpoints`, `register`, `releaseReservations`, `fail`, `close`, `wakeReader`. | | `AppEnd` | Q `awaitNext` returning `null` (futures empty, pending empty, `opening == 0`, `!moreExpected`, under the lock), R `next` returning false. | | `AppThrow` | Q `awaitNext` -> `checkOpen`, `throwIfFailed`; R `next` top-of-call checks of `cancelled` and `queue.failure()`. | @@ -76,7 +76,7 @@ Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/a Run it when a diff touches any covered file: ```sh -git diff --name-only d7c3ed4ab4d30601447bc0518ac05294462b37d3..HEAD -- \ +git diff --name-only dadd45d8a..HEAD -- \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ @@ -101,7 +101,7 @@ Any output means the model may no longer describe the code. Also use this skill N=4 formal/pollinfo-poll-ahead/run.sh ``` - The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `finding-stale-idle` must fail on `Terminates` until the finding below is fixed in the code and `IdleFix` becomes the only behavior (then delete the constant, the finding row and the `idleReset` wording, and run the liveness check on the main row). Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the open finding cannot hide a variant that no longer fails. `openNotReserved` only fails from `N=4` on. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. 3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. 4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. 5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. @@ -109,18 +109,18 @@ Any output means the model may no longer describe the code. Also use this skill ## Known findings -### 1. `finding-stale-idle`: `next()` can hang after a rejected resume (open in the code) +### 1. Stale `idleTried`: `next()` could hang after a rejected resume (found by the model, fixed in `dadd45d8a`) -`Terminates` fails on the model of the code at `d7c3ed4ab`. `FlightEndpointDataQueue.awaitNext` keeps a local `idleTried` flag (line 464). It sets it when the idle hook returns false (line 490) and clears it only after a wait (line 482). If an endpoint finishes between those two, the flag stays set. Shortest path, with a limit of 2 (`finding-stale-idle`, 16 steps): +`Terminates` failed on the model of the code at `d7c3ed4ab` (check `finding-stale-idle`, now the broken variant `staleIdle` with `IdleFix = FALSE`, which still fails). `FlightEndpointDataQueue.awaitNext` keeps a local `idleTried` flag. It set it when the idle hook returned false and cleared it only after a wait. If an endpoint finished between those two, the flag stayed set. Shortest path, with a limit of 2 (16 steps): -1. The application has read the first endpoint. `awaitNext` finds nothing queued, `moreExpected` true. It calls the idle hook (`EndpointPoller.runInlineIfOrphaned`), which returns false because the poller is not orphaned, so `idleTried = true` (line 490). -2. Before the reader takes the lock again (line 468), the poller's open poll answers with two new endpoints. `addEndpoints` reserves both slots, `openReserved` registers the streams (futures not empty), and the poller pauses at the limit (`pauseIfFull`). +1. The application has read the first endpoint. `awaitNext` finds nothing queued, `moreExpected` true. It calls the idle hook (`EndpointPoller.runInlineIfOrphaned`), which returns false because the poller is not orphaned, so `idleTried = true`. +2. Before the reader takes the lock again, the poller's open poll answers with two new endpoints. `addEndpoints` reserves both slots, `openReserved` registers the streams (futures not empty), and the poller pauses at the limit (`pauseIfFull`). 3. The reader takes the first new stream's future. It yields `null` (an endpoint with no rows). `onStreamFinished` frees a slot, clears the paused flag and runs the resume (`EndpointPoller.resume` -> `handBack`). The pool rejects the submit 10 times, so the poller is orphaned (`orphaned.set(true)`, `wakeReader()` on the reader's own thread, so nobody is waiting). -4. The second new stream also yields `null`. The loop reaches the empty-futures branch with nothing queued and `moreExpected` true. `!idleTried` is false (line 477), so the reader does not run the orphaned poller. It waits (line 481) for a signal nobody will send. +4. The second new stream also yields `null`. The loop reaches the empty-futures branch with nothing queued and `moreExpected` true. `!idleTried` is false, so the reader does not run the orphaned poller. It waits for a signal nobody will send. -The code can take this path, but it is narrow: the poller must answer and register a stream inside the reader's few instructions between lines 490 and 468, the connection's poller pool must reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down; a fresh pool below its core size creates a thread instead), and the new endpoints must have no rows. When it happens, `next()` hangs until `cancel()` or `close()`. It was not replayed as a test. +The path was narrow: the poller had to answer and register a stream inside the reader's few instructions between the idle hook and the next lock, the connection's poller pool had to reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down), and the new endpoints had to have no rows. When it happened, `next()` hung until `cancel()` or `close()`. -Fix (checked as `IdleFix = TRUE`, `deferred-open-fixed`): clear `idleTried` whenever the loop consumes a future, for example right after `onStreamFinished(source)` (line 522). Another fix: test the `orphaned` flag inside the locked check at lines 472-483. +Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppRead` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. Commit `dadd45d8a` (`next()` rethrows `queue.failure()` before the CANCELLED mapping) changes only which exception a blocked reader throws, not any model action. ### 2. `finding-open-streams`: the first proposal (`EagerOpen = TRUE`, resolved) @@ -129,4 +129,4 @@ Fix (checked as `IdleFix = TRUE`, `deferred-open-fixed`): clear `idleTried` when ## Files - `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. -- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`. diff --git a/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla index 19004f0666..97cc253118 100644 --- a/formal/pollinfo-poll-ahead/PollAhead.tla +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -64,8 +64,8 @@ CONSTANTS N, \* most endpoints the query can publish Limit, \* pollInfoPrefetch: the poller polls only while queued, unread endpoints < Limit EagerOpen, \* TRUE: every enqueued endpoint takes a stream slot at once (the proposal as first written) - IdleFix, \* FALSE: the code at the sync commit (the reader clears its idle flag only after a wait); - \* TRUE: the proposed fix (it also clears it whenever it finishes an endpoint) + IdleFix, \* TRUE: the code (awaitNext clears idleTried after a wait and after every consumed + \* future, dadd45d8a); FALSE: the stale-idle bug, kept to show that the model catches it Mutation \* "none", or the name of a deliberately broken variant (see run.sh) VARIABLES @@ -405,7 +405,8 @@ AppRead == badPoll, polledAtLimit, resent, spun>> \* Take a null future (an endpoint with no rows) and finish it. awaitNext loops without -\* returning to the application, so idleTried keeps its value unless IdleFix. +\* returning to the application. The code clears idleTried right after onStreamFinished +\* (IdleFix); without it the flag would stay set (the bug fixed in dadd45d8a). AppReadEmpty == /\ app = "reading" /\ rd = "run" diff --git a/formal/pollinfo-poll-ahead/run.sh b/formal/pollinfo-poll-ahead/run.sh index 6f6fdb35f3..0ad8a9642a 100755 --- a/formal/pollinfo-poll-ahead/run.sh +++ b/formal/pollinfo-poll-ahead/run.sh @@ -60,14 +60,13 @@ check() { echo "PollAhead model check N=$N Limit=$LIMIT ($(java -cp "$JAR" tlc2.TLC 2>&1 | head -1))" echo -echo "Design checks (IdleFix = TRUE is the proposed fix; FALSE is the code at the sync commit)" +echo "Design checks (IdleFix = TRUE is the code: awaitNext clears idleTried after every consumed future)" check proposal-as-written TRUE TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" check finding-open-streams TRUE TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" -check deferred-open-fixed FALSE TRUE none "$ALL" yes pass "deferred open, idle flag cleared on progress" -check deferred-open FALSE FALSE none "$ALL" no pass "the code as written: every safety rule holds" -check finding-stale-idle FALSE FALSE none "TypeOK" yes liveness "KNOWN FINDING: next() can hang after a rejected resume (stale idleTried)" +check deferred-open FALSE TRUE none "$ALL" yes pass "the code as written: every safety rule and Terminates hold" echo -echo "Broken variants (each must fail on the rule it targets; the idle fix is on, so only the variant is at fault)" +echo "Broken variants (each must fail on the rule it targets; the idle fix is on, so only the variant is at fault," +echo "except staleIdle, which turns the idle fix off: the bug fixed in dadd45d8a)" check endWhenQueueEmpty FALSE TRUE endWhenQueueEmpty "$ALL" no invariant:NoPrematureEnd "next() ends when the queue is empty" check endIgnoresOpening FALSE TRUE endIgnoresOpening "$ALL" no invariant:NoPrematureEnd "end test forgets streams still opening" check finishBeforeEnqueue FALSE TRUE finishBeforeEnqueue "$ALL" no invariant:NoPrematureEnd "moreExpected cleared before the final endpoints are queued" @@ -85,6 +84,7 @@ check noWake FALSE TRUE noWake "$ALL" yes livenes check pauseNotAtomic FALSE TRUE pauseNotAtomic "$ALL" yes liveness "limit check and pause in separate steps" check ownedClearedLate FALSE TRUE ownedClearedLate "$ALL" yes liveness "pause clears owned after the lock: resume finds it set" check noIdleHook FALSE TRUE noIdleHook "$ALL" yes liveness "an orphaned poller is never run inline" +check staleIdle FALSE FALSE none "$SAFE" yes liveness "idleTried not cleared after a consumed future (rejected resume strands next())" echo if [ "$unexpected" -eq 0 ]; then echo "All checks matched their expectations."; else echo "Some checks did not match. See above."; fi From d58d2cac6a79cff139d0d5cbc49ac63bf573bf36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 01:34:52 +0000 Subject: [PATCH 28/39] BDX-645: end-to-end poll-ahead tests against the conformance server Add SharedServerPollAheadTest (burst, trickle, empty-answers, late-error-buffered, cancel, prefetch 0, prepared, opt-out), enabled by the same pollinfo.shared.* properties. Pin the two POC-order assertions in SharedServerPollInfoExecutionTest to pollInfoPrefetch=0. Co-Authored-By: Claude Opus 5.5 --- .../jdbc/SharedServerPollAheadTest.java | 555 ++++++++++++++++++ .../SharedServerPollInfoExecutionTest.java | 18 +- 2 files changed, 569 insertions(+), 4 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java new file mode 100644 index 0000000000..bebea15b89 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java @@ -0,0 +1,555 @@ +/* + * 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.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.BooleanSupplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +/** + * End-to-end poll-ahead checks (BDX-645) against the standalone conformance server. The assertions + * are on what the server observed: stream concurrency, the order of polls relative to held streams, + * the gaps between polls, and which streams were cancelled. + * + *

    Enable with {@code -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=... + * -Dpollinfo.shared.controlPort=...}. Connections use {@code threadPoolSize=4}: the reader pool + * defaults to 1, and a held stream would starve the others. + */ +@EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") +public class SharedServerPollAheadTest { + private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); + private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); + private static final Duration WAIT = Duration.ofSeconds(10); + // Negative assertions ("nothing happens") hold for this long while /state is polled. + private static final Duration QUIET = Duration.ofMillis(400); + private static final String CONTINUATION = "continuation"; + + private ExecutorService background; + + @BeforeEach + public void resetServer() throws Exception { + background = + Executors.newCachedThreadPool( + runnable -> { + final Thread thread = new Thread(runnable, "shared-server-poll-ahead"); + thread.setDaemon(true); + return thread; + }); + // The previous test closed its connections; wait until the server saw its streams end, because + // /reset must not run with streams open. + awaitUntil("no open streams before reset", () -> counter("do_get_active") == 0); + post("/reset", ""); + } + + @AfterEach + public void printServerState(final TestInfo testInfo) throws Exception { + background.shutdownNow(); + System.out.println("SHARED_SERVER_STATE " + testInfo.getDisplayName()); + System.out.println(state()); + } + + @Test + public void burstDeliversAllRowsWithinThePrefetchLimit() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("burst")) { + rows = values(resultSet, "burst"); + } + assertEquals(range(1, 8), sorted(rows)); + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertTrue(counter("do_get_max_concurrent") <= 2, state()); + assertEquals(4, counter("do_get"), state()); + assertEquals(List.of("1", "2"), continuationOrderSuffixes()); + assertEquals(2, continuationPolls().size()); + assertEquals(0, counter("get_flight_info")); + assertEquals(0, counter("cancellation")); + } + + @Test + public void heldStreamsNeverExceedThePrefetchLimit() throws Exception { + for (int endpoint = 1; endpoint <= 4; endpoint++) { + post("/hold", "{\"endpoint\":" + endpoint + "}"); + } + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + // Four endpoints are known and three streams could be opened, but only two may be. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet( + "a third stream opened at the limit", + () -> counter("do_get") == 2 && counter("do_get_max_concurrent") == 2); + for (int endpoint = 1; endpoint <= 4; endpoint++) { + post("/release-endpoint", "{\"endpoint\":" + endpoint + "}"); + } + try (ResultSet resultSet = result(execution)) { + assertEquals(range(1, 8), sorted(values(resultSet, "burst"))); + } + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertEquals(2, counter("do_get_max_concurrent"), state()); + assertEquals(4, counter("do_get"), state()); + } + + @Test + public void continuationIsPolledWhileTheFirstStreamIsStillHeld() throws Exception { + post("/hold", "{\"endpoint\":1}"); + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertTrue( + events("DoGet.end").stream().noneMatch(event -> event.path("endpoint").asInt() == 1), + "E1 must still be open: " + state()); + post("/release-endpoint", "{\"endpoint\":1}"); + try (ResultSet resultSet = result(execution)) { + assertEquals(range(1, 8), sorted(values(resultSet, "burst"))); + } + } + final long firstContinuationPoll = continuationPolls().get(0).path("sequence").asLong(); + final JsonNode endOfFirstStream = single(events("DoGet.end"), 1); + assertTrue( + firstContinuationPoll < endOfFirstStream.path("sequence").asLong(), + "C1 must be polled before E1 ends: " + state()); + } + + @Test + public void trickleStopsPollingAtTheLimitAndResumesAfterTheStreamsAreReleased() throws Exception { + post("/hold", "{\"endpoint\":1}"); + post("/hold", "{\"endpoint\":2}"); + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "trickle"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + // E1 and E2 are queued and unread, so C2 must not be polled. + assertQuiet( + "polled past the limit", + () -> continuationPolls().size() == 1 && counter("do_get_max_concurrent") == 2); + post("/release-endpoint", "{\"endpoint\":1}"); + post("/release-endpoint", "{\"endpoint\":2}"); + try (ResultSet resultSet = result(execution)) { + rows = values(resultSet, "trickle"); + } + } + assertEquals(range(1, 12), sorted(rows)); + assertEquals(List.of("1", "2", "3", "4", "5"), continuationOrderSuffixes()); + assertEquals(5, continuationPolls().size()); + final long lastRelease = + events("control.release-endpoint").stream() + .mapToLong(event -> event.path("sequence").asLong()) + .max() + .orElseThrow(); + assertTrue( + continuationPolls().get(1).path("sequence").asLong() > lastRelease, + "C2 was polled before the held endpoints were released: " + state()); + assertTrue(counter("do_get_max_concurrent") <= 2, state()); + } + + @Test + public void emptyAnswersBackOffExponentiallyUpToTheCap() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoMaxBackoffMs=300"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("empty-answers")) { + rows = values(resultSet, "empty-answers"); + } + assertEquals(range(1, 4), sorted(rows)); + final List polls = continuationPolls(); + assertEquals(4, polls.size(), state()); + final long gap1 = gapMillis(polls.get(0), polls.get(1)); + final long gap2 = gapMillis(polls.get(1), polls.get(2)); + final long gap3 = gapMillis(polls.get(2), polls.get(3)); + System.out.printf("SHARED_BACKOFF_GAPS_MILLIS %d %d %d%n", gap1, gap2, gap3); + // Lower bounds are the configured delays (with a little slack); the upper bounds are generous, + // except that the third gap must show the cap: 400 ms uncapped, 300 ms capped. + assertTrue(gap1 >= 90 && gap1 < 1000, "gap1=" + gap1); + assertTrue(gap2 >= 180 && gap2 < 1000, "gap2=" + gap2); + assertTrue(gap3 >= 270 && gap3 < 390, "gap3=" + gap3); + } + + @Test + public void lateFailureCancelsTheBufferedStreamsAndDeliversNoRows() throws Exception { + post("/hold", "{\"endpoint\":1}"); + post("/hold", "{\"endpoint\":2}"); + try (Connection connection = connect(true, ""); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "late-error-buffered"); + awaitUntil("C2 polled", () -> continuationPolls().size() >= 2); + // The failure cancels every buffered stream by itself, before anything is read or closed. + awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + // E1 is held, so the first read may still be pending when the poller records the failure. + // The failure then surfaces from executeQuery; otherwise from the first next(). Either way + // it is the same exception and no row is delivered. + final SQLException failure; + final ResultSet resultSet = awaitResultOrFailure(execution); + if (resultSet == null) { + failure = executionFailure(execution); + } else { + try (ResultSet toClose = resultSet) { + failure = assertThrows(SQLException.class, toClose::next); + assertThrows(SQLException.class, toClose::next); + } + } + assertEquals("Continuation PollFlightInfo failed", failureWithMessage(failure)); + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + final List ends = events("DoGet.end"); + assertTrue( + ends.stream().noneMatch(event -> "completed".equals(event.path("outcome").asText())), + "no stream may complete: " + state()); + // E2 was either cancelled or never started; it never sent a row. + assertTrue( + ends.stream() + .filter(event -> event.path("endpoint").asInt() == 2) + .allMatch(event -> "cancelled".equals(event.path("outcome").asText())), + state()); + assertFalse(hasHold(2, "released"), state()); + assertEquals(2, continuationPolls().size(), state()); + // The server already ended the query, so the driver sends no CancelFlightInfo. + assertEquals(0, counter("cancellation"), state()); + } + + @Test + public void cancelWhileAPollIsOpenSendsNoMorePollsAndOneCancelFlightInfo() throws Exception { + try (Connection connection = connect(true, ""); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("cancel-observable")) { + awaitUntil("C1 poll blocked on the server", () -> continuationPolls().size() >= 1); + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + } + assertEquals(1, counter("cancellation"), state()); + assertEquals(1, continuationPolls().size(), state()); + assertEquals(2, counter("poll_flight_info"), state()); + } + + @Test + public void cancelWhileAStreamIsHeldCancelsItAndPollsNoMore() throws Exception { + post("/hold", "{\"endpoint\":1}"); + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + awaitUntil("E1 held", () -> hasHold(1, "held")); + // E1..E4 are known and the poller is paused at the limit, so the poll count is settled. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet("polled past the limit", () -> continuationPolls().size() == 1); + // E2 is readable while E1 is held, so execution has returned its result set. + try (ResultSet resultSet = result(execution)) { + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + } + assertEquals(2, counter("poll_flight_info"), state()); + assertTrue(counter("cancellation") <= 1, state()); + // The held stream was cancelled, never completed. + assertFalse(hasEnd(1, "completed"), state()); + } + + @Test + public void prefetchZeroKeepsThePocOrderOfPollsAndStreams() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=0"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("trickle")) { + rows = values(resultSet, "trickle"); + } + assertEquals(range(1, 12), rows); + final List polls = continuationPolls(); + assertEquals(5, polls.size(), state()); + final List ends = events("DoGet.end"); + assertEquals(6, ends.size(), state()); + for (int k = 1; k <= 5; k++) { + final long endOfPrevious = single(ends, k).path("sequence").asLong(); + assertTrue( + polls.get(k - 1).path("sequence").asLong() > endOfPrevious, + "C" + k + " was polled before E" + k + " ended: " + state()); + } + assertEquals(1, counter("do_get_max_concurrent"), state()); + } + + @Test + public void preparedStatementBindsOnceAndDeliversAllRows() throws Exception { + final List rows; + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + PreparedStatement statement = connection.prepareStatement("burst")) { + statement.setLong(1, 7); + try (ResultSet resultSet = statement.executeQuery()) { + rows = values(resultSet, "burst"); + } + } + assertEquals(range(1, 8), sorted(rows)); + assertEquals(1, counter("parameter_binding"), state()); + assertEquals(1, counter("original_descriptors"), state()); + assertEquals(2, counter("continuation_descriptors"), state()); + assertEquals(3, familyCounter("prepared", "poll_flight_info"), state()); + assertEquals(0, counter("get_flight_info"), state()); + } + + @Test + public void optOutUsesGetFlightInfoOnly() throws Exception { + final List rows; + try (Connection connection = connect(false, ""); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("burst")) { + rows = values(resultSet, "burst"); + } + assertEquals(range(1, 8), sorted(rows)); + assertEquals(1, counter("get_flight_info"), state()); + assertEquals(0, counter("poll_flight_info"), state()); + assertEquals(4, counter("do_get"), state()); + assertTrue(events("PollFlightInfo").isEmpty(), state()); + } + + private Future executeAsync(final Statement statement, final String query) { + return background.submit(() -> statement.executeQuery(query)); + } + + // Null if executeQuery failed; its exception is then available from executionFailure. + private static ResultSet awaitResultOrFailure(final Future execution) + throws Exception { + try { + return result(execution); + } catch (ExecutionException e) { + return null; + } + } + + private static SQLException executionFailure(final Future execution) throws Exception { + final ExecutionException e = assertThrows(ExecutionException.class, execution::get); + assertTrue(e.getCause() instanceof SQLException, e.toString()); + return (SQLException) e.getCause(); + } + + // The message of the first exception in the cause chain that is the driver's own failure. + private static String failureWithMessage(final Throwable failure) { + Throwable current = failure; + while (current != null) { + if ("Continuation PollFlightInfo failed".equals(current.getMessage())) { + return current.getMessage(); + } + current = current.getCause(); + } + return failure.getMessage(); + } + + private static ResultSet result(final Future execution) throws Exception { + final ResultSet resultSet = execution.get(WAIT.toSeconds(), TimeUnit.SECONDS); + assertNotNull(resultSet); + return resultSet; + } + + private static Connection connect(final boolean usePollInfo, final String extraProperties) + throws Exception { + return DriverManager.getConnection( + String.format( + "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s" + + "&threadPoolSize=4%s", + FLIGHT_PORT, usePollInfo, extraProperties.isEmpty() ? "" : "&" + extraProperties)); + } + + private static List values(final ResultSet resultSet, final String scenario) + throws Exception { + final List values = new ArrayList<>(); + while (resultSet.next()) { + assertEquals(scenario, resultSet.getString("scenario")); + values.add(resultSet.getLong("value")); + } + return values; + } + + private static List range(final int firstInclusive, final int lastInclusive) { + return IntStream.rangeClosed(firstInclusive, lastInclusive) + .mapToObj(Long::valueOf) + .collect(Collectors.toList()); + } + + private static List sorted(final List values) { + final List copy = new ArrayList<>(values); + Collections.sort(copy); + return copy; + } + + private static long gapMillis(final JsonNode earlier, final JsonNode later) { + return TimeUnit.NANOSECONDS.toMillis( + later.path("elapsed_ns").asLong() - earlier.path("elapsed_ns").asLong()); + } + + // Events, filtered by method; lifecycle events sit between requests, so never go by position. + private static List events(final String method) { + final List matching = new ArrayList<>(); + for (final JsonNode event : stateJson().path("events")) { + if (method.equals(event.path("method").asText())) { + matching.add(event); + } + } + return matching; + } + + private static List continuationPolls() { + return events("PollFlightInfo").stream() + .filter(event -> CONTINUATION.equals(event.path("descriptor_kind").asText())) + .collect(Collectors.toList()); + } + + private static List continuationOrderSuffixes() { + final List suffixes = new ArrayList<>(); + for (final JsonNode descriptor : stateJson().path("continuation_order")) { + final String text = descriptor.asText(); + suffixes.add(text.substring(text.lastIndexOf('/') + 1)); + } + return suffixes; + } + + private static boolean hasHold(final int endpoint, final String outcome) { + return events("DoGet.hold").stream() + .anyMatch( + event -> + event.path("endpoint").asInt() == endpoint + && outcome.equals(event.path("outcome").asText())); + } + + private static boolean hasEnd(final int endpoint, final String outcome) { + return events("DoGet.end").stream() + .anyMatch( + event -> + event.path("endpoint").asInt() == endpoint + && outcome.equals(event.path("outcome").asText())); + } + + private static JsonNode single(final List events, final int endpoint) { + final List matching = + events.stream() + .filter(event -> event.path("endpoint").asInt() == endpoint) + .collect(Collectors.toList()); + assertEquals(1, matching.size(), "endpoint " + endpoint + ": " + matching); + return matching.get(0); + } + + private static int counter(final String name) { + return stateJson().path("counters").path(name).asInt(); + } + + private static int familyCounter(final String family, final String name) { + return stateJson().path("counters_by_family").path(family).path(name).asInt(); + } + + private static void awaitUntil(final String description, final BooleanSupplier condition) + throws Exception { + final long deadline = System.nanoTime() + WAIT.toNanos(); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + throw new AssertionError("Timed out waiting for: " + description + "\n" + state()); + } + Thread.sleep(10); + } + } + + // The condition must stay true for the whole quiet window. + private static void assertQuiet(final String message, final BooleanSupplier condition) + throws Exception { + final long end = System.nanoTime() + QUIET.toNanos(); + do { + assertTrue(condition.getAsBoolean(), message + "\n" + state()); + Thread.sleep(25); + } while (System.nanoTime() < end); + } + + private static JsonNode stateJson() { + try { + return JSON.readTree(state()); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String state() { + return request("GET", "/state", ""); + } + + private static void post(final String path, final String body) { + request("POST", path, body); + } + + private static String request(final String method, final String path, final String body) { + try { + final HttpRequest.Builder builder = + HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + CONTROL_PORT + path)) + .timeout(Duration.ofSeconds(2)); + if ("POST".equals(method)) { + builder.header("Content-Type", "application/json"); + builder.POST(HttpRequest.BodyPublishers.ofString(body)); + } else { + builder.GET(); + } + final HttpResponse response = + HTTP_CLIENT.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + assertEquals("POST".equals(method) ? 204 : 200, response.statusCode(), response.body()); + return response.body(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java index 165a1d72dc..b6e0408a8a 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -167,8 +167,10 @@ public void t7UnavailableDoesNotFallbackOrReexecute() throws Exception { @Test @Order(8) + // Pinned to the POC path (pollInfoPrefetch=0): with poll-ahead the failure may surface before + // the first row is read. public void t7LateErrorSurfacesAtNextReadBoundary() throws Exception { - try (Connection connection = connect(true); + try (Connection connection = connect(true, "pollInfoPrefetch=0"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("late-error")) { assertTrue(resultSet.next()); @@ -241,8 +243,10 @@ public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { @Test @Order(11) + // Pinned to the POC path (pollInfoPrefetch=0): poll-ahead polls C1 in the background, so the + // poll count asserted here is only fixed when the reader polls. public void t9ClosingIncompleteResultAttemptsFlightInfoCancellation() throws Exception { - try (Connection connection = connect(true); + try (Connection connection = connect(true, "pollInfoPrefetch=0"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("cancel-observable")) { assertTrue(resultSet.next()); @@ -253,10 +257,16 @@ public void t9ClosingIncompleteResultAttemptsFlightInfoCancellation() throws Exc } private static Connection connect(final boolean usePollInfo) throws Exception { + return connect(usePollInfo, ""); + } + + /** Connects with extra properties, for example {@code pollInfoPrefetch=0} for the POC path. */ + private static Connection connect(final boolean usePollInfo, final String extraProperties) + throws Exception { return DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s", - FLIGHT_PORT, usePollInfo)); + "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s%s", + FLIGHT_PORT, usePollInfo, extraProperties.isEmpty() ? "" : "&" + extraProperties)); } private static List directValues(final Connection connection, final String query) From 4b831553c195a6fbf180efe446dfc409fdc6ee79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 02:25:04 +0000 Subject: [PATCH 29/39] BDX-645: fix poll-ahead correctness findings (slot release, errors, first load, fallback, cancel) - Free an endpoint's slot on the application thread when its stream is exhausted (queue.endpointExhausted); no re-enqueue, so the poller no longer waits for completion order or a free reader thread. - Fail the queue for any Throwable on the poller thread (rethrow Errors) and release opener reservations in a finally. - executeQuery's first load no longer waits for unpublished endpoints (queue.nextAvailable); next() waits instead. - Fallback path (prefetch 0 / busy pool) loops while a continuation remains, so zero-row endpoints cannot end the result early. - A cancel racing a poll reports "Statement canceled"; the queue fails before the blocking CancelFlightInfo runs. - populateData exits cancel the unfinished operation. - Stop opening streams after a failure. - Restore interrupt flags; make the poller field volatile. - PollInfoExecutionTest: the UNIMPLEMENTED continuation test accepts the fail-fast failure before the first row under poll-ahead. Co-Authored-By: Claude Opus 5.5 --- .../ArrowFlightJdbcFlightStreamResultSet.java | 94 ++++++--- .../arrow/driver/jdbc/EndpointPoller.java | 24 ++- .../driver/jdbc/client/PollInfoOperation.java | 3 +- .../jdbc/utils/FlightEndpointDataQueue.java | 104 +++++++--- .../arrow/driver/jdbc/EndpointPollerTest.java | 126 ++++++++++++ .../arrow/driver/jdbc/PollAheadTest.java | 193 +++++++++++++++++- .../driver/jdbc/PollInfoExecutionTest.java | 26 ++- ...ightEndpointDataQueueDeferredOpenTest.java | 95 +++++++++ .../driver/jdbc/utils/ScriptedPollQuery.java | 46 ++++- 9 files changed, 639 insertions(+), 72 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index 115b9548cb..ab53e7971b 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -59,7 +59,7 @@ public final class ArrowFlightJdbcFlightStreamResultSet private final PollInfoOperation pollInfoOperation; // Written by whichever party currently owns polling (the poller, or the reader inline). private volatile int consumedEndpointCount; - private EndpointPoller poller; + private volatile EndpointPoller poller; private int pollerQueryTimeoutSeconds; private CloseableEndpointStreamPair currentEndpointData; private FlightEndpointDataQueue flightEndpointDataQueue; @@ -176,7 +176,8 @@ private void loadNewFlightStream() throws SQLException { if (currentEndpointData != null) { AutoCloseables.closeNoChecked(currentEndpointData); } - this.currentEndpointData = getNextEndpointStream(true); + // The first load must not wait for endpoints that were not published yet. + this.currentEndpointData = getNextEndpointStream(true, false); } @Override @@ -198,6 +199,11 @@ private void populateData() throws SQLException { startPoller(); } loadNewFlightStream(); + // Ownership of the root will be passed onto the cursor. Without a stream yet, next() waits + // for the first endpoint that has rows. + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + } } catch (final SQLException | RuntimeException e) { if (poller != null) { poller.stop(); @@ -207,13 +213,13 @@ private void populateData() throws SQLException { } catch (final Exception closeException) { e.addSuppressed(closeException); } + // No ResultSet will be returned to close an unfinished operation: end it here. + if (pollInfoOperation != null && !pollInfoOperation.isComplete()) { + pollInfoOperation.cancel(); + } + finishPollInfoOperation(); throw e; } - - // Ownership of the root will be passed onto the cursor. - if (currentEndpointData != null) { - populateDataForCurrentFlightStream(); - } } private void populateDataForCurrentFlightStream() throws SQLException { @@ -274,23 +280,28 @@ public boolean next() throws SQLException { continue; } - enqueueEndpointData(currentEndpointData); + // The slot is freed here, on the application thread, not when a reader task later + // consumes the end of the stream. + final CloseableEndpointStreamPair exhausted = currentEndpointData; + currentEndpointData = null; + endpointExhausted(exhausted); } - currentEndpointData = getNextEndpointStream(false); + currentEndpointData = getNextEndpointStream(false, true); } catch (final FlightRuntimeException e) { + // A concurrent statement.cancel() (or close) cancels in-flight FlightStreams, + // which surface here as CANCELLED. Normalize to Avatica's "Statement canceled". This wins + // over a failure recorded by a poll that the cancel ended. + if ((cancelled || flightEndpointDataQueue.isClosed()) + && e.status().code() == CallStatus.CANCELLED.code()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } // A failed continuation poll cancels the open streams, which surface here as CANCELLED // while the reader is blocked on one: report the recorded failure, not the cancel. final SQLException recordedFailure = flightEndpointDataQueue.failure(); if (recordedFailure != null) { throw recordedFailure; } - // A concurrent statement.cancel() (or close) cancels in-flight FlightStreams, - // which surface here as CANCELLED. Normalize to Avatica's "Statement canceled". - if ((cancelled || flightEndpointDataQueue.isClosed()) - && e.status().code() == CallStatus.CANCELLED.code()) { - throw AvaticaConnection.HELPER.createException("Statement canceled"); - } throw e; } @@ -371,8 +382,8 @@ public synchronized void close() { } } - private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeout) - throws SQLException { + private CloseableEndpointStreamPair getNextEndpointStream( + final boolean canTimeout, final boolean waitForMore) throws SQLException { try { if (canTimeout) { final long remainingTimeoutNanos = remainingQueryTimeoutNanos(); @@ -381,7 +392,10 @@ private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeo throw new SQLTimeoutException("Query timed out before retrieving its first endpoint"); } try { - return flightEndpointDataQueue.next(remainingTimeoutNanos, TimeUnit.NANOSECONDS); + return waitForMore + ? flightEndpointDataQueue.next(remainingTimeoutNanos, TimeUnit.NANOSECONDS) + : flightEndpointDataQueue.nextAvailable( + remainingTimeoutNanos, TimeUnit.NANOSECONDS); } catch (SQLTimeoutException e) { if (statement != null && e.getMessage().startsWith("Query timed out after")) { final SQLTimeoutException jdbcTimeout = @@ -396,7 +410,7 @@ private CloseableEndpointStreamPair getNextEndpointStream(final boolean canTimeo } } } - return flightEndpointDataQueue.next(); + return waitForMore ? flightEndpointDataQueue.next() : flightEndpointDataQueue.nextAvailable(); } catch (final IllegalStateException e) { throw normalizeClosedQueueException(flightEndpointDataQueue, e); } @@ -431,10 +445,10 @@ static void enqueueEndpointData( } } - private void enqueueEndpointData(final CloseableEndpointStreamPair endpointRequest) + private void endpointExhausted(final CloseableEndpointStreamPair endpointRequest) throws SQLException { try { - flightEndpointDataQueue.enqueue(endpointRequest); + flightEndpointDataQueue.endpointExhausted(endpointRequest); } catch (final IllegalStateException e) { throw normalizeClosedQueueException(flightEndpointDataQueue, e); } @@ -466,6 +480,7 @@ private void startPoller() throws SQLException { connection.getPollerExecutor(), answer -> appendEndpoints(answer.flightInfo(), answer.hasContinuation()), this::mapContinuationFailure, + this::endPollInfoOperationAfterFailure, this::finishPollInfoOperation, connection.getPollInfoMaxBackoffMs()); flightEndpointDataQueue.setResumeAction(newPoller::resume); @@ -506,13 +521,11 @@ private void appendEndpoints(final FlightInfo updatedFlightInfo, final boolean m /** Maps a failed background continuation poll to the exception the reader will throw. */ private SQLException mapContinuationFailure(final FlightRuntimeException e) { - if (e.status().code() == FlightStatusCode.CANCELLED - || e.status().code() == FlightStatusCode.TIMED_OUT) { - pollInfoOperation.cancel(); - } else { - pollInfoOperation.terminate(); + // A cancel that ended this poll is not a failure: Statement.cancel() cancels the operation + // before ResultSet.cancel() raises the flag, so the poller can get here first. + if (pollInfoOperation.isCancelled()) { + return AvaticaConnection.HELPER.createException("Statement canceled"); } - finishPollInfoOperation(); if (e.status().code() == FlightStatusCode.TIMED_OUT) { final SQLTimeoutException timeout = new SQLTimeoutException( @@ -524,12 +537,23 @@ private SQLException mapContinuationFailure(final FlightRuntimeException e) { return new SQLException("Continuation PollFlightInfo failed", e); } + // Runs after the queue recorded the failure, because cancel() is a blocking RPC. + private void endPollInfoOperationAfterFailure(final FlightRuntimeException e) { + if (e.status().code() == FlightStatusCode.CANCELLED + || e.status().code() == FlightStatusCode.TIMED_OUT) { + pollInfoOperation.cancel(); + } else { + pollInfoOperation.terminate(); + } + finishPollInfoOperation(); + } + private boolean loadNextPublishedEndpoint() throws SQLException { if (poller != null) { // Poll-ahead: the queue is the single source of truth. It waits while more may arrive, and // null means every endpoint was read and the poller finished. try { - currentEndpointData = getNextEndpointStream(false); + currentEndpointData = getNextEndpointStream(false, true); } catch (final FlightRuntimeException e) { if ((cancelled || flightEndpointDataQueue.isClosed()) && e.status().code() == CallStatus.CANCELLED.code()) { @@ -552,11 +576,15 @@ private boolean loadNextPublishedEndpoint() throws SQLException { return false; } try { - appendEndpoints(pollInfoOperation.pollNextAvailable(), false); - currentEndpointData = getNextEndpointStream(false); - if (currentEndpointData != null) { - populateDataForCurrentFlightStream(); - return true; + // Endpoints that were appended but have no rows must not end the result while the query + // still has a continuation. + while (pollInfoOperation.hasContinuation()) { + appendEndpoints(pollInfoOperation.pollNextAvailable(), false); + currentEndpointData = getNextEndpointStream(false, true); + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + return true; + } } finishPollInfoOperation(); return false; diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java index 71db29fe52..69379fffb4 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java @@ -21,6 +21,7 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.LockSupport; +import java.util.function.Consumer; import java.util.function.Function; import org.apache.arrow.driver.jdbc.client.PollBackoff; import org.apache.arrow.driver.jdbc.client.PollInfoOperation; @@ -71,6 +72,7 @@ interface AnswerSink { private final Executor executor; private final AnswerSink sink; private final Function failureMapper; + private final Consumer afterFailure; private final Runnable onFinished; private final PollBackoff backoff; @@ -85,6 +87,7 @@ interface AnswerSink { final Executor executor, final AnswerSink sink, final Function failureMapper, + final Consumer afterFailure, final Runnable onFinished, final long maxBackoffMillis) { this.queue = queue; @@ -92,6 +95,7 @@ interface AnswerSink { this.executor = executor; this.sink = sink; this.failureMapper = failureMapper; + this.afterFailure = afterFailure; this.onFinished = onFinished; this.backoff = new PollBackoff(maxBackoffMillis); } @@ -144,8 +148,11 @@ boolean runInlineIfOrphaned() { } try { drive(true); - } catch (final RuntimeException e) { - fail(e); + } catch (final Throwable t) { + fail(t); + if (t instanceof Error) { + throw (Error) t; + } } return true; } @@ -176,8 +183,12 @@ private void handBack() { private void runOnPool() { try { drive(false); - } catch (final RuntimeException e) { - fail(e); + } catch (final Throwable t) { + // Whatever ends the poller must reach the reader, or next() would wait forever. + fail(t); + if (t instanceof Error) { + throw (Error) t; + } } } @@ -267,10 +278,13 @@ private void onPollFailed(final FlightRuntimeException e) { return; } state = State.FAILED; + // The queue fails first, so the reader sees the failure at once; the cleanup (a blocking + // CancelFlightInfo RPC) follows. queue.fail(failureMapper.apply(e)); + afterFailure.accept(e); } - private void fail(final RuntimeException e) { + private void fail(final Throwable e) { LOGGER.debug("PollFlightInfo poller failed unexpectedly", e); state = State.FAILED; queue.fail(new SQLException("Continuation PollFlightInfo failed", e)); diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java index 040b7327f5..0b70cae593 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -109,7 +109,8 @@ public void cancel() { } } - boolean isCancelled() { + /** Whether {@link #cancel()} was called, by the statement, the deadline handling or close. */ + public boolean isCancelled() { return cancelled.get(); } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java index 28a0b7cf61..09c0053da2 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java @@ -245,6 +245,10 @@ public void addEndpoints(final List endpoints, final boolean mor lock.lock(); try { checkOpen(); + if (failure != null) { + // Fail fast: nothing is queued or opened after a failure; the reader rethrows it. + return; + } pending.addAll(endpoints); this.moreExpected = moreExpected; toOpen = reserveSlotsLocked(); @@ -338,26 +342,36 @@ private List reserveSlotsLocked() { return reserved; } - // Opens reserved endpoints without the lock. On failure, the rest are released and the queue - // fails. + // Opens reserved endpoints without the lock. On failure, or once the queue failed or closed, the + // reservations that were not handed to register() are released, even for an Error. private void openReserved(final List reserved) throws SQLException { - for (int index = 0; index < reserved.size(); index++) { - final CloseableEndpointStreamPair stream; - try { - stream = opener.open(reserved.get(index)); - } catch (final SQLException | RuntimeException e) { - final SQLException cause = - e instanceof SQLException ? (SQLException) e : new SQLException(e); - releaseReservations(reserved.size() - index); - fail(cause); - throw cause; + int settled = 0; + try { + while (settled < reserved.size()) { + if (shutdown || failure != null) { + return; + } + final CloseableEndpointStreamPair stream; + try { + stream = opener.open(reserved.get(settled)); + } catch (final SQLException | RuntimeException e) { + final SQLException cause = + e instanceof SQLException ? (SQLException) e : new SQLException(e); + fail(cause); + throw cause; + } + // From here register() settles this endpoint's reservation, even when it throws. + settled++; + try { + register(stream); + } catch (final RuntimeException e) { + fail(new SQLException("Failed to start reading an endpoint stream", e)); + throw e; + } } - try { - register(stream); - } catch (final RuntimeException e) { - releaseReservations(reserved.size() - index - 1); - fail(new SQLException("Failed to start reading an endpoint stream", e)); - throw e; + } finally { + if (settled < reserved.size()) { + releaseReservations(reserved.size() - settled); } } } @@ -427,6 +441,25 @@ private static void closeQuietly(final CloseableEndpointStreamPair endpoint) { } } + /** + * The application read an endpoint's stream to its end. Frees the endpoint's slot at once, on the + * calling thread, under the queue lock: the open-unread count drops, the stream is closed, + * pending endpoints open, and a paused poller resumes. Nothing is re-enqueued, so a slot does not + * wait for a reader task or for the completion order of other endpoints. + * + * @param finished the stream the application just exhausted; it is closed here. + * @throws SQLException if opening a pending endpoint fails; the queue is then failed with it. + */ + public void endpointExhausted(final CloseableEndpointStreamPair finished) throws SQLException { + checkNotNull(finished); + if (opener == null) { + // A queue without an opener has no slots; the reader task consumes the end of the stream. + enqueue(finished); + return; + } + onStreamFinished(finished); + } + // The reader finished an endpoint: free its slot, open pending endpoints, and wake the poller. private void onStreamFinished(final CloseableEndpointStreamPair finished) throws SQLException { final List toOpen; @@ -458,7 +491,10 @@ private void onStreamFinished(final CloseableEndpointStreamPair finished) throws } private CloseableEndpointStreamPair awaitNext( - final boolean timed, final long timeoutValue, final TimeUnit timeoutUnit) + final boolean timed, + final long timeoutValue, + final TimeUnit timeoutUnit, + final boolean waitForMore) throws SQLException { final long deadlineNanos = timed ? System.nanoTime() + timeoutUnit.toNanos(timeoutValue) : 0L; boolean idleTried = false; @@ -471,7 +507,7 @@ private CloseableEndpointStreamPair awaitNext( throwIfFailed(); if (futures.isEmpty()) { final boolean nothingQueued = pending.isEmpty() && opening == 0; - if (nothingQueued && !moreExpected) { + if (nothingQueued && (!moreExpected || !waitForMore)) { return null; } if (nothingQueued && idleAction != null && !idleTried) { @@ -511,7 +547,10 @@ private CloseableEndpointStreamPair awaitNext( throw (FlightRuntimeException) cause; } throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); - } catch (InterruptedException | CancellationException e) { + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); + } catch (final CancellationException e) { throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); } // Get the next FlightStream that has a root with content. @@ -557,6 +596,7 @@ private Future takeFuture() throws SQLException { try { return completionService.take(); } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); throw AvaticaConnection.HELPER.wrap(e.getMessage(), e); } } @@ -572,6 +612,7 @@ private Future pollFuture( return future; } } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); throw new SQLTimeoutException("Query was interrupted", e); } throw new SQLTimeoutException( @@ -594,7 +635,7 @@ private void throwIfFailed() throws SQLException { */ public CloseableEndpointStreamPair next(final long timeoutValue, final TimeUnit timeoutUnit) throws SQLException { - return awaitNext(true, timeoutValue, timeoutUnit); + return awaitNext(true, timeoutValue, timeoutUnit, true); } /** @@ -603,7 +644,24 @@ public CloseableEndpointStreamPair next(final long timeoutValue, final TimeUnit * @return a FlightStream that is ready to consume or null if all FlightStreams are ended. */ public CloseableEndpointStreamPair next() throws SQLException { - return awaitNext(false, 0L, TimeUnit.NANOSECONDS); + return awaitNext(false, 0L, TimeUnit.NANOSECONDS, true); + } + + /** + * Like {@link #next(long, TimeUnit)}, but returns {@code null} instead of waiting for endpoints + * that were not published yet: it waits only while a queued endpoint may still produce a batch. + * The first load of a result uses it, so that {@code executeQuery} does not wait for the poller. + * + * @return a FlightStream that is ready to consume, or null if no queued endpoint is left. + */ + public CloseableEndpointStreamPair nextAvailable( + final long timeoutValue, final TimeUnit timeoutUnit) throws SQLException { + return awaitNext(true, timeoutValue, timeoutUnit, false); + } + + /** Untimed variant of {@link #nextAvailable(long, TimeUnit)}. */ + public CloseableEndpointStreamPair nextAvailable() throws SQLException { + return awaitNext(false, 0L, TimeUnit.NANOSECONDS, false); } /** Checks if this queue is open. */ diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java new file mode 100644 index 0000000000..ee56e648a6 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.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.arrow.driver.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.SQLException; +import java.util.Collections; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.apache.arrow.driver.jdbc.client.PollInfoOperation; +import org.apache.arrow.driver.jdbc.utils.FlightEndpointDataQueue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +/** Tests how {@link EndpointPoller} ends: whatever stops the poller must reach the reader. */ +@Timeout(60) +public class EndpointPollerTest { + private static final long WAIT_MS = 10_000; + + private ExecutorService readers; + private ExecutorService pollerPool; + + @BeforeEach + public void setUp() { + readers = Executors.newCachedThreadPool(daemonThreads()); + // An Error escapes the pool task by design; keep it out of the test output. + pollerPool = Executors.newCachedThreadPool(daemonThreads()); + } + + @AfterEach + public void tearDown() { + readers.shutdownNow(); + pollerPool.shutdownNow(); + } + + private static ThreadFactory daemonThreads() { + return runnable -> { + final Thread thread = new Thread(runnable, "endpoint-poller-test"); + thread.setDaemon(true); + thread.setUncaughtExceptionHandler((t, e) -> {}); + return thread; + }; + } + + // F2. An Error on the poller thread used to leave next() waiting forever. + @Test + public void anErrorOnThePollerThreadFailsTheQueueInsteadOfHangingTheReader() throws Exception { + final StackOverflowError error = new StackOverflowError("scripted"); + final PollInfoOperation operation = mock(PollInfoOperation.class); + when(operation.pollOnce()).thenThrow(error); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + throw new AssertionError("no endpoint is expected"); + })) { + queue.addEndpoints(Collections.emptyList(), true); + final EndpointPoller poller = + new EndpointPoller( + queue, + operation, + pollerPool, + answer -> {}, + exception -> new SQLException(exception), + exception -> {}, + () -> {}, + 100); + assertTrue(poller.start()); + + final CompletableFuture next = new CompletableFuture<>(); + final Thread reader = + new Thread( + () -> { + try { + next.complete(queue.next()); + } catch (final Throwable t) { + next.completeExceptionally(t); + } + }); + reader.setDaemon(true); + reader.start(); + + final ExecutionException thrown; + try { + next.get(WAIT_MS, TimeUnit.MILLISECONDS); + throw new AssertionError("next() returned instead of failing"); + } catch (final TimeoutException e) { + throw new AssertionError("next() hung after an Error on the poller thread", e); + } catch (final ExecutionException e) { + thrown = e; + } + final SQLException failure = assertInstanceOf(SQLException.class, thrown.getCause()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertSame(error, failure.getCause()); + assertEquals(EndpointPoller.State.FAILED, poller.state()); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java index 0cc5053a8f..0a089fae55 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -39,6 +39,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer; import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery; import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; @@ -521,6 +522,178 @@ public void schemaChangeFailsTheResultAsAPlainSqlException() throws Exception { } } + // F1. A finished endpoint frees its slot when the application finishes it, not when a reader + // task later consumes the end of the stream. + @Test + public void steadyStateOverlapPollsWhileTheNextEndpointIsStillUnread() throws Exception { + // E0 is held after its row, so E1's batch is ready (and its future completed) before the + // application finishes E0. Completion order would hand E1 to the application first and keep + // E0's slot until E1 was fully read. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.endpoints(1), Answer.done(0)) + .holdEnd(0) + .holdEnd(1) + .holdStart(1); + final List rows = new ArrayList<>(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + rows.add(0); + assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertFalse(script.awaitPollCount(3, QUIET_MS), "polled past the limit"); + + script.releaseStart(1); + assertTrue(script.awaitStream(EventType.BATCH_SENT, 1, WAIT_MS)); + // Let the client's reader task receive E1's batch. + Thread.sleep(QUIET_MS); + + try (AsyncReader reader = + new AsyncReader(() -> List.of(resultSet.next() ? resultSet.getInt(1) : -1))) { + script.releaseEnd(0); + rows.addAll(reader.rows()); + } + // The application is now reading E1 (unread, still held on the server) and has not asked for + // more: finishing E0 alone must have resumed the poller. + assertTrue(script.awaitPollCount(3, WAIT_MS), "C2 waited for the application to go idle"); + assertFalse(script.hasEvent(EventType.DOGET_END, 1)); + + script.releaseEnd(1); + rows.addAll(readAll(resultSet)); + } + assertEquals(List.of(0, 100, 200), sorted(rows)); + assertEquals(List.of(0, 1, 2, 3), script.pollIndices()); + } + + @Test + public void singleReaderThreadStillFreesAFinishedEndpointsSlot() throws Exception { + // threadPoolSize=1: E1's reader task, held before its first batch, occupies the only reader + // thread, so a marker task for the finished E0 could never run. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.endpoints(1), Answer.done(0)) + .holdStart(1); + final List rows = new ArrayList<>(); + try (Connection connection = connect(1, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + rows.add(0); + assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertFalse(script.awaitPollCount(3, QUIET_MS), "polled past the limit"); + + try (AsyncReader reader = + new AsyncReader(() -> List.of(resultSet.next() ? resultSet.getInt(1) : -1))) { + // E0 is done: its slot is freed on the application thread and the poller polls C2, while + // the application waits for E1 and the only reader thread is stuck on E1. + assertTrue( + script.awaitPollCount(3, WAIT_MS), "the slot of a finished endpoint stayed held"); + reader.awaitBlocked(); + script.releaseStart(1); + rows.addAll(reader.rows()); + } + rows.addAll(readAll(resultSet)); + } + assertEquals(List.of(0, 100, 200), sorted(rows)); + assertEquals(List.of(0, 1, 2, 3), script.pollIndices()); + } + + // F3. executeQuery returns once the first endpoint exists; it does not wait for later ones. + @Test + public void executeQueryDoesNotWaitForFutureEndpointsWhenTheFirstHasNoRows() throws Exception { + final CountDownLatch gate = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.done(1).gatedBy(gate)).emptyEndpoints(0); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final AtomicReference opened = new AtomicReference<>(); + try (AsyncReader execute = + new AsyncReader( + () -> { + opened.set(statement.executeQuery(script.query())); + return List.of(); + })) { + execute.rows(); + } + try (ResultSet resultSet = opened.get(); + AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + reader.awaitBlocked(); + gate.countDown(); + assertEquals(List.of(100), reader.rows()); + } + } + } + + // F3, held first stream: the first batch is enough; executeQuery does not wait for the stream to + // end or for the continuation. + @Test + public void executeQueryReturnsWhileTheFirstStreamIsHeldAfterItsFirstBatch() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()).holdEnd(0); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final AtomicReference opened = new AtomicReference<>(); + try (AsyncReader execute = + new AsyncReader( + () -> { + opened.set(statement.executeQuery(script.query())); + return List.of(); + })) { + execute.rows(); + } + try (ResultSet resultSet = opened.get()) { + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + } + } + } + + // F4. The fallback path must not report the end while a continuation remains. + @Test + public void prefetchZeroDeliversRowsAfterAnEndpointWithoutRows() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)).emptyEndpoints(1); + try (Connection connection = connect("pollInfoPrefetch=0"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertEquals(List.of(0, 200), readAll(resultSet)); + } + assertEquals(List.of(0, 1, 2), script.pollIndices()); + } + + // F5. A cancel that races a poll in flight reports "Statement canceled", not a poll failure. + @Test + public void cancelRacingAPollInFlightReportsStatementCanceled() throws Exception { + // The server holds its CancelFlightInfo answer, so Statement.cancel() is still inside + // operation.cancel() (before ResultSet.cancel() raises its flag) when the poll ends. + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.hang()).holdCancelFlightInfo(); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet)); + AsyncReader canceller = + new AsyncReader( + () -> { + statement.cancel(); + return List.of(); + }, + false)) { + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + reader.awaitBlocked(); + canceller.start(); + final SQLException failure = reader.failure(); + assertTrue(failure.getMessage().contains("Statement canceled"), failure.getMessage()); + script.releaseCancelFlightInfo(); + canceller.rows(); + } finally { + script.releaseCancelFlightInfo(); + } + } + } + // ---- helpers ---------------------------------------------------------------------------- private static ScriptedPollQuery scripted(final Answer... answers) { @@ -530,11 +703,16 @@ private static ScriptedPollQuery scripted(final Answer... answers) { // threadPoolSize=4: a stream held open must not starve the readers of the other streams, which // share one pool per connection (its default size is 1). private static Connection connect(final String properties) throws SQLException { + return connect(4, properties); + } + + private static Connection connect(final int threadPoolSize, final String properties) + throws SQLException { return DriverManager.getConnection( String.format( "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=true" - + "&threadPoolSize=4&%s", - server.getPort(), properties)); + + "&threadPoolSize=%d&%s", + server.getPort(), threadPoolSize, properties)); } private static List readAll(final ResultSet resultSet) throws SQLException { @@ -606,6 +784,11 @@ private static final class AsyncReader implements AutoCloseable { private final Thread thread; AsyncReader(final Callable call) { + this(call, true); + } + + /** With {@code start} false, the thread runs only once {@link #start()} is called. */ + AsyncReader(final Callable call, final boolean start) { thread = new Thread( () -> { @@ -618,6 +801,12 @@ private static final class AsyncReader implements AutoCloseable { }, "poll-ahead-test-reader"); thread.setDaemon(true); + if (start) { + thread.start(); + } + } + + void start() { thread.start(); } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java index 140919db15..968d879591 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -59,6 +59,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** Executable POC coverage for synchronous PollInfo through the unchanged JDBC surface. */ public class PollInfoExecutionTest { @@ -232,15 +234,27 @@ public void unavailableDoesNotFallbackOrReexecute() throws Exception { assertEquals(0, producer.getFlightInfoCount()); } - @Test - public void continuationUnimplementedDoesNotFallbackOrReexecute() throws Exception { + @ParameterizedTest + @ValueSource(ints = {0, 2}) + public void continuationUnimplementedDoesNotFallbackOrReexecute(final int pollInfoPrefetch) + throws Exception { producer.configure(Scenario.CONTINUATION_UNIMPLEMENTED, STATEMENT_FAMILY); - try (Connection connection = connect(true); + try (Connection connection = connect(true, pollInfoPrefetch); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { - assertTrue(resultSet.next()); - assertEquals(42, resultSet.getInt(1)); - final Throwable failure = assertThrows(Throwable.class, resultSet::next); + if (pollInfoPrefetch == 0) { + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + } + // With poll-ahead the failed continuation fails fast, so it may surface before the first row. + final Throwable failure = + assertThrows( + Throwable.class, + () -> { + while (resultSet.next()) { + assertEquals(42, resultSet.getInt(1)); + } + }); assertTrue(hasFlightStatus(failure, FlightStatusCode.UNIMPLEMENTED), failure.toString()); } assertEquals(2, producer.pollDescriptors().size()); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java index 768e464849..e156ab5905 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java @@ -364,6 +364,101 @@ public void anUnexpectedOpenFailureIsWrappedInAPlainSqlException() throws Except } } + // F2. An Error from the opener used to leave the reservations held. + @Test + public void anErrorFromTheOpenerReleasesTheReservations() throws Exception { + final AssertionError error = new AssertionError("scripted"); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + throw error; + })) { + assertSame( + error, assertThrows(AssertionError.class, () -> queue.addEndpoints(endpoints(2), true))); + assertEquals(0, queue.openUnreadCount()); + assertEquals(0, queue.unreadCount()); + } + } + + // F7. Nothing is queued or opened after a failure. + @Test + public void addEndpointsAfterAFailureOpensNothing() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + final SQLException cause = new SQLException("continuation failed"); + queue.fail(cause); + queue.addEndpoints(endpoints(2), true); + assertEquals(List.of(), opened); + assertEquals(0, queue.unreadCount()); + assertSame(cause, assertThrows(SQLException.class, queue::next)); + } + } + + @Test + public void failureWhileOpeningStopsOpeningTheRestOfTheBatch() throws Exception { + final AtomicReference queueRef = new AtomicReference<>(); + final SQLException cause = new SQLException("continuation failed"); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 3, + endpoint -> { + final CloseableEndpointStreamPair stream = recordingOpener().open(endpoint); + queueRef.get().fail(cause); + return stream; + })) { + queueRef.set(queue); + queue.addEndpoints(endpoints(3), true); + assertEquals(List.of(fake(0)), opened); + assertEquals(0, queue.openUnreadCount()); + assertSame(cause, queue.failure()); + } + } + + // F1. The application finishing an endpoint frees its slot at once, with no reader task. + @Test + public void endpointExhaustedFreesTheSlotOnTheCallingThread() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + final AtomicInteger resumes = new AtomicInteger(); + queue.setResumeAction(resumes::incrementAndGet); + queue.addEndpoints(endpoints(3), true); + assertTrue(queue.pauseIfFull(() -> {})); + fake(0).ready(); + final CloseableEndpointStreamPair first = queue.next(); + assertSame(fake(0).pair, first); + assertEquals(List.of(fake(0), fake(1)), opened); + + queue.endpointExhausted(first); + + // All of it happened before the call returned: the stream closed and the pending endpoint + // opened. The limit is full again, so the poller stays paused. + verify(fake(0).pair).close(); + assertEquals(List.of(fake(0), fake(1), fake(2)), opened); + assertEquals(2, queue.openUnreadCount()); + assertEquals(0, resumes.get()); + + fake(1).ready(); + final CloseableEndpointStreamPair second = queue.next(); + assertSame(fake(1).pair, second); + queue.endpointExhausted(second); + assertEquals(1, queue.openUnreadCount()); + assertEquals(1, resumes.get()); + } + } + + // F3. The first load waits for queued endpoints only, never for endpoints not published yet. + @Test + public void nextAvailableDoesNotWaitForEndpointsThatWereNotPublished() throws Exception { + try (FlightEndpointDataQueue queue = queue(2)) { + queue.addEndpoints(emptyEndpoints(1), true); + // The one queued endpoint ends without a row; more may arrive, but nextAvailable() returns. + final Waiter reader = new Waiter(queue::nextAvailable); + assertNull(reader.value()); + assertTrue(queue.isMoreExpected()); + } + } + @Test public void closeWakesAReaderWaitingForMoreEndpoints() throws Exception { final FlightEndpointDataQueue queue = queue(2); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java index 840286e7c4..a2a8952525 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java @@ -22,8 +22,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @@ -77,6 +79,7 @@ public enum EventType { POLL, POLL_CANCELLED, DOGET_START, + BATCH_SENT, DOGET_END, DOGET_CANCELLED, CANCEL_FLIGHT_INFO @@ -179,6 +182,8 @@ public Answer gatedBy(final CountDownLatch gate) { private final List events = new ArrayList<>(); private final Map startGates = new HashMap<>(); private final Map endGates = new HashMap<>(); + private final Set emptyEndpoints = new HashSet<>(); + private volatile CountDownLatch cancelFlightInfoGate; private final CountDownLatch blockedPoll = new CountDownLatch(1); private final CountDownLatch pollTerminated = new CountDownLatch(1); private int openStreams; @@ -204,6 +209,29 @@ public ScriptedPollQuery rowsPerEndpoint(final int rows) { return this; } + /** The listed endpoints stream a single batch with no rows, then complete. */ + public ScriptedPollQuery emptyEndpoints(final int... ids) { + synchronized (this) { + for (final int id : ids) { + emptyEndpoints.add(id); + } + } + return this; + } + + /** Makes the server hold its CancelFlightInfo answer until {@link #releaseCancelFlightInfo()}. */ + public ScriptedPollQuery holdCancelFlightInfo() { + cancelFlightInfoGate = new CountDownLatch(1); + return this; + } + + public void releaseCancelFlightInfo() { + final CountDownLatch gate = cancelFlightInfoGate; + if (gate != null) { + gate.countDown(); + } + } + // ---- hold and release ------------------------------------------------------------------- /** Holds the listed streams before they send anything. */ @@ -415,6 +443,14 @@ boolean matches(final FlightDescriptor candidate) { void recordCancelFlightInfo() { record(EventType.CANCEL_FLIGHT_INFO, 0); + final CountDownLatch gate = cancelFlightInfoGate; + if (gate != null) { + try { + gate.await(10, TimeUnit.SECONDS); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + } + } } private FlightDescriptor continuation(final int index) { @@ -516,6 +552,7 @@ void doGet(final Ticket ticket, final ServerStreamListener listener) { return; } sendBatch(id, listener); + record(EventType.BATCH_SENT, id); if (!awaitStreamGate(endGates, id, listener)) { return; } @@ -559,11 +596,16 @@ private void sendBatch(final int id, final ServerStreamListener listener) { VectorSchemaRoot root = VectorSchemaRoot.create(SCHEMA, allocator)) { root.allocateNew(); final IntVector vector = (IntVector) root.getVector("answer"); - for (int row = 0; row < rowsPerEndpoint; row++) { + final boolean empty; + synchronized (this) { + empty = emptyEndpoints.contains(id); + } + final int rows = empty ? 0 : rowsPerEndpoint; + for (int row = 0; row < rows; row++) { vector.setSafe(row, id * 100 + row); } - root.setRowCount(rowsPerEndpoint); listener.start(root); + root.setRowCount(rows); listener.putNext(); } } From 704ae1ae4fd80511078ea3ec412ea9749c3770f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 02:42:20 +0000 Subject: [PATCH 30/39] BDX-645: make the shared-server tests fork-safe and deterministic - Serialize the shared-server classes with a cross-JVM file lock held from @BeforeAll to @AfterAll (Surefire runs several forks against one server); reset in @AfterAll and wait for do_get_active == 0 before every reset. - Pin the tests that assert POC-order requests or the POC cancel exception (t2, t9) to pollInfoPrefetch=0. - Late failure now surfaces from next(): the failing continuation is held with /hold-poll and released after the streams are open. - Cancel with a poll open uses burst + /hold-poll 2, so endpoints are readable while the poll is open. - Exact failure assertions (class, message, FlightRuntimeException cause), exactly one CancelFlightInfo, a wider cap margin for the backoff gaps. - New: closing an unfinished result with a poll open, and with the poller paused at the limit, sends one CancelFlightInfo and polls no more. - Declare jackson-databind (test scope, version managed by the Jackson BOM) so dependency:analyze accepts the JSON parsing in the shared-server test. Co-Authored-By: Claude Opus 5.5 --- flight/flight-sql-jdbc-core/pom.xml | 6 + .../arrow/driver/jdbc/SharedServerLock.java | 90 +++++++ .../jdbc/SharedServerPollAheadTest.java | 224 ++++++++++++------ .../SharedServerPollInfoExecutionTest.java | 55 ++++- 4 files changed, 305 insertions(+), 70 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java diff --git a/flight/flight-sql-jdbc-core/pom.xml b/flight/flight-sql-jdbc-core/pom.xml index f2a2d08816..f5abf537fb 100644 --- a/flight/flight-sql-jdbc-core/pom.xml +++ b/flight/flight-sql-jdbc-core/pom.xml @@ -94,6 +94,12 @@ under the License. protobuf-java + + com.fasterxml.jackson.core + jackson-databind + test + + org.hamcrest hamcrest diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java new file mode 100644 index 0000000000..3165b8949c --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerLock.java @@ -0,0 +1,90 @@ +/* + * 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.arrow.driver.jdbc; + +import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + +/** + * A cross-JVM lock that serializes the test classes sharing the one standalone conformance server. + * + *

    The root POM runs Surefire with several reused forks, and every shared-server class resets the + * server and asserts its global counters, so two classes running in two forks would corrupt each + * other. A class takes the lock in {@code @BeforeAll} and releases it in {@code @AfterAll}. The + * lock file lives in {@code java.io.tmpdir} (Surefire points it at {@code target/}), named after + * the control port, so every fork of one build agrees on it. + */ +final class SharedServerLock implements AutoCloseable { + private static final long TIMEOUT_MINUTES = 10; + private static final long RETRY_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(50); + + private final FileChannel channel; + private final FileLock lock; + + private SharedServerLock(final FileChannel channel, final FileLock lock) { + this.channel = channel; + this.lock = lock; + } + + /** Blocks until no other class, in this JVM or another, holds the lock for {@code port}. */ + static SharedServerLock acquire(final int controlPort) throws IOException { + final Path file = + Paths.get(System.getProperty("java.io.tmpdir"), "pollinfo-shared-server-" + controlPort) + .toAbsolutePath(); + Files.createDirectories(file.getParent()); + final FileChannel channel = + FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.WRITE); + final long deadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(TIMEOUT_MINUTES); + try { + while (true) { + try { + final FileLock lock = channel.tryLock(); + if (lock != null) { + return new SharedServerLock(channel, lock); + } + } catch (final OverlappingFileLockException e) { + // Held by another class of this JVM: wait like for another process. + } + if (System.nanoTime() > deadline) { + throw new IOException( + "Timed out waiting for the shared conformance server lock: " + file); + } + LockSupport.parkNanos(RETRY_PARK_NANOS); + } + } catch (final IOException | RuntimeException e) { + channel.close(); + throw e; + } + } + + @Override + public void close() throws IOException { + try { + lock.release(); + } finally { + channel.close(); + } + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java index bebea15b89..66a83f228e 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java @@ -38,8 +38,8 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collections; +import java.util.HashSet; import java.util.List; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -47,7 +47,11 @@ import java.util.function.BooleanSupplier; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.apache.arrow.flight.FlightRuntimeException; +import org.apache.arrow.flight.FlightStatusCode; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; @@ -60,7 +64,11 @@ * *

    Enable with {@code -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=... * -Dpollinfo.shared.controlPort=...}. Connections use {@code threadPoolSize=4}: the reader pool - * defaults to 1, and a held stream would starve the others. + * defaults to 1, and a held stream would starve the others (and the default prefetch is then 4). + * + *

    Every shared-server class resets the server and asserts its global counters, so two of them + * must never run at once. Surefire runs several forks, hence each class holds the cross-JVM {@link + * SharedServerLock} from {@code @BeforeAll} to {@code @AfterAll} and leaves the server reset. */ @EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") public class SharedServerPollAheadTest { @@ -73,8 +81,25 @@ public class SharedServerPollAheadTest { private static final Duration QUIET = Duration.ofMillis(400); private static final String CONTINUATION = "continuation"; + private static SharedServerLock serverLock; + private ExecutorService background; + @BeforeAll + public static void lockServer() throws Exception { + serverLock = SharedServerLock.acquire(CONTROL_PORT); + } + + @AfterAll + public static void resetAndUnlockServer() throws Exception { + try { + awaitUntil("no open streams before reset", () -> counter("do_get_active") == 0); + post("/reset", ""); + } finally { + serverLock.close(); + } + } + @BeforeEach public void resetServer() throws Exception { background = @@ -202,7 +227,7 @@ public void trickleStopsPollingAtTheLimitAndResumesAfterTheStreamsAreReleased() @Test public void emptyAnswersBackOffExponentiallyUpToTheCap() throws Exception { final List rows; - try (Connection connection = connect(true, "pollInfoMaxBackoffMs=300"); + try (Connection connection = connect(true, "pollInfoMaxBackoffMs=250"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("empty-answers")) { rows = values(resultSet, "empty-answers"); @@ -215,69 +240,139 @@ public void emptyAnswersBackOffExponentiallyUpToTheCap() throws Exception { final long gap3 = gapMillis(polls.get(2), polls.get(3)); System.out.printf("SHARED_BACKOFF_GAPS_MILLIS %d %d %d%n", gap1, gap2, gap3); // Lower bounds are the configured delays (with a little slack); the upper bounds are generous, - // except that the third gap must show the cap: 400 ms uncapped, 300 ms capped. + // except that the third gap must show the cap: 400 ms uncapped, 250 ms capped, so 350 ms + // leaves 100 ms of headroom above the cap and 50 ms below the uncapped wait. assertTrue(gap1 >= 90 && gap1 < 1000, "gap1=" + gap1); assertTrue(gap2 >= 180 && gap2 < 1000, "gap2=" + gap2); - assertTrue(gap3 >= 270 && gap3 < 390, "gap3=" + gap3); + assertTrue(gap3 >= 225 && gap3 < 350, "gap3=" + gap3); } @Test - public void lateFailureCancelsTheBufferedStreamsAndDeliversNoRows() throws Exception { + public void lateFailureCancelsTheBufferedStreamsAndSurfacesFromNext() throws Exception { post("/hold", "{\"endpoint\":1}"); post("/hold", "{\"endpoint\":2}"); + // The failing poll (the second continuation) is held, so the failure cannot be recorded + // before executeQuery returns: it must surface from next(). + holdPoll(2); try (Connection connection = connect(true, ""); Statement statement = connection.createStatement()) { final Future execution = executeAsync(statement, "late-error-buffered"); - awaitUntil("C2 polled", () -> continuationPolls().size() >= 2); - // The failure cancels every buffered stream by itself, before anything is read or closed. - awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); - awaitUntil("streams ended", () -> counter("do_get_active") == 0); - // E1 is held, so the first read may still be pending when the poller records the failure. - // The failure then surfaces from executeQuery; otherwise from the first next(). Either way - // it is the same exception and no row is delivered. - final SQLException failure; - final ResultSet resultSet = awaitResultOrFailure(execution); - if (resultSet == null) { - failure = executionFailure(execution); - } else { - try (ResultSet toClose = resultSet) { - failure = assertThrows(SQLException.class, toClose::next); - assertThrows(SQLException.class, toClose::next); - } + try (ResultSet resultSet = result(execution)) { + awaitUntil("E1 held", () -> hasHold(1, "held")); + awaitUntil("E2 held", () -> hasHold(2, "held")); + awaitUntil("C2 held", () -> hasPollHold(2, "held")); + releasePoll(2); + // The failure cancels every buffered stream by itself, before anything is read or closed. + awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + awaitUntil("E2 cancelled", () -> hasEnd(2, "cancelled")); + + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertContinuationFailure(failure); + // The failure is sticky, and no row is delivered. + assertContinuationFailure(assertThrows(SQLException.class, resultSet::next)); } - assertEquals("Continuation PollFlightInfo failed", failureWithMessage(failure)); } awaitUntil("streams ended", () -> counter("do_get_active") == 0); final List ends = events("DoGet.end"); assertTrue( ends.stream().noneMatch(event -> "completed".equals(event.path("outcome").asText())), "no stream may complete: " + state()); - // E2 was either cancelled or never started; it never sent a row. - assertTrue( - ends.stream() - .filter(event -> event.path("endpoint").asInt() == 2) - .allMatch(event -> "cancelled".equals(event.path("outcome").asText())), - state()); + assertFalse(hasHold(1, "released"), state()); assertFalse(hasHold(2, "released"), state()); + assertTrue(hasPollHold(2, "released"), state()); assertEquals(2, continuationPolls().size(), state()); // The server already ended the query, so the driver sends no CancelFlightInfo. assertEquals(0, counter("cancellation"), state()); } + // The driver's own failure for a continuation the server failed: the exact class, the message, + // and the server's status as the cause. + private static void assertContinuationFailure(final SQLException failure) { + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertTrue(failure.getCause() instanceof FlightRuntimeException, failure.toString()); + final FlightRuntimeException cause = (FlightRuntimeException) failure.getCause(); + assertEquals(FlightStatusCode.INTERNAL, cause.status().code()); + assertTrue( + String.valueOf(cause.status().description()).contains("deterministic late query failure"), + cause.toString()); + } + @Test public void cancelWhileAPollIsOpenSendsNoMorePollsAndOneCancelFlightInfo() throws Exception { - try (Connection connection = connect(true, ""); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery("cancel-observable")) { - awaitUntil("C1 poll blocked on the server", () -> continuationPolls().size() >= 1); - statement.cancel(); - final SQLException canceled = assertThrows(SQLException.class, resultSet::next); - assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + // burst: [E1]+C1, then [E1..E4]+C2; the poll of C2 is held, so four endpoints are readable + // while a poll is open. A prefetch above 4 keeps the poller polling. + holdPoll(2); + try (Connection connection = connect(true, "pollInfoPrefetch=8"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + awaitUntil("C2 poll held", () -> hasPollHold(2, "held")); + final List rows = new ArrayList<>(); + for (int row = 0; row < 4; row++) { + assertTrue(resultSet.next()); + rows.add(resultSet.getLong("value")); + } + assertEquals(4, new HashSet<>(rows).size(), "rows were read twice: " + rows); + assertTrue(range(1, 8).containsAll(rows), rows.toString()); + + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + awaitUntil("the open poll ended", () -> hasPollHoldEnded(2)); + } + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the cancel", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 3); + assertEquals(2, continuationPolls().size(), state()); + assertFalse(hasPollHold(2, "released"), state()); + } + + @Test + public void closingAnUnfinishedResultWhileAPollIsOpenCancelsOnceAndPollsNoMore() + throws Exception { + holdPoll(2); + try (Connection connection = connect(true, "pollInfoPrefetch=8"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + awaitUntil("C2 poll held", () -> hasPollHold(2, "held")); + assertTrue(resultSet.next()); + } awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + awaitUntil("the open poll ended", () -> hasPollHoldEnded(2)); } - assertEquals(1, counter("cancellation"), state()); + // The statement and the connection are closed now; none of it may cancel or poll again. + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the close", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 3); + assertEquals(2, continuationPolls().size(), state()); + assertFalse(hasPollHold(2, "released"), state()); + } + + @Test + public void closingAnUnfinishedResultWhilePollingIsPausedCancelsOnceAndPollsNoMore() + throws Exception { + try (Connection connection = connect(true, "pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + final Future execution = executeAsync(statement, "burst"); + try (ResultSet resultSet = result(execution)) { + // E1..E4 are queued and unread, which is above the limit: the poller pauses before C2. + awaitUntil("C1 polled", () -> continuationPolls().size() >= 1); + assertQuiet("polled past the limit", () -> continuationPolls().size() == 1); + assertTrue(resultSet.next()); + } + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); + } + awaitUntil("streams ended", () -> counter("do_get_active") == 0); + assertQuiet( + "a poll or a cancel after the close", + () -> counter("cancellation") == 1 && counter("poll_flight_info") == 2); assertEquals(1, continuationPolls().size(), state()); - assertEquals(2, counter("poll_flight_info"), state()); } @Test @@ -296,11 +391,12 @@ public void cancelWhileAStreamIsHeldCancelsItAndPollsNoMore() throws Exception { final SQLException canceled = assertThrows(SQLException.class, resultSet::next); assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); awaitUntil("E1 cancelled", () -> hasEnd(1, "cancelled")); + awaitUntil("CancelFlightInfo", () -> counter("cancellation") >= 1); } awaitUntil("streams ended", () -> counter("do_get_active") == 0); } assertEquals(2, counter("poll_flight_info"), state()); - assertTrue(counter("cancellation") <= 1, state()); + assertEquals(1, counter("cancellation"), state()); // The held stream was cancelled, never completed. assertFalse(hasEnd(1, "completed"), state()); } @@ -364,34 +460,6 @@ private Future executeAsync(final Statement statement, final String q return background.submit(() -> statement.executeQuery(query)); } - // Null if executeQuery failed; its exception is then available from executionFailure. - private static ResultSet awaitResultOrFailure(final Future execution) - throws Exception { - try { - return result(execution); - } catch (ExecutionException e) { - return null; - } - } - - private static SQLException executionFailure(final Future execution) throws Exception { - final ExecutionException e = assertThrows(ExecutionException.class, execution::get); - assertTrue(e.getCause() instanceof SQLException, e.toString()); - return (SQLException) e.getCause(); - } - - // The message of the first exception in the cause chain that is the driver's own failure. - private static String failureWithMessage(final Throwable failure) { - Throwable current = failure; - while (current != null) { - if ("Continuation PollFlightInfo failed".equals(current.getMessage())) { - return current.getMessage(); - } - current = current.getCause(); - } - return failure.getMessage(); - } - private static ResultSet result(final Future execution) throws Exception { final ResultSet resultSet = execution.get(WAIT.toSeconds(), TimeUnit.SECONDS); assertNotNull(resultSet); @@ -468,6 +536,28 @@ private static boolean hasHold(final int endpoint, final String outcome) { && outcome.equals(event.path("outcome").asText())); } + private static void holdPoll(final int continuation) { + post("/hold-poll", "{\"continuation\":" + continuation + "}"); + } + + private static void releasePoll(final int continuation) { + post("/release-poll", "{\"continuation\":" + continuation + "}"); + } + + private static boolean hasPollHold(final int continuation, final String outcome) { + return events("PollFlightInfo.hold").stream() + .anyMatch( + event -> + event.path(CONTINUATION).asInt() == continuation + && outcome.equals(event.path("outcome").asText())); + } + + // A held poll ended by the client: CancelFlightInfo, or the cancelled call (context). + private static boolean hasPollHoldEnded(final int continuation) { + return hasPollHold(continuation, "cancel-terminated") + || hasPollHold(continuation, "context-terminated"); + } + private static boolean hasEnd(final int endpoint, final String outcome) { return events("DoGet.end").stream() .anyMatch( diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java index b6e0408a8a..6304165aa7 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -43,7 +43,9 @@ import java.util.regex.Pattern; import org.apache.arrow.flight.FlightRuntimeException; import org.apache.arrow.flight.FlightStatusCode; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; @@ -52,7 +54,14 @@ import org.junit.jupiter.api.TestMethodOrder; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; -/** Black-box BDX-645 contract checks against the standalone shared conformance server. */ +/** + * Black-box BDX-645 contract checks against the standalone shared conformance server. + * + *

    Enable with {@code -Dpollinfo.shared.enabled=true}. Every shared-server class resets the + * server and asserts its global counters, so two of them must never run at once. Surefire runs + * several forks, hence each class holds the cross-JVM {@link SharedServerLock} from + * {@code @BeforeAll} to {@code @AfterAll} and leaves the server reset. + */ @EnabledIfSystemProperty(named = "pollinfo.shared.enabled", matches = "true") @TestMethodOrder(OrderAnnotation.class) public class SharedServerPollInfoExecutionTest { @@ -60,8 +69,31 @@ public class SharedServerPollInfoExecutionTest { private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); + private static SharedServerLock serverLock; + + @BeforeAll + public static void lockServer() throws Exception { + serverLock = SharedServerLock.acquire(CONTROL_PORT); + } + + @AfterAll + public static void resetAndUnlockServer() throws Exception { + try { + resetWhenIdle(); + } finally { + serverLock.close(); + } + } + @BeforeEach public void resetServer() throws Exception { + resetWhenIdle(); + } + + // The previous test closed its connections; /reset must not run while the server still has + // streams open. + private static void resetWhenIdle() throws Exception { + awaitCounterEquals("do_get_active", 0, Duration.ofSeconds(10)); post("/reset", ""); } @@ -82,8 +114,10 @@ public void t1Immediate() throws Exception { @Test @Order(2) + // Pinned to the POC path (pollInfoPrefetch=0): the DoGet-before-first-continuation order below is + // the POC request order; poll-ahead polls the continuations in the background. public void t2MultiStepContinuationsAndFinalCumulativeInfo() throws Exception { - try (Connection connection = connect(true)) { + try (Connection connection = connect(true, "pollInfoPrefetch=0")) { assertEquals(Arrays.asList(1L, 2L, 3L), directValues(connection, "multi-step")); } final String state = state(); @@ -202,8 +236,11 @@ public void t8TimeoutEndsBlockedPollAtTheSingleStatementDeadline() throws Except @Test @Order(10) + // Pinned to the POC path (pollInfoPrefetch=0): the cancel surfaces as the CANCELLED + // FlightRuntimeException of the reader's own poll. With poll-ahead it is "Statement canceled" + // (SharedServerPollAheadTest). public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { - try (Connection connection = connect(true); + try (Connection connection = connect(true, "pollInfoPrefetch=0"); Statement statement = connection.createStatement()) { final AtomicReference failure = new AtomicReference<>(); final AtomicBoolean resultSetCreated = new AtomicBoolean(); @@ -336,6 +373,18 @@ private static void awaitCounter(final String name, final int expected, final Du assertEquals(expected, counter(state(), name), state()); } + private static void awaitCounterEquals( + final String name, final int expected, final Duration timeout) throws Exception { + final long deadline = System.nanoTime() + timeout.toNanos(); + do { + if (counter(state(), name) == expected) { + return; + } + Thread.sleep(20); + } while (System.nanoTime() < deadline); + assertEquals(expected, counter(state(), name), state()); + } + private static int counter(final String state, final String name) { final Matcher matcher = Pattern.compile("\\\"" + Pattern.quote(name) + "\\\"\\s*:\\s*(\\d+)").matcher(state); From 3158822e4ef7892212b381df01611ddb1b0f1677 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 02:42:32 +0000 Subject: [PATCH 31/39] BDX-645: fix the poll-ahead unit-test review findings - Gate fail() and schemaChange() so the first next() cannot race them, and gate the UNIMPLEMENTED continuation of PollInfoExecutionTest: both prefetch variants now assert the exact failure after the first row. - Backoff against cancel, close and the deadline (6 empty answers, cap 5000), on the fallback path (prefetch 0), and a PollBackoff unit test. - Exactly one CancelFlightInfo on the deadline; no zero-wait assertion. - Queue: an opener blocked while fail() or close() runs. - Append-only violations (fewer endpoints, changed ticket) in the scripted server; endpoints with locations; multi-batch and empty leading batches. - Backoff gap assertions: no wait after an answer that adds endpoints, real cap checks; sleep-based waits instead of spin waits. - Pin multi-step on-demand polling to prefetch 0; document the unlimited eager queue (complete first answer, prefetch 0) in the plan. Co-Authored-By: Claude Opus 5.5 --- .../arrow/driver/jdbc/PollAheadTest.java | 269 +++++++++++++++++- .../driver/jdbc/PollInfoExecutionTest.java | 37 ++- .../driver/jdbc/client/PollBackoffTest.java | 72 +++++ ...ightEndpointDataQueueDeferredOpenTest.java | 66 ++++- .../utils/PollingMockFlightSqlProducer.java | 32 +++ .../driver/jdbc/utils/ScriptedPollQuery.java | 89 +++++- reports/poll-ahead-implementation-plan.md | 3 +- 7 files changed, 524 insertions(+), 44 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java index 0a089fae55..174f186e11 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -40,6 +40,8 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; +import java.util.stream.Collectors; import org.apache.arrow.driver.jdbc.utils.PollingMockFlightSqlProducer; import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery; import org.apache.arrow.driver.jdbc.utils.ScriptedPollQuery.Answer; @@ -69,6 +71,7 @@ public class PollAheadTest { private static final long WAIT_MS = 10_000; private static final long QUIET_MS = 300; + private static final long POLL_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(1); private static final AtomicInteger QUERY_NUMBER = new AtomicInteger(); @@ -193,11 +196,15 @@ public void backoffDoublesAndResetsAfterAnAnswerThatAddsEndpoints() throws Excep } final List polls = script.pollNanos(); assertEquals(6, polls.size()); + // An answer that adds endpoints is followed at once: no wait after answers 0 and 3. The + // shortest backoff wait is 100 ms, so anything below that is no wait at all. + assertGapBetween(polls, 0, 1, 0, 100); + assertGapBetween(polls, 3, 4, 0, 100); // Answers 1 and 2 are empty: waits of 100 ms, then 200 ms. assertGapBetween(polls, 1, 2, 100, 1500); assertGapBetween(polls, 2, 3, 200, 1500); - // Answer 3 adds an endpoint: no wait is required, and the next empty answer waits 100 ms - // again, not 400 ms. + // After answer 4 (empty, after an answer that added endpoints) the wait starts at 100 ms + // again, not at 400 ms. assertGapBetween(polls, 4, 5, 100, 350); } @@ -214,9 +221,10 @@ public void backoffIsCappedByPollInfoMaxBackoffMs() throws Exception { } final List polls = script.pollNanos(); assertEquals(5, polls.size()); - // Waits after the three empty answers: 100 ms, then capped at 150 ms (not 200, not 400). - assertGapBetween(polls, 1, 2, 100, 1500); - assertGapBetween(polls, 2, 3, 150, 1500); + // Waits after the three empty answers: 100 ms, then capped at 150 ms. Uncapped they would be + // 100, 200 and 400 ms, so only the last gap tells the cap from no cap. + assertGapBetween(polls, 1, 2, 100, 350); + assertGapBetween(polls, 2, 3, 150, 350); assertGapBetween(polls, 3, 4, 150, 350); } @@ -224,8 +232,10 @@ public void backoffIsCappedByPollInfoMaxBackoffMs() throws Exception { // read, and the buffered streams are cancelled. @Test public void continuationFailureStopsReadsAndClosesStreams() throws Exception { + // The failing answer waits for the test, so that the first next() cannot race it. + final CountDownLatch failNow = new CountDownLatch(1); final ScriptedPollQuery script = - scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.fail()) + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.fail().gatedBy(failNow)) .rowsPerEndpoint(2) .holdEnd(0) .holdStart(1); @@ -234,6 +244,8 @@ public void continuationFailureStopsReadsAndClosesStreams() throws Exception { ResultSet resultSet = statement.executeQuery(script.query())) { assertTrue(resultSet.next()); assertEquals(0, resultSet.getInt(1)); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + failNow.countDown(); // fail() records the failure first and then cancels every open stream. assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 0, WAIT_MS)); assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 1, WAIT_MS)); @@ -294,7 +306,6 @@ public void cancelEndsTheOpenPollAndNextThrows() throws Exception { final SQLException canceled = assertThrows(SQLException.class, resultSet::next); assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); - assertFalse(script.awaitPollCount(3, 0)); } assertEquals(2, script.pollCount()); assertEquals(1, script.cancelFlightInfoCount()); @@ -334,7 +345,9 @@ public void finalEndpointsInTheDoneAnswerAreAllDelivered(final boolean readerWai final int firstRow = resultSet.getInt(1); try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { if (readerWaits) { - // The reader has consumed E0 and now waits for the done answer. + // The reader has consumed E0 (it ended on the server) and now waits for the done answer. + // awaitBlocked cannot tell the queue wait from a read blocked in FlightStream.next(); + // either way, releasing the gate must deliver both final endpoints. assertTrue(script.awaitBlockedPoll(WAIT_MS)); assertTrue(script.awaitStream(EventType.DOGET_END, 0, WAIT_MS)); reader.awaitBlocked(); @@ -498,24 +511,31 @@ public void queryTimeoutEndsAtAReadBoundary(final String property) throws Except assertEquals( FlightStatusCode.TIMED_OUT, ((FlightRuntimeException) timeout.getCause()).status().code()); + // The deadline cancels the operation once; closing the result must not cancel again. + assertTrue( + script.awaitCancelFlightInfo(1, WAIT_MS), "the deadline sent no CancelFlightInfo"); } } final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); assertTrue(elapsedMillis >= 850, "the deadline fired too early: " + elapsedMillis); assertTrue(script.awaitPollTerminated(WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); assertEquals(2, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); } // Decision: a schema change fails the queue as a plain SQLException. @Test public void schemaChangeFailsTheResultAsAPlainSqlException() throws Exception { + final CountDownLatch changeNow = new CountDownLatch(1); final ScriptedPollQuery script = - scripted(Answer.endpoints(1), Answer.schemaChange()).rowsPerEndpoint(2); + scripted(Answer.endpoints(1), Answer.schemaChange().gatedBy(changeNow)).rowsPerEndpoint(2); try (Connection connection = connect("pollInfoPrefetch=2"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(script.query())) { assertTrue(resultSet.next()); - assertTrue(script.awaitPollCount(2, WAIT_MS)); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + changeNow.countDown(); final SQLException failure = assertThrows(SQLException.class, () -> readAllWithin(resultSet)); assertEquals(SQLException.class, failure.getClass()); assertEquals("PollInfo changed the result schema", failure.getMessage()); @@ -694,6 +714,215 @@ public void cancelRacingAPollInFlightReportsStatementCanceled() throws Exception } } + // S2. Backoff against cancel, deadline and close. Six empty answers after the first endpoint: + // the waits are 100, 200, 400, 800 and then 1600 ms (cap 5000 ms), so once poll 5 arrived the + // poller sleeps for another 1.6 s, much longer than anything asserted below. + private static ScriptedPollQuery backingOff() { + return scripted( + Answer.endpoints(1), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty(), + Answer.empty()) + .rowsPerEndpoint(2); + } + + @Test + public void cancelDuringABackoffWaitEndsItAndSendsNoMorePolls() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitPollCount(6, WAIT_MS)); + final long cancelNanos = System.nanoTime(); + statement.cancel(); + final SQLException canceled = assertThrows(SQLException.class, resultSet::next); + assertTrue(canceled.getMessage().contains("Statement canceled"), canceled.getMessage()); + // Cancel ends the wait: the poller leaves its thread long before the 1.6 s are over. + awaitPollerPoolIdle(connection, 1000); + assertTrue( + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - cancelNanos) < 1000, + "the backoff wait outlived the cancel"); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(6, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + @Test + public void closeDuringABackoffWaitReturnsPromptlyAndSendsNoMorePolls() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000")) { + final Statement statement = connection.createStatement(); + final ResultSet resultSet = statement.executeQuery(script.query()); + assertTrue(resultSet.next()); + assertTrue(script.awaitPollCount(6, WAIT_MS)); + final long closeNanos = System.nanoTime(); + resultSet.close(); + statement.close(); + assertTrue( + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - closeNanos) < 1000, + "close waited for the backoff"); + // The close ends the wait itself (it cancels the operation); nothing interrupts the poller. + awaitPollerPoolIdle(connection, 1000); + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS)); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(6, script.pollCount()); + assertEquals(1, script.cancelFlightInfoCount()); + } + + @Test + public void theDeadlineEndsABackoffWaitAndSendsOneCancelFlightInfo() throws Exception { + final ScriptedPollQuery script = backingOff(); + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=5000"); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + final long startNanos = System.nanoTime(); + try (ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(resultSet.next()); + final SQLTimeoutException timeout = + assertThrows(SQLTimeoutException.class, resultSet::next); + final long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos); + assertEquals("Query timed out after 1 SECONDS", timeout.getMessage()); + assertInstanceOf(FlightRuntimeException.class, timeout.getCause()); + assertEquals( + FlightStatusCode.TIMED_OUT, + ((FlightRuntimeException) timeout.getCause()).status().code()); + // The polls are at 0, 0, 100, 300 and 700 ms; the wait after the last one is cut to the + // deadline (1000 ms) instead of 800 ms, so the next poll is not at 1500 ms. + assertTrue(elapsedMillis >= 850, "the deadline fired too early: " + elapsedMillis); + assertTrue(elapsedMillis < 1400, "the wait ran past the deadline: " + elapsedMillis); + assertTrue( + script.awaitCancelFlightInfo(1, WAIT_MS), "the deadline sent no CancelFlightInfo"); + } + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + } + assertEquals(1, script.cancelFlightInfoCount()); + } + + // S3. The fallback path (pollInfoPrefetch=0) backs off inside next() as well. + @Test + public void prefetchZeroBacksOffBetweenEmptyAnswersAndHonorsTheCap() throws Exception { + final ScriptedPollQuery script = + scripted( + Answer.endpoints(1), Answer.empty(), Answer.empty(), Answer.empty(), Answer.done(1)); + try (Connection connection = connect("pollInfoPrefetch=0&pollInfoMaxBackoffMs=150"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertEquals(List.of(0, 100), readAll(resultSet)); + } + final List polls = script.pollNanos(); + assertEquals(5, polls.size()); + // The reader polls C1 once E0 is read; the waits are 100 ms, then capped at 150 ms (uncapped: + // 200 and 400 ms). + assertGapBetween(polls, 1, 2, 100, 350); + assertGapBetween(polls, 2, 3, 150, 350); + assertGapBetween(polls, 3, 4, 150, 350); + } + + // S6. Append-only violations fail the result and cancel the open streams. + @Test + public void anAnswerWithFewerEndpointsFailsTheResultAndCancelsTheStreams() throws Exception { + final CountDownLatch breakNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.shrink().gatedBy(breakNow)) + .rowsPerEndpoint(2) + .holdAllEnds(2); + assertAppendOnlyViolation(script, breakNow, "PollInfo removed previously published endpoints"); + } + + @Test + public void anAnswerWithAChangedTicketFailsTheResultAndCancelsTheStreams() throws Exception { + final CountDownLatch breakNow = new CountDownLatch(1); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.changedTicket().gatedBy(breakNow)) + .rowsPerEndpoint(2) + .holdAllEnds(2); + assertAppendOnlyViolation(script, breakNow, "PollInfo mutated previously published endpoint 0"); + } + + private static void assertAppendOnlyViolation( + final ScriptedPollQuery script, final CountDownLatch breakNow, final String description) + throws Exception { + try (Connection connection = connect("pollInfoPrefetch=4"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitDoGetStarted(2, WAIT_MS)); + breakNow.countDown(); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 0, WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_CANCELLED, 1, WAIT_MS)); + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertInstanceOf(FlightRuntimeException.class, failure.getCause()); + final FlightRuntimeException cause = (FlightRuntimeException) failure.getCause(); + assertEquals(FlightStatusCode.INTERNAL, cause.status().code()); + assertEquals(description, cause.status().description()); + } + assertFalse(script.hasEvent(EventType.DOGET_END, 0)); + assertFalse(script.hasEvent(EventType.DOGET_END, 1)); + } + + // Mock fidelity: endpoints that name a location (the server itself, or "reuse the connection") + // take the single-endpoint open path that resolves locations. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void endpointsWithLocationsAreOpenedAndRead(final boolean reuseConnection) + throws Exception { + final Location location = reuseConnection ? Location.reuseConnection() : server.getLocation(); + final ScriptedPollQuery script = + scripted(Answer.endpoints(2), Answer.empty(), Answer.done(1)) + .endpointLocations(location) + .rowsPerEndpoint(2); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2&pollInfoMaxBackoffMs=20"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + rows = readAll(resultSet); + } + assertEquals(List.of(0, 1, 100, 101, 200, 201), sorted(rows)); + assertEquals(3, script.doGetStarted()); + assertEquals(List.of(0, 1, 2), script.pollIndices()); + } + + // Mock fidelity: streams with several batches and an empty batch in front of the data. The next + // batch of an endpoint must not free its slot; the end of its stream must. + @Test + public void multiBatchStreamsWithAnEmptyLeadingBatchAreReadInOrder() throws Exception { + final ScriptedPollQuery script = + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)) + .rowsPerEndpoint(2) + .batchesPerEndpoint(3) + .leadingEmptyBatch(); + final List rows; + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(script.query())) { + rows = readAll(resultSet); + } + assertEquals( + List.of(0, 1, 2, 3, 4, 5, 100, 101, 102, 103, 104, 105, 200, 201, 202, 203, 204, 205), + sorted(rows)); + for (int endpoint = 0; endpoint < 3; endpoint++) { + final int first = endpoint * 100; + assertEquals( + List.of(first, first + 1, first + 2, first + 3, first + 4, first + 5), + rows.stream().filter(row -> row / 100 == first / 100).collect(Collectors.toList()), + "the batches of endpoint " + endpoint + " arrived out of order"); + } + assertEquals(List.of(0, 1, 2), script.pollIndices()); + assertTrue(script.maxOpenStreams() <= 2); + } + // ---- helpers ---------------------------------------------------------------------------- private static ScriptedPollQuery scripted(final Answer... answers) { @@ -769,12 +998,18 @@ private static void assertGapBetween( } private static void awaitPollerPoolIdle(final Connection connection) throws Exception { + awaitPollerPoolIdle(connection, WAIT_MS); + } + + private static void awaitPollerPoolIdle(final Connection connection, final long millis) + throws Exception { final ThreadPoolExecutor pool = connection.unwrap(ArrowFlightConnection.class).getPollerExecutor(); - final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); + final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis); while (pool.getActiveCount() > 0) { - assertTrue(System.nanoTime() < deadline, "the poller pool never became idle"); - Thread.onSpinWait(); + assertTrue( + System.nanoTime() < deadline, "the poller pool was not idle within " + millis + " ms"); + LockSupport.parkNanos(POLL_PARK_NANOS); } } @@ -815,14 +1050,18 @@ private static List castList(final Object value) { return (List) value; } - /** Waits until the thread is parked, i.e. blocked inside the driver. */ + /** + * Waits until the thread is parked, i.e. blocked inside the driver. It cannot tell the cause: a + * reader blocked in {@code FlightStream.next()} looks the same as one waiting in the queue. + * Tests that need one of the two pin it with server state (held or gated streams and polls). + */ void awaitBlocked() throws InterruptedException { final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); while (thread.getState() != Thread.State.WAITING && thread.getState() != Thread.State.TIMED_WAITING) { assertTrue(System.nanoTime() < deadline, "the reader never blocked"); assertFalse(result.isDone(), "the reader finished instead of blocking"); - Thread.onSpinWait(); + LockSupport.parkNanos(POLL_PARK_NANOS); } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java index 968d879591..76a6f98dfd 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -29,6 +29,7 @@ import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; import java.util.Collections; @@ -123,9 +124,11 @@ public void immediateCompletionUsesOnePollAndNoGetFlightInfo() throws Exception } @Test + // Pinned to the POC path (pollInfoPrefetch=0): the continuations are polled on demand, which + // is what the name says. Poll-ahead is covered by pollAheadPollsContinuationsWhile... public void multiStepPollsOnDemandAfterPublishedEndpointIsConsumed() throws Exception { producer.configure(Scenario.MULTI_STEP, STATEMENT_FAMILY); - try (Connection connection = connect(true); + try (Connection connection = connect(true, 0); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { assertTrue(resultSet.next()); @@ -239,23 +242,29 @@ public void unavailableDoesNotFallbackOrReexecute() throws Exception { public void continuationUnimplementedDoesNotFallbackOrReexecute(final int pollInfoPrefetch) throws Exception { producer.configure(Scenario.CONTINUATION_UNIMPLEMENTED, STATEMENT_FAMILY); + if (pollInfoPrefetch > 0) { + // The background poller would otherwise fail before or after the first next(); the failing + // answer waits until the first row was read. + producer.holdContinuationFailure(); + } try (Connection connection = connect(true, pollInfoPrefetch); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { - if (pollInfoPrefetch == 0) { - assertTrue(resultSet.next()); - assertEquals(42, resultSet.getInt(1)); + assertTrue(resultSet.next()); + assertEquals(42, resultSet.getInt(1)); + if (pollInfoPrefetch > 0) { + assertTrue(producer.awaitActivePoll(5, TimeUnit.SECONDS), "the poller never polled C1"); + producer.releaseContinuationFailure(); } - // With poll-ahead the failed continuation fails fast, so it may surface before the first row. - final Throwable failure = - assertThrows( - Throwable.class, - () -> { - while (resultSet.next()) { - assertEquals(42, resultSet.getInt(1)); - } - }); - assertTrue(hasFlightStatus(failure, FlightStatusCode.UNIMPLEMENTED), failure.toString()); + final SQLException failure = assertThrows(SQLException.class, resultSet::next); + assertEquals(SQLException.class, failure.getClass()); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); + assertTrue(failure.getCause() instanceof FlightRuntimeException, failure.toString()); + assertEquals( + FlightStatusCode.UNIMPLEMENTED, + ((FlightRuntimeException) failure.getCause()).status().code()); + } finally { + producer.releaseContinuationFailure(); } assertEquals(2, producer.pollDescriptors().size()); assertEquals(0, producer.getFlightInfoCount()); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java new file mode 100644 index 0000000000..399ec71b50 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/PollBackoffTest.java @@ -0,0 +1,72 @@ +/* + * 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.arrow.driver.jdbc.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class PollBackoffTest { + private static List delays(final PollBackoff backoff, final int count) { + final List delays = new ArrayList<>(); + for (int i = 0; i < count; i++) { + delays.add(backoff.nextDelayMillis()); + } + return delays; + } + + @Test + public void doublesFromOneHundredMillisecondsUpToTheCap() { + assertEquals( + List.of(100L, 200L, 400L, 800L, 1600L, 3200L, 5000L, 5000L), + delays(new PollBackoff(PollBackoff.DEFAULT_MAX_MILLIS), 8)); + } + + @Test + public void capBetweenTwoStepsCutsTheLaterStepAndStaysThere() { + assertEquals(List.of(100L, 150L, 150L, 150L), delays(new PollBackoff(150), 4)); + } + + @Test + public void capBelowTheInitialDelayIsTheOnlyDelay() { + assertEquals(List.of(50L, 50L, 50L), delays(new PollBackoff(50), 3)); + } + + @Test + public void capBelowOneMillisecondIsRaisedToOne() { + assertEquals(List.of(1L, 1L), delays(new PollBackoff(0), 2)); + assertEquals(List.of(1L, 1L), delays(new PollBackoff(-5), 2)); + } + + @Test + public void resetStartsAgainFromTheInitialDelay() { + final PollBackoff backoff = new PollBackoff(5000); + assertEquals(List.of(100L, 200L, 400L), delays(backoff, 3)); + backoff.reset(); + assertEquals(List.of(100L, 200L), delays(backoff, 2)); + } + + @Test + public void resetAfterReachingTheCapStartsAgainFromTheInitialDelay() { + final PollBackoff backoff = new PollBackoff(300); + assertEquals(List.of(100L, 200L, 300L, 300L), delays(backoff, 4)); + backoff.reset(); + assertEquals(List.of(100L, 200L, 300L), delays(backoff, 3)); + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java index e156ab5905..7234d0405c 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueDeferredOpenTest.java @@ -48,6 +48,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.FlightEndpoint; @@ -58,6 +59,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Tests the progressive-results side of {@link FlightEndpointDataQueue}: deferred stream opening, @@ -70,6 +73,7 @@ @Timeout(60) public class FlightEndpointDataQueueDeferredOpenTest { private static final long WAIT_MS = 10_000; + private static final long POLL_PARK_NANOS = TimeUnit.MILLISECONDS.toNanos(1); private ExecutorService readers; private final List opened = new CopyOnWriteArrayList<>(); @@ -510,7 +514,7 @@ public void pauseIfFullPausesOnlyAtTheLimitAndTheReaderResumesIt() throws Except final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); while (resumes.get() < 1) { assertTrue(System.nanoTime() < deadline, "the paused poller was never resumed"); - Thread.onSpinWait(); + LockSupport.parkNanos(POLL_PARK_NANOS); } fake(1).ready(); assertSame(fake(1).pair, reader.value()); @@ -567,7 +571,7 @@ public void theIdleHookRunsAgainOnlyAfterTheReaderWasWoken() throws Exception { final long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(WAIT_MS); while (idleCalls.get() < 2) { assertTrue(System.nanoTime() < deadline, "the idle hook did not run after the wake-up"); - Thread.onSpinWait(); + LockSupport.parkNanos(POLL_PARK_NANOS); } assertEquals(2, idleCalls.get()); queue.addEndpoints(Collections.emptyList(), false); @@ -620,6 +624,62 @@ public void rejectedResumeDuringTheIdleHookDoesNotStrandTheReader() throws Excep } } + // S5. fail() and close() do not wait for an opener that is blocked in an RPC; the stream it + // opens late is closed and never read, and its reservation is released. + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void anOpenerBlockedWhileTheQueueFailsOrClosesDoesNotBlockItAndTheLateStreamIsNeverRead( + final boolean closeInsteadOfFail) throws Exception { + final CountDownLatch entered = new CountDownLatch(1); + final CountDownLatch release = new CountDownLatch(1); + try (FlightEndpointDataQueue queue = + FlightEndpointDataQueue.createNewQueue( + readers, + 2, + endpoint -> { + entered.countDown(); + try { + release.await(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new SQLException(e); + } + return recordingOpener().open(endpoint); + })) { + final Waiter adder = + new Waiter( + () -> { + queue.addEndpoints(endpoints(1), true); + return null; + }); + assertTrue(entered.await(WAIT_MS, TimeUnit.MILLISECONDS), "the opener was never called"); + assertEquals(1, queue.openUnreadCount()); + + // The opener is blocked and holds no queue lock: both calls return without it. + final Waiter ender = + new Waiter( + () -> { + if (closeInsteadOfFail) { + queue.close(); + } else { + queue.fail(new SQLException("continuation failed")); + } + return null; + }); + assertNull(ender.value()); + assertFalse(adder.isDone(), "addEndpoints returned before its opener did"); + + release.countDown(); + assertNull(adder.value()); + // The late stream was handed back: closed, never read, and its slot is free again. + verify(fake(0).pair).close(); + assertEquals(0, fake(0).reads.get()); + assertFalse(fake(0).cancelled.get()); + assertEquals(0, queue.openUnreadCount()); + assertEquals(0, queue.unreadCount()); + } + } + /** Runs a queue call on its own thread, so that a missing wake-up fails instead of hanging. */ private final class Waiter { private final CompletableFuture result = new CompletableFuture<>(); @@ -654,7 +714,7 @@ void awaitWaiting() { && thread.getState() != Thread.State.TIMED_WAITING) { assertTrue(System.nanoTime() < deadline, "the reader never waited"); assertFalse(result.isDone(), "the reader returned instead of waiting"); - Thread.onSpinWait(); + LockSupport.parkNanos(POLL_PARK_NANOS); } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java index af69fca0d0..1b099d1d6b 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/PollingMockFlightSqlProducer.java @@ -72,6 +72,7 @@ public enum Scenario { private volatile FlightInfo finalFlightInfo; private volatile CountDownLatch activePoll = new CountDownLatch(1); private volatile CountDownLatch pollTerminated = new CountDownLatch(1); + private volatile CountDownLatch continuationFailureGate; public void configure(final Scenario scenario, final String scenarioFamily) { this.scenario = scenario; @@ -85,6 +86,23 @@ public void configure(final Scenario scenario, final String scenarioFamily) { finalFlightInfo = null; activePoll = new CountDownLatch(1); pollTerminated = new CountDownLatch(1); + continuationFailureGate = null; + } + + /** + * Makes the failing continuation of {@link Scenario#CONTINUATION_UNIMPLEMENTED} wait, once it + * arrives, until {@link #releaseContinuationFailure()}. {@link #awaitActivePoll} reports that it + * arrived. Call it after {@link #configure}. + */ + public void holdContinuationFailure() { + continuationFailureGate = new CountDownLatch(1); + } + + public void releaseContinuationFailure() { + final CountDownLatch gate = continuationFailureGate; + if (gate != null) { + gate.countDown(); + } } @Override @@ -147,6 +165,20 @@ public PollInfo pollFlightInfo(final CallContext context, final FlightDescriptor if (initial) { return new PollInfo(partialInfo(finalFlightInfo), CONTINUATION_1, 0.25, null); } + final CountDownLatch gate = continuationFailureGate; + if (gate != null) { + activePoll.countDown(); + try { + while (!gate.await(10, TimeUnit.MILLISECONDS)) { + if (context.isCancelled()) { + throw CallStatus.CANCELLED.toRuntimeException(); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw CallStatus.CANCELLED.withCause(e).toRuntimeException(); + } + } throw CallStatus.UNIMPLEMENTED.toRuntimeException(); } if (selectedFamily && scenario == Scenario.TIMEOUT) { diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java index a2a8952525..4ce48ea476 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ScriptedPollQuery.java @@ -36,6 +36,7 @@ import org.apache.arrow.flight.FlightInfo; import org.apache.arrow.flight.FlightProducer.CallContext; import org.apache.arrow.flight.FlightProducer.ServerStreamListener; +import org.apache.arrow.flight.Location; import org.apache.arrow.flight.PollInfo; import org.apache.arrow.flight.Ticket; import org.apache.arrow.flight.sql.impl.FlightSql.CommandStatementQuery; @@ -116,12 +117,22 @@ public String toString() { } } + /** How an answer breaks the append-only rule for the endpoints published so far. */ + private enum Tamper { + NONE, + /** Publishes one endpoint fewer than the previous answer did. */ + SHRINK, + /** Publishes as many endpoints as before, with the first one's ticket replaced. */ + CHANGED_TICKET + } + /** The server's answer to one poll. */ public static final class Answer { private final int newEndpoints; private final boolean done; private final boolean failure; private final boolean schemaChange; + private final Tamper tamper; private final CountDownLatch gate; private Answer( @@ -129,22 +140,24 @@ private Answer( final boolean done, final boolean failure, final boolean schemaChange, + final Tamper tamper, final CountDownLatch gate) { this.newEndpoints = newEndpoints; this.done = done; this.failure = failure; this.schemaChange = schemaChange; + this.tamper = tamper; this.gate = gate; } /** Publishes {@code count} more endpoints; the query keeps running. */ public static Answer endpoints(final int count) { - return new Answer(count, false, false, false, null); + return new Answer(count, false, false, false, Tamper.NONE, null); } /** Publishes {@code count} more endpoints and completes the query. */ public static Answer done(final int count) { - return new Answer(count, true, false, false, null); + return new Answer(count, true, false, false, Tamper.NONE, null); } /** Publishes nothing; the query keeps running. */ @@ -154,12 +167,22 @@ public static Answer empty() { /** Fails the poll with INTERNAL. */ public static Answer fail() { - return new Answer(0, false, true, false, null); + return new Answer(0, false, true, false, Tamper.NONE, null); } /** Publishes one more endpoint but announces a different schema. */ public static Answer schemaChange() { - return new Answer(1, false, false, true, null); + return new Answer(1, false, false, true, Tamper.NONE, null); + } + + /** Publishes one endpoint fewer than before: an append-only violation. */ + public static Answer shrink() { + return new Answer(0, false, false, false, Tamper.SHRINK, null); + } + + /** Publishes the same number of endpoints, with the first one's ticket changed. */ + public static Answer changedTicket() { + return new Answer(0, false, false, false, Tamper.CHANGED_TICKET, null); } /** Never answers; the poll ends only when the client cancels it or its deadline expires. */ @@ -169,7 +192,7 @@ public static Answer hang() { /** Holds the answer until {@code gate} is released, or the client cancels the poll. */ public Answer gatedBy(final CountDownLatch gate) { - return new Answer(newEndpoints, done, failure, schemaChange, gate); + return new Answer(newEndpoints, done, failure, schemaChange, tamper, gate); } } @@ -178,6 +201,9 @@ public Answer gatedBy(final CountDownLatch gate) { private final List answers; private final FlightDescriptor descriptor; private volatile int rowsPerEndpoint = 1; + private volatile int batchesPerEndpoint = 1; + private volatile boolean leadingEmptyBatch; + private volatile Location[] endpointLocations = new Location[0]; private final List events = new ArrayList<>(); private final Map startGates = new HashMap<>(); @@ -209,6 +235,31 @@ public ScriptedPollQuery rowsPerEndpoint(final int rows) { return this; } + /** + * Streams {@code batches} batches of {@link #rowsPerEndpoint(int)} rows per endpoint. Row {@code + * r} of batch {@code b} holds {@code id * 100 + b * rowsPerEndpoint + r}. + */ + public ScriptedPollQuery batchesPerEndpoint(final int batches) { + this.batchesPerEndpoint = batches; + return this; + } + + /** Every endpoint stream sends one batch with no rows before its data. */ + public ScriptedPollQuery leadingEmptyBatch() { + this.leadingEmptyBatch = true; + return this; + } + + /** Publishes every endpoint with these locations, like a server that names itself. */ + public ScriptedPollQuery endpointLocations(final Location... locations) { + this.endpointLocations = locations.clone(); + return this; + } + + private Location[] locations() { + return endpointLocations; + } + /** The listed endpoints stream a single batch with no rows, then complete. */ public ScriptedPollQuery emptyEndpoints(final int... ids) { synchronized (this) { @@ -511,10 +562,17 @@ PollInfo poll(final CallContext context, final int index) { published += answers.get(i).newEndpoints; schemaChanged |= answers.get(i).schemaChange; } + if (answer.tamper == Tamper.SHRINK) { + published = Math.max(0, published - 1); + } final List endpoints = new ArrayList<>(); for (int id = 0; id < published; id++) { + final String ticket = + answer.tamper == Tamper.CHANGED_TICKET && id == 0 + ? ticketPrefix() + "changed" + : ticketPrefix() + id; endpoints.add( - new FlightEndpoint(new Ticket((ticketPrefix() + id).getBytes(StandardCharsets.UTF_8)))); + new FlightEndpoint(new Ticket(ticket.getBytes(StandardCharsets.UTF_8)), locations())); } final FlightInfo info = new FlightInfo(schemaChanged ? CHANGED_SCHEMA : SCHEMA, descriptor, endpoints, -1, -1); @@ -601,12 +659,21 @@ private void sendBatch(final int id, final ServerStreamListener listener) { empty = emptyEndpoints.contains(id); } final int rows = empty ? 0 : rowsPerEndpoint; - for (int row = 0; row < rows; row++) { - vector.setSafe(row, id * 100 + row); - } listener.start(root); - root.setRowCount(rows); - listener.putNext(); + if (empty || leadingEmptyBatch) { + root.setRowCount(0); + listener.putNext(); + } + if (empty) { + return; + } + for (int batch = 0; batch < batchesPerEndpoint; batch++) { + for (int row = 0; row < rows; row++) { + vector.setSafe(row, id * 100 + batch * rows + row); + } + root.setRowCount(rows); + listener.putNext(); + } } } } diff --git a/reports/poll-ahead-implementation-plan.md b/reports/poll-ahead-implementation-plan.md index 0e2c6cf8df..16b6890e11 100644 --- a/reports/poll-ahead-implementation-plan.md +++ b/reports/poll-ahead-implementation-plan.md @@ -17,7 +17,8 @@ All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/a 6. End of results: `next()` returns false only when the queue is empty, nothing is pending, and the poller has finished. The poller must mark itself finished in the same locked step that queues the final endpoints. 7. Fail fast: a failed continuation poll records the failure, closes every open stream, drops pending endpoints and buffered batches, and makes the next `next()` throw. No `CancelFlightInfo` is needed, because the server already ended the query. The exception keeps today's mapping: `TIMED_OUT` becomes `SQLTimeoutException("Query timed out after N SECONDS")`; anything else becomes `SQLException("Continuation PollFlightInfo failed", cause)`. 8. Cancel and close stop the poller. `Statement.cancel()`, the deadline and `ResultSet.close()` on an incomplete result cancel the operation context, end any open poll, send best-effort `CancelFlightInfo` once (existing `PollInfoOperation.cancel`), close the queue, and make the next `next()` throw "Statement canceled". -9. Metadata calls, `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, and `usePollInfo=false` are unchanged. +9. Unlimited eager queue: a first answer that is already complete (no continuation) and `pollInfoPrefetch=0` both use the queue without an open limit, so every endpoint opens at once, as it always did. The limit applies only while a poller is running. +10. Metadata calls, `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, and `usePollInfo=false` are unchanged. ## Configuration (connection properties) From 436156f29b6e336c98ddf9fcc2e0e7782d97754e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 02:42:43 +0000 Subject: [PATCH 32/39] BDX-645: do not interrupt a poller's CancelFlightInfo when the connection closes A poller that fails the result on a deadline records the failure first and then sends the blocking CancelFlightInfo. A connection closed as soon as next() threw called shutdownNow() on the poller pool, which interrupted that RPC before it reached the server (5 of 5 runs of the reproduction). The statements are already closed at that point, so the pollers are ending: shut the pool down gracefully for up to 2 s before interrupting. Co-Authored-By: Claude Opus 5.5 --- .../driver/jdbc/ArrowFlightConnection.java | 12 +++++++++--- .../arrow/driver/jdbc/PollAheadTest.java | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index 0028e1b72b..cde492c57e 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -234,9 +234,15 @@ private void shutdownPollerExecutor() throws InterruptedException { executor = pollerExecutor; } if (executor != null) { - executor.shutdownNow(); - if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { - LOGGER.warn("PollFlightInfo poller threads did not terminate within 5 seconds"); + // The statements were closed, so every poller is ending. One that failed the result on a + // deadline is still sending its CancelFlightInfo (bounded to 1 s): interrupting it now would + // drop the cancel, so give the pollers a moment before interrupting them. + executor.shutdown(); + if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { + executor.shutdownNow(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + LOGGER.warn("PollFlightInfo poller threads did not terminate within 5 seconds"); + } } } } diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java index 174f186e11..5b6530e740 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -923,6 +923,25 @@ public void multiBatchStreamsWithAnEmptyLeadingBatchAreReadInOrder() throws Exce assertTrue(script.maxOpenStreams() <= 2); } + // Reproduction of a dropped CancelFlightInfo: the poller records the failure first and sends + // the (blocking) cancel after it, so a connection that is closed as soon as next() threw used + // to interrupt the cancel before it reached the server. + @Test + public void closingRightAfterTheDeadlineFailureStillSendsTheCancelFlightInfo() throws Exception { + final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); + try (Connection connection = connect("pollInfoPrefetch=2"); + Statement statement = connection.createStatement()) { + statement.setQueryTimeout(1); + try (ResultSet resultSet = statement.executeQuery(script.query())) { + assertTrue(resultSet.next()); + assertThrows(SQLTimeoutException.class, resultSet::next); + } + } + assertTrue(script.awaitCancelFlightInfo(1, WAIT_MS), "the CancelFlightInfo was dropped"); + assertFalse(script.awaitCancelFlightInfo(2, QUIET_MS)); + assertEquals(1, script.cancelFlightInfoCount()); + } + // ---- helpers ---------------------------------------------------------------------------- private static ScriptedPollQuery scripted(final Answer... answers) { From f6374c4428a3f4b99e90d7b2c27bd5e97c8ecaaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 02:45:59 +0000 Subject: [PATCH 33/39] BDX-645: sync the poll-ahead TLA+ model with the slot-release and error-handling fixes Mirror 4b831553c in the model and move the sync commit to it. - AppRead is split into AppTake (hand-over, the stream keeps its slot) and AppExhaust (the application's own stream.next() returned false: read and free in one step under the queue lock, as Q.endpointExhausted does). OpenWithinLimit now counts the stream being read. - New rule SlotFreedOnExhaust and broken variant lateRelease (the old re-enqueue and null-future release). A reviewer found the late release, not TLC: lateRelease-old-rules shows every earlier rule passes it. - CancelOp: Statement.cancel's operation cancel runs before the cancelled flag, so a poll it ends is recorded as the queue failure. - A failed queue is inert: ApplyQ is a no-op, OpenReserved registers nothing, ReadFree finds no pending endpoint. New rule FailedQueueInert, variant applyAfterFail. - PollerCrash: any Throwable fails the queue. Variant errorNotReported (an Error kills the poller, next() waits forever, fails Terminates). - SKILL.md: coverage table, not-modeled list (fallback path, cleanup RPC, reader pool), findings 3 and 4. Every run.sh line is ok at N=3 and N=4. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-jdbc-poll-ahead/SKILL.md | 106 +++++-- formal/pollinfo-poll-ahead/PollAhead.tla | 263 +++++++++++++----- formal/pollinfo-poll-ahead/run.sh | 11 +- 3 files changed, 286 insertions(+), 94 deletions(-) diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md index 35591c9eb5..493bd986a8 100644 --- a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -17,9 +17,11 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. | `EachEndpointOnce` | Each endpoint is queued for download once, even though every PollInfo repeats all earlier endpoints. | Duplicate rows. | | `ContinuationsOnce` | Each continuation descriptor is sent at most once. | The server rejects the reused descriptor (`FAILED_PRECONDITION` in the conformance server), or the query re-runs. | | `FailFast` | No row reaches the application after the driver saw the query fail or was cancelled. | The application processes data from a failed query. | +| `FailedQueueInert` | After the queue recorded a failure, `addEndpoints` queues, reserves and opens nothing. | Endpoints and reservations pile up on a dead queue, and `moreExpected` could be set again after `fail()` cleared it. | | `CancelStopsPolling` | No poll is sent after `Statement.cancel()`, the deadline, or `close()` has finished stopping the poller. | Server work continues after the user cancelled. | | `Backpressure` | The poller does not poll while unread endpoints are at `pollInfoPrefetch`. | The driver runs ahead of a slow reader without bound. | -| `OpenWithinLimit` | Open, opening and unread `DoGet` streams never exceed the limit. | More open streams, each buffering up to 5 batches, than the setting promises. | +| `OpenWithinLimit` | Open, opening and unread `DoGet` streams never exceed the limit. The stream the application is reading counts until it is read to the end. | More open streams, each buffering up to 5 batches, than the setting promises. | +| `SlotFreedOnExhaust` | A stream's slot is freed in the step where the application's own `stream.next()` returns false. No finished stream still holds a slot while the application reads another one. | The poller stays paused, and pending endpoints stay unopened, behind a stream nobody reads. This is a progress rule, not a safety rule: see finding 3. | | `NoSpin` | No poll is sent straight after an answer that added nothing. | A busy loop against servers that answer at once. | | `Terminates` | Every result eventually ends or throws, if nobody cancels. | `next()` hangs forever. | | `InlineMeansPoller` | Structural: when the reader runs the poller inline, the poller is not paused or orphaned. | Two threads drive one continuation chain. | @@ -27,56 +29,81 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. ## Scope, bounds, assumptions - Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled, except that a rejected resume is a free choice (`ReaderResumeRejected`). -- Rows are abstracted: reading an endpoint is one step, and an endpoint is either empty (its future yields `null`) or not. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". +- Rows are abstracted: an endpoint is taken (`AppTake`) and later read to the end (`AppExhaust`), and nothing between is tracked. An endpoint is either empty (its future yields `null`, `AppReadEmpty`) or not. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". - Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked, and neither are the 10 x 100 us resubmit retries (only their outcome). - The server may answer a poll at any moment, including at once with nothing new. - Atomic steps in the model, each one a single locked step or RPC answer in the code: - `Q.addEndpoints`: append, set `moreExpected`, reserve slots, signal (`PollerApply*`). - `Q.pauseIfFull`: count check, paused flag, and the poller's `owned = false` (`PollerPause`). - - `Q.onStreamFinished`, the part under the lock: free the slot, reserve pending endpoints, clear the paused flag (`AppRead`, `AppReadEmpty`). + - `Q.onStreamFinished`, the part under the lock: free the slot, reserve pending endpoints, clear the paused flag. The application thread runs it in two places: `Q.endpointExhausted` when its own `stream.next()` returned false (`AppExhaust`, read to the end and free in one step), and `awaitNext` consuming a null future (`AppReadEmpty`). Closing the finished stream and opening the reserved endpoints happen after the unlock and are not part of the step. - `Q.awaitNext`'s lock-protected check and the start of the wait (`AppEnd`, `AppIdle`, `ReaderWait`). - Steps the model splits because the code does not do them atomically: + - taking a ready stream (`AppTake`, no slot change) and reading it to the end (`AppExhaust`, slot freed): the stream keeps its slot in between, as `openUnread` does; - the resume after unlocking (`ReaderResume`, `ReaderResumeRejected`), against the poller's `owned` flag; - stream opening outside the lock into reserved slots (`OpenReserved`, `OpenFails`); - the orphaned poller run inline by the reader (`AppIdle`, `InlineExit`, `PollerApplyHandBack`); - - `cancel()`: the `cancelled` flag, then stop, cancel the operation and close the queue (`AppCancel`, `CancelStop`); + - `Statement.cancel()`: `PollInfoOperation.cancel()` first (`CancelOp`: an open poll ends `CANCELLED`, so the poller can record "Statement canceled" as the queue failure before `cancelled` is set), then `ResultSet.cancel()`: the `cancelled` flag, then stop, cancel the operation and close the queue (`AppCancel`, `CancelStop`). `CancelOp` is optional: `close()` and a direct `ResultSet.cancel()` start at `AppCancel`; - the reader's idle hook and its wait (`idleTried`). -- Over-approximations (safe, they only add behaviors): any step may open a reserved stream (the code opens it on the thread that reserved it, before that thread goes on); a stream registered after a failure or cancel still counts as open (the code closes it at once). -- Not modeled: a row already buffered when cancel or a failure starts can still reach the application from a `next()` call that was already running (the next call throws). -- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, protocol violations in an answer (`validateAppendOnly`, schema change), the poller pool failing to start (`start()` rejected, then `disablePollAhead`), the timed first wait, or an `Error` (not `RuntimeException`) killing the poller thread. +- Over-approximations (safe, they only add behaviors): any step may open a reserved stream (the code opens it on the thread that reserved it, before that thread goes on); `AppExhaust` is allowed after a failure or cancel (the stream's `next()` would usually throw `CANCELLED` first); `PollerCrash` may hit the poller in any of `running`, `polling`, `received`, `backoff`; a started `Statement.cancel()` always reaches `ResultSet.cancel()` (fairness on `AppCancel`). +- Not tracked: the rows between `AppTake` and `AppExhaust`. Each `next()` call starts with the `cancelled` and `queue.failure()` checks, which the model treats as `AppThrow`, so `FailFast` only watches the hand-over of a stream. A row already buffered when cancel or a failure starts can still reach the application from a `next()` call that was already running (the next call throws). +- Not modeled, by design: the cleanup RPC that follows a failed poll (`afterFailure`: `cancel()` or `terminate()`, then `finishPollInfoOperation`; `CancelFlightInfo` has a 1 s timeout). The model has no time, so it cannot say how long a failure takes to reach the reader. It records the failure in the step that takes the answer, which is what `onPollFailed` now does. +- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, the poller pool failing to start (`start()` rejected, then `disablePollAhead`), the timed first wait (`SQLTimeoutException`), the reader pool's size and the other results that share it, `endpointExhausted` on a queue without an opener (it re-enqueues), a cancel during `executeQuery` before the `ResultSet` exists, or **the fallback path** (`pollInfoPrefetch = 0` or a busy poller pool): `loadNextPublishedEndpoint` polls inside `next()` on the unlimited eager queue, and since `4b831553c` it loops while a continuation remains. Before that it returned false when the new endpoints had no rows, which truncates the result (the class of `NoPrematureEnd`, on a path the model does not describe; found by review, covered only by Java tests). +- Answer validation (`validateAppendOnly`, schema change, no continuation to poll) and an interrupted backoff are not modeled as such. They all end the poller with a queue failure, which is `PollerCrash`. - **The implementation corresponds to `EagerOpen = FALSE`** for continuations: a queue built with `maxOpen = pollInfoPrefetch`. **Complete answers** (no continuation) **and `pollInfoPrefetch = 0` use the unlimited eager queue** (`maxOpen = Integer.MAX_VALUE`, no poller, the reader polls in `next()`); the model does not cover that path. `EagerOpen = TRUE` is kept only to show the old finding. +- The first load (`populateData` -> `getNextEndpointStream(true, false)` -> `Q.nextAvailable`) is not a separate action. It runs the same `awaitNext` loop and only differs by returning null where `next()` would idle, wait or end. The model starts when the poller has started, with the reader at the top of that loop and `idleTried` false, which is also the state of a fresh `next()` call; every state after the first load is one the model reaches from there. ## Coverage record -Sync commit: `dadd45d8a` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`). The diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream, and the application still gets a throw either way). - Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. +Sync commit: `4b831553c` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`) and the slot release on exhaustion. + +Earlier syncs: the diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream). + +The diff `dadd45d8a..4b831553c` of the main code (four files: **R**, **P**, **O**, **Q**) changed these behaviors. Findings 3 and 4 say what each one did to the model: + +1. A finished endpoint's slot is freed by `Q.endpointExhausted` when the application's own `stream.next()` returns false (model: `AppRead` split into `AppTake` and `AppExhaust`). +2. The first load uses `Q.nextAvailable` (waitForMore = false), so `executeQuery` does not wait for unpublished endpoints (no model change). +3. The queue is failed before the operation's blocking `cancel()` / `terminate()` (no model change). +4. A cancel that races a poll is recorded as the queue failure "Statement canceled" (model: `CancelOp`). +5. A failed queue is inert: `addEndpoints` is a no-op and `openReserved` stops opening (model: `ApplyQ`, `OpenReserved`, `ReadFree`). +6. Any `Throwable` on the poller fails the queue (model: `PollerCrash`). +7. The fallback path loops while a continuation remains (not modeled). + +Not a model action: `Thread.currentThread().interrupt()` before wrapping an `InterruptedException`, `volatile` on `R.poller`, and the new public `O.isCancelled()` (it is read by `mapContinuationFailure`, see `CancelOp`). + +Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection` shuts the poller pool down with `shutdown()` and a 2 s grace before `shutdownNow()`, so a poller's `CancelFlightInfo` is not interrupted). A rejected submit after the shutdown is already the free choice `ReaderResumeRejected`, and, per the commit message, the statements are closed (pollers stopped) before the pool goes. The sync commit stays at `4b831553c`: move it to a later commit once its main-code diff has been checked the same way. + | Model action | Code at the sync commit | | --- | --- | | `PollerSend`, `PollerTake` | P `drive` -> O `pollOnce` -> `poll`. The poll runs on a pool thread, or on the reader's thread when run inline. | -| `PollerApplyBackoff`, `PollerApplyGo` | O `remember` (inside `pollOnce`: `validateAppendOnly`, new continuation), then R `appendEndpoints` -> Q `addEndpoints`; then P `drive`: `operation.backoff` (backoff) or the next loop iteration (go). | +| `PollerApplyBackoff`, `PollerApplyGo` | O `remember` (inside `pollOnce`: `validateAppendOnly`, new continuation), then R `appendEndpoints` -> Q `addEndpoints`; then P `drive`: `operation.backoff` (backoff) or the next loop iteration (go). On a failed queue Q `addEndpoints` returns at its `failure != null` check and changes nothing (`ApplyQ`, `FailedQueueInert`); P `drive` then stops at its loop-top check (`PollerSeesFail`). | | `PollerApplyHandBack` | The same, run inline: P `drive(true)` after an answer that added endpoints calls `handBack` (`submit`, or orphaned again). | | `PollerApplyFinish` | Q `addEndpoints(list, false)` and P `drive`: `FINISHED`, `onFinished`. | | `PollerPause`, `PollerPauseEnd`, `PollerCheck` | Q `pauseIfFull` with P `drive`'s `onPaused` (paused flag and `owned.set(false)` under the lock). `PollerPauseEnd` and `PollerCheck` exist only for the broken variants. | | `PollerSeesFail`, `PollerDrop` | P `drive`: the loop-top check and the check after `pollOnce`. | | `BackoffElapses` | O `backoff` (cancellable wait), P `drive` `BACKOFF` state. | -| `OpenReserved`, `OpenFails` | Q `openReserved`, `register`, `releaseReservations`, `fail`. The `opening` count is `resv`. | -| `AppRead`, `AppReadEmpty` | R `next` and `loadNextPublishedEndpoint` -> Q `awaitNext` taking a ready future, or a `null` future -> `onStreamFinished` (slot freed, `reserveSlotsLocked`, paused flag cleared). | +| `OpenReserved`, `OpenFails` | Q `openReserved`, `register`, `releaseReservations`, `fail`. The `opening` count is `resv`. `openReserved` stops at `shutdown \|\| failure != null` and releases the rest, and `register` drops a stream opened after a failure or close: in both cases the reservation is released and no stream is registered (`OpenReserved` leaves `opened` unchanged once `failSeen` or `gated`). | +| `AppTake` | R `populateData` (first load: Q `nextAvailable`), `next` and `loadNextPublishedEndpoint` -> Q `awaitNext` returning a ready future (`ready != null`, after `throwIfFailed`). No slot changes: the stream stays in `openUnread` and `endpointsToClose`. | +| `AppExhaust` | R `next`: `currentEndpointData.getStream().next()` returned false, then R `endpointExhausted` -> Q `endpointExhausted` -> `onStreamFinished(finished)`: under the lock `endpointsToClose.remove`, `openUnread--`, `reserveSlotsLocked`, paused flag cleared (`ReadFree`); after the unlock `closeQuietly`, the resume action (`ReaderResume`), `openReserved`. Only R `next` calls it, on the application thread. | +| `AppReadEmpty` | Q `awaitNext` taking a `null` future (a stream that ended inside the pool task without rows) -> `onStreamFinished` (same locked step as `AppExhaust`). | +| `ReadFree` (the shared locked step) | Q `onStreamFinished`. On a failed or closed queue `pending` is empty (`fail()` and `close()` clear it), so it reserves nothing. | | `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). | | `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`). `idleTried` is the local variable in `awaitNext`; it is cleared after a wait and after every consumed future (`AppReadEmpty`, `IdleFix`). | | `ReaderWait` and the wakes (`WakeRd`) | Q `awaitNext` -> `awaitChange`; `signalAll` in `addEndpoints`, `register`, `releaseReservations`, `fail`, `close`, `wakeReader`. | | `AppEnd` | Q `awaitNext` returning `null` (futures empty, pending empty, `opening == 0`, `!moreExpected`, under the lock), R `next` returning false. | | `AppThrow` | Q `awaitNext` -> `checkOpen`, `throwIfFailed`; R `next` top-of-call checks of `cancelled` and `queue.failure()`. | -| `AppCancel`, `CancelStop` | R `cancel` and `close`: `cancelled = true`; then P `stop`, O `cancel`, Q `close`. Also `ArrowFlightStatement.cancel`, `ArrowFlightPreparedStatement.cancel`. | -| `SrvAnswer` failure branch, `PollerTake` error branch | P `onPollFailed` -> Q `fail` (R `mapContinuationFailure`). | +| `CancelOp` | `ArrowFlightStatement.cancel` and `ArrowFlightPreparedStatement.cancel`: `operation.cancel()` runs before `super.cancel()` reaches `R.cancel`. O `cancel` sets `cancelled`, cancels the gRPC context (an open poll ends `CANCELLED`, O `call` refuses new RPCs). | +| `AppCancel`, `CancelStop` | R `cancel` and `close`: `cancelled = true`; then P `stop`, O `cancel`, Q `close`. | +| `SrvAnswer` failure branch, `PollerTake` error branch | P `onPollFailed` -> `queue.fail(failureMapper.apply(e))` (R `mapContinuationFailure`), then `afterFailure` (not modeled). If the poller is not stopped and the queue is not closed yet, a poll that `CancelOp` ended is recorded as the failure "Statement canceled" (O `isCancelled`). If `stopped` or the queue is closed, `onPollFailed` returns without a failure (`PollerDrop`). | +| `PollerCrash` | P `runOnPool` and `runInlineIfOrphaned`: `catch (Throwable)` -> P `fail(Throwable)` -> Q `fail` (an `Error` is rethrown afterwards). Also P `drive`'s `queue.fail` for a sink `SQLException`, a missing continuation, and an interrupted backoff. | ## When to use it Run it when a diff touches any covered file: ```sh -git diff --name-only dadd45d8a..HEAD -- \ +git --no-pager diff --name-only 4b831553c..HEAD -- \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ @@ -89,19 +116,19 @@ git diff --name-only dadd45d8a..HEAD -- \ formal/pollinfo-poll-ahead/ ``` -Any output means the model may no longer describe the code. Also use this skill for any new class that polls or opens streams on a background thread. +Any output means the model may no longer describe the code. Also use this skill for any new class that polls or opens streams on a background thread. Read the code diff itself with `git --no-pager diff 4b831553c..HEAD -- ` (or `git show`, or `rtk proxy git diff`): a hook may summarize plain `git diff` output. ## How to check a change 1. **Mirror the change in the model.** The model is a hand-written design model, so TLC cannot read Java. Use the coverage record to find the action that corresponds to the code you changed, and edit that action so it does what the new code does. Keep each atomic step in the model atomic in the code: a step under one lock, or one RPC answer, is one action. -2. **Run every check** (about 15 seconds; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): +2. **Run every check** (about 35 seconds each; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): ```sh formal/pollinfo-poll-ahead/run.sh N=4 formal/pollinfo-poll-ahead/run.sh ``` - The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. `lateRelease-old-rules` is the other exception, on purpose: it runs `lateRelease` against the rules that existed before `SlotFreedOnExhaust` and must pass, which records that the late release is invisible to them (finding 3). A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. 3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. 4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. 5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. @@ -120,13 +147,52 @@ Any output means the model may no longer describe the code. Also use this skill The path was narrow: the poller had to answer and register a stream inside the reader's few instructions between the idle hook and the next lock, the connection's poller pool had to reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down), and the new endpoints had to have no rows. When it happened, `next()` hung until `cancel()` or `close()`. -Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppRead` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. Commit `dadd45d8a` (`next()` rethrows `queue.failure()` before the CANCELLED mapping) changes only which exception a blocked reader throws, not any model action. +Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppTake` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. Commit `dadd45d8a` (`next()` rethrows `queue.failure()` before the CANCELLED mapping) changes only which exception a blocked reader throws, not any model action. ### 2. `finding-open-streams`: the first proposal (`EagerOpen = TRUE`, resolved) `OpenWithinLimit` fails for the proposal as first written. The limit is checked before a poll, but one answer can publish several endpoints, and their streams all open at once. With a limit of 2: one stream is open, the poller sends the continuation, and an answer with three endpoints opens two more, leaving three open streams. The implementation does not do this: `reserveSlotsLocked` opens only while fewer than `maxOpen` streams are open or opening (`EagerOpen = FALSE`, check `deferred-open`). +### 3. Late slot release: found by a reviewer, not by the model checker (fixed in `4b831553c`) + +**What the code did** (`dadd45d8a`). When the application read a stream to its end, `ResultSet.next()` re-enqueued it (`enqueueEndpointData` -> `Q.enqueue`). A reader-pool task then ran `stream.next()`, got false and returned `null`, and the slot (`openUnread`) was freed only when a later `awaitNext` took that `null` future (`onStreamFinished`). Three consequences: + +- The slot of a finished stream stayed taken while the application read another one, because `awaitNext` takes the first completed future, whichever stream it belongs to. +- So the poller stayed paused, and pending endpoints stayed unopened, behind a stream nobody reads. With `pollInfoPrefetch = 2`, a finished stream plus the stream being read fill the window. +- The release needed a free thread in the connection's fixed-size reader pool, which every statement of the connection shares. A pool full of tasks blocked on slow streams of other results delays the release of an unrelated stream. + +**Why the model did not see it.** The old `AppRead` took a ready future and freed its slot in the same step, at hand-over, before the application read anything. That is not an over-approximation of the old code, it is a different point in time, and it was wrong in both directions: + +- Too tight: no state had "the application finished a stream, its slot is still taken", so the late release could not occur. +- Too loose: while the application held a stream the model had already freed its slot, so `Unread`, `Backpressure` and `OpenWithinLimit` ignored it. The model's poller could run one endpoint further ahead than the code's (`pauseIfFull` counts `openUnread`, which includes the stream being read), and the model's number of open streams, the one being read included, could reach `Limit + 1` without any rule noticing. + +No rule could have caught it, and none does: `lateRelease-old-rules` shows that the late-release model passes every rule that existed before this change, `Terminates` included. It is a progress problem (the poller is blocked by a stream that is already finished), not a safety or termination problem. + +**What the model does now.** `AppRead` is split into `AppTake` (hand-over, no slot change) and `AppExhaust` (the application's own `stream.next()` returned false, and the slot is freed under the lock in the same step, on the application thread). The held stream counts as unread and open, as `openUnread` does. The new rule `SlotFreedOnExhaust` says "no finished stream holds a slot while the application reads another one", which is the "poller is not blocked by an unrelated stream" property. The broken variant `lateRelease` reproduces the old code: `AppExhaust` only marks the stream as spent, and the slot is freed when `AppReadEmpty` takes its null future. It fails `SlotFreedOnExhaust` in 9 steps, with a limit of 2: + +1. The server publishes a second endpoint. The poller polls and the answer lists two endpoints. +2. The poller applies the answer, the second endpoint is reserved, and its stream is opened. Two streams are open: the limit. +3. The application takes the first stream (`AppTake`), reads it to the end (`AppExhaust`): its slot stays taken. +4. The reader takes the second stream's ready future first (`AppTake`, completion order) while the first stream's slot is still taken. The poller cannot prefetch anything while the application reads the second stream. + +**Limits of this check.** `SlotFreedOnExhaust` holds in the faithful model by the construction of `AppExhaust`: it guards the action against being split again, it does not look at Java. The code is guarded by Java tests such as `FlightEndpointDataQueueDeferredOpenTest.endpointExhaustedFreesTheSlotOnTheCallingThread`: after `endpointExhausted`, `openUnreadCount()` has dropped on the calling thread. The third consequence (the reader pool) is not modeled: pool threads and other results are not in the model, so no rule can say that a release depends on a free thread. + +### 4. The other review fixes in `4b831553c` + +None of these was found by TLC. Each row says what the model did about it. + +| Change | Model | Rule or variant | +| --- | --- | --- | +| 2. The first load does not wait for unpublished endpoints | None. The first load is the same `awaitNext` loop (see the scope section), and the model starts at its top. A first endpoint without rows leaves no stream, and the following `next()` does the waiting: states the model already has. | None. A "`executeQuery` does not block on the poller" rule would need time or an uncooperative server. | +| 3. The queue is failed before the blocking `cancel()` / `terminate()` | None. The model already records the failure in the step that takes the answer, so the old code was the one that did not match. The delay was bounded by the 1 s timeout of `cancelFlightInfoBestEffort`, a latency problem. | None, for the same reason: no time in the model. | +| 4. A cancel that races a poll is recorded as the failure "Statement canceled" | New action `CancelOp` (`PollInfoOperation.cancel()` before `ResultSet.cancel()`), `SrvAnswer` answers `CANCELLED` once `opCancelled`, and `PollerTake` records it as `failSeen` while `cancelled` is still false. Reachable (checked), and every rule holds: the reader throws either way, only the exception differs. | No new rule. `FailFast` and `CancelStopsPolling` hold with the extra step. | +| 5. A failed queue is inert | `ApplyQ` is a no-op once `failSeen`; `OpenReserved` registers nothing once `failSeen` or `gated`; `ReadFree` finds no pending endpoint after a failure or close (the model derives pending from `known - opened - resv`, so it is masked by `failSeen \/ gated`). | New rule `FailedQueueInert`, variant `applyAfterFail`. The check in `openReserved` is a `volatile` read outside the lock, so "no `DoGet` starts after a failure" is not a rule: a race window remains and only the locked part is atomic. | +| 6. Any `Throwable` on the poller fails the queue | New action `PollerCrash`. Before this, the model listed an `Error` killing the poller as not modeled. | Variant `errorNotReported`: an `Error` leaves the poller dead and the queue not failed, so `next()` waits forever (`Terminates`). The old code did exactly this for an `Error`. | +| 7. The fallback path loops while a continuation remains | None. The path is outside the model (see the scope section). | None. Its old defect belongs to the class of `NoPrematureEnd`. Extending the model to the fallback path is the open follow-up. | + +No rule failed on the model of `4b831553c`: every line of `run.sh` says `ok` at `N=3` and `N=4`, and the design checks also pass with a limit of 1 and of 3. + ## Files - `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. -- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`, `lateRelease`, `applyAfterFail`, `errorNotReported`, plus the gap check `lateRelease-old-rules`. diff --git a/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla index 97cc253118..7a314b1142 100644 --- a/formal/pollinfo-poll-ahead/PollAhead.tla +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -2,9 +2,12 @@ (***************************************************************************) (* Bounded poll-ahead for the Arrow Flight SQL JDBC driver (BDX-645). *) (* *) -(* One progressive JDBC ResultSet, from the moment executeQuery has *) -(* returned it: the first PollInfo published endpoint E1 and continuation *) -(* C1, and C1 has been handed to the poller. *) +(* One progressive JDBC ResultSet, from the moment its poller has started: *) +(* the first PollInfo published endpoint E1 and continuation C1, and C1 *) +(* has been handed to the poller. The application thread is in *) +(* executeQuery's first load (Q.nextAvailable) or in ResultSet.next(); both*) +(* run the same awaitNext loop, and the first load only differs by *) +(* returning null instead of waiting, so the model does not tell them apart.*) (* *) (* Parties that run concurrently: *) (* - the Flight SQL server, which publishes endpoints and finishes or *) @@ -14,8 +17,9 @@ (* a pool thread, or, if the pool rejected a resume, inline on the *) (* reader's thread; *) (* - the reader: the application thread inside ResultSet.next(), which *) -(* is inside FlightEndpointDataQueue.awaitNext, reads endpoints, ends *) -(* the results, or throws; *) +(* is inside FlightEndpointDataQueue.awaitNext, takes a ready stream, *) +(* reads it to the end (and frees its slot), ends the results, or *) +(* throws; *) (* - another application thread that may call Statement.cancel(). *) (* *) (* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md;*) @@ -33,18 +37,31 @@ (* opens OUTSIDE the lock, into a slot that *) (* was reserved under it (the "opening" *) (* count) *) -(* AppRead, AppReadEmpty Q.awaitNext taking a ready future, or a *) -(* null future -> Q.onStreamFinished: under *) -(* the lock free the slot, reserve pending *) -(* endpoints, clear the paused flag *) +(* AppTake Q.awaitNext returning a ready stream to R. *) +(* The stream keeps its slot while the *) +(* application reads it *) +(* AppExhaust R.next: the application's own stream.next()*) +(* returned false -> Q.endpointExhausted -> *) +(* Q.onStreamFinished: under the lock free *) +(* the slot, reserve pending endpoints, clear *) +(* the paused flag (one step on the reader) *) +(* AppReadEmpty Q.awaitNext taking a null future (a stream *) +(* that ended inside the pool task without *) +(* rows) -> Q.onStreamFinished, same locked *) +(* step *) (* ReaderResume the resume action Q.onStreamFinished runs *) (* AFTER unlocking: P.resume (claim owned, *) (* resubmit; 10 rejected submits orphan P) *) (* AppIdle, ReaderWait, Q.awaitNext, empty-futures branch: end, *) (* AppEnd, AppThrow idle hook (P.runInlineIfOrphaned), or wait *) (* InlineExit P.runInlineIfOrphaned returning *) -(* AppCancel / CancelStop R.cancel: the cancelled flag first, then *) -(* P.stop + O.cancel + Q.close *) +(* CancelOp, AppCancel, Statement.cancel: O.cancel first (an open *) +(* CancelStop poll ends CANCELLED), then R.cancel: the *) +(* cancelled flag, then P.stop + O.cancel + *) +(* Q.close *) +(* PollerCrash P.runOnPool / P.runInlineIfOrphaned catch *) +(* any Throwable -> P.fail -> Q.fail; also *) +(* the answer-validation failures *) (* PollerSeesFail, PollerDrop P.drive loop top and the check after the *) (* poll *) (* *) @@ -53,10 +70,12 @@ (* pollInfoPrefetch = 0, use an unlimited eager queue and never start a *) (* poller; the model does not cover them. *) (* *) -(* Rows are abstracted: reading an endpoint is one step. Endpoint i is the *) -(* i-th endpoint the server publishes; PollInfo is cumulative, so an *) -(* answer is just how many endpoints exist so far. An endpoint is either *) -(* empty (no rows: its future yields null) or not. *) +(* Rows are abstracted: an endpoint is taken (AppTake, its first batch *) +(* reaches the application) and later read to the end (AppExhaust, which *) +(* frees its slot); nothing in between is tracked. Endpoint i is the i-th *) +(* endpoint the server publishes; PollInfo is cumulative, so an answer is *) +(* just how many endpoints exist so far. An endpoint is either empty (no *) +(* rows: its future yields null, AppReadEmpty) or not. *) (***************************************************************************) EXTENDS Naturals @@ -90,10 +109,14 @@ VARIABLES sawFull, \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet rd, \* the reader: "run" (top of the awaitNext loop) | "resume" | "waiting" | "inline" idleTried, \* awaitNext's local idleTried flag + held, \* the application holds a stream (currentEndpointData) that still has its slot + spent, \* lateRelease only: streams the application finished, slot not freed yet app, \* "reading" | "ended" | "threw" failSeen, \* the queue recorded a failure + opCancelled, \* Statement.cancel called PollInfoOperation.cancel: an open poll ends CANCELLED cancelled, \* ResultSet.cancelled: next() throws from now on gated, \* cancel finished: poller stopped, operation cancelled, queue closed + badApply, \* addEndpoints queued endpoints on a queue that had already failed badRow, \* a row was handed to the application after a failure or cancel badPoll, \* a poll was sent after cancel finished polledAtLimit, \* a poll was sent while queued, unread endpoints were at the limit @@ -104,9 +127,10 @@ srvV == <> qV == <> rpcV == <> polV == <> -rdV == <> -appV == <> -flagV == <> +rdV == <> +appV == <> +flag5 == <> +flagV == <> vars == <> @@ -116,13 +140,15 @@ Max(a, b) == IF a > b THEN a ELSE b Answer == [has : BOOLEAN, count : 0..N, more : BOOLEAN, err : BOOLEAN] NoAnswer == [has |-> FALSE, count |-> 0, more |-> FALSE, err |-> FALSE] -Unread == known - read \* pending + open-unread -NoFutures == opened = read \* every registered stream was finished +Unread == known - read \* pending + open-unread (a held stream is still open-unread) +Futs == opened - read - (IF held THEN 1 ELSE 0) \* futures in the completion queue +NoFutures == Futs = 0 \* the queue's `futures` map is empty NothingQueued == known = opened /\ resv = 0 \* pending empty and opening == 0 \* The reader is woken (signalAll) only if it is waiting; then it clears its idle flag. WakeRd == /\ rd' = IF rd = "waiting" THEN "run" ELSE rd /\ idleTried' = IF rd = "waiting" THEN FALSE ELSE idleTried + /\ UNCHANGED <> ----------------------------------------------------------------------------- Init == @@ -146,10 +172,14 @@ Init == /\ sawFull = FALSE /\ rd = "run" /\ idleTried = FALSE + /\ held = FALSE + /\ spent = 0 /\ app = "reading" /\ failSeen = FALSE + /\ opCancelled = FALSE /\ cancelled = FALSE /\ gated = FALSE + /\ badApply = FALSE /\ badRow = FALSE /\ badPoll = FALSE /\ polledAtLimit = FALSE @@ -176,11 +206,12 @@ SrvFail == /\ UNCHANGED <> \* The server answers the open poll. It may answer at once with nothing new. -\* Once cancel has cancelled the operation's context, the open poll ends with CANCELLED. +\* Once Statement.cancel has cancelled the operation's context (opCancelled, which comes before +\* R.cancel sets `cancelled`), the open poll ends with CANCELLED. SrvAnswer == /\ inflight /\ ~resp.has - /\ resp' = IF gated \/ server = "failed" + /\ resp' = IF opCancelled \/ gated \/ server = "failed" THEN [has |-> TRUE, count |-> 0, more |-> FALSE, err |-> TRUE] ELSE [has |-> TRUE, count |-> published, more |-> server = "running", err |-> FALSE] /\ inflight' = FALSE @@ -203,7 +234,7 @@ PollerSend == /\ badPoll' = (badPoll \/ gated) /\ polledAtLimit' = (polledAtLimit \/ Unread >= Limit) /\ waited' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> \* Q.pauseIfFull: at the limit, the poller sets the paused flag and gives its thread back. \* The count check, the flag and P's owned=false are one step under the queue lock. @@ -246,7 +277,10 @@ PollerSeesFail == /\ poller' = "stopped" /\ UNCHANGED <> -\* The poller takes the answer. A failure fails the queue at once (onPollFailed -> Q.fail). +\* The poller takes the answer. A failure fails the queue at once (onPollFailed -> Q.fail; the +\* operation's own cancel/terminate RPC runs afterwards and is not modeled). An answer to a poll +\* that Statement.cancel ended (opCancelled, but P.stop and Q.close have not run yet) is recorded +\* as a failure too: the failure mapper turns it into "Statement canceled". PollerTake == /\ poller = "polling" /\ resp.has @@ -255,7 +289,7 @@ PollerTake == THEN /\ poller' = "failed" /\ failSeen' = TRUE /\ contHeld' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> /\ rd' = IF rd \in {"waiting", "inline"} THEN "run" ELSE rd /\ idleTried' = IF rd \in {"waiting", "inline"} THEN FALSE ELSE idleTried ELSE /\ got' = resp @@ -263,7 +297,29 @@ PollerTake == /\ more' = IF Mutation = "finishBeforeEnqueue" /\ ~resp.more THEN FALSE ELSE more /\ UNCHANGED <> /\ UNCHANGED <> + waited, sawFull, app, opCancelled, cancelled, gated, flagV>> + +\* Anything unexpected ends the poller (a RuntimeException or an Error from the RPC layer or the +\* sink, a protocol violation in an answer, an interrupted backoff): P.runOnPool and +\* P.runInlineIfOrphaned catch every Throwable and fail the queue (P.fail -> Q.fail). The poller +\* never keeps a half-applied answer. Broken variant errorNotReported: only a RuntimeException +\* failed the queue, an Error silently killed the pool thread (the poller is "dead"). +PollerCrash == + /\ poller \in {"running", "polling", "received", "backoff"} + /\ IF Mutation = "errorNotReported" + THEN /\ rd # "inline" + /\ poller' = "dead" + /\ UNCHANGED <> + ELSE /\ poller' = "failed" + /\ failSeen' = TRUE + /\ rd' = IF rd \in {"waiting", "inline"} THEN "run" ELSE rd + /\ idleTried' = IF rd \in {"waiting", "inline"} THEN FALSE ELSE idleTried + /\ contHeld' = FALSE + /\ inflight' = FALSE + /\ resp' = NoAnswer + /\ got' = NoAnswer + /\ UNCHANGED <> \* Slots addEndpoints can reserve: fewer than Limit streams open or opening and unread. \* EagerOpen: every new endpoint takes a slot at once. @@ -274,16 +330,22 @@ ApplyRsv == IN IF EagerOpen THEN pendNew ELSE Min(pendNew, free) \* addEndpoints: in one locked step append only the new suffix, set moreExpected, reserve slots -\* (their streams open later, outside the lock), and signal the reader. +\* (their streams open later, outside the lock), and signal the reader. On a failed queue it is a +\* no-op: nothing is queued or opened, the reader rethrows the failure (broken variant +\* applyAfterFail: the old code queued and reserved anyway). ApplyQ == /\ got.has /\ poller = "received" - /\ enq' = [i \in 1..N |-> - IF i >= (IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1) /\ i <= got.count - THEN Min(enq[i] + 1, 2) ELSE enq[i]] - /\ known' = got.count - /\ resv' = resv + ApplyRsv - /\ more' = got.more + /\ IF failSeen /\ Mutation # "applyAfterFail" + THEN /\ UNCHANGED <> + ELSE /\ enq' = [i \in 1..N |-> + IF i >= (IF Mutation = "enqueueWholeList" THEN 1 ELSE known + 1) + /\ i <= got.count + THEN Min(enq[i] + 1, 2) ELSE enq[i]] + /\ known' = got.count + /\ resv' = resv + ApplyRsv + /\ more' = got.more + /\ badApply' = (badApply \/ failSeen) /\ got' = NoAnswer \* An answer that adds nothing while the query runs: back off, then poll again. @@ -296,7 +358,7 @@ PollerApplyBackoff == /\ lastEmpty' = TRUE /\ poller' = IF Mutation = "noBackoff" THEN "running" ELSE "backoff" /\ WakeRd - /\ UNCHANGED <> + /\ UNCHANGED <> \* An answer that adds endpoints, applied by a pool thread: go on to the next iteration. PollerApplyGo == @@ -309,7 +371,7 @@ PollerApplyGo == /\ lastEmpty' = FALSE /\ poller' = "running" /\ WakeRd - /\ UNCHANGED <> + /\ UNCHANGED <> \* An answer that adds endpoints, applied inline on the reader: hand the poller back to the \* pool (handBack). If the pool rejects it 10 times, the poller stays orphaned. @@ -324,7 +386,8 @@ PollerApplyHandBack == /\ poller' \in {"running", "orphaned"} /\ rd' = "run" /\ idleTried' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> \* The final answer: the queue sees the last endpoints and moreExpected = FALSE together. PollerApplyFinish == @@ -336,7 +399,7 @@ PollerApplyFinish == /\ rd' = IF rd = "inline" \/ rd = "waiting" THEN "run" ELSE rd /\ idleTried' = IF rd = "inline" \/ rd = "waiting" THEN FALSE ELSE idleTried /\ UNCHANGED <> + held, spent, appV, flag5>> \* 100 ms doubling up to pollInfoMaxBackoff; time is abstracted to one step. BackoffElapses == @@ -354,14 +417,14 @@ PollerDrop == ----------------------------------------------------------------------------- (* Opening streams, outside the lock, into reserved slots. Whoever reserved the slot opens it; - the model lets any step do it, which only adds behaviors. A stream registered after a failure - or cancel is closed at once in the code; here it still counts as open, which also only adds - behaviors. *) + the model lets any step do it, which only adds behaviors. On a failed or closed queue + openReserved stops opening and register() drops a stream that was already open: either way the + reservation is released and no stream is registered. *) OpenReserved == /\ resv > 0 /\ resv' = resv - 1 - /\ opened' = opened + 1 + /\ opened' = IF failSeen \/ gated THEN opened ELSE opened + 1 /\ WakeRd /\ UNCHANGED <> @@ -371,18 +434,19 @@ OpenFails == /\ resv' = resv - 1 /\ failSeen' = TRUE /\ WakeRd - /\ UNCHANGED <> + /\ UNCHANGED <> ----------------------------------------------------------------------------- -(* The reader: ResultSet.next() inside Q.awaitNext *) +(* The reader: ResultSet.next() inside Q.awaitNext, and the application between calls *) \* onStreamFinished, the part under the lock: free the slot, reserve pending endpoints for \* opening, and clear the paused flag if unread endpoints are below the limit. The resume -\* action runs after unlocking (ReaderResume). +\* action runs after unlocking (ReaderResume). A failed or closed queue has no pending endpoints +\* (fail() and close() clear them). ReadFree == LET read1 == read + 1 - pend == known - opened - resv + pend == IF failSeen \/ gated THEN 0 ELSE known - opened - resv free == Max(0, Limit - (opened - read1) - (IF Mutation = "openNotReserved" THEN 0 ELSE resv)) rsv == IF EagerOpen THEN 0 ELSE Min(pend, free) @@ -392,29 +456,53 @@ ReadFree == /\ pflag' = IF wake THEN FALSE ELSE pflag /\ rd' = IF wake THEN "resume" ELSE "run" -\* Take a ready stream, read it, and finish it: rows reach the application. -AppRead == +\* awaitNext returns a ready stream (a future with rows) to the application. The stream keeps its +\* slot (openUnread) until the application has read it to the end (AppExhaust). Rows reach the +\* application from here on; later next() calls start with the cancelled and failure checks. +AppTake == /\ app = "reading" /\ rd = "run" - /\ opened > read + /\ ~held + /\ Futs - spent > 0 /\ (Mutation = "readAfterFail" \/ (~failSeen /\ ~cancelled)) - /\ ReadFree + /\ held' = TRUE /\ badRow' = (badRow \/ failSeen \/ cancelled) /\ idleTried' = FALSE - /\ UNCHANGED <> - -\* Take a null future (an endpoint with no rows) and finish it. awaitNext loops without -\* returning to the application. The code clears idleTried right after onStreamFinished -\* (IdleFix); without it the flag would stay set (the bug fixed in dadd45d8a). + /\ UNCHANGED <> + +\* R.next: the application's own stream.next() returned false. It frees the slot at once, on the +\* application thread, under the queue lock (Q.endpointExhausted -> onStreamFinished): read and +\* free are one step. The resume action runs after unlocking (ReaderResume). Broken variant +\* lateRelease is the old code: the stream was re-enqueued and the slot was freed only when a +\* later awaitNext consumed its null future, in completion order. +AppExhaust == + /\ app = "reading" + /\ rd = "run" + /\ held + /\ held' = FALSE + /\ IF Mutation = "lateRelease" + THEN /\ spent' = spent + 1 + /\ UNCHANGED <> + ELSE /\ spent' = spent + /\ ReadFree + /\ UNCHANGED <> + +\* Take a null future (a stream that ended inside the pool task without rows) and finish it. +\* awaitNext loops without returning to the application. The code clears idleTried right after +\* onStreamFinished (IdleFix); without it the flag would stay set (the bug fixed in dadd45d8a). +\* In the lateRelease variant the null future may be the one of a stream the application finished. AppReadEmpty == /\ app = "reading" /\ rd = "run" - /\ opened > read + /\ ~held + /\ Futs > 0 /\ ~failSeen /\ ~cancelled + /\ \/ spent > 0 /\ spent' = spent - 1 + \/ Futs > spent /\ spent' = spent /\ ReadFree /\ idleTried' = IF IdleFix THEN FALSE ELSE idleTried - /\ UNCHANGED <> + /\ UNCHANGED <> \* The resume action of onStreamFinished, run on the reader's thread after unlocking: \* P.resume claims `owned` (true only if the poller gave it up) and resubmits. A rejected @@ -423,7 +511,8 @@ ReaderResume == /\ rd = "resume" /\ rd' = "run" /\ poller' = IF poller = "paused" THEN "running" ELSE poller - /\ UNCHANGED <> + /\ UNCHANGED <> \* The resume was rejected: the poller is orphaned, owned stays true, the reader is woken. ReaderResumeRejected == @@ -431,7 +520,8 @@ ReaderResumeRejected == /\ poller = "paused" /\ rd' = "run" /\ poller' = "orphaned" - /\ UNCHANGED <> + /\ UNCHANGED <> \* Nothing is queued and more may come: call the idle hook (P.runInlineIfOrphaned). If the poller \* is orphaned, it polls on the reader's thread; otherwise the hook returns false and @@ -439,6 +529,7 @@ ReaderResumeRejected == AppIdle == /\ app = "reading" /\ rd = "run" + /\ ~held /\ ~failSeen /\ ~cancelled /\ NoFutures /\ NothingQueued /\ more @@ -449,7 +540,7 @@ AppIdle == /\ UNCHANGED idleTried ELSE /\ idleTried' = TRUE /\ UNCHANGED <> - /\ UNCHANGED <> + /\ UNCHANGED <> \* The inline run ended because the poller was stopped; the idle hook returns true. InlineExit == @@ -459,25 +550,27 @@ InlineExit == /\ ~resp.has /\ rd' = "run" /\ idleTried' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> \* Futures empty and no endpoint queued or opening, but more may come (or the idle hook said no): \* wait on the condition, which the lock-protected check makes atomic. ReaderWait == /\ app = "reading" /\ rd = "run" + /\ ~held /\ ~failSeen /\ ~cancelled /\ NoFutures /\ ~(NothingQueued /\ ~more) /\ ~(NothingQueued /\ ~idleTried) /\ rd' = "waiting" - /\ UNCHANGED <> + /\ UNCHANGED <> \* next() returns false: futures empty, pending empty, opening == 0, and !moreExpected, \* all read under the lock. AppEnd == /\ app = "reading" /\ rd = "run" + /\ ~held /\ ~failSeen /\ ~cancelled /\ NoFutures @@ -485,21 +578,32 @@ AppEnd == /\ (resv = 0 \/ Mutation = "endIgnoresOpening") /\ (~more \/ Mutation = "endWhenQueueEmpty") /\ app' = "ended" - /\ UNCHANGED <> + /\ UNCHANGED <> +\* next() throws: the top-of-call checks of `cancelled` and queue.failure(), or awaitNext's +\* checkOpen and throwIfFailed. The application may hold a stream while it does. AppThrow == /\ app = "reading" /\ rd = "run" /\ failSeen \/ cancelled /\ app' = "threw" - /\ UNCHANGED <> + /\ UNCHANGED <> + +\* Statement.cancel, step 0: PollInfoOperation.cancel. An open poll ends with CANCELLED and no +\* new RPC starts. This runs before R.cancel sets `cancelled`, so the poller can record the ended +\* poll as the queue failure "Statement canceled" first. +CancelOp == + /\ app = "reading" + /\ ~opCancelled + /\ opCancelled' = TRUE + /\ UNCHANGED <> \* R.cancel, step 1: the cancelled flag. next() throws from the next call on. AppCancel == /\ app = "reading" /\ ~cancelled /\ cancelled' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> \* R.cancel, step 2: P.stop (stopped = true), O.cancel (an open poll ends with CANCELLED, no new \* RPC starts), Q.close (wakes the reader). @@ -507,6 +611,7 @@ CancelStop == /\ cancelled /\ ~gated /\ gated' = TRUE + /\ opCancelled' = TRUE /\ poller' = IF poller \in {"finished", "failed"} \/ Mutation = "cancelIgnoresPoller" THEN poller ELSE "stopped" /\ contHeld' = IF Mutation = "cancelIgnoresPoller" THEN contHeld ELSE FALSE @@ -522,14 +627,15 @@ Done == Next == \/ SrvPublish \/ SrvComplete \/ SrvFail \/ SrvAnswer \/ PollerSend \/ PollerCheck \/ PollerPause \/ PollerPauseEnd \/ PollerSeesFail - \/ PollerTake \/ PollerApplyBackoff \/ PollerApplyGo \/ PollerApplyHandBack + \/ PollerTake \/ PollerCrash \/ PollerApplyBackoff \/ PollerApplyGo \/ PollerApplyHandBack \/ PollerApplyFinish \/ BackoffElapses \/ PollerDrop \/ OpenReserved \/ OpenFails - \/ AppRead \/ AppReadEmpty \/ ReaderResume \/ ReaderResumeRejected \/ AppIdle \/ InlineExit - \/ ReaderWait \/ AppEnd \/ AppThrow \/ AppCancel \/ CancelStop + \/ AppTake \/ AppExhaust \/ AppReadEmpty \/ ReaderResume \/ ReaderResumeRejected \/ AppIdle + \/ InlineExit \/ ReaderWait \/ AppEnd \/ AppThrow \/ CancelOp \/ AppCancel \/ CancelStop \/ Done \* The server eventually finishes; the driver, the cancel call and the application keep going. +\* A started Statement.cancel always reaches R.cancel. Fairness == /\ WF_vars(SrvComplete) /\ WF_vars(SrvAnswer) /\ WF_vars(PollerSend) /\ WF_vars(PollerPause) /\ WF_vars(PollerPauseEnd) @@ -537,9 +643,11 @@ Fairness == /\ WF_vars(PollerApplyBackoff) /\ WF_vars(PollerApplyGo) /\ WF_vars(PollerApplyHandBack) /\ WF_vars(PollerApplyFinish) /\ WF_vars(BackoffElapses) /\ WF_vars(PollerDrop) /\ WF_vars(OpenReserved) - /\ WF_vars(AppRead \/ AppReadEmpty) /\ WF_vars(ReaderResume \/ ReaderResumeRejected) + /\ WF_vars(AppTake \/ AppReadEmpty) /\ WF_vars(AppExhaust) + /\ WF_vars(ReaderResume \/ ReaderResumeRejected) /\ WF_vars(AppIdle) /\ WF_vars(InlineExit) /\ WF_vars(ReaderWait) - /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) /\ WF_vars(CancelStop) + /\ WF_vars(AppEnd) /\ WF_vars(AppThrow) /\ WF_vars(AppCancel /\ opCancelled) + /\ WF_vars(CancelStop) Spec == Init /\ [][Next]_vars /\ Fairness @@ -549,11 +657,13 @@ Spec == Init /\ [][Next]_vars /\ Fairness TypeOK == /\ published \in 1..N /\ server \in {"running", "done", "failed"} - /\ read <= opened /\ opened + resv <= known /\ known <= published + /\ read + (IF held THEN 1 ELSE 0) <= opened /\ opened + resv <= known /\ known <= published + /\ held \in BOOLEAN /\ spent \in 0..N /\ spent <= Futs + /\ gated => opCancelled /\ enq \in [1..N -> 0..2] /\ resp \in Answer /\ got \in Answer /\ poller \in {"running", "polling", "received", "backoff", "paused", "pausing", - "orphaned", "finished", "failed", "stopped"} + "orphaned", "finished", "failed", "stopped", "dead"} /\ rd \in {"run", "resume", "waiting", "inline"} /\ app \in {"reading", "ended", "threw"} /\ sawFull \in BOOLEAN @@ -580,6 +690,13 @@ CancelStopsPolling == ~badPoll \* The poller never polls while queued, unread endpoints are at the limit. Backpressure == ~polledAtLimit +\* No slot stays held by a stream the application has read to the end while the application reads +\* another one: the poller and the pending endpoints must not wait for a finished stream. +SlotFreedOnExhaust == ~(held /\ spent > 0) + +\* A failed queue takes nothing more: addEndpoints queues and opens nothing after a failure. +FailedQueueInert == ~badApply + \* Open, opening and unread DoGet streams never exceed the limit. OpenWithinLimit == opened + resv - read <= Limit diff --git a/formal/pollinfo-poll-ahead/run.sh b/formal/pollinfo-poll-ahead/run.sh index 0ad8a9642a..012a4eda32 100755 --- a/formal/pollinfo-poll-ahead/run.sh +++ b/formal/pollinfo-poll-ahead/run.sh @@ -25,7 +25,9 @@ WORK=$(mktemp -d) trap 'rm -rf "$WORK"' EXIT cp "$HERE/PollAhead.tla" "$WORK/" -SAFE="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin" +# The rules before the slot-release change (4b831553c): no rule says when a finished stream's slot is freed. +OLD_RULES="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin OpenWithinLimit" +SAFE="TypeOK InlineMeansPoller EachEndpointOnce ContinuationsOnce NoPrematureEnd FailFast CancelStopsPolling Backpressure NoSpin SlotFreedOnExhaust FailedQueueInert" ALL="$SAFE OpenWithinLimit" unexpected=0 @@ -85,6 +87,13 @@ check pauseNotAtomic FALSE TRUE pauseNotAtomic "$ALL" yes livenes check ownedClearedLate FALSE TRUE ownedClearedLate "$ALL" yes liveness "pause clears owned after the lock: resume finds it set" check noIdleHook FALSE TRUE noIdleHook "$ALL" yes liveness "an orphaned poller is never run inline" check staleIdle FALSE FALSE none "$SAFE" yes liveness "idleTried not cleared after a consumed future (rejected resume strands next())" +check lateRelease FALSE TRUE lateRelease "$ALL" no invariant:SlotFreedOnExhaust "slot freed only when a later awaitNext consumes the null future, not when the application finishes the stream" +check applyAfterFail FALSE TRUE applyAfterFail "$ALL" no invariant:FailedQueueInert "addEndpoints queues and reserves on a queue that already failed" +check errorNotReported FALSE TRUE errorNotReported "$ALL" yes liveness "an Error kills the poller thread without failing the queue (next() waits forever)" +echo +echo "Gap check: lateRelease passes every rule that existed before SlotFreedOnExhaust. The late release is a progress" +echo "problem (a finished stream blocks the poller), not a safety or termination one, and only the new rule sees it." +check lateRelease-old-rules FALSE TRUE lateRelease "$OLD_RULES" yes pass "NOT a bug in the model: shows what the old rule set could not express" echo if [ "$unexpected" -eq 0 ]; then echo "All checks matched their expectations."; else echo "Some checks did not match. See above."; fi From 2574a511cadc4493c4d04640a312b7e956d81de9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 03:07:06 +0000 Subject: [PATCH 34/39] BDX-645: make the backoff cancel and close tests wait inside the backoff The server sees a poll arrive, not the poller start sleeping, so a cancel or close right after the sixth poll ended the RPC instead of the wait, and mutating backoff() to ignore a cancel went unnoticed. Give the poller a moment to answer and start its wait, assert that it is waiting, then cancel. Co-Authored-By: Claude Opus 5.5 --- .../arrow/driver/jdbc/PollAheadTest.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java index 5b6530e740..88c766ffaf 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -730,6 +730,20 @@ private static ScriptedPollQuery backingOff() { .rowsPerEndpoint(2); } + // Returns once the poller sleeps in the long backoff wait that follows poll 5. The server only + // sees a poll arrive, so the answer and the start of the wait are given a moment: a cancel that + // came during the RPC would end the poll, not the wait, and prove nothing about the backoff. + private static void awaitBackoffWait(final ScriptedPollQuery script, final Connection connection) + throws Exception { + assertTrue(script.awaitPollCount(6, WAIT_MS)); + Thread.sleep(QUIET_MS); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "the poller is not waiting in its backoff"); + assertEquals(6, script.pollCount(), "the poller polled again before the wait ended"); + } + @Test public void cancelDuringABackoffWaitEndsItAndSendsNoMorePolls() throws Exception { final ScriptedPollQuery script = backingOff(); @@ -737,7 +751,7 @@ public void cancelDuringABackoffWaitEndsItAndSendsNoMorePolls() throws Exception Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(script.query())) { assertTrue(resultSet.next()); - assertTrue(script.awaitPollCount(6, WAIT_MS)); + awaitBackoffWait(script, connection); final long cancelNanos = System.nanoTime(); statement.cancel(); final SQLException canceled = assertThrows(SQLException.class, resultSet::next); @@ -761,7 +775,7 @@ public void closeDuringABackoffWaitReturnsPromptlyAndSendsNoMorePolls() throws E final Statement statement = connection.createStatement(); final ResultSet resultSet = statement.executeQuery(script.query()); assertTrue(resultSet.next()); - assertTrue(script.awaitPollCount(6, WAIT_MS)); + awaitBackoffWait(script, connection); final long closeNanos = System.nanoTime(); resultSet.close(); statement.close(); From c77fa206b67afb17930df601b07569414bc88f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 03:21:03 +0000 Subject: [PATCH 35/39] BDX-645: move the poll-ahead verification sync commit to 2574a511c The only main-code change after 4b831553c is the poller-pool shutdown in ArrowFlightConnection (436156f29), which is not a model action. run.sh matches every expectation at N=3 and N=4. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/verify-jdbc-poll-ahead/SKILL.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md index 493bd986a8..5b6310f11e 100644 --- a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -56,7 +56,7 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. -Sync commit: `4b831553c` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`) and the slot release on exhaustion. +Sync commit: `2574a511c` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`) and the slot release on exhaustion. The only main-code change after `4b831553c` is `436156f29` (see below), which is not a model action. Earlier syncs: the diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream). @@ -72,7 +72,7 @@ The diff `dadd45d8a..4b831553c` of the main code (four files: **R**, **P**, **O* Not a model action: `Thread.currentThread().interrupt()` before wrapping an `InterruptedException`, `volatile` on `R.poller`, and the new public `O.isCancelled()` (it is read by `mapContinuationFailure`, see `CancelOp`). -Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection` shuts the poller pool down with `shutdown()` and a 2 s grace before `shutdownNow()`, so a poller's `CancelFlightInfo` is not interrupted). A rejected submit after the shutdown is already the free choice `ReaderResumeRejected`, and, per the commit message, the statements are closed (pollers stopped) before the pool goes. The sync commit stays at `4b831553c`: move it to a later commit once its main-code diff has been checked the same way. +Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection` shuts the poller pool down with `shutdown()` and a 2 s grace before `shutdownNow()`, so a poller's `CancelFlightInfo` is not interrupted). A rejected submit after the shutdown is already the free choice `ReaderResumeRejected`, and, per the commit message, the statements are closed (pollers stopped) before the pool goes. Checked against the code at `2574a511c`, whose main code differs from `4b831553c` only by this change, so the sync commit moved there. | Model action | Code at the sync commit | | --- | --- | @@ -103,7 +103,7 @@ Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection Run it when a diff touches any covered file: ```sh -git --no-pager diff --name-only 4b831553c..HEAD -- \ +git --no-pager diff --name-only 2574a511c..HEAD -- \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ @@ -147,7 +147,7 @@ Any output means the model may no longer describe the code. Also use this skill The path was narrow: the poller had to answer and register a stream inside the reader's few instructions between the idle hook and the next lock, the connection's poller pool had to reject a resume (all `pollInfoPollerThreads` busy with other results, or the pool shut down), and the new endpoints had to have no rows. When it happened, `next()` hung until `cancel()` or `close()`. -Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppTake` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. Commit `dadd45d8a` (`next()` rethrows `queue.failure()` before the CANCELLED mapping) changes only which exception a blocked reader throws, not any model action. +Fix, in `dadd45d8a`: `awaitNext` sets `idleTried = false` right after `onStreamFinished(source)`. This is exactly `IdleFix = TRUE` (`AppReadEmpty` clears `idleTried`; `AppTake` returns to the application, where the local flag ends). Regression test: `rejectedResumeDuringTheIdleHookDoesNotStrandTheReader` in `FlightEndpointDataQueueDeferredOpenTest`. The same commit also makes `next()` rethrow `queue.failure()` before the CANCELLED mapping. That changes only which exception a blocked reader throws, not any model action. ### 2. `finding-open-streams`: the first proposal (`EagerOpen = TRUE`, resolved) From b618dbc1461e754b10c0b63d8c5da1e3a195f22b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 13:07:59 +0000 Subject: [PATCH 36/39] BDX-645: update the go/no-go doc for poll-ahead Add a poll-ahead section (behavior, settings, verification, bugs found) and the 2026-11-26 re-validation. Contract item 12 is now implemented by the backoff, so the doc no longer lists it as a reason not to merge. Co-Authored-By: Claude Opus 5.5 --- reports/production-recommendation.md | 62 +++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/reports/production-recommendation.md b/reports/production-recommendation.md index 26ffef22b2..5b6cb72e11 100644 --- a/reports/production-recommendation.md +++ b/reports/production-recommendation.md @@ -6,20 +6,22 @@ Detailed evidence: [`jdbc-report.md`](jdbc-report.md), [`call-site-inventory.md` ## Recommendation: GO, as a production change built from this POC; not mergeable as-is -PollInfo-by-default works in JDBC without changing any `java.sql` signature or result type. Direct, prepared and metadata queries all went through `PollFlightInfo` against both in-process producers and the shared Go conformance server. The contract held: send the original descriptor once, bind once, fall back only on an initial `UNIMPLEMENTED`, cache per family, offer an opt-out, use one deadline, and let cancel work before the `ResultSet` exists. Progressive endpoint consumption at `ResultSet.next()` also works. +PollInfo-by-default works in JDBC without changing any `java.sql` signature or result type. Direct, prepared and metadata queries all went through `PollFlightInfo` against both in-process producers and the shared Go conformance server. The contract held: send the original descriptor once, bind once, fall back only on an initial `UNIMPLEMENTED`, cache per family, offer an opt-out, use one deadline, and let cancel work before the `ResultSet` exists. Progressive endpoint consumption works, and since 2026-11-26 a background poller fetches continuations while the application reads (see "Poll-ahead" below). -The branch has been rebased onto current upstream `main` (see "Rebase onto upstream main" below). It is still not ready to merge, for two reasons: +The branch has been rebased onto current upstream `main` (see "Rebase onto upstream main" below). It is still not ready to merge, because of the public API: 1. **The public API surface is accidental.** The POC adds a protected `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)` in the published `flight-sql` artifact. That method can collide with subclasses that already exist downstream. It also adds a public `PollInfoOperation` and public handler and builder methods in `flight-sql-jdbc-core`. All of this needs an intentional design and an upstream Apache discussion before it lands. -2. **Contract item 12 was not implemented.** `PollInfoOperation.pollNextAvailable()` loops with no delay while the server keeps returning responses that add no endpoints. It relies entirely on the server to long-poll. A server that answers immediately makes the loop spin, and with no statement timeout set, nothing bounds it. + +Contract item 12 (a delay between answers that add nothing) was missing from the first POC. It is now implemented: both the background poller and the reader's own polling wait 100 ms after such an answer, doubling up to `pollInfoMaxBackoffMs` (default 5000), never past the deadline. Cancel and close end the wait. ## Documented limitations (behavioral) -- **Late errors move to `ResultSet.next()`.** In progressive mode, `executeQuery` returns once the first endpoint is published. A query that fails afterwards raises `SQLException` from `next()`, not from `executeQuery`. JDBC allows this, but applications that treat a successful `executeQuery` as a successful query will see different behavior. Production needs an explicit decision here, because the ticket rules out an opt-in: either progressive by default, or final-only by default with progressive behind a property. +- **Late errors move to `ResultSet.next()`.** In progressive mode, `executeQuery` returns once the first endpoint is published. A query that fails afterwards raises `SQLException` from `next()`, not from `executeQuery`. JDBC allows this, but applications that treat a successful `executeQuery` as a successful query will see different behavior. With poll-ahead the failure is found in the background, so it can also be thrown before the first row is read: buffered rows are dropped and the next `next()` throws. Production needs an explicit decision here, because the ticket rules out an opt-in: either progressive by default, or final-only by default with progressive behind a property. - **The deadline excludes schema preparation.** The single deadline and cancellable context cover the parameter `DoPut`, every poll and the first endpoint wait. They do not cover the earlier schema/prepare action. - **CancelFlightInfo needs a payload.** Best-effort `CancelFlightInfo` is only possible after at least one `PollInfo` has returned a `FlightInfo`. Cancelling a blocked initial poll terminates the RPC but sends no server-side cancel. - **Cleanup is synchronous.** The cancel cleanup call is bounded to one second, but it runs on the caller's thread. A slow server can delay the delivery of a timeout or cancel by up to that second. - **The capability cache is scoped to the handler.** Unsupported families are cached per `ArrowFlightSqlClientHandler`, keyed by Flight SQL command `type_url`. Pooled or reused physical connections have not been tested. +- **Poll-ahead uses threads per connection.** Each connection can start up to `pollInfoPollerThreads` (default 4) daemon poller threads. When they are all busy, a new result falls back to polling inside `next()`. Several results sharing one pool are covered by unit tests, not by the model. - **The opt-out name differs from the ticket.** The ticket suggested `usePollFlightInfo=false`; the POC implements `usePollInfo=false`. Pick one name before release and document it. ## GetFlightInfo call-site coverage @@ -49,17 +51,45 @@ The POC's `prepareDirect` path was removed in the rebase, because GH-62 already ### Shared library (`flight-sql`), needs upstream design agreement 1. Replace the protected `getInfo` hook with an intentional descriptor-resolution abstraction, or with a package-private or `@InternalApi` seam, and run a compatibility review. 2. Move the poll loop into a reusable component: continuation handling, append-only endpoint validation, initial-`UNIMPLEMENTED` fallback and the family cache. Unit-test it against every command constructor and against the default producer (which returns an already-completed `PollInfo`). -3. Add a small bounded delay or backoff for consecutive successful responses that add no endpoints (contract item 12). +3. ~~Add a small bounded delay or backoff for consecutive successful responses that add no endpoints (contract item 12).~~ Done with poll-ahead (`PollBackoff`). ### JDBC (`flight-sql-jdbc-core`) 4. Replace the POC's `ArrowFlightStatement` → prepared-delegate lookup through `statementMap` (used for cancel, timeout and operation lookup on the `Statement.execute(String)` path) with an explicit owner reference. 5. Make `PollInfoOperation` and the handler and builder additions package-private. Keep only the documented connection property. 6. Decide the default behavior for late errors (progressive or final-only). Decide whether the operation deadline should start at `prepareAndExecute` entry so that it includes schema preparation. 7. Run best-effort `CancelFlightInfo` off the caller's thread, or with a tighter bound, so it can never delay a timeout or cancel. -8. Add tests for pooled connections and the family cache, and for races between cancel, close and an in-flight poll. +8. Add tests for pooled connections and the family cache. Races between cancel, close and an in-flight poll are now covered by the poll-ahead tests and the model. 9. Add PollInfo black-box scenarios for at least one more metadata family (for example `getTables`) once the fixture supports it. 10. Keep the POC's regression tests: direct select and update, OAuth on `POLL_FLIGHT_INFO`, the exact timeout message, prepared single-bind, pre-`ResultSet` cancel, and close of an incomplete result. +## Poll-ahead (2026-11-26) + +The first POC polled the next continuation only after the application had read every published endpoint, so endpoints were found and downloaded one at a time. Poll-ahead removes that wait without changing the JDBC API. The design was agreed in review, model-checked before it was written, and implemented from [`poll-ahead-implementation-plan.md`](poll-ahead-implementation-plan.md). + +- `executeQuery` is unchanged: it returns once the first endpoint exists. +- An `EndpointPoller` on the connection's poller pool then polls each continuation once, in the same operation (one deadline, one cancel), checks append-only, and queues only the new endpoints. +- Backpressure: the poller pauses while unread endpoints reach `pollInfoPrefetch`, and holds no thread while paused. Streams open only while fewer than the limit are open and unread. The reader frees a slot and resumes the poller when it finishes an endpoint. +- Backoff as described above. +- Fail fast: a failed continuation closes every stream, drops buffered batches, and makes the next `next()` throw, with the existing exception mapping. +- Cancel, the deadline, and closing an unfinished result stop the poller and send `CancelFlightInfo` once. +- `pollInfoPrefetch=0`, or a busy poller pool, keeps the first POC's behavior (with backoff). A first answer that is already complete opens every endpoint at once, as before. + +| Property | Default | Meaning | +| --- | --- | --- | +| `pollInfoPrefetch` | `-1` = `max(2, threadPoolSize)` | Most queued, unread endpoints. `0` keeps the first POC's behavior. | +| `pollInfoPollerThreads` | `4` | Size of the connection's poller pool. | +| `pollInfoMaxBackoffMs` | `5000` | Longest wait between answers that add nothing. | + +The review set the prefetch default to `threadPoolSize`, but `threadPoolSize` defaults to 1, and a limit of 1 never polls while an endpoint is being read. + +Verification: + +- **Model.** `formal/pollinfo-poll-ahead/PollAhead.tla`, checked with TLC 2.19 by `run.sh`: 22 checks match at 3 and 4 endpoints, including a broken variant for each rule. How to recheck after a change: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`. +- **Bugs found before release.** The model found a hang after a rejected poller resume (`dadd45d8a`). A code review found a late slot release that made poll-ahead fall back to the first POC's timing, plus error, fallback and cancel edge cases (`4b831553c`). The tests found a raw `CANCELLED` error leaking from `next()` (`dadd45d8a`) and a lost `CancelFlightInfo` when the connection closed right after a deadline failure (`436156f29`). +- **Tests.** `PollAheadTest` (30), `FlightEndpointDataQueueDeferredOpenTest` (24), `EndpointPollerTest` (1) and `PollBackoffTest` (6) against scripted mock servers, and `SharedServerPollAheadTest` (13) against the conformance server's poll-ahead scenarios (`burst`, `trickle`, `empty-answers`, `late-error-buffered`), which check the server's maximum concurrent streams, poll timing against held streams, backoff gaps and cancellation. Four existing tests that assert the first POC's exact request order now run with `pollInfoPrefetch=0`. + +Not covered by the model: `executeQuery`'s first poll, the fallback path, and several results sharing one pool. + ## Rebase onto upstream main (2026-11-25) The branch was rebased from base `91b4a2ca4` onto `apache/arrow-java` `main` at `10c55b9c8`, which is 164 upstream commits. All five POC commits were kept. Six JDBC files conflicted, with 15 hunks in total, mostly against GH-62 (`054c7b8b7`). The rest were against GH-1268, GH-1499/GH-1500, GH-1232 and GH-1319/GH-1442. Resolutions: @@ -104,3 +134,23 @@ mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -am test \ | T10: Flight SQL + JDBC core full suites | not rerun (Sept: 97 + 1,269, 56 skipped) | Flight SQL 97/97; JDBC core 1,365 run, 0 failures/errors, 46 skipped (includes the PollInfo tests) | The post-rebase runs had Spotless and Checkstyle enabled. The pre-rebase runs skipped them. + +## Re-validation with poll-ahead (2026-11-26) + +Same environment. Conformance server at commit `5d0d11c` (adds the poll-ahead scenarios, holds and counters) on Flight `127.0.0.1:31337` and control `127.0.0.1:31338`. Use path-style `-Dtest` patterns so top-level test classes are included: + +```sh +mvn -pl flight/flight-sql,flight/flight-sql-jdbc-core -am install \ + -Dtest='org/apache/arrow/flight/sql/**/*.java,org/apache/arrow/driver/jdbc/**/*.java' -Dsurefire.failIfNoSpecifiedTests=false \ + -Dpollinfo.shared.enabled=true -Dpollinfo.shared.flightPort=31337 -Dpollinfo.shared.controlPort=31338 \ + -Dmaven.gitcommitid.skip=true +formal/pollinfo-poll-ahead/run.sh && N=4 formal/pollinfo-poll-ahead/run.sh +``` + +| Run | Result | +| --- | --- | +| Flight SQL suite | 97/97 | +| JDBC core suite, shared-server tests enabled | 1,458 run, 0 failures, 49 skipped | +| `SharedServerPollAheadTest` / `SharedServerPollInfoExecutionTest` | 13/13 and 11/11 | +| `install` (Spotless, Checkstyle, `dependency:analyze`) | passes | +| Model checks | all 22 match at N=3 and N=4 | From b19d8370a25e732c729825795f65e942a16aa504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 13:50:04 +0000 Subject: [PATCH 37/39] BDX-645: remove the first POC's reader-side polling; poll-ahead only A progressive result that still has a continuation is now always polled by an EndpointPoller; there is no longer a path where the reader polls continuations itself inside next(). - ResultSet: drop the pollNextAvailable loop in loadNextPublishedEndpoint, the prefetch > 0 condition in shouldPollAhead and the startPoller fallback. A busy poller pool leaves the poller orphaned, and the reader runs it inline through the existing idle hook. - EndpointPoller.start() no longer reports failure; it reuses handBack(). - Remove FlightEndpointDataQueue.disablePollAhead(), PollInfoOperation.pollNextAvailable() and the operation's now-unused max-backoff field. - pollInfoPrefetch accepts -1 (auto) or a positive number; 0 and values below -1 are rejected when the connection is created. - Tests: delete the prefetch=0 tests, rewrite the ones pinned to it to assert poll-ahead behavior, replace the busy-pool test with one that shows the second result's poller runs on the reader thread, and add tests for the hand-back to the pool and for the prefetch validation. Co-Authored-By: Claude Opus 5.5 --- .../driver/jdbc/ArrowFlightConnection.java | 5 +- .../ArrowFlightJdbcFlightStreamResultSet.java | 92 +++------ .../arrow/driver/jdbc/EndpointPoller.java | 21 +- .../driver/jdbc/client/PollInfoOperation.java | 32 --- .../ArrowFlightConnectionConfigImpl.java | 26 ++- .../jdbc/utils/FlightEndpointDataQueue.java | 19 -- .../arrow/driver/jdbc/EndpointPollerTest.java | 3 +- .../arrow/driver/jdbc/PollAheadTest.java | 191 +++++++++++------- .../driver/jdbc/PollInfoExecutionTest.java | 51 ++--- .../jdbc/SharedServerPollAheadTest.java | 22 -- .../SharedServerPollInfoExecutionTest.java | 74 ++++--- 11 files changed, 247 insertions(+), 289 deletions(-) diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java index cde492c57e..2b778327c8 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java @@ -116,6 +116,7 @@ static ArrowFlightConnection createNewConnection( url = replaceSemiColons(url); final ArrowFlightConnectionConfigImpl config = new ArrowFlightConnectionConfigImpl(properties); + config.validatePollInfoPrefetch(); clientHandler = createNewClientHandler(config, allocator, driver.getDriverVersion()); return new ArrowFlightConnection( driver, factory, url, properties, config, allocator, clientHandler); @@ -200,7 +201,7 @@ synchronized ExecutorService getExecutorService() { /** * Gets the pool that runs background PollFlightInfo pollers, creating it on first use. The pool * is bounded and has no queue: when every thread is busy, submitting a task is rejected and the - * result set falls back to polling inside {@code next()}. + * poller is run by the result set's reader inside {@code next()} instead. */ synchronized ThreadPoolExecutor getPollerExecutor() { if (pollerExecutor == null) { @@ -218,7 +219,7 @@ synchronized ThreadPoolExecutor getPollerExecutor() { return pollerExecutor; } - /** The effective most queued, unread endpoints; 0 means poll inside {@code next()}. */ + /** The effective most queued, unread endpoints of a progressive result; at least 1. */ int getPollInfoPrefetch() { return config.pollInfoPrefetch(); } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java index ab53e7971b..a199cb3416 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java @@ -85,9 +85,6 @@ public final class ArrowFlightJdbcFlightStreamResultSet try { this.flightInfo = ((ArrowFlightInfoStatement) statement).executeFlightInfoQuery(); this.pollInfoOperation = activePollInfoOperation(statement); - if (pollInfoOperation != null) { - pollInfoOperation.setMaxBackoffMillis(connection.getPollInfoMaxBackoffMs()); - } } catch (FlightRuntimeException e) { if (e.status().code() != FlightStatusCode.TIMED_OUT) { throw e; @@ -152,10 +149,9 @@ static ArrowFlightJdbcFlightStreamResultSet fromFlightInfo( return resultSet; } + // A progressive result that still has a continuation is polled in the background. private boolean shouldPollAhead() { - return pollInfoOperation != null - && pollInfoOperation.hasContinuation() - && connection.getPollInfoPrefetch() > 0; + return pollInfoOperation != null && pollInfoOperation.hasContinuation(); } private void loadNewQueue(final boolean pollAhead) { @@ -164,7 +160,8 @@ private void loadNewQueue(final boolean pollAhead) { poller = null; } Optional.ofNullable(flightEndpointDataQueue).ifPresent(AutoCloseables::closeNoChecked); - // Without poll-ahead the limit is lifted and every endpoint opens at once, as it always did. + // Without a continuation the limit is lifted and every endpoint opens at once, as it always + // did. flightEndpointDataQueue = FlightEndpointDataQueue.createNewQueue( connection.getExecutorService(), @@ -486,14 +483,8 @@ private void startPoller() throws SQLException { flightEndpointDataQueue.setResumeAction(newPoller::resume); flightEndpointDataQueue.setIdleAction(newPoller::runInlineIfOrphaned); poller = newPoller; - if (newPoller.start()) { - return; - } - // The poller pool is busy: keep the behavior of polling inside next(). - poller = null; - flightEndpointDataQueue.setResumeAction(null); - flightEndpointDataQueue.setIdleAction(null); - flightEndpointDataQueue.disablePollAhead(); + // A busy poller pool leaves the poller orphaned: the reader runs it inline when it would wait. + newPoller.start(); } /** Records the endpoints a poll answer appended, and whether more may follow, in one step. */ @@ -549,66 +540,31 @@ private void endPollInfoOperationAfterFailure(final FlightRuntimeException e) { } private boolean loadNextPublishedEndpoint() throws SQLException { - if (poller != null) { - // Poll-ahead: the queue is the single source of truth. It waits while more may arrive, and - // null means every endpoint was read and the poller finished. - try { - currentEndpointData = getNextEndpointStream(false, true); - } catch (final FlightRuntimeException e) { - if ((cancelled || flightEndpointDataQueue.isClosed()) - && e.status().code() == CallStatus.CANCELLED.code()) { - throw AvaticaConnection.HELPER.createException("Statement canceled"); - } - throw e; - } - if (currentEndpointData != null) { - populateDataForCurrentFlightStream(); - return true; - } - if (cancelled || flightEndpointDataQueue.isClosed()) { - throw AvaticaConnection.HELPER.createException("Statement canceled"); - } - finishPollInfoOperation(); - return false; - } - if (pollInfoOperation == null || !pollInfoOperation.hasContinuation()) { + if (poller == null) { + // No continuation was left after the first answer: every endpoint was read. finishPollInfoOperation(); return false; } + // The queue is the single source of truth. It waits while more may arrive, and null means every + // endpoint was read and the poller finished. try { - // Endpoints that were appended but have no rows must not end the result while the query - // still has a continuation. - while (pollInfoOperation.hasContinuation()) { - appendEndpoints(pollInfoOperation.pollNextAvailable(), false); - currentEndpointData = getNextEndpointStream(false, true); - if (currentEndpointData != null) { - populateDataForCurrentFlightStream(); - return true; - } - } - finishPollInfoOperation(); - return false; - } catch (FlightRuntimeException e) { - if (e.status().code() == FlightStatusCode.CANCELLED - || e.status().code() == FlightStatusCode.TIMED_OUT) { - pollInfoOperation.cancel(); - } else { - pollInfoOperation.terminate(); - } - finishPollInfoOperation(); - if (cancelled && e.status().code() == FlightStatusCode.CANCELLED) { + currentEndpointData = getNextEndpointStream(false, true); + } catch (final FlightRuntimeException e) { + if ((cancelled || flightEndpointDataQueue.isClosed()) + && e.status().code() == CallStatus.CANCELLED.code()) { throw AvaticaConnection.HELPER.createException("Statement canceled"); } - if (e.status().code() == FlightStatusCode.TIMED_OUT) { - final SQLTimeoutException timeout = - new SQLTimeoutException( - String.format( - "Query timed out after %d %s", statement.getQueryTimeout(), TimeUnit.SECONDS)); - timeout.initCause(e); - throw timeout; - } - throw new SQLException("Continuation PollFlightInfo failed", e); + throw e; } + if (currentEndpointData != null) { + populateDataForCurrentFlightStream(); + return true; + } + if (cancelled || flightEndpointDataQueue.isClosed()) { + throw AvaticaConnection.HELPER.createException("Statement canceled"); + } + finishPollInfoOperation(); + return false; } private static PollInfoOperation activePollInfoOperation(final AvaticaStatement statement) { diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java index 69379fffb4..1a2b74bc4d 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java @@ -41,9 +41,10 @@ * on the connection's poller pool, never on the stream reader pool. At the limit it pauses and * returns its thread; the reader resumes it when it frees a slot. * - *

    At most one party runs the poller at any moment (the {@code owned} flag). If a resume finds - * the pool busy, the poller is orphaned and the reader runs it inline when it would otherwise wait - * for more endpoints, which is the behavior of the polling-in-{@code next()} path. + *

    At most one party runs the poller at any moment (the {@code owned} flag). If the pool is busy + * when the poller starts or resumes, the poller is orphaned: the reader runs it inline when it + * would otherwise wait for more endpoints, and hands it back to the pool after an answer adds + * endpoints. */ final class EndpointPoller { private static final Logger LOGGER = LoggerFactory.getLogger(EndpointPoller.class); @@ -105,18 +106,12 @@ State state() { } /** - * Starts polling on the executor. - * - * @return false if the executor rejected the task; the poller is then unused. + * Starts polling on the executor. If the pool rejects the task, the poller is orphaned: the + * reader runs it inline when it would otherwise wait for more endpoints. */ - boolean start() { + void start() { owned.set(true); - if (submit()) { - return true; - } - owned.set(false); - state = State.STOPPED; - return false; + handBack(); } /** Stops the poller. Cancelling the operation ends an open poll and a backoff wait. */ diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java index 0b70cae593..8f7e8dac75 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/PollInfoOperation.java @@ -48,7 +48,6 @@ public final class PollInfoOperation implements AutoCloseable { private final Context.CancellableContext context; private final AtomicBoolean cancelled = new AtomicBoolean(); private final CountDownLatch cancelLatch = new CountDownLatch(1); - private volatile long maxBackoffMillis = PollBackoff.DEFAULT_MAX_MILLIS; private final AtomicBoolean cancelFlightInfoAttempted = new AtomicBoolean(); private volatile FlightInfo latestFlightInfo; private volatile FlightDescriptor continuationDescriptor; @@ -145,37 +144,6 @@ synchronized void complete(final FlightInfo flightInfo) { continuationDescriptor = null; } - /** Set the longest wait between answers that add no endpoints. */ - public void setMaxBackoffMillis(final long maxBackoffMillis) { - this.maxBackoffMillis = Math.max(1L, maxBackoffMillis); - } - - /** The longest wait between answers that add no endpoints. */ - public long maxBackoffMillis() { - return maxBackoffMillis; - } - - /** - * Poll until another endpoint is appended, the query completes, or the poll fails. After an - * answer that adds nothing while the query is still running, wait with exponential backoff (100 - * ms doubling up to {@link #maxBackoffMillis()}) before the next poll. - */ - public FlightInfo pollNextAvailable() { - final int previousEndpointCount = endpointCount(latestFlightInfo); - final PollBackoff backoff = new PollBackoff(maxBackoffMillis); - while (continuationDescriptor != null) { - remember(poll(continuationDescriptor)); - if (endpointCount(latestFlightInfo) > previousEndpointCount - || continuationDescriptor == null) { - return latestFlightInfo; - } - if (!backoff(backoff.nextDelayMillis())) { - throw CallStatus.CANCELLED.withDescription("Statement canceled").toRuntimeException(); - } - } - return latestFlightInfo; - } - /** * Poll the held continuation exactly once and remember the answer. The operation monitor is not * held across the RPC, so {@link #cancel()} always gets through. diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java index d00e41baad..2879e277ad 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImpl.java @@ -37,6 +37,8 @@ /** A {@link ConnectionConfig} for the {@link ArrowFlightConnection}. */ public final class ArrowFlightConnectionConfigImpl extends ConnectionConfigImpl { + private static final int POLL_INFO_PREFETCH_AUTO = -1; + public ArrowFlightConnectionConfigImpl(final Properties properties) { super(properties); } @@ -212,13 +214,29 @@ public boolean usePollInfo() { } /** - * Most queued, unread endpoints during progressive PollFlightInfo execution. Negative means auto: - * {@code max(2, threadPoolSize)}. Zero disables background polling (the reader polls inside - * {@code next()}). + * Most queued, unread endpoints during progressive PollFlightInfo execution. {@code -1} (the + * default) means auto: {@code max(2, threadPoolSize)}; a positive value is the limit. The value + * is checked when the connection is created, see {@link #validatePollInfoPrefetch()}. */ public int pollInfoPrefetch() { final int configured = ArrowFlightConnectionProperty.POLL_INFO_PREFETCH.getInteger(properties); - return configured < 0 ? Math.max(2, threadPoolSize()) : configured; + return configured == POLL_INFO_PREFETCH_AUTO ? Math.max(2, threadPoolSize()) : configured; + } + + /** + * Checks the {@code pollInfoPrefetch} property: {@code -1} (auto) or a positive number. Zero and + * anything below {@code -1} are rejected, because a progressive result always polls ahead. + * + * @throws SQLException if the value is not allowed. + */ + public void validatePollInfoPrefetch() throws SQLException { + final int configured = ArrowFlightConnectionProperty.POLL_INFO_PREFETCH.getInteger(properties); + if (configured != POLL_INFO_PREFETCH_AUTO && configured < 1) { + throw new SQLException( + String.format( + "Invalid pollInfoPrefetch value %d: use -1 (auto) or a positive number of endpoints.", + configured)); + } } /** Size of the connection's pool of background PollFlightInfo pollers. */ diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java index 09c0053da2..f729e7b895 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueue.java @@ -259,25 +259,6 @@ public void addEndpoints(final List endpoints, final boolean mor openReserved(toOpen); } - /** - * Stops waiting for a poller and lifts the open limit: nothing more is expected through {@link - * #addEndpoints}, and pending endpoints open now. - */ - public void disablePollAhead() throws SQLException { - final List toOpen; - lock.lock(); - try { - maxOpen = Integer.MAX_VALUE; - moreExpected = false; - paused = false; - toOpen = reserveSlotsLocked(); - changed.signalAll(); - } finally { - lock.unlock(); - } - openReserved(toOpen); - } - /** * Atomically checks the limit and pauses the poller. Returns true, after running {@code onPaused} * under the lock, when more endpoints are expected but unread endpoints are at the limit. Because diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java index ee56e648a6..e1893590aa 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/EndpointPollerTest.java @@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -93,7 +92,7 @@ public void anErrorOnThePollerThreadFailsTheQueueInsteadOfHangingTheReader() thr exception -> {}, () -> {}, 100); - assertTrue(poller.start()); + poller.start(); final CompletableFuture next = new CompletableFuture<>(); final Thread reader = diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java index 88c766ffaf..b0e2b86fea 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollAheadTest.java @@ -380,27 +380,8 @@ public void continuationsAreSentOnceEachAndInOrder() throws Exception { assertEquals(1, script.maxInFlightPolls()); } - // 10. pollInfoPrefetch=0 keeps the exact POC order: poll, DoGet, poll, DoGet. - @Test - public void prefetchZeroKeepsThePocRequestOrder() throws Exception { - final ScriptedPollQuery script = - scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)).holdEnd(0); - try (Connection connection = connect("pollInfoPrefetch=0"); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(script.query())) { - assertTrue(resultSet.next()); - assertEquals(0, resultSet.getInt(1)); - // The reader polls only when its queue is empty, so C1 waits for E0 to finish. - assertFalse(script.awaitPollCount(2, QUIET_MS), "polled ahead with pollInfoPrefetch=0"); - script.releaseEnd(0); - assertEquals(List.of(100, 200), readAll(resultSet)); - } - assertEquals( - List.of("POLL:0", "DOGET_START:0", "POLL:1", "DOGET_START:1", "POLL:2", "DOGET_START:2"), - script.eventNames(EventType.POLL, EventType.DOGET_START)); - } - - // Decision: answers with no continuation, and pollInfoPrefetch=0, open every endpoint at once. + // Decision: an answer with no continuation opens every endpoint at once, as the driver always + // did. @Test public void completeFirstAnswerOpensEveryEndpointEagerly() throws Exception { final ScriptedPollQuery script = scripted(Answer.done(4)).holdAllEnds(4); @@ -415,26 +396,29 @@ public void completeFirstAnswerOpensEveryEndpointEagerly() throws Exception { assertEquals(4, script.maxOpenStreams()); } - @Test - public void prefetchZeroOpensEveryEndpointEagerly() throws Exception { - final ScriptedPollQuery script = scripted(Answer.endpoints(3), Answer.done(1)).holdAllEnds(4); - final List rows; - try (Connection connection = connect("pollInfoPrefetch=0"); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(script.query())) { - assertTrue(script.awaitDoGetStarted(3, WAIT_MS), "not every endpoint opened eagerly"); - rows = readReleasing(resultSet, script); - } - assertEquals(List.of(0, 100, 200, 300), sorted(rows)); + // pollInfoPrefetch is -1 (auto) or positive: a progressive result always polls ahead. + @ParameterizedTest + @ValueSource(strings = {"0", "-2", "-100"}) + public void anInvalidPollInfoPrefetchIsRejectedWhenTheConnectionIsCreated(final String value) { + final SQLException failure = + assertThrows(SQLException.class, () -> connect("pollInfoPrefetch=" + value)); + assertEquals( + "Invalid pollInfoPrefetch value " + + value + + ": use -1 (auto) or a positive number of endpoints.", + failure.getMessage()); } - // 11. Poller pool busy: the second result falls back to polling in next(). + // 11. Poller pool busy: the second result's poller starts orphaned and the reader runs it inline. @Test - public void busyPollerPoolMakesTheNextResultPollInNext() throws Exception { + public void busyPollerPoolMakesTheReaderRunTheSecondResultsPollerInline() throws Exception { final CountDownLatch releaseA = new CountDownLatch(1); + final CountDownLatch releaseB = new CountDownLatch(1); final ScriptedPollQuery scriptA = scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseA), Answer.done(1)); - final ScriptedPollQuery scriptB = scripted(Answer.endpoints(1), Answer.done(1)).holdEnd(0); + final ScriptedPollQuery scriptB = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseB), Answer.done(1)) + .holdEnd(0); try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); Statement statementA = connection.createStatement(); Statement statementB = connection.createStatement()) { @@ -445,12 +429,30 @@ public void busyPollerPoolMakesTheNextResultPollInNext() throws Exception { try (ResultSet resultSetB = statementB.executeQuery(scriptB.query())) { assertTrue(resultSetB.next()); assertEquals(0, resultSetB.getInt(1)); - // B has no poller: it polls inside next(), after E0 finished. + // B's poller has no thread. It is orphaned: nobody polls C1 while the reader still has + // an open stream to read. assertFalse(scriptB.awaitPollCount(2, QUIET_MS), "B polled ahead without a poller"); - scriptB.releaseEnd(0); - assertEquals(List.of(100), readAll(resultSetB)); + + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSetB))) { + scriptB.releaseEnd(0); + // The reader has nothing left to read, so it polls C1 itself, on its own thread, while + // A's poller still holds the pool thread inside A's C1. + assertTrue(scriptB.awaitBlockedPoll(WAIT_MS), "B's C1 was never polled"); + assertEquals(2, scriptB.pollCount()); + assertEquals(2, scriptA.pollCount(), "A's poller moved on"); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "B's poll must not be running on the pool"); + assertTrue( + reader.isInside("runInlineIfOrphaned"), "B's poll is not made by the reader"); + + releaseB.countDown(); + // Every poll of B ran inline: the pool stayed busy with A the whole time. + assertEquals(List.of(100, 200), reader.rows()); + } + assertEquals(List.of(0, 1, 2), scriptB.pollIndices()); } - assertEquals(List.of(0, 1), scriptB.pollIndices()); assertEquals(2, scriptA.pollCount()); releaseA.countDown(); @@ -459,6 +461,53 @@ public void busyPollerPoolMakesTheNextResultPollInNext() throws Exception { } } + // 11b. The orphaned poller goes back to the pool once an inline answer finds it free again. + @Test + public void anOrphanedStartIsHandedBackToThePoolWhenItFreesUp() throws Exception { + final CountDownLatch releaseA = new CountDownLatch(1); + final CountDownLatch releaseB1 = new CountDownLatch(1); + final CountDownLatch releaseB2 = new CountDownLatch(1); + final ScriptedPollQuery scriptA = + scripted(Answer.endpoints(1), Answer.endpoints(1).gatedBy(releaseA), Answer.done(1)); + final ScriptedPollQuery scriptB = + scripted( + Answer.endpoints(1), + Answer.endpoints(1).gatedBy(releaseB1), + Answer.endpoints(1).gatedBy(releaseB2), + Answer.done(1)); + try (Connection connection = connect("pollInfoPollerThreads=1&pollInfoPrefetch=2"); + Statement statementA = connection.createStatement(); + Statement statementB = connection.createStatement(); + ResultSet resultSetA = statementA.executeQuery(scriptA.query())) { + assertTrue(scriptA.awaitBlockedPoll(WAIT_MS)); + try (ResultSet resultSetB = statementB.executeQuery(scriptB.query())) { + assertTrue(resultSetB.next()); + assertEquals(0, resultSetB.getInt(1)); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSetB))) { + // The reader polls B's C1 inline, because the pool is busy with A. + assertTrue(scriptB.awaitBlockedPoll(WAIT_MS)); + assertTrue(reader.isInside("runInlineIfOrphaned")); + + // Let A finish, which frees the pool thread, then answer B's C1. + releaseA.countDown(); + assertEquals(List.of(0, 100, 200), sorted(readAllWithin(resultSetA))); + awaitPollerPoolIdle(connection); + releaseB1.countDown(); + + // The answer added an endpoint, so the poller went back to the pool: C2 is polled by a + // pool thread, not by the reader. + assertTrue(scriptB.awaitPollCount(3, WAIT_MS), "B's C2 was never polled"); + assertEquals( + 1, + connection.unwrap(ArrowFlightConnection.class).getPollerExecutor().getActiveCount(), + "B's poller was not handed back to the pool"); + releaseB2.countDown(); + assertEquals(List.of(100, 200, 300), sorted(reader.rows())); + } + } + } + } + // 13. Orphaned poller: a resume finds the pool busy; the reader runs the poller inline. @Test public void anOrphanedPollerIsRunInlineByTheReader() throws Exception { @@ -493,12 +542,11 @@ public void anOrphanedPollerIsRunInlineByTheReader() throws Exception { } // 14. A continuation that never answers ends at a read boundary with the JDBC timeout message. - @ParameterizedTest - @ValueSource(strings = {"pollInfoPrefetch=0", "pollInfoPrefetch=2"}) - public void queryTimeoutEndsAtAReadBoundary(final String property) throws Exception { + @Test + public void queryTimeoutEndsAtAReadBoundary() throws Exception { final ScriptedPollQuery script = scripted(Answer.endpoints(1), Answer.hang()); final long startNanos = System.nanoTime(); - try (Connection connection = connect(property); + try (Connection connection = connect("pollInfoPrefetch=2"); Statement statement = connection.createStatement()) { statement.setQueryTimeout(1); try (ResultSet resultSet = statement.executeQuery(script.query())) { @@ -669,15 +717,28 @@ public void executeQueryReturnsWhileTheFirstStreamIsHeldAfterItsFirstBatch() thr } } - // F4. The fallback path must not report the end while a continuation remains. + // F4. An endpoint without rows must not end the result while a continuation remains. @Test - public void prefetchZeroDeliversRowsAfterAnEndpointWithoutRows() throws Exception { + public void anEndpointWithoutRowsDoesNotEndTheResultWhileAContinuationRemains() throws Exception { + final CountDownLatch gate = new CountDownLatch(1); + // E1 has no rows and is the last endpoint published until the gated done answer arrives. final ScriptedPollQuery script = - scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1)).emptyEndpoints(1); - try (Connection connection = connect("pollInfoPrefetch=0"); + scripted(Answer.endpoints(1), Answer.endpoints(1), Answer.done(1).gatedBy(gate)) + .emptyEndpoints(1); + try (Connection connection = connect("pollInfoPrefetch=2"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(script.query())) { - assertEquals(List.of(0, 200), readAll(resultSet)); + assertTrue(resultSet.next()); + assertEquals(0, resultSet.getInt(1)); + try (AsyncReader reader = new AsyncReader(() -> readAll(resultSet))) { + // E0 and E1 are read to their end; only the unanswered poll of the continuation is left. + assertTrue(script.awaitBlockedPoll(WAIT_MS)); + assertTrue(script.awaitStream(EventType.DOGET_END, 1, WAIT_MS)); + reader.awaitBlocked(); + assertFalse(reader.isDone(), "the result ended while a continuation remained"); + gate.countDown(); + assertEquals(List.of(200), reader.rows()); + } } assertEquals(List.of(0, 1, 2), script.pollIndices()); } @@ -821,26 +882,6 @@ public void theDeadlineEndsABackoffWaitAndSendsOneCancelFlightInfo() throws Exce assertEquals(1, script.cancelFlightInfoCount()); } - // S3. The fallback path (pollInfoPrefetch=0) backs off inside next() as well. - @Test - public void prefetchZeroBacksOffBetweenEmptyAnswersAndHonorsTheCap() throws Exception { - final ScriptedPollQuery script = - scripted( - Answer.endpoints(1), Answer.empty(), Answer.empty(), Answer.empty(), Answer.done(1)); - try (Connection connection = connect("pollInfoPrefetch=0&pollInfoMaxBackoffMs=150"); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(script.query())) { - assertEquals(List.of(0, 100), readAll(resultSet)); - } - final List polls = script.pollNanos(); - assertEquals(5, polls.size()); - // The reader polls C1 once E0 is read; the waits are 100 ms, then capped at 150 ms (uncapped: - // 200 and 400 ms). - assertGapBetween(polls, 1, 2, 100, 350); - assertGapBetween(polls, 2, 3, 150, 350); - assertGapBetween(polls, 3, 4, 150, 350); - } - // S6. Append-only violations fail the result and cancel the open streams. @Test public void anAnswerWithFewerEndpointsFailsTheResultAndCancelsTheStreams() throws Exception { @@ -1078,6 +1119,20 @@ void start() { thread.start(); } + boolean isDone() { + return result.isDone(); + } + + /** Whether the thread's stack is inside a method with this name, e.g. a poll made inline. */ + boolean isInside(final String methodName) { + for (final StackTraceElement frame : thread.getStackTrace()) { + if (frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + @SuppressWarnings("unchecked") private static List castList(final Object value) { return (List) value; diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java index 76a6f98dfd..87ce5f4ee0 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/PollInfoExecutionTest.java @@ -34,6 +34,7 @@ import java.sql.Statement; import java.util.Collections; import java.util.List; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -60,8 +61,6 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; /** Executable POC coverage for synchronous PollInfo through the unchanged JDBC surface. */ public class PollInfoExecutionTest { @@ -124,11 +123,9 @@ public void immediateCompletionUsesOnePollAndNoGetFlightInfo() throws Exception } @Test - // Pinned to the POC path (pollInfoPrefetch=0): the continuations are polled on demand, which - // is what the name says. Poll-ahead is covered by pollAheadPollsContinuationsWhile... - public void multiStepPollsOnDemandAfterPublishedEndpointIsConsumed() throws Exception { + public void multiStepSendsEachContinuationOnceAndInOrder() throws Exception { producer.configure(Scenario.MULTI_STEP, STATEMENT_FAMILY); - try (Connection connection = connect(true, 0); + try (Connection connection = connect(true); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { assertTrue(resultSet.next()); @@ -237,25 +234,19 @@ public void unavailableDoesNotFallbackOrReexecute() throws Exception { assertEquals(0, producer.getFlightInfoCount()); } - @ParameterizedTest - @ValueSource(ints = {0, 2}) - public void continuationUnimplementedDoesNotFallbackOrReexecute(final int pollInfoPrefetch) - throws Exception { + @Test + public void continuationUnimplementedDoesNotFallbackOrReexecute() throws Exception { producer.configure(Scenario.CONTINUATION_UNIMPLEMENTED, STATEMENT_FAMILY); - if (pollInfoPrefetch > 0) { - // The background poller would otherwise fail before or after the first next(); the failing - // answer waits until the first row was read. - producer.holdContinuationFailure(); - } - try (Connection connection = connect(true, pollInfoPrefetch); + // The background poller would otherwise fail before or after the first next(); the failing + // answer waits until the first row was read. + producer.holdContinuationFailure(); + try (Connection connection = connect(true); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { assertTrue(resultSet.next()); assertEquals(42, resultSet.getInt(1)); - if (pollInfoPrefetch > 0) { - assertTrue(producer.awaitActivePoll(5, TimeUnit.SECONDS), "the poller never polled C1"); - producer.releaseContinuationFailure(); - } + assertTrue(producer.awaitActivePoll(5, TimeUnit.SECONDS), "the poller never polled C1"); + producer.releaseContinuationFailure(); final SQLException failure = assertThrows(SQLException.class, resultSet::next); assertEquals(SQLException.class, failure.getClass()); assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); @@ -350,10 +341,11 @@ public void preparedBindIsCancelledBeforePolling() throws Exception { @Test public void statementCancelInterruptsContinuationAtReadBoundary() throws Exception { producer.configure(Scenario.CANCEL_OBSERVABLE, STATEMENT_FAMILY); - try (Connection connection = connect(true, 0); + try (Connection connection = connect(true); Statement statement = connection.createStatement()) { final AtomicReference failure = new AtomicReference<>(); final AtomicBoolean resultSetCreated = new AtomicBoolean(); + final CountDownLatch firstRowRead = new CountDownLatch(1); final Thread execution = new Thread( () -> { @@ -362,6 +354,7 @@ public void statementCancelInterruptsContinuationAtReadBoundary() throws Excepti if (!resultSet.next() || resultSet.getInt(1) != 42) { throw new AssertionError("missing published row"); } + firstRowRead.countDown(); resultSet.next(); } catch (Throwable e) { failure.set(e); @@ -369,6 +362,9 @@ public void statementCancelInterruptsContinuationAtReadBoundary() throws Excepti }, "jdbc-pollinfo-cancellation-test"); execution.start(); + // The background poller polls C1 as soon as the result exists; cancel once the application + // is waiting for more endpoints. + assertTrue(firstRowRead.await(5, TimeUnit.SECONDS), "the first row was never read"); assertTrue(producer.awaitActivePoll(2, TimeUnit.SECONDS)); assertNotNull(statement.getResultSet()); final long cancelStart = System.nanoTime(); @@ -379,8 +375,9 @@ public void statementCancelInterruptsContinuationAtReadBoundary() throws Excepti assertFalse(execution.isAlive()); assertTrue(resultSetCreated.get(), "ResultSet should expose the first published endpoint"); assertNotNull(failure.get()); + assertTrue(failure.get() instanceof SQLException, failure.get().toString()); assertTrue( - hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); + failure.get().getMessage().contains("Statement canceled"), failure.get().toString()); assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); assertTrue(producer.awaitPollTerminated(1, TimeUnit.SECONDS)); assertEquals(1, producer.cancelFlightInfoCount()); @@ -395,16 +392,6 @@ private static Connection connect(final boolean usePollInfo) throws Exception { server.getPort(), usePollInfo)); } - /** Connects with a fixed pollInfoPrefetch; 0 keeps the POC behavior of polling inside next(). */ - private static Connection connect(final boolean usePollInfo, final int pollInfoPrefetch) - throws Exception { - return DriverManager.getConnection( - String.format( - "jdbc:arrow-flight-sql://localhost:%d?useEncryption=false&usePollInfo=%s" - + "&pollInfoPrefetch=%d", - server.getPort(), usePollInfo, pollInfoPrefetch)); - } - private static void assertDirectRow(final Connection connection) throws Exception { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(DIRECT_QUERY)) { diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java index 66a83f228e..520cf926ab 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollAheadTest.java @@ -401,28 +401,6 @@ public void cancelWhileAStreamIsHeldCancelsItAndPollsNoMore() throws Exception { assertFalse(hasEnd(1, "completed"), state()); } - @Test - public void prefetchZeroKeepsThePocOrderOfPollsAndStreams() throws Exception { - final List rows; - try (Connection connection = connect(true, "pollInfoPrefetch=0"); - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery("trickle")) { - rows = values(resultSet, "trickle"); - } - assertEquals(range(1, 12), rows); - final List polls = continuationPolls(); - assertEquals(5, polls.size(), state()); - final List ends = events("DoGet.end"); - assertEquals(6, ends.size(), state()); - for (int k = 1; k <= 5; k++) { - final long endOfPrevious = single(ends, k).path("sequence").asLong(); - assertTrue( - polls.get(k - 1).path("sequence").asLong() > endOfPrevious, - "C" + k + " was polled before E" + k + " ended: " + state()); - } - assertEquals(1, counter("do_get_max_concurrent"), state()); - } - @Test public void preparedStatementBindsOnceAndDeliversAllRows() throws Exception { final List rows; diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java index 6304165aa7..6a6aa59bd8 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/SharedServerPollInfoExecutionTest.java @@ -22,6 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -30,12 +32,14 @@ import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLException; import java.sql.SQLTimeoutException; import java.sql.Statement; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -66,6 +70,7 @@ @TestMethodOrder(OrderAnnotation.class) public class SharedServerPollInfoExecutionTest { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); + private static final ObjectMapper JSON = new ObjectMapper(); private static final int FLIGHT_PORT = Integer.getInteger("pollinfo.shared.flightPort", 32347); private static final int CONTROL_PORT = Integer.getInteger("pollinfo.shared.controlPort", 32348); @@ -114,20 +119,15 @@ public void t1Immediate() throws Exception { @Test @Order(2) - // Pinned to the POC path (pollInfoPrefetch=0): the DoGet-before-first-continuation order below is - // the POC request order; poll-ahead polls the continuations in the background. public void t2MultiStepContinuationsAndFinalCumulativeInfo() throws Exception { - try (Connection connection = connect(true, "pollInfoPrefetch=0")) { + try (Connection connection = connect(true)) { assertEquals(Arrays.asList(1L, 2L, 3L), directValues(connection, "multi-step")); } final String state = state(); assertCounters(state, 3, 0, 0, 1, 2, 0, 0, 3); assertTrue(state.contains("bdx-645-poll/v1/")); + // Each continuation is sent once, and C1 before C2. assertTrue(state.indexOf("/1\"") < state.indexOf("/2\""), state); - assertTrue( - state.indexOf("\"method\": \"DoGet\"") - < state.indexOf("\"descriptor_kind\": \"continuation\""), - state); } @Test @@ -201,15 +201,19 @@ public void t7UnavailableDoesNotFallbackOrReexecute() throws Exception { @Test @Order(8) - // Pinned to the POC path (pollInfoPrefetch=0): with poll-ahead the failure may surface before - // the first row is read. public void t7LateErrorSurfacesAtNextReadBoundary() throws Exception { - try (Connection connection = connect(true, "pollInfoPrefetch=0"); + // The failing continuation is held, so the poller cannot record the failure before the first + // row was read: it surfaces at the next read. + post("/hold-poll", "{\"continuation\":1}"); + try (Connection connection = connect(true); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("late-error")) { assertTrue(resultSet.next()); assertEquals(1L, resultSet.getLong("value")); + awaitPollHeld(1); + post("/release-poll", "{\"continuation\":1}"); final Throwable failure = assertThrows(Throwable.class, resultSet::next); + assertEquals("Continuation PollFlightInfo failed", failure.getMessage()); assertTrue(hasFlightStatus(failure, FlightStatusCode.INTERNAL), failure.toString()); } assertCounters(2, 0, 0, 1, 1, 0, 0, 1); @@ -236,14 +240,12 @@ public void t8TimeoutEndsBlockedPollAtTheSingleStatementDeadline() throws Except @Test @Order(10) - // Pinned to the POC path (pollInfoPrefetch=0): the cancel surfaces as the CANCELLED - // FlightRuntimeException of the reader's own poll. With poll-ahead it is "Statement canceled" - // (SharedServerPollAheadTest). public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { - try (Connection connection = connect(true, "pollInfoPrefetch=0"); + try (Connection connection = connect(true); Statement statement = connection.createStatement()) { final AtomicReference failure = new AtomicReference<>(); final AtomicBoolean resultSetCreated = new AtomicBoolean(); + final CountDownLatch rowsRead = new CountDownLatch(1); final Thread execution = new Thread( () -> { @@ -253,6 +255,7 @@ public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { assertEquals(1L, resultSet.getLong("value")); assertTrue(resultSet.next()); assertEquals(2L, resultSet.getLong("value")); + rowsRead.countDown(); resultSet.next(); } catch (Throwable e) { failure.set(e); @@ -260,6 +263,8 @@ public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { }, "shared-server-jdbc-cancel"); execution.start(); + // The poller polls C1 in the background; the application waits for more endpoints. + assertTrue(rowsRead.await(5, TimeUnit.SECONDS), "the rows were never read"); awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); assertTrue(resultSetCreated.get()); assertNotNull(statement.getResultSet()); @@ -270,8 +275,9 @@ public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { System.out.println("SHARED_T9_CANCEL_MILLIS " + cancelMillis); assertFalse(execution.isAlive()); assertNotNull(failure.get()); + assertTrue(failure.get() instanceof SQLException, failure.get().toString()); assertTrue( - hasFlightStatus(failure.get(), FlightStatusCode.CANCELLED), failure.get().toString()); + failure.get().getMessage().contains("Statement canceled"), failure.get().toString()); assertTrue(cancelMillis < 1000, "cancellation was not prompt: " + cancelMillis); } awaitCounter("cancellation", 1, Duration.ofSeconds(2)); @@ -280,30 +286,26 @@ public void t9CancelWhileResultSetWaitsForMoreEndpoints() throws Exception { @Test @Order(11) - // Pinned to the POC path (pollInfoPrefetch=0): poll-ahead polls C1 in the background, so the - // poll count asserted here is only fixed when the reader polls. public void t9ClosingIncompleteResultAttemptsFlightInfoCancellation() throws Exception { - try (Connection connection = connect(true, "pollInfoPrefetch=0"); + try (Connection connection = connect(true); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("cancel-observable")) { assertTrue(resultSet.next()); assertEquals(1L, resultSet.getLong("value")); + // The background poller has C1 open (the server answers it only when cancelled); closing + // the result ends that poll and sends one CancelFlightInfo. + awaitCounter("poll_flight_info", 2, Duration.ofSeconds(3)); } awaitCounter("cancellation", 1, Duration.ofSeconds(2)); - assertCounters(1, 0, 0, 1, 0, 1, 0, 1); + awaitCounter("active_call_terminations", 1, Duration.ofSeconds(2)); + assertCounters(2, 0, 0, 1, 1, 1, 1, 1); } private static Connection connect(final boolean usePollInfo) throws Exception { - return connect(usePollInfo, ""); - } - - /** Connects with extra properties, for example {@code pollInfoPrefetch=0} for the POC path. */ - private static Connection connect(final boolean usePollInfo, final String extraProperties) - throws Exception { return DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s%s", - FLIGHT_PORT, usePollInfo, extraProperties.isEmpty() ? "" : "&" + extraProperties)); + "jdbc:arrow-flight-sql://127.0.0.1:%d/?useEncryption=false&usePollInfo=%s", + FLIGHT_PORT, usePollInfo)); } private static List directValues(final Connection connection, final String query) @@ -373,6 +375,23 @@ private static void awaitCounter(final String name, final int expected, final Du assertEquals(expected, counter(state(), name), state()); } + // Waits until the server holds the given continuation poll (set with POST /hold-poll). + private static void awaitPollHeld(final int continuation) throws Exception { + final long deadline = System.nanoTime() + Duration.ofSeconds(5).toNanos(); + while (true) { + final JsonNode events = JSON.readTree(state()).path("events"); + for (final JsonNode event : events) { + if ("PollFlightInfo.hold".equals(event.path("method").asText()) + && event.path("continuation").asInt() == continuation + && "held".equals(event.path("outcome").asText())) { + return; + } + } + assertTrue(System.nanoTime() < deadline, "continuation " + continuation + " was not held"); + Thread.sleep(20); + } + } + private static void awaitCounterEquals( final String name, final int expected, final Duration timeout) throws Exception { final long deadline = System.nanoTime() + timeout.toNanos(); @@ -406,6 +425,7 @@ private static String request(final String method, final String path, final Stri HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + CONTROL_PORT + path)) .timeout(Duration.ofSeconds(2)); if ("POST".equals(method)) { + builder.header("Content-Type", "application/json"); builder.POST(HttpRequest.BodyPublishers.ofString(body)); } else { builder.GET(); From 481ce860d548e8804156fd55b30b2002b2141dec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 13:56:05 +0000 Subject: [PATCH 38/39] BDX-645: model the rejected poller start; sync the poll-ahead model with b19d8370a EndpointPoller.start() is now owned.set(true); handBack(), so a pool that rejects the start leaves the poller orphaned, like a rejected resume. Init now chooses between a running and an orphaned poller and reuses AppIdle, InlineExit and PollerApplyHandBack. New broken variant rejectedStartUnused (a rejected start leaves the poller unused) fails Terminates. The reader-side fallback caveat is gone from the skill; sync commit moved to b19d8370a. 23 checks match at N=3 and N=4. Co-Authored-By: Claude Opus 5.5 --- .../skills/verify-jdbc-poll-ahead/SKILL.md | 39 ++++++++++------- formal/pollinfo-poll-ahead/PollAhead.tla | 42 +++++++++++++------ formal/pollinfo-poll-ahead/run.sh | 2 + 3 files changed, 54 insertions(+), 29 deletions(-) diff --git a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md index 5b6310f11e..2d8a973910 100644 --- a/.claude/skills/verify-jdbc-poll-ahead/SKILL.md +++ b/.claude/skills/verify-jdbc-poll-ahead/SKILL.md @@ -28,7 +28,7 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. ## Scope, bounds, assumptions -- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled, except that a rejected resume is a free choice (`ReaderResumeRejected`). +- Bounds: up to `N` endpoints per query (default 3; also checked with `N=4`), `Limit=2`. One `ResultSet`. Two or more results sharing the poller pool are not modeled, except that a rejected start (`Init`) and a rejected resume (`ReaderResumeRejected`) are free choices: the pool may be busy or not. - Rows are abstracted: an endpoint is taken (`AppTake`) and later read to the end (`AppExhaust`), and nothing between is tracked. An endpoint is either empty (its future yields `null`, `AppReadEmpty`) or not. PollInfo is modeled as a count of endpoints so far, so the append-only rule shows up as "never fewer than before". - Time is abstracted: a backoff is one step. Its length (100 ms doubling up to `pollInfoMaxBackoff`) is not checked, and neither are the 10 x 100 us resubmit retries (only their outcome). - The server may answer a poll at any moment, including at once with nothing new. @@ -41,22 +41,28 @@ Each rule is an INVARIANT or PROPERTY in `PollAhead.tla`. - taking a ready stream (`AppTake`, no slot change) and reading it to the end (`AppExhaust`, slot freed): the stream keeps its slot in between, as `openUnread` does; - the resume after unlocking (`ReaderResume`, `ReaderResumeRejected`), against the poller's `owned` flag; - stream opening outside the lock into reserved slots (`OpenReserved`, `OpenFails`); - - the orphaned poller run inline by the reader (`AppIdle`, `InlineExit`, `PollerApplyHandBack`); + - the orphaned poller run inline by the reader (`AppIdle`, `InlineExit`, `PollerApplyHandBack`). A poller starts orphaned when the pool rejects `start()`, as it becomes orphaned after a rejected resume or hand-back, and the same three actions serve all three; - `Statement.cancel()`: `PollInfoOperation.cancel()` first (`CancelOp`: an open poll ends `CANCELLED`, so the poller can record "Statement canceled" as the queue failure before `cancelled` is set), then `ResultSet.cancel()`: the `cancelled` flag, then stop, cancel the operation and close the queue (`AppCancel`, `CancelStop`). `CancelOp` is optional: `close()` and a direct `ResultSet.cancel()` start at `AppCancel`; - the reader's idle hook and its wait (`idleTried`). - Over-approximations (safe, they only add behaviors): any step may open a reserved stream (the code opens it on the thread that reserved it, before that thread goes on); `AppExhaust` is allowed after a failure or cancel (the stream's `next()` would usually throw `CANCELLED` first); `PollerCrash` may hit the poller in any of `running`, `polling`, `received`, `backoff`; a started `Statement.cancel()` always reaches `ResultSet.cancel()` (fairness on `AppCancel`). - Not tracked: the rows between `AppTake` and `AppExhaust`. Each `next()` call starts with the `cancelled` and `queue.failure()` checks, which the model treats as `AppThrow`, so `FailFast` only watches the hand-over of a stream. A row already buffered when cancel or a failure starts can still reach the application from a `next()` call that was already running (the next call throws). - Not modeled, by design: the cleanup RPC that follows a failed poll (`afterFailure`: `cancel()` or `terminate()`, then `finishPollInfoOperation`; `CancelFlightInfo` has a 1 s timeout). The model has no time, so it cannot say how long a failure takes to reach the reader. It records the failure in the step that takes the answer, which is what `onPollFailed` now does. -- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, the poller pool failing to start (`start()` rejected, then `disablePollAhead`), the timed first wait (`SQLTimeoutException`), the reader pool's size and the other results that share it, `endpointExhausted` on a queue without an opener (it re-enqueues), a cancel during `executeQuery` before the `ResultSet` exists, or **the fallback path** (`pollInfoPrefetch = 0` or a busy poller pool): `loadNextPublishedEndpoint` polls inside `next()` on the unlimited eager queue, and since `4b831553c` it loops while a continuation remains. Before that it returned false when the new endpoints had no rows, which truncates the result (the class of `NoPrematureEnd`, on a path the model does not describe; found by review, covered only by Java tests). +- The model covers the poll-ahead path only. It does not cover `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata calls, parameter upload, the timed first wait (`SQLTimeoutException`), the reader pool's size and the other results that share it (and the poller pool they share: a rejected start, resume or hand-back is a free choice, not a function of other results' load), `endpointExhausted` on a queue without an opener (it re-enqueues), a cancel during `executeQuery` before the `ResultSet` exists, the backoff timing, or the check of the `pollInfoPrefetch` value at connect (a connection property check, not a result action). The reader-side fallback of the first POC (`disablePollAhead`, `pollNextAvailable`, polling inside `next()`) no longer exists since `b19d8370a`: a rejected start leaves the poller orphaned instead. - Answer validation (`validateAppendOnly`, schema change, no continuation to poll) and an interrupted backoff are not modeled as such. They all end the poller with a queue failure, which is `PollerCrash`. -- **The implementation corresponds to `EagerOpen = FALSE`** for continuations: a queue built with `maxOpen = pollInfoPrefetch`. **Complete answers** (no continuation) **and `pollInfoPrefetch = 0` use the unlimited eager queue** (`maxOpen = Integer.MAX_VALUE`, no poller, the reader polls in `next()`); the model does not cover that path. `EagerOpen = TRUE` is kept only to show the old finding. -- The first load (`populateData` -> `getNextEndpointStream(true, false)` -> `Q.nextAvailable`) is not a separate action. It runs the same `awaitNext` loop and only differs by returning null where `next()` would idle, wait or end. The model starts when the poller has started, with the reader at the top of that loop and `idleTried` false, which is also the state of a fresh `next()` call; every state after the first load is one the model reaches from there. +- **The implementation corresponds to `EagerOpen = FALSE`** for continuations: a queue built with `maxOpen = pollInfoPrefetch`, which is at least 1 (`0` and values below `-1` are rejected at connect). **A complete first answer** (no continuation) **uses the unlimited eager queue** (`maxOpen = Integer.MAX_VALUE`, no poller, nothing to poll); the model does not cover that path, which has no background party. `EagerOpen = TRUE` is kept only to show the old finding. +- The first load (`populateData` -> `getNextEndpointStream(true, false)` -> `Q.nextAvailable`) is not a separate action. It runs the same `awaitNext` loop and only differs by returning null where `next()` would idle, wait or end. The model starts when `P.start()` has run: the poller is running on a pool thread, or orphaned because the pool rejected the task (`Init` chooses). The reader is at the top of that loop with `idleTried` false, which is also the state of a fresh `next()` call; every state after the first load is one the model reaches from there. ## Coverage record Abbreviations, all under `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/`: **P** = `EndpointPoller.java`, **Q** = `utils/FlightEndpointDataQueue.java`, **R** = `ArrowFlightJdbcFlightStreamResultSet.java`, **O** = `client/PollInfoOperation.java`. -Sync commit: `2574a511c` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`) and the slot release on exhaustion. The only main-code change after `4b831553c` is `436156f29` (see below), which is not a model action. +Sync commit: `b19d8370a` (branch `bdx-645-pollinfo-poc`, rebased on apache/arrow-java `10c55b9c8`). The model matches the main code there, including the idle-flag fix (`IdleFix = TRUE`), the slot release on exhaustion, and the orphaned start. The main-code changes after `4b831553c` are `436156f29` and `b19d8370a` (see below); only the second one is a model change. + +The diff `2574a511c..b19d8370a` of the main code (commits `b618dbc14` and `c77fa206b` between them changed docs only) removed the first POC's reader-side polling: + +1. `EndpointPoller.start()` is `void`: `owned.set(true); handBack();`. Before, it returned false when the pool rejected the task, and the result set then dropped the poller (`poller = null`, `setResumeAction(null)`, `setIdleAction(null)`) and called `Q.disablePollAhead()`, which lifted the limit and cleared `moreExpected`, so `next()` polled by itself (`O.pollNextAvailable`, with `setMaxBackoffMillis`). All of that is deleted. A rejected start now leaves the poller orphaned (`orphaned` set, `Q.wakeReader()`), exactly like a rejected resume. Model: `Init` starts the poller `running` or `orphaned`, a free choice; `AppIdle`, `InlineExit` and `PollerApplyHandBack` are reused unchanged, as the code reuses `runInlineIfOrphaned` and `handBack`. The state space grows by about 4 percent (27,569 to 28,658 distinct states for `deferred-open` at `N=3`). +2. `R.loadNextPublishedEndpoint` has no `poller == null` polling branch: with no poller, no continuation was left after the first answer, so every endpoint was read (the result ends). `R.shouldPollAhead` no longer tests `pollInfoPrefetch > 0`: every progressive result with a continuation has a poller. `validatePollInfoPrefetch()` rejects `0` and anything below `-1` when the connection is created (not a model action). +3. New broken variant `rejectedStartUnused`: the old `start()` without its fallback, a rejected start leaves the poller stopped and unused while more endpoints are expected. `Terminates` catches it (TLC's trace has 4 steps: the application finishes the first endpoint, `AppIdle` finds the poller not orphaned and sets `idleTried`, `ReaderWait`; nobody ever wakes the reader). No safety rule sees it: `next()` hangs instead of returning wrong data. Earlier syncs: the diff `d7c3ed4ab..dadd45d8a` of the main code has two changes: the `idleTried = false` line in `awaitNext` (mirrored, see finding 1) and a rethrow of `queue.failure()` in `ResultSet.next()`'s `FlightRuntimeException` catch (not a model action: it only picks the exception thrown while the reader is blocked in a stream). @@ -68,7 +74,7 @@ The diff `dadd45d8a..4b831553c` of the main code (four files: **R**, **P**, **O* 4. A cancel that races a poll is recorded as the queue failure "Statement canceled" (model: `CancelOp`). 5. A failed queue is inert: `addEndpoints` is a no-op and `openReserved` stops opening (model: `ApplyQ`, `OpenReserved`, `ReadFree`). 6. Any `Throwable` on the poller fails the queue (model: `PollerCrash`). -7. The fallback path loops while a continuation remains (not modeled). +7. The fallback path loops while a continuation remains (not modeled; the path was removed in `b19d8370a`, see above). Not a model action: `Thread.currentThread().interrupt()` before wrapping an `InterruptedException`, `volatile` on `R.poller`, and the new public `O.isCancelled()` (it is read by `mapContinuationFailure`, see `CancelOp`). @@ -76,9 +82,10 @@ Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection | Model action | Code at the sync commit | | --- | --- | +| `Init` (`poller = running` or `orphaned`) | R `startPoller` -> P `start`: `owned.set(true)`, then `handBack` (`submit`, 10 attempts). Accepted: the task runs `drive(false)` on a pool thread (`running`). Rejected: `orphaned.set(true)`, `queue.wakeReader()` (`orphaned`), the state a rejected resume leaves. The reader then runs the poller inline from `AppIdle` when it would otherwise wait, and `handBack` re-submits it after an answer adds endpoints. Broken variant `rejectedStartUnused`: the poller is `unused` (the old `start()`: `owned.set(false)`, `STOPPED`, no fallback). | | `PollerSend`, `PollerTake` | P `drive` -> O `pollOnce` -> `poll`. The poll runs on a pool thread, or on the reader's thread when run inline. | | `PollerApplyBackoff`, `PollerApplyGo` | O `remember` (inside `pollOnce`: `validateAppendOnly`, new continuation), then R `appendEndpoints` -> Q `addEndpoints`; then P `drive`: `operation.backoff` (backoff) or the next loop iteration (go). On a failed queue Q `addEndpoints` returns at its `failure != null` check and changes nothing (`ApplyQ`, `FailedQueueInert`); P `drive` then stops at its loop-top check (`PollerSeesFail`). | -| `PollerApplyHandBack` | The same, run inline: P `drive(true)` after an answer that added endpoints calls `handBack` (`submit`, or orphaned again). | +| `PollerApplyHandBack` | The same, run inline: P `drive(true)` after an answer that added endpoints calls `handBack` (`submit`, or orphaned again, the same step as in `start()`). | | `PollerApplyFinish` | Q `addEndpoints(list, false)` and P `drive`: `FINISHED`, `onFinished`. | | `PollerPause`, `PollerPauseEnd`, `PollerCheck` | Q `pauseIfFull` with P `drive`'s `onPaused` (paused flag and `owned.set(false)` under the lock). `PollerPauseEnd` and `PollerCheck` exist only for the broken variants. | | `PollerSeesFail`, `PollerDrop` | P `drive`: the loop-top check and the check after `pollOnce`. | @@ -88,8 +95,8 @@ Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection | `AppExhaust` | R `next`: `currentEndpointData.getStream().next()` returned false, then R `endpointExhausted` -> Q `endpointExhausted` -> `onStreamFinished(finished)`: under the lock `endpointsToClose.remove`, `openUnread--`, `reserveSlotsLocked`, paused flag cleared (`ReadFree`); after the unlock `closeQuietly`, the resume action (`ReaderResume`), `openReserved`. Only R `next` calls it, on the application thread. | | `AppReadEmpty` | Q `awaitNext` taking a `null` future (a stream that ended inside the pool task without rows) -> `onStreamFinished` (same locked step as `AppExhaust`). | | `ReadFree` (the shared locked step) | Q `onStreamFinished`. On a failed or closed queue `pending` is empty (`fail()` and `close()` clear it), so it reserves nothing. | -| `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). | -| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`). `idleTried` is the local variable in `awaitNext`; it is cleared after a wait and after every consumed future (`AppReadEmpty`, `IdleFix`). | +| `ReaderResume`, `ReaderResumeRejected` | The resume action `onStreamFinished` runs after `lock.unlock()`: P `resume` (`owned` compare-and-set), `handBack` (`submit`, 10 attempts, then `orphaned.set(true)`, `wakeReader`). The rejected start is the same `handBack`, modeled in `Init`. A resume of an orphaned poller finds `owned` set and does nothing (`ReaderResume` leaves a poller that is not `paused` alone). | +| `AppIdle`, `InlineExit` | Q `awaitNext`'s idle hook -> P `runInlineIfOrphaned` (`drive(true)`), for a poller orphaned by a rejected start, resume or hand-back. `idleTried` is the local variable in `awaitNext`; it is cleared after a wait and after every consumed future (`AppReadEmpty`, `IdleFix`). | | `ReaderWait` and the wakes (`WakeRd`) | Q `awaitNext` -> `awaitChange`; `signalAll` in `addEndpoints`, `register`, `releaseReservations`, `fail`, `close`, `wakeReader`. | | `AppEnd` | Q `awaitNext` returning `null` (futures empty, pending empty, `opening == 0`, `!moreExpected`, under the lock), R `next` returning false. | | `AppThrow` | Q `awaitNext` -> `checkOpen`, `throwIfFailed`; R `next` top-of-call checks of `cancelled` and `queue.failure()`. | @@ -103,7 +110,7 @@ Reviewed after the sync, not a model action: `436156f29` (`ArrowFlightConnection Run it when a diff touches any covered file: ```sh -git --no-pager diff --name-only 2574a511c..HEAD -- \ +git --no-pager diff --name-only b19d8370a..HEAD -- \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFlightStreamResultSet.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/EndpointPoller.java \ flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightConnection.java \ @@ -116,19 +123,19 @@ git --no-pager diff --name-only 2574a511c..HEAD -- \ formal/pollinfo-poll-ahead/ ``` -Any output means the model may no longer describe the code. Also use this skill for any new class that polls or opens streams on a background thread. Read the code diff itself with `git --no-pager diff 4b831553c..HEAD -- ` (or `git show`, or `rtk proxy git diff`): a hook may summarize plain `git diff` output. +Any output means the model may no longer describe the code. Also use this skill for any new class that polls or opens streams on a background thread. Read the code diff itself with `git --no-pager diff b19d8370a..HEAD -- ` (or `git show`, or `rtk proxy git diff`): a hook may summarize plain `git diff` output. ## How to check a change 1. **Mirror the change in the model.** The model is a hand-written design model, so TLC cannot read Java. Use the coverage record to find the action that corresponds to the code you changed, and edit that action so it does what the new code does. Keep each atomic step in the model atomic in the code: a step under one lock, or one RPC answer, is one action. -2. **Run every check** (about 35 seconds each; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): +2. **Run every check** (23 checks, about 35 seconds a run; needs Java 11+ and `tla2tools.jar` v1.7.4, found through `TLA2TOOLS` or the mise install path): ```sh formal/pollinfo-poll-ahead/run.sh N=4 formal/pollinfo-poll-ahead/run.sh ``` - The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. `lateRelease-old-rules` is the other exception, on purpose: it runs `lateRelease` against the rules that existed before `SlotFreedOnExhaust` and must pass, which records that the late release is invisible to them (finding 3). A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. + The script exits 0 only when every line says `ok`. The design checks must pass. `finding-open-streams` fails on `OpenWithinLimit` by design: it is the old `EagerOpen = TRUE` proposal, which the implementation does not follow. `deferred-open` is the code as written, with `IdleFix = TRUE`, every safety rule and `Terminates`; it must pass. Every design check also covers the rejected start, because `Init` chooses between a running and an orphaned poller. Every broken variant must fail on its rule; they run with `IdleFix = TRUE` so the stale-idle bug cannot hide a variant that no longer fails. `staleIdle` is the exception: it runs with `IdleFix = FALSE` and must fail on `Terminates`. `openNotReserved` only fails from `N=4` on. `rejectedStartUnused` fails on `Terminates`. `lateRelease-old-rules` is the other exception, on purpose: it runs `lateRelease` against the rules that existed before `SlotFreedOnExhaust` and must pass, which records that the late release is invisible to them (finding 3). A variant that suddenly passes means the model lost the ability to catch that bug: fix the model before you trust any pass. 3. **Read any failure with the pstack `/statechart` skill** (type `/pstack:statechart`). Give it a copy of `PollAhead.tla` and a config with the failing rule, in a scratch folder outside the repo. It prints the shortest path to the violation as numbered steps in plain words. When the model passes, it can draw how a result moves between states. 4. **Decide whether it is a bug or a modeling error.** Replay the path against the real code, one model action per step: as a unit test with a scripted Flight SQL producer (see `PollingMockFlightSqlProducer` in the JDBC tests), or against the Go conformance server (branch `bdx-645-pollinfo-conformance-server` of `dremio-employees/helder.gregorio`). If the code does the same thing, it is a real bug: report it with the path in the code's words, and do not weaken the rule. If the code cannot take that path, the model is wrong: fix the action, and say what you fixed. 5. **When a behavior change is intended**, change the action and, if a rule no longer applies, change that rule in a separate commit that explains why. Add a broken variant (a new `Mutation` value plus a `check` line in `run.sh`) for any new rule, and confirm it fails. @@ -188,11 +195,11 @@ None of these was found by TLC. Each row says what the model did about it. | 4. A cancel that races a poll is recorded as the failure "Statement canceled" | New action `CancelOp` (`PollInfoOperation.cancel()` before `ResultSet.cancel()`), `SrvAnswer` answers `CANCELLED` once `opCancelled`, and `PollerTake` records it as `failSeen` while `cancelled` is still false. Reachable (checked), and every rule holds: the reader throws either way, only the exception differs. | No new rule. `FailFast` and `CancelStopsPolling` hold with the extra step. | | 5. A failed queue is inert | `ApplyQ` is a no-op once `failSeen`; `OpenReserved` registers nothing once `failSeen` or `gated`; `ReadFree` finds no pending endpoint after a failure or close (the model derives pending from `known - opened - resv`, so it is masked by `failSeen \/ gated`). | New rule `FailedQueueInert`, variant `applyAfterFail`. The check in `openReserved` is a `volatile` read outside the lock, so "no `DoGet` starts after a failure" is not a rule: a race window remains and only the locked part is atomic. | | 6. Any `Throwable` on the poller fails the queue | New action `PollerCrash`. Before this, the model listed an `Error` killing the poller as not modeled. | Variant `errorNotReported`: an `Error` leaves the poller dead and the queue not failed, so `next()` waits forever (`Terminates`). The old code did exactly this for an `Error`. | -| 7. The fallback path loops while a continuation remains | None. The path is outside the model (see the scope section). | None. Its old defect belongs to the class of `NoPrematureEnd`. Extending the model to the fallback path is the open follow-up. | +| 7. The fallback path loops while a continuation remains | None at the time: the path was outside the model. | None. Its old defect belonged to the class of `NoPrematureEnd`. The path was removed in `b19d8370a` (the rejected start is now an orphaned poller, which the model covers), so no follow-up remains. | No rule failed on the model of `4b831553c`: every line of `run.sh` says `ok` at `N=3` and `N=4`, and the design checks also pass with a limit of 1 and of 3. ## Files - `formal/pollinfo-poll-ahead/PollAhead.tla`: the model, with the code map in its header. -- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`, `lateRelease`, `applyAfterFail`, `errorNotReported`, plus the gap check `lateRelease-old-rules`. +- `formal/pollinfo-poll-ahead/run.sh`: all design checks and broken variants, with their expected results. Variants: `staleIdle`, `endWhenQueueEmpty`, `endIgnoresOpening`, `finishBeforeEnqueue`, `enqueueWholeList`, `reuseContinuation`, `readAfterFail`, `cancelIgnoresPoller`, `noLimit`, `openNotReserved`, `noBackoff`, `noWake`, `pauseNotAtomic`, `ownedClearedLate`, `noIdleHook`, `lateRelease`, `applyAfterFail`, `errorNotReported`, `rejectedStartUnused`, plus the gap check `lateRelease-old-rules`. diff --git a/formal/pollinfo-poll-ahead/PollAhead.tla b/formal/pollinfo-poll-ahead/PollAhead.tla index 7a314b1142..14665b34bb 100644 --- a/formal/pollinfo-poll-ahead/PollAhead.tla +++ b/formal/pollinfo-poll-ahead/PollAhead.tla @@ -2,20 +2,24 @@ (***************************************************************************) (* Bounded poll-ahead for the Arrow Flight SQL JDBC driver (BDX-645). *) (* *) -(* One progressive JDBC ResultSet, from the moment its poller has started: *) -(* the first PollInfo published endpoint E1 and continuation C1, and C1 *) -(* has been handed to the poller. The application thread is in *) -(* executeQuery's first load (Q.nextAvailable) or in ResultSet.next(); both*) -(* run the same awaitNext loop, and the first load only differs by *) -(* returning null instead of waiting, so the model does not tell them apart.*) +(* One progressive JDBC ResultSet that has a continuation, from the moment *) +(* its poller has started: the first PollInfo published endpoint E1 and *) +(* continuation C1, and C1 has been handed to the poller (P.start: owned *) +(* is set, then handBack). The pool either took the task (the poller is *) +(* "running") or rejected it (the poller is "orphaned", which is the same *) +(* state a rejected resume leaves); Init chooses either. The application *) +(* thread is in executeQuery's first load (Q.nextAvailable) or in *) +(* ResultSet.next(); both run the same awaitNext loop, and the first load *) +(* only differs by returning null instead of waiting, so the model does not*) +(* tell them apart.*) (* *) (* Parties that run concurrently: *) (* - the Flight SQL server, which publishes endpoints and finishes or *) (* fails the query, and answers PollFlightInfo at any moment (a server *) (* that does not long-poll may answer at once with nothing new); *) (* - the poller (EndpointPoller), which chains continuations. It runs on *) -(* a pool thread, or, if the pool rejected a resume, inline on the *) -(* reader's thread; *) +(* a pool thread, or, if the pool rejected its start or a resume, *) +(* inline on the reader's thread; *) (* - the reader: the application thread inside ResultSet.next(), which *) (* is inside FlightEndpointDataQueue.awaitNext, takes a ready stream, *) (* reads it to the end (and frees its slot), ends the results, or *) @@ -25,6 +29,11 @@ (* Code map (sync commit in .claude/skills/verify-jdbc-poll-ahead/SKILL.md;*) (* "Q" = utils/FlightEndpointDataQueue, "P" = EndpointPoller, "R" = *) (* ArrowFlightJdbcFlightStreamResultSet, "O" = client/PollInfoOperation): *) +(* Init (poller) R.startPoller -> P.start: owned.set(true); *) +(* handBack(). The pool accepts: "running". *) +(* The pool rejects 10 submits: orphaned set, *) +(* Q.wakeReader: "orphaned", exactly as after *) +(* a rejected resume *) (* PollerSend / PollerTake P.drive -> O.pollOnce -> O.poll *) (* PollerApply* O.remember (inside pollOnce) and *) (* R.appendEndpoints -> Q.addEndpoints, one *) @@ -55,6 +64,8 @@ (* AppIdle, ReaderWait, Q.awaitNext, empty-futures branch: end, *) (* AppEnd, AppThrow idle hook (P.runInlineIfOrphaned), or wait *) (* InlineExit P.runInlineIfOrphaned returning *) +(* PollerApplyHandBack P.drive(true) -> handBack after an answer *) +(* that added endpoints (submit, or orphaned) *) (* CancelOp, AppCancel, Statement.cancel: O.cancel first (an open *) (* CancelStop poll ends CANCELLED), then R.cancel: the *) (* cancelled flag, then P.stop + O.cancel + *) @@ -66,9 +77,10 @@ (* poll *) (* *) (* The implementation corresponds to EagerOpen = FALSE (a Q built with *) -(* maxOpen = pollInfoPrefetch). Answers with no continuation, and *) -(* pollInfoPrefetch = 0, use an unlimited eager queue and never start a *) -(* poller; the model does not cover them. *) +(* maxOpen = pollInfoPrefetch, which must be >= 1). A result whose first *) +(* answer has no continuation uses an unlimited eager queue and never *) +(* starts a poller; the model does not cover it. There is no fallback that *) +(* polls inside next(): a poller the pool did not accept is orphaned. *) (* *) (* Rows are abstracted: an endpoint is taken (AppTake, its first batch *) (* reaches the application) and later read to the end (AppExhaust, which *) @@ -104,6 +116,7 @@ VARIABLES got, \* the answer the poller took, not yet applied poller, \* "running" (at the top of its loop) | "polling" | "received" | "backoff" \* | "paused" | "pausing" | "orphaned" | "finished" | "failed" | "stopped" + \* | "dead" | "unused" (rejectedStartUnused only) lastEmpty, \* the last applied answer added no endpoints while the query was running waited, \* a backoff has elapsed since that empty answer sawFull, \* pauseNotAtomic only: the poller saw the limit reached and has not paused yet @@ -166,7 +179,10 @@ Init == /\ inflight = FALSE /\ resp = NoAnswer /\ got = NoAnswer - /\ poller = "running" + \* P.start: the pool accepts the task ("running") or rejects it and the poller is orphaned, + \* the state a rejected resume leaves too. Broken variant rejectedStartUnused: a rejected + \* start leaves the poller stopped and unused, nobody runs it ("unused"). + /\ poller \in {"running", IF Mutation = "rejectedStartUnused" THEN "unused" ELSE "orphaned"} /\ lastEmpty = FALSE /\ waited = FALSE /\ sawFull = FALSE @@ -663,7 +679,7 @@ TypeOK == /\ enq \in [1..N -> 0..2] /\ resp \in Answer /\ got \in Answer /\ poller \in {"running", "polling", "received", "backoff", "paused", "pausing", - "orphaned", "finished", "failed", "stopped", "dead"} + "orphaned", "finished", "failed", "stopped", "dead", "unused"} /\ rd \in {"run", "resume", "waiting", "inline"} /\ app \in {"reading", "ended", "threw"} /\ sawFull \in BOOLEAN diff --git a/formal/pollinfo-poll-ahead/run.sh b/formal/pollinfo-poll-ahead/run.sh index 012a4eda32..c91a537936 100755 --- a/formal/pollinfo-poll-ahead/run.sh +++ b/formal/pollinfo-poll-ahead/run.sh @@ -63,6 +63,7 @@ check() { echo "PollAhead model check N=$N Limit=$LIMIT ($(java -cp "$JAR" tlc2.TLC 2>&1 | head -1))" echo echo "Design checks (IdleFix = TRUE is the code: awaitNext clears idleTried after every consumed future)" +echo "(every check starts the poller either accepted by the pool or rejected, which leaves it orphaned)" check proposal-as-written TRUE TRUE none "$SAFE" yes pass "streams open as soon as endpoints are enqueued" check finding-open-streams TRUE TRUE none "OpenWithinLimit" no invariant:OpenWithinLimit "KNOWN FINDING: one answer can add more streams than the limit" check deferred-open FALSE TRUE none "$ALL" yes pass "the code as written: every safety rule and Terminates hold" @@ -90,6 +91,7 @@ check staleIdle FALSE FALSE none "$SAFE" yes livene check lateRelease FALSE TRUE lateRelease "$ALL" no invariant:SlotFreedOnExhaust "slot freed only when a later awaitNext consumes the null future, not when the application finishes the stream" check applyAfterFail FALSE TRUE applyAfterFail "$ALL" no invariant:FailedQueueInert "addEndpoints queues and reserves on a queue that already failed" check errorNotReported FALSE TRUE errorNotReported "$ALL" yes liveness "an Error kills the poller thread without failing the queue (next() waits forever)" +check rejectedStartUnused FALSE TRUE rejectedStartUnused "$ALL" yes liveness "a rejected poller start leaves the poller unused instead of orphaned (next() waits forever)" echo echo "Gap check: lateRelease passes every rule that existed before SlotFreedOnExhaust. The late release is a progress" echo "problem (a finished stream blocks the poller), not a safety or termination one, and only the new rule sees it." From 1aba194fba7464c49fcd8ec242d562ad040723be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Thu, 26 Nov 2026 13:59:00 +0000 Subject: [PATCH 39/39] BDX-645: update the plan and go/no-go doc for poll-ahead only The first POC's reader-side polling is gone (b19d8370a): a busy poller pool orphans the poller and the reader runs it inline, and pollInfoPrefetch must be -1 or positive. Update the behavior, settings, test counts and model coverage (23 checks) to match. Co-Authored-By: Claude Opus 5.5 --- reports/poll-ahead-implementation-plan.md | 20 +++++++++++--------- reports/production-recommendation.md | 20 ++++++++++---------- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/reports/poll-ahead-implementation-plan.md b/reports/poll-ahead-implementation-plan.md index 16b6890e11..f2ce1f3320 100644 --- a/reports/poll-ahead-implementation-plan.md +++ b/reports/poll-ahead-implementation-plan.md @@ -1,5 +1,7 @@ # BDX-645 JDBC poll-ahead: implementation plan +> **Revision (2026-11-26).** The first POC's reader-side polling is removed (`b19d8370a`). Every progressive result with a continuation gets an `EndpointPoller`. A busy poller pool leaves the poller orphaned, and the reader runs it inline when it would otherwise wait. `pollInfoPrefetch` must be `-1` or positive. Behavior 2 and 9, the configuration table and U1/U2 below are updated to match. + Goal: during progressive `PollFlightInfo` execution, poll continuations in the background while the application reads, without changing the JDBC API. The design was agreed in review and model-checked in `formal/pollinfo-poll-ahead/` (skill: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`). The implementation must match the model's **deferred-open** configuration (`EagerOpen = FALSE`). All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/` unless shown in full. @@ -7,7 +9,7 @@ All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/a ## Behavior 1. `executeQuery` is unchanged. It polls until the first endpoint exists and returns the `ResultSet`. -2. If a continuation is pending, the prefetch limit is above 0, and the poller pool accepts the task, the `ResultSet` hands the continuation to an `EndpointPoller`. Otherwise it keeps today's behavior: the reader polls inside `next()` when its queue is empty (the POC path, plus backoff). +2. If a continuation is pending, the `ResultSet` hands it to an `EndpointPoller`. If the poller pool rejects the task, the poller starts orphaned: the reader runs it inline, through the queue's idle hook, when it would otherwise wait, and hands it back to the pool after an answer adds endpoints. There is no other polling path. 3. The poller polls the held continuation once, in the execution's `PollInfoOperation` context (one deadline, one cancel). It checks append-only, queues only the appended endpoints, and continues with the next continuation. 4. Backpressure: - The poller does not poll while queued, unread endpoints (opened-unread plus not-yet-opened) are at or above the limit. It pauses and holds no thread. @@ -17,15 +19,15 @@ All paths below are relative to `flight/flight-sql-jdbc-core/src/main/java/org/a 6. End of results: `next()` returns false only when the queue is empty, nothing is pending, and the poller has finished. The poller must mark itself finished in the same locked step that queues the final endpoints. 7. Fail fast: a failed continuation poll records the failure, closes every open stream, drops pending endpoints and buffered batches, and makes the next `next()` throw. No `CancelFlightInfo` is needed, because the server already ended the query. The exception keeps today's mapping: `TIMED_OUT` becomes `SQLTimeoutException("Query timed out after N SECONDS")`; anything else becomes `SQLException("Continuation PollFlightInfo failed", cause)`. 8. Cancel and close stop the poller. `Statement.cancel()`, the deadline and `ResultSet.close()` on an incomplete result cancel the operation context, end any open poll, send best-effort `CancelFlightInfo` once (existing `PollInfoOperation.cancel`), close the queue, and make the next `next()` throw "Statement canceled". -9. Unlimited eager queue: a first answer that is already complete (no continuation) and `pollInfoPrefetch=0` both use the queue without an open limit, so every endpoint opens at once, as it always did. The limit applies only while a poller is running. +9. Unlimited eager queue: a first answer that is already complete (no continuation) uses the queue without an open limit, so every endpoint opens at once, as it always did. The limit applies only while a poller exists. 10. Metadata calls, `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, and `usePollInfo=false` are unchanged. ## Configuration (connection properties) | Property | Type | Default | Meaning | | --- | --- | --- | --- | -| `pollInfoPrefetch` | number | `-1` = auto: `max(2, threadPoolSize)` | Most queued, unread endpoints. The poller polls only below it, and streams open only below it. `0` keeps the POC behavior (the reader polls when its queue is empty). | -| `pollInfoPollerThreads` | number | `4` | Size of the connection's poller pool. When all threads are busy, a new result uses the `0` behavior. | +| `pollInfoPrefetch` | number | `-1` = auto: `max(2, threadPoolSize)` | Most queued, unread endpoints. The poller polls only below it, and streams open only below it. Must be `-1` or positive; other values are rejected when the connection is created. | +| `pollInfoPollerThreads` | number | `4` | Size of the connection's poller pool. When all threads are busy, a new result's poller runs inline on the reader until a pool thread is free. | | `pollInfoMaxBackoffMs` | number | `5000` | Longest wait between answers that add nothing. | Deviation from the review decision: the review set the prefetch default to `threadPoolSize`, but `threadPoolSize` defaults to 1. A limit of 1 never polls while an endpoint is being read, so the default is `max(2, threadPoolSize)`. Follow the naming and type conventions of the existing properties in `utils/ArrowFlightConnectionConfigImpl.java`. If they use a different suffix for durations, use theirs and record the name here. @@ -47,7 +49,7 @@ Deviation from the review decision: the review set the prefetch default to `thre - An atomic `pauseIfFull()` for the poller and a resume callback fired when the unread count drops below the limit, all under one lock. Never hold that lock across a blocking `future.get()`, `take()`, or a network call. - `client/PollInfoOperation.java`: - A single-poll method for the poller: poll the held continuation once, `remember` the answer, and report whether it added endpoints. - - Keep `pollNextAvailable` for the fallback path, but add the same backoff between empty answers. + - ~~Keep `pollNextAvailable` for the fallback path~~ Removed in the revision, with the fallback path. - Keep `validateAppendOnly`. - New `EndpointPoller` (package `org.apache.arrow.driver.jdbc`, package-private), started by the result set. - States: running, polling, paused, backoff, finished, failed, stopped. @@ -57,8 +59,8 @@ Deviation from the review decision: the review set the prefetch default to `thre - Create the queue with the limit and opener, and queue the first answer's endpoints through it, so deferred opening applies to the first answer too. - Start the poller, or fall back. - In poller mode, `next()` relies on the queue: `null` means done. Map a failure to the exceptions above. - - Keep the POC path for prefetch `0` or a rejected submit. Keep cancel and close semantics. -- Keep every existing test green. If an existing test asserts the POC request order (`Poll, DoGet, Poll, DoGet`), run it with `pollInfoPrefetch=0` rather than deleting the assertion. + - A rejected start orphans the poller (revision; the POC path for prefetch `0` or a rejected submit was removed). Keep cancel and close semantics. +- Keep every existing test green. Tests that asserted the POC request order (`Poll, DoGet, Poll, DoGet`) were rewritten in the revision to assert poll-ahead behavior, with answers gated where order matters. - Do not change the TLA+ model. ### U2. Unit tests (after U1) @@ -74,8 +76,8 @@ Add to `flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/` 7. Close of an unfinished result stops the poller and sends one `CancelFlightInfo`. 8. No premature end: the final endpoints arrive in the done answer, and all rows are delivered. 9. Continuations are sent once each and in order. -10. `pollInfoPrefetch=0` keeps the exact POC order. -11. Poller pool busy (`pollInfoPollerThreads=1`, two concurrent results): the second falls back, and both return correct rows. +10. ~~`pollInfoPrefetch=0` keeps the exact POC order.~~ Revision: `pollInfoPrefetch=0` is rejected when the connection is created. +11. Poller pool busy (`pollInfoPollerThreads=1`, two concurrent results): the second result's poller runs inline on the reader, is handed back to the pool once a thread is free, and both return correct rows. 12. `FlightEndpointDataQueue` unit tests for deferred open, wait-for-more, fail, and close. ### U3. End-to-end tests against the conformance server (after U2 and the server additions) diff --git a/reports/production-recommendation.md b/reports/production-recommendation.md index 5b6cb72e11..2d8f72dca5 100644 --- a/reports/production-recommendation.md +++ b/reports/production-recommendation.md @@ -12,7 +12,7 @@ The branch has been rebased onto current upstream `main` (see "Rebase onto upstr 1. **The public API surface is accidental.** The POC adds a protected `FlightSqlClient.getInfo(FlightDescriptor, CallOption...)` in the published `flight-sql` artifact. That method can collide with subclasses that already exist downstream. It also adds a public `PollInfoOperation` and public handler and builder methods in `flight-sql-jdbc-core`. All of this needs an intentional design and an upstream Apache discussion before it lands. -Contract item 12 (a delay between answers that add nothing) was missing from the first POC. It is now implemented: both the background poller and the reader's own polling wait 100 ms after such an answer, doubling up to `pollInfoMaxBackoffMs` (default 5000), never past the deadline. Cancel and close end the wait. +Contract item 12 (a delay between answers that add nothing) was missing from the first POC. It is now implemented: the poller waits 100 ms after such an answer, doubling up to `pollInfoMaxBackoffMs` (default 5000), never past the deadline. Cancel and close end the wait. ## Documented limitations (behavioral) @@ -21,7 +21,7 @@ Contract item 12 (a delay between answers that add nothing) was missing from the - **CancelFlightInfo needs a payload.** Best-effort `CancelFlightInfo` is only possible after at least one `PollInfo` has returned a `FlightInfo`. Cancelling a blocked initial poll terminates the RPC but sends no server-side cancel. - **Cleanup is synchronous.** The cancel cleanup call is bounded to one second, but it runs on the caller's thread. A slow server can delay the delivery of a timeout or cancel by up to that second. - **The capability cache is scoped to the handler.** Unsupported families are cached per `ArrowFlightSqlClientHandler`, keyed by Flight SQL command `type_url`. Pooled or reused physical connections have not been tested. -- **Poll-ahead uses threads per connection.** Each connection can start up to `pollInfoPollerThreads` (default 4) daemon poller threads. When they are all busy, a new result falls back to polling inside `next()`. Several results sharing one pool are covered by unit tests, not by the model. +- **Poll-ahead uses threads per connection.** Each connection can start up to `pollInfoPollerThreads` (default 4) daemon poller threads. When they are all busy, a new result's poller runs inline on the application's thread inside `next()` until a pool thread is free. Several results sharing one pool are covered by unit tests, not by the model. - **The opt-out name differs from the ticket.** The ticket suggested `usePollFlightInfo=false`; the POC implements `usePollInfo=false`. Pick one name before release and document it. ## GetFlightInfo call-site coverage @@ -72,11 +72,11 @@ The first POC polled the next continuation only after the application had read e - Backoff as described above. - Fail fast: a failed continuation closes every stream, drops buffered batches, and makes the next `next()` throw, with the existing exception mapping. - Cancel, the deadline, and closing an unfinished result stop the poller and send `CancelFlightInfo` once. -- `pollInfoPrefetch=0`, or a busy poller pool, keeps the first POC's behavior (with backoff). A first answer that is already complete opens every endpoint at once, as before. +- Every result with a continuation has a poller. If the poller pool is busy, the poller starts orphaned: the reader runs it inline when it would otherwise wait, and hands it back to the pool after an answer adds endpoints. The first POC's reader-side polling path was removed in `b19d8370a`. A first answer that is already complete opens every endpoint at once, as before. | Property | Default | Meaning | | --- | --- | --- | -| `pollInfoPrefetch` | `-1` = `max(2, threadPoolSize)` | Most queued, unread endpoints. `0` keeps the first POC's behavior. | +| `pollInfoPrefetch` | `-1` = `max(2, threadPoolSize)` | Most queued, unread endpoints. Must be `-1` or positive; `0` is rejected when the connection is created. | | `pollInfoPollerThreads` | `4` | Size of the connection's poller pool. | | `pollInfoMaxBackoffMs` | `5000` | Longest wait between answers that add nothing. | @@ -84,11 +84,11 @@ The review set the prefetch default to `threadPoolSize`, but `threadPoolSize` de Verification: -- **Model.** `formal/pollinfo-poll-ahead/PollAhead.tla`, checked with TLC 2.19 by `run.sh`: 22 checks match at 3 and 4 endpoints, including a broken variant for each rule. How to recheck after a change: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`. +- **Model.** `formal/pollinfo-poll-ahead/PollAhead.tla`, checked with TLC 2.19 by `run.sh`: 23 checks match at 3 and 4 endpoints, including a broken variant for each rule. The poller may start on the pool or orphaned (pool busy), and both starts are checked. How to recheck after a change: `.claude/skills/verify-jdbc-poll-ahead/SKILL.md`. - **Bugs found before release.** The model found a hang after a rejected poller resume (`dadd45d8a`). A code review found a late slot release that made poll-ahead fall back to the first POC's timing, plus error, fallback and cancel edge cases (`4b831553c`). The tests found a raw `CANCELLED` error leaking from `next()` (`dadd45d8a`) and a lost `CancelFlightInfo` when the connection closed right after a deadline failure (`436156f29`). -- **Tests.** `PollAheadTest` (30), `FlightEndpointDataQueueDeferredOpenTest` (24), `EndpointPollerTest` (1) and `PollBackoffTest` (6) against scripted mock servers, and `SharedServerPollAheadTest` (13) against the conformance server's poll-ahead scenarios (`burst`, `trickle`, `empty-answers`, `late-error-buffered`), which check the server's maximum concurrent streams, poll timing against held streams, backoff gaps and cancellation. Four existing tests that assert the first POC's exact request order now run with `pollInfoPrefetch=0`. +- **Tests.** `PollAheadTest` (36 runs), `FlightEndpointDataQueueDeferredOpenTest` (26), `EndpointPollerTest` (1) and `PollBackoffTest` (6) against scripted mock servers, and `SharedServerPollAheadTest` (12) against the conformance server's poll-ahead scenarios (`burst`, `trickle`, `empty-answers`, `late-error-buffered`), which check the server's maximum concurrent streams, poll timing against held streams, backoff gaps and cancellation. Existing tests that asserted the first POC's exact request order now assert poll-ahead behavior, with answers held back where order matters. -Not covered by the model: `executeQuery`'s first poll, the fallback path, and several results sharing one pool. +Not covered by the model: `executeQuery`'s first poll, the `UNIMPLEMENTED` fallback, metadata, several results sharing one pool, and backoff timing. ## Rebase onto upstream main (2026-11-25) @@ -150,7 +150,7 @@ formal/pollinfo-poll-ahead/run.sh && N=4 formal/pollinfo-poll-ahead/run.sh | Run | Result | | --- | --- | | Flight SQL suite | 97/97 | -| JDBC core suite, shared-server tests enabled | 1,458 run, 0 failures, 49 skipped | -| `SharedServerPollAheadTest` / `SharedServerPollInfoExecutionTest` | 13/13 and 11/11 | +| JDBC core suite, shared-server tests enabled | 1,456 run, 0 failures, 49 skipped (after removing the first POC's path in `b19d8370a`) | +| `SharedServerPollAheadTest` / `SharedServerPollInfoExecutionTest` | 12/12 and 11/11 | | `install` (Spotless, Checkstyle, `dependency:analyze`) | passes | -| Model checks | all 22 match at N=3 and N=4 | +| Model checks | all 23 match at N=3 and N=4 |