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
display-dependency-updates honours
allowPreReleases. Since 2.25.0 every goal is meant
to skip alpha, beta, milestone, release candidate, preview and
early-access versions by default, but this goal still offered them
whatever allowPreReleases was set to (#1491).
Early-access versions such as 28-ea+12 are now recognised
as pre-releases in every goal.
The maxDependencyUpdates enforcer rule gains
allowPreReleases. Default false, as
in the goals: pre-releases no longer count as updates and no longer fail
the rule unless you set it to true.
display-plugin-updates no longer fails with
"Duplicate key". A report plugin declared in two
profiles of a parent POM broke the goal in 2.25.1 (#1490);
the last declaration now wins.
No more minimumReleaseAge warnings for
snapshots. With minimumReleaseAge set, every
SNAPSHOT in the local repository logged "Cannot determine the
publication date". Snapshots now skip the age check;
allowSnapshots decides whether they are offered.
🚀 New features and improvements
Leave pre-releases out of the maxDependencyUpdates rule (#1495)
@slachiewicz
[](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.mojoversions-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.mojoversions-maven-plugin
- 2.25.1
+ 2.25.2io.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
• 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
• 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
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.
true2.52.04.4.0
- 1.6.6
+ 1.6.8none-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
[](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.lz4lz4-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
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.
[](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.32.0.2033.8.0-jre
- 4.2.20.Final
+ 4.2.21.Final1.85.14.36.22.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
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.
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.
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).
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.
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.
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).
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.
210.23.0true
- 2.52.0
+ 2.53.04.4.01.6.8none
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
[](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.grpcproto-google-common-protos
- 2.81.0
+ 2.82.0test
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
[](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.lubenzstd-jni
- 1.5.7-26
+ 1.5.7-28at.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